For cycle in unittest

Is there a way to say that python unittest executes all the statements in the method and shows all the cases when it fails, instead of stopping on the first failure.

class MyTestCase(TestCase): def test_a(self): with open('testcase.txt') as ifile: for iline in ifile: self.assertEqual(iline, 'it is a test!') 
+5
source share
3 answers

Python 3.4 introduced the subTest context subTest . Your code will look like

 class MyTestCase(TestCase): def test_a(self): with open('testcase.txt') as ifile: for iline in ifile: with self.subTest(line=iline): self.assertEqual(iline, 'it is a test!') 

An ugly way to achieve this without subTest is to make self.assert* calls in the try block, print out the detected errors, and explicitly AssertionError after the loop if at least one test fails.

+7
source

Alternatively, you can perform data validation with the ddt package :

DDT (Data-Driven Tests) allows you to multiply one test case by running it with different test data and making it appear as several test cases.

 import unittest from ddt import ddt, data @ddt class FooTestCase(unittest.TestCase): @data('it is a test!', 'it is a test!', 'something else') def test_lines(self, value): self.assertEqual(value, 'it is a test!') 

ddt may also have data coming from a file , but it must be a JSON file.

+3
source

Generally not. First, device tests are disabled. If you want to compare all the lines, you need to have a local list, and then put different lines in the list. Then assert that the length of the list is zero. Or a local boolean variable.

+1
source

Source: https://habr.com/ru/post/1205066/


All Articles