forked from oxc-project/oxc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtester.rs
424 lines (379 loc) · 12.9 KB
/
tester.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
use std::{
env,
path::{Path, PathBuf},
};
use cow_utils::CowUtils;
use oxc_allocator::Allocator;
use oxc_diagnostics::{DiagnosticService, GraphicalReportHandler, GraphicalTheme, NamedSource};
use serde::Deserialize;
use serde_json::Value;
use crate::{
fixer::FixKind, options::LintPluginOptions, rules::RULES, AllowWarnDeny, Fixer, LintService,
LintServiceOptions, Linter, OxlintOptions, Oxlintrc, RuleEnum, RuleWithSeverity,
};
#[derive(Eq, PartialEq)]
enum TestResult {
Passed,
Failed,
Fixed(String),
}
#[derive(Debug, Clone, Default)]
pub struct TestCase {
source: String,
rule_config: Option<Value>,
eslint_config: Option<Value>,
path: Option<PathBuf>,
}
impl From<&str> for TestCase {
fn from(source: &str) -> Self {
Self { source: source.to_string(), ..Self::default() }
}
}
impl From<String> for TestCase {
fn from(source: String) -> Self {
Self { source, ..Self::default() }
}
}
impl From<(&str, Option<Value>)> for TestCase {
fn from((source, rule_config): (&str, Option<Value>)) -> Self {
Self { source: source.to_string(), rule_config, ..Self::default() }
}
}
impl From<(&str, Option<Value>, Option<Value>)> for TestCase {
fn from((source, rule_config, eslint_config): (&str, Option<Value>, Option<Value>)) -> Self {
Self { source: source.to_string(), rule_config, eslint_config, ..Self::default() }
}
}
impl From<(&str, Option<Value>, Option<Value>, Option<PathBuf>)> for TestCase {
fn from(
(source, rule_config, eslint_config, path): (
&str,
Option<Value>,
Option<Value>,
Option<PathBuf>,
),
) -> Self {
Self { source: source.to_string(), rule_config, eslint_config, path }
}
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub enum ExpectFixKind {
/// We expect no fix to be applied
#[default]
None,
/// We expect some fix to be applied, but don't care what kind it is
Any,
/// We expect a fix of a certain [`FixKind`] to be applied
Specific(FixKind),
}
impl ExpectFixKind {
#[inline]
pub fn is_none(self) -> bool {
matches!(self, Self::None)
}
#[inline]
pub fn is_some(self) -> bool {
!self.is_none()
}
}
impl From<FixKind> for ExpectFixKind {
fn from(kind: FixKind) -> Self {
Self::Specific(kind)
}
}
impl From<ExpectFixKind> for FixKind {
fn from(expected_kind: ExpectFixKind) -> Self {
match expected_kind {
ExpectFixKind::None => FixKind::None,
ExpectFixKind::Any => FixKind::All,
ExpectFixKind::Specific(kind) => kind,
}
}
}
impl From<Option<FixKind>> for ExpectFixKind {
fn from(maybe_kind: Option<FixKind>) -> Self {
match maybe_kind {
Some(kind) => Self::Specific(kind),
None => Self::Any, // intentionally not None
}
}
}
#[derive(Debug, Clone)]
pub struct ExpectFix {
/// Source code being tested
source: String,
/// Expected source code after fix has been applied
expected: String,
kind: ExpectFixKind,
rule_config: Option<Value>,
}
impl<S: Into<String>> From<(S, S, Option<Value>)> for ExpectFix {
fn from(value: (S, S, Option<Value>)) -> Self {
Self {
source: value.0.into(),
expected: value.1.into(),
kind: ExpectFixKind::Any,
rule_config: value.2,
}
}
}
impl<S: Into<String>> From<(S, S)> for ExpectFix {
fn from(value: (S, S)) -> Self {
Self {
source: value.0.into(),
expected: value.1.into(),
kind: ExpectFixKind::Any,
rule_config: None,
}
}
}
impl<S, F> From<(S, S, Option<Value>, F)> for ExpectFix
where
S: Into<String>,
F: Into<ExpectFixKind>,
{
fn from((source, expected, config, kind): (S, S, Option<Value>, F)) -> Self {
Self {
source: source.into(),
expected: expected.into(),
kind: kind.into(),
rule_config: config,
}
}
}
pub struct Tester {
rule_name: &'static str,
rule_path: PathBuf,
expect_pass: Vec<TestCase>,
expect_fail: Vec<TestCase>,
expect_fix: Vec<ExpectFix>,
snapshot: String,
/// Suffix added to end of snapshot name.
///
/// See: [insta::Settings::set_snapshot_suffix]
snapshot_suffix: Option<&'static str>,
current_working_directory: Box<Path>,
// import_plugin: bool,
// jest_plugin: bool,
// vitest_plugin: bool,
// jsx_a11y_plugin: bool,
// nextjs_plugin: bool,
// react_perf_plugin: bool,
plugins: LintPluginOptions,
}
impl Tester {
pub fn new<T: Into<TestCase>>(
rule_name: &'static str,
expect_pass: Vec<T>,
expect_fail: Vec<T>,
) -> Self {
let rule_path =
PathBuf::from(rule_name.cow_replace('-', "_").into_owned()).with_extension("tsx");
let expect_pass = expect_pass.into_iter().map(Into::into).collect::<Vec<_>>();
let expect_fail = expect_fail.into_iter().map(Into::into).collect::<Vec<_>>();
let current_working_directory =
env::current_dir().unwrap().join("fixtures/import").into_boxed_path();
Self {
rule_name,
rule_path,
expect_pass,
expect_fail,
expect_fix: vec![],
snapshot: String::new(),
snapshot_suffix: None,
current_working_directory,
plugins: LintPluginOptions::none(),
}
}
/// Change the path
pub fn change_rule_path(mut self, path: &str) -> Self {
self.rule_path = self.current_working_directory.join(path);
self
}
/// Change the extension of the path
pub fn change_rule_path_extension(mut self, ext: &str) -> Self {
self.rule_path = self.rule_path.with_extension(ext);
self
}
pub fn with_snapshot_suffix(mut self, suffix: &'static str) -> Self {
self.snapshot_suffix = Some(suffix);
self
}
pub fn with_import_plugin(mut self, yes: bool) -> Self {
self.plugins.import = yes;
self
}
pub fn with_jest_plugin(mut self, yes: bool) -> Self {
self.plugins.jest = yes;
self
}
pub fn with_vitest_plugin(mut self, yes: bool) -> Self {
self.plugins.vitest = yes;
self
}
pub fn with_jsx_a11y_plugin(mut self, yes: bool) -> Self {
self.plugins.jsx_a11y = yes;
self
}
pub fn with_nextjs_plugin(mut self, yes: bool) -> Self {
self.plugins.nextjs = yes;
self
}
pub fn with_react_perf_plugin(mut self, yes: bool) -> Self {
self.plugins.react_perf = yes;
self
}
pub fn with_node_plugin(mut self, yes: bool) -> Self {
self.plugins.node = yes;
self
}
/// Add cases that should fix problems found in the source code.
///
/// These cases will fail if no fixes are produced or if the fixed source
/// code does not match the expected result.
///
/// ```
/// use oxc_linter::tester::Tester;
///
/// let pass = vec![
/// ("let x = 1", None)
/// ];
/// let fail = vec![];
/// // You can omit the rule_config if you never use it,
/// //otherwise its an Option<Value>
/// let fix = vec![
/// // source, expected, rule_config?
/// ("let x = 1", "let x = 1", None)
/// ];
///
/// // the first argument is normally `MyRuleStruct::NAME`.
/// Tester::new("no-undef", pass, fail).expect_fix(fix).test();
/// ```
pub fn expect_fix<F: Into<ExpectFix>>(mut self, expect_fix: Vec<F>) -> Self {
self.expect_fix = expect_fix.into_iter().map(std::convert::Into::into).collect::<Vec<_>>();
self
}
pub fn test(&mut self) {
self.test_pass();
self.test_fail();
self.test_fix();
}
pub fn test_and_snapshot(&mut self) {
self.test();
self.snapshot();
}
fn snapshot(&self) {
let name = self.rule_name.cow_replace('-', "_");
let mut settings = insta::Settings::clone_current();
settings.set_prepend_module_to_snapshot(false);
settings.set_omit_expression(true);
if let Some(suffix) = self.snapshot_suffix {
settings.set_snapshot_suffix(suffix);
}
settings.bind(|| {
insta::assert_snapshot!(name.as_ref(), self.snapshot);
});
}
fn test_pass(&mut self) {
for TestCase { source, rule_config, eslint_config, path } in self.expect_pass.clone() {
let result = self.run(&source, rule_config, &eslint_config, path, ExpectFixKind::None);
let passed = result == TestResult::Passed;
assert!(passed, "expect test to pass: {source} {}", self.snapshot);
}
}
fn test_fail(&mut self) {
for TestCase { source, rule_config, eslint_config, path } in self.expect_fail.clone() {
let result = self.run(&source, rule_config, &eslint_config, path, ExpectFixKind::None);
let failed = result == TestResult::Failed;
assert!(failed, "expect test to fail: {source}");
}
}
fn test_fix(&mut self) {
for fix in self.expect_fix.clone() {
let ExpectFix { source, expected, kind, rule_config: config } = fix;
let result = self.run(&source, config, &None, None, kind);
match result {
TestResult::Fixed(fixed_str) => assert_eq!(
expected, fixed_str,
r#"Expected "{source}" to be fixed into "{expected}""#
),
TestResult::Passed => panic!("Expected a fix, but test passed: {source}"),
TestResult::Failed => panic!("Expected a fix, but test failed: {source}"),
}
}
}
fn run(
&mut self,
source_text: &str,
rule_config: Option<Value>,
eslint_config: &Option<Value>,
path: Option<PathBuf>,
fix: ExpectFixKind,
) -> TestResult {
let allocator = Allocator::default();
let rule = self.find_rule().read_json(rule_config.unwrap_or_default());
let options = OxlintOptions::default()
.with_fix(fix.into())
.with_import_plugin(self.plugins.import)
.with_jest_plugin(self.plugins.jest)
.with_vitest_plugin(self.plugins.vitest)
.with_jsx_a11y_plugin(self.plugins.jsx_a11y)
.with_nextjs_plugin(self.plugins.nextjs)
.with_react_perf_plugin(self.plugins.react_perf)
.with_node_plugin(self.plugins.node);
let eslint_config = eslint_config
.as_ref()
.map_or_else(Oxlintrc::default, |v| Oxlintrc::deserialize(v).unwrap());
let linter = Linter::from_options(options)
.unwrap()
.with_rules(vec![RuleWithSeverity::new(rule, AllowWarnDeny::Warn)])
.with_eslint_config(eslint_config.into());
let path_to_lint = if self.plugins.import {
assert!(path.is_none(), "import plugin does not support path");
self.current_working_directory.join(&self.rule_path)
} else if let Some(path) = path {
self.current_working_directory.join(path)
} else if self.plugins.jest {
self.rule_path.with_extension("test.tsx")
} else {
self.rule_path.clone()
};
let cwd = self.current_working_directory.clone();
let paths = vec![path_to_lint.into_boxed_path()];
let options = LintServiceOptions::new(cwd, paths).with_cross_module(self.plugins.import);
let lint_service = LintService::from_linter(linter, options);
let diagnostic_service = DiagnosticService::default();
let tx_error = diagnostic_service.sender();
let result = lint_service.run_source(&allocator, source_text, false, tx_error);
if result.is_empty() {
return TestResult::Passed;
}
if fix.is_some() {
let fix_result = Fixer::new(source_text, result).fix();
return TestResult::Fixed(fix_result.fixed_code.to_string());
}
let diagnostic_path = if self.plugins.import {
self.rule_path.strip_prefix(&self.current_working_directory).unwrap()
} else {
&self.rule_path
}
.to_string_lossy();
let handler = GraphicalReportHandler::new()
.with_links(false)
.with_theme(GraphicalTheme::unicode_nocolor());
for diagnostic in result {
let diagnostic = diagnostic.error.with_source_code(NamedSource::new(
diagnostic_path.clone(),
source_text.to_string(),
));
handler.render_report(&mut self.snapshot, diagnostic.as_ref()).unwrap();
}
TestResult::Failed
}
fn find_rule(&self) -> &RuleEnum {
RULES
.iter()
.find(|rule| rule.name() == self.rule_name)
.unwrap_or_else(|| panic!("Rule not found: {}", &self.rule_name))
}
}