Skip to content

Commit 2e790ce

Browse files
meysam81cclauss
andauthored
file-transfer: writing tests and ensuring that all is going well (TheAlgorithms#2413)
* file-transfer: writing tests and ensuring that all is going well * def send_file(filename: str = "mytext.txt", testing: bool = False) -> None: * send_file(filename="mytext.txt", testing=True) * Update send_file.py * requirements.txt: lxml Co-authored-by: Christian Clauss <cclauss@me.com>
1 parent c676956 commit 2e790ce

File tree

3 files changed

+40
-10
lines changed

3 files changed

+40
-10
lines changed

file_transfer/send_file.py

+7-10
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,6 @@
1-
if __name__ == "__main__":
2-
import socket # Import socket module
3-
4-
ONE_CONNECTION_ONLY = (
5-
True # Set this to False if you wish to continuously accept connections
6-
)
1+
def send_file(filename: str = "mytext.txt", testing: bool = False) -> None:
2+
import socket
73

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

3025
print("Done sending")
3126
conn.close()
32-
if (
33-
ONE_CONNECTION_ONLY
34-
): # This is to make sure that the program doesn't hang while testing
27+
if testing: # Allow the test to complete
3528
break
3629

3730
sock.shutdown(1)
3831
sock.close()
32+
33+
34+
if __name__ == "__main__":
35+
send_file()

file_transfer/tests/test_send_file.py

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
from unittest.mock import patch, Mock
2+
3+
4+
from file_transfer.send_file import send_file
5+
6+
7+
@patch("socket.socket")
8+
@patch("builtins.open")
9+
def test_send_file_running_as_expected(file, sock):
10+
# ===== initialization =====
11+
conn = Mock()
12+
sock.return_value.accept.return_value = conn, Mock()
13+
f = iter([1, None])
14+
file.return_value.__enter__.return_value.read.side_effect = lambda _: next(f)
15+
16+
# ===== invoke =====
17+
send_file(filename="mytext.txt", testing=True)
18+
19+
# ===== ensurance =====
20+
sock.assert_called_once()
21+
sock.return_value.bind.assert_called_once()
22+
sock.return_value.listen.assert_called_once()
23+
sock.return_value.accept.assert_called_once()
24+
conn.recv.assert_called_once()
25+
26+
file.return_value.__enter__.assert_called_once()
27+
file.return_value.__enter__.return_value.read.assert_called()
28+
29+
conn.send.assert_called_once()
30+
conn.close.assert_called_once()
31+
sock.return_value.shutdown.assert_called_once()
32+
sock.return_value.close.assert_called_once()

requirements.txt

+1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ black
33
fake_useragent
44
flake8
55
keras
6+
lxml
67
matplotlib
78
mypy
89
numpy

0 commit comments

Comments
 (0)