Skip to content

file-transfer: writing tests and ensuring that all is going well #2413

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Sep 11, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 7 additions & 10 deletions file_transfer/send_file.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,6 @@
if __name__ == "__main__":
import socket # Import socket module

ONE_CONNECTION_ONLY = (
True # Set this to False if you wish to continuously accept connections
)
def send_file(filename: str = "mytext.txt", testing: bool = False) -> None:
import socket

filename = "mytext.txt"
port = 12312 # Reserve a port for your service.
sock = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
Expand All @@ -29,10 +24,12 @@

print("Done sending")
conn.close()
if (
ONE_CONNECTION_ONLY
): # This is to make sure that the program doesn't hang while testing
if testing: # Allow the test to complete
break

sock.shutdown(1)
sock.close()


if __name__ == "__main__":
send_file()
32 changes: 32 additions & 0 deletions file_transfer/tests/test_send_file.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
from unittest.mock import patch, Mock


from file_transfer.send_file import send_file


@patch("socket.socket")
@patch("builtins.open")
def test_send_file_running_as_expected(file, sock):
# ===== initialization =====
conn = Mock()
sock.return_value.accept.return_value = conn, Mock()
f = iter([1, None])
file.return_value.__enter__.return_value.read.side_effect = lambda _: next(f)

# ===== invoke =====
send_file(filename="mytext.txt", testing=True)

# ===== ensurance =====
sock.assert_called_once()
sock.return_value.bind.assert_called_once()
sock.return_value.listen.assert_called_once()
sock.return_value.accept.assert_called_once()
conn.recv.assert_called_once()

file.return_value.__enter__.assert_called_once()
file.return_value.__enter__.return_value.read.assert_called()

conn.send.assert_called_once()
conn.close.assert_called_once()
sock.return_value.shutdown.assert_called_once()
sock.return_value.close.assert_called_once()
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ black
fake_useragent
flake8
keras
lxml
matplotlib
mypy
numpy
Expand Down