filtration 2.3.2__tar.gz → 2.3.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,22 +1,24 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: filtration
3
- Version: 2.3.2
3
+ Version: 2.3.3
4
4
  Summary: filtration - A library for parsing arbitrary filters
5
- Author: Steve McMaster
6
- Author-email: mcmaster@hurricanelabs.com
5
+ Author-email: Steve McMaster <mcmaster@hurricanelabs.com>
6
+ License-Expression: MIT
7
7
  Project-URL: Bug Tracker, https://github.com/HurricaneLabs/filtration/issues
8
- Classifier: License :: OSI Approved :: MIT License
9
- Classifier: Programming Language :: Python :: 3
10
8
  Classifier: Development Status :: 5 - Production/Stable
11
- Requires-Dist: pyparsing>=3.0.0
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Programming Language :: Python :: 3 :: Only
11
+ Classifier: Programming Language :: Python :: 3.9
12
+ Classifier: Programming Language :: Python :: 3.10
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Classifier: Programming Language :: Python :: 3.14
17
+ Requires-Python: >=3.9
18
+ Description-Content-Type: text/x-rst
19
+ Requires-Dist: pyparsing>=3.0.1
12
20
  Requires-Dist: ipcalc
13
- Dynamic: author
14
- Dynamic: author-email
15
- Dynamic: classifier
16
- Dynamic: description
17
- Dynamic: project-url
18
- Dynamic: requires-dist
19
- Dynamic: summary
21
+ Requires-Dist: six
20
22
 
21
23
  ##########
22
24
  Filtration
@@ -38,13 +40,13 @@ Get Filtration
38
40
 
39
41
  Run the tests
40
42
  =============
41
- You must install nose2, then run:
43
+ With `uv <https://docs.astral.sh/uv/>`_ installed, run:
42
44
 
43
45
  .. code-block:: shell
44
46
 
45
47
  git clone https://github.com/HurricaneLabs/filtration.git
46
48
  cd filtration
47
- nose2
49
+ uv run pytest
48
50
 
49
51
  ########
50
52
  Usage
@@ -18,13 +18,13 @@ Get Filtration
18
18
 
19
19
  Run the tests
20
20
  =============
21
- You must install nose2, then run:
21
+ With `uv <https://docs.astral.sh/uv/>`_ installed, run:
22
22
 
23
23
  .. code-block:: shell
24
24
 
25
25
  git clone https://github.com/HurricaneLabs/filtration.git
26
26
  cd filtration
27
- nose2
27
+ uv run pytest
28
28
 
29
29
  ########
30
30
  Usage
@@ -4,17 +4,34 @@ import re
4
4
  from functools import reduce
5
5
 
6
6
  import ipcalc
7
- from pyparsing import alphas, nums
8
- from pyparsing import CaselessLiteral, Combine, Group, Keyword, Literal, MatchFirst, OneOrMore
9
- from pyparsing import infix_notation, OpAssoc, Optional, ParseException, quoted_string
10
- from pyparsing import QuotedString, remove_quotes, Suppress, Word, ZeroOrMore
7
+ from pyparsing import (
8
+ CaselessLiteral,
9
+ Combine,
10
+ Group,
11
+ Keyword,
12
+ Literal,
13
+ MatchFirst,
14
+ OneOrMore,
15
+ OpAssoc,
16
+ Optional,
17
+ ParseException,
18
+ QuotedString,
19
+ Suppress,
20
+ Word,
21
+ ZeroOrMore,
22
+ alphas,
23
+ infix_notation,
24
+ nums,
25
+ quoted_string,
26
+ remove_quotes,
27
+ )
11
28
 
12
29
 
13
30
  class Token:
14
31
  def __init__(self, toks):
15
32
  compiler = getattr(self, "compiler", None)
16
33
  if callable(compiler):
17
- self.value = compiler(*toks) # pylint: disable=not-callable
34
+ self.value = compiler(*toks)
18
35
  else:
19
36
  try:
20
37
  self.value = toks[0]
@@ -22,7 +39,6 @@ class Token:
22
39
  self.value = toks
23
40
 
24
41
  def __call__(self, ctx):
25
- # pylint: disable=unused-argument
26
42
  return self.value
27
43
 
28
44
 
