GitNexus/gitnexus/test/integration/resolvers/python-attribute-accesses.test.ts
Gergő Magyar 1f2804e52f
fix(python): link field readers and qualify incomplete results (#3795)
* fix(python): track attribute accesses

Index constructor fields in both structure and class scope. Report known cross-language omissions consistently in context and upstream impact.

Fixes #3794

* refactor(python): share field classification rules

* fix(python): ignore replaced constructors

* fix(python): extract fields from binding targets

* fix: preserve Python field evidence (#3795)

* ci: fix Windows launch and Python baselines

Launch Vitest directly through Node so the native test subset avoids
cmd.exe's command-length limit and preserves argument boundaries.
Cover long lists, shell metacharacters, and child failures.

Refresh the Python capture fingerprint for attribute reads and constructor
fields. Receiver read drops increase from 31 to 34: two Path.parent reads
and admin.site.urls in existing Django fixtures. Call drops remain 141;
receiver-shape states and scaling budgets stay unchanged.

Validation: 425 tests, typecheck, lint, and all three benchmark checks pass.
Refs #3795

* test: disambiguate Python field cases

Vitest truncates interpolated case names, making distinct import and pattern cases collide in the execution audit. Include the case index so each receipt has a unique identity.

Validation: 420 tests passed. Reconciled all 31,481 CI test receipts after replacing the affected suite with its fresh result.

---------

Co-authored-by: Gergo Magyar <gergomagyar0@gmail.com>
2026-11-01 14:01:35 +00:00

171 lines
5.3 KiB
TypeScript

import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import {
getRelationships,
runPipelineFromRepo,
writeFixtureRepo,
type PipelineResult,
} from './helpers.js';
import { cleanupTempDirSync } from '../../helpers/test-db.js';
// Issue #3794. Attribute reads and assignments are different operations:
// https://docs.python.org/3/reference/expressions.html#attribute-references
// https://docs.python.org/3/reference/simple_stmts.html#assignment-statements
describe('Python attribute access edges (#3794)', () => {
let repoDir: string;
let result: PipelineResult;
beforeAll(async () => {
repoDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gitnexus-python-attributes-'));
writeFixtureRepo(repoDir, {
'pkg/__init__.py': '',
'pkg/model.py': `from dataclasses import dataclass, field
@dataclass
class Result:
failures: dict[str, str] = field(default_factory=dict)
class Plain:
def __init__(self) -> None:
self.value = 1
for self.loop in (1,):
pass
class Decoy:
def __init__(self):
self.value = 2
class Replaced:
def __init__(self):
self.stale = 1
def __init__(self):
self.live = 2
class AssignedConstructor:
def __init__(self):
self.stale = 1
__init__ = object.__init__
class ReboundReceiver:
def __init__(self):
def self():
pass
self.foreign = 1
def check() -> Result:
return Result()
`,
'pkg/use.py': `from pkg.model import Plain, Result, check
def read_from_annotated_return() -> dict[str, str]:
r = check()
return r.failures
def read_from_constructor() -> dict[str, str]:
r = Result()
return r.failures
def read_from_annotated_param(p: Plain) -> int:
return p.value
def read_from_loop_target(p: Plain) -> int:
return p.loop
def increment(p: Plain) -> None:
p.value += 1
def increment_fallback(p) -> None:
p.loop += 1
`,
'ts/box.ts': `export class Box { size = 1; }
export function readBox(b: Box): number { return b.size; }
`,
});
result = await runPipelineFromRepo(repoDir, () => {});
}, 60_000);
afterAll(() => {
if (repoDir) cleanupTempDirSync(repoDir);
});
it.each(['read_from_annotated_return', 'read_from_constructor'])(
'links %s to the dataclass field',
(reader) => {
const accesses = getRelationships(result, 'ACCESSES').filter(
(edge) => edge.source === reader,
);
expect(accesses.map((edge) => [edge.rel.targetId, edge.rel.reason])).toEqual([
['Property:pkg/model.py:Result.failures', 'read'],
]);
},
);
it('creates a Property for an attribute assigned on the constructor receiver', () => {
expect(result.graph.getNode('Property:pkg/model.py:Plain.value')).toMatchObject({
label: 'Property',
properties: { name: 'value', filePath: 'pkg/model.py', startLine: 8 },
});
});
it('links an annotated parameter read to its instance field', () => {
const accesses = getRelationships(result, 'ACCESSES').filter(
(edge) => edge.source === 'read_from_annotated_param',
);
expect(accesses.map((edge) => [edge.rel.targetId, edge.rel.reason])).toEqual([
['Property:pkg/model.py:Plain.value', 'read'],
]);
});
it('does not create fields from a replaced constructor', () => {
expect(result.graph.getNode('Property:pkg/model.py:Replaced.stale')).toBeUndefined();
expect(result.graph.getNode('Property:pkg/model.py:Replaced.live')).toMatchObject({
label: 'Property',
properties: { name: 'live' },
});
});
it('links reads to a field introduced by a constructor loop target', () => {
expect(result.graph.getNode('Property:pkg/model.py:Plain.loop')).toMatchObject({
label: 'Property',
properties: { name: 'loop' },
});
const accesses = getRelationships(result, 'ACCESSES').filter(
(edge) => edge.source === 'read_from_loop_target',
);
expect(accesses.map((edge) => [edge.rel.targetId, edge.rel.reason])).toEqual([
['Property:pkg/model.py:Plain.loop', 'read'],
]);
});
it.each([
['increment', 'value'],
['increment_fallback', 'loop'],
])('retains both access kinds for %s', (caller, field) => {
const accesses = getRelationships(result, 'ACCESSES').filter((edge) => edge.source === caller);
expect(accesses.map((edge) => edge.rel.targetId)).toEqual([
`Property:pkg/model.py:Plain.${field}`,
`Property:pkg/model.py:Plain.${field}`,
]);
expect(accesses.map((edge) => edge.rel.reason?.split(': ').at(-1)).sort()).toEqual([
'read',
'write',
]);
expect(new Set(accesses.map((edge) => edge.rel.id)).size).toBe(2);
});
it('rejects replaced constructors and locally rebound receivers', () => {
expect(result.graph.getNode('Property:pkg/model.py:AssignedConstructor.stale')).toBeUndefined();
expect(result.graph.getNode('Property:pkg/model.py:ReboundReceiver.foreign')).toBeUndefined();
});
it('retains the TypeScript control edge', () => {
const accesses = getRelationships(result, 'ACCESSES').filter(
(edge) => edge.source === 'readBox',
);
expect(accesses.map((edge) => [edge.rel.targetId, edge.rel.reason])).toEqual([
['Property:ts/box.ts:Box.size', 'read'],
]);
});
});