Skip to content

Commit

Permalink
working on tests.
Browse files Browse the repository at this point in the history
  • Loading branch information
benami171 committed Aug 31, 2024
1 parent ff4aab4 commit 2e486c1
Show file tree
Hide file tree
Showing 9 changed files with 197 additions and 65 deletions.
2 changes: 1 addition & 1 deletion QUIC.py
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,7 @@ def __init__(self, stream_id: int, packets_amount: int, frames_amount: int, byte

class QUIC_PACKET:
packet_id_counter = 0
Max_size = 20000
Max_size = 9000
HEADER_LENGTH = struct.calcsize('!BIQ')
FRAME_LENGTH = struct.calcsize('!IIQ')
MAX_DATA_SIZE = Max_size - HEADER_LENGTH
Expand Down
240 changes: 184 additions & 56 deletions QUIC_TEST.py
Original file line number Diff line number Diff line change
@@ -1,58 +1,186 @@
import unittest
import subprocess
import difflib
import os

FILE1 = "random_data_file.txt"
NUM_OF_FILES = 3

class MyTestCase(unittest.TestCase):

def setUp(self):
"""
Ensure the environment is clean before running tests.
"""
self.cleanup_files()

def cleanup_files(self):
for i in range(1, NUM_OF_FILES + 1):
try:
os.remove(f"output_f{i}.txt")
except OSError:
pass

def run_receiver(self):
subprocess.run(["python", "receiver.py"], check=True)

def run_sender(self):
subprocess.run(["python", "sender.py"], check=True)

def compare_files(self):
with open(FILE1, "r", encoding="utf-8") as original_file:
original_content = original_file.readlines()
for i in range(1, NUM_OF_FILES + 1):
with open(f"output_f{i}.txt", "r", encoding="utf-8") as output_file:
output_content = output_file.readlines()
diff = difflib.unified_diff(
original_content,
output_content,
fromfile=FILE1,
tofile=f"output_f{i}.txt",
)

if list(diff):
raise AssertionError(f"output_f{i}.txt is different from {FILE1}")

def test_run_and_compare(self):
self.run_receiver()
self.run_sender()
self.compare_files()

def tearDown(self):
"""
Clean up files after running tests.
"""
self.cleanup_files()
# from QUIC import *
# import threading
# import asyncio
#
# HOST = '127.0.0.1'
# PORT = 9191
# FILE_TO_SEND = "random_data_file.txt"
# NUMBER_OF_STREAMS = 3
#
#
# async def start_receiver():
# conn = QUIC_CONNECTION()
# conn.listen_incoming_connections(HOST, PORT)
# file_data = []
#
# while True:
# new_file_data = await conn.receive_data()
# if new_file_data is None:
# break
# file_data = new_file_data
#
# if len(file_data) != NUMBER_OF_STREAMS:
# print("Error: Insufficient number of files received")
# return
#
# with open(FILE_TO_SEND, 'rb') as f1:
# original_data = f1.read()
# for file in file_data:
# if original_data != file:
# print("Error: Files are not equal")
# return
#
# print("Comparison successful")
# return
#
#
# async def start_sender():
# await asyncio.sleep(1) # wait for the receiver to start listening
# with open(FILE_TO_SEND, "rb") as f:
# file_data = f.read()
# conn = QUIC_CONNECTION()
# conn.connect_to(HOST, PORT)
# await conn.send_data([file_data] * NUMBER_OF_STREAMS)
# conn.end_communication()
#
#
# def run_async_function(func):
# # Run the async function
# asyncio.set_event_loop(asyncio.new_event_loop())
# loop = asyncio.get_event_loop()
# result = loop.run_until_complete(func())
# loop.close()
# return result
#
#
# def main():
# receiver_result = None
#
# def run_receiver():
# nonlocal receiver_result
# receiver_result = run_async_function(start_receiver)
#
# def run_sender():
# run_async_function(start_sender)
#
# # Run the receiver and sender in two different threads
# receiver_thread = threading.Thread(target=run_receiver)
# sender_thread = threading.Thread(target=run_sender)
#
# receiver_thread.start()
# sender_thread.start()
#
# # Wait for the two threads to finish
# receiver_thread.join()
# sender_thread.join()
#
# # Print the results
# print(receiver_result)
#
#
# if __name__ == '__main__':
# main()
import time

from QUIC import QUIC_CONNECTION as QuicConn
import threading
import asyncio

# Server and client configuration
SERVER_ADDRESS = '127.0.0.1'
SERVER_PORT = 9191
SOURCE_FILE = "random_data_file.txt"
STREAMS_COUNT = 3


async def receive_files():
# Setup QUIC connection and listen for incoming connections
receiver_conn = QuicConn()
receiver_conn.listen_incoming_connections(SERVER_ADDRESS, SERVER_PORT)
received_files = []

while True:
incoming_data = await receiver_conn.receive_data()
if incoming_data is None:
break
received_files = incoming_data

# Verify the number of received files
if len(received_files) != STREAMS_COUNT:
print("Error: Mismatch in the number of received files")
return

# Compare each received file with the original file data
with open(SOURCE_FILE, 'rb') as original_file:
original_content = original_file.read()
for received_content in received_files:
if received_content != original_content:
print("Error: Discrepancy found in file contents")
return

print("File transfer successful and contents match.")
return


async def send_files():
# Delay to ensure the receiver is ready
await asyncio.sleep(1)

# Read and send file data using QUIC connection
with open(SOURCE_FILE, "rb") as source_file:
file_content = source_file.read()
sender_conn = QuicConn()
sender_conn.connect_to(SERVER_ADDRESS, SERVER_PORT)
await sender_conn.send_data([file_content] * STREAMS_COUNT)
sender_conn.end_communication()


def execute_async_task(async_task):
# Initialize and run the event loop for asynchronous tasks
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
result = loop.run_until_complete(async_task())
finally:
loop.close()
return result


def execute_receiver():
return execute_async_task(receive_files)


def execute_sender():
time.sleep(1)
return execute_async_task(send_files)


def run_transfer():
receiver_output = None

# Wrapper functions for threading
def initiate_receiver():
nonlocal receiver_output
receiver_output = execute_receiver()

def initiate_sender():
execute_sender()

# Create and start threads for receiver and sender
receiver_thread = threading.Thread(target=initiate_receiver)

sender_thread = threading.Thread(target=initiate_sender)

receiver_thread.start()
sender_thread.start()

# Wait for both threads to complete
receiver_thread.join()
sender_thread.join()

# Display the result of the file transfer
print(receiver_output)


if __name__ == '__main__':
unittest.main()
run_transfer()
9 changes: 6 additions & 3 deletions generate_data_file.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import os
import random

def generate_data_file(file_name: str, size_in_mb: int):
file_path = os.path.join(os.getcwd(), file_name)
with open(file_path, 'wb') as file:
file.write(os.urandom(size_in_mb * 1024 * 1024))
characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
data = ''.join(random.choice(characters) for _ in range(size_in_mb * 1024 * 1024))
with open(file_path, 'w') as file:
file.write(data)

if __name__ == "__main__":
generate_data_file("small_data_file.txt", 2)
generate_data_file("random_data_file.txt", 1)
Binary file removed output_f0.txt
Binary file not shown.
Binary file removed output_f1.txt
Binary file not shown.
Binary file removed output_f2.txt
Binary file not shown.
Binary file modified random_data_file.txt
Binary file not shown.
2 changes: 1 addition & 1 deletion receiver.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
LISTEN_PORT = 9191


async def accept_data():
async def accept_data() -> None:
conn = QUIC_CONNECTION()
conn.listen_incoming_connections(BIND_ADDRESS, LISTEN_PORT)

Expand Down
9 changes: 5 additions & 4 deletions sender.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,13 @@

import asyncio
from QUIC import QUIC_CONNECTION
from QUIC_TEST import FILE_TO_SEND

LOCAL_ADDRESS = '127.0.0.1'
TARGET_PORT = 9191


async def transmit_data():
async def transmit_data(file_to_send: str, num_of_streams: int):
"""
This method is used to send data to the receiver. The data is read from a file and sent to the receiver.
The method is defined as an asynchronous method to allow for the use of the await keyword,
Expand All @@ -38,10 +39,10 @@ async def transmit_data():
conn = QUIC_CONNECTION()
conn.connect_to(LOCAL_ADDRESS, TARGET_PORT)

with open("random_data_file.txt", "rb") as file:
with open(FILE_TO_SEND, "rb") as file:
content = file.read()

num_of_streams = int(input("Enter the desired number of streams: "))
# num_of_streams = int(input("Enter the desired number of streams: "))
payload = [content] * num_of_streams
await conn.send_data(payload)

Expand All @@ -51,7 +52,7 @@ async def transmit_data():


def main():
asyncio.run(transmit_data())
asyncio.run(transmit_data(FILE_TO_SEND, 3))


if __name__ == '__main__':
Expand Down

0 comments on commit 2e486c1

Please sign in to comment.