2017年8月25日 星期五

[Python 文章收集] pytest introduction

Source From Here 
Preface 
I think of pytest as the run-anything, no boilerplate, no required api, use-this-unless-you-have-a-reason-not-to test framework. This is really where testing gets fun. As with previous intro’s on this site, I’ll run through an overview, then a simple example, then throw pytest at my markdown.py project. I’ll also cover fixtures, test discovery, and running unittests with pytest. 

Contents 


No boilerplate, no required api 
The doctest and unittest both come with Python. They are pretty powerful on their own, and I think you should at least know about those frameworks, and learn how to run them at least on some toy examples, as it gives you a mental framework to view other test frameworks. 
Note: 
The module unnecessary_math is non-standard and can be found here: implementation of unnecessary_math.py

With unittest, you a very basic test file might look like this: 
  1. import unittest  
  2. from unnecessary_math import multiply  
  3.   
  4. class TestUM(unittest.TestCase):  
  5.   
  6.     def test_numbers_3_4(self):  
  7.         self.assertEqual( multiply(3,4), 12)  
The style of deriving from unittest.TestCase is something unittest shares with it’s xUnit counterparts like JUnit. I don’t want to get into the history of xUnit style frameworks. However, it’s informative to know that inheritance is quite important in some languages to get the test framework to work right. 

But this is Python. We have very powerful introspection and runtime capabilities, and very little information hiding. Pytest takes advantage of this. An identical test as above could look like this if we remove the boilerplate: 
  1. from unnecessary_math import multiply  
  2.   
  3. def test_numbers_3_4():  
  4.     assert( multiply(3,4) == 12 )  
Yep, three lines of code. (Four, if you include the blank line.) 
* There is no need to import unnittest. 
* There is no need to derive from TestCase. 
* There is no need to for special self.assertEqual(), since we can use Python’s built in assert statement.

This works in pytest. Once you start writing tests like this, you won’t want to go back. 

However, you may have a bunch of tests already written for doctest or unittest. Pytest can be used to run doctests and unittests. It also claims to support some twisted trial tests (although I haven’t tried this). You can extend pytest using plugins you pull from the web, or write yourself. I’m not going to cover plugins in this article, but I’m sure I’ll get into it in a future article. 

pytest example 
Using the same unnecessary_math.py module that I wrote in the doctest intro, this is some example test code to test the ‘multiply’ function. 
- pytest_e1.py 
  1. from unnecessary_math import multiply  
  2.   
  3. def test_numbers_3_4():  
  4.     assert multiply(3,4) == 12   
  5.   
  6. def test_strings_a_3():  
  7.     assert multiply('a',3) == 'aaa'   
Running pytest 
To run pytest: 
# pytest pytest_e1.py 
=================================== test session starts =================================== 
platform linux -- Python 3.5.0, pytest-3.2.1, py-1.4.34, pluggy-0.4.0 
rootdir: /root/Tmp, inifile: 
collected 2 items 

pytest_e1.py .. 

================================ 2 passed in 0.01 seconds =================================

And with verbose: 
# pytest -v pytest_e1.py 
=================================== test session starts =================================== 
platform linux -- Python 3.5.0, pytest-3.2.1, py-1.4.34, pluggy-0.4.0 -- /usr/local/bin/python3.5 
cachedir: .cache 
rootdir: /root/Tmp, inifile: 
collected 2 items 

pytest_e1.py::test_numbers_3_4 PASSED 
pytest_e1.py::test_strings_a_3 PASSED 

================================ 2 passed in 0.00 seconds =================================

pytest fixtures 
Although unittest does allow us to have setup and teardown, pytest extends this quite a bit. We can add specific code to run: 
* At the beginning and end of a module of test code (setup_module/teardown_module) 
* At the beginning and end of a class of test methods (setup_class/teardown_class) 
* Alternate style of the class level fixtures (setup/teardown) 
* Before and after a test function call (setup_function/teardown_function) 
* Before and after a test method call (setup_method/teardown_method)

We can also use pytest style fixtures, which are covered in pytest fixtures nuts and bolts. 

