38

I have been looking at PEP 8 -- Style Guide for Python Code and PEP8 -- Advanced Usage for clues on how to name my test classes. However, this is never mentioned on both sites, as well as many other sites I have looked at, such as the unittest page in the Python documentation. The only consistent style I see is "CapWords". In the unittest documentation they have examples for TestSequenceFunctions as well as DefaultWidgetSizeTestCase.

What I am trying to find out is whether to use "Name"Test or Test"Name". Methods use test_"name" and that's pretty much established. With regards to classes I am struggling to find a convention if there's one.

Would appreciate the forum's help on this.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
musabaloyi
  • 651
  • 1
  • 7
  • 11

2 Answers2

28

The documentation for unittest suggests, e.g.:

class TestSequenceFunctions(unittest.TestCase):

    def test_shuffle(self):
        ...

    def test_choice(self):
        ...

commenting

The three individual tests are defined with methods whose names start with the letters test. This naming convention informs the test runner about which methods represent tests.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • Thanks. Tests themselves are not a problem because otherwise unittest won't pick them up. – musabaloyi Mar 27 '14 at 09:06
  • In 2021 (hello new year), [this](https://docs.python.org/3/library/unittest.html#basic-example) has not changed. – Timo Jan 01 '21 at 17:31
20

Django and SQLAlchemy, two large, popular Python projects, both use "Name"Test(s). Personally, I prefer that to Test"Name", mainly because when there are multiple TestCases in a file, having each start with "Test" makes scanning difficult.

Not saying this equals a consensus, only two significant data points and a personal observation.

Chris Lawlor
  • 47,306
  • 11
  • 48
  • 68
  • 1
    Thanks. I do agree with your reasoning. – musabaloyi Mar 27 '14 at 09:06
  • 1
    I personally do this, and it's convenient for autocompleting things too. – turiyag Aug 09 '18 at 17:34
  • 2
    That's a good point, but if you list symbols in a module (`Ctrl+Shift+O` in VS Code), it's much easier to find the test cases if they're `test`-prefixed because these lists are typically alphabetically sorted. Most autocomplete algorithms don't require you to start typing names from the beginning anymore either. – natiiix Aug 05 '19 at 15:15