Tribler/py-ipv8

Don't read/write to files while unit testing

Closed this issue · 0 comments

Our TestBase case has facilities to create temporary files. However, ideally, these should never be used. Even so, this functionality is used in the following two locations:

File "ipv8/test/REST/test_identity_endpoint.py", line 34, in create_node
    temp_dir = self.temporary_directory()

async def create_node(self, *args, **kwargs):
"""
We load each node i with a pseudonym `my_peer{i}`, which is the default IPv8 `my_peer` key.
"""
ipv8 = await super(TestIdentityEndpoint, self).create_node(*args, **kwargs)
temp_dir = self.temporary_directory()
key_file_name = 'my_peer' + str(len(self.pseudonym_directories))
with open(os.path.join(temp_dir, key_file_name), 'wb') as f:
f.write(ipv8.my_peer.key.key_to_bin())
communication_manager = ipv8.rest_manager.root_endpoint.endpoints['/identity'].communication_manager
communication_manager.working_directory = ':memory:'
communication_manager.pseudonym_folder = temp_dir
identity_overlay = ipv8.get_overlay(IdentityCommunity)
attestation_overlay = AttestationCommunity(identity_overlay.my_peer, identity_overlay.endpoint,
identity_overlay.network, working_directory=':memory:')
channel = CommunicationChannel(attestation_overlay, identity_overlay)
communication_manager.channels[ipv8.my_peer.public_key.key_to_bin()] = channel
communication_manager.name_to_channel[key_file_name] = channel
self.pseudonym_directories.append(temp_dir)
return ipv8

Fixed in #1158
File "ipv8/test/attestation/wallet/test_attestation_community.py", line 307, in test_load_key
    temp_folder = self.temporary_directory()

def test_load_key(self):
"""
Check if we can load the community correctly after shut down.
"""
# Write to a temporary folder.
temp_folder = self.temporary_directory()
self.overlay(0).database = AttestationsDB(temp_folder, "test")
# Create an attestation and write it to file.
# Then close the database.
attestation = BonehAttestation(TestCommunity.private_key.public_key(), [], "id_metadata")
self.overlay(0).on_attestation_complete(attestation, TestCommunity.private_key, None, "test", b"a" * 20,
"id_metadata")
self.overlay(0).database.close(True)
# Reload the community with the same database.
self.overlay(0).__init__(self.my_peer(0), self.endpoint(0), self.network(0), working_directory=temp_folder,
db_name="test")
# The attestation should persist
db_entries = self.overlay(0).database.get_all()
self.assertEqual(1, len(db_entries))

We should try to refactor these two cases to not use real file I/O.