-
Notifications
You must be signed in to change notification settings - Fork 2
wip: pytest support #80
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
Draft
gnufede
wants to merge
26
commits into
main
Choose a base branch
from
gnufede/pytest-support
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
26 commits
Select commit
Hold shift + click to select a range
57df98f
Add Python and Pytest support
gnufede db483ad
Add ddtrace pytest plugin auto-instrumentation
gnufede d45c62e
Update pytest instrumentation to use --ddtrace and verify both packages
gnufede bc28e5e
Update ddtrace minimum version to 4.10.3
gnufede 2a06372
Remove redundant datadog-test-lib check, ddtrace is the instrumentati…
gnufede a6a868e
Append --ddtrace to PYTEST_ADDOPTS instead of replacing
gnufede 5c47416
Fix pytest DiscoverTests ignoring --tests-location
gnufede d5438df
Use importlib.metadata instead of pip show to check ddtrace version
gnufede abbb18c
Load test file patterns from pytest config, fall back to Buildkite de…
gnufede ba303aa
Add tests for Python platform
gnufede c31a67d
Simplify DiscoverTestFiles to use a single glob pattern
gnufede a31132f
fix(pytest): align discovery env vars with dd-trace-py and Ruby imple…
gnufede b5d8609
revert(pytest): restore original discovery env var names in BaseDisco…
gnufede 7170ff3
Handle PEP 440 pre-release versions in SanityCheck
gnufede 694904a
Downgrade cancelled discovery log from WARN to DEBUG
gnufede 9c320c9
Revert "Downgrade cancelled discovery log from WARN to DEBUG"
gnufede ecd8e56
Downgrade cancelled discovery log from WARN to DEBUG
gnufede 56415e5
Downgrade cancelled discovery log from WARN to DEBUG
gnufede b6d83d9
Revert log changes to framework.go and planner.go
gnufede 94005b0
Also set DD_TEST_OPTIMIZATION_MANIFEST_FILE for worker processes
gnufede 1a6a8bd
Bump manifest version to 2 to enable cached test skipping in ddtest mode
gnufede 4dc367e
Revert manifest version bump — ddtest stays on version 1
gnufede 8497270
fix(python): align runtime.name and os.platform tags with ddtrace
gnufede f163cf6
feat(debug): add DDTEST_LOG_LEVEL=debug support and matching diagnostics
gnufede d546dc7
test(python): skip TestDetectPlatform_Python when ddtrace not installed
gnufede 6f5e23c
fix(lint): pass context.TODO() instead of nil to slog.Enabled
gnufede File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,135 @@ | ||
| package framework | ||
|
|
||
| import ( | ||
| "context" | ||
| "log/slog" | ||
| "maps" | ||
| "strings" | ||
|
|
||
| "github.com/DataDog/ddtest/internal/ext" | ||
| "github.com/DataDog/ddtest/internal/settings" | ||
| "github.com/DataDog/ddtest/internal/testoptimization" | ||
| ) | ||
|
|
||
| const ( | ||
| // pytestDefaultPattern is used when no config file specifies testpaths/python_files. | ||
| // Matches both pytest conventions (test_*.py and *_test.py) everywhere in the tree. | ||
| pytestDefaultPattern = "**/{test_*,*_test}.py" | ||
| ) | ||
|
|
||
| type PyTest struct { | ||
| executor ext.CommandExecutor | ||
| commandOverride []string | ||
| platformEnv map[string]string | ||
| } | ||
|
|
||
| func NewPytest() *PyTest { | ||
| return &PyTest{ | ||
| executor: &ext.DefaultCommandExecutor{}, | ||
| commandOverride: loadCommandOverride(), | ||
| platformEnv: make(map[string]string), | ||
| } | ||
| } | ||
|
|
||
| func (p *PyTest) SetPlatformEnv(platformEnv map[string]string) { | ||
| p.platformEnv = platformEnv | ||
| } | ||
|
|
||
| func (p *PyTest) GetPlatformEnv() map[string]string { | ||
| return p.platformEnv | ||
| } | ||
|
|
||
| func (p *PyTest) Name() string { | ||
| return "pytest" | ||
| } | ||
|
|
||
| func (p *PyTest) DiscoverTests(ctx context.Context) ([]testoptimization.Test, error) { | ||
| cleanupDiscoveryFile(TestsDiscoveryFilePath) | ||
|
|
||
| args := []string{"-m", "pytest"} | ||
|
|
||
| // When a custom tests location is configured, resolve the glob to actual files | ||
| // and pass them to pytest so collection is constrained to only those files. | ||
| // Without this, --tests-location would be silently ignored during discovery. | ||
| if settings.GetTestsLocation() != "" { | ||
| testFiles, err := p.DiscoverTestFiles() | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| slog.Info("Constraining test discovery to custom location", | ||
| "pattern", settings.GetTestsLocation(), "fileCount", len(testFiles)) | ||
| args = append(args, testFiles...) | ||
| } | ||
|
|
||
| // Merge env maps: platform env -> base discovery env | ||
| envMap := make(map[string]string) | ||
| maps.Copy(envMap, p.platformEnv) | ||
| maps.Copy(envMap, BaseDiscoveryEnv()) | ||
|
|
||
| slog.Info("Discovering tests with command", "command", "python", "args", args) | ||
| _, err := executeDiscoveryCommand(ctx, p.executor, "python", args, envMap, p.Name()) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
|
|
||
| tests, err := parseDiscoveryFile(TestsDiscoveryFilePath) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
|
|
||
| slog.Debug("Parsed pytest report", "tests", len(tests)) | ||
| return tests, nil | ||
| } | ||
|
|
||
| func (p *PyTest) DiscoverTestFiles() ([]string, error) { | ||
| testFiles, err := globTestFiles(p.testPattern()) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| slog.Debug("Discovered pytest test files", "count", len(testFiles)) | ||
| return testFiles, nil | ||
| } | ||
|
|
||
| // testPattern returns the single glob pattern used to discover test files. | ||
| // Priority: explicit --tests-location flag > pytest config file > built-in default. | ||
| // Multiple testpaths or python_files from config are collapsed into brace-expansion | ||
| // syntax that doublestar handles natively, e.g. {tests,src}/**/{test_*,*_test}.py. | ||
| func (p *PyTest) testPattern() string { | ||
| if custom := settings.GetTestsLocation(); custom != "" { | ||
| return custom | ||
| } | ||
|
|
||
| cfg := loadPytestConfig() | ||
|
|
||
| filePatterns := cfg.PythonFiles | ||
| if len(filePatterns) == 0 { | ||
| filePatterns = []string{"{test_*,*_test}.py"} | ||
| } | ||
| filePart := braceExpand(filePatterns) | ||
|
|
||
| if len(cfg.Testpaths) == 0 { | ||
| return "**/" + filePart | ||
| } | ||
| return braceExpand(cfg.Testpaths) + "/**/" + filePart | ||
| } | ||
|
|
||
| // braceExpand collapses a list into a single glob token. | ||
| // A single item is returned as-is; multiple items are wrapped: {a,b,c}. | ||
| func braceExpand(items []string) string { | ||
| if len(items) == 1 { | ||
| return items[0] | ||
| } | ||
| return "{" + strings.Join(items, ",") + "}" | ||
| } | ||
|
|
||
| func (p *PyTest) RunTests(ctx context.Context, testFiles []string, envMap map[string]string) error { | ||
| command := "python" | ||
| args := []string{"-m", "pytest"} | ||
| slog.Info("Running tests with command", "command", command, "args", args) | ||
| args = append(args, testFiles...) | ||
|
|
||
| mergedEnv := make(map[string]string) | ||
| maps.Copy(mergedEnv, p.platformEnv) | ||
| maps.Copy(mergedEnv, envMap) | ||
| return p.executor.Run(ctx, command, args, mergedEnv) | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,133 @@ | ||
| package framework | ||
|
|
||
| import ( | ||
| "bufio" | ||
| "bytes" | ||
| "os" | ||
| "strings" | ||
|
|
||
| "github.com/pelletier/go-toml/v2" | ||
| ) | ||
|
|
||
| // pytestConfig holds the subset of pytest config relevant for test file discovery. | ||
| type pytestConfig struct { | ||
| Testpaths []string | ||
| PythonFiles []string | ||
| } | ||
|
|
||
| // loadPytestConfig reads testpaths and python_files from the first pytest config | ||
| // file found, checking in pytest's own precedence order. | ||
| // Returns a zero-value config when no file is found or no relevant keys are set. | ||
| func loadPytestConfig() pytestConfig { | ||
| if data, err := os.ReadFile("pytest.ini"); err == nil { | ||
| if cfg, ok := parsePytestIni(data, "pytest"); ok { | ||
| return cfg | ||
| } | ||
| } | ||
| if data, err := os.ReadFile("pyproject.toml"); err == nil { | ||
| if cfg, ok := parsePyprojectToml(data); ok { | ||
| return cfg | ||
| } | ||
| } | ||
| if data, err := os.ReadFile("tox.ini"); err == nil { | ||
| if cfg, ok := parsePytestIni(data, "pytest"); ok { | ||
| return cfg | ||
| } | ||
| } | ||
| if data, err := os.ReadFile("setup.cfg"); err == nil { | ||
| if cfg, ok := parsePytestIni(data, "tool:pytest"); ok { | ||
| return cfg | ||
| } | ||
| } | ||
| return pytestConfig{} | ||
| } | ||
|
|
||
| // parsePytestIni extracts testpaths and python_files from an INI-format config. | ||
| // section is the section name to look for (e.g. "pytest" or "tool:pytest"). | ||
| // Values may be space-separated on the same line, or newline-indented continuations. | ||
| func parsePytestIni(data []byte, section string) (pytestConfig, bool) { | ||
| var cfg pytestConfig | ||
| inSection := false | ||
| var currentKey string | ||
| var currentValues []string | ||
|
|
||
| flush := func() { | ||
| switch currentKey { | ||
| case "testpaths": | ||
| cfg.Testpaths = currentValues | ||
| case "python_files": | ||
| cfg.PythonFiles = currentValues | ||
| } | ||
| currentKey = "" | ||
| currentValues = nil | ||
| } | ||
|
|
||
| scanner := bufio.NewScanner(bytes.NewReader(data)) | ||
| for scanner.Scan() { | ||
| line := scanner.Text() | ||
| trimmed := strings.TrimSpace(line) | ||
|
|
||
| if trimmed == "" || strings.HasPrefix(trimmed, "#") || strings.HasPrefix(trimmed, ";") { | ||
| continue | ||
| } | ||
|
|
||
| if strings.HasPrefix(trimmed, "[") && strings.HasSuffix(trimmed, "]") { | ||
| flush() | ||
| inSection = trimmed[1:len(trimmed)-1] == section | ||
| continue | ||
| } | ||
|
|
||
| if !inSection { | ||
| continue | ||
| } | ||
|
|
||
| // Continuation lines are indented | ||
| if line[0] == ' ' || line[0] == '\t' { | ||
| currentValues = append(currentValues, strings.Fields(trimmed)...) | ||
| continue | ||
| } | ||
|
|
||
| idx := strings.IndexByte(trimmed, '=') | ||
| if idx < 0 { | ||
| continue | ||
| } | ||
| flush() | ||
| key := strings.TrimSpace(trimmed[:idx]) | ||
| value := strings.TrimSpace(trimmed[idx+1:]) | ||
| if key == "testpaths" || key == "python_files" { | ||
| currentKey = key | ||
| if value != "" { | ||
| currentValues = strings.Fields(value) | ||
| } | ||
| } | ||
| } | ||
| flush() | ||
|
|
||
| return cfg, len(cfg.Testpaths) > 0 || len(cfg.PythonFiles) > 0 | ||
| } | ||
|
|
||
| type pyprojectTomlFile struct { | ||
| Tool struct { | ||
| Pytest struct { | ||
| IniOptions struct { | ||
| Testpaths []string `toml:"testpaths"` | ||
| PythonFiles []string `toml:"python_files"` | ||
| } `toml:"ini_options"` | ||
| } `toml:"pytest"` | ||
| } `toml:"tool"` | ||
| } | ||
|
|
||
| func parsePyprojectToml(data []byte) (pytestConfig, bool) { | ||
| var parsed pyprojectTomlFile | ||
| if err := toml.Unmarshal(data, &parsed); err != nil { | ||
| return pytestConfig{}, false | ||
| } | ||
| opts := parsed.Tool.Pytest.IniOptions | ||
| if len(opts.Testpaths) == 0 && len(opts.PythonFiles) == 0 { | ||
| return pytestConfig{}, false | ||
| } | ||
| return pytestConfig{ | ||
| Testpaths: opts.Testpaths, | ||
| PythonFiles: opts.PythonFiles, | ||
| }, true | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
you can probably reuse
globTestFilesfunction defined inframework.goThere was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
globTestFileswas used in line 88, I guess you mean to try yo simplify this function.A small refactor around it is in commit c31a67d
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
yes, exactly, I was just under the impression that this is too long