Skip to content
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

Enable Fuzz Testing for parts of the project that process user/operator input #1116

Open
v0lkan opened this issue Aug 20, 2024 · 0 comments
Open

Comments

@v0lkan
Copy link
Contributor

v0lkan commented Aug 20, 2024

Here is a roughly the steps needed where necesary:

To enable fuzzing for your Go project with existing unit tests, you can follow these steps:

  • Identify the functions you want to fuzz test. These are typically functions that take input and produce output, especially those that handle parsing or complex data structures.
  • Create a new file for each function you want to fuzz, naming it with the format *_test.go. For example, if you're fuzzing a function called ParseInput, you might create a file named parse_input_fuzz_test.go.
  • In this new file, write a fuzz test function. The function should have the following signature:
func FuzzYourFunctionName(f *testing.F) {
    // Fuzz test code here
}
  • Inside the fuzz function, use f.Add() to provide seed inputs. These are inputs that will be used as a starting point for the fuzzer to generate new inputs.
  • Use f.Fuzz() to define the actual fuzzing logic. This function takes a closure that accepts fuzzed inputs and tests your function with them.

Here's a simple example:

func FuzzParseInput(f *testing.F) {
    // Add some seed inputs
    f.Add("valid input")
    f.Add("another valid input")

    // Define the fuzzing function
    f.Fuzz(func(t *testing.T, input string) {
        result, err := ParseInput(input)
        if err != nil {
            // If there's an error, make sure it's an expected one
            if !errors.Is(err, ErrInvalidInput) {
                t.Errorf("Unexpected error: %v", err)
            }
        } else {
            // If no error, check that the result is valid
            if !isValidResult(result) {
                t.Errorf("Invalid result for input %q: %v", input, result)
            }
        }
    })
}

To run the fuzz tests, use the go test command with the -fuzz flag:

go test -fuzz=FuzzYourFunctionName

This will run the fuzzer, which will generate inputs and try to find cases that cause your function to crash or fail assertions.

Go's fuzzer will save any inputs that cause crashes or failures. You can add these to your regular test cases to ensure the issues don't recur.

Remember, effective fuzzing often requires letting the tests run for an extended period. The longer it runs, the more likely it is to find edge cases.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant