2018-10-08 17:51:02 +00:00
|
|
|
import pytest
|
|
|
|
import os
|
2018-10-09 01:29:51 +00:00
|
|
|
import asyncio
|
|
|
|
import hashlib
|
|
|
|
import uvloop
|
2018-10-11 00:28:54 +00:00
|
|
|
from p2pfs import Tracker, Peer
|
2018-10-08 17:51:02 +00:00
|
|
|
|
|
|
|
TEST_SMALL_FILE = 'test_small_file'
|
2018-10-10 03:53:03 +00:00
|
|
|
TEST_SMALL_FILE_1 = 'test_small_file_1'
|
2018-10-08 17:51:02 +00:00
|
|
|
TEST_LARGE_FILE = 'test_large_file'
|
2018-10-08 18:08:30 +00:00
|
|
|
TEST_SMALL_FILE_SIZE = 1000
|
|
|
|
TEST_LARGE_FILE_SIZE = 500 * 1000 * 1000
|
2018-10-08 17:51:02 +00:00
|
|
|
|
|
|
|
|
2018-10-09 01:29:51 +00:00
|
|
|
def fmd5(fname):
|
|
|
|
""" calculate the md5 value of a file
|
|
|
|
:param fname: file name
|
|
|
|
:return: md5 value.
|
|
|
|
"""
|
|
|
|
hash_md5 = hashlib.md5()
|
|
|
|
with open(fname, "rb") as f:
|
|
|
|
for chunk in iter(lambda: f.read(4096), b""):
|
|
|
|
hash_md5.update(chunk)
|
|
|
|
return hash_md5.hexdigest()
|
|
|
|
|
|
|
|
|
2018-10-11 00:28:54 +00:00
|
|
|
async def setup_tracker_and_peers(peer_num, tracker_port):
|
|
|
|
tracker = Tracker()
|
|
|
|
peers = tuple(Peer() for _ in range(peer_num))
|
2018-10-13 21:47:58 +00:00
|
|
|
await tracker.start(('localhost', tracker_port))
|
2018-10-11 00:28:54 +00:00
|
|
|
# spawn peers concurrently
|
2018-10-13 21:47:58 +00:00
|
|
|
await asyncio.gather(*[peer.start(('localhost', 0)) for peer in peers])
|
2018-10-13 20:40:38 +00:00
|
|
|
await asyncio.gather(*[peer.connect(('localhost', tracker_port)) for peer in peers])
|
2018-10-11 00:28:54 +00:00
|
|
|
return tracker, peers
|
|
|
|
|
|
|
|
|
2018-10-08 17:51:02 +00:00
|
|
|
@pytest.fixture(scope='session', autouse=True)
|
|
|
|
def create_test_files(request):
|
2018-10-09 01:29:51 +00:00
|
|
|
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
|
2018-10-08 17:51:02 +00:00
|
|
|
with open(TEST_SMALL_FILE, 'wb') as fout:
|
|
|
|
fout.write(os.urandom(1000))
|
|
|
|
|
2018-10-10 03:53:03 +00:00
|
|
|
with open(TEST_SMALL_FILE_1, 'wb') as fout:
|
|
|
|
fout.write(os.urandom(1000))
|
|
|
|
|
2018-10-08 17:51:02 +00:00
|
|
|
with open(TEST_LARGE_FILE, 'wb') as fout:
|
|
|
|
# write 500MB random data into the file
|
|
|
|
for _ in range(500):
|
|
|
|
fout.write(os.urandom(1000 * 1000))
|
|
|
|
|
|
|
|
def delete_files():
|
|
|
|
os.remove(TEST_SMALL_FILE)
|
2018-10-10 03:53:03 +00:00
|
|
|
os.remove(TEST_SMALL_FILE_1)
|
2018-10-08 17:51:02 +00:00
|
|
|
os.remove(TEST_LARGE_FILE)
|
|
|
|
|
|
|
|
request.addfinalizer(delete_files)
|