I’ve modified our simple test code with some fixture calls, and added some print statements so that we can see what’s going on. Here’s the code: 
- pytest_e2.py 
  1. from unnecessary_math import multiply  
  2.   
  3. def setup_module(module):  
  4.     print("setup_module      module:%s" % module.__name__)  
  5.   
  6. def teardown_module(module):  
  7.     print("teardown_module   module:%s" % module.__name__)  
  8.   
  9. def setup_function(function):  
  10.     print("setup_function    function:%s" % function.__name__)  
  11.   
  12. def teardown_function(function):  
  13.     print("teardown_function function:%s" % function.__name__)  
  14.   
  15. def test_numbers_3_4():  
  16.     print('test_numbers_3_4  <============================ actual test code')  
  17.     assert multiply(3,4) == 12  
  18.   
  19. def test_strings_a_3():  
  20.     print('test_strings_a_3  <============================ actual test code')  
  21.     assert multiply('a',3) == 'aaa'  
  22.   
  23.   
  24. class TestUM:  
  25.   
  26.     def setup(self):  
  27.         print("setup             class:TestStuff")  
  28.   
  29.     def teardown(self):  
  30.         print("teardown          class:TestStuff")  
  31.   
  32.     def setup_class(cls):  
  33.         print("setup_class       class:%s" % cls.__name__)  
  34.   
  35.     def teardown_class(cls):  
  36.         print("teardown_class    class:%s" % cls.__name__)  
  37.   
  38.     def setup_method(self, method):  
  39.         print("setup_method      method:%s" % method.__name__)  
  40.   
  41.     def teardown_method(self, method):  
  42.         print("teardown_method   method:%s" % method.__name__)  
  43.   
  44.     def test_numbers_5_6(self):  
  45.         print('test_numbers_5_6  <============================ actual test code')  
  46.         assert multiply(5,6) == 30  
  47.   
  48.     def test_strings_b_2(self):  
  49.         print('test_strings_b_2  <============================ actual test code')  
To see it in action, I’ll use the -s option, which turns off output capture. This will show the order of the different fixture calls. 
# pytest -s pytest_e2.py 
... 
pytest_e2.py setup_module module:pytest_e2 
setup_function function:test_numbers_3_4 
test_numbers_3_4 <============================ actual test code 
.teardown_function function:test_numbers_3_4 
setup_function function:test_strings_a_3 
test_strings_a_3 <============================ actual test code 
.teardown_function function:test_strings_a_3 
setup_class class:TestUM 
setup_method method:test_numbers_5_6 
setup class:TestStuff 
test_numbers_5_6 <============================ actual test code 
.teardown class:TestStuff 
teardown_method method:test_numbers_5_6 
setup_method method:test_strings_b_2 
setup class:TestStuff 
test_strings_b_2 <============================ actual test code 
.teardown class:TestStuff 
teardown_method method:test_strings_b_2 
teardown_class class:TestUM 
teardown_module module:pytest_e2 
...

Test discovery 
The unittest module comes with a ‘discovery’ option. Discovery is just built in to pytest. Test discovery was used in my examples to find tests within a specified module. However, pytest can find tests residing in multiple modules, and multiple packages, and even find unittest and doctests. To be honest, I haven’t memorized the discovery rules. I just try to do this, and at seems to work nicely: 
* Name my test modules/files starting with ‘test_’. 
* Name my test functions starting with ‘test_’. 
* Name my test classes starting with ‘Test’. 
* Name my test methods starting with ‘test_’. 
* Make sure all packages with test code have an ‘init.py’ file.

If I do all of that, pytest seems to find all my code nicely. 
If you are doing something else, and are having trouble getting pytest to see your test code, then take a look at the pytest discovery documentation. 

Running unittests from pytest 
To show how pytest handles unittests, here’s a sample run of pytest on the simple unittests I wrote in the unittest introduction: 
# pytest test_um_unittest.py 
============================= test session starts ============================== 
platform win32 -- Python 2.7.3 -- pytest-2.2.4 
collecting ... collected 2 items 

test_um_unittest.py .. 

=========================== 2 passed in 0.07 seconds ===========================
 

# pytest -v test_um_unittest.py 
============================= test session starts ============================== 
platform win32 -- Python 2.7.3 -- pytest-2.2.4 -- C:\python27\python.exe 
collecting ... collected 2 items 

test_um_unittest.py:15: TestUM.test_numbers_3_4 PASSED 
test_um_unittest.py:18: TestUM.test_strings_a_3 PASSED 

=========================== 2 passed in 0.06 seconds ===========================

As you can see, I didn’t provide any extra options, pytest finds unittests automatically. 

More pytest info (links) 


沒有留言:

張貼留言

[Linux 常見問題] What's the best way to send a signal to all members of a process group?

Source From  Here   Question   I want to  kill a whole process tree.  What is the best way to do this using any common scripting languages? ...