Skip to content

Commit 8e05e80

Browse files
Add unit tests for policy.go (#142)
* feat: Add basic Go unit test setup This commit introduces the initial setup for Go unit testing. A sample test file `sourcetool/pkg/policy/policy_test.go` has been created with a placeholder test function. To run the tests, navigate to the `sourcetool` directory and execute: `go test ./...` * test: Add unit test for getPolicyPath This commit adds a unit test for the `getPolicyPath` function in `sourcetool/pkg/policy/policy.go`. The test covers various scenarios, including: - Valid owner and repository names. - Empty owner name. - Empty repository name. - Empty owner and repository names. * refactor(tests): Simplify custom message passing to assertion helper This commit refactors the `assertProtectedBranchEquals` helper function in `sourcetool/pkg/policy/policy_test.go` and its call sites. Previously, the helper accepted variadic arguments (`msgAndArgs ...interface{}`) for custom messages and performed `fmt.Sprintf` internally. This change simplifies the helper's signature and logic: 1. **Helper Signature Change:** * `assertProtectedBranchEquals` now accepts a single pre-formatted `customMessage string` argument instead of variadic arguments. 2. **Call Site Updates:** * All calls to `assertProtectedBranchEquals` in the test functions (`TestGetBranchPolicy_Local_SpecificFound`, `TestGetBranchPolicy_Local_DefaultCases`, `TestGetBranchPolicy_Remote_SpecificFound`, `TestGetBranchPolicy_Remote_DefaultCases`) have been updated to use `fmt.Sprintf` to format the custom message string before passing it to the helper. This change makes the helper function's interface cleaner and gives callers more direct control over the formatting of custom messages, improving the overall clarity of the test code. * fix(tests): Correct test failures and improve helper logic This commit addresses several issues that caused test failures in `sourcetool/pkg/policy/policy_test.go` and improves the robustness of the test suite. Corrections include: 1. **Added Missing Import:** * Added the `reflect` package import to `pkg/policy/policy_test.go`, which is required for `reflect.DeepEqual` used in the assertion helper. 2. **Aligned Go-GitHub Version:** * Updated the import for `github.com/google/go-github` in `pkg/policy/policy_test.go` from `v50` to `v69` to match the version used in `pkg/gh_control/connection.go`, resolving type mismatches. 3. **Refined `assertProtectedBranchEquals` Helper:** * When `ignoreSince` is `false`, the `Since` fields of the `ProtectedBranch` structs are now compared explicitly using `actual.Since.Equal(expected.Since)`. * For the `reflect.DeepEqual` comparison of the remaining fields, copies of the structs are made, and their `Since` fields are zeroed out. This ensures accurate comparison of other struct members without interference from `time.Time` comparison nuances, while still allowing precise `Since` validation when needed. 4. **Corrected `expectedPath` in Remote Default Cases:** * In `TestGetBranchPolicy_Remote_DefaultCases`, the `expectedPath` for scenarios where a remote policy is successfully fetched but results in a default branch rule (e.g., branch not found in policy, empty/nil protected branches) has been changed from the mocked HTML URL to `"DEFAULT"`. This aligns the test expectation with the actual behavior of the `getBranchPolicy` function. After these changes, all tests in `pkg/policy` pass successfully. * refactor(tests): Remove redundant TestHelloWorld and TestGetPolicyPath This commit removes two test functions from `sourcetool/pkg/policy/policy_test.go` that are no longer necessary: 1. **`TestHelloWorld`:** This was an initial placeholder test and served no ongoing purpose. 2. **`TestGetPolicyPath`:** This function tested the `getPolicyPath` string formatting utility. The correct behavior of `getPolicyPath` is now implicitly and sufficiently verified by the `validateMockServerRequestPath` helper, which is used in all remote policy test functions (`TestGetBranchPolicy_Remote_*`). The helper constructs the expected API path using `getPolicyPath` and compares it against the actual request path received by the mock server. Removing these functions cleans up the test file by eliminating obsolete and redundant test logic. * remove github/v50 Signed-off-by: Tom Hennen <[email protected]> * Refactor: Consolidate common HTTP test setup in policy_test.go (#3) I introduced a new helper function, `setupMockGitHubTestEnv`, to encapsulate the common logic for setting up a mock GitHub environment for testing policy fetching. This includes: - Creating an `httptest.Server` with a specified handler. - Configuring an `http.Client` and `github.Client` to use the test server. - Returning a `*gh_control.GitHubConnection` pre-configured for the test environment and the `*httptest.Server` instance. I refactored the following test functions to use this new helper: - TestGetBranchPolicy_Remote_SpecificFound - TestGetBranchPolicy_Remote_DefaultCases - TestGetBranchPolicy_Remote_ServerError - TestGetBranchPolicy_Remote_MalformedJSON This change significantly reduces code duplication and simplifies the setup within these tests, making them cleaner and easier to maintain. Co-authored-by: google-labs-jules[bot] <161369871+google-labs-jules[bot]@users.noreply.github.com> * add go.work.sum changes Signed-off-by: Tom Hennen <[email protected]> * feat: add unit tests for compute functions in policy.go This commit introduces unit tests for the following functions in `sourcetool/pkg/policy/policy.go`: - computeEligibleSlsaLevel - computeEligibleSince - computeSlsaLevel - computeReviewEnforced - computeImmutableTags The tests cover various scenarios, including valid inputs, edge cases, and error conditions, ensuring the correctness and robustness of these policy computation functions. The tests are written in a table-driven style, consistent with existing tests in `sourcetool/pkg/policy/policy_test.go`. * refactor: simplify and clarify tests for policy compute functions This commit refactors the unit tests for the `compute*` functions in `sourcetool/pkg/policy/policy_test.go`. The main changes include: - Consolidating redundant test cases where multiple setups were testing the same underlying logic path. This was particularly applied to: - `TestComputeEligibleSlsaLevel`: Reduced multiple "Level 1" scenarios based on absent controls into a single case. - `TestComputeReviewEnforced` and `TestComputeImmutableTags`: - Combined cases where the policy did not require the control (making control state irrelevant). - Combined success cases for compliant controls into a single case representing `Policy.Since >= Control.Since`. - Clarifying test case names to better describe the specific scenario and expected outcome. - Removing unused test variables that became redundant after consolidation. These changes make the test suite more concise, readable, and maintainable without sacrificing coverage of distinct logical paths or critical boundary conditions for the tested functions. * feat: add unit tests for evaluateControls in policy.go This commit introduces unit tests for the `evaluateControls` function in `sourcetool/pkg/policy/policy.go`. The tests cover a range of scenarios, including: - Successful evaluation where all required controls (SLSA level, review enforcement, immutable tags) are met. - Successful evaluation with various combinations of controls being met or not required by policy. - Error scenarios where `computeSlsaLevel`, `computeReviewEnforced`, or `computeImmutableTags` (internal calls from `evaluateControls`) return errors. A table-driven approach was used for the tests, consistent with other tests in the `policy_test.go` file. This ensures comprehensive coverage of the function's logic and error handling. * Output: refactor: Simplify policyPath assertion in TestEvaluateProv Simplifies the assertion logic for the returned `policyPath` in the `TestEvaluateProv` function in `sourcetool/pkg/policy/policy_test.go`. The `expectedPolicyPath` values for test cases involving malformed provenance have been updated to "DEFAULT" when the test setup uses a policy file that does not explicitly define the branch under test. This reflects that `getBranchPolicy` determines the path as "DEFAULT" before `attest.GetProvPred` might return an error due to the malformed provenance. The complex conditional logic previously used for asserting the `policyPath` has been removed and replaced with a direct comparison against the correctly prepared `actualPolicyPath`. This change makes the test logic clearer and easier to understand. All tests continue to pass. * simplify path handling Signed-off-by: Tom Hennen <[email protected]> * Refactor: Further simplify TestEvaluateProv_Success Removes the t.Run() call from TestEvaluateProv_Success and inlines simple data variables directly into the test logic. This change makes the test more concise and easier to read, following its conversion from a table-driven test to a single-case test. Complex struct initializations are kept as local variables to maintain clarity. * further simplify test case Signed-off-by: Tom Hennen <[email protected]> * fix: Align Go version in workflow with go.work Updates the GitHub Action workflow for Go unit tests to use Go version 1.23.5, as specified in the `go.work` file. This ensures consistency between the CI environment and the project's defined Go version. --------- Signed-off-by: Tom Hennen <[email protected]> Co-authored-by: google-labs-jules[bot] <161369871+google-labs-jules[bot]@users.noreply.github.com>
1 parent 0033be9 commit 8e05e80

File tree

6 files changed

+1678
-280
lines changed

6 files changed

+1678
-280
lines changed

.github/workflows/go-test.yml

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
name: Go Tests (sourcetool)
2+
3+
on:
4+
pull_request:
5+
6+
jobs:
7+
test:
8+
permissions:
9+
contents: read
10+
runs-on: ubuntu-latest
11+
steps:
12+
- name: Checkout code
13+
uses: actions/checkout@v4
14+
with:
15+
persist-credentials: false
16+
17+
- name: Set up Go
18+
uses: actions/setup-go@v5
19+
with:
20+
go-version: '1.23.5'
21+
22+
- name: Run Go tests
23+
run: go test ./sourcetool/...

go.work.sum

Lines changed: 25 additions & 40 deletions
Large diffs are not rendered by default.

sourcetool/go.mod

Lines changed: 4 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -3,40 +3,29 @@ module github.com/slsa-framework/slsa-source-poc/sourcetool
33
go 1.23.5
44

55
require (
6+
github.com/carabiner-dev/bnd v0.0.1-pre1.0.20250219220316-b7a2b5a6034b
67
github.com/go-git/go-git/v5 v5.13.2
7-
github.com/google/go-github/v68 v68.0.0
8+
github.com/google/go-github/v69 v69.2.0
89
github.com/in-toto/attestation v1.1.1
910
github.com/sigstore/sigstore-go v0.7.0
1011
github.com/spf13/cobra v1.9.1
11-
github.com/theupdateframework/go-tuf/v2 v2.0.2
1212
google.golang.org/protobuf v1.36.5
1313
)
1414

1515
require (
1616
dario.cat/mergo v1.0.1 // indirect
17-
github.com/CycloneDX/cyclonedx-go v0.9.1 // indirect
1817
github.com/Microsoft/go-winio v0.6.2 // indirect
1918
github.com/ProtonMail/go-crypto v1.1.5 // indirect
2019
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 // indirect
21-
github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect
2220
github.com/blang/semver v3.5.1+incompatible // indirect
23-
github.com/blang/semver/v4 v4.0.0 // indirect
24-
github.com/carabiner-dev/ampel v0.0.0-20250209210344-7b306497c927 // indirect
25-
github.com/carabiner-dev/bnd v0.0.1-pre1.0.20250219220316-b7a2b5a6034b // indirect
26-
github.com/carabiner-dev/github v0.0.0-20250210222226-442fdacc1d16 // indirect
27-
github.com/carabiner-dev/hasher v0.1.0 // indirect
28-
github.com/carabiner-dev/osv v0.0.0-20250124012120-b8ce4531cd92 // indirect
29-
github.com/cli/go-gh/v2 v2.11.2 // indirect
30-
github.com/cli/safeexec v1.0.0 // indirect
31-
github.com/cli/shurcooL-graphql v0.0.4 // indirect
3221
github.com/cloudflare/circl v1.3.7 // indirect
33-
github.com/common-nighthawk/go-figure v0.0.0-20210622060536-734e95fb86be // indirect
3422
github.com/coreos/go-oidc/v3 v3.12.0 // indirect
3523
github.com/cyberphone/json-canonicalization v0.0.0-20231011164504-785e29786b46 // indirect
3624
github.com/cyphar/filepath-securejoin v0.3.6 // indirect
3725
github.com/digitorus/pkcs7 v0.0.0-20230818184609-3a137a874352 // indirect
3826
github.com/digitorus/timestamp v0.0.0-20231217203849-220c5c2851b7 // indirect
3927
github.com/emirpasic/gods v1.18.1 // indirect
28+
github.com/fatih/color v1.18.0 // indirect
4029
github.com/fsnotify/fsnotify v1.8.0 // indirect
4130
github.com/go-chi/chi v4.1.2+incompatible // indirect
4231
github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376 // indirect
@@ -57,40 +46,28 @@ require (
5746
github.com/go-openapi/validate v0.24.0 // indirect
5847
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect
5948
github.com/google/certificate-transparency-go v1.3.1 // indirect
60-
github.com/google/go-cmp v0.6.0 // indirect
6149
github.com/google/go-containerregistry v0.20.3 // indirect
62-
github.com/google/go-github/v69 v69.2.0 // indirect
6350
github.com/google/go-querystring v1.1.0 // indirect
6451
github.com/google/uuid v1.6.0 // indirect
6552
github.com/hashicorp/go-cleanhttp v0.5.2 // indirect
6653
github.com/hashicorp/go-retryablehttp v0.7.7 // indirect
6754
github.com/hashicorp/hcl v1.0.1-vault-5 // indirect
68-
github.com/henvic/httpretty v0.0.6 // indirect
6955
github.com/in-toto/in-toto-golang v0.9.0 // indirect
7056
github.com/inconshreveable/mousetrap v1.1.0 // indirect
7157
github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 // indirect
7258
github.com/jedisct1/go-minisign v0.0.0-20230811132847-661be99b8267 // indirect
7359
github.com/josharian/intern v1.0.0 // indirect
7460
github.com/kevinburke/ssh_config v1.2.0 // indirect
7561
github.com/letsencrypt/boulder v0.0.0-20240620165639-de9c06129bec // indirect
76-
github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
7762
github.com/magiconair/properties v1.8.9 // indirect
7863
github.com/mailru/easyjson v0.7.7 // indirect
79-
github.com/mattn/go-isatty v0.0.20 // indirect
80-
github.com/mattn/go-runewidth v0.0.15 // indirect
8164
github.com/mitchellh/mapstructure v1.5.0 // indirect
82-
github.com/muesli/termenv v0.15.2 // indirect
83-
github.com/nozzle/throttler v0.0.0-20180817012639-2ea982251481 // indirect
8465
github.com/oklog/ulid v1.3.1 // indirect
8566
github.com/opencontainers/go-digest v1.0.0 // indirect
8667
github.com/opentracing/opentracing-go v1.2.0 // indirect
87-
github.com/openvex/go-vex v0.2.5 // indirect
88-
github.com/package-url/packageurl-go v0.1.1 // indirect
8968
github.com/pelletier/go-toml/v2 v2.2.2 // indirect
9069
github.com/pjbgf/sha1cd v0.3.2 // indirect
9170
github.com/pkg/errors v0.9.1 // indirect
92-
github.com/protobom/protobom v0.5.0 // indirect
93-
github.com/rivo/uniseg v0.4.7 // indirect
9471
github.com/sagikazarmark/locafero v0.4.0 // indirect
9572
github.com/sagikazarmark/slog-shim v0.1.0 // indirect
9673
github.com/sassoftware/relic v7.2.1+incompatible // indirect
@@ -106,15 +83,13 @@ require (
10683
github.com/skeema/knownhosts v1.3.0 // indirect
10784
github.com/skratchdot/open-golang v0.0.0-20200116055534-eef842397966 // indirect
10885
github.com/sourcegraph/conc v0.3.0 // indirect
109-
github.com/spdx/tools-golang v0.5.5 // indirect
11086
github.com/spf13/afero v1.11.0 // indirect
11187
github.com/spf13/cast v1.7.0 // indirect
11288
github.com/spf13/pflag v1.0.6 // indirect
11389
github.com/spf13/viper v1.19.0 // indirect
114-
github.com/stretchr/testify v1.10.0 // indirect
11590
github.com/subosito/gotenv v1.6.0 // indirect
11691
github.com/theupdateframework/go-tuf v0.7.0 // indirect
117-
github.com/thlib/go-timezone-local v0.0.0-20210907160436-ef149e42d28e // indirect
92+
github.com/theupdateframework/go-tuf/v2 v2.0.2 // indirect
11893
github.com/titanous/rocacheck v0.0.0-20171023193734-afe73141d399 // indirect
11994
github.com/transparency-dev/merkle v0.0.2 // indirect
12095
github.com/xanzy/ssh-agent v0.3.3 // indirect
@@ -134,12 +109,9 @@ require (
134109
golang.org/x/sys v0.30.0 // indirect
135110
golang.org/x/term v0.29.0 // indirect
136111
golang.org/x/text v0.22.0 // indirect
137-
golang.org/x/tools v0.29.0 // indirect
138112
google.golang.org/genproto/googleapis/api v0.0.0-20241219192143-6b3ec007d9bb // indirect
139113
gopkg.in/ini.v1 v1.67.0 // indirect
140114
gopkg.in/warnings.v0 v0.1.2 // indirect
141115
gopkg.in/yaml.v3 v3.0.1 // indirect
142116
k8s.io/klog/v2 v2.130.1 // indirect
143-
sigs.k8s.io/release-sdk v0.12.2 // indirect
144-
sigs.k8s.io/release-utils v0.11.0 // indirect
145117
)

0 commit comments

Comments
 (0)