Debian Codegraph @

src/widgets/process_table/query.rs

raw symbols SCIP
1 //! How we query processes.
2 //!
3 //! Yes, this is a hand-rolled parser. I originally wrote this back in uni where
4 //! writing a parser was basically a thing I did every year, and parsing crate
5 //! options were not as good as they are now. This will be rewritten as time
6 //! goes on, though.
7
8 mod and;
9 mod attribute;
10 mod error;
11 mod or;
12 mod prefix;
13
14 use std::{collections::VecDeque, time::Duration};
15
16 use and::And;
17 use attribute::ProcessAttribute;
18 use error::{QueryError, QueryResult};
19 use or::Or;
20 use prefix::Prefix;
21 use regex::Regex;
22
23 use crate::{collection::processes::ProcessHarvest, multi_eq_ignore_ascii_case};
24
25 const DELIMITER_LIST: [char; 7] = ['=', '>', '<', '!', '(', ')', '\"'];
26 const COMPARISON_LIST: [&str; 4] = [">", "=", "<", "!="];
27
28 /// A node type that can take a query and read it, advancing the current read
29 /// state and returning an instance of the node.
30 trait QueryProcessor {
31 fn process(query: &mut VecDeque<String>, regex_options: &QueryOptions) -> QueryResult<Self>
32 where
33 Self: Sized;
34 }
35
36 /// Process a new regex given a `base` string and some settings.
37 ///
38 /// TODO: Push this into a struct so I don't have to throw the options around so
39 /// much.
40 fn new_regex(base: &str, regex_options: &QueryOptions) -> QueryResult<Regex> {
41 let QueryOptions {
42 whole_word: is_searching_whole_word,
43 ignore_case: is_ignoring_case,
44 use_regex: is_searching_with_regex,
45 } = regex_options;
46 let escaped_regex: String; // Needed for ownership reasons.
47
48 let final_regex_string = &format!(
49 "{}{}{}{}",
50 if *is_searching_whole_word { "^" } else { "" },
51 if *is_ignoring_case { "(?i)" } else { "" },
52 if !(*is_searching_with_regex) {
53 escaped_regex = regex::escape(base);
54 &escaped_regex
55 } else {
56 base
57 },
58 if *is_searching_whole_word { "$" } else { "" },
59 );
60
61 Ok(Regex::new(final_regex_string)?)
62 }
63
64 /// Options when creating a new query.
65 #[derive(PartialEq, Eq)]
66 pub struct QueryOptions {
67 /// Whether we only allow matches on the entire word.
68 pub whole_word: bool,
69
70 /// Whether to ignore case-sensitivity when searching. On by default.
71 pub ignore_case: bool,
72
73 /// Whether we should use regex syntax when searching. If not set, then it
74 /// should treat everything as a literal string.
75 pub use_regex: bool,
76 }
77
78 impl Default for QueryOptions {
79 fn default() -> Self {
80 Self {
81 ignore_case: true,
82 whole_word: false,
83 use_regex: false,
84 }
85 }
86 }
87
88 /// In charge of parsing the given query, case-insensitive, possibly marked
89 /// by a prefix. For example:
90 ///
91 /// - Process names: No prefix required, can use regex, match word, or case.
92 /// Enclosing anything, including prefixes, in quotes, means we treat it as an
93 /// entire process rather than a prefix.
94 /// - PIDs: Use prefix `pid`, can use regex or match word.
95 /// - CPU: Use prefix `cpu`.
96 /// - MEM: Use prefix `mem`.
97 /// - STATE: Use prefix `state`.
98 /// - USER: Use prefix `user`.
99 /// - Read/s: Use prefix `r`.
100 /// - Write/s: Use prefix `w`.
101 /// - Total read: Use prefix `read`.
102 /// - Total write: Use prefix `write`.
103 ///
104 /// For queries, whitespaces are our delimiters. We will merge together any
105 /// adjacent non-prefixed or quoted elements after splitting to treat as process
106 /// names. Furthermore, we want to support boolean joiners like AND and OR, and
107 /// brackets.
108 pub(crate) fn parse_query(search_query: &str, options: &QueryOptions) -> QueryResult<ProcessQuery> {
109 fn process_string_to_filter(
110 query: &mut VecDeque<String>, options: &QueryOptions,
111 ) -> QueryResult<ProcessQuery> {
112 let lhs = Or::process(query, options)?;
113 let mut list_of_ors = vec![lhs];
114
115 while query.front().is_some() {
116 list_of_ors.push(Or::process(query, options)?);
117 }
118
119 Ok(ProcessQuery { query: list_of_ors })
120 }
121
122 let mut split_query = VecDeque::new();
123 let mut in_quotes = false;
124
125 search_query.split_whitespace().for_each(|s| {
126 // From https://stackoverflow.com/a/56923739 get a split but include the parentheses
127 let mut last = 0;
128 for (index, matched) in s.match_indices(|x| DELIMITER_LIST.contains(&x)) {
129 if matched == "\"" {
130 // Always split on quote delimiters to open/close quoted sections.
131 if last != index {
132 split_query.push_back(s[last..index].to_owned());
133 }
134 split_query.push_back(matched.to_owned());
135 last = index + matched.len();
136 in_quotes = !in_quotes;
137 } else if !in_quotes {
138 // Only split on other delimiters when outside a quoted section,
139 // so that special chars like `<` and `>` in `"Thread<15>"` are
140 // preserved as literals.
141 if last != index {
142 split_query.push_back(s[last..index].to_owned());
143 }
144 split_query.push_back(matched.to_owned());
145 last = index + matched.len();
146 }
147 }
148 if last < s.len() {
149 split_query.push_back(s[last..].to_owned());
150 }
151 });
152
153 // Merge adjacent "!" and "=" tokens into a single "!=" token.
154 let mut i = 0;
155 while i + 1 < split_query.len() {
156 if split_query[i] == "!" && split_query[i + 1] == "=" {
157 split_query[i] = "!=".to_owned();
158 split_query.remove(i + 1);
159 }
160 i += 1;
161 }
162
163 process_string_to_filter(&mut split_query, options)
164 }
165
166 #[derive(Debug)]
167 pub struct ProcessQuery {
168 /// Remember, AND > OR, but AND must come after OR when we parse.
169 query: Vec<Or>,
170 }
171
172 impl ProcessQuery {
173 pub(crate) fn check(&self, process: &ProcessHarvest, is_using_command: bool) -> bool {
174 self.query
175 .iter()
176 .all(|ok| ok.check(process, is_using_command))
177 }
178 }
179
180 #[derive(Debug)]
181 enum PrefixType {
182 Pid,
183 CpuPercentage,
184 MemBytes,
185 MemPercentage,
186 ReadPerSecond,
187 WritePerSecond,
188 TotalRead,
189 TotalWrite,
190 Name,
191 State,
192 User,
193 Time,
194 #[cfg(unix)]
195 Nice,
196 Priority,
197 #[cfg(feature = "gpu")]
198 GpuPercentage,
199 #[cfg(feature = "gpu")]
200 GpuMemoryBytes,
201 #[cfg(feature = "gpu")]
202 GpuMemoryPercentage,
203 }
204
205 impl std::str::FromStr for PrefixType {
206 type Err = QueryError;
207
208 fn from_str(s: &str) -> QueryResult<Self> {
209 use PrefixType::*;
210
211 // TODO: Didn't add mem_bytes, total_read, and total_write
212 // for now as it causes help to be clogged.
213
214 // TODO: Add a `name` keyword alias so something like `name = blah` is valid.
215
216 let mut result = Name;
217 if multi_eq_ignore_ascii_case!(s, "cpu" | "cpu%") {
218 result = CpuPercentage;
219 } else if multi_eq_ignore_ascii_case!(s, "mem" | "mem%") {
220 result = MemPercentage;
221 } else if multi_eq_ignore_ascii_case!(s, "memb") {
222 result = MemBytes;
223 } else if multi_eq_ignore_ascii_case!(s, "read" | "r/s" | "rps") {
224 result = ReadPerSecond;
225 } else if multi_eq_ignore_ascii_case!(s, "write" | "w/s" | "wps") {
226 result = WritePerSecond;
227 } else if multi_eq_ignore_ascii_case!(s, "tread" | "t.read") {
228 result = TotalRead;
229 } else if multi_eq_ignore_ascii_case!(s, "twrite" | "t.write") {
230 result = TotalWrite;
231 } else if multi_eq_ignore_ascii_case!(s, "pid") {
232 result = Pid;
233 } else if multi_eq_ignore_ascii_case!(s, "state") {
234 result = State;
235 } else if multi_eq_ignore_ascii_case!(s, "user") {
236 result = User;
237 } else if multi_eq_ignore_ascii_case!(s, "time") {
238 result = Time;
239 } else if multi_eq_ignore_ascii_case!(s, "nice") {
240 #[cfg(unix)]
241 {
242 result = Nice;
243 }
244 } else if multi_eq_ignore_ascii_case!(s, "priority") {
245 result = Priority;
246 }
247 #[cfg(feature = "gpu")]
248 {
249 if multi_eq_ignore_ascii_case!(s, "gmem") {
250 result = GpuMemoryBytes;
251 } else if multi_eq_ignore_ascii_case!(s, "gmem%") {
252 result = GpuMemoryPercentage;
253 } else if multi_eq_ignore_ascii_case!(s, "gpu%") {
254 result = GpuPercentage;
255 }
256 }
257 Ok(result)
258 }
259 }
260
261 #[derive(Debug)]
262 enum QueryComparison {
263 Equal,
264 NotEqual,
265 Less,
266 Greater,
267 LessOrEqual,
268 GreaterOrEqual,
269 }
270
271 #[derive(Debug)]
272 struct NumericalQuery {
273 condition: QueryComparison,
274 value: f64,
275 }
276
277 impl NumericalQuery {
278 /// Compare `lhs` to the value in the query as `rhs`.
279 fn check<I: Into<f64>>(&self, lhs: I) -> bool {
280 let lhs: f64 = lhs.into();
281 let rhs: f64 = self.value;
282
283 match self.condition {
284 QueryComparison::Equal => (lhs - rhs).abs() < f64::EPSILON,
285 QueryComparison::NotEqual => (lhs - rhs).abs() >= f64::EPSILON,
286 QueryComparison::Less => lhs < rhs,
287 QueryComparison::Greater => lhs > rhs,
288 QueryComparison::LessOrEqual => lhs <= rhs,
289 QueryComparison::GreaterOrEqual => lhs >= rhs,
290 }
291 }
292 }
293
294 #[derive(Debug)]
295 struct TimeQuery {
296 condition: QueryComparison,
297 duration: Duration,
298 }
299
300 impl TimeQuery {
301 /// Compare `lhs` to the value in the query as `rhs`.
302 fn check(&self, lhs: Duration) -> bool {
303 let rhs = self.duration;
304
305 match self.condition {
306 QueryComparison::Equal => lhs == rhs,
307 QueryComparison::NotEqual => lhs != rhs,
308 QueryComparison::Less => lhs < rhs,
309 QueryComparison::Greater => lhs > rhs,
310 QueryComparison::LessOrEqual => lhs <= rhs,
311 QueryComparison::GreaterOrEqual => lhs >= rhs,
312 }
313 }
314 }
315
316 #[cfg(test)]
317 mod tests {
318 use super::*;
319
320 fn simple_process(name: &str) -> ProcessHarvest {
321 ProcessHarvest {
322 name: name.into(),
323 ..Default::default()
324 }
325 }
326
327 fn parse_query_no_options(query: &str) -> QueryResult<ProcessQuery> {
328 parse_query(
329 query,
330 &QueryOptions {
331 whole_word: false,
332 ignore_case: false,
333 use_regex: false,
334 },
335 )
336 }
337
338 #[test]
339 fn basic_query() {
340 let query = parse_query_no_options("test").unwrap();
341
342 let exact_match = simple_process("test");
343 let contains = simple_process("test string");
344 let invalid = simple_process("no");
345
346 assert!(query.check(&exact_match, false));
347 assert!(query.check(&contains, false));
348 assert!(!query.check(&invalid, false));
349 }
350
351 #[test]
352 fn basic_or_query() {
353 let query = parse_query_no_options("a or b").unwrap();
354
355 let a = simple_process("a");
356 let b = simple_process("b");
357 let invalid = simple_process("c");
358
359 assert!(query.check(&a, false));
360 assert!(query.check(&b, false));
361 assert!(!query.check(&invalid, false));
362 }
363
364 #[test]
365 fn basic_and_query() {
366 let query = parse_query_no_options("a and b").unwrap();
367
368 let a = simple_process("a");
369 let b = simple_process("b");
370 let c = simple_process("c");
371 let a_and_b = simple_process("a and b");
372
373 assert!(!query.check(&a, false));
374 assert!(!query.check(&b, false));
375 assert!(!query.check(&c, false));
376 assert!(query.check(&a_and_b, false));
377 }
378
379 #[test]
380 fn implied_and_query() {
381 let query = parse_query_no_options("a b c").unwrap();
382
383 let a = simple_process("a");
384 let b = simple_process("b");
385 let c = simple_process("c");
386 let all = simple_process("a b c");
387
388 assert!(!query.check(&a, false));
389 assert!(!query.check(&b, false));
390 assert!(!query.check(&c, false));
391 assert!(query.check(&all, false));
392 }
393
394 /// Ensure that quoted keywords are treated as strings. In this case, rather
395 /// than `"a" OR "b"`, it should be treated as the string `"a or b"`.
396 #[test]
397 fn quoted_query() {
398 let query = parse_query_no_options("a \"or\" b").unwrap();
399
400 let a = simple_process("a");
401 let b = simple_process("b");
402 let or = simple_process("or");
403 let valid = simple_process("a \"or\" b"); // This is valid as the query is "match a word with a, or, and b".
404 let valid_2 = simple_process("a or b");
405 let valid_3 = simple_process("a \"or\" b \"or\" c");
406
407 assert!(!query.check(&a, false));
408 assert!(!query.check(&b, false));
409 assert!(!query.check(&or, false));
410 assert!(query.check(&valid, false));
411 assert!(query.check(&valid_2, false));
412 assert!(query.check(&valid_3, false));
413 }
414
415 /// Ensure that multi-word quoted keywords are treated as strings. In this
416 /// case, rather than `"a" OR "b"`, it should be treated as the string
417 /// `"a or b"`.
418 #[test]
419 fn quoted_multi_word_query() {
420 let query = parse_query_no_options("\"a or b\"").unwrap();
421
422 let a = simple_process("a");
423 let b = simple_process("b");
424 let or = simple_process("or");
425 let valid = simple_process("a or b");
426 let valid_2 = simple_process("a or b \"or\" c");
427 let invalid_no_regex = simple_process("a \"or\" b"); // Invalid now as the query is one big string!
428
429 assert!(!query.check(&a, false));
430 assert!(!query.check(&b, false));
431 assert!(!query.check(&or, false));
432 assert!(query.check(&valid, false));
433 assert!(query.check(&valid_2, false));
434 assert!(!query.check(&invalid_no_regex, false));
435 }
436
437 #[test]
438 fn basic_cpu_query() {
439 let query = parse_query_no_options("cpu > 50").unwrap();
440
441 let mut over = simple_process("a");
442 over.cpu_usage_percent = 60.0;
443
444 let mut under = simple_process("a");
445 under.cpu_usage_percent = 40.0;
446
447 let mut exact = simple_process("a");
448 exact.cpu_usage_percent = 50.0;
449
450 assert!(query.check(&over, false));
451 assert!(!query.check(&under, false));
452 assert!(!query.check(&exact, false));
453 }
454
455 #[test]
456 fn basic_mem_query() {
457 let query = parse_query_no_options("memb > 1 GiB").unwrap();
458
459 let mut over = simple_process("a");
460 over.mem_usage = 2 * 1024 * 1024 * 1024;
461
462 let mut under = simple_process("a");
463 under.mem_usage = 0;
464
465 let mut exact = simple_process("a");
466 exact.mem_usage = 1024 * 1024 * 1024;
467
468 assert!(query.check(&over, false));
469 assert!(!query.check(&under, false));
470 assert!(!query.check(&exact, false));
471 }
472
473 /// This test sees if parentheses work.
474 #[test]
475 fn nested_query_1() {
476 let query = parse_query_no_options("(a or b) and (c or a)").unwrap();
477
478 let a = simple_process("a");
479 let b = simple_process("b");
480 let c = simple_process("c");
481 let d = simple_process("d");
482
483 assert!(query.check(&a, false));
484 assert!(!query.check(&b, false));
485 assert!(!query.check(&c, false));
486 assert!(!query.check(&d, false));
487 }
488
489 /// This test sees if parentheses and mixed query types work.
490 #[test]
491 fn nested_query_2() {
492 let query = parse_query_no_options("(cpu > 10 or cpu < 5) and (c or a)").unwrap();
493
494 let mut a_valid_1 = simple_process("a");
495 a_valid_1.cpu_usage_percent = 100.0;
496
497 let mut a_valid_2 = simple_process("a");
498 a_valid_2.cpu_usage_percent = 1.0;
499
500 let mut a_invalid = simple_process("a");
501 a_invalid.cpu_usage_percent = 6.0;
502
503 let mut c = simple_process("c");
504 c.cpu_usage_percent = 50.0;
505
506 let mut b = simple_process("b");
507 b.cpu_usage_percent = 50.0;
508
509 let mut d = simple_process("d");
510 d.cpu_usage_percent = 6.0;
511
512 assert!(query.check(&a_valid_1, false));
513 assert!(query.check(&a_valid_2, false));
514 assert!(query.check(&c, false));
515
516 assert!(!query.check(&a_invalid, false));
517 assert!(!query.check(&b, false));
518 assert!(!query.check(&d, false));
519 }
520
521 /// This test adds a further layer of nesting to consider.
522 #[test]
523 fn nested_query_3() {
524 let query =
525 parse_query_no_options("((cpu > 10 or cpu < 5) or d) and ((c or a) or d)").unwrap();
526
527 let mut a_valid_1 = simple_process("a");
528 a_valid_1.cpu_usage_percent = 100.0;
529
530 let mut a_valid_2 = simple_process("a");
531 a_valid_2.cpu_usage_percent = 1.0;
532
533 let mut a_invalid = simple_process("a");
534 a_invalid.cpu_usage_percent = 6.0;
535
536 let mut c = simple_process("c");
537 c.cpu_usage_percent = 50.0;
538
539 let mut b = simple_process("b");
540 b.cpu_usage_percent = 50.0;
541
542 let mut d = simple_process("d");
543 d.cpu_usage_percent = 6.0;
544
545 assert!(query.check(&a_valid_1, false));
546 assert!(query.check(&a_valid_2, false));
547 assert!(query.check(&c, false));
548 assert!(query.check(&d, false));
549
550 assert!(!query.check(&a_invalid, false));
551 assert!(!query.check(&b, false));
552 }
553
554 #[test]
555 fn ambiguous_precedence_1() {
556 let query = parse_query_no_options("a and b or c").unwrap();
557
558 let a = simple_process("a");
559 let b = simple_process("b");
560 let c = simple_process("c");
561
562 assert!(!query.check(&a, false));
563 assert!(!query.check(&b, false));
564 assert!(query.check(&c, false));
565 }
566
567 #[test]
568 fn ambiguous_precedence_2() {
569 let query = parse_query_no_options("a or b and c").unwrap();
570
571 let a = simple_process("a");
572 let b = simple_process("b");
573 let c = simple_process("c");
574
575 assert!(query.check(&a, false));
576 assert!(!query.check(&b, false));
577 assert!(!query.check(&c, false));
578 }
579
580 /// Test if a complicated query even parses.
581 #[test]
582 fn parse_complicated_query() {
583 parse_query_no_options(
584 "cpu > 10.5 AND (memb = 1 MiB || state = sleeping) and (a or b) and (read >= 0 or write >= 0)",
585
586 )
587 .unwrap();
588 }
589
590 /// Test empty quotes works.
591 #[test]
592 fn parse_empty_quotes() {
593 parse_query_no_options("\"\"").unwrap();
594 parse_query_no_options("\"\"\"\"").unwrap();
595 parse_query_no_options("\"\" OR \"\"").unwrap();
596 }
597
598 #[test]
599 fn search_empty_quotes() {
600 let a = parse_query_no_options("\"\"").unwrap();
601 let b = parse_query_no_options("\"\" OR test").unwrap();
602
603 let process = simple_process("test");
604
605 assert!(a.check(&process, false));
606 assert!(b.check(&process, false));
607 }
608
609 /// Test unfinished quotes error.
610 #[test]
611 fn parse_unfinished_quotes() {
612 parse_query_no_options("\"").unwrap_err();
613 parse_query_no_options("\"asdf").unwrap_err();
614 parse_query_no_options("asdf\"").unwrap_err();
615 }
616
617 /// Test a fix for a bug with closing quotations. The problem seems to arise
618 /// from quotes being used as an argument to a prefix... but this should
619 /// probably be valid.
620 #[test]
621 fn parse_nested_closing_quotes() {
622 parse_query_no_options("state = \"test\"").unwrap();
623 parse_query_no_options("state = \"2 words\"").unwrap();
624 parse_query_no_options("(memb = 1 MiB || state = \"test\")").unwrap();
625 parse_query_no_options("(memb = 1 MiB || state = \"2 words\")").unwrap();
626 }
627
628 // TODO: Add this after fixed.
629 // /// Test if units can ignore spaces from their preceding value.
630 // #[test]
631 // fn units_with_and_without_spaces() {}
632
633 #[test]
634 fn invalid_uncompleted_queries_1() {
635 parse_query_no_options("state =").unwrap_err();
636 parse_query_no_options("a or").unwrap_err();
637 parse_query_no_options("a >").unwrap_err();
638 }
639
640 #[track_caller]
641 fn invalid_lhs_rhs(op: &str) {
642 parse_query_no_options(&format!("a {op} asdf = 100")).unwrap_err();
643 parse_query_no_options(&format!("asdf = 100 {op} b")).unwrap_err();
644 parse_query_no_options(&format!("a {op} asdf = 100 {op} b")).unwrap_err();
645
646 parse_query_no_options(&format!("asdf = 100 {op} bsdf = \"")).unwrap_err();
647 parse_query_no_options(&format!("a {op} bsdf = \"")).unwrap_err();
648 }
649
650 #[test]
651 fn invalid_or() {
652 invalid_lhs_rhs("OR");
653 invalid_lhs_rhs("||");
654 }
655
656 #[test]
657 fn invalid_and() {
658 invalid_lhs_rhs("AND");
659 invalid_lhs_rhs("&&");
660 invalid_lhs_rhs("");
661 }
662
663 // /// Test keywords.
664 // ///
665 // /// TODO: Should these be invalid...?
666 // #[test]
667 // fn invalid_query_x() {
668 // parse_query_no_options("or").unwrap_err();
669 // parse_query_no_options("and").unwrap_err();
670 // parse_query_no_options("a or >").unwrap_err();
671 // parse_query_no_options("a and >").unwrap_err();
672 // }
673
674 #[test]
675 fn test_command_check() {
676 let query = parse_query_no_options("command").unwrap();
677
678 let mut process_a = simple_process("test");
679 process_a.command = "command".into();
680
681 let mut process_b = simple_process("test");
682 process_b.command = "no".into();
683
684 assert!(query.check(&process_a, true));
685 assert!(!query.check(&process_b, true));
686 }
687
688 #[test]
689 fn test_non_ascii_only_1() {
690 let query = parse_query_no_options("食").unwrap();
691
692 let process_a = simple_process("施氏食獅史");
693 let process_b = simple_process("沒有");
694
695 assert!(query.check(&process_a, false));
696 assert!(!query.check(&process_b, false));
697 }
698
699 #[test]
700 fn test_non_ascii_only_2() {
701 let query = parse_query_no_options("परीक्षा").unwrap();
702
703 let process_a = simple_process("परीक्षा");
704 let process_b = simple_process("उपलब्ध नहीं है");
705
706 assert!(query.check(&process_a, false));
707 assert!(!query.check(&process_b, false));
708 }
709
710 #[test]
711 fn test_non_ascii_only_3() {
712 let query = parse_query_no_options("🇨🇦").unwrap();
713
714 let process_a = simple_process("🇨🇦");
715 let process_b = simple_process("❤️🇨🇦❤️");
716 let process_c = simple_process("❤️");
717
718 assert!(query.check(&process_a, false));
719 assert!(query.check(&process_b, false));
720 assert!(!query.check(&process_c, false));
721 }
722
723 #[test]
724 fn test_non_ascii_only_4() {
725 let query = parse_query_no_options("獅 or 狮").unwrap();
726
727 let process_a = simple_process("施氏食獅史");
728 let process_b = simple_process("施氏食狮史");
729 let process_c = simple_process("沒有");
730
731 assert!(query.check(&process_a, false));
732 assert!(query.check(&process_b, false));
733 assert!(!query.check(&process_c, false));
734 }
735
736 #[test]
737 fn test_invalid_non_ascii() {
738 parse_query_no_options("cpu = 食").unwrap_err();
739 }
740
741 #[test]
742 fn test_mixed_unicode() {
743 let query = parse_query_no_options("食 or test").unwrap();
744
745 let process_a = simple_process("施氏食獅史");
746 let process_b = simple_process("test");
747 let process_c = simple_process("施氏食獅史test");
748 let process_d = simple_process("沒有");
749 let process_e = simple_process("nope");
750
751 assert!(query.check(&process_a, false));
752 assert!(query.check(&process_b, false));
753 assert!(query.check(&process_c, false));
754 assert!(!query.check(&process_d, false));
755 assert!(!query.check(&process_e, false));
756 }
757
758 #[test]
759 fn test_regex_1() {
760 let query = parse_query(
761 "(a|b)",
762 &QueryOptions {
763 whole_word: false,
764 ignore_case: true,
765 use_regex: true,
766 },
767 )
768 .unwrap();
769
770 let process_a = simple_process("abc");
771 let process_b = simple_process("test");
772
773 assert!(query.check(&process_a, false));
774 assert!(!query.check(&process_b, false));
775 }
776
777 #[test]
778 fn test_regex_2() {
779 let query = parse_query(
780 "^a.*z$",
781 &QueryOptions {
782 whole_word: false,
783 ignore_case: true,
784 use_regex: true,
785 },
786 )
787 .unwrap();
788
789 let process_a = simple_process("atoz");
790 let process_b = simple_process("atob");
791 let process_c = simple_process("ytoz");
792 let process_d = simple_process("atozoops");
793
794 assert!(query.check(&process_a, false));
795 assert!(!query.check(&process_b, false));
796 assert!(!query.check(&process_c, false));
797 assert!(!query.check(&process_d, false));
798 }
799
800 #[test]
801 fn test_whole_word_1() {
802 let query = parse_query(
803 "test",
804 &QueryOptions {
805 whole_word: true,
806 ignore_case: true,
807 use_regex: false,
808 },
809 )
810 .unwrap();
811
812 let process_a = simple_process("test");
813 let process_b = simple_process("testa");
814 let process_c = simple_process("atest");
815
816 assert!(query.check(&process_a, false));
817 assert!(!query.check(&process_b, false));
818 assert!(!query.check(&process_c, false));
819 }
820
821 #[test]
822 fn test_case_sensitive_1() {
823 let query = parse_query(
824 "tEsT",
825 &QueryOptions {
826 whole_word: false,
827 ignore_case: false,
828 use_regex: false,
829 },
830 )
831 .unwrap();
832
833 let process_a = simple_process("tEsT");
834 let process_b = simple_process("tEsT a");
835 let process_c = simple_process("a tEsT");
836
837 assert!(query.check(&process_a, false));
838 assert!(query.check(&process_b, false));
839 assert!(query.check(&process_c, false));
840
841 let process_d = simple_process("test");
842 let process_e = simple_process("test a");
843 let process_f = simple_process("a test");
844
845 assert!(!query.check(&process_d, false));
846 assert!(!query.check(&process_e, false));
847 assert!(!query.check(&process_f, false));
848 }
849
850 #[cfg(feature = "gpu")]
851 #[test]
852 fn test_gpu_queries() {
853 let mem = parse_query_no_options("gmem > 50 b").unwrap();
854 let mem_percent = parse_query_no_options("gmem% = 50").unwrap();
855 let use_percent = parse_query_no_options("gpu% = 50").unwrap();
856
857 let mut process_a = simple_process("test");
858 process_a.gpu_mem = 100;
859 process_a.gpu_mem_percent = 50.0;
860 process_a.gpu_util = 50;
861
862 assert!(mem.check(&process_a, false));
863 assert!(mem_percent.check(&process_a, false));
864 assert!(use_percent.check(&process_a, false));
865
866 let mut process_b = simple_process("test");
867 process_b.gpu_mem = 0;
868 process_b.gpu_mem_percent = 10.0;
869 process_b.gpu_util = 10;
870
871 assert!(!mem.check(&process_b, false));
872 assert!(!mem_percent.check(&process_b, false));
873 assert!(!use_percent.check(&process_b, false));
874 }
875
876 /// Test GPU queries that involve invalid string comparisons.
877 #[cfg(feature = "gpu")]
878 #[test]
879 fn test_invalid_gpu_queries() {
880 parse_query_no_options("gmem = \"what\"").unwrap_err();
881 parse_query_no_options("gmem% = \"the\"").unwrap_err();
882 parse_query_no_options("gpu% = \"heck\"").unwrap_err();
883 }
884
885 // TODO: Test all attribute keywords (e.g. cpu, mem, etc.)
886 // #[test]
887 // fn test_all_attribute_keywords() {}
888
889 // TODO: Support 'bytes' or similar
890 // #[test]
891 // fn test_bytes_keyword() {
892 // let mem = parse_query_no_options("mem > 50 bytes").unwrap();
893 // let mut process_a = simple_process("test");
894 // process_a.mem_usage = 100;
895
896 // assert!(mem.check(&process_a, false));
897 // }
898
899 /// Basic numerical non-equality operator test.
900 #[test]
901 fn numerical_not_equal_query() {
902 let query = parse_query_no_options("cpu != 50").unwrap();
903
904 let mut equal = simple_process("a");
905 equal.cpu_usage_percent = 50.0;
906
907 let mut other = simple_process("a");
908 other.cpu_usage_percent = 40.0;
909
910 assert!(!query.check(&equal, false));
911 assert!(query.check(&other, false));
912 }
913
914 /// `!=` should tokenize the same whether written as `foo!=bar` or
915 /// `foo != bar`.
916 #[test]
917 fn not_equal_tokenizes_without_spaces() {
918 let spaced = parse_query_no_options("cpu != 50").unwrap();
919 let joined = parse_query_no_options("cpu!=50").unwrap();
920
921 let mut proc = simple_process("a");
922 proc.cpu_usage_percent = 40.0;
923
924 assert!(spaced.check(&proc, false));
925 assert!(joined.check(&proc, false));
926 }
927
928 /// Test the non-equality operator with time.
929 #[test]
930 fn time_not_equal_query() {
931 let query = parse_query_no_options("time != 1h").unwrap();
932
933 let mut equal = simple_process("a");
934 equal.time = Duration::from_secs(3600);
935
936 let mut other = simple_process("a");
937 other.time = Duration::from_secs(60);
938
939 assert!(!query.check(&equal, false));
940 assert!(query.check(&other, false));
941 }
942
943 /// Test state queries with the non-equality operator. This also tests that string comparisons.
944 #[test]
945 fn state_not_equal_query() {
946 let query = parse_query_no_options("state != sleeping").unwrap();
947
948 let mut sleeping = simple_process("a");
949 sleeping.process_state.0 = "sleeping";
950
951 let mut running = simple_process("a");
952 running.process_state.0 = "running";
953
954 assert!(!query.check(&sleeping, false));
955 assert!(query.check(&running, false));
956 }
957
958 /// Test byte unit searches work with the non-equality operator.
959 #[test]
960 fn mem_bytes_not_equal_with_unit() {
961 let query = parse_query_no_options("memb != 1 GiB").unwrap();
962
963 let mut equal = simple_process("a");
964 equal.mem_usage = 1024 * 1024 * 1024;
965
966 let mut other = simple_process("a");
967 other.mem_usage = 0;
968
969 assert!(!query.check(&equal, false));
970 assert!(query.check(&other, false));
971 }
972
973 /// `!(...)` negates a whole group.
974 #[test]
975 fn negate_group_query() {
976 let query = parse_query_no_options("!(cpu > 5 or a)").unwrap();
977
978 let mut high_cpu = simple_process("b");
979 high_cpu.cpu_usage_percent = 10.0;
980
981 let name_match = simple_process("a");
982
983 let mut low_cpu_no_match = simple_process("b");
984 low_cpu_no_match.cpu_usage_percent = 1.0;
985
986 assert!(!query.check(&high_cpu, false));
987 assert!(!query.check(&name_match, false));
988 assert!(query.check(&low_cpu_no_match, false));
989 }
990
991 /// `!name` negates a bare-name match.
992 #[test]
993 fn negate_bare_name_query() {
994 let query = parse_query_no_options("!firefox").unwrap();
995
996 let firefox = simple_process("firefox");
997 let other = simple_process("btm");
998
999 assert!(!query.check(&firefox, false));
1000 assert!(query.check(&other, false));
1001 }
1002
1003 /// `!"..."` negates a quoted-name match.
1004 #[test]
1005 fn negate_quoted_name_query() {
1006 let query = parse_query_no_options("!\"a or b\"").unwrap();
1007
1008 let exact = simple_process("a or b");
1009 let other = simple_process("c");
1010
1011 assert!(!query.check(&exact, false));
1012 assert!(query.check(&other, false));
1013 }
1014
1015 /// `!!x` is double negation, which should behave like `x`.
1016 #[test]
1017 fn double_negate_query_a() {
1018 let query = parse_query_no_options("!!firefox").unwrap();
1019
1020 let firefox = simple_process("firefox");
1021 let other = simple_process("btm");
1022
1023 assert!(query.check(&firefox, false));
1024 assert!(!query.check(&other, false));
1025 }
1026
1027 /// `!!(cpu > 5)` is double negation, which should behave like `cpu > 5`.
1028 #[test]
1029 fn double_negate_query_b() {
1030 let query = parse_query_no_options("!!(cpu > 5) ").unwrap();
1031
1032 let mut big = simple_process("big");
1033 big.cpu_usage_percent = 10.0;
1034 let mut small = simple_process("small");
1035 small.cpu_usage_percent = 1.0;
1036
1037 assert!(query.check(&big, false));
1038 assert!(!query.check(&small, false));
1039 }
1040
1041 /// `!` composes with `and`/`or`.
1042 #[test]
1043 fn negate_with_boolean_operators() {
1044 let query = parse_query_no_options("!firefox and cpu > 5").unwrap();
1045
1046 let mut firefox = simple_process("firefox");
1047 firefox.cpu_usage_percent = 10.0;
1048
1049 let mut other_high = simple_process("btm");
1050 other_high.cpu_usage_percent = 10.0;
1051
1052 let mut other_low = simple_process("btm");
1053 other_low.cpu_usage_percent = 1.0;
1054
1055 assert!(!query.check(&firefox, false));
1056 assert!(query.check(&other_high, false));
1057 assert!(!query.check(&other_low, false));
1058 }
1059
1060 /// A bare `!` with nothing parseable after it must be rejected so that it
1061 /// doesn't silently become `name = "!"`. The literal form `"!"` still
1062 /// works.
1063 #[test]
1064 fn lone_bang_is_rejected() {
1065 parse_query_no_options("!").unwrap_err();
1066 parse_query_no_options("! ").unwrap_err();
1067 parse_query_no_options("!)").unwrap_err();
1068 parse_query_no_options("(!)").unwrap_err();
1069 }
1070
1071 /// A quoted `"!"` as the RHS of a prefixed string query should match the
1072 /// literal `!`, not be treated as an operator.
1073 #[test]
1074 fn user_equals_quoted_bang() {
1075 let query = parse_query_no_options("user = \"!\"").unwrap();
1076
1077 let mut with_bang = simple_process("a");
1078 with_bang.user = Some("!".into());
1079
1080 let mut other = simple_process("a");
1081 other.user = Some("root".into());
1082
1083 assert!(query.check(&with_bang, false));
1084 assert!(!query.check(&other, false));
1085 }
1086
1087 /// A quoted `"!"` as the RHS of a prefixed string query with "!=" should not match the
1088 /// literal `!`, nor should it be treated as an operator.
1089 #[test]
1090 fn user_negated_equals_quoted_bang() {
1091 let query = parse_query_no_options("user != \"!\"").unwrap();
1092
1093 let mut with_bang = simple_process("a");
1094 with_bang.user = Some("!".into());
1095
1096 let mut other = simple_process("a");
1097 other.user = Some("root".into());
1098
1099 assert!(!query.check(&with_bang, false));
1100 assert!(query.check(&other, false));
1101 }
1102
1103 /// A quoted `"!"` should remain a valid literal-name match.
1104 #[test]
1105 fn quoted_bang_matches_literal() {
1106 let query = parse_query_no_options("\"!\"").unwrap();
1107
1108 let with_bang = simple_process("foo!");
1109 let without = simple_process("foo");
1110
1111 assert!(query.check(&with_bang, false));
1112 assert!(!query.check(&without, false));
1113 }
1114
1115 /// Quoted angle brackets should be treated as literal characters in name matches.
1116 #[test]
1117 fn quoted_angle_brackets_match_literal() {
1118 let query = parse_query_no_options("\"Thread<15>\"").unwrap();
1119
1120 let matching = simple_process("Thread<15>");
1121 let non_matching = simple_process("Thread");
1122
1123 assert!(query.check(&matching, false));
1124 assert!(!query.check(&non_matching, false));
1125 }
1126
1127 /// A quoted `=` should be treated as a literal character in name matches.
1128 #[test]
1129 fn quoted_equals_matches_literal() {
1130 let query = parse_query_no_options("\"a=b\"").unwrap();
1131
1132 let matching = simple_process("a=b");
1133 let non_matching = simple_process("ab");
1134
1135 assert!(query.check(&matching, false));
1136 assert!(!query.check(&non_matching, false));
1137 }
1138
1139 /// A quoted `!=` should be treated as a literal character sequence in name matches.
1140 #[test]
1141 fn quoted_not_equals_matches_literal() {
1142 let query = parse_query_no_options("\"a!=b\"").unwrap();
1143
1144 let matching = simple_process("a!=b");
1145 let non_matching = simple_process("ab");
1146
1147 assert!(query.check(&matching, false));
1148 assert!(!query.check(&non_matching, false));
1149 }
1150
1151 /// Quoted parentheses should be treated as literal characters in name matches.
1152 #[test]
1153 fn quoted_parens_match_literal() {
1154 let query = parse_query_no_options("\"a(b)\"").unwrap();
1155
1156 let matching = simple_process("a(b)");
1157 let non_matching = simple_process("ab");
1158
1159 assert!(query.check(&matching, false));
1160 assert!(!query.check(&non_matching, false));
1161 }
1162
1163 /// Trailing operators with no RHS must error.
1164 #[test]
1165 fn not_equal_missing_value_is_rejected() {
1166 parse_query_no_options("user !=").unwrap_err();
1167 parse_query_no_options("state !=").unwrap_err();
1168 parse_query_no_options("time !=").unwrap_err();
1169 }
1170
1171 /// Some miscellaneous invalid string searches involving negation (`!`) parsing.
1172 #[test]
1173 fn misc_invalid_bang_search() {
1174 parse_query_no_options("user = !").unwrap_err();
1175 parse_query_no_options("user != !").unwrap_err();
1176 parse_query_no_options("pid = !").unwrap_err();
1177 parse_query_no_options("state !").unwrap_err();
1178 parse_query_no_options("!cpu > 5").unwrap_err();
1179 parse_query_no_options("! cpu > 5").unwrap_err();
1180 }
1181
1182 /// `=!` is not a valid operator.
1183 #[test]
1184 fn reversed_bang_equal_is_rejected() {
1185 parse_query_no_options("cpu =!").unwrap_err();
1186 parse_query_no_options("cpu = !").unwrap_err();
1187 parse_query_no_options("cpu = ! 5").unwrap_err();
1188 }
1189
1190 /// `!=` with a non-numeric RHS should fail.
1191 #[test]
1192 fn not_equal_non_numeric_rhs_is_rejected() {
1193 parse_query_no_options("cpu != abc").unwrap_err();
1194 }
1195 }