Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork2.8k
feat(utils): addRuleTester
API for top-level dependency constraints#5896
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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.
Already on GitHub?Sign in to your account
Merged
Uh oh!
There was an error while loading.Please reload this page.
Merged
Changes fromall commits
Commits
Show all changes
5 commits Select commitHold shift + click to select a range
a3f7b95
feat(utils): add `RuleTester` API for top-level dependency constraints
bradzachere220691
Apply suggestions from code review
bradzacher3e85184
address comments
bradzacher7e0c2cc
Merge branch 'main' into top-level-dependency-constraints-for-tests
bradzacher48c1196
oops
bradzacherFile filter
Filter by extension
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Diff view
Diff view
There are no files selected for viewing
89 changes: 76 additions & 13 deletionspackages/utils/src/eslint-utils/rule-tester/RuleTester.ts
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 |
---|---|---|
@@ -1,28 +1,42 @@ | ||
import type * as TSESLintParserType from '@typescript-eslint/parser'; | ||
import assert from 'assert'; | ||
import { version as eslintVersion } from 'eslint/package.json'; | ||
import * as path from 'path'; | ||
import * as semver from 'semver'; | ||
import type { ParserOptions } from '../../ts-eslint/ParserOptions'; | ||
import type { RuleModule } from '../../ts-eslint/Rule'; | ||
import type { RuleTesterTestFrameworkFunction } from '../../ts-eslint/RuleTester'; | ||
import * as BaseRuleTester from '../../ts-eslint/RuleTester'; | ||
import { deepMerge } from '../deepMerge'; | ||
import type { DependencyConstraint } from './dependencyConstraints'; | ||
import { satisfiesAllDependencyConstraints } from './dependencyConstraints'; | ||
const TS_ESLINT_PARSER = '@typescript-eslint/parser'; | ||
const ERROR_MESSAGE = `Do not set the parser at the test level unless you want to use a parser other than ${TS_ESLINT_PARSER}`; | ||
type RuleTesterConfig = Omit<BaseRuleTester.RuleTesterConfig, 'parser'> & { | ||
parser: typeof TS_ESLINT_PARSER; | ||
/** | ||
* Constraints that must pass in the current environment for any tests to run | ||
*/ | ||
dependencyConstraints?: DependencyConstraint; | ||
bradzacher marked this conversation as resolved. Show resolvedHide resolvedUh oh!There was an error while loading.Please reload this page. | ||
}; | ||
interface InvalidTestCase< | ||
TMessageIds extends string, | ||
TOptions extends Readonly<unknown[]>, | ||
> extends BaseRuleTester.InvalidTestCase<TMessageIds, TOptions> { | ||
/** | ||
* Constraints that must pass in the current environment for the test to run | ||
*/ | ||
dependencyConstraints?: DependencyConstraint; | ||
} | ||
interface ValidTestCase<TOptions extends Readonly<unknown[]>> | ||
extends BaseRuleTester.ValidTestCase<TOptions> { | ||
/** | ||
* Constraints that must pass in the current environment for the test to run | ||
*/ | ||
dependencyConstraints?: DependencyConstraint; | ||
} | ||
interface RunTests< | ||
@@ -36,24 +50,42 @@ interface RunTests< | ||
type AfterAll = (fn: () => void) => void; | ||
function isDescribeWithSkip( | ||
value: unknown, | ||
): value is RuleTesterTestFrameworkFunction & { | ||
skip: RuleTesterTestFrameworkFunction; | ||
} { | ||
return ( | ||
typeof value === 'object' && | ||
value != null && | ||
'skip' in value && | ||
typeof (value as Record<string, unknown>).skip === 'function' | ||
); | ||
} | ||
class RuleTester extends BaseRuleTester.RuleTester { | ||
readonly #baseOptions: RuleTesterConfig; | ||
static #afterAll: AfterAll | undefined; | ||
/** | ||
* If you supply a value to this property, the rule tester will call this instead of using the version defined on | ||
* the global namespace. | ||
*/ | ||
static get afterAll(): AfterAll { | ||
return ( | ||
this.#afterAll?? | ||
(typeof afterAll === 'function' ? afterAll : (): void => {}) | ||
); | ||
} | ||
static set afterAll(value: AfterAll | undefined) { | ||
this.#afterAll = value; | ||
} | ||
private get staticThis(): typeof RuleTester { | ||
// the cast here is due to https://github.com/microsoft/TypeScript/issues/3841 | ||
return this.constructor as typeof RuleTester; | ||
} | ||
constructor(baseOptions: RuleTesterConfig) { | ||
super({ | ||
...baseOptions, | ||
@@ -73,8 +105,7 @@ class RuleTester extends TSESLint.RuleTester { | ||
// make sure that the parser doesn't hold onto file handles between tests | ||
// on linux (i.e. our CI env), there can be very a limited number of watch handles available | ||
this.staticThis.afterAll(() => { | ||
try { | ||
// instead of creating a hard dependency, just use a soft require | ||
// a bit weird, but if they're using this tooling, it'll be installed | ||
@@ -85,11 +116,11 @@ class RuleTester extends TSESLint.RuleTester { | ||
} | ||
}); | ||
} | ||
private getFilename(testOptions?: ParserOptions): string { | ||
const resolvedOptions = deepMerge( | ||
this.#baseOptions.parserOptions, | ||
testOptions, | ||
) as ParserOptions; | ||
const filename = `file.ts${resolvedOptions.ecmaFeatures?.jsx ? 'x' : ''}`; | ||
if (resolvedOptions.project) { | ||
return path.join( | ||
@@ -107,9 +138,41 @@ class RuleTester extends TSESLint.RuleTester { | ||
// This is a lot more explicit | ||
run<TMessageIds extends string, TOptions extends Readonly<unknown[]>>( | ||
name: string, | ||
rule: RuleModule<TMessageIds, TOptions>, | ||
testsReadonly: RunTests<TMessageIds, TOptions>, | ||
): void { | ||
if ( | ||
this.#baseOptions.dependencyConstraints && | ||
!satisfiesAllDependencyConstraints( | ||
this.#baseOptions.dependencyConstraints, | ||
) | ||
) { | ||
if (isDescribeWithSkip(this.staticThis.describe)) { | ||
// for frameworks like mocha or jest that have a "skip" version of their function | ||
// we can provide a nice skipped test! | ||
this.staticThis.describe.skip(name, () => { | ||
this.staticThis.it( | ||
'All tests skipped due to unsatisfied constructor dependency constraints', | ||
() => {}, | ||
); | ||
}); | ||
} else { | ||
// otherwise just declare an empty test | ||
this.staticThis.describe(name, () => { | ||
this.staticThis.it( | ||
'All tests skipped due to unsatisfied constructor dependency constraints', | ||
() => { | ||
// some frameworks error if there are no assertions | ||
assert.equal(true, true); | ||
}, | ||
); | ||
}); | ||
} | ||
// don't run any tests because we don't match the base constraint | ||
return; | ||
} | ||
const tests = { | ||
// standardize the valid tests as objects | ||
valid: testsReadonly.valid.map(test => { | ||
21 changes: 10 additions & 11 deletionspackages/utils/src/ts-eslint/RuleTester.ts
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
91 changes: 89 additions & 2 deletionspackages/utils/tests/eslint-utils/rule-tester/RuleTester.test.ts
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 |
---|---|---|
@@ -73,8 +73,8 @@ RuleTester.itOnly = jest.fn(); | ||
/* eslint-enable jest/prefer-spy-on */ | ||
const mockedAfterAll = jest.mocked(RuleTester.afterAll); | ||
constmockedDescribe = jest.mocked(RuleTester.describe); | ||
constmockedIt = jest.mocked(RuleTester.it); | ||
const _mockedItOnly = jest.mocked(RuleTester.itOnly); | ||
const runSpy = jest.spyOn(BaseRuleTester.prototype, 'run'); | ||
const mockedParserClearCaches = jest.mocked(parser.clearCaches); | ||
@@ -715,5 +715,92 @@ describe('RuleTester', () => { | ||
} | ||
`); | ||
}); | ||
describe('constructor constraints', () => { | ||
it('skips all tests if a constructor constraint is not satisifed', () => { | ||
const ruleTester = new RuleTester({ | ||
parser: '@typescript-eslint/parser', | ||
dependencyConstraints: { | ||
'totally-real-dependency': '999', | ||
}, | ||
}); | ||
ruleTester.run('my-rule', NOOP_RULE, { | ||
invalid: [ | ||
{ | ||
code: 'failing - major', | ||
errors: [], | ||
}, | ||
], | ||
valid: [ | ||
{ | ||
code: 'passing - major', | ||
}, | ||
], | ||
}); | ||
// trigger the describe block | ||
expect(mockedDescribe.mock.calls.length).toBeGreaterThanOrEqual(1); | ||
mockedDescribe.mock.lastCall?.[1](); | ||
expect(mockedDescribe.mock.calls).toMatchInlineSnapshot(` | ||
[ | ||
[ | ||
"my-rule", | ||
[Function], | ||
], | ||
] | ||
`); | ||
expect(mockedIt.mock.lastCall).toMatchInlineSnapshot(` | ||
[ | ||
"All tests skipped due to unsatisfied constructor dependency constraints", | ||
[Function], | ||
] | ||
`); | ||
}); | ||
it('does not skip all tests if a constructor constraint is satisifed', () => { | ||
const ruleTester = new RuleTester({ | ||
parser: '@typescript-eslint/parser', | ||
dependencyConstraints: { | ||
'totally-real-dependency': '10', | ||
}, | ||
}); | ||
ruleTester.run('my-rule', NOOP_RULE, { | ||
invalid: [ | ||
{ | ||
code: 'valid', | ||
errors: [], | ||
}, | ||
], | ||
valid: [ | ||
{ | ||
code: 'valid', | ||
}, | ||
], | ||
}); | ||
bradzacher marked this conversation as resolved. Show resolvedHide resolvedUh oh!There was an error while loading.Please reload this page. | ||
// trigger the describe block | ||
expect(mockedDescribe.mock.calls.length).toBeGreaterThanOrEqual(1); | ||
mockedDescribe.mock.lastCall?.[1](); | ||
expect(mockedDescribe.mock.calls).toMatchInlineSnapshot(` | ||
[ | ||
[ | ||
"my-rule", | ||
[Function], | ||
], | ||
[ | ||
"valid", | ||
[Function], | ||
], | ||
[ | ||
"invalid", | ||
[Function], | ||
], | ||
] | ||
`); | ||
// expect(mockedIt.mock.lastCall).toMatchInlineSnapshot(`undefined`); | ||
}); | ||
}); | ||
}); | ||
}); |
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.