lundi 29 janvier 2018

Is it a good idea to use global variables for test data values?

First, a bit of context:

I have a class with a series of methods performing tests on a set of files.This class also has a setUpClass method where those files are created.

Over the lifetime of this class, names like fake.txt, foobar, etc. have been used, but they are all string literals used at three or four places and not actual variables.

I recently decided to change one of those string literals into something that better reflects its use (foobar to initial_value for example), but one of the test failed since I forgot to rename one of the occurrence of foobar.

To avoid facing this issue anymore, I decided to replace all of the string literals by global variables. For example:

TEST_FILE = 'fake.txt'

However, I found that this change make the test suite way less readable for a number of reasons:

  • Previously, it was easy to scan what was a file name and what was a file content because we alway used file extensions to indicate file names (i.e., foo.txt is a file, bar is what would be written in foo.txt). My change makes it harder to distinguish between the two at first glance.
  • Due to syntax highlighting of string literals, it was easy to scan where those fake values were used. Using variables makes them less distinguishable.
  • Variable names usually take more space (i.e., f.write('bar') over f.write(FAKE_FILE_CONTENT), with some more extreme examples in the actual code.

On the one hand (and considering the points I just made), the complexity of the file is low enough so we can use string literals without much more issue than forgetting one occurrence. On the other hand, it is unclear if this file is going to evolve at a later time, and I feel like it would be easier to fix the issue now (if we decide to fix it at all).

What are the pros and cons of the two approaches (beyond what I listed), and is there a preferred solution?

Aucun commentaire:

Enregistrer un commentaire