carta / styleguide

Carta's style guides
26 stars 5 forks source link

Classes for methods under test #3

Open bhardin opened 6 years ago

bhardin commented 6 years ago

Discussion on best practice of Classes for methods.

rbusquet commented 6 years ago

What if a single test covers a simple method. If we have the files named after the class, say a class has a simple method that would be tested with a single test, Say:

# -- some/package/main.py --
class ClassA:
    def capitalize_text(self, text):
        # ...

# -- tests/unit/some/package/main/class_a.py --

# this is a single test that would cover the expected result
def test_capitalize_text():
    assert ClassA().capitalize_text('test text') == 'Test text'

# the convention requires this to be like
class TestCapitalizeText:
    def test_capitalizes_text(self):
        assert ClassA().capitalize_text('test text') == 'Test text'

Enforcing the idea of pytest as a functional library for tests, I believe using classes:

  1. resembles the structure of using TestCase
  2. can get a little verbose for simple tests.

Waiting for responses on that matter :) awesome job on getting this together.

bhardin commented 6 years ago

It may be a little more verbose (1 line) in simple test cases. However, as classes begin growing and doing more, the structure is already setup for the next person to add to. I see it as an "Explicit is better than implicit" and "convention over configuration".

I see it as keeping tests together by class helps encapsulate behavior.

wagnerluis1982 commented 6 years ago

I have to say that, in general, I would never use this convention, too many classes to create. However I could have another opinion in face of bigger projects than I'm used to.

wagnerluis1982 commented 6 years ago

Additionally, I can see that this convention of one class per method is logical, after all we are talking of unit tests, so we should not mix things!

Congrats for the good work!

JamesHutchisonCarta commented 4 years ago

Typically I write a test class per class under test. I.E.

class TestCar:
    def test_open_door_changes_air_pressure():
         ...

Having a test class per function under test feels over-verbose to me.

JamesHutchisonCarta commented 4 years ago

Additionally the test structure should, IMO, try to mirror the actual code structure, but with test_ in front.

rbusquet commented 4 years ago

It's a matter of code organization. How would you visually identify groups of tests that map to a class method? If the file name maps the class we're testing, it makes sense to group tests on different methods with different classes.