Is this a good way to implement testing

Mark Lawrence breamoreboy at yahoo.co.uk
Sun May 3 06:21:36 EDT 2015


On 03/05/2015 10:49, Cecil Westerhof wrote:
> Op Sunday 3 May 2015 10:45 CEST schreef Peter Otten:
>
>> Cecil Westerhof wrote:
>>
>>> Another question. Is it acceptable to have it in the module itself,
>>> or should I put it in something like test_<module>.py? The code for
>>> testing is bigger as the code for the implementation, so I am
>>> leaning to putting it in a separate file.
>>
>> Definitely use an established testing framework instead of rolling
>> your own, and definitely put it into a separate file -- by the time
>> there is good coverage the test code is usually much bigger than the
>> tested code.
>
> Yep, the module already has 370 lines of testing code and only 225 of
> working code. And I just started.
>
>
>> Be aware that there is also doctest which scans docstrings for text
>> resembling interactive Python sessions. Doctests are both tests and
>> usage examples, so I think it's good to put a few of these into the
>> module. Here's how it works:
>>
>> $ cat factorial.py
>> def factorial(n):
>> """Calculate the factorial 1 * 2 * ... * n.
>>
>>>>> factorial(0)
>> 1
>>>>> factorial(1)
>> 1
>>>>> factorial(10)
>> 3628800 """ return 1 $ python3 -m doctest factorial.py
>> **********************************************************************
>> File "/home/peter/clpy/factorial.py", line 8, in factorial.factorial
>> Failed example: factorial(10) Expected: 3628800 Got: 1
>> **********************************************************************
>> 1 items had failures: 1 of 3 in factorial.factorial ***Test
>> Failed*** 1 failures. $
>
> That looks very promising. But I use the test to verify the
> correctness and show the performance. Is that also possible? Or should
> I split those out.
>

Get it working correctly and if it's fast enough for your needs then job 
done.  If and only if you actually have a performance issue profile your 
code to find the bottlenecks, as gut instinct about Python performance 
is wrong 99.99% of the time.

-- 
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence




More information about the Python-list mailing list