async def _use_stored_companions(self) -> AsyncGenerator[List[CompanionInfo], None]: async with _open_lockfile(filename=self.state_file_path): # Create the state file Path(self.state_file_path).touch(exist_ok=True) fresh_state = False with open(self.state_file_path, "r") as f: try: companion_info_in = json_to_companion_info(json.load(f)) except json.JSONDecodeError: fresh_state = True self.logger.info( "State file is invalid or empty, creating empty companion info" ) companion_info_in = [] companion_info_in = sorted( companion_info_in, key=lambda companion: companion.udid ) companion_info_out = list(companion_info_in) yield companion_info_out companion_info_out = sorted( companion_info_out, key=lambda companion: companion.udid ) if fresh_state: self.logger.info( f"Created a fresh companion info of {companion_info_out}, writing to file" ) elif companion_info_in != companion_info_out: self.logger.info( f"Companion info changed from {companion_info_in} to {companion_info_out}, writing to file" ) else: return with open(self.state_file_path, "w") as f: json.dump(json_data_companions(companion_info_out), f)
async def test_add_companion(self) -> None: with tempfile.NamedTemporaryFile() as f: companion_manager = DirectCompanionManager( logger=mock.MagicMock(), state_file_path=f.name ) companion = CompanionInfo( udid="asdasda", host="foohost", port=123, is_local=False ) companion_manager.add_companion(companion) data = json.load(f) companions = json_to_companion_info(data) read_companion: CompanionInfo = companions[0] self.assertEqual(companion, read_companion)
async def _use_stored_companions(self) -> AsyncGenerator[List[CompanionInfo], None]: async with exclusive_rw_open(self.state_file_path) as f: try: companion_info_in = json_to_companion_info(json.load(f)) except json.JSONDecodeError: companion_info_in = [] companion_info_out = list(companion_info_in) yield companion_info_out if companion_info_in == companion_info_out: return f.seek(0) companion_info_out = sorted( companion_info_out, key=lambda companion: companion.udid ) json.dump(json_data_companions(companion_info_out), f) f.truncate()
def test_json_to_companion_info(self) -> None: self.assertEqual( [COMPANION_INFO_FIXTURE], json_to_companion_info(json_data_companions([COMPANION_INFO_FIXTURE])), )
def _load(self) -> List[CompanionInfo]: if os.path.exists(self.state_file_path): with open(self.state_file_path, "r") as f: return json_to_companion_info(json.load(f)) return []
def _load(self) -> List[CompanionInfo]: if os.path.exists(self.state_file_path): # pyre-fixme[16]: `AsyncGenerator` has no attribute `__enter__`. with exclusive_open(self.state_file_path, "r") as f: return json_to_companion_info(json.load(f)) return []