Do not judge strictly) I have been puzzling for 5 hours and read literature, but I can not understand the meaning. There is a request to the server that returns the response code: resp=requests.get('http://q.com') . I need to write a test to check the correctness of the code by type:

 def func(x): return x + 1 def test_answer(): assert func(3) == 5 

Below are my attempts

 import requests def Test_fuction(): resp=requests.get('http://q.com') return resp.status_code assert resp.status_code == 200 

Result: no tests ran in 0.12 seconds

  • assert resp.status_code == 200 will fail; is after return - gil9red
  • test with a small letter, not? - andreymal
  • Tried with a little d-does not help. Below was an example through unittest. I'll be using it for now. Later I'll come back and try to make this code workable. - Alex Koss

2 answers 2

  1. Pytest collects tests from modules with names starting with test_ (although you can specify the module name explicitly when calling pytest), classes for Test and functions for test_ , and can also collect all test modules from the tests folder (I don’t remember the exact rules, I need to look at the documentation) . Accordingly, your function should be called test_function .
  2. Remove from the testing function return . The testing function is not required to return anything (although this is not prohibited), but in this case, the output occurs before assert , so the check is not performed. In the example from your question, func is a test function, it returns a value, test_answer is a testing function, it does not return anything, it just checks the results of a call to the function under test. assert can be several assert in one function, for example, if we check the response status first, then the presence of some text in the response, etc.

Based on this, the test_module.py file:

 import requests def test_function(): resp=requests.get('http://q.com') assert resp.status_code == 200 # сначала проверяем статус assert 'welcome' in resp.text # потом проверяем наличие слова welcome в ответе 

Run py.test , we get the result:

 ============================= test session starts ============================= platform win32 -- Python 3.5.3, pytest-3.5.0, py-1.5.3, pluggy-0.6.0 rootdir: ***, inifile: collected 1 item test_module.py . [100%] ========================== 1 passed in 2.77 seconds =========================== 
  • Very informative answer! Thank you very much! - Alex Koss
 import unittest import requests class TRequest(unitest.TestCase): def test_simple_get(self): req = requests.get('http://q.com') req.raise_for_status() self.assertEqual(req.status_code, 200) unittest.main() 
  • Thank you! I will try through unittest. Everything works with the corrected code, there were a couple of inaccuracies. - Alex Koss