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