@@ -47,29 +63,25 @@ DateTime = (Date + Suppress(Optional("T")) + Time).set_parse_action(
47
63
 
48
64
  class _Regex(Token):
49
65
  def compiler(self, pattern, flags):
50
- # pylint: disable=no-self-use
51
66
  try:
52
67
  return re.compile(pattern, flags)
53
68
  except re.error as exc:
54
69
  raise ParseException(str(exc)) from exc
55
70
 
56
71
 
57
- RegexFlag = Word("ims", exact=1).set_parse_action(
58
- lambda toks: getattr(re, toks[0].upper())
59
- )
72
+ RegexFlag = Word("ims", exact=1).set_parse_action(lambda toks: getattr(re, toks[0].upper()))
60
73
  RegexFlags = ZeroOrMore(RegexFlag).set_parse_action(
61
74
  lambda toks: reduce(lambda a, b: a | b, toks, 0)
62
75
  )
63
76
  Regex = (QuotedString("/") + RegexFlags).set_parse_action(_Regex)
64
77
 
65
- Octet = Word(nums, max=3).addCondition(lambda toks: int(toks[0]) <= 255)
78
+ Octet = Word(nums, max=3).add_condition(lambda toks: int(toks[0]) <= 255)
66
79
  IpAddr = Combine(Octet + "." + Octet + "." + Octet + "." + Octet)
67
- Cidr = Word(nums, max=2).addCondition(lambda toks: int(toks[0]) <= 32)
80
+ Cidr = Word(nums, max=2).add_condition(lambda toks: int(toks[0]) <= 32)
68
81
 
69
82
 
70
83
  class _Subnet(Token):
71
84
  def compiler(self, subnet):
72
- # pylint: disable=no-self-use
73
85
  return ipcalc.Network(subnet)
74
86
 
75
87
 
@@ -94,16 +106,18 @@ class _Symbol(Token):
94
106
  return value
95
107
 
96
108
 
97
- Symbol = Word((alphas + "_"), bodyChars=(alphas + nums + "." + "_")).set_parse_action(_Symbol)
109
+ Symbol = Word((alphas + "_"), body_chars=(alphas + nums + "." + "_")).set_parse_action(_Symbol)
98
110
 
99
111
 
100
- Value = MatchFirst([
101
- DateTime,
102
- Date,
103
- Time,
104
- quoted_string.set_parse_action(remove_quotes),
105
- Word(nums).set_parse_action(lambda toks: int(toks[0])),
106
- ]).set_parse_action(Token)
112
+ Value = MatchFirst(
113
+ [
114
+ DateTime,
115
+ Date,
116
+ Time,
117
+ quoted_string.set_parse_action(remove_quotes),
118
+ Word(nums).set_parse_action(lambda toks: int(toks[0])),
119
+ ]
120
+ ).set_parse_action(Token)
107
121
 
108
122
 
109
123
  class _List(Token):
@@ -139,21 +153,22 @@ def re_op(lhs, rhs):
139
153
 
140
154
 
141
155
  # Operators
142
- ComparisonOp = MatchFirst([
143
- Literal("==").set_parse_action(lambda toks: operator.eq),
144
- Literal("!=").set_parse_action(lambda toks: operator.ne),
145
- Literal("<=").set_parse_action(lambda toks: operator.le),
146
- Literal("<").set_parse_action(lambda toks: operator.lt),
147
- Literal(">=").set_parse_action(lambda toks: operator.ge),
148
- Literal(">").set_parse_action(lambda toks: operator.gt),
149
- Keyword("in").set_parse_action(lambda toks: in_op),
150
- Literal("=~").set_parse_action(lambda toks: re_op),
151
- ])
156
+ ComparisonOp = MatchFirst(
157
+ [
158
+ Literal("==").set_parse_action(lambda toks: operator.eq),
159
+ Literal("!=").set_parse_action(lambda toks: operator.ne),
160
+ Literal("<=").set_parse_action(lambda toks: operator.le),
161
+ Literal("<").set_parse_action(lambda toks: operator.lt),
162
+ Literal(">=").set_parse_action(lambda toks: operator.ge),
163
+ Literal(">").set_parse_action(lambda toks: operator.gt),
164
+ Keyword("in").set_parse_action(lambda toks: in_op),
165
+ Literal("=~").set_parse_action(lambda toks: re_op),
166
+ ]
167
+ )
152
168
 
153
169
 
154
170
  class _Not(Token):
155
171
  def compiler(self, *toks):
156
- # pylint: disable=no-self-use
157
172
  return toks[0][1]
158
173
 
159
174
  def __call__(self, ctx):
@@ -162,7 +177,6 @@ class _Not(Token):
162
177
 
163
178
  class _And(Token):
164
179
  def compiler(self, *toks):
165
- # pylint: disable=no-self-use
166
180
  return toks[0][0::2]
167
181
 
168
182
  def __call__(self, ctx):
@@ -171,7 +185,6 @@ class _And(Token):
171
185
 
172
186
  class _Or(Token):
173
187
  def compiler(self, *toks):
174
- # pylint: disable=no-self-use
175
188
  return toks[0][0::2]
176
189
 
177
190
  def __call__(self, ctx):
@@ -191,7 +204,7 @@ RHS = Symbol | Subnet | List | Value | Regex
191
204
  class _Statement:
192
205
  def __init__(self, lhs, op=None, rhs=None):
193
206
  self.lhs = lhs
194
- self.op = op # pylint: disable=invalid-name
207
+ self.op = op
195
208
  self.rhs = rhs
196
209
 
197
210
  def __call__(self, ctx):
@@ -201,9 +214,7 @@ class _Statement:
201
214
  return self.op(self.lhs(ctx), self.rhs(ctx))
202
215
 
203
216
 
204
- Statement = (LHS + Optional(ComparisonOp + RHS)).set_parse_action(
205
- lambda toks: _Statement(*toks)
206
- )
217
+ Statement = (LHS + Optional(ComparisonOp + RHS)).set_parse_action(lambda toks: _Statement(*toks))
207
218
 
208
219
 
209
220
  class Expression:
@@ -1,22 +1,24 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: filtration
3
- Version: 2.3.2
3
+ Version: 2.3.3
4
4
  Summary: filtration - A library for parsing arbitrary filters
5
- Author: Steve McMaster
6
- Author-email: mcmaster@hurricanelabs.com
5
+ Author-email: Steve McMaster <mcmaster@hurricanelabs.com>
6
+ License-Expression: MIT
7
7
  Project-URL: Bug Tracker, https://github.com/HurricaneLabs/filtration/issues
8
- Classifier: License :: OSI Approved :: MIT License
9
- Classifier: Programming Language :: Python :: 3
10
8
  Classifier: Development Status :: 5 - Production/Stable
11
- Requires-Dist: pyparsing>=3.0.0
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Programming Language :: Python :: 3 :: Only
11
+ Classifier: Programming Language :: Python :: 3.9
12
+ Classifier: Programming Language :: Python :: 3.10
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Classifier: Programming Language :: Python :: 3.14
17
+ Requires-Python: >=3.9
18
+ Description-Content-Type: text/x-rst
19
+ Requires-Dist: pyparsing>=3.0.1
12
20
  Requires-Dist: ipcalc
13
- Dynamic: author
14
- Dynamic: author-email
15
- Dynamic: classifier
16
- Dynamic: description
17
- Dynamic: project-url
18
- Dynamic: requires-dist
19
- Dynamic: summary
21
+ Requires-Dist: six
20
22
 
21
23
  ##########
22
24
  Filtration
@@ -38,13 +40,13 @@ Get Filtration
38
40
 
39
41
  Run the tests
40
42
  =============
41
- You must install nose2, then run:
43
+ With `uv <https://docs.astral.sh/uv/>`_ installed, run:
42
44
 
43
45
  .. code-block:: shell
44
46
 
45
47
  git clone https://github.com/HurricaneLabs/filtration.git
46
48
  cd filtration
47
- nose2
49
+ uv run pytest
48
50
 
49
51
  ########
50
52
  Usage
@@ -1,5 +1,5 @@
1
1
  README.rst
2
- setup.py
2
+ pyproject.toml
3
3
  filtration/__init__.py
4
4
  filtration.egg-info/PKG-INFO
5
5
  filtration.egg-info/SOURCES.txt
@@ -0,0 +1,3 @@
1
+ pyparsing>=3.0.1
2
+ ipcalc
3
+ six
@@ -0,0 +1,66 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "filtration"
7
+ version = "2.3.3"
8
+ description = "filtration - A library for parsing arbitrary filters"
9
+ readme = "README.rst"
10
+ license = "MIT"
11
+ authors = [{ name = "Steve McMaster", email = "mcmaster@hurricanelabs.com" }]
12
+ requires-python = ">=3.9"
13
+ dependencies = [
14
+ # 3.0.0 can't parse subnets; 3.0.1 fixed it
15
+ "pyparsing>=3.0.1",
16
+ "ipcalc",
17
+ # ipcalc imports six without declaring it
18
+ "six",
19
+ ]
20
+ classifiers = [
21
+ "Development Status :: 5 - Production/Stable",
22
+ "Programming Language :: Python :: 3",
23
+ "Programming Language :: Python :: 3 :: Only",
24
+ "Programming Language :: Python :: 3.9",
25
+ "Programming Language :: Python :: 3.10",
26
+ "Programming Language :: Python :: 3.11",
27
+ "Programming Language :: Python :: 3.12",
28
+ "Programming Language :: Python :: 3.13",
29
+ "Programming Language :: Python :: 3.14",
30
+ ]
31
+
32
+ [project.urls]
33
+ "Bug Tracker" = "https://github.com/HurricaneLabs/filtration/issues"
34
+
35
+ [tool.setuptools]
36
+ packages = ["filtration"]
37
+
38
+ [dependency-groups]
39
+ dev = [
40
+ "pytest>=8",
41
+ "pytest-cov>=5",
42
+ # pinned so new ruff releases can't fail CI without a code change
43
+ "ruff==0.17.5",
44
+ ]
45
+
46
+ [tool.pytest.ini_options]
47
+ addopts = "--strict-markers -ra"
48
+ testpaths = ["tests"]
49
+ filterwarnings = ["error"]
50
+
51
+ [tool.coverage.run]
52
+ branch = true
53
+ source = ["filtration"]
54
+
55
+ [tool.coverage.report]
56
+ show_missing = true
57
+
58
+ [tool.ruff]
59
+ line-length = 99
60
+
61
+ [tool.ruff.lint]
62
+ select = ["E", "W", "F", "I", "B", "UP", "S"]
63
+
64
+ [tool.ruff.lint.per-file-ignores]
65
+ # bandit only ever scanned filtration/; tests are full of asserts
66
+ "tests/*" = ["S"]
@@ -0,0 +1,136 @@
1
+ import pytest
2
+ from pyparsing import ParseException
3
+
4
+ from filtration import Expression, List, Regex, Statement, Subnet, Symbol, Value
5
+
6
+ SYMBOLS = ["abcXYZ", "_abcXYZ", "abc.XYZ", "_abc.XYZ"]
7
+ NOT_SYMBOLS = ["'abcXYZ'", '"abcXYZ"', "12345"]
8
+
9
+ VALUES = [
10
+ "'abcXYZ'",
11
+ '"abcXYZ"',
12
+ "12345",
13
+ "2015-03-01",
14
+ "12:34:56",
15
+ "2015-03-01T12:34:56",
16
+ ]
17
+ NOT_VALUES = ["abcXYZ", "_abcXYZ", "abc.XYZ", "_abc.XYZ"]
18
+
19
+ REGEXES = ["/regex/", "/regex/i", "/regex/im"]
20
+ NOT_REGEXES = ["/not[a-valid/", "/not(a-valid/", "/not-a-valid)", "'regex'"]
21
+
22
+ SUBNETS = [
23
+ "0.0.0.0/0",
24
+ "0.0.0.0/8",
25
+ "172.16.0.0/8",
26
+ "192.168.0.0/16",
27
+ "192.168.100.0/24",
28
+ "255.255.255.255/32",
29
+ ]
30
+ NOT_SUBNETS = ["0.0.0.0", "0.0.0.0/33", "256.256.256.256/0", "256.256.256.256/32"]
31
+
32
+ TERMS = [
33
+ "symbol1",
34
+ "symbol1 == symbol2",
35
+ "symbol1 == 'value1'",
36
+ "symbol1 =~ /regex1/",
37
+ "symbol1 in 10.0.0.0/8",
38
+ "symbol1 in 'list','list','list'",
39
+ "symbol1 in symbol1",
40
+ "'value1' in symbol1",
41
+ ]
42
+
43
+ EXPRESSION_FORMATS = [
44
+ "{0}",
45
+ "not {0}",
46
+ "({0})",
47
+ "not ({0})",
48
+ "{0} and {0}",
49
+ "{0} or {0}",
50
+ "{0} and {0} or {0}",
51
+ "{0} and ({0} or {0})",
52
+ "{0} or {0} and {0}",
53
+ "({0} or {0}) and {0}",
54
+ ]
55
+
56
+
57
+ @pytest.mark.parametrize("expr", SYMBOLS)
58
+ def test_parse_symbol(expr: str) -> None:
59
+ """A symbol starts with a letter or underscore, then letters, digits, dots or underscores."""
60
+ Symbol.parse_string(expr, parse_all=True)
61
+
62
+
63
+ @pytest.mark.parametrize("expr", NOT_SYMBOLS)
64
+ def test_parse_symbol_rejects(expr: str) -> None:
65
+ """Quoted strings and bare numbers are not symbols."""
66
+ with pytest.raises(ParseException):
67
+ Symbol.parse_string(expr)
68
+
69
+
70
+ @pytest.mark.parametrize("expr", VALUES)
71
+ def test_parse_value(expr: str) -> None:
72
+ """A value is a quoted string, a number, a date, a time or a date/time."""
73
+ Value.parse_string(expr, parse_all=True)
74
+
75
+
76
+ @pytest.mark.parametrize("expr", NOT_VALUES)
77
+ def test_parse_value_rejects(expr: str) -> None:
78
+ """Bare words are symbols, not values."""
79
+ with pytest.raises(ParseException):
80
+ Value.parse_string(expr)
81
+
82
+
83
+ @pytest.mark.parametrize("expr", REGEXES)
84
+ def test_parse_regex(expr: str) -> None:
85
+ """A regex is wrapped in / with optional i, m or s flags after it."""
86
+ Regex.parse_string(expr, parse_all=True)
87
+
88
+
89
+ @pytest.mark.parametrize("expr", NOT_REGEXES)
90
+ def test_parse_regex_rejects(expr: str) -> None:
91
+ """Invalid patterns and unslashed strings are not regexes."""
92
+ with pytest.raises(ParseException):
93
+ Regex.parse_string(expr)
94
+
95
+
96
+ @pytest.mark.parametrize("expr", SUBNETS)
97
+ def test_parse_subnet(expr: str) -> None:
98
+ """Subnets are IPv4 CIDR notation."""
99
+ Subnet.parse_string(expr, parse_all=True)
100
+
101
+
102
+ @pytest.mark.parametrize("expr", NOT_SUBNETS)
103
+ def test_parse_subnet_rejects(expr: str) -> None:
104
+ """A bare IP, a prefix over 32 or an octet over 255 is not a subnet."""
105
+ with pytest.raises(ParseException):
106
+ Subnet.parse_string(expr)
107
+
108
+
109
+ @pytest.mark.parametrize("length", range(2, 10))
110
+ def test_parse_valuelist(length: int) -> None:
111
+ """A list is two or more values separated by commas."""
112
+ List.parse_string(",".join(["'value'"] * length), parse_all=True)
113
+
114
+
115
+ def test_parse_valuelist_rejects_single_value() -> None:
116
+ """One value on its own is not a list."""
117
+ with pytest.raises(ParseException):
118
+ List.parse_string("'value'")
119
+
120
+
121
+ @pytest.mark.parametrize("expr", TERMS)
122
+ def test_parse_statement(expr: str) -> None:
123
+ """Each statement form parses."""
124
+ Statement.parse_string(expr, parse_all=True)
125
+
126
+
127
+ @pytest.mark.parametrize("term", TERMS)
128
+ @pytest.mark.parametrize("fmt", EXPRESSION_FORMATS)
129
+ def test_parse_expression(fmt: str, term: str) -> None:
130
+ """Statements combine with not, and, or and parentheses."""
131
+ Expression.parse_string(fmt.format(term), parse_all=True)
132
+
133
+
134
+ def test_parse_string_camelcase_alias() -> None:
135
+ """Expression.parseString stays available; libhurricane and Tempest call it."""
136
+ assert Expression.parseString == Expression.parse_string
@@ -0,0 +1,98 @@
1
+ from __future__ import annotations
2
+
3
+ import datetime
4
+ import re
5
+ from typing import Any
6
+
7
+ import pytest
8
+
9
+ from filtration import Expression, Regex, Subnet, Symbol, Value
10
+
11
+ REGEX_EVALUATE = [
12
+ ("/abc/", re.compile("abc")),
13
+ ("/abc/i", re.compile("abc", flags=re.IGNORECASE)),
14
+ ("/abc/m", re.compile("abc", flags=re.MULTILINE)),
15
+ ("/abc/s", re.compile("abc", flags=re.DOTALL)),
16
+ ("/abc/ims", re.compile("abc", flags=re.IGNORECASE | re.MULTILINE | re.DOTALL)),
17
+ ]
18
+
19
+ # (expression that should be true, expression that should be false)
20
+ EXPRESSION_EVALUATE = [
21
+ ("symbol_true", "symbol_false"),
22
+ ("symbol_true and symbol_true", "symbol_true and symbol_false"),
23
+ ("symbol_true or symbol_false", "symbol_false or symbol_false"),
24
+ ("not symbol_false", "not symbol_true"),
25
+ ("dict.symbol_true", "dict.doesnt_exist"),
26
+ ("symbol_int == 1", "symbol_int == 2"),
27
+ ("symbol_int != 2", "symbol_int != 1"),
28
+ ("symbol_int < 2", "symbol_int < 1"),
29
+ ("symbol_int <= 1", "symbol_int <= 0"),
30
+ ("symbol_int > 0", "symbol_int > 1"),
31
+ ("symbol_int >= 1", "symbol_int >= 2"),
32
+ ("symbol_str in 'a','b'", "symbol_str in 'c','d'"),
33
+ (None, "'a' in nonexistant"),
34
+ ("symbol_str =~ /^a/", "symbol_str =~ /c$/"),
35
+ ("symbol_list =~ /cde/", "symbol_list =~ /xyz/"),
36
+ (None, "nonexistant =~ /a/"),
37
+ ("symbol_dt > 2015-03-01", "symbol_dt < 2000-01-01"),
38
+ ]
39
+
40
+
41
+ @pytest.fixture
42
+ def context() -> dict[str, Any]:
43
+ """An evaluation context with one value of each type the grammar compares."""
44
+ ctx: dict[str, Any] = {
45
+ "symbol_true": True,
46
+ "symbol_false": False,
47
+ "symbol_int": 1,
48
+ "symbol_str": "a",
49
+ "symbol_dt": datetime.datetime.now(),
50
+ "symbol_list": ["abcde", "cdefg"],
51
+ }
52
+ ctx["dict"] = ctx
53
+ return ctx
54
+
55
+
56
+ def test_evaluate_symbol() -> None:
57
+ """A symbol evaluates to its value in the context."""
58
+ sym = Symbol.parse_string("symbol", parse_all=True)[0]
59
+ assert sym({"symbol": "value"}) == "value"
60
+
61
+
62
+ def test_evaluate_value() -> None:
63
+ """A quoted value evaluates to the string without quotes."""
64
+ val = Value.parse_string("'value'", parse_all=True)[0]
65
+ assert val({}) == "value"
66
+
67
+
68
+ @pytest.mark.parametrize(("expr", "expected"), REGEX_EVALUATE)
69
+ def test_evaluate_regex(expr: str, expected: re.Pattern) -> None:
70
+ """A regex evaluates to a compiled pattern with the flags given."""
71
+ rex = Regex.parse_string(expr, parse_all=True)[0]
72
+ result = rex({})
73
+ assert result.pattern == expected.pattern
74
+ assert result.flags == expected.flags
75
+
76
+
77
+ def test_evaluate_subnet() -> None:
78
+ """A subnet evaluates to a network object."""
79
+ subnet = Subnet.parse_string("192.168.0.0/16", parse_all=True)[0]
80
+ assert subnet({}).network() == "192.168.0.0"
81
+ assert subnet({}).size() == 2**16
82
+
83
+
84
+ @pytest.mark.parametrize(("expr_true", "expr_false"), EXPRESSION_EVALUATE)
85
+ def test_evaluate_expression(
86
+ context: dict[str, Any], expr_true: str | None, expr_false: str
87
+ ) -> None:
88
+ """Each operator gives the expected result against the context."""
89
+ if expr_true:
90
+ assert Expression.parse_string(expr_true, parse_all=True)(context)
91
+ assert not Expression.parse_string(expr_false, parse_all=True)(context)
92
+
93
+
94
+ def test_subnet_contains() -> None:
95
+ """`in` a subnet matches IPs inside it and rejects non-IPs."""
96
+ expr = Expression.parse_string("src in 127.0.0.0/8", parse_all=True)
97
+ assert expr({"src": "127.0.0.1"})
98
+ assert not expr({"src": "localhost"})
@@ -1,2 +0,0 @@
1
- pyparsing>=3.0.0
2
- ipcalc
filtration-2.3.2/setup.py DELETED
@@ -1,31 +0,0 @@
1
- from setuptools import setup
2
-
3
-
4
- VERSION = "2.3.2"
5
-
6
-
7
- with open("README.rst", "r") as f:
8
- long_description = f.read()
9
-
10
-
11
- setup(
12
- name="filtration",
13
- version=VERSION,
14
- author="Steve McMaster",
15
- author_email="mcmaster@hurricanelabs.com",
16
- packages=["filtration"],
17
- description="filtration - A library for parsing arbitrary filters",
18
- long_description=long_description,
19
- install_requires=[
20
- "pyparsing>=3.0.0",
21
- "ipcalc"
22
- ],
23
- classifiers=[
24
- "License :: OSI Approved :: MIT License",
25
- "Programming Language :: Python :: 3",
26
- "Development Status :: 5 - Production/Stable",
27
- ],
28
- project_urls={
29
- "Bug Tracker": "https://github.com/HurricaneLabs/filtration/issues"
30
- }
31
- )
@@ -1,162 +0,0 @@
1
- import unittest
2
-
3
- from nose2.tools import params
4
- from pyparsing import ParseException
5
- import fauxfactory
6
-
7
-
8
- symbol_tests = [
9
- fauxfactory.gen_alpha(),
10
- "_{0}".format(fauxfactory.gen_alpha()),
11
- "{0}.{1}".format(fauxfactory.gen_alpha(), fauxfactory.gen_alpha()),
12
- "_{0}.{1}".format(fauxfactory.gen_alpha(), fauxfactory.gen_alpha()),
13
- ("'{0}'".format(fauxfactory.gen_alpha()), ParseException),
14
- ('"{0}"'.format(fauxfactory.gen_alpha()), ParseException),
15
- (fauxfactory.gen_numeric_string(), ParseException),
16
- ]
17
-
18
- value_tests = [
19
- "'{0}'".format(fauxfactory.gen_alpha()),
20
- '"{0}"'.format(fauxfactory.gen_alpha()),
21
- fauxfactory.gen_numeric_string(),
22
- fauxfactory.gen_date().isoformat(),
23
- fauxfactory.gen_time().isoformat(),
24
- fauxfactory.gen_datetime().isoformat(),
25
- (fauxfactory.gen_alpha(), ParseException),
26
- ("_{0}".format(fauxfactory.gen_alpha()), ParseException),
27
- ("{0}.{1}".format(fauxfactory.gen_alpha(), fauxfactory.gen_alpha()), ParseException),
28
- ("_{0}.{1}".format(fauxfactory.gen_alpha(), fauxfactory.gen_alpha()), ParseException),
29
- ]
30
-
31
- regex_tests = [
32
- "/regex/",
33
- "/regex/i",
34
- "/regex/im",
35
- ("/not[a-valid/", ParseException),
36
- ("/not(a-valid/", ParseException),
37
- ("/not-a-valid)", ParseException),
38
- ("'regex'", ParseException),
39
- ]
40
-
41
- subnet_tests = [
42
- "0.0.0.0/0",
43
- "0.0.0.0/8",
44
- "172.16.0.0/8",
45
- "192.168.0.0/16",
46
- "192.168.100.0/24",
47
- "255.255.255.255/32",
48
- ("0.0.0.0", ParseException),
49
- ("0.0.0.0/33", ParseException),
50
- ("256.256.256.256/0", ParseException),
51
- ("256.256.256.256/32", ParseException),
52
- ]
53
-
54
- term_parse_tests = [
55
- "symbol1",
56
- "symbol1 == symbol2",
57
- "symbol1 == 'value1'",
58
- "symbol1 =~ /regex1/",
59
- "symbol1 in 10.0.0.0/8",
60
- "symbol1 in 'list','list','list'",
61
- "symbol1 in symbol1",
62
- "'value1' in symbol1",
63
- ]
64
-
65
- expression_parse_tests = [
66
- "{0}",
67
- "not {0}",
68
- "({0})",
69
- "not ({0})",
70
- "{0} and {1}",
71
- "{0} or {1}",
72
- "{0} and {1} or {2}",
73
- "{0} and ({1} or {2})",
74
- "{0} or {1} and {2}",
75
- "({0} or {1}) and {2}",
76
- ]
77
-
78
-
79
- def generate_expression_tests():
80
- for test_expr_fmt in expression_parse_tests:
81
- for (expr_a, expr_b, expr_c) in zip(term_parse_tests, term_parse_tests, term_parse_tests):
82
- yield test_expr_fmt.format(expr_a, expr_b, expr_c)
83
-
84
-
85
- class TestGrammar(unittest.TestCase):
86
- @params(*symbol_tests)
87
- def test_parse_symbol(self, test_expr, expect_failure=None):
88
- """
89
- A symbol begins with a letter or an underscore, and may contain any combination of
90
- letters, numbers, dot (".") and underscore ("_")
91
- """
92
- from filtration import Symbol
93
-
94
- if expect_failure is None:
95
- Symbol.parseString(test_expr)
96
- else:
97
- self.assertRaises(expect_failure, Symbol.parseString, test_expr)
98
-
99
- @params(*value_tests)
100
- def test_parse_value(self, test_expr, expect_failure=None):
101
- """
102
- A value is a quoted string, with single or double quotes, or a number.
103
- """
104
- from filtration import Value
105
-
106
- if expect_failure is None:
107
- Value.parseString(test_expr)
108
- else:
109
- self.assertRaises(expect_failure, Value.parseString, test_expr)
110
-
111
- @params(*regex_tests)
112
- def test_parse_regex(self, test_expr, expect_failure=None):
113
- """
114
- A regex is a string surrounded by /
115
- """
116
- from filtration import Regex
117
-
118
- if expect_failure is None:
119
- Regex.parseString(test_expr)
120
- else:
121
- self.assertRaises(expect_failure, Regex.parseString, test_expr)
122
-
123
- @params(*subnet_tests)
124
- def test_parse_subnet(self, test_expr, expect_failure=None):
125
- """
126
- Subnets are defined in CIDR notation
127
- """
128
- from filtration import Subnet
129
-
130
- if expect_failure is None:
131
- Subnet.parseString(test_expr)
132
- else:
133
- self.assertRaises(expect_failure, Subnet.parseString, test_expr)
134
-
135
- @params(*range(1, 10))
136
- def test_parse_valuelist(self, test_expr_len, expect_failure=None):
137
- """
138
- A list is two or more values, separated by commas
139
- """
140
- from filtration import List
141
-
142
- test_expr = ",".join(["'value'" for _ in range(0, test_expr_len)])
143
- if test_expr_len > 1:
144
- List.parseString(test_expr)
145
- else:
146
- self.assertRaises(ParseException, List.parseString, test_expr)
147
-
148
- @params(*term_parse_tests)
149
- def test_parse_statement(self, test_expr, expect_failure=None):
150
- """
151
- """
152
- from filtration import Statement
153
-
154
- Statement.parseString(test_expr)
155
-
156
- @params(*generate_expression_tests())
157
- def test_parse_expression(self, test_expr):
158
- """
159
- """
160
- from filtration import Expression
161
-
162
- Expression.parseString(test_expr)
@@ -1,106 +0,0 @@
1
- import unittest
2
-
3
- from nose2.tools import params
4
-
5
-
6
- import re
7
- regex_evaluate_tests = [
8
- ("/abc/", re.compile("abc")),
9
- ("/abc/i", re.compile("abc", flags=re.I)),
10
- ("/abc/m", re.compile("abc", flags=re.M)),
11
- ("/abc/s", re.compile("abc", flags=re.S)),
12
- ("/abc/ims", re.compile("abc", flags=re.I | re.M | re.S)),
13
- ]
14
-
15
- expression_evaluate_tests = [
16
- ("symbol_true", "symbol_false"),
17
- ("symbol_true and symbol_true", "symbol_true and symbol_false"),
18
- ("symbol_true or symbol_false", "symbol_false or symbol_false"),
19
- ("not symbol_false", "not symbol_true"),
20
- ("dict.symbol_true", "dict.doesnt_exist"),
21
- ("symbol_int == 1", "symbol_int == 2"),
22
- ("symbol_int != 2", "symbol_int != 1"),
23
- ("symbol_int < 2", "symbol_int < 1"),
24
- ("symbol_int <= 1", "symbol_int <= 0"),
25
- ("symbol_int > 0", "symbol_int > 1"),
26
- ("symbol_int >= 1", "symbol_int >= 2"),
27
- ("symbol_str in 'a','b'", "symbol_str in 'c','d'"),
28
- (None, "'a' in nonexistant"),
29
- ("symbol_str =~ /^a/", "symbol_str =~ /c$/"),
30
- ("symbol_list =~ /cde/", "symbol_list =~ /xyz/"),
31
- (None, "nonexistant =~ /a/"),
32
- ("symbol_dt > 2015-03-01", "symbol_dt < 2000-01-01"),
33
- ]
34
-
35
-
36
- class TestTokens(unittest.TestCase):
37
- def test_evaluate_symbol(self):
38
- """
39
- """
40
- from filtration import Symbol
41
-
42
- sym = Symbol.parseString("symbol")[0]
43
- self.assertEqual(sym({"symbol": "value"}), "value")
44
-
45
- def test_evaluate_value(self):
46
- """
47
- """
48
- from filtration import Value
49
-
50
- val = Value.parseString("'value'")[0]
51
- self.assertEqual(val({}), "value")
52
-
53
- @params(*regex_evaluate_tests)
54
- def test_evaluate_regex(self, test_expr, expected):
55
- """
56
- """
57
- from filtration import Regex
58
-
59
- rex = Regex.parseString(test_expr)[0]
60
- result = rex({})
61
-
62
- self.assertEqual(result.pattern, expected.pattern)
63
- self.assertEqual(result.flags, expected.flags)
64
-
65
- def test_evaluate_subnet(self):
66
- """
67
- """
68
- from filtration import Subnet
69
-
70
- subnet = Subnet.parseString("192.168.0.0/16")[0]
71
- self.assertEqual(subnet({}).network(), "192.168.0.0")
72
- self.assertEqual(subnet({}).size(), 2 ** 16)
73
-
74
- @params(*expression_evaluate_tests)
75
- def test_evaluate_expression(self, test_expr_true, test_expr_false=None):
76
- """
77
- """
78
- import datetime
79
- from filtration import Expression
80
-
81
- context = {
82
- "symbol_true": True,
83
- "symbol_False": False,
84
- "symbol_int": 1,
85
- "symbol_str": "a",
86
- "symbol_dt": datetime.datetime.now(),
87
- "symbol_list": ["abcde", "cdefg"]
88
- }
89
- context["dict"] = context
90
-
91
- if test_expr_true:
92
- expr = Expression.parseString(test_expr_true)
93
- self.assertTrue(expr(context))
94
-
95
- if test_expr_false:
96
- expr = Expression.parseString(test_expr_false)
97
- self.assertFalse(expr(context))
98
-
99
- def test_subnet_contains(self):
100
- """
101
- """
102
- from filtration import Expression
103
-
104
- expr = Expression.parseString("src in 127.0.0.0/8")
105
- self.assertTrue(expr({"src": "127.0.0.1"}))
106
- self.assertFalse(expr({"src": "localhost"}))
File without changes