From 03892cb83a660af69bf01c99f6d4a122df0f8396 Mon Sep 17 00:00:00 2001 From: Tomasz Suchorowski Date: Wed, 3 Jan 2024 11:40:28 +0100 Subject: [PATCH] [fix] unit test worked but broke the client await for reply --- tcp-client-server/tcp-client/tcp-client.go | 1 - tcp-client-server/tcp-client/tcp-client_test.go | 16 ++++++++++------ 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/tcp-client-server/tcp-client/tcp-client.go b/tcp-client-server/tcp-client/tcp-client.go index e3f1b1e..55b3b96 100644 --- a/tcp-client-server/tcp-client/tcp-client.go +++ b/tcp-client-server/tcp-client/tcp-client.go @@ -21,7 +21,6 @@ func SendUserInput(conn net.Conn, r io.Reader) { if err := input.Err(); err != nil { log.Fatal(err) } - defer conn.Close() } func main() { diff --git a/tcp-client-server/tcp-client/tcp-client_test.go b/tcp-client-server/tcp-client/tcp-client_test.go index 1944fbd..fd7d9c8 100644 --- a/tcp-client-server/tcp-client/tcp-client_test.go +++ b/tcp-client-server/tcp-client/tcp-client_test.go @@ -2,7 +2,7 @@ package main import ( - "io" + "log" "net" "strings" "testing" @@ -18,12 +18,16 @@ func TestSendUserInput(t *testing.T) { // call SendUserInput function with the connection go SendUserInput(conn1, strings.NewReader(testString)) - // read the data written to the connection until EOF - data, _ := io.ReadAll(conn2) + // read the 1024 bytes written to the connection + data := make([]byte, 1024) + n, err := conn2.Read(data) + if err != nil { + log.Fatal("Error reading connection: ", err) + } + r_msg := string(data[:n]) // check if the data written matches the expected output - expectedOutput := "Hello, World!\n" - if string(data) != expectedOutput { - t.Errorf("Expected output %s, got %s", expectedOutput, string(data)) + if r_msg != testString { + t.Errorf("Expected output %s, got %s", testString, r_msg) } }