mardi 29 octobre 2019

How to implement unit testing for a CLI that interacts with sqlite

I am building a command line tool that uses sqlite with go. This is the first time I try to do unit testing so I am having a hard time working out an appropriate structure for my code

For example, the CLI will open a sqlite database and check if it has the tables needed. This part of the function is handled by the cmd package. If not it will bootstrap those tables. Say I want to test that it correctly detects the absence of those tables and correctly bootstrap the database.

Some problems I have:

  1. Should I create _test files as a separate package or as part of the cmd package?

  2. I am trying to generate some files and compare them with some preexisting files. Where should I be generating those files (some temp folder?) ? Am I responsible for removing those files before the end of those tests?

  3. The cmd package has an unexported variable db that points to the database it should use in production. So the package defines db, err := sql.Open(...). Now during testing I want to use another database. What I am doing now is to set db to point to something else at the start of the test function. This feels sloppy somehow. Is it the right way to do it?

  4. Combination of 1 and 3: If I am to do testing in a separate package, how am I supposed to make this it use some different database given that it is unexported?

I feel some of them might be silly questions. But anyways, Thank you for any help!

Aucun commentaire:

Enregistrer un commentaire