Skip to content

Commit 03173db

Browse files
test(analyser): add debug_test
1 parent c7aea51 commit 03173db

File tree

7 files changed

+94
-13
lines changed

7 files changed

+94
-13
lines changed

Cargo.lock

Lines changed: 3 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

crates/pg_analyse/src/rule.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@ pub trait Rule: RuleMeta + Sized {
9494
}
9595

9696
/// Diagnostic object returned by a single analysis rule
97-
#[derive(Debug, Diagnostic)]
97+
#[derive(Debug, Diagnostic, PartialEq)]
9898
pub struct RuleDiagnostic {
9999
#[category]
100100
pub(crate) category: &'static Category,
@@ -109,7 +109,7 @@ pub struct RuleDiagnostic {
109109
pub(crate) rule_advice: RuleAdvice,
110110
}
111111

112-
#[derive(Debug, Default)]
112+
#[derive(Debug, Default, PartialEq)]
113113
/// It contains possible advices to show when printing a diagnostic that belong to the rule
114114
pub struct RuleAdvice {
115115
pub(crate) details: Vec<Detail>,
@@ -118,7 +118,7 @@ pub struct RuleAdvice {
118118
pub(crate) code_suggestion_list: Vec<CodeSuggestionAdvice<MarkupBuf>>,
119119
}
120120

121-
#[derive(Debug, Default)]
121+
#[derive(Debug, Default, PartialEq)]
122122
pub struct SuggestionList {
123123
pub(crate) message: MarkupBuf,
124124
pub(crate) list: Vec<MarkupBuf>,
@@ -160,7 +160,7 @@ impl Advices for RuleAdvice {
160160
}
161161
}
162162

163-
#[derive(Debug)]
163+
#[derive(Debug, PartialEq)]
164164
pub struct Detail {
165165
pub log_category: LogCategory,
166166
pub message: MarkupBuf,

crates/pg_analyser/CONTRIBUTING.md

Lines changed: 22 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ We follow a naming convention according to what the rule does:
3535
A rule should be informative to the user, and give as much explanation as possible.
3636

3737
When writing a rule, you must adhere to the following **pillars**:
38+
3839
1. Explain to the user the error. Generally, this is the message of the diagnostic.
3940
1. Explain to the user **why** the error is triggered. Generally, this is implemented with an additional node.
4041
1. Tell the user what they should do. Generally, this is implemented using a code action. If a code action is not applicable a note should tell the user what they should do to fix the error.
@@ -53,6 +54,7 @@ Let's say we want to create a new **lint** rule called `useMyRuleName`, follow t
5354
```shell
5455
just new-lintrule safety useMyRuleName
5556
```
57+
5658
The script will generate a bunch of files inside the `pg_analyser` crate.
5759
Among the other files, you'll find a file called `use_my_new_rule_name.rs` inside the `pg_analyser/lib/src/lint/safety` folder. You'll implement your rule in this file.
5860

@@ -127,6 +129,7 @@ The compiler should warn you that `MyRuleOptions` does not implement some requir
127129
We currently require implementing _serde_'s traits `Deserialize`/`Serialize`.
128130

129131
Also, we use other `serde` macros to adjust the JSON configuration:
132+
130133
- `rename_all = "snake_case"`: it renames all fields in camel-case, so they are in line with the naming style of the `pglsp.toml`.
131134
- `deny_unknown_fields`: it raises an error if the configuration contains extraneous fields.
132135
- `default`: it uses the `Default` value when the field is missing from `pglsp.toml`. This macro makes the field optional.
@@ -159,7 +162,6 @@ pub enum Behavior {
159162

160163
Below, there are many tips and guidelines on how to create a lint rule using our infrastructure.
161164

162-
163165
#### `declare_lint_rule`
164166

165167
This macro is used to declare an analyzer rule type, and implement the [RuleMeta] trait for it.
@@ -235,6 +237,7 @@ impl Rule for BanDropColumn {
235237
### Document the rule
236238

237239
The documentation needs to adhere to the following rules:
240+
238241
- The **first** paragraph of the documentation is used as brief description of the rule, and it **must** be written in one single line. Breaking the paragraph in multiple lines will break the table content of the rules page.
239242
- The next paragraphs can be used to further document the rule with as many details as you see fit.
240243
- The documentation must have a `## Examples` header, followed by two headers: `### Invalid` and `### Valid`. `### Invalid` must go first because we need to show when the rule is triggered.
@@ -246,7 +249,7 @@ The documentation needs to adhere to the following rules:
246249

247250
Here's an example of how the documentation could look like:
248251

249-
```rust
252+
````rust
250253
declare_lint_rule! {
251254
/// Dropping a column may break existing clients.
252255
///
@@ -269,12 +272,26 @@ declare_lint_rule! {
269272
sources: &[RuleSource::Squawk("ban-drop-column")],
270273
}
271274
}
272-
```
275+
````
273276

274277
This will cause the documentation generator to ensure the rule does emit
275278
exactly one diagnostic for this code, and to include a snapshot for the
276279
diagnostic in the resulting documentation page.
277280

281+
### Testing the Rule
282+
283+
#### Quick Test
284+
285+
To quickly test your rule, head to the `pg_analyser/src/lib.rs` file and modify the `debug_test` function.
286+
287+
You should:
288+
289+
- remove the `#[ignore]` macro if present
290+
- change the content of the `SQL` static `&str` to whatever you need
291+
- pass your group and rule to the `RuleFilter::Rule(..)`
292+
293+
If you run the test, you'll see any diagnostics your rule created in your console.
294+
278295
### Code generation
279296

280297
For simplicity, use `just` to run all the commands with:
@@ -294,15 +311,14 @@ Stage and commit your changes:
294311
> git commit -m 'feat(pg_analyser): myRuleName'
295312
```
296313

297-
298314
### Deprecate a rule
299315

300316
There are occasions when a rule must be deprecated, to avoid breaking changes. The reason
301317
of deprecation can be multiple.
302318

303319
In order to do, the macro allows adding additional field to add the reason for deprecation
304320

305-
```rust
321+
````rust
306322
use pg_analyse::declare_lint_rule;
307323

308324
declare_lint_rule! {
@@ -328,5 +344,4 @@ declare_lint_rule! {
328344
sources: &[RuleSource::Squawk("ban-drop-column")],
329345
}
330346
}
331-
```
332-
347+
````

crates/pg_analyser/Cargo.toml

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,3 +16,8 @@ pg_analyse = { workspace = true }
1616
pg_console = { workspace = true }
1717
pg_query_ext = { workspace = true }
1818
serde = { workspace = true }
19+
20+
[dev-dependencies]
21+
termcolor = { workspace = true }
22+
pg_query = { workspace = true}
23+
pg_diagnostics = { workspace = true}

crates/pg_analyser/src/lib.rs

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,3 +65,61 @@ impl<'a> Analyser<'a> {
6565
.collect::<Vec<_>>()
6666
}
6767
}
68+
69+
#[cfg(test)]
70+
mod tests {
71+
use core::slice;
72+
73+
use pg_analyse::{AnalyserOptions, AnalysisFilter, RuleFilter};
74+
use pg_console::{
75+
fmt::{Formatter, Termcolor},
76+
markup, Markup,
77+
};
78+
use pg_diagnostics::PrintDiagnostic;
79+
use termcolor::NoColor;
80+
81+
use crate::Analyser;
82+
83+
#[ignore]
84+
#[test]
85+
fn debug_test() {
86+
fn markup_to_string(markup: Markup) -> String {
87+
let mut buffer = Vec::new();
88+
let mut write = Termcolor(NoColor::new(&mut buffer));
89+
let mut fmt = Formatter::new(&mut write);
90+
fmt.write_markup(markup).unwrap();
91+
92+
String::from_utf8(buffer).unwrap()
93+
}
94+
95+
const SQL: &str = r#"alter table test drop column id;"#;
96+
let rule_filter = RuleFilter::Rule("safety", "banDropColumn");
97+
98+
let filter = AnalysisFilter {
99+
enabled_rules: Some(slice::from_ref(&rule_filter)),
100+
..Default::default()
101+
};
102+
103+
let ast = pg_query_ext::parse(SQL).expect("failed to parse SQL");
104+
105+
let options = AnalyserOptions::default();
106+
107+
let analyser = Analyser::new(crate::AnalyserConfig {
108+
options: &options,
109+
filter,
110+
});
111+
112+
let results = analyser.run(crate::AnalyserContext { root: &ast });
113+
114+
println!("*******************");
115+
for result in &results {
116+
let text = markup_to_string(markup! {
117+
{PrintDiagnostic::simple(result)}
118+
});
119+
eprintln!("{}", text);
120+
}
121+
println!("*******************");
122+
123+
// assert_eq!(results, vec![]);
124+
}
125+
}

crates/pg_diagnostics/src/advice.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -195,7 +195,7 @@ where
195195
}
196196
}
197197

198-
#[derive(Debug)]
198+
#[derive(Debug, PartialEq)]
199199
/// Utility type implementing [Advices] that emits a
200200
/// code suggestion with the provided text
201201
pub struct CodeSuggestionAdvice<M> {

crates/pg_diagnostics/src/display/message.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ use termcolor::NoColor;
1818
/// message: MessageAndDescription
1919
/// }
2020
/// ```
21-
#[derive(Clone, Deserialize, Serialize)]
21+
#[derive(Clone, Deserialize, Serialize, PartialEq)]
2222
pub struct MessageAndDescription {
2323
/// Shown when medium supports custom markup
2424
message: MarkupBuf,

0 commit comments

Comments
 (0)