Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any way to pass args from test to setUp() method for a Python unittest test?

Is there a way to pass arguments to the setUp() method from a given test, or some other way to simulate this? e.g.,

import unittest

class MyTests(unittest.TestCase):
    def setUp(self, my_arg):
        # use the value of my_arg in some way

    def test_1(self):
        # somehow have setUp use my_arg='foo'
        # do the test

    def test_2(self):
        # somehow have setUp use my_arg='bar'
        # do the test
like image 628
Rob Bednark Avatar asked May 08 '14 18:05

Rob Bednark


People also ask

Can we use pytest and unittest together?

pytest supports running Python unittest -based tests out of the box. It's meant for leveraging existing unittest -based test suites to use pytest as a test runner and also allow to incrementally adapt the test suite to take full advantage of pytest's features.

What is the purpose of using self ID in tests while working with unittest in Python?

b) self.id returns the name of method The test object is represented by the string returned. The string returned consists of the full name of the test method, It's module name, it's class name.

Is PyUnit the same as unittest?

Yes. unittest is a xUnit style frameworkfor Python, it was previously called PyUnit.


1 Answers

setUp() is a convenience method and doesn't have to be used. Instead of (or in addition to) using the setUp() method, you can use your own setup method and call it directly from each test, e.g.,

class MyTests(unittest.TestCase):
    def _setup(self, my_arg):
        # do something with my_arg

    def test_1(self):
        self._setup(my_arg='foo')
        # do the test

    def test_2(self):
        self._setup(my_arg='bar')
        # do the test
like image 152
Rob Bednark Avatar answered Sep 27 '22 22:09

Rob Bednark