mawelpac
mawelpac

Reputation: 35

Run multiple unittest.TestCase methods with the same random data in each one

I would like to execute test suite with Selenium RC in Python. In this set of tests I would like to:

  1. With help of Selenium simulate user input data on website
  2. Check if data are correctly put into database
  3. Get an email from selected account and parse it to check if data is correct

All tests are in principle finished, but they do not work as entire test suite containing those three tests. I tried to generate data in setUp method, but in all tests the data was different. I already learned that in every test execution setUp() and tearDown() methods are run so I tried to move my data generators into test class constructor, but I still can't deal with it.

Structure of my test looks as follows:

class TestClass(unittest.TestCase):
  def __init__(self, TestClass):
     unittest.TestCase.__init__(self, TestClass)
     self.define_random_data()
  def setUp(self):
    db_connection_function(self)
  def some_internal_methods(self):
    ...
  def test_website_data_input(self):
    ...
  def test_db_test(self):
    ...
  def test_email_parse(self):
    ...
  def tearDown(self):
    ...
suite = unittest.TestLoader().loadTestsFromTestCase(TestClass)
unittest.TextTestRunner(verbosity=2).run(suite)

What am I doing wrong? In every test generated data is different and I do not know how to deal with it - I tried to run this method in every possible place, but it is still wrong.

Upvotes: 1

Views: 1859

Answers (1)

aychedee
aychedee

Reputation: 25589

Ah okay. A new instance of the TestClass is created for each test method that is run. So you would have to do this.

import unittest
import random
random_data = random.random()

class TestClass(unittest.TestCase):
    def __init__(self, TestClass):
        unittest.TestCase.__init__(self, 'test_first')
        self.data = random_data

    def test_first(self):
        self.fail(self.data)

    def test_second(self):
        self.fail(self.data)

if __name__ == '__main__':
    unittest.main()

I've just tested that and prints out the same failure message for each test. The random data is only generated on the import of the test module.

Upvotes: 1

Related Questions