-1
\$\begingroup\$

Background: The following code is unit-testing for another program called pw in the code. The "module-level data" is represented in the @classmethods. The setUp creates a storage.json data dictionary, and the tearDownClass deletes it.

I'm curious about functions being tested--is it acceptable that the main functions being tested rely on other functions of the program?
Here are the tests (47 lines):

import os
import pw
import pyperclip
import unittest
# from unittest.mock import patch


class TestPw(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        pw.initialize()
        f = pw.initialize_storage()
        cls.f = f
        return cls.f

    def test_load_manager(self):
        self.assertIsInstance(pw.load_manager(), dict)

    def test_add_new(self):
        pw.add_new("test_account", "test_value", self.f)
        self.assertTrue(pw.exist_in_storage("test_account", pw.load_manager()))

    def test_retrieve(self):
        pw.add_new("test_account", "test_value", self.f)
        pw.retrieve("test_account", self.f)
        self.assertEqual(pyperclip.paste(), "test_value")

    def test_update(self):
        pw.add_new("test_account", "test_value", self.f)
        pw.update("test_account", "new_test_value", self.f)
        pw.retrieve("test_account", self.f)
        self.assertEqual(pyperclip.paste(), "new_test_value")

    def test_delete(self):
        pw.delete("test_account")
        self.assertFalse(pw.exist_in_storage("test_account",
                         pw.load_manager()))

    @classmethod
    def tearDownClass(cls):
        os.remove("storage.json")


if __name__ == '__main__':
    unittest.main()
\$\endgroup\$
4
  • \$\begingroup\$ You should add a bit more information about what the goal of this code is. \$\endgroup\$
    – Graipher
    Oct 18, 2017 at 12:16
  • \$\begingroup\$ @Graipher they're purely tests. Did you mean what the goal of the main program is? edit: the program being tested? pw? \$\endgroup\$
    – Homer
    Oct 18, 2017 at 12:18
  • 1
    \$\begingroup\$ Yes, I see. In this case maybe add a sentence saying that this code is to test the pw module (this is the one from pip, right?). \$\endgroup\$
    – Graipher
    Oct 18, 2017 at 12:20
  • \$\begingroup\$ No, it's not from pip. It's simply what I named my program. \$\endgroup\$
    – Homer
    Oct 18, 2017 at 12:23

1 Answer 1

1
\$\begingroup\$

This seems like the usecase for the setup/teardown functions which are run before and after each test. I would not use the setupclass and teardownclass methods as these functions are called once for the whole test suite, and as a result could result in test pollution where one test impacts another. Test pollution can be incredibly time consuming to troubleshoot.

\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.