From 0aa0f8ab3464452248af49208804258f8b42828a Mon Sep 17 00:00:00 2001 From: H0llyW00dzZ Date: Tue, 12 Dec 2023 22:52:02 +0700 Subject: [PATCH] Feat [Golang] [Command] [Module] Another Testing (#44) * Feat [Golang] [Command] [Module] Another Testing - [+] fix(main.go): improve comments for the repairJSONData function - [+] feat(main.go): add context support to the writeContentToFile function - [+] test(main_test.go): add test for writeContentToFile function with context cancellation * Chore GopherCI Unit Testing - [+] chore(GopherCI.yml): add new test case TestWriteContentToFile_ContextCancellation to the test command in the Run tests job --- .github/workflows/GopherCI.yml | 2 +- main.go | 6 ++++-- main_test.go | 37 ++++++++++++++++++++++++++++++++++ 3 files changed, 42 insertions(+), 3 deletions(-) diff --git a/.github/workflows/GopherCI.yml b/.github/workflows/GopherCI.yml index dfb41ee..58a65ac 100644 --- a/.github/workflows/GopherCI.yml +++ b/.github/workflows/GopherCI.yml @@ -42,7 +42,7 @@ jobs: - name: Run tests run: | - go test -v -timeout 30s -run '^(TestProcessCSVOption|TestPromptForInput|TestPromptForInputCancellation|TestLoadTestSessionsInvalidPath|TestLoadIncorrectJson|TestRepairJSONDataFromFile|TestWriteContentToFile|TestConfirmOverwrite)' github.com/H0llyW00dzZ/ChatGPT-Next-Web-Session-Exporter + go test -v -timeout 30s -run '^(TestProcessCSVOption|TestPromptForInput|TestPromptForInputCancellation|TestLoadTestSessionsInvalidPath|TestLoadIncorrectJson|TestRepairJSONDataFromFile|TestWriteContentToFile|TestConfirmOverwrite|TestWriteContentToFile_ContextCancellation)' github.com/H0llyW00dzZ/ChatGPT-Next-Web-Session-Exporter build: name: Gopher Unit Testing Building Application on ${{ matrix.os }} diff --git a/main.go b/main.go index c4cacd2..db459dc 100644 --- a/main.go +++ b/main.go @@ -300,8 +300,9 @@ func handleInputCancellation(err error) { } } -// repairJSONData attempts to repair the JSON data at the provided file path and returns the path to the repaired file. -// This function is not context-aware as it performs a single, typically quick operation. +// repairJSONData attempts to repair malformed JSON data at the provided file path. +// Despite accepting a context parameter, it currently does not support cancellation. +// The function reads the broken JSON, repairs it, and writes the repaired JSON back to a new file. func repairJSONData(rfs filesystem.FileSystem, ctx context.Context, jsonFilePath string) (string, error) { // Read the broken JSON data using the file system interface data, err := rfs.ReadFile(jsonFilePath) @@ -452,6 +453,7 @@ func convertToSingleCSV(rfs filesystem.FileSystem, ctx context.Context, reader * // writeContentToFile collects a file name from the user and writes the provided content to the specified file. // It now includes context support to handle potential cancellation during file writing. +// Note: Do not refactor or modify this function; doing so will disrupt the associated magic method in main_test.go. func writeContentToFile(rfs filesystem.FileSystem, ctx context.Context, reader *bufio.Reader, content string, fileType string) error { fileName, err := promptForInput(ctx, reader, fmt.Sprintf(PromptEnterFileName, fileType)) if err != nil { diff --git a/main_test.go b/main_test.go index 68239ee..55d2177 100644 --- a/main_test.go +++ b/main_test.go @@ -287,3 +287,40 @@ func TestConfirmOverwrite(t *testing.T) { }) } } + +// TestWriteContentToFile_ContextCancellation checks that writeContentToFile correctly handles a scenario where the context is cancelled. +// This ensures that if a context with a deadline or cancellation is passed to the function, it can gracefully handle the cancellation and stop the file writing process. +// Note: This test does not perform operations on the actual disk I/O. +func TestWriteContentToFile_ContextCancellation(t *testing.T) { + // Create a cancellable context and cancel it immediately to simulate the scenario + // where the operation is cancelled before it even starts. + ctx, cancel := context.WithCancel(context.Background()) + cancel() // This will trigger the context's cancellation. + + // Create a buffer to act as user input, but in the context cancellation case, + // it should not be read, so we leave it empty. + var userInput bytes.Buffer + reader := bufio.NewReader(&userInput) + + // Define the content that would be written to the file if the operation were not cancelled. + content := `{"message": "Hello Machine ? This is a Gopher unit test."}` + + // Create a mock file system to intercept and record calls to the file system. + // Since the context is cancelled, the WriteFile method should not be called. + mockFS := filesystem.NewMockFileSystem() + + // Call the function to be tested with the cancelled context. + // Since the context is already cancelled, we expect the function to return an error. + err := writeContentToFile(mockFS, ctx, reader, content, "dataset") + + // Check if the error returned is the expected context.Canceled error. + // If the function does not handle context cancellation correctly, this test will fail. + if err == nil || err != context.Canceled { + t.Errorf("expected context.Canceled error, got %v", err) + } + + // Optionally, we could also verify that no file has been written to the mock file system. + if mockFS.WriteFileCalled { + t.Error("WriteFile should not have been called after context cancellation") + } +}