2

I try to unittest if a file gets saved correctly. The unittest works if I run it directly with python -m unittest test.test_save But if I try to run all unittests at once with python -m unittest discover every test runs perfecty except of the save test. Test Code:

def test_save(self):
    with patch('builtins.open', mock_open()) as fake_open:
        Saver.save(Player("Bob", True), Player("Ross", False))
        fake_open().write.assert_called_with(self.dummyjson)

Function to test:

def save(player1, player2):
    with open(FILENAME, 'w') as file_score:
        data: dict = {
            "player1": {
                "name": player1.name,
                "human": player1.human,
                "field_own": player1.board.field_own,
                "field_enemy": player1.board.field_enemy,
            },
            "player2": {
                "name": player2.name,
                "human": player2.human,
                "field_own": player2.board.field_own,
                "field_enemy": player2.board.field_enemy,
            }
        }
        file_score.write(json.dumps(data))

With coverage I could see, that with unittest discover the with open() statement won't be executed at all. Thus the mock isn't registering any calls. When directly executing this test the with open() statement gets executed normally and I have 100% coverage.

Can anyone explain why this happens and maybe has a workaround?

Edit Project Tree:

Project Directory/
├─ modules/
│  ├─ __init__,py
│  ├─ module1.py
│  ├─ module2.py
│  ├─ save.py
├─ test/
│  ├─ __init__.py
│  ├─ test_module1.py
│  ├─ test_module2.py
│  ├─ test_save.py
├─ main.py
DomeE__
  • 21
  • 3
  • So what are you saying is that this test is not discovered, while the others are, right? Can you show your test module/class layout? – MrBean Bremen Apr 27 '21 at 17:11
  • The test is discovered. And another test method in this file runs also without a problem. Coverage also shows that save() in the test method is called correctly, but in the actual code the save() method never gets called. (When running with discover). When running directly the save() method in the code gets called, too. I edit my question to provide a project tree. – DomeE__ Apr 27 '21 at 17:15
  • Hm, weird - looks like `unittest.discover` has some side effect here. The test structure itself is certainly not the problem. I would try to debug into this, or at least do some print-debugging to understand what is going on - without having the code it is difficult to say (at least for me). – MrBean Bremen Apr 27 '21 at 17:36

0 Answers0