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

[don't merge]Adding test case with ai agent help #1911

Draft
wants to merge 10 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions .github/workflows/dispatch.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
name: Dispatch Trigger as expirement for SamYuan1990/OpenAI_CodeAgent-action

on:

Check warning on line 3 in .github/workflows/dispatch.yml

View workflow job for this annotation

GitHub Actions / yamllint / yamllint

3:1 [truthy] truthy value should be one of [false, true]

Check warning on line 3 in .github/workflows/dispatch.yml

View workflow job for this annotation

GitHub Actions / pre-commit

3:1 [truthy] truthy value should be one of [false, true]
workflow_dispatch:

permissions:
contents: read
pull-requests: write

jobs:
test-action:
name: GitHub Actions Test
runs-on: ubuntu-latest

steps:
- name: Checkout
id: checkout
uses: actions/checkout@v4

- name: Test Local Action
id: test-action
uses: SamYuan1990/OpenAI_CodeAgent-action@main
with:
baseURL: https://api.deepseek.com
apiKey: ${{ secrets.API_KEY }}
fileOverWrite: true

- name: Create Pull Request
uses: peter-evans/create-pull-request@v5
with:
token: ${{ secrets.MyPATToken }} # 使用 GitHub 提供的 token
branch: auto-pr-branch # 新分支名称
base: main # 目标分支
title: 'Automated PR: Update generated files'

Check failure on line 34 in .github/workflows/dispatch.yml

View workflow job for this annotation

GitHub Actions / yamllint / yamllint

34:18 [quoted-strings] string value is not quoted with double quotes

Check failure on line 34 in .github/workflows/dispatch.yml

View workflow job for this annotation

GitHub Actions / pre-commit

34:18 [quoted-strings] string value is not quoted with double quotes
body: 'This is an automated pull request created by GitHub Actions.'

Check failure on line 35 in .github/workflows/dispatch.yml

View workflow job for this annotation

GitHub Actions / yamllint / yamllint

35:17 [quoted-strings] string value is redundantly quoted with double quotes

Check failure on line 35 in .github/workflows/dispatch.yml

View workflow job for this annotation

GitHub Actions / pre-commit

35:17 [quoted-strings] string value is redundantly quoted with double quotes
commit-message: 'Auto-generated changes'

Check failure on line 36 in .github/workflows/dispatch.yml

View workflow job for this annotation

GitHub Actions / yamllint / yamllint

36:27 [quoted-strings] string value is redundantly quoted with double quotes

Check failure on line 36 in .github/workflows/dispatch.yml

View workflow job for this annotation

GitHub Actions / pre-commit

36:27 [quoted-strings] string value is redundantly quoted with double quotes
sign-commits: true
labels: automated # 可选:为 PR 添加标签
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -168,3 +168,5 @@ dual licensed as above, without any additional terms or conditions.
## Star History

[![Star History Chart](https://api.star-history.com/svg?repos=sustainable-computing-io/kepler&type=Date)](https://star-history.com/#sustainable-computing-io/kepler&Date)

just dummy change
20 changes: 20 additions & 0 deletions Tasks.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"tasks": [
{
"id": "my_example_task_for_golang",
"inputFilePath": "./cmd/exporter/exporter.go",
"inputFileProcessMethod": "by_function",
"prompt": "Please help me create unit test file for this function with ginkgo framework, here is the function:",
"outputProcessMethod": "regex_match",
"outputFilePath": "./cmd/exporter/exporter{{index}}_test.go"
},
{
"id": "my_example_task_for_golang_test",
"inputFilePath": "./pkg/collector/metric_collector_test.go",
"inputFileProcessMethod": "by_function",
"prompt": "Please help me create benchmark test content for this function, here is the content:",
"outputProcessMethod": "regex_match",
"outputFilePath": "./pkg/collector/metric_collector{{index}}_test.go"
}
]
}
13 changes: 13 additions & 0 deletions cmd/exporter/exporter_suite_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package main

import (
"testing"

. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)

func TestExporter(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Exporter Suite")
}
159 changes: 159 additions & 0 deletions cmd/exporter/exporter_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
package main

import (
"flag"
"fmt"
"net/http"
"net/http/httptest"
"strings"

. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/sustainable-computing-io/kepler/pkg/config"
)

var _ = Describe("AppConfig", func() {
var cfg *AppConfig

BeforeEach(func() {
cfg = newAppConfig()
// Reset the command-line flags before each test
flag.CommandLine = flag.NewFlagSet("test", flag.ContinueOnError)
})

It("should initialize with default values", func() {
Expect(cfg.BaseDir).To(Equal(config.BaseDir))
Expect(cfg.Address).To(Equal("0.0.0.0:8888"))
Expect(cfg.MetricsPath).To(Equal("/metrics"))
Expect(cfg.EnableGPU).To(BeFalse())
Expect(cfg.EnableEBPFCgroupID).To(BeTrue())
Expect(cfg.ExposeHardwareCounterMetrics).To(BeTrue())
Expect(cfg.EnableMSR).To(BeFalse())
Expect(cfg.Kubeconfig).To(BeEmpty())
Expect(cfg.ApiserverEnabled).To(BeTrue())
Expect(cfg.RedfishCredFilePath).To(BeEmpty())
Expect(cfg.ExposeEstimatedIdlePower).To(BeFalse())
Expect(cfg.MachineSpecFilePath).To(BeEmpty())
Expect(cfg.DisablePowerMeter).To(BeFalse())
Expect(cfg.TLSFilePath).To(BeEmpty())
})

It("should override default values with command-line flags", func() {
cfg = newAppConfig()
// Set command-line flags
flag.Set("config-dir", "/custom/config/dir")

Check failure on line 44 in cmd/exporter/exporter_test.go

View workflow job for this annotation

GitHub Actions / golang / lint

Error return value of `flag.Set` is not checked (errcheck)
flag.Set("address", "127.0.0.1:8080")

Check failure on line 45 in cmd/exporter/exporter_test.go

View workflow job for this annotation

GitHub Actions / golang / lint

Error return value of `flag.Set` is not checked (errcheck)
flag.Set("metrics-path", "/custom/metrics")

Check failure on line 46 in cmd/exporter/exporter_test.go

View workflow job for this annotation

GitHub Actions / golang / lint

Error return value of `flag.Set` is not checked (errcheck)
flag.Set("enable-gpu", "true")
flag.Set("enable-cgroup-id", "false")
flag.Set("expose-hardware-counter-metrics", "false")
flag.Set("enable-msr", "true")
flag.Set("kubeconfig", "/custom/kubeconfig")
flag.Set("apiserver", "false")
flag.Set("redfish-cred-file-path", "/custom/redfish/cred")
flag.Set("expose-estimated-idle-power", "true")
flag.Set("machine-spec", "/custom/machine/spec")
flag.Set("disable-power-meter", "true")
flag.Set("web.config.file", "/custom/tls/config")

// Parse the flags
flag.Parse()

// Verify that the values are overridden
Expect(cfg.BaseDir).To(Equal("/custom/config/dir"))
Expect(cfg.Address).To(Equal("127.0.0.1:8080"))
Expect(cfg.MetricsPath).To(Equal("/custom/metrics"))
Expect(cfg.EnableGPU).To(BeTrue())
Expect(cfg.EnableEBPFCgroupID).To(BeFalse())
Expect(cfg.ExposeHardwareCounterMetrics).To(BeFalse())
Expect(cfg.EnableMSR).To(BeTrue())
Expect(cfg.Kubeconfig).To(Equal("/custom/kubeconfig"))
Expect(cfg.ApiserverEnabled).To(BeFalse())
Expect(cfg.RedfishCredFilePath).To(Equal("/custom/redfish/cred"))
Expect(cfg.ExposeEstimatedIdlePower).To(BeTrue())
Expect(cfg.MachineSpecFilePath).To(Equal("/custom/machine/spec"))
Expect(cfg.DisablePowerMeter).To(BeTrue())
Expect(cfg.TLSFilePath).To(Equal("/custom/tls/config"))
})
})

var _ = Describe("HealthProbe", func() {
var (
w *httptest.ResponseRecorder
req *http.Request
)

BeforeEach(func() {
// Initialize the response recorder and request before each test
w = httptest.NewRecorder()
req = httptest.NewRequest("GET", "/health", nil)

Check failure on line 89 in cmd/exporter/exporter_test.go

View workflow job for this annotation

GitHub Actions / golang / lint

httpNoBody: http.NoBody should be preferred to the nil request body (gocritic)
})

Context("when the health probe is called", func() {
It("should return HTTP status OK", func() {
healthProbe(w, req)

Expect(w.Code).To(Equal(http.StatusOK))
})

It("should return 'ok' in the response body", func() {
healthProbe(w, req)

Expect(w.Body.String()).To(Equal("ok"))
})
})
})

var _ = Describe("RootHandler", func() {
var (
metricPathConfig string
handler http.HandlerFunc
recorder *httptest.ResponseRecorder
request *http.Request
)

BeforeEach(func() {
metricPathConfig = "/metrics"
handler = rootHandler(metricPathConfig)
recorder = httptest.NewRecorder()
request = httptest.NewRequest("GET", "/", nil)

Check failure on line 119 in cmd/exporter/exporter_test.go

View workflow job for this annotation

GitHub Actions / golang / lint

httpNoBody: http.NoBody should be preferred to the nil request body (gocritic)
})

Context("when the root endpoint is accessed", func() {
It("should return a valid HTML response with the correct metric path", func() {
handler.ServeHTTP(recorder, request)

Expect(recorder.Code).To(Equal(http.StatusOK))
Expect(recorder.Body.String()).To(ContainSubstring("<title>Energy Stats Exporter</title>"))
Expect(recorder.Body.String()).To(ContainSubstring("<h1>Energy Stats Exporter</h1>"))
Expect(recorder.Body.String()).To(ContainSubstring(`<a href="` + metricPathConfig + `">Metrics</a>`))
})
})

Context("when the response writing fails", func() {
It("should log an error", func() {
// Mock the response writer to simulate a write failure
failingRecorder := &FailingResponseRecorder{httptest.NewRecorder(), false}
handler.ServeHTTP(failingRecorder, request)

// Here you would typically check if the error was logged.
// Since klog is used, you might need to capture logs or mock klog for this test.
// This is a placeholder to indicate where you would check for the error log.
Expect(failingRecorder.Failed).To(BeTrue())
})
})
})

// FailingResponseRecorder is a custom ResponseRecorder that fails on Write
type FailingResponseRecorder struct {
*httptest.ResponseRecorder
Failed bool
}

func (r *FailingResponseRecorder) Write(b []byte) (int, error) {
if strings.Contains(string(b), "Metrics") {
r.Failed = true
return 0, fmt.Errorf("simulated write failure")
}
return r.ResponseRecorder.Write(b)
}
22 changes: 22 additions & 0 deletions pkg/collector/metric_collector_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package collector

import (
"testing"

. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"

Expand Down Expand Up @@ -74,3 +76,23 @@
})

})

func BenchmarkHandleInactiveContainers(b *testing.B) {
// Initialize the mock exporter and collector
config.Initialize(".")

Check failure on line 82 in pkg/collector/metric_collector_test.go

View workflow job for this annotation

GitHub Actions / golang / lint

Error return value of `config.Initialize` is not checked (errcheck)
bpfExporter := bpf.NewMockExporter(bpf.DefaultSupportedMetrics())
metricCollector := newMockCollector(bpfExporter)

// Create a map of found containers
foundContainer := make(map[string]bool)
foundContainer["container1"] = true
foundContainer["container2"] = true

// Reset the timer to exclude setup time from the benchmark
b.ResetTimer()

// Run the benchmark
for i := 0; i < b.N; i++ {
metricCollector.handleInactiveContainers(foundContainer)
}
}
Loading