├── go.mod ├── go.sum ├── .githooks └── pre-commit ├── SECURITY.md ├── .github ├── workflows │ ├── build-workflow.yml │ └── golangci-lint.yml └── ISSUE_TEMPLATE │ ├── feature_request.md │ └── bug_report.md ├── README.md ├── .gitignore ├── CONTRIBUTING.md ├── CODE_OF_CONDUCT.md ├── keploy └── keploy.go └── LICENSE /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/keploy/go-sdk/v3 2 | 3 | go 1.21 4 | 5 | //replace go.keploy.io/server => ../keploy 6 | 7 | require golang.org/x/tools v0.1.5 8 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | golang.org/x/tools v0.1.5 h1:ouewzE6p+/VEB31YYnTbEJdi8pFqKp4P4n85vwo3DHA= 2 | golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= 3 | -------------------------------------------------------------------------------- /.githooks/pre-commit: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | echo "Checking for changes!" 3 | 4 | GO_FILES=$(git diff --cached --name-only -- '*.go') 5 | 6 | if [[ $GO_FILES == "" ]]; then 7 | echo "No Go Files to Update" 8 | else 9 | for file in $GO_FILES; do 10 | go fmt $file 11 | git add $file 12 | done 13 | fi -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | ## Reporting a Vulnerability 4 | 5 | We value security for the project very highly. We encourage all users to report any vulnerabilities they discover to us. 6 | If you find a security vulnerability in the Keploy project, please report it responsibly by sending an email to hello@keploy.io 7 | 8 | At this juncture, we don't have a bug bounty program. We are a small team trying to solve a big problem. We urge you to report any vulnerabilities responsibly 9 | so that we can continue building a secure application for the entire community. -------------------------------------------------------------------------------- /.github/workflows/build-workflow.yml: -------------------------------------------------------------------------------- 1 | name: Build Keploy's Go-SDK 2 | 3 | on: 4 | push: 5 | branches: [ "main" ] 6 | pull_request: 7 | branches: [ "main" ] 8 | 9 | jobs: 10 | 11 | build: 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: actions/checkout@v3 15 | 16 | - name: Set up Go 17 | uses: actions/setup-go@v3 18 | with: 19 | go-version: 1.24 20 | 21 | - name: Install dependencies 22 | run: go mod tidy 23 | 24 | - name: Build 25 | run: go build -v ./... 26 | 27 | - name: Test 28 | run: go test -v ./... -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Desktop (please complete the following information):** 27 | - OS: [e.g. iOS] 28 | - Browser [e.g. chrome, safari] 29 | - Version [e.g. 22] 30 | 31 | **Smartphone (please complete the following information):** 32 | - Device: [e.g. iPhone6] 33 | - OS: [e.g. iOS8.1] 34 | - Browser [e.g. stock browser, safari] 35 | - Version [e.g. 22] 36 | 37 | **Additional context** 38 | Add any other context about the problem here. 39 | -------------------------------------------------------------------------------- /.github/workflows/golangci-lint.yml: -------------------------------------------------------------------------------- 1 | name: golangci-lint 2 | 3 | on: 4 | push: 5 | branches: ["main"] 6 | pull_request: 7 | branches: ["main"] 8 | 9 | permissions: 10 | contents: read 11 | # Optional: allow read access to pull request. Use with `only-new-issues` option. 12 | pull-requests: read 13 | 14 | # Cancel the in-progress workflow when PR is refreshed. 15 | concurrency: 16 | group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.head_ref || github.sha }} 17 | cancel-in-progress: true 18 | 19 | jobs: 20 | golangci: 21 | name: lint 22 | runs-on: ubuntu-latest 23 | env: 24 | CGO_ENABLED: "1" 25 | permissions: 26 | contents: read 27 | packages: write 28 | id-token: write 29 | 30 | steps: 31 | - uses: actions/checkout@v4 32 | 33 | - uses: actions/setup-go@v4 34 | with: 35 | go-version: "1.24" 36 | cache: false 37 | - name: Installing build Essentials and gcc 38 | run: | 39 | sudo apt -y update 40 | sudo apt -y install build-essential gcc libc-dev \ 41 | pkg-config \ 42 | libgl1-mesa-dev \ 43 | libxi-dev libxcursor-dev \ 44 | libxrandr-dev libxinerama-dev \ 45 | libxxf86vm-dev libx11-dev libx11-xcb-dev 46 | 47 | - name: golangci-lint 48 | uses: golangci/golangci-lint-action@v7 49 | with: 50 | only-new-issues: true 51 | args: --timeout=7m 52 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Keploy Go Coverage Agent 2 | 3 | This package enables native Go coverage reporting for tests generated by Keploy enterprise. It works by listening for commands from the Keploy binary to start and stop coverage collection for each test case. 4 | 5 | ## How to Use 6 | 7 | To integrate the coverage agent into your Go application, follow these two steps: 8 | 9 | ### 1. Activate the Agent 10 | 11 | Add a blank import for the package in your application's main entry point (e.g., in your `main.go` file). This import's side effects will automatically initialize and run the coverage agent in the background. 12 | 13 | ```go 14 | import ( 15 | // ... other imports 16 | _ "github.com/keploy/go-sdk/v3/keploy" 17 | ) 18 | ``` 19 | 20 | ### 2. Build with Coverage Flags 21 | 22 | Compile your application using the `-cover` and `-covermode=atomic` flags. These are required for the agent to access and clear coverage data for each test run according to https://pkg.go.dev/runtime/coverage@go1.25rc2#ClearCounters 23 | 24 | ```bash 25 | go build -cover -covermode=atomic -o your-app . 26 | ``` 27 | 28 | ### 3. Run tests with Keploy enterprise version 29 | 30 | ```bash 31 | sudo -E keploy-enterprise test -c "./your-app" --dedup 32 | ``` 33 | 34 | Now you will see `dedupData.yaml` getting created. 35 | 36 | Run `sudo -E keploy-enterprise dedup` to get the tests which are duplicate in `duplicates.yaml` file 37 | 38 | In order to remove the duplicate tests, run the following command: 39 | 40 | ```bash 41 | sudo -E keploy-enterprise dedup --rm 42 | ``` 43 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | /**/.idea/* 3 | .vscode/**/* 4 | 5 | # Created by https://www.toptal.com/developers/gitignore/api/go,macos,windows,linux 6 | # Edit at https://www.toptal.com/developers/gitignore?templates=go,macos,windows,linux 7 | 8 | ### Go ### 9 | # Binaries for programs and plugins 10 | *.exe 11 | *.exe~ 12 | *.dll 13 | *.so 14 | *.dylib 15 | 16 | # Test binary, built with `go test -c` 17 | *.test 18 | 19 | # Output of the go coverage tool, specifically when used with LiteIDE 20 | *.out 21 | 22 | # Dependency directories (remove the comment below to include it) 23 | # vendor/ 24 | 25 | ### Go Patch ### 26 | /Godeps/ 27 | 28 | ### Linux ### 29 | *~ 30 | 31 | # temporary files which can be created if a process still has a handle open of a deleted file 32 | .fuse_hidden* 33 | 34 | # KDE directory preferences 35 | .directory 36 | 37 | # Linux trash folder which might appear on any partition or disk 38 | .Trash-* 39 | 40 | # .nfs files are created when an open file is removed but is still being accessed 41 | .nfs* 42 | 43 | ### macOS ### 44 | # General 45 | .DS_Store 46 | .AppleDouble 47 | .LSOverride 48 | 49 | # Icon must end with two \r 50 | Icon 51 | 52 | 53 | # Thumbnails 54 | ._* 55 | 56 | # Files that might appear in the root of a volume 57 | .DocumentRevisions-V100 58 | .fseventsd 59 | .Spotlight-V100 60 | .TemporaryItems 61 | .Trashes 62 | .VolumeIcon.icns 63 | .com.apple.timemachine.donotpresent 64 | 65 | # Directories potentially created on remote AFP share 66 | .AppleDB 67 | .AppleDesktop 68 | Network Trash Folder 69 | Temporary Items 70 | .apdisk 71 | 72 | ### Windows ### 73 | # Windows thumbnail cache files 74 | Thumbs.db 75 | Thumbs.db:encryptable 76 | ehthumbs.db 77 | ehthumbs_vista.db 78 | 79 | # Dump file 80 | *.stackdump 81 | 82 | # Folder config file 83 | [Dd]esktop.ini 84 | 85 | # Recycle Bin used on file shares 86 | $RECYCLE.BIN/ 87 | 88 | # Windows Installer files 89 | *.cab 90 | *.msi 91 | *.msix 92 | *.msm 93 | *.msp 94 | 95 | # Windows shortcuts 96 | *.lnk 97 | 98 | # End of https://www.toptal.com/developers/gitignore/api/go,macos,windows,linux -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to Keploy 2 | 3 | Thank you for your interest in Keploy and for taking the time to contribute to this project. 🙌 4 | Keploy is a project by developers for developers and there are a lot of ways you can contribute. 5 | If you don't know where to start contributing, ask us on our [Slack channel](https://join.slack.com/t/keploy/shared_invite/zt-12rfbvc01-o54cOG0X1G6eVJTuI_orSA). 6 | 7 | ## Code of conduct 8 | 9 | Read our [Code of Conduct](CODE_OF_CONDUCT.md) before contributing 10 | 11 | ## How can I contribute? 12 | 13 | There are many ways in which you can contribute to Keploy. 14 | 15 | #### 🐛 Report a bug 16 | Report all issues through GitHub Issues using the [Report a Bug](https://github.com/keploy/keploy/issues/new?assignees=&labels=&template=bug_report.md&title=) template. 17 | To help resolve your issue as quickly as possible, read the template and provide all the requested information. 18 | 19 | #### 🛠 File a feature request 20 | We welcome all feature requests, whether it's to add new functionality to an existing extension or to offer an idea for a brand new extension. 21 | File your feature request through GitHub Issues using the [Feature Request](https://github.com/keploy/keploy/issues/new?assignees=&labels=&template=feature_request.md&title=) template. 22 | 23 | #### 📝 Improve the documentation 24 | In the process of shipping features quickly, we may forget to keep our docs up to date. You can help by suggesting improvements to our documentation using the [Documentation Improvement](https://github.com/keploy/docs/issues) template! 25 | 26 | #### ⚙️ Close a Bug / Feature issue 27 | We welcome contributions that help make keploy bug free & improve the experience of our users. You can also find issues tagged [Good First Issues](https://github.com/keploy/keploy/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22). 28 | 29 | # How to Contribute 30 | 31 | ## Prerequisites 32 | 33 | Make sure that the following prequisites are installed in your Operating System before you start contributing to the project - : 34 | 35 | - [Go](https://go.dev/) 36 | 37 | To verify run : 38 | 39 | ``` 40 | go version 41 | ``` 42 | 43 | ## Set up your Local Development Environment 44 | 45 | Follow the following instructions to start contributing - 46 | 47 | 1 . Fork [this](https://github.com/keploy/go-sdk.git) 48 | 49 | 2 . Clone the copy of your forked project 50 | 51 | ``` 52 | git clone https://github.com//go-sdk.git 53 | ``` 54 | 55 | 3 . Navigate to the project directory 56 | 57 | ``` 58 | cd go-sdk 59 | ``` 60 | 4 . Add a remote reference (upstream) to the original repository. 61 | 62 | ``` 63 | git remote add upstream https://github.com/keploy/go-sdk.git 64 | ``` 65 | 66 | 5 . Always take a pull from the upstream repository to your master branch to keep it updated with the main project. 67 | 68 | ``` 69 | git pull upstream main 70 | ``` 71 | 72 | 6 . Configure the pre-commit hook by running the following path. 73 | 74 | ``` 75 | git config core.hooksPath .githooks && chmod +x .githooks/* 76 | ``` 77 | 78 | 7 . create a new branch 79 | 80 | ``` 81 | git checkout -b 82 | ``` 83 | 84 | 8 . Install the dependencies by running the following command 85 | 86 | ``` 87 | go get -u github.com/keploy/go-sdk 88 | ``` 89 | 90 | 9 . Make the desired changes 91 | 92 | 10 . Track your changes 93 | 94 | ``` 95 | git status 96 | ``` 97 | 98 | 11 . Add your changes to staging area 99 | 100 | ``` 101 | git add . 102 | ``` 103 | 104 | 12 . Commit your changes. [Please refer to this article to know more about the commit message convention followed by Keploy.](https://www.conventionalcommits.org/en/v1.0.0/) 105 | 106 | ``` 107 | git commit -m "" 108 | ``` 109 | 110 | 13 . While you are working on your branch, other developers may update the `main` branch with their branch. This action means your branch is now out of date with the `main` branch and missing content which may lead to merge conflicts. So to avoid this fetch the new changes, follow along: 111 | 112 | ``` 113 | git checkout main 114 | git fetch origin main 115 | git merge upstream/main 116 | git push origin 117 | ``` 118 | 119 | 14 . Now you need to merge the `main` branch into your branch. This can be done in the following way -: 120 | 121 | ``` 122 | git checkout 123 | git merge main 124 | ``` 125 | 126 | 15 . Push the committed changes in your feature branch to your remote repository. 127 | 128 | ``` 129 | git push -u origin 130 | ``` 131 | 132 | Once you’ve committed and pushed all of your changes to GitHub, go to the page for your fork on GitHub, select your development branch, and click the compare & pull request button. This will create a Pull Request for your branch. Wait untill a contributor give you a feedback on the contribution. After the feedback your branch will be merged into main branch of the repository. -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, religion, or sexual identity 10 | and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | * Demonstrating empathy and kindness toward other people 21 | * Being respectful of differing opinions, viewpoints, and experiences 22 | * Giving and gracefully accepting constructive feedback 23 | * Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | * Focusing on what is best not just for us as individuals, but for the 26 | overall community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | * The use of sexualized language or imagery, and sexual attention or 31 | advances of any kind 32 | * Trolling, insulting or derogatory comments, and personal or political attacks 33 | * Public or private harassment 34 | * Publishing others' private information, such as a physical or email 35 | address, without their explicit permission 36 | * Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at 63 | support@keploy.io. 64 | All complaints will be reviewed and investigated promptly and fairly. 65 | 66 | All community leaders are obligated to respect the privacy and security of the 67 | reporter of any incident. 68 | 69 | ## Enforcement Guidelines 70 | 71 | Community leaders will follow these Community Impact Guidelines in determining 72 | the consequences for any action they deem in violation of this Code of Conduct: 73 | 74 | ### 1. Correction 75 | 76 | **Community Impact**: Use of inappropriate language or other behavior deemed 77 | unprofessional or unwelcome in the community. 78 | 79 | **Consequence**: A private, written warning from community leaders, providing 80 | clarity around the nature of the violation and an explanation of why the 81 | behavior was inappropriate. A public apology may be requested. 82 | 83 | ### 2. Warning 84 | 85 | **Community Impact**: A violation through a single incident or series 86 | of actions. 87 | 88 | **Consequence**: A warning with consequences for continued behavior. No 89 | interaction with the people involved, including unsolicited interaction with 90 | those enforcing the Code of Conduct, for a specified period of time. This 91 | includes avoiding interactions in community spaces as well as external channels 92 | like social media. Violating these terms may lead to a temporary or 93 | permanent ban. 94 | 95 | ### 3. Temporary Ban 96 | 97 | **Community Impact**: A serious violation of community standards, including 98 | sustained inappropriate behavior. 99 | 100 | **Consequence**: A temporary ban from any sort of interaction or public 101 | communication with the community for a specified period of time. No public or 102 | private interaction with the people involved, including unsolicited interaction 103 | with those enforcing the Code of Conduct, is allowed during this period. 104 | Violating these terms may lead to a permanent ban. 105 | 106 | ### 4. Permanent Ban 107 | 108 | **Community Impact**: Demonstrating a pattern of violation of community 109 | standards, including sustained inappropriate behavior, harassment of an 110 | individual, or aggression toward or disparagement of classes of individuals. 111 | 112 | **Consequence**: A permanent ban from any sort of public interaction within 113 | the community. 114 | 115 | ## Attribution 116 | 117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 118 | version 2.0, available at 119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 120 | 121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct 122 | enforcement ladder](https://github.com/mozilla/diversity). 123 | 124 | [homepage]: https://www.contributor-covenant.org 125 | 126 | For answers to common questions about this code of conduct, see the FAQ at 127 | https://www.contributor-covenant.org/faq. Translations are available at 128 | https://www.contributor-covenant.org/translations. 129 | -------------------------------------------------------------------------------- /keploy/keploy.go: -------------------------------------------------------------------------------- 1 | // To activate, simply import this package for its side effects: 2 | // 3 | // import _ "github.com/keploy/go-sdk/v3/keploy" 4 | // 5 | // Then, build your application with atomic coverage instrumentation: 6 | // 7 | // go build -cover -covermode=atomic -o your-app . (-cover and -covermode=atomic is required as per https://pkg.go.dev/runtime/coverage@go1.25rc2#ClearCounters) 8 | package keploy 9 | 10 | import ( 11 | "bufio" 12 | "bytes" 13 | "encoding/json" 14 | "fmt" 15 | "log" 16 | "net" 17 | "os" 18 | "os/exec" 19 | "path/filepath" 20 | "runtime/coverage" 21 | "sort" 22 | "strings" 23 | "sync" 24 | 25 | "golang.org/x/tools/cover" 26 | ) 27 | 28 | const ( 29 | // controlSocketPath is used by Keploy to send commands (START/END) to the app. 30 | controlSocketPath = "/tmp/coverage_control.sock" 31 | // dataSocketPath is used by the app to send coverage data back to Keploy. 32 | dataSocketPath = "/tmp/coverage_data.sock" 33 | ) 34 | 35 | var ( 36 | // controlMu protects access to the currentTestID, ensuring command handling is atomic. 37 | controlMu sync.Mutex 38 | // currentTestID stores the ID of the test case currently being recorded. 39 | currentTestID string 40 | ) 41 | 42 | // init starts the background control server that listens for commands from the Keploy test runner. 43 | func init() { 44 | go startControlServer() 45 | } 46 | 47 | // startControlServer sets up and runs the Unix socket server that listens for commands from Keploy. 48 | func startControlServer() { 49 | err := os.RemoveAll(controlSocketPath) 50 | if err != nil { 51 | log.Printf("[Agent] Failed to remove old control socket: %v", err) 52 | return 53 | } 54 | 55 | ln, err := net.Listen("unix", controlSocketPath) 56 | if err != nil { 57 | log.Printf("[Agent] 🚨 FATAL: Could not start control server: %v", err) 58 | return 59 | } 60 | defer func() { 61 | if err := ln.Close(); err != nil { 62 | log.Printf("[Agent] Error closing control server: %v", err) 63 | } 64 | }() 65 | 66 | for { 67 | conn, err := ln.Accept() 68 | if err != nil { 69 | if strings.Contains(err.Error(), "use of closed network connection") { 70 | break 71 | } 72 | log.Printf("[Agent] Error accepting connection: %v", err) 73 | continue 74 | } 75 | go handleControlRequest(conn) 76 | } 77 | } 78 | 79 | // handleControlRequest parses commands from Keploy ("START testID", "END testID") 80 | func handleControlRequest(conn net.Conn) { 81 | defer func() { 82 | if err := conn.Close(); err != nil { 83 | log.Printf("[Agent] Error closing connection: %v", err) 84 | } 85 | }() 86 | 87 | command, err := bufio.NewReader(conn).ReadString('\n') 88 | if err != nil { 89 | log.Printf("[Agent] Error reading command: %v", err) 90 | return 91 | } 92 | 93 | // Split the command into action and testID 94 | parts := strings.SplitN(strings.TrimSpace(command), " ", 2) 95 | if len(parts) != 2 { 96 | log.Printf("[Agent] Invalid command format: '%s'", command) 97 | return 98 | } 99 | action, id := parts[0], parts[1] 100 | 101 | controlMu.Lock() 102 | defer controlMu.Unlock() 103 | 104 | switch action { 105 | case "START": 106 | currentTestID = id 107 | err := coverage.ClearCounters() 108 | if err != nil { 109 | log.Printf("[Agent] Error clearing coverage counters: %v", err) 110 | } 111 | case "END": 112 | if currentTestID != id { 113 | log.Printf("[Agent] Warning: Mismatched END command. Expected '%s', got '%s'. Skipping coverage report to avoid inconsistent state.", currentTestID, id) 114 | return 115 | } 116 | err := reportCoverage(id) 117 | if err != nil { 118 | log.Printf("[Agent] 🚨 Error reporting coverage for test %s: %v", id, err) 119 | } 120 | // Reset the currentTestID to an empty string to indicate that no test is currently being recorded. 121 | currentTestID = "" 122 | 123 | _, err = conn.Write([]byte("ACK\n")) 124 | if err != nil { 125 | log.Printf("[Agent] Error sending ACK to controller: %v", err) 126 | } 127 | default: 128 | log.Printf("[Agent] Unrecognized command: %s", action) 129 | } 130 | } 131 | 132 | // reportCoverage dumps, processes, and sends the coverage data. 133 | func reportCoverage(testID string) error { 134 | // Only take the part before the first slash, 135 | // e.g. "test-2" from "test-set-0/test-2" 136 | parts := strings.SplitN(testID, "/", 2) 137 | baseID := parts[1] 138 | 139 | // Create a temporary directory to store the coverage data. 140 | tempDir, err := os.MkdirTemp("", fmt.Sprintf("keploy-coverage-%s-", baseID)) 141 | if err != nil { 142 | return fmt.Errorf("failed to create temp dir: %w", err) 143 | } 144 | defer func() { 145 | if err := os.RemoveAll(tempDir); err != nil { 146 | log.Printf("[Agent] Error removing temp dir: %v", err) 147 | } 148 | }() 149 | 150 | err = coverage.WriteCountersDir(tempDir) 151 | if err != nil { 152 | return fmt.Errorf("failed to write coverage counters. Ensure the application was built with '-cover -covermode=atomic'. Original error: %w", err) 153 | } 154 | 155 | err = coverage.WriteMetaDir(tempDir) 156 | if err != nil { 157 | return fmt.Errorf("failed to write meta dir: %w", err) 158 | } 159 | 160 | processedData, err := processCoverageProfilesUsingCovdata(tempDir) 161 | if err != nil { 162 | return fmt.Errorf("failed to process coverage profiles: %w", err) 163 | } 164 | 165 | if len(processedData) == 0 { 166 | log.Printf("[Agent-Warning] No covered lines were found for test %s. The report will be empty.", testID) 167 | } 168 | 169 | payload := map[string]interface{}{ 170 | "id": testID, 171 | "executedLinesByFile": processedData, 172 | } 173 | 174 | jsonData, err := json.Marshal(payload) 175 | if err != nil { 176 | return fmt.Errorf("failed to marshal coverage data to JSON: %w", err) 177 | } 178 | 179 | return sendToSocket(jsonData) 180 | } 181 | 182 | // sendToSocket connects to the Keploy data socket and writes the JSON payload. 183 | func sendToSocket(data []byte) error { 184 | conn, err := net.Dial("unix", dataSocketPath) 185 | if err != nil { 186 | return fmt.Errorf("could not connect to keploy data socket at %s: %w", dataSocketPath, err) 187 | } 188 | defer func() { 189 | if err := conn.Close(); err != nil { 190 | log.Printf("[Agent] Error closing connection: %v", err) 191 | } 192 | }() 193 | 194 | _, err = conn.Write(data) 195 | return err 196 | } 197 | 198 | // processCoverageProfilesUsingCovdata uses the covdata tool to convert binary coverage data to text format 199 | // and then processes it using the standard cover package. 200 | func processCoverageProfilesUsingCovdata(dir string) (map[string][]int, error) { 201 | // Create a temporary file for the text format output 202 | textFile, err := os.CreateTemp("", "coverage-*.txt") 203 | if err != nil { 204 | return nil, fmt.Errorf("failed to create temp file for text coverage: %w", err) 205 | } 206 | defer func() { 207 | if err := os.Remove(textFile.Name()); err != nil { 208 | log.Printf("[Agent] Error removing temp file: %v", err) 209 | } 210 | }() 211 | 212 | defer func() { 213 | if err := textFile.Close(); err != nil { 214 | log.Printf("[Agent] Error closing temp file: %v", err) 215 | } 216 | }() 217 | 218 | // Use covdata to convert binary format to text format 219 | cmd := exec.Command("go", "tool", "covdata", "textfmt", "-i="+dir, "-o="+textFile.Name()) 220 | var stderr bytes.Buffer 221 | cmd.Stderr = &stderr 222 | 223 | err = cmd.Run() 224 | if err != nil { 225 | return nil, fmt.Errorf("failed to convert coverage data to text format: %w\nStderr: %s", err, stderr.String()) 226 | } 227 | 228 | // Get the module path (e.g., "your/module/path") to resolve file paths correctly. 229 | modulePathCmd := exec.Command("go", "list", "-m") 230 | var stderrModPath bytes.Buffer 231 | modulePathCmd.Stderr = &stderrModPath 232 | modulePathBytes, err := modulePathCmd.Output() 233 | if err != nil { 234 | return nil, fmt.Errorf("failed to get module path with 'go list -m': %w\nStderr: %s", err, stderrModPath.String()) 235 | } 236 | modulePath := strings.TrimSpace(string(modulePathBytes)) 237 | 238 | // Get the module's root directory on the filesystem. 239 | moduleDirCmd := exec.Command("go", "list", "-m", "-f", "{{.Dir}}") 240 | var stderrModDir bytes.Buffer 241 | moduleDirCmd.Stderr = &stderrModDir 242 | moduleDirBytes, err := moduleDirCmd.Output() 243 | if err != nil { 244 | return nil, fmt.Errorf("failed to get module directory with 'go list -m -f {{.Dir}}': %w\nStderr: %s", err, stderrModDir.String()) 245 | } 246 | moduleDir := strings.TrimSpace(string(moduleDirBytes)) 247 | 248 | // Parse the text format using the standard cover package. 249 | profiles, err := cover.ParseProfiles(textFile.Name()) 250 | if err != nil { 251 | return nil, fmt.Errorf("failed to parse text coverage profile: %w", err) 252 | } 253 | 254 | executedLinesByFile := make(map[string][]int) 255 | 256 | for _, profile := range profiles { 257 | var absolutePath string 258 | if strings.HasPrefix(profile.FileName, modulePath) { 259 | relativePath := strings.TrimPrefix(profile.FileName, modulePath) 260 | absolutePath = filepath.Join(moduleDir, relativePath) 261 | } else if !filepath.IsAbs(profile.FileName) { 262 | continue 263 | } else { 264 | absolutePath = profile.FileName 265 | } 266 | 267 | lineSet := make(map[int]bool) 268 | 269 | // For each block in the profile, if the count is greater than 0, add the lines to the map. 270 | for _, block := range profile.Blocks { 271 | if block.Count <= 0 { 272 | continue 273 | } 274 | for line := block.StartLine; line <= block.EndLine; line++ { 275 | lineSet[line] = true 276 | } 277 | } 278 | 279 | // If there are any lines executed, add them to the map. 280 | if len(lineSet) > 0 { 281 | lines := make([]int, 0, len(lineSet)) 282 | for line := range lineSet { 283 | lines = append(lines, line) 284 | } 285 | sort.Ints(lines) 286 | executedLinesByFile[absolutePath] = lines 287 | } 288 | } 289 | 290 | return executedLinesByFile, nil 291 | } 292 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2022 Keploy Inc 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------