def mock_credentials_file(geocaching: Geocaching, contents: Union[bytes, dict, list, str]): """Create a temporary credentials file with given contents and mock a Geocaching instance to use it.""" backup = geocaching._credentials_file f = NamedTemporaryFile(delete=False) try: # bytes are written as-is, others are encoded to JSON if type(contents) is bytes: f.write(contents) else: f.write(json.dumps(contents).encode("utf-8")) f.flush() f.close() geocaching._credentials_file = f.name yield finally: os.remove(f.name) geocaching._credentials_file = backup