ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Python json dump and load
    Python/pytest 2022. 1. 1. 13:40

    How to use json dump and json load from fixtures using tmpdir_factory?

     

    We need two separate files

    First conftest.py file, and the second test_auhor.py file

    #conftest.py
    
    @pytest.fixture(scope="module")
    def author_file_json(tmpdir_factory):
        """Write some authors to a data file."""
        python_author_data = {
            'Ned': {'City':'Boston'},
            'Brian': {'City': 'Portland'},
            'Luciano': {'City': 'Sau Paulo'}
        }
    
        file = tmpdir_factory.mktemp('data').join('author_file.json')
        print(f"file : {str(file)}")
    
        with open(file, 'w') as fp:
            json.dump(python_author_data, fp)
    
        return file
    #test_author.py
    
    """Some tests that use temp data files."""
    
    import json
    
    def test_brian_in_portland(author_file_json):
        with author_file_json.open() as f:
            authors = json.load(f)
        
        assert authors['Brian']['City'] == 'Portland'
    
    def test_all_have_cities(author_file_json):
        with open(author_file_json, 'r') as f:
            authors = json.load(f)
    
        for key in authors:
            assert len(authors[key]['City']) > 0

    댓글