Python unittest to create a mock .json file

Solution 1:

You want to be able to provide different return values for each call to os.path.exists. Since you know the order of the calls, you can use side_effects to supply a list of values to be used in order.

class TestAdminJsonCreation(unittest.TestCase): 

    # No JSON file                                
    @patch('os.path.exists', return_value=True)                                                    
    def test_existing_admin_json(self):                                         
        self.assertNone(postprocess_results.create_json_file())

    # JSON file, log file                                
    @patch('os.path.exists', side_effects=[True, False])                                                    
    def test_existing_admin_json(self):                                         
        self.assertNone(postprocess_results.create_json_file())

    # JSON file, no log file
    @patch('os.path.exists', side_effects=[True, True])                                                    
    def test_existing_admin_json(self):                                         
        ...

The third test requires an actual file system, or for you to mock open.