instance_id
stringlengths 10
57
| patch
stringlengths 261
37.7k
| repo
stringlengths 7
53
| base_commit
stringlengths 40
40
| hints_text
stringclasses 301
values | test_patch
stringlengths 212
2.22M
| problem_statement
stringlengths 23
37.7k
| version
int64 0
0
| environment_setup_commit
stringclasses 89
values | FAIL_TO_PASS
sequencelengths 1
4.94k
| PASS_TO_PASS
sequencelengths 0
7.82k
| meta
dict | created_at
unknown | license
stringclasses 8
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
PyCQA__flake8-bugbear-209 | diff --git a/bugbear.py b/bugbear.py
index 77b4dc6..9249550 100644
--- a/bugbear.py
+++ b/bugbear.py
@@ -639,7 +639,6 @@ class BugBearVisitor(ast.NodeVisitor):
if isinstance(
subnode.value,
(
- ast.Str,
ast.Num,
ast.Bytes,
ast.NameConstant,
| PyCQA/flake8-bugbear | 9e311d5af7ffd2bba272fc6471b8ecfe21bf1993 | diff --git a/tests/b018_classes.py b/tests/b018_classes.py
index 12195c0..551b14e 100644
--- a/tests/b018_classes.py
+++ b/tests/b018_classes.py
@@ -1,6 +1,6 @@
"""
Should emit:
-B018 - on lines 15-26, 30, 32
+B018 - on lines 16-26, 30, 33
"""
@@ -30,3 +30,4 @@ class Foo3:
123
a = 2
"str"
+ 1
diff --git a/tests/b018_functions.py b/tests/b018_functions.py
index 9764274..f8c3f77 100644
--- a/tests/b018_functions.py
+++ b/tests/b018_functions.py
@@ -1,6 +1,6 @@
"""
Should emit:
-B018 - on lines 14-25, 29, 31
+B018 - on lines 15-25, 29, 32
"""
@@ -29,3 +29,4 @@ def foo3():
123
a = 2
"str"
+ 3
diff --git a/tests/test_bugbear.py b/tests/test_bugbear.py
index c05b828..319a508 100644
--- a/tests/test_bugbear.py
+++ b/tests/test_bugbear.py
@@ -234,9 +234,9 @@ class BugbearTestCase(unittest.TestCase):
bbc = BugBearChecker(filename=str(filename))
errors = list(bbc.run())
- expected = [B018(line, 4) for line in range(14, 26)]
+ expected = [B018(line, 4) for line in range(15, 26)]
expected.append(B018(29, 4))
- expected.append(B018(31, 4))
+ expected.append(B018(32, 4))
self.assertEqual(errors, self.errors(*expected))
def test_b018_classes(self):
@@ -244,9 +244,9 @@ class BugbearTestCase(unittest.TestCase):
bbc = BugBearChecker(filename=str(filename))
errors = list(bbc.run())
- expected = [B018(line, 4) for line in range(15, 27)]
+ expected = [B018(line, 4) for line in range(16, 27)]
expected.append(B018(30, 4))
- expected.append(B018(32, 4))
+ expected.append(B018(33, 4))
self.assertEqual(errors, self.errors(*expected))
def test_b901(self):
| B018 wrongly detects inline variable or attribute docstrings
Having an inline attribute doc string or a module variable docstring, it is wrongly marked as B018 (sample from sphinx doc):
```
module_level_variable2 = 98765
"""int: Module level variable documented inline.
The docstring may span multiple lines. The type may optionally be specified
on the first line, separated by a colon.
"""
``` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_bugbear.py::BugbearTestCase::test_b018_classes",
"tests/test_bugbear.py::BugbearTestCase::test_b018_functions"
] | [
"tests/test_bugbear.py::BugbearTestCase::test_b001",
"tests/test_bugbear.py::BugbearTestCase::test_b002",
"tests/test_bugbear.py::BugbearTestCase::test_b003",
"tests/test_bugbear.py::BugbearTestCase::test_b004",
"tests/test_bugbear.py::BugbearTestCase::test_b005",
"tests/test_bugbear.py::BugbearTestCase::test_b006_b008",
"tests/test_bugbear.py::BugbearTestCase::test_b007",
"tests/test_bugbear.py::BugbearTestCase::test_b008_extended",
"tests/test_bugbear.py::BugbearTestCase::test_b009_b010",
"tests/test_bugbear.py::BugbearTestCase::test_b011",
"tests/test_bugbear.py::BugbearTestCase::test_b012",
"tests/test_bugbear.py::BugbearTestCase::test_b013",
"tests/test_bugbear.py::BugbearTestCase::test_b014",
"tests/test_bugbear.py::BugbearTestCase::test_b015",
"tests/test_bugbear.py::BugbearTestCase::test_b016",
"tests/test_bugbear.py::BugbearTestCase::test_b017",
"tests/test_bugbear.py::BugbearTestCase::test_b901",
"tests/test_bugbear.py::BugbearTestCase::test_b902",
"tests/test_bugbear.py::BugbearTestCase::test_b902_py38",
"tests/test_bugbear.py::BugbearTestCase::test_b903",
"tests/test_bugbear.py::BugbearTestCase::test_b904",
"tests/test_bugbear.py::BugbearTestCase::test_b950",
"tests/test_bugbear.py::BugbearTestCase::test_selfclean_test_bugbear",
"tests/test_bugbear.py::TestFuzz::test_does_not_crash_on_any_valid_code",
"tests/test_bugbear.py::TestFuzz::test_does_not_crash_on_call_in_except_statement",
"tests/test_bugbear.py::TestFuzz::test_does_not_crash_on_site_code",
"tests/test_bugbear.py::TestFuzz::test_does_not_crash_on_tuple_expansion_in_except_statement"
] | {
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
} | "2021-11-29T18:59:11Z" | mit |
|
PyCQA__flake8-bugbear-213 | diff --git a/.gitignore b/.gitignore
index fc8539e..1dc5815 100644
--- a/.gitignore
+++ b/.gitignore
@@ -23,6 +23,7 @@ var/
*.egg-info/
.installed.cfg
*.egg
+venv/
# PyInstaller
# Usually these files are written by a python script from a template
diff --git a/README.rst b/README.rst
index 6d94ba7..7ad3874 100644
--- a/README.rst
+++ b/README.rst
@@ -173,7 +173,15 @@ significantly violate the line length, you will receive a message that
states what the actual limit is. This is inspired by Raymond Hettinger's
`"Beyond PEP 8" talk <https://www.youtube.com/watch?v=wf-BqAjZb8M>`_ and
highway patrol not stopping you if you drive < 5mph too fast. Disable
-E501 to avoid duplicate warnings.
+E501 to avoid duplicate warnings. Like E501, this error ignores long shebangs
+on the first line and urls or paths that are on their own line::
+
+ #! long shebang ignored
+
+ # https://some-super-long-domain-name.com/with/some/very/long/paths
+ url = (
+ "https://some-super-long-domain-name.com/with/some/very/long/paths"
+ )
How to enable opinionated warnings
@@ -237,6 +245,11 @@ MIT
Change Log
----------
+21.12.0
+~~~~~~~~~~
+
+* B950: Add same special cases as E501 (#213)
+
21.11.29
~~~~~~~~~~
diff --git a/bugbear.py b/bugbear.py
index eab2b53..78c2ca3 100644
--- a/bugbear.py
+++ b/bugbear.py
@@ -67,8 +67,31 @@ class BugBearChecker:
The following simple checks are based on the raw lines, not the AST.
"""
for lineno, line in enumerate(self.lines, start=1):
+ # Special case: ignore long shebang (following pycodestyle).
+ if lineno == 1 and line.startswith("#!"):
+ continue
+
length = len(line) - 1
if length > 1.1 * self.max_line_length:
+ # Special case long URLS and paths to follow pycodestyle.
+ # Would use the `pycodestyle.maximum_line_length` directly but
+ # need to supply it arguments that are not available so chose
+ # to replicate instead.
+ chunks = line.split()
+
+ is_line_comment_url_path = len(chunks) == 2 and chunks[0] == "#"
+
+ just_long_url_path = len(chunks) == 1
+
+ num_leading_whitespaces = len(line) - len(chunks[-1])
+ too_many_leading_white_spaces = (
+ num_leading_whitespaces >= self.max_line_length - 7
+ )
+
+ skip = is_line_comment_url_path or just_long_url_path
+ if skip and not too_many_leading_white_spaces:
+ continue
+
yield B950(lineno, length, vars=(length, self.max_line_length))
@classmethod
| PyCQA/flake8-bugbear | 49aec1807ead4c7da7d055e20118563ed13b5201 | diff --git a/tests/b950.py b/tests/b950.py
index 1939105..942e50c 100644
--- a/tests/b950.py
+++ b/tests/b950.py
@@ -1,3 +1,4 @@
+#! Ignore long shebang fooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
# Assumes the default allowed line length of 79
"line is fine"
@@ -5,3 +6,16 @@
" line is still fine "
" line is no longer fine by any measures, yup"
"line is fine again"
+
+# Ensure URL/path on it's own line is fine
+"https://foooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo.com"
+"NOT OK: https://foooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo.com"
+# https://foooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo.com
+# NOT OK: https://foooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo.com
+#
+#: Okay
+# This
+# almost_empty_line_too_long
+
+# This
+# almost_empty_line_too_long
diff --git a/tests/test_bugbear.py b/tests/test_bugbear.py
index 319a508..d1af992 100644
--- a/tests/test_bugbear.py
+++ b/tests/test_bugbear.py
@@ -318,7 +318,15 @@ class BugbearTestCase(unittest.TestCase):
filename = Path(__file__).absolute().parent / "b950.py"
bbc = BugBearChecker(filename=str(filename))
errors = list(bbc.run())
- self.assertEqual(errors, self.errors(B950(6, 92, vars=(92, 79))))
+ self.assertEqual(
+ errors,
+ self.errors(
+ B950(7, 92, vars=(92, 79)),
+ B950(12, 103, vars=(103, 79)),
+ B950(14, 103, vars=(103, 79)),
+ B950(21, 97, vars=(97, 79)),
+ ),
+ )
def test_selfclean_bugbear(self):
filename = Path(__file__).absolute().parent.parent / "bugbear.py"
| B950: Propose exemption for long URLs
I like the idea of using B950 over E501, but I do not want to be warned anytime I include a long URL in a comment. Breaking URLs over multiple lines is not acceptable as I want them to be clickable.
pycodestyle addresses this by making an exemption to the line length error for comments that contain no whitespace. See [line 304](https://github.com/PyCQA/pycodestyle/blob/aa3417b6a51f5912e32d9c8c879e1b9dd660d5f8/pycodestyle.py#L304) (currently) of pycodestyle.py:
```
# Special case for long URLs in multi-line docstrings or
# comments, but still report the error when the 72 first chars
# are whitespaces.
chunks = line.split()
if ((len(chunks) == 1 and multiline) or
(len(chunks) == 2 and chunks[0] == '#')) and \
len(line) - len(chunks[-1]) < max_line_length - 7:
return
```
I propose adding a similar exemption to flake8-bugbear. Of course, I could add a `# noqa` comment after every URL comment, but I much prefer pycodestyle's solution. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_bugbear.py::BugbearTestCase::test_b950"
] | [
"tests/test_bugbear.py::BugbearTestCase::test_b001",
"tests/test_bugbear.py::BugbearTestCase::test_b002",
"tests/test_bugbear.py::BugbearTestCase::test_b003",
"tests/test_bugbear.py::BugbearTestCase::test_b004",
"tests/test_bugbear.py::BugbearTestCase::test_b005",
"tests/test_bugbear.py::BugbearTestCase::test_b006_b008",
"tests/test_bugbear.py::BugbearTestCase::test_b007",
"tests/test_bugbear.py::BugbearTestCase::test_b008_extended",
"tests/test_bugbear.py::BugbearTestCase::test_b009_b010",
"tests/test_bugbear.py::BugbearTestCase::test_b011",
"tests/test_bugbear.py::BugbearTestCase::test_b012",
"tests/test_bugbear.py::BugbearTestCase::test_b013",
"tests/test_bugbear.py::BugbearTestCase::test_b014",
"tests/test_bugbear.py::BugbearTestCase::test_b015",
"tests/test_bugbear.py::BugbearTestCase::test_b016",
"tests/test_bugbear.py::BugbearTestCase::test_b017",
"tests/test_bugbear.py::BugbearTestCase::test_b018_classes",
"tests/test_bugbear.py::BugbearTestCase::test_b018_functions",
"tests/test_bugbear.py::BugbearTestCase::test_b901",
"tests/test_bugbear.py::BugbearTestCase::test_b902",
"tests/test_bugbear.py::BugbearTestCase::test_b902_py38",
"tests/test_bugbear.py::BugbearTestCase::test_b903",
"tests/test_bugbear.py::BugbearTestCase::test_b904",
"tests/test_bugbear.py::BugbearTestCase::test_selfclean_test_bugbear",
"tests/test_bugbear.py::TestFuzz::test_does_not_crash_on_any_valid_code",
"tests/test_bugbear.py::TestFuzz::test_does_not_crash_on_call_in_except_statement",
"tests/test_bugbear.py::TestFuzz::test_does_not_crash_on_site_code",
"tests/test_bugbear.py::TestFuzz::test_does_not_crash_on_tuple_expansion_in_except_statement"
] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2021-12-31T20:56:05Z" | mit |
|
PyCQA__flake8-bugbear-216 | diff --git a/bugbear.py b/bugbear.py
index 78c2ca3..b8ecbd5 100644
--- a/bugbear.py
+++ b/bugbear.py
@@ -654,18 +654,15 @@ class BugBearVisitor(ast.NodeVisitor):
self.errors.append(B903(node.lineno, node.col_offset))
def check_for_b018(self, node):
- for index, subnode in enumerate(node.body):
+ for subnode in node.body:
if not isinstance(subnode, ast.Expr):
continue
- if index == 0 and isinstance(subnode.value, ast.Str):
- continue # most likely a docstring
if isinstance(
subnode.value,
(
ast.Num,
ast.Bytes,
ast.NameConstant,
- ast.JoinedStr,
ast.List,
ast.Set,
ast.Dict,
| PyCQA/flake8-bugbear | c0a9c878dd50b57e8f39f34b07f1730866c9d86d | diff --git a/tests/b018_classes.py b/tests/b018_classes.py
index 551b14e..7992f15 100644
--- a/tests/b018_classes.py
+++ b/tests/b018_classes.py
@@ -1,6 +1,6 @@
"""
Should emit:
-B018 - on lines 16-26, 30, 33
+B018 - on lines 17-26, 30, 33
"""
@@ -12,12 +12,12 @@ class Foo2:
"""abc"""
a = 2
- "str" # Str
+ "str" # Str (no raise)
+ f"{int}" # JoinedStr (no raise)
1j # Number (complex)
1 # Number (int)
1.0 # Number (float)
b"foo" # Binary
- f"{int}" # JoinedStr
True # NameConstant (True)
False # NameConstant (False)
None # NameConstant (None)
diff --git a/tests/b018_functions.py b/tests/b018_functions.py
index f8c3f77..763d6b8 100644
--- a/tests/b018_functions.py
+++ b/tests/b018_functions.py
@@ -1,6 +1,6 @@
"""
Should emit:
-B018 - on lines 15-25, 29, 32
+B018 - on lines 16-25, 29, 32
"""
@@ -11,12 +11,12 @@ def foo1():
def foo2():
"""my docstring"""
a = 2
- "str" # Str
+ "str" # Str (no raise)
+ f"{int}" # JoinedStr (no raise)
1j # Number (complex)
1 # Number (int)
1.0 # Number (float)
b"foo" # Binary
- f"{int}" # JoinedStr
True # NameConstant (True)
False # NameConstant (False)
None # NameConstant (None)
diff --git a/tests/test_bugbear.py b/tests/test_bugbear.py
index d1af992..d02b637 100644
--- a/tests/test_bugbear.py
+++ b/tests/test_bugbear.py
@@ -234,7 +234,7 @@ class BugbearTestCase(unittest.TestCase):
bbc = BugBearChecker(filename=str(filename))
errors = list(bbc.run())
- expected = [B018(line, 4) for line in range(15, 26)]
+ expected = [B018(line, 4) for line in range(16, 26)]
expected.append(B018(29, 4))
expected.append(B018(32, 4))
self.assertEqual(errors, self.errors(*expected))
@@ -244,7 +244,7 @@ class BugbearTestCase(unittest.TestCase):
bbc = BugBearChecker(filename=str(filename))
errors = list(bbc.run())
- expected = [B018(line, 4) for line in range(16, 27)]
+ expected = [B018(line, 4) for line in range(17, 27)]
expected.append(B018(30, 4))
expected.append(B018(33, 4))
self.assertEqual(errors, self.errors(*expected))
| B018 wrongly detects inline variable or attribute docstrings
Having an inline attribute doc string or a module variable docstring, it is wrongly marked as B018 (sample from sphinx doc):
```
module_level_variable2 = 98765
"""int: Module level variable documented inline.
The docstring may span multiple lines. The type may optionally be specified
on the first line, separated by a colon.
"""
``` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_bugbear.py::BugbearTestCase::test_b018_classes",
"tests/test_bugbear.py::BugbearTestCase::test_b018_functions"
] | [
"tests/test_bugbear.py::BugbearTestCase::test_b001",
"tests/test_bugbear.py::BugbearTestCase::test_b002",
"tests/test_bugbear.py::BugbearTestCase::test_b003",
"tests/test_bugbear.py::BugbearTestCase::test_b004",
"tests/test_bugbear.py::BugbearTestCase::test_b005",
"tests/test_bugbear.py::BugbearTestCase::test_b006_b008",
"tests/test_bugbear.py::BugbearTestCase::test_b007",
"tests/test_bugbear.py::BugbearTestCase::test_b008_extended",
"tests/test_bugbear.py::BugbearTestCase::test_b009_b010",
"tests/test_bugbear.py::BugbearTestCase::test_b011",
"tests/test_bugbear.py::BugbearTestCase::test_b012",
"tests/test_bugbear.py::BugbearTestCase::test_b013",
"tests/test_bugbear.py::BugbearTestCase::test_b014",
"tests/test_bugbear.py::BugbearTestCase::test_b015",
"tests/test_bugbear.py::BugbearTestCase::test_b016",
"tests/test_bugbear.py::BugbearTestCase::test_b017",
"tests/test_bugbear.py::BugbearTestCase::test_b901",
"tests/test_bugbear.py::BugbearTestCase::test_b902",
"tests/test_bugbear.py::BugbearTestCase::test_b902_py38",
"tests/test_bugbear.py::BugbearTestCase::test_b903",
"tests/test_bugbear.py::BugbearTestCase::test_b904",
"tests/test_bugbear.py::BugbearTestCase::test_b950",
"tests/test_bugbear.py::BugbearTestCase::test_selfclean_test_bugbear",
"tests/test_bugbear.py::TestFuzz::test_does_not_crash_on_any_valid_code",
"tests/test_bugbear.py::TestFuzz::test_does_not_crash_on_call_in_except_statement",
"tests/test_bugbear.py::TestFuzz::test_does_not_crash_on_site_code",
"tests/test_bugbear.py::TestFuzz::test_does_not_crash_on_tuple_expansion_in_except_statement"
] | {
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
} | "2022-01-10T15:26:51Z" | mit |
|
PyCQA__flake8-bugbear-220 | diff --git a/.gitignore b/.gitignore
index 1dc5815..fca188e 100644
--- a/.gitignore
+++ b/.gitignore
@@ -63,3 +63,6 @@ target/
.ipynb_checkpoints
.vscode
+
+# JetBrains
+.idea/
diff --git a/README.rst b/README.rst
index 2ecc7b8..09e87df 100644
--- a/README.rst
+++ b/README.rst
@@ -132,6 +132,8 @@ data available in ``ex``.
**B018**: Found useless expression. Either assign it to a variable or remove it.
+**B020**: Loop control variable overrides iterable it iterates
+
Opinionated warnings
~~~~~~~~~~~~~~~~~~~~
@@ -245,6 +247,11 @@ MIT
Change Log
----------
+Unreleased
+~~~~~~~~~~
+
+* B020: ensure loop control variable doesn't overrides iterable it iterates (#220)
+
22.1.11
~~~~~~~~~~
diff --git a/bugbear.py b/bugbear.py
index b4fcf89..177af11 100644
--- a/bugbear.py
+++ b/bugbear.py
@@ -333,6 +333,7 @@ class BugBearVisitor(ast.NodeVisitor):
def visit_For(self, node):
self.check_for_b007(node)
+ self.check_for_b020(node)
self.generic_visit(node)
def visit_Assert(self, node):
@@ -506,6 +507,20 @@ class BugBearVisitor(ast.NodeVisitor):
):
self.errors.append(B017(node.lineno, node.col_offset))
+ def check_for_b020(self, node):
+ targets = NameFinder()
+ targets.visit(node.target)
+ ctrl_names = set(targets.names)
+
+ iterset = NameFinder()
+ iterset.visit(node.iter)
+ iterset_names = set(iterset.names)
+
+ for name in sorted(ctrl_names):
+ if name in iterset_names:
+ n = targets.names[name][0]
+ self.errors.append(B020(n.lineno, n.col_offset, vars=(name,)))
+
def check_for_b904(self, node):
"""Checks `raise` without `from` inside an `except` clause.
@@ -871,6 +886,12 @@ B018 = Error(
"B018 Found useless expression. Either assign it to a variable or remove it."
)
)
+B020 = Error(
+ message=(
+ "B020 Found for loop that reassigns the iterable it is iterating "
+ + "with each iterable value."
+ )
+)
# Warnings disabled by default.
B901 = Error(
| PyCQA/flake8-bugbear | 1c47a162d4b2c41ada9164a12b536d6f49833d7e | diff --git a/tests/b020.py b/tests/b020.py
new file mode 100644
index 0000000..df30e75
--- /dev/null
+++ b/tests/b020.py
@@ -0,0 +1,22 @@
+"""
+Should emit:
+B020 - on lines 8 and 21
+"""
+
+items = [1, 2, 3]
+
+for items in items:
+ print(items)
+
+items = [1, 2, 3]
+
+for item in items:
+ print(item)
+
+values = {"secret": 123}
+
+for key, value in values.items():
+ print(f"{key}, {value}")
+
+for key, values in values.items():
+ print(f"{key}, {values}")
diff --git a/tests/test_bugbear.py b/tests/test_bugbear.py
index d02b637..7e25386 100644
--- a/tests/test_bugbear.py
+++ b/tests/test_bugbear.py
@@ -29,6 +29,7 @@ from bugbear import (
B016,
B017,
B018,
+ B020,
B901,
B902,
B903,
@@ -249,6 +250,18 @@ class BugbearTestCase(unittest.TestCase):
expected.append(B018(33, 4))
self.assertEqual(errors, self.errors(*expected))
+ def test_b020(self):
+ filename = Path(__file__).absolute().parent / "b020.py"
+ bbc = BugBearChecker(filename=str(filename))
+ errors = list(bbc.run())
+ self.assertEqual(
+ errors,
+ self.errors(
+ B020(8, 4, vars=("items",)),
+ B020(21, 9, vars=("values",)),
+ ),
+ )
+
def test_b901(self):
filename = Path(__file__).absolute().parent / "b901.py"
bbc = BugBearChecker(filename=str(filename))
| Proposed Check: same variable name of list and interating item in for-loop
I've already placed a question [here](https://stackoverflow.com/questions/70827394/is-there-pep-rule-or-pre-commit-check-to-prevent-same-name-of-variable-and-list). Then found this project.
```
items = [1, 2, 3]
for items in items:
continue
# items == 3
```
This typo accidentally happened to me and caused a bug.
Would be nice to catch it with something like: `Bxxx for-loop with the same variable name of the list and interating item found.` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_bugbear.py::BugbearTestCase::test_b001",
"tests/test_bugbear.py::BugbearTestCase::test_b002",
"tests/test_bugbear.py::BugbearTestCase::test_b003",
"tests/test_bugbear.py::BugbearTestCase::test_b004",
"tests/test_bugbear.py::BugbearTestCase::test_b005",
"tests/test_bugbear.py::BugbearTestCase::test_b006_b008",
"tests/test_bugbear.py::BugbearTestCase::test_b007",
"tests/test_bugbear.py::BugbearTestCase::test_b008_extended",
"tests/test_bugbear.py::BugbearTestCase::test_b009_b010",
"tests/test_bugbear.py::BugbearTestCase::test_b011",
"tests/test_bugbear.py::BugbearTestCase::test_b012",
"tests/test_bugbear.py::BugbearTestCase::test_b013",
"tests/test_bugbear.py::BugbearTestCase::test_b014",
"tests/test_bugbear.py::BugbearTestCase::test_b015",
"tests/test_bugbear.py::BugbearTestCase::test_b016",
"tests/test_bugbear.py::BugbearTestCase::test_b017",
"tests/test_bugbear.py::BugbearTestCase::test_b018_classes",
"tests/test_bugbear.py::BugbearTestCase::test_b018_functions",
"tests/test_bugbear.py::BugbearTestCase::test_b020",
"tests/test_bugbear.py::BugbearTestCase::test_b901",
"tests/test_bugbear.py::BugbearTestCase::test_b902",
"tests/test_bugbear.py::BugbearTestCase::test_b902_py38",
"tests/test_bugbear.py::BugbearTestCase::test_b903",
"tests/test_bugbear.py::BugbearTestCase::test_b904",
"tests/test_bugbear.py::BugbearTestCase::test_b950",
"tests/test_bugbear.py::BugbearTestCase::test_selfclean_test_bugbear",
"tests/test_bugbear.py::TestFuzz::test_does_not_crash_on_any_valid_code",
"tests/test_bugbear.py::TestFuzz::test_does_not_crash_on_call_in_except_statement",
"tests/test_bugbear.py::TestFuzz::test_does_not_crash_on_site_code",
"tests/test_bugbear.py::TestFuzz::test_does_not_crash_on_tuple_expansion_in_except_statement"
] | [] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2022-01-25T16:55:40Z" | mit |
|
PyCQA__flake8-bugbear-230 | diff --git a/README.rst b/README.rst
index 09e87df..7994a6c 100644
--- a/README.rst
+++ b/README.rst
@@ -134,6 +134,9 @@ data available in ``ex``.
**B020**: Loop control variable overrides iterable it iterates
+**B021**: f-string used as docstring. This will be interpreted by python
+as a joined string rather than a docstring.
+
Opinionated warnings
~~~~~~~~~~~~~~~~~~~~
diff --git a/bugbear.py b/bugbear.py
index 5e7ea93..d71a44b 100644
--- a/bugbear.py
+++ b/bugbear.py
@@ -350,11 +350,13 @@ class BugBearVisitor(ast.NodeVisitor):
self.check_for_b902(node)
self.check_for_b006(node)
self.check_for_b018(node)
+ self.check_for_b021(node)
self.generic_visit(node)
def visit_ClassDef(self, node):
self.check_for_b903(node)
self.check_for_b018(node)
+ self.check_for_b021(node)
self.generic_visit(node)
def visit_Try(self, node):
@@ -685,6 +687,16 @@ class BugBearVisitor(ast.NodeVisitor):
):
self.errors.append(B018(subnode.lineno, subnode.col_offset))
+ def check_for_b021(self, node):
+ if (
+ node.body
+ and isinstance(node.body[0], ast.Expr)
+ and isinstance(node.body[0].value, ast.JoinedStr)
+ ):
+ self.errors.append(
+ B021(node.body[0].value.lineno, node.body[0].value.col_offset)
+ )
+
@attr.s
class NameFinder(ast.NodeVisitor):
@@ -892,6 +904,12 @@ B020 = Error(
+ "with each iterable value."
)
)
+B021 = Error(
+ message=(
+ "B021 f-string used as docstring."
+ "This will be interpreted by python as a joined string rather than a docstring."
+ )
+)
# Warnings disabled by default.
B901 = Error(
| PyCQA/flake8-bugbear | 3206da7d3a3ef98f7c2bd38d7b533cb1d65f8a3b | diff --git a/tests/b021.py b/tests/b021.py
new file mode 100644
index 0000000..dd0bb63
--- /dev/null
+++ b/tests/b021.py
@@ -0,0 +1,76 @@
+"""
+Should emit:
+B021 - on lines 14, 22, 30, 38, 46, 54, 62, 70, 73
+"""
+
+VARIABLE = "world"
+
+
+def foo1():
+ """hello world!"""
+
+
+def foo2():
+ f"""hello {VARIABLE}!"""
+
+
+class bar1:
+ """hello world!"""
+
+
+class bar2:
+ f"""hello {VARIABLE}!"""
+
+
+def foo1():
+ """hello world!"""
+
+
+def foo2():
+ f"""hello {VARIABLE}!"""
+
+
+class bar1:
+ """hello world!"""
+
+
+class bar2:
+ f"""hello {VARIABLE}!"""
+
+
+def foo1():
+ "hello world!"
+
+
+def foo2():
+ f"hello {VARIABLE}!"
+
+
+class bar1:
+ "hello world!"
+
+
+class bar2:
+ f"hello {VARIABLE}!"
+
+
+def foo1():
+ "hello world!"
+
+
+def foo2():
+ f"hello {VARIABLE}!"
+
+
+class bar1:
+ "hello world!"
+
+
+class bar2:
+ f"hello {VARIABLE}!"
+
+
+def baz():
+ f"""I'm probably a docstring: {VARIABLE}!"""
+ print(f"""I'm a normal string""")
+ f"""Don't detect me!"""
diff --git a/tests/test_bugbear.py b/tests/test_bugbear.py
index 7e25386..05f9cbf 100644
--- a/tests/test_bugbear.py
+++ b/tests/test_bugbear.py
@@ -30,6 +30,7 @@ from bugbear import (
B017,
B018,
B020,
+ B021,
B901,
B902,
B903,
@@ -262,6 +263,23 @@ class BugbearTestCase(unittest.TestCase):
),
)
+ def test_b021_classes(self):
+ filename = Path(__file__).absolute().parent / "b021.py"
+ bbc = BugBearChecker(filename=str(filename))
+ errors = list(bbc.run())
+ expected = self.errors(
+ B021(14, 4),
+ B021(22, 4),
+ B021(30, 4),
+ B021(38, 4),
+ B021(46, 4),
+ B021(54, 4),
+ B021(62, 4),
+ B021(70, 4),
+ B021(74, 4),
+ )
+ self.assertEqual(errors, expected)
+
def test_b901(self):
filename = Path(__file__).absolute().parent / "b901.py"
bbc = BugBearChecker(filename=str(filename))
| B018 complains about f-strings as docstrings... and it's right! (but a more specific message would be helpful)
```python
CONSTANT = "magic value"
def f():
f"""Return {CONSTANT!r}.""" # warning B018
return CONSTANT
assert f.__doc__ is not None # fails!
```
I was originally reporting this as a bug, but it turns out that f-strings don't work as docstrings! IMO this deserves to be split out into a new B019 check with a more specific message. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_bugbear.py::BugbearTestCase::test_b001",
"tests/test_bugbear.py::BugbearTestCase::test_b002",
"tests/test_bugbear.py::BugbearTestCase::test_b003",
"tests/test_bugbear.py::BugbearTestCase::test_b004",
"tests/test_bugbear.py::BugbearTestCase::test_b005",
"tests/test_bugbear.py::BugbearTestCase::test_b006_b008",
"tests/test_bugbear.py::BugbearTestCase::test_b007",
"tests/test_bugbear.py::BugbearTestCase::test_b008_extended",
"tests/test_bugbear.py::BugbearTestCase::test_b009_b010",
"tests/test_bugbear.py::BugbearTestCase::test_b011",
"tests/test_bugbear.py::BugbearTestCase::test_b012",
"tests/test_bugbear.py::BugbearTestCase::test_b013",
"tests/test_bugbear.py::BugbearTestCase::test_b014",
"tests/test_bugbear.py::BugbearTestCase::test_b015",
"tests/test_bugbear.py::BugbearTestCase::test_b016",
"tests/test_bugbear.py::BugbearTestCase::test_b017",
"tests/test_bugbear.py::BugbearTestCase::test_b018_classes",
"tests/test_bugbear.py::BugbearTestCase::test_b018_functions",
"tests/test_bugbear.py::BugbearTestCase::test_b020",
"tests/test_bugbear.py::BugbearTestCase::test_b021_classes",
"tests/test_bugbear.py::BugbearTestCase::test_b901",
"tests/test_bugbear.py::BugbearTestCase::test_b902",
"tests/test_bugbear.py::BugbearTestCase::test_b902_py38",
"tests/test_bugbear.py::BugbearTestCase::test_b903",
"tests/test_bugbear.py::BugbearTestCase::test_b904",
"tests/test_bugbear.py::BugbearTestCase::test_b950",
"tests/test_bugbear.py::BugbearTestCase::test_selfclean_test_bugbear",
"tests/test_bugbear.py::TestFuzz::test_does_not_crash_on_any_valid_code",
"tests/test_bugbear.py::TestFuzz::test_does_not_crash_on_call_in_except_statement",
"tests/test_bugbear.py::TestFuzz::test_does_not_crash_on_site_code",
"tests/test_bugbear.py::TestFuzz::test_does_not_crash_on_tuple_expansion_in_except_statement"
] | [] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2022-03-17T02:27:46Z" | mit |
|
PyCQA__flake8-bugbear-261 | diff --git a/bugbear.py b/bugbear.py
index 06e598d..e47ede1 100644
--- a/bugbear.py
+++ b/bugbear.py
@@ -155,12 +155,13 @@ class BugBearChecker:
return True
for i in range(2, len(code) + 1):
- if code[:i] in self.options.select:
+ if self.options.select and code[:i] in self.options.select:
return True
# flake8 >=4.0: Also check for codes in extend_select
if (
hasattr(self.options, "extend_select")
+ and self.options.extend_select
and code[:i] in self.options.extend_select
):
return True
| PyCQA/flake8-bugbear | b1e4ef296ec6afb6df788d81db0953cf5fd79566 | diff --git a/tests/test_bugbear.py b/tests/test_bugbear.py
index a974cf4..12469e6 100644
--- a/tests/test_bugbear.py
+++ b/tests/test_bugbear.py
@@ -438,6 +438,16 @@ class BugbearTestCase(unittest.TestCase):
),
)
+ def test_b9_flake8_next_default_options(self):
+ filename = Path(__file__).absolute().parent / "b950.py"
+
+ # in flake8 next, unset select / extend_select will be `None` to
+ # signify the default values
+ mock_options = Namespace(select=None, extend_select=None)
+ bbc = BugBearChecker(filename=str(filename), options=mock_options)
+ errors = list(bbc.run())
+ self.assertEqual(errors, [])
+
def test_selfclean_bugbear(self):
filename = Path(__file__).absolute().parent.parent / "bugbear.py"
proc = subprocess.run(
| `should_warn` is incompatible with flake8 (next)
minimal reproduction (trigger any `B9*` warning with the default settings)
```console
$ rm -rf venv && virtualenv -qq venv && venv/bin/pip install -qq git+https://github.com/pycqa/flake8 git+https://github.com/pycqa/flake8-bugbear && venv/bin/flake8 --config /dev/null - <<< $'class C:\n def __init__(wat): ...'
Traceback (most recent call last):
File "venv/bin/flake8", line 8, in <module>
sys.exit(main())
File "/tmp/y/venv/lib/python3.8/site-packages/flake8/main/cli.py", line 22, in main
app.run(argv)
File "/tmp/y/venv/lib/python3.8/site-packages/flake8/main/application.py", line 336, in run
self._run(argv)
File "/tmp/y/venv/lib/python3.8/site-packages/flake8/main/application.py", line 325, in _run
self.run_checks()
File "/tmp/y/venv/lib/python3.8/site-packages/flake8/main/application.py", line 229, in run_checks
self.file_checker_manager.run()
File "/tmp/y/venv/lib/python3.8/site-packages/flake8/checker.py", line 252, in run
self.run_serial()
File "/tmp/y/venv/lib/python3.8/site-packages/flake8/checker.py", line 237, in run_serial
checker.run_checks()
File "/tmp/y/venv/lib/python3.8/site-packages/flake8/checker.py", line 531, in run_checks
self.run_ast_checks()
File "/tmp/y/venv/lib/python3.8/site-packages/flake8/checker.py", line 435, in run_ast_checks
for (line_number, offset, text, _) in runner:
File "/tmp/y/venv/lib/python3.8/site-packages/bugbear.py", line 61, in run
if self.should_warn(e.message[:4]):
File "/tmp/y/venv/lib/python3.8/site-packages/bugbear.py", line 158, in should_warn
if code[:i] in self.options.select:
TypeError: argument of type 'NoneType' is not iterable
```
looking at the code, you should be able to delete `should_warn` entirely and rely on `extend-select` (and delete `load_file` while you're at it!) | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_bugbear.py::BugbearTestCase::test_b9_flake8_next_default_options"
] | [
"tests/test_bugbear.py::BugbearTestCase::test_b001",
"tests/test_bugbear.py::BugbearTestCase::test_b002",
"tests/test_bugbear.py::BugbearTestCase::test_b003",
"tests/test_bugbear.py::BugbearTestCase::test_b004",
"tests/test_bugbear.py::BugbearTestCase::test_b005",
"tests/test_bugbear.py::BugbearTestCase::test_b006_b008",
"tests/test_bugbear.py::BugbearTestCase::test_b007",
"tests/test_bugbear.py::BugbearTestCase::test_b008_extended",
"tests/test_bugbear.py::BugbearTestCase::test_b009_b010",
"tests/test_bugbear.py::BugbearTestCase::test_b011",
"tests/test_bugbear.py::BugbearTestCase::test_b012",
"tests/test_bugbear.py::BugbearTestCase::test_b013",
"tests/test_bugbear.py::BugbearTestCase::test_b014",
"tests/test_bugbear.py::BugbearTestCase::test_b015",
"tests/test_bugbear.py::BugbearTestCase::test_b016",
"tests/test_bugbear.py::BugbearTestCase::test_b017",
"tests/test_bugbear.py::BugbearTestCase::test_b018_classes",
"tests/test_bugbear.py::BugbearTestCase::test_b018_functions",
"tests/test_bugbear.py::BugbearTestCase::test_b019",
"tests/test_bugbear.py::BugbearTestCase::test_b020",
"tests/test_bugbear.py::BugbearTestCase::test_b021_classes",
"tests/test_bugbear.py::BugbearTestCase::test_b022",
"tests/test_bugbear.py::BugbearTestCase::test_b901",
"tests/test_bugbear.py::BugbearTestCase::test_b902",
"tests/test_bugbear.py::BugbearTestCase::test_b902_py38",
"tests/test_bugbear.py::BugbearTestCase::test_b903",
"tests/test_bugbear.py::BugbearTestCase::test_b904",
"tests/test_bugbear.py::BugbearTestCase::test_b950",
"tests/test_bugbear.py::BugbearTestCase::test_b9_extend_select",
"tests/test_bugbear.py::BugbearTestCase::test_b9_select",
"tests/test_bugbear.py::BugbearTestCase::test_selfclean_test_bugbear",
"tests/test_bugbear.py::TestFuzz::test_does_not_crash_on_any_valid_code",
"tests/test_bugbear.py::TestFuzz::test_does_not_crash_on_call_in_except_statement",
"tests/test_bugbear.py::TestFuzz::test_does_not_crash_on_site_code",
"tests/test_bugbear.py::TestFuzz::test_does_not_crash_on_tuple_expansion_in_except_statement"
] | {
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
} | "2022-06-12T16:06:43Z" | mit |
|
PyCQA__flake8-bugbear-284 | diff --git a/README.rst b/README.rst
index 63e3fb5..c12f73e 100644
--- a/README.rst
+++ b/README.rst
@@ -156,6 +156,10 @@ the loop, because `late-binding closures are a classic gotcha
**B024**: Abstract base class with no abstract method. Remember to use @abstractmethod, @abstractclassmethod, and/or @abstractproperty decorators.
+**B025**: ``try-except`` block with duplicate exceptions found.
+This check identifies exception types that are specified in multiple ``except``
+clauses. The first specification is the only one ever considered, so all others can be removed.
+
Opinionated warnings
~~~~~~~~~~~~~~~~~~~~
diff --git a/bugbear.py b/bugbear.py
index 3db1e0d..7f95e2e 100644
--- a/bugbear.py
+++ b/bugbear.py
@@ -421,6 +421,7 @@ class BugBearVisitor(ast.NodeVisitor):
def visit_Try(self, node):
self.check_for_b012(node)
+ self.check_for_b025(node)
self.generic_visit(node)
def visit_Compare(self, node):
@@ -837,6 +838,24 @@ class BugBearVisitor(ast.NodeVisitor):
):
self.errors.append(B022(node.lineno, node.col_offset))
+ def check_for_b025(self, node):
+ seen = []
+ for handler in node.handlers:
+ if isinstance(handler.type, (ast.Name, ast.Attribute)):
+ name = ".".join(compose_call_path(handler.type))
+ seen.append(name)
+ elif isinstance(handler.type, ast.Tuple):
+ # to avoid checking the same as B014, remove duplicates per except
+ uniques = set()
+ for entry in handler.type.elts:
+ name = ".".join(compose_call_path(entry))
+ uniques.add(name)
+ seen.extend(uniques)
+ # sort to have a deterministic output
+ duplicates = sorted(set(x for x in seen if seen.count(x) > 1))
+ for duplicate in duplicates:
+ self.errors.append(B025(node.lineno, node.col_offset, vars=(duplicate,)))
+
def compose_call_path(node):
if isinstance(node, ast.Attribute):
@@ -1178,6 +1197,12 @@ B024 = Error(
" decorators."
)
)
+B025 = Error(
+ message=(
+ "B025 Exception `{0}` has been caught multiple times. Only the first except"
+ " will be considered and all other except catches can be safely removed."
+ )
+)
# Warnings disabled by default.
B901 = Error(
| PyCQA/flake8-bugbear | 4c34177d04953cd124006379cb503114f382e0d0 | diff --git a/tests/b025.py b/tests/b025.py
new file mode 100644
index 0000000..085f82f
--- /dev/null
+++ b/tests/b025.py
@@ -0,0 +1,38 @@
+"""
+Should emit:
+B025 - on lines 15, 22, 31
+"""
+
+import pickle
+
+try:
+ a = 1
+except ValueError:
+ a = 2
+finally:
+ a = 3
+
+try:
+ a = 1
+except ValueError:
+ a = 2
+except ValueError:
+ a = 2
+
+try:
+ a = 1
+except pickle.PickleError:
+ a = 2
+except ValueError:
+ a = 2
+except pickle.PickleError:
+ a = 2
+
+try:
+ a = 1
+except (ValueError, TypeError):
+ a = 2
+except ValueError:
+ a = 2
+except (OSError, TypeError):
+ a = 2
diff --git a/tests/test_bugbear.py b/tests/test_bugbear.py
index 5db013b..b09bb48 100644
--- a/tests/test_bugbear.py
+++ b/tests/test_bugbear.py
@@ -35,6 +35,7 @@ from bugbear import (
B022,
B023,
B024,
+ B025,
B901,
B902,
B903,
@@ -366,6 +367,20 @@ class BugbearTestCase(unittest.TestCase):
)
self.assertEqual(errors, expected)
+ def test_b025(self):
+ filename = Path(__file__).absolute().parent / "b025.py"
+ bbc = BugBearChecker(filename=str(filename))
+ errors = list(bbc.run())
+ self.assertEqual(
+ errors,
+ self.errors(
+ B025(15, 0, vars=("ValueError",)),
+ B025(22, 0, vars=("pickle.PickleError",)),
+ B025(31, 0, vars=("TypeError",)),
+ B025(31, 0, vars=("ValueError",)),
+ ),
+ )
+
def test_b901(self):
filename = Path(__file__).absolute().parent / "b901.py"
bbc = BugBearChecker(filename=str(filename))
| New check which find duplicate except clauses
flake8-bugbear already find duplicate exeptions in the same tuple, but across different except's this is not done
**Examples**:
```python
try:
pass
except ValueError:
pass
except ValueError:
pass
```
```python
try:
pass
except (ValueError, TypeError):
pass
except (ValueError, UnicodeError):
pass
```
I'm happy tp contribute this check 😄 | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_bugbear.py::BugbearTestCase::test_b001",
"tests/test_bugbear.py::BugbearTestCase::test_b002",
"tests/test_bugbear.py::BugbearTestCase::test_b003",
"tests/test_bugbear.py::BugbearTestCase::test_b004",
"tests/test_bugbear.py::BugbearTestCase::test_b005",
"tests/test_bugbear.py::BugbearTestCase::test_b006_b008",
"tests/test_bugbear.py::BugbearTestCase::test_b007",
"tests/test_bugbear.py::BugbearTestCase::test_b008_extended",
"tests/test_bugbear.py::BugbearTestCase::test_b009_b010",
"tests/test_bugbear.py::BugbearTestCase::test_b011",
"tests/test_bugbear.py::BugbearTestCase::test_b012",
"tests/test_bugbear.py::BugbearTestCase::test_b013",
"tests/test_bugbear.py::BugbearTestCase::test_b014",
"tests/test_bugbear.py::BugbearTestCase::test_b015",
"tests/test_bugbear.py::BugbearTestCase::test_b016",
"tests/test_bugbear.py::BugbearTestCase::test_b017",
"tests/test_bugbear.py::BugbearTestCase::test_b018_classes",
"tests/test_bugbear.py::BugbearTestCase::test_b018_functions",
"tests/test_bugbear.py::BugbearTestCase::test_b019",
"tests/test_bugbear.py::BugbearTestCase::test_b020",
"tests/test_bugbear.py::BugbearTestCase::test_b021_classes",
"tests/test_bugbear.py::BugbearTestCase::test_b022",
"tests/test_bugbear.py::BugbearTestCase::test_b023",
"tests/test_bugbear.py::BugbearTestCase::test_b024",
"tests/test_bugbear.py::BugbearTestCase::test_b025",
"tests/test_bugbear.py::BugbearTestCase::test_b901",
"tests/test_bugbear.py::BugbearTestCase::test_b902",
"tests/test_bugbear.py::BugbearTestCase::test_b902_py38",
"tests/test_bugbear.py::BugbearTestCase::test_b903",
"tests/test_bugbear.py::BugbearTestCase::test_b904",
"tests/test_bugbear.py::BugbearTestCase::test_b950",
"tests/test_bugbear.py::BugbearTestCase::test_b9_extend_select",
"tests/test_bugbear.py::BugbearTestCase::test_b9_flake8_next_default_options",
"tests/test_bugbear.py::BugbearTestCase::test_b9_select",
"tests/test_bugbear.py::BugbearTestCase::test_selfclean_test_bugbear",
"tests/test_bugbear.py::TestFuzz::test_does_not_crash_on_any_valid_code",
"tests/test_bugbear.py::TestFuzz::test_does_not_crash_on_call_in_except_statement",
"tests/test_bugbear.py::TestFuzz::test_does_not_crash_on_site_code",
"tests/test_bugbear.py::TestFuzz::test_does_not_crash_on_tuple_expansion_in_except_statement"
] | [] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2022-09-10T20:35:55Z" | mit |
|
PyCQA__flake8-bugbear-287 | diff --git a/README.rst b/README.rst
index d7981f7..b7d4f38 100644
--- a/README.rst
+++ b/README.rst
@@ -160,6 +160,13 @@ the loop, because `late-binding closures are a classic gotcha
This check identifies exception types that are specified in multiple ``except``
clauses. The first specification is the only one ever considered, so all others can be removed.
+**B026**: Star-arg unpacking after a keyword argument is strongly discouraged, because
+it only works when the keyword parameter is declared after all parameters supplied by
+the unpacked sequence, and this change of ordering can surprise and mislead readers.
+There was `cpython discussion of disallowing this syntax
+<https://github.com/python/cpython/issues/82741>`_, but legacy usage and parser
+limitations make it difficult.
+
Opinionated warnings
~~~~~~~~~~~~~~~~~~~~
diff --git a/bugbear.py b/bugbear.py
index 4b742b7..cc92b92 100644
--- a/bugbear.py
+++ b/bugbear.py
@@ -354,6 +354,8 @@ class BugBearVisitor(ast.NodeVisitor):
):
self.errors.append(B010(node.lineno, node.col_offset))
+ self.check_for_b026(node)
+
self.generic_visit(node)
def visit_Assign(self, node):
@@ -641,6 +643,22 @@ class BugBearVisitor(ast.NodeVisitor):
self.errors.append(B024(node.lineno, node.col_offset, vars=(node.name,)))
+ def check_for_b026(self, call: ast.Call):
+ if not call.keywords:
+ return
+
+ starreds = [arg for arg in call.args if isinstance(arg, ast.Starred)]
+ if not starreds:
+ return
+
+ first_keyword = call.keywords[0].value
+ for starred in starreds:
+ if (starred.lineno, starred.col_offset) > (
+ first_keyword.lineno,
+ first_keyword.col_offset,
+ ):
+ self.errors.append(B026(starred.lineno, starred.col_offset))
+
def _get_assigned_names(self, loop_node):
loop_targets = (ast.For, ast.AsyncFor, ast.comprehension)
for node in children_in_scope(loop_node):
@@ -1203,6 +1221,14 @@ B025 = Error(
" will be considered and all other except catches can be safely removed."
)
)
+B026 = Error(
+ message=(
+ "B026 Star-arg unpacking after a keyword argument is strongly discouraged, "
+ "because it only works when the keyword parameter is declared after all "
+ "parameters supplied by the unpacked sequence, and this change of ordering can "
+ "surprise and mislead readers."
+ )
+)
# Warnings disabled by default.
B901 = Error(
| PyCQA/flake8-bugbear | 3f3fd33fab17c569f0fdbd6291539a7436bee4b9 | diff --git a/tests/b026.py b/tests/b026.py
new file mode 100644
index 0000000..ada19b4
--- /dev/null
+++ b/tests/b026.py
@@ -0,0 +1,21 @@
+"""
+Should emit:
+B026 - on lines 16, 17, 18, 19, 20, 21
+"""
+
+
+def foo(bar, baz, bam):
+ pass
+
+
+bar_baz = ["bar", "baz"]
+
+foo("bar", "baz", bam="bam")
+foo("bar", baz="baz", bam="bam")
+foo(bar="bar", baz="baz", bam="bam")
+foo(bam="bam", *["bar", "baz"])
+foo(bam="bam", *bar_baz)
+foo(baz="baz", bam="bam", *["bar"])
+foo(bar="bar", baz="baz", bam="bam", *[])
+foo(bam="bam", *["bar"], *["baz"])
+foo(*["bar"], bam="bam", *["baz"])
diff --git a/tests/test_bugbear.py b/tests/test_bugbear.py
index b09bb48..28eb964 100644
--- a/tests/test_bugbear.py
+++ b/tests/test_bugbear.py
@@ -36,6 +36,7 @@ from bugbear import (
B023,
B024,
B025,
+ B026,
B901,
B902,
B903,
@@ -381,6 +382,23 @@ class BugbearTestCase(unittest.TestCase):
),
)
+ def test_b026(self):
+ filename = Path(__file__).absolute().parent / "b026.py"
+ bbc = BugBearChecker(filename=str(filename))
+ errors = list(bbc.run())
+ self.assertEqual(
+ errors,
+ self.errors(
+ B026(16, 15),
+ B026(17, 15),
+ B026(18, 26),
+ B026(19, 37),
+ B026(20, 15),
+ B026(20, 25),
+ B026(21, 25),
+ ),
+ )
+
def test_b901(self):
filename = Path(__file__).absolute().parent / "b901.py"
bbc = BugBearChecker(filename=str(filename))
| Proposed check: don't allow argument unpacking in a call after a keyword argument
Imagine a function like
```py
def foo(bar, baz):
pass
```
The following call is a syntactically incorrect:
```py
foo(baz="baz", "bar")
```
However, with unpacking the following is allowed:
```py
foo(baz="baz", *["bar"])
```
[However](https://github.com/python/cpython/issues/82741#issuecomment-1093845041),
> [T]he resulting argument binding is awkward, and almost never does what you want/expect it to
It was [not ruled a bug or a behavior that can or should be deprecated](https://github.com/python/cpython/issues/82741#issuecomment-1093845049). Still, I think in most cases this is probably an oversight and should not be used.
If we want this check, I would be willing to contribute a patch. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_bugbear.py::BugbearTestCase::test_b001",
"tests/test_bugbear.py::BugbearTestCase::test_b002",
"tests/test_bugbear.py::BugbearTestCase::test_b003",
"tests/test_bugbear.py::BugbearTestCase::test_b004",
"tests/test_bugbear.py::BugbearTestCase::test_b005",
"tests/test_bugbear.py::BugbearTestCase::test_b006_b008",
"tests/test_bugbear.py::BugbearTestCase::test_b007",
"tests/test_bugbear.py::BugbearTestCase::test_b008_extended",
"tests/test_bugbear.py::BugbearTestCase::test_b009_b010",
"tests/test_bugbear.py::BugbearTestCase::test_b011",
"tests/test_bugbear.py::BugbearTestCase::test_b012",
"tests/test_bugbear.py::BugbearTestCase::test_b013",
"tests/test_bugbear.py::BugbearTestCase::test_b014",
"tests/test_bugbear.py::BugbearTestCase::test_b015",
"tests/test_bugbear.py::BugbearTestCase::test_b016",
"tests/test_bugbear.py::BugbearTestCase::test_b017",
"tests/test_bugbear.py::BugbearTestCase::test_b018_classes",
"tests/test_bugbear.py::BugbearTestCase::test_b018_functions",
"tests/test_bugbear.py::BugbearTestCase::test_b019",
"tests/test_bugbear.py::BugbearTestCase::test_b020",
"tests/test_bugbear.py::BugbearTestCase::test_b021_classes",
"tests/test_bugbear.py::BugbearTestCase::test_b022",
"tests/test_bugbear.py::BugbearTestCase::test_b023",
"tests/test_bugbear.py::BugbearTestCase::test_b024",
"tests/test_bugbear.py::BugbearTestCase::test_b025",
"tests/test_bugbear.py::BugbearTestCase::test_b026",
"tests/test_bugbear.py::BugbearTestCase::test_b901",
"tests/test_bugbear.py::BugbearTestCase::test_b902",
"tests/test_bugbear.py::BugbearTestCase::test_b902_py38",
"tests/test_bugbear.py::BugbearTestCase::test_b903",
"tests/test_bugbear.py::BugbearTestCase::test_b904",
"tests/test_bugbear.py::BugbearTestCase::test_b950",
"tests/test_bugbear.py::BugbearTestCase::test_b9_extend_select",
"tests/test_bugbear.py::BugbearTestCase::test_b9_flake8_next_default_options",
"tests/test_bugbear.py::BugbearTestCase::test_b9_select",
"tests/test_bugbear.py::BugbearTestCase::test_selfclean_test_bugbear",
"tests/test_bugbear.py::TestFuzz::test_does_not_crash_on_any_valid_code",
"tests/test_bugbear.py::TestFuzz::test_does_not_crash_on_call_in_except_statement",
"tests/test_bugbear.py::TestFuzz::test_does_not_crash_on_site_code",
"tests/test_bugbear.py::TestFuzz::test_does_not_crash_on_tuple_expansion_in_except_statement"
] | [] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2022-09-20T06:12:34Z" | mit |
|
PyCQA__flake8-bugbear-316 | diff --git a/README.rst b/README.rst
index 498b000..53a3dab 100644
--- a/README.rst
+++ b/README.rst
@@ -205,6 +205,10 @@ to raise a ``ValueError`` if the arguments are exhausted at differing lengths. T
was added in Python 3.10, so don't enable this flag for code that should work on <3.10.
For more information: https://peps.python.org/pep-0618/
+**B906**: ``visit_`` function with no further call to a ``visit`` function. This is often an error, and will stop the visitor from recursing into the subnodes of a visited node. Consider adding a call ``self.generic_visit(node)`` at the end of the function.
+Will only trigger on function names where the part after ``visit_`` is a valid ``ast`` type with a non-empty ``_fields`` attribute.
+This is meant to be enabled by developers writing visitors using the ``ast`` module, such as flake8 plugin writers.
+
**B950**: Line too long. This is a pragmatic equivalent of
``pycodestyle``'s ``E501``: it considers "max-line-length" but only triggers
when the value has been exceeded by **more than 10%**. You will no
@@ -302,6 +306,11 @@ MIT
Change Log
----------
+Future
+~~~~~~~~~
+
+* Add B906: ``visit_`` function with no further calls to a ``visit`` function. (#313)
+
22.12.6
~~~~~~~~~
diff --git a/bugbear.py b/bugbear.py
index 2d2b7cd..90d238a 100644
--- a/bugbear.py
+++ b/bugbear.py
@@ -413,6 +413,7 @@ class BugBearVisitor(ast.NodeVisitor):
self.check_for_b018(node)
self.check_for_b019(node)
self.check_for_b021(node)
+ self.check_for_b906(node)
self.generic_visit(node)
def visit_ClassDef(self, node):
@@ -969,6 +970,27 @@ class BugBearVisitor(ast.NodeVisitor):
):
self.errors.append(B905(node.lineno, node.col_offset))
+ def check_for_b906(self, node: ast.FunctionDef):
+ if not node.name.startswith("visit_"):
+ return
+
+ # extract what's visited, only error if it's a valid ast subclass
+ # with a non-empty _fields attribute - which is what's iterated over in
+ # ast.NodeVisitor.generic_visit
+ class_name = node.name[len("visit_") :]
+ class_type = getattr(ast, class_name, None)
+ if class_type is None or not getattr(class_type, "_fields", None):
+ return
+
+ for n in itertools.chain.from_iterable(ast.walk(nn) for nn in node.body):
+ if isinstance(n, ast.Call) and (
+ (isinstance(n.func, ast.Attribute) and "visit" in n.func.attr)
+ or (isinstance(n.func, ast.Name) and "visit" in n.func.id)
+ ):
+ break
+ else:
+ self.errors.append(B906(node.lineno, node.col_offset))
+
def compose_call_path(node):
if isinstance(node, ast.Attribute):
@@ -990,7 +1012,7 @@ class NameFinder(ast.NodeVisitor):
names = attr.ib(default=attr.Factory(dict))
- def visit_Name(self, node):
+ def visit_Name(self, node): # noqa: B906 # names don't contain other names
self.names.setdefault(node.id, []).append(node)
def visit(self, node):
@@ -1054,7 +1076,7 @@ class FuntionDefDefaultsVisitor(ast.NodeVisitor):
# Check for nested functions.
self.generic_visit(node)
- def visit_Lambda(self, node):
+ def visit_Lambda(self, node): # noqa: B906
# Don't recurse into lambda expressions
# as they are evaluated at call time.
pass
@@ -1371,6 +1393,14 @@ B904 = Error(
B905 = Error(message="B905 `zip()` without an explicit `strict=` parameter.")
+B906 = Error(
+ message=(
+ "B906 `visit_` function with no further calls to a visit function, which might"
+ " prevent the `ast` visitor from properly visiting all nodes."
+ " Consider adding a call to `self.generic_visit(node)`."
+ )
+)
+
B950 = Error(message="B950 line too long ({} > {} characters)")
-disabled_by_default = ["B901", "B902", "B903", "B904", "B905", "B950"]
+disabled_by_default = ["B901", "B902", "B903", "B904", "B905", "B906", "B950"]
| PyCQA/flake8-bugbear | 71410094e3c34b23e8c12c081b9a7901c2cc6ffe | diff --git a/tests/b906.py b/tests/b906.py
new file mode 100644
index 0000000..a4bf0d1
--- /dev/null
+++ b/tests/b906.py
@@ -0,0 +1,55 @@
+import ast
+
+# error if method name starts with `visit_`, the type is a valid `ast` type
+# which has subfields, and contains no call to a method name containing `visit`
+# anywhere in it's body
+
+# error
+def visit_For():
+ ...
+
+
+# has call to visit function
+def visit_For():
+ foo_visit_bar()
+
+
+# has call to visit method
+def visit_While():
+ foo.bar_visit_bar()
+
+
+# this visit call clearly won't run, but is treated as safe
+def visit_If():
+ def foo():
+ a_visit_function()
+
+
+# not a valid AST class, no error
+def visit_foo():
+ ...
+
+
+# Break has no subfields to visit, so no error
+def visit_Break():
+ ...
+
+
+# explicitly check `visit` and `generic_visit`
+# doesn't start with _visit, safe
+def visit():
+ ...
+
+
+# doesn't start with _visit, safe
+def generic_visit():
+ ...
+
+
+# check no crash on short name
+def a():
+ ...
+
+
+def visit_():
+ ...
diff --git a/tests/test_bugbear.py b/tests/test_bugbear.py
index bfd536c..e3ee667 100644
--- a/tests/test_bugbear.py
+++ b/tests/test_bugbear.py
@@ -43,6 +43,7 @@ from bugbear import (
B903,
B904,
B905,
+ B906,
B950,
BugBearChecker,
BugBearVisitor,
@@ -501,6 +502,15 @@ class BugbearTestCase(unittest.TestCase):
]
self.assertEqual(errors, self.errors(*expected))
+ def test_b906(self):
+ filename = Path(__file__).absolute().parent / "b906.py"
+ bbc = BugBearChecker(filename=str(filename))
+ errors = list(bbc.run())
+ expected = [
+ B906(8, 0),
+ ]
+ self.assertEqual(errors, self.errors(*expected))
+
def test_b950(self):
filename = Path(__file__).absolute().parent / "b950.py"
bbc = BugBearChecker(filename=str(filename))
| New check: visit_ function with no generic_visit/visit
This is kind of super niche, and mostly just of interest to flake8 plugin writers in particular, but I accidentally forgot to continue `visit`'ing in a couple functions I wrote recently in flake8-trio and realized it'd be incredibly handy - and very easy to implement - an optional check where if a function name matches `visit_*` it raises a warning if there's no `self.visit(...)` or `self.generic_visit(...)` within it's body.
I imagine it'd be nice to have that in the CI for flake8-bugbear itself as well, even though your structure makes it less likely than it is for flake8-trio currently. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_bugbear.py::BugbearTestCase::test_b001",
"tests/test_bugbear.py::BugbearTestCase::test_b002",
"tests/test_bugbear.py::BugbearTestCase::test_b003",
"tests/test_bugbear.py::BugbearTestCase::test_b004",
"tests/test_bugbear.py::BugbearTestCase::test_b005",
"tests/test_bugbear.py::BugbearTestCase::test_b006_b008",
"tests/test_bugbear.py::BugbearTestCase::test_b007",
"tests/test_bugbear.py::BugbearTestCase::test_b008_extended",
"tests/test_bugbear.py::BugbearTestCase::test_b009_b010",
"tests/test_bugbear.py::BugbearTestCase::test_b011",
"tests/test_bugbear.py::BugbearTestCase::test_b012",
"tests/test_bugbear.py::BugbearTestCase::test_b013",
"tests/test_bugbear.py::BugbearTestCase::test_b014",
"tests/test_bugbear.py::BugbearTestCase::test_b015",
"tests/test_bugbear.py::BugbearTestCase::test_b016",
"tests/test_bugbear.py::BugbearTestCase::test_b017",
"tests/test_bugbear.py::BugbearTestCase::test_b018_classes",
"tests/test_bugbear.py::BugbearTestCase::test_b018_functions",
"tests/test_bugbear.py::BugbearTestCase::test_b019",
"tests/test_bugbear.py::BugbearTestCase::test_b020",
"tests/test_bugbear.py::BugbearTestCase::test_b021_classes",
"tests/test_bugbear.py::BugbearTestCase::test_b022",
"tests/test_bugbear.py::BugbearTestCase::test_b023",
"tests/test_bugbear.py::BugbearTestCase::test_b024",
"tests/test_bugbear.py::BugbearTestCase::test_b025",
"tests/test_bugbear.py::BugbearTestCase::test_b026",
"tests/test_bugbear.py::BugbearTestCase::test_b027",
"tests/test_bugbear.py::BugbearTestCase::test_b901",
"tests/test_bugbear.py::BugbearTestCase::test_b902",
"tests/test_bugbear.py::BugbearTestCase::test_b902_py38",
"tests/test_bugbear.py::BugbearTestCase::test_b903",
"tests/test_bugbear.py::BugbearTestCase::test_b904",
"tests/test_bugbear.py::BugbearTestCase::test_b906",
"tests/test_bugbear.py::BugbearTestCase::test_b950",
"tests/test_bugbear.py::BugbearTestCase::test_b9_extend_select",
"tests/test_bugbear.py::BugbearTestCase::test_b9_flake8_next_default_options",
"tests/test_bugbear.py::BugbearTestCase::test_b9_select",
"tests/test_bugbear.py::BugbearTestCase::test_selfclean_test_bugbear",
"tests/test_bugbear.py::TestFuzz::test_does_not_crash_on_any_valid_code",
"tests/test_bugbear.py::TestFuzz::test_does_not_crash_on_call_in_except_statement",
"tests/test_bugbear.py::TestFuzz::test_does_not_crash_on_site_code",
"tests/test_bugbear.py::TestFuzz::test_does_not_crash_on_tuple_expansion_in_except_statement"
] | [] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2022-12-07T13:25:37Z" | mit |
|
PyCQA__flake8-bugbear-342 | diff --git a/README.rst b/README.rst
index fe72e3c..832cbd9 100644
--- a/README.rst
+++ b/README.rst
@@ -173,6 +173,10 @@ limitations make it difficult.
**B027**: Empty method in abstract base class, but has no abstract decorator. Consider adding @abstractmethod.
+**BO28**: No explicit stacklevel keyword argument found. The warn method from the warnings module uses a
+stacklevel of 1 by default. This will only show a stack trace for the line on which the warn method is called.
+It is therefore recommended to use a stacklevel of 2 or greater to provide more information to the user.
+
Opinionated warnings
~~~~~~~~~~~~~~~~~~~~
@@ -320,6 +324,7 @@ Future
``ast.Str`` nodes are all deprecated, but may still be used by some codebases in
order to maintain backwards compatibility with Python 3.7.
* B016: Warn when raising f-strings.
+* Add B028: Check for an explicit stacklevel keyword argument on the warn method from the warnings module.
23.1.20
~~~~~~~~~
diff --git a/bugbear.py b/bugbear.py
index a6b883b..edd4faf 100644
--- a/bugbear.py
+++ b/bugbear.py
@@ -360,6 +360,7 @@ class BugBearVisitor(ast.NodeVisitor):
self.check_for_b026(node)
self.check_for_b905(node)
+ self.check_for_b028(node)
self.generic_visit(node)
def visit_Module(self, node):
@@ -1146,6 +1147,16 @@ class BugBearVisitor(ast.NodeVisitor):
# if no pre-mark or variable detected, reset state
current_mark = variable = None
+ def check_for_b028(self, node):
+ if (
+ isinstance(node.func, ast.Attribute)
+ and node.func.attr == "warn"
+ and isinstance(node.func.value, ast.Name)
+ and node.func.value.id == "warnings"
+ and not any(kw.arg == "stacklevel" for kw in node.keywords)
+ ):
+ self.errors.append(B028(node.lineno, node.col_offset))
+
def compose_call_path(node):
if isinstance(node, ast.Attribute):
@@ -1510,6 +1521,15 @@ B027 = Error(
" decorator. Consider adding @abstractmethod."
)
)
+B028 = Error(
+ message=(
+ "B028 No explicit stacklevel keyword argument found. The warn method from the"
+ " warnings module uses a stacklevel of 1 by default. This will only show a"
+ " stack trace for the line on which the warn method is called."
+ " It is therefore recommended to use a stacklevel of 2 or"
+ " greater to provide more information to the user."
+ )
+)
# Warnings disabled by default.
B901 = Error(
| PyCQA/flake8-bugbear | a2e0c951146300f507c11e4f2bf7d22df7368129 | diff --git a/tests/b028.py b/tests/b028.py
new file mode 100644
index 0000000..a2915f2
--- /dev/null
+++ b/tests/b028.py
@@ -0,0 +1,11 @@
+import warnings
+
+"""
+Should emit:
+B028 - on lines 8 and 9
+"""
+
+warnings.warn(DeprecationWarning("test"))
+warnings.warn(DeprecationWarning("test"), source=None)
+warnings.warn(DeprecationWarning("test"), source=None, stacklevel=2)
+warnings.warn(DeprecationWarning("test"), stacklevel=1)
diff --git a/tests/test_bugbear.py b/tests/test_bugbear.py
index 0b91a06..0f5f283 100644
--- a/tests/test_bugbear.py
+++ b/tests/test_bugbear.py
@@ -39,6 +39,7 @@ from bugbear import (
B025,
B026,
B027,
+ B028,
B901,
B902,
B903,
@@ -430,6 +431,13 @@ class BugbearTestCase(unittest.TestCase):
)
self.assertEqual(errors, expected)
+ def test_b028(self):
+ filename = Path(__file__).absolute().parent / "b028.py"
+ bbc = BugBearChecker(filename=str(filename))
+ errors = list(bbc.run())
+ expected = self.errors(B028(8, 0), B028(9, 0))
+ self.assertEqual(errors, expected)
+
@unittest.skipIf(sys.version_info < (3, 8), "not implemented for <3.8")
def test_b907(self):
filename = Path(__file__).absolute().parent / "b907.py"
| Require warnings.warn stacklevel argument as 2+
Calling [`warnings.warn()`](https://docs.python.org/3/library/warnings.html#warnings.warn) without a `stacklevel`, or a `stacklevel` value of <2, is nearly always a mistake. Doing so flags the warning inside the called function, rather than the caller, making it hard to fix the warning.
flake8-bugbear could detect such invocations of `warnings.warn()`.
This issue inspired by @asottile's video of the day: https://www.youtube.com/watch?v=CtFdXBEwYfk . This is also something I've seen recur as a review point in Django PR's. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_bugbear.py::BugbearTestCase::test_b001",
"tests/test_bugbear.py::BugbearTestCase::test_b002",
"tests/test_bugbear.py::BugbearTestCase::test_b003",
"tests/test_bugbear.py::BugbearTestCase::test_b004",
"tests/test_bugbear.py::BugbearTestCase::test_b005",
"tests/test_bugbear.py::BugbearTestCase::test_b006_b008",
"tests/test_bugbear.py::BugbearTestCase::test_b007",
"tests/test_bugbear.py::BugbearTestCase::test_b008_extended",
"tests/test_bugbear.py::BugbearTestCase::test_b009_b010",
"tests/test_bugbear.py::BugbearTestCase::test_b011",
"tests/test_bugbear.py::BugbearTestCase::test_b012",
"tests/test_bugbear.py::BugbearTestCase::test_b013",
"tests/test_bugbear.py::BugbearTestCase::test_b014",
"tests/test_bugbear.py::BugbearTestCase::test_b015",
"tests/test_bugbear.py::BugbearTestCase::test_b016",
"tests/test_bugbear.py::BugbearTestCase::test_b017",
"tests/test_bugbear.py::BugbearTestCase::test_b018_classes",
"tests/test_bugbear.py::BugbearTestCase::test_b018_functions",
"tests/test_bugbear.py::BugbearTestCase::test_b018_modules",
"tests/test_bugbear.py::BugbearTestCase::test_b019",
"tests/test_bugbear.py::BugbearTestCase::test_b020",
"tests/test_bugbear.py::BugbearTestCase::test_b021_classes",
"tests/test_bugbear.py::BugbearTestCase::test_b022",
"tests/test_bugbear.py::BugbearTestCase::test_b023",
"tests/test_bugbear.py::BugbearTestCase::test_b024",
"tests/test_bugbear.py::BugbearTestCase::test_b025",
"tests/test_bugbear.py::BugbearTestCase::test_b026",
"tests/test_bugbear.py::BugbearTestCase::test_b027",
"tests/test_bugbear.py::BugbearTestCase::test_b028",
"tests/test_bugbear.py::BugbearTestCase::test_b901",
"tests/test_bugbear.py::BugbearTestCase::test_b902",
"tests/test_bugbear.py::BugbearTestCase::test_b902_py38",
"tests/test_bugbear.py::BugbearTestCase::test_b903",
"tests/test_bugbear.py::BugbearTestCase::test_b904",
"tests/test_bugbear.py::BugbearTestCase::test_b906",
"tests/test_bugbear.py::BugbearTestCase::test_b907",
"tests/test_bugbear.py::BugbearTestCase::test_b907_format_specifier_permutations",
"tests/test_bugbear.py::BugbearTestCase::test_b950",
"tests/test_bugbear.py::BugbearTestCase::test_b9_extend_select",
"tests/test_bugbear.py::BugbearTestCase::test_b9_flake8_next_default_options",
"tests/test_bugbear.py::BugbearTestCase::test_b9_select",
"tests/test_bugbear.py::BugbearTestCase::test_selfclean_test_bugbear",
"tests/test_bugbear.py::TestFuzz::test_does_not_crash_on_any_valid_code",
"tests/test_bugbear.py::TestFuzz::test_does_not_crash_on_call_in_except_statement",
"tests/test_bugbear.py::TestFuzz::test_does_not_crash_on_site_code",
"tests/test_bugbear.py::TestFuzz::test_does_not_crash_on_tuple_expansion_in_except_statement"
] | [] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2023-01-30T20:58:09Z" | mit |
|
PyCQA__flake8-bugbear-346 | diff --git a/README.rst b/README.rst
index e2e821c..8fe5020 100644
--- a/README.rst
+++ b/README.rst
@@ -179,6 +179,8 @@ It is therefore recommended to use a stacklevel of 2 or greater to provide more
**B029**: Using ``except: ()`` with an empty tuple does not handle/catch anything. Add exceptions to handle.
+**B030**: Except handlers should only be exception classes or tuples of exception classes.
+
Opinionated warnings
~~~~~~~~~~~~~~~~~~~~
diff --git a/bugbear.py b/bugbear.py
index 12d4718..7f9f80b 100644
--- a/bugbear.py
+++ b/bugbear.py
@@ -189,6 +189,51 @@ def _is_identifier(arg):
return re.match(r"^[A-Za-z_][A-Za-z0-9_]*$", arg.s) is not None
+def _flatten_excepthandler(node):
+ if isinstance(node, ast.Tuple):
+ for elt in node.elts:
+ yield from _flatten_excepthandler(elt)
+ else:
+ yield node
+
+
+def _check_redundant_excepthandlers(names, node):
+ # See if any of the given exception names could be removed, e.g. from:
+ # (MyError, MyError) # duplicate names
+ # (MyError, BaseException) # everything derives from the Base
+ # (Exception, TypeError) # builtins where one subclasses another
+ # (IOError, OSError) # IOError is an alias of OSError since Python3.3
+ # but note that other cases are impractical to handle from the AST.
+ # We expect this is mostly useful for users who do not have the
+ # builtin exception hierarchy memorised, and include a 'shadowed'
+ # subtype without realising that it's redundant.
+ good = sorted(set(names), key=names.index)
+ if "BaseException" in good:
+ good = ["BaseException"]
+ # Remove redundant exceptions that the automatic system either handles
+ # poorly (usually aliases) or can't be checked (e.g. it's not an
+ # built-in exception).
+ for primary, equivalents in B014.redundant_exceptions.items():
+ if primary in good:
+ good = [g for g in good if g not in equivalents]
+
+ for name, other in itertools.permutations(tuple(good), 2):
+ if _typesafe_issubclass(
+ getattr(builtins, name, type), getattr(builtins, other, ())
+ ):
+ if name in good:
+ good.remove(name)
+ if good != names:
+ desc = good[0] if len(good) == 1 else "({})".format(", ".join(good))
+ as_ = " as " + node.name if node.name is not None else ""
+ return B014(
+ node.lineno,
+ node.col_offset,
+ vars=(", ".join(names), as_, desc),
+ )
+ return None
+
+
def _to_name_str(node):
# Turn Name and Attribute nodes to strings, e.g "ValueError" or
# "pkg.mod.error", handling any depth of attribute accesses.
@@ -196,6 +241,7 @@ def _to_name_str(node):
return node.id
if isinstance(node, ast.Call):
return _to_name_str(node.func)
+ assert isinstance(node, ast.Attribute), f"Unexpected node type: {type(node)}"
try:
return _to_name_str(node.value) + "." + node.attr
except AttributeError:
@@ -277,48 +323,27 @@ class BugBearVisitor(ast.NodeVisitor):
def visit_ExceptHandler(self, node):
if node.type is None:
self.errors.append(B001(node.lineno, node.col_offset))
- elif isinstance(node.type, ast.Tuple):
- names = [_to_name_str(e) for e in node.type.elts]
- as_ = " as " + node.name if node.name is not None else ""
- if len(names) == 0:
- self.errors.append(B029(node.lineno, node.col_offset))
- elif len(names) == 1:
- self.errors.append(B013(node.lineno, node.col_offset, vars=names))
+ self.generic_visit(node)
+ return
+ handlers = _flatten_excepthandler(node.type)
+ good_handlers = []
+ bad_handlers = []
+ for handler in handlers:
+ if isinstance(handler, (ast.Name, ast.Attribute)):
+ good_handlers.append(handler)
else:
- # See if any of the given exception names could be removed, e.g. from:
- # (MyError, MyError) # duplicate names
- # (MyError, BaseException) # everything derives from the Base
- # (Exception, TypeError) # builtins where one subclasses another
- # (IOError, OSError) # IOError is an alias of OSError since Python3.3
- # but note that other cases are impractical to handle from the AST.
- # We expect this is mostly useful for users who do not have the
- # builtin exception hierarchy memorised, and include a 'shadowed'
- # subtype without realising that it's redundant.
- good = sorted(set(names), key=names.index)
- if "BaseException" in good:
- good = ["BaseException"]
- # Remove redundant exceptions that the automatic system either handles
- # poorly (usually aliases) or can't be checked (e.g. it's not an
- # built-in exception).
- for primary, equivalents in B014.redundant_exceptions.items():
- if primary in good:
- good = [g for g in good if g not in equivalents]
-
- for name, other in itertools.permutations(tuple(good), 2):
- if _typesafe_issubclass(
- getattr(builtins, name, type), getattr(builtins, other, ())
- ):
- if name in good:
- good.remove(name)
- if good != names:
- desc = good[0] if len(good) == 1 else "({})".format(", ".join(good))
- self.errors.append(
- B014(
- node.lineno,
- node.col_offset,
- vars=(", ".join(names), as_, desc),
- )
- )
+ bad_handlers.append(handler)
+ if bad_handlers:
+ self.errors.append(B030(node.lineno, node.col_offset))
+ names = [_to_name_str(e) for e in good_handlers]
+ if len(names) == 0 and not bad_handlers:
+ self.errors.append(B029(node.lineno, node.col_offset))
+ elif len(names) == 1 and not bad_handlers and isinstance(node.type, ast.Tuple):
+ self.errors.append(B013(node.lineno, node.col_offset, vars=names))
+ else:
+ maybe_error = _check_redundant_excepthandlers(names, node)
+ if maybe_error is not None:
+ self.errors.append(maybe_error)
self.generic_visit(node)
def visit_UAdd(self, node):
@@ -1533,6 +1558,7 @@ B029 = Error(
"anything. Add exceptions to handle."
)
)
+B030 = Error(message="B030 Except handlers should only be names of exception classes")
# Warnings disabled by default.
B901 = Error(
| PyCQA/flake8-bugbear | 315f4e7d201cbbb674f61f9fa221b91400caf278 | diff --git a/tests/b030.py b/tests/b030.py
new file mode 100644
index 0000000..4b66f04
--- /dev/null
+++ b/tests/b030.py
@@ -0,0 +1,14 @@
+try:
+ pass
+except (ValueError, (RuntimeError, (KeyError, TypeError))): # ok
+ pass
+
+try:
+ pass
+except 1: # error
+ pass
+
+try:
+ pass
+except (1, ValueError): # error
+ pass
diff --git a/tests/test_bugbear.py b/tests/test_bugbear.py
index bbd1c2b..4751e73 100644
--- a/tests/test_bugbear.py
+++ b/tests/test_bugbear.py
@@ -41,6 +41,7 @@ from bugbear import (
B027,
B028,
B029,
+ B030,
B901,
B902,
B903,
@@ -448,6 +449,16 @@ class BugbearTestCase(unittest.TestCase):
)
self.assertEqual(errors, expected)
+ def test_b030(self):
+ filename = Path(__file__).absolute().parent / "b030.py"
+ bbc = BugBearChecker(filename=str(filename))
+ errors = list(bbc.run())
+ expected = self.errors(
+ B030(8, 0),
+ B030(13, 0),
+ )
+ self.assertEqual(errors, expected)
+
@unittest.skipIf(sys.version_info < (3, 8), "not implemented for <3.8")
def test_b907(self):
filename = Path(__file__).absolute().parent / "b907.py"
| Crash on nested tuple in except handler
Run flake8-bugbear on this file:
```python
try: x
except (a, (b, c)): pass
```
And you will get a stack trace that ends with
```
File "/Users/jelle/py/venvs/py311/lib/python3.11/site-packages/bugbear.py", line 283, in visit_ExceptHandler
names = [_to_name_str(e) for e in node.type.elts]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/jelle/py/venvs/py311/lib/python3.11/site-packages/bugbear.py", line 283, in <listcomp>
names = [_to_name_str(e) for e in node.type.elts]
^^^^^^^^^^^^^^^
File "/Users/jelle/py/venvs/py311/lib/python3.11/site-packages/bugbear.py", line 202, in _to_name_str
return _to_name_str(node.value)
^^^^^^^^^^
AttributeError: 'Tuple' object has no attribute 'value'
```
Why would you use nested tuples in except handlers, you may ask. I'm not sure, but it's legal syntax so I am testing it in the [pyanalyze](/quora/pyanalyze) test suite. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_bugbear.py::BugbearTestCase::test_b001",
"tests/test_bugbear.py::BugbearTestCase::test_b002",
"tests/test_bugbear.py::BugbearTestCase::test_b003",
"tests/test_bugbear.py::BugbearTestCase::test_b004",
"tests/test_bugbear.py::BugbearTestCase::test_b005",
"tests/test_bugbear.py::BugbearTestCase::test_b006_b008",
"tests/test_bugbear.py::BugbearTestCase::test_b007",
"tests/test_bugbear.py::BugbearTestCase::test_b008_extended",
"tests/test_bugbear.py::BugbearTestCase::test_b009_b010",
"tests/test_bugbear.py::BugbearTestCase::test_b011",
"tests/test_bugbear.py::BugbearTestCase::test_b012",
"tests/test_bugbear.py::BugbearTestCase::test_b013",
"tests/test_bugbear.py::BugbearTestCase::test_b014",
"tests/test_bugbear.py::BugbearTestCase::test_b015",
"tests/test_bugbear.py::BugbearTestCase::test_b016",
"tests/test_bugbear.py::BugbearTestCase::test_b017",
"tests/test_bugbear.py::BugbearTestCase::test_b018_classes",
"tests/test_bugbear.py::BugbearTestCase::test_b018_functions",
"tests/test_bugbear.py::BugbearTestCase::test_b018_modules",
"tests/test_bugbear.py::BugbearTestCase::test_b019",
"tests/test_bugbear.py::BugbearTestCase::test_b020",
"tests/test_bugbear.py::BugbearTestCase::test_b021_classes",
"tests/test_bugbear.py::BugbearTestCase::test_b022",
"tests/test_bugbear.py::BugbearTestCase::test_b023",
"tests/test_bugbear.py::BugbearTestCase::test_b024",
"tests/test_bugbear.py::BugbearTestCase::test_b025",
"tests/test_bugbear.py::BugbearTestCase::test_b026",
"tests/test_bugbear.py::BugbearTestCase::test_b027",
"tests/test_bugbear.py::BugbearTestCase::test_b028",
"tests/test_bugbear.py::BugbearTestCase::test_b029",
"tests/test_bugbear.py::BugbearTestCase::test_b030",
"tests/test_bugbear.py::BugbearTestCase::test_b901",
"tests/test_bugbear.py::BugbearTestCase::test_b902",
"tests/test_bugbear.py::BugbearTestCase::test_b902_py38",
"tests/test_bugbear.py::BugbearTestCase::test_b903",
"tests/test_bugbear.py::BugbearTestCase::test_b904",
"tests/test_bugbear.py::BugbearTestCase::test_b906",
"tests/test_bugbear.py::BugbearTestCase::test_b907",
"tests/test_bugbear.py::BugbearTestCase::test_b907_format_specifier_permutations",
"tests/test_bugbear.py::BugbearTestCase::test_b950",
"tests/test_bugbear.py::BugbearTestCase::test_b9_extend_select",
"tests/test_bugbear.py::BugbearTestCase::test_b9_flake8_next_default_options",
"tests/test_bugbear.py::BugbearTestCase::test_b9_select",
"tests/test_bugbear.py::BugbearTestCase::test_selfclean_test_bugbear",
"tests/test_bugbear.py::TestFuzz::test_does_not_crash_on_any_valid_code",
"tests/test_bugbear.py::TestFuzz::test_does_not_crash_on_call_in_except_statement",
"tests/test_bugbear.py::TestFuzz::test_does_not_crash_on_site_code",
"tests/test_bugbear.py::TestFuzz::test_does_not_crash_on_tuple_expansion_in_except_statement"
] | [] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2023-02-03T15:39:10Z" | mit |
|
PyCQA__flake8-bugbear-385 | diff --git a/bugbear.py b/bugbear.py
index 4717a4f..eff5c58 100644
--- a/bugbear.py
+++ b/bugbear.py
@@ -1351,12 +1351,16 @@ class BugBearVisitor(ast.NodeVisitor):
self.errors.append(B032(node.lineno, node.col_offset))
def check_for_b033(self, node):
- constants = [
- item.value
- for item in filter(lambda x: isinstance(x, ast.Constant), node.elts)
- ]
- if len(constants) != len(set(constants)):
- self.errors.append(B033(node.lineno, node.col_offset))
+ seen = set()
+ for elt in node.elts:
+ if not isinstance(elt, ast.Constant):
+ continue
+ if elt.value in seen:
+ self.errors.append(
+ B033(elt.lineno, elt.col_offset, vars=(repr(elt.value),))
+ )
+ else:
+ seen.add(elt.value)
def compose_call_path(node):
@@ -1757,8 +1761,8 @@ B032 = Error(
B033 = Error(
message=(
- "B033 Sets should not contain duplicate items. Duplicate items will be replaced"
- " with a single item at runtime."
+ "B033 Set should not contain duplicate item {}. Duplicate items will be"
+ " replaced with a single item at runtime."
)
)
@@ -1817,7 +1821,7 @@ B907 = Error(
)
B908 = Error(
message=(
- "B908 assertRaises-type context should not contains more than one top-level"
+ "B908 assertRaises-type context should not contain more than one top-level"
" statement."
)
)
| PyCQA/flake8-bugbear | 535c109e409d93c298e72b7d707a7ea6723f0a35 | diff --git a/tests/b033.py b/tests/b033.py
index 4738344..8ce42c9 100644
--- a/tests/b033.py
+++ b/tests/b033.py
@@ -1,6 +1,6 @@
"""
Should emit:
-B033 - on lines 6-12
+B033 - on lines 6-12, 16, 18
"""
test = {1, 2, 3, 3, 5}
@@ -10,6 +10,13 @@ test = {None, True, None}
test = {3, 3.0}
test = {1, True}
test = {0, False}
+multi_line = {
+ "alongvalueeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",
+ 1,
+ True,
+ 0,
+ False,
+}
test = {1, 2, 3, 3.5, 5}
test = {"a", "b", "c", "d", "e"}
diff --git a/tests/test_bugbear.py b/tests/test_bugbear.py
index 73e7b19..9047a41 100644
--- a/tests/test_bugbear.py
+++ b/tests/test_bugbear.py
@@ -493,13 +493,15 @@ class BugbearTestCase(unittest.TestCase):
bbc = BugBearChecker(filename=str(filename))
errors = list(bbc.run())
expected = self.errors(
- B033(6, 7),
- B033(7, 7),
- B033(8, 7),
- B033(9, 7),
- B033(10, 7),
- B033(11, 7),
- B033(12, 7),
+ B033(6, 17, vars=("3",)),
+ B033(7, 23, vars=("'c'",)),
+ B033(8, 21, vars=("True",)),
+ B033(9, 20, vars=("None",)),
+ B033(10, 11, vars=("3.0",)),
+ B033(11, 11, vars=("True",)),
+ B033(12, 11, vars=("False",)),
+ B033(16, 4, vars=("True",)),
+ B033(18, 4, vars=("False",)),
)
self.assertEqual(errors, expected)
| B033 should say what the duplicate set item is
I got an error `taxonomy/parsing.py:87:11: B033 Sets should not contain duplicate items. Duplicate items will be replaced with a single item at runtime.`
Now, part of this set looks like this:
```
"İ",
"À",
"Á",
"Ć",
"Á",
"Å",
"Ä",
```
I think it's the `Á`, but it would have been more helpful if flake8-bugbear had told me directly.
I'll work on a fix. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_bugbear.py::BugbearTestCase::test_b033"
] | [
"tests/test_bugbear.py::BugbearTestCase::test_b001",
"tests/test_bugbear.py::BugbearTestCase::test_b002",
"tests/test_bugbear.py::BugbearTestCase::test_b003",
"tests/test_bugbear.py::BugbearTestCase::test_b004",
"tests/test_bugbear.py::BugbearTestCase::test_b005",
"tests/test_bugbear.py::BugbearTestCase::test_b006_b008",
"tests/test_bugbear.py::BugbearTestCase::test_b007",
"tests/test_bugbear.py::BugbearTestCase::test_b008_extended",
"tests/test_bugbear.py::BugbearTestCase::test_b009_b010",
"tests/test_bugbear.py::BugbearTestCase::test_b011",
"tests/test_bugbear.py::BugbearTestCase::test_b012",
"tests/test_bugbear.py::BugbearTestCase::test_b013",
"tests/test_bugbear.py::BugbearTestCase::test_b014",
"tests/test_bugbear.py::BugbearTestCase::test_b015",
"tests/test_bugbear.py::BugbearTestCase::test_b016",
"tests/test_bugbear.py::BugbearTestCase::test_b017",
"tests/test_bugbear.py::BugbearTestCase::test_b018_classes",
"tests/test_bugbear.py::BugbearTestCase::test_b018_functions",
"tests/test_bugbear.py::BugbearTestCase::test_b018_modules",
"tests/test_bugbear.py::BugbearTestCase::test_b019",
"tests/test_bugbear.py::BugbearTestCase::test_b020",
"tests/test_bugbear.py::BugbearTestCase::test_b021_classes",
"tests/test_bugbear.py::BugbearTestCase::test_b022",
"tests/test_bugbear.py::BugbearTestCase::test_b023",
"tests/test_bugbear.py::BugbearTestCase::test_b024",
"tests/test_bugbear.py::BugbearTestCase::test_b025",
"tests/test_bugbear.py::BugbearTestCase::test_b026",
"tests/test_bugbear.py::BugbearTestCase::test_b027",
"tests/test_bugbear.py::BugbearTestCase::test_b028",
"tests/test_bugbear.py::BugbearTestCase::test_b029",
"tests/test_bugbear.py::BugbearTestCase::test_b030",
"tests/test_bugbear.py::BugbearTestCase::test_b031",
"tests/test_bugbear.py::BugbearTestCase::test_b032",
"tests/test_bugbear.py::BugbearTestCase::test_b901",
"tests/test_bugbear.py::BugbearTestCase::test_b902",
"tests/test_bugbear.py::BugbearTestCase::test_b902_py38",
"tests/test_bugbear.py::BugbearTestCase::test_b903",
"tests/test_bugbear.py::BugbearTestCase::test_b904",
"tests/test_bugbear.py::BugbearTestCase::test_b906",
"tests/test_bugbear.py::BugbearTestCase::test_b907",
"tests/test_bugbear.py::BugbearTestCase::test_b907_format_specifier_permutations",
"tests/test_bugbear.py::BugbearTestCase::test_b908",
"tests/test_bugbear.py::BugbearTestCase::test_b950",
"tests/test_bugbear.py::BugbearTestCase::test_b9_extend_select",
"tests/test_bugbear.py::BugbearTestCase::test_b9_flake8_next_default_options",
"tests/test_bugbear.py::BugbearTestCase::test_b9_select",
"tests/test_bugbear.py::BugbearTestCase::test_selfclean_test_bugbear",
"tests/test_bugbear.py::TestFuzz::test_does_not_crash_on_any_valid_code",
"tests/test_bugbear.py::TestFuzz::test_does_not_crash_on_call_in_except_statement",
"tests/test_bugbear.py::TestFuzz::test_does_not_crash_on_site_code",
"tests/test_bugbear.py::TestFuzz::test_does_not_crash_on_tuple_expansion_in_except_statement"
] | {
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
} | "2023-05-22T03:07:09Z" | mit |
|
PyCQA__flake8-bugbear-424 | diff --git a/bugbear.py b/bugbear.py
index 5fbfa19..ee2afd4 100644
--- a/bugbear.py
+++ b/bugbear.py
@@ -547,6 +547,9 @@ class BugBearVisitor(ast.NodeVisitor):
self.check_for_b005(node)
self.generic_visit(node)
+ def visit_ImportFrom(self, node):
+ self.visit_Import(node)
+
def visit_Set(self, node):
self.check_for_b033(node)
self.generic_visit(node)
@@ -555,6 +558,9 @@ class BugBearVisitor(ast.NodeVisitor):
if isinstance(node, ast.Import):
for name in node.names:
self._b005_imports.add(name.asname or name.name)
+ elif isinstance(node, ast.ImportFrom):
+ for name in node.names:
+ self._b005_imports.add(f"{node.module}.{name.name or name.asname}")
elif isinstance(node, ast.Call):
if node.func.attr not in B005.methods:
return # method name doesn't match
@@ -652,13 +658,25 @@ class BugBearVisitor(ast.NodeVisitor):
if (
hasattr(item_context, "func")
- and isinstance(item_context.func, ast.Attribute)
and (
- item_context.func.attr == "assertRaises"
+ (
+ isinstance(item_context.func, ast.Attribute)
+ and (
+ item_context.func.attr == "assertRaises"
+ or (
+ item_context.func.attr == "raises"
+ and isinstance(item_context.func.value, ast.Name)
+ and item_context.func.value.id == "pytest"
+ and "match"
+ not in [kwd.arg for kwd in item_context.keywords]
+ )
+ )
+ )
or (
- item_context.func.attr == "raises"
- and isinstance(item_context.func.value, ast.Name)
- and item_context.func.value.id == "pytest"
+ isinstance(item_context.func, ast.Name)
+ and item_context.func.id == "raises"
+ and isinstance(item_context.func.ctx, ast.Load)
+ and "pytest.raises" in self._b005_imports
and "match" not in [kwd.arg for kwd in item_context.keywords]
)
)
| PyCQA/flake8-bugbear | 907e0dd29a99818591a604d4557c70ea33204712 | diff --git a/tests/b017.py b/tests/b017.py
index 2365cd1..af52f6d 100644
--- a/tests/b017.py
+++ b/tests/b017.py
@@ -7,6 +7,7 @@ import asyncio
import unittest
import pytest
+from pytest import raises
CONSTANT = True
@@ -28,31 +29,42 @@ class Foobar(unittest.TestCase):
raise Exception("Evil I say!")
with pytest.raises(Exception):
raise Exception("Evil I say!")
+ with raises(Exception):
+ raise Exception("Evil I say!")
# These are evil as well but we are only testing inside a with statement
self.assertRaises(Exception, lambda x, y: x / y, 1, y=0)
pytest.raises(Exception, lambda x, y: x / y, 1, y=0)
+ raises(Exception, lambda x, y: x / y, 1, y=0)
def context_manager_raises(self) -> None:
with self.assertRaises(Exception) as ex:
raise Exception("Context manager is good")
with pytest.raises(Exception) as pyt_ex:
raise Exception("Context manager is good")
+ with raises(Exception) as r_ex:
+ raise Exception("Context manager is good")
self.assertEqual("Context manager is good", str(ex.exception))
self.assertEqual("Context manager is good", str(pyt_ex.value))
+ self.assertEqual("Context manager is good", str(r_ex.value))
def regex_raises(self) -> None:
with self.assertRaisesRegex(Exception, "Regex is good"):
raise Exception("Regex is good")
with pytest.raises(Exception, match="Regex is good"):
raise Exception("Regex is good")
+ with raises(Exception, match="Regex is good"):
+ raise Exception("Regex is good")
def non_context_manager_raises(self) -> None:
self.assertRaises(ZeroDivisionError, lambda x, y: x / y, 1, y=0)
pytest.raises(ZeroDivisionError, lambda x, y: x / y, 1, y=0)
+ raises(ZeroDivisionError, lambda x, y: x / y, 1, y=0)
def raises_with_absolute_reference(self):
with self.assertRaises(asyncio.CancelledError):
Foo()
with pytest.raises(asyncio.CancelledError):
Foo()
+ with raises(asyncio.CancelledError):
+ Foo()
diff --git a/tests/test_bugbear.py b/tests/test_bugbear.py
index 49377b4..22ccd6a 100644
--- a/tests/test_bugbear.py
+++ b/tests/test_bugbear.py
@@ -258,7 +258,7 @@ class BugbearTestCase(unittest.TestCase):
filename = Path(__file__).absolute().parent / "b017.py"
bbc = BugBearChecker(filename=str(filename))
errors = list(bbc.run())
- expected = self.errors(B017(25, 8), B017(27, 8), B017(29, 8))
+ expected = self.errors(B017(26, 8), B017(28, 8), B017(30, 8), B017(32, 8))
self.assertEqual(errors, expected)
def test_b018_functions(self):
@@ -530,9 +530,11 @@ class BugbearTestCase(unittest.TestCase):
B908(15, 8),
B908(21, 8),
B908(27, 8),
+ B017(37, 0),
B908(37, 0),
B908(41, 0),
B908(45, 0),
+ B017(56, 0),
)
self.assertEqual(errors, expected)
| B017: False negative when "from" imports used
## Summary
B017 fails when raises is imported directly
## Version
Replicated on version `23.9.16`
## Sample code
```
import pytest
from pytest import raises
def foo():
raise
def test_pytest_raises():
with raises(Exception):
foo()
with pytest.raises(Exception):
foo()
``` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_bugbear.py::BugbearTestCase::test_b017",
"tests/test_bugbear.py::BugbearTestCase::test_b908"
] | [
"tests/test_bugbear.py::BugbearTestCase::test_b001",
"tests/test_bugbear.py::BugbearTestCase::test_b002",
"tests/test_bugbear.py::BugbearTestCase::test_b003",
"tests/test_bugbear.py::BugbearTestCase::test_b004",
"tests/test_bugbear.py::BugbearTestCase::test_b005",
"tests/test_bugbear.py::BugbearTestCase::test_b006_b008",
"tests/test_bugbear.py::BugbearTestCase::test_b007",
"tests/test_bugbear.py::BugbearTestCase::test_b008_extended",
"tests/test_bugbear.py::BugbearTestCase::test_b009_b010",
"tests/test_bugbear.py::BugbearTestCase::test_b011",
"tests/test_bugbear.py::BugbearTestCase::test_b012",
"tests/test_bugbear.py::BugbearTestCase::test_b013",
"tests/test_bugbear.py::BugbearTestCase::test_b014",
"tests/test_bugbear.py::BugbearTestCase::test_b015",
"tests/test_bugbear.py::BugbearTestCase::test_b016",
"tests/test_bugbear.py::BugbearTestCase::test_b018_classes",
"tests/test_bugbear.py::BugbearTestCase::test_b018_functions",
"tests/test_bugbear.py::BugbearTestCase::test_b018_modules",
"tests/test_bugbear.py::BugbearTestCase::test_b019",
"tests/test_bugbear.py::BugbearTestCase::test_b020",
"tests/test_bugbear.py::BugbearTestCase::test_b021_classes",
"tests/test_bugbear.py::BugbearTestCase::test_b022",
"tests/test_bugbear.py::BugbearTestCase::test_b023",
"tests/test_bugbear.py::BugbearTestCase::test_b024",
"tests/test_bugbear.py::BugbearTestCase::test_b025",
"tests/test_bugbear.py::BugbearTestCase::test_b026",
"tests/test_bugbear.py::BugbearTestCase::test_b027",
"tests/test_bugbear.py::BugbearTestCase::test_b028",
"tests/test_bugbear.py::BugbearTestCase::test_b029",
"tests/test_bugbear.py::BugbearTestCase::test_b030",
"tests/test_bugbear.py::BugbearTestCase::test_b031",
"tests/test_bugbear.py::BugbearTestCase::test_b032",
"tests/test_bugbear.py::BugbearTestCase::test_b033",
"tests/test_bugbear.py::BugbearTestCase::test_b034",
"tests/test_bugbear.py::BugbearTestCase::test_b901",
"tests/test_bugbear.py::BugbearTestCase::test_b902",
"tests/test_bugbear.py::BugbearTestCase::test_b902_extended",
"tests/test_bugbear.py::BugbearTestCase::test_b902_py38",
"tests/test_bugbear.py::BugbearTestCase::test_b903",
"tests/test_bugbear.py::BugbearTestCase::test_b904",
"tests/test_bugbear.py::BugbearTestCase::test_b906",
"tests/test_bugbear.py::BugbearTestCase::test_b907",
"tests/test_bugbear.py::BugbearTestCase::test_b907_format_specifier_permutations",
"tests/test_bugbear.py::BugbearTestCase::test_b950",
"tests/test_bugbear.py::BugbearTestCase::test_b9_extend_select",
"tests/test_bugbear.py::BugbearTestCase::test_b9_flake8_next_default_options",
"tests/test_bugbear.py::BugbearTestCase::test_b9_select",
"tests/test_bugbear.py::BugbearTestCase::test_selfclean_bugbear",
"tests/test_bugbear.py::BugbearTestCase::test_selfclean_test_bugbear",
"tests/test_bugbear.py::TestFuzz::test_does_not_crash_on_any_valid_code",
"tests/test_bugbear.py::TestFuzz::test_does_not_crash_on_call_in_except_statement",
"tests/test_bugbear.py::TestFuzz::test_does_not_crash_on_site_code",
"tests/test_bugbear.py::TestFuzz::test_does_not_crash_on_tuple_expansion_in_except_statement"
] | {
"failed_lite_validators": [
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
} | "2023-11-23T05:57:42Z" | mit |
|
PyCQA__isort-1432 | diff --git a/isort/output.py b/isort/output.py
index 1a6c504b..8cf915f9 100644
--- a/isort/output.py
+++ b/isort/output.py
@@ -328,13 +328,20 @@ def _with_from_imports(
while from_imports and from_imports[0] in as_imports:
from_import = from_imports.pop(0)
as_imports[from_import] = sorting.naturally(as_imports[from_import])
- from_comments = parsed.categorized_comments["straight"].get(
- f"{module}.{from_import}"
+ from_comments = (
+ parsed.categorized_comments["straight"].get(f"{module}.{from_import}") or []
)
if (
parsed.imports[section]["from"][module][from_import]
and not only_show_as_imports
):
+ specific_comment = (
+ parsed.categorized_comments["nested"]
+ .get(module, {})
+ .pop(from_import, None)
+ )
+ if specific_comment:
+ from_comments.append(specific_comment)
output.append(
wrap.line(
with_comments(
@@ -347,19 +354,31 @@ def _with_from_imports(
config,
)
)
- output.extend(
- wrap.line(
- with_comments(
- from_comments,
- import_start + as_import,
- removed=config.ignore_comments,
- comment_prefix=config.comment_prefix,
- ),
- parsed.line_separator,
- config,
+ from_comments = []
+
+ for as_import in as_imports[from_import]:
+ specific_comment = (
+ parsed.categorized_comments["nested"]
+ .get(module, {})
+ .pop(as_import, None)
)
- for as_import in as_imports[from_import]
- )
+ if specific_comment:
+ from_comments.append(specific_comment)
+
+ output.append(
+ wrap.line(
+ with_comments(
+ from_comments,
+ import_start + as_import,
+ removed=config.ignore_comments,
+ comment_prefix=config.comment_prefix,
+ ),
+ parsed.line_separator,
+ config,
+ )
+ )
+
+ from_comments = []
if "*" in from_imports:
output.append(
diff --git a/isort/parse.py b/isort/parse.py
index 913cdbb1..4a537422 100644
--- a/isort/parse.py
+++ b/isort/parse.py
@@ -235,7 +235,7 @@ def file_contents(contents: str, config: Config = DEFAULT_CONFIG) -> ParsedConte
if (
type_of_import == "from"
and stripped_line
- and " " not in stripped_line
+ and " " not in stripped_line.replace(" as ", "")
and new_comment
):
nested_comments[stripped_line] = comments[-1]
@@ -257,7 +257,7 @@ def file_contents(contents: str, config: Config = DEFAULT_CONFIG) -> ParsedConte
if (
type_of_import == "from"
and stripped_line
- and " " not in stripped_line
+ and " " not in stripped_line.replace(" as ", "")
and new_comment
):
nested_comments[stripped_line] = comments[-1]
@@ -272,7 +272,7 @@ def file_contents(contents: str, config: Config = DEFAULT_CONFIG) -> ParsedConte
if (
type_of_import == "from"
and stripped_line
- and " " not in stripped_line
+ and " " not in stripped_line.replace(" as ", "")
and new_comment
):
nested_comments[stripped_line] = comments[-1]
@@ -282,7 +282,7 @@ def file_contents(contents: str, config: Config = DEFAULT_CONFIG) -> ParsedConte
if (
type_of_import == "from"
and stripped_line
- and " " not in stripped_line
+ and " " not in stripped_line.replace(" as ", "")
and new_comment
):
nested_comments[stripped_line] = comments[-1]
@@ -332,6 +332,15 @@ def file_contents(contents: str, config: Config = DEFAULT_CONFIG) -> ParsedConte
pass
elif as_name not in as_map["from"][module]:
as_map["from"][module].append(as_name)
+
+ full_name = f"{nested_module} as {as_name}"
+ associated_comment = nested_comments.get(full_name)
+ if associated_comment:
+ categorized_comments["nested"].setdefault(top_level_module, {})[
+ full_name
+ ] = associated_comment
+ if associated_comment in comments:
+ comments.pop(comments.index(associated_comment))
else:
module = just_imports[as_index - 1]
as_name = just_imports[as_index + 1]
@@ -340,7 +349,7 @@ def file_contents(contents: str, config: Config = DEFAULT_CONFIG) -> ParsedConte
elif as_name not in as_map["straight"][module]:
as_map["straight"][module].append(as_name)
- if config.combine_as_imports and nested_module:
+ if nested_module and config.combine_as_imports:
categorized_comments["from"].setdefault(
f"{top_level_module}.__combined_as__", []
).extend(comments)
| PyCQA/isort | 281dfbc8579cb178886f37ee51225cd043cfc4ea | diff --git a/tests/unit/test_regressions.py b/tests/unit/test_regressions.py
index 3b35c401..9a44c967 100644
--- a/tests/unit/test_regressions.py
+++ b/tests/unit/test_regressions.py
@@ -645,3 +645,17 @@ from package import * # noqa
force_single_line=True,
show_diff=True,
)
+
+
+def test_isort_doesnt_misplace_comments_issue_1431():
+ """Test to ensure isort wont misplace comments.
+ See: https://github.com/PyCQA/isort/issues/1431
+ """
+ input_text = """from com.my_lovely_company.my_lovely_team.my_lovely_project.my_lovely_component import (
+ MyLovelyCompanyTeamProjectComponent, # NOT DRY
+)
+from com.my_lovely_company.my_lovely_team.my_lovely_project.my_lovely_component import (
+ MyLovelyCompanyTeamProjectComponent as component, # DRY
+)
+"""
+ assert isort.code(input_text, profile="black") == input_text
| Comment incorrectly moved
When running isort over the following snippet, comments both incorrectly become `# DRY`:
```
from com.my_lovely_company.my_lovely_team.my_lovely_project.my_lovely_component import (
MyLovelyCompanyTeamProjectComponent, # NOT DRY
)
from com.my_lovely_company.my_lovely_team.my_lovely_project.my_lovely_component import (
MyLovelyCompanyTeamProjectComponent as component, # DRY
)
``` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/unit/test_regressions.py::test_isort_doesnt_misplace_comments_issue_1431"
] | [
"tests/unit/test_regressions.py::test_isort_duplicating_comments_issue_1264",
"tests/unit/test_regressions.py::test_moving_comments_issue_726",
"tests/unit/test_regressions.py::test_blank_lined_removed_issue_1275",
"tests/unit/test_regressions.py::test_blank_lined_removed_issue_1283",
"tests/unit/test_regressions.py::test_extra_blank_line_added_nested_imports_issue_1290",
"tests/unit/test_regressions.py::test_add_imports_shouldnt_make_isort_unusable_issue_1297",
"tests/unit/test_regressions.py::test_no_extra_lines_for_imports_in_functions_issue_1277",
"tests/unit/test_regressions.py::test_no_extra_blank_lines_in_methods_issue_1293",
"tests/unit/test_regressions.py::test_force_single_line_shouldnt_remove_preceding_comment_lines_issue_1296",
"tests/unit/test_regressions.py::test_ensure_new_line_before_comments_mixed_with_ensure_newline_before_comments_1295",
"tests/unit/test_regressions.py::test_trailing_comma_doesnt_introduce_broken_code_with_comment_and_wrap_issue_1302",
"tests/unit/test_regressions.py::test_ensure_sre_parse_is_identified_as_stdlib_issue_1304",
"tests/unit/test_regressions.py::test_add_imports_shouldnt_move_lower_comments_issue_1300",
"tests/unit/test_regressions.py::test_windows_newline_issue_1277",
"tests/unit/test_regressions.py::test_windows_newline_issue_1278",
"tests/unit/test_regressions.py::test_check_never_passes_with_indented_headings_issue_1301",
"tests/unit/test_regressions.py::test_isort_shouldnt_fail_on_long_from_with_dot_issue_1190",
"tests/unit/test_regressions.py::test_isort_shouldnt_add_extra_new_line_when_fass_and_n_issue_1315",
"tests/unit/test_regressions.py::test_isort_doesnt_rewrite_import_with_dot_to_from_import_issue_1280",
"tests/unit/test_regressions.py::test_isort_shouldnt_introduce_extra_lines_with_fass_issue_1322",
"tests/unit/test_regressions.py::test_comments_should_cause_wrapping_on_long_lines_black_mode_issue_1219",
"tests/unit/test_regressions.py::test_comment_blocks_should_stay_associated_without_extra_lines_issue_1156",
"tests/unit/test_regressions.py::test_comment_shouldnt_be_duplicated_with_fass_enabled_issue_1329",
"tests/unit/test_regressions.py::test_wrap_mode_equal_to_line_length_with_indendet_imports_issue_1333",
"tests/unit/test_regressions.py::test_isort_skipped_nested_imports_issue_1339",
"tests/unit/test_regressions.py::test_windows_diff_too_large_misrepresentative_issue_1348",
"tests/unit/test_regressions.py::test_combine_as_does_not_lose_comments_issue_1321",
"tests/unit/test_regressions.py::test_combine_as_does_not_lose_comments_issue_1381",
"tests/unit/test_regressions.py::test_incorrect_grouping_when_comments_issue_1396",
"tests/unit/test_regressions.py::test_reverse_relative_combined_with_force_sort_within_sections_issue_1395",
"tests/unit/test_regressions.py::test_isort_should_be_able_to_add_independent_of_doc_string_placement_issue_1420",
"tests/unit/test_regressions.py::test_comments_should_never_be_moved_between_imports_issue_1427"
] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2020-08-30T08:03:45Z" | mit |
|
PyCQA__isort-1717 | diff --git a/isort/parse.py b/isort/parse.py
index 714e39ab..2a15c90f 100644
--- a/isort/parse.py
+++ b/isort/parse.py
@@ -293,6 +293,7 @@ def file_contents(contents: str, config: Config = DEFAULT_CONFIG) -> ParsedConte
else:
while line.strip().endswith("\\"):
line, new_comment = parse_comments(in_lines[index])
+ line = line.lstrip()
index += 1
if new_comment:
comments.append(new_comment)
| PyCQA/isort | 5e29571377dc8879328d8f7d7ecd6a725bdbc320 | diff --git a/tests/unit/test_isort.py b/tests/unit/test_isort.py
index 7a02884b..8f0368d7 100644
--- a/tests/unit/test_isort.py
+++ b/tests/unit/test_isort.py
@@ -4095,6 +4095,14 @@ def test_isort_keeps_comments_issue_691() -> None:
assert isort.code(test_input) == expected_output
+def test_isort_multiline_with_tab_issue_1714() -> None:
+ test_input = "from sys \\ \n" "\timport version\n" "print(version)\n"
+
+ expected_output = "from sys import version\n" "\n" "print(version)\n"
+
+ assert isort.code(test_input) == expected_output
+
+
def test_isort_ensures_blank_line_between_import_and_comment() -> None:
config = {
"ensure_newline_before_comments": True,
| Line break and tab indentation makes wrong fix
`isort` causes odd fixing with import line which contains line berak and tab indentation.
before `isort` (Notice that this code uses Tab indentation, not spaces.)
```py
from sys \
import version
print(version)
```
after `isort`
```py
from sys import importversion
print(version)
```
expected
```py
from sys import version
print(version)
```
### Versions
- macOS Big Sur 11.2.3
- Python 3.9.4
- isort 5.7.0 | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/unit/test_isort.py::test_isort_multiline_with_tab_issue_1714"
] | [
"tests/unit/test_isort.py::test_happy_path",
"tests/unit/test_isort.py::test_code_intermixed",
"tests/unit/test_isort.py::test_correct_space_between_imports",
"tests/unit/test_isort.py::test_sort_on_number",
"tests/unit/test_isort.py::test_line_length",
"tests/unit/test_isort.py::test_output_modes",
"tests/unit/test_isort.py::test_qa_comment_case",
"tests/unit/test_isort.py::test_length_sort",
"tests/unit/test_isort.py::test_length_sort_straight",
"tests/unit/test_isort.py::test_length_sort_section",
"tests/unit/test_isort.py::test_convert_hanging",
"tests/unit/test_isort.py::test_custom_indent",
"tests/unit/test_isort.py::test_use_parentheses",
"tests/unit/test_isort.py::test_skip",
"tests/unit/test_isort.py::test_skip_with_file_name",
"tests/unit/test_isort.py::test_skip_within_file",
"tests/unit/test_isort.py::test_force_to_top",
"tests/unit/test_isort.py::test_add_imports",
"tests/unit/test_isort.py::test_remove_imports",
"tests/unit/test_isort.py::test_comments_above",
"tests/unit/test_isort.py::test_explicitly_local_import",
"tests/unit/test_isort.py::test_quotes_in_file",
"tests/unit/test_isort.py::test_check_newline_in_imports",
"tests/unit/test_isort.py::test_forced_separate",
"tests/unit/test_isort.py::test_default_section",
"tests/unit/test_isort.py::test_first_party_overrides_standard_section",
"tests/unit/test_isort.py::test_thirdy_party_overrides_standard_section",
"tests/unit/test_isort.py::test_known_pattern_path_expansion",
"tests/unit/test_isort.py::test_force_single_line_imports",
"tests/unit/test_isort.py::test_force_single_line_long_imports",
"tests/unit/test_isort.py::test_force_single_line_imports_and_sort_within_sections",
"tests/unit/test_isort.py::test_titled_imports",
"tests/unit/test_isort.py::test_balanced_wrapping",
"tests/unit/test_isort.py::test_relative_import_with_space",
"tests/unit/test_isort.py::test_multiline_import",
"tests/unit/test_isort.py::test_single_multiline",
"tests/unit/test_isort.py::test_atomic_mode",
"tests/unit/test_isort.py::test_order_by_type",
"tests/unit/test_isort.py::test_custom_lines_after_import_section",
"tests/unit/test_isort.py::test_smart_lines_after_import_section",
"tests/unit/test_isort.py::test_settings_overwrite",
"tests/unit/test_isort.py::test_combined_from_and_as_imports",
"tests/unit/test_isort.py::test_as_imports_with_line_length",
"tests/unit/test_isort.py::test_keep_comments",
"tests/unit/test_isort.py::test_multiline_split_on_dot",
"tests/unit/test_isort.py::test_import_star",
"tests/unit/test_isort.py::test_include_trailing_comma",
"tests/unit/test_isort.py::test_similar_to_std_library",
"tests/unit/test_isort.py::test_correctly_placed_imports",
"tests/unit/test_isort.py::test_auto_detection",
"tests/unit/test_isort.py::test_same_line_statements",
"tests/unit/test_isort.py::test_long_line_comments",
"tests/unit/test_isort.py::test_tab_character_in_import",
"tests/unit/test_isort.py::test_split_position",
"tests/unit/test_isort.py::test_place_comments",
"tests/unit/test_isort.py::test_placement_control",
"tests/unit/test_isort.py::test_custom_sections",
"tests/unit/test_isort.py::test_glob_known",
"tests/unit/test_isort.py::test_sticky_comments",
"tests/unit/test_isort.py::test_zipimport",
"tests/unit/test_isort.py::test_from_ending",
"tests/unit/test_isort.py::test_from_first",
"tests/unit/test_isort.py::test_top_comments",
"tests/unit/test_isort.py::test_consistency",
"tests/unit/test_isort.py::test_force_grid_wrap",
"tests/unit/test_isort.py::test_force_grid_wrap_long",
"tests/unit/test_isort.py::test_uses_jinja_variables",
"tests/unit/test_isort.py::test_fcntl",
"tests/unit/test_isort.py::test_import_split_is_word_boundary_aware",
"tests/unit/test_isort.py::test_other_file_encodings",
"tests/unit/test_isort.py::test_encoding_not_in_comment",
"tests/unit/test_isort.py::test_encoding_not_in_first_two_lines",
"tests/unit/test_isort.py::test_comment_at_top_of_file",
"tests/unit/test_isort.py::test_alphabetic_sorting",
"tests/unit/test_isort.py::test_alphabetic_sorting_multi_line",
"tests/unit/test_isort.py::test_comments_not_duplicated",
"tests/unit/test_isort.py::test_top_of_line_comments",
"tests/unit/test_isort.py::test_basic_comment",
"tests/unit/test_isort.py::test_shouldnt_add_lines",
"tests/unit/test_isort.py::test_sections_parsed_correct",
"tests/unit/test_isort.py::test_alphabetic_sorting_no_newlines",
"tests/unit/test_isort.py::test_sort_within_section",
"tests/unit/test_isort.py::test_sort_within_section_case_honored",
"tests/unit/test_isort.py::test_sorting_with_two_top_comments",
"tests/unit/test_isort.py::test_lines_between_sections",
"tests/unit/test_isort.py::test_forced_sepatate_globs",
"tests/unit/test_isort.py::test_no_additional_lines_issue_358",
"tests/unit/test_isort.py::test_import_by_paren_issue_375",
"tests/unit/test_isort.py::test_import_by_paren_issue_460",
"tests/unit/test_isort.py::test_function_with_docstring",
"tests/unit/test_isort.py::test_plone_style",
"tests/unit/test_isort.py::test_third_party_case_sensitive",
"tests/unit/test_isort.py::test_exists_case_sensitive_file",
"tests/unit/test_isort.py::test_exists_case_sensitive_directory",
"tests/unit/test_isort.py::test_sys_path_mutation",
"tests/unit/test_isort.py::test_long_single_line",
"tests/unit/test_isort.py::test_import_inside_class_issue_432",
"tests/unit/test_isort.py::test_wildcard_import_without_space_issue_496",
"tests/unit/test_isort.py::test_import_line_mangles_issues_491",
"tests/unit/test_isort.py::test_import_line_mangles_issues_505",
"tests/unit/test_isort.py::test_import_line_mangles_issues_439",
"tests/unit/test_isort.py::test_alias_using_paren_issue_466",
"tests/unit/test_isort.py::test_long_alias_using_paren_issue_957",
"tests/unit/test_isort.py::test_strict_whitespace_by_default",
"tests/unit/test_isort.py::test_strict_whitespace_no_closing_newline_issue_676",
"tests/unit/test_isort.py::test_ignore_whitespace",
"tests/unit/test_isort.py::test_import_wraps_with_comment_issue_471",
"tests/unit/test_isort.py::test_import_case_produces_inconsistent_results_issue_472",
"tests/unit/test_isort.py::test_inconsistent_behavior_in_python_2_and_3_issue_479",
"tests/unit/test_isort.py::test_sort_within_section_comments_issue_436",
"tests/unit/test_isort.py::test_sort_within_sections_with_force_to_top_issue_473",
"tests/unit/test_isort.py::test_force_sort_within_sections_with_relative_imports",
"tests/unit/test_isort.py::test_force_sort_within_sections_with_reverse_relative_imports",
"tests/unit/test_isort.py::test_sort_relative_in_force_sorted_sections_issue_1659",
"tests/unit/test_isort.py::test_reverse_sort_relative_in_force_sorted_sections_issue_1659",
"tests/unit/test_isort.py::test_correct_number_of_new_lines_with_comment_issue_435",
"tests/unit/test_isort.py::test_future_below_encoding_issue_545",
"tests/unit/test_isort.py::test_no_extra_lines_issue_557",
"tests/unit/test_isort.py::test_long_import_wrap_support_with_mode_2",
"tests/unit/test_isort.py::test_pylint_comments_incorrectly_wrapped_issue_571",
"tests/unit/test_isort.py::test_ensure_async_methods_work_issue_537",
"tests/unit/test_isort.py::test_ensure_as_imports_sort_correctly_within_from_imports_issue_590",
"tests/unit/test_isort.py::test_ensure_line_endings_are_preserved_issue_493",
"tests/unit/test_isort.py::test_not_splitted_sections",
"tests/unit/test_isort.py::test_no_lines_before_empty_section",
"tests/unit/test_isort.py::test_no_inline_sort",
"tests/unit/test_isort.py::test_relative_import_of_a_module",
"tests/unit/test_isort.py::test_escaped_parens_sort",
"tests/unit/test_isort.py::test_escaped_parens_sort_with_comment",
"tests/unit/test_isort.py::test_escaped_parens_sort_with_first_comment",
"tests/unit/test_isort.py::test_escaped_no_parens_sort_with_first_comment",
"tests/unit/test_isort.py::test_to_ensure_importing_from_imports_module_works_issue_662",
"tests/unit/test_isort.py::test_to_ensure_no_unexpected_changes_issue_666",
"tests/unit/test_isort.py::test_to_ensure_tabs_dont_become_space_issue_665",
"tests/unit/test_isort.py::test_new_lines_are_preserved",
"tests/unit/test_isort.py::test_forced_separate_is_deterministic_issue_774",
"tests/unit/test_isort.py::test_monkey_patched_urllib",
"tests/unit/test_isort.py::test_argument_parsing",
"tests/unit/test_isort.py::test_command_line[False]",
"tests/unit/test_isort.py::test_command_line[True]",
"tests/unit/test_isort.py::test_quiet[False]",
"tests/unit/test_isort.py::test_quiet[True]",
"tests/unit/test_isort.py::test_safety_skips[False]",
"tests/unit/test_isort.py::test_safety_skips[True]",
"tests/unit/test_isort.py::test_skip_glob[skip_glob_assert0]",
"tests/unit/test_isort.py::test_skip_glob[skip_glob_assert1]",
"tests/unit/test_isort.py::test_skip_glob[skip_glob_assert2]",
"tests/unit/test_isort.py::test_broken",
"tests/unit/test_isort.py::test_comments_not_removed_issue_576",
"tests/unit/test_isort.py::test_reverse_relative_imports_issue_417",
"tests/unit/test_isort.py::test_inconsistent_relative_imports_issue_577",
"tests/unit/test_isort.py::test_unwrap_issue_762",
"tests/unit/test_isort.py::test_multiple_as_imports",
"tests/unit/test_isort.py::test_all_imports_from_single_module",
"tests/unit/test_isort.py::test_noqa_issue_679",
"tests/unit/test_isort.py::test_extract_multiline_output_wrap_setting_from_a_config_file",
"tests/unit/test_isort.py::test_ensure_support_for_non_typed_but_cased_alphabetic_sort_issue_890",
"tests/unit/test_isort.py::test_to_ensure_empty_line_not_added_to_file_start_issue_889",
"tests/unit/test_isort.py::test_to_ensure_correctly_handling_of_whitespace_only_issue_811",
"tests/unit/test_isort.py::test_standard_library_deprecates_user_issue_778",
"tests/unit/test_isort.py::test_failing_file_check_916",
"tests/unit/test_isort.py::test_import_heading_issue_905",
"tests/unit/test_isort.py::test_isort_keeps_comments_issue_691",
"tests/unit/test_isort.py::test_isort_ensures_blank_line_between_import_and_comment",
"tests/unit/test_isort.py::test_pyi_formatting_issue_942",
"tests/unit/test_isort.py::test_move_class_issue_751",
"tests/unit/test_isort.py::test_python_version",
"tests/unit/test_isort.py::test_isort_with_single_character_import",
"tests/unit/test_isort.py::test_isort_nested_imports",
"tests/unit/test_isort.py::test_isort_off",
"tests/unit/test_isort.py::test_isort_split",
"tests/unit/test_isort.py::test_comment_look_alike",
"tests/unit/test_isort.py::test_cimport_support",
"tests/unit/test_isort.py::test_cdef_support",
"tests/unit/test_isort.py::test_top_level_import_order",
"tests/unit/test_isort.py::test_noqa_issue_1065",
"tests/unit/test_isort.py::test_single_line_exclusions",
"tests/unit/test_isort.py::test_nested_comment_handling",
"tests/unit/test_isort.py::test_comments_top_of_file",
"tests/unit/test_isort.py::test_multiple_aliases",
"tests/unit/test_isort.py::test_parens_in_comment",
"tests/unit/test_isort.py::test_as_imports_mixed",
"tests/unit/test_isort.py::test_no_sections_with_future",
"tests/unit/test_isort.py::test_no_sections_with_as_import",
"tests/unit/test_isort.py::test_no_lines_too_long",
"tests/unit/test_isort.py::test_python_future_category",
"tests/unit/test_isort.py::test_combine_star_comments_above",
"tests/unit/test_isort.py::test_deprecated_settings",
"tests/unit/test_isort.py::test_deprecated_settings_no_warn_in_quiet_mode",
"tests/unit/test_isort.py::test_only_sections",
"tests/unit/test_isort.py::test_combine_straight_imports",
"tests/unit/test_isort.py::test_find_imports_in_code",
"tests/unit/test_isort.py::test_find_imports_in_stream"
] | {
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
} | "2021-04-29T17:23:08Z" | mit |
|
PyCQA__isort-1727 | diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8a67e349..217e2bef 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,7 +6,8 @@ Find out more about isort's release policy [here](https://pycqa.github.io/isort/
### 5.9.0 TBD
- Fixed (https://github.com/PyCQA/isort/pull/1695) added imports being added to doc string in some cases.
- - Fixed (https://github.com/PyCQA/isort/pull/1714) in rare case line continuation combined with tab can output invalid code.
+ - Fixed (https://github.com/PyCQA/isort/pull/1714) in rare cases line continuation combined with tabs can output invalid code.
+ - Fixed (https://github.com/PyCQA/isort/pull/1726) isort ignores reverse_sort when force_sort_within_sections is true.
- Implemented #1697: Provisional support for PEP 582: skip `__pypackages__` directories by default.
- Implemented #1705: More intuitive handling of isort:skip_file comments on streams.
diff --git a/isort/output.py b/isort/output.py
index 61c2e30e..fb74ef73 100644
--- a/isort/output.py
+++ b/isort/output.py
@@ -108,6 +108,7 @@ def sorted_imports(
new_section_output = sorting.naturally(
new_section_output,
key=partial(sorting.section_key, config=config),
+ reverse=config.reverse_sort,
)
# uncollapse comments
| PyCQA/isort | a4c9719423f3d9ebd525eb571184e0a36f5c7116 | diff --git a/tests/unit/test_ticketed_features.py b/tests/unit/test_ticketed_features.py
index a0e5e164..17aaf166 100644
--- a/tests/unit/test_ticketed_features.py
+++ b/tests/unit/test_ticketed_features.py
@@ -1082,3 +1082,36 @@ from ._foo import a
from ._bar import All, Any, Not
"""
)
+
+
+def test_isort_can_combine_reverse_sort_with_force_sort_within_sections_issue_1726():
+ """isort should support reversing import order even with force sort within sections turned on.
+ See: https://github.com/PyCQA/isort/issues/1726
+ """
+ assert (
+ isort.code(
+ """
+import blaaa
+from bl4aaaaaaaaaaaaaaaa import r
+import blaaaaaaaaaaaa
+import bla
+import blaaaaaaa
+from bl1aaaaaaaaaaaaaa import this_is_1
+from bl2aaaaaaa import THIIIIIIIIIIIISS_is_2
+from bl3aaaaaa import less
+""",
+ length_sort=True,
+ reverse_sort=True,
+ force_sort_within_sections=True,
+ )
+ == """
+from bl2aaaaaaa import THIIIIIIIIIIIISS_is_2
+from bl1aaaaaaaaaaaaaa import this_is_1
+from bl4aaaaaaaaaaaaaaaa import r
+from bl3aaaaaa import less
+import blaaaaaaaaaaaa
+import blaaaaaaa
+import blaaa
+import bla
+"""
+ )
| isort ignores `reverse_sort` when `force_sort_within_sections` is true
i have a mix of imports that i want sorted by length, and running isort on it while force_sort_within_sections and reverse_sort are both true causes them to be sorted shortest line to longest, rather than longest to shortest, as expected.
> `pyproject.toml`
> ```toml
> [tool.isort]
> length_sort = true
> reverse_sort = true
> force_sort_within_sections = true
> ```
> IN
> ```python
> import blaaa
> from bl4aaaaaaaaaaaaaaaa import r
> import blaaaaaaaaaaaa
> import bla
> import blaaaaaaa
> from bl1aaaaaaaaaaaaaa import this_is_1
> from bl2aaaaaaa import THIIIIIIIIIIIISS_is_2
> from bl3aaaaaa import less
> ```
> OUT
> ```python
> import bla
> import blaaa
> import blaaaaaaa
> import blaaaaaaaaaaaa
> from bl3aaaaaa import less
> from bl4aaaaaaaaaaaaaaaa import r
> from bl1aaaaaaaaaaaaaa import this_is_1
> from bl2aaaaaaa import THIIIIIIIIIIIISS_is_2
> ```
> EXPECTED
> ```python
> from bl2aaaaaaa import THIIIIIIIIIIIISS_is_2
> from bl1aaaaaaaaaaaaaa import this_is_1
> from bl4aaaaaaaaaaaaaaaa import r
> from bl3aaaaaa import less
> import blaaaaaaaaaaaa
> import blaaaaaaa
> import blaaa
> import bla
> ``` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/unit/test_ticketed_features.py::test_isort_can_combine_reverse_sort_with_force_sort_within_sections_issue_1726"
] | [
"tests/unit/test_ticketed_features.py::test_semicolon_ignored_for_dynamic_lines_after_import_issue_1178",
"tests/unit/test_ticketed_features.py::test_isort_automatically_removes_duplicate_aliases_issue_1193",
"tests/unit/test_ticketed_features.py::test_isort_enables_floating_imports_to_top_of_module_issue_1228",
"tests/unit/test_ticketed_features.py::test_isort_provides_official_api_for_diff_output_issue_1335",
"tests/unit/test_ticketed_features.py::test_isort_warns_when_known_sections_dont_match_issue_1331",
"tests/unit/test_ticketed_features.py::test_isort_supports_append_only_imports_issue_727",
"tests/unit/test_ticketed_features.py::test_treating_comments_as_code_issue_1357",
"tests/unit/test_ticketed_features.py::test_isort_allows_setting_import_types_issue_1181",
"tests/unit/test_ticketed_features.py::test_isort_enables_deduping_section_headers_issue_953",
"tests/unit/test_ticketed_features.py::test_isort_doesnt_remove_as_imports_when_combine_star_issue_1380",
"tests/unit/test_ticketed_features.py::test_isort_support_custom_groups_above_stdlib_that_contain_stdlib_modules_issue_1407",
"tests/unit/test_ticketed_features.py::test_isort_intelligently_places_noqa_comments_issue_1456",
"tests/unit/test_ticketed_features.py::test_isort_respects_quiet_from_sort_file_api_see_1461",
"tests/unit/test_ticketed_features.py::test_float_to_top_should_respect_existing_newlines_between_imports_issue_1502",
"tests/unit/test_ticketed_features.py::test_api_to_allow_custom_diff_and_output_stream_1583",
"tests/unit/test_ticketed_features.py::test_autofix_mixed_indent_imports_1575",
"tests/unit/test_ticketed_features.py::test_indented_import_headings_issue_1604",
"tests/unit/test_ticketed_features.py::test_isort_auto_detects_and_ignores_invalid_from_imports_issue_1688",
"tests/unit/test_ticketed_features.py::test_isort_allows_reversing_sort_order_issue_1645",
"tests/unit/test_ticketed_features.py::test_isort_can_push_star_imports_above_others_issue_1504"
] | {
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2021-05-12T05:24:59Z" | mit |
|
PyCQA__isort-1995 | diff --git a/isort/settings.py b/isort/settings.py
index fb9bba2f..24de2337 100644
--- a/isort/settings.py
+++ b/isort/settings.py
@@ -11,7 +11,6 @@ import stat
import subprocess # nosec: Needed for gitignore support.
import sys
from dataclasses import dataclass, field
-from functools import lru_cache
from pathlib import Path
from typing import (
TYPE_CHECKING,
@@ -766,7 +765,6 @@ def _abspaths(cwd: str, values: Iterable[str]) -> Set[str]:
return paths
-@lru_cache()
def _find_config(path: str) -> Tuple[str, Dict[str, Any]]:
current_directory = path
tries = 0
@@ -799,7 +797,6 @@ def _find_config(path: str) -> Tuple[str, Dict[str, Any]]:
return (path, {})
-@lru_cache()
def find_all_configs(path: str) -> Trie:
"""
Looks for config files in the path provided and in all of its sub-directories.
@@ -828,8 +825,7 @@ def find_all_configs(path: str) -> Trie:
return trie_root
-@lru_cache()
-def _get_config_data(file_path: str, sections: Tuple[str]) -> Dict[str, Any]:
+def _get_config_data(file_path: str, sections: Tuple[str, ...]) -> Dict[str, Any]:
settings: Dict[str, Any] = {}
if file_path.endswith(".toml"):
| PyCQA/isort | 4e3ccb1c635badad59fb0dd95ef8923a95390f21 | diff --git a/tests/unit/test_settings.py b/tests/unit/test_settings.py
index 86354512..295b30c1 100644
--- a/tests/unit/test_settings.py
+++ b/tests/unit/test_settings.py
@@ -126,8 +126,6 @@ def test_find_config(tmpdir):
tmp_config = tmpdir.join(".isort.cfg")
# can't find config if it has no relevant section
- settings._find_config.cache_clear()
- settings._get_config_data.cache_clear()
tmp_config.write_text(
"""
[section]
@@ -138,14 +136,10 @@ force_grid_wrap=true
assert not settings._find_config(str(tmpdir))[1]
# or if it is malformed
- settings._find_config.cache_clear()
- settings._get_config_data.cache_clear()
tmp_config.write_text("""arstoyrsyan arienrsaeinrastyngpuywnlguyn354q^%$)(%_)@$""", "utf8")
assert not settings._find_config(str(tmpdir))[1]
# can when it has either a file format, or generic relevant section
- settings._find_config.cache_clear()
- settings._get_config_data.cache_clear()
_write_simple_settings(tmp_config)
assert settings._find_config(str(tmpdir))[1]
@@ -155,8 +149,6 @@ def test_find_config_deep(tmpdir):
dirs = [f"dir{i}" for i in range(settings.MAX_CONFIG_SEARCH_DEPTH + 1)]
tmp_dirs = tmpdir.ensure(*dirs, dirs=True)
tmp_config = tmpdir.join("dir0", ".isort.cfg")
- settings._find_config.cache_clear()
- settings._get_config_data.cache_clear()
_write_simple_settings(tmp_config)
assert not settings._find_config(str(tmp_dirs))[1]
# but can find config if it is MAX_CONFIG_SEARCH_DEPTH up
diff --git a/tests/unit/test_ticketed_features.py b/tests/unit/test_ticketed_features.py
index 6f483e8f..32eeb709 100644
--- a/tests/unit/test_ticketed_features.py
+++ b/tests/unit/test_ticketed_features.py
@@ -555,7 +555,6 @@ def test_isort_respects_quiet_from_sort_file_api_see_1461(capsys, tmpdir):
assert not out
# Present in an automatically loaded configuration file
- isort.settings._find_config.cache_clear()
settings_file.write(
"""
[isort]
@@ -610,7 +609,6 @@ quiet = true
with pytest.warns(UserWarning):
assert not Config(settings_file=str(settings_file)).quiet
- isort.settings._get_config_data.cache_clear()
settings_file.write(
"""
[isort]
| Do not cache configuration files
isort can run in long processes when used in an editor. In that
scenario users might edit their configuration files and literally
save a file again to see its outcome.
This is not possible right now because we `lru_cache()` all the
relevant functions in `settings.py`.
It is strange that we do this in the first place as we either collect
all known configs using the `Trie` implementation *or* we only
construct exactly one `Config` object based on the first file name,
the working dir, or from `settings_path|file`...
We can probably remove the caches in `settings.py` completely.
Except of course you explicitly wanted to optimize for long
running processes. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/unit/test_settings.py::test_find_config",
"tests/unit/test_ticketed_features.py::test_isort_respects_quiet_from_sort_file_api_see_1461"
] | [
"tests/unit/test_settings.py::TestConfig::test_init",
"tests/unit/test_settings.py::TestConfig::test_init_unsupported_settings_fails_gracefully",
"tests/unit/test_settings.py::TestConfig::test_known_settings",
"tests/unit/test_settings.py::TestConfig::test_invalid_settings_path",
"tests/unit/test_settings.py::TestConfig::test_invalid_pyversion",
"tests/unit/test_settings.py::TestConfig::test_invalid_profile",
"tests/unit/test_settings.py::TestConfig::test_is_skipped",
"tests/unit/test_settings.py::TestConfig::test_is_supported_filetype",
"tests/unit/test_settings.py::TestConfig::test_is_supported_filetype_ioerror",
"tests/unit/test_settings.py::TestConfig::test_is_supported_filetype_shebang",
"tests/unit/test_settings.py::TestConfig::test_is_supported_filetype_editor_backup",
"tests/unit/test_settings.py::TestConfig::test_is_supported_filetype_defaults",
"tests/unit/test_settings.py::TestConfig::test_is_supported_filetype_configuration",
"tests/unit/test_settings.py::TestConfig::test_is_supported_filetype_fifo",
"tests/unit/test_settings.py::TestConfig::test_src_paths_are_combined_and_deduplicated",
"tests/unit/test_settings.py::TestConfig::test_src_paths_supports_glob_expansion",
"tests/unit/test_settings.py::TestConfig::test_deprecated_multi_line_output",
"tests/unit/test_settings.py::test_as_list",
"tests/unit/test_settings.py::test_find_config_deep",
"tests/unit/test_settings.py::test_get_config_data",
"tests/unit/test_settings.py::test_editorconfig_without_sections",
"tests/unit/test_settings.py::test_get_config_data_with_toml_and_utf8",
"tests/unit/test_settings.py::test_as_bool",
"tests/unit/test_settings.py::test_find_all_configs",
"tests/unit/test_ticketed_features.py::test_semicolon_ignored_for_dynamic_lines_after_import_issue_1178",
"tests/unit/test_ticketed_features.py::test_isort_automatically_removes_duplicate_aliases_issue_1193",
"tests/unit/test_ticketed_features.py::test_isort_enables_floating_imports_to_top_of_module_issue_1228",
"tests/unit/test_ticketed_features.py::test_isort_provides_official_api_for_diff_output_issue_1335",
"tests/unit/test_ticketed_features.py::test_isort_warns_when_known_sections_dont_match_issue_1331",
"tests/unit/test_ticketed_features.py::test_isort_supports_append_only_imports_issue_727",
"tests/unit/test_ticketed_features.py::test_treating_comments_as_code_issue_1357",
"tests/unit/test_ticketed_features.py::test_isort_allows_setting_import_types_issue_1181",
"tests/unit/test_ticketed_features.py::test_isort_enables_deduping_section_headers_issue_953",
"tests/unit/test_ticketed_features.py::test_isort_doesnt_remove_as_imports_when_combine_star_issue_1380",
"tests/unit/test_ticketed_features.py::test_isort_support_custom_groups_above_stdlib_that_contain_stdlib_modules_issue_1407",
"tests/unit/test_ticketed_features.py::test_isort_intelligently_places_noqa_comments_issue_1456",
"tests/unit/test_ticketed_features.py::test_float_to_top_should_respect_existing_newlines_between_imports_issue_1502",
"tests/unit/test_ticketed_features.py::test_api_to_allow_custom_diff_and_output_stream_1583",
"tests/unit/test_ticketed_features.py::test_autofix_mixed_indent_imports_1575",
"tests/unit/test_ticketed_features.py::test_indented_import_headings_issue_1604",
"tests/unit/test_ticketed_features.py::test_isort_auto_detects_and_ignores_invalid_from_imports_issue_1688",
"tests/unit/test_ticketed_features.py::test_isort_allows_reversing_sort_order_issue_1645",
"tests/unit/test_ticketed_features.py::test_isort_can_push_star_imports_above_others_issue_1504",
"tests/unit/test_ticketed_features.py::test_isort_can_combine_reverse_sort_with_force_sort_within_sections_issue_1726",
"tests/unit/test_ticketed_features.py::test_isort_can_turn_off_import_adds_with_action_comment_issue_1737",
"tests/unit/test_ticketed_features.py::test_cython_pure_python_imports_2062"
] | {
"failed_lite_validators": [
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2022-11-11T22:37:10Z" | mit |
|
PyCQA__pyflakes-273 | diff --git a/.travis.yml b/.travis.yml
index 1ea3e20..2d614cd 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -11,9 +11,6 @@ python:
- pypy-5.3
- pypy3
- pypy3.3-5.2-alpha1
-matrix:
- allow_failures:
- - python: nightly
install:
- pip install flake8==2.1.0 pep8==1.5.6
- python setup.py install
diff --git a/README.rst b/README.rst
index e84d334..aeb15f9 100644
--- a/README.rst
+++ b/README.rst
@@ -72,7 +72,7 @@ rebase your commits for you.
All changes should include tests and pass flake8_.
-.. image:: https://api.travis-ci.org/PyCQA/pyflakes.svg
+.. image:: https://api.travis-ci.org/PyCQA/pyflakes.svg?branch=master
:target: https://travis-ci.org/PyCQA/pyflakes
:alt: Build status
diff --git a/pyflakes/api.py b/pyflakes/api.py
index a535bff..49ee38d 100644
--- a/pyflakes/api.py
+++ b/pyflakes/api.py
@@ -5,6 +5,7 @@ from __future__ import with_statement
import sys
import os
+import re
import _ast
from pyflakes import checker, __version__
@@ -13,6 +14,9 @@ from pyflakes import reporter as modReporter
__all__ = ['check', 'checkPath', 'checkRecursive', 'iterSourceCode', 'main']
+PYTHON_SHEBANG_REGEX = re.compile(br'^#!.*\bpython[23w]?\b\s*$')
+
+
def check(codeString, filename, reporter=None):
"""
Check the Python source given by C{codeString} for flakes.
@@ -108,6 +112,25 @@ def checkPath(filename, reporter=None):
return check(codestr, filename, reporter)
+def isPythonFile(filename):
+ """Return True if filename points to a Python file."""
+ if filename.endswith('.py'):
+ return True
+
+ max_bytes = 128
+
+ try:
+ with open(filename, 'rb') as f:
+ text = f.read(max_bytes)
+ if not text:
+ return False
+ except IOError:
+ return False
+
+ first_line = text.splitlines()[0]
+ return PYTHON_SHEBANG_REGEX.match(first_line)
+
+
def iterSourceCode(paths):
"""
Iterate over all Python source files in C{paths}.
@@ -120,8 +143,9 @@ def iterSourceCode(paths):
if os.path.isdir(path):
for dirpath, dirnames, filenames in os.walk(path):
for filename in filenames:
- if filename.endswith('.py'):
- yield os.path.join(dirpath, filename)
+ full_path = os.path.join(dirpath, filename)
+ if isPythonFile(full_path):
+ yield full_path
else:
yield path
diff --git a/pyflakes/checker.py b/pyflakes/checker.py
index 382574e..75abdc0 100644
--- a/pyflakes/checker.py
+++ b/pyflakes/checker.py
@@ -870,7 +870,19 @@ class Checker(object):
def handleDoctests(self, node):
try:
- (docstring, node_lineno) = self.getDocstring(node.body[0])
+ if hasattr(node, 'docstring'):
+ docstring = node.docstring
+
+ # This is just a reasonable guess. In Python 3.7, docstrings no
+ # longer have line numbers associated with them. This will be
+ # incorrect if there are empty lines between the beginning
+ # of the function and the docstring.
+ node_lineno = node.lineno
+ if hasattr(node, 'args'):
+ node_lineno = max([node_lineno] +
+ [arg.lineno for arg in node.args.args])
+ else:
+ (docstring, node_lineno) = self.getDocstring(node.body[0])
examples = docstring and self._getDoctestExamples(docstring)
except (ValueError, IndexError):
# e.g. line 6 of the docstring for <string> has inconsistent
diff --git a/setup.cfg b/setup.cfg
index 5e40900..2a9acf1 100644
--- a/setup.cfg
+++ b/setup.cfg
@@ -1,2 +1,2 @@
-[wheel]
+[bdist_wheel]
universal = 1
| PyCQA/pyflakes | 1af4f14ad4675bf5c61c47bbb7c2421b50d1cba4 | diff --git a/pyflakes/test/test_api.py b/pyflakes/test/test_api.py
index 51b0027..3f54ca4 100644
--- a/pyflakes/test/test_api.py
+++ b/pyflakes/test/test_api.py
@@ -187,6 +187,36 @@ class TestIterSourceCode(TestCase):
sorted(iterSourceCode([self.tempdir])),
sorted([apath, bpath, cpath]))
+ def test_shebang(self):
+ """
+ Find Python files that don't end with `.py`, but contain a Python
+ shebang.
+ """
+ python = os.path.join(self.tempdir, 'a')
+ with open(python, 'w') as fd:
+ fd.write('#!/usr/bin/env python\n')
+
+ self.makeEmptyFile('b')
+
+ with open(os.path.join(self.tempdir, 'c'), 'w') as fd:
+ fd.write('hello\nworld\n')
+
+ python2 = os.path.join(self.tempdir, 'd')
+ with open(python2, 'w') as fd:
+ fd.write('#!/usr/bin/env python2\n')
+
+ python3 = os.path.join(self.tempdir, 'e')
+ with open(python3, 'w') as fd:
+ fd.write('#!/usr/bin/env python3\n')
+
+ pythonw = os.path.join(self.tempdir, 'f')
+ with open(pythonw, 'w') as fd:
+ fd.write('#!/usr/bin/env pythonw\n')
+
+ self.assertEqual(
+ sorted(iterSourceCode([self.tempdir])),
+ sorted([python, python2, python3, pythonw]))
+
def test_multipleDirectories(self):
"""
L{iterSourceCode} can be given multiple directories. It will recurse
| Support Python 3.7
*I'm moving https://github.com/PyCQA/pyflakes/pull/90#issuecomment-301317699 here since we have GitHub issue support now.*
It looks like the [CPython 3.7 failure](https://travis-ci.org/PyCQA/pyflakes/jobs/231571260) is related to a change in the AST. The docstring is no longer in `node.body`.
https://github.com/python/cpython/pull/46
We can mostly replace our `getDocstring(node.body[0])` call with `node.docstring`. But I'm not sure how to get the line number of the docstring anymore. `node.lineno` is close, but not quite the line number of the docstring.
https://github.com/PyCQA/pyflakes/blob/074c21da3174bc88b2ec02fea767a436e2db643d/pyflakes/checker.py#L873
```diff
diff --git a/pyflakes/checker.py b/pyflakes/checker.py
index 382574e..2c19533 100644
--- a/pyflakes/checker.py
+++ b/pyflakes/checker.py
@@ -870,7 +870,11 @@ class Checker(object):
def handleDoctests(self, node):
try:
- (docstring, node_lineno) = self.getDocstring(node.body[0])
+ if hasattr(node, 'docstring'):
+ docstring = node.docstring
+ node_lineno = ??? # TODO
+ else:
+ (docstring, node_lineno) = self.getDocstring(node.body[0])
examples = docstring and self._getDoctestExamples(docstring)
except (ValueError, IndexError):
# e.g. line 6 of the docstring for <string> has inconsistent
```
I've reported this to the [CPython issue tracker](http://bugs.python.org/issue30497). | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"pyflakes/test/test_api.py::TestIterSourceCode::test_shebang"
] | [
"pyflakes/test/test_api.py::TestIterSourceCode::test_emptyDirectory",
"pyflakes/test/test_api.py::TestIterSourceCode::test_explicitFiles",
"pyflakes/test/test_api.py::TestIterSourceCode::test_multipleDirectories",
"pyflakes/test/test_api.py::TestIterSourceCode::test_onlyPythonSource",
"pyflakes/test/test_api.py::TestIterSourceCode::test_recurses",
"pyflakes/test/test_api.py::TestIterSourceCode::test_singleFile",
"pyflakes/test/test_api.py::TestReporter::test_flake",
"pyflakes/test/test_api.py::TestReporter::test_multiLineSyntaxError",
"pyflakes/test/test_api.py::TestReporter::test_syntaxError",
"pyflakes/test/test_api.py::TestReporter::test_syntaxErrorNoOffset",
"pyflakes/test/test_api.py::TestReporter::test_unexpectedError",
"pyflakes/test/test_api.py::CheckTests::test_checkPathNonExisting",
"pyflakes/test/test_api.py::CheckTests::test_checkRecursive",
"pyflakes/test/test_api.py::CheckTests::test_legacyScript",
"pyflakes/test/test_api.py::CheckTests::test_misencodedFileUTF16",
"pyflakes/test/test_api.py::CheckTests::test_misencodedFileUTF8",
"pyflakes/test/test_api.py::CheckTests::test_missingTrailingNewline",
"pyflakes/test/test_api.py::CheckTests::test_pyflakesWarning",
"pyflakes/test/test_api.py::IntegrationTests::test_errors_io",
"pyflakes/test/test_api.py::IntegrationTests::test_fileWithFlakes",
"pyflakes/test/test_api.py::IntegrationTests::test_goodFile",
"pyflakes/test/test_api.py::IntegrationTests::test_readFromStdin",
"pyflakes/test/test_api.py::TestMain::test_errors_io",
"pyflakes/test/test_api.py::TestMain::test_fileWithFlakes",
"pyflakes/test/test_api.py::TestMain::test_goodFile",
"pyflakes/test/test_api.py::TestMain::test_readFromStdin"
] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2017-05-29T15:56:21Z" | mit |
|
PyCQA__pyflakes-275 | diff --git a/README.rst b/README.rst
index e84d334..aeb15f9 100644
--- a/README.rst
+++ b/README.rst
@@ -72,7 +72,7 @@ rebase your commits for you.
All changes should include tests and pass flake8_.
-.. image:: https://api.travis-ci.org/PyCQA/pyflakes.svg
+.. image:: https://api.travis-ci.org/PyCQA/pyflakes.svg?branch=master
:target: https://travis-ci.org/PyCQA/pyflakes
:alt: Build status
diff --git a/pyflakes/api.py b/pyflakes/api.py
index a535bff..e30f920 100644
--- a/pyflakes/api.py
+++ b/pyflakes/api.py
@@ -5,6 +5,7 @@ from __future__ import with_statement
import sys
import os
+import re
import _ast
from pyflakes import checker, __version__
@@ -13,6 +14,9 @@ from pyflakes import reporter as modReporter
__all__ = ['check', 'checkPath', 'checkRecursive', 'iterSourceCode', 'main']
+PYTHON_SHEBANG_REGEX = re.compile(br'^#!.*\bpython[23]?\b\s*$')
+
+
def check(codeString, filename, reporter=None):
"""
Check the Python source given by C{codeString} for flakes.
@@ -108,6 +112,25 @@ def checkPath(filename, reporter=None):
return check(codestr, filename, reporter)
+def isPythonFile(filename):
+ """Return True if filename points to a Python file."""
+ if filename.endswith('.py'):
+ return True
+
+ max_bytes = 128
+
+ try:
+ with open(filename, 'rb') as f:
+ text = f.read(max_bytes)
+ if not text:
+ return False
+ except IOError:
+ return False
+
+ first_line = text.splitlines()[0]
+ return PYTHON_SHEBANG_REGEX.match(first_line)
+
+
def iterSourceCode(paths):
"""
Iterate over all Python source files in C{paths}.
@@ -120,8 +143,9 @@ def iterSourceCode(paths):
if os.path.isdir(path):
for dirpath, dirnames, filenames in os.walk(path):
for filename in filenames:
- if filename.endswith('.py'):
- yield os.path.join(dirpath, filename)
+ full_path = os.path.join(dirpath, filename)
+ if isPythonFile(full_path):
+ yield full_path
else:
yield path
| PyCQA/pyflakes | 1af4f14ad4675bf5c61c47bbb7c2421b50d1cba4 | diff --git a/pyflakes/test/test_api.py b/pyflakes/test/test_api.py
index 51b0027..a1e0be2 100644
--- a/pyflakes/test/test_api.py
+++ b/pyflakes/test/test_api.py
@@ -187,6 +187,22 @@ class TestIterSourceCode(TestCase):
sorted(iterSourceCode([self.tempdir])),
sorted([apath, bpath, cpath]))
+ def test_shebang(self):
+ """
+ Find Python files that don't end with `.py`, but contain a Python
+ shebang.
+ """
+ apath = os.path.join(self.tempdir, 'a')
+ fd = open(apath, 'w')
+ fd.write('#!/usr/bin/env python\n')
+ fd.close()
+
+ self.makeEmptyFile('b')
+
+ self.assertEqual(
+ list(iterSourceCode([self.tempdir])),
+ list([apath]))
+
def test_multipleDirectories(self):
"""
L{iterSourceCode} can be given multiple directories. It will recurse
| Please also check python scripts that are not named *.py
*Original report by [morph-debian](https://launchpad.net/~morph-debian) on [Launchpad](https://bugs.launchpad.net/bugs/970465):*
------------------------------------
Hello,
as reported on Debian at http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=653890:
"""
It would be great if pyflakes could detect files that are python scripts
but are not named *.py. It would have to read the first two bytes of
each file to check for scripts and then read the rest of the line to
determine if it is a python script. It would need to process stuff like:
#!/usr/bin/python
#!/usr/local/bin/python
#!/usr/bin/env python
#!/usr/bin/python2.6
#!/usr/bin/python3.2
"""
Regards,
Sandro
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"pyflakes/test/test_api.py::TestIterSourceCode::test_shebang"
] | [
"pyflakes/test/test_api.py::TestIterSourceCode::test_emptyDirectory",
"pyflakes/test/test_api.py::TestIterSourceCode::test_explicitFiles",
"pyflakes/test/test_api.py::TestIterSourceCode::test_multipleDirectories",
"pyflakes/test/test_api.py::TestIterSourceCode::test_onlyPythonSource",
"pyflakes/test/test_api.py::TestIterSourceCode::test_recurses",
"pyflakes/test/test_api.py::TestIterSourceCode::test_singleFile",
"pyflakes/test/test_api.py::TestReporter::test_flake",
"pyflakes/test/test_api.py::TestReporter::test_multiLineSyntaxError",
"pyflakes/test/test_api.py::TestReporter::test_syntaxError",
"pyflakes/test/test_api.py::TestReporter::test_syntaxErrorNoOffset",
"pyflakes/test/test_api.py::TestReporter::test_unexpectedError",
"pyflakes/test/test_api.py::CheckTests::test_checkPathNonExisting",
"pyflakes/test/test_api.py::CheckTests::test_checkRecursive",
"pyflakes/test/test_api.py::CheckTests::test_legacyScript",
"pyflakes/test/test_api.py::CheckTests::test_misencodedFileUTF16",
"pyflakes/test/test_api.py::CheckTests::test_misencodedFileUTF8",
"pyflakes/test/test_api.py::CheckTests::test_missingTrailingNewline",
"pyflakes/test/test_api.py::CheckTests::test_pyflakesWarning",
"pyflakes/test/test_api.py::IntegrationTests::test_errors_io",
"pyflakes/test/test_api.py::IntegrationTests::test_fileWithFlakes",
"pyflakes/test/test_api.py::IntegrationTests::test_goodFile",
"pyflakes/test/test_api.py::IntegrationTests::test_readFromStdin",
"pyflakes/test/test_api.py::TestMain::test_errors_io",
"pyflakes/test/test_api.py::TestMain::test_fileWithFlakes",
"pyflakes/test/test_api.py::TestMain::test_goodFile",
"pyflakes/test/test_api.py::TestMain::test_readFromStdin"
] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2017-05-31T03:24:45Z" | mit |
|
PyCQA__pyflakes-374 | diff --git a/.travis.yml b/.travis.yml
index 29f1d44..2113aec 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,18 +1,21 @@
language: python
cache: pip
-python:
- - 2.7
- - 3.4
- - 3.5
- - 3.6
- - nightly
- - pypy
- - pypy-5.3
- - pypy3
+matrix:
+ include:
+ - python: 2.7
+ - python: 3.4
+ - python: 3.5
+ - python: 3.6
+ - python: pypy
+ - python: pypy-5.3
+ - python: pypy3
+ - python: 3.7
+ dist: xenial
+ - python: nightly
+ dist: xenial
install:
- pip install --upgrade .
- pip list
script:
- python setup.py test -q
- if [ "$TRAVIS_PYTHON_VERSION" != "nightly" ]; then pip install flake8==2.1.0 pep8==1.5.6 && flake8 --version && flake8 pyflakes setup.py; fi
-sudo: false
diff --git a/pyflakes/checker.py b/pyflakes/checker.py
index 5c12820..e05bdf4 100644
--- a/pyflakes/checker.py
+++ b/pyflakes/checker.py
@@ -476,6 +476,7 @@ class GeneratorScope(Scope):
class ModuleScope(Scope):
"""Scope for a module."""
_futures_allowed = True
+ _annotations_future_enabled = False
class DoctestScope(ModuleScope):
@@ -628,6 +629,19 @@ class Checker(object):
if isinstance(self.scope, ModuleScope):
self.scope._futures_allowed = False
+ @property
+ def annotationsFutureEnabled(self):
+ scope = self.scopeStack[0]
+ if not isinstance(scope, ModuleScope):
+ return False
+ return scope._annotations_future_enabled
+
+ @annotationsFutureEnabled.setter
+ def annotationsFutureEnabled(self, value):
+ assert value is True
+ assert isinstance(self.scope, ModuleScope)
+ self.scope._annotations_future_enabled = True
+
@property
def scope(self):
return self.scopeStack[-1]
@@ -1068,6 +1082,8 @@ class Checker(object):
self.handleNode(parsed_annotation, node)
self.deferFunction(handleForwardAnnotation)
+ elif self.annotationsFutureEnabled:
+ self.deferFunction(lambda: self.handleNode(annotation, node))
else:
self.handleNode(annotation, node)
@@ -1448,6 +1464,8 @@ class Checker(object):
if alias.name not in __future__.all_feature_names:
self.report(messages.FutureFeatureNotDefined,
node, alias.name)
+ if alias.name == 'annotations':
+ self.annotationsFutureEnabled = True
elif alias.name == '*':
# Only Python 2, local import * is a SyntaxWarning
if not PY2 and not isinstance(self.scope, ModuleScope):
diff --git a/tox.ini b/tox.ini
index fabad9d..f3db2bb 100644
--- a/tox.ini
+++ b/tox.ini
@@ -1,7 +1,7 @@
[tox]
skip_missing_interpreters = True
envlist =
- py27,py34,py35,py36,pypy,pypy3
+ py27,py34,py35,py36,py37,pypy,pypy3
[testenv]
deps =
| PyCQA/pyflakes | 7c74ab0ddccb60a9154c2af5aa4ee4581ccada4a | diff --git a/pyflakes/test/test_other.py b/pyflakes/test/test_other.py
index b8301ea..d0fff0a 100644
--- a/pyflakes/test/test_other.py
+++ b/pyflakes/test/test_other.py
@@ -2055,6 +2055,24 @@ class TestAsyncStatements(TestCase):
a: 'a: "A"'
''', m.ForwardAnnotationSyntaxError)
+ @skipIf(version_info < (3, 7), 'new in Python 3.7')
+ def test_postponed_annotations(self):
+ self.flakes('''
+ from __future__ import annotations
+ def f(a: A) -> A: pass
+ class A:
+ b: B
+ class B: pass
+ ''')
+
+ self.flakes('''
+ from __future__ import annotations
+ def f(a: A) -> A: pass
+ class A:
+ b: Undefined
+ class B: pass
+ ''', m.UndefinedName)
+
def test_raise_notimplemented(self):
self.flakes('''
raise NotImplementedError("This is fine")
| F821 Error with Forward Reference and `from __future__ import annotations`
With this example file:
```python
# test.py
from __future__ import annotations
from dataclasses import dataclass
@dataclass
class MyData:
member: MyMember
@dataclass
class MyMember:
value: int
```
I get an F821 error:
```shell
$ flake8 --select=F test.py
test.py:8:13: F821 undefined name 'MyMember'
```
I suppose the error is correct, but forward references in this form are explicitly supported with the `annotations` future and I think this should be changed in some manner. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"pyflakes/test/test_other.py::TestAsyncStatements::test_postponed_annotations"
] | [
"pyflakes/test/test_other.py::Test::test_attrAugmentedAssignment",
"pyflakes/test/test_other.py::Test::test_breakInsideLoop",
"pyflakes/test/test_other.py::Test::test_breakOutsideLoop",
"pyflakes/test/test_other.py::Test::test_classFunctionDecorator",
"pyflakes/test/test_other.py::Test::test_classNameDefinedPreviously",
"pyflakes/test/test_other.py::Test::test_classNameUndefinedInClassBody",
"pyflakes/test/test_other.py::Test::test_classRedefinedAsFunction",
"pyflakes/test/test_other.py::Test::test_classRedefinition",
"pyflakes/test/test_other.py::Test::test_classWithReturn",
"pyflakes/test/test_other.py::Test::test_classWithYield",
"pyflakes/test/test_other.py::Test::test_classWithYieldFrom",
"pyflakes/test/test_other.py::Test::test_comparison",
"pyflakes/test/test_other.py::Test::test_containment",
"pyflakes/test/test_other.py::Test::test_continueInFinally",
"pyflakes/test/test_other.py::Test::test_continueInsideLoop",
"pyflakes/test/test_other.py::Test::test_continueOutsideLoop",
"pyflakes/test/test_other.py::Test::test_defaultExceptLast",
"pyflakes/test/test_other.py::Test::test_defaultExceptNotLast",
"pyflakes/test/test_other.py::Test::test_doubleAssignmentConditionally",
"pyflakes/test/test_other.py::Test::test_doubleAssignmentWithUse",
"pyflakes/test/test_other.py::Test::test_duplicateArgs",
"pyflakes/test/test_other.py::Test::test_ellipsis",
"pyflakes/test/test_other.py::Test::test_extendedSlice",
"pyflakes/test/test_other.py::Test::test_functionDecorator",
"pyflakes/test/test_other.py::Test::test_functionRedefinedAsClass",
"pyflakes/test/test_other.py::Test::test_function_arguments",
"pyflakes/test/test_other.py::Test::test_function_arguments_python3",
"pyflakes/test/test_other.py::Test::test_globalDeclaredInDifferentScope",
"pyflakes/test/test_other.py::Test::test_identity",
"pyflakes/test/test_other.py::Test::test_localReferencedBeforeAssignment",
"pyflakes/test/test_other.py::Test::test_loopControl",
"pyflakes/test/test_other.py::Test::test_modernProperty",
"pyflakes/test/test_other.py::Test::test_moduleWithReturn",
"pyflakes/test/test_other.py::Test::test_moduleWithYield",
"pyflakes/test/test_other.py::Test::test_moduleWithYieldFrom",
"pyflakes/test/test_other.py::Test::test_redefinedClassFunction",
"pyflakes/test/test_other.py::Test::test_redefinedFunction",
"pyflakes/test/test_other.py::Test::test_redefinedIfElseFunction",
"pyflakes/test/test_other.py::Test::test_redefinedIfElseInListComp",
"pyflakes/test/test_other.py::Test::test_redefinedIfFunction",
"pyflakes/test/test_other.py::Test::test_redefinedInDictComprehension",
"pyflakes/test/test_other.py::Test::test_redefinedInGenerator",
"pyflakes/test/test_other.py::Test::test_redefinedInSetComprehension",
"pyflakes/test/test_other.py::Test::test_redefinedTryExceptFunction",
"pyflakes/test/test_other.py::Test::test_redefinedTryFunction",
"pyflakes/test/test_other.py::Test::test_redefinedUnderscoreFunction",
"pyflakes/test/test_other.py::Test::test_redefinedUnderscoreImportation",
"pyflakes/test/test_other.py::Test::test_starredAssignmentErrors",
"pyflakes/test/test_other.py::Test::test_starredAssignmentNoError",
"pyflakes/test/test_other.py::Test::test_typingOverload",
"pyflakes/test/test_other.py::Test::test_unaryPlus",
"pyflakes/test/test_other.py::Test::test_undefinedBaseClass",
"pyflakes/test/test_other.py::Test::test_varAugmentedAssignment",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assert_static",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assert_tuple",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assert_tuple_empty",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assert_with_message",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assert_without_message",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assignInForLoop",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assignInListComprehension",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assignToGlobal",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assignToMember",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assignToNonlocal",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assignmentInsideLoop",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_augmentedAssignmentImportedFunctionCall",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_closedOver",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_dictComprehension",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_doubleClosedOver",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_exceptWithoutNameInFunction",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_exceptWithoutNameInFunctionTuple",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_exceptionUnusedInExcept",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_exceptionUnusedInExceptInFunction",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_exceptionUsedInExcept",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_f_string",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_generatorExpression",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_ifexp",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_listUnpacking",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_setComprehensionAndLiteral",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_tracebackhideSpecialVariable",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_tupleUnpacking",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_unusedUnderscoreVariable",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_unusedVariable",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_unusedVariableAsLocals",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_unusedVariableNoLocals",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_variableUsedInLoop",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementAttributeName",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementComplicatedTarget",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementListNames",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementNameDefinedInBody",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementNoNames",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementSingleName",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementSingleNameRedefined",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementSingleNameUndefined",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementSubscript",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementSubscriptUndefined",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementTupleNames",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementTupleNamesRedefined",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementTupleNamesUndefined",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementUndefinedInExpression",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementUndefinedInside",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_yieldFromUndefined",
"pyflakes/test/test_other.py::TestAsyncStatements::test_asyncDef",
"pyflakes/test/test_other.py::TestAsyncStatements::test_asyncDefAwait",
"pyflakes/test/test_other.py::TestAsyncStatements::test_asyncDefUndefined",
"pyflakes/test/test_other.py::TestAsyncStatements::test_asyncFor",
"pyflakes/test/test_other.py::TestAsyncStatements::test_asyncForUnderscoreLoopVar",
"pyflakes/test/test_other.py::TestAsyncStatements::test_asyncWith",
"pyflakes/test/test_other.py::TestAsyncStatements::test_asyncWithItem",
"pyflakes/test/test_other.py::TestAsyncStatements::test_continueInAsyncForFinally",
"pyflakes/test/test_other.py::TestAsyncStatements::test_formatstring",
"pyflakes/test/test_other.py::TestAsyncStatements::test_loopControlInAsyncFor",
"pyflakes/test/test_other.py::TestAsyncStatements::test_loopControlInAsyncForElse",
"pyflakes/test/test_other.py::TestAsyncStatements::test_matmul",
"pyflakes/test/test_other.py::TestAsyncStatements::test_raise_notimplemented",
"pyflakes/test/test_other.py::TestAsyncStatements::test_variable_annotations",
"pyflakes/test/test_other.py::TestIncompatiblePrintOperator::test_invalid_print_when_imported_from_future",
"pyflakes/test/test_other.py::TestIncompatiblePrintOperator::test_print_as_condition_test",
"pyflakes/test/test_other.py::TestIncompatiblePrintOperator::test_print_function_assignment",
"pyflakes/test/test_other.py::TestIncompatiblePrintOperator::test_print_in_lambda",
"pyflakes/test/test_other.py::TestIncompatiblePrintOperator::test_print_returned_in_function",
"pyflakes/test/test_other.py::TestIncompatiblePrintOperator::test_valid_print"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2018-10-25T00:31:43Z" | mit |
|
PyCQA__pyflakes-396 | diff --git a/pyflakes/api.py b/pyflakes/api.py
index 805a886..3ddb386 100644
--- a/pyflakes/api.py
+++ b/pyflakes/api.py
@@ -5,6 +5,7 @@ from __future__ import with_statement
import sys
import os
+import platform
import re
import _ast
@@ -91,9 +92,6 @@ def checkPath(filename, reporter=None):
try:
with open(filename, 'rb') as f:
codestr = f.read()
- except UnicodeError:
- reporter.unexpectedError(filename, 'problem decoding source')
- return 1
except IOError:
msg = sys.exc_info()[1]
reporter.unexpectedError(filename, msg.args[1])
@@ -186,6 +184,14 @@ def _exitOnSignal(sigName, message):
pass
+def _get_version():
+ """
+ Retrieve and format package version along with python version & OS used
+ """
+ return ('%s Python %s on %s' %
+ (__version__, platform.python_version(), platform.system()))
+
+
def main(prog=None, args=None):
"""Entry point for the script "pyflakes"."""
import optparse
@@ -194,7 +200,7 @@ def main(prog=None, args=None):
_exitOnSignal('SIGINT', '... stopped')
_exitOnSignal('SIGPIPE', 1)
- parser = optparse.OptionParser(prog=prog, version=__version__)
+ parser = optparse.OptionParser(prog=prog, version=_get_version())
(__, args) = parser.parse_args(args=args)
reporter = modReporter._makeDefaultReporter()
if args:
diff --git a/pyflakes/checker.py b/pyflakes/checker.py
index e05bdf4..406b806 100644
--- a/pyflakes/checker.py
+++ b/pyflakes/checker.py
@@ -11,7 +11,8 @@ import os
import sys
PY2 = sys.version_info < (3, 0)
-PY34 = sys.version_info < (3, 5) # Python 2.7 to 3.4
+PY35_PLUS = sys.version_info >= (3, 5) # Python 3.5 and above
+PY36_PLUS = sys.version_info >= (3, 6) # Python 3.6 and above
try:
sys.pypy_version_info
PYPY = True
@@ -55,12 +56,12 @@ else:
if isinstance(n, ast.Try):
return [n.body + n.orelse] + [[hdl] for hdl in n.handlers]
-if PY34:
- FOR_TYPES = (ast.For,)
- LOOP_TYPES = (ast.While, ast.For)
-else:
+if PY35_PLUS:
FOR_TYPES = (ast.For, ast.AsyncFor)
LOOP_TYPES = (ast.While, ast.For, ast.AsyncFor)
+else:
+ FOR_TYPES = (ast.For,)
+ LOOP_TYPES = (ast.While, ast.For)
class _FieldsOrder(dict):
@@ -486,6 +487,9 @@ class DoctestScope(ModuleScope):
# Globally defined names which are not attributes of the builtins module, or
# are only present on some platforms.
_MAGIC_GLOBALS = ['__file__', '__builtins__', 'WindowsError']
+# module scope annotation will store in `__annotations__`, see also PEP 526.
+if PY36_PLUS:
+ _MAGIC_GLOBALS.append('__annotations__')
def getNodeName(node):
| PyCQA/pyflakes | 6ee966df7e1973771f578bb6d5d041785a0685ec | diff --git a/pyflakes/test/test_undefined_names.py b/pyflakes/test/test_undefined_names.py
index 88eba93..222ffce 100644
--- a/pyflakes/test/test_undefined_names.py
+++ b/pyflakes/test/test_undefined_names.py
@@ -227,6 +227,14 @@ class Test(TestCase):
"""
self.flakes('WindowsError')
+ @skipIf(version_info < (3, 6), 'new feature in 3.6')
+ def test_moduleAnnotations(self):
+ """
+ Use of the C{__annotations__} in module scope should not emit
+ an undefined name warning when version is greater than or equal to 3.6.
+ """
+ self.flakes('__annotations__')
+
def test_magicGlobalsFile(self):
"""
Use of the C{__file__} magic global should not emit an undefined name
| undefined name '__annotations__' when use __annotations__ in module level
Environment:
- Python==3.7.1
- pyflakes==2.0.0
When using pyflake to check following code:
```Python3
# t.py
a: int = 2
print(__annotations__)
```
It will reported that
```
t.py:3: undefined name '__annotations__'
```
About `__annotations__`, please see [PEP 526 -- Syntax for Variable Annotations](https://www.python.org/dev/peps/pep-0526/)
> In addition, at the module or class level, if the item being annotated is a simple name, then it and the annotation will be stored in the `__annotations__` attribute of that module or class (mangled if private) as an ordered mapping from names to evaluated annotations.
And `__annotations__` is not a [`builtin_vars`](https://github.com/PyCQA/pyflakes/blob/master/pyflakes/checker.py#L21), so it will not found.
I think this attribute should be added in [`_MAGIC_GLOBALS = ['__file__', '__builtins__', 'WindowsError']`](https://github.com/PyCQA/pyflakes/blob/master/pyflakes/checker.py#L488)
If you accept this solution, I will pull request to fix it :) | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"pyflakes/test/test_undefined_names.py::Test::test_moduleAnnotations"
] | [
"pyflakes/test/test_undefined_names.py::Test::test_annotationUndefined",
"pyflakes/test/test_undefined_names.py::Test::test_badNestedClass",
"pyflakes/test/test_undefined_names.py::Test::test_builtinWindowsError",
"pyflakes/test/test_undefined_names.py::Test::test_builtins",
"pyflakes/test/test_undefined_names.py::Test::test_definedAsStarArgs",
"pyflakes/test/test_undefined_names.py::Test::test_definedAsStarUnpack",
"pyflakes/test/test_undefined_names.py::Test::test_definedByGlobal",
"pyflakes/test/test_undefined_names.py::Test::test_definedByGlobalMultipleNames",
"pyflakes/test/test_undefined_names.py::Test::test_definedFromLambdaInDictionaryComprehension",
"pyflakes/test/test_undefined_names.py::Test::test_definedFromLambdaInGenerator",
"pyflakes/test/test_undefined_names.py::Test::test_definedInClass",
"pyflakes/test/test_undefined_names.py::Test::test_definedInClassNested",
"pyflakes/test/test_undefined_names.py::Test::test_definedInGenExp",
"pyflakes/test/test_undefined_names.py::Test::test_definedInListComp",
"pyflakes/test/test_undefined_names.py::Test::test_del",
"pyflakes/test/test_undefined_names.py::Test::test_delConditional",
"pyflakes/test/test_undefined_names.py::Test::test_delConditionalNested",
"pyflakes/test/test_undefined_names.py::Test::test_delExceptionInExcept",
"pyflakes/test/test_undefined_names.py::Test::test_delGlobal",
"pyflakes/test/test_undefined_names.py::Test::test_delUndefined",
"pyflakes/test/test_undefined_names.py::Test::test_delWhile",
"pyflakes/test/test_undefined_names.py::Test::test_delWhileNested",
"pyflakes/test/test_undefined_names.py::Test::test_delWhileTestUsage",
"pyflakes/test/test_undefined_names.py::Test::test_doubleNestingReportsClosestName",
"pyflakes/test/test_undefined_names.py::Test::test_dunderClass",
"pyflakes/test/test_undefined_names.py::Test::test_functionsNeedGlobalScope",
"pyflakes/test/test_undefined_names.py::Test::test_globalFromNestedScope",
"pyflakes/test/test_undefined_names.py::Test::test_globalImportStar",
"pyflakes/test/test_undefined_names.py::Test::test_globalInGlobalScope",
"pyflakes/test/test_undefined_names.py::Test::test_global_reset_name_only",
"pyflakes/test/test_undefined_names.py::Test::test_intermediateClassScopeIgnored",
"pyflakes/test/test_undefined_names.py::Test::test_keywordOnlyArgs",
"pyflakes/test/test_undefined_names.py::Test::test_keywordOnlyArgsUndefined",
"pyflakes/test/test_undefined_names.py::Test::test_laterRedefinedGlobalFromNestedScope",
"pyflakes/test/test_undefined_names.py::Test::test_laterRedefinedGlobalFromNestedScope2",
"pyflakes/test/test_undefined_names.py::Test::test_laterRedefinedGlobalFromNestedScope3",
"pyflakes/test/test_undefined_names.py::Test::test_magicGlobalsBuiltins",
"pyflakes/test/test_undefined_names.py::Test::test_magicGlobalsFile",
"pyflakes/test/test_undefined_names.py::Test::test_magicGlobalsName",
"pyflakes/test/test_undefined_names.py::Test::test_magicGlobalsPath",
"pyflakes/test/test_undefined_names.py::Test::test_magicModuleInClassScope",
"pyflakes/test/test_undefined_names.py::Test::test_metaClassUndefined",
"pyflakes/test/test_undefined_names.py::Test::test_namesDeclaredInExceptBlocks",
"pyflakes/test/test_undefined_names.py::Test::test_nestedClass",
"pyflakes/test/test_undefined_names.py::Test::test_undefined",
"pyflakes/test/test_undefined_names.py::Test::test_undefinedAugmentedAssignment",
"pyflakes/test/test_undefined_names.py::Test::test_undefinedExceptionName",
"pyflakes/test/test_undefined_names.py::Test::test_undefinedExceptionNameObscuringGlobalVariableFalsePositive1",
"pyflakes/test/test_undefined_names.py::Test::test_undefinedExceptionNameObscuringGlobalVariableFalsePositive2",
"pyflakes/test/test_undefined_names.py::Test::test_undefinedExceptionNameObscuringLocalVariable2",
"pyflakes/test/test_undefined_names.py::Test::test_undefinedExceptionNameObscuringLocalVariableFalsePositive1",
"pyflakes/test/test_undefined_names.py::Test::test_undefinedExceptionNameObscuringLocalVariableFalsePositive2",
"pyflakes/test/test_undefined_names.py::Test::test_undefinedFromLambdaInComprehension",
"pyflakes/test/test_undefined_names.py::Test::test_undefinedFromLambdaInDictionaryComprehension",
"pyflakes/test/test_undefined_names.py::Test::test_undefinedInGenExpNested",
"pyflakes/test/test_undefined_names.py::Test::test_undefinedInListComp",
"pyflakes/test/test_undefined_names.py::Test::test_undefinedInLoop",
"pyflakes/test/test_undefined_names.py::Test::test_undefinedWithErrorHandler",
"pyflakes/test/test_undefined_names.py::Test::test_unusedAsStarUnpack",
"pyflakes/test/test_undefined_names.py::Test::test_usedAsStarUnpack",
"pyflakes/test/test_undefined_names.py::NameTests::test_impossibleContext"
] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2018-12-31T05:55:48Z" | mit |
|
PyCQA__pyflakes-410 | diff --git a/pyflakes/checker.py b/pyflakes/checker.py
index 3c4fa0f..e94bc71 100644
--- a/pyflakes/checker.py
+++ b/pyflakes/checker.py
@@ -20,6 +20,7 @@ from pyflakes import messages
PY2 = sys.version_info < (3, 0)
PY35_PLUS = sys.version_info >= (3, 5) # Python 3.5 and above
PY36_PLUS = sys.version_info >= (3, 6) # Python 3.6 and above
+PY38_PLUS = sys.version_info >= (3, 8)
try:
sys.pypy_version_info
PYPY = True
@@ -618,6 +619,8 @@ class Checker(object):
ast.GeneratorExp: GeneratorScope,
ast.DictComp: GeneratorScope,
}
+ if PY35_PLUS:
+ _ast_node_scope[ast.AsyncFunctionDef] = FunctionScope,
nodeDepth = 0
offset = None
@@ -1073,7 +1076,7 @@ class Checker(object):
if not isinstance(node, ast.Str):
return (None, None)
- if PYPY:
+ if PYPY or PY38_PLUS:
doctest_lineno = node.lineno - 1
else:
# Computed incorrectly if the docstring has backslash
| PyCQA/pyflakes | f1444872d7e4abfe1359778bca56ad3fd59a6f9b | diff --git a/pyflakes/test/test_type_annotations.py b/pyflakes/test/test_type_annotations.py
index e828412..1ed676b 100644
--- a/pyflakes/test/test_type_annotations.py
+++ b/pyflakes/test/test_type_annotations.py
@@ -179,6 +179,13 @@ class TestTypeAnnotations(TestCase):
a: 'a: "A"'
''', m.ForwardAnnotationSyntaxError)
+ @skipIf(version_info < (3, 5), 'new in Python 3.5')
+ def test_annotated_async_def(self):
+ self.flakes('''
+ class c: pass
+ async def func(c: c) -> None: pass
+ ''')
+
@skipIf(version_info < (3, 7), 'new in Python 3.7')
def test_postponed_annotations(self):
self.flakes('''
| crash: AttributeError: 'Module' object has no attribute 'parent'
9dd73ec54411a563410872b47e76f0f89f34ecfe seems to introduce a bug that causes pyflakes to crash on this code:
```python3
class foo:
pass
async def func(foo: foo):
pass
```
**backtrace:**
```
$ venv/bin/pyflakes foo.py
Traceback (most recent call last):
File "venv/bin/pyflakes", line 11, in <module>
sys.exit(main())
File "venv/lib/python3.7/site-packages/pyflakes/api.py", line 207, in main
warnings = checkRecursive(args, reporter)
File "venv/lib/python3.7/site-packages/pyflakes/api.py", line 156, in checkRecursive
warnings += checkPath(sourcePath, reporter)
File "venv/lib/python3.7/site-packages/pyflakes/api.py", line 99, in checkPath
return check(codestr, filename, reporter)
File "venv/lib/python3.7/site-packages/pyflakes/api.py", line 74, in check
w = checker.Checker(tree, filename)
File "venv/lib/python3.7/site-packages/pyflakes/checker.py", line 579, in __init__
self.runDeferred(self._deferredFunctions)
File "venv/lib/python3.7/site-packages/pyflakes/checker.py", line 616, in runDeferred
handler()
File "venv/lib/python3.7/site-packages/pyflakes/checker.py", line 1354, in runFunction
self.handleChildren(node, omit='decorator_list')
File "venv/lib/python3.7/site-packages/pyflakes/checker.py", line 957, in handleChildren
self.handleNode(node, tree)
File "venv/lib/python3.7/site-packages/pyflakes/checker.py", line 1004, in handleNode
handler(node)
File "venv/lib/python3.7/site-packages/pyflakes/checker.py", line 1379, in ARGUMENTS
self.handleChildren(node, omit=('defaults', 'kw_defaults'))
File "venv/lib/python3.7/site-packages/pyflakes/checker.py", line 957, in handleChildren
self.handleNode(node, tree)
File "venv/lib/python3.7/site-packages/pyflakes/checker.py", line 1004, in handleNode
handler(node)
File "venv/lib/python3.7/site-packages/pyflakes/checker.py", line 1388, in ARG
self.addBinding(node, Argument(node.arg, self.getScopeNode(node)))
File "venv/lib/python3.7/site-packages/pyflakes/checker.py", line 784, in addBinding
parent_stmt = self.getParent(value.source)
File "venv/lib/python3.7/site-packages/pyflakes/checker.py", line 722, in getParent
node = node.parent
AttributeError: 'Module' object has no attribute 'parent'
```
**version:**
* debian/unstable
* python3.7 (from debian)
* pyflakes 066ba4a93c1077f9154d6ff3806fe1e3a66843a1 | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_annotated_async_def"
] | [
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_postponed_annotations",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsAdditionalComemnt",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsAssignedToPreviousNode",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsFullSignature",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsFullSignatureWithDocstring",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsInvalidDoesNotMarkAsUsed",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsMarkImportsAsUsed",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsNoWhitespaceAnnotation",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsSyntaxError",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typingOverload",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_variable_annotations"
] | {
"failed_lite_validators": [
"has_git_commit_hash"
],
"has_test_patch": true,
"is_lite": false
} | "2019-01-17T17:07:55Z" | mit |
|
PyCQA__pyflakes-420 | diff --git a/pyflakes/checker.py b/pyflakes/checker.py
index 70aaff2..4c88af2 100644
--- a/pyflakes/checker.py
+++ b/pyflakes/checker.py
@@ -507,6 +507,13 @@ class DoctestScope(ModuleScope):
"""Scope for a doctest."""
+class DummyNode(object):
+ """Used in place of an `ast.AST` to set error message positions"""
+ def __init__(self, lineno, col_offset):
+ self.lineno = lineno
+ self.col_offset = col_offset
+
+
# Globally defined names which are not attributes of the builtins module, or
# are only present on some platforms.
_MAGIC_GLOBALS = ['__file__', '__builtins__', 'WindowsError']
@@ -1056,7 +1063,7 @@ class Checker(object):
part = part.replace('...', 'Ellipsis')
self.deferFunction(functools.partial(
self.handleStringAnnotation,
- part, node, lineno, col_offset,
+ part, DummyNode(lineno, col_offset), lineno, col_offset,
messages.CommentAnnotationSyntaxError,
))
| PyCQA/pyflakes | 2c29431eaeb9c5b681f1615bf568fc68c6469486 | diff --git a/pyflakes/test/test_type_annotations.py b/pyflakes/test/test_type_annotations.py
index 5af4441..48635bb 100644
--- a/pyflakes/test/test_type_annotations.py
+++ b/pyflakes/test/test_type_annotations.py
@@ -297,6 +297,13 @@ class TestTypeAnnotations(TestCase):
pass
""", m.CommentAnnotationSyntaxError)
+ def test_typeCommentsSyntaxErrorCorrectLine(self):
+ checker = self.flakes("""\
+ x = 1
+ # type: definitely not a PEP 484 comment
+ """, m.CommentAnnotationSyntaxError)
+ self.assertEqual(checker.messages[0].lineno, 2)
+
def test_typeCommentsAssignedToPreviousNode(self):
# This test demonstrates an issue in the implementation which
# associates the type comment with a node above it, however the type
| Incorrect line number for syntax error in type comment
Minor issue, pyflakes 2.1.0 (macOS High Sierra and Ubuntu Xenial) is reporting an issue at line 196 when it's really at line 208. Pyflakes 2.0.0 did not report the issue at all.
To reproduce:
```console
$ pip install -U pyflakes
Requirement already up-to-date: pyflakes in /usr/local/lib/python3.7/site-packages (2.1.0)
$ wget https://raw.githubusercontent.com/python-pillow/Pillow/a656a0bd603bcc333184ad1baf61d118925b3772/Tests/test_file_libtiff.py
--2019-01-30 11:03:02-- https://raw.githubusercontent.com/python-pillow/Pillow/a656a0bd603bcc333184ad1baf61d118925b3772/Tests/test_file_libtiff.py
Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 151.101.244.133
Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|151.101.244.133|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 23915 (23K) [text/plain]
Saving to: ‘test_file_libtiff.py’
test_file_libtiff.py 100%[==============================================================>] 23.35K --.-KB/s in 0.001s
2019-01-30 11:03:02 (15.9 MB/s) - ‘test_file_libtiff.py’ saved [23915/23915]
$ pyflakes test_file_libtiff.py
test_file_libtiff.py:196: syntax error in type comment 'dummy value'
$ grep --line-number "dummy value" test_file_libtiff.py
208: # type: dummy value
```
File on GitHub:
https://github.com/python-pillow/Pillow/blob/a656a0bd603bcc333184ad1baf61d118925b3772/Tests/test_file_libtiff.py#L208
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsSyntaxErrorCorrectLine"
] | [
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_annotated_async_def",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_not_a_typing_overload",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_postponed_annotations",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsAdditionalComemnt",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsAssignedToPreviousNode",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsFullSignature",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsFullSignatureWithDocstring",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsInvalidDoesNotMarkAsUsed",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsMarkImportsAsUsed",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsNoWhitespaceAnnotation",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsStarArgs",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsSyntaxError",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typingOverload",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_variable_annotations"
] | {
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
} | "2019-01-30T09:44:00Z" | mit |
|
PyCQA__pyflakes-423 | diff --git a/.appveyor.yml b/.appveyor.yml
index f7d7aa2..0e05ec3 100644
--- a/.appveyor.yml
+++ b/.appveyor.yml
@@ -1,8 +1,6 @@
# To activate, change the Appveyor settings to use `.appveyor.yml`.
install:
- - ps: "[Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12"
-
- - python -m pip install --upgrade virtualenv pip setuptools tox
+ - python -m pip install --upgrade tox virtualenv
# Fetch the three main PyPy releases
- ps: (New-Object Net.WebClient).DownloadFile('https://bitbucket.org/pypy/pypy/downloads/pypy-2.6.1-win32.zip', "$env:appveyor_build_folder\pypy-2.6.1-win32.zip")
@@ -13,36 +11,16 @@ install:
- ps: 7z x pypy2-v5.3.1-win32.zip | Out-Null
- move pypy2-v5.3.1-win32 C:\
- # Note: pypy3-v5.10.0 is commented out as it needs an updated pip to
- # recognise the new python_requires, but there's a pypy bug preventing that.
- # It's been fixed and will be in the next 5.10.1 release.
- # See https://bitbucket.org/pypy/pypy/issues/2720/ensurepip-on-pypy-c-jit-93579-a4194a67868f
- # and https://stackoverflow.com/q/47999518/724176.
-
-# - ps: (New-Object Net.WebClient).DownloadFile('https://bitbucket.org/pypy/pypy/downloads/pypy3-v5.10.0-win32.zip', "$env:appveyor_build_folder\pypy3-v5.10.0-win32.zip")
-# - ps: 7z x pypy3-v5.10.0-win32.zip | Out-Null
-# - move pypy3-v5.10.0-win32 C:\
-
- # workaround https://github.com/pypa/virtualenv/issues/93
- - mkdir C:\python33\tcl\tcl8.6
- - mkdir C:\python33\tcl\tk8.6
-# - mkdir C:\pypy3-v5.10.0-win32\tcl\tcl8.6
-# - mkdir C:\pypy3-v5.10.0-win32\tcl\tk8.6
-
- # Only pypy2-5.3.1 is integrated into tox, as pypy3-2.4.0 fails and
- # a Windows distribution of pypy3-5.2 isnt available yet.
- - ps: $env:path = "$env:path;C:\pypy2-v5.3.1-win32;C:\pypy-2.6.1-win32\bin"
-
- # pypy3-2.4.0 and pypy-2.6.1 are manually bootstrapped and tested
- - ps: (New-Object Net.WebClient).DownloadFile('https://bootstrap.pypa.io/get-pip.py', "$env:appveyor_build_folder\get-pip.py")
- # errors are ignored due to https://github.com/pypa/pip/issues/2669#issuecomment-136405390
-# - ps: C:\pypy3-v5.10.0-win32\pypy3 "$env:appveyor_build_folder\get-pip.py"; echo "ignore error"
-# - ps: C:\pypy3-v5.10.0-win32\pypy3 -m pip install -U --force-reinstall pip setuptools; echo "ignore error"
- - ps: C:\pypy-2.6.1-win32\pypy "$env:appveyor_build_folder\get-pip.py"
+ # TODO: pypy 6.0.0 offsets are different
+ #- ps: (New-Object Net.WebClient).DownloadFile('https://bitbucket.org/pypy/pypy/downloads/pypy3-v6.0.0-win32.zip', "$env:appveyor_build_folder\pypy3-v6.0.0-win32.zip")
+ #- ps: 7z x pypy3-v6.0.0-win32.zip | Out-Null
+ #- move pypy3-v6.0.0-win32 C:\
build: off
test_script:
- python -m tox
-# - C:\pypy3-v5.10.0-win32\pypy3 -m unittest discover pyflakes
- C:\pypy-2.6.1-win32\pypy -m unittest discover pyflakes
+ - C:\pypy2-v5.3.1-win32\pypy -m unittest discover pyflakes
+ # TODO: pypy 6.0.0 offsets are different
+ #- C:\pypy3-v6.0.0-win32\pypy3 -m unittest discover pyflakes
diff --git a/pyflakes/checker.py b/pyflakes/checker.py
index 650d788..70aaff2 100644
--- a/pyflakes/checker.py
+++ b/pyflakes/checker.py
@@ -529,6 +529,7 @@ def is_typing_overload(value, scope):
(
isinstance(node, ast.Name) and
node.id in scope and
+ isinstance(scope[node.id], ImportationFrom) and
scope[node.id].fullName == 'typing.overload'
) or (
isinstance(node, ast.Attribute) and
| PyCQA/pyflakes | 4bc1f21df9d96b5dd1f5f3e213255b27f7104919 | diff --git a/pyflakes/test/test_type_annotations.py b/pyflakes/test/test_type_annotations.py
index 40397e8..5af4441 100644
--- a/pyflakes/test/test_type_annotations.py
+++ b/pyflakes/test/test_type_annotations.py
@@ -39,6 +39,28 @@ class TestTypeAnnotations(TestCase):
return s
""")
+ def test_not_a_typing_overload(self):
+ """regression test for @typing.overload detection bug in 2.1.0"""
+ self.flakes("""
+ x = lambda f: f
+
+ @x
+ def t():
+ pass
+
+ y = lambda f: f
+
+ @x
+ @y
+ def t():
+ pass
+
+ @x
+ @y
+ def t():
+ pass
+ """, m.RedefinedWhileUnused, m.RedefinedWhileUnused)
+
@skipIf(version_info < (3, 6), 'new in Python 3.6')
def test_variable_annotations(self):
self.flakes('''
| 2.1.0 is broken
https://travis-ci.org/borgbackup/borg/jobs/486513787 | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_not_a_typing_overload"
] | [
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_annotated_async_def",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_postponed_annotations",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsAdditionalComemnt",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsAssignedToPreviousNode",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsFullSignature",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsFullSignatureWithDocstring",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsInvalidDoesNotMarkAsUsed",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsMarkImportsAsUsed",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsNoWhitespaceAnnotation",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsStarArgs",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsSyntaxError",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typingOverload",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_variable_annotations"
] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2019-01-31T00:52:28Z" | mit |
|
PyCQA__pyflakes-435 | diff --git a/pyflakes/checker.py b/pyflakes/checker.py
index 4c88af2..0e636c1 100644
--- a/pyflakes/checker.py
+++ b/pyflakes/checker.py
@@ -530,14 +530,21 @@ def getNodeName(node):
return node.name
-def is_typing_overload(value, scope):
+def is_typing_overload(value, scope_stack):
+ def name_is_typing_overload(name): # type: (str) -> bool
+ for scope in reversed(scope_stack):
+ if name in scope:
+ return (
+ isinstance(scope[name], ImportationFrom) and
+ scope[name].fullName == 'typing.overload'
+ )
+ else:
+ return False
+
def is_typing_overload_decorator(node):
return (
(
- isinstance(node, ast.Name) and
- node.id in scope and
- isinstance(scope[node.id], ImportationFrom) and
- scope[node.id].fullName == 'typing.overload'
+ isinstance(node, ast.Name) and name_is_typing_overload(node.id)
) or (
isinstance(node, ast.Attribute) and
isinstance(node.value, ast.Name) and
@@ -548,8 +555,10 @@ def is_typing_overload(value, scope):
return (
isinstance(value.source, ast.FunctionDef) and
- len(value.source.decorator_list) == 1 and
- is_typing_overload_decorator(value.source.decorator_list[0])
+ any(
+ is_typing_overload_decorator(dec)
+ for dec in value.source.decorator_list
+ )
)
@@ -888,7 +897,7 @@ class Checker(object):
node, value.name, existing.source)
elif not existing.used and value.redefines(existing):
if value.name != '_' or isinstance(existing, Importation):
- if not is_typing_overload(existing, self.scope):
+ if not is_typing_overload(existing, self.scopeStack):
self.report(messages.RedefinedWhileUnused,
node, value.name, existing.source)
| PyCQA/pyflakes | 6ba3f8e0b59b8fe880345be7ae594ccd76661f6d | diff --git a/pyflakes/test/test_type_annotations.py b/pyflakes/test/test_type_annotations.py
index 48635bb..b8876cb 100644
--- a/pyflakes/test/test_type_annotations.py
+++ b/pyflakes/test/test_type_annotations.py
@@ -39,6 +39,41 @@ class TestTypeAnnotations(TestCase):
return s
""")
+ def test_overload_with_multiple_decorators(self):
+ self.flakes("""
+ from typing import overload
+ dec = lambda f: f
+
+ @dec
+ @overload
+ def f(x): # type: (int) -> int
+ pass
+
+ @dec
+ @overload
+ def f(x): # type: (str) -> str
+ pass
+
+ @dec
+ def f(x): return x
+ """)
+
+ def test_overload_in_class(self):
+ self.flakes("""
+ from typing import overload
+
+ class C:
+ @overload
+ def f(self, x): # type: (int) -> int
+ pass
+
+ @overload
+ def f(self, x): # type: (str) -> str
+ pass
+
+ def f(self, x): return x
+ """)
+
def test_not_a_typing_overload(self):
"""regression test for @typing.overload detection bug in 2.1.0"""
self.flakes("""
| F811 (redefinition of unused variable) incorrectly triggered with @overload decorator
This bug was fixed for functions in #320. It still occurs if the function is inside a class and/or has multiple decorators (e.g. @staticmethod, @classmethod):
```python
from typing import overload
class test:
@overload
def utf8(value: None) -> None:
pass
@overload
def utf8(value: bytes) -> bytes:
pass
@overload
def utf8(value: str) -> bytes:
pass
def utf8(value):
pass # actual implementation
```
```
test.py:9:5: F811 redefinition of unused 'utf8' from line 5
test.py:13:5: F811 redefinition of unused 'utf8' from line 9
test.py:17:5: F811 redefinition of unused 'utf8' from line 13
```
```python
from typing import overload
def do_nothing(func):
return func
@overload
@do_nothing
def utf8(value: None) -> None:
pass
@overload
@do_nothing
def utf8(value: bytes) -> bytes:
pass
@overload
@do_nothing
def utf8(value: str) -> bytes:
pass
def utf8(value):
pass # actual implementation
```
```
test.py:14:1: F811 redefinition of unused 'utf8' from line 8
test.py:20:1: F811 redefinition of unused 'utf8' from line 14
test.py:26:1: F811 redefinition of unused 'utf8' from line 20
``` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_overload_in_class",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_overload_with_multiple_decorators"
] | [
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_annotated_async_def",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_not_a_typing_overload",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_postponed_annotations",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsAdditionalComemnt",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsAssignedToPreviousNode",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsFullSignature",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsFullSignatureWithDocstring",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsInvalidDoesNotMarkAsUsed",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsMarkImportsAsUsed",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsNoWhitespaceAnnotation",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsStarArgs",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsSyntaxError",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsSyntaxErrorCorrectLine",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typingOverload",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_variable_annotations"
] | {
"failed_lite_validators": [
"has_issue_reference"
],
"has_test_patch": true,
"is_lite": false
} | "2019-02-22T18:12:26Z" | mit |
|
PyCQA__pyflakes-448 | diff --git a/pyflakes/checker.py b/pyflakes/checker.py
index 0e636c1..83f92aa 100644
--- a/pyflakes/checker.py
+++ b/pyflakes/checker.py
@@ -1480,7 +1480,7 @@ class Checker(object):
self.pushScope()
- self.handleChildren(node, omit='decorator_list')
+ self.handleChildren(node, omit=['decorator_list', 'returns'])
def checkUnusedAssignments():
"""
| PyCQA/pyflakes | 0b163640274b15b74ac9a650cf24439b0205fc76 | diff --git a/pyflakes/test/test_type_annotations.py b/pyflakes/test/test_type_annotations.py
index 03f70bb..9c34dcf 100644
--- a/pyflakes/test/test_type_annotations.py
+++ b/pyflakes/test/test_type_annotations.py
@@ -342,3 +342,23 @@ class TestTypeAnnotations(TestCase):
x = 1
# type: F
""")
+
+ @skipIf(version_info < (3,), 'new in Python 3')
+ def test_return_annotation_is_class_scope_variable(self):
+ self.flakes("""
+ from typing import TypeVar
+ class Test:
+ Y = TypeVar('Y')
+
+ def t(self, x: Y) -> Y:
+ return x
+ """)
+
+ @skipIf(version_info < (3,), 'new in Python 3')
+ def test_return_annotation_is_function_body_variable(self):
+ self.flakes("""
+ class Test:
+ def t(self) -> Y:
+ Y = 2
+ return Y
+ """, m.UndefinedName)
| Class-level `TypeVar` resulting in "undefined name" error
Minimal sample:
```
from typing import TypeVar
class IdClass:
Y = TypeVar('Y')
def id(self, x: Y) -> Y:
return x
```
Result:
```
# pyflakes t.py
t.py:7: undefined name 'Y'
```
MyPy supports such typing annotations and does not complain about this file.
Probably this issue is related to similar ones #427 and #126 | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_return_annotation_is_class_scope_variable"
] | [
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_annotated_async_def",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_not_a_typing_overload",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_overload_in_class",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_overload_with_multiple_decorators",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_postponed_annotations",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_return_annotation_is_function_body_variable",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsAdditionalComemnt",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsAssignedToPreviousNode",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsFullSignature",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsFullSignatureWithDocstring",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsInvalidDoesNotMarkAsUsed",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsMarkImportsAsUsed",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsNoWhitespaceAnnotation",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsStarArgs",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsSyntaxError",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsSyntaxErrorCorrectLine",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typingOverload",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_variable_annotations"
] | {
"failed_lite_validators": [
"has_issue_reference"
],
"has_test_patch": true,
"is_lite": false
} | "2019-06-03T13:46:47Z" | mit |
|
PyCQA__pyflakes-472 | diff --git a/pyflakes/checker.py b/pyflakes/checker.py
index 44c6b25..eca2002 100644
--- a/pyflakes/checker.py
+++ b/pyflakes/checker.py
@@ -72,9 +72,11 @@ else:
if PY35_PLUS:
FOR_TYPES = (ast.For, ast.AsyncFor)
LOOP_TYPES = (ast.While, ast.For, ast.AsyncFor)
+ FUNCTION_TYPES = (ast.FunctionDef, ast.AsyncFunctionDef)
else:
FOR_TYPES = (ast.For,)
LOOP_TYPES = (ast.While, ast.For)
+ FUNCTION_TYPES = (ast.FunctionDef,)
# https://github.com/python/typed_ast/blob/1.4.0/ast27/Parser/tokenizer.c#L102-L104
TYPE_COMMENT_RE = re.compile(r'^#\s*type:\s*')
@@ -642,7 +644,7 @@ def is_typing_overload(value, scope_stack):
)
return (
- isinstance(value.source, ast.FunctionDef) and
+ isinstance(value.source, FUNCTION_TYPES) and
any(
is_typing_overload_decorator(dec)
for dec in value.source.decorator_list
| PyCQA/pyflakes | 5ed30a6b9e4b9c1bb4042e5c5b3b506e52133da4 | diff --git a/pyflakes/test/test_type_annotations.py b/pyflakes/test/test_type_annotations.py
index 676a4a5..045c57a 100644
--- a/pyflakes/test/test_type_annotations.py
+++ b/pyflakes/test/test_type_annotations.py
@@ -56,6 +56,24 @@ class TestTypeAnnotations(TestCase):
return s
""")
+ @skipIf(version_info < (3, 5), 'new in Python 3.5')
+ def test_typingOverloadAsync(self):
+ """Allow intentional redefinitions via @typing.overload (async)"""
+ self.flakes("""
+ from typing import overload
+
+ @overload
+ async def f(s): # type: (None) -> None
+ pass
+
+ @overload
+ async def f(s): # type: (int) -> int
+ pass
+
+ async def f(s):
+ return s
+ """)
+
def test_overload_with_multiple_decorators(self):
self.flakes("""
from typing import overload
| @overload of async functions
Since #435, pyflakes git tip copes with synchronous @overload'ed functions, but not with async ones:
```python
from typing import overload
@overload
def f(x: int) -> int:
...
@overload
def f(x: float) -> float:
...
def f(x):
return x
@overload
async def g(x: int) -> int:
...
@overload
async def g(x: float) -> float:
...
async def g(x):
return x
```
```bash
$ python -m pyflakes .
18:1 redefinition of unused 'g' from line 14
22:1 redefinition of unused 'g' from line 18
``` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typingOverloadAsync"
] | [
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_annotated_async_def",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_not_a_typing_overload",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_overload_in_class",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_overload_with_multiple_decorators",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_postponed_annotations",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_return_annotation_is_class_scope_variable",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_return_annotation_is_function_body_variable",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsAdditionalComemnt",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsAssignedToPreviousNode",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsFullSignature",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsFullSignatureWithDocstring",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsInvalidDoesNotMarkAsUsed",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsMarkImportsAsUsed",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsNoWhitespaceAnnotation",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsStarArgs",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsSyntaxError",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsSyntaxErrorCorrectLine",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeIgnore",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeIgnoreBogus",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeIgnoreBogusUnicode",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typingExtensionsOverload",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typingOverload",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_variable_annotations"
] | {
"failed_lite_validators": [
"has_issue_reference"
],
"has_test_patch": true,
"is_lite": false
} | "2019-09-23T12:32:58Z" | mit |
|
PyCQA__pyflakes-479 | diff --git a/pyflakes/checker.py b/pyflakes/checker.py
index d157008..c89d6fb 100644
--- a/pyflakes/checker.py
+++ b/pyflakes/checker.py
@@ -618,40 +618,55 @@ def getNodeName(node):
return node.name
-def is_typing_overload(value, scope_stack):
- def name_is_typing_overload(name): # type: (str) -> bool
+def _is_typing(node, typing_attr, scope_stack):
+ def _bare_name_is_attr(name):
+ expected_typing_names = {
+ 'typing.{}'.format(typing_attr),
+ 'typing_extensions.{}'.format(typing_attr),
+ }
for scope in reversed(scope_stack):
if name in scope:
return (
isinstance(scope[name], ImportationFrom) and
- scope[name].fullName in (
- 'typing.overload', 'typing_extensions.overload',
- )
+ scope[name].fullName in expected_typing_names
)
return False
- def is_typing_overload_decorator(node):
- return (
- (
- isinstance(node, ast.Name) and name_is_typing_overload(node.id)
- ) or (
- isinstance(node, ast.Attribute) and
- isinstance(node.value, ast.Name) and
- node.value.id == 'typing' and
- node.attr == 'overload'
- )
+ return (
+ (
+ isinstance(node, ast.Name) and
+ _bare_name_is_attr(node.id)
+ ) or (
+ isinstance(node, ast.Attribute) and
+ isinstance(node.value, ast.Name) and
+ node.value.id in {'typing', 'typing_extensions'} and
+ node.attr == typing_attr
)
+ )
+
+def is_typing_overload(value, scope_stack):
return (
isinstance(value.source, FUNCTION_TYPES) and
any(
- is_typing_overload_decorator(dec)
+ _is_typing(dec, 'overload', scope_stack)
for dec in value.source.decorator_list
)
)
+def in_annotation(func):
+ @functools.wraps(func)
+ def in_annotation_func(self, *args, **kwargs):
+ orig, self._in_annotation = self._in_annotation, True
+ try:
+ return func(self, *args, **kwargs)
+ finally:
+ self._in_annotation = orig
+ return in_annotation_func
+
+
def make_tokens(code):
# PY3: tokenize.tokenize requires readline of bytes
if not isinstance(code, bytes):
@@ -738,6 +753,9 @@ class Checker(object):
nodeDepth = 0
offset = None
traceTree = False
+ _in_annotation = False
+ _in_typing_literal = False
+ _in_deferred = False
builtIns = set(builtin_vars).union(_MAGIC_GLOBALS)
_customBuiltIns = os.environ.get('PYFLAKES_BUILTINS')
@@ -769,6 +787,7 @@ class Checker(object):
for builtin in self.builtIns:
self.addBinding(None, Builtin(builtin))
self.handleChildren(tree)
+ self._in_deferred = True
self.runDeferred(self._deferredFunctions)
# Set _deferredFunctions to None so that deferFunction will fail
# noisily if called after we've run through the deferred functions.
@@ -1009,12 +1028,30 @@ class Checker(object):
self.scope[value.name] = value
+ def _unknown_handler(self, node):
+ # this environment variable configures whether to error on unknown
+ # ast types.
+ #
+ # this is silent by default but the error is enabled for the pyflakes
+ # testsuite.
+ #
+ # this allows new syntax to be added to python without *requiring*
+ # changes from the pyflakes side. but will still produce an error
+ # in the pyflakes testsuite (so more specific handling can be added if
+ # needed).
+ if os.environ.get('PYFLAKES_ERROR_UNKNOWN'):
+ raise NotImplementedError('Unexpected type: {}'.format(type(node)))
+ else:
+ self.handleChildren(node)
+
def getNodeHandler(self, node_class):
try:
return self._nodeHandlers[node_class]
except KeyError:
nodeType = getNodeType(node_class)
- self._nodeHandlers[node_class] = handler = getattr(self, nodeType)
+ self._nodeHandlers[node_class] = handler = getattr(
+ self, nodeType, self._unknown_handler,
+ )
return handler
def handleNodeLoad(self, node):
@@ -1281,6 +1318,7 @@ class Checker(object):
self.popScope()
self.scopeStack = saved_stack
+ @in_annotation
def handleStringAnnotation(self, s, node, ref_lineno, ref_col_offset, err):
try:
tree = ast.parse(s)
@@ -1304,6 +1342,7 @@ class Checker(object):
self.handleNode(parsed_annotation, node)
+ @in_annotation
def handleAnnotation(self, annotation, node):
if isinstance(annotation, ast.Str):
# Defer handling forward annotation.
@@ -1316,7 +1355,8 @@ class Checker(object):
messages.ForwardAnnotationSyntaxError,
))
elif self.annotationsFutureEnabled:
- self.deferFunction(lambda: self.handleNode(annotation, node))
+ fn = in_annotation(Checker.handleNode)
+ self.deferFunction(lambda: fn(self, annotation, node))
else:
self.handleNode(annotation, node)
@@ -1332,9 +1372,19 @@ class Checker(object):
# "expr" type nodes
BOOLOP = UNARYOP = IFEXP = SET = \
- REPR = ATTRIBUTE = SUBSCRIPT = \
+ REPR = ATTRIBUTE = \
STARRED = NAMECONSTANT = NAMEDEXPR = handleChildren
+ def SUBSCRIPT(self, node):
+ if _is_typing(node.value, 'Literal', self.scopeStack):
+ orig, self._in_typing_literal = self._in_typing_literal, True
+ try:
+ self.handleChildren(node)
+ finally:
+ self._in_typing_literal = orig
+ else:
+ self.handleChildren(node)
+
def _handle_string_dot_format(self, node):
try:
placeholders = tuple(parse_format_string(node.func.value.s))
@@ -1575,7 +1625,27 @@ class Checker(object):
self._handle_percent_format(node)
self.handleChildren(node)
- NUM = STR = BYTES = ELLIPSIS = CONSTANT = ignore
+ def STR(self, node):
+ if self._in_annotation and not self._in_typing_literal:
+ fn = functools.partial(
+ self.handleStringAnnotation,
+ node.s,
+ node,
+ node.lineno,
+ node.col_offset,
+ messages.ForwardAnnotationSyntaxError,
+ )
+ if self._in_deferred:
+ fn()
+ else:
+ self.deferFunction(fn)
+
+ if PY38_PLUS:
+ def CONSTANT(self, node):
+ if isinstance(node.value, str):
+ return self.STR(node)
+ else:
+ NUM = BYTES = ELLIPSIS = CONSTANT = ignore
# "slice" type nodes
SLICE = EXTSLICE = INDEX = handleChildren
diff --git a/tox.ini b/tox.ini
index 5821483..f2256c8 100644
--- a/tox.ini
+++ b/tox.ini
@@ -5,6 +5,7 @@ envlist =
[testenv]
deps = flake8==3.6.0
+setenv = PYFLAKES_ERROR_UNKNOWN=1
commands =
python -m unittest discover pyflakes
flake8 pyflakes setup.py
| PyCQA/pyflakes | be88036019005b769596ca82fb7b82dfdffdca0f | diff --git a/pyflakes/test/test_type_annotations.py b/pyflakes/test/test_type_annotations.py
index 1fa4f5e..15c658b 100644
--- a/pyflakes/test/test_type_annotations.py
+++ b/pyflakes/test/test_type_annotations.py
@@ -42,6 +42,7 @@ class TestTypeAnnotations(TestCase):
def test_typingExtensionsOverload(self):
"""Allow intentional redefinitions via @typing_extensions.overload"""
self.flakes("""
+ import typing_extensions
from typing_extensions import overload
@overload
@@ -54,6 +55,17 @@ class TestTypeAnnotations(TestCase):
def f(s):
return s
+
+ @typing_extensions.overload
+ def g(s): # type: (None) -> None
+ pass
+
+ @typing_extensions.overload
+ def g(s): # type: (int) -> int
+ pass
+
+ def g(s):
+ return s
""")
@skipIf(version_info < (3, 5), 'new in Python 3.5')
@@ -426,3 +438,64 @@ class TestTypeAnnotations(TestCase):
def f(c: C, /): ...
""")
+
+ @skipIf(version_info < (3,), 'new in Python 3')
+ def test_partially_quoted_type_annotation(self):
+ self.flakes("""
+ from queue import Queue
+ from typing import Optional
+
+ def f() -> Optional['Queue[str]']:
+ return None
+ """)
+
+ @skipIf(version_info < (3,), 'new in Python 3')
+ def test_literal_type_typing(self):
+ self.flakes("""
+ from typing import Literal
+
+ def f(x: Literal['some string']) -> None:
+ return None
+ """)
+
+ @skipIf(version_info < (3,), 'new in Python 3')
+ def test_literal_type_typing_extensions(self):
+ self.flakes("""
+ from typing_extensions import Literal
+
+ def f(x: Literal['some string']) -> None:
+ return None
+ """)
+
+ @skipIf(version_info < (3,), 'new in Python 3')
+ def test_literal_union_type_typing(self):
+ self.flakes("""
+ from typing import Literal
+
+ def f(x: Literal['some string', 'foo bar']) -> None:
+ return None
+ """)
+
+ @skipIf(version_info < (3,), 'new in Python 3')
+ def test_deferred_twice_annotation(self):
+ self.flakes("""
+ from queue import Queue
+ from typing import Optional
+
+
+ def f() -> "Optional['Queue[str]']":
+ return None
+ """)
+
+ @skipIf(version_info < (3, 7), 'new in Python 3.7')
+ def test_partial_string_annotations_with_future_annotations(self):
+ self.flakes("""
+ from __future__ import annotations
+
+ from queue import Queue
+ from typing import Optional
+
+
+ def f() -> Optional['Queue[str]']:
+ return None
+ """)
| Spurious import warning for type used in nested quoted annotation
This is similar to #290 and #313, but seems to still be an issue.
If you import a type and then use it only within a type annotation which includes a nested quoted part, then `pyflakes` reports the import as unused.
``` python
from queue import Queue # F401: 'queue.Queue' imported but unused
from typing import Optional
def foo(queue: Optional['Queue[int]'] = None) -> None:
print(queue)
# Revealed type is 'def (queue: Union[queue.Queue[builtins.int], None] =)'
reveal_type(foo)
```
This can be worked around by quoting the whole of the type annotation:
``` python
def foo(queue: 'Optional[Queue[int]]' = None) -> None:
print(queue)
```
I'm using pyflakes 2.1.1 on Python 3.5.2 on Linux. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_deferred_twice_annotation",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_partial_string_annotations_with_future_annotations",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_partially_quoted_type_annotation",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typingExtensionsOverload"
] | [
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_annotated_async_def",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_literal_type_typing",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_literal_type_typing_extensions",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_literal_union_type_typing",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_not_a_typing_overload",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_overload_in_class",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_overload_with_multiple_decorators",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_positional_only_argument_annotations",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_postponed_annotations",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_return_annotation_is_class_scope_variable",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_return_annotation_is_function_body_variable",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsAdditionalComment",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsAssignedToPreviousNode",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsFullSignature",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsFullSignatureWithDocstring",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsInvalidDoesNotMarkAsUsed",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsMarkImportsAsUsed",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsNoWhitespaceAnnotation",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsStarArgs",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsSyntaxError",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsSyntaxErrorCorrectLine",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeIgnore",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeIgnoreBogus",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeIgnoreBogusUnicode",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typingOverload",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typingOverloadAsync",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_variable_annotations"
] | {
"failed_lite_validators": [
"has_issue_reference",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2019-10-05T20:43:14Z" | mit |
|
PyCQA__pyflakes-484 | diff --git a/pyflakes/checker.py b/pyflakes/checker.py
index eca2002..351ab12 100644
--- a/pyflakes/checker.py
+++ b/pyflakes/checker.py
@@ -78,6 +78,51 @@ else:
LOOP_TYPES = (ast.While, ast.For)
FUNCTION_TYPES = (ast.FunctionDef,)
+
+if PY38_PLUS:
+ def _is_singleton(node): # type: (ast.AST) -> bool
+ return (
+ isinstance(node, ast.Constant) and
+ isinstance(node.value, (bool, type(Ellipsis), type(None)))
+ )
+elif not PY2:
+ def _is_singleton(node): # type: (ast.AST) -> bool
+ return isinstance(node, (ast.NameConstant, ast.Ellipsis))
+else:
+ def _is_singleton(node): # type: (ast.AST) -> bool
+ return (
+ isinstance(node, ast.Name) and
+ node.id in {'True', 'False', 'Ellipsis', 'None'}
+ )
+
+
+def _is_tuple_constant(node): # type: (ast.AST) -> bool
+ return (
+ isinstance(node, ast.Tuple) and
+ all(_is_constant(elt) for elt in node.elts)
+ )
+
+
+if PY38_PLUS:
+ def _is_constant(node):
+ return isinstance(node, ast.Constant) or _is_tuple_constant(node)
+else:
+ _const_tps = (ast.Str, ast.Num)
+ if not PY2:
+ _const_tps += (ast.Bytes,)
+
+ def _is_constant(node):
+ return (
+ isinstance(node, _const_tps) or
+ _is_singleton(node) or
+ _is_tuple_constant(node)
+ )
+
+
+def _is_const_non_singleton(node): # type: (ast.AST) -> bool
+ return _is_constant(node) and not _is_singleton(node)
+
+
# https://github.com/python/typed_ast/blob/1.4.0/ast27/Parser/tokenizer.c#L102-L104
TYPE_COMMENT_RE = re.compile(r'^#\s*type:\s*')
# https://github.com/python/typed_ast/blob/1.4.0/ast27/Parser/tokenizer.c#L1408-L1413
@@ -618,40 +663,55 @@ def getNodeName(node):
return node.name
-def is_typing_overload(value, scope_stack):
- def name_is_typing_overload(name): # type: (str) -> bool
+def _is_typing(node, typing_attr, scope_stack):
+ def _bare_name_is_attr(name):
+ expected_typing_names = {
+ 'typing.{}'.format(typing_attr),
+ 'typing_extensions.{}'.format(typing_attr),
+ }
for scope in reversed(scope_stack):
if name in scope:
return (
isinstance(scope[name], ImportationFrom) and
- scope[name].fullName in (
- 'typing.overload', 'typing_extensions.overload',
- )
+ scope[name].fullName in expected_typing_names
)
return False
- def is_typing_overload_decorator(node):
- return (
- (
- isinstance(node, ast.Name) and name_is_typing_overload(node.id)
- ) or (
- isinstance(node, ast.Attribute) and
- isinstance(node.value, ast.Name) and
- node.value.id == 'typing' and
- node.attr == 'overload'
- )
+ return (
+ (
+ isinstance(node, ast.Name) and
+ _bare_name_is_attr(node.id)
+ ) or (
+ isinstance(node, ast.Attribute) and
+ isinstance(node.value, ast.Name) and
+ node.value.id in {'typing', 'typing_extensions'} and
+ node.attr == typing_attr
)
+ )
+
+def is_typing_overload(value, scope_stack):
return (
isinstance(value.source, FUNCTION_TYPES) and
any(
- is_typing_overload_decorator(dec)
+ _is_typing(dec, 'overload', scope_stack)
for dec in value.source.decorator_list
)
)
+def in_annotation(func):
+ @functools.wraps(func)
+ def in_annotation_func(self, *args, **kwargs):
+ orig, self._in_annotation = self._in_annotation, True
+ try:
+ return func(self, *args, **kwargs)
+ finally:
+ self._in_annotation = orig
+ return in_annotation_func
+
+
def make_tokens(code):
# PY3: tokenize.tokenize requires readline of bytes
if not isinstance(code, bytes):
@@ -738,6 +798,9 @@ class Checker(object):
nodeDepth = 0
offset = None
traceTree = False
+ _in_annotation = False
+ _in_typing_literal = False
+ _in_deferred = False
builtIns = set(builtin_vars).union(_MAGIC_GLOBALS)
_customBuiltIns = os.environ.get('PYFLAKES_BUILTINS')
@@ -769,6 +832,7 @@ class Checker(object):
for builtin in self.builtIns:
self.addBinding(None, Builtin(builtin))
self.handleChildren(tree)
+ self._in_deferred = True
self.runDeferred(self._deferredFunctions)
# Set _deferredFunctions to None so that deferFunction will fail
# noisily if called after we've run through the deferred functions.
@@ -1009,12 +1073,30 @@ class Checker(object):
self.scope[value.name] = value
+ def _unknown_handler(self, node):
+ # this environment variable configures whether to error on unknown
+ # ast types.
+ #
+ # this is silent by default but the error is enabled for the pyflakes
+ # testsuite.
+ #
+ # this allows new syntax to be added to python without *requiring*
+ # changes from the pyflakes side. but will still produce an error
+ # in the pyflakes testsuite (so more specific handling can be added if
+ # needed).
+ if os.environ.get('PYFLAKES_ERROR_UNKNOWN'):
+ raise NotImplementedError('Unexpected type: {}'.format(type(node)))
+ else:
+ self.handleChildren(node)
+
def getNodeHandler(self, node_class):
try:
return self._nodeHandlers[node_class]
except KeyError:
nodeType = getNodeType(node_class)
- self._nodeHandlers[node_class] = handler = getattr(self, nodeType)
+ self._nodeHandlers[node_class] = handler = getattr(
+ self, nodeType, self._unknown_handler,
+ )
return handler
def handleNodeLoad(self, node):
@@ -1281,6 +1363,7 @@ class Checker(object):
self.popScope()
self.scopeStack = saved_stack
+ @in_annotation
def handleStringAnnotation(self, s, node, ref_lineno, ref_col_offset, err):
try:
tree = ast.parse(s)
@@ -1304,6 +1387,7 @@ class Checker(object):
self.handleNode(parsed_annotation, node)
+ @in_annotation
def handleAnnotation(self, annotation, node):
if isinstance(annotation, ast.Str):
# Defer handling forward annotation.
@@ -1316,7 +1400,8 @@ class Checker(object):
messages.ForwardAnnotationSyntaxError,
))
elif self.annotationsFutureEnabled:
- self.deferFunction(lambda: self.handleNode(annotation, node))
+ fn = in_annotation(Checker.handleNode)
+ self.deferFunction(lambda: fn(self, annotation, node))
else:
self.handleNode(annotation, node)
@@ -1332,9 +1417,19 @@ class Checker(object):
# "expr" type nodes
BOOLOP = UNARYOP = IFEXP = SET = \
- REPR = ATTRIBUTE = SUBSCRIPT = \
+ REPR = ATTRIBUTE = \
STARRED = NAMECONSTANT = NAMEDEXPR = handleChildren
+ def SUBSCRIPT(self, node):
+ if _is_typing(node.value, 'Literal', self.scopeStack):
+ orig, self._in_typing_literal = self._in_typing_literal, True
+ try:
+ self.handleChildren(node)
+ finally:
+ self._in_typing_literal = orig
+ else:
+ self.handleChildren(node)
+
def _handle_string_dot_format(self, node):
try:
placeholders = tuple(parse_format_string(node.func.value.s))
@@ -1575,7 +1670,27 @@ class Checker(object):
self._handle_percent_format(node)
self.handleChildren(node)
- NUM = STR = BYTES = ELLIPSIS = CONSTANT = ignore
+ def STR(self, node):
+ if self._in_annotation and not self._in_typing_literal:
+ fn = functools.partial(
+ self.handleStringAnnotation,
+ node.s,
+ node,
+ node.lineno,
+ node.col_offset,
+ messages.ForwardAnnotationSyntaxError,
+ )
+ if self._in_deferred:
+ fn()
+ else:
+ self.deferFunction(fn)
+
+ if PY38_PLUS:
+ def CONSTANT(self, node):
+ if isinstance(node.value, str):
+ return self.STR(node)
+ else:
+ NUM = BYTES = ELLIPSIS = CONSTANT = ignore
# "slice" type nodes
SLICE = EXTSLICE = INDEX = handleChildren
@@ -1738,7 +1853,7 @@ class Checker(object):
break
# Handle Try/TryFinally difference in Python < and >= 3.3
if hasattr(n, 'finalbody') and isinstance(node, ast.Continue):
- if n_child in n.finalbody:
+ if n_child in n.finalbody and not PY38_PLUS:
self.report(messages.ContinueInFinally, node)
return
if isinstance(node, ast.Continue):
@@ -1799,6 +1914,10 @@ class Checker(object):
addArgs(node.args.args)
defaults = node.args.defaults
else:
+ if PY38_PLUS:
+ for arg in node.args.posonlyargs:
+ args.append(arg.arg)
+ annotations.append(arg.annotation)
for arg in node.args.args + node.args.kwonlyargs:
args.append(arg.arg)
annotations.append(arg.annotation)
@@ -2050,14 +2169,14 @@ class Checker(object):
self.handleNode(node.value, node)
def COMPARE(self, node):
- literals = (ast.Str, ast.Num)
- if not PY2:
- literals += (ast.Bytes,)
-
left = node.left
for op, right in zip(node.ops, node.comparators):
- if (isinstance(op, (ast.Is, ast.IsNot)) and
- (isinstance(left, literals) or isinstance(right, literals))):
+ if (
+ isinstance(op, (ast.Is, ast.IsNot)) and (
+ _is_const_non_singleton(left) or
+ _is_const_non_singleton(right)
+ )
+ ):
self.report(messages.IsLiteral, node)
left = right
diff --git a/pyflakes/messages.py b/pyflakes/messages.py
index cf67cf8..e93a493 100644
--- a/pyflakes/messages.py
+++ b/pyflakes/messages.py
@@ -265,7 +265,7 @@ class InvalidPrintSyntax(Message):
class IsLiteral(Message):
- message = 'use ==/!= to compare str, bytes, and int literals'
+ message = 'use ==/!= to compare constant literals (str, bytes, int, float, tuple)'
class FStringMissingPlaceholders(Message):
diff --git a/tox.ini b/tox.ini
index 5821483..f2256c8 100644
--- a/tox.ini
+++ b/tox.ini
@@ -5,6 +5,7 @@ envlist =
[testenv]
deps = flake8==3.6.0
+setenv = PYFLAKES_ERROR_UNKNOWN=1
commands =
python -m unittest discover pyflakes
flake8 pyflakes setup.py
| PyCQA/pyflakes | ffe938667e03b02ab8c1dfad98d30998e7d712ec | diff --git a/pyflakes/test/test_is_literal.py b/pyflakes/test/test_is_literal.py
index 9280cda..fbbb205 100644
--- a/pyflakes/test/test_is_literal.py
+++ b/pyflakes/test/test_is_literal.py
@@ -198,3 +198,25 @@ class Test(TestCase):
if 4 < x is 'foo':
pass
""", IsLiteral)
+
+ def test_is_tuple_constant(self):
+ self.flakes('''\
+ x = 5
+ if x is ():
+ pass
+ ''', IsLiteral)
+
+ def test_is_tuple_constant_containing_constants(self):
+ self.flakes('''\
+ x = 5
+ if x is (1, '2', True, (1.5, ())):
+ pass
+ ''', IsLiteral)
+
+ def test_is_tuple_containing_variables_ok(self):
+ # a bit nonsensical, but does not trigger a SyntaxWarning
+ self.flakes('''\
+ x = 5
+ if x is (x,):
+ pass
+ ''')
diff --git a/pyflakes/test/test_other.py b/pyflakes/test/test_other.py
index df2f790..282accb 100644
--- a/pyflakes/test/test_other.py
+++ b/pyflakes/test/test_other.py
@@ -493,8 +493,10 @@ class Test(TestCase):
continue
''')
+ @skipIf(version_info > (3, 8), "Python <= 3.8 only")
def test_continueInFinally(self):
# 'continue' inside 'finally' is a special syntax error
+ # that is removed in 3.8
self.flakes('''
while True:
try:
@@ -2003,6 +2005,7 @@ class TestAsyncStatements(TestCase):
''', m.BreakOutsideLoop)
@skipIf(version_info < (3, 5), 'new in Python 3.5')
+ @skipIf(version_info > (3, 8), "Python <= 3.8 only")
def test_continueInAsyncForFinally(self):
self.flakes('''
async def read_data(db):
diff --git a/pyflakes/test/test_type_annotations.py b/pyflakes/test/test_type_annotations.py
index 289535d..15c658b 100644
--- a/pyflakes/test/test_type_annotations.py
+++ b/pyflakes/test/test_type_annotations.py
@@ -42,6 +42,7 @@ class TestTypeAnnotations(TestCase):
def test_typingExtensionsOverload(self):
"""Allow intentional redefinitions via @typing_extensions.overload"""
self.flakes("""
+ import typing_extensions
from typing_extensions import overload
@overload
@@ -54,6 +55,17 @@ class TestTypeAnnotations(TestCase):
def f(s):
return s
+
+ @typing_extensions.overload
+ def g(s): # type: (None) -> None
+ pass
+
+ @typing_extensions.overload
+ def g(s): # type: (int) -> int
+ pass
+
+ def g(s):
+ return s
""")
@skipIf(version_info < (3, 5), 'new in Python 3.5')
@@ -418,3 +430,72 @@ class TestTypeAnnotations(TestCase):
Y = 2
return Y
""", m.UndefinedName)
+
+ @skipIf(version_info < (3, 8), 'new in Python 3.8')
+ def test_positional_only_argument_annotations(self):
+ self.flakes("""
+ from x import C
+
+ def f(c: C, /): ...
+ """)
+
+ @skipIf(version_info < (3,), 'new in Python 3')
+ def test_partially_quoted_type_annotation(self):
+ self.flakes("""
+ from queue import Queue
+ from typing import Optional
+
+ def f() -> Optional['Queue[str]']:
+ return None
+ """)
+
+ @skipIf(version_info < (3,), 'new in Python 3')
+ def test_literal_type_typing(self):
+ self.flakes("""
+ from typing import Literal
+
+ def f(x: Literal['some string']) -> None:
+ return None
+ """)
+
+ @skipIf(version_info < (3,), 'new in Python 3')
+ def test_literal_type_typing_extensions(self):
+ self.flakes("""
+ from typing_extensions import Literal
+
+ def f(x: Literal['some string']) -> None:
+ return None
+ """)
+
+ @skipIf(version_info < (3,), 'new in Python 3')
+ def test_literal_union_type_typing(self):
+ self.flakes("""
+ from typing import Literal
+
+ def f(x: Literal['some string', 'foo bar']) -> None:
+ return None
+ """)
+
+ @skipIf(version_info < (3,), 'new in Python 3')
+ def test_deferred_twice_annotation(self):
+ self.flakes("""
+ from queue import Queue
+ from typing import Optional
+
+
+ def f() -> "Optional['Queue[str]']":
+ return None
+ """)
+
+ @skipIf(version_info < (3, 7), 'new in Python 3.7')
+ def test_partial_string_annotations_with_future_annotations(self):
+ self.flakes("""
+ from __future__ import annotations
+
+ from queue import Queue
+ from typing import Optional
+
+
+ def f() -> Optional['Queue[str]']:
+ return None
+ """)
| python 3.8 SyntaxWarning: "is" with a literal. Did you mean "=="?
Hi there -
I searched a bit for this but couldn't find it. This is a warning generated by Python 3.8 and I think it's new. It's very hard to get pytest to raise for this, so it would be better if it were in pyflakes / flake8.
demo:
```
"""test a syntax warning."""
x = 5
if x is ():
print("hi")
```
```
$ /opt/python3.8/bin/python3 -m py_compile test.py
test.py:5: SyntaxWarning: "is" with a literal. Did you mean "=="?
if x is ():
```
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"pyflakes/test/test_is_literal.py::Test::test_is_tuple_constant",
"pyflakes/test/test_is_literal.py::Test::test_is_tuple_constant_containing_constants",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_deferred_twice_annotation",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_partial_string_annotations_with_future_annotations",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_partially_quoted_type_annotation",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_positional_only_argument_annotations",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typingExtensionsOverload"
] | [
"pyflakes/test/test_is_literal.py::Test::test_chained_operators_is_str",
"pyflakes/test/test_is_literal.py::Test::test_chained_operators_is_str_end",
"pyflakes/test/test_is_literal.py::Test::test_chained_operators_is_true",
"pyflakes/test/test_is_literal.py::Test::test_chained_operators_is_true_end",
"pyflakes/test/test_is_literal.py::Test::test_is_bytes",
"pyflakes/test/test_is_literal.py::Test::test_is_false",
"pyflakes/test/test_is_literal.py::Test::test_is_int",
"pyflakes/test/test_is_literal.py::Test::test_is_not_bytes",
"pyflakes/test/test_is_literal.py::Test::test_is_not_false",
"pyflakes/test/test_is_literal.py::Test::test_is_not_int",
"pyflakes/test/test_is_literal.py::Test::test_is_not_str",
"pyflakes/test/test_is_literal.py::Test::test_is_not_true",
"pyflakes/test/test_is_literal.py::Test::test_is_not_unicode",
"pyflakes/test/test_is_literal.py::Test::test_is_str",
"pyflakes/test/test_is_literal.py::Test::test_is_true",
"pyflakes/test/test_is_literal.py::Test::test_is_tuple_containing_variables_ok",
"pyflakes/test/test_is_literal.py::Test::test_is_unicode",
"pyflakes/test/test_is_literal.py::Test::test_left_is_bytes",
"pyflakes/test/test_is_literal.py::Test::test_left_is_false",
"pyflakes/test/test_is_literal.py::Test::test_left_is_int",
"pyflakes/test/test_is_literal.py::Test::test_left_is_not_bytes",
"pyflakes/test/test_is_literal.py::Test::test_left_is_not_false",
"pyflakes/test/test_is_literal.py::Test::test_left_is_not_int",
"pyflakes/test/test_is_literal.py::Test::test_left_is_not_str",
"pyflakes/test/test_is_literal.py::Test::test_left_is_not_true",
"pyflakes/test/test_is_literal.py::Test::test_left_is_not_unicode",
"pyflakes/test/test_is_literal.py::Test::test_left_is_str",
"pyflakes/test/test_is_literal.py::Test::test_left_is_true",
"pyflakes/test/test_is_literal.py::Test::test_left_is_unicode",
"pyflakes/test/test_other.py::Test::test_attrAugmentedAssignment",
"pyflakes/test/test_other.py::Test::test_breakInsideLoop",
"pyflakes/test/test_other.py::Test::test_breakOutsideLoop",
"pyflakes/test/test_other.py::Test::test_classFunctionDecorator",
"pyflakes/test/test_other.py::Test::test_classNameDefinedPreviously",
"pyflakes/test/test_other.py::Test::test_classNameUndefinedInClassBody",
"pyflakes/test/test_other.py::Test::test_classRedefinedAsFunction",
"pyflakes/test/test_other.py::Test::test_classRedefinition",
"pyflakes/test/test_other.py::Test::test_classWithReturn",
"pyflakes/test/test_other.py::Test::test_classWithYield",
"pyflakes/test/test_other.py::Test::test_classWithYieldFrom",
"pyflakes/test/test_other.py::Test::test_comparison",
"pyflakes/test/test_other.py::Test::test_containment",
"pyflakes/test/test_other.py::Test::test_continueInsideLoop",
"pyflakes/test/test_other.py::Test::test_continueOutsideLoop",
"pyflakes/test/test_other.py::Test::test_defaultExceptLast",
"pyflakes/test/test_other.py::Test::test_defaultExceptNotLast",
"pyflakes/test/test_other.py::Test::test_doubleAssignmentConditionally",
"pyflakes/test/test_other.py::Test::test_doubleAssignmentWithUse",
"pyflakes/test/test_other.py::Test::test_duplicateArgs",
"pyflakes/test/test_other.py::Test::test_ellipsis",
"pyflakes/test/test_other.py::Test::test_extendedSlice",
"pyflakes/test/test_other.py::Test::test_functionDecorator",
"pyflakes/test/test_other.py::Test::test_functionRedefinedAsClass",
"pyflakes/test/test_other.py::Test::test_function_arguments",
"pyflakes/test/test_other.py::Test::test_function_arguments_python3",
"pyflakes/test/test_other.py::Test::test_globalDeclaredInDifferentScope",
"pyflakes/test/test_other.py::Test::test_identity",
"pyflakes/test/test_other.py::Test::test_localReferencedBeforeAssignment",
"pyflakes/test/test_other.py::Test::test_loopControl",
"pyflakes/test/test_other.py::Test::test_modernProperty",
"pyflakes/test/test_other.py::Test::test_moduleWithReturn",
"pyflakes/test/test_other.py::Test::test_moduleWithYield",
"pyflakes/test/test_other.py::Test::test_moduleWithYieldFrom",
"pyflakes/test/test_other.py::Test::test_redefinedClassFunction",
"pyflakes/test/test_other.py::Test::test_redefinedFunction",
"pyflakes/test/test_other.py::Test::test_redefinedIfElseFunction",
"pyflakes/test/test_other.py::Test::test_redefinedIfElseInListComp",
"pyflakes/test/test_other.py::Test::test_redefinedIfFunction",
"pyflakes/test/test_other.py::Test::test_redefinedInDictComprehension",
"pyflakes/test/test_other.py::Test::test_redefinedInGenerator",
"pyflakes/test/test_other.py::Test::test_redefinedInSetComprehension",
"pyflakes/test/test_other.py::Test::test_redefinedTryExceptFunction",
"pyflakes/test/test_other.py::Test::test_redefinedTryFunction",
"pyflakes/test/test_other.py::Test::test_redefinedUnderscoreFunction",
"pyflakes/test/test_other.py::Test::test_redefinedUnderscoreImportation",
"pyflakes/test/test_other.py::Test::test_starredAssignmentErrors",
"pyflakes/test/test_other.py::Test::test_starredAssignmentNoError",
"pyflakes/test/test_other.py::Test::test_unaryPlus",
"pyflakes/test/test_other.py::Test::test_undefinedBaseClass",
"pyflakes/test/test_other.py::Test::test_varAugmentedAssignment",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assert_static",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assert_tuple",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assert_tuple_empty",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assert_with_message",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assert_without_message",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assignInForLoop",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assignInListComprehension",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assignToGlobal",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assignToMember",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assignToNonlocal",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assign_expr",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assignmentInsideLoop",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_augmentedAssignmentImportedFunctionCall",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_closedOver",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_dictComprehension",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_doubleClosedOver",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_exceptWithoutNameInFunction",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_exceptWithoutNameInFunctionTuple",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_exceptionUnusedInExcept",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_exceptionUnusedInExceptInFunction",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_exceptionUsedInExcept",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_f_string",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_generatorExpression",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_ifexp",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_listUnpacking",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_setComprehensionAndLiteral",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_tracebackhideSpecialVariable",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_tupleUnpacking",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_unusedUnderscoreVariable",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_unusedVariable",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_unusedVariableAsLocals",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_unusedVariableNoLocals",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_variableUsedInLoop",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementAttributeName",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementComplicatedTarget",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementListNames",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementNameDefinedInBody",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementNoNames",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementSingleName",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementSingleNameRedefined",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementSingleNameUndefined",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementSubscript",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementSubscriptUndefined",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementTupleNames",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementTupleNamesRedefined",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementTupleNamesUndefined",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementUndefinedInExpression",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementUndefinedInside",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_yieldFromUndefined",
"pyflakes/test/test_other.py::TestStringFormatting::test_f_string_without_placeholders",
"pyflakes/test/test_other.py::TestStringFormatting::test_invalid_dot_format_calls",
"pyflakes/test/test_other.py::TestStringFormatting::test_invalid_percent_format_calls",
"pyflakes/test/test_other.py::TestStringFormatting::test_ok_percent_format_cannot_determine_element_count",
"pyflakes/test/test_other.py::TestAsyncStatements::test_asyncDef",
"pyflakes/test/test_other.py::TestAsyncStatements::test_asyncDefAwait",
"pyflakes/test/test_other.py::TestAsyncStatements::test_asyncDefUndefined",
"pyflakes/test/test_other.py::TestAsyncStatements::test_asyncFor",
"pyflakes/test/test_other.py::TestAsyncStatements::test_asyncForUnderscoreLoopVar",
"pyflakes/test/test_other.py::TestAsyncStatements::test_asyncWith",
"pyflakes/test/test_other.py::TestAsyncStatements::test_asyncWithItem",
"pyflakes/test/test_other.py::TestAsyncStatements::test_formatstring",
"pyflakes/test/test_other.py::TestAsyncStatements::test_loopControlInAsyncFor",
"pyflakes/test/test_other.py::TestAsyncStatements::test_loopControlInAsyncForElse",
"pyflakes/test/test_other.py::TestAsyncStatements::test_matmul",
"pyflakes/test/test_other.py::TestAsyncStatements::test_raise_notimplemented",
"pyflakes/test/test_other.py::TestIncompatiblePrintOperator::test_invalid_print_when_imported_from_future",
"pyflakes/test/test_other.py::TestIncompatiblePrintOperator::test_print_as_condition_test",
"pyflakes/test/test_other.py::TestIncompatiblePrintOperator::test_print_function_assignment",
"pyflakes/test/test_other.py::TestIncompatiblePrintOperator::test_print_in_lambda",
"pyflakes/test/test_other.py::TestIncompatiblePrintOperator::test_print_returned_in_function",
"pyflakes/test/test_other.py::TestIncompatiblePrintOperator::test_valid_print",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_annotated_async_def",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_literal_type_typing",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_literal_type_typing_extensions",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_literal_union_type_typing",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_not_a_typing_overload",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_overload_in_class",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_overload_with_multiple_decorators",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_postponed_annotations",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_return_annotation_is_class_scope_variable",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_return_annotation_is_function_body_variable",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsAdditionalComment",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsAssignedToPreviousNode",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsFullSignature",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsFullSignatureWithDocstring",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsInvalidDoesNotMarkAsUsed",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsMarkImportsAsUsed",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsNoWhitespaceAnnotation",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsStarArgs",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsSyntaxError",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsSyntaxErrorCorrectLine",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeIgnore",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeIgnoreBogus",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeIgnoreBogusUnicode",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typingOverload",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typingOverloadAsync",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_variable_annotations"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2019-10-24T22:54:11Z" | mit |
|
PyCQA__pyflakes-508 | diff --git a/pyflakes/checker.py b/pyflakes/checker.py
index c8ccf56..d157008 100644
--- a/pyflakes/checker.py
+++ b/pyflakes/checker.py
@@ -1799,6 +1799,10 @@ class Checker(object):
addArgs(node.args.args)
defaults = node.args.defaults
else:
+ if PY38_PLUS:
+ for arg in node.args.posonlyargs:
+ args.append(arg.arg)
+ annotations.append(arg.annotation)
for arg in node.args.args + node.args.kwonlyargs:
args.append(arg.arg)
annotations.append(arg.annotation)
| PyCQA/pyflakes | 1911c203a13826d2eb03d582d60874b91e36f4fc | diff --git a/pyflakes/test/test_type_annotations.py b/pyflakes/test/test_type_annotations.py
index 289535d..1fa4f5e 100644
--- a/pyflakes/test/test_type_annotations.py
+++ b/pyflakes/test/test_type_annotations.py
@@ -418,3 +418,11 @@ class TestTypeAnnotations(TestCase):
Y = 2
return Y
""", m.UndefinedName)
+
+ @skipIf(version_info < (3, 8), 'new in Python 3.8')
+ def test_positional_only_argument_annotations(self):
+ self.flakes("""
+ from x import C
+
+ def f(c: C, /): ...
+ """)
| F401 (imported but unused) false positive on Foo when using def x(a: Foo, /, *, b: Bar)
```python
from datetime import datetime as Foo, time as Bar
def x(a: Foo, /, *, b: Bar):
pass
```
Running this on the file results in:
```
› flake8 --version
3.7.9 (mccabe: 0.6.1, pycodestyle: 2.5.0, pyflakes: 2.1.1) CPython 3.8.1 on Linux
› pyflakes --version
2.1.1 Python 3.8.1 on Linux
› flake8 example.py
example.py:1:1: F401 'datetime.datetime as Foo' imported but unused
› pyflakes example.py
example.py:1: 'datetime.datetime as Foo' imported but unused
``` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_positional_only_argument_annotations"
] | [
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_annotated_async_def",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_not_a_typing_overload",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_overload_in_class",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_overload_with_multiple_decorators",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_postponed_annotations",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_return_annotation_is_class_scope_variable",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_return_annotation_is_function_body_variable",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsAdditionalComment",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsAssignedToPreviousNode",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsFullSignature",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsFullSignatureWithDocstring",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsInvalidDoesNotMarkAsUsed",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsMarkImportsAsUsed",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsNoWhitespaceAnnotation",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsStarArgs",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsSyntaxError",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsSyntaxErrorCorrectLine",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeIgnore",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeIgnoreBogus",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeIgnoreBogusUnicode",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typingExtensionsOverload",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typingOverload",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typingOverloadAsync",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_variable_annotations"
] | {
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
} | "2020-01-17T18:59:12Z" | mit |
|
PyCQA__pyflakes-580 | diff --git a/pyflakes/checker.py b/pyflakes/checker.py
index 16c783f..a6439d6 100644
--- a/pyflakes/checker.py
+++ b/pyflakes/checker.py
@@ -128,6 +128,13 @@ def _is_const_non_singleton(node): # type: (ast.AST) -> bool
return _is_constant(node) and not _is_singleton(node)
+def _is_name_or_attr(node, name): # type: (ast.Ast, str) -> bool
+ return (
+ (isinstance(node, ast.Name) and node.id == name) or
+ (isinstance(node, ast.Attribute) and node.attr == name)
+ )
+
+
# https://github.com/python/typed_ast/blob/1.4.0/ast27/Parser/tokenizer.c#L102-L104
TYPE_COMMENT_RE = re.compile(r'^#\s*type:\s*')
# https://github.com/python/typed_ast/blob/1.4.0/ast27/Parser/tokenizer.c#L1408-L1413
@@ -1497,20 +1504,39 @@ class Checker(object):
STARRED = NAMECONSTANT = NAMEDEXPR = handleChildren
def SUBSCRIPT(self, node):
- if (
- (
- isinstance(node.value, ast.Name) and
- node.value.id == 'Literal'
- ) or (
- isinstance(node.value, ast.Attribute) and
- node.value.attr == 'Literal'
- )
- ):
+ if _is_name_or_attr(node.value, 'Literal'):
orig, self._in_typing_literal = self._in_typing_literal, True
try:
self.handleChildren(node)
finally:
self._in_typing_literal = orig
+ elif _is_name_or_attr(node.value, 'Annotated'):
+ self.handleNode(node.value, node)
+
+ # py39+
+ if isinstance(node.slice, ast.Tuple):
+ slice_tuple = node.slice
+ # <py39
+ elif (
+ isinstance(node.slice, ast.Index) and
+ isinstance(node.slice.value, ast.Tuple)
+ ):
+ slice_tuple = node.slice.value
+ else:
+ slice_tuple = None
+
+ # not a multi-arg `Annotated`
+ if slice_tuple is None or len(slice_tuple.elts) < 2:
+ self.handleNode(node.slice, node)
+ else:
+ # the first argument is the type
+ self.handleNode(slice_tuple.elts[0], node)
+ # the rest of the arguments are not
+ with self._enter_annotation(AnnotationState.NONE):
+ for arg in slice_tuple.elts[1:]:
+ self.handleNode(arg, node)
+
+ self.handleNode(node.ctx, node)
else:
if _is_any_typing_member(node.value, self.scopeStack):
with self._enter_annotation():
| PyCQA/pyflakes | 5fc37cbda5bf4e5afcb64c45caa62062979256b4 | diff --git a/pyflakes/test/test_type_annotations.py b/pyflakes/test/test_type_annotations.py
index eff222b..d5a3e08 100644
--- a/pyflakes/test/test_type_annotations.py
+++ b/pyflakes/test/test_type_annotations.py
@@ -542,6 +542,42 @@ class TestTypeAnnotations(TestCase):
return None
""")
+ @skipIf(version_info < (3,), 'new in Python 3')
+ def test_annotated_type_typing_missing_forward_type(self):
+ self.flakes("""
+ from typing import Annotated
+
+ def f(x: Annotated['integer']) -> None:
+ return None
+ """, m.UndefinedName)
+
+ @skipIf(version_info < (3,), 'new in Python 3')
+ def test_annotated_type_typing_missing_forward_type_multiple_args(self):
+ self.flakes("""
+ from typing import Annotated
+
+ def f(x: Annotated['integer', 1]) -> None:
+ return None
+ """, m.UndefinedName)
+
+ @skipIf(version_info < (3,), 'new in Python 3')
+ def test_annotated_type_typing_with_string_args(self):
+ self.flakes("""
+ from typing import Annotated
+
+ def f(x: Annotated[int, '> 0']) -> None:
+ return None
+ """)
+
+ @skipIf(version_info < (3,), 'new in Python 3')
+ def test_annotated_type_typing_with_string_args_in_union(self):
+ self.flakes("""
+ from typing import Annotated, Union
+
+ def f(x: Union[Annotated['int', '>0'], 'integer']) -> None:
+ return None
+ """, m.UndefinedName)
+
@skipIf(version_info < (3,), 'new in Python 3')
def test_literal_type_some_other_module(self):
"""err on the side of false-negatives for types named Literal"""
| syntax error in forward annotation when using Annotated
When using [`Annotated`](https://www.python.org/dev/peps/pep-0593/) with string annotations the following error is raised:
```
./pyflakes.py:3:16 syntax error in forward annotation '>1'
```
Triggering code:
```
from typing import Annotated
Annotated[int, '>1']
``` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_annotated_type_typing_with_string_args",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_annotated_type_typing_with_string_args_in_union"
] | [
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_annotated_async_def",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_annotated_type_typing_missing_forward_type",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_annotated_type_typing_missing_forward_type_multiple_args",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_deferred_twice_annotation",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_idomiatic_typing_guards",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_literal_type_some_other_module",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_literal_type_typing",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_literal_type_typing_extensions",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_literal_union_type_typing",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_nested_partially_quoted_type_assignment",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_not_a_typing_overload",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_overload_in_class",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_overload_with_multiple_decorators",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_partial_string_annotations_with_future_annotations",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_partially_quoted_type_annotation",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_partially_quoted_type_assignment",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_positional_only_argument_annotations",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_postponed_annotations",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_quoted_type_cast",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_quoted_type_cast_renamed_import",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_return_annotation_is_class_scope_variable",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_return_annotation_is_function_body_variable",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsAdditionalComment",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsAssignedToPreviousNode",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsFullSignature",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsFullSignatureWithDocstring",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsInvalidDoesNotMarkAsUsed",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsMarkImportsAsUsed",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsNoWhitespaceAnnotation",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsStarArgs",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsSyntaxError",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsSyntaxErrorCorrectLine",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeIgnore",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeIgnoreBogus",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeIgnoreBogusUnicode",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_type_cast_literal_str_to_str",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typingExtensionsOverload",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typingOverload",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typingOverloadAsync",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typing_guard_for_protocol",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_unused_annotation",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_variable_annotations"
] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
} | "2020-09-27T23:29:16Z" | mit |
|
PyCQA__pyflakes-604 | diff --git a/pyflakes/checker.py b/pyflakes/checker.py
index 0d65506..38f8f73 100644
--- a/pyflakes/checker.py
+++ b/pyflakes/checker.py
@@ -992,7 +992,10 @@ class Checker(object):
if all_binding:
all_names = set(all_binding.names)
- undefined = all_names.difference(scope)
+ undefined = [
+ name for name in all_binding.names
+ if name not in scope
+ ]
else:
all_names = undefined = []
@@ -1680,6 +1683,19 @@ class Checker(object):
with self._enter_annotation(AnnotationState.STRING):
self.handleNode(node.args[0], node)
+ elif _is_typing(node.func, 'TypeVar', self.scopeStack):
+ # TypeVar("T", "int", "str")
+ for arg in node.args[1:]:
+ if isinstance(arg, ast.Str):
+ with self._enter_annotation():
+ self.handleNode(arg, node)
+
+ # TypeVar("T", bound="str")
+ for keyword in node.keywords:
+ if keyword.arg == 'bound' and isinstance(keyword.value, ast.Str):
+ with self._enter_annotation():
+ self.handleNode(keyword.value, node)
+
self.handleChildren(node)
def _handle_percent_format(self, node):
| PyCQA/pyflakes | 0e4194b238ffd006441f1a33373062d9c7272d0e | diff --git a/pyflakes/test/test_type_annotations.py b/pyflakes/test/test_type_annotations.py
index d5a3e08..409238b 100644
--- a/pyflakes/test/test_type_annotations.py
+++ b/pyflakes/test/test_type_annotations.py
@@ -524,6 +524,21 @@ class TestTypeAnnotations(TestCase):
maybe_int = tsac('Maybe[int]', 42)
""")
+ def test_quoted_TypeVar_constraints(self):
+ self.flakes("""
+ from typing import TypeVar, Optional
+
+ T = TypeVar('T', 'str', 'Optional[int]', bytes)
+ """)
+
+ def test_quoted_TypeVar_bound(self):
+ self.flakes("""
+ from typing import TypeVar, Optional, List
+
+ T = TypeVar('T', bound='Optional[int]')
+ S = TypeVar('S', int, bound='List[int]')
+ """)
+
@skipIf(version_info < (3,), 'new in Python 3')
def test_literal_type_typing(self):
self.flakes("""
| "undefined name in __all__" has non-deterministic ordering
Found this while putting together a tool to look for regressions in the latest release and noticed that this produces things out-of-order!
```console
$ cat t.py
__all__ = ('a', 'b', 'c', 'd')
$ python3 -m pyflakes t.py
t.py:1:1 undefined name 'a' in __all__
t.py:1:1 undefined name 'd' in __all__
t.py:1:1 undefined name 'b' in __all__
t.py:1:1 undefined name 'c' in __all__
$ python3 -m pyflakes t.py
t.py:1:1 undefined name 'c' in __all__
t.py:1:1 undefined name 'd' in __all__
t.py:1:1 undefined name 'b' in __all__
t.py:1:1 undefined name 'a' in __all__
```
This is due to an intermediate set in the code for that check: https://github.com/PyCQA/pyflakes/blob/0e4194b238ffd006441f1a33373062d9c7272d0e/pyflakes/checker.py#L993-L997 | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_quoted_TypeVar_bound",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_quoted_TypeVar_constraints"
] | [
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_annotated_async_def",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_annotated_type_typing_missing_forward_type",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_annotated_type_typing_missing_forward_type_multiple_args",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_annotated_type_typing_with_string_args",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_annotated_type_typing_with_string_args_in_union",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_deferred_twice_annotation",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_idomiatic_typing_guards",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_literal_type_some_other_module",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_literal_type_typing",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_literal_type_typing_extensions",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_literal_union_type_typing",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_nested_partially_quoted_type_assignment",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_not_a_typing_overload",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_overload_in_class",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_overload_with_multiple_decorators",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_partial_string_annotations_with_future_annotations",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_partially_quoted_type_annotation",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_partially_quoted_type_assignment",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_positional_only_argument_annotations",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_postponed_annotations",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_quoted_type_cast",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_quoted_type_cast_renamed_import",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_return_annotation_is_class_scope_variable",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_return_annotation_is_function_body_variable",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsAdditionalComment",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsAssignedToPreviousNode",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsFullSignature",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsFullSignatureWithDocstring",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsInvalidDoesNotMarkAsUsed",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsMarkImportsAsUsed",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsNoWhitespaceAnnotation",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsStarArgs",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsSyntaxError",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsSyntaxErrorCorrectLine",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeIgnore",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeIgnoreBogus",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeIgnoreBogusUnicode",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_type_cast_literal_str_to_str",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typingExtensionsOverload",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typingOverload",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typingOverloadAsync",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typing_guard_for_protocol",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_unused_annotation",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_variable_annotations"
] | {
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
} | "2021-01-04T21:22:50Z" | mit |
|
PyCQA__pyflakes-606 | diff --git a/pyflakes/checker.py b/pyflakes/checker.py
index 38f8f73..215bd31 100644
--- a/pyflakes/checker.py
+++ b/pyflakes/checker.py
@@ -1140,7 +1140,10 @@ class Checker(object):
# then assume the rebound name is used as a global or within a loop
value.used = self.scope[value.name].used
- self.scope[value.name] = value
+ # don't treat annotations as assignments if there is an existing value
+ # in scope
+ if value.name not in self.scope or not isinstance(value, Annotation):
+ self.scope[value.name] = value
def _unknown_handler(self, node):
# this environment variable configures whether to error on unknown
| PyCQA/pyflakes | 650efb92fd27ae60ec08a70f2ac1afbea37ac3e3 | diff --git a/pyflakes/test/test_type_annotations.py b/pyflakes/test/test_type_annotations.py
index 409238b..835d8d9 100644
--- a/pyflakes/test/test_type_annotations.py
+++ b/pyflakes/test/test_type_annotations.py
@@ -335,6 +335,19 @@ class TestTypeAnnotations(TestCase):
def g(t: 'T'): pass
''')
+ @skipIf(version_info < (3, 6), 'new in Python 3.6')
+ def test_type_annotation_clobbers_all(self):
+ self.flakes('''\
+ from typing import TYPE_CHECKING, List
+
+ from y import z
+
+ if not TYPE_CHECKING:
+ __all__ = ("z",)
+ else:
+ __all__: List[str]
+ ''')
+
def test_typeCommentsMarkImportsAsUsed(self):
self.flakes("""
from mod import A, B, C, D, E, F, G
| Odd edge-case regression in type annotated `__all__`
I'm not quite sure how to approach fixing this -- it regressed as part of #535 -- CC @srittau
Here's a simplified example, this is boiled down from numpy's `numpy/typing/__init__.py`
```python
from typing import TYPE_CHECKING, List
from y import z
if not TYPE_CHECKING:
__all__ = ("z",)
else:
__all__: List[str]
```
After #535, the type annotation clobbers the `__all__` "`ExportBinding`" which causes it to no longer mark the imports as used
I *think* we can make `Annotated` a `setdefault` on the latest namespace to prevent this? | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_type_annotation_clobbers_all"
] | [
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_annotated_async_def",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_annotated_type_typing_missing_forward_type",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_annotated_type_typing_missing_forward_type_multiple_args",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_annotated_type_typing_with_string_args",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_annotated_type_typing_with_string_args_in_union",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_deferred_twice_annotation",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_idomiatic_typing_guards",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_literal_type_some_other_module",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_literal_type_typing",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_literal_type_typing_extensions",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_literal_union_type_typing",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_nested_partially_quoted_type_assignment",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_not_a_typing_overload",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_overload_in_class",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_overload_with_multiple_decorators",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_partial_string_annotations_with_future_annotations",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_partially_quoted_type_annotation",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_partially_quoted_type_assignment",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_positional_only_argument_annotations",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_postponed_annotations",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_quoted_TypeVar_bound",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_quoted_TypeVar_constraints",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_quoted_type_cast",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_quoted_type_cast_renamed_import",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_return_annotation_is_class_scope_variable",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_return_annotation_is_function_body_variable",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsAdditionalComment",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsAssignedToPreviousNode",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsFullSignature",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsFullSignatureWithDocstring",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsInvalidDoesNotMarkAsUsed",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsMarkImportsAsUsed",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsNoWhitespaceAnnotation",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsStarArgs",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsSyntaxError",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsSyntaxErrorCorrectLine",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeIgnore",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeIgnoreBogus",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeIgnoreBogusUnicode",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_type_cast_literal_str_to_str",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typingExtensionsOverload",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typingOverload",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typingOverloadAsync",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typing_guard_for_protocol",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_unused_annotation",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_variable_annotations"
] | {
"failed_lite_validators": [
"has_issue_reference"
],
"has_test_patch": true,
"is_lite": false
} | "2021-01-04T23:00:51Z" | mit |
|
PyCQA__pyflakes-609 | diff --git a/pyflakes/checker.py b/pyflakes/checker.py
index 215bd31..01bcf50 100644
--- a/pyflakes/checker.py
+++ b/pyflakes/checker.py
@@ -1678,28 +1678,79 @@ class Checker(object):
):
self._handle_string_dot_format(node)
+ omit = []
+ annotated = []
+ not_annotated = []
+
if (
_is_typing(node.func, 'cast', self.scopeStack) and
- len(node.args) >= 1 and
- isinstance(node.args[0], ast.Str)
+ len(node.args) >= 1
):
- with self._enter_annotation(AnnotationState.STRING):
+ with self._enter_annotation():
self.handleNode(node.args[0], node)
elif _is_typing(node.func, 'TypeVar', self.scopeStack):
+
# TypeVar("T", "int", "str")
- for arg in node.args[1:]:
- if isinstance(arg, ast.Str):
- with self._enter_annotation():
- self.handleNode(arg, node)
+ omit += ["args"]
+ annotated += [arg for arg in node.args[1:]]
# TypeVar("T", bound="str")
- for keyword in node.keywords:
- if keyword.arg == 'bound' and isinstance(keyword.value, ast.Str):
- with self._enter_annotation():
- self.handleNode(keyword.value, node)
+ omit += ["keywords"]
+ annotated += [k.value for k in node.keywords if k.arg == "bound"]
+ not_annotated += [
+ (k, ["value"] if k.arg == "bound" else None)
+ for k in node.keywords
+ ]
+
+ elif _is_typing(node.func, "TypedDict", self.scopeStack):
+ # TypedDict("a", {"a": int})
+ if len(node.args) > 1 and isinstance(node.args[1], ast.Dict):
+ omit += ["args"]
+ annotated += node.args[1].values
+ not_annotated += [
+ (arg, ["values"] if i == 1 else None)
+ for i, arg in enumerate(node.args)
+ ]
- self.handleChildren(node)
+ # TypedDict("a", a=int)
+ omit += ["keywords"]
+ annotated += [k.value for k in node.keywords]
+ not_annotated += [(k, ["value"]) for k in node.keywords]
+
+ elif _is_typing(node.func, "NamedTuple", self.scopeStack):
+ # NamedTuple("a", [("a", int)])
+ if (
+ len(node.args) > 1 and
+ isinstance(node.args[1], (ast.Tuple, ast.List)) and
+ all(isinstance(x, (ast.Tuple, ast.List)) and
+ len(x.elts) == 2 for x in node.args[1].elts)
+ ):
+ omit += ["args"]
+ annotated += [elt.elts[1] for elt in node.args[1].elts]
+ not_annotated += [(elt.elts[0], None) for elt in node.args[1].elts]
+ not_annotated += [
+ (arg, ["elts"] if i == 1 else None)
+ for i, arg in enumerate(node.args)
+ ]
+ not_annotated += [(elt, "elts") for elt in node.args[1].elts]
+
+ # NamedTuple("a", a=int)
+ omit += ["keywords"]
+ annotated += [k.value for k in node.keywords]
+ not_annotated += [(k, ["value"]) for k in node.keywords]
+
+ if omit:
+ with self._enter_annotation(AnnotationState.NONE):
+ for na_node, na_omit in not_annotated:
+ self.handleChildren(na_node, omit=na_omit)
+ self.handleChildren(node, omit=omit)
+
+ with self._enter_annotation():
+ for annotated_node in annotated:
+ self.handleNode(annotated_node, node)
+ else:
+ self.handleChildren(node)
def _handle_percent_format(self, node):
try:
| PyCQA/pyflakes | 43541ee1dd394ec4691625e7295f701b3b073dca | diff --git a/pyflakes/test/test_type_annotations.py b/pyflakes/test/test_type_annotations.py
index 835d8d9..9e7ca14 100644
--- a/pyflakes/test/test_type_annotations.py
+++ b/pyflakes/test/test_type_annotations.py
@@ -695,3 +695,44 @@ class TestTypeAnnotations(TestCase):
def f(): # type: () -> int
pass
""")
+
+ def test_typednames_correct_forward_ref(self):
+ self.flakes("""
+ from typing import TypedDict, List, NamedTuple
+
+ List[TypedDict("x", {})]
+ List[TypedDict("x", x=int)]
+ List[NamedTuple("a", a=int)]
+ List[NamedTuple("a", [("a", int)])]
+ """)
+ self.flakes("""
+ from typing import TypedDict, List, NamedTuple, TypeVar
+
+ List[TypedDict("x", {"x": "Y"})]
+ List[TypedDict("x", x="Y")]
+ List[NamedTuple("a", [("a", "Y")])]
+ List[NamedTuple("a", a="Y")]
+ List[TypedDict("x", {"x": List["a"]})]
+ List[TypeVar("A", bound="C")]
+ List[TypeVar("A", List["C"])]
+ """, *[m.UndefinedName]*7)
+ self.flakes("""
+ from typing import NamedTuple, TypeVar, cast
+ from t import A, B, C, D, E
+
+ NamedTuple("A", [("a", A["C"])])
+ TypeVar("A", bound=A["B"])
+ TypeVar("A", A["D"])
+ cast(A["E"], [])
+ """)
+
+ @skipIf(version_info < (3, 6), 'new in Python 3.6')
+ def test_namedtypes_classes(self):
+ self.flakes("""
+ from typing import TypedDict, NamedTuple
+ class X(TypedDict):
+ y: TypedDict("z", {"zz":int})
+
+ class Y(NamedTuple):
+ y: NamedTuple("v", [("vv", int)])
+ """)
| Nested TypedDict not supported
Flake8 returns strange `undefined name` errors when using nested [alternative syntax style](https://www.python.org/dev/peps/pep-0589/#alternative-syntax) `TypedDict` declarations.
Example:
```py
from typing import TypedDict
class Example(TypedDict):
nested: TypedDict("Nested", {"foo/bar": str})
```
Pyflakes returns the following:
```sh
foo.py:5:23 undefined name 'Nested'
foo.py:5:34 undefined name 'foo'
foo.py:5:34 undefined name 'bar'
```
Version information:
```sh
$ pyflakes --version
2.2.0 Python 3.8.0 on Darwin
```
A workaround is to simply not nest the declarations:
```py
from typing import TypedDict
Nested = TypedDict("Nested", {"foo/bar": str})
class Example(TypedDict):
nested: Nested
``` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_namedtypes_classes",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typednames_correct_forward_ref"
] | [
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_annotated_async_def",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_annotated_type_typing_missing_forward_type",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_annotated_type_typing_missing_forward_type_multiple_args",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_annotated_type_typing_with_string_args",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_annotated_type_typing_with_string_args_in_union",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_deferred_twice_annotation",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_idomiatic_typing_guards",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_literal_type_some_other_module",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_literal_type_typing",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_literal_type_typing_extensions",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_literal_union_type_typing",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_nested_partially_quoted_type_assignment",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_not_a_typing_overload",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_overload_in_class",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_overload_with_multiple_decorators",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_partial_string_annotations_with_future_annotations",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_partially_quoted_type_annotation",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_partially_quoted_type_assignment",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_positional_only_argument_annotations",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_postponed_annotations",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_quoted_TypeVar_bound",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_quoted_TypeVar_constraints",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_quoted_type_cast",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_quoted_type_cast_renamed_import",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_return_annotation_is_class_scope_variable",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_return_annotation_is_function_body_variable",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsAdditionalComment",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsAssignedToPreviousNode",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsFullSignature",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsFullSignatureWithDocstring",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsInvalidDoesNotMarkAsUsed",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsMarkImportsAsUsed",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsNoWhitespaceAnnotation",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsStarArgs",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsSyntaxError",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsSyntaxErrorCorrectLine",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeIgnore",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeIgnoreBogus",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeIgnoreBogusUnicode",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_type_annotation_clobbers_all",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_type_cast_literal_str_to_str",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typingExtensionsOverload",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typingOverload",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typingOverloadAsync",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typing_guard_for_protocol",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_unused_annotation",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_variable_annotations"
] | {
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
} | "2021-01-14T07:23:14Z" | mit |
|
PyCQA__pyflakes-668 | diff --git a/pyflakes/checker.py b/pyflakes/checker.py
index 56fc3ca..89c9d0a 100644
--- a/pyflakes/checker.py
+++ b/pyflakes/checker.py
@@ -588,7 +588,7 @@ class FunctionScope(Scope):
self.returnValue = None # First non-empty return
self.isGenerator = False # Detect a generator
- def unusedAssignments(self):
+ def unused_assignments(self):
"""
Return a generator for the assignments which have not been used.
"""
@@ -600,6 +600,14 @@ class FunctionScope(Scope):
isinstance(binding, Assignment)):
yield name, binding
+ def unused_annotations(self):
+ """
+ Return a generator for the annotations which have not been used.
+ """
+ for name, binding in self.items():
+ if not binding.used and isinstance(binding, Annotation):
+ yield name, binding
+
class GeneratorScope(Scope):
pass
@@ -1156,6 +1164,7 @@ class Checker:
binding = scope.get(name, None)
if isinstance(binding, Annotation) and not self._in_postponed_annotation:
+ scope[name].used = True
continue
if name == 'print' and isinstance(binding, Builtin):
@@ -2084,13 +2093,22 @@ class Checker:
self.handleChildren(node, omit=['decorator_list', 'returns'])
- def checkUnusedAssignments():
+ def check_unused_assignments():
"""
Check to see if any assignments have not been used.
"""
- for name, binding in self.scope.unusedAssignments():
+ for name, binding in self.scope.unused_assignments():
self.report(messages.UnusedVariable, binding.source, name)
- self.deferAssignment(checkUnusedAssignments)
+
+ def check_unused_annotations():
+ """
+ Check to see if any annotations have not been used.
+ """
+ for name, binding in self.scope.unused_annotations():
+ self.report(messages.UnusedAnnotation, binding.source, name)
+
+ self.deferAssignment(check_unused_assignments)
+ self.deferAssignment(check_unused_annotations)
self.popScope()
diff --git a/pyflakes/messages.py b/pyflakes/messages.py
index 37c4432..c2246cf 100644
--- a/pyflakes/messages.py
+++ b/pyflakes/messages.py
@@ -156,6 +156,18 @@ class UnusedVariable(Message):
self.message_args = (names,)
+class UnusedAnnotation(Message):
+ """
+ Indicates that a variable has been explicitly annotated to but not actually
+ used.
+ """
+ message = 'local variable %r is annotated but never used'
+
+ def __init__(self, filename, loc, names):
+ Message.__init__(self, filename, loc)
+ self.message_args = (names,)
+
+
class ReturnOutsideFunction(Message):
"""
Indicates a return statement outside of a function/method.
| PyCQA/pyflakes | 4dcd92e45efeb0615ba1c96d45241a037d30abe0 | diff --git a/pyflakes/test/test_type_annotations.py b/pyflakes/test/test_type_annotations.py
index d881205..2ad9f45 100644
--- a/pyflakes/test/test_type_annotations.py
+++ b/pyflakes/test/test_type_annotations.py
@@ -174,7 +174,7 @@ class TestTypeAnnotations(TestCase):
def f():
name: str
age: int
- ''')
+ ''', m.UnusedAnnotation, m.UnusedAnnotation)
self.flakes('''
def f():
name: str = 'Bob'
@@ -190,7 +190,7 @@ class TestTypeAnnotations(TestCase):
from typing import Any
def f():
a: Any
- ''')
+ ''', m.UnusedAnnotation)
self.flakes('''
foo: not_a_real_type
''', m.UndefinedName)
@@ -356,11 +356,10 @@ class TestTypeAnnotations(TestCase):
class Cls:
y: int
''')
- # TODO: this should print a UnusedVariable message
self.flakes('''
def f():
x: int
- ''')
+ ''', m.UnusedAnnotation)
# This should only print one UnusedVariable message
self.flakes('''
def f():
@@ -368,6 +367,12 @@ class TestTypeAnnotations(TestCase):
x = 3
''', m.UnusedVariable)
+ def test_unassigned_annotation_is_undefined(self):
+ self.flakes('''
+ name: str
+ print(name)
+ ''', m.UndefinedName)
+
def test_annotated_async_def(self):
self.flakes('''
class c: pass
| Is an unused variable annotation able to be detected?
Given this sample file:
```python
def foo():
a = 10
b: str
return 1
foo()
```
It correctly gives an error about the variable `a`: `test.py:2:5 local variable 'a' is assigned to but never used`
It would be nice if an error could be given about `b` as well since it is also never used. I'm not sure if this is a bug report or a feature request, but I just wasn't sure if this was possible. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_unused_annotation",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_variable_annotations"
] | [
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_TypeAlias_annotations",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_aliased_import",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_annotated_async_def",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_annotated_type_typing_missing_forward_type",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_annotated_type_typing_missing_forward_type_multiple_args",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_annotated_type_typing_with_string_args",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_annotated_type_typing_with_string_args_in_union",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_annotating_an_import",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_deferred_twice_annotation",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_idomiatic_typing_guards",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_literal_type_some_other_module",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_literal_type_typing",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_literal_type_typing_extensions",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_literal_union_type_typing",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_namedtypes_classes",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_nested_partially_quoted_type_assignment",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_not_a_typing_overload",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_overload_in_class",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_overload_with_multiple_decorators",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_partial_string_annotations_with_future_annotations",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_partially_quoted_type_annotation",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_partially_quoted_type_assignment",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_positional_only_argument_annotations",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_postponed_annotations",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_quoted_TypeVar_bound",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_quoted_TypeVar_constraints",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_quoted_type_cast",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_quoted_type_cast_renamed_import",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_return_annotation_is_class_scope_variable",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_return_annotation_is_function_body_variable",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsAdditionalComment",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsAssignedToPreviousNode",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsFullSignature",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsFullSignatureWithDocstring",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsInvalidDoesNotMarkAsUsed",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsMarkImportsAsUsed",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsNoWhitespaceAnnotation",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsStarArgs",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsSyntaxError",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsSyntaxErrorCorrectLine",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeIgnore",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeIgnoreBogus",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeIgnoreBogusUnicode",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_type_annotation_clobbers_all",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_type_cast_literal_str_to_str",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typednames_correct_forward_ref",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typingExtensionsOverload",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typingOverload",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typingOverloadAsync",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typing_guard_for_protocol",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_unassigned_annotation_is_undefined",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_variable_annotation_references_self_name_undefined"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2021-12-25T18:12:24Z" | mit |
|
PyCQA__pyflakes-698 | diff --git a/pyflakes/checker.py b/pyflakes/checker.py
index 7f33d6a..0c3f66e 100644
--- a/pyflakes/checker.py
+++ b/pyflakes/checker.py
@@ -540,6 +540,12 @@ class Assignment(Binding):
"""
+class NamedExprAssignment(Assignment):
+ """
+ Represents binding a name with an assignment expression.
+ """
+
+
class Annotation(Binding):
"""
Represents binding a name to a type without an associated value.
@@ -1159,7 +1165,14 @@ class Checker(object):
# don't treat annotations as assignments if there is an existing value
# in scope
if value.name not in self.scope or not isinstance(value, Annotation):
- self.scope[value.name] = value
+ cur_scope_pos = -1
+ # As per PEP 572, use scope in which outermost generator is defined
+ while (
+ isinstance(value, NamedExprAssignment) and
+ isinstance(self.scopeStack[cur_scope_pos], GeneratorScope)
+ ):
+ cur_scope_pos -= 1
+ self.scopeStack[cur_scope_pos][value.name] = value
def _unknown_handler(self, node):
# this environment variable configures whether to error on unknown
@@ -1302,6 +1315,8 @@ class Checker(object):
binding = ExportBinding(name, node._pyflakes_parent, self.scope)
elif PY2 and isinstance(getattr(node, 'ctx', None), ast.Param):
binding = Argument(name, self.getScopeNode(node))
+ elif PY38_PLUS and isinstance(parent_stmt, ast.NamedExpr):
+ binding = NamedExprAssignment(name, node)
else:
binding = Assignment(name, node)
self.addBinding(node, binding)
| PyCQA/pyflakes | dd446ed156837f50a06596ec79efc292e856954f | diff --git a/pyflakes/test/test_other.py b/pyflakes/test/test_other.py
index 68813bd..efbc75d 100644
--- a/pyflakes/test/test_other.py
+++ b/pyflakes/test/test_other.py
@@ -1772,6 +1772,23 @@ class TestUnusedAssignment(TestCase):
print(x)
''')
+ @skipIf(version_info < (3, 8), 'new in Python 3.8')
+ def test_assign_expr_generator_scope(self):
+ """Test assignment expressions in generator expressions."""
+ self.flakes('''
+ if (any((y := x[0]) for x in [[True]])):
+ print(y)
+ ''')
+
+ @skipIf(version_info < (3, 8), 'new in Python 3.8')
+ def test_assign_expr_nested(self):
+ """Test assignment expressions in nested expressions."""
+ self.flakes('''
+ if ([(y:=x) for x in range(4) if [(z:=q) for q in range(4)]]):
+ print(y)
+ print(z)
+ ''')
+
class TestStringFormatting(TestCase):
| assignment expression in comprehension should target outer scope
Please consider the following example, which finds the first String in a list that contains the Substring "OH":
```
list = ["STEVE", "JOHN", "YOANN"]
pattern = re.compile(".*%s.*" % "OH")
word = ""
if any((match := pattern.match(item)) for item in list):
word = match.group(0)
print(word)
```
The code works as intended and outputs "JOHN", but I am getting the following warning from flake8 at
the line ```word = match.group(0):```
```
F821 -- undefined name 'match'
```
I made a post on [StackOverflow](https://stackoverflow.com/questions/67547135/why-does-flake8-give-the-warning-f821-undefined-name-match-when-using-match), where Anthony Sottile recommended me to post the issue here. I'm using flake8 3.9.2 (mccabe: 0.6.1, pycodestyle: 2.7.0, pyflakes: 2.3.1) CPython 3.9.5 on Windows. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assign_expr_generator_scope",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assign_expr_nested"
] | [
"pyflakes/test/test_other.py::Test::test_attrAugmentedAssignment",
"pyflakes/test/test_other.py::Test::test_breakInsideLoop",
"pyflakes/test/test_other.py::Test::test_breakOutsideLoop",
"pyflakes/test/test_other.py::Test::test_classFunctionDecorator",
"pyflakes/test/test_other.py::Test::test_classNameDefinedPreviously",
"pyflakes/test/test_other.py::Test::test_classNameUndefinedInClassBody",
"pyflakes/test/test_other.py::Test::test_classRedefinedAsFunction",
"pyflakes/test/test_other.py::Test::test_classRedefinition",
"pyflakes/test/test_other.py::Test::test_classWithReturn",
"pyflakes/test/test_other.py::Test::test_classWithYield",
"pyflakes/test/test_other.py::Test::test_classWithYieldFrom",
"pyflakes/test/test_other.py::Test::test_comparison",
"pyflakes/test/test_other.py::Test::test_containment",
"pyflakes/test/test_other.py::Test::test_continueInsideLoop",
"pyflakes/test/test_other.py::Test::test_continueOutsideLoop",
"pyflakes/test/test_other.py::Test::test_defaultExceptLast",
"pyflakes/test/test_other.py::Test::test_defaultExceptNotLast",
"pyflakes/test/test_other.py::Test::test_doubleAssignmentConditionally",
"pyflakes/test/test_other.py::Test::test_doubleAssignmentWithUse",
"pyflakes/test/test_other.py::Test::test_duplicateArgs",
"pyflakes/test/test_other.py::Test::test_ellipsis",
"pyflakes/test/test_other.py::Test::test_extendedSlice",
"pyflakes/test/test_other.py::Test::test_functionDecorator",
"pyflakes/test/test_other.py::Test::test_functionRedefinedAsClass",
"pyflakes/test/test_other.py::Test::test_function_arguments",
"pyflakes/test/test_other.py::Test::test_function_arguments_python3",
"pyflakes/test/test_other.py::Test::test_globalDeclaredInDifferentScope",
"pyflakes/test/test_other.py::Test::test_identity",
"pyflakes/test/test_other.py::Test::test_localReferencedBeforeAssignment",
"pyflakes/test/test_other.py::Test::test_loopControl",
"pyflakes/test/test_other.py::Test::test_modernProperty",
"pyflakes/test/test_other.py::Test::test_moduleWithReturn",
"pyflakes/test/test_other.py::Test::test_moduleWithYield",
"pyflakes/test/test_other.py::Test::test_moduleWithYieldFrom",
"pyflakes/test/test_other.py::Test::test_redefinedClassFunction",
"pyflakes/test/test_other.py::Test::test_redefinedFunction",
"pyflakes/test/test_other.py::Test::test_redefinedIfElseFunction",
"pyflakes/test/test_other.py::Test::test_redefinedIfElseInListComp",
"pyflakes/test/test_other.py::Test::test_redefinedIfFunction",
"pyflakes/test/test_other.py::Test::test_redefinedInDictComprehension",
"pyflakes/test/test_other.py::Test::test_redefinedInGenerator",
"pyflakes/test/test_other.py::Test::test_redefinedInSetComprehension",
"pyflakes/test/test_other.py::Test::test_redefinedTryExceptFunction",
"pyflakes/test/test_other.py::Test::test_redefinedTryFunction",
"pyflakes/test/test_other.py::Test::test_redefinedUnderscoreFunction",
"pyflakes/test/test_other.py::Test::test_redefinedUnderscoreImportation",
"pyflakes/test/test_other.py::Test::test_starredAssignmentErrors",
"pyflakes/test/test_other.py::Test::test_starredAssignmentNoError",
"pyflakes/test/test_other.py::Test::test_unaryPlus",
"pyflakes/test/test_other.py::Test::test_undefinedBaseClass",
"pyflakes/test/test_other.py::Test::test_varAugmentedAssignment",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assert_static",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assert_tuple",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assert_tuple_empty",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assert_with_message",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assert_without_message",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assignInForLoop",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assignInListComprehension",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assignToGlobal",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assignToMember",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assignToNonlocal",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assign_expr",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assignmentInsideLoop",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_augmentedAssignmentImportedFunctionCall",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_closedOver",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_dictComprehension",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_doubleClosedOver",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_exceptWithoutNameInFunction",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_exceptWithoutNameInFunctionTuple",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_exceptionUnusedInExcept",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_exceptionUnusedInExceptInFunction",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_exceptionUsedInExcept",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_f_string",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_generatorExpression",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_if_tuple",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_ifexp",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_listUnpacking",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_setComprehensionAndLiteral",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_tracebackhideSpecialVariable",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_tupleUnpacking",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_unusedUnderscoreVariable",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_unusedVariable",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_unusedVariableAsLocals",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_unusedVariableNoLocals",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_variableUsedInLoop",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementAttributeName",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementComplicatedTarget",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementListNames",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementNameDefinedInBody",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementNoNames",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementSingleName",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementSingleNameRedefined",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementSingleNameUndefined",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementSubscript",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementSubscriptUndefined",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementTupleNames",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementTupleNamesRedefined",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementTupleNamesUndefined",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementUndefinedInExpression",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementUndefinedInside",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_yieldFromUndefined",
"pyflakes/test/test_other.py::TestStringFormatting::test_f_string_without_placeholders",
"pyflakes/test/test_other.py::TestStringFormatting::test_invalid_dot_format_calls",
"pyflakes/test/test_other.py::TestStringFormatting::test_invalid_percent_format_calls",
"pyflakes/test/test_other.py::TestStringFormatting::test_ok_percent_format_cannot_determine_element_count",
"pyflakes/test/test_other.py::TestAsyncStatements::test_asyncDef",
"pyflakes/test/test_other.py::TestAsyncStatements::test_asyncDefAwait",
"pyflakes/test/test_other.py::TestAsyncStatements::test_asyncDefUndefined",
"pyflakes/test/test_other.py::TestAsyncStatements::test_asyncFor",
"pyflakes/test/test_other.py::TestAsyncStatements::test_asyncForUnderscoreLoopVar",
"pyflakes/test/test_other.py::TestAsyncStatements::test_asyncWith",
"pyflakes/test/test_other.py::TestAsyncStatements::test_asyncWithItem",
"pyflakes/test/test_other.py::TestAsyncStatements::test_formatstring",
"pyflakes/test/test_other.py::TestAsyncStatements::test_loopControlInAsyncFor",
"pyflakes/test/test_other.py::TestAsyncStatements::test_loopControlInAsyncForElse",
"pyflakes/test/test_other.py::TestAsyncStatements::test_matmul",
"pyflakes/test/test_other.py::TestAsyncStatements::test_raise_notimplemented",
"pyflakes/test/test_other.py::TestIncompatiblePrintOperator::test_invalid_print_when_imported_from_future",
"pyflakes/test/test_other.py::TestIncompatiblePrintOperator::test_print_as_condition_test",
"pyflakes/test/test_other.py::TestIncompatiblePrintOperator::test_print_function_assignment",
"pyflakes/test/test_other.py::TestIncompatiblePrintOperator::test_print_in_lambda",
"pyflakes/test/test_other.py::TestIncompatiblePrintOperator::test_print_returned_in_function",
"pyflakes/test/test_other.py::TestIncompatiblePrintOperator::test_valid_print"
] | {
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
} | "2022-05-24T00:47:15Z" | mit |
|
PyCQA__pyflakes-729 | diff --git a/pyflakes/checker.py b/pyflakes/checker.py
index ae15621..56fc3ca 100644
--- a/pyflakes/checker.py
+++ b/pyflakes/checker.py
@@ -2265,7 +2265,6 @@ class Checker:
self.scope[node.name] = prev_definition
def ANNASSIGN(self, node):
- self.handleNode(node.target, node)
self.handleAnnotation(node.annotation, node)
# If the assignment has value, handle the *value* now.
if node.value:
@@ -2274,6 +2273,7 @@ class Checker:
self.handleAnnotation(node.value, node)
else:
self.handleNode(node.value, node)
+ self.handleNode(node.target, node)
def COMPARE(self, node):
left = node.left
| PyCQA/pyflakes | 7d6479e46f8f3e9607c9ef7975cc892db023d413 | diff --git a/pyflakes/test/test_type_annotations.py b/pyflakes/test/test_type_annotations.py
index 3775cd3..d881205 100644
--- a/pyflakes/test/test_type_annotations.py
+++ b/pyflakes/test/test_type_annotations.py
@@ -298,6 +298,11 @@ class TestTypeAnnotations(TestCase):
a: 'a: "A"'
''', m.ForwardAnnotationSyntaxError)
+ def test_variable_annotation_references_self_name_undefined(self):
+ self.flakes("""
+ x: int = x
+ """, m.UndefinedName)
+
def test_TypeAlias_annotations(self):
self.flakes("""
from typing_extensions import TypeAlias
| annotated variable hides "undefined name"
this works:
```console
$ pyflakes /dev/stdin <<< 'x = x'
/dev/stdin:1:5: undefined name 'x'
$
```
this does not:
```console
$ pyflakes /dev/stdin <<< 'x: int = x'
$
``` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_variable_annotation_references_self_name_undefined"
] | [
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_TypeAlias_annotations",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_aliased_import",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_annotated_async_def",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_annotated_type_typing_missing_forward_type",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_annotated_type_typing_missing_forward_type_multiple_args",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_annotated_type_typing_with_string_args",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_annotated_type_typing_with_string_args_in_union",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_annotating_an_import",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_deferred_twice_annotation",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_idomiatic_typing_guards",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_literal_type_some_other_module",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_literal_type_typing",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_literal_type_typing_extensions",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_literal_union_type_typing",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_namedtypes_classes",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_nested_partially_quoted_type_assignment",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_not_a_typing_overload",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_overload_in_class",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_overload_with_multiple_decorators",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_partial_string_annotations_with_future_annotations",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_partially_quoted_type_annotation",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_partially_quoted_type_assignment",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_positional_only_argument_annotations",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_postponed_annotations",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_quoted_TypeVar_bound",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_quoted_TypeVar_constraints",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_quoted_type_cast",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_quoted_type_cast_renamed_import",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_return_annotation_is_class_scope_variable",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_return_annotation_is_function_body_variable",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsAdditionalComment",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsAssignedToPreviousNode",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsFullSignature",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsFullSignatureWithDocstring",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsInvalidDoesNotMarkAsUsed",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsMarkImportsAsUsed",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsNoWhitespaceAnnotation",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsStarArgs",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsSyntaxError",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeCommentsSyntaxErrorCorrectLine",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeIgnore",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeIgnoreBogus",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typeIgnoreBogusUnicode",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_type_annotation_clobbers_all",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_type_cast_literal_str_to_str",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typednames_correct_forward_ref",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typingExtensionsOverload",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typingOverload",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typingOverloadAsync",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typing_guard_for_protocol",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_unused_annotation",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_variable_annotations"
] | {
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false
} | "2022-09-08T20:11:15Z" | mit |
|
PyCQA__pyflakes-745 | diff --git a/pyflakes/checker.py b/pyflakes/checker.py
index b87bc88..15b4c2b 100644
--- a/pyflakes/checker.py
+++ b/pyflakes/checker.py
@@ -1068,7 +1068,7 @@ class Checker:
)
return handler
- def handleNodeLoad(self, node):
+ def handleNodeLoad(self, node, parent):
name = getNodeName(node)
if not name:
return
@@ -1093,7 +1093,6 @@ class Checker:
continue
if name == 'print' and isinstance(binding, Builtin):
- parent = self.getParent(node)
if (isinstance(parent, ast.BinOp) and
isinstance(parent.op, ast.RShift)):
self.report(messages.InvalidPrintSyntax, node)
@@ -1880,7 +1879,7 @@ class Checker:
"""
# Locate the name in locals / function / globals scopes.
if isinstance(node.ctx, ast.Load):
- self.handleNodeLoad(node)
+ self.handleNodeLoad(node, self.getParent(node))
if (node.id == 'locals' and isinstance(self.scope, FunctionScope) and
isinstance(node._pyflakes_parent, ast.Call)):
# we are doing locals() call in current scope
@@ -2049,7 +2048,7 @@ class Checker:
self.addBinding(node, ClassDefinition(node.name, node))
def AUGASSIGN(self, node):
- self.handleNodeLoad(node.target)
+ self.handleNodeLoad(node.target, node)
self.handleNode(node.value, node)
self.handleNode(node.target, node)
| PyCQA/pyflakes | 2c64ae48e2b1984a16cf25d215c9f9d21146426d | diff --git a/pyflakes/test/test_other.py b/pyflakes/test/test_other.py
index b138cf6..ce742a5 100644
--- a/pyflakes/test/test_other.py
+++ b/pyflakes/test/test_other.py
@@ -2052,6 +2052,10 @@ class TestIncompatiblePrintOperator(TestCase):
self.assertEqual(exc.lineno, 4)
self.assertEqual(exc.col, 0)
+ def test_print_augmented_assign(self):
+ # nonsense, but shouldn't crash pyflakes
+ self.flakes('print += 1')
+
def test_print_function_assignment(self):
"""
A valid assignment, tested for catching false positives.
| Internal error on invalid print (py2) statement
Hi, I'd like to report a bug that occurred during using flake8. Please don't ask me about the code, I'm just analyzing data submitted by other people. Thanks!
## Packages
```
$ pip freeze
flake8==6.0.0
flake8-json==21.7.0
mccabe==0.7.0
pycodestyle==2.10.0
pyflakes==3.0.0
```
## code
```py
print *= -1
```
## Traceback
```
flake8.checker MainProcess 85 INFO Making checkers
flake8.checker ForkPoolWorker-4 44861 CRITICAL Plugin pyflakes[F] raised an unexpected exception
Traceback (most recent call last):
File "/venv/lib/python3.10/site-packages/flake8/checker.py", line 341, in run_check
return plugin.obj(**arguments, **params)
File "/venv/lib/python3.10/site-packages/flake8/plugins/pyflakes.py", line 96, in __init__
super().__init__(tree, filename=filename, withDoctest=with_doctest)
File "/venv/lib/python3.10/site-packages/pyflakes/checker.py", line 787, in __init__
self.handleChildren(tree)
File "/venv/lib/python3.10/site-packages/pyflakes/checker.py", line 1238, in handleChildren
self.handleNode(node, tree)
File "/venv/lib/python3.10/site-packages/pyflakes/checker.py", line 1283, in handleNode
handler(node)
File "/venv/lib/python3.10/site-packages/pyflakes/checker.py", line 2052, in AUGASSIGN
self.handleNodeLoad(node.target)
File "/venv/lib/python3.10/site-packages/pyflakes/checker.py", line 1096, in handleNodeLoad
parent = self.getParent(node)
File "/venv/lib/python3.10/site-packages/pyflakes/checker.py", line 941, in getParent
node = node._pyflakes_parent
AttributeError: 'Name' object has no attribute '_pyflakes_parent'
flake8.main.application MainProcess 44924 INFO Finished running
flake8.main.application MainProcess 44924 INFO Reporting errors
flake8.main.application MainProcess 44924 INFO Found a total of 0 violations and reported 0
Flake8 failed.
offending_file.py: "pyflakes[F]" failed during execution due to AttributeError("'Name' object has no attribute '_pyflakes_parent'")
```
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"pyflakes/test/test_other.py::TestIncompatiblePrintOperator::test_print_augmented_assign"
] | [
"pyflakes/test/test_other.py::Test::test_attrAugmentedAssignment",
"pyflakes/test/test_other.py::Test::test_breakInsideLoop",
"pyflakes/test/test_other.py::Test::test_breakOutsideLoop",
"pyflakes/test/test_other.py::Test::test_classFunctionDecorator",
"pyflakes/test/test_other.py::Test::test_classNameDefinedPreviously",
"pyflakes/test/test_other.py::Test::test_classNameUndefinedInClassBody",
"pyflakes/test/test_other.py::Test::test_classRedefinedAsFunction",
"pyflakes/test/test_other.py::Test::test_classRedefinition",
"pyflakes/test/test_other.py::Test::test_classWithReturn",
"pyflakes/test/test_other.py::Test::test_classWithYield",
"pyflakes/test/test_other.py::Test::test_classWithYieldFrom",
"pyflakes/test/test_other.py::Test::test_comparison",
"pyflakes/test/test_other.py::Test::test_containment",
"pyflakes/test/test_other.py::Test::test_continueInsideLoop",
"pyflakes/test/test_other.py::Test::test_continueOutsideLoop",
"pyflakes/test/test_other.py::Test::test_defaultExceptLast",
"pyflakes/test/test_other.py::Test::test_defaultExceptNotLast",
"pyflakes/test/test_other.py::Test::test_doubleAssignmentConditionally",
"pyflakes/test/test_other.py::Test::test_doubleAssignmentWithUse",
"pyflakes/test/test_other.py::Test::test_duplicateArgs",
"pyflakes/test/test_other.py::Test::test_ellipsis",
"pyflakes/test/test_other.py::Test::test_extendedSlice",
"pyflakes/test/test_other.py::Test::test_functionDecorator",
"pyflakes/test/test_other.py::Test::test_functionRedefinedAsClass",
"pyflakes/test/test_other.py::Test::test_function_arguments",
"pyflakes/test/test_other.py::Test::test_function_arguments_python3",
"pyflakes/test/test_other.py::Test::test_globalDeclaredInDifferentScope",
"pyflakes/test/test_other.py::Test::test_identity",
"pyflakes/test/test_other.py::Test::test_localReferencedBeforeAssignment",
"pyflakes/test/test_other.py::Test::test_loopControl",
"pyflakes/test/test_other.py::Test::test_modernProperty",
"pyflakes/test/test_other.py::Test::test_moduleWithReturn",
"pyflakes/test/test_other.py::Test::test_moduleWithYield",
"pyflakes/test/test_other.py::Test::test_moduleWithYieldFrom",
"pyflakes/test/test_other.py::Test::test_redefinedClassFunction",
"pyflakes/test/test_other.py::Test::test_redefinedFunction",
"pyflakes/test/test_other.py::Test::test_redefinedIfElseFunction",
"pyflakes/test/test_other.py::Test::test_redefinedIfElseInListComp",
"pyflakes/test/test_other.py::Test::test_redefinedIfFunction",
"pyflakes/test/test_other.py::Test::test_redefinedInDictComprehension",
"pyflakes/test/test_other.py::Test::test_redefinedInGenerator",
"pyflakes/test/test_other.py::Test::test_redefinedInSetComprehension",
"pyflakes/test/test_other.py::Test::test_redefinedTryExceptFunction",
"pyflakes/test/test_other.py::Test::test_redefinedTryFunction",
"pyflakes/test/test_other.py::Test::test_redefinedUnderscoreFunction",
"pyflakes/test/test_other.py::Test::test_redefinedUnderscoreImportation",
"pyflakes/test/test_other.py::Test::test_starredAssignmentErrors",
"pyflakes/test/test_other.py::Test::test_starredAssignmentNoError",
"pyflakes/test/test_other.py::Test::test_unaryPlus",
"pyflakes/test/test_other.py::Test::test_undefinedBaseClass",
"pyflakes/test/test_other.py::Test::test_varAugmentedAssignment",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assert_static",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assert_tuple",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assert_tuple_empty",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assert_with_message",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assert_without_message",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assignInForLoop",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assignInListComprehension",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assignToGlobal",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assignToMember",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assignToNonlocal",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assign_expr",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assign_expr_generator_scope",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assign_expr_nested",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assignmentInsideLoop",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_augmentedAssignmentImportedFunctionCall",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_closedOver",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_dictComprehension",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_doubleClosedOver",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_exceptWithoutNameInFunction",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_exceptWithoutNameInFunctionTuple",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_exceptionUnusedInExcept",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_exceptionUnusedInExceptInFunction",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_exceptionUsedInExcept",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_f_string",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_generatorExpression",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_if_tuple",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_ifexp",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_listUnpacking",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_setComprehensionAndLiteral",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_tracebackhideSpecialVariable",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_tupleUnpacking",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_unusedUnderscoreVariable",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_unusedVariable",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_unusedVariableAsLocals",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_unusedVariableNoLocals",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_variableUsedInLoop",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementAttributeName",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementComplicatedTarget",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementListNames",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementNameDefinedInBody",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementNoNames",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementSingleName",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementSingleNameRedefined",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementSingleNameUndefined",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementSubscript",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementSubscriptUndefined",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementTupleNames",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementTupleNamesRedefined",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementTupleNamesUndefined",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementUndefinedInExpression",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementUndefinedInside",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_yieldFromUndefined",
"pyflakes/test/test_other.py::TestStringFormatting::test_f_string_without_placeholders",
"pyflakes/test/test_other.py::TestStringFormatting::test_invalid_dot_format_calls",
"pyflakes/test/test_other.py::TestStringFormatting::test_invalid_percent_format_calls",
"pyflakes/test/test_other.py::TestStringFormatting::test_ok_percent_format_cannot_determine_element_count",
"pyflakes/test/test_other.py::TestAsyncStatements::test_asyncDef",
"pyflakes/test/test_other.py::TestAsyncStatements::test_asyncDefAwait",
"pyflakes/test/test_other.py::TestAsyncStatements::test_asyncDefUndefined",
"pyflakes/test/test_other.py::TestAsyncStatements::test_asyncFor",
"pyflakes/test/test_other.py::TestAsyncStatements::test_asyncForUnderscoreLoopVar",
"pyflakes/test/test_other.py::TestAsyncStatements::test_asyncWith",
"pyflakes/test/test_other.py::TestAsyncStatements::test_asyncWithItem",
"pyflakes/test/test_other.py::TestAsyncStatements::test_formatstring",
"pyflakes/test/test_other.py::TestAsyncStatements::test_loopControlInAsyncFor",
"pyflakes/test/test_other.py::TestAsyncStatements::test_loopControlInAsyncForElse",
"pyflakes/test/test_other.py::TestAsyncStatements::test_matmul",
"pyflakes/test/test_other.py::TestAsyncStatements::test_raise_notimplemented",
"pyflakes/test/test_other.py::TestIncompatiblePrintOperator::test_invalid_print_when_imported_from_future",
"pyflakes/test/test_other.py::TestIncompatiblePrintOperator::test_print_as_condition_test",
"pyflakes/test/test_other.py::TestIncompatiblePrintOperator::test_print_function_assignment",
"pyflakes/test/test_other.py::TestIncompatiblePrintOperator::test_print_in_lambda",
"pyflakes/test/test_other.py::TestIncompatiblePrintOperator::test_print_returned_in_function",
"pyflakes/test/test_other.py::TestIncompatiblePrintOperator::test_valid_print"
] | {
"failed_lite_validators": [
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2022-11-24T16:21:09Z" | mit |
|
PyCQA__pyflakes-754 | diff --git a/pyflakes/checker.py b/pyflakes/checker.py
index 919e1bb..7ee6a1d 100644
--- a/pyflakes/checker.py
+++ b/pyflakes/checker.py
@@ -7,6 +7,7 @@ Also, it models the Bindings and Scopes.
import __future__
import builtins
import ast
+import collections
import contextlib
import doctest
import functools
@@ -735,7 +736,6 @@ class Checker:
nodeDepth = 0
offset = None
_in_annotation = AnnotationState.NONE
- _in_deferred = False
builtIns = set(builtin_vars).union(_MAGIC_GLOBALS)
_customBuiltIns = os.environ.get('PYFLAKES_BUILTINS')
@@ -746,7 +746,7 @@ class Checker:
def __init__(self, tree, filename='(none)', builtins=None,
withDoctest='PYFLAKES_DOCTEST' in os.environ, file_tokens=()):
self._nodeHandlers = {}
- self._deferredFunctions = []
+ self._deferred = collections.deque()
self.deadScopes = []
self.messages = []
self.filename = filename
@@ -762,12 +762,8 @@ class Checker:
for builtin in self.builtIns:
self.addBinding(None, Builtin(builtin))
self.handleChildren(tree)
- self._in_deferred = True
- self.runDeferred(self._deferredFunctions)
- # Set _deferredFunctions to None so that deferFunction will fail
- # noisily if called after we've run through the deferred functions.
- self._deferredFunctions = None
- del self.scopeStack[1:]
+
+ self._run_deferred()
self.popScope()
self.checkDeadScopes()
@@ -787,17 +783,18 @@ class Checker:
`callable` is called, the scope at the time this is called will be
restored, however it will contain any new bindings added to it.
"""
- self._deferredFunctions.append((callable, self.scopeStack[:], self.offset))
+ self._deferred.append((callable, self.scopeStack[:], self.offset))
- def runDeferred(self, deferred):
- """
- Run the callables in C{deferred} using their associated scope stack.
- """
- for handler, scope, offset in deferred:
- self.scopeStack = scope
- self.offset = offset
+ def _run_deferred(self):
+ orig = (self.scopeStack, self.offset)
+
+ while self._deferred:
+ handler, scope, offset = self._deferred.popleft()
+ self.scopeStack, self.offset = scope, offset
handler()
+ self.scopeStack, self.offset = orig
+
def _in_doctest(self):
return (len(self.scopeStack) >= 2 and
isinstance(self.scopeStack[1], DoctestScope))
@@ -1696,10 +1693,7 @@ class Checker:
node.col_offset,
messages.ForwardAnnotationSyntaxError,
)
- if self._in_deferred:
- fn()
- else:
- self.deferFunction(fn)
+ self.deferFunction(fn)
def CONSTANT(self, node):
if isinstance(node.value, str):
| PyCQA/pyflakes | 4158a4537773ec3da41aed5afdea46c121082804 | diff --git a/pyflakes/test/test_type_annotations.py b/pyflakes/test/test_type_annotations.py
index 2f27b06..f0fd3b9 100644
--- a/pyflakes/test/test_type_annotations.py
+++ b/pyflakes/test/test_type_annotations.py
@@ -594,6 +594,20 @@ class TestTypeAnnotations(TestCase):
return None
""")
+ def test_forward_annotations_for_classes_in_scope(self):
+ # see #749
+ self.flakes("""
+ from typing import Optional
+
+ def f():
+ class C:
+ a: "D"
+ b: Optional["D"]
+ c: "Optional[D]"
+
+ class D: pass
+ """)
+
def test_idomiatic_typing_guards(self):
# typing.TYPE_CHECKING: python3.5.3+
self.flakes("""
| Error when referencing a class yet not declared inside function
I am facing a bug.
I created this example to test all behaviours I can foresee and spotted a bug:
```python
from typing import Optional
class InnerModel1:
model2: "Model2"
mode2_no_err1: Optional["Model2"] # NO ERROR
mode2_no_err2: "Optional[Model2]" # NO ERROR
class Model2:
pass
def f():
class InnerModel1:
model2: "InnerModel2"
mode2_err: Optional["InnerModel2"] # ERROR
mode2_no_err: "Optional[InnerModel2]"
class InnerModel2:
pass
```
if I run `pyflakes` against this code I get:
`pyflakes_bug.py:14:29: undefined name 'InnerModel2'`
I would expect that annotating a with `Optional["InnerModel2"]` or with `"Optional[InnerModel2]"` should have the same behaviour as demonstrated with `Optional["Model2"]` and `"Optional[Model2]"`.
Why am I defining a class inside a method? For now this is supporting lots of unit testing on my side.
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_forward_annotations_for_classes_in_scope"
] | [
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_TypeAlias_annotations",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_aliased_import",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_annotated_async_def",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_annotated_type_typing_missing_forward_type",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_annotated_type_typing_missing_forward_type_multiple_args",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_annotated_type_typing_with_string_args",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_annotated_type_typing_with_string_args_in_union",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_annotating_an_import",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_deferred_twice_annotation",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_idomiatic_typing_guards",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_literal_type_some_other_module",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_literal_type_typing",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_literal_type_typing_extensions",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_literal_union_type_typing",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_namedtypes_classes",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_nested_partially_quoted_type_assignment",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_not_a_typing_overload",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_overload_in_class",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_overload_with_multiple_decorators",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_partial_string_annotations_with_future_annotations",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_partially_quoted_type_annotation",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_partially_quoted_type_assignment",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_positional_only_argument_annotations",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_postponed_annotations",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_quoted_TypeVar_bound",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_quoted_TypeVar_constraints",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_quoted_type_cast",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_quoted_type_cast_renamed_import",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_return_annotation_is_class_scope_variable",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_return_annotation_is_function_body_variable",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_type_annotation_clobbers_all",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_type_cast_literal_str_to_str",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typednames_correct_forward_ref",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typingExtensionsOverload",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typingOverload",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typingOverloadAsync",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typing_guard_for_protocol",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_unassigned_annotation_is_undefined",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_unused_annotation",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_variable_annotation_references_self_name_undefined",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_variable_annotations"
] | {
"failed_lite_validators": [
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2022-11-27T20:53:59Z" | mit |
|
PyCQA__pyflakes-761 | diff --git a/pyflakes/checker.py b/pyflakes/checker.py
index e927715..4d778a8 100644
--- a/pyflakes/checker.py
+++ b/pyflakes/checker.py
@@ -263,6 +263,11 @@ class Definition(Binding):
"""
A binding that defines a function or a class.
"""
+ def redefines(self, other):
+ return (
+ super().redefines(other) or
+ (isinstance(other, Assignment) and self.name == other.name)
+ )
class Builtin(Definition):
| PyCQA/pyflakes | 33bbb8266420e34a93ea74299177c19fd463acc0 | diff --git a/pyflakes/test/test_other.py b/pyflakes/test/test_other.py
index 42e99ae..aebdcea 100644
--- a/pyflakes/test/test_other.py
+++ b/pyflakes/test/test_other.py
@@ -118,6 +118,12 @@ class Test(TestCase):
def a(): pass
''', m.RedefinedWhileUnused)
+ def test_redefined_function_shadows_variable(self):
+ self.flakes('''
+ x = 1
+ def x(): pass
+ ''', m.RedefinedWhileUnused)
+
def test_redefinedUnderscoreFunction(self):
"""
Test that shadowing a function definition named with underscore doesn't
| should produce error for attribute hidden by a method
# How to reproduce
```
$ flake8 --version
6.0.0 (mccabe: 0.7.0, pycodestyle: 2.10.0, pyflakes: 3.0.1) CPython 3.11.1 on Linux
$ flake8 ok.py
ok.py:5:5: F811 redefinition of unused 'bar' from line 2
$ flake8 fail.py
```
## `ok.py`
```python
class Foo:
def bar(self):
return 0
def bar(self):
return 1
```
## `fail.py`
```python
class Foo:
bar = 0
def bar(self):
return 1
```
# Reasons
I do understand that redefinition of variables is a useful pattern, for example [`structlog` Bound Loggers](https://www.structlog.org/en/stable/bound-loggers.html) uses it extensively.
```python
log = structlog.get_logger()
log = log.bind(user=user)
log = log.bind(time=now())
log.info('hello world')
```
## Problems
I spent some time debugging a problem in our code base related to [Factory Boy Lazy Attributes](https://factoryboy.readthedocs.io/en/stable/#lazy-attributes).
```python
class UserFactory(Factory):
class Meta:
model = User
name = 'joe'
email = LazyAttribute(lambda user: f'{user.name}@example.com')
# A 1000 lines later
@post_generation
def email(self):
return '[email protected]'
```
## Proposal
Deny attribute redefinition inside class body.
Thoughts? | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"pyflakes/test/test_other.py::Test::test_redefined_function_shadows_variable"
] | [
"pyflakes/test/test_other.py::Test::test_attrAugmentedAssignment",
"pyflakes/test/test_other.py::Test::test_breakInsideLoop",
"pyflakes/test/test_other.py::Test::test_breakOutsideLoop",
"pyflakes/test/test_other.py::Test::test_classFunctionDecorator",
"pyflakes/test/test_other.py::Test::test_classNameDefinedPreviously",
"pyflakes/test/test_other.py::Test::test_classNameUndefinedInClassBody",
"pyflakes/test/test_other.py::Test::test_classRedefinedAsFunction",
"pyflakes/test/test_other.py::Test::test_classRedefinition",
"pyflakes/test/test_other.py::Test::test_classWithReturn",
"pyflakes/test/test_other.py::Test::test_classWithYield",
"pyflakes/test/test_other.py::Test::test_classWithYieldFrom",
"pyflakes/test/test_other.py::Test::test_comparison",
"pyflakes/test/test_other.py::Test::test_containment",
"pyflakes/test/test_other.py::Test::test_continueInsideLoop",
"pyflakes/test/test_other.py::Test::test_continueOutsideLoop",
"pyflakes/test/test_other.py::Test::test_defaultExceptLast",
"pyflakes/test/test_other.py::Test::test_defaultExceptNotLast",
"pyflakes/test/test_other.py::Test::test_doubleAssignmentConditionally",
"pyflakes/test/test_other.py::Test::test_doubleAssignmentWithUse",
"pyflakes/test/test_other.py::Test::test_duplicateArgs",
"pyflakes/test/test_other.py::Test::test_ellipsis",
"pyflakes/test/test_other.py::Test::test_extendedSlice",
"pyflakes/test/test_other.py::Test::test_functionDecorator",
"pyflakes/test/test_other.py::Test::test_functionRedefinedAsClass",
"pyflakes/test/test_other.py::Test::test_function_arguments",
"pyflakes/test/test_other.py::Test::test_function_arguments_python3",
"pyflakes/test/test_other.py::Test::test_globalDeclaredInDifferentScope",
"pyflakes/test/test_other.py::Test::test_identity",
"pyflakes/test/test_other.py::Test::test_localReferencedBeforeAssignment",
"pyflakes/test/test_other.py::Test::test_loopControl",
"pyflakes/test/test_other.py::Test::test_modernProperty",
"pyflakes/test/test_other.py::Test::test_moduleWithReturn",
"pyflakes/test/test_other.py::Test::test_moduleWithYield",
"pyflakes/test/test_other.py::Test::test_moduleWithYieldFrom",
"pyflakes/test/test_other.py::Test::test_redefinedClassFunction",
"pyflakes/test/test_other.py::Test::test_redefinedFunction",
"pyflakes/test/test_other.py::Test::test_redefinedIfElseFunction",
"pyflakes/test/test_other.py::Test::test_redefinedIfElseInListComp",
"pyflakes/test/test_other.py::Test::test_redefinedIfFunction",
"pyflakes/test/test_other.py::Test::test_redefinedInDictComprehension",
"pyflakes/test/test_other.py::Test::test_redefinedInGenerator",
"pyflakes/test/test_other.py::Test::test_redefinedInSetComprehension",
"pyflakes/test/test_other.py::Test::test_redefinedTryExceptFunction",
"pyflakes/test/test_other.py::Test::test_redefinedTryFunction",
"pyflakes/test/test_other.py::Test::test_redefinedUnderscoreFunction",
"pyflakes/test/test_other.py::Test::test_redefinedUnderscoreImportation",
"pyflakes/test/test_other.py::Test::test_starredAssignmentErrors",
"pyflakes/test/test_other.py::Test::test_starredAssignmentNoError",
"pyflakes/test/test_other.py::Test::test_unaryPlus",
"pyflakes/test/test_other.py::Test::test_undefinedBaseClass",
"pyflakes/test/test_other.py::Test::test_varAugmentedAssignment",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assert_static",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assert_tuple",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assert_tuple_empty",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assert_with_message",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assert_without_message",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assignInForLoop",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assignInListComprehension",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assignToGlobal",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assignToMember",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assignToNonlocal",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assign_expr",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assign_expr_generator_scope",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assign_expr_nested",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assignmentInsideLoop",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_augmentedAssignmentImportedFunctionCall",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_closedOver",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_dictComprehension",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_doubleClosedOver",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_exceptWithoutNameInFunction",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_exceptWithoutNameInFunctionTuple",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_exceptionUnusedInExcept",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_exceptionUnusedInExceptInFunction",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_exceptionUsedInExcept",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_f_string",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_generatorExpression",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_if_tuple",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_ifexp",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_listUnpacking",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_setComprehensionAndLiteral",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_tracebackhideSpecialVariable",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_tupleUnpacking",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_unusedUnderscoreVariable",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_unusedVariable",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_unusedVariableAsLocals",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_unusedVariableNoLocals",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_variableUsedInLoop",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementAttributeName",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementComplicatedTarget",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementListNames",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementNameDefinedInBody",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementNoNames",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementSingleName",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementSingleNameRedefined",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementSingleNameUndefined",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementSubscript",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementSubscriptUndefined",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementTupleNames",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementTupleNamesRedefined",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementTupleNamesUndefined",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementUndefinedInExpression",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementUndefinedInside",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_yieldFromUndefined",
"pyflakes/test/test_other.py::TestStringFormatting::test_f_string_without_placeholders",
"pyflakes/test/test_other.py::TestStringFormatting::test_invalid_dot_format_calls",
"pyflakes/test/test_other.py::TestStringFormatting::test_invalid_percent_format_calls",
"pyflakes/test/test_other.py::TestStringFormatting::test_ok_percent_format_cannot_determine_element_count",
"pyflakes/test/test_other.py::TestAsyncStatements::test_asyncDef",
"pyflakes/test/test_other.py::TestAsyncStatements::test_asyncDefAwait",
"pyflakes/test/test_other.py::TestAsyncStatements::test_asyncDefUndefined",
"pyflakes/test/test_other.py::TestAsyncStatements::test_asyncFor",
"pyflakes/test/test_other.py::TestAsyncStatements::test_asyncForUnderscoreLoopVar",
"pyflakes/test/test_other.py::TestAsyncStatements::test_asyncWith",
"pyflakes/test/test_other.py::TestAsyncStatements::test_asyncWithItem",
"pyflakes/test/test_other.py::TestAsyncStatements::test_formatstring",
"pyflakes/test/test_other.py::TestAsyncStatements::test_loopControlInAsyncFor",
"pyflakes/test/test_other.py::TestAsyncStatements::test_loopControlInAsyncForElse",
"pyflakes/test/test_other.py::TestAsyncStatements::test_matmul",
"pyflakes/test/test_other.py::TestAsyncStatements::test_raise_notimplemented",
"pyflakes/test/test_other.py::TestIncompatiblePrintOperator::test_invalid_print_when_imported_from_future",
"pyflakes/test/test_other.py::TestIncompatiblePrintOperator::test_print_as_condition_test",
"pyflakes/test/test_other.py::TestIncompatiblePrintOperator::test_print_augmented_assign",
"pyflakes/test/test_other.py::TestIncompatiblePrintOperator::test_print_function_assignment",
"pyflakes/test/test_other.py::TestIncompatiblePrintOperator::test_print_in_lambda",
"pyflakes/test/test_other.py::TestIncompatiblePrintOperator::test_print_returned_in_function",
"pyflakes/test/test_other.py::TestIncompatiblePrintOperator::test_valid_print"
] | {
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
} | "2023-01-12T16:20:17Z" | mit |
|
PyCQA__pyflakes-765 | diff --git a/pyflakes/checker.py b/pyflakes/checker.py
index 4d778a8..e654afa 100644
--- a/pyflakes/checker.py
+++ b/pyflakes/checker.py
@@ -1068,7 +1068,7 @@ class Checker:
binding = scope.get(name, None)
if isinstance(binding, Annotation) and not self._in_postponed_annotation:
- scope[name].used = True
+ scope[name].used = (self.scope, node)
continue
if name == 'print' and isinstance(binding, Builtin):
| PyCQA/pyflakes | e9324649874a7124a08c3826d4cf78a4dc3aa32c | diff --git a/pyflakes/test/test_type_annotations.py b/pyflakes/test/test_type_annotations.py
index f0fd3b9..396d676 100644
--- a/pyflakes/test/test_type_annotations.py
+++ b/pyflakes/test/test_type_annotations.py
@@ -367,6 +367,13 @@ class TestTypeAnnotations(TestCase):
x = 3
''', m.UnusedVariable)
+ def test_unused_annotation_in_outer_scope_reassigned_in_local_scope(self):
+ self.flakes('''
+ x: int
+ x.__dict__
+ def f(): x = 1
+ ''', m.UndefinedName, m.UnusedVariable)
+
def test_unassigned_annotation_is_undefined(self):
self.flakes('''
name: str
| Regression with version 3.0 ('bool' object is not subscriptable)
Hello! I found a regression with version 3.0
This snippet:
```
test: int
test.__dict__
def fn():
test = 1
```
Raises the following exception with version 3.0.1:
```
Traceback (most recent call last):
File "/opt/homebrew/bin/pyflakes", line 8, in <module>
sys.exit(main())
File "/opt/homebrew/lib/python3.10/site-packages/pyflakes/api.py", line 182, in main
warnings = checkRecursive(args, reporter)
File "/opt/homebrew/lib/python3.10/site-packages/pyflakes/api.py", line 127, in checkRecursive
warnings += checkPath(sourcePath, reporter)
File "/opt/homebrew/lib/python3.10/site-packages/pyflakes/api.py", line 71, in checkPath
return check(codestr, filename, reporter)
File "/opt/homebrew/lib/python3.10/site-packages/pyflakes/api.py", line 47, in check
w = checker.Checker(tree, filename=filename)
File "/opt/homebrew/lib/python3.10/site-packages/pyflakes/checker.py", line 789, in __init__
self.runDeferred(self._deferredFunctions)
File "/opt/homebrew/lib/python3.10/site-packages/pyflakes/checker.py", line 832, in runDeferred
handler()
File "/opt/homebrew/lib/python3.10/site-packages/pyflakes/checker.py", line 1998, in runFunction
self.handleChildren(node, omit=['decorator_list', 'returns'])
File "/opt/homebrew/lib/python3.10/site-packages/pyflakes/checker.py", line 1238, in handleChildren
self.handleNode(node, tree)
File "/opt/homebrew/lib/python3.10/site-packages/pyflakes/checker.py", line 1283, in handleNode
handler(node)
File "/opt/homebrew/lib/python3.10/site-packages/pyflakes/checker.py", line 1238, in handleChildren
self.handleNode(node, tree)
File "/opt/homebrew/lib/python3.10/site-packages/pyflakes/checker.py", line 1283, in handleNode
handler(node)
File "/opt/homebrew/lib/python3.10/site-packages/pyflakes/checker.py", line 1889, in NAME
self.handleNodeStore(node)
File "/opt/homebrew/lib/python3.10/site-packages/pyflakes/checker.py", line 1163, in handleNodeStore
if used and used[0] is self.scope and name not in self.scope.globals:
TypeError: 'bool' object is not subscriptable
```
But it is correctly handled by version 2.5.0, that returns the correct errors:
```
test.py:3:1: undefined name 'test'
test.py:7:5: local variable 'test' is assigned to but never used
```
The snippet does not cause exceptions when any part of it is removed (for example the type annotation or the `test.__dict__` or the assignment in the function)
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_unused_annotation_in_outer_scope_reassigned_in_local_scope"
] | [
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_TypeAlias_annotations",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_aliased_import",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_annotated_async_def",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_annotated_type_typing_missing_forward_type",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_annotated_type_typing_missing_forward_type_multiple_args",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_annotated_type_typing_with_string_args",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_annotated_type_typing_with_string_args_in_union",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_annotating_an_import",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_deferred_twice_annotation",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_forward_annotations_for_classes_in_scope",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_idomiatic_typing_guards",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_literal_type_some_other_module",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_literal_type_typing",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_literal_type_typing_extensions",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_literal_union_type_typing",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_namedtypes_classes",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_nested_partially_quoted_type_assignment",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_not_a_typing_overload",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_overload_in_class",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_overload_with_multiple_decorators",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_partial_string_annotations_with_future_annotations",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_partially_quoted_type_annotation",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_partially_quoted_type_assignment",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_positional_only_argument_annotations",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_postponed_annotations",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_quoted_TypeVar_bound",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_quoted_TypeVar_constraints",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_quoted_type_cast",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_quoted_type_cast_renamed_import",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_return_annotation_is_class_scope_variable",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_return_annotation_is_function_body_variable",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_type_annotation_clobbers_all",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_type_cast_literal_str_to_str",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typednames_correct_forward_ref",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typingExtensionsOverload",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typingOverload",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typingOverloadAsync",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_typing_guard_for_protocol",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_unassigned_annotation_is_undefined",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_unused_annotation",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_variable_annotation_references_self_name_undefined",
"pyflakes/test/test_type_annotations.py::TestTypeAnnotations::test_variable_annotations"
] | {
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
} | "2023-01-31T18:34:43Z" | mit |
|
PyCQA__pyflakes-801 | diff --git a/pyflakes/checker.py b/pyflakes/checker.py
index 754ab30..47a59ba 100644
--- a/pyflakes/checker.py
+++ b/pyflakes/checker.py
@@ -548,7 +548,7 @@ class FunctionScope(Scope):
"""
usesLocals = False
alwaysUsed = {'__tracebackhide__', '__traceback_info__',
- '__traceback_supplement__'}
+ '__traceback_supplement__', '__debuggerskip__'}
def __init__(self):
super().__init__()
@@ -1003,14 +1003,17 @@ class Checker:
# don't treat annotations as assignments if there is an existing value
# in scope
if value.name not in self.scope or not isinstance(value, Annotation):
- cur_scope_pos = -1
- # As per PEP 572, use scope in which outermost generator is defined
- while (
- isinstance(value, NamedExprAssignment) and
- isinstance(self.scopeStack[cur_scope_pos], GeneratorScope)
- ):
- cur_scope_pos -= 1
- self.scopeStack[cur_scope_pos][value.name] = value
+ if isinstance(value, NamedExprAssignment):
+ # PEP 572: use scope in which outermost generator is defined
+ scope = next(
+ scope
+ for scope in reversed(self.scopeStack)
+ if not isinstance(scope, GeneratorScope)
+ )
+ # it may be a re-assignment to an already existing name
+ scope.setdefault(value.name, value)
+ else:
+ self.scope[value.name] = value
def _unknown_handler(self, node):
# this environment variable configures whether to error on unknown
| PyCQA/pyflakes | 881ed2f00255cb247577adad59d4f05122a5f87a | diff --git a/pyflakes/test/test_other.py b/pyflakes/test/test_other.py
index aebdcea..0af87ec 100644
--- a/pyflakes/test/test_other.py
+++ b/pyflakes/test/test_other.py
@@ -1349,6 +1349,16 @@ class TestUnusedAssignment(TestCase):
__tracebackhide__ = True
""")
+ def test_debuggerskipSpecialVariable(self):
+ """
+ Do not warn about unused local variable __debuggerskip__, which is
+ a special variable for IPython.
+ """
+ self.flakes("""
+ def helper():
+ __debuggerskip__ = True
+ """)
+
def test_ifexp(self):
"""
Test C{foo if bar else baz} statements.
@@ -1707,6 +1717,13 @@ class TestUnusedAssignment(TestCase):
print(y)
''')
+ def test_assign_expr_generator_scope_reassigns_parameter(self):
+ self.flakes('''
+ def foo(x):
+ fns = [lambda x: x + 1, lambda x: x + 2, lambda x: x + 3]
+ return [(x := fn(x)) for fn in fns]
+ ''')
+
def test_assign_expr_nested(self):
"""Test assignment expressions in nested expressions."""
self.flakes('''
| False Positive: walrus in a list comprehension
Minimal reproduction:
```python
def foo(x):
fns = [lambda x: x + 1, lambda x: x + 2, lambda x: x + 3]
return [(x := fn(x)) for fn in fns]
```
This raises F841 incorrectly asserting that the `x` variable assigned in the comprehension is never used | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assign_expr_generator_scope_reassigns_parameter",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_debuggerskipSpecialVariable"
] | [
"pyflakes/test/test_other.py::Test::test_attrAugmentedAssignment",
"pyflakes/test/test_other.py::Test::test_breakInsideLoop",
"pyflakes/test/test_other.py::Test::test_breakOutsideLoop",
"pyflakes/test/test_other.py::Test::test_classFunctionDecorator",
"pyflakes/test/test_other.py::Test::test_classNameDefinedPreviously",
"pyflakes/test/test_other.py::Test::test_classNameUndefinedInClassBody",
"pyflakes/test/test_other.py::Test::test_classRedefinedAsFunction",
"pyflakes/test/test_other.py::Test::test_classRedefinition",
"pyflakes/test/test_other.py::Test::test_classWithReturn",
"pyflakes/test/test_other.py::Test::test_classWithYield",
"pyflakes/test/test_other.py::Test::test_classWithYieldFrom",
"pyflakes/test/test_other.py::Test::test_comparison",
"pyflakes/test/test_other.py::Test::test_containment",
"pyflakes/test/test_other.py::Test::test_continueInsideLoop",
"pyflakes/test/test_other.py::Test::test_continueOutsideLoop",
"pyflakes/test/test_other.py::Test::test_defaultExceptLast",
"pyflakes/test/test_other.py::Test::test_defaultExceptNotLast",
"pyflakes/test/test_other.py::Test::test_doubleAssignmentConditionally",
"pyflakes/test/test_other.py::Test::test_doubleAssignmentWithUse",
"pyflakes/test/test_other.py::Test::test_duplicateArgs",
"pyflakes/test/test_other.py::Test::test_ellipsis",
"pyflakes/test/test_other.py::Test::test_extendedSlice",
"pyflakes/test/test_other.py::Test::test_functionDecorator",
"pyflakes/test/test_other.py::Test::test_functionRedefinedAsClass",
"pyflakes/test/test_other.py::Test::test_function_arguments",
"pyflakes/test/test_other.py::Test::test_function_arguments_python3",
"pyflakes/test/test_other.py::Test::test_globalDeclaredInDifferentScope",
"pyflakes/test/test_other.py::Test::test_identity",
"pyflakes/test/test_other.py::Test::test_localReferencedBeforeAssignment",
"pyflakes/test/test_other.py::Test::test_loopControl",
"pyflakes/test/test_other.py::Test::test_modernProperty",
"pyflakes/test/test_other.py::Test::test_moduleWithReturn",
"pyflakes/test/test_other.py::Test::test_moduleWithYield",
"pyflakes/test/test_other.py::Test::test_moduleWithYieldFrom",
"pyflakes/test/test_other.py::Test::test_redefinedClassFunction",
"pyflakes/test/test_other.py::Test::test_redefinedFunction",
"pyflakes/test/test_other.py::Test::test_redefinedIfElseFunction",
"pyflakes/test/test_other.py::Test::test_redefinedIfElseInListComp",
"pyflakes/test/test_other.py::Test::test_redefinedIfFunction",
"pyflakes/test/test_other.py::Test::test_redefinedInDictComprehension",
"pyflakes/test/test_other.py::Test::test_redefinedInGenerator",
"pyflakes/test/test_other.py::Test::test_redefinedInSetComprehension",
"pyflakes/test/test_other.py::Test::test_redefinedTryExceptFunction",
"pyflakes/test/test_other.py::Test::test_redefinedTryFunction",
"pyflakes/test/test_other.py::Test::test_redefinedUnderscoreFunction",
"pyflakes/test/test_other.py::Test::test_redefinedUnderscoreImportation",
"pyflakes/test/test_other.py::Test::test_redefined_function_shadows_variable",
"pyflakes/test/test_other.py::Test::test_starredAssignmentErrors",
"pyflakes/test/test_other.py::Test::test_starredAssignmentNoError",
"pyflakes/test/test_other.py::Test::test_unaryPlus",
"pyflakes/test/test_other.py::Test::test_undefinedBaseClass",
"pyflakes/test/test_other.py::Test::test_varAugmentedAssignment",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assert_static",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assert_tuple",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assert_tuple_empty",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assert_with_message",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assert_without_message",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assignInForLoop",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assignInListComprehension",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assignToGlobal",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assignToMember",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assignToNonlocal",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assign_expr",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assign_expr_generator_scope",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assign_expr_nested",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assignmentInsideLoop",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_augmentedAssignmentImportedFunctionCall",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_closedOver",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_dictComprehension",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_doubleClosedOver",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_exceptWithoutNameInFunction",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_exceptWithoutNameInFunctionTuple",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_exceptionUnusedInExcept",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_exceptionUnusedInExceptInFunction",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_exceptionUsedInExcept",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_f_string",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_generatorExpression",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_if_tuple",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_ifexp",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_listUnpacking",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_setComprehensionAndLiteral",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_tracebackhideSpecialVariable",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_tupleUnpacking",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_unusedUnderscoreVariable",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_unusedVariable",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_unusedVariableAsLocals",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_unusedVariableNoLocals",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_variableUsedInLoop",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementAttributeName",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementComplicatedTarget",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementListNames",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementNameDefinedInBody",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementNoNames",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementSingleName",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementSingleNameRedefined",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementSingleNameUndefined",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementSubscript",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementSubscriptUndefined",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementTupleNames",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementTupleNamesRedefined",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementTupleNamesUndefined",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementUndefinedInExpression",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementUndefinedInside",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_yieldFromUndefined",
"pyflakes/test/test_other.py::TestStringFormatting::test_f_string_without_placeholders",
"pyflakes/test/test_other.py::TestStringFormatting::test_invalid_dot_format_calls",
"pyflakes/test/test_other.py::TestStringFormatting::test_invalid_percent_format_calls",
"pyflakes/test/test_other.py::TestStringFormatting::test_ok_percent_format_cannot_determine_element_count",
"pyflakes/test/test_other.py::TestAsyncStatements::test_asyncDef",
"pyflakes/test/test_other.py::TestAsyncStatements::test_asyncDefAwait",
"pyflakes/test/test_other.py::TestAsyncStatements::test_asyncDefUndefined",
"pyflakes/test/test_other.py::TestAsyncStatements::test_asyncFor",
"pyflakes/test/test_other.py::TestAsyncStatements::test_asyncForUnderscoreLoopVar",
"pyflakes/test/test_other.py::TestAsyncStatements::test_asyncWith",
"pyflakes/test/test_other.py::TestAsyncStatements::test_asyncWithItem",
"pyflakes/test/test_other.py::TestAsyncStatements::test_formatstring",
"pyflakes/test/test_other.py::TestAsyncStatements::test_loopControlInAsyncFor",
"pyflakes/test/test_other.py::TestAsyncStatements::test_loopControlInAsyncForElse",
"pyflakes/test/test_other.py::TestAsyncStatements::test_matmul",
"pyflakes/test/test_other.py::TestAsyncStatements::test_raise_notimplemented",
"pyflakes/test/test_other.py::TestIncompatiblePrintOperator::test_invalid_print_when_imported_from_future",
"pyflakes/test/test_other.py::TestIncompatiblePrintOperator::test_print_as_condition_test",
"pyflakes/test/test_other.py::TestIncompatiblePrintOperator::test_print_augmented_assign",
"pyflakes/test/test_other.py::TestIncompatiblePrintOperator::test_print_function_assignment",
"pyflakes/test/test_other.py::TestIncompatiblePrintOperator::test_print_in_lambda",
"pyflakes/test/test_other.py::TestIncompatiblePrintOperator::test_print_returned_in_function",
"pyflakes/test/test_other.py::TestIncompatiblePrintOperator::test_valid_print"
] | {
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
} | "2024-02-10T20:19:58Z" | mit |
|
PyFilesystem__pyfilesystem2-161 | diff --git a/fs/tarfs.py b/fs/tarfs.py
index 543b203..917eb03 100644
--- a/fs/tarfs.py
+++ b/fs/tarfs.py
@@ -16,7 +16,7 @@ from .enums import ResourceType
from .info import Info
from .iotools import RawWrapper
from .opener import open_fs
-from .path import dirname, normpath, relpath, basename
+from .path import dirname, relpath, basename, isbase, parts, frombase
from .wrapfs import WrapFS
from .permissions import Permissions
@@ -256,9 +256,14 @@ class ReadTarFS(FS):
else:
try:
+ implicit = False
member = self._tar.getmember(self._encode(_path))
except KeyError:
- raise errors.ResourceNotFound(path)
+ if not self.isdir(_path):
+ raise errors.ResourceNotFound(path)
+ implicit = True
+ member = tarfile.TarInfo(_path)
+ member.type = tarfile.DIRTYPE
raw_info["basic"] = {
"name": basename(self._decode(member.name)),
@@ -268,10 +273,11 @@ class ReadTarFS(FS):
if "details" in namespaces:
raw_info["details"] = {
"size": member.size,
- "type": int(self.type_map[member.type]),
- "modified": member.mtime,
+ "type": int(self.type_map[member.type])
}
- if "access" in namespaces:
+ if not implicit:
+ raw_info["details"]["modified"] = member.mtime
+ if "access" in namespaces and not implicit:
raw_info["access"] = {
"gid": member.gid,
"group": member.gname,
@@ -279,7 +285,7 @@ class ReadTarFS(FS):
"uid": member.uid,
"user": member.uname,
}
- if "tar" in namespaces:
+ if "tar" in namespaces and not implicit:
raw_info["tar"] = _get_member_info(member, self.encoding)
raw_info["tar"].update({
k.replace('is', 'is_'):getattr(member, k)()
@@ -289,39 +295,46 @@ class ReadTarFS(FS):
return Info(raw_info)
+ def isdir(self, path):
+ _path = relpath(self.validatepath(path))
+ try:
+ return self._directory[_path].isdir()
+ except KeyError:
+ return any(isbase(_path, name) for name in self._directory)
+
+ def isfile(self, path):
+ _path = relpath(self.validatepath(path))
+ try:
+ return self._directory[_path].isfile()
+ except KeyError:
+ return False
+
def setinfo(self, path, info):
self.check()
raise errors.ResourceReadOnly(path)
def listdir(self, path):
- self.check()
- _path = relpath(path)
- info = self._directory.get(_path)
- if _path:
- if info is None:
- raise errors.ResourceNotFound(path)
- if not info.isdir():
- raise errors.DirectoryExpected(path)
- dir_list = [
- basename(name)
- for name in self._directory.keys()
- if dirname(name) == _path
- ]
- return dir_list
+ _path = relpath(self.validatepath(path))
+
+ if not self.gettype(path) is ResourceType.directory:
+ raise errors.DirectoryExpected(path)
+
+ children = (frombase(_path, n) for n in self._directory if isbase(_path, n))
+ content = (parts(child)[1] for child in children if relpath(child))
+ return list(OrderedDict.fromkeys(content))
def makedir(self, path, permissions=None, recreate=False):
self.check()
raise errors.ResourceReadOnly(path)
def openbin(self, path, mode="r", buffering=-1, **options):
- self.check()
- path = relpath(normpath(path))
+ _path = relpath(self.validatepath(path))
if 'w' in mode or '+' in mode or 'a' in mode:
raise errors.ResourceReadOnly(path)
try:
- member = self._tar.getmember(self._encode(path))
+ member = self._tar.getmember(self._encode(_path))
except KeyError:
six.raise_from(errors.ResourceNotFound(path), None)
| PyFilesystem/pyfilesystem2 | 41040141870d4842f4d3b970c07436c3673ce740 | diff --git a/tests/test_tarfs.py b/tests/test_tarfs.py
index e894f6b..bfe0bc4 100644
--- a/tests/test_tarfs.py
+++ b/tests/test_tarfs.py
@@ -1,16 +1,20 @@
# -*- encoding: UTF-8
from __future__ import unicode_literals
+import io
import os
import six
import gzip
import tarfile
import getpass
+import tarfile
import tempfile
import unittest
+import uuid
from fs import tarfs
from fs import errors
+from fs.enums import ResourceType
from fs.compress import write_tar
from fs.opener import open_fs
from fs.opener.errors import NotWriteable
@@ -184,6 +188,73 @@ class TestReadTarFS(ArchiveTestCases, unittest.TestCase):
self.assertTrue(top.get('tar', 'is_file'))
+class TestImplicitDirectories(unittest.TestCase):
+ """Regression tests for #160.
+ """
+
+ @classmethod
+ def setUpClass(cls):
+ cls.tmpfs = open_fs("temp://")
+
+ @classmethod
+ def tearDownClass(cls):
+ cls.tmpfs.close()
+
+ def setUp(self):
+ self.tempfile = self.tmpfs.open('test.tar', 'wb+')
+ with tarfile.open(mode="w", fileobj=self.tempfile) as tf:
+ tf.addfile(tarfile.TarInfo("foo/bar/baz/spam.txt"), io.StringIO())
+ tf.addfile(tarfile.TarInfo("foo/eggs.bin"), io.StringIO())
+ tf.addfile(tarfile.TarInfo("foo/yolk/beans.txt"), io.StringIO())
+ info = tarfile.TarInfo("foo/yolk")
+ info.type = tarfile.DIRTYPE
+ tf.addfile(info, io.BytesIO())
+ self.tempfile.seek(0)
+ self.fs = tarfs.TarFS(self.tempfile)
+
+ def tearDown(self):
+ self.fs.close()
+ self.tempfile.close()
+
+ def test_isfile(self):
+ self.assertFalse(self.fs.isfile("foo"))
+ self.assertFalse(self.fs.isfile("foo/bar"))
+ self.assertFalse(self.fs.isfile("foo/bar/baz"))
+ self.assertTrue(self.fs.isfile("foo/bar/baz/spam.txt"))
+ self.assertTrue(self.fs.isfile("foo/yolk/beans.txt"))
+ self.assertTrue(self.fs.isfile("foo/eggs.bin"))
+ self.assertFalse(self.fs.isfile("foo/eggs.bin/baz"))
+
+ def test_isdir(self):
+ self.assertTrue(self.fs.isdir("foo"))
+ self.assertTrue(self.fs.isdir("foo/yolk"))
+ self.assertTrue(self.fs.isdir("foo/bar"))
+ self.assertTrue(self.fs.isdir("foo/bar/baz"))
+ self.assertFalse(self.fs.isdir("foo/bar/baz/spam.txt"))
+ self.assertFalse(self.fs.isdir("foo/eggs.bin"))
+ self.assertFalse(self.fs.isdir("foo/eggs.bin/baz"))
+ self.assertFalse(self.fs.isdir("foo/yolk/beans.txt"))
+
+ def test_listdir(self):
+ self.assertEqual(sorted(self.fs.listdir("foo")), ["bar", "eggs.bin", "yolk"])
+ self.assertEqual(self.fs.listdir("foo/bar"), ["baz"])
+ self.assertEqual(self.fs.listdir("foo/bar/baz"), ["spam.txt"])
+ self.assertEqual(self.fs.listdir("foo/yolk"), ["beans.txt"])
+
+ def test_getinfo(self):
+ info = self.fs.getdetails("foo/bar/baz")
+ self.assertEqual(info.name, "baz")
+ self.assertEqual(info.size, 0)
+ self.assertIs(info.type, ResourceType.directory)
+
+ info = self.fs.getdetails("foo")
+ self.assertEqual(info.name, "foo")
+ self.assertEqual(info.size, 0)
+ self.assertIs(info.type, ResourceType.directory)
+
+
+
+
class TestReadTarFSMem(TestReadTarFS):
def make_source_fs(self):
| PyFilesystem can't find existing file in tar-fs
I wrote a stackoverflow post about this, I'm not entirely sure, but I suspect this to be a bug:
https://stackoverflow.com/questions/49811622/pyfilesystem-cant-find-existing-file-in-tar-fs | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_tarfs.py::TestImplicitDirectories::test_getinfo",
"tests/test_tarfs.py::TestImplicitDirectories::test_isdir",
"tests/test_tarfs.py::TestImplicitDirectories::test_listdir"
] | [
"tests/test_tarfs.py::TestWriteReadTarFS::test_unicode_paths",
"tests/test_tarfs.py::TestWriteTarFS::test_appendbytes",
"tests/test_tarfs.py::TestWriteTarFS::test_appendtext",
"tests/test_tarfs.py::TestWriteTarFS::test_basic",
"tests/test_tarfs.py::TestWriteTarFS::test_bin_files",
"tests/test_tarfs.py::TestWriteTarFS::test_close",
"tests/test_tarfs.py::TestWriteTarFS::test_copy",
"tests/test_tarfs.py::TestWriteTarFS::test_copy_dir_mem",
"tests/test_tarfs.py::TestWriteTarFS::test_copy_dir_temp",
"tests/test_tarfs.py::TestWriteTarFS::test_copy_file",
"tests/test_tarfs.py::TestWriteTarFS::test_copy_structure",
"tests/test_tarfs.py::TestWriteTarFS::test_copydir",
"tests/test_tarfs.py::TestWriteTarFS::test_create",
"tests/test_tarfs.py::TestWriteTarFS::test_desc",
"tests/test_tarfs.py::TestWriteTarFS::test_exists",
"tests/test_tarfs.py::TestWriteTarFS::test_files",
"tests/test_tarfs.py::TestWriteTarFS::test_filterdir",
"tests/test_tarfs.py::TestWriteTarFS::test_getbytes",
"tests/test_tarfs.py::TestWriteTarFS::test_getfile",
"tests/test_tarfs.py::TestWriteTarFS::test_getinfo",
"tests/test_tarfs.py::TestWriteTarFS::test_getmeta",
"tests/test_tarfs.py::TestWriteTarFS::test_getsize",
"tests/test_tarfs.py::TestWriteTarFS::test_getsyspath",
"tests/test_tarfs.py::TestWriteTarFS::test_gettext",
"tests/test_tarfs.py::TestWriteTarFS::test_geturl",
"tests/test_tarfs.py::TestWriteTarFS::test_geturl_purpose",
"tests/test_tarfs.py::TestWriteTarFS::test_invalid_chars",
"tests/test_tarfs.py::TestWriteTarFS::test_isdir",
"tests/test_tarfs.py::TestWriteTarFS::test_isempty",
"tests/test_tarfs.py::TestWriteTarFS::test_isfile",
"tests/test_tarfs.py::TestWriteTarFS::test_islink",
"tests/test_tarfs.py::TestWriteTarFS::test_listdir",
"tests/test_tarfs.py::TestWriteTarFS::test_makedir",
"tests/test_tarfs.py::TestWriteTarFS::test_makedirs",
"tests/test_tarfs.py::TestWriteTarFS::test_match",
"tests/test_tarfs.py::TestWriteTarFS::test_move",
"tests/test_tarfs.py::TestWriteTarFS::test_move_dir_mem",
"tests/test_tarfs.py::TestWriteTarFS::test_move_dir_temp",
"tests/test_tarfs.py::TestWriteTarFS::test_move_file_mem",
"tests/test_tarfs.py::TestWriteTarFS::test_move_file_same_fs",
"tests/test_tarfs.py::TestWriteTarFS::test_move_file_temp",
"tests/test_tarfs.py::TestWriteTarFS::test_move_same_fs",
"tests/test_tarfs.py::TestWriteTarFS::test_movedir",
"tests/test_tarfs.py::TestWriteTarFS::test_open",
"tests/test_tarfs.py::TestWriteTarFS::test_open_files",
"tests/test_tarfs.py::TestWriteTarFS::test_openbin",
"tests/test_tarfs.py::TestWriteTarFS::test_openbin_rw",
"tests/test_tarfs.py::TestWriteTarFS::test_opendir",
"tests/test_tarfs.py::TestWriteTarFS::test_remove",
"tests/test_tarfs.py::TestWriteTarFS::test_removedir",
"tests/test_tarfs.py::TestWriteTarFS::test_removetree",
"tests/test_tarfs.py::TestWriteTarFS::test_repeat_dir",
"tests/test_tarfs.py::TestWriteTarFS::test_scandir",
"tests/test_tarfs.py::TestWriteTarFS::test_setbinfile",
"tests/test_tarfs.py::TestWriteTarFS::test_setbytes",
"tests/test_tarfs.py::TestWriteTarFS::test_setfile",
"tests/test_tarfs.py::TestWriteTarFS::test_setinfo",
"tests/test_tarfs.py::TestWriteTarFS::test_settext",
"tests/test_tarfs.py::TestWriteTarFS::test_settimes",
"tests/test_tarfs.py::TestWriteTarFS::test_touch",
"tests/test_tarfs.py::TestWriteTarFS::test_tree",
"tests/test_tarfs.py::TestWriteTarFS::test_validatepath",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_appendbytes",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_appendtext",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_basic",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_bin_files",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_close",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_copy",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_copy_dir_mem",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_copy_dir_temp",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_copy_file",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_copy_structure",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_copydir",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_create",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_desc",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_exists",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_files",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_filterdir",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_getbytes",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_getfile",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_getinfo",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_getmeta",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_getsize",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_getsyspath",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_gettext",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_geturl",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_geturl_purpose",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_invalid_chars",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_isdir",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_isempty",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_isfile",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_islink",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_listdir",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_makedir",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_makedirs",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_match",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_move",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_move_dir_mem",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_move_dir_temp",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_move_file_mem",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_move_file_same_fs",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_move_file_temp",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_move_same_fs",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_movedir",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_open",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_open_files",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_openbin",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_openbin_rw",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_opendir",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_remove",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_removedir",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_removetree",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_repeat_dir",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_scandir",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_setbinfile",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_setbytes",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_setfile",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_setinfo",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_settext",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_settimes",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_touch",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_tree",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_validatepath",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_appendbytes",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_appendtext",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_basic",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_bin_files",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_close",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_copy",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_copy_dir_mem",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_copy_dir_temp",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_copy_file",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_copy_structure",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_copydir",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_create",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_desc",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_exists",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_files",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_filterdir",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_getbytes",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_getfile",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_getinfo",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_getmeta",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_getsize",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_getsyspath",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_gettext",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_geturl",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_geturl_purpose",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_invalid_chars",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_isdir",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_isempty",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_isfile",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_islink",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_listdir",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_makedir",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_makedirs",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_match",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_move",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_move_dir_mem",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_move_dir_temp",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_move_file_mem",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_move_file_same_fs",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_move_file_temp",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_move_same_fs",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_movedir",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_open",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_open_files",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_openbin",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_openbin_rw",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_opendir",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_remove",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_removedir",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_removetree",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_repeat_dir",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_scandir",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_setbinfile",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_setbytes",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_setfile",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_setinfo",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_settext",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_settimes",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_touch",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_tree",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_validatepath",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_appendbytes",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_appendtext",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_basic",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_bin_files",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_close",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_copy",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_copy_dir_mem",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_copy_dir_temp",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_copy_file",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_copy_structure",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_copydir",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_create",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_desc",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_exists",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_files",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_filterdir",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_getbytes",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_getfile",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_getinfo",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_getmeta",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_getsize",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_getsyspath",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_gettext",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_geturl",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_geturl_purpose",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_invalid_chars",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_isdir",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_isempty",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_isfile",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_islink",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_listdir",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_makedir",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_makedirs",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_match",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_move",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_move_dir_mem",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_move_dir_temp",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_move_file_mem",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_move_file_same_fs",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_move_file_temp",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_move_same_fs",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_movedir",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_open",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_open_files",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_openbin",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_openbin_rw",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_opendir",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_remove",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_removedir",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_removetree",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_repeat_dir",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_scandir",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_setbinfile",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_setbytes",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_setfile",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_setinfo",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_settext",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_settimes",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_touch",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_tree",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_validatepath",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_appendbytes",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_appendtext",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_basic",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_bin_files",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_close",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_copy",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_copy_dir_mem",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_copy_dir_temp",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_copy_file",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_copy_structure",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_copydir",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_create",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_desc",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_exists",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_files",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_filterdir",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_getbytes",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_getfile",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_getinfo",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_getmeta",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_getsize",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_getsyspath",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_gettext",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_geturl",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_geturl_purpose",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_invalid_chars",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_isdir",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_isempty",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_isfile",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_islink",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_listdir",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_makedir",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_makedirs",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_match",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_move",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_move_dir_mem",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_move_dir_temp",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_move_file_mem",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_move_file_same_fs",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_move_file_temp",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_move_same_fs",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_movedir",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_open",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_open_files",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_openbin",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_openbin_rw",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_opendir",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_remove",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_removedir",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_removetree",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_repeat_dir",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_scandir",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_setbinfile",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_setbytes",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_setfile",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_setinfo",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_settext",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_settimes",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_touch",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_tree",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_validatepath",
"tests/test_tarfs.py::TestReadTarFS::test_getinfo",
"tests/test_tarfs.py::TestReadTarFS::test_gets",
"tests/test_tarfs.py::TestReadTarFS::test_implied_dir",
"tests/test_tarfs.py::TestReadTarFS::test_listdir",
"tests/test_tarfs.py::TestReadTarFS::test_open",
"tests/test_tarfs.py::TestReadTarFS::test_read_from_filename",
"tests/test_tarfs.py::TestReadTarFS::test_read_from_fileobject",
"tests/test_tarfs.py::TestReadTarFS::test_readonly",
"tests/test_tarfs.py::TestReadTarFS::test_repr",
"tests/test_tarfs.py::TestReadTarFS::test_str",
"tests/test_tarfs.py::TestReadTarFS::test_walk_files",
"tests/test_tarfs.py::TestImplicitDirectories::test_isfile",
"tests/test_tarfs.py::TestReadTarFSMem::test_getinfo",
"tests/test_tarfs.py::TestReadTarFSMem::test_gets",
"tests/test_tarfs.py::TestReadTarFSMem::test_implied_dir",
"tests/test_tarfs.py::TestReadTarFSMem::test_listdir",
"tests/test_tarfs.py::TestReadTarFSMem::test_open",
"tests/test_tarfs.py::TestReadTarFSMem::test_read_from_filename",
"tests/test_tarfs.py::TestReadTarFSMem::test_read_from_fileobject",
"tests/test_tarfs.py::TestReadTarFSMem::test_readonly",
"tests/test_tarfs.py::TestReadTarFSMem::test_repr",
"tests/test_tarfs.py::TestReadTarFSMem::test_str",
"tests/test_tarfs.py::TestReadTarFSMem::test_walk_files",
"tests/test_tarfs.py::TestOpener::test_not_writeable"
] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2018-04-16T12:41:21Z" | mit |
|
PyFilesystem__pyfilesystem2-314 | diff --git a/CHANGELOG.md b/CHANGELOG.md
index aaf125a..b36f9a9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,13 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/)
and this project adheres to [Semantic Versioning](http://semver.org/).
+## [2.4.9] - (Unreleased)
+
+### Changed
+
+- `MemFS` now immediately releases all memory it holds when `close()` is called,
+ rather than when it gets garbage collected. Closes [issue #308](https://github.com/PyFilesystem/pyfilesystem2/issues/308).
+
## [2.4.8] - 2019-06-12
### Changed
diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md
index 5c2a9b5..ef1d3a0 100644
--- a/CONTRIBUTORS.md
+++ b/CONTRIBUTORS.md
@@ -2,6 +2,7 @@
Many thanks to the following developers for contributing to this project:
+- [Diego Argueta](https://github.com/dargueta)
- [Geoff Jukes](https://github.com/geoffjukes)
- [Giampaolo](https://github.com/gpcimino)
- [Martin Larralde](https://github.com/althonos)
diff --git a/fs/base.py b/fs/base.py
index 25f6db4..9e1f858 100644
--- a/fs/base.py
+++ b/fs/base.py
@@ -101,6 +101,9 @@ class FS(object):
# most FS will use default walking algorithms
walker_class = Walker
+ # default to SubFS, used by opendir and should be returned by makedir(s)
+ subfs_class = None
+
def __init__(self):
# type: (...) -> None
"""Create a filesystem. See help(type(self)) for accurate signature.
@@ -1180,7 +1183,7 @@ class FS(object):
factory (callable, optional): A callable that when invoked
with an FS instance and ``path`` will return a new FS object
representing the sub-directory contents. If no ``factory``
- is supplied then `~fs.subfs.SubFS` will be used.
+ is supplied then `~fs.subfs_class` will be used.
Returns:
~fs.subfs.SubFS: A filesystem representing a sub-directory.
@@ -1192,7 +1195,7 @@ class FS(object):
"""
from .subfs import SubFS
- _factory = factory or SubFS
+ _factory = factory or self.subfs_class or SubFS
if not self.getbasic(path).is_dir:
raise errors.DirectoryExpected(path=path)
diff --git a/fs/memoryfs.py b/fs/memoryfs.py
index 2446b0d..dcee49d 100644
--- a/fs/memoryfs.py
+++ b/fs/memoryfs.py
@@ -340,6 +340,11 @@ class MemoryFS(FS):
current_entry = current_entry.get_entry(path_component)
return current_entry
+ def close(self):
+ # type: () -> None
+ self.root = None
+ return super(MemoryFS, self).close()
+
def getinfo(self, path, namespaces=None):
# type: (Text, Optional[Collection[Text]]) -> Info
namespaces = namespaces or ()
| PyFilesystem/pyfilesystem2 | 37b46b4a991a124f4d8e199e111ee21f00c2213b | diff --git a/tests/test_memoryfs.py b/tests/test_memoryfs.py
index 8f8adbd..aaf6e77 100644
--- a/tests/test_memoryfs.py
+++ b/tests/test_memoryfs.py
@@ -1,9 +1,17 @@
from __future__ import unicode_literals
+import posixpath
import unittest
from fs import memoryfs
from fs.test import FSTestCases
+from fs.test import UNICODE_TEXT
+
+try:
+ # Only supported on Python 3.4+
+ import tracemalloc
+except ImportError:
+ tracemalloc = None
class TestMemoryFS(FSTestCases, unittest.TestCase):
@@ -11,3 +19,50 @@ class TestMemoryFS(FSTestCases, unittest.TestCase):
def make_fs(self):
return memoryfs.MemoryFS()
+
+ def _create_many_files(self):
+ for parent_dir in {"/", "/one", "/one/two", "/one/other-two/three"}:
+ self.fs.makedirs(parent_dir, recreate=True)
+ for file_id in range(50):
+ self.fs.writetext(
+ posixpath.join(parent_dir, str(file_id)), UNICODE_TEXT
+ )
+
+ @unittest.skipIf(
+ not tracemalloc, "`tracemalloc` isn't supported on this Python version."
+ )
+ def test_close_mem_free(self):
+ """Ensure all file memory is freed when calling close().
+
+ Prevents regression against issue #308.
+ """
+ trace_filters = [tracemalloc.Filter(True, "*/memoryfs.py")]
+ tracemalloc.start()
+
+ before = tracemalloc.take_snapshot().filter_traces(trace_filters)
+ self._create_many_files()
+ after_create = tracemalloc.take_snapshot().filter_traces(trace_filters)
+
+ self.fs.close()
+ after_close = tracemalloc.take_snapshot().filter_traces(trace_filters)
+ tracemalloc.stop()
+
+ [diff_create] = after_create.compare_to(
+ before, key_type="filename", cumulative=True
+ )
+ self.assertGreater(
+ diff_create.size_diff,
+ 0,
+ "Memory usage didn't increase after creating files; diff is %0.2f KiB."
+ % (diff_create.size_diff / 1024.0),
+ )
+
+ [diff_close] = after_close.compare_to(
+ after_create, key_type="filename", cumulative=True
+ )
+ self.assertLess(
+ diff_close.size_diff,
+ 0,
+ "Memory usage increased after closing the file system; diff is %0.2f KiB."
+ % (diff_close.size_diff / 1024.0),
+ )
diff --git a/tests/test_subfs.py b/tests/test_subfs.py
index 633048f..c360431 100644
--- a/tests/test_subfs.py
+++ b/tests/test_subfs.py
@@ -3,8 +3,11 @@ from __future__ import unicode_literals
import os
import shutil
import tempfile
+import unittest
from fs import osfs
+from fs.subfs import SubFS
+from fs.memoryfs import MemoryFS
from fs.path import relpath
from .test_osfs import TestOSFS
@@ -26,3 +29,44 @@ class TestSubFS(TestOSFS):
def _get_real_path(self, path):
_path = os.path.join(self.temp_dir, "__subdir__", relpath(path))
return _path
+
+
+class CustomSubFS(SubFS):
+ """Just a custom class to change the type"""
+
+ def custom_function(self, custom_path):
+ fs, delegate_path = self.delegate_path(custom_path)
+ fs.custom_function(delegate_path)
+
+
+class CustomSubFS2(SubFS):
+ """Just a custom class to change the type"""
+
+
+class CustomFS(MemoryFS):
+ subfs_class = CustomSubFS
+
+ def __init__(self):
+ super(CustomFS, self).__init__()
+ self.custom_path = None
+
+ def custom_function(self, custom_path):
+ self.custom_path = custom_path
+
+
+class TestCustomSubFS(unittest.TestCase):
+ """Test customization of the SubFS returned from opendir etc"""
+
+ def test_opendir(self):
+ fs = CustomFS()
+ fs.makedir("__subdir__")
+ subfs = fs.opendir("__subdir__")
+ # By default, you get the fs's defined custom SubFS
+ assert isinstance(subfs, CustomSubFS)
+
+ subfs.custom_function("filename")
+ assert fs.custom_path == "/__subdir__/filename"
+
+ # Providing the factory explicitly still works
+ subfs = fs.opendir("__subdir__", factory=CustomSubFS2)
+ assert isinstance(subfs, CustomSubFS2)
| Expose SubFS factory
There are some custom methods (i.e. not overrides) on GoogleFS and OneDriveFS to expose specific features of those filesystems.
My problem is that makedir(s) returns a SubFS which then doesn't support those custom methods so you can't use it transparently (e.g. in the tests)
I see that opendir has a factory parameter so that you can customize the return type, but that's missing from the other SubFS-returning functions.
I'd suggest that we could add the same factory parameter to makedir(s), except that it seems to me that it shouldn't be specified by the user but by the filesystem developer - maybe in the _meta dictionary?
I suppose that another way to do it would be to use the custom factory if the user specifies one but if factory is None, use the GoogleFS-specified one.
What do you think? | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_subfs.py::TestCustomSubFS::test_opendir"
] | [
"tests/test_subfs.py::TestOSFS::test_appendbytes",
"tests/test_subfs.py::TestOSFS::test_unicode_paths",
"tests/test_subfs.py::TestOSFS::test_root_dir",
"tests/test_subfs.py::TestOSFS::test_openbin_rw",
"tests/test_subfs.py::TestOSFS::test_openbin_exclusive",
"tests/test_subfs.py::TestOSFS::test_copydir",
"tests/test_subfs.py::TestOSFS::test_download_4",
"tests/test_subfs.py::TestOSFS::test_geturl",
"tests/test_subfs.py::TestOSFS::test_openbin",
"tests/test_subfs.py::TestOSFS::test_symlinks",
"tests/test_subfs.py::TestOSFS::test_setinfo",
"tests/test_subfs.py::TestOSFS::test_getsyspath",
"tests/test_subfs.py::TestOSFS::test_match",
"tests/test_subfs.py::TestOSFS::test_getinfo",
"tests/test_subfs.py::TestOSFS::test_invalid_chars",
"tests/test_subfs.py::TestOSFS::test_basic",
"tests/test_subfs.py::TestOSFS::test_not_exists",
"tests/test_subfs.py::TestOSFS::test_readbytes",
"tests/test_subfs.py::TestOSFS::test_isfile",
"tests/test_subfs.py::TestOSFS::test_isempty",
"tests/test_subfs.py::TestOSFS::test_writebytes",
"tests/test_subfs.py::TestOSFS::test_appendtext",
"tests/test_subfs.py::TestOSFS::test_listdir",
"tests/test_subfs.py::TestOSFS::test_writefile",
"tests/test_subfs.py::TestOSFS::test_move_dir_mem",
"tests/test_subfs.py::TestOSFS::test_move_file_temp",
"tests/test_subfs.py::TestOSFS::test_upload_chunk_size",
"tests/test_subfs.py::TestOSFS::test_exists",
"tests/test_subfs.py::TestOSFS::test_opendir",
"tests/test_subfs.py::TestOSFS::test_tree",
"tests/test_subfs.py::TestOSFS::test_upload_4",
"tests/test_subfs.py::TestOSFS::test_validatepath",
"tests/test_subfs.py::TestOSFS::test_readtext",
"tests/test_subfs.py::TestOSFS::test_upload_2",
"tests/test_subfs.py::TestOSFS::test_copy_dir_mem",
"tests/test_subfs.py::TestOSFS::test_isdir",
"tests/test_subfs.py::TestOSFS::test_removetree",
"tests/test_subfs.py::TestOSFS::test_filterdir",
"tests/test_subfs.py::TestOSFS::test_copy_file",
"tests/test_subfs.py::TestOSFS::test_move_same_fs",
"tests/test_subfs.py::TestOSFS::test_upload",
"tests/test_subfs.py::TestOSFS::test_geturl_purpose",
"tests/test_subfs.py::TestOSFS::test_movedir",
"tests/test_subfs.py::TestOSFS::test_copy",
"tests/test_subfs.py::TestOSFS::test_settimes",
"tests/test_subfs.py::TestOSFS::test_makedirs",
"tests/test_subfs.py::TestOSFS::test_open",
"tests/test_subfs.py::TestOSFS::test_download",
"tests/test_subfs.py::TestOSFS::test_removedir",
"tests/test_subfs.py::TestOSFS::test_hash",
"tests/test_subfs.py::TestOSFS::test_copy_structure",
"tests/test_subfs.py::TestOSFS::test_files",
"tests/test_subfs.py::TestOSFS::test_remove",
"tests/test_subfs.py::TestOSFS::test_open_files",
"tests/test_subfs.py::TestOSFS::test_move_dir_temp",
"tests/test_subfs.py::TestOSFS::test_close",
"tests/test_subfs.py::TestOSFS::test_getsize",
"tests/test_subfs.py::TestOSFS::test_download_2",
"tests/test_subfs.py::TestOSFS::test_open_exclusive",
"tests/test_subfs.py::TestOSFS::test_desc",
"tests/test_subfs.py::TestOSFS::test_upload_0",
"tests/test_subfs.py::TestOSFS::test_move_file_mem",
"tests/test_subfs.py::TestOSFS::test_glob",
"tests/test_subfs.py::TestOSFS::test_writetext",
"tests/test_subfs.py::TestOSFS::test_expand_vars",
"tests/test_subfs.py::TestOSFS::test_repeat_dir",
"tests/test_subfs.py::TestOSFS::test_touch",
"tests/test_subfs.py::TestOSFS::test_copy_dir_temp",
"tests/test_subfs.py::TestOSFS::test_islink",
"tests/test_subfs.py::TestOSFS::test_scandir",
"tests/test_subfs.py::TestOSFS::test_upload_1",
"tests/test_subfs.py::TestOSFS::test_create",
"tests/test_subfs.py::TestOSFS::test_download_0",
"tests/test_subfs.py::TestOSFS::test_getmeta",
"tests/test_subfs.py::TestOSFS::test_bin_files",
"tests/test_subfs.py::TestOSFS::test_makedir",
"tests/test_subfs.py::TestOSFS::test_move",
"tests/test_subfs.py::TestOSFS::test_download_chunk_size",
"tests/test_subfs.py::TestOSFS::test_move_file_same_fs",
"tests/test_subfs.py::TestOSFS::test_case_sensitive",
"tests/test_subfs.py::TestOSFS::test_download_1",
"tests/test_subfs.py::TestSubFS::test_copydir",
"tests/test_subfs.py::TestSubFS::test_move_same_fs",
"tests/test_subfs.py::TestSubFS::test_writebytes",
"tests/test_subfs.py::TestSubFS::test_getmeta",
"tests/test_subfs.py::TestSubFS::test_scandir",
"tests/test_subfs.py::TestSubFS::test_makedirs",
"tests/test_subfs.py::TestSubFS::test_openbin_exclusive",
"tests/test_subfs.py::TestSubFS::test_match",
"tests/test_subfs.py::TestSubFS::test_move_dir_temp",
"tests/test_subfs.py::TestSubFS::test_appendtext",
"tests/test_subfs.py::TestSubFS::test_desc",
"tests/test_subfs.py::TestSubFS::test_download_2",
"tests/test_subfs.py::TestSubFS::test_root_dir",
"tests/test_subfs.py::TestSubFS::test_exists",
"tests/test_subfs.py::TestSubFS::test_move_file_temp",
"tests/test_subfs.py::TestSubFS::test_geturl",
"tests/test_subfs.py::TestSubFS::test_copy_dir_mem",
"tests/test_subfs.py::TestSubFS::test_isdir",
"tests/test_subfs.py::TestSubFS::test_removetree",
"tests/test_subfs.py::TestSubFS::test_files",
"tests/test_subfs.py::TestSubFS::test_move",
"tests/test_subfs.py::TestSubFS::test_filterdir",
"tests/test_subfs.py::TestSubFS::test_download_4",
"tests/test_subfs.py::TestSubFS::test_validatepath",
"tests/test_subfs.py::TestSubFS::test_movedir",
"tests/test_subfs.py::TestSubFS::test_isfile",
"tests/test_subfs.py::TestSubFS::test_readbytes",
"tests/test_subfs.py::TestSubFS::test_bin_files",
"tests/test_subfs.py::TestSubFS::test_writefile",
"tests/test_subfs.py::TestSubFS::test_open",
"tests/test_subfs.py::TestSubFS::test_move_file_same_fs",
"tests/test_subfs.py::TestSubFS::test_openbin_rw",
"tests/test_subfs.py::TestSubFS::test_basic",
"tests/test_subfs.py::TestSubFS::test_readtext",
"tests/test_subfs.py::TestSubFS::test_copy",
"tests/test_subfs.py::TestSubFS::test_upload_2",
"tests/test_subfs.py::TestSubFS::test_unicode_paths",
"tests/test_subfs.py::TestSubFS::test_listdir",
"tests/test_subfs.py::TestSubFS::test_not_exists",
"tests/test_subfs.py::TestSubFS::test_remove",
"tests/test_subfs.py::TestSubFS::test_geturl_purpose",
"tests/test_subfs.py::TestSubFS::test_tree",
"tests/test_subfs.py::TestSubFS::test_download",
"tests/test_subfs.py::TestSubFS::test_copy_structure",
"tests/test_subfs.py::TestSubFS::test_upload_0",
"tests/test_subfs.py::TestSubFS::test_removedir",
"tests/test_subfs.py::TestSubFS::test_getsize",
"tests/test_subfs.py::TestSubFS::test_repeat_dir",
"tests/test_subfs.py::TestSubFS::test_upload_chunk_size",
"tests/test_subfs.py::TestSubFS::test_appendbytes",
"tests/test_subfs.py::TestSubFS::test_touch",
"tests/test_subfs.py::TestSubFS::test_copy_file",
"tests/test_subfs.py::TestSubFS::test_case_sensitive",
"tests/test_subfs.py::TestSubFS::test_download_chunk_size",
"tests/test_subfs.py::TestSubFS::test_move_dir_mem",
"tests/test_subfs.py::TestSubFS::test_symlinks",
"tests/test_subfs.py::TestSubFS::test_open_exclusive",
"tests/test_subfs.py::TestSubFS::test_move_file_mem",
"tests/test_subfs.py::TestSubFS::test_upload_4",
"tests/test_subfs.py::TestSubFS::test_makedir",
"tests/test_subfs.py::TestSubFS::test_create",
"tests/test_subfs.py::TestSubFS::test_open_files",
"tests/test_subfs.py::TestSubFS::test_download_1",
"tests/test_subfs.py::TestSubFS::test_download_0",
"tests/test_subfs.py::TestSubFS::test_settimes",
"tests/test_subfs.py::TestSubFS::test_setinfo",
"tests/test_subfs.py::TestSubFS::test_upload",
"tests/test_subfs.py::TestSubFS::test_upload_1",
"tests/test_subfs.py::TestSubFS::test_openbin",
"tests/test_subfs.py::TestSubFS::test_close",
"tests/test_subfs.py::TestSubFS::test_getinfo",
"tests/test_subfs.py::TestSubFS::test_isempty",
"tests/test_subfs.py::TestSubFS::test_writetext",
"tests/test_subfs.py::TestSubFS::test_hash",
"tests/test_subfs.py::TestSubFS::test_getsyspath",
"tests/test_subfs.py::TestSubFS::test_expand_vars",
"tests/test_subfs.py::TestSubFS::test_invalid_chars",
"tests/test_subfs.py::TestSubFS::test_copy_dir_temp",
"tests/test_subfs.py::TestSubFS::test_glob",
"tests/test_subfs.py::TestSubFS::test_opendir",
"tests/test_subfs.py::TestSubFS::test_islink",
"tests/test_memoryfs.py::TestMemoryFS::test_movedir",
"tests/test_memoryfs.py::TestMemoryFS::test_openbin",
"tests/test_memoryfs.py::TestMemoryFS::test_open",
"tests/test_memoryfs.py::TestMemoryFS::test_create",
"tests/test_memoryfs.py::TestMemoryFS::test_validatepath",
"tests/test_memoryfs.py::TestMemoryFS::test_unicode_path",
"tests/test_memoryfs.py::TestMemoryFS::test_upload_2",
"tests/test_memoryfs.py::TestMemoryFS::test_download_chunk_size",
"tests/test_memoryfs.py::TestMemoryFS::test_getsyspath",
"tests/test_memoryfs.py::TestMemoryFS::test_writefile",
"tests/test_memoryfs.py::TestMemoryFS::test_desc",
"tests/test_memoryfs.py::TestMemoryFS::test_settimes",
"tests/test_memoryfs.py::TestMemoryFS::test_upload_4",
"tests/test_memoryfs.py::TestMemoryFS::test_move_dir_temp",
"tests/test_memoryfs.py::TestMemoryFS::test_open_files",
"tests/test_memoryfs.py::TestMemoryFS::test_root_dir",
"tests/test_memoryfs.py::TestMemoryFS::test_upload_chunk_size",
"tests/test_memoryfs.py::TestMemoryFS::test_setinfo",
"tests/test_memoryfs.py::TestMemoryFS::test_copy_file",
"tests/test_memoryfs.py::TestMemoryFS::test_readtext",
"tests/test_memoryfs.py::TestMemoryFS::test_appendbytes",
"tests/test_memoryfs.py::TestMemoryFS::test_download",
"tests/test_memoryfs.py::TestMemoryFS::test_move_same_fs",
"tests/test_memoryfs.py::TestMemoryFS::test_tree",
"tests/test_memoryfs.py::TestMemoryFS::test_openbin_exclusive",
"tests/test_memoryfs.py::TestMemoryFS::test_files",
"tests/test_memoryfs.py::TestMemoryFS::test_move_file_temp",
"tests/test_memoryfs.py::TestMemoryFS::test_copydir",
"tests/test_memoryfs.py::TestMemoryFS::test_makedir",
"tests/test_memoryfs.py::TestMemoryFS::test_makedirs",
"tests/test_memoryfs.py::TestMemoryFS::test_basic",
"tests/test_memoryfs.py::TestMemoryFS::test_move_dir_mem",
"tests/test_memoryfs.py::TestMemoryFS::test_listdir",
"tests/test_memoryfs.py::TestMemoryFS::test_upload",
"tests/test_memoryfs.py::TestMemoryFS::test_match",
"tests/test_memoryfs.py::TestMemoryFS::test_download_2",
"tests/test_memoryfs.py::TestMemoryFS::test_geturl",
"tests/test_memoryfs.py::TestMemoryFS::test_download_4",
"tests/test_memoryfs.py::TestMemoryFS::test_download_0",
"tests/test_memoryfs.py::TestMemoryFS::test_move",
"tests/test_memoryfs.py::TestMemoryFS::test_remove",
"tests/test_memoryfs.py::TestMemoryFS::test_scandir",
"tests/test_memoryfs.py::TestMemoryFS::test_filterdir",
"tests/test_memoryfs.py::TestMemoryFS::test_exists",
"tests/test_memoryfs.py::TestMemoryFS::test_copy_structure",
"tests/test_memoryfs.py::TestMemoryFS::test_removetree",
"tests/test_memoryfs.py::TestMemoryFS::test_copy_dir_temp",
"tests/test_memoryfs.py::TestMemoryFS::test_appendtext",
"tests/test_memoryfs.py::TestMemoryFS::test_removedir",
"tests/test_memoryfs.py::TestMemoryFS::test_getsize",
"tests/test_memoryfs.py::TestMemoryFS::test_getmeta",
"tests/test_memoryfs.py::TestMemoryFS::test_isfile",
"tests/test_memoryfs.py::TestMemoryFS::test_glob",
"tests/test_memoryfs.py::TestMemoryFS::test_bin_files",
"tests/test_memoryfs.py::TestMemoryFS::test_readbytes",
"tests/test_memoryfs.py::TestMemoryFS::test_touch",
"tests/test_memoryfs.py::TestMemoryFS::test_close_mem_free",
"tests/test_memoryfs.py::TestMemoryFS::test_isempty",
"tests/test_memoryfs.py::TestMemoryFS::test_case_sensitive",
"tests/test_memoryfs.py::TestMemoryFS::test_move_file_mem",
"tests/test_memoryfs.py::TestMemoryFS::test_islink",
"tests/test_memoryfs.py::TestMemoryFS::test_opendir",
"tests/test_memoryfs.py::TestMemoryFS::test_hash",
"tests/test_memoryfs.py::TestMemoryFS::test_close",
"tests/test_memoryfs.py::TestMemoryFS::test_getinfo",
"tests/test_memoryfs.py::TestMemoryFS::test_openbin_rw",
"tests/test_memoryfs.py::TestMemoryFS::test_copy",
"tests/test_memoryfs.py::TestMemoryFS::test_download_1",
"tests/test_memoryfs.py::TestMemoryFS::test_repeat_dir",
"tests/test_memoryfs.py::TestMemoryFS::test_open_exclusive",
"tests/test_memoryfs.py::TestMemoryFS::test_writetext",
"tests/test_memoryfs.py::TestMemoryFS::test_move_file_same_fs",
"tests/test_memoryfs.py::TestMemoryFS::test_upload_0",
"tests/test_memoryfs.py::TestMemoryFS::test_copy_dir_mem",
"tests/test_memoryfs.py::TestMemoryFS::test_upload_1",
"tests/test_memoryfs.py::TestMemoryFS::test_isdir",
"tests/test_memoryfs.py::TestMemoryFS::test_writebytes",
"tests/test_memoryfs.py::TestMemoryFS::test_geturl_purpose",
"tests/test_memoryfs.py::TestMemoryFS::test_invalid_chars"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2019-07-26T05:05:22Z" | mit |
|
PyFilesystem__pyfilesystem2-330 | diff --git a/CHANGELOG.md b/CHANGELOG.md
index aa0975e..20d7568 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,11 +7,18 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
## [2.4.11] - Unreleased
+### Added
+
+- Added geturl for TarFS and ZipFS for 'fs' purpose. NoURL for 'download' purpose.
+- Added helpful root path in CreateFailed exception [#340](https://github.com/PyFilesystem/pyfilesystem2/issues/340)
+
### Fixed
- Fixed tests leaving tmp files
- Fixed typing issues
- Fixed link namespace returning bytes
+- Fixed broken FSURL in windows [#329](https://github.com/PyFilesystem/pyfilesystem2/issues/329)
+- Fixed hidden exception at fs.close() when opening an absent zip/tar file URL [#333](https://github.com/PyFilesystem/pyfilesystem2/issues/333)
- Fixed abstract class import from `collections` which would break on Python 3.8
- Fixed incorrect imports of `mock` on Python 3
- Removed some unused imports and unused `requirements.txt` file
@@ -19,8 +26,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
### Changed
-Entire test suite has been migrated to [pytest](https://docs.pytest.org/en/latest/).
-Closes [#327](https://github.com/PyFilesystem/pyfilesystem2/issues/327).
+- Entire test suite has been migrated to [pytest](https://docs.pytest.org/en/latest/). Closes [#327](https://github.com/PyFilesystem/pyfilesystem2/issues/327).
## [2.4.10] - 2019-07-29
diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md
index ef1d3a0..cb55cf7 100644
--- a/CONTRIBUTORS.md
+++ b/CONTRIBUTORS.md
@@ -2,6 +2,7 @@
Many thanks to the following developers for contributing to this project:
+- [C. W.](https://github.com/chfw)
- [Diego Argueta](https://github.com/dargueta)
- [Geoff Jukes](https://github.com/geoffjukes)
- [Giampaolo](https://github.com/gpcimino)
diff --git a/fs/_url_tools.py b/fs/_url_tools.py
new file mode 100644
index 0000000..4c6fd73
--- /dev/null
+++ b/fs/_url_tools.py
@@ -0,0 +1,49 @@
+import re
+import six
+import platform
+
+if False: # typing.TYPE_CHECKING
+ from typing import Text, Union, BinaryIO
+
+_WINDOWS_PLATFORM = platform.system() == "Windows"
+
+
+def url_quote(path_snippet):
+ # type: (Text) -> Text
+ """
+ On Windows, it will separate drive letter and quote windows
+ path alone. No magic on Unix-alie path, just pythonic
+ `pathname2url`
+
+ Arguments:
+ path_snippet: a file path, relative or absolute.
+ """
+ if _WINDOWS_PLATFORM and _has_drive_letter(path_snippet):
+ drive_letter, path = path_snippet.split(":", 1)
+ if six.PY2:
+ path = path.encode("utf-8")
+ path = six.moves.urllib.request.pathname2url(path)
+ path_snippet = "{}:{}".format(drive_letter, path)
+ else:
+ if six.PY2:
+ path_snippet = path_snippet.encode("utf-8")
+ path_snippet = six.moves.urllib.request.pathname2url(path_snippet)
+ return path_snippet
+
+
+def _has_drive_letter(path_snippet):
+ # type: (Text) -> bool
+ """
+ The following path will get True
+ D:/Data
+ C:\\My Dcouments\\ test
+
+ And will get False
+
+ /tmp/abc:test
+
+ Arguments:
+ path_snippet: a file path, relative or absolute.
+ """
+ windows_drive_pattern = ".:[/\\\\].*$"
+ return re.match(windows_drive_pattern, path_snippet) is not None
diff --git a/fs/base.py b/fs/base.py
index 18f3ccd..fae7ce1 100644
--- a/fs/base.py
+++ b/fs/base.py
@@ -1633,7 +1633,7 @@ class FS(object):
fs.errors.UnsupportedHash: If the requested hash is not supported.
"""
- _path = self.validatepath(path)
+ self.validatepath(path)
try:
hash_object = hashlib.new(name)
except ValueError:
diff --git a/fs/osfs.py b/fs/osfs.py
index 10f8713..8782551 100644
--- a/fs/osfs.py
+++ b/fs/osfs.py
@@ -39,7 +39,6 @@ except ImportError:
sendfile = None # type: ignore # pragma: no cover
from . import errors
-from .errors import FileExists
from .base import FS
from .enums import ResourceType
from ._fscompat import fsencode, fsdecode, fspath
@@ -49,6 +48,7 @@ from .permissions import Permissions
from .error_tools import convert_os_errors
from .mode import Mode, validate_open_mode
from .errors import FileExpected, NoURL
+from ._url_tools import url_quote
if False: # typing.TYPE_CHECKING
from typing import (
@@ -137,7 +137,8 @@ class OSFS(FS):
)
else:
if not os.path.isdir(_root_path):
- raise errors.CreateFailed("root path does not exist")
+ message = "root path '{}' does not exist".format(_root_path)
+ raise errors.CreateFailed(message)
_meta = self._meta = {
"network": False,
@@ -526,7 +527,6 @@ class OSFS(FS):
namespaces = namespaces or ()
_path = self.validatepath(path)
sys_path = self.getsyspath(_path)
- _sys_path = fsencode(sys_path)
with convert_os_errors("scandir", path, directory=True):
for entry_name in os.listdir(sys_path):
_entry_name = fsdecode(entry_name)
@@ -584,9 +584,14 @@ class OSFS(FS):
def geturl(self, path, purpose="download"):
# type: (Text, Text) -> Text
- if purpose != "download":
+ sys_path = self.getsyspath(path)
+ if purpose == "download":
+ return "file://" + sys_path
+ elif purpose == "fs":
+ url_path = url_quote(sys_path)
+ return "osfs://" + url_path
+ else:
raise NoURL(path, purpose)
- return "file://" + self.getsyspath(path)
def gettype(self, path):
# type: (Text) -> ResourceType
diff --git a/fs/tarfs.py b/fs/tarfs.py
index ce2109c..250291a 100644
--- a/fs/tarfs.py
+++ b/fs/tarfs.py
@@ -4,7 +4,6 @@
from __future__ import print_function
from __future__ import unicode_literals
-import copy
import os
import tarfile
import typing
@@ -17,14 +16,14 @@ from . import errors
from .base import FS
from .compress import write_tar
from .enums import ResourceType
-from .errors import IllegalBackReference
+from .errors import IllegalBackReference, NoURL
from .info import Info
from .iotools import RawWrapper
from .opener import open_fs
-from .path import dirname, relpath, basename, isbase, normpath, parts, frombase
+from .path import relpath, basename, isbase, normpath, parts, frombase
from .wrapfs import WrapFS
from .permissions import Permissions
-
+from ._url_tools import url_quote
if False: # typing.TYPE_CHECKING
from tarfile import TarInfo
@@ -461,16 +460,25 @@ class ReadTarFS(FS):
def close(self):
# type: () -> None
super(ReadTarFS, self).close()
- self._tar.close()
+ if hasattr(self, "_tar"):
+ self._tar.close()
def isclosed(self):
# type: () -> bool
return self._tar.closed # type: ignore
+ def geturl(self, path, purpose="download"):
+ # type: (Text, Text) -> Text
+ if purpose == "fs" and isinstance(self._file, six.string_types):
+ quoted_file = url_quote(self._file)
+ quoted_path = url_quote(path)
+ return "tar://{}!/{}".format(quoted_file, quoted_path)
+ else:
+ raise NoURL(path, purpose)
+
if __name__ == "__main__": # pragma: no cover
from fs.tree import render
- from fs.opener import open_fs
with TarFS("tests.tar") as tar_fs:
print(tar_fs.listdir("/"))
diff --git a/fs/zipfs.py b/fs/zipfs.py
index 1fdf463..c347731 100644
--- a/fs/zipfs.py
+++ b/fs/zipfs.py
@@ -22,6 +22,7 @@ from .opener import open_fs
from .path import dirname, forcedir, normpath, relpath
from .time import datetime_to_epoch
from .wrapfs import WrapFS
+from ._url_tools import url_quote
if False: # typing.TYPE_CHECKING
from typing import (
@@ -434,7 +435,8 @@ class ReadZipFS(FS):
def close(self):
# type: () -> None
super(ReadZipFS, self).close()
- self._zip.close()
+ if hasattr(self, "_zip"):
+ self._zip.close()
def readbytes(self, path):
# type: (Text) -> bytes
@@ -444,3 +446,12 @@ class ReadZipFS(FS):
zip_name = self._path_to_zip_name(path)
zip_bytes = self._zip.read(zip_name)
return zip_bytes
+
+ def geturl(self, path, purpose="download"):
+ # type: (Text, Text) -> Text
+ if purpose == "fs" and isinstance(self._file, six.string_types):
+ quoted_file = url_quote(self._file)
+ quoted_path = url_quote(path)
+ return "zip://{}!/{}".format(quoted_file, quoted_path)
+ else:
+ raise errors.NoURL(path, purpose)
| PyFilesystem/pyfilesystem2 | 667d47753cbb282ac4c46d566324a895fc787e63 | diff --git a/tests/test_osfs.py b/tests/test_osfs.py
index 3286b87..bd125c1 100644
--- a/tests/test_osfs.py
+++ b/tests/test_osfs.py
@@ -7,13 +7,11 @@ import os
import shutil
import tempfile
import unittest
-
import pytest
-from fs import osfs
-from fs.path import relpath
+from fs import osfs, open_fs
+from fs.path import relpath, dirname
from fs import errors
-
from fs.test import FSTestCases
from six import text_type
@@ -77,7 +75,7 @@ class TestOSFS(FSTestCases, unittest.TestCase):
def test_not_exists(self):
with self.assertRaises(errors.CreateFailed):
- fs = osfs.OSFS("/does/not/exists/")
+ osfs.OSFS("/does/not/exists/")
def test_expand_vars(self):
self.fs.makedir("TYRIONLANISTER")
@@ -162,3 +160,40 @@ class TestOSFS(FSTestCases, unittest.TestCase):
with self.assertRaises(errors.InvalidCharsInPath):
with self.fs.open("13 – Marked Register.pdf", "wb") as fh:
fh.write(b"foo")
+
+ def test_consume_geturl(self):
+ self.fs.create("foo")
+ try:
+ url = self.fs.geturl("foo", purpose="fs")
+ except errors.NoURL:
+ self.assertFalse(self.fs.hasurl("foo"))
+ else:
+ self.assertTrue(self.fs.hasurl("foo"))
+
+ # Should not throw an error
+ base_dir = dirname(url)
+ open_fs(base_dir)
+
+ def test_complex_geturl(self):
+ self.fs.makedirs("foo/bar ha")
+ test_fixtures = [
+ # test file, expected url path
+ ["foo", "foo"],
+ ["foo-bar", "foo-bar"],
+ ["foo_bar", "foo_bar"],
+ ["foo/bar ha/barz", "foo/bar%20ha/barz"],
+ ["example b.txt", "example%20b.txt"],
+ ["exampleㄓ.txt", "example%E3%84%93.txt"],
+ ]
+ file_uri_prefix = "osfs://"
+ for test_file, relative_url_path in test_fixtures:
+ self.fs.create(test_file)
+ expected = file_uri_prefix + self.fs.getsyspath(relative_url_path).replace(
+ "\\", "/"
+ )
+ actual = self.fs.geturl(test_file, purpose="fs")
+
+ self.assertEqual(actual, expected)
+
+ def test_geturl_return_no_url(self):
+ self.assertRaises(errors.NoURL, self.fs.geturl, "test/path", "upload")
diff --git a/tests/test_tarfs.py b/tests/test_tarfs.py
index dd8ad47..c3570bd 100644
--- a/tests/test_tarfs.py
+++ b/tests/test_tarfs.py
@@ -7,7 +7,6 @@ import six
import tarfile
import tempfile
import unittest
-
import pytest
from fs import tarfs
@@ -15,6 +14,7 @@ from fs.enums import ResourceType
from fs.compress import write_tar
from fs.opener import open_fs
from fs.opener.errors import NotWriteable
+from fs.errors import NoURL
from fs.test import FSTestCases
from .test_archives import ArchiveTestCases
@@ -93,15 +93,6 @@ class TestWriteGZippedTarFS(FSTestCases, unittest.TestCase):
os.remove(fs._tar_file)
del fs._tar_file
- def assert_is_bzip(self):
- try:
- tarfile.open(fs._tar_file, "r:gz")
- except tarfile.ReadError:
- self.fail("{} is not a valid gz archive".format(fs._tar_file))
- for other_comps in ["xz", "bz2", ""]:
- with self.assertRaises(tarfile.ReadError):
- tarfile.open(fs._tar_file, "r:{}".format(other_comps))
-
@pytest.mark.skipif(six.PY2, reason="Python2 does not support LZMA")
class TestWriteXZippedTarFS(FSTestCases, unittest.TestCase):
@@ -181,11 +172,44 @@ class TestReadTarFS(ArchiveTestCases, unittest.TestCase):
except:
self.fail("Couldn't open tarfs from filename")
+ def test_read_non_existent_file(self):
+ fs = tarfs.TarFS(open(self._temp_path, "rb"))
+ # it has been very difficult to catch exception in __del__()
+ del fs._tar
+ try:
+ fs.close()
+ except AttributeError:
+ self.fail("Could not close tar fs properly")
+ except Exception:
+ self.fail("Strange exception in closing fs")
+
def test_getinfo(self):
super(TestReadTarFS, self).test_getinfo()
top = self.fs.getinfo("top.txt", ["tar"])
self.assertTrue(top.get("tar", "is_file"))
+ def test_geturl_for_fs(self):
+ test_fixtures = [
+ # test_file, expected
+ ["foo/bar/egg/foofoo", "foo/bar/egg/foofoo"],
+ ["foo/bar egg/foo foo", "foo/bar%20egg/foo%20foo"],
+ ]
+ tar_file_path = self._temp_path.replace("\\", "/")
+ for test_file, expected_file in test_fixtures:
+ expected = "tar://{tar_file_path}!/{file_inside_tar}".format(
+ tar_file_path=tar_file_path, file_inside_tar=expected_file
+ )
+ self.assertEqual(self.fs.geturl(test_file, purpose="fs"), expected)
+
+ def test_geturl_for_fs_but_file_is_binaryio(self):
+ self.fs._file = six.BytesIO()
+ self.assertRaises(NoURL, self.fs.geturl, "test", "fs")
+
+ def test_geturl_for_download(self):
+ test_file = "foo/bar/egg/foofoo"
+ with self.assertRaises(NoURL):
+ self.fs.geturl(test_file)
+
class TestBrokenPaths(unittest.TestCase):
@classmethod
diff --git a/tests/test_url_tools.py b/tests/test_url_tools.py
new file mode 100644
index 0000000..5b5d4a1
--- /dev/null
+++ b/tests/test_url_tools.py
@@ -0,0 +1,39 @@
+# coding: utf-8
+"""Test url tools. """
+from __future__ import unicode_literals
+
+import platform
+import unittest
+
+from fs._url_tools import url_quote
+
+
+class TestBase(unittest.TestCase):
+ def test_quote(self):
+ test_fixtures = [
+ # test_snippet, expected
+ ["foo/bar/egg/foofoo", "foo/bar/egg/foofoo"],
+ ["foo/bar ha/barz", "foo/bar%20ha/barz"],
+ ["example b.txt", "example%20b.txt"],
+ ["exampleㄓ.txt", "example%E3%84%93.txt"],
+ ]
+ if platform.system() == "Windows":
+ test_fixtures.extend(
+ [
+ ["C:\\My Documents\\test.txt", "C:/My%20Documents/test.txt"],
+ ["C:/My Documents/test.txt", "C:/My%20Documents/test.txt"],
+ # on Windows '\' is regarded as path separator
+ ["test/forward\\slash", "test/forward/slash"],
+ ]
+ )
+ else:
+ test_fixtures.extend(
+ [
+ # colon:tmp is bad path under Windows
+ ["test/colon:tmp", "test/colon%3Atmp"],
+ # Unix treat \ as %5C
+ ["test/forward\\slash", "test/forward%5Cslash"],
+ ]
+ )
+ for test_snippet, expected in test_fixtures:
+ self.assertEqual(url_quote(test_snippet), expected)
diff --git a/tests/test_zipfs.py b/tests/test_zipfs.py
index 421d80d..9b2e82e 100644
--- a/tests/test_zipfs.py
+++ b/tests/test_zipfs.py
@@ -13,8 +13,9 @@ from fs import zipfs
from fs.compress import write_zip
from fs.opener import open_fs
from fs.opener.errors import NotWriteable
+from fs.errors import NoURL
from fs.test import FSTestCases
-from fs.enums import Seek, ResourceType
+from fs.enums import Seek
from .test_archives import ArchiveTestCases
@@ -168,6 +169,33 @@ class TestReadZipFS(ArchiveTestCases, unittest.TestCase):
self.assertEqual(f.seek(-5, Seek.end), 7)
self.assertEqual(f.read(), b"World")
+ def test_geturl_for_fs(self):
+ test_file = "foo/bar/egg/foofoo"
+ expected = "zip://{zip_file_path}!/{file_inside_zip}".format(
+ zip_file_path=self._temp_path.replace("\\", "/"), file_inside_zip=test_file
+ )
+ self.assertEqual(self.fs.geturl(test_file, purpose="fs"), expected)
+
+ def test_geturl_for_fs_but_file_is_binaryio(self):
+ self.fs._file = six.BytesIO()
+ self.assertRaises(NoURL, self.fs.geturl, "test", "fs")
+
+ def test_geturl_for_download(self):
+ test_file = "foo/bar/egg/foofoo"
+ with self.assertRaises(NoURL):
+ self.fs.geturl(test_file)
+
+ def test_read_non_existent_file(self):
+ fs = zipfs.ZipFS(open(self._temp_path, "rb"))
+ # it has been very difficult to catch exception in __del__()
+ del fs._zip
+ try:
+ fs.close()
+ except AttributeError:
+ self.fail("Could not close tar fs properly")
+ except Exception:
+ self.fail("Strange exception in closing fs")
+
class TestReadZipFSMem(TestReadZipFS):
def make_source_fs(self):
@@ -184,8 +212,8 @@ class TestDirsZipFS(unittest.TestCase):
z.writestr("foo/bar/baz/egg", b"hello")
with zipfs.ReadZipFS(path) as zip_fs:
foo = zip_fs.getinfo("foo", ["details"])
- bar = zip_fs.getinfo("foo/bar")
- baz = zip_fs.getinfo("foo/bar/baz")
+ self.assertEqual(zip_fs.getinfo("foo/bar").name, "bar")
+ self.assertEqual(zip_fs.getinfo("foo/bar/baz").name, "baz")
self.assertTrue(foo.is_dir)
self.assertTrue(zip_fs.isfile("foo/bar/baz/egg"))
finally:
| Bug: return value of OSFS.geturl cannot be consumed by FS on Windows
`geturl()` will return `file://D:\a\1\s\tests\fixtures\template`(the dog food) on windows, which can be not used(eaten) by osfs itself.
an PR is coming to fix it. I am logging this issue here. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_osfs.py::TestOSFS::test_appendbytes",
"tests/test_osfs.py::TestOSFS::test_appendtext",
"tests/test_osfs.py::TestOSFS::test_basic",
"tests/test_osfs.py::TestOSFS::test_bin_files",
"tests/test_osfs.py::TestOSFS::test_case_sensitive",
"tests/test_osfs.py::TestOSFS::test_close",
"tests/test_osfs.py::TestOSFS::test_complex_geturl",
"tests/test_osfs.py::TestOSFS::test_consume_geturl",
"tests/test_osfs.py::TestOSFS::test_copy",
"tests/test_osfs.py::TestOSFS::test_copy_dir_mem",
"tests/test_osfs.py::TestOSFS::test_copy_dir_temp",
"tests/test_osfs.py::TestOSFS::test_copy_file",
"tests/test_osfs.py::TestOSFS::test_copy_structure",
"tests/test_osfs.py::TestOSFS::test_copydir",
"tests/test_osfs.py::TestOSFS::test_create",
"tests/test_osfs.py::TestOSFS::test_desc",
"tests/test_osfs.py::TestOSFS::test_download",
"tests/test_osfs.py::TestOSFS::test_download_0",
"tests/test_osfs.py::TestOSFS::test_download_1",
"tests/test_osfs.py::TestOSFS::test_download_2",
"tests/test_osfs.py::TestOSFS::test_download_4",
"tests/test_osfs.py::TestOSFS::test_download_chunk_size",
"tests/test_osfs.py::TestOSFS::test_exists",
"tests/test_osfs.py::TestOSFS::test_expand_vars",
"tests/test_osfs.py::TestOSFS::test_files",
"tests/test_osfs.py::TestOSFS::test_filterdir",
"tests/test_osfs.py::TestOSFS::test_getinfo",
"tests/test_osfs.py::TestOSFS::test_getmeta",
"tests/test_osfs.py::TestOSFS::test_getsize",
"tests/test_osfs.py::TestOSFS::test_getsyspath",
"tests/test_osfs.py::TestOSFS::test_geturl",
"tests/test_osfs.py::TestOSFS::test_geturl_purpose",
"tests/test_osfs.py::TestOSFS::test_geturl_return_no_url",
"tests/test_osfs.py::TestOSFS::test_glob",
"tests/test_osfs.py::TestOSFS::test_hash",
"tests/test_osfs.py::TestOSFS::test_invalid_chars",
"tests/test_osfs.py::TestOSFS::test_isdir",
"tests/test_osfs.py::TestOSFS::test_isempty",
"tests/test_osfs.py::TestOSFS::test_isfile",
"tests/test_osfs.py::TestOSFS::test_islink",
"tests/test_osfs.py::TestOSFS::test_listdir",
"tests/test_osfs.py::TestOSFS::test_makedir",
"tests/test_osfs.py::TestOSFS::test_makedirs",
"tests/test_osfs.py::TestOSFS::test_match",
"tests/test_osfs.py::TestOSFS::test_move",
"tests/test_osfs.py::TestOSFS::test_move_dir_mem",
"tests/test_osfs.py::TestOSFS::test_move_dir_temp",
"tests/test_osfs.py::TestOSFS::test_move_file_mem",
"tests/test_osfs.py::TestOSFS::test_move_file_same_fs",
"tests/test_osfs.py::TestOSFS::test_move_file_temp",
"tests/test_osfs.py::TestOSFS::test_move_same_fs",
"tests/test_osfs.py::TestOSFS::test_movedir",
"tests/test_osfs.py::TestOSFS::test_not_exists",
"tests/test_osfs.py::TestOSFS::test_open",
"tests/test_osfs.py::TestOSFS::test_open_exclusive",
"tests/test_osfs.py::TestOSFS::test_open_files",
"tests/test_osfs.py::TestOSFS::test_openbin",
"tests/test_osfs.py::TestOSFS::test_openbin_exclusive",
"tests/test_osfs.py::TestOSFS::test_openbin_rw",
"tests/test_osfs.py::TestOSFS::test_opendir",
"tests/test_osfs.py::TestOSFS::test_readbytes",
"tests/test_osfs.py::TestOSFS::test_readtext",
"tests/test_osfs.py::TestOSFS::test_remove",
"tests/test_osfs.py::TestOSFS::test_removedir",
"tests/test_osfs.py::TestOSFS::test_removetree",
"tests/test_osfs.py::TestOSFS::test_repeat_dir",
"tests/test_osfs.py::TestOSFS::test_root_dir",
"tests/test_osfs.py::TestOSFS::test_scandir",
"tests/test_osfs.py::TestOSFS::test_setinfo",
"tests/test_osfs.py::TestOSFS::test_settimes",
"tests/test_osfs.py::TestOSFS::test_symlinks",
"tests/test_osfs.py::TestOSFS::test_touch",
"tests/test_osfs.py::TestOSFS::test_tree",
"tests/test_osfs.py::TestOSFS::test_unicode_paths",
"tests/test_osfs.py::TestOSFS::test_upload",
"tests/test_osfs.py::TestOSFS::test_upload_0",
"tests/test_osfs.py::TestOSFS::test_upload_1",
"tests/test_osfs.py::TestOSFS::test_upload_2",
"tests/test_osfs.py::TestOSFS::test_upload_4",
"tests/test_osfs.py::TestOSFS::test_upload_chunk_size",
"tests/test_osfs.py::TestOSFS::test_validatepath",
"tests/test_osfs.py::TestOSFS::test_writebytes",
"tests/test_osfs.py::TestOSFS::test_writefile",
"tests/test_osfs.py::TestOSFS::test_writetext",
"tests/test_tarfs.py::TestWriteReadTarFS::test_unicode_paths",
"tests/test_tarfs.py::TestWriteTarFS::test_appendbytes",
"tests/test_tarfs.py::TestWriteTarFS::test_appendtext",
"tests/test_tarfs.py::TestWriteTarFS::test_basic",
"tests/test_tarfs.py::TestWriteTarFS::test_bin_files",
"tests/test_tarfs.py::TestWriteTarFS::test_case_sensitive",
"tests/test_tarfs.py::TestWriteTarFS::test_close",
"tests/test_tarfs.py::TestWriteTarFS::test_copy",
"tests/test_tarfs.py::TestWriteTarFS::test_copy_dir_mem",
"tests/test_tarfs.py::TestWriteTarFS::test_copy_dir_temp",
"tests/test_tarfs.py::TestWriteTarFS::test_copy_file",
"tests/test_tarfs.py::TestWriteTarFS::test_copy_structure",
"tests/test_tarfs.py::TestWriteTarFS::test_copydir",
"tests/test_tarfs.py::TestWriteTarFS::test_create",
"tests/test_tarfs.py::TestWriteTarFS::test_desc",
"tests/test_tarfs.py::TestWriteTarFS::test_download",
"tests/test_tarfs.py::TestWriteTarFS::test_download_0",
"tests/test_tarfs.py::TestWriteTarFS::test_download_1",
"tests/test_tarfs.py::TestWriteTarFS::test_download_2",
"tests/test_tarfs.py::TestWriteTarFS::test_download_4",
"tests/test_tarfs.py::TestWriteTarFS::test_download_chunk_size",
"tests/test_tarfs.py::TestWriteTarFS::test_exists",
"tests/test_tarfs.py::TestWriteTarFS::test_files",
"tests/test_tarfs.py::TestWriteTarFS::test_filterdir",
"tests/test_tarfs.py::TestWriteTarFS::test_getinfo",
"tests/test_tarfs.py::TestWriteTarFS::test_getmeta",
"tests/test_tarfs.py::TestWriteTarFS::test_getsize",
"tests/test_tarfs.py::TestWriteTarFS::test_getsyspath",
"tests/test_tarfs.py::TestWriteTarFS::test_geturl",
"tests/test_tarfs.py::TestWriteTarFS::test_geturl_purpose",
"tests/test_tarfs.py::TestWriteTarFS::test_glob",
"tests/test_tarfs.py::TestWriteTarFS::test_hash",
"tests/test_tarfs.py::TestWriteTarFS::test_invalid_chars",
"tests/test_tarfs.py::TestWriteTarFS::test_isdir",
"tests/test_tarfs.py::TestWriteTarFS::test_isempty",
"tests/test_tarfs.py::TestWriteTarFS::test_isfile",
"tests/test_tarfs.py::TestWriteTarFS::test_islink",
"tests/test_tarfs.py::TestWriteTarFS::test_listdir",
"tests/test_tarfs.py::TestWriteTarFS::test_makedir",
"tests/test_tarfs.py::TestWriteTarFS::test_makedirs",
"tests/test_tarfs.py::TestWriteTarFS::test_match",
"tests/test_tarfs.py::TestWriteTarFS::test_move",
"tests/test_tarfs.py::TestWriteTarFS::test_move_dir_mem",
"tests/test_tarfs.py::TestWriteTarFS::test_move_dir_temp",
"tests/test_tarfs.py::TestWriteTarFS::test_move_file_mem",
"tests/test_tarfs.py::TestWriteTarFS::test_move_file_same_fs",
"tests/test_tarfs.py::TestWriteTarFS::test_move_file_temp",
"tests/test_tarfs.py::TestWriteTarFS::test_move_same_fs",
"tests/test_tarfs.py::TestWriteTarFS::test_movedir",
"tests/test_tarfs.py::TestWriteTarFS::test_open",
"tests/test_tarfs.py::TestWriteTarFS::test_open_exclusive",
"tests/test_tarfs.py::TestWriteTarFS::test_open_files",
"tests/test_tarfs.py::TestWriteTarFS::test_openbin",
"tests/test_tarfs.py::TestWriteTarFS::test_openbin_exclusive",
"tests/test_tarfs.py::TestWriteTarFS::test_openbin_rw",
"tests/test_tarfs.py::TestWriteTarFS::test_opendir",
"tests/test_tarfs.py::TestWriteTarFS::test_readbytes",
"tests/test_tarfs.py::TestWriteTarFS::test_readtext",
"tests/test_tarfs.py::TestWriteTarFS::test_remove",
"tests/test_tarfs.py::TestWriteTarFS::test_removedir",
"tests/test_tarfs.py::TestWriteTarFS::test_removetree",
"tests/test_tarfs.py::TestWriteTarFS::test_repeat_dir",
"tests/test_tarfs.py::TestWriteTarFS::test_root_dir",
"tests/test_tarfs.py::TestWriteTarFS::test_scandir",
"tests/test_tarfs.py::TestWriteTarFS::test_setinfo",
"tests/test_tarfs.py::TestWriteTarFS::test_settimes",
"tests/test_tarfs.py::TestWriteTarFS::test_touch",
"tests/test_tarfs.py::TestWriteTarFS::test_tree",
"tests/test_tarfs.py::TestWriteTarFS::test_upload",
"tests/test_tarfs.py::TestWriteTarFS::test_upload_0",
"tests/test_tarfs.py::TestWriteTarFS::test_upload_1",
"tests/test_tarfs.py::TestWriteTarFS::test_upload_2",
"tests/test_tarfs.py::TestWriteTarFS::test_upload_4",
"tests/test_tarfs.py::TestWriteTarFS::test_upload_chunk_size",
"tests/test_tarfs.py::TestWriteTarFS::test_validatepath",
"tests/test_tarfs.py::TestWriteTarFS::test_writebytes",
"tests/test_tarfs.py::TestWriteTarFS::test_writefile",
"tests/test_tarfs.py::TestWriteTarFS::test_writetext",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_appendbytes",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_appendtext",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_basic",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_bin_files",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_case_sensitive",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_close",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_copy",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_copy_dir_mem",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_copy_dir_temp",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_copy_file",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_copy_structure",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_copydir",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_create",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_desc",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_download",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_download_0",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_download_1",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_download_2",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_download_4",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_download_chunk_size",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_exists",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_files",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_filterdir",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_getinfo",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_getmeta",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_getsize",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_getsyspath",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_geturl",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_geturl_purpose",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_glob",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_hash",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_invalid_chars",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_isdir",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_isempty",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_isfile",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_islink",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_listdir",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_makedir",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_makedirs",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_match",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_move",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_move_dir_mem",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_move_dir_temp",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_move_file_mem",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_move_file_same_fs",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_move_file_temp",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_move_same_fs",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_movedir",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_open",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_open_exclusive",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_open_files",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_openbin",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_openbin_exclusive",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_openbin_rw",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_opendir",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_readbytes",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_readtext",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_remove",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_removedir",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_removetree",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_repeat_dir",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_root_dir",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_scandir",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_setinfo",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_settimes",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_touch",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_tree",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_upload",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_upload_0",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_upload_1",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_upload_2",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_upload_4",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_upload_chunk_size",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_validatepath",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_writebytes",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_writefile",
"tests/test_tarfs.py::TestWriteTarFSToFileobj::test_writetext",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_appendbytes",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_appendtext",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_basic",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_bin_files",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_case_sensitive",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_close",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_copy",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_copy_dir_mem",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_copy_dir_temp",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_copy_file",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_copy_structure",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_copydir",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_create",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_desc",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_download",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_download_0",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_download_1",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_download_2",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_download_4",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_download_chunk_size",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_exists",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_files",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_filterdir",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_getinfo",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_getmeta",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_getsize",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_getsyspath",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_geturl",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_geturl_purpose",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_glob",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_hash",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_invalid_chars",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_isdir",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_isempty",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_isfile",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_islink",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_listdir",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_makedir",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_makedirs",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_match",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_move",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_move_dir_mem",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_move_dir_temp",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_move_file_mem",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_move_file_same_fs",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_move_file_temp",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_move_same_fs",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_movedir",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_open",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_open_exclusive",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_open_files",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_openbin",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_openbin_exclusive",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_openbin_rw",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_opendir",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_readbytes",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_readtext",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_remove",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_removedir",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_removetree",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_repeat_dir",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_root_dir",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_scandir",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_setinfo",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_settimes",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_touch",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_tree",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_upload",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_upload_0",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_upload_1",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_upload_2",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_upload_4",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_upload_chunk_size",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_validatepath",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_writebytes",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_writefile",
"tests/test_tarfs.py::TestWriteGZippedTarFS::test_writetext",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_appendbytes",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_appendtext",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_basic",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_bin_files",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_case_sensitive",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_close",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_copy",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_copy_dir_mem",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_copy_dir_temp",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_copy_file",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_copy_structure",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_copydir",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_create",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_desc",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_download",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_download_0",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_download_1",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_download_2",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_download_4",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_download_chunk_size",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_exists",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_files",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_filterdir",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_getinfo",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_getmeta",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_getsize",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_getsyspath",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_geturl",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_geturl_purpose",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_glob",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_hash",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_invalid_chars",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_isdir",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_isempty",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_isfile",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_islink",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_listdir",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_makedir",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_makedirs",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_match",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_move",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_move_dir_mem",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_move_dir_temp",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_move_file_mem",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_move_file_same_fs",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_move_file_temp",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_move_same_fs",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_movedir",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_open",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_open_exclusive",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_open_files",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_openbin",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_openbin_exclusive",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_openbin_rw",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_opendir",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_readbytes",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_readtext",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_remove",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_removedir",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_removetree",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_repeat_dir",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_root_dir",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_scandir",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_setinfo",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_settimes",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_touch",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_tree",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_upload",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_upload_0",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_upload_1",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_upload_2",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_upload_4",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_upload_chunk_size",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_validatepath",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_writebytes",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_writefile",
"tests/test_tarfs.py::TestWriteXZippedTarFS::test_writetext",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_appendbytes",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_appendtext",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_basic",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_bin_files",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_case_sensitive",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_close",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_copy",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_copy_dir_mem",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_copy_dir_temp",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_copy_file",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_copy_structure",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_copydir",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_create",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_desc",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_download",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_download_0",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_download_1",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_download_2",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_download_4",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_download_chunk_size",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_exists",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_files",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_filterdir",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_getinfo",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_getmeta",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_getsize",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_getsyspath",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_geturl",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_geturl_purpose",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_glob",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_hash",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_invalid_chars",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_isdir",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_isempty",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_isfile",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_islink",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_listdir",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_makedir",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_makedirs",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_match",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_move",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_move_dir_mem",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_move_dir_temp",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_move_file_mem",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_move_file_same_fs",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_move_file_temp",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_move_same_fs",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_movedir",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_open",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_open_exclusive",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_open_files",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_openbin",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_openbin_exclusive",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_openbin_rw",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_opendir",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_readbytes",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_readtext",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_remove",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_removedir",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_removetree",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_repeat_dir",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_root_dir",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_scandir",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_setinfo",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_settimes",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_touch",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_tree",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_upload",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_upload_0",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_upload_1",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_upload_2",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_upload_4",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_upload_chunk_size",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_validatepath",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_writebytes",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_writefile",
"tests/test_tarfs.py::TestWriteBZippedTarFS::test_writetext",
"tests/test_tarfs.py::TestReadTarFS::test_getinfo",
"tests/test_tarfs.py::TestReadTarFS::test_gets",
"tests/test_tarfs.py::TestReadTarFS::test_geturl_for_download",
"tests/test_tarfs.py::TestReadTarFS::test_geturl_for_fs",
"tests/test_tarfs.py::TestReadTarFS::test_geturl_for_fs_but_file_is_binaryio",
"tests/test_tarfs.py::TestReadTarFS::test_implied_dir",
"tests/test_tarfs.py::TestReadTarFS::test_listdir",
"tests/test_tarfs.py::TestReadTarFS::test_open",
"tests/test_tarfs.py::TestReadTarFS::test_read_from_filename",
"tests/test_tarfs.py::TestReadTarFS::test_read_from_fileobject",
"tests/test_tarfs.py::TestReadTarFS::test_read_non_existent_file",
"tests/test_tarfs.py::TestReadTarFS::test_readonly",
"tests/test_tarfs.py::TestReadTarFS::test_repr",
"tests/test_tarfs.py::TestReadTarFS::test_str",
"tests/test_tarfs.py::TestReadTarFS::test_walk_files",
"tests/test_tarfs.py::TestBrokenPaths::test_listdir",
"tests/test_tarfs.py::TestImplicitDirectories::test_getinfo",
"tests/test_tarfs.py::TestImplicitDirectories::test_isdir",
"tests/test_tarfs.py::TestImplicitDirectories::test_isfile",
"tests/test_tarfs.py::TestImplicitDirectories::test_listdir",
"tests/test_tarfs.py::TestReadTarFSMem::test_getinfo",
"tests/test_tarfs.py::TestReadTarFSMem::test_gets",
"tests/test_tarfs.py::TestReadTarFSMem::test_geturl_for_download",
"tests/test_tarfs.py::TestReadTarFSMem::test_geturl_for_fs",
"tests/test_tarfs.py::TestReadTarFSMem::test_geturl_for_fs_but_file_is_binaryio",
"tests/test_tarfs.py::TestReadTarFSMem::test_implied_dir",
"tests/test_tarfs.py::TestReadTarFSMem::test_listdir",
"tests/test_tarfs.py::TestReadTarFSMem::test_open",
"tests/test_tarfs.py::TestReadTarFSMem::test_read_from_filename",
"tests/test_tarfs.py::TestReadTarFSMem::test_read_from_fileobject",
"tests/test_tarfs.py::TestReadTarFSMem::test_read_non_existent_file",
"tests/test_tarfs.py::TestReadTarFSMem::test_readonly",
"tests/test_tarfs.py::TestReadTarFSMem::test_repr",
"tests/test_tarfs.py::TestReadTarFSMem::test_str",
"tests/test_tarfs.py::TestReadTarFSMem::test_walk_files",
"tests/test_tarfs.py::TestOpener::test_not_writeable",
"tests/test_url_tools.py::TestBase::test_quote",
"tests/test_zipfs.py::TestWriteReadZipFS::test_unicode_paths",
"tests/test_zipfs.py::TestWriteZipFS::test_appendbytes",
"tests/test_zipfs.py::TestWriteZipFS::test_appendtext",
"tests/test_zipfs.py::TestWriteZipFS::test_basic",
"tests/test_zipfs.py::TestWriteZipFS::test_bin_files",
"tests/test_zipfs.py::TestWriteZipFS::test_case_sensitive",
"tests/test_zipfs.py::TestWriteZipFS::test_close",
"tests/test_zipfs.py::TestWriteZipFS::test_copy",
"tests/test_zipfs.py::TestWriteZipFS::test_copy_dir_mem",
"tests/test_zipfs.py::TestWriteZipFS::test_copy_dir_temp",
"tests/test_zipfs.py::TestWriteZipFS::test_copy_file",
"tests/test_zipfs.py::TestWriteZipFS::test_copy_structure",
"tests/test_zipfs.py::TestWriteZipFS::test_copydir",
"tests/test_zipfs.py::TestWriteZipFS::test_create",
"tests/test_zipfs.py::TestWriteZipFS::test_desc",
"tests/test_zipfs.py::TestWriteZipFS::test_download",
"tests/test_zipfs.py::TestWriteZipFS::test_download_0",
"tests/test_zipfs.py::TestWriteZipFS::test_download_1",
"tests/test_zipfs.py::TestWriteZipFS::test_download_2",
"tests/test_zipfs.py::TestWriteZipFS::test_download_4",
"tests/test_zipfs.py::TestWriteZipFS::test_download_chunk_size",
"tests/test_zipfs.py::TestWriteZipFS::test_exists",
"tests/test_zipfs.py::TestWriteZipFS::test_files",
"tests/test_zipfs.py::TestWriteZipFS::test_filterdir",
"tests/test_zipfs.py::TestWriteZipFS::test_getinfo",
"tests/test_zipfs.py::TestWriteZipFS::test_getmeta",
"tests/test_zipfs.py::TestWriteZipFS::test_getsize",
"tests/test_zipfs.py::TestWriteZipFS::test_getsyspath",
"tests/test_zipfs.py::TestWriteZipFS::test_geturl",
"tests/test_zipfs.py::TestWriteZipFS::test_geturl_purpose",
"tests/test_zipfs.py::TestWriteZipFS::test_glob",
"tests/test_zipfs.py::TestWriteZipFS::test_hash",
"tests/test_zipfs.py::TestWriteZipFS::test_invalid_chars",
"tests/test_zipfs.py::TestWriteZipFS::test_isdir",
"tests/test_zipfs.py::TestWriteZipFS::test_isempty",
"tests/test_zipfs.py::TestWriteZipFS::test_isfile",
"tests/test_zipfs.py::TestWriteZipFS::test_islink",
"tests/test_zipfs.py::TestWriteZipFS::test_listdir",
"tests/test_zipfs.py::TestWriteZipFS::test_makedir",
"tests/test_zipfs.py::TestWriteZipFS::test_makedirs",
"tests/test_zipfs.py::TestWriteZipFS::test_match",
"tests/test_zipfs.py::TestWriteZipFS::test_move",
"tests/test_zipfs.py::TestWriteZipFS::test_move_dir_mem",
"tests/test_zipfs.py::TestWriteZipFS::test_move_dir_temp",
"tests/test_zipfs.py::TestWriteZipFS::test_move_file_mem",
"tests/test_zipfs.py::TestWriteZipFS::test_move_file_same_fs",
"tests/test_zipfs.py::TestWriteZipFS::test_move_file_temp",
"tests/test_zipfs.py::TestWriteZipFS::test_move_same_fs",
"tests/test_zipfs.py::TestWriteZipFS::test_movedir",
"tests/test_zipfs.py::TestWriteZipFS::test_open",
"tests/test_zipfs.py::TestWriteZipFS::test_open_exclusive",
"tests/test_zipfs.py::TestWriteZipFS::test_open_files",
"tests/test_zipfs.py::TestWriteZipFS::test_openbin",
"tests/test_zipfs.py::TestWriteZipFS::test_openbin_exclusive",
"tests/test_zipfs.py::TestWriteZipFS::test_openbin_rw",
"tests/test_zipfs.py::TestWriteZipFS::test_opendir",
"tests/test_zipfs.py::TestWriteZipFS::test_readbytes",
"tests/test_zipfs.py::TestWriteZipFS::test_readtext",
"tests/test_zipfs.py::TestWriteZipFS::test_remove",
"tests/test_zipfs.py::TestWriteZipFS::test_removedir",
"tests/test_zipfs.py::TestWriteZipFS::test_removetree",
"tests/test_zipfs.py::TestWriteZipFS::test_repeat_dir",
"tests/test_zipfs.py::TestWriteZipFS::test_root_dir",
"tests/test_zipfs.py::TestWriteZipFS::test_scandir",
"tests/test_zipfs.py::TestWriteZipFS::test_setinfo",
"tests/test_zipfs.py::TestWriteZipFS::test_settimes",
"tests/test_zipfs.py::TestWriteZipFS::test_touch",
"tests/test_zipfs.py::TestWriteZipFS::test_tree",
"tests/test_zipfs.py::TestWriteZipFS::test_upload",
"tests/test_zipfs.py::TestWriteZipFS::test_upload_0",
"tests/test_zipfs.py::TestWriteZipFS::test_upload_1",
"tests/test_zipfs.py::TestWriteZipFS::test_upload_2",
"tests/test_zipfs.py::TestWriteZipFS::test_upload_4",
"tests/test_zipfs.py::TestWriteZipFS::test_upload_chunk_size",
"tests/test_zipfs.py::TestWriteZipFS::test_validatepath",
"tests/test_zipfs.py::TestWriteZipFS::test_writebytes",
"tests/test_zipfs.py::TestWriteZipFS::test_writefile",
"tests/test_zipfs.py::TestWriteZipFS::test_writetext",
"tests/test_zipfs.py::TestReadZipFS::test_getinfo",
"tests/test_zipfs.py::TestReadZipFS::test_gets",
"tests/test_zipfs.py::TestReadZipFS::test_geturl_for_download",
"tests/test_zipfs.py::TestReadZipFS::test_geturl_for_fs",
"tests/test_zipfs.py::TestReadZipFS::test_geturl_for_fs_but_file_is_binaryio",
"tests/test_zipfs.py::TestReadZipFS::test_implied_dir",
"tests/test_zipfs.py::TestReadZipFS::test_large",
"tests/test_zipfs.py::TestReadZipFS::test_listdir",
"tests/test_zipfs.py::TestReadZipFS::test_open",
"tests/test_zipfs.py::TestReadZipFS::test_openbin",
"tests/test_zipfs.py::TestReadZipFS::test_read",
"tests/test_zipfs.py::TestReadZipFS::test_read1",
"tests/test_zipfs.py::TestReadZipFS::test_read_non_existent_file",
"tests/test_zipfs.py::TestReadZipFS::test_readonly",
"tests/test_zipfs.py::TestReadZipFS::test_repr",
"tests/test_zipfs.py::TestReadZipFS::test_seek_current",
"tests/test_zipfs.py::TestReadZipFS::test_seek_end",
"tests/test_zipfs.py::TestReadZipFS::test_seek_set",
"tests/test_zipfs.py::TestReadZipFS::test_str",
"tests/test_zipfs.py::TestReadZipFS::test_walk_files",
"tests/test_zipfs.py::TestReadZipFSMem::test_getinfo",
"tests/test_zipfs.py::TestReadZipFSMem::test_gets",
"tests/test_zipfs.py::TestReadZipFSMem::test_geturl_for_download",
"tests/test_zipfs.py::TestReadZipFSMem::test_geturl_for_fs",
"tests/test_zipfs.py::TestReadZipFSMem::test_geturl_for_fs_but_file_is_binaryio",
"tests/test_zipfs.py::TestReadZipFSMem::test_implied_dir",
"tests/test_zipfs.py::TestReadZipFSMem::test_large",
"tests/test_zipfs.py::TestReadZipFSMem::test_listdir",
"tests/test_zipfs.py::TestReadZipFSMem::test_open",
"tests/test_zipfs.py::TestReadZipFSMem::test_openbin",
"tests/test_zipfs.py::TestReadZipFSMem::test_read",
"tests/test_zipfs.py::TestReadZipFSMem::test_read1",
"tests/test_zipfs.py::TestReadZipFSMem::test_read_non_existent_file",
"tests/test_zipfs.py::TestReadZipFSMem::test_readonly",
"tests/test_zipfs.py::TestReadZipFSMem::test_repr",
"tests/test_zipfs.py::TestReadZipFSMem::test_seek_current",
"tests/test_zipfs.py::TestReadZipFSMem::test_seek_end",
"tests/test_zipfs.py::TestReadZipFSMem::test_seek_set",
"tests/test_zipfs.py::TestReadZipFSMem::test_str",
"tests/test_zipfs.py::TestReadZipFSMem::test_walk_files",
"tests/test_zipfs.py::TestDirsZipFS::test_implied",
"tests/test_zipfs.py::TestOpener::test_not_writeable"
] | [] | {
"failed_lite_validators": [
"has_added_files",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
} | "2019-08-02T08:06:25Z" | mit |
|
PyFilesystem__pyfilesystem2-396 | diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0449d14..7cec240 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,6 +16,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
ensuring `conftest.py` is present, fixes [#364](https://github.com/PyFilesystem/pyfilesystem2/issues/364).
- Stop patching copy with Python 3.8+ because it already uses sendfile.
- Fixed crash when CPython's -OO flag is used
+- Fixed error when parsing timestamps from a FTP directory served from a WindowsNT FTP Server, fixes [#395](https://github.com/PyFilesystem/pyfilesystem2/issues/395).
## [2.4.11] - 2019-09-07
diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md
index de54b66..3b3e8c2 100644
--- a/CONTRIBUTORS.md
+++ b/CONTRIBUTORS.md
@@ -11,3 +11,4 @@ Many thanks to the following developers for contributing to this project:
- [Martin Larralde](https://github.com/althonos)
- [Will McGugan](https://github.com/willmcgugan)
- [Zmej Serow](https://github.com/zmej-serow)
+- [Morten Engelhardt Olsen](https://github.com/xoriath)
diff --git a/fs/_ftp_parse.py b/fs/_ftp_parse.py
index b50f75e..b503d73 100644
--- a/fs/_ftp_parse.py
+++ b/fs/_ftp_parse.py
@@ -41,7 +41,7 @@ RE_LINUX = re.compile(
RE_WINDOWSNT = re.compile(
r"""
^
- (?P<modified>.*(AM|PM))
+ (?P<modified>.*?(AM|PM))
\s*
(?P<size>(<DIR>|\d*))
\s*
| PyFilesystem/pyfilesystem2 | 34084cf5d1027d413fff265c93af5b8dc0685ea7 | diff --git a/tests/test_ftp_parse.py b/tests/test_ftp_parse.py
index c649a1f..d0abc05 100644
--- a/tests/test_ftp_parse.py
+++ b/tests/test_ftp_parse.py
@@ -166,6 +166,7 @@ drwxr-xr-x 2 foo-user foo-group 0 Jan 5 11:59 240485
directory = """\
11-02-17 02:00AM <DIR> docs
11-02-17 02:12PM <DIR> images
+11-02-17 02:12PM <DIR> AM to PM
11-02-17 03:33PM 9276 logo.gif
"""
expected = [
@@ -183,6 +184,13 @@ drwxr-xr-x 2 foo-user foo-group 0 Jan 5 11:59 240485
"ls": "11-02-17 02:12PM <DIR> images"
},
},
+ {
+ "basic": {"is_dir": True, "name": "AM to PM"},
+ "details": {"modified": 1486822320.0, "type": 1},
+ "ftp": {
+ "ls": "11-02-17 02:12PM <DIR> AM to PM"
+ },
+ },
{
"basic": {"is_dir": False, "name": "logo.gif"},
"details": {"modified": 1486827180.0, "size": 9276, "type": 2},
| fs/_ftp_parse.py fails when parsing directory listing on NT format if folder or filename contains AM or PM
The regex pattern used to parse the directory listing for NT servers uses a greedy (default) pattern when parsing the modified date column. This causes the `(<modified>)` capture group to capture until the last AM or PM, which could be in the file name.
Example file listing that fails:
```
01-29-20 04:11AM <DIR> Clock at AM or PM
```
This fails with the following trace
```
File ".venv\lib\site-packages\fs\ftpfs.py", line 746, in scandir
if not self.supports_mlst and not self.getinfo(path).is_dir:
File ".venv\lib\site-packages\fs\ftpfs.py", line 614, in getinfo
directory = self._read_dir(dir_name)
File ".venv\lib\site-packages\fs\ftpfs.py", line 495, in _read_dir
_list = [Info(raw_info) for raw_info in ftp_parse.parse(lines)]
File ".venv\lib\site-packages\fs\_ftp_parse.py", line 70, in parse
raw_info = parse_line(line)
File ".venv\lib\site-packages\fs\_ftp_parse.py", line 81, in parse_line
return decode_callable(line, match)
File ".venv\lib\site-packages\fs\_ftp_parse.py", line 163, in decode_windowsnt
raw_info["details"]["size"] = int(match.group("size"))
ValueError: invalid literal for int() with base 10: ''
```
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_ftp_parse.py::TestFTPParse::test_decode_windowsnt"
] | [
"tests/test_ftp_parse.py::TestFTPParse::test_decode_linux",
"tests/test_ftp_parse.py::TestFTPParse::test_parse",
"tests/test_ftp_parse.py::TestFTPParse::test_parse_line",
"tests/test_ftp_parse.py::TestFTPParse::test_parse_time"
] | {
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2020-05-16T03:05:58Z" | mit |
|
PyFilesystem__pyfilesystem2-439 | diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3b965c9..9e0a768 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,6 +12,8 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
- Missing `mode` attribute to `_MemoryFile` objects returned by `MemoryFS.openbin`.
- Missing `readinto` method for `MemoryFS` and `FTPFS` file objects. Closes
[#380](https://github.com/PyFilesystem/pyfilesystem2/issues/380).
+- Added compatibility if a Windows FTP server returns file information to the
+ `LIST` command with 24-hour times. Closes [#438](https://github.com/PyFilesystem/pyfilesystem2/issues/438).
### Changed
diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md
index ba15fd7..5df2715 100644
--- a/CONTRIBUTORS.md
+++ b/CONTRIBUTORS.md
@@ -2,6 +2,7 @@
Many thanks to the following developers for contributing to this project:
+- [Andreas Tollkötter](https://github.com/atollk)
- [C. W.](https://github.com/chfw)
- [Diego Argueta](https://github.com/dargueta)
- [Geoff Jukes](https://github.com/geoffjukes)
@@ -9,7 +10,7 @@ Many thanks to the following developers for contributing to this project:
- [Justin Charlong](https://github.com/jcharlong)
- [Louis Sautier](https://github.com/sbraz)
- [Martin Larralde](https://github.com/althonos)
+- [Morten Engelhardt Olsen](https://github.com/xoriath)
- [Nick Henderson](https://github.com/nwh)
- [Will McGugan](https://github.com/willmcgugan)
- [Zmej Serow](https://github.com/zmej-serow)
-- [Morten Engelhardt Olsen](https://github.com/xoriath)
diff --git a/fs/_ftp_parse.py b/fs/_ftp_parse.py
index b503d73..9e15a26 100644
--- a/fs/_ftp_parse.py
+++ b/fs/_ftp_parse.py
@@ -41,14 +41,17 @@ RE_LINUX = re.compile(
RE_WINDOWSNT = re.compile(
r"""
^
- (?P<modified>.*?(AM|PM))
- \s*
- (?P<size>(<DIR>|\d*))
- \s*
+ (?P<modified_date>\S+)
+ \s+
+ (?P<modified_time>\S+(AM|PM)?)
+ \s+
+ (?P<size>(<DIR>|\d+))
+ \s+
(?P<name>.*)
$
""",
- re.VERBOSE)
+ re.VERBOSE,
+)
def get_decoders():
@@ -82,15 +85,13 @@ def parse_line(line):
def _parse_time(t, formats):
- t = " ".join(token.strip() for token in t.lower().split(" "))
-
- _t = None
for frmt in formats:
try:
_t = time.strptime(t, frmt)
+ break
except ValueError:
continue
- if not _t:
+ else:
return None
year = _t.tm_year if _t.tm_year != 1900 else time.localtime().tm_year
@@ -104,6 +105,10 @@ def _parse_time(t, formats):
return epoch_time
+def _decode_linux_time(mtime):
+ return _parse_time(mtime, formats=["%b %d %Y", "%b %d %H:%M"])
+
+
def decode_linux(line, match):
perms, links, uid, gid, size, mtime, name = match.groups()
is_link = perms.startswith("l")
@@ -114,7 +119,7 @@ def decode_linux(line, match):
_link_name = _link_name.strip()
permissions = Permissions.parse(perms[1:])
- mtime_epoch = _parse_time(mtime, formats=["%b %d %Y", "%b %d %H:%M"])
+ mtime_epoch = _decode_linux_time(mtime)
name = unicodedata.normalize("NFC", name)
@@ -138,12 +143,18 @@ def decode_linux(line, match):
return raw_info
+def _decode_windowsnt_time(mtime):
+ return _parse_time(mtime, formats=["%d-%m-%y %I:%M%p", "%d-%m-%y %H:%M"])
+
+
def decode_windowsnt(line, match):
"""
- Decodes a Windows NT FTP LIST line like these two:
+ Decodes a Windows NT FTP LIST line like one of these:
`11-02-18 02:12PM <DIR> images`
`11-02-18 03:33PM 9276 logo.gif`
+
+ Alternatively, the time (02:12PM) might also be present in 24-hour format (14:12).
"""
is_dir = match.group("size") == "<DIR>"
@@ -161,7 +172,9 @@ def decode_windowsnt(line, match):
if not is_dir:
raw_info["details"]["size"] = int(match.group("size"))
- modified = _parse_time(match.group("modified"), formats=["%d-%m-%y %I:%M%p"])
+ modified = _decode_windowsnt_time(
+ match.group("modified_date") + " " + match.group("modified_time")
+ )
if modified is not None:
raw_info["details"]["modified"] = modified
| PyFilesystem/pyfilesystem2 | c5d193bf7e4b3696386d6d4439e8192d5060f6d6 | diff --git a/tests/test_ftp_parse.py b/tests/test_ftp_parse.py
index d0abc05..b9a69cf 100644
--- a/tests/test_ftp_parse.py
+++ b/tests/test_ftp_parse.py
@@ -17,17 +17,18 @@ class TestFTPParse(unittest.TestCase):
@mock.patch("time.localtime")
def test_parse_time(self, mock_localtime):
self.assertEqual(
- ftp_parse._parse_time("JUL 05 1974", formats=["%b %d %Y"]),
- 142214400.0)
+ ftp_parse._parse_time("JUL 05 1974", formats=["%b %d %Y"]), 142214400.0
+ )
mock_localtime.return_value = time2017
self.assertEqual(
- ftp_parse._parse_time("JUL 05 02:00", formats=["%b %d %H:%M"]),
- 1499220000.0)
+ ftp_parse._parse_time("JUL 05 02:00", formats=["%b %d %H:%M"]), 1499220000.0
+ )
self.assertEqual(
ftp_parse._parse_time("05-07-17 02:00AM", formats=["%d-%m-%y %I:%M%p"]),
- 1499220000.0)
+ 1499220000.0,
+ )
self.assertEqual(ftp_parse._parse_time("notadate", formats=["%b %d %Y"]), None)
@@ -164,39 +165,68 @@ drwxr-xr-x 2 foo-user foo-group 0 Jan 5 11:59 240485
def test_decode_windowsnt(self, mock_localtime):
mock_localtime.return_value = time2017
directory = """\
+unparsable line
11-02-17 02:00AM <DIR> docs
11-02-17 02:12PM <DIR> images
-11-02-17 02:12PM <DIR> AM to PM
+11-02-17 02:12PM <DIR> AM to PM
11-02-17 03:33PM 9276 logo.gif
+05-11-20 22:11 <DIR> src
+11-02-17 01:23 1 12
+11-02-17 4:54 0 icon.bmp
+11-02-17 4:54AM 0 icon.gif
+11-02-17 4:54PM 0 icon.png
+11-02-17 16:54 0 icon.jpg
"""
expected = [
{
"basic": {"is_dir": True, "name": "docs"},
"details": {"modified": 1486778400.0, "type": 1},
- "ftp": {
- "ls": "11-02-17 02:00AM <DIR> docs"
- },
+ "ftp": {"ls": "11-02-17 02:00AM <DIR> docs"},
},
{
"basic": {"is_dir": True, "name": "images"},
"details": {"modified": 1486822320.0, "type": 1},
- "ftp": {
- "ls": "11-02-17 02:12PM <DIR> images"
- },
+ "ftp": {"ls": "11-02-17 02:12PM <DIR> images"},
},
{
"basic": {"is_dir": True, "name": "AM to PM"},
"details": {"modified": 1486822320.0, "type": 1},
- "ftp": {
- "ls": "11-02-17 02:12PM <DIR> AM to PM"
- },
+ "ftp": {"ls": "11-02-17 02:12PM <DIR> AM to PM"},
},
{
"basic": {"is_dir": False, "name": "logo.gif"},
"details": {"modified": 1486827180.0, "size": 9276, "type": 2},
- "ftp": {
- "ls": "11-02-17 03:33PM 9276 logo.gif"
- },
+ "ftp": {"ls": "11-02-17 03:33PM 9276 logo.gif"},
+ },
+ {
+ "basic": {"is_dir": True, "name": "src"},
+ "details": {"modified": 1604614260.0, "type": 1},
+ "ftp": {"ls": "05-11-20 22:11 <DIR> src"},
+ },
+ {
+ "basic": {"is_dir": False, "name": "12"},
+ "details": {"modified": 1486776180.0, "size": 1, "type": 2},
+ "ftp": {"ls": "11-02-17 01:23 1 12"},
+ },
+ {
+ "basic": {"is_dir": False, "name": "icon.bmp"},
+ "details": {"modified": 1486788840.0, "size": 0, "type": 2},
+ "ftp": {"ls": "11-02-17 4:54 0 icon.bmp"},
+ },
+ {
+ "basic": {"is_dir": False, "name": "icon.gif"},
+ "details": {"modified": 1486788840.0, "size": 0, "type": 2},
+ "ftp": {"ls": "11-02-17 4:54AM 0 icon.gif"},
+ },
+ {
+ "basic": {"is_dir": False, "name": "icon.png"},
+ "details": {"modified": 1486832040.0, "size": 0, "type": 2},
+ "ftp": {"ls": "11-02-17 4:54PM 0 icon.png"},
+ },
+ {
+ "basic": {"is_dir": False, "name": "icon.jpg"},
+ "details": {"modified": 1486832040.0, "size": 0, "type": 2},
+ "ftp": {"ls": "11-02-17 16:54 0 icon.jpg"},
},
]
| Add support for different FTP LIST locales (Windows CE exclusive?)
We are using pyfilesystem2 to access a German locale FTP server on an MS Windows CE operating system. I cannot pinpoint whether it is the locale, the OS, or a different factor altogether, but the FTP LIST command, which is apparently used almost everywhere in the library, yields its data in a different format than Windows NT. Thus, `FTPFS.read_dir` fails to parse any items and always returns an empty dict and most operations fail.
To be precise, the LIST output only differs slightly in that it uses 24 hour days rather than 12 hour AM/PM days.
WinNT:
`11-02-18 02:12PM <DIR> images`
`11-02-18 03:33PM 9276 logo.gif`
WinCE:
`11-02-18 14:12 <DIR> images`
`11-02-18 15:33 9276 logo.gif`
We would like to see support for that format added, either as an extension to the "WindowsNT" parsing, or as a new kind of response parsing. If this is an acceptable change, we'd create the suitable PR for it. It would be great if this fix would make it into 2.4.12, as we'd have to keep using a custom fix in our code until 2.4.13 otherwise.
Thanks! | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_ftp_parse.py::TestFTPParse::test_decode_windowsnt"
] | [
"tests/test_ftp_parse.py::TestFTPParse::test_decode_linux",
"tests/test_ftp_parse.py::TestFTPParse::test_parse",
"tests/test_ftp_parse.py::TestFTPParse::test_parse_line",
"tests/test_ftp_parse.py::TestFTPParse::test_parse_time"
] | {
"failed_lite_validators": [
"has_media",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2020-11-05T07:47:56Z" | mit |
|
PyFilesystem__pyfilesystem2-473 | diff --git a/CHANGELOG.md b/CHANGELOG.md
index c99ffcc..aacded9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -25,7 +25,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
test suites.
- `FSTestCases` now builds the large data required for `upload` and `download` tests only
once in order to reduce the total testing time.
-- `MemoryFS.move` and `MemoryFS.movedir` will now avoid copying data.
+- `MemoryFS.move` and `MemoryFS.movedir` will now avoid copying data.
Closes [#452](https://github.com/PyFilesystem/pyfilesystem2/issues/452).
### Fixed
@@ -36,6 +36,8 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
- Avoid creating a new connection on every call of `FTPFS.upload`. Closes [#455](https://github.com/PyFilesystem/pyfilesystem2/issues/455).
- `WrapReadOnly.removetree` not raising a `ResourceReadOnly` when called. Closes [#468](https://github.com/PyFilesystem/pyfilesystem2/issues/468).
- `WrapCachedDir.isdir` and `WrapCachedDir.isfile` raising a `ResourceNotFound` error on non-existing path ([#470](https://github.com/PyFilesystem/pyfilesystem2/pull/470)).
+- `FTPFS` not listing certain entries with sticky/SUID/SGID permissions set by Linux server ([#473](https://github.com/PyFilesystem/pyfilesystem2/pull/473)).
+ Closes [#451](https://github.com/PyFilesystem/pyfilesystem2/issues/451).
## [2.4.12] - 2021-01-14
diff --git a/fs/_ftp_parse.py b/fs/_ftp_parse.py
index 9e15a26..a9088ab 100644
--- a/fs/_ftp_parse.py
+++ b/fs/_ftp_parse.py
@@ -19,7 +19,8 @@ EPOCH_DT = datetime.datetime.fromtimestamp(0, UTC)
RE_LINUX = re.compile(
r"""
^
- ([ldrwx-]{10})
+ ([-dlpscbD])
+ ([r-][w-][xsS-][r-][w-][xsS-][r-][w-][xtT-][\.\+]?)
\s+?
(\d+)
\s+?
@@ -110,14 +111,14 @@ def _decode_linux_time(mtime):
def decode_linux(line, match):
- perms, links, uid, gid, size, mtime, name = match.groups()
- is_link = perms.startswith("l")
- is_dir = perms.startswith("d") or is_link
+ ty, perms, links, uid, gid, size, mtime, name = match.groups()
+ is_link = ty == "l"
+ is_dir = ty == "d" or is_link
if is_link:
name, _, _link_name = name.partition("->")
name = name.strip()
_link_name = _link_name.strip()
- permissions = Permissions.parse(perms[1:])
+ permissions = Permissions.parse(perms)
mtime_epoch = _decode_linux_time(mtime)
| PyFilesystem/pyfilesystem2 | 4efe083ebb1a43aafd0e171b3b20d6b546c86756 | diff --git a/tests/test_ftp_parse.py b/tests/test_ftp_parse.py
index b9a69cf..d027082 100644
--- a/tests/test_ftp_parse.py
+++ b/tests/test_ftp_parse.py
@@ -1,5 +1,6 @@
from __future__ import unicode_literals
+import textwrap
import time
import unittest
@@ -33,7 +34,7 @@ class TestFTPParse(unittest.TestCase):
self.assertEqual(ftp_parse._parse_time("notadate", formats=["%b %d %Y"]), None)
def test_parse(self):
- self.assertEqual(ftp_parse.parse([""]), [])
+ self.assertListEqual(ftp_parse.parse([""]), [])
def test_parse_line(self):
self.assertIs(ftp_parse.parse_line("not a dir"), None)
@@ -41,15 +42,17 @@ class TestFTPParse(unittest.TestCase):
@mock.patch("time.localtime")
def test_decode_linux(self, mock_localtime):
mock_localtime.return_value = time2017
- directory = """\
-lrwxrwxrwx 1 0 0 19 Jan 18 2006 debian -> ./pub/mirror/debian
-drwxr-xr-x 10 0 0 4096 Aug 03 09:21 debian-archive
-lrwxrwxrwx 1 0 0 27 Nov 30 2015 debian-backports -> pub/mirror/debian-backports
-drwxr-xr-x 12 0 0 4096 Sep 29 13:13 pub
--rw-r--r-- 1 0 0 26 Mar 04 2010 robots.txt
-drwxr-xr-x 8 foo bar 4096 Oct 4 09:05 test
-drwxr-xr-x 2 foo-user foo-group 0 Jan 5 11:59 240485
-"""
+ directory = textwrap.dedent(
+ """
+ lrwxrwxrwx 1 0 0 19 Jan 18 2006 debian -> ./pub/mirror/debian
+ drwxr-xr-x 10 0 0 4096 Aug 03 09:21 debian-archive
+ lrwxrwxrwx 1 0 0 27 Nov 30 2015 debian-backports -> pub/mirror/debian-backports
+ drwxr-xr-x 12 0 0 4096 Sep 29 13:13 pub
+ -rw-r--r-- 1 0 0 26 Mar 04 2010 robots.txt
+ drwxr-xr-x 8 foo bar 4096 Oct 4 09:05 test
+ drwxr-xr-x 2 foo-user foo-group 0 Jan 5 11:59 240485
+ """
+ )
expected = [
{
@@ -158,25 +161,27 @@ drwxr-xr-x 2 foo-user foo-group 0 Jan 5 11:59 240485
},
]
- parsed = ftp_parse.parse(directory.splitlines())
- self.assertEqual(parsed, expected)
+ parsed = ftp_parse.parse(directory.strip().splitlines())
+ self.assertListEqual(parsed, expected)
@mock.patch("time.localtime")
def test_decode_windowsnt(self, mock_localtime):
mock_localtime.return_value = time2017
- directory = """\
-unparsable line
-11-02-17 02:00AM <DIR> docs
-11-02-17 02:12PM <DIR> images
-11-02-17 02:12PM <DIR> AM to PM
-11-02-17 03:33PM 9276 logo.gif
-05-11-20 22:11 <DIR> src
-11-02-17 01:23 1 12
-11-02-17 4:54 0 icon.bmp
-11-02-17 4:54AM 0 icon.gif
-11-02-17 4:54PM 0 icon.png
-11-02-17 16:54 0 icon.jpg
-"""
+ directory = textwrap.dedent(
+ """
+ unparsable line
+ 11-02-17 02:00AM <DIR> docs
+ 11-02-17 02:12PM <DIR> images
+ 11-02-17 02:12PM <DIR> AM to PM
+ 11-02-17 03:33PM 9276 logo.gif
+ 05-11-20 22:11 <DIR> src
+ 11-02-17 01:23 1 12
+ 11-02-17 4:54 0 icon.bmp
+ 11-02-17 4:54AM 0 icon.gif
+ 11-02-17 4:54PM 0 icon.png
+ 11-02-17 16:54 0 icon.jpg
+ """
+ )
expected = [
{
"basic": {"is_dir": True, "name": "docs"},
@@ -230,5 +235,94 @@ unparsable line
},
]
- parsed = ftp_parse.parse(directory.splitlines())
+ parsed = ftp_parse.parse(directory.strip().splitlines())
self.assertEqual(parsed, expected)
+
+ @mock.patch("time.localtime")
+ def test_decode_linux_suid(self, mock_localtime):
+ # reported in #451
+ mock_localtime.return_value = time2017
+ directory = textwrap.dedent(
+ """
+ drwxr-sr-x 66 ftp ftp 8192 Mar 16 17:54 pub
+ -rw-r--r-- 1 ftp ftp 25 Mar 18 19:34 robots.txt
+ """
+ )
+ expected = [
+ {
+ "access": {
+ "group": "ftp",
+ "permissions": [
+ "g_r",
+ "g_s",
+ "o_r",
+ "o_x",
+ "u_r",
+ "u_w",
+ "u_x",
+ ],
+ "user": "ftp",
+ },
+ "basic": {"is_dir": True, "name": "pub"},
+ "details": {"modified": 1489686840.0, "size": 8192, "type": 1},
+ "ftp": {
+ "ls": "drwxr-sr-x 66 ftp ftp 8192 Mar 16 17:54 pub"
+ },
+ },
+ {
+ "access": {
+ "group": "ftp",
+ "permissions": [
+ "g_r",
+ "o_r",
+ "u_r",
+ "u_w",
+ ],
+ "user": "ftp",
+ },
+ "basic": {"is_dir": False, "name": "robots.txt"},
+ "details": {"modified": 1489865640.0, "size": 25, "type": 2},
+ "ftp": {
+ "ls": "-rw-r--r-- 1 ftp ftp 25 Mar 18 19:34 robots.txt"
+ },
+ },
+ ]
+
+ parsed = ftp_parse.parse(directory.strip().splitlines())
+ self.assertListEqual(parsed, expected)
+
+ @mock.patch("time.localtime")
+ def test_decode_linux_sticky(self, mock_localtime):
+ # reported in #451
+ mock_localtime.return_value = time2017
+ directory = textwrap.dedent(
+ """
+ drwxr-xr-t 66 ftp ftp 8192 Mar 16 17:54 pub
+ """
+ )
+ expected = [
+ {
+ "access": {
+ "group": "ftp",
+ "permissions": [
+ "g_r",
+ "g_x",
+ "o_r",
+ "o_t",
+ "u_r",
+ "u_w",
+ "u_x",
+ ],
+ "user": "ftp",
+ },
+ "basic": {"is_dir": True, "name": "pub"},
+ "details": {"modified": 1489686840.0, "size": 8192, "type": 1},
+ "ftp": {
+ "ls": "drwxr-xr-t 66 ftp ftp 8192 Mar 16 17:54 pub"
+ },
+ },
+ ]
+
+ self.maxDiff = None
+ parsed = ftp_parse.parse(directory.strip().splitlines())
+ self.assertListEqual(parsed, expected)
| FTPFS does not list certain folders
It seems that the pub folder is not listed and igrnoed. ftplib does show the folder. This is with python 3.8.
```python
import fs
fs.__version__
# 2.4.12
from fs.ftpfs import FTPFS
a = FTP(host='ftp.ensemblgenomes.org', user="anonymous", passwd="")
a.dir()
""""
drwxr-sr-x 72 ftp ftp 8192 Feb 16 02:00 pub
-rw-r--r-- 1 ftp ftp 25 Jan 06 22:41 robots.txt
""""
from ftplib import FTP
a = FTPFS(host='ftp.ensemblgenomes.org')
a.listdir('.')
# ['robots.txt']
``` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_ftp_parse.py::TestFTPParse::test_decode_linux_sticky",
"tests/test_ftp_parse.py::TestFTPParse::test_decode_linux_suid"
] | [
"tests/test_ftp_parse.py::TestFTPParse::test_decode_linux",
"tests/test_ftp_parse.py::TestFTPParse::test_decode_windowsnt",
"tests/test_ftp_parse.py::TestFTPParse::test_parse",
"tests/test_ftp_parse.py::TestFTPParse::test_parse_line",
"tests/test_ftp_parse.py::TestFTPParse::test_parse_time"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2021-03-26T18:30:40Z" | mit |
|
PyFilesystem__pyfilesystem2-474 | diff --git a/CHANGELOG.md b/CHANGELOG.md
index aacded9..62cc085 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,6 +13,8 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
- Added FTP over TLS (FTPS) support to FTPFS.
Closes [#437](https://github.com/PyFilesystem/pyfilesystem2/issues/437),
[#449](https://github.com/PyFilesystem/pyfilesystem2/pull/449).
+- `PathError` now supports wrapping an exception using the `exc` argument.
+ Closes [#453](https://github.com/PyFilesystem/pyfilesystem2/issues/453).
### Changed
diff --git a/fs/errors.py b/fs/errors.py
index 25625e2..2448c7a 100644
--- a/fs/errors.py
+++ b/fs/errors.py
@@ -139,13 +139,14 @@ class PathError(FSError):
default_message = "path '{path}' is invalid"
- def __init__(self, path, msg=None): # noqa: D107
- # type: (Text, Optional[Text]) -> None
+ def __init__(self, path, msg=None, exc=None): # noqa: D107
+ # type: (Text, Optional[Text], Optional[Exception]) -> None
self.path = path
+ self.exc = exc
super(PathError, self).__init__(msg=msg)
def __reduce__(self):
- return type(self), (self.path, self._msg)
+ return type(self), (self.path, self._msg, self.exc)
class NoSysPath(PathError):
| PyFilesystem/pyfilesystem2 | 60b0a6347e3bbcee4a2a6261a5e1b3166c45e192 | diff --git a/tests/test_error_tools.py b/tests/test_error_tools.py
index b9ac25c..4f6aa32 100644
--- a/tests/test_error_tools.py
+++ b/tests/test_error_tools.py
@@ -3,13 +3,23 @@ from __future__ import unicode_literals
import errno
import unittest
+import fs.errors
from fs.error_tools import convert_os_errors
-from fs import errors as fserrors
class TestErrorTools(unittest.TestCase):
- def assert_convert_os_errors(self):
+ def test_convert_enoent(self):
+ exception = OSError(errno.ENOENT, "resource not found")
+ with self.assertRaises(fs.errors.ResourceNotFound) as ctx:
+ with convert_os_errors("stat", "/tmp/test"):
+ raise exception
+ self.assertEqual(ctx.exception.exc, exception)
+ self.assertEqual(ctx.exception.path, "/tmp/test")
- with self.assertRaises(fserrors.ResourceNotFound):
- with convert_os_errors("foo", "test"):
- raise OSError(errno.ENOENT)
+ def test_convert_enametoolong(self):
+ exception = OSError(errno.ENAMETOOLONG, "File name too long: test")
+ with self.assertRaises(fs.errors.PathError) as ctx:
+ with convert_os_errors("stat", "/tmp/test"):
+ raise exception
+ self.assertEqual(ctx.exception.exc, exception)
+ self.assertEqual(ctx.exception.path, "/tmp/test")
| convert_os_errors error when converting errno.ENAMETOOLONG to PathError
Using convert_os_errors to convert errno.ENAMETOOLONG to PathError results in unexpected keyword arguement 'exc' error. Seems that [this line](https://github.com/PyFilesystem/pyfilesystem2/blob/8784fd61797fac654511f16fd50c38c8a1675f16/fs/error_tools.py#L89) will set exc=exc_value however PathError does not take in exc parameter.
The following example code:
```
import errno
from fs.error_tools import convert_os_errors
from fs import errors as fserrors
try:
from fs import open_fs
f = open_fs('/tmp')
f.open('x'*500, mode='w')
except OSError as e:
with convert_os_errors("foo", "test"):
raise e
```
results in: TypeError: __init__() got an unexpected keyword argument 'exc' | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_error_tools.py::TestErrorTools::test_convert_enametoolong"
] | [
"tests/test_error_tools.py::TestErrorTools::test_convert_enoent"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
} | "2021-03-27T02:24:49Z" | mit |
|
PyFstat__PyFstat-489 | diff --git a/docs/source/pyfstat.utils.rst b/docs/source/pyfstat.utils.rst
index 260c2a7..1465894 100644
--- a/docs/source/pyfstat.utils.rst
+++ b/docs/source/pyfstat.utils.rst
@@ -7,7 +7,7 @@ Most of these are used internally by other parts of the package
and are of interest mostly only for developers,
but others can also be helpful for end users.
-Functions in these modules can be directly acessed via ``pyfstat.utils``
+Functions in these modules can be directly accessed via ``pyfstat.utils``
without explicitly mentioning the specific module in where they reside.
(E.g. just call ``pyfstat.utils.some_function``,
not ``pyfstat.utils.some_topic.some_function``.)
@@ -15,6 +15,14 @@ not ``pyfstat.utils.some_topic.some_function``.)
Submodules
----------
+pyfstat.utils.atoms module
+--------------------------
+
+.. automodule:: pyfstat.utils.atoms
+ :members:
+ :undoc-members:
+ :show-inheritance:
+
pyfstat.utils.cli module
------------------------
diff --git a/pyfstat/core.py b/pyfstat/core.py
index 9f0b3f1..023ec12 100644
--- a/pyfstat/core.py
+++ b/pyfstat/core.py
@@ -1317,19 +1317,10 @@ class ComputeFstat(BaseSearchClass):
# and return the maximum of that?
idx_maxTwoF = self.FstatMap.get_maxF_idx()
for X in range(self.FstatResults.numDetectors):
- # For each detector, we need to build a MultiFstatAtomVector
- # because that's what the Fstat map function expects.
- singleIFOmultiFatoms = lalpulsar.CreateMultiFstatAtomVector(1)
- # The first [0] index on the multiFatoms here is over frequency bins;
+ # The [0] index on the multiFatoms here is over frequency bins;
# we always operate on a single bin.
- singleIFOmultiFatoms.data[0] = lalpulsar.CreateFstatAtomVector(
- self.FstatResults.multiFatoms[0].data[X].length
- )
- singleIFOmultiFatoms.data[0].TAtom = (
- self.FstatResults.multiFatoms[0].data[X].TAtom
- )
- singleIFOmultiFatoms.data[0].data = (
- self.FstatResults.multiFatoms[0].data[X].data
+ singleIFOmultiFatoms = utils.extract_singleIFOmultiFatoms_from_multiAtoms(
+ self.FstatResults.multiFatoms[0], X
)
FXstatMap, timingFXstatMap = tcw.call_compute_transient_fstat_map(
self.tCWFstatMapVersion,
@@ -1987,19 +1978,10 @@ class SemiCoherentSearch(ComputeFstat):
"This function is available only if singleFstats or BSGL options were set."
)
for X in range(self.FstatResults.numDetectors):
- # For each detector, we need to build a MultiFstatAtomVector
- # because that's what the Fstat map function expects.
- singleIFOmultiFatoms = lalpulsar.CreateMultiFstatAtomVector(1)
- # The first [0] index on the multiFatoms here is over frequency bins;
+ # The [0] index on the multiFatoms here is over frequency bins;
# we always operate on a single bin.
- singleIFOmultiFatoms.data[0] = lalpulsar.CreateFstatAtomVector(
- self.FstatResults.multiFatoms[0].data[X].length
- )
- singleIFOmultiFatoms.data[0].TAtom = (
- self.FstatResults.multiFatoms[0].data[X].TAtom
- )
- singleIFOmultiFatoms.data[0].data = (
- self.FstatResults.multiFatoms[0].data[X].data
+ singleIFOmultiFatoms = utils.extract_singleIFOmultiFatoms_from_multiAtoms(
+ self.FstatResults.multiFatoms[0], X
)
FXstatMap = lalpulsar.ComputeTransientFstatMap(
multiFstatAtoms=singleIFOmultiFatoms,
diff --git a/pyfstat/utils/__init__.py b/pyfstat/utils/__init__.py
index 7230235..2161e53 100644
--- a/pyfstat/utils/__init__.py
+++ b/pyfstat/utils/__init__.py
@@ -6,6 +6,7 @@ and are of interest mostly only for developers,
but others can also be helpful for end users.
"""
+from .atoms import copy_FstatAtomVector, extract_singleIFOmultiFatoms_from_multiAtoms
from .cli import match_commandlines, run_commandline
from .converting import (
convert_aPlus_aCross_to_h0_cosi,
diff --git a/pyfstat/utils/atoms.py b/pyfstat/utils/atoms.py
new file mode 100644
index 0000000..39eb2f8
--- /dev/null
+++ b/pyfstat/utils/atoms.py
@@ -0,0 +1,69 @@
+import logging
+
+import lalpulsar
+
+logger = logging.getLogger(__name__)
+
+
+def extract_singleIFOmultiFatoms_from_multiAtoms(
+ multiAtoms: lalpulsar.MultiFstatAtomVector, X: int
+) -> lalpulsar.MultiFstatAtomVector:
+ """Extract a length-1 MultiFstatAtomVector from a larger MultiFstatAtomVector.
+
+ The result is needed as input to ``lalpulsar.ComputeTransientFstatMap`` in some places.
+
+ The new object is freshly allocated,
+ and we do a deep copy of the actual per-timestamp atoms.
+
+ Parameters
+ -------
+ multiAtoms:
+ Fully allocated multi-detector struct of `length > X`.
+ X:
+ The detector index for which to extract atoms.
+ Returns
+ -------
+ singleIFOmultiFatoms:
+ Length-1 MultiFstatAtomVector with only the data for detector `X`.
+ """
+ if X >= multiAtoms.length:
+ raise ValueError(
+ f"Detector index {X} is out of range for multiAtoms of length {multiAtoms.length}."
+ )
+ singleIFOmultiFatoms = lalpulsar.CreateMultiFstatAtomVector(1)
+ singleIFOmultiFatoms.data[0] = lalpulsar.CreateFstatAtomVector(
+ multiAtoms.data[X].length
+ )
+ # we deep-copy the entries of the atoms vector,
+ # since just assigning the whole array can cause a segfault
+ # from memory cleanup in looping over this function
+ copy_FstatAtomVector(singleIFOmultiFatoms.data[0], multiAtoms.data[X])
+ return singleIFOmultiFatoms
+
+
+def copy_FstatAtomVector(
+ dest: lalpulsar.FstatAtomVector, src: lalpulsar.FstatAtomVector
+):
+ """Deep-copy an FstatAtomVector with all its per-SFT FstatAtoms.
+
+ The two vectors must have the same length,
+ and the destination vector must already be allocated.
+
+ Parameters
+ -------
+ dest:
+ The destination vector to copy to.
+ Must already be allocated.
+ Will be modified in-place.
+ src:
+ The source vector to copy from.
+ """
+ if dest.length != src.length:
+ raise ValueError(
+ f"Lengths of destination and source vectors do not match. ({dest.length} != {src.length})"
+ )
+ dest.TAtom = src.TAtom
+ for k in range(dest.length):
+ # this is now copying the actual FstatAtom object,
+ # with its actual data in memory (no more pointers)
+ dest.data[k] = src.data[k]
| PyFstat/PyFstat | c502303284fc4fba4dbe34eee1063d0f75d8b7e5 | diff --git a/tests/test_utils/test_atoms.py b/tests/test_utils/test_atoms.py
new file mode 100644
index 0000000..a425fec
--- /dev/null
+++ b/tests/test_utils/test_atoms.py
@@ -0,0 +1,75 @@
+import lalpulsar
+import pytest
+
+from pyfstat.utils import (
+ copy_FstatAtomVector,
+ extract_singleIFOmultiFatoms_from_multiAtoms,
+)
+
+
[email protected]
+def arbitrary_singleAtoms():
+ single_atoms = lalpulsar.CreateFstatAtomVector(5)
+
+ single_atoms.TAtom = 1800
+
+ for i in range(single_atoms.length):
+
+ for attr in [
+ "timestamp",
+ "a2_alpha",
+ "b2_alpha",
+ "ab_alpha",
+ "Fa_alpha",
+ "Fb_alpha",
+ ]:
+ setattr(single_atoms.data[i], attr, i)
+
+ return single_atoms
+
+
[email protected]
+def arbitrary_multiAtoms(arbitrary_singleAtoms):
+ ma = lalpulsar.CreateMultiFstatAtomVector(1)
+ ma.data[0] = arbitrary_singleAtoms
+ return ma
+
+
+def compare_FstatAtomVector(vectorA, vectorB):
+
+ for attr in ["TAtom", "length"]:
+ assert getattr(vectorA, attr) == getattr(vectorB, attr)
+
+ for i in range(vectorA.length):
+
+ for attr in [
+ "timestamp",
+ "a2_alpha",
+ "b2_alpha",
+ "ab_alpha",
+ "Fa_alpha",
+ "Fb_alpha",
+ ]:
+ assert getattr(vectorA.data[i], attr) == getattr(vectorB.data[i], attr)
+
+
+def test_extract_singleIFOmultiFatoms_from_multiAtoms(
+ arbitrary_singleAtoms, arbitrary_multiAtoms
+):
+
+ single_atoms = extract_singleIFOmultiFatoms_from_multiAtoms(arbitrary_multiAtoms, 0)
+ compare_FstatAtomVector(single_atoms.data[0], arbitrary_multiAtoms.data[0])
+
+ with pytest.raises(ValueError):
+ extract_singleIFOmultiFatoms_from_multiAtoms(arbitrary_multiAtoms, 1)
+
+
+def test_copy_FstatAtomVector(arbitrary_singleAtoms):
+
+ single_atoms = lalpulsar.CreateFstatAtomVector(arbitrary_singleAtoms.length)
+ copy_FstatAtomVector(single_atoms, arbitrary_singleAtoms)
+ compare_FstatAtomVector(single_atoms, arbitrary_singleAtoms)
+
+ faulty_atoms = lalpulsar.CreateFstatAtomVector(arbitrary_singleAtoms.length + 1)
+ with pytest.raises(ValueError):
+ copy_FstatAtomVector(faulty_atoms, arbitrary_singleAtoms)
| segmentation fault from BSGL grid test with recent LALSuite nightlies
**Describe the bug**
see https://github.com/PyFstat/PyFstat/actions/runs/3360239212/jobs/5569188206#step:7:104
The first failing version seems to be `7.10.1.dev20221025`.
Note that the non-BSGL `TestGridSearch::test_semicoherent_grid_search` does **not** segfault.
**Expected behavior**
no segfault
**Environment (please complete the following information):**
- see action setup, but can aso reproduce locally
**To Reproduce**
```
pip install --upgrade --pre lalsuite==7.10.1.dev20221025
pytest tests/test_grid_based_searches.py::TestGridSearchBSGL::test_semicoherent_grid_search
```
**Additional context**
---
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_utils/test_atoms.py::test_extract_singleIFOmultiFatoms_from_multiAtoms",
"tests/test_utils/test_atoms.py::test_copy_FstatAtomVector"
] | [] | {
"failed_lite_validators": [
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2022-11-01T17:07:09Z" | mit |
|
PyMySQL__PyMySQL-1160 | diff --git a/pymysql/connections.py b/pymysql/connections.py
index dc121e1..3a04ddd 100644
--- a/pymysql/connections.py
+++ b/pymysql/connections.py
@@ -765,8 +765,6 @@ class Connection:
dump_packet(recv_data)
buff += recv_data
# https://dev.mysql.com/doc/internals/en/sending-more-than-16mbyte.html
- if bytes_to_read == 0xFFFFFF:
- continue
if bytes_to_read < MAX_PACKET_LEN:
break
diff --git a/pymysql/err.py b/pymysql/err.py
index 3da5b16..dac65d3 100644
--- a/pymysql/err.py
+++ b/pymysql/err.py
@@ -136,7 +136,14 @@ del _map_error, ER
def raise_mysql_exception(data):
errno = struct.unpack("<h", data[1:3])[0]
- errval = data[9:].decode("utf-8", "replace")
+ # https://dev.mysql.com/doc/dev/mysql-server/latest/page_protocol_basic_err_packet.html
+ # Error packet has optional sqlstate that is 5 bytes and starts with '#'.
+ if data[3] == 0x23: # '#'
+ # sqlstate = data[4:9].decode()
+ # TODO: Append (sqlstate) in the error message. This will be come in next minor release.
+ errval = data[9:].decode("utf-8", "replace")
+ else:
+ errval = data[3:].decode("utf-8", "replace")
errorclass = error_map.get(errno)
if errorclass is None:
errorclass = InternalError if errno < 1000 else OperationalError
diff --git a/pyproject.toml b/pyproject.toml
index 1c10b4b..8cd9ddb 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -56,6 +56,8 @@ version = {attr = "pymysql.VERSION_STRING"}
exclude = [
"pymysql/tests/thirdparty",
]
+
+[tool.ruff.lint]
ignore = ["E721"]
[tool.pdm.dev-dependencies]
| PyMySQL/PyMySQL | 9694747ae619e88b792a8e0b4c08036572452584 | diff --git a/pymysql/tests/test_err.py b/pymysql/tests/test_err.py
index 6b54c6d..6eb0f98 100644
--- a/pymysql/tests/test_err.py
+++ b/pymysql/tests/test_err.py
@@ -1,14 +1,16 @@
-import unittest
-
+import pytest
from pymysql import err
-__all__ = ["TestRaiseException"]
-
+def test_raise_mysql_exception():
+ data = b"\xff\x15\x04#28000Access denied"
+ with pytest.raises(err.OperationalError) as cm:
+ err.raise_mysql_exception(data)
+ assert cm.type == err.OperationalError
+ assert cm.value.args == (1045, "Access denied")
-class TestRaiseException(unittest.TestCase):
- def test_raise_mysql_exception(self):
- data = b"\xff\x15\x04#28000Access denied"
- with self.assertRaises(err.OperationalError) as cm:
- err.raise_mysql_exception(data)
- self.assertEqual(cm.exception.args, (1045, "Access denied"))
+ data = b"\xff\x10\x04Too many connections"
+ with pytest.raises(err.OperationalError) as cm:
+ err.raise_mysql_exception(data)
+ assert cm.type == err.OperationalError
+ assert cm.value.args == (1040, "Too many connections")
| Display log exception when MySQL throws Too many connections exception.
**Describe the bug**
Display log exception when MySQL throws `Too many connections exception`.
The log: `pymysql.err.OperationalError: (1040, 'ny connections')`
**To Reproduce**
MySQL Server
--
Product: | MySQL Community Server (GPL)
Version: | 5.7.23-log
![image](https://github.com/PyMySQL/PyMySQL/assets/7112305/ecdbe475-378d-4fd0-8184-bff36972795b)
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"pymysql/tests/test_err.py::test_raise_mysql_exception"
] | [] | {
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2024-02-02T08:00:38Z" | mit |
|
PyPSA__PyPSA-524 | diff --git a/pypsa/descriptors.py b/pypsa/descriptors.py
index ec33baf9..56d1ac6c 100644
--- a/pypsa/descriptors.py
+++ b/pypsa/descriptors.py
@@ -368,7 +368,7 @@ def get_active_assets(n, c, investment_period):
if period not in n.investment_periods:
raise ValueError("Investment period not in `network.investment_periods`")
active[period] = n.df(c).eval("build_year <= @period < build_year + lifetime")
- return pd.DataFrame(active).any(1)
+ return pd.DataFrame(active).any(axis=1)
def get_activity_mask(n, c, sns=None, index=None):
diff --git a/pypsa/optimization/global_constraints.py b/pypsa/optimization/global_constraints.py
index a05515fd..e51a8ab8 100644
--- a/pypsa/optimization/global_constraints.py
+++ b/pypsa/optimization/global_constraints.py
@@ -17,6 +17,71 @@ from pypsa.descriptors import nominal_attrs
logger = logging.getLogger(__name__)
+def define_tech_capacity_expansion_limit(n, sns):
+ """
+ Defines per-carrier and potentially per-bus capacity expansion limits.
+
+ Parameters
+ ----------
+ n : pypsa.Network
+ sns : list-like
+ Set of snapshots to which the constraint should be applied.
+
+ Returns
+ -------
+ None.
+ """
+ m = n.model
+ glcs = n.global_constraints.loc[
+ lambda df: df.type == "tech_capacity_expansion_limit"
+ ]
+
+ for (carrier, sense, period), glcs_group in glcs.groupby(
+ ["carrier_attribute", "sense", "investment_period"]
+ ):
+ period = None if isnan(period) else int(period)
+ sign = "=" if sense == "==" else sense
+ busdim = f"Bus-{carrier}-{period}"
+ lhs_per_bus = []
+
+ for c, attr in nominal_attrs.items():
+ var = f"{c}-{attr}"
+ dim = f"{c}-ext"
+ df = n.df(c)
+
+ if c not in n.one_port_components or "carrier" not in df:
+ continue
+
+ ext_i = (
+ n.get_extendable_i(c)
+ .intersection(df.index[df.carrier == carrier])
+ .rename(dim)
+ )
+ if period is not None:
+ ext_i = ext_i[n.get_active_assets(c, period)[ext_i]]
+
+ if ext_i.empty:
+ continue
+
+ busmap = df.loc[ext_i, "bus"].rename(busdim).to_xarray()
+ expr = m[var].loc[ext_i].groupby_sum(busmap)
+ lhs_per_bus.append(expr)
+
+ if not lhs_per_bus:
+ continue
+
+ lhs_per_bus = merge(lhs_per_bus)
+
+ for name, glc in glcs_group.iterrows():
+ bus = glc.get("bus")
+ if bus is None:
+ lhs = lhs_per_bus.sum(busdim)
+ else:
+ lhs = lhs_per_bus.sel(**{busdim: str(bus)}, drop=True)
+
+ n.model.add_constraints(lhs, sign, glc.constant, f"GlobalConstraint-{name}")
+
+
def define_nominal_constraints_per_bus_carrier(n, sns):
"""
Set an capacity expansion limit for assets of the same carrier at the same
@@ -38,10 +103,11 @@ def define_nominal_constraints_per_bus_carrier(n, sns):
"""
m = n.model
cols = n.buses.columns[n.buses.columns.str.startswith("nom_")]
+ buses = n.buses.index[n.buses[cols].notnull().any(axis=1)].rename("Bus-nom_min_max")
for col in cols:
msg = (
- f"Bus column '{col}' has invalid specifaction and cannot be "
+ f"Bus column '{col}' has invalid specification and cannot be "
"interpreted as constraint, must match the pattern "
"`nom_{min/max}_{carrier}` or `nom_{min/max}_{carrier}_{period}`"
)
@@ -51,42 +117,51 @@ def define_nominal_constraints_per_bus_carrier(n, sns):
sign = "<="
else:
logger.warn(msg)
+ continue
remainder = col[len("nom_max_") :]
if remainder in n.carriers.index:
carrier = remainder
period = None
- elif not isinstance(n.snapshots, pd.MultiIndex):
- logger.warn(msg)
- continue
- else:
+ elif isinstance(n.snapshots, pd.MultiIndex):
carrier, period = remainder.rsplit("_", 1)
+ period = int(period)
if carrier not in n.carriers.index or period not in sns.unique("period"):
logger.warn(msg)
continue
+ else:
+ logger.warn(msg)
+ continue
- rhs = n.buses[col]
lhs = []
for c, attr in nominal_attrs.items():
var = f"{c}-{attr}"
dim = f"{c}-ext"
- ext_i = n.get_extendable_i(c)
+ df = n.df(c)
- if c not in n.one_port_components or ext_i.empty:
+ if c not in n.one_port_components or "carrier" not in df:
continue
+ ext_i = (
+ n.get_extendable_i(c)
+ .intersection(df.index[df.carrier == carrier])
+ .rename(dim)
+ )
if period is not None:
- ext_i = ext_i[n.get_active_assets(c, 1)[ext_i]]
+ ext_i = ext_i[n.get_active_assets(c, period)[ext_i]]
+
+ if ext_i.empty:
+ continue
- buses = n.df(c)["bus"][ext_i].rename("Bus").rename_axis(dim).to_xarray()
- expr = m[var].loc[ext_i].groupby_sum(buses)
+ busmap = df.loc[ext_i, "bus"].rename(buses.name).to_xarray()
+ expr = m[var].loc[ext_i].groupby_sum(busmap).reindex({buses.name: buses})
lhs.append(expr)
if not lhs:
continue
lhs = merge(lhs)
- rhs = rhs[lhs.Bus.data]
+ rhs = n.buses.loc[buses, col]
mask = rhs.notnull()
n.model.add_constraints(lhs, sign, rhs, f"Bus-{col}", mask=mask)
diff --git a/pypsa/optimization/optimize.py b/pypsa/optimization/optimize.py
index 6319e3d7..c464ac72 100644
--- a/pypsa/optimization/optimize.py
+++ b/pypsa/optimization/optimize.py
@@ -35,6 +35,7 @@ from pypsa.optimization.global_constraints import (
define_growth_limit,
define_nominal_constraints_per_bus_carrier,
define_primary_energy_limit,
+ define_tech_capacity_expansion_limit,
define_transmission_expansion_cost_limit,
define_transmission_volume_expansion_limit,
)
@@ -225,6 +226,7 @@ def create_model(
define_primary_energy_limit(n, sns)
define_transmission_expansion_cost_limit(n, sns)
define_transmission_volume_expansion_limit(n, sns)
+ define_tech_capacity_expansion_limit(n, sns)
define_nominal_constraints_per_bus_carrier(n, sns)
define_growth_limit(n, sns)
| PyPSA/PyPSA | 0670f3d8bbe744d665585c6619e2b23af997a37f | diff --git a/test/test_lopf_multiinvest.py b/test/test_lopf_multiinvest.py
index 8c85aff4..378881f5 100644
--- a/test/test_lopf_multiinvest.py
+++ b/test/test_lopf_multiinvest.py
@@ -24,6 +24,7 @@ kwargs = dict(multi_investment_periods=True)
def n():
n = pypsa.Network(snapshots=range(10))
n.investment_periods = [2020, 2030, 2040, 2050]
+ n.add("Carrier", "gencarrier")
n.madd("Bus", [1, 2])
for i, period in enumerate(n.investment_periods):
@@ -463,7 +464,7 @@ def test_global_constraint_transmission_cost_limit(n, api):
assert round(lines.eval("s_nom_opt * capital_cost").sum(), 2) == 1000
[email protected]("api", ["native"])
[email protected]("api", ["native", "linopy"])
def test_global_constraint_bus_tech_limit(n, api):
n.add(
"GlobalConstraint",
@@ -488,10 +489,29 @@ def test_global_constraint_bus_tech_limit(n, api):
assert n.global_constraints.at["expansion_limit", "mu"] == 0
[email protected]("api", ["linopy"])
+def test_nominal_constraint_bus_carrier_expansion_limit(n, api):
+ n.buses.at["1", "nom_max_gencarrier"] = 100
+ status, cond = optimize(n, api, **kwargs)
+ gen1s = [f"gen1-{period}" for period in n.investment_periods]
+ assert round(n.generators.p_nom_opt[gen1s], 0).sum() == 100
+ n.buses.drop(["nom_max_gencarrier"], inplace=True, axis=1)
+
+ n.buses.at["1", "nom_max_gencarrier_2020"] = 100
+ status, cond = optimize(n, api, **kwargs)
+ assert n.generators.at["gen1-2020", "p_nom_opt"] == 100
+ n.buses.drop(["nom_max_gencarrier_2020"], inplace=True, axis=1)
+
+ # make the constraint non-binding and check that the shadow price is zero
+ n.buses.at["1", "nom_min_gencarrier_2020"] = 100
+ status, cond = optimize(n, api, **kwargs)
+ assert (n.model.dual["Bus-nom_min_gencarrier_2020"]).item() == 0
+
+
@pytest.mark.parametrize("api", MULTIINVEST_APIS)
def test_max_growth_constraint(n, api):
# test generator grow limit
gen_carrier = n.generators.carrier.unique()[0]
- n.add("Carrier", name="gencarrier", max_growth=218)
+ n.carriers.at[gen_carrier, "max_growth"] = 218
status, cond = optimize(n, api, **kwargs)
assert all(n.generators.p_nom_opt.groupby(n.generators.build_year).sum() <= 218)
| `nom_max_{carrier}` limits all extendable components regardless of carrier
<!-- Please do not post usage questions here. Ask them on the PyPSA mailing list: https://groups.google.com/forum/#!forum/pypsa -->
Will also quickly look into a fix myself today.
Affects new `global_constraints.py` linopy-based implementation.
## Checklist
- [x] I am using the current [`master`](https://github.com/pypsa/pypsa/tree/master) branch or the latest [release](https://github.com/pypsa/pypsa/releases). Please indicate:
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/test_lopf_multiinvest.py::test_tiny_infeasible[native]",
"test/test_lopf_multiinvest.py::test_active_assets",
"test/test_lopf_multiinvest.py::test_tiny_infeasible[linopy]"
] | [
"test/test_lopf_multiinvest.py::test_investment_period_values",
"test/test_lopf_multiinvest.py::test_single_to_multi_level_snapshots"
] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2022-12-19T15:18:55Z" | mit |
|
PyPSA__PyPSA-784 | diff --git a/pypsa/io.py b/pypsa/io.py
index 1fbb37d5..42fe4a65 100644
--- a/pypsa/io.py
+++ b/pypsa/io.py
@@ -653,7 +653,7 @@ def import_from_netcdf(network, path, skip_time=False):
"""
assert has_xarray, "xarray must be installed for netCDF support."
- basename = Path(path).name
+ basename = "" if isinstance(path, xr.Dataset) else Path(path).name
with ImporterNetCDF(path=path) as importer:
_import_from_importer(network, importer, basename=basename, skip_time=skip_time)
| PyPSA/PyPSA | 9df3c7e951438375e0a4e7f4f52fd95cc3daaa7c | diff --git a/test/test_bugs.py b/test/test_bugs.py
index ddb1561a..e517457b 100644
--- a/test/test_bugs.py
+++ b/test/test_bugs.py
@@ -93,3 +93,14 @@ def test_515():
n.lopf(pyomo=False)
assert n.objective == 10
+
+
+def test_779():
+ """
+ Importing from xarray dataset.
+ """
+ n1 = pypsa.Network()
+ n1.add("Bus", "bus")
+ xarr = n1.export_to_netcdf()
+ n2 = pypsa.Network()
+ n2.import_from_netcdf(xarr)
| import_from_netcdf fails when importing from an XArray instance
## Checklist
- [X] I am using the current [`master`](https://github.com/pypsa/pypsa/tree/master) branch or the latest [release](https://github.com/pypsa/pypsa/releases).
## Describe the Bug
The [docs](https://pypsa.readthedocs.io/en/latest/api_reference.html#pypsa.Network.import_from_netcdf) state that `pypsa.Network.import_from_netcdf` should accept an xarray instance:
> import_from_netcdf(path, skip_time=False)
>
> Import network data from netCDF file or xarray Dataset at path.
> - path (string|xr.Dataset) – Path to netCDF dataset or instance of xarray Dataset. The string could be a URL.
However, a TypeError is raised if an XArray instance is passed. Possibly related: #381
## Minimal example:
```python
n1 = pypsa.Network()
xarr = n1.export_to_netcdf()
n2 = pypsa.Network()
n2.import_from_netcdf(xarr)
```
Gives error:
```
TypeError: expected str, bytes or os.PathLike object, not Dataset
```
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/test_bugs.py::test_779"
] | [
"test/test_bugs.py::test_nomansland_bus"
] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_issue_reference"
],
"has_test_patch": true,
"is_lite": false
} | "2023-11-12T19:20:07Z" | mit |
|
PyPSA__linopy-249 | diff --git a/doc/release_notes.rst b/doc/release_notes.rst
index 3e104b1..de2a926 100644
--- a/doc/release_notes.rst
+++ b/doc/release_notes.rst
@@ -1,8 +1,12 @@
Release Notes
=============
-.. Upcoming Version
-.. ----------------
+Upcoming Version
+----------------
+
+**New Features**
+
+* The LinearExpression and QuadraticExpression class have a new attribute `solution` which returns the optimal values of the expression if the underlying model was optimized.
Version 0.3.6
diff --git a/linopy/expressions.py b/linopy/expressions.py
index 477d41f..5709d9a 100644
--- a/linopy/expressions.py
+++ b/linopy/expressions.py
@@ -33,6 +33,7 @@ from linopy.common import (
forward_as_properties,
generate_indices_for_printout,
get_index_map,
+ has_optimized_model,
print_single_expression,
to_dataframe,
)
@@ -605,6 +606,30 @@ class LinearExpression:
def mask(self):
return None
+ @has_optimized_model
+ def _map_solution(self):
+ """
+ Replace variable labels by solution values.
+ """
+ m = self.model
+ sol = pd.Series(m.matrices.sol, m.matrices.vlabels)
+ sol.loc[-1] = np.nan
+ idx = np.ravel(self.vars)
+ values = sol[idx].values.reshape(self.vars.shape)
+ return xr.DataArray(values, dims=self.vars.dims, coords=self.vars.coords)
+
+ @property
+ def solution(self):
+ """
+ Get the optimal values of the expression.
+
+ The function raises an error in case no model is set as a
+ reference or the model is not optimized.
+ """
+ vals = self._map_solution()
+ sol = (self.coeffs * vals).sum(TERM_DIM) + self.const
+ return sol.rename("solution")
+
@classmethod
def _sum(cls, expr: Union["LinearExpression", Dataset], dims=None) -> Dataset:
data = _expr_unwrap(expr)
@@ -1297,6 +1322,18 @@ class QuadraticExpression(LinearExpression):
else:
NotImplemented
+ @property
+ def solution(self):
+ """
+ Get the optimal values of the expression.
+
+ The function raises an error in case no model is set as a
+ reference or the model is not optimized.
+ """
+ vals = self._map_solution()
+ sol = (self.coeffs * vals.prod(FACTOR_DIM)).sum(TERM_DIM) + self.const
+ return sol.rename("solution")
+
@classmethod
def _sum(cls, expr: "QuadraticExpression", dims=None) -> Dataset:
data = _expr_unwrap(expr)
diff --git a/linopy/matrices.py b/linopy/matrices.py
index 911c44f..74cabe4 100644
--- a/linopy/matrices.py
+++ b/linopy/matrices.py
@@ -72,6 +72,16 @@ class MatrixAccessor:
df = self.flat_vars
return create_vector(df.key, df.lower)
+ @cached_property
+ def sol(self):
+ "Vector of solution values of all non-missing variables."
+ if not self._parent.status == "ok":
+ raise ValueError("Model is not optimized.")
+ if "solution" not in self.flat_vars:
+ del self.flat_vars # clear cache
+ df = self.flat_vars
+ return create_vector(df.key, df.solution, fill_value=np.nan)
+
@property
def ub(self):
"Vector of upper bounds of all non-missing variables."
| PyPSA/linopy | 9cb6467e101a80fa0a3fc82d1324dcfd08c868ff | diff --git a/test/test_optimization.py b/test/test_optimization.py
index 0f92598..236892f 100644
--- a/test/test_optimization.py
+++ b/test/test_optimization.py
@@ -340,6 +340,23 @@ def test_default_setting_sol_and_dual_accessor(model, solver, io_api):
assert_equal(c.dual, model.dual["con1"])
[email protected]("solver,io_api", params)
+def test_default_setting_expression_sol_accessor(model, solver, io_api):
+ status, condition = model.solve(solver, io_api=io_api)
+ assert status == "ok"
+ x = model["x"]
+ y = model["y"]
+
+ expr = 4 * x
+ assert_equal(expr.solution, 4 * x.solution)
+
+ qexpr = 4 * x**2
+ assert_equal(qexpr.solution, 4 * x.solution**2)
+
+ qexpr = 4 * x * y
+ assert_equal(qexpr.solution, 4 * x.solution * y.solution)
+
+
@pytest.mark.parametrize("solver,io_api", params)
def test_anonymous_constraint(model, model_anonymous_constraint, solver, io_api):
status, condition = model_anonymous_constraint.solve(solver, io_api=io_api)
@@ -567,10 +584,14 @@ def test_modified_model(modified_model, solver, io_api):
@pytest.mark.parametrize("solver,io_api", params)
def test_masked_variable_model(masked_variable_model, solver, io_api):
masked_variable_model.solve(solver, io_api=io_api)
- assert masked_variable_model.solution.y[-2:].isnull().all()
- assert masked_variable_model.solution.y[:-2].notnull().all()
- assert masked_variable_model.solution.x.notnull().all()
- assert (masked_variable_model.solution.x[-2:] == 10).all()
+ x = masked_variable_model.variables.x
+ y = masked_variable_model.variables.y
+ assert y.solution[-2:].isnull().all()
+ assert y.solution[:-2].notnull().all()
+ assert x.solution.notnull().all()
+ assert (x.solution[-2:] == 10).all()
+ # Squeeze in solution getter for expressions with masked variables
+ assert_equal(x.add(y).solution, x.solution + y.solution.fillna(0))
@pytest.mark.parametrize("solver,io_api", params)
| Add solution values for linear expressions
Variables have computed values in the solution after a successful model solve, but linear expressions do not.
It would be great for solution values to be computed for any linear expressions that are stored in memory at solve time. Or, like Pyomo, to have linear expressions added to the model (`add_linexpr`?) and then have values computed for those expressions on a successful solve. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/test_optimization.py::test_default_setting_expression_sol_accessor[gurobi-lp]",
"test/test_optimization.py::test_default_setting_expression_sol_accessor[highs-lp]",
"test/test_optimization.py::test_default_setting_expression_sol_accessor[gurobi-mps]",
"test/test_optimization.py::test_default_setting_expression_sol_accessor[highs-mps]",
"test/test_optimization.py::test_default_setting_expression_sol_accessor[gurobi-direct]",
"test/test_optimization.py::test_default_setting_expression_sol_accessor[highs-direct]",
"test/test_optimization.py::test_masked_variable_model[gurobi-lp]",
"test/test_optimization.py::test_masked_variable_model[highs-lp]",
"test/test_optimization.py::test_masked_variable_model[gurobi-mps]",
"test/test_optimization.py::test_masked_variable_model[highs-mps]",
"test/test_optimization.py::test_masked_variable_model[gurobi-direct]",
"test/test_optimization.py::test_masked_variable_model[highs-direct]"
] | [
"test/test_optimization.py::test_model_types",
"test/test_optimization.py::test_default_setting[gurobi-lp]",
"test/test_optimization.py::test_default_setting[highs-lp]",
"test/test_optimization.py::test_default_setting[gurobi-mps]",
"test/test_optimization.py::test_default_setting[highs-mps]",
"test/test_optimization.py::test_default_setting[gurobi-direct]",
"test/test_optimization.py::test_default_setting[highs-direct]",
"test/test_optimization.py::test_default_setting_sol_and_dual_accessor[gurobi-lp]",
"test/test_optimization.py::test_default_setting_sol_and_dual_accessor[highs-lp]",
"test/test_optimization.py::test_default_setting_sol_and_dual_accessor[gurobi-mps]",
"test/test_optimization.py::test_default_setting_sol_and_dual_accessor[highs-mps]",
"test/test_optimization.py::test_default_setting_sol_and_dual_accessor[gurobi-direct]",
"test/test_optimization.py::test_default_setting_sol_and_dual_accessor[highs-direct]",
"test/test_optimization.py::test_anonymous_constraint[gurobi-lp]",
"test/test_optimization.py::test_anonymous_constraint[highs-lp]",
"test/test_optimization.py::test_anonymous_constraint[gurobi-mps]",
"test/test_optimization.py::test_anonymous_constraint[highs-mps]",
"test/test_optimization.py::test_anonymous_constraint[gurobi-direct]",
"test/test_optimization.py::test_anonymous_constraint[highs-direct]",
"test/test_optimization.py::test_model_maximization[gurobi-lp]",
"test/test_optimization.py::test_model_maximization[highs-lp]",
"test/test_optimization.py::test_model_maximization[gurobi-direct]",
"test/test_optimization.py::test_default_settings_chunked[gurobi-lp]",
"test/test_optimization.py::test_default_settings_chunked[highs-lp]",
"test/test_optimization.py::test_default_settings_chunked[gurobi-mps]",
"test/test_optimization.py::test_default_settings_chunked[highs-mps]",
"test/test_optimization.py::test_default_settings_chunked[gurobi-direct]",
"test/test_optimization.py::test_default_settings_chunked[highs-direct]",
"test/test_optimization.py::test_solver_options[gurobi-lp]",
"test/test_optimization.py::test_solver_options[highs-lp]",
"test/test_optimization.py::test_solver_options[gurobi-mps]",
"test/test_optimization.py::test_solver_options[highs-mps]",
"test/test_optimization.py::test_solver_options[gurobi-direct]",
"test/test_optimization.py::test_solver_options[highs-direct]",
"test/test_optimization.py::test_duplicated_variables[gurobi-lp]",
"test/test_optimization.py::test_duplicated_variables[highs-lp]",
"test/test_optimization.py::test_duplicated_variables[gurobi-mps]",
"test/test_optimization.py::test_duplicated_variables[highs-mps]",
"test/test_optimization.py::test_duplicated_variables[gurobi-direct]",
"test/test_optimization.py::test_duplicated_variables[highs-direct]",
"test/test_optimization.py::test_non_aligned_variables[gurobi-lp]",
"test/test_optimization.py::test_non_aligned_variables[highs-lp]",
"test/test_optimization.py::test_non_aligned_variables[gurobi-mps]",
"test/test_optimization.py::test_non_aligned_variables[highs-mps]",
"test/test_optimization.py::test_non_aligned_variables[gurobi-direct]",
"test/test_optimization.py::test_non_aligned_variables[highs-direct]",
"test/test_optimization.py::test_set_files[gurobi-lp]",
"test/test_optimization.py::test_set_files[highs-lp]",
"test/test_optimization.py::test_set_files[gurobi-mps]",
"test/test_optimization.py::test_set_files[highs-mps]",
"test/test_optimization.py::test_set_files[gurobi-direct]",
"test/test_optimization.py::test_set_files[highs-direct]",
"test/test_optimization.py::test_set_files_and_keep_files[gurobi-lp]",
"test/test_optimization.py::test_set_files_and_keep_files[highs-lp]",
"test/test_optimization.py::test_set_files_and_keep_files[gurobi-mps]",
"test/test_optimization.py::test_set_files_and_keep_files[highs-mps]",
"test/test_optimization.py::test_set_files_and_keep_files[gurobi-direct]",
"test/test_optimization.py::test_set_files_and_keep_files[highs-direct]",
"test/test_optimization.py::test_infeasible_model[gurobi-lp]",
"test/test_optimization.py::test_infeasible_model[highs-lp]",
"test/test_optimization.py::test_infeasible_model[gurobi-mps]",
"test/test_optimization.py::test_infeasible_model[highs-mps]",
"test/test_optimization.py::test_infeasible_model[gurobi-direct]",
"test/test_optimization.py::test_infeasible_model[highs-direct]",
"test/test_optimization.py::test_model_with_inf[gurobi-lp]",
"test/test_optimization.py::test_model_with_inf[highs-lp]",
"test/test_optimization.py::test_model_with_inf[gurobi-mps]",
"test/test_optimization.py::test_model_with_inf[highs-mps]",
"test/test_optimization.py::test_model_with_inf[gurobi-direct]",
"test/test_optimization.py::test_model_with_inf[highs-direct]",
"test/test_optimization.py::test_milp_binary_model[gurobi-lp]",
"test/test_optimization.py::test_milp_binary_model[highs-lp]",
"test/test_optimization.py::test_milp_binary_model[gurobi-mps]",
"test/test_optimization.py::test_milp_binary_model[highs-mps]",
"test/test_optimization.py::test_milp_binary_model[gurobi-direct]",
"test/test_optimization.py::test_milp_binary_model[highs-direct]",
"test/test_optimization.py::test_milp_binary_model_r[gurobi-lp]",
"test/test_optimization.py::test_milp_binary_model_r[highs-lp]",
"test/test_optimization.py::test_milp_binary_model_r[gurobi-mps]",
"test/test_optimization.py::test_milp_binary_model_r[highs-mps]",
"test/test_optimization.py::test_milp_binary_model_r[gurobi-direct]",
"test/test_optimization.py::test_milp_binary_model_r[highs-direct]",
"test/test_optimization.py::test_milp_model[gurobi-lp]",
"test/test_optimization.py::test_milp_model[highs-lp]",
"test/test_optimization.py::test_milp_model[gurobi-mps]",
"test/test_optimization.py::test_milp_model[highs-mps]",
"test/test_optimization.py::test_milp_model[gurobi-direct]",
"test/test_optimization.py::test_milp_model[highs-direct]",
"test/test_optimization.py::test_milp_model_r[gurobi-lp]",
"test/test_optimization.py::test_milp_model_r[highs-lp]",
"test/test_optimization.py::test_milp_model_r[gurobi-mps]",
"test/test_optimization.py::test_milp_model_r[highs-mps]",
"test/test_optimization.py::test_milp_model_r[gurobi-direct]",
"test/test_optimization.py::test_milp_model_r[highs-direct]",
"test/test_optimization.py::test_quadratic_model[gurobi-lp]",
"test/test_optimization.py::test_quadratic_model[highs-lp]",
"test/test_optimization.py::test_quadratic_model[gurobi-mps]",
"test/test_optimization.py::test_quadratic_model[highs-mps]",
"test/test_optimization.py::test_quadratic_model[gurobi-direct]",
"test/test_optimization.py::test_quadratic_model[highs-direct]",
"test/test_optimization.py::test_quadratic_model_cross_terms[gurobi-lp]",
"test/test_optimization.py::test_quadratic_model_cross_terms[highs-lp]",
"test/test_optimization.py::test_quadratic_model_cross_terms[gurobi-mps]",
"test/test_optimization.py::test_quadratic_model_cross_terms[highs-mps]",
"test/test_optimization.py::test_quadratic_model_cross_terms[gurobi-direct]",
"test/test_optimization.py::test_quadratic_model_cross_terms[highs-direct]",
"test/test_optimization.py::test_quadratic_model_wo_constraint[gurobi-lp]",
"test/test_optimization.py::test_quadratic_model_wo_constraint[highs-lp]",
"test/test_optimization.py::test_quadratic_model_wo_constraint[gurobi-mps]",
"test/test_optimization.py::test_quadratic_model_wo_constraint[highs-mps]",
"test/test_optimization.py::test_quadratic_model_wo_constraint[gurobi-direct]",
"test/test_optimization.py::test_quadratic_model_wo_constraint[highs-direct]",
"test/test_optimization.py::test_quadratic_model_unbounded[gurobi-lp]",
"test/test_optimization.py::test_quadratic_model_unbounded[highs-lp]",
"test/test_optimization.py::test_quadratic_model_unbounded[gurobi-mps]",
"test/test_optimization.py::test_quadratic_model_unbounded[highs-mps]",
"test/test_optimization.py::test_quadratic_model_unbounded[gurobi-direct]",
"test/test_optimization.py::test_quadratic_model_unbounded[highs-direct]",
"test/test_optimization.py::test_modified_model[gurobi-lp]",
"test/test_optimization.py::test_modified_model[highs-lp]",
"test/test_optimization.py::test_modified_model[gurobi-mps]",
"test/test_optimization.py::test_modified_model[highs-mps]",
"test/test_optimization.py::test_modified_model[gurobi-direct]",
"test/test_optimization.py::test_modified_model[highs-direct]",
"test/test_optimization.py::test_masked_constraint_model[gurobi-lp]",
"test/test_optimization.py::test_masked_constraint_model[highs-lp]",
"test/test_optimization.py::test_masked_constraint_model[gurobi-mps]",
"test/test_optimization.py::test_masked_constraint_model[highs-mps]",
"test/test_optimization.py::test_masked_constraint_model[gurobi-direct]",
"test/test_optimization.py::test_masked_constraint_model[highs-direct]",
"test/test_optimization.py::test_basis_and_warmstart[gurobi-lp]",
"test/test_optimization.py::test_basis_and_warmstart[highs-lp]",
"test/test_optimization.py::test_basis_and_warmstart[gurobi-mps]",
"test/test_optimization.py::test_basis_and_warmstart[highs-mps]",
"test/test_optimization.py::test_basis_and_warmstart[gurobi-direct]",
"test/test_optimization.py::test_basis_and_warmstart[highs-direct]",
"test/test_optimization.py::test_solution_fn_parent_dir_doesnt_exist[gurobi-lp]",
"test/test_optimization.py::test_solution_fn_parent_dir_doesnt_exist[highs-lp]",
"test/test_optimization.py::test_solution_fn_parent_dir_doesnt_exist[gurobi-mps]",
"test/test_optimization.py::test_solution_fn_parent_dir_doesnt_exist[highs-mps]",
"test/test_optimization.py::test_solution_fn_parent_dir_doesnt_exist[gurobi-direct]",
"test/test_optimization.py::test_solution_fn_parent_dir_doesnt_exist[highs-direct]",
"test/test_optimization.py::test_non_supported_solver_io[gurobi]",
"test/test_optimization.py::test_non_supported_solver_io[highs]"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2024-03-07T08:01:22Z" | mit |
|
PyThaiNLP__pythainlp-371 | diff --git a/pythainlp/__init__.py b/pythainlp/__init__.py
index 7bccff38..f4fed0d7 100644
--- a/pythainlp/__init__.py
+++ b/pythainlp/__init__.py
@@ -2,26 +2,33 @@
__version__ = "2.2.0-dev0"
thai_consonants = "กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรลวศษสหฬอฮ" # 44 chars
+
thai_vowels = (
- "ฤฦะ\u0e31าำ\u0e34\u0e35\u0e36\u0e37\u0e38\u0e39เแโใไ\u0e45\u0e47" # 19
-)
+ "\u0e24\u0e26\u0e30\u0e31\u0e32\u0e33\u0e34\u0e35\u0e36\u0e37"
+ + "\u0e38\u0e39\u0e40\u0e41\u0e42\u0e43\u0e44\u0e45\u0e4d\u0e47"
+) # 20
+thai_lead_vowels = "\u0e40\u0e41\u0e42\u0e43\u0e44" # 5
+thai_follow_vowels = "\u0e30\u0e32\u0e33\u0e45" # 4
+thai_above_vowels = "\u0e31\u0e34\u0e35\u0e36\u0e37\u0e4d\u0e47" # 7
+thai_below_vowels = "\u0e38\u0e39" # 2
+
thai_tonemarks = "\u0e48\u0e49\u0e4a\u0e4b" # 4
-# Thai Characters: Paiyannoi, Maiyamok, Phinthu, Thanthakhat, Nikhahit, Yamakkan
+# Paiyannoi, Maiyamok, Phinthu, Thanthakhat, Nikhahit, Yamakkan:
# These signs can be part of a word
-thai_signs = "ฯๆ\u0e3a\u0e4c\u0e4d\u0e4e" # 6 chars
+thai_signs = "\u0e2f\u0e3a\u0e46\u0e4c\u0e4d\u0e4e" # 6 chars
# Any Thai character that can be part of a word
thai_letters = "".join(
[thai_consonants, thai_vowels, thai_tonemarks, thai_signs]
-) # 73
+) # 74
-# Thai Characters Fongman, Angkhankhu, Khomut
+# Fongman, Angkhankhu, Khomut:
# These characters are section markers
thai_punctuations = "\u0e4f\u0e5a\u0e5b" # 3 chars
thai_digits = "๐๑๒๓๔๕๖๗๘๙" # 10
-thai_symbols = "฿"
+thai_symbols = "\u0e3f" # Thai Bath ฿
# All Thai characters that presented in Unicode
thai_characters = "".join(
diff --git a/pythainlp/util/normalize.py b/pythainlp/util/normalize.py
index f68d7d25..84138143 100644
--- a/pythainlp/util/normalize.py
+++ b/pythainlp/util/normalize.py
@@ -5,53 +5,44 @@ Text normalization
import re
import warnings
-from pythainlp import thai_tonemarks
-
-_NORMALIZE_RULE1 = [
- "ะ",
- "ั",
- "็",
- "า",
- "ิ",
- "ี",
- "ึ",
- "่",
- "ํ",
- "ุ",
- "ู",
- "ใ",
- "ไ",
- "โ",
- "ื",
- "่",
- "้",
- "๋",
- "๊",
- "ึ",
- "์",
- "๋",
- "ำ",
-] # เก็บพวกสระ วรรณยุกต์ที่ซ้ำกันแล้วมีปัญหา
-
-
-_NORMALIZE_RULE2 = [
- ("เเ", "แ"), # เ เ -> แ
- ("ํา", "ำ"), # นิคหิต + สระอา -> สระอำ
- ("ํ(t)า", "\\1ำ"),
- ("ํา(t)", "\\1ำ"),
- ("([่-๋])([ัิ-ื])", "\\2\\1"),
- ("([่-๋])([ูุ])", "\\2\\1"),
- ("ำ([่-๋])", "\\1ำ"),
- ("(์)([ัิ-ู])", "\\2\\1"),
-] # เก็บพวก พิมพ์ลำดับผิดหรือผิดแป้นแต่กลับแสดงผลถูกต้อง ให้ไปเป็นแป้นที่ถูกต้อง เช่น เ + เ ไปเป็น แ
+from pythainlp import thai_above_vowels as above_v
+from pythainlp import thai_below_vowels as below_v
+from pythainlp import thai_follow_vowels as follow_v
+from pythainlp import thai_lead_vowels as lead_v
+from pythainlp import thai_tonemarks as tonemarks
+
+
+# VOWELS + Phinthu,Thanthakhat, Nikhahit, Yamakkan
+_NO_REPEAT_CHARS = (
+ f"{follow_v}{lead_v}{above_v}{below_v}\u0e3a\u0e4c\u0e4d\u0e4e"
+)
+_NORMALIZE_REPETITION = list(
+ zip([ch + "+" for ch in _NO_REPEAT_CHARS], _NO_REPEAT_CHARS)
+)
+
+_NORMALIZE_REORDER = [
+ ("\u0e40\u0e40", "\u0e41"), # Sara E + Sara E -> Sara Ae
+ (
+ f"([{tonemarks}\u0e4c]+)([{above_v}{below_v}]+)",
+ "\\2\\1",
+ ), # TONE/Thanthakhat+ + A/BVOWELV+ -> A/BVOWEL+ + TONE/Thanthakhat+
+ (
+ f"\u0e4d([{tonemarks}]*)\u0e32",
+ "\\1\u0e33",
+ ), # Nikhahit + TONEMARK* + Sara Aa -> TONEMARK* + Sara Am
+ (
+ f"([{follow_v}]+)([{tonemarks}]+)",
+ "\\2\\1",
+ ), # FOLLOWVOWEL+ + TONEMARK+ -> TONEMARK+ + FOLLOWVOWEL+
+]
def normalize(text: str) -> str:
"""
This function normalize thai text with normalizing rules as follows:
- * Remove redudant symbol of tones and vowels.
- * Subsitute ["เ", "เ"] to "แ".
+ * Remove redundant vowels and tonemarks
+ * Subsitute "เ" + "เ" with "แ"
:param str text: thai text to be normalized
:return: normalized Thai text according to the fules
@@ -71,10 +62,10 @@ def normalize(text: str) -> str:
normalize('นานาาา')
# output: นานา
"""
- for data in _NORMALIZE_RULE2:
- text = re.sub(data[0].replace("t", "[่้๊๋]"), data[1], text)
- for data in list(zip(_NORMALIZE_RULE1, _NORMALIZE_RULE1)):
- text = re.sub(data[0].replace("t", "[่้๊๋]") + "+", data[1], text)
+ for data in _NORMALIZE_REORDER:
+ text = re.sub(data[0], data[1], text)
+ for data in _NORMALIZE_REPETITION:
+ text = re.sub(data[0], data[1], text)
return text
@@ -100,7 +91,7 @@ def delete_tone(text: str) -> str:
delete_tone('สองพันหนึ่งร้อยสี่สิบเจ็ดล้านสี่แสนแปดหมื่นสามพันหกร้อยสี่สิบเจ็ด')
# output: สองพันหนึงรอยสีสิบเจ็ดลานสีแสนแปดหมืนสามพันหกรอยสีสิบเจ็ด
"""
- chars = [ch for ch in text if ch not in thai_tonemarks]
+ chars = [ch for ch in text if ch not in tonemarks]
return "".join(chars)
| PyThaiNLP/pythainlp | 94830ccd0deeb959a2f3d426be07772d4e414ff8 | diff --git a/tests/test_util.py b/tests/test_util.py
index 3ba011e3..585a29e9 100644
--- a/tests/test_util.py
+++ b/tests/test_util.py
@@ -255,9 +255,30 @@ class TestUtilPackage(unittest.TestCase):
self.assertEqual(deletetone("จิ้น"), delete_tone("จิ้น"))
def test_normalize(self):
+ self.assertIsNotNone(normalize("พรรค์จันทร์ab์"))
+
+ # sara e + sara e
self.assertEqual(normalize("เเปลก"), "แปลก")
+
+ # consonant + follow vowel + tonemark
+ self.assertEqual(normalize("\u0e01\u0e30\u0e48"), "\u0e01\u0e48\u0e30")
+
+ # consonant + nikhahit + sara aa
self.assertEqual(normalize("นํา"), "นำ")
- self.assertIsNotNone(normalize("พรรค์จันทร์ab์"))
+ self.assertEqual(normalize("\u0e01\u0e4d\u0e32"), "\u0e01\u0e33")
+
+ # consonant + nikhahit + tonemark + sara aa
+ self.assertEqual(
+ normalize("\u0e01\u0e4d\u0e48\u0e32"), "\u0e01\u0e48\u0e33"
+ )
+
+ # consonant + tonemark + nikhahit + sara aa
+ self.assertEqual(
+ normalize("\u0e01\u0e48\u0e4d\u0e32"), "\u0e01\u0e48\u0e33"
+ )
+
+ # consonant + follow vowel + tonemark
+ self.assertEqual(normalize("\u0e01\u0e32\u0e48"), "\u0e01\u0e48\u0e32")
# ### pythainlp.util.thai
@@ -329,13 +350,16 @@ class TestUtilPackage(unittest.TestCase):
now + datetime.timedelta(days=0), thai_day2datetime("วันนี้", now)
)
self.assertEqual(
- now + datetime.timedelta(days=1), thai_day2datetime("พรุ่งนี้", now)
+ now + datetime.timedelta(days=1),
+ thai_day2datetime("พรุ่งนี้", now),
)
self.assertEqual(
- now + datetime.timedelta(days=2), thai_day2datetime("มะรืนนี้", now)
+ now + datetime.timedelta(days=2),
+ thai_day2datetime("มะรืนนี้", now),
)
self.assertEqual(
- now + datetime.timedelta(days=-1), thai_day2datetime("เมื่อวาน", now)
+ now + datetime.timedelta(days=-1),
+ thai_day2datetime("เมื่อวาน", now),
)
self.assertEqual(
now + datetime.timedelta(days=-2), thai_day2datetime("วานซืน", now)
| Generalized reorder rules in text normalization
- Generalized `Nikhahit + Tonemark + Sara A` case to also cover `Nikhahit + Sara A`
- New rule: `Nikhahit + TONEMARK* + Sara Aa -> TONEMARK* + Sara Am`
- Generalized `Sara Am + Tonemark` case to also cover follow vowels
- New rule: `FOLLOWVOWEL+ + TONEMARK+ -> TONEMARK+ + FOLLOWVOWEL+`
- Generalized `Thanthakhat + Above/Follow vowel` and `Tonemark + Above/Follow vowel`
- New rule: `TONE/Thanthakhat+ + A/BVOWELV+ -> A/BVOWEL+ + TONE/Thanthakhat+`
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_util.py::TestUtilPackage::test_normalize"
] | [
"tests/test_util.py::TestUtilPackage::test_collate",
"tests/test_util.py::TestUtilPackage::test_countthai",
"tests/test_util.py::TestUtilPackage::test_date",
"tests/test_util.py::TestUtilPackage::test_delete_tone",
"tests/test_util.py::TestUtilPackage::test_is_native_thai",
"tests/test_util.py::TestUtilPackage::test_isthai",
"tests/test_util.py::TestUtilPackage::test_isthaichar",
"tests/test_util.py::TestUtilPackage::test_keyboard",
"tests/test_util.py::TestUtilPackage::test_keywords",
"tests/test_util.py::TestUtilPackage::test_number",
"tests/test_util.py::TestUtilPackage::test_rank",
"tests/test_util.py::TestUtilPackage::test_thai_day2datetime",
"tests/test_util.py::TestUtilPackage::test_thai_strftime",
"tests/test_util.py::TestUtilPackage::test_thai_time",
"tests/test_util.py::TestUtilPackage::test_thai_time2time"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2020-03-26T04:54:40Z" | apache-2.0 |
|
PyThaiNLP__pythainlp-389 | diff --git a/docs/api/util.rst b/docs/api/util.rst
index 4d41da6d..9a90e1c5 100644
--- a/docs/api/util.rst
+++ b/docs/api/util.rst
@@ -24,6 +24,10 @@ Modules
.. autofunction:: num_to_thaiword
.. autofunction:: rank
.. autofunction:: reign_year_to_ad
+.. autofunction:: remove_dangling
+.. autofunction:: remove_dup_spaces
+.. autofunction:: remove_tonemark
+.. autofunction:: remove_zw
.. autofunction:: thai_time
.. autofunction:: text_to_arabic_digit
.. autofunction:: text_to_thai_digit
diff --git a/pythainlp/util/__init__.py b/pythainlp/util/__init__.py
index d52a6e1e..d91ea38f 100644
--- a/pythainlp/util/__init__.py
+++ b/pythainlp/util/__init__.py
@@ -22,6 +22,10 @@ __all__ = [
"num_to_thaiword",
"rank",
"reign_year_to_ad",
+ "remove_dangling",
+ "remove_dup_spaces",
+ "remove_tonemark",
+ "remove_zw",
"text_to_arabic_digit",
"text_to_thai_digit",
"thai_digit_to_arabic_digit",
@@ -49,7 +53,14 @@ from pythainlp.util.digitconv import (
)
from pythainlp.util.keyboard import eng_to_thai, thai_to_eng
from pythainlp.util.keywords import find_keyword, rank
-from pythainlp.util.normalize import delete_tone, normalize
+from pythainlp.util.normalize import (
+ delete_tone,
+ normalize,
+ remove_dangling,
+ remove_dup_spaces,
+ remove_tonemark,
+ remove_zw,
+)
from pythainlp.util.numtoword import bahttext, num_to_thaiword
from pythainlp.util.thai import countthai, isthai, isthaichar
from pythainlp.util.thaiwordcheck import is_native_thai
diff --git a/pythainlp/util/normalize.py b/pythainlp/util/normalize.py
index 86e267c0..92e27fee 100644
--- a/pythainlp/util/normalize.py
+++ b/pythainlp/util/normalize.py
@@ -12,75 +12,99 @@ from pythainlp import thai_lead_vowels as lead_v
from pythainlp import thai_tonemarks as tonemarks
-# VOWELS + Phinthu,Thanthakhat, Nikhahit, Yamakkan
-_NO_REPEAT_CHARS = (
- f"{follow_v}{lead_v}{above_v}{below_v}\u0e3a\u0e4c\u0e4d\u0e4e"
-)
-_NORMALIZE_REPETITION = list(
- zip([ch + "+" for ch in _NO_REPEAT_CHARS], _NO_REPEAT_CHARS)
-)
+_DANGLING_CHARS = f"{above_v}{below_v}{tonemarks}\u0e3a\u0e4c\u0e4d\u0e4e"
+_RE_REMOVE_DANGLINGS = re.compile(f"^[{_DANGLING_CHARS}]+")
-_NORMALIZE_REORDER = [
+_ZERO_WIDTH_CHARS = "\u200b\u200c" # ZWSP, ZWNJ
+
+_REORDER_PAIRS = [
("\u0e40\u0e40", "\u0e41"), # Sara E + Sara E -> Sara Ae
(
f"([{tonemarks}\u0e4c]+)([{above_v}{below_v}]+)",
"\\2\\1",
- ), # TONE/Thanthakhat+ + A/BVOWELV+ -> A/BVOWEL+ + TONE/Thanthakhat+
+ ), # TONE/Thanthakhat + ABV/BLW VOWEL -> ABV/BLW VOWEL + TONE/Thanthakhat
(
f"\u0e4d([{tonemarks}]*)\u0e32",
"\\1\u0e33",
- ), # Nikhahit + TONEMARK* + Sara Aa -> TONEMARK* + Sara Am
+ ), # Nikhahit + TONEMARK + Sara Aa -> TONEMARK + Sara Am
(
f"([{follow_v}]+)([{tonemarks}]+)",
"\\2\\1",
- ), # FOLLOWVOWEL+ + TONEMARK+ -> TONEMARK+ + FOLLOWVOWEL+
+ ), # FOLLOW VOWEL + TONEMARK+ -> TONEMARK + FOLLOW VOWEL
]
+# VOWELS + Phinthu, Thanthakhat, Nikhahit, Yamakkan
+_NOREPEAT_CHARS = (
+ f"{follow_v}{lead_v}{above_v}{below_v}\u0e3a\u0e4c\u0e4d\u0e4e"
+)
+_NOREPEAT_PAIRS = list(
+ zip([f"({ch}[ ]*)+" for ch in _NOREPEAT_CHARS], _NOREPEAT_CHARS)
+)
+
+_RE_TONEMARKS = re.compile(f"[{tonemarks}]+")
-def normalize(text: str) -> str:
+_RE_REMOVE_NEWLINES = re.compile("[ \n]*\n[ \n]*")
+
+
+def _last_char(matchobj): # to be used with _RE_NOREPEAT_TONEMARKS
+ return matchobj.group(0)[-1]
+
+
+def remove_dangling(text: str) -> str:
"""
- This function normalize thai text with normalizing rules as follows:
+ Remove Thai non-base characters at the beginning of text.
- * Remove redundant vowels and tonemarks
- * Subsitute "เ" + "เ" with "แ"
+ This is a common "typo", especially for input field in a form,
+ as these non-base characters can be visually hidden from user
+ who may accidentally typed them in.
- :param str text: thai text to be normalized
- :return: normalized Thai text according to the fules
- :rtype: str
+ A character to be removed should be both:
- :Example:
- ::
+ * tone mark, above vowel, below vowel, or non-base sign AND
+ * located at the beginning of the text
- from pythainlp.util import normalize
+ :param str text: input text
+ :return: text without dangling Thai characters at the beginning
+ :rtype: str
+ """
+ return _RE_REMOVE_DANGLINGS.sub("", text)
- normalize('สระะน้ำ')
- # output: สระน้ำ
- normalize('เเปลก')
- # output: แปลก
+def remove_dup_spaces(text: str) -> str:
+ """
+ Remove duplicate spaces. Replace multiple spaces with one space.
- normalize('นานาาา')
- # output: นานา
+ Multiple newline characters and empty lines will be replaced
+ with one newline character.
+
+ :param str text: input text
+ :return: text without duplicated spaces and newlines
+ :rtype: str
"""
- for data in _NORMALIZE_REORDER:
- text = re.sub(data[0], data[1], text)
- for data in _NORMALIZE_REPETITION:
- text = re.sub(data[0], data[1], text)
+ while " " in text:
+ text = text.replace(" ", " ")
+ text = _RE_REMOVE_NEWLINES.sub("\n", text)
+ text = text.strip()
return text
-def delete_tone(text: str) -> str:
+def remove_tonemark(text: str) -> str:
"""
- This function removes Thai tonemarks from the text.
- There are 4 tonemarks indicating 4 tones as follows:
+ Remove all Thai tone marks from the text.
+
+ Thai script has four tone marks indicating four tones as follows:
* Down tone (Thai: ไม้เอก _่ )
* Falling tone (Thai: ไม้โท _้ )
* High tone (Thai: ไม้ตรี _๊ )
* Rising tone (Thai: ไม้จัตวา _๋ )
- :param str text: text in Thai language
- :return: text without Thai tonemarks
+ Putting wrong tone mark is a common mistake in Thai writing.
+ By removing tone marks from the string, it could be used to
+ for a approximate string matching
+
+ :param str text: input text
+ :return: text without Thai tone marks
:rtype: str
:Example:
@@ -91,5 +115,123 @@ def delete_tone(text: str) -> str:
delete_tone('สองพันหนึ่งร้อยสี่สิบเจ็ดล้านสี่แสนแปดหมื่นสามพันหกร้อยสี่สิบเจ็ด')
# output: สองพันหนึงรอยสีสิบเจ็ดลานสีแสนแปดหมืนสามพันหกรอยสีสิบเจ็ด
"""
- chars = [ch for ch in text if ch not in tonemarks]
- return "".join(chars)
+ for ch in tonemarks:
+ while ch in text:
+ text = text.replace(ch, "")
+ return text
+
+
+def remove_zw(text: str) -> str:
+ """
+ Remove zero-width characters.
+
+ These non-visible characters may cause unexpected result from the
+ user's point of view. Removing them can make string matching more robust.
+
+ Characters to be removed:
+
+ * Zero-width space (ZWSP)
+ * Zero-with non-joiner (ZWJP)
+
+ :param str text: input text
+ :return: text without zero-width characters
+ :rtype: str
+ """
+ for ch in _ZERO_WIDTH_CHARS:
+ while ch in text:
+ text = text.replace(ch, "")
+
+ return text
+
+
+def reorder_vowels(text: str) -> str:
+ """
+ Reorder vowels and tone marks to the standard logical order/spelling.
+
+ Characters in input text will be reordered/transformed,
+ according to these rules:
+
+ * Sara E + Sara E -> Sara Ae
+ * Nikhahit + Sara Aa -> Sara Am
+ * tone mark + non-base vowel -> non-base vowel + tone mark
+ * follow vowel + tone mark -> tone mark + follow vowel
+
+ :param str text: input text
+ :return: text with vowels and tone marks in the standard logical order
+ :rtype: str
+ """
+ for pair in _REORDER_PAIRS:
+ text = re.sub(pair[0], pair[1], text)
+
+ return text
+
+
+def remove_repeat_vowels(text: str) -> str:
+ """
+ Remove repeating vowels, tone marks, and signs.
+
+ This function will call reorder_vowels() first, to make sure that
+ double Sara E will be converted to Sara Ae and not be removed.
+
+ :param str text: input text
+ :return: text without repeating Thai vowels, tone marks, and signs
+ :rtype: str
+ """
+ text = reorder_vowels(text)
+ for pair in _NOREPEAT_PAIRS:
+ text = re.sub(pair[0], pair[1], text)
+
+ # remove repeating tone marks, use last tone mark
+ text = _RE_TONEMARKS.sub(_last_char, text)
+
+ return text
+
+
+def normalize(text: str) -> str:
+ """
+ Normalize and clean Thai text with normalizing rules as follows:
+
+ * Remove zero-width spaces
+ * Remove duplicate spaces
+ * Reorder tone marks and vowels to standard order/spelling
+ * Remove duplicate vowels and signs
+ * Remove duplicate tone marks
+ * Remove dangling non-base characters at the beginning of text
+
+ normalize() simply call remove_zw(), remove_dup_spaces(),
+ remove_repeat_vowels(), and remove_dangling(), in that order.
+
+ If a user wants to customize the selection or the order of rules
+ to be applied, they can choose to call those functions by themselves.
+
+ :param str text: input text
+ :return: normalized text according to the fules
+ :rtype: str
+
+ :Example:
+ ::
+
+ from pythainlp.util import normalize
+
+ normalize('สระะน้ำ')
+ # output: สระน้ำ
+
+ normalize('เเปลก')
+ # output: แปลก
+
+ normalize('นานาาา')
+ # output: นานา
+ """
+ text = remove_zw(text)
+ text = remove_dup_spaces(text)
+ text = remove_repeat_vowels(text)
+ text = remove_dangling(text)
+
+ return text
+
+
+def delete_tone(text: str) -> str:
+ """
+ DEPRECATED: Please use remove_tonemark().
+ """
+ return remove_tonemark(text)
| PyThaiNLP/pythainlp | d1475c2fa7006828b3549d5b7261ca2879915c4e | diff --git a/tests/test_util.py b/tests/test_util.py
index 2f02cea6..cdd020a5 100644
--- a/tests/test_util.py
+++ b/tests/test_util.py
@@ -15,7 +15,6 @@ from pythainlp.util import (
bahttext,
collate,
countthai,
- delete_tone,
dict_trie,
digit_to_text,
eng_to_thai,
@@ -28,6 +27,10 @@ from pythainlp.util import (
num_to_thaiword,
rank,
reign_year_to_ad,
+ remove_dangling,
+ remove_dup_spaces,
+ remove_tonemark,
+ remove_zw,
text_to_arabic_digit,
text_to_thai_digit,
thai_day2datetime,
@@ -272,36 +275,66 @@ class TestUtilPackage(unittest.TestCase):
# ### pythainlp.util.normalize
- def test_delete_tone(self):
- self.assertEqual(delete_tone("จิ้น"), "จิน")
- self.assertEqual(delete_tone("เก๋า"), "เกา")
-
def test_normalize(self):
self.assertIsNotNone(normalize("พรรค์จันทร์ab์"))
# sara e + sara e
self.assertEqual(normalize("เเปลก"), "แปลก")
- # consonant + follow vowel + tonemark
+ # consonant + follow vowel + tone mark
self.assertEqual(normalize("\u0e01\u0e30\u0e48"), "\u0e01\u0e48\u0e30")
# consonant + nikhahit + sara aa
self.assertEqual(normalize("นํา"), "นำ")
self.assertEqual(normalize("\u0e01\u0e4d\u0e32"), "\u0e01\u0e33")
- # consonant + nikhahit + tonemark + sara aa
+ # consonant + nikhahit + tone mark + sara aa
self.assertEqual(
normalize("\u0e01\u0e4d\u0e48\u0e32"), "\u0e01\u0e48\u0e33"
)
- # consonant + tonemark + nikhahit + sara aa
+ # consonant + tone mark + nikhahit + sara aa
self.assertEqual(
normalize("\u0e01\u0e48\u0e4d\u0e32"), "\u0e01\u0e48\u0e33"
)
- # consonant + follow vowel + tonemark
+ # consonant + follow vowel + tone mark
self.assertEqual(normalize("\u0e01\u0e32\u0e48"), "\u0e01\u0e48\u0e32")
+ # repeating following vowels
+ self.assertEqual(normalize("กาา"), "กา")
+ self.assertEqual(normalize("กา า า า"), "กา")
+ self.assertEqual(normalize("กา าาะา"), "กาะา")
+
+ # repeating tone marks
+ self.assertEqual(normalize("\u0e01\u0e48\u0e48"), "\u0e01\u0e48")
+
+ # repeating different ton emarks
+ self.assertEqual(normalize("\u0e01\u0e48\u0e49"), "\u0e01\u0e49")
+ self.assertEqual(
+ normalize("\u0e01\u0e48\u0e49\u0e48\u0e49"), "\u0e01\u0e49"
+ )
+
+ # remove tone mark at the beginning of text
+ self.assertEqual(remove_dangling("\u0e48\u0e01"), "\u0e01")
+ self.assertEqual(remove_dangling("\u0e48\u0e48\u0e01"), "\u0e01")
+ self.assertEqual(remove_dangling("\u0e48\u0e49\u0e01"), "\u0e01")
+ self.assertEqual(remove_dangling("\u0e48\u0e01\u0e48"), "\u0e01\u0e48")
+
+ # remove duplicate spaces
+ self.assertEqual(remove_dup_spaces(" ab c d "), "ab c d")
+ self.assertEqual(remove_dup_spaces("\nab c \n d \n"), "ab c\nd")
+
+ # removing tone marks
+ self.assertEqual(remove_tonemark("จิ้น"), "จิน")
+ self.assertEqual(remove_tonemark("เก๋า"), "เกา")
+
+ # removing zero width chars
+ self.assertEqual(remove_zw("กา\u200b"), "กา")
+ self.assertEqual(remove_zw("ก\u200cา"), "กา")
+ self.assertEqual(remove_zw("\u200bกา"), "กา")
+ self.assertEqual(remove_zw("กา\u200b\u200c\u200b"), "กา")
+
# ### pythainlp.util.thai
def test_countthai(self):
| Text normalization not working in some cases
**Describe the bug**
Text normalization not working in some cases such as `'เค้้้าเดินไปสนามหญา้หนา้บา้น'` output '`เค้้้าเดินไปสนามหญ้าหน้าบ้าน'` and `'พ ุ่มดอกไม้ในสนามหญา้หนา้บา้น'` output `'พ ุ่มดอกไม้ในสนามหญ้าหน้าบ้าน'.`
**To Reproduce**
Steps to reproduce the behavior:
1. `from pythainlp.util import normalize`
2. `normalize('เค้้้าเดินไปสนามหญา้หนา้บา้น')`
2. `normalize('พ ุ่มดอกไม้ในสนามหญา้หนา้บา้น')`
**Desktop (please complete the following information):**
Colab. PyThaiNLP 2.2.0dev0 | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_util.py::TestUtilPackage::test_collate",
"tests/test_util.py::TestUtilPackage::test_countthai",
"tests/test_util.py::TestUtilPackage::test_date",
"tests/test_util.py::TestUtilPackage::test_is_native_thai",
"tests/test_util.py::TestUtilPackage::test_isthai",
"tests/test_util.py::TestUtilPackage::test_isthaichar",
"tests/test_util.py::TestUtilPackage::test_keyboard",
"tests/test_util.py::TestUtilPackage::test_keywords",
"tests/test_util.py::TestUtilPackage::test_normalize",
"tests/test_util.py::TestUtilPackage::test_number",
"tests/test_util.py::TestUtilPackage::test_rank",
"tests/test_util.py::TestUtilPackage::test_thai_day2datetime",
"tests/test_util.py::TestUtilPackage::test_thai_strftime",
"tests/test_util.py::TestUtilPackage::test_thai_time",
"tests/test_util.py::TestUtilPackage::test_thai_time2time",
"tests/test_util.py::TestUtilPackage::test_trie"
] | [] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2020-05-06T18:31:34Z" | apache-2.0 |
|
PyThaiNLP__pythainlp-399 | diff --git a/pythainlp/util/thai.py b/pythainlp/util/thai.py
index 1a78dc32..b141b260 100644
--- a/pythainlp/util/thai.py
+++ b/pythainlp/util/thai.py
@@ -127,7 +127,7 @@ def countthai(text: str, ignore_chars: str = _DEFAULT_IGNORE_CHARS) -> float:
# output: 0.0
"""
if not text or not isinstance(text, str):
- return 0
+ return 0.0
if not ignore_chars:
ignore_chars = ""
@@ -143,4 +143,7 @@ def countthai(text: str, ignore_chars: str = _DEFAULT_IGNORE_CHARS) -> float:
num_count = len(text) - num_ignore
+ if num_count == 0:
+ return 0.0
+
return (num_thai / num_count) * 100
| PyThaiNLP/pythainlp | b50968d9f3100ba701648f15b6a94a80783c75a3 | diff --git a/tests/test_util.py b/tests/test_util.py
index 34d2491e..958fa201 100644
--- a/tests/test_util.py
+++ b/tests/test_util.py
@@ -340,8 +340,11 @@ class TestUtilPackage(unittest.TestCase):
# ### pythainlp.util.thai
def test_countthai(self):
- self.assertEqual(countthai(""), 0)
+ self.assertEqual(countthai(""), 0.0)
+ self.assertEqual(countthai("123"), 0.0)
+ self.assertEqual(countthai("1 2 3"), 0.0)
self.assertEqual(countthai("ประเทศไทย"), 100.0)
+ self.assertEqual(countthai("โรค COVID-19"), 37.5)
self.assertEqual(countthai("(กกต.)", ".()"), 100.0)
self.assertEqual(countthai("(กกต.)", None), 50.0)
| countthai not cover all cases
**Describe the bug**
Input countthai('123') or countthai(' ') or countthai('1 2 3 4') create error instead of zero?
**To Reproduce**
Steps to reproduce the behavior:
1. from pythainlp.util import countthai
2. input either '123' or ' '
**Expected behavior**
it should return zero? | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_util.py::TestUtilPackage::test_countthai"
] | [
"tests/test_util.py::TestUtilPackage::test_collate",
"tests/test_util.py::TestUtilPackage::test_date",
"tests/test_util.py::TestUtilPackage::test_is_native_thai",
"tests/test_util.py::TestUtilPackage::test_isthai",
"tests/test_util.py::TestUtilPackage::test_isthaichar",
"tests/test_util.py::TestUtilPackage::test_keyboard",
"tests/test_util.py::TestUtilPackage::test_keywords",
"tests/test_util.py::TestUtilPackage::test_normalize",
"tests/test_util.py::TestUtilPackage::test_number",
"tests/test_util.py::TestUtilPackage::test_rank",
"tests/test_util.py::TestUtilPackage::test_thai_day2datetime",
"tests/test_util.py::TestUtilPackage::test_thai_strftime",
"tests/test_util.py::TestUtilPackage::test_thai_time",
"tests/test_util.py::TestUtilPackage::test_thai_time2time",
"tests/test_util.py::TestUtilPackage::test_trie"
] | {
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
} | "2020-05-12T21:03:10Z" | apache-2.0 |
|
PyThaiNLP__pythainlp-849 | diff --git a/docs/api/util.rst b/docs/api/util.rst
index d3773a9c..41b635d9 100644
--- a/docs/api/util.rst
+++ b/docs/api/util.rst
@@ -162,6 +162,12 @@ Modules
The `reorder_vowels` function is a text processing utility for reordering vowel characters in Thai text. It is essential for phonetic analysis and pronunciation guides.
+.. autofunction:: rhyme
+ :noindex:
+
+
+ The `rhyme` function is a utility for find rhyme of Thai word.
+
.. autofunction:: sound_syllable
:noindex:
diff --git a/pythainlp/util/__init__.py b/pythainlp/util/__init__.py
index 59c42412..2b2ff40e 100644
--- a/pythainlp/util/__init__.py
+++ b/pythainlp/util/__init__.py
@@ -45,6 +45,7 @@ __all__ = [
"remove_tonemark",
"remove_zw",
"reorder_vowels",
+ "rhyme",
"text_to_arabic_digit",
"text_to_thai_digit",
"thai_digit_to_arabic_digit",
@@ -126,3 +127,4 @@ from pythainlp.util.phoneme import nectec_to_ipa, ipa_to_rtgs, remove_tone_ipa
from pythainlp.util.encoding import tis620_to_utf8
from pythainlp.util import spell_words
from pythainlp.util.abbreviation import abbreviation_to_full_text
+from pythainlp.util.pronounce import rhyme
diff --git a/pythainlp/util/pronounce.py b/pythainlp/util/pronounce.py
new file mode 100644
index 00000000..d1021d67
--- /dev/null
+++ b/pythainlp/util/pronounce.py
@@ -0,0 +1,47 @@
+# -*- coding: utf-8 -*-
+# Copyright (C) 2016-2023 PyThaiNLP Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import List
+
+from pythainlp.corpus import thai_words
+from pythainlp.tokenize import syllable_tokenize
+from pythainlp.khavee import KhaveeVerifier
+
+
+kv = KhaveeVerifier()
+all_thai_words_dict = [
+ i for i in list(thai_words()) if len(syllable_tokenize(i)) == 1
+]
+
+
+def rhyme(word: str) -> List[str]:
+ """
+ Find Thai rhyme
+
+ :param str word: A Thai word
+ :return: All list Thai rhyme words
+ :rtype: List[str]
+
+ :Example:
+ ::
+ from pythainlp.util import rhyme
+
+ print(rhyme("จีบ"))
+ # output: ['กลีบ', 'กีบ', 'ครีบ', ...]
+ """
+ list_sumpus = []
+ for i in all_thai_words_dict:
+ if kv.is_sumpus(word, i) and i != word:
+ list_sumpus.append(i)
+ return sorted(list_sumpus)
| PyThaiNLP/pythainlp | 9aabf579688a9764a1b72da516a5a9b6ee057afa | diff --git a/tests/test_util.py b/tests/test_util.py
index 065f2082..1840e2dc 100644
--- a/tests/test_util.py
+++ b/tests/test_util.py
@@ -36,6 +36,7 @@ from pythainlp.util import (
remove_dup_spaces,
remove_tonemark,
remove_zw,
+ rhyme,
text_to_arabic_digit,
text_to_thai_digit,
thaiword_to_date,
@@ -853,5 +854,9 @@ class TestUtilPackage(unittest.TestCase):
self.assertEqual(spell_word("คน"),['คอ', 'นอ', 'คน'])
self.assertEqual(spell_word("คนดี"),['คอ', 'นอ', 'คน', 'ดอ', 'อี', 'ดี', 'คนดี'])
+ def test_rhyme(self):
+ self.assertIsInstance(rhyme("แมว"), list)
+ self.assertTrue(len(rhyme("แมว")) > 2)
+
# def test_abbreviation_to_full_text(self):
# self.assertIsInstance(abbreviation_to_full_text("รร.ของเราน่าอยู่", list))
| Add Find rhyme to PyThaiNLP
From [our tutorials](https://pythainlp.github.io/tutorials/notebooks/find_all_thai_rhyming_words.html), I will add the `rhyme` function to PyThaiNLP. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_util.py::TestUtilPackage::test_collate",
"tests/test_util.py::TestUtilPackage::test_convert_years",
"tests/test_util.py::TestUtilPackage::test_count_thai_chars",
"tests/test_util.py::TestUtilPackage::test_countthai",
"tests/test_util.py::TestUtilPackage::test_date",
"tests/test_util.py::TestUtilPackage::test_display_thai_char",
"tests/test_util.py::TestUtilPackage::test_emoji_to_thai",
"tests/test_util.py::TestUtilPackage::test_find_keywords",
"tests/test_util.py::TestUtilPackage::test_ipa_to_rtgs",
"tests/test_util.py::TestUtilPackage::test_is_native_thai",
"tests/test_util.py::TestUtilPackage::test_isthai",
"tests/test_util.py::TestUtilPackage::test_isthaichar",
"tests/test_util.py::TestUtilPackage::test_keyboard",
"tests/test_util.py::TestUtilPackage::test_nectec_to_ipa",
"tests/test_util.py::TestUtilPackage::test_normalize",
"tests/test_util.py::TestUtilPackage::test_number",
"tests/test_util.py::TestUtilPackage::test_rank",
"tests/test_util.py::TestUtilPackage::test_remove_tone_ipa",
"tests/test_util.py::TestUtilPackage::test_rhyme",
"tests/test_util.py::TestUtilPackage::test_sound_syllable",
"tests/test_util.py::TestUtilPackage::test_syllable_length",
"tests/test_util.py::TestUtilPackage::test_syllable_open_close_detector",
"tests/test_util.py::TestUtilPackage::test_thai_keyboard_dist",
"tests/test_util.py::TestUtilPackage::test_thai_strftime",
"tests/test_util.py::TestUtilPackage::test_thai_strptime",
"tests/test_util.py::TestUtilPackage::test_thai_word_tone_detector",
"tests/test_util.py::TestUtilPackage::test_thaiword_to_date",
"tests/test_util.py::TestUtilPackage::test_thaiword_to_time",
"tests/test_util.py::TestUtilPackage::test_time_to_thaiword",
"tests/test_util.py::TestUtilPackage::test_tis620_to_utf8",
"tests/test_util.py::TestUtilPackage::test_tone_detector",
"tests/test_util.py::TestUtilPackage::test_trie"
] | [] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks",
"has_added_files",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2023-10-18T06:22:54Z" | apache-2.0 |
|
PyThaiNLP__pythainlp-854 | diff --git a/pythainlp/khavee/core.py b/pythainlp/khavee/core.py
index 26146d10..98daed36 100644
--- a/pythainlp/khavee/core.py
+++ b/pythainlp/khavee/core.py
@@ -22,7 +22,7 @@ class KhaveeVerifier:
KhaveeVerifier: Thai Poetry verifier
"""
- def check_sara(self, word: str)-> str:
+ def check_sara(self, word: str) -> str:
"""
Check the vowels in the Thai word.
@@ -216,13 +216,17 @@ class KhaveeVerifier:
print(kv.check_marttra('สาว'))
# output: 'เกอว'
"""
- if word[-1] == 'ร' and word[-2] in ['ต','ท'] :
+ if word[-1] == 'ร' and word[-2] in ['ต', 'ท']:
word = word[:-1]
word = self.handle_karun_sound_silence(word)
word = remove_tonemark(word)
if 'ำ' in word or ('ํ' in word and 'า' in word) or 'ไ' in word or 'ใ' in word:
return 'กา'
- elif word[-1] in ['า','ะ','ิ','ี','ุ','ู','อ'] or ('ี' in word and 'ย' in word[-1]) or ('ื' in word and 'อ' in word[-1]):
+ elif (
+ word[-1] in ['า', 'ะ', 'ิ', 'ี', 'ุ', 'ู', 'อ'] or
+ ('ี' in word and 'ย' in word[-1]) or
+ ('ื' in word and 'อ' in word[-1])
+ ):
return 'กา'
elif word[-1] in ['ง']:
return 'กง'
@@ -235,11 +239,13 @@ class KhaveeVerifier:
return 'เกย'
elif word[-1] in ['ว']:
return 'เกอว'
- elif word[-1] in ['ก','ข','ค','ฆ']:
+ elif word[-1] in ['ก', 'ข', 'ค', 'ฆ']:
return 'กก'
- elif word[-1] in ['จ','ช','ซ','ฎ','ฏ','ฐ','ฑ','ฒ','ด','ต','ถ','ท','ธ','ศ','ษ','ส'] :
+ elif word[-1] in [
+ 'จ', 'ช', 'ซ', 'ฎ', 'ฏ', 'ฐ', 'ฑ', 'ฒ', 'ด', 'ต', 'ถ', 'ท', 'ธ', 'ศ', 'ษ', 'ส'
+ ]:
return 'กด'
- elif word[-1] in ['ญ',', ณ' ,'น' ,'ร' ,'ล' ,'ฬ']:
+ elif word[-1] in ['ญ', ', ณ', 'น', 'ร', 'ล', 'ฬ']:
return 'กน'
elif word[-1] in ['บ', 'ป', 'พ', 'ฟ', 'ภ']:
return 'กบ'
@@ -249,8 +255,7 @@ class KhaveeVerifier:
else:
return 'Cant find Marttra in this word'
-
- def is_sumpus(self, word1: str,word2: str) -> bool:
+ def is_sumpus(self, word1: str, word2: str) -> bool:
"""
Check the rhyme between two words.
@@ -266,10 +271,10 @@ class KhaveeVerifier:
kv = KhaveeVerifier()
- print(kv.is_sumpus('สรร','อัน'))
+ print(kv.is_sumpus('สรร', 'อัน'))
# output: True
- print(kv.is_sumpus('สรร','แมว'))
+ print(kv.is_sumpus('สรร', 'แมว'))
# output: False
"""
marttra1 = self.check_marttra(word1)
@@ -290,13 +295,27 @@ class KhaveeVerifier:
marttra2 = 'กา'
return bool(marttra1 == marttra2 and sara1 == sara2)
- def check_karu_lahu(self,text):
- if (self.check_marttra(text) != 'กา' or (self.check_marttra(text) == 'กา' and self.check_sara(text) in ['อา','อี', 'อือ', 'อู', 'เอ', 'แอ', 'โอ', 'ออ', 'เออ', 'เอีย', 'เอือ' ,'อัว']) or self.check_sara(text) in ['อำ','ไอ','เอา']) and text not in ['บ่','ณ','ธ','ก็']:
+ def check_karu_lahu(self, text):
+ if (
+ (
+ self.check_marttra(text) != 'กา' or
+ (
+ self.check_marttra(text) == 'กา' and
+ self.check_sara(text) in [
+ 'อา', 'อี', 'อือ', 'อู', 'เอ',
+ 'แอ', 'โอ', 'ออ', 'เออ', 'เอีย',
+ 'เอือ', 'อัว'
+ ]
+ ) or
+ self.check_sara(text) in ['อำ', 'ไอ', 'เอา']
+ ) and
+ text not in ['บ่', 'ณ', 'ธ', 'ก็']
+ ):
return 'karu'
else:
return 'lahu'
- def check_klon(self, text: str,k_type: int=8) -> Union[List[str], str]:
+ def check_klon(self, text: str, k_type: int = 8) -> Union[List[str], str]:
"""
Check the suitability of the poem according to Thai principles.
@@ -312,11 +331,22 @@ class KhaveeVerifier:
kv = KhaveeVerifier()
- print(kv.check_klon('''ฉันชื่อหมูกรอบ ฉันชอบกินไก่ แล้วก็วิ่งไล่ หมาชื่อนํ้าทอง ลคคนเก่ง เอ๋งเอ๋งคะนอง มีคนจับจอง เขาชื่อน้องเธียร''', k_type=4))
+ print(kv.check_klon(
+ 'ฉันชื่อหมูกรอบ ฉันชอบกินไก่ แล้วก็วิ่งไล่ หมาชื่อนํ้าทอง ลคคนเก่ง เอ๋งเอ๋งคะนอง \
+ มีคนจับจอง เขาชื่อน้องเธียร',
+ k_type=4
+ ))
# output: The poem is correct according to the principle.
- print(kv.check_klon('''ฉันชื่อหมูกรอบ ฉันชอบกินไก่ แล้วก็วิ่งไล่ หมาชื่อนํ้าทอง ลคคนเก่ง เอ๋งเอ๋งเสียงหมา มีคนจับจอง เขาชื่อน้องเธียร''',k_type=4))
- # # -> ["Can't find rhyme between paragraphs ('หมา', 'จอง')in paragraph 2", "Can't find rhyme between paragraphs ('หมา', 'ทอง')in paragraph 2"]
+ print(kv.check_klon(
+ 'ฉันชื่อหมูกรอบ ฉันชอบกินไก่ แล้วก็วิ่งไล่ หมาชื่อนํ้าทอง ลคคนเก่ง \
+ เอ๋งเอ๋งเสียงหมา มีคนจับจอง เขาชื่อน้องเธียร',
+ k_type=4
+ ))
+ # output: [
+ "Can't find rhyme between paragraphs ('หมา', 'จอง') in paragraph 2",
+ "Can't find rhyme between paragraphs ('หมา', 'ทอง') in paragraph 2"
+ ]
"""
if k_type == 8:
try:
@@ -327,34 +357,63 @@ class KhaveeVerifier:
list_sumpus_sent3 = []
list_sumpus_sent4 = []
for i, sent in enumerate(text.split()):
- sub_sent = subword_tokenize(sent,engine='dict')
+ sub_sent = subword_tokenize(sent, engine='dict')
if len(sub_sent) > 10:
- error.append('In sentence '+str(i+2)+', there are more than 10 words. '+str(sub_sent))
- if (i+1) % 4 == 1:
+ error.append(
+ 'In sentence ' +
+ str(i + 2) +
+ ', there are more than 10 words. ' +
+ str(sub_sent)
+ )
+ if (i + 1) % 4 == 1:
list_sumpus_sent1.append(sub_sent[-1])
- elif (i+1) % 4 == 2:
- list_sumpus_sent2h.append([sub_sent[1],sub_sent[2],sub_sent[3],sub_sent[4]])
+ elif (i + 1) % 4 == 2:
+ list_sumpus_sent2h.append(
+ [sub_sent[1], sub_sent[2], sub_sent[3], sub_sent[4]]
+ )
list_sumpus_sent2l.append(sub_sent[-1])
- elif (i+1) % 4 == 3:
+ elif (i + 1) % 4 == 3:
list_sumpus_sent3.append(sub_sent[-1])
- elif (i+1) % 4 == 0:
+ elif (i + 1) % 4 == 0:
list_sumpus_sent4.append(sub_sent[-1])
- if len(list_sumpus_sent1) != len(list_sumpus_sent2h) or len(list_sumpus_sent2h) != len(list_sumpus_sent2l) or len(list_sumpus_sent2l) != len(list_sumpus_sent3) or len(list_sumpus_sent3) != len(list_sumpus_sent4) or len(list_sumpus_sent4) != len(list_sumpus_sent1):
+ if (
+ len(list_sumpus_sent1) != len(list_sumpus_sent2h) or
+ len(list_sumpus_sent2h) != len(list_sumpus_sent2l) or
+ len(list_sumpus_sent2l) != len(list_sumpus_sent3) or
+ len(list_sumpus_sent3) != len(list_sumpus_sent4) or
+ len(list_sumpus_sent4) != len(list_sumpus_sent1)
+ ):
return 'The poem does not have 4 complete sentences.'
else:
for i in range(len(list_sumpus_sent1)):
countwrong = 0
for j in list_sumpus_sent2h[i]:
if self.is_sumpus(list_sumpus_sent1[i], j) is False:
- countwrong +=1
- if countwrong > 3:
- error.append('Can\'t find rhyme between paragraphs '+str((list_sumpus_sent1[i],list_sumpus_sent2h[i]))+' in paragraph '+str(i+1))
+ countwrong += 1
+ if countwrong > 3:
+ error.append(
+ 'Can\'t find rhyme between paragraphs ' +
+ str((list_sumpus_sent1[i], list_sumpus_sent2h[i])) +
+ ' in paragraph ' +
+ str(i + 1)
+ )
if self.is_sumpus(list_sumpus_sent2l[i], list_sumpus_sent3[i]) is False:
- # print(sumpus_sent2l,sumpus_sent3)
- error.append('Can\'t find rhyme between paragraphs '+str((list_sumpus_sent2l[i],list_sumpus_sent3[i]))+' in paragraph '+str(i+1))
+ error.append(
+ 'Can\'t find rhyme between paragraphs ' +
+ str((list_sumpus_sent2l[i], list_sumpus_sent3[i])) +
+ ' in paragraph ' +
+ str(i + 1)
+ )
if i > 0:
- if self.is_sumpus(list_sumpus_sent2l[i], list_sumpus_sent4[i-1]) is False:
- error.append('Can\'t find rhyme between paragraphs '+str((list_sumpus_sent2l[i],list_sumpus_sent4[i-1]))+' in paragraph '+str(i+1))
+ if self.is_sumpus(
+ list_sumpus_sent2l[i], list_sumpus_sent4[i - 1]
+ ) is False:
+ error.append(
+ 'Can\'t find rhyme between paragraphs ' +
+ str((list_sumpus_sent2l[i], list_sumpus_sent4[i - 1])) +
+ ' in paragraph ' +
+ str(i + 1)
+ )
if not error:
return 'The poem is correct according to the principle.'
else:
@@ -370,36 +429,61 @@ class KhaveeVerifier:
list_sumpus_sent3 = []
list_sumpus_sent4 = []
for i, sent in enumerate(text.split()):
- sub_sent = subword_tokenize(sent,engine='dict')
+ sub_sent = subword_tokenize(sent, engine='dict')
if len(sub_sent) > 5:
- error.append('In sentence '+str(i+2)+', there are more than 4 words. '+str(sub_sent))
- if (i+1) % 4 == 1:
+ error.append(
+ 'In sentence ' +
+ str(i + 2) +
+ ', there are more than 4 words. ' +
+ str(sub_sent)
+ )
+ if (i + 1) % 4 == 1:
list_sumpus_sent1.append(sub_sent[-1])
- elif (i+1) % 4 == 2:
- # print([sub_sent[1],sub_sent[2]])
- list_sumpus_sent2h.append([sub_sent[1],sub_sent[2]])
+ elif (i + 1) % 4 == 2:
+ list_sumpus_sent2h.append([sub_sent[1], sub_sent[2]])
list_sumpus_sent2l.append(sub_sent[-1])
- elif (i+1) % 4 == 3:
+ elif (i + 1) % 4 == 3:
list_sumpus_sent3.append(sub_sent[-1])
- elif (i+1) % 4 == 0:
+ elif (i + 1) % 4 == 0:
list_sumpus_sent4.append(sub_sent[-1])
- if len(list_sumpus_sent1) != len(list_sumpus_sent2h) or len(list_sumpus_sent2h) != len(list_sumpus_sent2l) or len(list_sumpus_sent2l) != len(list_sumpus_sent3) or len(list_sumpus_sent3) != len(list_sumpus_sent4) or len(list_sumpus_sent4) != len(list_sumpus_sent1):
+ if (
+ len(list_sumpus_sent1) != len(list_sumpus_sent2h) or
+ len(list_sumpus_sent2h) != len(list_sumpus_sent2l) or
+ len(list_sumpus_sent2l) != len(list_sumpus_sent3) or
+ len(list_sumpus_sent3) != len(list_sumpus_sent4) or
+ len(list_sumpus_sent4) != len(list_sumpus_sent1)
+ ):
return 'The poem does not have 4 complete sentences.'
else:
for i in range(len(list_sumpus_sent1)):
countwrong = 0
for j in list_sumpus_sent2h[i]:
- # print(list_sumpus_sent1[i],j)
if self.is_sumpus(list_sumpus_sent1[i], j) is False:
- countwrong +=1
- if countwrong > 1:
- error.append('Can\'t find rhyme between paragraphs '+str((list_sumpus_sent1[i],list_sumpus_sent2h[i]))+'in paragraph '+str(i+1))
+ countwrong += 1
+ if countwrong > 1:
+ error.append(
+ 'Can\'t find rhyme between paragraphs ' +
+ str((list_sumpus_sent1[i], list_sumpus_sent2h[i])) +
+ ' in paragraph ' +
+ str(i + 1)
+ )
if self.is_sumpus(list_sumpus_sent2l[i], list_sumpus_sent3[i]) is False:
- # print(sumpus_sent2l,sumpus_sent3)
- error.append('Can\'t find rhyme between paragraphs '+str((list_sumpus_sent2l[i],list_sumpus_sent3[i]))+'in paragraph '+str(i+1))
+ error.append(
+ 'Can\'t find rhyme between paragraphs ' +
+ str((list_sumpus_sent2l[i], list_sumpus_sent3[i])) +
+ ' in paragraph ' +
+ str(i + 1)
+ )
if i > 0:
- if self.is_sumpus(list_sumpus_sent2l[i], list_sumpus_sent4[i-1]) is False:
- error.append('Can\'t find rhyme between paragraphs '+str((list_sumpus_sent2l[i],list_sumpus_sent4[i-1]))+' in paragraph '+str(i+1))
+ if self.is_sumpus(
+ list_sumpus_sent2l[i], list_sumpus_sent4[i - 1]
+ ) is False:
+ error.append(
+ 'Can\'t find rhyme between paragraphs ' +
+ str((list_sumpus_sent2l[i], list_sumpus_sent4[i - 1])) +
+ ' in paragraph ' +
+ str(i + 1)
+ )
if not error:
return 'The poem is correct according to the principle.'
else:
@@ -410,7 +494,11 @@ class KhaveeVerifier:
else:
return 'Something went wrong. Make sure you enter it in the correct form.'
- def check_aek_too(self, text: Union[List[str], str], dead_syllable_as_aek:bool = False) -> Union[List[bool], List[str], bool, str]:
+ def check_aek_too(
+ self,
+ text: Union[List[str], str],
+ dead_syllable_as_aek: bool = False
+ ) -> Union[List[bool], List[str], bool, str]:
"""
Checker of Thai tonal words
@@ -428,9 +516,9 @@ class KhaveeVerifier:
# การเช็คคำเอกโท
print(kv.check_aek_too('เอง'), kv.check_aek_too('เอ่ง'), kv.check_aek_too('เอ้ง'))
- ## -> False, aek, too
+ # -> False, aek, too
print(kv.check_aek_too(['เอง', 'เอ่ง', 'เอ้ง'])) # ใช้ List ได้เหมือนกัน
- ## -> [False, 'aek', 'too']
+ # -> [False, 'aek', 'too']
"""
diff --git a/pythainlp/khavee/example.py b/pythainlp/khavee/example.py
index d0e0400b..6fd1a7a3 100644
--- a/pythainlp/khavee/example.py
+++ b/pythainlp/khavee/example.py
@@ -4,27 +4,27 @@ kv = core.KhaveeVerifier()
# การเช็คสระ
-print('เออ',kv.check_sara('เมอ'))
+print('เออ', kv.check_sara('เมอ'))
# 'เออ'
# การเช็คมาตราตัวสะกด
-print('เทอว',kv.check_marttra('เทอว'))
+print('เทอว', kv.check_marttra('เทอว'))
# 'เกอว'
# การตรวจสอบคำสำผัสที่ถูกต้อง
-print('สรร อัน',kv.is_sumpus('สรร','อัน'))
+print('สรร อัน', kv.is_sumpus('สรร', 'อัน'))
# True
# การตรวจสอบคำสำผัสที่ผิด
-print('เพื่อน ล้วน',kv.is_sumpus('เพื่อน','ล้วน'))
+print('เพื่อน ล้วน', kv.is_sumpus('เพื่อน', 'ล้วน'))
# False
# การตรวจสอบคำ ครุ ลหุ
-print('สรร',kv.check_karu_lahu('สรร'))
+print('สรร', kv.check_karu_lahu('สรร'))
#karu
# การตรวจสอบคำ ครุ ลหุ
-print('ชิชะ',kv.check_karu_lahu('ชิชะ'))
+print('ชิชะ', kv.check_karu_lahu('ชิชะ'))
# lahu
# การตรวจสอบกลอน 8 ที่ถูกฉันทลักษณ์
| PyThaiNLP/pythainlp | 4f5b0cf2208a3bc94ae36e07b972457e1e634e8b | diff --git a/tests/test_khavee.py b/tests/test_khavee.py
index 92c3452a..2de1b09f 100644
--- a/tests/test_khavee.py
+++ b/tests/test_khavee.py
@@ -13,17 +13,27 @@ class TestKhaveePackage(unittest.TestCase):
self.assertEqual(kv.check_marttra('สาว'), 'เกอว')
def test_is_sumpus(self):
- self.assertTrue(kv.is_sumpus('สรร','อัน'))
- self.assertFalse(kv.is_sumpus('สรร','แมว'))
+ self.assertTrue(kv.is_sumpus('สรร', 'อัน'))
+ self.assertFalse(kv.is_sumpus('สรร', 'แมว'))
def test_check_klon(self):
self.assertEqual(
- kv.check_klon('''ฉันชื่อหมูกรอบ ฉันชอบกินไก่ แล้วก็วิ่งไล่ หมาชื่อนํ้าทอง ลคคนเก่ง เอ๋งเอ๋งคะนอง มีคนจับจอง เขาชื่อน้องเธียร''',k_type=4),
+ kv.check_klon(
+ 'ฉันชื่อหมูกรอบ ฉันชอบกินไก่ แล้วก็วิ่งไล่ หมาชื่อนํ้าทอง ลคคนเก่ง เอ๋งเอ๋งคะนอง \
+ มีคนจับจอง เขาชื่อน้องเธียร',
+ k_type=4
+ ),
'The poem is correct according to the principle.'
)
self.assertEqual(
- kv.check_klon('''ฉันชื่อหมูกรอบ ฉันชอบกินไก่ แล้วก็วิ่งไล่ หมาชื่อนํ้าทอง ลคคนเก่ง เอ๋งเอ๋งเสียงหมา มีคนจับจอง เขาชื่อน้องเธียร''',k_type=4),
- ["Can't find rhyme between paragraphs ('หมา', 'จอง') in paragraph 2", "Can't find rhyme between paragraphs ('หมา', 'ทอง') in paragraph 2"]
+ kv.check_klon(
+ 'ฉันชื่อหมูกรอบ ฉันชอบกินไก่ แล้วก็วิ่งไล่ หมาชื่อนํ้าทอง ลคคนเก่ง \
+ เอ๋งเอ๋งเสียงหมา มีคนจับจอง เขาชื่อน้องเธียร',
+ k_type=4
+ ), [
+ "Can't find rhyme between paragraphs ('หมา', 'จอง') in paragraph 2",
+ "Can't find rhyme between paragraphs ('หมา', 'ทอง') in paragraph 2"
+ ]
)
def test_check_aek_too(self):
| bug: test_khavee.py failed - Can't find rhyme between paragraphs
### Description
A test in test_khavee.py failed.
### Expected results
It should passed.
### Current results
FAIL: test_check_klon (tests.test_khavee.TestKhaveePackage)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/runner/work/pythainlp/pythainlp/tests/test_khavee.py", line 24, in test_check_klon
self.assertEqual(
AssertionError: Lists differ: ["Can[42 chars]จอง')in paragraph 2", "Can't find rhyme betwee[39 chars]h 2"] != ["Can[42 chars]จอง') in paragraph 2", "Can't find rhyme betwe[40 chars]h 2"]
First differing element 0:
"Can't find rhyme between paragraphs ('หมา', 'จอง')in paragraph 2"
"Can't find rhyme between paragraphs ('หมา', 'จอง') in paragraph 2"
- ["Can't find rhyme between paragraphs ('หมา', 'จอง')in paragraph 2",
+ ["Can't find rhyme between paragraphs ('หมา', 'จอง') in paragraph 2",
? +
"Can't find rhyme between paragraphs ('หมา', 'ทอง') in paragraph 2"]
### Steps to reproduce
Run test.
### PyThaiNLP version
dev latest
### Python version
3.8
### Operating system and version
n/a
### More info
_No response_
### Possible solution
_No response_
### Files
pythainlp/pythainlp/tests/test_khavee.py | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_khavee.py::TestKhaveePackage::test_check_klon"
] | [
"tests/test_khavee.py::TestKhaveePackage::test_check_aek_too",
"tests/test_khavee.py::TestKhaveePackage::test_check_marttra",
"tests/test_khavee.py::TestKhaveePackage::test_check_sara",
"tests/test_khavee.py::TestKhaveePackage::test_is_sumpus"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2023-10-23T08:13:51Z" | apache-2.0 |
|
PyThaiNLP__pythainlp-862 | diff --git a/pythainlp/util/__init__.py b/pythainlp/util/__init__.py
index 2b2ff40e..55302507 100644
--- a/pythainlp/util/__init__.py
+++ b/pythainlp/util/__init__.py
@@ -21,19 +21,21 @@ __all__ = [
"abbreviation_to_full_text",
"arabic_digit_to_thai_digit",
"bahttext",
- "convert_years",
"collate",
- "countthai",
+ "convert_years",
"count_thai_chars",
+ "countthai",
"dict_trie",
"digit_to_text",
"display_thai_char",
"emoji_to_thai",
"eng_to_thai",
"find_keyword",
+ "ipa_to_rtgs",
"is_native_thai",
"isthai",
"isthaichar",
+ "nectec_to_ipa",
"normalize",
"now_reign_year",
"num_to_thaiword",
@@ -42,11 +44,18 @@ __all__ = [
"remove_dangling",
"remove_dup_spaces",
"remove_repeat_vowels",
+ "remove_tone_ipa",
"remove_tonemark",
+ "remove_trailing_repeat_consonants",
"remove_zw",
"reorder_vowels",
"rhyme",
+ "sound_syllable",
+ "spell_words",
+ "syllable_length",
+ "syllable_open_close_detector",
"text_to_arabic_digit",
+ "text_to_num",
"text_to_thai_digit",
"thai_digit_to_arabic_digit",
"thai_keyboard_dist",
@@ -58,17 +67,9 @@ __all__ = [
"thaiword_to_num",
"thaiword_to_time",
"time_to_thaiword",
- "text_to_num",
+ "tis620_to_utf8",
"tone_detector",
"words_to_num",
- "sound_syllable",
- "syllable_length",
- "syllable_open_close_detector",
- "nectec_to_ipa",
- "ipa_to_rtgs",
- "remove_tone_ipa",
- "tis620_to_utf8",
- "spell_words",
]
from pythainlp.util.collate import collate
@@ -103,6 +104,9 @@ from pythainlp.util.normalize import (
remove_zw,
reorder_vowels,
)
+from pythainlp.util.remove_trailing_repeat_consonants import (
+ remove_trailing_repeat_consonants,
+)
from pythainlp.util.numtoword import bahttext, num_to_thaiword
from pythainlp.util.strftime import thai_strftime
from pythainlp.util.thai import (
diff --git a/pythainlp/util/remove_trailing_repeat_consonants.py b/pythainlp/util/remove_trailing_repeat_consonants.py
new file mode 100644
index 00000000..7aae7e51
--- /dev/null
+++ b/pythainlp/util/remove_trailing_repeat_consonants.py
@@ -0,0 +1,256 @@
+# -*- coding: utf-8 -*-
+# Copyright (C) 2016-2023 PyThaiNLP Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""
+Removement of repeated consonants at the end of words
+"""
+from pythainlp.corpus import thai_words
+from pythainlp.util.trie import Trie
+from pythainlp import thai_consonants as consonants
+from typing import Tuple, List
+
+# used by remove_trailing_repeat_consonants()
+# contains all words that has repeating consonants at the end
+# for each consonant
+# when dictionary updated, this should be updated too
+# key: consonant
+# value: list of words that has repeating consonants at the end
+last_consonants_repeaters = {}
+
+
+def remove_trailing_repeat_consonants(
+ text: str, dictionary: Trie = None, has_dictionary_updated: bool = True
+) -> str:
+ """
+ Remove repeating consonants at the last of the sentence.
+
+ This function will remove the repeating consonants
+ before a whitespace, new line or at the last
+ so that the last word matches a word in the given dictionary.
+ If there is no match, the repeating consonants will be
+ reduced to one.
+ If there are several match, the longest word will be used.
+ Since this function uses a dictionary, the result may differs
+ depending on the dictionary used.
+ Plus, it is recommended to use normalize() to have a better result.
+
+ :param str text: input text
+ :param Trie dictionary: Trie dictionary to check the last word.
+ If None, pythainlp.corpus.thai_words() will be used
+ :param bool has_dictionary_updated: If the dictionary is updated
+ or the first time using in the kernel, set this true.
+ If not, set this false to save time.
+ :return: text without repeating Thai consonants
+ :rtype: str
+
+ :Example:
+ ::
+
+ from pythainlp.util import remove_trailing_repeat_consonants
+ from pythainlp.util import dict_trie
+
+ # use default dictionary (pythainlp.corpus.thai_words())
+ remove_trailing_repeat_consonants('เริ่ดดดดดดดด')
+ # output: เริ่ด
+
+ remove_trailing_repeat_consonants('อืมมมมมมมมมมมมมมม')
+ # output: อืมมม
+ # "อืมมม" is in the default dictionary
+
+ # use custom dictionary
+ custom_dictionary = dict_trie(["อืมมมมม"])
+ remove_trailing_repeat_consonants('อืมมมมมมมมมมมมมมม', custom_dictionary)
+ # output: อืมมมมม
+
+ # long text
+ remove_trailing_repeat_consonants('อืมมมมมมมมมมมมม คุณมีบุคลิกที่เริ่ดดดดด '\
+ 'ฉันจะให้เกรดดีกับคุณณณ\nนี่เป็นความลับบบบบ')
+ # output: อืมมม คุณมีบุคลิกที่เริ่ด ฉันจะให้เกรดดีกับคุณ
+ # นี่เป็นความลับ
+ """
+ # use default dictionary if not given
+ if dictionary is None:
+ dictionary = thai_words()
+
+ # update repeaters dictionary if not updated
+ if has_dictionary_updated:
+ _update_consonant_repeaters(dictionary)
+
+ # seperate by newline
+ modified_lines = []
+ for line in text.split("\n"):
+ segments = line.split(" ")
+
+ for cnt, segment in enumerate(segments):
+ segments[cnt] = _remove_repeat_trailing_consonants_from_segment(
+ segment
+ )
+
+ # revert spaces
+ modified_line = " ".join(segments)
+ modified_lines.append(modified_line)
+
+ # revert newlines
+ modified_text = "\n".join(modified_lines)
+
+ return modified_text
+
+
+def _remove_repeat_trailing_consonants_from_segment(segment: str) -> str:
+ """
+ Remove repeating consonants at the last of the segment.
+
+ This function process only at the last of the given text.
+ Details is same as remove_repeat_consonants().
+
+ :param str segment: segment of text
+ :return: segment without repeating Thai consonants
+ :rtype: str
+ """
+ # skip if the segment is not the target
+ if not (
+ # the segment is long enough
+ (len(segment) > 1)
+ # last is Thai consonant
+ and (segment[-1] in consonants)
+ # has repiitition
+ and (segment[-1] == segment[-2])
+ ):
+ # no need to process
+ return segment
+
+ # duplicating character
+ dup = segment[-1]
+
+ # find the words that has 2 or more duplication of
+ # this character at the end.
+ repeaters = last_consonants_repeaters[dup]
+
+ # remove all of the last repeating character
+ segment_head = _remove_all_last_consonants(segment, dup)
+
+ # find the longest word that matches the segment
+ longest_word, repetition = _find_longest_consonant_repeaters_match(
+ segment_head, repeaters
+ )
+
+ if len(longest_word) > 0:
+ # if there is a match, use it
+ segment = segment_head + (dup * repetition)
+ else:
+ # if none found,
+ # the chance is that the correct is one character,
+ # or it's not in the dictionary.
+
+ # make the repition to once
+ segment = segment_head + (dup * 1)
+
+ return segment
+
+
+def _remove_all_last_consonants(text: str, dup: str) -> str:
+ """
+ Reduce repeating characters at the end of the text.
+
+ This function will remove the repeating characters at the last.
+ The text just before the repeating characters will be returned.
+
+ :param str text: input text
+ :param str dup: repeating character to be removed
+ :return: text without repeating characters at the end
+ :rtype: str
+ """
+ removed = text
+ while (len(removed) > 0) and (removed[-1] == dup):
+ removed = removed[:-1]
+
+ return removed
+
+
+def _update_consonant_repeaters(dictionary: Trie) -> None:
+ """
+ Update dictionary of all words that has
+ repeating consonants at the end from the dictionary.
+
+ Search all words in the dictionary that has more than 1 consonants
+ repeating at the end and store them in the global dictionary.
+
+ :param str consonant: consonant to be searched
+ :param Trie dictionary: Trie dictionary to search
+ :rtype: None
+ """
+ # initialize dictionary
+ for consonant in list(consonants):
+ last_consonants_repeaters[consonant] = []
+
+ # register
+ for word in dictionary:
+ if _is_last_consonant_repeater(word):
+ last_consonants_repeaters[word[-1]].append(word)
+
+ return
+
+
+def _is_last_consonant_repeater(word: str) -> bool:
+ """
+ Check if the word has repeating consonants at the end.
+
+ This function checks if the word has
+ more than 1 repeating consonants at the end.
+
+ :param str word: word to be checked
+ :return: True if the word has repeating consonants at the end.
+ :rtype: bool
+ """
+ return (
+ (len(word) > 1) and (word[-1] == word[-2]) and (word[-1] in consonants)
+ )
+
+
+def _find_longest_consonant_repeaters_match(
+ segment_head: str, repeaters: List[str]
+) -> Tuple[str, int]:
+ """
+ Find the longest word that matches the segment.
+
+ Find the longest word that matches the last
+ of the segment from the given repeaters list.
+ This returns the word and
+ how much the last character is repeated correctly.
+
+ :param str segment: segment of text
+ :param List[str] repeaters: list of words
+ that has repeating consonants at the end
+ :return: "tuple of the word" and
+ "how much the last character is repeated correctly"
+ If none, ("", 0) will be returned.
+ :rtype: Tuple[str, int]
+ """
+ longest_word = "" # the longest word that matches the segment
+ repetition = 0 # how much the last character is repeated correctly
+ for repeater in repeaters:
+ # remove all of the last repeating character
+ repeater_head = _remove_all_last_consonants(repeater, repeater[-1])
+
+ # check match
+ if (
+ (len(segment_head) >= len(repeater_head))
+ and (segment_head[-len(repeater_head) :] == repeater_head)
+ # matched confirmed, check it's longer
+ and (len(repeater) > len(longest_word))
+ ):
+ longest_word = repeater
+ repetition = len(repeater) - len(repeater_head)
+
+ return longest_word, repetition
| PyThaiNLP/pythainlp | edb52b32c4dee034bba9b3f89294a9d73c5ef02d | diff --git a/tests/test_util.py b/tests/test_util.py
index 1840e2dc..e45319c9 100644
--- a/tests/test_util.py
+++ b/tests/test_util.py
@@ -60,6 +60,7 @@ from pythainlp.util import (
ipa_to_rtgs,
remove_tone_ipa,
tis620_to_utf8,
+ remove_trailing_repeat_consonants
)
from pythainlp.util.spell_words import spell_word
@@ -832,7 +833,8 @@ class TestUtilPackage(unittest.TestCase):
self.assertEqual(convert_years("242", src="re", target="ad"), "2023")
self.assertEqual(convert_years("242", src="re", target="ah"), "1444")
with self.assertRaises(NotImplementedError):
- self.assertIsNotNone(convert_years("2023", src="cat", target="dog"))
+ self.assertIsNotNone(convert_years(
+ "2023", src="cat", target="dog"))
def test_nectec_to_ipa(self):
self.assertEqual(nectec_to_ipa("kl-uua-j^-2"), 'kl uua j ˥˩')
@@ -846,17 +848,44 @@ class TestUtilPackage(unittest.TestCase):
self.assertEqual(remove_tone_ipa("laː˦˥.sa˨˩.maj˩˩˦"), "laː.sa.maj")
def test_tis620_to_utf8(self):
- self.assertEqual(tis620_to_utf8("¡ÃзÃǧÍصÊÒË¡ÃÃÁ"), "กระทรวงอุตสาหกรรม")
+ self.assertEqual(tis620_to_utf8(
+ "¡ÃзÃǧÍصÊÒË¡ÃÃÁ"), "กระทรวงอุตสาหกรรม")
def test_spell_word(self):
- self.assertEqual(spell_word("เสือ"),['สอ', 'เอือ', 'เสือ'])
- self.assertEqual(spell_word("เสื้อ"),['สอ', 'เอือ', 'ไม้โท', 'เสื้อ'])
- self.assertEqual(spell_word("คน"),['คอ', 'นอ', 'คน'])
- self.assertEqual(spell_word("คนดี"),['คอ', 'นอ', 'คน', 'ดอ', 'อี', 'ดี', 'คนดี'])
+ self.assertEqual(spell_word("เสือ"), ['สอ', 'เอือ', 'เสือ'])
+ self.assertEqual(spell_word("เสื้อ"), ['สอ', 'เอือ', 'ไม้โท', 'เสื้อ'])
+ self.assertEqual(spell_word("คน"), ['คอ', 'นอ', 'คน'])
+ self.assertEqual(spell_word("คนดี"), [
+ 'คอ', 'นอ', 'คน', 'ดอ', 'อี', 'ดี', 'คนดี'])
def test_rhyme(self):
self.assertIsInstance(rhyme("แมว"), list)
self.assertTrue(len(rhyme("แมว")) > 2)
+ def test_remove_repeat_consonants(self):
+ # update of pythainlp.copus.thai_words() able to break this
+ self.assertEqual(
+ remove_trailing_repeat_consonants('เริ่ดดดดดดดด'),
+ 'เริ่ด'
+ )
+ self.assertEqual(
+ remove_trailing_repeat_consonants('อืมมมมมมมมมมมมมมม'),
+ 'อืมมม'
+ )
+
+ custom_dictionary = dict_trie(["อืมมมมม"])
+ self.assertEqual(
+ remove_trailing_repeat_consonants('อืมมมมมมมมมมมมมมม', custom_dictionary),
+ 'อืมมมมม'
+ )
+
+ self.assertEqual(
+ remove_trailing_repeat_consonants(
+ 'อืมมมมมมมมมมมมม คุณมีบุคลิกที่เริ่ดดดดด '
+ 'ฉันจะให้เกรดดีกับคุณณณ\nนี่เป็นความลับบบบบ'
+ ),
+ 'อืมมม คุณมีบุคลิกที่เริ่ด ฉันจะให้เกรดดีกับคุณ\nนี่เป็นความลับ'
+ )
+
# def test_abbreviation_to_full_text(self):
# self.assertIsInstance(abbreviation_to_full_text("รร.ของเราน่าอยู่", list))
| [Suggestion] Add consonant-remover method
## Detailed description
I suggest to add a dictionary-based consonant-remover method.
As like เริศศศศศศศศศศศศศศ -> เริศ
## Context
I am doing text mining of Pantip. I saw that there are not few people write like "เริศศศศศศศศศศศศศศ", to express their emotions. Current `pythainlp.utils.normalize()` removes only vowels duplication, so there is no method to handle this now. Current tokenizers may separate this as "เริศ / ศศศศศศศศศศศศศ", but it becomes a noise of analysis.
Plus the implementation was a little long, so I wanted this method in pythainlp library
## Possible implementation
My implementation was like below.
```python
#>>against เริศศศศศศศศศศศศศศ
if (len(sentence) > 2) and pythainlp.util.isthaichar(sentence[-1]) and (sentence[-1] == sentence[-2]):
# The last of the sentence has duplication (duplication typically at the last)
dup = sentence[-1]
#find the words in the dictionary that has duplication at the last
#required here because dictio dynamically added
repeaters = []
for word in dictio:
if (len(word) > 2) and (word[-1] == dup) and (word[-2] == dup):
all_same = True
for cnt_1 in range(len(word)):
if word[cnt_1] != dup:
all_same = False
break
if not all_same:
repeaters.append(word)
#check if there is matching with repeaters
sentence_head = sentence
while(sentence_head[-1] == dup):
if (len(sentence_head) == 1):
break
sentence_head = sentence_head[:-1]
found = False
for repeater in repeaters:
rep_head = repeater
repetition = 0
while(rep_head[-1] == dup):
rep_head = rep_head[:-1]
repetition += 1
if sentence_head[-len(rep_head):] == rep_head:
found = True
break
if found:
sentences[cnt] = sentence_head + (dup * repetition)
else:
sentences[cnt] = sentence_head + (dup * 1)
```
If this plan seems good, I could make a PR | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_util.py::TestUtilPackage::test_collate",
"tests/test_util.py::TestUtilPackage::test_convert_years",
"tests/test_util.py::TestUtilPackage::test_count_thai_chars",
"tests/test_util.py::TestUtilPackage::test_countthai",
"tests/test_util.py::TestUtilPackage::test_date",
"tests/test_util.py::TestUtilPackage::test_display_thai_char",
"tests/test_util.py::TestUtilPackage::test_emoji_to_thai",
"tests/test_util.py::TestUtilPackage::test_find_keywords",
"tests/test_util.py::TestUtilPackage::test_ipa_to_rtgs",
"tests/test_util.py::TestUtilPackage::test_is_native_thai",
"tests/test_util.py::TestUtilPackage::test_isthai",
"tests/test_util.py::TestUtilPackage::test_isthaichar",
"tests/test_util.py::TestUtilPackage::test_keyboard",
"tests/test_util.py::TestUtilPackage::test_nectec_to_ipa",
"tests/test_util.py::TestUtilPackage::test_normalize",
"tests/test_util.py::TestUtilPackage::test_number",
"tests/test_util.py::TestUtilPackage::test_rank",
"tests/test_util.py::TestUtilPackage::test_remove_repeat_consonants",
"tests/test_util.py::TestUtilPackage::test_remove_tone_ipa",
"tests/test_util.py::TestUtilPackage::test_rhyme",
"tests/test_util.py::TestUtilPackage::test_sound_syllable",
"tests/test_util.py::TestUtilPackage::test_syllable_length",
"tests/test_util.py::TestUtilPackage::test_syllable_open_close_detector",
"tests/test_util.py::TestUtilPackage::test_thai_keyboard_dist",
"tests/test_util.py::TestUtilPackage::test_thai_strftime",
"tests/test_util.py::TestUtilPackage::test_thai_strptime",
"tests/test_util.py::TestUtilPackage::test_thaiword_to_date",
"tests/test_util.py::TestUtilPackage::test_thaiword_to_time",
"tests/test_util.py::TestUtilPackage::test_time_to_thaiword",
"tests/test_util.py::TestUtilPackage::test_tis620_to_utf8",
"tests/test_util.py::TestUtilPackage::test_tone_detector",
"tests/test_util.py::TestUtilPackage::test_trie"
] | [] | {
"failed_lite_validators": [
"has_added_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
} | "2023-11-09T16:42:49Z" | apache-2.0 |
|
Pylons__colander-321 | diff --git a/CHANGES.rst b/CHANGES.rst
index 43c932c..669d34e 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -1,3 +1,10 @@
+Unreleased
+==========
+
+- Number once again will allow you to serialize None to colander.null, this
+ reverts an accidental revert. See
+ https://github.com/Pylons/colander/issues/204#issuecomment-459556100
+
1.6.0 (2019-01-31)
==================
diff --git a/colander/__init__.py b/colander/__init__.py
index 8bddfd6..728eceb 100644
--- a/colander/__init__.py
+++ b/colander/__init__.py
@@ -1399,7 +1399,7 @@ class Number(SchemaType):
num = None
def serialize(self, node, appstruct):
- if appstruct is null:
+ if appstruct in (null, None):
return null
try:
| Pylons/colander | b7acdff5e83e41208c323f8cac52c48ff6328a85 | diff --git a/colander/tests/test_colander.py b/colander/tests/test_colander.py
index 12b904e..0d911d7 100644
--- a/colander/tests/test_colander.py
+++ b/colander/tests/test_colander.py
@@ -1752,6 +1752,14 @@ class TestInteger(unittest.TestCase):
result = typ.serialize(node, val)
self.assertEqual(result, colander.null)
+ def test_serialize_none(self):
+ import colander
+
+ node = DummySchemaNode(None)
+ typ = self._makeOne()
+ result = typ.serialize(node, None)
+ self.assertEqual(result, colander.null)
+
def test_deserialize_emptystring(self):
import colander
@@ -1812,6 +1820,21 @@ class TestFloat(unittest.TestCase):
result = typ.serialize(node, val)
self.assertEqual(result, colander.null)
+ def test_serialize_none(self):
+ import colander
+
+ node = DummySchemaNode(None)
+ typ = self._makeOne()
+ result = typ.serialize(node, None)
+ self.assertEqual(result, colander.null)
+
+ def test_serialize_zero(self):
+ val = 0
+ node = DummySchemaNode(None)
+ typ = self._makeOne()
+ result = typ.serialize(node, val)
+ self.assertEqual(result, '0.0')
+
def test_serialize_emptystring(self):
import colander
@@ -1865,6 +1888,21 @@ class TestDecimal(unittest.TestCase):
result = typ.serialize(node, val)
self.assertEqual(result, colander.null)
+ def test_serialize_none(self):
+ import colander
+
+ node = DummySchemaNode(None)
+ typ = self._makeOne()
+ result = typ.serialize(node, None)
+ self.assertEqual(result, colander.null)
+
+ def test_serialize_zero(self):
+ val = 0
+ node = DummySchemaNode(None)
+ typ = self._makeOne()
+ result = typ.serialize(node, val)
+ self.assertEqual(result, '0')
+
def test_serialize_emptystring(self):
import colander
| Why not allow `None` in an appstruct serialized by Number?
relates to part of #186
A commit was made a while ago that removed the ability to pass `None` as an appstruct value to a `Number` type ( commit 513d860 ). The commit says it's reverting a change related to **Strings** but then made this change to `Number`. It seems like an odd change and is removing useful functionality.
Basically, it comes down to the fact `colander.null` is not equal to `None`. This makes sense in the cases where `None` is a valid serialization. From the docs:
> Note that colander.null has no relationship to the built-in Python None value. colander.null is used instead of None because None is a potentially valid value for some serializations and deserializations, and using it as a sentinel would prevent None from being used in this way.
However, in the cases where `None` is not a valid value, why not treat it as equal to `colander.null` for simplicity? The very common use case is when using an SQL DB for storing of values. An integer column that's nullable can store both integers and None.
Incidentally, where is the case where `None` is a valid value?
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"colander/tests/test_colander.py::TestInteger::test_serialize_none",
"colander/tests/test_colander.py::TestFloat::test_serialize_none",
"colander/tests/test_colander.py::TestDecimal::test_serialize_none"
] | [
"colander/tests/test_colander.py::TestInvalid::test___setitem__fails",
"colander/tests/test_colander.py::TestInvalid::test___setitem__succeeds",
"colander/tests/test_colander.py::TestInvalid::test___str__",
"colander/tests/test_colander.py::TestInvalid::test__keyname_no_parent",
"colander/tests/test_colander.py::TestInvalid::test__keyname_nonpositional_parent",
"colander/tests/test_colander.py::TestInvalid::test__keyname_positional",
"colander/tests/test_colander.py::TestInvalid::test_add",
"colander/tests/test_colander.py::TestInvalid::test_add_positional",
"colander/tests/test_colander.py::TestInvalid::test_asdict",
"colander/tests/test_colander.py::TestInvalid::test_asdict_with_all_validator",
"colander/tests/test_colander.py::TestInvalid::test_asdict_with_all_validator_functional",
"colander/tests/test_colander.py::TestInvalid::test_ctor",
"colander/tests/test_colander.py::TestInvalid::test_messages_msg_None",
"colander/tests/test_colander.py::TestInvalid::test_messages_msg_iterable",
"colander/tests/test_colander.py::TestInvalid::test_messages_msg_not_iterable",
"colander/tests/test_colander.py::TestInvalid::test_paths",
"colander/tests/test_colander.py::TestAll::test_Invalid_children",
"colander/tests/test_colander.py::TestAll::test_failure",
"colander/tests/test_colander.py::TestAll::test_success",
"colander/tests/test_colander.py::TestAny::test_Invalid_children",
"colander/tests/test_colander.py::TestAny::test_failure",
"colander/tests/test_colander.py::TestAny::test_success",
"colander/tests/test_colander.py::TestFunction::test_deprecated_message",
"colander/tests/test_colander.py::TestFunction::test_deprecated_message_warning",
"colander/tests/test_colander.py::TestFunction::test_error_message_adds_mapping_to_configured_message",
"colander/tests/test_colander.py::TestFunction::test_error_message_adds_mapping_to_return_message",
"colander/tests/test_colander.py::TestFunction::test_error_message_does_not_overwrite_configured_domain",
"colander/tests/test_colander.py::TestFunction::test_error_message_does_not_overwrite_returned_domain",
"colander/tests/test_colander.py::TestFunction::test_fail_function_returns_False",
"colander/tests/test_colander.py::TestFunction::test_fail_function_returns_empty_string",
"colander/tests/test_colander.py::TestFunction::test_fail_function_returns_string",
"colander/tests/test_colander.py::TestFunction::test_msg_and_message_error",
"colander/tests/test_colander.py::TestFunction::test_propagation",
"colander/tests/test_colander.py::TestFunction::test_success_function_returns_True",
"colander/tests/test_colander.py::TestRange::test_max_failure",
"colander/tests/test_colander.py::TestRange::test_max_failure_msg_override",
"colander/tests/test_colander.py::TestRange::test_min_failure",
"colander/tests/test_colander.py::TestRange::test_min_failure_msg_override",
"colander/tests/test_colander.py::TestRange::test_success_min_and_max",
"colander/tests/test_colander.py::TestRange::test_success_minimum_bound_only",
"colander/tests/test_colander.py::TestRange::test_success_no_bounds",
"colander/tests/test_colander.py::TestRange::test_success_upper_bound_only",
"colander/tests/test_colander.py::TestRegex::test_invalid_regexs",
"colander/tests/test_colander.py::TestRegex::test_regex_not_string",
"colander/tests/test_colander.py::TestRegex::test_valid_regex",
"colander/tests/test_colander.py::TestEmail::test_empty_email",
"colander/tests/test_colander.py::TestEmail::test_invalid_emails",
"colander/tests/test_colander.py::TestEmail::test_valid_emails",
"colander/tests/test_colander.py::TestLength::test_max_failure",
"colander/tests/test_colander.py::TestLength::test_max_failure_msg_override",
"colander/tests/test_colander.py::TestLength::test_min_failure",
"colander/tests/test_colander.py::TestLength::test_min_failure_msg_override",
"colander/tests/test_colander.py::TestLength::test_success_min_and_max",
"colander/tests/test_colander.py::TestLength::test_success_minimum_bound_only",
"colander/tests/test_colander.py::TestLength::test_success_no_bounds",
"colander/tests/test_colander.py::TestLength::test_success_upper_bound_only",
"colander/tests/test_colander.py::TestOneOf::test_failure",
"colander/tests/test_colander.py::TestOneOf::test_success",
"colander/tests/test_colander.py::TestNoneOf::test_failure",
"colander/tests/test_colander.py::TestNoneOf::test_success",
"colander/tests/test_colander.py::TestContainsOnly::test_failure",
"colander/tests/test_colander.py::TestContainsOnly::test_failure_with_custom_error_template",
"colander/tests/test_colander.py::TestContainsOnly::test_success",
"colander/tests/test_colander.py::Test_luhnok::test_fail",
"colander/tests/test_colander.py::Test_luhnok::test_fail2",
"colander/tests/test_colander.py::Test_luhnok::test_fail3",
"colander/tests/test_colander.py::Test_luhnok::test_success",
"colander/tests/test_colander.py::Test_url_validator::test_it_failure",
"colander/tests/test_colander.py::Test_url_validator::test_it_success",
"colander/tests/test_colander.py::TestUUID::test_failure_invalid_length",
"colander/tests/test_colander.py::TestUUID::test_failure_not_hexadecimal",
"colander/tests/test_colander.py::TestUUID::test_failure_random_string",
"colander/tests/test_colander.py::TestUUID::test_failure_with_invalid_urn_ns",
"colander/tests/test_colander.py::TestUUID::test_success_hexadecimal",
"colander/tests/test_colander.py::TestUUID::test_success_upper_case",
"colander/tests/test_colander.py::TestUUID::test_success_with_braces",
"colander/tests/test_colander.py::TestUUID::test_success_with_dashes",
"colander/tests/test_colander.py::TestUUID::test_success_with_urn_ns",
"colander/tests/test_colander.py::TestSchemaType::test_cstruct_children",
"colander/tests/test_colander.py::TestSchemaType::test_flatten",
"colander/tests/test_colander.py::TestSchemaType::test_flatten_listitem",
"colander/tests/test_colander.py::TestSchemaType::test_get_value",
"colander/tests/test_colander.py::TestSchemaType::test_set_value",
"colander/tests/test_colander.py::TestSchemaType::test_unflatten",
"colander/tests/test_colander.py::TestMapping::test_cstruct_children",
"colander/tests/test_colander.py::TestMapping::test_cstruct_children_cstruct_is_null",
"colander/tests/test_colander.py::TestMapping::test_ctor_bad_unknown",
"colander/tests/test_colander.py::TestMapping::test_ctor_good_unknown",
"colander/tests/test_colander.py::TestMapping::test_deserialize_no_subnodes",
"colander/tests/test_colander.py::TestMapping::test_deserialize_not_a_mapping",
"colander/tests/test_colander.py::TestMapping::test_deserialize_null",
"colander/tests/test_colander.py::TestMapping::test_deserialize_ok",
"colander/tests/test_colander.py::TestMapping::test_deserialize_subnode_missing_default",
"colander/tests/test_colander.py::TestMapping::test_deserialize_subnodes_raise",
"colander/tests/test_colander.py::TestMapping::test_deserialize_unknown_preserve",
"colander/tests/test_colander.py::TestMapping::test_deserialize_unknown_raise",
"colander/tests/test_colander.py::TestMapping::test_flatten",
"colander/tests/test_colander.py::TestMapping::test_flatten_listitem",
"colander/tests/test_colander.py::TestMapping::test_get_value",
"colander/tests/test_colander.py::TestMapping::test_serialize_no_subnodes",
"colander/tests/test_colander.py::TestMapping::test_serialize_not_a_mapping",
"colander/tests/test_colander.py::TestMapping::test_serialize_null",
"colander/tests/test_colander.py::TestMapping::test_serialize_ok",
"colander/tests/test_colander.py::TestMapping::test_serialize_value_has_drop",
"colander/tests/test_colander.py::TestMapping::test_serialize_value_is_null",
"colander/tests/test_colander.py::TestMapping::test_serialize_with_unknown",
"colander/tests/test_colander.py::TestMapping::test_set_value",
"colander/tests/test_colander.py::TestMapping::test_unflatten",
"colander/tests/test_colander.py::TestMapping::test_unflatten_nested",
"colander/tests/test_colander.py::TestTuple::test_cstruct_children_cstruct_is_null",
"colander/tests/test_colander.py::TestTuple::test_cstruct_children_justright",
"colander/tests/test_colander.py::TestTuple::test_cstruct_children_toofew",
"colander/tests/test_colander.py::TestTuple::test_cstruct_children_toomany",
"colander/tests/test_colander.py::TestTuple::test_deserialize_no_subnodes",
"colander/tests/test_colander.py::TestTuple::test_deserialize_not_iterable",
"colander/tests/test_colander.py::TestTuple::test_deserialize_null",
"colander/tests/test_colander.py::TestTuple::test_deserialize_ok",
"colander/tests/test_colander.py::TestTuple::test_deserialize_subnodes_raise",
"colander/tests/test_colander.py::TestTuple::test_deserialize_toobig",
"colander/tests/test_colander.py::TestTuple::test_deserialize_toosmall",
"colander/tests/test_colander.py::TestTuple::test_flatten",
"colander/tests/test_colander.py::TestTuple::test_flatten_listitem",
"colander/tests/test_colander.py::TestTuple::test_get_value",
"colander/tests/test_colander.py::TestTuple::test_get_value_bad_path",
"colander/tests/test_colander.py::TestTuple::test_serialize_no_subnodes",
"colander/tests/test_colander.py::TestTuple::test_serialize_not_iterable",
"colander/tests/test_colander.py::TestTuple::test_serialize_null",
"colander/tests/test_colander.py::TestTuple::test_serialize_ok",
"colander/tests/test_colander.py::TestTuple::test_serialize_subnodes_raise",
"colander/tests/test_colander.py::TestTuple::test_serialize_toobig",
"colander/tests/test_colander.py::TestTuple::test_serialize_toosmall",
"colander/tests/test_colander.py::TestTuple::test_set_value",
"colander/tests/test_colander.py::TestTuple::test_set_value_bad_path",
"colander/tests/test_colander.py::TestTuple::test_unflatten",
"colander/tests/test_colander.py::TestSet::test_deserialize_empty_set",
"colander/tests/test_colander.py::TestSet::test_deserialize_no_iter",
"colander/tests/test_colander.py::TestSet::test_deserialize_null",
"colander/tests/test_colander.py::TestSet::test_deserialize_str_no_iter",
"colander/tests/test_colander.py::TestSet::test_deserialize_valid",
"colander/tests/test_colander.py::TestSet::test_serialize",
"colander/tests/test_colander.py::TestSet::test_serialize_null",
"colander/tests/test_colander.py::TestList::test_deserialize_empty_set",
"colander/tests/test_colander.py::TestList::test_deserialize_no_iter",
"colander/tests/test_colander.py::TestList::test_deserialize_null",
"colander/tests/test_colander.py::TestList::test_deserialize_str_no_iter",
"colander/tests/test_colander.py::TestList::test_deserialize_valid",
"colander/tests/test_colander.py::TestList::test_serialize",
"colander/tests/test_colander.py::TestList::test_serialize_null",
"colander/tests/test_colander.py::TestSequence::test_alias",
"colander/tests/test_colander.py::TestSequence::test_cstruct_children_cstruct_is_non_null",
"colander/tests/test_colander.py::TestSequence::test_cstruct_children_cstruct_is_null",
"colander/tests/test_colander.py::TestSequence::test_deserialize_no_null",
"colander/tests/test_colander.py::TestSequence::test_deserialize_no_subnodes",
"colander/tests/test_colander.py::TestSequence::test_deserialize_not_iterable",
"colander/tests/test_colander.py::TestSequence::test_deserialize_not_iterable_accept_scalar",
"colander/tests/test_colander.py::TestSequence::test_deserialize_ok",
"colander/tests/test_colander.py::TestSequence::test_deserialize_string_accept_scalar",
"colander/tests/test_colander.py::TestSequence::test_deserialize_subnodes_raise",
"colander/tests/test_colander.py::TestSequence::test_flatten",
"colander/tests/test_colander.py::TestSequence::test_flatten_listitem",
"colander/tests/test_colander.py::TestSequence::test_flatten_with_integer",
"colander/tests/test_colander.py::TestSequence::test_getvalue",
"colander/tests/test_colander.py::TestSequence::test_serialize_drop",
"colander/tests/test_colander.py::TestSequence::test_serialize_no_subnodes",
"colander/tests/test_colander.py::TestSequence::test_serialize_not_iterable",
"colander/tests/test_colander.py::TestSequence::test_serialize_not_iterable_accept_scalar",
"colander/tests/test_colander.py::TestSequence::test_serialize_null",
"colander/tests/test_colander.py::TestSequence::test_serialize_ok",
"colander/tests/test_colander.py::TestSequence::test_serialize_string_accept_scalar",
"colander/tests/test_colander.py::TestSequence::test_serialize_subnodes_raise",
"colander/tests/test_colander.py::TestSequence::test_setvalue",
"colander/tests/test_colander.py::TestSequence::test_unflatten",
"colander/tests/test_colander.py::TestString::test_alias",
"colander/tests/test_colander.py::TestString::test_deserialize_emptystring",
"colander/tests/test_colander.py::TestString::test_deserialize_from_nonstring_obj",
"colander/tests/test_colander.py::TestString::test_deserialize_from_utf16",
"colander/tests/test_colander.py::TestString::test_deserialize_from_utf8",
"colander/tests/test_colander.py::TestString::test_deserialize_nonunicode_from_None",
"colander/tests/test_colander.py::TestString::test_deserialize_uncooperative",
"colander/tests/test_colander.py::TestString::test_deserialize_unicode_from_None",
"colander/tests/test_colander.py::TestString::test_serialize_emptystring",
"colander/tests/test_colander.py::TestString::test_serialize_encoding_with_non_string_type",
"colander/tests/test_colander.py::TestString::test_serialize_nonunicode_to_None",
"colander/tests/test_colander.py::TestString::test_serialize_null",
"colander/tests/test_colander.py::TestString::test_serialize_string_with_high_unresolveable_high_order_chars",
"colander/tests/test_colander.py::TestString::test_serialize_to_utf16",
"colander/tests/test_colander.py::TestString::test_serialize_to_utf8",
"colander/tests/test_colander.py::TestString::test_serialize_uncooperative",
"colander/tests/test_colander.py::TestString::test_serialize_unicode_to_None",
"colander/tests/test_colander.py::TestInteger::test_alias",
"colander/tests/test_colander.py::TestInteger::test_deserialize_emptystring",
"colander/tests/test_colander.py::TestInteger::test_deserialize_fails",
"colander/tests/test_colander.py::TestInteger::test_deserialize_ok",
"colander/tests/test_colander.py::TestInteger::test_serialize_fails",
"colander/tests/test_colander.py::TestInteger::test_serialize_null",
"colander/tests/test_colander.py::TestInteger::test_serialize_ok",
"colander/tests/test_colander.py::TestInteger::test_serialize_zero",
"colander/tests/test_colander.py::TestFloat::test_deserialize_fails",
"colander/tests/test_colander.py::TestFloat::test_deserialize_ok",
"colander/tests/test_colander.py::TestFloat::test_serialize_emptystring",
"colander/tests/test_colander.py::TestFloat::test_serialize_fails",
"colander/tests/test_colander.py::TestFloat::test_serialize_null",
"colander/tests/test_colander.py::TestFloat::test_serialize_ok",
"colander/tests/test_colander.py::TestFloat::test_serialize_zero",
"colander/tests/test_colander.py::TestDecimal::test_deserialize_fails",
"colander/tests/test_colander.py::TestDecimal::test_deserialize_ok",
"colander/tests/test_colander.py::TestDecimal::test_deserialize_with_normalize",
"colander/tests/test_colander.py::TestDecimal::test_deserialize_with_quantize",
"colander/tests/test_colander.py::TestDecimal::test_serialize_emptystring",
"colander/tests/test_colander.py::TestDecimal::test_serialize_fails",
"colander/tests/test_colander.py::TestDecimal::test_serialize_normalize",
"colander/tests/test_colander.py::TestDecimal::test_serialize_null",
"colander/tests/test_colander.py::TestDecimal::test_serialize_ok",
"colander/tests/test_colander.py::TestDecimal::test_serialize_quantize_no_rounding",
"colander/tests/test_colander.py::TestDecimal::test_serialize_quantize_with_rounding_up",
"colander/tests/test_colander.py::TestDecimal::test_serialize_zero",
"colander/tests/test_colander.py::TestMoney::test_deserialize_rounds_up",
"colander/tests/test_colander.py::TestMoney::test_serialize_rounds_up",
"colander/tests/test_colander.py::TestBoolean::test_alias",
"colander/tests/test_colander.py::TestBoolean::test_deserialize",
"colander/tests/test_colander.py::TestBoolean::test_deserialize_null",
"colander/tests/test_colander.py::TestBoolean::test_deserialize_unstringable",
"colander/tests/test_colander.py::TestBoolean::test_serialize",
"colander/tests/test_colander.py::TestBoolean::test_serialize_null",
"colander/tests/test_colander.py::TestBooleanCustomFalseReprs::test_deserialize",
"colander/tests/test_colander.py::TestBooleanCustomFalseAndTrueReprs::test_deserialize",
"colander/tests/test_colander.py::TestBooleanCustomSerializations::test_serialize",
"colander/tests/test_colander.py::TestGlobalObject::test__pkg_resources_style_irrresolveable_absolute",
"colander/tests/test_colander.py::TestGlobalObject::test__pkg_resources_style_irrresolveable_relative",
"colander/tests/test_colander.py::TestGlobalObject::test__pkg_resources_style_resolve_absolute",
"colander/tests/test_colander.py::TestGlobalObject::test__pkg_resources_style_resolve_relative_is_dot",
"colander/tests/test_colander.py::TestGlobalObject::test__pkg_resources_style_resolve_relative_nocurrentpackage",
"colander/tests/test_colander.py::TestGlobalObject::test__pkg_resources_style_resolve_relative_startswith_colon",
"colander/tests/test_colander.py::TestGlobalObject::test__pkg_resources_style_resolve_relative_startswith_dot",
"colander/tests/test_colander.py::TestGlobalObject::test__zope_dottedname_style_irresolveable_absolute",
"colander/tests/test_colander.py::TestGlobalObject::test__zope_dottedname_style_irresolveable_relative_is_dot",
"colander/tests/test_colander.py::TestGlobalObject::test__zope_dottedname_style_resolve_relative",
"colander/tests/test_colander.py::TestGlobalObject::test__zope_dottedname_style_resolve_relative_is_dot",
"colander/tests/test_colander.py::TestGlobalObject::test__zope_dottedname_style_resolve_relative_leading_dots",
"colander/tests/test_colander.py::TestGlobalObject::test__zope_dottedname_style_resolveable_absolute",
"colander/tests/test_colander.py::TestGlobalObject::test__zope_dottedname_style_resolveable_relative",
"colander/tests/test_colander.py::TestGlobalObject::test_deserialize_None",
"colander/tests/test_colander.py::TestGlobalObject::test_deserialize_class_fail",
"colander/tests/test_colander.py::TestGlobalObject::test_deserialize_class_ok",
"colander/tests/test_colander.py::TestGlobalObject::test_deserialize_notastring",
"colander/tests/test_colander.py::TestGlobalObject::test_deserialize_null",
"colander/tests/test_colander.py::TestGlobalObject::test_deserialize_style_raises",
"colander/tests/test_colander.py::TestGlobalObject::test_deserialize_using_pkgresources_style",
"colander/tests/test_colander.py::TestGlobalObject::test_deserialize_using_zope_dottedname_style",
"colander/tests/test_colander.py::TestGlobalObject::test_serialize_class",
"colander/tests/test_colander.py::TestGlobalObject::test_serialize_fail",
"colander/tests/test_colander.py::TestGlobalObject::test_serialize_null",
"colander/tests/test_colander.py::TestGlobalObject::test_serialize_ok",
"colander/tests/test_colander.py::TestGlobalObject::test_zope_dottedname_style_irrresolveable_absolute",
"colander/tests/test_colander.py::TestGlobalObject::test_zope_dottedname_style_irrresolveable_relative",
"colander/tests/test_colander.py::TestGlobalObject::test_zope_dottedname_style_resolve_absolute",
"colander/tests/test_colander.py::TestGlobalObject::test_zope_dottedname_style_resolve_relative_nocurrentpackage",
"colander/tests/test_colander.py::TestDateTime::test_ctor_default_tzinfo_None",
"colander/tests/test_colander.py::TestDateTime::test_ctor_default_tzinfo_non_None",
"colander/tests/test_colander.py::TestDateTime::test_ctor_default_tzinfo_not_specified",
"colander/tests/test_colander.py::TestDateTime::test_deserialize_date",
"colander/tests/test_colander.py::TestDateTime::test_deserialize_datetime_with_custom_format",
"colander/tests/test_colander.py::TestDateTime::test_deserialize_empty",
"colander/tests/test_colander.py::TestDateTime::test_deserialize_invalid_ParseError",
"colander/tests/test_colander.py::TestDateTime::test_deserialize_naive_with_default_tzinfo",
"colander/tests/test_colander.py::TestDateTime::test_deserialize_none_tzinfo",
"colander/tests/test_colander.py::TestDateTime::test_deserialize_null",
"colander/tests/test_colander.py::TestDateTime::test_deserialize_slashes_invalid",
"colander/tests/test_colander.py::TestDateTime::test_deserialize_success",
"colander/tests/test_colander.py::TestDateTime::test_serialize_none",
"colander/tests/test_colander.py::TestDateTime::test_serialize_null",
"colander/tests/test_colander.py::TestDateTime::test_serialize_with_date",
"colander/tests/test_colander.py::TestDateTime::test_serialize_with_garbage",
"colander/tests/test_colander.py::TestDateTime::test_serialize_with_naive_datetime",
"colander/tests/test_colander.py::TestDateTime::test_serialize_with_naive_datetime_and_custom_format",
"colander/tests/test_colander.py::TestDateTime::test_serialize_with_none_tzinfo_naive_datetime",
"colander/tests/test_colander.py::TestDateTime::test_serialize_with_none_tzinfo_naive_datetime_custom_format",
"colander/tests/test_colander.py::TestDateTime::test_serialize_with_tzware_datetime",
"colander/tests/test_colander.py::TestDate::test_deserialize_date_with_custom_format",
"colander/tests/test_colander.py::TestDate::test_deserialize_empty",
"colander/tests/test_colander.py::TestDate::test_deserialize_invalid_ParseError",
"colander/tests/test_colander.py::TestDate::test_deserialize_invalid_weird",
"colander/tests/test_colander.py::TestDate::test_deserialize_null",
"colander/tests/test_colander.py::TestDate::test_deserialize_success_date",
"colander/tests/test_colander.py::TestDate::test_deserialize_success_datetime",
"colander/tests/test_colander.py::TestDate::test_serialize_date_with_custom_format",
"colander/tests/test_colander.py::TestDate::test_serialize_none",
"colander/tests/test_colander.py::TestDate::test_serialize_null",
"colander/tests/test_colander.py::TestDate::test_serialize_with_date",
"colander/tests/test_colander.py::TestDate::test_serialize_with_datetime",
"colander/tests/test_colander.py::TestDate::test_serialize_with_garbage",
"colander/tests/test_colander.py::TestTime::test_deserialize_empty",
"colander/tests/test_colander.py::TestTime::test_deserialize_four_digit_string",
"colander/tests/test_colander.py::TestTime::test_deserialize_invalid_ParseError",
"colander/tests/test_colander.py::TestTime::test_deserialize_missing_seconds",
"colander/tests/test_colander.py::TestTime::test_deserialize_null",
"colander/tests/test_colander.py::TestTime::test_deserialize_success_datetime",
"colander/tests/test_colander.py::TestTime::test_deserialize_success_time",
"colander/tests/test_colander.py::TestTime::test_deserialize_three_digit_string",
"colander/tests/test_colander.py::TestTime::test_deserialize_two_digit_string",
"colander/tests/test_colander.py::TestTime::test_serialize_none",
"colander/tests/test_colander.py::TestTime::test_serialize_null",
"colander/tests/test_colander.py::TestTime::test_serialize_with_datetime",
"colander/tests/test_colander.py::TestTime::test_serialize_with_garbage",
"colander/tests/test_colander.py::TestTime::test_serialize_with_time",
"colander/tests/test_colander.py::TestTime::test_serialize_with_zero_time",
"colander/tests/test_colander.py::TestEnum::test_deserialize_failure",
"colander/tests/test_colander.py::TestEnum::test_deserialize_failure_typ",
"colander/tests/test_colander.py::TestEnum::test_deserialize_name",
"colander/tests/test_colander.py::TestEnum::test_deserialize_null",
"colander/tests/test_colander.py::TestEnum::test_deserialize_value_int",
"colander/tests/test_colander.py::TestEnum::test_deserialize_value_str",
"colander/tests/test_colander.py::TestEnum::test_non_unique_failure",
"colander/tests/test_colander.py::TestEnum::test_non_unique_failure2",
"colander/tests/test_colander.py::TestEnum::test_serialize_failure",
"colander/tests/test_colander.py::TestEnum::test_serialize_name",
"colander/tests/test_colander.py::TestEnum::test_serialize_null",
"colander/tests/test_colander.py::TestEnum::test_serialize_value_int",
"colander/tests/test_colander.py::TestEnum::test_serialize_value_str",
"colander/tests/test_colander.py::TestSchemaNode::test___contains__",
"colander/tests/test_colander.py::TestSchemaNode::test___delitem__failure",
"colander/tests/test_colander.py::TestSchemaNode::test___delitem__success",
"colander/tests/test_colander.py::TestSchemaNode::test___getitem__failure",
"colander/tests/test_colander.py::TestSchemaNode::test___getitem__success",
"colander/tests/test_colander.py::TestSchemaNode::test___iter__",
"colander/tests/test_colander.py::TestSchemaNode::test___setitem__no_override",
"colander/tests/test_colander.py::TestSchemaNode::test___setitem__override",
"colander/tests/test_colander.py::TestSchemaNode::test_add",
"colander/tests/test_colander.py::TestSchemaNode::test_bind",
"colander/tests/test_colander.py::TestSchemaNode::test_bind_with_after_bind",
"colander/tests/test_colander.py::TestSchemaNode::test_clone",
"colander/tests/test_colander.py::TestSchemaNode::test_clone_mapping_references",
"colander/tests/test_colander.py::TestSchemaNode::test_clone_with_modified_schema_instance",
"colander/tests/test_colander.py::TestSchemaNode::test_cstruct_children",
"colander/tests/test_colander.py::TestSchemaNode::test_cstruct_children_warning",
"colander/tests/test_colander.py::TestSchemaNode::test_ctor_children_kwarg_typ",
"colander/tests/test_colander.py::TestSchemaNode::test_ctor_no_title",
"colander/tests/test_colander.py::TestSchemaNode::test_ctor_with_description",
"colander/tests/test_colander.py::TestSchemaNode::test_ctor_with_kwarg_typ",
"colander/tests/test_colander.py::TestSchemaNode::test_ctor_with_preparer",
"colander/tests/test_colander.py::TestSchemaNode::test_ctor_with_title",
"colander/tests/test_colander.py::TestSchemaNode::test_ctor_with_unknown_kwarg",
"colander/tests/test_colander.py::TestSchemaNode::test_ctor_with_widget",
"colander/tests/test_colander.py::TestSchemaNode::test_ctor_without_preparer",
"colander/tests/test_colander.py::TestSchemaNode::test_ctor_without_type",
"colander/tests/test_colander.py::TestSchemaNode::test_declarative_name_reassignment",
"colander/tests/test_colander.py::TestSchemaNode::test_deserialize_appstruct_deferred",
"colander/tests/test_colander.py::TestSchemaNode::test_deserialize_no_validator",
"colander/tests/test_colander.py::TestSchemaNode::test_deserialize_noargs_uses_default",
"colander/tests/test_colander.py::TestSchemaNode::test_deserialize_null_can_be_used_as_missing",
"colander/tests/test_colander.py::TestSchemaNode::test_deserialize_preparer_before_missing_check",
"colander/tests/test_colander.py::TestSchemaNode::test_deserialize_value_is_null_no_missing",
"colander/tests/test_colander.py::TestSchemaNode::test_deserialize_value_is_null_with_missing",
"colander/tests/test_colander.py::TestSchemaNode::test_deserialize_value_is_null_with_missing_msg",
"colander/tests/test_colander.py::TestSchemaNode::test_deserialize_value_with_interpolated_missing_msg",
"colander/tests/test_colander.py::TestSchemaNode::test_deserialize_with_multiple_preparers",
"colander/tests/test_colander.py::TestSchemaNode::test_deserialize_with_preparer",
"colander/tests/test_colander.py::TestSchemaNode::test_deserialize_with_unbound_validator",
"colander/tests/test_colander.py::TestSchemaNode::test_deserialize_with_validator",
"colander/tests/test_colander.py::TestSchemaNode::test_insert",
"colander/tests/test_colander.py::TestSchemaNode::test_new_sets_order",
"colander/tests/test_colander.py::TestSchemaNode::test_raise_invalid",
"colander/tests/test_colander.py::TestSchemaNode::test_repr",
"colander/tests/test_colander.py::TestSchemaNode::test_required_deferred",
"colander/tests/test_colander.py::TestSchemaNode::test_required_false",
"colander/tests/test_colander.py::TestSchemaNode::test_required_true",
"colander/tests/test_colander.py::TestSchemaNode::test_serialize",
"colander/tests/test_colander.py::TestSchemaNode::test_serialize_default_deferred",
"colander/tests/test_colander.py::TestSchemaNode::test_serialize_noargs_uses_default",
"colander/tests/test_colander.py::TestSchemaNode::test_serialize_value_is_null_no_default",
"colander/tests/test_colander.py::TestSchemaNode::test_serialize_value_is_null_with_default",
"colander/tests/test_colander.py::TestSchemaNodeSubclassing::test_deferred_methods_dont_quite_work_yet",
"colander/tests/test_colander.py::TestSchemaNodeSubclassing::test_functions_can_be_deferred",
"colander/tests/test_colander.py::TestSchemaNodeSubclassing::test_method_values_can_rely_on_binding",
"colander/tests/test_colander.py::TestSchemaNodeSubclassing::test_nodes_can_be_deffered",
"colander/tests/test_colander.py::TestSchemaNodeSubclassing::test_nonmethod_values_can_be_deferred_though",
"colander/tests/test_colander.py::TestSchemaNodeSubclassing::test_nonmethod_values_can_rely_on_after_bind",
"colander/tests/test_colander.py::TestSchemaNodeSubclassing::test_schema_child_names_conflict_with_value_names_in_subclass",
"colander/tests/test_colander.py::TestSchemaNodeSubclassing::test_schema_child_names_conflict_with_value_names_in_superclass",
"colander/tests/test_colander.py::TestSchemaNodeSubclassing::test_schema_child_names_conflict_with_value_names_notused",
"colander/tests/test_colander.py::TestSchemaNodeSubclassing::test_schema_child_names_conflict_with_value_names_used",
"colander/tests/test_colander.py::TestSchemaNodeSubclassing::test_subclass_title_overwritten_by_constructor",
"colander/tests/test_colander.py::TestSchemaNodeSubclassing::test_subclass_uses_missing",
"colander/tests/test_colander.py::TestSchemaNodeSubclassing::test_subclass_uses_title",
"colander/tests/test_colander.py::TestSchemaNodeSubclassing::test_subclass_uses_validator_method",
"colander/tests/test_colander.py::TestSchemaNodeSubclassing::test_subclass_value_overridden_by_constructor",
"colander/tests/test_colander.py::TestSchemaNodeSubclassing::test_subelement_title_not_overwritten",
"colander/tests/test_colander.py::TestMappingSchemaInheritance::test_insert_before_failure",
"colander/tests/test_colander.py::TestMappingSchemaInheritance::test_multiple_inheritance",
"colander/tests/test_colander.py::TestMappingSchemaInheritance::test_single_inheritance",
"colander/tests/test_colander.py::TestMappingSchemaInheritance::test_single_inheritance2",
"colander/tests/test_colander.py::TestMappingSchemaInheritance::test_single_inheritance_with_insert_before",
"colander/tests/test_colander.py::TestDeferred::test___call__",
"colander/tests/test_colander.py::TestDeferred::test_ctor",
"colander/tests/test_colander.py::TestDeferred::test_retain_func_details",
"colander/tests/test_colander.py::TestDeferred::test_w_callable_instance_no_name",
"colander/tests/test_colander.py::TestDeferred::test_w_callable_instance_no_name_or_doc",
"colander/tests/test_colander.py::TestSchema::test_alias",
"colander/tests/test_colander.py::TestSchema::test_deserialize_drop",
"colander/tests/test_colander.py::TestSchema::test_imperative_with_implicit_schema_type",
"colander/tests/test_colander.py::TestSchema::test_it",
"colander/tests/test_colander.py::TestSchema::test_schema_with_cloned_nodes",
"colander/tests/test_colander.py::TestSchema::test_serialize_drop_default",
"colander/tests/test_colander.py::TestSchema::test_title_munging",
"colander/tests/test_colander.py::TestSequenceSchema::test_clone_with_sequence_schema",
"colander/tests/test_colander.py::TestSequenceSchema::test_deserialize_drop",
"colander/tests/test_colander.py::TestSequenceSchema::test_fail_toofew",
"colander/tests/test_colander.py::TestSequenceSchema::test_fail_toomany",
"colander/tests/test_colander.py::TestSequenceSchema::test_imperative_with_implicit_schema_type",
"colander/tests/test_colander.py::TestSequenceSchema::test_serialize_drop_default",
"colander/tests/test_colander.py::TestSequenceSchema::test_succeed",
"colander/tests/test_colander.py::TestTupleSchema::test_imperative_with_implicit_schema_type",
"colander/tests/test_colander.py::TestTupleSchema::test_it",
"colander/tests/test_colander.py::TestImperative::test_deserialize_ok",
"colander/tests/test_colander.py::TestImperative::test_flatten_mapping_has_no_name",
"colander/tests/test_colander.py::TestImperative::test_flatten_ok",
"colander/tests/test_colander.py::TestImperative::test_flatten_unflatten_roundtrip",
"colander/tests/test_colander.py::TestImperative::test_get_value",
"colander/tests/test_colander.py::TestImperative::test_invalid_asdict",
"colander/tests/test_colander.py::TestImperative::test_invalid_asdict_translation_callback",
"colander/tests/test_colander.py::TestImperative::test_set_value",
"colander/tests/test_colander.py::TestImperative::test_unflatten_mapping_no_name",
"colander/tests/test_colander.py::TestImperative::test_unflatten_ok",
"colander/tests/test_colander.py::TestDeclarative::test_deserialize_ok",
"colander/tests/test_colander.py::TestDeclarative::test_flatten_mapping_has_no_name",
"colander/tests/test_colander.py::TestDeclarative::test_flatten_ok",
"colander/tests/test_colander.py::TestDeclarative::test_flatten_unflatten_roundtrip",
"colander/tests/test_colander.py::TestDeclarative::test_get_value",
"colander/tests/test_colander.py::TestDeclarative::test_invalid_asdict",
"colander/tests/test_colander.py::TestDeclarative::test_invalid_asdict_translation_callback",
"colander/tests/test_colander.py::TestDeclarative::test_set_value",
"colander/tests/test_colander.py::TestDeclarative::test_unflatten_mapping_no_name",
"colander/tests/test_colander.py::TestDeclarative::test_unflatten_ok",
"colander/tests/test_colander.py::TestUltraDeclarative::test_deserialize_ok",
"colander/tests/test_colander.py::TestUltraDeclarative::test_flatten_mapping_has_no_name",
"colander/tests/test_colander.py::TestUltraDeclarative::test_flatten_ok",
"colander/tests/test_colander.py::TestUltraDeclarative::test_flatten_unflatten_roundtrip",
"colander/tests/test_colander.py::TestUltraDeclarative::test_get_value",
"colander/tests/test_colander.py::TestUltraDeclarative::test_invalid_asdict",
"colander/tests/test_colander.py::TestUltraDeclarative::test_invalid_asdict_translation_callback",
"colander/tests/test_colander.py::TestUltraDeclarative::test_set_value",
"colander/tests/test_colander.py::TestUltraDeclarative::test_unflatten_mapping_no_name",
"colander/tests/test_colander.py::TestUltraDeclarative::test_unflatten_ok",
"colander/tests/test_colander.py::TestDeclarativeWithInstantiate::test_deserialize_ok",
"colander/tests/test_colander.py::TestDeclarativeWithInstantiate::test_flatten_mapping_has_no_name",
"colander/tests/test_colander.py::TestDeclarativeWithInstantiate::test_flatten_ok",
"colander/tests/test_colander.py::TestDeclarativeWithInstantiate::test_flatten_unflatten_roundtrip",
"colander/tests/test_colander.py::TestDeclarativeWithInstantiate::test_get_value",
"colander/tests/test_colander.py::TestDeclarativeWithInstantiate::test_invalid_asdict",
"colander/tests/test_colander.py::TestDeclarativeWithInstantiate::test_invalid_asdict_translation_callback",
"colander/tests/test_colander.py::TestDeclarativeWithInstantiate::test_set_value",
"colander/tests/test_colander.py::TestDeclarativeWithInstantiate::test_unflatten_mapping_no_name",
"colander/tests/test_colander.py::TestDeclarativeWithInstantiate::test_unflatten_ok",
"colander/tests/test_colander.py::Test_null::test___nonzero__",
"colander/tests/test_colander.py::Test_null::test___repr__",
"colander/tests/test_colander.py::Test_null::test_pickling",
"colander/tests/test_colander.py::Test_required::test___repr__",
"colander/tests/test_colander.py::Test_required::test_pickling",
"colander/tests/test_colander.py::Test_drop::test___repr__",
"colander/tests/test_colander.py::Test_drop::test_pickling"
] | {
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2019-02-01T07:16:12Z" | bsd-4-clause |
|
Pylons__colander-322 | diff --git a/CHANGES.rst b/CHANGES.rst
index c40160b..d6903c1 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -1,6 +1,23 @@
Unreleased
==========
+- The URL validator regex has been updated to no longer be vulnerable to a
+ catastrophic backtracking that would have led to an infinite loop. See
+ https://github.com/Pylons/colander/pull/323 and
+ https://github.com/Pylons/colander/issues/290. With thanks to Przemek
+ (https://github.com/p-m-k).
+
+ This does change the behaviour of the URL validator and it no longer supports
+ ``file://`` URI scheme (https://tools.ietf.org/html/rfc8089). Users that
+ wish to validate ``file://`` URI's should change their validator to use
+ ``colander.file_uri`` instead.
+
+ It has also dropped support for alternate schemes outside of http/ftp (and
+ their secure equivelants). Please let us know if we need to relax this
+ requirement.
+
+ CVE-ID: CVE-2017-18361
+
- The Email validator has been updated to use the same regular expression that
is used by the WhatWG HTML specification, thereby increasing the email
addresses that will validate correctly from web forms submitted. See
@@ -11,6 +28,11 @@ Unreleased
reverts an accidental revert. See
https://github.com/Pylons/colander/issues/204#issuecomment-459556100
+- Integer SchemaType now supports an optional ``strict`` mode that will
+ validate that the number is an integer, rather than silently accepting floats
+ and truncating. See https://github.com/Pylons/colander/pull/322 and
+ https://github.com/Pylons/colander/issues/292
+
1.6.0 (2019-01-31)
==================
diff --git a/colander/__init__.py b/colander/__init__.py
index 6f0dff5..e5ed2c7 100644
--- a/colander/__init__.py
+++ b/colander/__init__.py
@@ -607,14 +607,40 @@ def _luhnok(value):
return checksum
+# Gingerly lifted from Django 1.3.x:
+# https://github.com/django/django/blob/stable/1.3.x/django/core/validators.py#L45
+# <3 y'all!
URL_REGEX = (
- r'(?i)\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|'
- r'[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|'
- r'(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|'
- r'[^\s`!()\[\]{};:\'".,<>?«»“”‘’]))' # "emacs!
+ # {http,ftp}s:// (not required)
+ r'^((?:http|ftp)s?://)?'
+ # Domain
+ r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+'
+ r'(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|'
+ # Localhost
+ r'localhost|'
+ # IPv6 address
+ r'\[[a-f0-9:]+\]|'
+ # IPv4 address
+ r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'
+ # Optional port
+ r'(?::\d+)?'
+ # Path
+ r'(?:/?|[/?]\S+)$'
)
-url = Regex(URL_REGEX, _('Must be a URL'))
+url = Regex(URL_REGEX, msg=_('Must be a URL'), flags=re.IGNORECASE)
+
+
+URI_REGEX = (
+ # file:// (required)
+ r'^file://'
+ # Path
+ r'(?:/|[/?]\S+)$'
+)
+
+file_uri = Regex(
+ URI_REGEX, msg=_('Must be a file:// URI scheme'), flags=re.IGNORECASE
+)
UUID_REGEX = (
r'^(?:urn:uuid:)?\{?[a-f0-9]{8}(?:-?[a-f0-9]{4}){3}-?[a-f0-9]{12}\}?$'
@@ -1426,12 +1452,28 @@ class Integer(Number):
method of this class, the :attr:`colander.null` value will be
returned.
+ The Integer constructor takes an optional argument ``strict``, which if
+ enabled will verify that the number passed to serialize/deserialize is an
+ integer, and not a float that would get truncated.
+
The subnodes of the :class:`colander.SchemaNode` that wraps
this type are ignored.
"""
num = int
+ def __init__(self, strict=False):
+ if strict:
+
+ def _strict_int(val):
+ if not float(val).is_integer():
+ raise ValueError("Value is not an Integer")
+ return int(val)
+
+ self.num = _strict_int
+
+ super(Integer, self).__init__()
+
Int = Integer
| Pylons/colander | 1c3bd63aa06b4f01081035c1b54ff4586aef4c9f | diff --git a/colander/tests/test_colander.py b/colander/tests/test_colander.py
index 917a719..90b4d91 100644
--- a/colander/tests/test_colander.py
+++ b/colander/tests/test_colander.py
@@ -646,6 +646,76 @@ class Test_url_validator(unittest.TestCase):
self.assertRaises(Invalid, self._callFUT, val)
+ def test_add_sample_dos(self):
+ # In the old regex (colander <=1.6) this would cause a catastrophic
+ # backtracking that would cause the regex engine to go into an infinite
+ # loop.
+ val = "http://www.mysite.com/(tttttttttttttttttttttt.jpg"
+
+ result = self._callFUT(val)
+ self.assertEqual(result, None)
+
+ def test_website_no_scheme(self):
+ val = "www.mysite.com"
+
+ result = self._callFUT(val)
+ self.assertEqual(result, None)
+
+ def test_ipv6(self):
+ val = "http://[2001:db8::0]/"
+
+ result = self._callFUT(val)
+ self.assertEqual(result, None)
+
+ def test_ipv4(self):
+ val = "http://192.0.2.1/"
+
+ result = self._callFUT(val)
+ self.assertEqual(result, None)
+
+ def test_file_raises(self):
+ from colander import Invalid
+
+ val = "file:///this/is/a/file.jpg"
+
+ self.assertRaises(Invalid, self._callFUT, val)
+
+
+class Test_file_uri_validator(unittest.TestCase):
+ def _callFUT(self, val):
+ from colander import file_uri
+
+ return file_uri(None, val)
+
+ def test_it_success(self):
+ val = 'file:///'
+ result = self._callFUT(val)
+ self.assertEqual(result, None)
+
+ def test_it_failure(self):
+ val = 'not-a-uri'
+ from colander import Invalid
+
+ self.assertRaises(Invalid, self._callFUT, val)
+
+ def test_no_path_fails(self):
+ val = 'file://'
+ from colander import Invalid
+
+ self.assertRaises(Invalid, self._callFUT, val)
+
+ def test_file_with_path(self):
+ val = "file:///this/is/a/file.jpg"
+
+ result = self._callFUT(val)
+ self.assertEqual(result, None)
+
+ def test_file_with_path_windows(self):
+ val = "file:///c:/is/a/file.jpg"
+
+ result = self._callFUT(val)
+ self.assertEqual(result, None)
+
class TestUUID(unittest.TestCase):
def _callFUT(self, val):
@@ -1730,10 +1800,10 @@ class TestString(unittest.TestCase):
class TestInteger(unittest.TestCase):
- def _makeOne(self):
+ def _makeOne(self, strict=False):
from colander import Integer
- return Integer()
+ return Integer(strict=strict)
def test_alias(self):
from colander import Int
@@ -1802,6 +1872,34 @@ class TestInteger(unittest.TestCase):
result = typ.serialize(node, val)
self.assertEqual(result, '0')
+ def test_serialize_strict_float(self):
+ val = 1.2
+ node = DummySchemaNode(None)
+ typ = self._makeOne(strict=True)
+ e = invalid_exc(typ.serialize, node, val)
+ self.assertTrue(e.msg)
+
+ def test_serialize_strict_int(self):
+ val = 1
+ node = DummySchemaNode(None)
+ typ = self._makeOne(strict=True)
+ result = typ.serialize(node, val)
+ self.assertEqual(result, '1')
+
+ def test_deserialize_strict(self):
+ val = '58'
+ node = DummySchemaNode(None)
+ typ = self._makeOne(strict=True)
+ result = typ.deserialize(node, val)
+ self.assertEqual(result, 58)
+
+ def test_serialize_truncates(self):
+ val = 1.4
+ node = DummySchemaNode(None)
+ typ = self._makeOne(strict=False)
+ result = typ.serialize(node, val)
+ self.assertEqual(result, '1')
+
class TestFloat(unittest.TestCase):
def _makeOne(self):
| passing a float to colander.Integer does not throw exception
When passing a float value (e.g. 1.21) to a colander.Integer node, no exception is thrown.
I am not sure of the expected behaviour though...
Version: 1.3.3 | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"colander/tests/test_colander.py::Test_url_validator::test_file_raises",
"colander/tests/test_colander.py::Test_file_uri_validator::test_file_with_path",
"colander/tests/test_colander.py::Test_file_uri_validator::test_file_with_path_windows",
"colander/tests/test_colander.py::Test_file_uri_validator::test_it_failure",
"colander/tests/test_colander.py::Test_file_uri_validator::test_it_success",
"colander/tests/test_colander.py::Test_file_uri_validator::test_no_path_fails",
"colander/tests/test_colander.py::TestInteger::test_deserialize_emptystring",
"colander/tests/test_colander.py::TestInteger::test_deserialize_fails",
"colander/tests/test_colander.py::TestInteger::test_deserialize_ok",
"colander/tests/test_colander.py::TestInteger::test_deserialize_strict",
"colander/tests/test_colander.py::TestInteger::test_serialize_fails",
"colander/tests/test_colander.py::TestInteger::test_serialize_none",
"colander/tests/test_colander.py::TestInteger::test_serialize_null",
"colander/tests/test_colander.py::TestInteger::test_serialize_ok",
"colander/tests/test_colander.py::TestInteger::test_serialize_strict_float",
"colander/tests/test_colander.py::TestInteger::test_serialize_strict_int",
"colander/tests/test_colander.py::TestInteger::test_serialize_truncates",
"colander/tests/test_colander.py::TestInteger::test_serialize_zero"
] | [
"colander/tests/test_colander.py::TestInvalid::test___setitem__fails",
"colander/tests/test_colander.py::TestInvalid::test___setitem__succeeds",
"colander/tests/test_colander.py::TestInvalid::test___str__",
"colander/tests/test_colander.py::TestInvalid::test__keyname_no_parent",
"colander/tests/test_colander.py::TestInvalid::test__keyname_nonpositional_parent",
"colander/tests/test_colander.py::TestInvalid::test__keyname_positional",
"colander/tests/test_colander.py::TestInvalid::test_add",
"colander/tests/test_colander.py::TestInvalid::test_add_positional",
"colander/tests/test_colander.py::TestInvalid::test_asdict",
"colander/tests/test_colander.py::TestInvalid::test_asdict_with_all_validator",
"colander/tests/test_colander.py::TestInvalid::test_asdict_with_all_validator_functional",
"colander/tests/test_colander.py::TestInvalid::test_ctor",
"colander/tests/test_colander.py::TestInvalid::test_messages_msg_None",
"colander/tests/test_colander.py::TestInvalid::test_messages_msg_iterable",
"colander/tests/test_colander.py::TestInvalid::test_messages_msg_not_iterable",
"colander/tests/test_colander.py::TestInvalid::test_paths",
"colander/tests/test_colander.py::TestAll::test_Invalid_children",
"colander/tests/test_colander.py::TestAll::test_failure",
"colander/tests/test_colander.py::TestAll::test_success",
"colander/tests/test_colander.py::TestAny::test_Invalid_children",
"colander/tests/test_colander.py::TestAny::test_failure",
"colander/tests/test_colander.py::TestAny::test_success",
"colander/tests/test_colander.py::TestFunction::test_deprecated_message",
"colander/tests/test_colander.py::TestFunction::test_deprecated_message_warning",
"colander/tests/test_colander.py::TestFunction::test_error_message_adds_mapping_to_configured_message",
"colander/tests/test_colander.py::TestFunction::test_error_message_adds_mapping_to_return_message",
"colander/tests/test_colander.py::TestFunction::test_error_message_does_not_overwrite_configured_domain",
"colander/tests/test_colander.py::TestFunction::test_error_message_does_not_overwrite_returned_domain",
"colander/tests/test_colander.py::TestFunction::test_fail_function_returns_False",
"colander/tests/test_colander.py::TestFunction::test_fail_function_returns_empty_string",
"colander/tests/test_colander.py::TestFunction::test_fail_function_returns_string",
"colander/tests/test_colander.py::TestFunction::test_msg_and_message_error",
"colander/tests/test_colander.py::TestFunction::test_propagation",
"colander/tests/test_colander.py::TestFunction::test_success_function_returns_True",
"colander/tests/test_colander.py::TestRange::test_max_failure",
"colander/tests/test_colander.py::TestRange::test_max_failure_msg_override",
"colander/tests/test_colander.py::TestRange::test_min_failure",
"colander/tests/test_colander.py::TestRange::test_min_failure_msg_override",
"colander/tests/test_colander.py::TestRange::test_success_min_and_max",
"colander/tests/test_colander.py::TestRange::test_success_minimum_bound_only",
"colander/tests/test_colander.py::TestRange::test_success_no_bounds",
"colander/tests/test_colander.py::TestRange::test_success_upper_bound_only",
"colander/tests/test_colander.py::TestRegex::test_invalid_regexs",
"colander/tests/test_colander.py::TestRegex::test_regex_not_string",
"colander/tests/test_colander.py::TestRegex::test_valid_regex",
"colander/tests/test_colander.py::TestEmail::test_empty_email",
"colander/tests/test_colander.py::TestEmail::test_invalid_emails",
"colander/tests/test_colander.py::TestEmail::test_valid_emails",
"colander/tests/test_colander.py::TestLength::test_max_failure",
"colander/tests/test_colander.py::TestLength::test_max_failure_msg_override",
"colander/tests/test_colander.py::TestLength::test_min_failure",
"colander/tests/test_colander.py::TestLength::test_min_failure_msg_override",
"colander/tests/test_colander.py::TestLength::test_success_min_and_max",
"colander/tests/test_colander.py::TestLength::test_success_minimum_bound_only",
"colander/tests/test_colander.py::TestLength::test_success_no_bounds",
"colander/tests/test_colander.py::TestLength::test_success_upper_bound_only",
"colander/tests/test_colander.py::TestOneOf::test_failure",
"colander/tests/test_colander.py::TestOneOf::test_success",
"colander/tests/test_colander.py::TestNoneOf::test_failure",
"colander/tests/test_colander.py::TestNoneOf::test_success",
"colander/tests/test_colander.py::TestContainsOnly::test_failure",
"colander/tests/test_colander.py::TestContainsOnly::test_failure_with_custom_error_template",
"colander/tests/test_colander.py::TestContainsOnly::test_success",
"colander/tests/test_colander.py::Test_luhnok::test_fail",
"colander/tests/test_colander.py::Test_luhnok::test_fail2",
"colander/tests/test_colander.py::Test_luhnok::test_fail3",
"colander/tests/test_colander.py::Test_luhnok::test_success",
"colander/tests/test_colander.py::Test_url_validator::test_add_sample_dos",
"colander/tests/test_colander.py::Test_url_validator::test_ipv4",
"colander/tests/test_colander.py::Test_url_validator::test_ipv6",
"colander/tests/test_colander.py::Test_url_validator::test_it_failure",
"colander/tests/test_colander.py::Test_url_validator::test_it_success",
"colander/tests/test_colander.py::Test_url_validator::test_website_no_scheme",
"colander/tests/test_colander.py::TestUUID::test_failure_invalid_length",
"colander/tests/test_colander.py::TestUUID::test_failure_not_hexadecimal",
"colander/tests/test_colander.py::TestUUID::test_failure_random_string",
"colander/tests/test_colander.py::TestUUID::test_failure_with_invalid_urn_ns",
"colander/tests/test_colander.py::TestUUID::test_success_hexadecimal",
"colander/tests/test_colander.py::TestUUID::test_success_upper_case",
"colander/tests/test_colander.py::TestUUID::test_success_with_braces",
"colander/tests/test_colander.py::TestUUID::test_success_with_dashes",
"colander/tests/test_colander.py::TestUUID::test_success_with_urn_ns",
"colander/tests/test_colander.py::TestSchemaType::test_cstruct_children",
"colander/tests/test_colander.py::TestSchemaType::test_flatten",
"colander/tests/test_colander.py::TestSchemaType::test_flatten_listitem",
"colander/tests/test_colander.py::TestSchemaType::test_get_value",
"colander/tests/test_colander.py::TestSchemaType::test_set_value",
"colander/tests/test_colander.py::TestSchemaType::test_unflatten",
"colander/tests/test_colander.py::TestMapping::test_cstruct_children",
"colander/tests/test_colander.py::TestMapping::test_cstruct_children_cstruct_is_null",
"colander/tests/test_colander.py::TestMapping::test_ctor_bad_unknown",
"colander/tests/test_colander.py::TestMapping::test_ctor_good_unknown",
"colander/tests/test_colander.py::TestMapping::test_deserialize_no_subnodes",
"colander/tests/test_colander.py::TestMapping::test_deserialize_not_a_mapping",
"colander/tests/test_colander.py::TestMapping::test_deserialize_null",
"colander/tests/test_colander.py::TestMapping::test_deserialize_ok",
"colander/tests/test_colander.py::TestMapping::test_deserialize_subnode_missing_default",
"colander/tests/test_colander.py::TestMapping::test_deserialize_subnodes_raise",
"colander/tests/test_colander.py::TestMapping::test_deserialize_unknown_preserve",
"colander/tests/test_colander.py::TestMapping::test_deserialize_unknown_raise",
"colander/tests/test_colander.py::TestMapping::test_flatten",
"colander/tests/test_colander.py::TestMapping::test_flatten_listitem",
"colander/tests/test_colander.py::TestMapping::test_get_value",
"colander/tests/test_colander.py::TestMapping::test_serialize_no_subnodes",
"colander/tests/test_colander.py::TestMapping::test_serialize_not_a_mapping",
"colander/tests/test_colander.py::TestMapping::test_serialize_null",
"colander/tests/test_colander.py::TestMapping::test_serialize_ok",
"colander/tests/test_colander.py::TestMapping::test_serialize_value_has_drop",
"colander/tests/test_colander.py::TestMapping::test_serialize_value_is_null",
"colander/tests/test_colander.py::TestMapping::test_serialize_with_unknown",
"colander/tests/test_colander.py::TestMapping::test_set_value",
"colander/tests/test_colander.py::TestMapping::test_unflatten",
"colander/tests/test_colander.py::TestMapping::test_unflatten_nested",
"colander/tests/test_colander.py::TestTuple::test_cstruct_children_cstruct_is_null",
"colander/tests/test_colander.py::TestTuple::test_cstruct_children_justright",
"colander/tests/test_colander.py::TestTuple::test_cstruct_children_toofew",
"colander/tests/test_colander.py::TestTuple::test_cstruct_children_toomany",
"colander/tests/test_colander.py::TestTuple::test_deserialize_no_subnodes",
"colander/tests/test_colander.py::TestTuple::test_deserialize_not_iterable",
"colander/tests/test_colander.py::TestTuple::test_deserialize_null",
"colander/tests/test_colander.py::TestTuple::test_deserialize_ok",
"colander/tests/test_colander.py::TestTuple::test_deserialize_subnodes_raise",
"colander/tests/test_colander.py::TestTuple::test_deserialize_toobig",
"colander/tests/test_colander.py::TestTuple::test_deserialize_toosmall",
"colander/tests/test_colander.py::TestTuple::test_flatten",
"colander/tests/test_colander.py::TestTuple::test_flatten_listitem",
"colander/tests/test_colander.py::TestTuple::test_get_value",
"colander/tests/test_colander.py::TestTuple::test_get_value_bad_path",
"colander/tests/test_colander.py::TestTuple::test_serialize_no_subnodes",
"colander/tests/test_colander.py::TestTuple::test_serialize_not_iterable",
"colander/tests/test_colander.py::TestTuple::test_serialize_null",
"colander/tests/test_colander.py::TestTuple::test_serialize_ok",
"colander/tests/test_colander.py::TestTuple::test_serialize_subnodes_raise",
"colander/tests/test_colander.py::TestTuple::test_serialize_toobig",
"colander/tests/test_colander.py::TestTuple::test_serialize_toosmall",
"colander/tests/test_colander.py::TestTuple::test_set_value",
"colander/tests/test_colander.py::TestTuple::test_set_value_bad_path",
"colander/tests/test_colander.py::TestTuple::test_unflatten",
"colander/tests/test_colander.py::TestSet::test_deserialize_empty_set",
"colander/tests/test_colander.py::TestSet::test_deserialize_no_iter",
"colander/tests/test_colander.py::TestSet::test_deserialize_null",
"colander/tests/test_colander.py::TestSet::test_deserialize_str_no_iter",
"colander/tests/test_colander.py::TestSet::test_deserialize_valid",
"colander/tests/test_colander.py::TestSet::test_serialize",
"colander/tests/test_colander.py::TestSet::test_serialize_null",
"colander/tests/test_colander.py::TestList::test_deserialize_empty_set",
"colander/tests/test_colander.py::TestList::test_deserialize_no_iter",
"colander/tests/test_colander.py::TestList::test_deserialize_null",
"colander/tests/test_colander.py::TestList::test_deserialize_str_no_iter",
"colander/tests/test_colander.py::TestList::test_deserialize_valid",
"colander/tests/test_colander.py::TestList::test_serialize",
"colander/tests/test_colander.py::TestList::test_serialize_null",
"colander/tests/test_colander.py::TestSequence::test_alias",
"colander/tests/test_colander.py::TestSequence::test_cstruct_children_cstruct_is_non_null",
"colander/tests/test_colander.py::TestSequence::test_cstruct_children_cstruct_is_null",
"colander/tests/test_colander.py::TestSequence::test_deserialize_no_null",
"colander/tests/test_colander.py::TestSequence::test_deserialize_no_subnodes",
"colander/tests/test_colander.py::TestSequence::test_deserialize_not_iterable",
"colander/tests/test_colander.py::TestSequence::test_deserialize_not_iterable_accept_scalar",
"colander/tests/test_colander.py::TestSequence::test_deserialize_ok",
"colander/tests/test_colander.py::TestSequence::test_deserialize_string_accept_scalar",
"colander/tests/test_colander.py::TestSequence::test_deserialize_subnodes_raise",
"colander/tests/test_colander.py::TestSequence::test_flatten",
"colander/tests/test_colander.py::TestSequence::test_flatten_listitem",
"colander/tests/test_colander.py::TestSequence::test_flatten_with_integer",
"colander/tests/test_colander.py::TestSequence::test_getvalue",
"colander/tests/test_colander.py::TestSequence::test_serialize_drop",
"colander/tests/test_colander.py::TestSequence::test_serialize_no_subnodes",
"colander/tests/test_colander.py::TestSequence::test_serialize_not_iterable",
"colander/tests/test_colander.py::TestSequence::test_serialize_not_iterable_accept_scalar",
"colander/tests/test_colander.py::TestSequence::test_serialize_null",
"colander/tests/test_colander.py::TestSequence::test_serialize_ok",
"colander/tests/test_colander.py::TestSequence::test_serialize_string_accept_scalar",
"colander/tests/test_colander.py::TestSequence::test_serialize_subnodes_raise",
"colander/tests/test_colander.py::TestSequence::test_setvalue",
"colander/tests/test_colander.py::TestSequence::test_unflatten",
"colander/tests/test_colander.py::TestString::test_alias",
"colander/tests/test_colander.py::TestString::test_deserialize_emptystring",
"colander/tests/test_colander.py::TestString::test_deserialize_from_nonstring_obj",
"colander/tests/test_colander.py::TestString::test_deserialize_from_utf16",
"colander/tests/test_colander.py::TestString::test_deserialize_from_utf8",
"colander/tests/test_colander.py::TestString::test_deserialize_nonunicode_from_None",
"colander/tests/test_colander.py::TestString::test_deserialize_uncooperative",
"colander/tests/test_colander.py::TestString::test_deserialize_unicode_from_None",
"colander/tests/test_colander.py::TestString::test_serialize_emptystring",
"colander/tests/test_colander.py::TestString::test_serialize_encoding_with_non_string_type",
"colander/tests/test_colander.py::TestString::test_serialize_nonunicode_to_None",
"colander/tests/test_colander.py::TestString::test_serialize_null",
"colander/tests/test_colander.py::TestString::test_serialize_string_with_high_unresolveable_high_order_chars",
"colander/tests/test_colander.py::TestString::test_serialize_to_utf16",
"colander/tests/test_colander.py::TestString::test_serialize_to_utf8",
"colander/tests/test_colander.py::TestString::test_serialize_uncooperative",
"colander/tests/test_colander.py::TestString::test_serialize_unicode_to_None",
"colander/tests/test_colander.py::TestInteger::test_alias",
"colander/tests/test_colander.py::TestFloat::test_deserialize_fails",
"colander/tests/test_colander.py::TestFloat::test_deserialize_ok",
"colander/tests/test_colander.py::TestFloat::test_serialize_emptystring",
"colander/tests/test_colander.py::TestFloat::test_serialize_fails",
"colander/tests/test_colander.py::TestFloat::test_serialize_none",
"colander/tests/test_colander.py::TestFloat::test_serialize_null",
"colander/tests/test_colander.py::TestFloat::test_serialize_ok",
"colander/tests/test_colander.py::TestFloat::test_serialize_zero",
"colander/tests/test_colander.py::TestDecimal::test_deserialize_fails",
"colander/tests/test_colander.py::TestDecimal::test_deserialize_ok",
"colander/tests/test_colander.py::TestDecimal::test_deserialize_with_normalize",
"colander/tests/test_colander.py::TestDecimal::test_deserialize_with_quantize",
"colander/tests/test_colander.py::TestDecimal::test_serialize_emptystring",
"colander/tests/test_colander.py::TestDecimal::test_serialize_fails",
"colander/tests/test_colander.py::TestDecimal::test_serialize_none",
"colander/tests/test_colander.py::TestDecimal::test_serialize_normalize",
"colander/tests/test_colander.py::TestDecimal::test_serialize_null",
"colander/tests/test_colander.py::TestDecimal::test_serialize_ok",
"colander/tests/test_colander.py::TestDecimal::test_serialize_quantize_no_rounding",
"colander/tests/test_colander.py::TestDecimal::test_serialize_quantize_with_rounding_up",
"colander/tests/test_colander.py::TestDecimal::test_serialize_zero",
"colander/tests/test_colander.py::TestMoney::test_deserialize_rounds_up",
"colander/tests/test_colander.py::TestMoney::test_serialize_rounds_up",
"colander/tests/test_colander.py::TestBoolean::test_alias",
"colander/tests/test_colander.py::TestBoolean::test_deserialize",
"colander/tests/test_colander.py::TestBoolean::test_deserialize_null",
"colander/tests/test_colander.py::TestBoolean::test_deserialize_unstringable",
"colander/tests/test_colander.py::TestBoolean::test_serialize",
"colander/tests/test_colander.py::TestBoolean::test_serialize_null",
"colander/tests/test_colander.py::TestBooleanCustomFalseReprs::test_deserialize",
"colander/tests/test_colander.py::TestBooleanCustomFalseAndTrueReprs::test_deserialize",
"colander/tests/test_colander.py::TestBooleanCustomSerializations::test_serialize",
"colander/tests/test_colander.py::TestGlobalObject::test__pkg_resources_style_irrresolveable_absolute",
"colander/tests/test_colander.py::TestGlobalObject::test__pkg_resources_style_irrresolveable_relative",
"colander/tests/test_colander.py::TestGlobalObject::test__pkg_resources_style_resolve_absolute",
"colander/tests/test_colander.py::TestGlobalObject::test__pkg_resources_style_resolve_relative_is_dot",
"colander/tests/test_colander.py::TestGlobalObject::test__pkg_resources_style_resolve_relative_nocurrentpackage",
"colander/tests/test_colander.py::TestGlobalObject::test__pkg_resources_style_resolve_relative_startswith_colon",
"colander/tests/test_colander.py::TestGlobalObject::test__pkg_resources_style_resolve_relative_startswith_dot",
"colander/tests/test_colander.py::TestGlobalObject::test__zope_dottedname_style_irresolveable_absolute",
"colander/tests/test_colander.py::TestGlobalObject::test__zope_dottedname_style_irresolveable_relative_is_dot",
"colander/tests/test_colander.py::TestGlobalObject::test__zope_dottedname_style_resolve_relative",
"colander/tests/test_colander.py::TestGlobalObject::test__zope_dottedname_style_resolve_relative_is_dot",
"colander/tests/test_colander.py::TestGlobalObject::test__zope_dottedname_style_resolve_relative_leading_dots",
"colander/tests/test_colander.py::TestGlobalObject::test__zope_dottedname_style_resolveable_absolute",
"colander/tests/test_colander.py::TestGlobalObject::test__zope_dottedname_style_resolveable_relative",
"colander/tests/test_colander.py::TestGlobalObject::test_deserialize_None",
"colander/tests/test_colander.py::TestGlobalObject::test_deserialize_class_fail",
"colander/tests/test_colander.py::TestGlobalObject::test_deserialize_class_ok",
"colander/tests/test_colander.py::TestGlobalObject::test_deserialize_notastring",
"colander/tests/test_colander.py::TestGlobalObject::test_deserialize_null",
"colander/tests/test_colander.py::TestGlobalObject::test_deserialize_style_raises",
"colander/tests/test_colander.py::TestGlobalObject::test_deserialize_using_pkgresources_style",
"colander/tests/test_colander.py::TestGlobalObject::test_deserialize_using_zope_dottedname_style",
"colander/tests/test_colander.py::TestGlobalObject::test_serialize_class",
"colander/tests/test_colander.py::TestGlobalObject::test_serialize_fail",
"colander/tests/test_colander.py::TestGlobalObject::test_serialize_null",
"colander/tests/test_colander.py::TestGlobalObject::test_serialize_ok",
"colander/tests/test_colander.py::TestGlobalObject::test_zope_dottedname_style_irrresolveable_absolute",
"colander/tests/test_colander.py::TestGlobalObject::test_zope_dottedname_style_irrresolveable_relative",
"colander/tests/test_colander.py::TestGlobalObject::test_zope_dottedname_style_resolve_absolute",
"colander/tests/test_colander.py::TestGlobalObject::test_zope_dottedname_style_resolve_relative_nocurrentpackage",
"colander/tests/test_colander.py::TestDateTime::test_ctor_default_tzinfo_None",
"colander/tests/test_colander.py::TestDateTime::test_ctor_default_tzinfo_non_None",
"colander/tests/test_colander.py::TestDateTime::test_ctor_default_tzinfo_not_specified",
"colander/tests/test_colander.py::TestDateTime::test_deserialize_date",
"colander/tests/test_colander.py::TestDateTime::test_deserialize_datetime_with_custom_format",
"colander/tests/test_colander.py::TestDateTime::test_deserialize_empty",
"colander/tests/test_colander.py::TestDateTime::test_deserialize_invalid_ParseError",
"colander/tests/test_colander.py::TestDateTime::test_deserialize_naive_with_default_tzinfo",
"colander/tests/test_colander.py::TestDateTime::test_deserialize_none_tzinfo",
"colander/tests/test_colander.py::TestDateTime::test_deserialize_null",
"colander/tests/test_colander.py::TestDateTime::test_deserialize_slashes_invalid",
"colander/tests/test_colander.py::TestDateTime::test_deserialize_success",
"colander/tests/test_colander.py::TestDateTime::test_serialize_none",
"colander/tests/test_colander.py::TestDateTime::test_serialize_null",
"colander/tests/test_colander.py::TestDateTime::test_serialize_with_date",
"colander/tests/test_colander.py::TestDateTime::test_serialize_with_garbage",
"colander/tests/test_colander.py::TestDateTime::test_serialize_with_naive_datetime",
"colander/tests/test_colander.py::TestDateTime::test_serialize_with_naive_datetime_and_custom_format",
"colander/tests/test_colander.py::TestDateTime::test_serialize_with_none_tzinfo_naive_datetime",
"colander/tests/test_colander.py::TestDateTime::test_serialize_with_none_tzinfo_naive_datetime_custom_format",
"colander/tests/test_colander.py::TestDateTime::test_serialize_with_tzware_datetime",
"colander/tests/test_colander.py::TestDate::test_deserialize_date_with_custom_format",
"colander/tests/test_colander.py::TestDate::test_deserialize_empty",
"colander/tests/test_colander.py::TestDate::test_deserialize_invalid_ParseError",
"colander/tests/test_colander.py::TestDate::test_deserialize_invalid_weird",
"colander/tests/test_colander.py::TestDate::test_deserialize_null",
"colander/tests/test_colander.py::TestDate::test_deserialize_success_date",
"colander/tests/test_colander.py::TestDate::test_deserialize_success_datetime",
"colander/tests/test_colander.py::TestDate::test_serialize_date_with_custom_format",
"colander/tests/test_colander.py::TestDate::test_serialize_none",
"colander/tests/test_colander.py::TestDate::test_serialize_null",
"colander/tests/test_colander.py::TestDate::test_serialize_with_date",
"colander/tests/test_colander.py::TestDate::test_serialize_with_datetime",
"colander/tests/test_colander.py::TestDate::test_serialize_with_garbage",
"colander/tests/test_colander.py::TestTime::test_deserialize_empty",
"colander/tests/test_colander.py::TestTime::test_deserialize_four_digit_string",
"colander/tests/test_colander.py::TestTime::test_deserialize_invalid_ParseError",
"colander/tests/test_colander.py::TestTime::test_deserialize_missing_seconds",
"colander/tests/test_colander.py::TestTime::test_deserialize_null",
"colander/tests/test_colander.py::TestTime::test_deserialize_success_datetime",
"colander/tests/test_colander.py::TestTime::test_deserialize_success_time",
"colander/tests/test_colander.py::TestTime::test_deserialize_three_digit_string",
"colander/tests/test_colander.py::TestTime::test_deserialize_two_digit_string",
"colander/tests/test_colander.py::TestTime::test_serialize_none",
"colander/tests/test_colander.py::TestTime::test_serialize_null",
"colander/tests/test_colander.py::TestTime::test_serialize_with_datetime",
"colander/tests/test_colander.py::TestTime::test_serialize_with_garbage",
"colander/tests/test_colander.py::TestTime::test_serialize_with_time",
"colander/tests/test_colander.py::TestTime::test_serialize_with_zero_time",
"colander/tests/test_colander.py::TestEnum::test_deserialize_failure",
"colander/tests/test_colander.py::TestEnum::test_deserialize_failure_typ",
"colander/tests/test_colander.py::TestEnum::test_deserialize_name",
"colander/tests/test_colander.py::TestEnum::test_deserialize_null",
"colander/tests/test_colander.py::TestEnum::test_deserialize_value_int",
"colander/tests/test_colander.py::TestEnum::test_deserialize_value_str",
"colander/tests/test_colander.py::TestEnum::test_non_unique_failure",
"colander/tests/test_colander.py::TestEnum::test_non_unique_failure2",
"colander/tests/test_colander.py::TestEnum::test_serialize_failure",
"colander/tests/test_colander.py::TestEnum::test_serialize_name",
"colander/tests/test_colander.py::TestEnum::test_serialize_null",
"colander/tests/test_colander.py::TestEnum::test_serialize_value_int",
"colander/tests/test_colander.py::TestEnum::test_serialize_value_str",
"colander/tests/test_colander.py::TestSchemaNode::test___contains__",
"colander/tests/test_colander.py::TestSchemaNode::test___delitem__failure",
"colander/tests/test_colander.py::TestSchemaNode::test___delitem__success",
"colander/tests/test_colander.py::TestSchemaNode::test___getitem__failure",
"colander/tests/test_colander.py::TestSchemaNode::test___getitem__success",
"colander/tests/test_colander.py::TestSchemaNode::test___iter__",
"colander/tests/test_colander.py::TestSchemaNode::test___setitem__no_override",
"colander/tests/test_colander.py::TestSchemaNode::test___setitem__override",
"colander/tests/test_colander.py::TestSchemaNode::test_add",
"colander/tests/test_colander.py::TestSchemaNode::test_bind",
"colander/tests/test_colander.py::TestSchemaNode::test_bind_with_after_bind",
"colander/tests/test_colander.py::TestSchemaNode::test_clone",
"colander/tests/test_colander.py::TestSchemaNode::test_clone_mapping_references",
"colander/tests/test_colander.py::TestSchemaNode::test_clone_with_modified_schema_instance",
"colander/tests/test_colander.py::TestSchemaNode::test_cstruct_children",
"colander/tests/test_colander.py::TestSchemaNode::test_cstruct_children_warning",
"colander/tests/test_colander.py::TestSchemaNode::test_ctor_children_kwarg_typ",
"colander/tests/test_colander.py::TestSchemaNode::test_ctor_no_title",
"colander/tests/test_colander.py::TestSchemaNode::test_ctor_with_description",
"colander/tests/test_colander.py::TestSchemaNode::test_ctor_with_kwarg_typ",
"colander/tests/test_colander.py::TestSchemaNode::test_ctor_with_preparer",
"colander/tests/test_colander.py::TestSchemaNode::test_ctor_with_title",
"colander/tests/test_colander.py::TestSchemaNode::test_ctor_with_unknown_kwarg",
"colander/tests/test_colander.py::TestSchemaNode::test_ctor_with_widget",
"colander/tests/test_colander.py::TestSchemaNode::test_ctor_without_preparer",
"colander/tests/test_colander.py::TestSchemaNode::test_ctor_without_type",
"colander/tests/test_colander.py::TestSchemaNode::test_declarative_name_reassignment",
"colander/tests/test_colander.py::TestSchemaNode::test_deserialize_appstruct_deferred",
"colander/tests/test_colander.py::TestSchemaNode::test_deserialize_no_validator",
"colander/tests/test_colander.py::TestSchemaNode::test_deserialize_noargs_uses_default",
"colander/tests/test_colander.py::TestSchemaNode::test_deserialize_null_can_be_used_as_missing",
"colander/tests/test_colander.py::TestSchemaNode::test_deserialize_preparer_before_missing_check",
"colander/tests/test_colander.py::TestSchemaNode::test_deserialize_value_is_null_no_missing",
"colander/tests/test_colander.py::TestSchemaNode::test_deserialize_value_is_null_with_missing",
"colander/tests/test_colander.py::TestSchemaNode::test_deserialize_value_is_null_with_missing_msg",
"colander/tests/test_colander.py::TestSchemaNode::test_deserialize_value_with_interpolated_missing_msg",
"colander/tests/test_colander.py::TestSchemaNode::test_deserialize_with_multiple_preparers",
"colander/tests/test_colander.py::TestSchemaNode::test_deserialize_with_preparer",
"colander/tests/test_colander.py::TestSchemaNode::test_deserialize_with_unbound_validator",
"colander/tests/test_colander.py::TestSchemaNode::test_deserialize_with_validator",
"colander/tests/test_colander.py::TestSchemaNode::test_insert",
"colander/tests/test_colander.py::TestSchemaNode::test_new_sets_order",
"colander/tests/test_colander.py::TestSchemaNode::test_raise_invalid",
"colander/tests/test_colander.py::TestSchemaNode::test_repr",
"colander/tests/test_colander.py::TestSchemaNode::test_required_deferred",
"colander/tests/test_colander.py::TestSchemaNode::test_required_false",
"colander/tests/test_colander.py::TestSchemaNode::test_required_true",
"colander/tests/test_colander.py::TestSchemaNode::test_serialize",
"colander/tests/test_colander.py::TestSchemaNode::test_serialize_default_deferred",
"colander/tests/test_colander.py::TestSchemaNode::test_serialize_noargs_uses_default",
"colander/tests/test_colander.py::TestSchemaNode::test_serialize_value_is_null_no_default",
"colander/tests/test_colander.py::TestSchemaNode::test_serialize_value_is_null_with_default",
"colander/tests/test_colander.py::TestSchemaNodeSubclassing::test_deferred_methods_dont_quite_work_yet",
"colander/tests/test_colander.py::TestSchemaNodeSubclassing::test_functions_can_be_deferred",
"colander/tests/test_colander.py::TestSchemaNodeSubclassing::test_method_values_can_rely_on_binding",
"colander/tests/test_colander.py::TestSchemaNodeSubclassing::test_nodes_can_be_deffered",
"colander/tests/test_colander.py::TestSchemaNodeSubclassing::test_nonmethod_values_can_be_deferred_though",
"colander/tests/test_colander.py::TestSchemaNodeSubclassing::test_nonmethod_values_can_rely_on_after_bind",
"colander/tests/test_colander.py::TestSchemaNodeSubclassing::test_schema_child_names_conflict_with_value_names_in_subclass",
"colander/tests/test_colander.py::TestSchemaNodeSubclassing::test_schema_child_names_conflict_with_value_names_in_superclass",
"colander/tests/test_colander.py::TestSchemaNodeSubclassing::test_schema_child_names_conflict_with_value_names_notused",
"colander/tests/test_colander.py::TestSchemaNodeSubclassing::test_schema_child_names_conflict_with_value_names_used",
"colander/tests/test_colander.py::TestSchemaNodeSubclassing::test_subclass_title_overwritten_by_constructor",
"colander/tests/test_colander.py::TestSchemaNodeSubclassing::test_subclass_uses_missing",
"colander/tests/test_colander.py::TestSchemaNodeSubclassing::test_subclass_uses_title",
"colander/tests/test_colander.py::TestSchemaNodeSubclassing::test_subclass_uses_validator_method",
"colander/tests/test_colander.py::TestSchemaNodeSubclassing::test_subclass_value_overridden_by_constructor",
"colander/tests/test_colander.py::TestSchemaNodeSubclassing::test_subelement_title_not_overwritten",
"colander/tests/test_colander.py::TestMappingSchemaInheritance::test_insert_before_failure",
"colander/tests/test_colander.py::TestMappingSchemaInheritance::test_multiple_inheritance",
"colander/tests/test_colander.py::TestMappingSchemaInheritance::test_single_inheritance",
"colander/tests/test_colander.py::TestMappingSchemaInheritance::test_single_inheritance2",
"colander/tests/test_colander.py::TestMappingSchemaInheritance::test_single_inheritance_with_insert_before",
"colander/tests/test_colander.py::TestDeferred::test___call__",
"colander/tests/test_colander.py::TestDeferred::test_ctor",
"colander/tests/test_colander.py::TestDeferred::test_retain_func_details",
"colander/tests/test_colander.py::TestDeferred::test_w_callable_instance_no_name",
"colander/tests/test_colander.py::TestDeferred::test_w_callable_instance_no_name_or_doc",
"colander/tests/test_colander.py::TestSchema::test_alias",
"colander/tests/test_colander.py::TestSchema::test_deserialize_drop",
"colander/tests/test_colander.py::TestSchema::test_imperative_with_implicit_schema_type",
"colander/tests/test_colander.py::TestSchema::test_it",
"colander/tests/test_colander.py::TestSchema::test_schema_with_cloned_nodes",
"colander/tests/test_colander.py::TestSchema::test_serialize_drop_default",
"colander/tests/test_colander.py::TestSchema::test_title_munging",
"colander/tests/test_colander.py::TestSequenceSchema::test_clone_with_sequence_schema",
"colander/tests/test_colander.py::TestSequenceSchema::test_deserialize_drop",
"colander/tests/test_colander.py::TestSequenceSchema::test_fail_toofew",
"colander/tests/test_colander.py::TestSequenceSchema::test_fail_toomany",
"colander/tests/test_colander.py::TestSequenceSchema::test_imperative_with_implicit_schema_type",
"colander/tests/test_colander.py::TestSequenceSchema::test_serialize_drop_default",
"colander/tests/test_colander.py::TestSequenceSchema::test_succeed",
"colander/tests/test_colander.py::TestTupleSchema::test_imperative_with_implicit_schema_type",
"colander/tests/test_colander.py::TestTupleSchema::test_it",
"colander/tests/test_colander.py::TestImperative::test_deserialize_ok",
"colander/tests/test_colander.py::TestImperative::test_flatten_mapping_has_no_name",
"colander/tests/test_colander.py::TestImperative::test_flatten_ok",
"colander/tests/test_colander.py::TestImperative::test_flatten_unflatten_roundtrip",
"colander/tests/test_colander.py::TestImperative::test_get_value",
"colander/tests/test_colander.py::TestImperative::test_invalid_asdict",
"colander/tests/test_colander.py::TestImperative::test_invalid_asdict_translation_callback",
"colander/tests/test_colander.py::TestImperative::test_set_value",
"colander/tests/test_colander.py::TestImperative::test_unflatten_mapping_no_name",
"colander/tests/test_colander.py::TestImperative::test_unflatten_ok",
"colander/tests/test_colander.py::TestDeclarative::test_deserialize_ok",
"colander/tests/test_colander.py::TestDeclarative::test_flatten_mapping_has_no_name",
"colander/tests/test_colander.py::TestDeclarative::test_flatten_ok",
"colander/tests/test_colander.py::TestDeclarative::test_flatten_unflatten_roundtrip",
"colander/tests/test_colander.py::TestDeclarative::test_get_value",
"colander/tests/test_colander.py::TestDeclarative::test_invalid_asdict",
"colander/tests/test_colander.py::TestDeclarative::test_invalid_asdict_translation_callback",
"colander/tests/test_colander.py::TestDeclarative::test_set_value",
"colander/tests/test_colander.py::TestDeclarative::test_unflatten_mapping_no_name",
"colander/tests/test_colander.py::TestDeclarative::test_unflatten_ok",
"colander/tests/test_colander.py::TestUltraDeclarative::test_deserialize_ok",
"colander/tests/test_colander.py::TestUltraDeclarative::test_flatten_mapping_has_no_name",
"colander/tests/test_colander.py::TestUltraDeclarative::test_flatten_ok",
"colander/tests/test_colander.py::TestUltraDeclarative::test_flatten_unflatten_roundtrip",
"colander/tests/test_colander.py::TestUltraDeclarative::test_get_value",
"colander/tests/test_colander.py::TestUltraDeclarative::test_invalid_asdict",
"colander/tests/test_colander.py::TestUltraDeclarative::test_invalid_asdict_translation_callback",
"colander/tests/test_colander.py::TestUltraDeclarative::test_set_value",
"colander/tests/test_colander.py::TestUltraDeclarative::test_unflatten_mapping_no_name",
"colander/tests/test_colander.py::TestUltraDeclarative::test_unflatten_ok",
"colander/tests/test_colander.py::TestDeclarativeWithInstantiate::test_deserialize_ok",
"colander/tests/test_colander.py::TestDeclarativeWithInstantiate::test_flatten_mapping_has_no_name",
"colander/tests/test_colander.py::TestDeclarativeWithInstantiate::test_flatten_ok",
"colander/tests/test_colander.py::TestDeclarativeWithInstantiate::test_flatten_unflatten_roundtrip",
"colander/tests/test_colander.py::TestDeclarativeWithInstantiate::test_get_value",
"colander/tests/test_colander.py::TestDeclarativeWithInstantiate::test_invalid_asdict",
"colander/tests/test_colander.py::TestDeclarativeWithInstantiate::test_invalid_asdict_translation_callback",
"colander/tests/test_colander.py::TestDeclarativeWithInstantiate::test_set_value",
"colander/tests/test_colander.py::TestDeclarativeWithInstantiate::test_unflatten_mapping_no_name",
"colander/tests/test_colander.py::TestDeclarativeWithInstantiate::test_unflatten_ok",
"colander/tests/test_colander.py::Test_null::test___nonzero__",
"colander/tests/test_colander.py::Test_null::test___repr__",
"colander/tests/test_colander.py::Test_null::test_pickling",
"colander/tests/test_colander.py::Test_required::test___repr__",
"colander/tests/test_colander.py::Test_required::test_pickling",
"colander/tests/test_colander.py::Test_drop::test___repr__",
"colander/tests/test_colander.py::Test_drop::test_pickling"
] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
} | "2019-02-01T07:36:34Z" | bsd-4-clause |
|
Pylons__colander-323 | diff --git a/CHANGES.rst b/CHANGES.rst
index c40160b..f3f5d14 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -1,6 +1,23 @@
Unreleased
==========
+- The URL validator regex has been updated to no longer be vulnerable to a
+ catastrophic backtracking that would have led to an infinite loop. See
+ https://github.com/Pylons/colander/pull/323 and
+ https://github.com/Pylons/colander/issues/290. With thanks to Przemek
+ (https://github.com/p-m-k).
+
+ This does change the behaviour of the URL validator and it no longer supports
+ ``file://`` URI scheme (https://tools.ietf.org/html/rfc8089). Users that
+ wish to validate ``file://`` URI's should change their validator to use
+ ``colander.file_uri`` instead.
+
+ It has also dropped support for alternate schemes outside of http/ftp (and
+ their secure equivelants). Please let us know if we need to relax this
+ requirement.
+
+ CVE-ID: CVE-2017-18361
+
- The Email validator has been updated to use the same regular expression that
is used by the WhatWG HTML specification, thereby increasing the email
addresses that will validate correctly from web forms submitted. See
diff --git a/colander/__init__.py b/colander/__init__.py
index 6f0dff5..6eac447 100644
--- a/colander/__init__.py
+++ b/colander/__init__.py
@@ -607,14 +607,40 @@ def _luhnok(value):
return checksum
+# Gingerly lifted from Django 1.3.x:
+# https://github.com/django/django/blob/stable/1.3.x/django/core/validators.py#L45
+# <3 y'all!
URL_REGEX = (
- r'(?i)\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|'
- r'[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|'
- r'(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|'
- r'[^\s`!()\[\]{};:\'".,<>?«»“”‘’]))' # "emacs!
+ # {http,ftp}s:// (not required)
+ r'^((?:http|ftp)s?://)?'
+ # Domain
+ r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+'
+ r'(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|'
+ # Localhost
+ r'localhost|'
+ # IPv6 address
+ r'\[[a-f0-9:]+\]|'
+ # IPv4 address
+ r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'
+ # Optional port
+ r'(?::\d+)?'
+ # Path
+ r'(?:/?|[/?]\S+)$'
)
-url = Regex(URL_REGEX, _('Must be a URL'))
+url = Regex(URL_REGEX, msg=_('Must be a URL'), flags=re.IGNORECASE)
+
+
+URI_REGEX = (
+ # file:// (required)
+ r'^file://'
+ # Path
+ r'(?:/|[/?]\S+)$'
+)
+
+file_uri = Regex(
+ URI_REGEX, msg=_('Must be a file:// URI scheme'), flags=re.IGNORECASE
+)
UUID_REGEX = (
r'^(?:urn:uuid:)?\{?[a-f0-9]{8}(?:-?[a-f0-9]{4}){3}-?[a-f0-9]{12}\}?$'
| Pylons/colander | 1c3bd63aa06b4f01081035c1b54ff4586aef4c9f | diff --git a/colander/tests/test_colander.py b/colander/tests/test_colander.py
index 917a719..5411c2b 100644
--- a/colander/tests/test_colander.py
+++ b/colander/tests/test_colander.py
@@ -646,6 +646,76 @@ class Test_url_validator(unittest.TestCase):
self.assertRaises(Invalid, self._callFUT, val)
+ def test_add_sample_dos(self):
+ # In the old regex (colander <=1.6) this would cause a catastrophic
+ # backtracking that would cause the regex engine to go into an infinite
+ # loop.
+ val = "http://www.mysite.com/(tttttttttttttttttttttt.jpg"
+
+ result = self._callFUT(val)
+ self.assertEqual(result, None)
+
+ def test_website_no_scheme(self):
+ val = "www.mysite.com"
+
+ result = self._callFUT(val)
+ self.assertEqual(result, None)
+
+ def test_ipv6(self):
+ val = "http://[2001:db8::0]/"
+
+ result = self._callFUT(val)
+ self.assertEqual(result, None)
+
+ def test_ipv4(self):
+ val = "http://192.0.2.1/"
+
+ result = self._callFUT(val)
+ self.assertEqual(result, None)
+
+ def test_file_raises(self):
+ from colander import Invalid
+
+ val = "file:///this/is/a/file.jpg"
+
+ self.assertRaises(Invalid, self._callFUT, val)
+
+
+class Test_file_uri_validator(unittest.TestCase):
+ def _callFUT(self, val):
+ from colander import file_uri
+
+ return file_uri(None, val)
+
+ def test_it_success(self):
+ val = 'file:///'
+ result = self._callFUT(val)
+ self.assertEqual(result, None)
+
+ def test_it_failure(self):
+ val = 'not-a-uri'
+ from colander import Invalid
+
+ self.assertRaises(Invalid, self._callFUT, val)
+
+ def test_no_path_fails(self):
+ val = 'file://'
+ from colander import Invalid
+
+ self.assertRaises(Invalid, self._callFUT, val)
+
+ def test_file_with_path(self):
+ val = "file:///this/is/a/file.jpg"
+
+ result = self._callFUT(val)
+ self.assertEqual(result, None)
+
+ def test_file_with_path_windows(self):
+ val = "file:///c:/is/a/file.jpg"
+
+ result = self._callFUT(val)
+ self.assertEqual(result, None)
+
class TestUUID(unittest.TestCase):
def _callFUT(self, val):
| Unclosed parenthesis in URL causes infinite loop
When there is an unclosed parenthesis in URL and we use _url_ validator, it causes an infinite loop. What's more interesting is that it only happens when the unclosed parenthesis is followed by many characters (check test case number 3 and 4).
```
from colander import MappingSchema, SchemaNode, Str, url
class MySchema(MappingSchema):
url = SchemaNode(Str(encoding='utf-8'), validator=url)
print MySchema().deserialize({"url": "http://www.mysite.com/tttttttttttttttttttttt.jpg"}) # it works
print MySchema().deserialize({"url": "http://www.mysite.com/(tttttttttttttttttttttt).jpg"}) # it works
print MySchema().deserialize({"url": "http://www.mysite.com/(ttttttttttt.jpg"}) # it works
print MySchema().deserialize({"url": "http://www.mysite.com/(tttttttttttttttttttttt.jpg"}) # infinite loop
```
In addition, if you check it in an online regex checker (https://regex101.com/) it also fails. Try this regex, it's used for URL validation in colander. It's taken from _colander.\_\_init\_\_.py:438_, I only escaped two slashes here.
```
(?i)\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))
```
Use this URL: _http://www.mysite.com/(tttttttttttttttttttttt.jpg_ and you'll get _catastrophic backtracking_. You can use debugger on that site to check which group falls in infinite loop.
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"colander/tests/test_colander.py::Test_url_validator::test_file_raises",
"colander/tests/test_colander.py::Test_file_uri_validator::test_file_with_path",
"colander/tests/test_colander.py::Test_file_uri_validator::test_file_with_path_windows",
"colander/tests/test_colander.py::Test_file_uri_validator::test_it_failure",
"colander/tests/test_colander.py::Test_file_uri_validator::test_it_success",
"colander/tests/test_colander.py::Test_file_uri_validator::test_no_path_fails"
] | [
"colander/tests/test_colander.py::TestInvalid::test___setitem__fails",
"colander/tests/test_colander.py::TestInvalid::test___setitem__succeeds",
"colander/tests/test_colander.py::TestInvalid::test___str__",
"colander/tests/test_colander.py::TestInvalid::test__keyname_no_parent",
"colander/tests/test_colander.py::TestInvalid::test__keyname_nonpositional_parent",
"colander/tests/test_colander.py::TestInvalid::test__keyname_positional",
"colander/tests/test_colander.py::TestInvalid::test_add",
"colander/tests/test_colander.py::TestInvalid::test_add_positional",
"colander/tests/test_colander.py::TestInvalid::test_asdict",
"colander/tests/test_colander.py::TestInvalid::test_asdict_with_all_validator",
"colander/tests/test_colander.py::TestInvalid::test_asdict_with_all_validator_functional",
"colander/tests/test_colander.py::TestInvalid::test_ctor",
"colander/tests/test_colander.py::TestInvalid::test_messages_msg_None",
"colander/tests/test_colander.py::TestInvalid::test_messages_msg_iterable",
"colander/tests/test_colander.py::TestInvalid::test_messages_msg_not_iterable",
"colander/tests/test_colander.py::TestInvalid::test_paths",
"colander/tests/test_colander.py::TestAll::test_Invalid_children",
"colander/tests/test_colander.py::TestAll::test_failure",
"colander/tests/test_colander.py::TestAll::test_success",
"colander/tests/test_colander.py::TestAny::test_Invalid_children",
"colander/tests/test_colander.py::TestAny::test_failure",
"colander/tests/test_colander.py::TestAny::test_success",
"colander/tests/test_colander.py::TestFunction::test_deprecated_message",
"colander/tests/test_colander.py::TestFunction::test_deprecated_message_warning",
"colander/tests/test_colander.py::TestFunction::test_error_message_adds_mapping_to_configured_message",
"colander/tests/test_colander.py::TestFunction::test_error_message_adds_mapping_to_return_message",
"colander/tests/test_colander.py::TestFunction::test_error_message_does_not_overwrite_configured_domain",
"colander/tests/test_colander.py::TestFunction::test_error_message_does_not_overwrite_returned_domain",
"colander/tests/test_colander.py::TestFunction::test_fail_function_returns_False",
"colander/tests/test_colander.py::TestFunction::test_fail_function_returns_empty_string",
"colander/tests/test_colander.py::TestFunction::test_fail_function_returns_string",
"colander/tests/test_colander.py::TestFunction::test_msg_and_message_error",
"colander/tests/test_colander.py::TestFunction::test_propagation",
"colander/tests/test_colander.py::TestFunction::test_success_function_returns_True",
"colander/tests/test_colander.py::TestRange::test_max_failure",
"colander/tests/test_colander.py::TestRange::test_max_failure_msg_override",
"colander/tests/test_colander.py::TestRange::test_min_failure",
"colander/tests/test_colander.py::TestRange::test_min_failure_msg_override",
"colander/tests/test_colander.py::TestRange::test_success_min_and_max",
"colander/tests/test_colander.py::TestRange::test_success_minimum_bound_only",
"colander/tests/test_colander.py::TestRange::test_success_no_bounds",
"colander/tests/test_colander.py::TestRange::test_success_upper_bound_only",
"colander/tests/test_colander.py::TestRegex::test_invalid_regexs",
"colander/tests/test_colander.py::TestRegex::test_regex_not_string",
"colander/tests/test_colander.py::TestRegex::test_valid_regex",
"colander/tests/test_colander.py::TestEmail::test_empty_email",
"colander/tests/test_colander.py::TestEmail::test_invalid_emails",
"colander/tests/test_colander.py::TestEmail::test_valid_emails",
"colander/tests/test_colander.py::TestLength::test_max_failure",
"colander/tests/test_colander.py::TestLength::test_max_failure_msg_override",
"colander/tests/test_colander.py::TestLength::test_min_failure",
"colander/tests/test_colander.py::TestLength::test_min_failure_msg_override",
"colander/tests/test_colander.py::TestLength::test_success_min_and_max",
"colander/tests/test_colander.py::TestLength::test_success_minimum_bound_only",
"colander/tests/test_colander.py::TestLength::test_success_no_bounds",
"colander/tests/test_colander.py::TestLength::test_success_upper_bound_only",
"colander/tests/test_colander.py::TestOneOf::test_failure",
"colander/tests/test_colander.py::TestOneOf::test_success",
"colander/tests/test_colander.py::TestNoneOf::test_failure",
"colander/tests/test_colander.py::TestNoneOf::test_success",
"colander/tests/test_colander.py::TestContainsOnly::test_failure",
"colander/tests/test_colander.py::TestContainsOnly::test_failure_with_custom_error_template",
"colander/tests/test_colander.py::TestContainsOnly::test_success",
"colander/tests/test_colander.py::Test_luhnok::test_fail",
"colander/tests/test_colander.py::Test_luhnok::test_fail2",
"colander/tests/test_colander.py::Test_luhnok::test_fail3",
"colander/tests/test_colander.py::Test_luhnok::test_success",
"colander/tests/test_colander.py::Test_url_validator::test_add_sample_dos",
"colander/tests/test_colander.py::Test_url_validator::test_ipv4",
"colander/tests/test_colander.py::Test_url_validator::test_ipv6",
"colander/tests/test_colander.py::Test_url_validator::test_it_failure",
"colander/tests/test_colander.py::Test_url_validator::test_it_success",
"colander/tests/test_colander.py::Test_url_validator::test_website_no_scheme",
"colander/tests/test_colander.py::TestUUID::test_failure_invalid_length",
"colander/tests/test_colander.py::TestUUID::test_failure_not_hexadecimal",
"colander/tests/test_colander.py::TestUUID::test_failure_random_string",
"colander/tests/test_colander.py::TestUUID::test_failure_with_invalid_urn_ns",
"colander/tests/test_colander.py::TestUUID::test_success_hexadecimal",
"colander/tests/test_colander.py::TestUUID::test_success_upper_case",
"colander/tests/test_colander.py::TestUUID::test_success_with_braces",
"colander/tests/test_colander.py::TestUUID::test_success_with_dashes",
"colander/tests/test_colander.py::TestUUID::test_success_with_urn_ns",
"colander/tests/test_colander.py::TestSchemaType::test_cstruct_children",
"colander/tests/test_colander.py::TestSchemaType::test_flatten",
"colander/tests/test_colander.py::TestSchemaType::test_flatten_listitem",
"colander/tests/test_colander.py::TestSchemaType::test_get_value",
"colander/tests/test_colander.py::TestSchemaType::test_set_value",
"colander/tests/test_colander.py::TestSchemaType::test_unflatten",
"colander/tests/test_colander.py::TestMapping::test_cstruct_children",
"colander/tests/test_colander.py::TestMapping::test_cstruct_children_cstruct_is_null",
"colander/tests/test_colander.py::TestMapping::test_ctor_bad_unknown",
"colander/tests/test_colander.py::TestMapping::test_ctor_good_unknown",
"colander/tests/test_colander.py::TestMapping::test_deserialize_no_subnodes",
"colander/tests/test_colander.py::TestMapping::test_deserialize_not_a_mapping",
"colander/tests/test_colander.py::TestMapping::test_deserialize_null",
"colander/tests/test_colander.py::TestMapping::test_deserialize_ok",
"colander/tests/test_colander.py::TestMapping::test_deserialize_subnode_missing_default",
"colander/tests/test_colander.py::TestMapping::test_deserialize_subnodes_raise",
"colander/tests/test_colander.py::TestMapping::test_deserialize_unknown_preserve",
"colander/tests/test_colander.py::TestMapping::test_deserialize_unknown_raise",
"colander/tests/test_colander.py::TestMapping::test_flatten",
"colander/tests/test_colander.py::TestMapping::test_flatten_listitem",
"colander/tests/test_colander.py::TestMapping::test_get_value",
"colander/tests/test_colander.py::TestMapping::test_serialize_no_subnodes",
"colander/tests/test_colander.py::TestMapping::test_serialize_not_a_mapping",
"colander/tests/test_colander.py::TestMapping::test_serialize_null",
"colander/tests/test_colander.py::TestMapping::test_serialize_ok",
"colander/tests/test_colander.py::TestMapping::test_serialize_value_has_drop",
"colander/tests/test_colander.py::TestMapping::test_serialize_value_is_null",
"colander/tests/test_colander.py::TestMapping::test_serialize_with_unknown",
"colander/tests/test_colander.py::TestMapping::test_set_value",
"colander/tests/test_colander.py::TestMapping::test_unflatten",
"colander/tests/test_colander.py::TestMapping::test_unflatten_nested",
"colander/tests/test_colander.py::TestTuple::test_cstruct_children_cstruct_is_null",
"colander/tests/test_colander.py::TestTuple::test_cstruct_children_justright",
"colander/tests/test_colander.py::TestTuple::test_cstruct_children_toofew",
"colander/tests/test_colander.py::TestTuple::test_cstruct_children_toomany",
"colander/tests/test_colander.py::TestTuple::test_deserialize_no_subnodes",
"colander/tests/test_colander.py::TestTuple::test_deserialize_not_iterable",
"colander/tests/test_colander.py::TestTuple::test_deserialize_null",
"colander/tests/test_colander.py::TestTuple::test_deserialize_ok",
"colander/tests/test_colander.py::TestTuple::test_deserialize_subnodes_raise",
"colander/tests/test_colander.py::TestTuple::test_deserialize_toobig",
"colander/tests/test_colander.py::TestTuple::test_deserialize_toosmall",
"colander/tests/test_colander.py::TestTuple::test_flatten",
"colander/tests/test_colander.py::TestTuple::test_flatten_listitem",
"colander/tests/test_colander.py::TestTuple::test_get_value",
"colander/tests/test_colander.py::TestTuple::test_get_value_bad_path",
"colander/tests/test_colander.py::TestTuple::test_serialize_no_subnodes",
"colander/tests/test_colander.py::TestTuple::test_serialize_not_iterable",
"colander/tests/test_colander.py::TestTuple::test_serialize_null",
"colander/tests/test_colander.py::TestTuple::test_serialize_ok",
"colander/tests/test_colander.py::TestTuple::test_serialize_subnodes_raise",
"colander/tests/test_colander.py::TestTuple::test_serialize_toobig",
"colander/tests/test_colander.py::TestTuple::test_serialize_toosmall",
"colander/tests/test_colander.py::TestTuple::test_set_value",
"colander/tests/test_colander.py::TestTuple::test_set_value_bad_path",
"colander/tests/test_colander.py::TestTuple::test_unflatten",
"colander/tests/test_colander.py::TestSet::test_deserialize_empty_set",
"colander/tests/test_colander.py::TestSet::test_deserialize_no_iter",
"colander/tests/test_colander.py::TestSet::test_deserialize_null",
"colander/tests/test_colander.py::TestSet::test_deserialize_str_no_iter",
"colander/tests/test_colander.py::TestSet::test_deserialize_valid",
"colander/tests/test_colander.py::TestSet::test_serialize",
"colander/tests/test_colander.py::TestSet::test_serialize_null",
"colander/tests/test_colander.py::TestList::test_deserialize_empty_set",
"colander/tests/test_colander.py::TestList::test_deserialize_no_iter",
"colander/tests/test_colander.py::TestList::test_deserialize_null",
"colander/tests/test_colander.py::TestList::test_deserialize_str_no_iter",
"colander/tests/test_colander.py::TestList::test_deserialize_valid",
"colander/tests/test_colander.py::TestList::test_serialize",
"colander/tests/test_colander.py::TestList::test_serialize_null",
"colander/tests/test_colander.py::TestSequence::test_alias",
"colander/tests/test_colander.py::TestSequence::test_cstruct_children_cstruct_is_non_null",
"colander/tests/test_colander.py::TestSequence::test_cstruct_children_cstruct_is_null",
"colander/tests/test_colander.py::TestSequence::test_deserialize_no_null",
"colander/tests/test_colander.py::TestSequence::test_deserialize_no_subnodes",
"colander/tests/test_colander.py::TestSequence::test_deserialize_not_iterable",
"colander/tests/test_colander.py::TestSequence::test_deserialize_not_iterable_accept_scalar",
"colander/tests/test_colander.py::TestSequence::test_deserialize_ok",
"colander/tests/test_colander.py::TestSequence::test_deserialize_string_accept_scalar",
"colander/tests/test_colander.py::TestSequence::test_deserialize_subnodes_raise",
"colander/tests/test_colander.py::TestSequence::test_flatten",
"colander/tests/test_colander.py::TestSequence::test_flatten_listitem",
"colander/tests/test_colander.py::TestSequence::test_flatten_with_integer",
"colander/tests/test_colander.py::TestSequence::test_getvalue",
"colander/tests/test_colander.py::TestSequence::test_serialize_drop",
"colander/tests/test_colander.py::TestSequence::test_serialize_no_subnodes",
"colander/tests/test_colander.py::TestSequence::test_serialize_not_iterable",
"colander/tests/test_colander.py::TestSequence::test_serialize_not_iterable_accept_scalar",
"colander/tests/test_colander.py::TestSequence::test_serialize_null",
"colander/tests/test_colander.py::TestSequence::test_serialize_ok",
"colander/tests/test_colander.py::TestSequence::test_serialize_string_accept_scalar",
"colander/tests/test_colander.py::TestSequence::test_serialize_subnodes_raise",
"colander/tests/test_colander.py::TestSequence::test_setvalue",
"colander/tests/test_colander.py::TestSequence::test_unflatten",
"colander/tests/test_colander.py::TestString::test_alias",
"colander/tests/test_colander.py::TestString::test_deserialize_emptystring",
"colander/tests/test_colander.py::TestString::test_deserialize_from_nonstring_obj",
"colander/tests/test_colander.py::TestString::test_deserialize_from_utf16",
"colander/tests/test_colander.py::TestString::test_deserialize_from_utf8",
"colander/tests/test_colander.py::TestString::test_deserialize_nonunicode_from_None",
"colander/tests/test_colander.py::TestString::test_deserialize_uncooperative",
"colander/tests/test_colander.py::TestString::test_deserialize_unicode_from_None",
"colander/tests/test_colander.py::TestString::test_serialize_emptystring",
"colander/tests/test_colander.py::TestString::test_serialize_encoding_with_non_string_type",
"colander/tests/test_colander.py::TestString::test_serialize_nonunicode_to_None",
"colander/tests/test_colander.py::TestString::test_serialize_null",
"colander/tests/test_colander.py::TestString::test_serialize_string_with_high_unresolveable_high_order_chars",
"colander/tests/test_colander.py::TestString::test_serialize_to_utf16",
"colander/tests/test_colander.py::TestString::test_serialize_to_utf8",
"colander/tests/test_colander.py::TestString::test_serialize_uncooperative",
"colander/tests/test_colander.py::TestString::test_serialize_unicode_to_None",
"colander/tests/test_colander.py::TestInteger::test_alias",
"colander/tests/test_colander.py::TestInteger::test_deserialize_emptystring",
"colander/tests/test_colander.py::TestInteger::test_deserialize_fails",
"colander/tests/test_colander.py::TestInteger::test_deserialize_ok",
"colander/tests/test_colander.py::TestInteger::test_serialize_fails",
"colander/tests/test_colander.py::TestInteger::test_serialize_none",
"colander/tests/test_colander.py::TestInteger::test_serialize_null",
"colander/tests/test_colander.py::TestInteger::test_serialize_ok",
"colander/tests/test_colander.py::TestInteger::test_serialize_zero",
"colander/tests/test_colander.py::TestFloat::test_deserialize_fails",
"colander/tests/test_colander.py::TestFloat::test_deserialize_ok",
"colander/tests/test_colander.py::TestFloat::test_serialize_emptystring",
"colander/tests/test_colander.py::TestFloat::test_serialize_fails",
"colander/tests/test_colander.py::TestFloat::test_serialize_none",
"colander/tests/test_colander.py::TestFloat::test_serialize_null",
"colander/tests/test_colander.py::TestFloat::test_serialize_ok",
"colander/tests/test_colander.py::TestFloat::test_serialize_zero",
"colander/tests/test_colander.py::TestDecimal::test_deserialize_fails",
"colander/tests/test_colander.py::TestDecimal::test_deserialize_ok",
"colander/tests/test_colander.py::TestDecimal::test_deserialize_with_normalize",
"colander/tests/test_colander.py::TestDecimal::test_deserialize_with_quantize",
"colander/tests/test_colander.py::TestDecimal::test_serialize_emptystring",
"colander/tests/test_colander.py::TestDecimal::test_serialize_fails",
"colander/tests/test_colander.py::TestDecimal::test_serialize_none",
"colander/tests/test_colander.py::TestDecimal::test_serialize_normalize",
"colander/tests/test_colander.py::TestDecimal::test_serialize_null",
"colander/tests/test_colander.py::TestDecimal::test_serialize_ok",
"colander/tests/test_colander.py::TestDecimal::test_serialize_quantize_no_rounding",
"colander/tests/test_colander.py::TestDecimal::test_serialize_quantize_with_rounding_up",
"colander/tests/test_colander.py::TestDecimal::test_serialize_zero",
"colander/tests/test_colander.py::TestMoney::test_deserialize_rounds_up",
"colander/tests/test_colander.py::TestMoney::test_serialize_rounds_up",
"colander/tests/test_colander.py::TestBoolean::test_alias",
"colander/tests/test_colander.py::TestBoolean::test_deserialize",
"colander/tests/test_colander.py::TestBoolean::test_deserialize_null",
"colander/tests/test_colander.py::TestBoolean::test_deserialize_unstringable",
"colander/tests/test_colander.py::TestBoolean::test_serialize",
"colander/tests/test_colander.py::TestBoolean::test_serialize_null",
"colander/tests/test_colander.py::TestBooleanCustomFalseReprs::test_deserialize",
"colander/tests/test_colander.py::TestBooleanCustomFalseAndTrueReprs::test_deserialize",
"colander/tests/test_colander.py::TestBooleanCustomSerializations::test_serialize",
"colander/tests/test_colander.py::TestGlobalObject::test__pkg_resources_style_irrresolveable_absolute",
"colander/tests/test_colander.py::TestGlobalObject::test__pkg_resources_style_irrresolveable_relative",
"colander/tests/test_colander.py::TestGlobalObject::test__pkg_resources_style_resolve_absolute",
"colander/tests/test_colander.py::TestGlobalObject::test__pkg_resources_style_resolve_relative_is_dot",
"colander/tests/test_colander.py::TestGlobalObject::test__pkg_resources_style_resolve_relative_nocurrentpackage",
"colander/tests/test_colander.py::TestGlobalObject::test__pkg_resources_style_resolve_relative_startswith_colon",
"colander/tests/test_colander.py::TestGlobalObject::test__pkg_resources_style_resolve_relative_startswith_dot",
"colander/tests/test_colander.py::TestGlobalObject::test__zope_dottedname_style_irresolveable_absolute",
"colander/tests/test_colander.py::TestGlobalObject::test__zope_dottedname_style_irresolveable_relative_is_dot",
"colander/tests/test_colander.py::TestGlobalObject::test__zope_dottedname_style_resolve_relative",
"colander/tests/test_colander.py::TestGlobalObject::test__zope_dottedname_style_resolve_relative_is_dot",
"colander/tests/test_colander.py::TestGlobalObject::test__zope_dottedname_style_resolve_relative_leading_dots",
"colander/tests/test_colander.py::TestGlobalObject::test__zope_dottedname_style_resolveable_absolute",
"colander/tests/test_colander.py::TestGlobalObject::test__zope_dottedname_style_resolveable_relative",
"colander/tests/test_colander.py::TestGlobalObject::test_deserialize_None",
"colander/tests/test_colander.py::TestGlobalObject::test_deserialize_class_fail",
"colander/tests/test_colander.py::TestGlobalObject::test_deserialize_class_ok",
"colander/tests/test_colander.py::TestGlobalObject::test_deserialize_notastring",
"colander/tests/test_colander.py::TestGlobalObject::test_deserialize_null",
"colander/tests/test_colander.py::TestGlobalObject::test_deserialize_style_raises",
"colander/tests/test_colander.py::TestGlobalObject::test_deserialize_using_pkgresources_style",
"colander/tests/test_colander.py::TestGlobalObject::test_deserialize_using_zope_dottedname_style",
"colander/tests/test_colander.py::TestGlobalObject::test_serialize_class",
"colander/tests/test_colander.py::TestGlobalObject::test_serialize_fail",
"colander/tests/test_colander.py::TestGlobalObject::test_serialize_null",
"colander/tests/test_colander.py::TestGlobalObject::test_serialize_ok",
"colander/tests/test_colander.py::TestGlobalObject::test_zope_dottedname_style_irrresolveable_absolute",
"colander/tests/test_colander.py::TestGlobalObject::test_zope_dottedname_style_irrresolveable_relative",
"colander/tests/test_colander.py::TestGlobalObject::test_zope_dottedname_style_resolve_absolute",
"colander/tests/test_colander.py::TestGlobalObject::test_zope_dottedname_style_resolve_relative_nocurrentpackage",
"colander/tests/test_colander.py::TestDateTime::test_ctor_default_tzinfo_None",
"colander/tests/test_colander.py::TestDateTime::test_ctor_default_tzinfo_non_None",
"colander/tests/test_colander.py::TestDateTime::test_ctor_default_tzinfo_not_specified",
"colander/tests/test_colander.py::TestDateTime::test_deserialize_date",
"colander/tests/test_colander.py::TestDateTime::test_deserialize_datetime_with_custom_format",
"colander/tests/test_colander.py::TestDateTime::test_deserialize_empty",
"colander/tests/test_colander.py::TestDateTime::test_deserialize_invalid_ParseError",
"colander/tests/test_colander.py::TestDateTime::test_deserialize_naive_with_default_tzinfo",
"colander/tests/test_colander.py::TestDateTime::test_deserialize_none_tzinfo",
"colander/tests/test_colander.py::TestDateTime::test_deserialize_null",
"colander/tests/test_colander.py::TestDateTime::test_deserialize_slashes_invalid",
"colander/tests/test_colander.py::TestDateTime::test_deserialize_success",
"colander/tests/test_colander.py::TestDateTime::test_serialize_none",
"colander/tests/test_colander.py::TestDateTime::test_serialize_null",
"colander/tests/test_colander.py::TestDateTime::test_serialize_with_date",
"colander/tests/test_colander.py::TestDateTime::test_serialize_with_garbage",
"colander/tests/test_colander.py::TestDateTime::test_serialize_with_naive_datetime",
"colander/tests/test_colander.py::TestDateTime::test_serialize_with_naive_datetime_and_custom_format",
"colander/tests/test_colander.py::TestDateTime::test_serialize_with_none_tzinfo_naive_datetime",
"colander/tests/test_colander.py::TestDateTime::test_serialize_with_none_tzinfo_naive_datetime_custom_format",
"colander/tests/test_colander.py::TestDateTime::test_serialize_with_tzware_datetime",
"colander/tests/test_colander.py::TestDate::test_deserialize_date_with_custom_format",
"colander/tests/test_colander.py::TestDate::test_deserialize_empty",
"colander/tests/test_colander.py::TestDate::test_deserialize_invalid_ParseError",
"colander/tests/test_colander.py::TestDate::test_deserialize_invalid_weird",
"colander/tests/test_colander.py::TestDate::test_deserialize_null",
"colander/tests/test_colander.py::TestDate::test_deserialize_success_date",
"colander/tests/test_colander.py::TestDate::test_deserialize_success_datetime",
"colander/tests/test_colander.py::TestDate::test_serialize_date_with_custom_format",
"colander/tests/test_colander.py::TestDate::test_serialize_none",
"colander/tests/test_colander.py::TestDate::test_serialize_null",
"colander/tests/test_colander.py::TestDate::test_serialize_with_date",
"colander/tests/test_colander.py::TestDate::test_serialize_with_datetime",
"colander/tests/test_colander.py::TestDate::test_serialize_with_garbage",
"colander/tests/test_colander.py::TestTime::test_deserialize_empty",
"colander/tests/test_colander.py::TestTime::test_deserialize_four_digit_string",
"colander/tests/test_colander.py::TestTime::test_deserialize_invalid_ParseError",
"colander/tests/test_colander.py::TestTime::test_deserialize_missing_seconds",
"colander/tests/test_colander.py::TestTime::test_deserialize_null",
"colander/tests/test_colander.py::TestTime::test_deserialize_success_datetime",
"colander/tests/test_colander.py::TestTime::test_deserialize_success_time",
"colander/tests/test_colander.py::TestTime::test_deserialize_three_digit_string",
"colander/tests/test_colander.py::TestTime::test_deserialize_two_digit_string",
"colander/tests/test_colander.py::TestTime::test_serialize_none",
"colander/tests/test_colander.py::TestTime::test_serialize_null",
"colander/tests/test_colander.py::TestTime::test_serialize_with_datetime",
"colander/tests/test_colander.py::TestTime::test_serialize_with_garbage",
"colander/tests/test_colander.py::TestTime::test_serialize_with_time",
"colander/tests/test_colander.py::TestTime::test_serialize_with_zero_time",
"colander/tests/test_colander.py::TestEnum::test_deserialize_failure",
"colander/tests/test_colander.py::TestEnum::test_deserialize_failure_typ",
"colander/tests/test_colander.py::TestEnum::test_deserialize_name",
"colander/tests/test_colander.py::TestEnum::test_deserialize_null",
"colander/tests/test_colander.py::TestEnum::test_deserialize_value_int",
"colander/tests/test_colander.py::TestEnum::test_deserialize_value_str",
"colander/tests/test_colander.py::TestEnum::test_non_unique_failure",
"colander/tests/test_colander.py::TestEnum::test_non_unique_failure2",
"colander/tests/test_colander.py::TestEnum::test_serialize_failure",
"colander/tests/test_colander.py::TestEnum::test_serialize_name",
"colander/tests/test_colander.py::TestEnum::test_serialize_null",
"colander/tests/test_colander.py::TestEnum::test_serialize_value_int",
"colander/tests/test_colander.py::TestEnum::test_serialize_value_str",
"colander/tests/test_colander.py::TestSchemaNode::test___contains__",
"colander/tests/test_colander.py::TestSchemaNode::test___delitem__failure",
"colander/tests/test_colander.py::TestSchemaNode::test___delitem__success",
"colander/tests/test_colander.py::TestSchemaNode::test___getitem__failure",
"colander/tests/test_colander.py::TestSchemaNode::test___getitem__success",
"colander/tests/test_colander.py::TestSchemaNode::test___iter__",
"colander/tests/test_colander.py::TestSchemaNode::test___setitem__no_override",
"colander/tests/test_colander.py::TestSchemaNode::test___setitem__override",
"colander/tests/test_colander.py::TestSchemaNode::test_add",
"colander/tests/test_colander.py::TestSchemaNode::test_bind",
"colander/tests/test_colander.py::TestSchemaNode::test_bind_with_after_bind",
"colander/tests/test_colander.py::TestSchemaNode::test_clone",
"colander/tests/test_colander.py::TestSchemaNode::test_clone_mapping_references",
"colander/tests/test_colander.py::TestSchemaNode::test_clone_with_modified_schema_instance",
"colander/tests/test_colander.py::TestSchemaNode::test_cstruct_children",
"colander/tests/test_colander.py::TestSchemaNode::test_cstruct_children_warning",
"colander/tests/test_colander.py::TestSchemaNode::test_ctor_children_kwarg_typ",
"colander/tests/test_colander.py::TestSchemaNode::test_ctor_no_title",
"colander/tests/test_colander.py::TestSchemaNode::test_ctor_with_description",
"colander/tests/test_colander.py::TestSchemaNode::test_ctor_with_kwarg_typ",
"colander/tests/test_colander.py::TestSchemaNode::test_ctor_with_preparer",
"colander/tests/test_colander.py::TestSchemaNode::test_ctor_with_title",
"colander/tests/test_colander.py::TestSchemaNode::test_ctor_with_unknown_kwarg",
"colander/tests/test_colander.py::TestSchemaNode::test_ctor_with_widget",
"colander/tests/test_colander.py::TestSchemaNode::test_ctor_without_preparer",
"colander/tests/test_colander.py::TestSchemaNode::test_ctor_without_type",
"colander/tests/test_colander.py::TestSchemaNode::test_declarative_name_reassignment",
"colander/tests/test_colander.py::TestSchemaNode::test_deserialize_appstruct_deferred",
"colander/tests/test_colander.py::TestSchemaNode::test_deserialize_no_validator",
"colander/tests/test_colander.py::TestSchemaNode::test_deserialize_noargs_uses_default",
"colander/tests/test_colander.py::TestSchemaNode::test_deserialize_null_can_be_used_as_missing",
"colander/tests/test_colander.py::TestSchemaNode::test_deserialize_preparer_before_missing_check",
"colander/tests/test_colander.py::TestSchemaNode::test_deserialize_value_is_null_no_missing",
"colander/tests/test_colander.py::TestSchemaNode::test_deserialize_value_is_null_with_missing",
"colander/tests/test_colander.py::TestSchemaNode::test_deserialize_value_is_null_with_missing_msg",
"colander/tests/test_colander.py::TestSchemaNode::test_deserialize_value_with_interpolated_missing_msg",
"colander/tests/test_colander.py::TestSchemaNode::test_deserialize_with_multiple_preparers",
"colander/tests/test_colander.py::TestSchemaNode::test_deserialize_with_preparer",
"colander/tests/test_colander.py::TestSchemaNode::test_deserialize_with_unbound_validator",
"colander/tests/test_colander.py::TestSchemaNode::test_deserialize_with_validator",
"colander/tests/test_colander.py::TestSchemaNode::test_insert",
"colander/tests/test_colander.py::TestSchemaNode::test_new_sets_order",
"colander/tests/test_colander.py::TestSchemaNode::test_raise_invalid",
"colander/tests/test_colander.py::TestSchemaNode::test_repr",
"colander/tests/test_colander.py::TestSchemaNode::test_required_deferred",
"colander/tests/test_colander.py::TestSchemaNode::test_required_false",
"colander/tests/test_colander.py::TestSchemaNode::test_required_true",
"colander/tests/test_colander.py::TestSchemaNode::test_serialize",
"colander/tests/test_colander.py::TestSchemaNode::test_serialize_default_deferred",
"colander/tests/test_colander.py::TestSchemaNode::test_serialize_noargs_uses_default",
"colander/tests/test_colander.py::TestSchemaNode::test_serialize_value_is_null_no_default",
"colander/tests/test_colander.py::TestSchemaNode::test_serialize_value_is_null_with_default",
"colander/tests/test_colander.py::TestSchemaNodeSubclassing::test_deferred_methods_dont_quite_work_yet",
"colander/tests/test_colander.py::TestSchemaNodeSubclassing::test_functions_can_be_deferred",
"colander/tests/test_colander.py::TestSchemaNodeSubclassing::test_method_values_can_rely_on_binding",
"colander/tests/test_colander.py::TestSchemaNodeSubclassing::test_nodes_can_be_deffered",
"colander/tests/test_colander.py::TestSchemaNodeSubclassing::test_nonmethod_values_can_be_deferred_though",
"colander/tests/test_colander.py::TestSchemaNodeSubclassing::test_nonmethod_values_can_rely_on_after_bind",
"colander/tests/test_colander.py::TestSchemaNodeSubclassing::test_schema_child_names_conflict_with_value_names_in_subclass",
"colander/tests/test_colander.py::TestSchemaNodeSubclassing::test_schema_child_names_conflict_with_value_names_in_superclass",
"colander/tests/test_colander.py::TestSchemaNodeSubclassing::test_schema_child_names_conflict_with_value_names_notused",
"colander/tests/test_colander.py::TestSchemaNodeSubclassing::test_schema_child_names_conflict_with_value_names_used",
"colander/tests/test_colander.py::TestSchemaNodeSubclassing::test_subclass_title_overwritten_by_constructor",
"colander/tests/test_colander.py::TestSchemaNodeSubclassing::test_subclass_uses_missing",
"colander/tests/test_colander.py::TestSchemaNodeSubclassing::test_subclass_uses_title",
"colander/tests/test_colander.py::TestSchemaNodeSubclassing::test_subclass_uses_validator_method",
"colander/tests/test_colander.py::TestSchemaNodeSubclassing::test_subclass_value_overridden_by_constructor",
"colander/tests/test_colander.py::TestSchemaNodeSubclassing::test_subelement_title_not_overwritten",
"colander/tests/test_colander.py::TestMappingSchemaInheritance::test_insert_before_failure",
"colander/tests/test_colander.py::TestMappingSchemaInheritance::test_multiple_inheritance",
"colander/tests/test_colander.py::TestMappingSchemaInheritance::test_single_inheritance",
"colander/tests/test_colander.py::TestMappingSchemaInheritance::test_single_inheritance2",
"colander/tests/test_colander.py::TestMappingSchemaInheritance::test_single_inheritance_with_insert_before",
"colander/tests/test_colander.py::TestDeferred::test___call__",
"colander/tests/test_colander.py::TestDeferred::test_ctor",
"colander/tests/test_colander.py::TestDeferred::test_retain_func_details",
"colander/tests/test_colander.py::TestDeferred::test_w_callable_instance_no_name",
"colander/tests/test_colander.py::TestDeferred::test_w_callable_instance_no_name_or_doc",
"colander/tests/test_colander.py::TestSchema::test_alias",
"colander/tests/test_colander.py::TestSchema::test_deserialize_drop",
"colander/tests/test_colander.py::TestSchema::test_imperative_with_implicit_schema_type",
"colander/tests/test_colander.py::TestSchema::test_it",
"colander/tests/test_colander.py::TestSchema::test_schema_with_cloned_nodes",
"colander/tests/test_colander.py::TestSchema::test_serialize_drop_default",
"colander/tests/test_colander.py::TestSchema::test_title_munging",
"colander/tests/test_colander.py::TestSequenceSchema::test_clone_with_sequence_schema",
"colander/tests/test_colander.py::TestSequenceSchema::test_deserialize_drop",
"colander/tests/test_colander.py::TestSequenceSchema::test_fail_toofew",
"colander/tests/test_colander.py::TestSequenceSchema::test_fail_toomany",
"colander/tests/test_colander.py::TestSequenceSchema::test_imperative_with_implicit_schema_type",
"colander/tests/test_colander.py::TestSequenceSchema::test_serialize_drop_default",
"colander/tests/test_colander.py::TestSequenceSchema::test_succeed",
"colander/tests/test_colander.py::TestTupleSchema::test_imperative_with_implicit_schema_type",
"colander/tests/test_colander.py::TestTupleSchema::test_it",
"colander/tests/test_colander.py::TestImperative::test_deserialize_ok",
"colander/tests/test_colander.py::TestImperative::test_flatten_mapping_has_no_name",
"colander/tests/test_colander.py::TestImperative::test_flatten_ok",
"colander/tests/test_colander.py::TestImperative::test_flatten_unflatten_roundtrip",
"colander/tests/test_colander.py::TestImperative::test_get_value",
"colander/tests/test_colander.py::TestImperative::test_invalid_asdict",
"colander/tests/test_colander.py::TestImperative::test_invalid_asdict_translation_callback",
"colander/tests/test_colander.py::TestImperative::test_set_value",
"colander/tests/test_colander.py::TestImperative::test_unflatten_mapping_no_name",
"colander/tests/test_colander.py::TestImperative::test_unflatten_ok",
"colander/tests/test_colander.py::TestDeclarative::test_deserialize_ok",
"colander/tests/test_colander.py::TestDeclarative::test_flatten_mapping_has_no_name",
"colander/tests/test_colander.py::TestDeclarative::test_flatten_ok",
"colander/tests/test_colander.py::TestDeclarative::test_flatten_unflatten_roundtrip",
"colander/tests/test_colander.py::TestDeclarative::test_get_value",
"colander/tests/test_colander.py::TestDeclarative::test_invalid_asdict",
"colander/tests/test_colander.py::TestDeclarative::test_invalid_asdict_translation_callback",
"colander/tests/test_colander.py::TestDeclarative::test_set_value",
"colander/tests/test_colander.py::TestDeclarative::test_unflatten_mapping_no_name",
"colander/tests/test_colander.py::TestDeclarative::test_unflatten_ok",
"colander/tests/test_colander.py::TestUltraDeclarative::test_deserialize_ok",
"colander/tests/test_colander.py::TestUltraDeclarative::test_flatten_mapping_has_no_name",
"colander/tests/test_colander.py::TestUltraDeclarative::test_flatten_ok",
"colander/tests/test_colander.py::TestUltraDeclarative::test_flatten_unflatten_roundtrip",
"colander/tests/test_colander.py::TestUltraDeclarative::test_get_value",
"colander/tests/test_colander.py::TestUltraDeclarative::test_invalid_asdict",
"colander/tests/test_colander.py::TestUltraDeclarative::test_invalid_asdict_translation_callback",
"colander/tests/test_colander.py::TestUltraDeclarative::test_set_value",
"colander/tests/test_colander.py::TestUltraDeclarative::test_unflatten_mapping_no_name",
"colander/tests/test_colander.py::TestUltraDeclarative::test_unflatten_ok",
"colander/tests/test_colander.py::TestDeclarativeWithInstantiate::test_deserialize_ok",
"colander/tests/test_colander.py::TestDeclarativeWithInstantiate::test_flatten_mapping_has_no_name",
"colander/tests/test_colander.py::TestDeclarativeWithInstantiate::test_flatten_ok",
"colander/tests/test_colander.py::TestDeclarativeWithInstantiate::test_flatten_unflatten_roundtrip",
"colander/tests/test_colander.py::TestDeclarativeWithInstantiate::test_get_value",
"colander/tests/test_colander.py::TestDeclarativeWithInstantiate::test_invalid_asdict",
"colander/tests/test_colander.py::TestDeclarativeWithInstantiate::test_invalid_asdict_translation_callback",
"colander/tests/test_colander.py::TestDeclarativeWithInstantiate::test_set_value",
"colander/tests/test_colander.py::TestDeclarativeWithInstantiate::test_unflatten_mapping_no_name",
"colander/tests/test_colander.py::TestDeclarativeWithInstantiate::test_unflatten_ok",
"colander/tests/test_colander.py::Test_null::test___nonzero__",
"colander/tests/test_colander.py::Test_null::test___repr__",
"colander/tests/test_colander.py::Test_null::test_pickling",
"colander/tests/test_colander.py::Test_required::test___repr__",
"colander/tests/test_colander.py::Test_required::test_pickling",
"colander/tests/test_colander.py::Test_drop::test___repr__",
"colander/tests/test_colander.py::Test_drop::test_pickling"
] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_media",
"has_many_modified_files",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
} | "2019-02-01T08:29:07Z" | bsd-4-clause |
|
Pylons__colander-324 | diff --git a/CHANGES.rst b/CHANGES.rst
index 43c932c..1d64b84 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -1,3 +1,12 @@
+Unreleased
+==========
+
+- The Email validator has been updated to use the same regular expression that
+ is used by the WhatWG HTML specification, thereby increasing the email
+ addresses that will validate correctly from web forms submitted. See
+ https://github.com/Pylons/colander/pull/324 and
+ https://github.com/Pylons/colander/issues/283
+
1.6.0 (2019-01-31)
==================
diff --git a/colander/__init__.py b/colander/__init__.py
index 8bddfd6..8956997 100644
--- a/colander/__init__.py
+++ b/colander/__init__.py
@@ -377,19 +377,17 @@ class Regex(object):
raise Invalid(node, self.msg)
-EMAIL_RE = r"""(?ix) # matches case insensitive with spaces and comments
- # ignored for the entire expression
-^ # matches the start of string
-[A-Z0-9._!#$%&'*+\-/=?^_`{|}~()]+ # matches multiples of the characters:
- # A-Z0-9._!#$%&'*+-/=?^_`{|}~() one or
- # more times
-@ # matches the @ sign
-[A-Z0-9]+ # matches multiples of the characters A-Z0-9
-([.-][A-Z0-9]+)* # matches one of . or - followed by at least one of A-Z0-9,
- # zero to unlimited times
-\.[A-Z]{2,22} # matches a period, followed by two to twenty-two of A-Z
-$ # matches the end of the string
-"""
+# Regex for email addresses.
+#
+# Stolen from the WhatWG HTML spec:
+# https://html.spec.whatwg.org/multipage/input.html#e-mail-state-(type=email)
+#
+# If it is good enough for browsers, it is good enough for us!
+EMAIL_RE = (
+ r"^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9]"
+ r"(?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9]"
+ r"(?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$"
+)
class Email(Regex):
| Pylons/colander | b7acdff5e83e41208c323f8cac52c48ff6328a85 | diff --git a/colander/tests/test_colander.py b/colander/tests/test_colander.py
index 12b904e..a6b85c2 100644
--- a/colander/tests/test_colander.py
+++ b/colander/tests/test_colander.py
@@ -480,6 +480,7 @@ class TestEmail(unittest.TestCase):
self.assertEqual(validator(None, '[email protected]'), None)
self.assertEqual(validator(None, '[email protected]'), None)
self.assertEqual(validator(None, "tip'[email protected]"), None)
+ self.assertEqual(validator(None, "[email protected]"), None)
def test_empty_email(self):
validator = self._makeOne()
@@ -491,9 +492,6 @@ class TestEmail(unittest.TestCase):
from colander import Invalid
self.assertRaises(Invalid, validator, None, 'me@here.')
- self.assertRaises(
- Invalid, validator, None, '[email protected]'
- )
self.assertRaises(Invalid, validator, None, '@here.us')
self.assertRaises(Invalid, validator, None, '[email protected]')
self.assertRaises(Invalid, validator, None, '[email protected]')
| Email validator does not allow double hyphen
`[email protected]` is a valid email address but the current email validator doesn't validate it.
Here's an email validator that I wrote with code that I stole from Django which works:
```python
class Email(object):
"""
Email validator shamelessly stolen from Django
"""
USER_REGEX = (
r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*\Z" # dot-atom
r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-\011\013\014\016-\177])*"\Z)' # quoted-string
)
# max length for domain name labels is 63 characters per RFC 1034
DOMAIN_REGEX = r'((?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+)(?:[A-Z0-9-]{2,63}(?<!-))\Z'
def __init__(self, msg=None):
if msg is None:
msg = "Invalid email address"
self.msg = msg
self.user_regex = re.compile(self.USER_REGEX, re.IGNORECASE)
self.domain_regex = re.compile(self.DOMAIN_REGEX, re.IGNORECASE)
def __call__(self, node, value):
if not value or '@' not in value:
raise Invalid(node, self.msg)
user_part, domain_part = value.rsplit('@', 1)
if not self.user_regex.match(user_part):
raise Invalid(node, self.msg)
if not self.domain_regex.match(domain_part):
# Try for possible IDN domain-part
try:
domain_part = domain_part.encode('idna').decode('ascii')
if self.domain_regex.match(domain_part):
return
except UnicodeError:
pass
raise Invalid(node, self.msg)
``` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"colander/tests/test_colander.py::TestEmail::test_valid_emails"
] | [
"colander/tests/test_colander.py::TestInvalid::test___setitem__fails",
"colander/tests/test_colander.py::TestInvalid::test___setitem__succeeds",
"colander/tests/test_colander.py::TestInvalid::test___str__",
"colander/tests/test_colander.py::TestInvalid::test__keyname_no_parent",
"colander/tests/test_colander.py::TestInvalid::test__keyname_nonpositional_parent",
"colander/tests/test_colander.py::TestInvalid::test__keyname_positional",
"colander/tests/test_colander.py::TestInvalid::test_add",
"colander/tests/test_colander.py::TestInvalid::test_add_positional",
"colander/tests/test_colander.py::TestInvalid::test_asdict",
"colander/tests/test_colander.py::TestInvalid::test_asdict_with_all_validator",
"colander/tests/test_colander.py::TestInvalid::test_asdict_with_all_validator_functional",
"colander/tests/test_colander.py::TestInvalid::test_ctor",
"colander/tests/test_colander.py::TestInvalid::test_messages_msg_None",
"colander/tests/test_colander.py::TestInvalid::test_messages_msg_iterable",
"colander/tests/test_colander.py::TestInvalid::test_messages_msg_not_iterable",
"colander/tests/test_colander.py::TestInvalid::test_paths",
"colander/tests/test_colander.py::TestAll::test_Invalid_children",
"colander/tests/test_colander.py::TestAll::test_failure",
"colander/tests/test_colander.py::TestAll::test_success",
"colander/tests/test_colander.py::TestAny::test_Invalid_children",
"colander/tests/test_colander.py::TestAny::test_failure",
"colander/tests/test_colander.py::TestAny::test_success",
"colander/tests/test_colander.py::TestFunction::test_deprecated_message",
"colander/tests/test_colander.py::TestFunction::test_deprecated_message_warning",
"colander/tests/test_colander.py::TestFunction::test_error_message_adds_mapping_to_configured_message",
"colander/tests/test_colander.py::TestFunction::test_error_message_adds_mapping_to_return_message",
"colander/tests/test_colander.py::TestFunction::test_error_message_does_not_overwrite_configured_domain",
"colander/tests/test_colander.py::TestFunction::test_error_message_does_not_overwrite_returned_domain",
"colander/tests/test_colander.py::TestFunction::test_fail_function_returns_False",
"colander/tests/test_colander.py::TestFunction::test_fail_function_returns_empty_string",
"colander/tests/test_colander.py::TestFunction::test_fail_function_returns_string",
"colander/tests/test_colander.py::TestFunction::test_msg_and_message_error",
"colander/tests/test_colander.py::TestFunction::test_propagation",
"colander/tests/test_colander.py::TestFunction::test_success_function_returns_True",
"colander/tests/test_colander.py::TestRange::test_max_failure",
"colander/tests/test_colander.py::TestRange::test_max_failure_msg_override",
"colander/tests/test_colander.py::TestRange::test_min_failure",
"colander/tests/test_colander.py::TestRange::test_min_failure_msg_override",
"colander/tests/test_colander.py::TestRange::test_success_min_and_max",
"colander/tests/test_colander.py::TestRange::test_success_minimum_bound_only",
"colander/tests/test_colander.py::TestRange::test_success_no_bounds",
"colander/tests/test_colander.py::TestRange::test_success_upper_bound_only",
"colander/tests/test_colander.py::TestRegex::test_invalid_regexs",
"colander/tests/test_colander.py::TestRegex::test_regex_not_string",
"colander/tests/test_colander.py::TestRegex::test_valid_regex",
"colander/tests/test_colander.py::TestEmail::test_empty_email",
"colander/tests/test_colander.py::TestEmail::test_invalid_emails",
"colander/tests/test_colander.py::TestLength::test_max_failure",
"colander/tests/test_colander.py::TestLength::test_max_failure_msg_override",
"colander/tests/test_colander.py::TestLength::test_min_failure",
"colander/tests/test_colander.py::TestLength::test_min_failure_msg_override",
"colander/tests/test_colander.py::TestLength::test_success_min_and_max",
"colander/tests/test_colander.py::TestLength::test_success_minimum_bound_only",
"colander/tests/test_colander.py::TestLength::test_success_no_bounds",
"colander/tests/test_colander.py::TestLength::test_success_upper_bound_only",
"colander/tests/test_colander.py::TestOneOf::test_failure",
"colander/tests/test_colander.py::TestOneOf::test_success",
"colander/tests/test_colander.py::TestNoneOf::test_failure",
"colander/tests/test_colander.py::TestNoneOf::test_success",
"colander/tests/test_colander.py::TestContainsOnly::test_failure",
"colander/tests/test_colander.py::TestContainsOnly::test_failure_with_custom_error_template",
"colander/tests/test_colander.py::TestContainsOnly::test_success",
"colander/tests/test_colander.py::Test_luhnok::test_fail",
"colander/tests/test_colander.py::Test_luhnok::test_fail2",
"colander/tests/test_colander.py::Test_luhnok::test_fail3",
"colander/tests/test_colander.py::Test_luhnok::test_success",
"colander/tests/test_colander.py::Test_url_validator::test_it_failure",
"colander/tests/test_colander.py::Test_url_validator::test_it_success",
"colander/tests/test_colander.py::TestUUID::test_failure_invalid_length",
"colander/tests/test_colander.py::TestUUID::test_failure_not_hexadecimal",
"colander/tests/test_colander.py::TestUUID::test_failure_random_string",
"colander/tests/test_colander.py::TestUUID::test_failure_with_invalid_urn_ns",
"colander/tests/test_colander.py::TestUUID::test_success_hexadecimal",
"colander/tests/test_colander.py::TestUUID::test_success_upper_case",
"colander/tests/test_colander.py::TestUUID::test_success_with_braces",
"colander/tests/test_colander.py::TestUUID::test_success_with_dashes",
"colander/tests/test_colander.py::TestUUID::test_success_with_urn_ns",
"colander/tests/test_colander.py::TestSchemaType::test_cstruct_children",
"colander/tests/test_colander.py::TestSchemaType::test_flatten",
"colander/tests/test_colander.py::TestSchemaType::test_flatten_listitem",
"colander/tests/test_colander.py::TestSchemaType::test_get_value",
"colander/tests/test_colander.py::TestSchemaType::test_set_value",
"colander/tests/test_colander.py::TestSchemaType::test_unflatten",
"colander/tests/test_colander.py::TestMapping::test_cstruct_children",
"colander/tests/test_colander.py::TestMapping::test_cstruct_children_cstruct_is_null",
"colander/tests/test_colander.py::TestMapping::test_ctor_bad_unknown",
"colander/tests/test_colander.py::TestMapping::test_ctor_good_unknown",
"colander/tests/test_colander.py::TestMapping::test_deserialize_no_subnodes",
"colander/tests/test_colander.py::TestMapping::test_deserialize_not_a_mapping",
"colander/tests/test_colander.py::TestMapping::test_deserialize_null",
"colander/tests/test_colander.py::TestMapping::test_deserialize_ok",
"colander/tests/test_colander.py::TestMapping::test_deserialize_subnode_missing_default",
"colander/tests/test_colander.py::TestMapping::test_deserialize_subnodes_raise",
"colander/tests/test_colander.py::TestMapping::test_deserialize_unknown_preserve",
"colander/tests/test_colander.py::TestMapping::test_deserialize_unknown_raise",
"colander/tests/test_colander.py::TestMapping::test_flatten",
"colander/tests/test_colander.py::TestMapping::test_flatten_listitem",
"colander/tests/test_colander.py::TestMapping::test_get_value",
"colander/tests/test_colander.py::TestMapping::test_serialize_no_subnodes",
"colander/tests/test_colander.py::TestMapping::test_serialize_not_a_mapping",
"colander/tests/test_colander.py::TestMapping::test_serialize_null",
"colander/tests/test_colander.py::TestMapping::test_serialize_ok",
"colander/tests/test_colander.py::TestMapping::test_serialize_value_has_drop",
"colander/tests/test_colander.py::TestMapping::test_serialize_value_is_null",
"colander/tests/test_colander.py::TestMapping::test_serialize_with_unknown",
"colander/tests/test_colander.py::TestMapping::test_set_value",
"colander/tests/test_colander.py::TestMapping::test_unflatten",
"colander/tests/test_colander.py::TestMapping::test_unflatten_nested",
"colander/tests/test_colander.py::TestTuple::test_cstruct_children_cstruct_is_null",
"colander/tests/test_colander.py::TestTuple::test_cstruct_children_justright",
"colander/tests/test_colander.py::TestTuple::test_cstruct_children_toofew",
"colander/tests/test_colander.py::TestTuple::test_cstruct_children_toomany",
"colander/tests/test_colander.py::TestTuple::test_deserialize_no_subnodes",
"colander/tests/test_colander.py::TestTuple::test_deserialize_not_iterable",
"colander/tests/test_colander.py::TestTuple::test_deserialize_null",
"colander/tests/test_colander.py::TestTuple::test_deserialize_ok",
"colander/tests/test_colander.py::TestTuple::test_deserialize_subnodes_raise",
"colander/tests/test_colander.py::TestTuple::test_deserialize_toobig",
"colander/tests/test_colander.py::TestTuple::test_deserialize_toosmall",
"colander/tests/test_colander.py::TestTuple::test_flatten",
"colander/tests/test_colander.py::TestTuple::test_flatten_listitem",
"colander/tests/test_colander.py::TestTuple::test_get_value",
"colander/tests/test_colander.py::TestTuple::test_get_value_bad_path",
"colander/tests/test_colander.py::TestTuple::test_serialize_no_subnodes",
"colander/tests/test_colander.py::TestTuple::test_serialize_not_iterable",
"colander/tests/test_colander.py::TestTuple::test_serialize_null",
"colander/tests/test_colander.py::TestTuple::test_serialize_ok",
"colander/tests/test_colander.py::TestTuple::test_serialize_subnodes_raise",
"colander/tests/test_colander.py::TestTuple::test_serialize_toobig",
"colander/tests/test_colander.py::TestTuple::test_serialize_toosmall",
"colander/tests/test_colander.py::TestTuple::test_set_value",
"colander/tests/test_colander.py::TestTuple::test_set_value_bad_path",
"colander/tests/test_colander.py::TestTuple::test_unflatten",
"colander/tests/test_colander.py::TestSet::test_deserialize_empty_set",
"colander/tests/test_colander.py::TestSet::test_deserialize_no_iter",
"colander/tests/test_colander.py::TestSet::test_deserialize_null",
"colander/tests/test_colander.py::TestSet::test_deserialize_str_no_iter",
"colander/tests/test_colander.py::TestSet::test_deserialize_valid",
"colander/tests/test_colander.py::TestSet::test_serialize",
"colander/tests/test_colander.py::TestSet::test_serialize_null",
"colander/tests/test_colander.py::TestList::test_deserialize_empty_set",
"colander/tests/test_colander.py::TestList::test_deserialize_no_iter",
"colander/tests/test_colander.py::TestList::test_deserialize_null",
"colander/tests/test_colander.py::TestList::test_deserialize_str_no_iter",
"colander/tests/test_colander.py::TestList::test_deserialize_valid",
"colander/tests/test_colander.py::TestList::test_serialize",
"colander/tests/test_colander.py::TestList::test_serialize_null",
"colander/tests/test_colander.py::TestSequence::test_alias",
"colander/tests/test_colander.py::TestSequence::test_cstruct_children_cstruct_is_non_null",
"colander/tests/test_colander.py::TestSequence::test_cstruct_children_cstruct_is_null",
"colander/tests/test_colander.py::TestSequence::test_deserialize_no_null",
"colander/tests/test_colander.py::TestSequence::test_deserialize_no_subnodes",
"colander/tests/test_colander.py::TestSequence::test_deserialize_not_iterable",
"colander/tests/test_colander.py::TestSequence::test_deserialize_not_iterable_accept_scalar",
"colander/tests/test_colander.py::TestSequence::test_deserialize_ok",
"colander/tests/test_colander.py::TestSequence::test_deserialize_string_accept_scalar",
"colander/tests/test_colander.py::TestSequence::test_deserialize_subnodes_raise",
"colander/tests/test_colander.py::TestSequence::test_flatten",
"colander/tests/test_colander.py::TestSequence::test_flatten_listitem",
"colander/tests/test_colander.py::TestSequence::test_flatten_with_integer",
"colander/tests/test_colander.py::TestSequence::test_getvalue",
"colander/tests/test_colander.py::TestSequence::test_serialize_drop",
"colander/tests/test_colander.py::TestSequence::test_serialize_no_subnodes",
"colander/tests/test_colander.py::TestSequence::test_serialize_not_iterable",
"colander/tests/test_colander.py::TestSequence::test_serialize_not_iterable_accept_scalar",
"colander/tests/test_colander.py::TestSequence::test_serialize_null",
"colander/tests/test_colander.py::TestSequence::test_serialize_ok",
"colander/tests/test_colander.py::TestSequence::test_serialize_string_accept_scalar",
"colander/tests/test_colander.py::TestSequence::test_serialize_subnodes_raise",
"colander/tests/test_colander.py::TestSequence::test_setvalue",
"colander/tests/test_colander.py::TestSequence::test_unflatten",
"colander/tests/test_colander.py::TestString::test_alias",
"colander/tests/test_colander.py::TestString::test_deserialize_emptystring",
"colander/tests/test_colander.py::TestString::test_deserialize_from_nonstring_obj",
"colander/tests/test_colander.py::TestString::test_deserialize_from_utf16",
"colander/tests/test_colander.py::TestString::test_deserialize_from_utf8",
"colander/tests/test_colander.py::TestString::test_deserialize_nonunicode_from_None",
"colander/tests/test_colander.py::TestString::test_deserialize_uncooperative",
"colander/tests/test_colander.py::TestString::test_deserialize_unicode_from_None",
"colander/tests/test_colander.py::TestString::test_serialize_emptystring",
"colander/tests/test_colander.py::TestString::test_serialize_encoding_with_non_string_type",
"colander/tests/test_colander.py::TestString::test_serialize_nonunicode_to_None",
"colander/tests/test_colander.py::TestString::test_serialize_null",
"colander/tests/test_colander.py::TestString::test_serialize_string_with_high_unresolveable_high_order_chars",
"colander/tests/test_colander.py::TestString::test_serialize_to_utf16",
"colander/tests/test_colander.py::TestString::test_serialize_to_utf8",
"colander/tests/test_colander.py::TestString::test_serialize_uncooperative",
"colander/tests/test_colander.py::TestString::test_serialize_unicode_to_None",
"colander/tests/test_colander.py::TestInteger::test_alias",
"colander/tests/test_colander.py::TestInteger::test_deserialize_emptystring",
"colander/tests/test_colander.py::TestInteger::test_deserialize_fails",
"colander/tests/test_colander.py::TestInteger::test_deserialize_ok",
"colander/tests/test_colander.py::TestInteger::test_serialize_fails",
"colander/tests/test_colander.py::TestInteger::test_serialize_null",
"colander/tests/test_colander.py::TestInteger::test_serialize_ok",
"colander/tests/test_colander.py::TestInteger::test_serialize_zero",
"colander/tests/test_colander.py::TestFloat::test_deserialize_fails",
"colander/tests/test_colander.py::TestFloat::test_deserialize_ok",
"colander/tests/test_colander.py::TestFloat::test_serialize_emptystring",
"colander/tests/test_colander.py::TestFloat::test_serialize_fails",
"colander/tests/test_colander.py::TestFloat::test_serialize_null",
"colander/tests/test_colander.py::TestFloat::test_serialize_ok",
"colander/tests/test_colander.py::TestDecimal::test_deserialize_fails",
"colander/tests/test_colander.py::TestDecimal::test_deserialize_ok",
"colander/tests/test_colander.py::TestDecimal::test_deserialize_with_normalize",
"colander/tests/test_colander.py::TestDecimal::test_deserialize_with_quantize",
"colander/tests/test_colander.py::TestDecimal::test_serialize_emptystring",
"colander/tests/test_colander.py::TestDecimal::test_serialize_fails",
"colander/tests/test_colander.py::TestDecimal::test_serialize_normalize",
"colander/tests/test_colander.py::TestDecimal::test_serialize_null",
"colander/tests/test_colander.py::TestDecimal::test_serialize_ok",
"colander/tests/test_colander.py::TestDecimal::test_serialize_quantize_no_rounding",
"colander/tests/test_colander.py::TestDecimal::test_serialize_quantize_with_rounding_up",
"colander/tests/test_colander.py::TestMoney::test_deserialize_rounds_up",
"colander/tests/test_colander.py::TestMoney::test_serialize_rounds_up",
"colander/tests/test_colander.py::TestBoolean::test_alias",
"colander/tests/test_colander.py::TestBoolean::test_deserialize",
"colander/tests/test_colander.py::TestBoolean::test_deserialize_null",
"colander/tests/test_colander.py::TestBoolean::test_deserialize_unstringable",
"colander/tests/test_colander.py::TestBoolean::test_serialize",
"colander/tests/test_colander.py::TestBoolean::test_serialize_null",
"colander/tests/test_colander.py::TestBooleanCustomFalseReprs::test_deserialize",
"colander/tests/test_colander.py::TestBooleanCustomFalseAndTrueReprs::test_deserialize",
"colander/tests/test_colander.py::TestBooleanCustomSerializations::test_serialize",
"colander/tests/test_colander.py::TestGlobalObject::test__pkg_resources_style_irrresolveable_absolute",
"colander/tests/test_colander.py::TestGlobalObject::test__pkg_resources_style_irrresolveable_relative",
"colander/tests/test_colander.py::TestGlobalObject::test__pkg_resources_style_resolve_absolute",
"colander/tests/test_colander.py::TestGlobalObject::test__pkg_resources_style_resolve_relative_is_dot",
"colander/tests/test_colander.py::TestGlobalObject::test__pkg_resources_style_resolve_relative_nocurrentpackage",
"colander/tests/test_colander.py::TestGlobalObject::test__pkg_resources_style_resolve_relative_startswith_colon",
"colander/tests/test_colander.py::TestGlobalObject::test__pkg_resources_style_resolve_relative_startswith_dot",
"colander/tests/test_colander.py::TestGlobalObject::test__zope_dottedname_style_irresolveable_absolute",
"colander/tests/test_colander.py::TestGlobalObject::test__zope_dottedname_style_irresolveable_relative_is_dot",
"colander/tests/test_colander.py::TestGlobalObject::test__zope_dottedname_style_resolve_relative",
"colander/tests/test_colander.py::TestGlobalObject::test__zope_dottedname_style_resolve_relative_is_dot",
"colander/tests/test_colander.py::TestGlobalObject::test__zope_dottedname_style_resolve_relative_leading_dots",
"colander/tests/test_colander.py::TestGlobalObject::test__zope_dottedname_style_resolveable_absolute",
"colander/tests/test_colander.py::TestGlobalObject::test__zope_dottedname_style_resolveable_relative",
"colander/tests/test_colander.py::TestGlobalObject::test_deserialize_None",
"colander/tests/test_colander.py::TestGlobalObject::test_deserialize_class_fail",
"colander/tests/test_colander.py::TestGlobalObject::test_deserialize_class_ok",
"colander/tests/test_colander.py::TestGlobalObject::test_deserialize_notastring",
"colander/tests/test_colander.py::TestGlobalObject::test_deserialize_null",
"colander/tests/test_colander.py::TestGlobalObject::test_deserialize_style_raises",
"colander/tests/test_colander.py::TestGlobalObject::test_deserialize_using_pkgresources_style",
"colander/tests/test_colander.py::TestGlobalObject::test_deserialize_using_zope_dottedname_style",
"colander/tests/test_colander.py::TestGlobalObject::test_serialize_class",
"colander/tests/test_colander.py::TestGlobalObject::test_serialize_fail",
"colander/tests/test_colander.py::TestGlobalObject::test_serialize_null",
"colander/tests/test_colander.py::TestGlobalObject::test_serialize_ok",
"colander/tests/test_colander.py::TestGlobalObject::test_zope_dottedname_style_irrresolveable_absolute",
"colander/tests/test_colander.py::TestGlobalObject::test_zope_dottedname_style_irrresolveable_relative",
"colander/tests/test_colander.py::TestGlobalObject::test_zope_dottedname_style_resolve_absolute",
"colander/tests/test_colander.py::TestGlobalObject::test_zope_dottedname_style_resolve_relative_nocurrentpackage",
"colander/tests/test_colander.py::TestDateTime::test_ctor_default_tzinfo_None",
"colander/tests/test_colander.py::TestDateTime::test_ctor_default_tzinfo_non_None",
"colander/tests/test_colander.py::TestDateTime::test_ctor_default_tzinfo_not_specified",
"colander/tests/test_colander.py::TestDateTime::test_deserialize_date",
"colander/tests/test_colander.py::TestDateTime::test_deserialize_datetime_with_custom_format",
"colander/tests/test_colander.py::TestDateTime::test_deserialize_empty",
"colander/tests/test_colander.py::TestDateTime::test_deserialize_invalid_ParseError",
"colander/tests/test_colander.py::TestDateTime::test_deserialize_naive_with_default_tzinfo",
"colander/tests/test_colander.py::TestDateTime::test_deserialize_none_tzinfo",
"colander/tests/test_colander.py::TestDateTime::test_deserialize_null",
"colander/tests/test_colander.py::TestDateTime::test_deserialize_slashes_invalid",
"colander/tests/test_colander.py::TestDateTime::test_deserialize_success",
"colander/tests/test_colander.py::TestDateTime::test_serialize_none",
"colander/tests/test_colander.py::TestDateTime::test_serialize_null",
"colander/tests/test_colander.py::TestDateTime::test_serialize_with_date",
"colander/tests/test_colander.py::TestDateTime::test_serialize_with_garbage",
"colander/tests/test_colander.py::TestDateTime::test_serialize_with_naive_datetime",
"colander/tests/test_colander.py::TestDateTime::test_serialize_with_naive_datetime_and_custom_format",
"colander/tests/test_colander.py::TestDateTime::test_serialize_with_none_tzinfo_naive_datetime",
"colander/tests/test_colander.py::TestDateTime::test_serialize_with_none_tzinfo_naive_datetime_custom_format",
"colander/tests/test_colander.py::TestDateTime::test_serialize_with_tzware_datetime",
"colander/tests/test_colander.py::TestDate::test_deserialize_date_with_custom_format",
"colander/tests/test_colander.py::TestDate::test_deserialize_empty",
"colander/tests/test_colander.py::TestDate::test_deserialize_invalid_ParseError",
"colander/tests/test_colander.py::TestDate::test_deserialize_invalid_weird",
"colander/tests/test_colander.py::TestDate::test_deserialize_null",
"colander/tests/test_colander.py::TestDate::test_deserialize_success_date",
"colander/tests/test_colander.py::TestDate::test_deserialize_success_datetime",
"colander/tests/test_colander.py::TestDate::test_serialize_date_with_custom_format",
"colander/tests/test_colander.py::TestDate::test_serialize_none",
"colander/tests/test_colander.py::TestDate::test_serialize_null",
"colander/tests/test_colander.py::TestDate::test_serialize_with_date",
"colander/tests/test_colander.py::TestDate::test_serialize_with_datetime",
"colander/tests/test_colander.py::TestDate::test_serialize_with_garbage",
"colander/tests/test_colander.py::TestTime::test_deserialize_empty",
"colander/tests/test_colander.py::TestTime::test_deserialize_four_digit_string",
"colander/tests/test_colander.py::TestTime::test_deserialize_invalid_ParseError",
"colander/tests/test_colander.py::TestTime::test_deserialize_missing_seconds",
"colander/tests/test_colander.py::TestTime::test_deserialize_null",
"colander/tests/test_colander.py::TestTime::test_deserialize_success_datetime",
"colander/tests/test_colander.py::TestTime::test_deserialize_success_time",
"colander/tests/test_colander.py::TestTime::test_deserialize_three_digit_string",
"colander/tests/test_colander.py::TestTime::test_deserialize_two_digit_string",
"colander/tests/test_colander.py::TestTime::test_serialize_none",
"colander/tests/test_colander.py::TestTime::test_serialize_null",
"colander/tests/test_colander.py::TestTime::test_serialize_with_datetime",
"colander/tests/test_colander.py::TestTime::test_serialize_with_garbage",
"colander/tests/test_colander.py::TestTime::test_serialize_with_time",
"colander/tests/test_colander.py::TestTime::test_serialize_with_zero_time",
"colander/tests/test_colander.py::TestEnum::test_deserialize_failure",
"colander/tests/test_colander.py::TestEnum::test_deserialize_failure_typ",
"colander/tests/test_colander.py::TestEnum::test_deserialize_name",
"colander/tests/test_colander.py::TestEnum::test_deserialize_null",
"colander/tests/test_colander.py::TestEnum::test_deserialize_value_int",
"colander/tests/test_colander.py::TestEnum::test_deserialize_value_str",
"colander/tests/test_colander.py::TestEnum::test_non_unique_failure",
"colander/tests/test_colander.py::TestEnum::test_non_unique_failure2",
"colander/tests/test_colander.py::TestEnum::test_serialize_failure",
"colander/tests/test_colander.py::TestEnum::test_serialize_name",
"colander/tests/test_colander.py::TestEnum::test_serialize_null",
"colander/tests/test_colander.py::TestEnum::test_serialize_value_int",
"colander/tests/test_colander.py::TestEnum::test_serialize_value_str",
"colander/tests/test_colander.py::TestSchemaNode::test___contains__",
"colander/tests/test_colander.py::TestSchemaNode::test___delitem__failure",
"colander/tests/test_colander.py::TestSchemaNode::test___delitem__success",
"colander/tests/test_colander.py::TestSchemaNode::test___getitem__failure",
"colander/tests/test_colander.py::TestSchemaNode::test___getitem__success",
"colander/tests/test_colander.py::TestSchemaNode::test___iter__",
"colander/tests/test_colander.py::TestSchemaNode::test___setitem__no_override",
"colander/tests/test_colander.py::TestSchemaNode::test___setitem__override",
"colander/tests/test_colander.py::TestSchemaNode::test_add",
"colander/tests/test_colander.py::TestSchemaNode::test_bind",
"colander/tests/test_colander.py::TestSchemaNode::test_bind_with_after_bind",
"colander/tests/test_colander.py::TestSchemaNode::test_clone",
"colander/tests/test_colander.py::TestSchemaNode::test_clone_mapping_references",
"colander/tests/test_colander.py::TestSchemaNode::test_clone_with_modified_schema_instance",
"colander/tests/test_colander.py::TestSchemaNode::test_cstruct_children",
"colander/tests/test_colander.py::TestSchemaNode::test_cstruct_children_warning",
"colander/tests/test_colander.py::TestSchemaNode::test_ctor_children_kwarg_typ",
"colander/tests/test_colander.py::TestSchemaNode::test_ctor_no_title",
"colander/tests/test_colander.py::TestSchemaNode::test_ctor_with_description",
"colander/tests/test_colander.py::TestSchemaNode::test_ctor_with_kwarg_typ",
"colander/tests/test_colander.py::TestSchemaNode::test_ctor_with_preparer",
"colander/tests/test_colander.py::TestSchemaNode::test_ctor_with_title",
"colander/tests/test_colander.py::TestSchemaNode::test_ctor_with_unknown_kwarg",
"colander/tests/test_colander.py::TestSchemaNode::test_ctor_with_widget",
"colander/tests/test_colander.py::TestSchemaNode::test_ctor_without_preparer",
"colander/tests/test_colander.py::TestSchemaNode::test_ctor_without_type",
"colander/tests/test_colander.py::TestSchemaNode::test_declarative_name_reassignment",
"colander/tests/test_colander.py::TestSchemaNode::test_deserialize_appstruct_deferred",
"colander/tests/test_colander.py::TestSchemaNode::test_deserialize_no_validator",
"colander/tests/test_colander.py::TestSchemaNode::test_deserialize_noargs_uses_default",
"colander/tests/test_colander.py::TestSchemaNode::test_deserialize_null_can_be_used_as_missing",
"colander/tests/test_colander.py::TestSchemaNode::test_deserialize_preparer_before_missing_check",
"colander/tests/test_colander.py::TestSchemaNode::test_deserialize_value_is_null_no_missing",
"colander/tests/test_colander.py::TestSchemaNode::test_deserialize_value_is_null_with_missing",
"colander/tests/test_colander.py::TestSchemaNode::test_deserialize_value_is_null_with_missing_msg",
"colander/tests/test_colander.py::TestSchemaNode::test_deserialize_value_with_interpolated_missing_msg",
"colander/tests/test_colander.py::TestSchemaNode::test_deserialize_with_multiple_preparers",
"colander/tests/test_colander.py::TestSchemaNode::test_deserialize_with_preparer",
"colander/tests/test_colander.py::TestSchemaNode::test_deserialize_with_unbound_validator",
"colander/tests/test_colander.py::TestSchemaNode::test_deserialize_with_validator",
"colander/tests/test_colander.py::TestSchemaNode::test_insert",
"colander/tests/test_colander.py::TestSchemaNode::test_new_sets_order",
"colander/tests/test_colander.py::TestSchemaNode::test_raise_invalid",
"colander/tests/test_colander.py::TestSchemaNode::test_repr",
"colander/tests/test_colander.py::TestSchemaNode::test_required_deferred",
"colander/tests/test_colander.py::TestSchemaNode::test_required_false",
"colander/tests/test_colander.py::TestSchemaNode::test_required_true",
"colander/tests/test_colander.py::TestSchemaNode::test_serialize",
"colander/tests/test_colander.py::TestSchemaNode::test_serialize_default_deferred",
"colander/tests/test_colander.py::TestSchemaNode::test_serialize_noargs_uses_default",
"colander/tests/test_colander.py::TestSchemaNode::test_serialize_value_is_null_no_default",
"colander/tests/test_colander.py::TestSchemaNode::test_serialize_value_is_null_with_default",
"colander/tests/test_colander.py::TestSchemaNodeSubclassing::test_deferred_methods_dont_quite_work_yet",
"colander/tests/test_colander.py::TestSchemaNodeSubclassing::test_functions_can_be_deferred",
"colander/tests/test_colander.py::TestSchemaNodeSubclassing::test_method_values_can_rely_on_binding",
"colander/tests/test_colander.py::TestSchemaNodeSubclassing::test_nodes_can_be_deffered",
"colander/tests/test_colander.py::TestSchemaNodeSubclassing::test_nonmethod_values_can_be_deferred_though",
"colander/tests/test_colander.py::TestSchemaNodeSubclassing::test_nonmethod_values_can_rely_on_after_bind",
"colander/tests/test_colander.py::TestSchemaNodeSubclassing::test_schema_child_names_conflict_with_value_names_in_subclass",
"colander/tests/test_colander.py::TestSchemaNodeSubclassing::test_schema_child_names_conflict_with_value_names_in_superclass",
"colander/tests/test_colander.py::TestSchemaNodeSubclassing::test_schema_child_names_conflict_with_value_names_notused",
"colander/tests/test_colander.py::TestSchemaNodeSubclassing::test_schema_child_names_conflict_with_value_names_used",
"colander/tests/test_colander.py::TestSchemaNodeSubclassing::test_subclass_title_overwritten_by_constructor",
"colander/tests/test_colander.py::TestSchemaNodeSubclassing::test_subclass_uses_missing",
"colander/tests/test_colander.py::TestSchemaNodeSubclassing::test_subclass_uses_title",
"colander/tests/test_colander.py::TestSchemaNodeSubclassing::test_subclass_uses_validator_method",
"colander/tests/test_colander.py::TestSchemaNodeSubclassing::test_subclass_value_overridden_by_constructor",
"colander/tests/test_colander.py::TestSchemaNodeSubclassing::test_subelement_title_not_overwritten",
"colander/tests/test_colander.py::TestMappingSchemaInheritance::test_insert_before_failure",
"colander/tests/test_colander.py::TestMappingSchemaInheritance::test_multiple_inheritance",
"colander/tests/test_colander.py::TestMappingSchemaInheritance::test_single_inheritance",
"colander/tests/test_colander.py::TestMappingSchemaInheritance::test_single_inheritance2",
"colander/tests/test_colander.py::TestMappingSchemaInheritance::test_single_inheritance_with_insert_before",
"colander/tests/test_colander.py::TestDeferred::test___call__",
"colander/tests/test_colander.py::TestDeferred::test_ctor",
"colander/tests/test_colander.py::TestDeferred::test_retain_func_details",
"colander/tests/test_colander.py::TestDeferred::test_w_callable_instance_no_name",
"colander/tests/test_colander.py::TestDeferred::test_w_callable_instance_no_name_or_doc",
"colander/tests/test_colander.py::TestSchema::test_alias",
"colander/tests/test_colander.py::TestSchema::test_deserialize_drop",
"colander/tests/test_colander.py::TestSchema::test_imperative_with_implicit_schema_type",
"colander/tests/test_colander.py::TestSchema::test_it",
"colander/tests/test_colander.py::TestSchema::test_schema_with_cloned_nodes",
"colander/tests/test_colander.py::TestSchema::test_serialize_drop_default",
"colander/tests/test_colander.py::TestSchema::test_title_munging",
"colander/tests/test_colander.py::TestSequenceSchema::test_clone_with_sequence_schema",
"colander/tests/test_colander.py::TestSequenceSchema::test_deserialize_drop",
"colander/tests/test_colander.py::TestSequenceSchema::test_fail_toofew",
"colander/tests/test_colander.py::TestSequenceSchema::test_fail_toomany",
"colander/tests/test_colander.py::TestSequenceSchema::test_imperative_with_implicit_schema_type",
"colander/tests/test_colander.py::TestSequenceSchema::test_serialize_drop_default",
"colander/tests/test_colander.py::TestSequenceSchema::test_succeed",
"colander/tests/test_colander.py::TestTupleSchema::test_imperative_with_implicit_schema_type",
"colander/tests/test_colander.py::TestTupleSchema::test_it",
"colander/tests/test_colander.py::TestImperative::test_deserialize_ok",
"colander/tests/test_colander.py::TestImperative::test_flatten_mapping_has_no_name",
"colander/tests/test_colander.py::TestImperative::test_flatten_ok",
"colander/tests/test_colander.py::TestImperative::test_flatten_unflatten_roundtrip",
"colander/tests/test_colander.py::TestImperative::test_get_value",
"colander/tests/test_colander.py::TestImperative::test_invalid_asdict",
"colander/tests/test_colander.py::TestImperative::test_invalid_asdict_translation_callback",
"colander/tests/test_colander.py::TestImperative::test_set_value",
"colander/tests/test_colander.py::TestImperative::test_unflatten_mapping_no_name",
"colander/tests/test_colander.py::TestImperative::test_unflatten_ok",
"colander/tests/test_colander.py::TestDeclarative::test_deserialize_ok",
"colander/tests/test_colander.py::TestDeclarative::test_flatten_mapping_has_no_name",
"colander/tests/test_colander.py::TestDeclarative::test_flatten_ok",
"colander/tests/test_colander.py::TestDeclarative::test_flatten_unflatten_roundtrip",
"colander/tests/test_colander.py::TestDeclarative::test_get_value",
"colander/tests/test_colander.py::TestDeclarative::test_invalid_asdict",
"colander/tests/test_colander.py::TestDeclarative::test_invalid_asdict_translation_callback",
"colander/tests/test_colander.py::TestDeclarative::test_set_value",
"colander/tests/test_colander.py::TestDeclarative::test_unflatten_mapping_no_name",
"colander/tests/test_colander.py::TestDeclarative::test_unflatten_ok",
"colander/tests/test_colander.py::TestUltraDeclarative::test_deserialize_ok",
"colander/tests/test_colander.py::TestUltraDeclarative::test_flatten_mapping_has_no_name",
"colander/tests/test_colander.py::TestUltraDeclarative::test_flatten_ok",
"colander/tests/test_colander.py::TestUltraDeclarative::test_flatten_unflatten_roundtrip",
"colander/tests/test_colander.py::TestUltraDeclarative::test_get_value",
"colander/tests/test_colander.py::TestUltraDeclarative::test_invalid_asdict",
"colander/tests/test_colander.py::TestUltraDeclarative::test_invalid_asdict_translation_callback",
"colander/tests/test_colander.py::TestUltraDeclarative::test_set_value",
"colander/tests/test_colander.py::TestUltraDeclarative::test_unflatten_mapping_no_name",
"colander/tests/test_colander.py::TestUltraDeclarative::test_unflatten_ok",
"colander/tests/test_colander.py::TestDeclarativeWithInstantiate::test_deserialize_ok",
"colander/tests/test_colander.py::TestDeclarativeWithInstantiate::test_flatten_mapping_has_no_name",
"colander/tests/test_colander.py::TestDeclarativeWithInstantiate::test_flatten_ok",
"colander/tests/test_colander.py::TestDeclarativeWithInstantiate::test_flatten_unflatten_roundtrip",
"colander/tests/test_colander.py::TestDeclarativeWithInstantiate::test_get_value",
"colander/tests/test_colander.py::TestDeclarativeWithInstantiate::test_invalid_asdict",
"colander/tests/test_colander.py::TestDeclarativeWithInstantiate::test_invalid_asdict_translation_callback",
"colander/tests/test_colander.py::TestDeclarativeWithInstantiate::test_set_value",
"colander/tests/test_colander.py::TestDeclarativeWithInstantiate::test_unflatten_mapping_no_name",
"colander/tests/test_colander.py::TestDeclarativeWithInstantiate::test_unflatten_ok",
"colander/tests/test_colander.py::Test_null::test___nonzero__",
"colander/tests/test_colander.py::Test_null::test___repr__",
"colander/tests/test_colander.py::Test_null::test_pickling",
"colander/tests/test_colander.py::Test_required::test___repr__",
"colander/tests/test_colander.py::Test_required::test_pickling",
"colander/tests/test_colander.py::Test_drop::test___repr__",
"colander/tests/test_colander.py::Test_drop::test_pickling"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
} | "2019-02-01T09:01:49Z" | bsd-4-clause |
|
Pylons__pyramid_zodbconn-8 | diff --git a/CHANGES.txt b/CHANGES.txt
index 52d8686..2d15203 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -1,6 +1,12 @@
0.8 (unreleased)
----------------
+- Open primary database using ``request.tm``, if present, as the transaction
+ manager. If not present, fall back to the default / global transaction
+ manager. Compatibility with ``pyramid_tm >= `0.11`, which allowed the
+ user to specify an explicit per-request transaction factory.
+ https://github.com/Pylons/pyramid_zodbconn/issues/6.
+
- Add support for Python 3.5 and 3.6.
- Drop support for Python 2.6, 3.2, and 3.3.
diff --git a/pyramid_zodbconn/__init__.py b/pyramid_zodbconn/__init__.py
index 4e96b6f..9c89ac3 100644
--- a/pyramid_zodbconn/__init__.py
+++ b/pyramid_zodbconn/__init__.py
@@ -11,7 +11,7 @@ from .compat import text_
def get_connection(request, dbname=None):
"""
``request`` must be a Pyramid request object.
-
+
When called with no ``dbname`` argument or a ``dbname`` argument of
``None``, return a connection to the primary datbase (the database set
up as ``zodbconn.uri`` in the current configuration).
@@ -46,7 +46,8 @@ def get_connection(request, dbname=None):
raise ConfigurationError(
'No zodbconn.uri defined in Pyramid settings')
- primary_conn = primary_db.open()
+ tm = getattr(request, 'tm', None)
+ primary_conn = primary_db.open(transaction_manager=tm)
registry.notify(ZODBConnectionOpened(primary_conn, request))
@@ -62,7 +63,7 @@ def get_connection(request, dbname=None):
if dbname is None:
return primary_conn
-
+
try:
conn = primary_conn.get_connection(dbname)
except KeyError:
| Pylons/pyramid_zodbconn | 6e2e5eb660bce5ce06f747fffe767908028d1892 | diff --git a/pyramid_zodbconn/tests/test_init.py b/pyramid_zodbconn/tests/test_init.py
index 901fdeb..2fb0538 100644
--- a/pyramid_zodbconn/tests/test_init.py
+++ b/pyramid_zodbconn/tests/test_init.py
@@ -16,7 +16,7 @@ class Test_get_connection(unittest.TestCase):
request = self._makeRequest()
del request.registry._zodb_databases
self.assertRaises(ConfigurationError, self._callFUT, request)
-
+
def test_without_zodb_database(self):
from pyramid.exceptions import ConfigurationError
request = self._makeRequest()
@@ -27,7 +27,7 @@ class Test_get_connection(unittest.TestCase):
from pyramid.exceptions import ConfigurationError
request = self._makeRequest()
self.assertRaises(ConfigurationError, self._callFUT, request, 'wont')
-
+
def test_primary_conn_already_exists(self):
request = self._makeRequest()
dummy_conn = DummyConnection()
@@ -42,12 +42,27 @@ class Test_get_connection(unittest.TestCase):
request._primary_zodb_conn = dummy_conn
conn = self._callFUT(request, 'secondary')
self.assertEqual(conn, secondary)
-
- def test_primary_conn_new(self):
+
+ def test_primary_conn_new_wo_request_tm(self):
request = self._makeRequest()
+ db = request.registry._zodb_databases['']
conn = self._callFUT(request)
- self.assertEqual(conn,
- request.registry._zodb_databases[''].connection)
+ self.assertEqual(conn, db.connection)
+ self.assertEqual(db._opened_with, [None])
+ self.assertEqual(len(request.finished_callbacks), 1)
+ callback = request.finished_callbacks[0]
+ self.assertFalse(conn.closed)
+ callback(request)
+ self.assertTrue(conn.closed)
+ self.assertTrue(conn.transaction_manager.aborted)
+
+ def test_primary_conn_new_w_request_tm(self):
+ request = self._makeRequest()
+ tm = request.tm = object()
+ db = request.registry._zodb_databases['']
+ conn = self._callFUT(request)
+ self.assertEqual(conn, db.connection)
+ self.assertEqual(db._opened_with, [tm])
self.assertEqual(len(request.finished_callbacks), 1)
callback = request.finished_callbacks[0]
self.assertFalse(conn.closed)
@@ -125,7 +140,7 @@ class Test_includeme(unittest.TestCase):
def tearDown(self):
testing.tearDown()
-
+
def _callFUT(self, config, db_from_uri=None, open=open):
config.captured_uris = []
self.db = DummyDB()
@@ -219,9 +234,11 @@ class Test_includeme(unittest.TestCase):
class DummyDB:
def __init__(self, connections=None):
+ self._opened_with = []
self.databases = {'unnamed': self}
self.connection = DummyConnection(connections)
- def open(self):
+ def open(self, transaction_manager=None):
+ self._opened_with.append(transaction_manager)
return self.connection
def setActivityMonitor(self, am):
self.am = am
| Use the transaction manager defined by the request.
https://github.com/Pylons/pyramid_zodbconn/blob/2bce04378e5d98e68cb49b3e4be47fe9e15a6ce1/pyramid_zodbconn/__init__.py#L49
This should be `primary_db.open(request.tm)` to support the request's transaction manager from pyramid_tm. Currently the pyramid scaffold is broken without this and it'd be better to improve this than to revert the scaffold - however I cannot cut releases of this package. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"pyramid_zodbconn/tests/test_init.py::Test_get_connection::test_primary_conn_new_w_request_tm"
] | [
"pyramid_zodbconn/tests/test_init.py::Test_get_connection::test_primary_conn_already_exists",
"pyramid_zodbconn/tests/test_init.py::Test_get_connection::test_primary_conn_new_wo_request_tm",
"pyramid_zodbconn/tests/test_init.py::Test_get_connection::test_secondary_conn",
"pyramid_zodbconn/tests/test_init.py::Test_get_connection::test_without_include",
"pyramid_zodbconn/tests/test_init.py::Test_get_connection::test_without_zodb_database",
"pyramid_zodbconn/tests/test_init.py::Test_get_connection::test_without_zodb_database_named",
"pyramid_zodbconn/tests/test_init.py::TestTransferLog::test_end_info_is_None",
"pyramid_zodbconn/tests/test_init.py::TestTransferLog::test_end_info_is_not_None",
"pyramid_zodbconn/tests/test_init.py::TestTransferLog::test_limited_by_threshhold",
"pyramid_zodbconn/tests/test_init.py::TestTransferLog::test_not_limited_by_threshhold",
"pyramid_zodbconn/tests/test_init.py::TestTransferLog::test_start",
"pyramid_zodbconn/tests/test_init.py::Test_db_from_uri::test_it",
"pyramid_zodbconn/tests/test_init.py::Test_includeme::test_activity_monitor_present",
"pyramid_zodbconn/tests/test_init.py::Test_includeme::test_with_bad_named_uri",
"pyramid_zodbconn/tests/test_init.py::Test_includeme::test_with_named_uris",
"pyramid_zodbconn/tests/test_init.py::Test_includeme::test_with_only_named_uri",
"pyramid_zodbconn/tests/test_init.py::Test_includeme::test_with_txlog_filename",
"pyramid_zodbconn/tests/test_init.py::Test_includeme::test_with_txlog_stdout",
"pyramid_zodbconn/tests/test_init.py::Test_includeme::test_with_txlog_threshhold",
"pyramid_zodbconn/tests/test_init.py::Test_includeme::test_with_uri",
"pyramid_zodbconn/tests/test_init.py::Test_includeme::test_without_uri"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
} | "2017-07-25T16:54:35Z" | bsd-4-clause |
|
Pylons__webob-291 | diff --git a/.travis.yml b/.travis.yml
index de5f487..7037c57 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -12,12 +12,17 @@ matrix:
env: TOXENV=py34
- python: 3.5
env: TOXENV=py35
+ - python: 3.6-dev
+ env: TOXENV=py36
+ - python: nightly
+ env: TOXENV=py37
- python: pypy
env: TOXENV=pypy
- - python: pypy3
- env: TOXENV=pypy3
- python: 3.5
env: TOXENV=py2-cover,py3-cover,coverage
+ allow_failures:
+ - env: TOXENV=py36
+ - env: TOXENV=py37
install:
- travis_retry pip install tox
diff --git a/CHANGES.txt b/CHANGES.txt
index af25400..2d1795f 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -39,6 +39,9 @@ Feature
Bugfix
~~~~~~
+- Fixes request.PATH_SAFE to contain all of the path safe characters according
+ to RFC3986. See https://github.com/Pylons/webob/pull/291
+
- WebOb's exceptions will lazily read underlying variables when inserted into
templates to avoid expensive computations/crashes when inserting into the
template. This had a bad performance regression on Py27 because of the way
@@ -84,4 +87,4 @@ Bugfix
This is used in the exception handling code so that if you use a WebOb HTTP
Exception and pass a generator to `app_iter` WebOb won't attempt to read the
whole thing and instead allows it to be returned to the WSGI server. See
- https://github.com/Pylons/webob/pull/259
+ https://github.com/Pylons/webob/pull/259
diff --git a/tox.ini b/tox.ini
index 402fd6a..79ee9c3 100644
--- a/tox.ini
+++ b/tox.ini
@@ -1,7 +1,8 @@
[tox]
envlist =
- py27,py33,py34,py35,pypy,pypy3,
+ py27,py33,py34,py35,py36,py37,pypy,
docs,{py2,py3}-cover,coverage
+skip_missing_interpreters = True
[testenv]
# Most of these are defaults but if you specify any you can't fall back
@@ -11,10 +12,11 @@ basepython =
py33: python3.3
py34: python3.4
py35: python3.5
+ py36: python3.6
+ py37: python3.7
pypy: pypy
- pypy3: pypy3
py2: python2.7
- py3: python3.4
+ py3: python3.5
commands =
pip install webob[testing]
diff --git a/webob/request.py b/webob/request.py
index 45bc6f9..191b1b7 100644
--- a/webob/request.py
+++ b/webob/request.py
@@ -83,7 +83,7 @@ class _NoDefault:
return '(No Default)'
NoDefault = _NoDefault()
-PATH_SAFE = '/:@&+$,'
+PATH_SAFE = "/~!$&'()*+,;=:@"
_LATIN_ENCODINGS = (
'ascii', 'latin-1', 'latin', 'latin_1', 'l1', 'latin1',
| Pylons/webob | a755ef991d7a87a4c41dbf727b84e91e90ef97ad | diff --git a/tests/test_request.py b/tests/test_request.py
index 9650702..de3b149 100644
--- a/tests/test_request.py
+++ b/tests/test_request.py
@@ -2558,11 +2558,17 @@ class TestRequest_functional(object):
assert req.cookies == {'foo': '?foo'}
def test_path_quoting(self):
- path = '/:@&+$,/bar'
+ path = "/_.-~!$&'()*+,;=:@/bar"
req = self._blankOne(path)
assert req.path == path
assert req.url.endswith(path)
+ def test_path_quoting_pct_encodes(self):
+ path = '/[]/bar'
+ req = self._blankOne(path)
+ assert req.path == '/%5B%5D/bar'
+ assert req.url.endswith('/%5B%5D/bar')
+
def test_params(self):
req = self._blankOne('/?a=1&b=2')
req.method = 'POST'
| Fixup w.r.PATH_SAFE to match RFC3986
Related to discussion in https://github.com/Pylons/pyramid/pull/2811. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_request.py::TestRequest_functional::test_path_quoting"
] | [
"tests/test_request.py::TestRequestCommon::test_ctor_environ_getter_raises_WTF",
"tests/test_request.py::TestRequestCommon::test_ctor_wo_environ_raises_WTF",
"tests/test_request.py::TestRequestCommon::test_ctor_w_environ",
"tests/test_request.py::TestRequestCommon::test_ctor_w_non_utf8_charset",
"tests/test_request.py::TestRequestCommon::test_scheme",
"tests/test_request.py::TestRequestCommon::test_body_file_getter",
"tests/test_request.py::TestRequestCommon::test_body_file_getter_seekable",
"tests/test_request.py::TestRequestCommon::test_body_file_getter_cache",
"tests/test_request.py::TestRequestCommon::test_body_file_getter_unreadable",
"tests/test_request.py::TestRequestCommon::test_body_file_setter_w_bytes",
"tests/test_request.py::TestRequestCommon::test_body_file_setter_non_bytes",
"tests/test_request.py::TestRequestCommon::test_body_file_deleter",
"tests/test_request.py::TestRequestCommon::test_body_file_raw",
"tests/test_request.py::TestRequestCommon::test_body_file_seekable_input_not_seekable",
"tests/test_request.py::TestRequestCommon::test_body_file_seekable_input_is_seekable",
"tests/test_request.py::TestRequestCommon::test_urlvars_getter_w_paste_key",
"tests/test_request.py::TestRequestCommon::test_urlvars_getter_w_wsgiorg_key",
"tests/test_request.py::TestRequestCommon::test_urlvars_getter_wo_keys",
"tests/test_request.py::TestRequestCommon::test_urlvars_setter_w_paste_key",
"tests/test_request.py::TestRequestCommon::test_urlvars_setter_w_wsgiorg_key",
"tests/test_request.py::TestRequestCommon::test_urlvars_setter_wo_keys",
"tests/test_request.py::TestRequestCommon::test_urlvars_deleter_w_paste_key",
"tests/test_request.py::TestRequestCommon::test_urlvars_deleter_w_wsgiorg_key_non_empty_tuple",
"tests/test_request.py::TestRequestCommon::test_urlvars_deleter_w_wsgiorg_key_empty_tuple",
"tests/test_request.py::TestRequestCommon::test_urlvars_deleter_wo_keys",
"tests/test_request.py::TestRequestCommon::test_urlargs_getter_w_paste_key",
"tests/test_request.py::TestRequestCommon::test_urlargs_getter_w_wsgiorg_key",
"tests/test_request.py::TestRequestCommon::test_urlargs_getter_wo_keys",
"tests/test_request.py::TestRequestCommon::test_urlargs_setter_w_paste_key",
"tests/test_request.py::TestRequestCommon::test_urlargs_setter_w_wsgiorg_key",
"tests/test_request.py::TestRequestCommon::test_urlargs_setter_wo_keys",
"tests/test_request.py::TestRequestCommon::test_urlargs_deleter_w_wsgiorg_key",
"tests/test_request.py::TestRequestCommon::test_urlargs_deleter_w_wsgiorg_key_empty",
"tests/test_request.py::TestRequestCommon::test_urlargs_deleter_wo_keys",
"tests/test_request.py::TestRequestCommon::test_cookies_empty_environ",
"tests/test_request.py::TestRequestCommon::test_cookies_is_mutable",
"tests/test_request.py::TestRequestCommon::test_cookies_w_webob_parsed_cookies_matching_source",
"tests/test_request.py::TestRequestCommon::test_cookies_w_webob_parsed_cookies_mismatched_source",
"tests/test_request.py::TestRequestCommon::test_set_cookies",
"tests/test_request.py::TestRequestCommon::test_body_getter",
"tests/test_request.py::TestRequestCommon::test_body_setter_None",
"tests/test_request.py::TestRequestCommon::test_body_setter_non_string_raises",
"tests/test_request.py::TestRequestCommon::test_body_setter_value",
"tests/test_request.py::TestRequestCommon::test_body_deleter_None",
"tests/test_request.py::TestRequestCommon::test_json_body",
"tests/test_request.py::TestRequestCommon::test_json_body_array",
"tests/test_request.py::TestRequestCommon::test_text_body",
"tests/test_request.py::TestRequestCommon::test__text_get_without_charset",
"tests/test_request.py::TestRequestCommon::test__text_set_without_charset",
"tests/test_request.py::TestRequestCommon::test_POST_not_POST_or_PUT",
"tests/test_request.py::TestRequestCommon::test_POST_existing_cache_hit",
"tests/test_request.py::TestRequestCommon::test_PUT_missing_content_type",
"tests/test_request.py::TestRequestCommon::test_PATCH_missing_content_type",
"tests/test_request.py::TestRequestCommon::test_POST_missing_content_type",
"tests/test_request.py::TestRequestCommon::test_POST_json_no_content_type",
"tests/test_request.py::TestRequestCommon::test_PUT_bad_content_type",
"tests/test_request.py::TestRequestCommon::test_POST_multipart",
"tests/test_request.py::TestRequestCommon::test_GET_reflects_query_string",
"tests/test_request.py::TestRequestCommon::test_GET_updates_query_string",
"tests/test_request.py::TestRequestCommon::test_cookies_wo_webob_parsed_cookies",
"tests/test_request.py::TestRequestCommon::test_copy_get",
"tests/test_request.py::TestRequestCommon::test_remove_conditional_headers_accept_encoding",
"tests/test_request.py::TestRequestCommon::test_remove_conditional_headers_if_modified_since",
"tests/test_request.py::TestRequestCommon::test_remove_conditional_headers_if_none_match",
"tests/test_request.py::TestRequestCommon::test_remove_conditional_headers_if_range",
"tests/test_request.py::TestRequestCommon::test_remove_conditional_headers_range",
"tests/test_request.py::TestRequestCommon::test_is_body_readable_POST",
"tests/test_request.py::TestRequestCommon::test_is_body_readable_PATCH",
"tests/test_request.py::TestRequestCommon::test_is_body_readable_GET",
"tests/test_request.py::TestRequestCommon::test_is_body_readable_unknown_method_and_content_length",
"tests/test_request.py::TestRequestCommon::test_is_body_readable_special_flag",
"tests/test_request.py::TestRequestCommon::test_cache_control_reflects_environ",
"tests/test_request.py::TestRequestCommon::test_cache_control_updates_environ",
"tests/test_request.py::TestRequestCommon::test_cache_control_set_dict",
"tests/test_request.py::TestRequestCommon::test_cache_control_set_object",
"tests/test_request.py::TestRequestCommon::test_cache_control_gets_cached",
"tests/test_request.py::TestRequestCommon::test_call_application_calls_application",
"tests/test_request.py::TestRequestCommon::test_call_application_provides_write",
"tests/test_request.py::TestRequestCommon::test_call_application_closes_iterable_when_mixed_w_write_calls",
"tests/test_request.py::TestRequestCommon::test_call_application_raises_exc_info",
"tests/test_request.py::TestRequestCommon::test_call_application_returns_exc_info",
"tests/test_request.py::TestRequestCommon::test_blank__method_subtitution",
"tests/test_request.py::TestRequestCommon::test_blank__ctype_in_env",
"tests/test_request.py::TestRequestCommon::test_blank__ctype_in_headers",
"tests/test_request.py::TestRequestCommon::test_blank__ctype_as_kw",
"tests/test_request.py::TestRequestCommon::test_blank__str_post_data_for_unsupported_ctype",
"tests/test_request.py::TestRequestCommon::test_blank__post_urlencoded",
"tests/test_request.py::TestRequestCommon::test_blank__post_multipart",
"tests/test_request.py::TestRequestCommon::test_blank__post_files",
"tests/test_request.py::TestRequestCommon::test_blank__post_file_w_wrong_ctype",
"tests/test_request.py::TestRequestCommon::test_from_bytes_extra_data",
"tests/test_request.py::TestRequestCommon::test_as_bytes_skip_body",
"tests/test_request.py::TestBaseRequest::test_method",
"tests/test_request.py::TestBaseRequest::test_http_version",
"tests/test_request.py::TestBaseRequest::test_script_name",
"tests/test_request.py::TestBaseRequest::test_path_info",
"tests/test_request.py::TestBaseRequest::test_content_length_getter",
"tests/test_request.py::TestBaseRequest::test_content_length_setter_w_str",
"tests/test_request.py::TestBaseRequest::test_remote_user",
"tests/test_request.py::TestBaseRequest::test_remote_addr",
"tests/test_request.py::TestBaseRequest::test_query_string",
"tests/test_request.py::TestBaseRequest::test_server_name",
"tests/test_request.py::TestBaseRequest::test_server_port_getter",
"tests/test_request.py::TestBaseRequest::test_server_port_setter_with_string",
"tests/test_request.py::TestBaseRequest::test_uscript_name",
"tests/test_request.py::TestBaseRequest::test_upath_info",
"tests/test_request.py::TestBaseRequest::test_upath_info_set_unicode",
"tests/test_request.py::TestBaseRequest::test_content_type_getter_no_parameters",
"tests/test_request.py::TestBaseRequest::test_content_type_getter_w_parameters",
"tests/test_request.py::TestBaseRequest::test_content_type_setter_w_None",
"tests/test_request.py::TestBaseRequest::test_content_type_setter_existing_paramter_no_new_paramter",
"tests/test_request.py::TestBaseRequest::test_content_type_deleter_clears_environ_value",
"tests/test_request.py::TestBaseRequest::test_content_type_deleter_no_environ_value",
"tests/test_request.py::TestBaseRequest::test_headers_getter",
"tests/test_request.py::TestBaseRequest::test_headers_setter",
"tests/test_request.py::TestBaseRequest::test_no_headers_deleter",
"tests/test_request.py::TestBaseRequest::test_client_addr_xff_singleval",
"tests/test_request.py::TestBaseRequest::test_client_addr_xff_multival",
"tests/test_request.py::TestBaseRequest::test_client_addr_prefers_xff",
"tests/test_request.py::TestBaseRequest::test_client_addr_no_xff",
"tests/test_request.py::TestBaseRequest::test_client_addr_no_xff_no_remote_addr",
"tests/test_request.py::TestBaseRequest::test_host_port_w_http_host_and_no_port",
"tests/test_request.py::TestBaseRequest::test_host_port_w_http_host_and_standard_port",
"tests/test_request.py::TestBaseRequest::test_host_port_w_http_host_and_oddball_port",
"tests/test_request.py::TestBaseRequest::test_host_port_w_http_host_https_and_no_port",
"tests/test_request.py::TestBaseRequest::test_host_port_w_http_host_https_and_standard_port",
"tests/test_request.py::TestBaseRequest::test_host_port_w_http_host_https_and_oddball_port",
"tests/test_request.py::TestBaseRequest::test_host_port_wo_http_host",
"tests/test_request.py::TestBaseRequest::test_host_url_w_http_host_and_no_port",
"tests/test_request.py::TestBaseRequest::test_host_url_w_http_host_and_standard_port",
"tests/test_request.py::TestBaseRequest::test_host_url_w_http_host_and_oddball_port",
"tests/test_request.py::TestBaseRequest::test_host_url_w_http_host_https_and_no_port",
"tests/test_request.py::TestBaseRequest::test_host_url_w_http_host_https_and_standard_port",
"tests/test_request.py::TestBaseRequest::test_host_url_w_http_host_https_and_oddball_port",
"tests/test_request.py::TestBaseRequest::test_host_url_wo_http_host",
"tests/test_request.py::TestBaseRequest::test_application_url",
"tests/test_request.py::TestBaseRequest::test_path_url",
"tests/test_request.py::TestBaseRequest::test_path",
"tests/test_request.py::TestBaseRequest::test_path_qs_no_qs",
"tests/test_request.py::TestBaseRequest::test_path_qs_w_qs",
"tests/test_request.py::TestBaseRequest::test_url_no_qs",
"tests/test_request.py::TestBaseRequest::test_url_w_qs",
"tests/test_request.py::TestBaseRequest::test_relative_url_to_app_true_wo_leading_slash",
"tests/test_request.py::TestBaseRequest::test_relative_url_to_app_true_w_leading_slash",
"tests/test_request.py::TestBaseRequest::test_relative_url_to_app_false_other_w_leading_slash",
"tests/test_request.py::TestBaseRequest::test_relative_url_to_app_false_other_wo_leading_slash",
"tests/test_request.py::TestBaseRequest::test_path_info_pop_empty",
"tests/test_request.py::TestBaseRequest::test_path_info_pop_just_leading_slash",
"tests/test_request.py::TestBaseRequest::test_path_info_pop_non_empty_no_pattern",
"tests/test_request.py::TestBaseRequest::test_path_info_pop_non_empty_w_pattern_miss",
"tests/test_request.py::TestBaseRequest::test_path_info_pop_non_empty_w_pattern_hit",
"tests/test_request.py::TestBaseRequest::test_path_info_pop_skips_empty_elements",
"tests/test_request.py::TestBaseRequest::test_path_info_peek_empty",
"tests/test_request.py::TestBaseRequest::test_path_info_peek_just_leading_slash",
"tests/test_request.py::TestBaseRequest::test_path_info_peek_non_empty",
"tests/test_request.py::TestBaseRequest::test_is_xhr_no_header",
"tests/test_request.py::TestBaseRequest::test_is_xhr_header_miss",
"tests/test_request.py::TestBaseRequest::test_is_xhr_header_hit",
"tests/test_request.py::TestBaseRequest::test_host_getter_w_HTTP_HOST",
"tests/test_request.py::TestBaseRequest::test_host_getter_wo_HTTP_HOST",
"tests/test_request.py::TestBaseRequest::test_host_setter",
"tests/test_request.py::TestBaseRequest::test_host_deleter_hit",
"tests/test_request.py::TestBaseRequest::test_host_deleter_miss",
"tests/test_request.py::TestBaseRequest::test_domain_nocolon",
"tests/test_request.py::TestBaseRequest::test_domain_withcolon",
"tests/test_request.py::TestBaseRequest::test_encget_raises_without_default",
"tests/test_request.py::TestBaseRequest::test_encget_doesnt_raises_with_default",
"tests/test_request.py::TestBaseRequest::test_encget_with_encattr",
"tests/test_request.py::TestBaseRequest::test_encget_with_encattr_latin_1",
"tests/test_request.py::TestBaseRequest::test_encget_no_encattr",
"tests/test_request.py::TestBaseRequest::test_relative_url",
"tests/test_request.py::TestBaseRequest::test_header_getter",
"tests/test_request.py::TestBaseRequest::test_json_body",
"tests/test_request.py::TestBaseRequest::test_host_get",
"tests/test_request.py::TestBaseRequest::test_host_get_w_no_http_host",
"tests/test_request.py::TestLegacyRequest::test_method",
"tests/test_request.py::TestLegacyRequest::test_http_version",
"tests/test_request.py::TestLegacyRequest::test_script_name",
"tests/test_request.py::TestLegacyRequest::test_path_info",
"tests/test_request.py::TestLegacyRequest::test_content_length_getter",
"tests/test_request.py::TestLegacyRequest::test_content_length_setter_w_str",
"tests/test_request.py::TestLegacyRequest::test_remote_user",
"tests/test_request.py::TestLegacyRequest::test_remote_addr",
"tests/test_request.py::TestLegacyRequest::test_query_string",
"tests/test_request.py::TestLegacyRequest::test_server_name",
"tests/test_request.py::TestLegacyRequest::test_server_port_getter",
"tests/test_request.py::TestLegacyRequest::test_server_port_setter_with_string",
"tests/test_request.py::TestLegacyRequest::test_uscript_name",
"tests/test_request.py::TestLegacyRequest::test_upath_info",
"tests/test_request.py::TestLegacyRequest::test_upath_info_set_unicode",
"tests/test_request.py::TestLegacyRequest::test_content_type_getter_no_parameters",
"tests/test_request.py::TestLegacyRequest::test_content_type_getter_w_parameters",
"tests/test_request.py::TestLegacyRequest::test_content_type_setter_w_None",
"tests/test_request.py::TestLegacyRequest::test_content_type_setter_existing_paramter_no_new_paramter",
"tests/test_request.py::TestLegacyRequest::test_content_type_deleter_clears_environ_value",
"tests/test_request.py::TestLegacyRequest::test_content_type_deleter_no_environ_value",
"tests/test_request.py::TestLegacyRequest::test_headers_getter",
"tests/test_request.py::TestLegacyRequest::test_headers_setter",
"tests/test_request.py::TestLegacyRequest::test_no_headers_deleter",
"tests/test_request.py::TestLegacyRequest::test_client_addr_xff_singleval",
"tests/test_request.py::TestLegacyRequest::test_client_addr_xff_multival",
"tests/test_request.py::TestLegacyRequest::test_client_addr_prefers_xff",
"tests/test_request.py::TestLegacyRequest::test_client_addr_no_xff",
"tests/test_request.py::TestLegacyRequest::test_client_addr_no_xff_no_remote_addr",
"tests/test_request.py::TestLegacyRequest::test_host_port_w_http_host_and_no_port",
"tests/test_request.py::TestLegacyRequest::test_host_port_w_http_host_and_standard_port",
"tests/test_request.py::TestLegacyRequest::test_host_port_w_http_host_and_oddball_port",
"tests/test_request.py::TestLegacyRequest::test_host_port_w_http_host_https_and_no_port",
"tests/test_request.py::TestLegacyRequest::test_host_port_w_http_host_https_and_standard_port",
"tests/test_request.py::TestLegacyRequest::test_host_port_w_http_host_https_and_oddball_port",
"tests/test_request.py::TestLegacyRequest::test_host_port_wo_http_host",
"tests/test_request.py::TestLegacyRequest::test_host_url_w_http_host_and_no_port",
"tests/test_request.py::TestLegacyRequest::test_host_url_w_http_host_and_standard_port",
"tests/test_request.py::TestLegacyRequest::test_host_url_w_http_host_and_oddball_port",
"tests/test_request.py::TestLegacyRequest::test_host_url_w_http_host_https_and_no_port",
"tests/test_request.py::TestLegacyRequest::test_host_url_w_http_host_https_and_standard_port",
"tests/test_request.py::TestLegacyRequest::test_host_url_w_http_host_https_and_oddball_port",
"tests/test_request.py::TestLegacyRequest::test_host_url_wo_http_host",
"tests/test_request.py::TestLegacyRequest::test_application_url",
"tests/test_request.py::TestLegacyRequest::test_path_url",
"tests/test_request.py::TestLegacyRequest::test_path",
"tests/test_request.py::TestLegacyRequest::test_path_qs_no_qs",
"tests/test_request.py::TestLegacyRequest::test_path_qs_w_qs",
"tests/test_request.py::TestLegacyRequest::test_url_no_qs",
"tests/test_request.py::TestLegacyRequest::test_url_w_qs",
"tests/test_request.py::TestLegacyRequest::test_relative_url_to_app_true_wo_leading_slash",
"tests/test_request.py::TestLegacyRequest::test_relative_url_to_app_true_w_leading_slash",
"tests/test_request.py::TestLegacyRequest::test_relative_url_to_app_false_other_w_leading_slash",
"tests/test_request.py::TestLegacyRequest::test_relative_url_to_app_false_other_wo_leading_slash",
"tests/test_request.py::TestLegacyRequest::test_path_info_pop_empty",
"tests/test_request.py::TestLegacyRequest::test_path_info_pop_just_leading_slash",
"tests/test_request.py::TestLegacyRequest::test_path_info_pop_non_empty_no_pattern",
"tests/test_request.py::TestLegacyRequest::test_path_info_pop_non_empty_w_pattern_miss",
"tests/test_request.py::TestLegacyRequest::test_path_info_pop_non_empty_w_pattern_hit",
"tests/test_request.py::TestLegacyRequest::test_path_info_pop_skips_empty_elements",
"tests/test_request.py::TestLegacyRequest::test_path_info_peek_empty",
"tests/test_request.py::TestLegacyRequest::test_path_info_peek_just_leading_slash",
"tests/test_request.py::TestLegacyRequest::test_path_info_peek_non_empty",
"tests/test_request.py::TestLegacyRequest::test_is_xhr_no_header",
"tests/test_request.py::TestLegacyRequest::test_is_xhr_header_miss",
"tests/test_request.py::TestLegacyRequest::test_is_xhr_header_hit",
"tests/test_request.py::TestLegacyRequest::test_host_getter_w_HTTP_HOST",
"tests/test_request.py::TestLegacyRequest::test_host_getter_wo_HTTP_HOST",
"tests/test_request.py::TestLegacyRequest::test_host_setter",
"tests/test_request.py::TestLegacyRequest::test_host_deleter_hit",
"tests/test_request.py::TestLegacyRequest::test_host_deleter_miss",
"tests/test_request.py::TestLegacyRequest::test_encget_raises_without_default",
"tests/test_request.py::TestLegacyRequest::test_encget_doesnt_raises_with_default",
"tests/test_request.py::TestLegacyRequest::test_encget_with_encattr",
"tests/test_request.py::TestLegacyRequest::test_encget_no_encattr",
"tests/test_request.py::TestLegacyRequest::test_relative_url",
"tests/test_request.py::TestLegacyRequest::test_header_getter",
"tests/test_request.py::TestLegacyRequest::test_json_body",
"tests/test_request.py::TestLegacyRequest::test_host_get_w_http_host",
"tests/test_request.py::TestLegacyRequest::test_host_get_w_no_http_host",
"tests/test_request.py::TestRequestConstructorWarnings::test_ctor_w_unicode_errors",
"tests/test_request.py::TestRequestConstructorWarnings::test_ctor_w_decode_param_names",
"tests/test_request.py::TestRequestWithAdhocAttr::test_adhoc_attrs_set",
"tests/test_request.py::TestRequestWithAdhocAttr::test_adhoc_attrs_set_nonadhoc",
"tests/test_request.py::TestRequestWithAdhocAttr::test_adhoc_attrs_get",
"tests/test_request.py::TestRequestWithAdhocAttr::test_adhoc_attrs_get_missing",
"tests/test_request.py::TestRequestWithAdhocAttr::test_adhoc_attrs_del",
"tests/test_request.py::TestRequestWithAdhocAttr::test_adhoc_attrs_del_missing",
"tests/test_request.py::TestRequest_functional::test_gets",
"tests/test_request.py::TestRequest_functional::test_gets_with_query_string",
"tests/test_request.py::TestRequest_functional::test_language_parsing1",
"tests/test_request.py::TestRequest_functional::test_language_parsing2",
"tests/test_request.py::TestRequest_functional::test_language_parsing3",
"tests/test_request.py::TestRequest_functional::test_mime_parsing1",
"tests/test_request.py::TestRequest_functional::test_mime_parsing2",
"tests/test_request.py::TestRequest_functional::test_mime_parsing3",
"tests/test_request.py::TestRequest_functional::test_accept_best_match",
"tests/test_request.py::TestRequest_functional::test_from_mimeparse",
"tests/test_request.py::TestRequest_functional::test_headers",
"tests/test_request.py::TestRequest_functional::test_bad_cookie",
"tests/test_request.py::TestRequest_functional::test_cookie_quoting",
"tests/test_request.py::TestRequest_functional::test_path_quoting_pct_encodes",
"tests/test_request.py::TestRequest_functional::test_params",
"tests/test_request.py::TestRequest_functional::test_copy_body",
"tests/test_request.py::TestRequest_functional::test_already_consumed_stream",
"tests/test_request.py::TestRequest_functional::test_broken_seek",
"tests/test_request.py::TestRequest_functional::test_set_body",
"tests/test_request.py::TestRequest_functional::test_broken_clen_header",
"tests/test_request.py::TestRequest_functional::test_nonstr_keys",
"tests/test_request.py::TestRequest_functional::test_authorization",
"tests/test_request.py::TestRequest_functional::test_as_bytes",
"tests/test_request.py::TestRequest_functional::test_as_text",
"tests/test_request.py::TestRequest_functional::test_req_kw_none_val",
"tests/test_request.py::TestRequest_functional::test_env_keys",
"tests/test_request.py::TestRequest_functional::test_repr_nodefault",
"tests/test_request.py::TestRequest_functional::test_request_noenviron_param",
"tests/test_request.py::TestRequest_functional::test_unexpected_kw",
"tests/test_request.py::TestRequest_functional::test_conttype_set_del",
"tests/test_request.py::TestRequest_functional::test_headers2",
"tests/test_request.py::TestRequest_functional::test_host_url",
"tests/test_request.py::TestRequest_functional::test_path_info_p",
"tests/test_request.py::TestRequest_functional::test_urlvars_property",
"tests/test_request.py::TestRequest_functional::test_urlargs_property",
"tests/test_request.py::TestRequest_functional::test_host_property",
"tests/test_request.py::TestRequest_functional::test_body_property",
"tests/test_request.py::TestRequest_functional::test_repr_invalid",
"tests/test_request.py::TestRequest_functional::test_from_garbage_file",
"tests/test_request.py::TestRequest_functional::test_from_file_patch",
"tests/test_request.py::TestRequest_functional::test_from_bytes",
"tests/test_request.py::TestRequest_functional::test_from_text",
"tests/test_request.py::TestRequest_functional::test_blank",
"tests/test_request.py::TestRequest_functional::test_post_does_not_reparse",
"tests/test_request.py::TestRequest_functional::test_middleware_body",
"tests/test_request.py::TestRequest_functional::test_body_file_noseek",
"tests/test_request.py::TestRequest_functional::test_cgi_escaping_fix",
"tests/test_request.py::TestRequest_functional::test_content_type_none",
"tests/test_request.py::TestRequest_functional::test_body_file_seekable",
"tests/test_request.py::TestRequest_functional::test_request_init",
"tests/test_request.py::TestRequest_functional::test_request_query_and_POST_vars",
"tests/test_request.py::TestRequest_functional::test_request_put",
"tests/test_request.py::TestRequest_functional::test_request_patch",
"tests/test_request.py::TestRequest_functional::test_call_WSGI_app",
"tests/test_request.py::TestRequest_functional::test_call_WSGI_app_204",
"tests/test_request.py::TestRequest_functional::test_call_WSGI_app_no_content_type",
"tests/test_request.py::TestRequest_functional::test_get_response_catch_exc_info_true",
"tests/test_request.py::TestFakeCGIBody::test_encode_multipart_value_type_options",
"tests/test_request.py::TestFakeCGIBody::test_encode_multipart_no_boundary",
"tests/test_request.py::TestFakeCGIBody::test_repr",
"tests/test_request.py::TestFakeCGIBody::test_fileno",
"tests/test_request.py::TestFakeCGIBody::test_iter",
"tests/test_request.py::TestFakeCGIBody::test_readline",
"tests/test_request.py::TestFakeCGIBody::test_read_bad_content_type",
"tests/test_request.py::TestFakeCGIBody::test_read_urlencoded",
"tests/test_request.py::TestFakeCGIBody::test_readable",
"tests/test_request.py::Test_cgi_FieldStorage__repr__patch::test_with_file",
"tests/test_request.py::Test_cgi_FieldStorage__repr__patch::test_without_file",
"tests/test_request.py::TestLimitedLengthFile::test_fileno",
"tests/test_request.py::Test_environ_from_url::test_environ_from_url",
"tests/test_request.py::Test_environ_from_url::test_environ_from_url_highorder_path_info",
"tests/test_request.py::Test_environ_from_url::test_fileupload_mime_type_detection",
"tests/test_request.py::TestRequestMultipart::test_multipart_with_charset"
] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2016-11-16T20:39:37Z" | mit |
|
Pylons__webob-306 | diff --git a/.travis.yml b/.travis.yml
index 7037c57..895d219 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -12,7 +12,7 @@ matrix:
env: TOXENV=py34
- python: 3.5
env: TOXENV=py35
- - python: 3.6-dev
+ - python: 3.6
env: TOXENV=py36
- python: nightly
env: TOXENV=py37
@@ -21,7 +21,6 @@ matrix:
- python: 3.5
env: TOXENV=py2-cover,py3-cover,coverage
allow_failures:
- - env: TOXENV=py36
- env: TOXENV=py37
install:
diff --git a/CHANGES.txt b/CHANGES.txt
index 393cd8d..2105fe8 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -1,4 +1,13 @@
Unreleased
----------
+Bugfix
+~~~~~~
+- ``Response.__init__`` would discard ``app_iter`` when a ``Response`` had no
+ body, this would cause issues when ``app_iter`` was an object that was tied
+ to the life-cycle of a web application and had to be properly closed.
+ ``app_iter`` is more advanced API for ``Response`` and thus even if it
+ contains a body and is thus against the HTTP RFC's, we should let the users
+ shoot themselves by returning a body. See
+ https://github.com/Pylons/webob/issues/305
diff --git a/setup.py b/setup.py
index a1418c5..d74f25e 100644
--- a/setup.py
+++ b/setup.py
@@ -38,6 +38,7 @@ setup(
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
+ "Programming Language :: Python :: 3.6",
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: Python :: Implementation :: PyPy",
],
diff --git a/webob/response.py b/webob/response.py
index 899fc99..cd376b9 100644
--- a/webob/response.py
+++ b/webob/response.py
@@ -320,7 +320,7 @@ class Response(object):
if k.lower() != 'content-length'
]
self._headerlist.append(('Content-Length', str(len(body))))
- elif app_iter is None or not code_has_body:
+ elif app_iter is None and not code_has_body:
app_iter = [b'']
self._app_iter = app_iter
| Pylons/webob | 1ac5148d680a020f3a05138ef0c1a5f529c49ed5 | diff --git a/tests/test_response.py b/tests/test_response.py
index 1d272c6..8e9b3ae 100644
--- a/tests/test_response.py
+++ b/tests/test_response.py
@@ -1316,7 +1316,9 @@ def test_204_has_no_body():
def test_204_app_iter_set():
res = Response(status='204', app_iter=[b'test'])
- assert res.body == b''
+
+ # You are on your own in this case... you set app_iter you bought it
+ assert res.body == b'test'
assert res.content_length is None
assert res.headerlist == []
@@ -1353,3 +1355,13 @@ def test_content_type_has_charset():
assert res.content_type == 'application/foo'
assert res.charset == 'UTF-8'
assert res.headers['Content-Type'] == 'application/foo; charset=UTF-8'
+
+def test_app_iter_is_same():
+ class app_iter(object):
+ pass
+
+ my_app_iter = app_iter()
+
+ res = Response(status=204, app_iter=my_app_iter)
+ assert res.app_iter == my_app_iter
+ assert isinstance(res.app_iter, app_iter)
| Seems WebOb 1.7 has some glitches with WebTest when a 204 is responded
The recent WebOb 1.7 changes to initialisation function seem to had introduced a side effect when WebTest is used, as webtest will recreate a new `Response` object from the application response.
A simple testcase can be created to showcase the issue:
```
from webob import Response
def wsgi_app(environ, start_response):
resp = Response(status='204 No Content', body=b'')
resp.content_type = None
return resp(environ, start_response)
```
The snippet is meant to work on both 1.6 and 1.7, so it adds some unnecessary values like `body` and `content_type` which are already provided in 1.7 (those values are in fact a nop on 1.7) while they are required on 1.6 to generate a response without content.
The response is as expected both on 1.6 and 1.7
```
Response: 204 No Content
```
Creating a plain webtest `TestApp` from the previous example:
```
from webtest import TestApp
app = TestApp(wsgi_app)
app.get('/')
```
will issue a validation error on WebOb 1.7:
```
Iterator garbage collected without being closedException AssertionError: AssertionError('Iterator garbage collected without being closed',) in <bound method IteratorWrapper.__del__ of <webtest.lint.IteratorWrapper object at 0x100ed0850>> ignored
```
while it will work without the error with WebOb 1.6.
This seems to be related to https://github.com/Pylons/webob/commit/35fd5854b4b706adafa4caab43b6bcdcf3e6a934 as https://github.com/Pylons/webob/blob/master/webob/response.py#L323 throws away the webtest `IteratorWrapper` injected by WebTest replacing it with `[b'']` as `code_has_body` is False and thus breaking `WebTest`
I wouldn't take for granted that if there is an `app_iter` it will be wrong and needs to be discarded as response has no content. It's probably a right assumption in the case of `body`, but discarding `app_iter` might in fact break some application by discarding an iterator which returns an empty response too but has other side effects. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_response.py::test_204_app_iter_set",
"tests/test_response.py::test_app_iter_is_same"
] | [
"tests/test_response.py::test_response",
"tests/test_response.py::test_set_response_status_binary",
"tests/test_response.py::test_set_response_status_str_no_reason",
"tests/test_response.py::test_set_response_status_str_generic_reason",
"tests/test_response.py::test_set_response_status_code",
"tests/test_response.py::test_set_response_status_bad",
"tests/test_response.py::test_set_response_status_code_generic_reason",
"tests/test_response.py::test_content_type",
"tests/test_response.py::test_init_content_type_w_charset",
"tests/test_response.py::test_init_adds_default_charset_when_not_json",
"tests/test_response.py::test_init_no_charset_when_json",
"tests/test_response.py::test_init_keeps_specified_charset_when_json",
"tests/test_response.py::test_init_doesnt_add_default_content_type_with_bodyless_status",
"tests/test_response.py::test_cookies",
"tests/test_response.py::test_unicode_cookies_error_raised",
"tests/test_response.py::test_unicode_cookies_warning_issued",
"tests/test_response.py::test_cookies_raises_typeerror",
"tests/test_response.py::test_http_only_cookie",
"tests/test_response.py::test_headers",
"tests/test_response.py::test_response_copy",
"tests/test_response.py::test_response_copy_content_md5",
"tests/test_response.py::test_HEAD_closes",
"tests/test_response.py::test_HEAD_conditional_response_returns_empty_response",
"tests/test_response.py::test_HEAD_conditional_response_range_empty_response",
"tests/test_response.py::test_conditional_response_if_none_match_false",
"tests/test_response.py::test_conditional_response_if_none_match_true",
"tests/test_response.py::test_conditional_response_if_none_match_weak",
"tests/test_response.py::test_conditional_response_if_modified_since_false",
"tests/test_response.py::test_conditional_response_if_modified_since_true",
"tests/test_response.py::test_conditional_response_range_not_satisfiable_response",
"tests/test_response.py::test_HEAD_conditional_response_range_not_satisfiable_response",
"tests/test_response.py::test_md5_etag",
"tests/test_response.py::test_md5_etag_set_content_md5",
"tests/test_response.py::test_decode_content_defaults_to_identity",
"tests/test_response.py::test_decode_content_with_deflate",
"tests/test_response.py::test_content_length",
"tests/test_response.py::test_app_iter_range",
"tests/test_response.py::test_app_iter_range_inner_method",
"tests/test_response.py::test_has_body",
"tests/test_response.py::test_str_crlf",
"tests/test_response.py::test_from_file",
"tests/test_response.py::test_from_file2",
"tests/test_response.py::test_from_text_file",
"tests/test_response.py::test_from_file_w_leading_space_in_header",
"tests/test_response.py::test_file_bad_header",
"tests/test_response.py::test_from_file_not_unicode_headers",
"tests/test_response.py::test_file_with_http_version",
"tests/test_response.py::test_file_with_http_version_more_status",
"tests/test_response.py::test_set_status",
"tests/test_response.py::test_set_headerlist",
"tests/test_response.py::test_request_uri_no_script_name",
"tests/test_response.py::test_request_uri_https",
"tests/test_response.py::test_app_iter_range_starts_after_iter_end",
"tests/test_response.py::test_resp_write_app_iter_non_list",
"tests/test_response.py::test_response_file_body_writelines",
"tests/test_response.py::test_response_file_body_tell_text",
"tests/test_response.py::test_response_write_non_str",
"tests/test_response.py::test_response_file_body_write_empty_app_iter",
"tests/test_response.py::test_response_file_body_write_empty_body",
"tests/test_response.py::test_response_file_body_close_not_implemented",
"tests/test_response.py::test_response_file_body_repr",
"tests/test_response.py::test_body_get_is_none",
"tests/test_response.py::test_body_get_is_unicode_notverylong",
"tests/test_response.py::test_body_get_is_unicode",
"tests/test_response.py::test_body_set_not_unicode_or_str",
"tests/test_response.py::test_body_set_unicode",
"tests/test_response.py::test_body_set_under_body_doesnt_exist",
"tests/test_response.py::test_body_del",
"tests/test_response.py::test_text_get_no_charset",
"tests/test_response.py::test_text_get_no_default_body_encoding",
"tests/test_response.py::test_unicode_body",
"tests/test_response.py::test_text_get_decode",
"tests/test_response.py::test_text_set_no_charset",
"tests/test_response.py::test_text_set_no_default_body_encoding",
"tests/test_response.py::test_text_set_not_unicode",
"tests/test_response.py::test_text_del",
"tests/test_response.py::test_body_file_del",
"tests/test_response.py::test_write_unicode",
"tests/test_response.py::test_write_unicode_no_charset",
"tests/test_response.py::test_write_text",
"tests/test_response.py::test_app_iter_del",
"tests/test_response.py::test_charset_set_no_content_type_header",
"tests/test_response.py::test_charset_del_no_content_type_header",
"tests/test_response.py::test_content_type_params_get_no_semicolon_in_content_type_header",
"tests/test_response.py::test_content_type_params_get_semicolon_in_content_type_header",
"tests/test_response.py::test_content_type_params_set_value_dict_empty",
"tests/test_response.py::test_content_type_params_set_ok_param_quoting",
"tests/test_response.py::test_charset_delete",
"tests/test_response.py::test_set_cookie_overwrite",
"tests/test_response.py::test_set_cookie_value_is_None",
"tests/test_response.py::test_set_cookie_expires_is_None_and_max_age_is_int",
"tests/test_response.py::test_set_cookie_expires_is_None_and_max_age_is_timedelta",
"tests/test_response.py::test_set_cookie_expires_is_datetime_and_max_age_is_None",
"tests/test_response.py::test_set_cookie_expires_is_timedelta_and_max_age_is_None",
"tests/test_response.py::test_set_cookie_expires_is_datetime_tz_and_max_age_is_None",
"tests/test_response.py::test_delete_cookie",
"tests/test_response.py::test_delete_cookie_with_path",
"tests/test_response.py::test_delete_cookie_with_domain",
"tests/test_response.py::test_unset_cookie_not_existing_and_not_strict",
"tests/test_response.py::test_unset_cookie_not_existing_and_strict",
"tests/test_response.py::test_unset_cookie_key_in_cookies",
"tests/test_response.py::test_merge_cookies_no_set_cookie",
"tests/test_response.py::test_merge_cookies_resp_is_Response",
"tests/test_response.py::test_merge_cookies_resp_is_wsgi_callable",
"tests/test_response.py::test_body_get_body_is_None_len_app_iter_is_zero",
"tests/test_response.py::test_cache_control_get",
"tests/test_response.py::test_location",
"tests/test_response.py::test_location_unicode",
"tests/test_response.py::test_request_uri_http",
"tests/test_response.py::test_request_uri_no_script_name2",
"tests/test_response.py::test_cache_control_object_max_age_ten",
"tests/test_response.py::test_cache_control_set_object_error",
"tests/test_response.py::test_cache_expires_set",
"tests/test_response.py::test_status_code_set",
"tests/test_response.py::test_cache_control_set_dict",
"tests/test_response.py::test_cache_control_set_None",
"tests/test_response.py::test_cache_control_set_unicode",
"tests/test_response.py::test_cache_control_set_control_obj_is_not_None",
"tests/test_response.py::test_cache_control_del",
"tests/test_response.py::test_body_file_get",
"tests/test_response.py::test_body_file_write_no_charset",
"tests/test_response.py::test_body_file_write_unicode_encodes",
"tests/test_response.py::test_repr",
"tests/test_response.py::test_cache_expires_set_timedelta",
"tests/test_response.py::test_cache_expires_set_int",
"tests/test_response.py::test_cache_expires_set_None",
"tests/test_response.py::test_cache_expires_set_zero",
"tests/test_response.py::test_encode_content_unknown",
"tests/test_response.py::test_encode_content_identity",
"tests/test_response.py::test_encode_content_gzip_already_gzipped",
"tests/test_response.py::test_encode_content_gzip_notyet_gzipped",
"tests/test_response.py::test_encode_content_gzip_notyet_gzipped_lazy",
"tests/test_response.py::test_encode_content_gzip_buffer_coverage",
"tests/test_response.py::test_decode_content_identity",
"tests/test_response.py::test_decode_content_weird",
"tests/test_response.py::test_decode_content_gzip",
"tests/test_response.py::test__make_location_absolute_has_scheme_only",
"tests/test_response.py::test__make_location_absolute_path",
"tests/test_response.py::test__make_location_absolute_already_absolute",
"tests/test_response.py::test_response_set_body_file1",
"tests/test_response.py::test_response_set_body_file2",
"tests/test_response.py::test_response_json_body",
"tests/test_response.py::test_cache_expires_set_zero_then_nonzero",
"tests/test_response.py::test_default_content_type",
"tests/test_response.py::test_default_charset",
"tests/test_response.py::test_header_list_no_defaults",
"tests/test_response.py::test_204_has_no_body",
"tests/test_response.py::test_explicit_charset",
"tests/test_response.py::test_set_content_type",
"tests/test_response.py::test_raises_no_charset",
"tests/test_response.py::test_raises_none_charset",
"tests/test_response.py::test_doesnt_raise_with_charset_content_type_has_no_charset",
"tests/test_response.py::test_content_type_has_charset"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2017-01-17T06:40:34Z" | mit |
|
Pylons__webob-309 | diff --git a/docs/do-it-yourself.txt b/docs/do-it-yourself.txt
index 3b65c7d..e88bbab 100644
--- a/docs/do-it-yourself.txt
+++ b/docs/do-it-yourself.txt
@@ -295,7 +295,7 @@ To do that we'll write a `decorator <http://www.ddj.com/web-development/18440607
**line 6**: Here we catch any ``webob.exc.HTTPException`` exceptions. This is so you can do ``raise webob.exc.HTTPNotFound()`` in your function. These exceptions are themselves WSGI applications.
-**line 7**: We call the function with the request object, any any variables in ``req.urlvars``. And we get back a response.
+**line 7**: We call the function with the request object, any variables in ``req.urlvars``. And we get back a response.
**line 10**: We'll allow the function to return a full response object, or just a string. If they return a string, we'll create a ``Response`` object with that (and with the standard ``200 OK`` status, ``text/html`` content type, and ``utf8`` charset/encoding).
diff --git a/webob/request.py b/webob/request.py
index 150dd37..923cce5 100644
--- a/webob/request.py
+++ b/webob/request.py
@@ -1629,8 +1629,9 @@ def _encode_multipart(vars, content_type, fout=None):
w(b'--')
wt(boundary)
w(CRLF)
- assert name is not None, 'Value associated with no name: %r' % value
- wt('Content-Disposition: form-data; name="%s"' % name)
+ wt('Content-Disposition: form-data')
+ if name is not None:
+ wt('; name="%s"' % name)
filename = None
if getattr(value, 'filename', None):
filename = value.filename
@@ -1708,7 +1709,10 @@ class Transcoder(object):
# transcode FieldStorage
if PY2:
def decode(b):
- return b.decode(self.charset, self.errors)
+ if b is not None:
+ return b.decode(self.charset, self.errors)
+ else:
+ return b
else:
def decode(b):
return b
| Pylons/webob | 8669fe335b54697f23a787f67da19552bc03d5c6 | diff --git a/tests/test_request.py b/tests/test_request.py
index de3b149..357a724 100644
--- a/tests/test_request.py
+++ b/tests/test_request.py
@@ -2618,6 +2618,20 @@ class TestRequest_functional(object):
req2 = req2.decode('latin-1')
assert body == req2.body
+ def test_none_field_name(self):
+ from webob.request import Request
+ body = b'--FOO\r\nContent-Disposition: form-data\r\n\r\n123\r\n--FOO--'
+ content_type = 'multipart/form-data; boundary=FOO'
+ environ = {
+ 'wsgi.input': BytesIO(body),
+ 'CONTENT_TYPE': content_type,
+ 'CONTENT_LENGTH': len(body),
+ 'REQUEST_METHOD': 'POST'
+ }
+ req = Request(environ)
+ req = req.decode('latin-1')
+ assert body == req.body
+
def test_broken_seek(self):
# copy() should work even when the input has a broken seek method
req = self._blankOne('/', method='POST',
| multipart field names may be None
I'm getting this stack trace.
```
Traceback (most recent call last):
File "/home/bukzor/my/wsgi/app.py", line 11, in handler
request = new_request(environ).decode('latin1')
File "/usr/lib/pymodules/python2.6/webob/request.py", line 243, in decode
fout = t.transcode_fs(fs, r._content_type_raw)
File "/usr/lib/pymodules/python2.6/webob/request.py", line 1699, in transcode_fs
field.name = decode(field.name)
File "/usr/lib/pymodules/python2.6/webob/request.py", line 1696, in <lambda>
decode = lambda b: b.decode(self.charset, self.errors)
AttributeError: 'NoneType' object has no attribute 'decode'
```
The docstring for fieldStorage notes that "None can occur as a field name". webob should allow for this.
You can use this little client to reproduce the issue:
``` python
#!/usr/bin/env python [0/1878]
import socket
HOST = 'www.buck.dev.yelp.com'
PATH = '/lil_brudder'
PORT = 80
body = '''\
--FOO
123
--FOO--'''
req = '''\
POST %s HTTP/1.0
Host: %s
Content-Length: %s
Content-Type: multipart/form-data; boundary=FOO
%s
''' % (PATH, HOST, len(body), body)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((HOST, PORT))
sock.send(req)
sock.close()
```
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_request.py::TestRequest_functional::test_none_field_name"
] | [
"tests/test_request.py::TestRequestCommon::test_ctor_environ_getter_raises_WTF",
"tests/test_request.py::TestRequestCommon::test_ctor_wo_environ_raises_WTF",
"tests/test_request.py::TestRequestCommon::test_ctor_w_environ",
"tests/test_request.py::TestRequestCommon::test_ctor_w_non_utf8_charset",
"tests/test_request.py::TestRequestCommon::test_scheme",
"tests/test_request.py::TestRequestCommon::test_body_file_getter",
"tests/test_request.py::TestRequestCommon::test_body_file_getter_seekable",
"tests/test_request.py::TestRequestCommon::test_body_file_getter_cache",
"tests/test_request.py::TestRequestCommon::test_body_file_getter_unreadable",
"tests/test_request.py::TestRequestCommon::test_body_file_setter_w_bytes",
"tests/test_request.py::TestRequestCommon::test_body_file_setter_non_bytes",
"tests/test_request.py::TestRequestCommon::test_body_file_deleter",
"tests/test_request.py::TestRequestCommon::test_body_file_raw",
"tests/test_request.py::TestRequestCommon::test_body_file_seekable_input_not_seekable",
"tests/test_request.py::TestRequestCommon::test_body_file_seekable_input_is_seekable",
"tests/test_request.py::TestRequestCommon::test_urlvars_getter_w_paste_key",
"tests/test_request.py::TestRequestCommon::test_urlvars_getter_w_wsgiorg_key",
"tests/test_request.py::TestRequestCommon::test_urlvars_getter_wo_keys",
"tests/test_request.py::TestRequestCommon::test_urlvars_setter_w_paste_key",
"tests/test_request.py::TestRequestCommon::test_urlvars_setter_w_wsgiorg_key",
"tests/test_request.py::TestRequestCommon::test_urlvars_setter_wo_keys",
"tests/test_request.py::TestRequestCommon::test_urlvars_deleter_w_paste_key",
"tests/test_request.py::TestRequestCommon::test_urlvars_deleter_w_wsgiorg_key_non_empty_tuple",
"tests/test_request.py::TestRequestCommon::test_urlvars_deleter_w_wsgiorg_key_empty_tuple",
"tests/test_request.py::TestRequestCommon::test_urlvars_deleter_wo_keys",
"tests/test_request.py::TestRequestCommon::test_urlargs_getter_w_paste_key",
"tests/test_request.py::TestRequestCommon::test_urlargs_getter_w_wsgiorg_key",
"tests/test_request.py::TestRequestCommon::test_urlargs_getter_wo_keys",
"tests/test_request.py::TestRequestCommon::test_urlargs_setter_w_paste_key",
"tests/test_request.py::TestRequestCommon::test_urlargs_setter_w_wsgiorg_key",
"tests/test_request.py::TestRequestCommon::test_urlargs_setter_wo_keys",
"tests/test_request.py::TestRequestCommon::test_urlargs_deleter_w_wsgiorg_key",
"tests/test_request.py::TestRequestCommon::test_urlargs_deleter_w_wsgiorg_key_empty",
"tests/test_request.py::TestRequestCommon::test_urlargs_deleter_wo_keys",
"tests/test_request.py::TestRequestCommon::test_cookies_empty_environ",
"tests/test_request.py::TestRequestCommon::test_cookies_is_mutable",
"tests/test_request.py::TestRequestCommon::test_cookies_w_webob_parsed_cookies_matching_source",
"tests/test_request.py::TestRequestCommon::test_cookies_w_webob_parsed_cookies_mismatched_source",
"tests/test_request.py::TestRequestCommon::test_set_cookies",
"tests/test_request.py::TestRequestCommon::test_body_getter",
"tests/test_request.py::TestRequestCommon::test_body_setter_None",
"tests/test_request.py::TestRequestCommon::test_body_setter_non_string_raises",
"tests/test_request.py::TestRequestCommon::test_body_setter_value",
"tests/test_request.py::TestRequestCommon::test_body_deleter_None",
"tests/test_request.py::TestRequestCommon::test_json_body",
"tests/test_request.py::TestRequestCommon::test_json_body_array",
"tests/test_request.py::TestRequestCommon::test_text_body",
"tests/test_request.py::TestRequestCommon::test__text_get_without_charset",
"tests/test_request.py::TestRequestCommon::test__text_set_without_charset",
"tests/test_request.py::TestRequestCommon::test_POST_not_POST_or_PUT",
"tests/test_request.py::TestRequestCommon::test_POST_existing_cache_hit",
"tests/test_request.py::TestRequestCommon::test_PUT_missing_content_type",
"tests/test_request.py::TestRequestCommon::test_PATCH_missing_content_type",
"tests/test_request.py::TestRequestCommon::test_POST_missing_content_type",
"tests/test_request.py::TestRequestCommon::test_POST_json_no_content_type",
"tests/test_request.py::TestRequestCommon::test_PUT_bad_content_type",
"tests/test_request.py::TestRequestCommon::test_POST_multipart",
"tests/test_request.py::TestRequestCommon::test_GET_reflects_query_string",
"tests/test_request.py::TestRequestCommon::test_GET_updates_query_string",
"tests/test_request.py::TestRequestCommon::test_cookies_wo_webob_parsed_cookies",
"tests/test_request.py::TestRequestCommon::test_copy_get",
"tests/test_request.py::TestRequestCommon::test_remove_conditional_headers_accept_encoding",
"tests/test_request.py::TestRequestCommon::test_remove_conditional_headers_if_modified_since",
"tests/test_request.py::TestRequestCommon::test_remove_conditional_headers_if_none_match",
"tests/test_request.py::TestRequestCommon::test_remove_conditional_headers_if_range",
"tests/test_request.py::TestRequestCommon::test_remove_conditional_headers_range",
"tests/test_request.py::TestRequestCommon::test_is_body_readable_POST",
"tests/test_request.py::TestRequestCommon::test_is_body_readable_PATCH",
"tests/test_request.py::TestRequestCommon::test_is_body_readable_GET",
"tests/test_request.py::TestRequestCommon::test_is_body_readable_unknown_method_and_content_length",
"tests/test_request.py::TestRequestCommon::test_is_body_readable_special_flag",
"tests/test_request.py::TestRequestCommon::test_cache_control_reflects_environ",
"tests/test_request.py::TestRequestCommon::test_cache_control_updates_environ",
"tests/test_request.py::TestRequestCommon::test_cache_control_set_dict",
"tests/test_request.py::TestRequestCommon::test_cache_control_set_object",
"tests/test_request.py::TestRequestCommon::test_cache_control_gets_cached",
"tests/test_request.py::TestRequestCommon::test_call_application_calls_application",
"tests/test_request.py::TestRequestCommon::test_call_application_provides_write",
"tests/test_request.py::TestRequestCommon::test_call_application_closes_iterable_when_mixed_w_write_calls",
"tests/test_request.py::TestRequestCommon::test_call_application_raises_exc_info",
"tests/test_request.py::TestRequestCommon::test_call_application_returns_exc_info",
"tests/test_request.py::TestRequestCommon::test_blank__method_subtitution",
"tests/test_request.py::TestRequestCommon::test_blank__ctype_in_env",
"tests/test_request.py::TestRequestCommon::test_blank__ctype_in_headers",
"tests/test_request.py::TestRequestCommon::test_blank__ctype_as_kw",
"tests/test_request.py::TestRequestCommon::test_blank__str_post_data_for_unsupported_ctype",
"tests/test_request.py::TestRequestCommon::test_blank__post_urlencoded",
"tests/test_request.py::TestRequestCommon::test_blank__post_multipart",
"tests/test_request.py::TestRequestCommon::test_blank__post_files",
"tests/test_request.py::TestRequestCommon::test_blank__post_file_w_wrong_ctype",
"tests/test_request.py::TestRequestCommon::test_from_bytes_extra_data",
"tests/test_request.py::TestRequestCommon::test_as_bytes_skip_body",
"tests/test_request.py::TestBaseRequest::test_method",
"tests/test_request.py::TestBaseRequest::test_http_version",
"tests/test_request.py::TestBaseRequest::test_script_name",
"tests/test_request.py::TestBaseRequest::test_path_info",
"tests/test_request.py::TestBaseRequest::test_content_length_getter",
"tests/test_request.py::TestBaseRequest::test_content_length_setter_w_str",
"tests/test_request.py::TestBaseRequest::test_remote_user",
"tests/test_request.py::TestBaseRequest::test_remote_addr",
"tests/test_request.py::TestBaseRequest::test_query_string",
"tests/test_request.py::TestBaseRequest::test_server_name",
"tests/test_request.py::TestBaseRequest::test_server_port_getter",
"tests/test_request.py::TestBaseRequest::test_server_port_setter_with_string",
"tests/test_request.py::TestBaseRequest::test_uscript_name",
"tests/test_request.py::TestBaseRequest::test_upath_info",
"tests/test_request.py::TestBaseRequest::test_upath_info_set_unicode",
"tests/test_request.py::TestBaseRequest::test_content_type_getter_no_parameters",
"tests/test_request.py::TestBaseRequest::test_content_type_getter_w_parameters",
"tests/test_request.py::TestBaseRequest::test_content_type_setter_w_None",
"tests/test_request.py::TestBaseRequest::test_content_type_setter_existing_paramter_no_new_paramter",
"tests/test_request.py::TestBaseRequest::test_content_type_deleter_clears_environ_value",
"tests/test_request.py::TestBaseRequest::test_content_type_deleter_no_environ_value",
"tests/test_request.py::TestBaseRequest::test_headers_getter",
"tests/test_request.py::TestBaseRequest::test_headers_setter",
"tests/test_request.py::TestBaseRequest::test_no_headers_deleter",
"tests/test_request.py::TestBaseRequest::test_client_addr_xff_singleval",
"tests/test_request.py::TestBaseRequest::test_client_addr_xff_multival",
"tests/test_request.py::TestBaseRequest::test_client_addr_prefers_xff",
"tests/test_request.py::TestBaseRequest::test_client_addr_no_xff",
"tests/test_request.py::TestBaseRequest::test_client_addr_no_xff_no_remote_addr",
"tests/test_request.py::TestBaseRequest::test_host_port_w_http_host_and_no_port",
"tests/test_request.py::TestBaseRequest::test_host_port_w_http_host_and_standard_port",
"tests/test_request.py::TestBaseRequest::test_host_port_w_http_host_and_oddball_port",
"tests/test_request.py::TestBaseRequest::test_host_port_w_http_host_https_and_no_port",
"tests/test_request.py::TestBaseRequest::test_host_port_w_http_host_https_and_standard_port",
"tests/test_request.py::TestBaseRequest::test_host_port_w_http_host_https_and_oddball_port",
"tests/test_request.py::TestBaseRequest::test_host_port_wo_http_host",
"tests/test_request.py::TestBaseRequest::test_host_url_w_http_host_and_no_port",
"tests/test_request.py::TestBaseRequest::test_host_url_w_http_host_and_standard_port",
"tests/test_request.py::TestBaseRequest::test_host_url_w_http_host_and_oddball_port",
"tests/test_request.py::TestBaseRequest::test_host_url_w_http_host_https_and_no_port",
"tests/test_request.py::TestBaseRequest::test_host_url_w_http_host_https_and_standard_port",
"tests/test_request.py::TestBaseRequest::test_host_url_w_http_host_https_and_oddball_port",
"tests/test_request.py::TestBaseRequest::test_host_url_wo_http_host",
"tests/test_request.py::TestBaseRequest::test_application_url",
"tests/test_request.py::TestBaseRequest::test_path_url",
"tests/test_request.py::TestBaseRequest::test_path",
"tests/test_request.py::TestBaseRequest::test_path_qs_no_qs",
"tests/test_request.py::TestBaseRequest::test_path_qs_w_qs",
"tests/test_request.py::TestBaseRequest::test_url_no_qs",
"tests/test_request.py::TestBaseRequest::test_url_w_qs",
"tests/test_request.py::TestBaseRequest::test_relative_url_to_app_true_wo_leading_slash",
"tests/test_request.py::TestBaseRequest::test_relative_url_to_app_true_w_leading_slash",
"tests/test_request.py::TestBaseRequest::test_relative_url_to_app_false_other_w_leading_slash",
"tests/test_request.py::TestBaseRequest::test_relative_url_to_app_false_other_wo_leading_slash",
"tests/test_request.py::TestBaseRequest::test_path_info_pop_empty",
"tests/test_request.py::TestBaseRequest::test_path_info_pop_just_leading_slash",
"tests/test_request.py::TestBaseRequest::test_path_info_pop_non_empty_no_pattern",
"tests/test_request.py::TestBaseRequest::test_path_info_pop_non_empty_w_pattern_miss",
"tests/test_request.py::TestBaseRequest::test_path_info_pop_non_empty_w_pattern_hit",
"tests/test_request.py::TestBaseRequest::test_path_info_pop_skips_empty_elements",
"tests/test_request.py::TestBaseRequest::test_path_info_peek_empty",
"tests/test_request.py::TestBaseRequest::test_path_info_peek_just_leading_slash",
"tests/test_request.py::TestBaseRequest::test_path_info_peek_non_empty",
"tests/test_request.py::TestBaseRequest::test_is_xhr_no_header",
"tests/test_request.py::TestBaseRequest::test_is_xhr_header_miss",
"tests/test_request.py::TestBaseRequest::test_is_xhr_header_hit",
"tests/test_request.py::TestBaseRequest::test_host_getter_w_HTTP_HOST",
"tests/test_request.py::TestBaseRequest::test_host_getter_wo_HTTP_HOST",
"tests/test_request.py::TestBaseRequest::test_host_setter",
"tests/test_request.py::TestBaseRequest::test_host_deleter_hit",
"tests/test_request.py::TestBaseRequest::test_host_deleter_miss",
"tests/test_request.py::TestBaseRequest::test_domain_nocolon",
"tests/test_request.py::TestBaseRequest::test_domain_withcolon",
"tests/test_request.py::TestBaseRequest::test_encget_raises_without_default",
"tests/test_request.py::TestBaseRequest::test_encget_doesnt_raises_with_default",
"tests/test_request.py::TestBaseRequest::test_encget_with_encattr",
"tests/test_request.py::TestBaseRequest::test_encget_with_encattr_latin_1",
"tests/test_request.py::TestBaseRequest::test_encget_no_encattr",
"tests/test_request.py::TestBaseRequest::test_relative_url",
"tests/test_request.py::TestBaseRequest::test_header_getter",
"tests/test_request.py::TestBaseRequest::test_json_body",
"tests/test_request.py::TestBaseRequest::test_host_get",
"tests/test_request.py::TestBaseRequest::test_host_get_w_no_http_host",
"tests/test_request.py::TestLegacyRequest::test_method",
"tests/test_request.py::TestLegacyRequest::test_http_version",
"tests/test_request.py::TestLegacyRequest::test_script_name",
"tests/test_request.py::TestLegacyRequest::test_path_info",
"tests/test_request.py::TestLegacyRequest::test_content_length_getter",
"tests/test_request.py::TestLegacyRequest::test_content_length_setter_w_str",
"tests/test_request.py::TestLegacyRequest::test_remote_user",
"tests/test_request.py::TestLegacyRequest::test_remote_addr",
"tests/test_request.py::TestLegacyRequest::test_query_string",
"tests/test_request.py::TestLegacyRequest::test_server_name",
"tests/test_request.py::TestLegacyRequest::test_server_port_getter",
"tests/test_request.py::TestLegacyRequest::test_server_port_setter_with_string",
"tests/test_request.py::TestLegacyRequest::test_uscript_name",
"tests/test_request.py::TestLegacyRequest::test_upath_info",
"tests/test_request.py::TestLegacyRequest::test_upath_info_set_unicode",
"tests/test_request.py::TestLegacyRequest::test_content_type_getter_no_parameters",
"tests/test_request.py::TestLegacyRequest::test_content_type_getter_w_parameters",
"tests/test_request.py::TestLegacyRequest::test_content_type_setter_w_None",
"tests/test_request.py::TestLegacyRequest::test_content_type_setter_existing_paramter_no_new_paramter",
"tests/test_request.py::TestLegacyRequest::test_content_type_deleter_clears_environ_value",
"tests/test_request.py::TestLegacyRequest::test_content_type_deleter_no_environ_value",
"tests/test_request.py::TestLegacyRequest::test_headers_getter",
"tests/test_request.py::TestLegacyRequest::test_headers_setter",
"tests/test_request.py::TestLegacyRequest::test_no_headers_deleter",
"tests/test_request.py::TestLegacyRequest::test_client_addr_xff_singleval",
"tests/test_request.py::TestLegacyRequest::test_client_addr_xff_multival",
"tests/test_request.py::TestLegacyRequest::test_client_addr_prefers_xff",
"tests/test_request.py::TestLegacyRequest::test_client_addr_no_xff",
"tests/test_request.py::TestLegacyRequest::test_client_addr_no_xff_no_remote_addr",
"tests/test_request.py::TestLegacyRequest::test_host_port_w_http_host_and_no_port",
"tests/test_request.py::TestLegacyRequest::test_host_port_w_http_host_and_standard_port",
"tests/test_request.py::TestLegacyRequest::test_host_port_w_http_host_and_oddball_port",
"tests/test_request.py::TestLegacyRequest::test_host_port_w_http_host_https_and_no_port",
"tests/test_request.py::TestLegacyRequest::test_host_port_w_http_host_https_and_standard_port",
"tests/test_request.py::TestLegacyRequest::test_host_port_w_http_host_https_and_oddball_port",
"tests/test_request.py::TestLegacyRequest::test_host_port_wo_http_host",
"tests/test_request.py::TestLegacyRequest::test_host_url_w_http_host_and_no_port",
"tests/test_request.py::TestLegacyRequest::test_host_url_w_http_host_and_standard_port",
"tests/test_request.py::TestLegacyRequest::test_host_url_w_http_host_and_oddball_port",
"tests/test_request.py::TestLegacyRequest::test_host_url_w_http_host_https_and_no_port",
"tests/test_request.py::TestLegacyRequest::test_host_url_w_http_host_https_and_standard_port",
"tests/test_request.py::TestLegacyRequest::test_host_url_w_http_host_https_and_oddball_port",
"tests/test_request.py::TestLegacyRequest::test_host_url_wo_http_host",
"tests/test_request.py::TestLegacyRequest::test_application_url",
"tests/test_request.py::TestLegacyRequest::test_path_url",
"tests/test_request.py::TestLegacyRequest::test_path",
"tests/test_request.py::TestLegacyRequest::test_path_qs_no_qs",
"tests/test_request.py::TestLegacyRequest::test_path_qs_w_qs",
"tests/test_request.py::TestLegacyRequest::test_url_no_qs",
"tests/test_request.py::TestLegacyRequest::test_url_w_qs",
"tests/test_request.py::TestLegacyRequest::test_relative_url_to_app_true_wo_leading_slash",
"tests/test_request.py::TestLegacyRequest::test_relative_url_to_app_true_w_leading_slash",
"tests/test_request.py::TestLegacyRequest::test_relative_url_to_app_false_other_w_leading_slash",
"tests/test_request.py::TestLegacyRequest::test_relative_url_to_app_false_other_wo_leading_slash",
"tests/test_request.py::TestLegacyRequest::test_path_info_pop_empty",
"tests/test_request.py::TestLegacyRequest::test_path_info_pop_just_leading_slash",
"tests/test_request.py::TestLegacyRequest::test_path_info_pop_non_empty_no_pattern",
"tests/test_request.py::TestLegacyRequest::test_path_info_pop_non_empty_w_pattern_miss",
"tests/test_request.py::TestLegacyRequest::test_path_info_pop_non_empty_w_pattern_hit",
"tests/test_request.py::TestLegacyRequest::test_path_info_pop_skips_empty_elements",
"tests/test_request.py::TestLegacyRequest::test_path_info_peek_empty",
"tests/test_request.py::TestLegacyRequest::test_path_info_peek_just_leading_slash",
"tests/test_request.py::TestLegacyRequest::test_path_info_peek_non_empty",
"tests/test_request.py::TestLegacyRequest::test_is_xhr_no_header",
"tests/test_request.py::TestLegacyRequest::test_is_xhr_header_miss",
"tests/test_request.py::TestLegacyRequest::test_is_xhr_header_hit",
"tests/test_request.py::TestLegacyRequest::test_host_getter_w_HTTP_HOST",
"tests/test_request.py::TestLegacyRequest::test_host_getter_wo_HTTP_HOST",
"tests/test_request.py::TestLegacyRequest::test_host_setter",
"tests/test_request.py::TestLegacyRequest::test_host_deleter_hit",
"tests/test_request.py::TestLegacyRequest::test_host_deleter_miss",
"tests/test_request.py::TestLegacyRequest::test_encget_raises_without_default",
"tests/test_request.py::TestLegacyRequest::test_encget_doesnt_raises_with_default",
"tests/test_request.py::TestLegacyRequest::test_encget_with_encattr",
"tests/test_request.py::TestLegacyRequest::test_encget_no_encattr",
"tests/test_request.py::TestLegacyRequest::test_relative_url",
"tests/test_request.py::TestLegacyRequest::test_header_getter",
"tests/test_request.py::TestLegacyRequest::test_json_body",
"tests/test_request.py::TestLegacyRequest::test_host_get_w_http_host",
"tests/test_request.py::TestLegacyRequest::test_host_get_w_no_http_host",
"tests/test_request.py::TestRequestConstructorWarnings::test_ctor_w_unicode_errors",
"tests/test_request.py::TestRequestConstructorWarnings::test_ctor_w_decode_param_names",
"tests/test_request.py::TestRequestWithAdhocAttr::test_adhoc_attrs_set",
"tests/test_request.py::TestRequestWithAdhocAttr::test_adhoc_attrs_set_nonadhoc",
"tests/test_request.py::TestRequestWithAdhocAttr::test_adhoc_attrs_get",
"tests/test_request.py::TestRequestWithAdhocAttr::test_adhoc_attrs_get_missing",
"tests/test_request.py::TestRequestWithAdhocAttr::test_adhoc_attrs_del",
"tests/test_request.py::TestRequestWithAdhocAttr::test_adhoc_attrs_del_missing",
"tests/test_request.py::TestRequest_functional::test_gets",
"tests/test_request.py::TestRequest_functional::test_gets_with_query_string",
"tests/test_request.py::TestRequest_functional::test_language_parsing1",
"tests/test_request.py::TestRequest_functional::test_language_parsing2",
"tests/test_request.py::TestRequest_functional::test_language_parsing3",
"tests/test_request.py::TestRequest_functional::test_mime_parsing1",
"tests/test_request.py::TestRequest_functional::test_mime_parsing2",
"tests/test_request.py::TestRequest_functional::test_mime_parsing3",
"tests/test_request.py::TestRequest_functional::test_accept_best_match",
"tests/test_request.py::TestRequest_functional::test_from_mimeparse",
"tests/test_request.py::TestRequest_functional::test_headers",
"tests/test_request.py::TestRequest_functional::test_bad_cookie",
"tests/test_request.py::TestRequest_functional::test_cookie_quoting",
"tests/test_request.py::TestRequest_functional::test_path_quoting",
"tests/test_request.py::TestRequest_functional::test_path_quoting_pct_encodes",
"tests/test_request.py::TestRequest_functional::test_params",
"tests/test_request.py::TestRequest_functional::test_copy_body",
"tests/test_request.py::TestRequest_functional::test_already_consumed_stream",
"tests/test_request.py::TestRequest_functional::test_broken_seek",
"tests/test_request.py::TestRequest_functional::test_set_body",
"tests/test_request.py::TestRequest_functional::test_broken_clen_header",
"tests/test_request.py::TestRequest_functional::test_nonstr_keys",
"tests/test_request.py::TestRequest_functional::test_authorization",
"tests/test_request.py::TestRequest_functional::test_as_bytes",
"tests/test_request.py::TestRequest_functional::test_as_text",
"tests/test_request.py::TestRequest_functional::test_req_kw_none_val",
"tests/test_request.py::TestRequest_functional::test_env_keys",
"tests/test_request.py::TestRequest_functional::test_repr_nodefault",
"tests/test_request.py::TestRequest_functional::test_request_noenviron_param",
"tests/test_request.py::TestRequest_functional::test_unexpected_kw",
"tests/test_request.py::TestRequest_functional::test_conttype_set_del",
"tests/test_request.py::TestRequest_functional::test_headers2",
"tests/test_request.py::TestRequest_functional::test_host_url",
"tests/test_request.py::TestRequest_functional::test_path_info_p",
"tests/test_request.py::TestRequest_functional::test_urlvars_property",
"tests/test_request.py::TestRequest_functional::test_urlargs_property",
"tests/test_request.py::TestRequest_functional::test_host_property",
"tests/test_request.py::TestRequest_functional::test_body_property",
"tests/test_request.py::TestRequest_functional::test_repr_invalid",
"tests/test_request.py::TestRequest_functional::test_from_garbage_file",
"tests/test_request.py::TestRequest_functional::test_from_file_patch",
"tests/test_request.py::TestRequest_functional::test_from_bytes",
"tests/test_request.py::TestRequest_functional::test_from_text",
"tests/test_request.py::TestRequest_functional::test_blank",
"tests/test_request.py::TestRequest_functional::test_post_does_not_reparse",
"tests/test_request.py::TestRequest_functional::test_middleware_body",
"tests/test_request.py::TestRequest_functional::test_body_file_noseek",
"tests/test_request.py::TestRequest_functional::test_cgi_escaping_fix",
"tests/test_request.py::TestRequest_functional::test_content_type_none",
"tests/test_request.py::TestRequest_functional::test_body_file_seekable",
"tests/test_request.py::TestRequest_functional::test_request_init",
"tests/test_request.py::TestRequest_functional::test_request_query_and_POST_vars",
"tests/test_request.py::TestRequest_functional::test_request_put",
"tests/test_request.py::TestRequest_functional::test_request_patch",
"tests/test_request.py::TestRequest_functional::test_call_WSGI_app",
"tests/test_request.py::TestRequest_functional::test_call_WSGI_app_204",
"tests/test_request.py::TestRequest_functional::test_call_WSGI_app_no_content_type",
"tests/test_request.py::TestRequest_functional::test_get_response_catch_exc_info_true",
"tests/test_request.py::TestFakeCGIBody::test_encode_multipart_value_type_options",
"tests/test_request.py::TestFakeCGIBody::test_encode_multipart_no_boundary",
"tests/test_request.py::TestFakeCGIBody::test_repr",
"tests/test_request.py::TestFakeCGIBody::test_fileno",
"tests/test_request.py::TestFakeCGIBody::test_iter",
"tests/test_request.py::TestFakeCGIBody::test_readline",
"tests/test_request.py::TestFakeCGIBody::test_read_bad_content_type",
"tests/test_request.py::TestFakeCGIBody::test_read_urlencoded",
"tests/test_request.py::TestFakeCGIBody::test_readable",
"tests/test_request.py::Test_cgi_FieldStorage__repr__patch::test_with_file",
"tests/test_request.py::Test_cgi_FieldStorage__repr__patch::test_without_file",
"tests/test_request.py::TestLimitedLengthFile::test_fileno",
"tests/test_request.py::Test_environ_from_url::test_environ_from_url",
"tests/test_request.py::Test_environ_from_url::test_environ_from_url_highorder_path_info",
"tests/test_request.py::Test_environ_from_url::test_fileupload_mime_type_detection",
"tests/test_request.py::TestRequestMultipart::test_multipart_with_charset"
] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2017-03-02T18:36:17Z" | mit |
|
Pylons__webob-332 | diff --git a/CHANGES.txt b/CHANGES.txt
index 4b5784a..ce5397f 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -44,6 +44,10 @@ These features are experimental and may change at any point in the future.
Bugfix
~~~~~~
+- Request.host_url, Request.host_port, Request.domain correctly parse IPv6 Host
+ headers as provided by a browser. See
+ https://github.com/Pylons/webob/pull/332
+
- Request.authorization would raise ValueError for unusual or malformed header
values. See https://github.com/Pylons/webob/issues/231
diff --git a/src/webob/request.py b/src/webob/request.py
index 011617c..b9f45d9 100644
--- a/src/webob/request.py
+++ b/src/webob/request.py
@@ -413,8 +413,8 @@ class BaseRequest(object):
e = self.environ
host = e.get('HTTP_HOST')
if host is not None:
- if ':' in host:
- host, port = host.split(':', 1)
+ if ':' in host and host[-1] != ']':
+ host, port = host.rsplit(':', 1)
else:
url_scheme = e['wsgi.url_scheme']
if url_scheme == 'https':
@@ -435,8 +435,8 @@ class BaseRequest(object):
url = scheme + '://'
host = e.get('HTTP_HOST')
if host is not None:
- if ':' in host:
- host, port = host.split(':', 1)
+ if ':' in host and host[-1] != ']':
+ host, port = host.rsplit(':', 1)
else:
port = None
else:
@@ -667,8 +667,8 @@ class BaseRequest(object):
.. code-block:: python
domain = request.host
- if ':' in domain:
- domain = domain.split(':', 1)[0]
+ if ':' in domain and domain[-1] != ']': # Check for ] because of IPv6
+ domain = domain.rsplit(':', 1)[0]
This will be equivalent to the domain portion of the ``HTTP_HOST``
value in the environment if it exists, or the ``SERVER_NAME`` value in
@@ -680,8 +680,8 @@ class BaseRequest(object):
value use :meth:`webob.request.Request.host` instead.
"""
domain = self.host
- if ':' in domain:
- domain = domain.split(':', 1)[0]
+ if ':' in domain and domain[-1] != ']':
+ domain = domain.rsplit(':', 1)[0]
return domain
@property
| Pylons/webob | b2e78a53af7abe866b90a532479cf5c0ae00301b | diff --git a/tests/test_request.py b/tests/test_request.py
index 85e6047..c0f932d 100644
--- a/tests/test_request.py
+++ b/tests/test_request.py
@@ -1639,6 +1639,16 @@ class TestBaseRequest(object):
req = self._makeOne(environ)
assert req.domain == 'example.com'
+ def test_domain_with_ipv6(self):
+ environ = {'HTTP_HOST': '[2001:DB8::1]:6453'}
+ req = self._makeOne(environ)
+ assert req.domain == '[2001:DB8::1]'
+
+ def test_domain_with_ipv6_no_port(self):
+ environ = {'HTTP_HOST': '[2001:DB8::1]'}
+ req = self._makeOne(environ)
+ assert req.domain == '[2001:DB8::1]'
+
def test_encget_raises_without_default(self):
inst = self._makeOne({})
with pytest.raises(KeyError):
@@ -1965,6 +1975,18 @@ class TestLegacyRequest(object):
req = self._makeOne(environ)
assert req.host_port == '4333'
+ def test_host_port_ipv6(self):
+ environ = {'HTTP_HOST': '[2001:DB8::1]:6453'}
+ req = self._makeOne(environ)
+ assert req.host_port == '6453'
+
+ def test_host_port_ipv6(self):
+ environ = {'wsgi.url_scheme': 'https',
+ 'HTTP_HOST': '[2001:DB8::1]'
+ }
+ req = self._makeOne(environ)
+ assert req.host_port == '443'
+
def test_host_url_w_http_host_and_no_port(self):
environ = {'wsgi.url_scheme': 'http',
'HTTP_HOST': 'example.com',
@@ -2015,6 +2037,20 @@ class TestLegacyRequest(object):
req = self._makeOne(environ)
assert req.host_url == 'https://example.com:4333'
+ def test_host_url_http_ipv6_host(self):
+ environ = {'wsgi.url_scheme': 'https',
+ 'HTTP_HOST': '[2001:DB8::1]:6453'
+ }
+ req = self._makeOne(environ)
+ assert req.host_url == 'https://[2001:DB8::1]:6453'
+
+ def test_host_url_http_ipv6_host_no_port(self):
+ environ = {'wsgi.url_scheme': 'https',
+ 'HTTP_HOST': '[2001:DB8::1]'
+ }
+ req = self._makeOne(environ)
+ assert req.host_url == 'https://[2001:DB8::1]'
+
@py2only
def test_application_url_py2(self):
inst = self._blankOne('/%C3%AB')
| IPv6 support
Parts of WebOb haven't been adapted to work in IPv6 environment:
- request.domain will split IPv6 addresses incorrectly
- request.host_port will split IPv6 addresses incorrectly
- request.host_url will split IPv6 addresses incorrectly
- .. maybe more places, I haven't checked all sources
This issue is similar to #174 however there it's about mitigating potential vulnerabilities and this issue is only about making API work correctly. Software using WebOb can workaround this by parsing the Host header manually, but it's just wasteful because everybody has to repeat the same work, that should be done by WebOb (as promised by the API)
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_request.py::TestBaseRequest::test_domain_with_ipv6",
"tests/test_request.py::TestBaseRequest::test_domain_with_ipv6_no_port",
"tests/test_request.py::TestLegacyRequest::test_host_port_ipv6"
] | [
"tests/test_request.py::TestRequestCommon::test_ctor_environ_getter_raises_WTF",
"tests/test_request.py::TestRequestCommon::test_ctor_wo_environ_raises_WTF",
"tests/test_request.py::TestRequestCommon::test_ctor_w_environ",
"tests/test_request.py::TestRequestCommon::test_ctor_w_non_utf8_charset",
"tests/test_request.py::TestRequestCommon::test_scheme",
"tests/test_request.py::TestRequestCommon::test_body_file_getter",
"tests/test_request.py::TestRequestCommon::test_body_file_getter_seekable",
"tests/test_request.py::TestRequestCommon::test_body_file_getter_cache",
"tests/test_request.py::TestRequestCommon::test_body_file_getter_unreadable",
"tests/test_request.py::TestRequestCommon::test_body_file_setter_w_bytes",
"tests/test_request.py::TestRequestCommon::test_body_file_setter_non_bytes",
"tests/test_request.py::TestRequestCommon::test_body_file_deleter",
"tests/test_request.py::TestRequestCommon::test_body_file_raw",
"tests/test_request.py::TestRequestCommon::test_body_file_seekable_input_not_seekable",
"tests/test_request.py::TestRequestCommon::test_body_file_seekable_input_is_seekable",
"tests/test_request.py::TestRequestCommon::test_urlvars_getter_w_paste_key",
"tests/test_request.py::TestRequestCommon::test_urlvars_getter_w_wsgiorg_key",
"tests/test_request.py::TestRequestCommon::test_urlvars_getter_wo_keys",
"tests/test_request.py::TestRequestCommon::test_urlvars_setter_w_paste_key",
"tests/test_request.py::TestRequestCommon::test_urlvars_setter_w_wsgiorg_key",
"tests/test_request.py::TestRequestCommon::test_urlvars_setter_wo_keys",
"tests/test_request.py::TestRequestCommon::test_urlvars_deleter_w_paste_key",
"tests/test_request.py::TestRequestCommon::test_urlvars_deleter_w_wsgiorg_key_non_empty_tuple",
"tests/test_request.py::TestRequestCommon::test_urlvars_deleter_w_wsgiorg_key_empty_tuple",
"tests/test_request.py::TestRequestCommon::test_urlvars_deleter_wo_keys",
"tests/test_request.py::TestRequestCommon::test_urlargs_getter_w_paste_key",
"tests/test_request.py::TestRequestCommon::test_urlargs_getter_w_wsgiorg_key",
"tests/test_request.py::TestRequestCommon::test_urlargs_getter_wo_keys",
"tests/test_request.py::TestRequestCommon::test_urlargs_setter_w_paste_key",
"tests/test_request.py::TestRequestCommon::test_urlargs_setter_w_wsgiorg_key",
"tests/test_request.py::TestRequestCommon::test_urlargs_setter_wo_keys",
"tests/test_request.py::TestRequestCommon::test_urlargs_deleter_w_wsgiorg_key",
"tests/test_request.py::TestRequestCommon::test_urlargs_deleter_w_wsgiorg_key_empty",
"tests/test_request.py::TestRequestCommon::test_urlargs_deleter_wo_keys",
"tests/test_request.py::TestRequestCommon::test_cookies_empty_environ",
"tests/test_request.py::TestRequestCommon::test_cookies_is_mutable",
"tests/test_request.py::TestRequestCommon::test_cookies_w_webob_parsed_cookies_matching_source",
"tests/test_request.py::TestRequestCommon::test_cookies_w_webob_parsed_cookies_mismatched_source",
"tests/test_request.py::TestRequestCommon::test_set_cookies",
"tests/test_request.py::TestRequestCommon::test_body_getter",
"tests/test_request.py::TestRequestCommon::test_body_setter_None",
"tests/test_request.py::TestRequestCommon::test_body_setter_non_string_raises",
"tests/test_request.py::TestRequestCommon::test_body_setter_value",
"tests/test_request.py::TestRequestCommon::test_body_deleter_None",
"tests/test_request.py::TestRequestCommon::test_json_body",
"tests/test_request.py::TestRequestCommon::test_json_body_array",
"tests/test_request.py::TestRequestCommon::test_text_body",
"tests/test_request.py::TestRequestCommon::test__text_get_without_charset",
"tests/test_request.py::TestRequestCommon::test__text_set_without_charset",
"tests/test_request.py::TestRequestCommon::test_POST_not_POST_or_PUT",
"tests/test_request.py::TestRequestCommon::test_POST_existing_cache_hit",
"tests/test_request.py::TestRequestCommon::test_PUT_missing_content_type",
"tests/test_request.py::TestRequestCommon::test_PATCH_missing_content_type",
"tests/test_request.py::TestRequestCommon::test_POST_missing_content_type",
"tests/test_request.py::TestRequestCommon::test_POST_json_no_content_type",
"tests/test_request.py::TestRequestCommon::test_PUT_bad_content_type",
"tests/test_request.py::TestRequestCommon::test_POST_multipart",
"tests/test_request.py::TestRequestCommon::test_GET_reflects_query_string",
"tests/test_request.py::TestRequestCommon::test_GET_updates_query_string",
"tests/test_request.py::TestRequestCommon::test_cookies_wo_webob_parsed_cookies",
"tests/test_request.py::TestRequestCommon::test_copy_get",
"tests/test_request.py::TestRequestCommon::test_remove_conditional_headers_accept_encoding",
"tests/test_request.py::TestRequestCommon::test_remove_conditional_headers_if_modified_since",
"tests/test_request.py::TestRequestCommon::test_remove_conditional_headers_if_none_match",
"tests/test_request.py::TestRequestCommon::test_remove_conditional_headers_if_range",
"tests/test_request.py::TestRequestCommon::test_remove_conditional_headers_range",
"tests/test_request.py::TestRequestCommon::test_is_body_readable_POST",
"tests/test_request.py::TestRequestCommon::test_is_body_readable_PATCH",
"tests/test_request.py::TestRequestCommon::test_is_body_readable_GET",
"tests/test_request.py::TestRequestCommon::test_is_body_readable_unknown_method_and_content_length",
"tests/test_request.py::TestRequestCommon::test_is_body_readable_special_flag",
"tests/test_request.py::TestRequestCommon::test_cache_control_reflects_environ",
"tests/test_request.py::TestRequestCommon::test_cache_control_updates_environ",
"tests/test_request.py::TestRequestCommon::test_cache_control_set_dict",
"tests/test_request.py::TestRequestCommon::test_cache_control_set_object",
"tests/test_request.py::TestRequestCommon::test_cache_control_gets_cached",
"tests/test_request.py::TestRequestCommon::test_call_application_calls_application",
"tests/test_request.py::TestRequestCommon::test_call_application_provides_write",
"tests/test_request.py::TestRequestCommon::test_call_application_closes_iterable_when_mixed_w_write_calls",
"tests/test_request.py::TestRequestCommon::test_call_application_raises_exc_info",
"tests/test_request.py::TestRequestCommon::test_call_application_returns_exc_info",
"tests/test_request.py::TestRequestCommon::test_blank__method_subtitution",
"tests/test_request.py::TestRequestCommon::test_blank__ctype_in_env",
"tests/test_request.py::TestRequestCommon::test_blank__ctype_in_headers",
"tests/test_request.py::TestRequestCommon::test_blank__ctype_as_kw",
"tests/test_request.py::TestRequestCommon::test_blank__str_post_data_for_unsupported_ctype",
"tests/test_request.py::TestRequestCommon::test_blank__post_urlencoded",
"tests/test_request.py::TestRequestCommon::test_blank__post_multipart",
"tests/test_request.py::TestRequestCommon::test_blank__post_files",
"tests/test_request.py::TestRequestCommon::test_blank__post_file_w_wrong_ctype",
"tests/test_request.py::TestRequestCommon::test_from_bytes_extra_data",
"tests/test_request.py::TestRequestCommon::test_as_bytes_skip_body",
"tests/test_request.py::TestRequestCommon::test_charset_in_content_type",
"tests/test_request.py::TestRequestCommon::test_limited_length_file_repr",
"tests/test_request.py::TestRequestCommon::test_request_wrong_clen[False]",
"tests/test_request.py::TestRequestCommon::test_request_wrong_clen[True]",
"tests/test_request.py::TestBaseRequest::test_method",
"tests/test_request.py::TestBaseRequest::test_http_version",
"tests/test_request.py::TestBaseRequest::test_script_name",
"tests/test_request.py::TestBaseRequest::test_path_info",
"tests/test_request.py::TestBaseRequest::test_content_length_getter",
"tests/test_request.py::TestBaseRequest::test_content_length_setter_w_str",
"tests/test_request.py::TestBaseRequest::test_remote_user",
"tests/test_request.py::TestBaseRequest::test_remote_addr",
"tests/test_request.py::TestBaseRequest::test_query_string",
"tests/test_request.py::TestBaseRequest::test_server_name",
"tests/test_request.py::TestBaseRequest::test_server_port_getter",
"tests/test_request.py::TestBaseRequest::test_server_port_setter_with_string",
"tests/test_request.py::TestBaseRequest::test_uscript_name",
"tests/test_request.py::TestBaseRequest::test_upath_info",
"tests/test_request.py::TestBaseRequest::test_upath_info_set_unicode",
"tests/test_request.py::TestBaseRequest::test_content_type_getter_no_parameters",
"tests/test_request.py::TestBaseRequest::test_content_type_getter_w_parameters",
"tests/test_request.py::TestBaseRequest::test_content_type_setter_w_None",
"tests/test_request.py::TestBaseRequest::test_content_type_setter_existing_paramter_no_new_paramter",
"tests/test_request.py::TestBaseRequest::test_content_type_deleter_clears_environ_value",
"tests/test_request.py::TestBaseRequest::test_content_type_deleter_no_environ_value",
"tests/test_request.py::TestBaseRequest::test_headers_getter",
"tests/test_request.py::TestBaseRequest::test_headers_setter",
"tests/test_request.py::TestBaseRequest::test_no_headers_deleter",
"tests/test_request.py::TestBaseRequest::test_client_addr_xff_singleval",
"tests/test_request.py::TestBaseRequest::test_client_addr_xff_multival",
"tests/test_request.py::TestBaseRequest::test_client_addr_prefers_xff",
"tests/test_request.py::TestBaseRequest::test_client_addr_no_xff",
"tests/test_request.py::TestBaseRequest::test_client_addr_no_xff_no_remote_addr",
"tests/test_request.py::TestBaseRequest::test_host_port_w_http_host_and_no_port",
"tests/test_request.py::TestBaseRequest::test_host_port_w_http_host_and_standard_port",
"tests/test_request.py::TestBaseRequest::test_host_port_w_http_host_and_oddball_port",
"tests/test_request.py::TestBaseRequest::test_host_port_w_http_host_https_and_no_port",
"tests/test_request.py::TestBaseRequest::test_host_port_w_http_host_https_and_standard_port",
"tests/test_request.py::TestBaseRequest::test_host_port_w_http_host_https_and_oddball_port",
"tests/test_request.py::TestBaseRequest::test_host_port_wo_http_host",
"tests/test_request.py::TestBaseRequest::test_host_url_w_http_host_and_no_port",
"tests/test_request.py::TestBaseRequest::test_host_url_w_http_host_and_standard_port",
"tests/test_request.py::TestBaseRequest::test_host_url_w_http_host_and_oddball_port",
"tests/test_request.py::TestBaseRequest::test_host_url_w_http_host_https_and_no_port",
"tests/test_request.py::TestBaseRequest::test_host_url_w_http_host_https_and_standard_port",
"tests/test_request.py::TestBaseRequest::test_host_url_w_http_host_https_and_oddball_port",
"tests/test_request.py::TestBaseRequest::test_host_url_wo_http_host",
"tests/test_request.py::TestBaseRequest::test_application_url",
"tests/test_request.py::TestBaseRequest::test_path_url",
"tests/test_request.py::TestBaseRequest::test_path",
"tests/test_request.py::TestBaseRequest::test_path_qs_no_qs",
"tests/test_request.py::TestBaseRequest::test_path_qs_w_qs",
"tests/test_request.py::TestBaseRequest::test_url_no_qs",
"tests/test_request.py::TestBaseRequest::test_url_w_qs",
"tests/test_request.py::TestBaseRequest::test_relative_url_to_app_true_wo_leading_slash",
"tests/test_request.py::TestBaseRequest::test_relative_url_to_app_true_w_leading_slash",
"tests/test_request.py::TestBaseRequest::test_relative_url_to_app_false_other_w_leading_slash",
"tests/test_request.py::TestBaseRequest::test_relative_url_to_app_false_other_wo_leading_slash",
"tests/test_request.py::TestBaseRequest::test_path_info_pop_empty",
"tests/test_request.py::TestBaseRequest::test_path_info_pop_just_leading_slash",
"tests/test_request.py::TestBaseRequest::test_path_info_pop_non_empty_no_pattern",
"tests/test_request.py::TestBaseRequest::test_path_info_pop_non_empty_w_pattern_miss",
"tests/test_request.py::TestBaseRequest::test_path_info_pop_non_empty_w_pattern_hit",
"tests/test_request.py::TestBaseRequest::test_path_info_pop_skips_empty_elements",
"tests/test_request.py::TestBaseRequest::test_path_info_peek_empty",
"tests/test_request.py::TestBaseRequest::test_path_info_peek_just_leading_slash",
"tests/test_request.py::TestBaseRequest::test_path_info_peek_non_empty",
"tests/test_request.py::TestBaseRequest::test_is_xhr_no_header",
"tests/test_request.py::TestBaseRequest::test_is_xhr_header_miss",
"tests/test_request.py::TestBaseRequest::test_is_xhr_header_hit",
"tests/test_request.py::TestBaseRequest::test_host_getter_w_HTTP_HOST",
"tests/test_request.py::TestBaseRequest::test_host_getter_wo_HTTP_HOST",
"tests/test_request.py::TestBaseRequest::test_host_setter",
"tests/test_request.py::TestBaseRequest::test_host_deleter_hit",
"tests/test_request.py::TestBaseRequest::test_host_deleter_miss",
"tests/test_request.py::TestBaseRequest::test_domain_nocolon",
"tests/test_request.py::TestBaseRequest::test_domain_withcolon",
"tests/test_request.py::TestBaseRequest::test_encget_raises_without_default",
"tests/test_request.py::TestBaseRequest::test_encget_doesnt_raises_with_default",
"tests/test_request.py::TestBaseRequest::test_encget_with_encattr",
"tests/test_request.py::TestBaseRequest::test_encget_with_encattr_latin_1",
"tests/test_request.py::TestBaseRequest::test_encget_no_encattr",
"tests/test_request.py::TestBaseRequest::test_relative_url",
"tests/test_request.py::TestBaseRequest::test_header_getter",
"tests/test_request.py::TestBaseRequest::test_json_body",
"tests/test_request.py::TestBaseRequest::test_host_get",
"tests/test_request.py::TestBaseRequest::test_host_get_w_no_http_host",
"tests/test_request.py::TestLegacyRequest::test_method",
"tests/test_request.py::TestLegacyRequest::test_http_version",
"tests/test_request.py::TestLegacyRequest::test_script_name",
"tests/test_request.py::TestLegacyRequest::test_path_info",
"tests/test_request.py::TestLegacyRequest::test_content_length_getter",
"tests/test_request.py::TestLegacyRequest::test_content_length_setter_w_str",
"tests/test_request.py::TestLegacyRequest::test_remote_user",
"tests/test_request.py::TestLegacyRequest::test_remote_addr",
"tests/test_request.py::TestLegacyRequest::test_query_string",
"tests/test_request.py::TestLegacyRequest::test_server_name",
"tests/test_request.py::TestLegacyRequest::test_server_port_getter",
"tests/test_request.py::TestLegacyRequest::test_server_port_setter_with_string",
"tests/test_request.py::TestLegacyRequest::test_uscript_name",
"tests/test_request.py::TestLegacyRequest::test_upath_info",
"tests/test_request.py::TestLegacyRequest::test_upath_info_set_unicode",
"tests/test_request.py::TestLegacyRequest::test_content_type_getter_no_parameters",
"tests/test_request.py::TestLegacyRequest::test_content_type_getter_w_parameters",
"tests/test_request.py::TestLegacyRequest::test_content_type_setter_w_None",
"tests/test_request.py::TestLegacyRequest::test_content_type_setter_existing_paramter_no_new_paramter",
"tests/test_request.py::TestLegacyRequest::test_content_type_deleter_clears_environ_value",
"tests/test_request.py::TestLegacyRequest::test_content_type_deleter_no_environ_value",
"tests/test_request.py::TestLegacyRequest::test_headers_getter",
"tests/test_request.py::TestLegacyRequest::test_headers_setter",
"tests/test_request.py::TestLegacyRequest::test_no_headers_deleter",
"tests/test_request.py::TestLegacyRequest::test_client_addr_xff_singleval",
"tests/test_request.py::TestLegacyRequest::test_client_addr_xff_multival",
"tests/test_request.py::TestLegacyRequest::test_client_addr_prefers_xff",
"tests/test_request.py::TestLegacyRequest::test_client_addr_no_xff",
"tests/test_request.py::TestLegacyRequest::test_client_addr_no_xff_no_remote_addr",
"tests/test_request.py::TestLegacyRequest::test_host_port_w_http_host_and_no_port",
"tests/test_request.py::TestLegacyRequest::test_host_port_w_http_host_and_standard_port",
"tests/test_request.py::TestLegacyRequest::test_host_port_w_http_host_and_oddball_port",
"tests/test_request.py::TestLegacyRequest::test_host_port_w_http_host_https_and_no_port",
"tests/test_request.py::TestLegacyRequest::test_host_port_w_http_host_https_and_standard_port",
"tests/test_request.py::TestLegacyRequest::test_host_port_w_http_host_https_and_oddball_port",
"tests/test_request.py::TestLegacyRequest::test_host_port_wo_http_host",
"tests/test_request.py::TestLegacyRequest::test_host_url_w_http_host_and_no_port",
"tests/test_request.py::TestLegacyRequest::test_host_url_w_http_host_and_standard_port",
"tests/test_request.py::TestLegacyRequest::test_host_url_w_http_host_and_oddball_port",
"tests/test_request.py::TestLegacyRequest::test_host_url_w_http_host_https_and_no_port",
"tests/test_request.py::TestLegacyRequest::test_host_url_w_http_host_https_and_standard_port",
"tests/test_request.py::TestLegacyRequest::test_host_url_w_http_host_https_and_oddball_port",
"tests/test_request.py::TestLegacyRequest::test_host_url_wo_http_host",
"tests/test_request.py::TestLegacyRequest::test_host_url_http_ipv6_host",
"tests/test_request.py::TestLegacyRequest::test_host_url_http_ipv6_host_no_port",
"tests/test_request.py::TestLegacyRequest::test_application_url",
"tests/test_request.py::TestLegacyRequest::test_path_url",
"tests/test_request.py::TestLegacyRequest::test_path",
"tests/test_request.py::TestLegacyRequest::test_path_qs_no_qs",
"tests/test_request.py::TestLegacyRequest::test_path_qs_w_qs",
"tests/test_request.py::TestLegacyRequest::test_url_no_qs",
"tests/test_request.py::TestLegacyRequest::test_url_w_qs",
"tests/test_request.py::TestLegacyRequest::test_relative_url_to_app_true_wo_leading_slash",
"tests/test_request.py::TestLegacyRequest::test_relative_url_to_app_true_w_leading_slash",
"tests/test_request.py::TestLegacyRequest::test_relative_url_to_app_false_other_w_leading_slash",
"tests/test_request.py::TestLegacyRequest::test_relative_url_to_app_false_other_wo_leading_slash",
"tests/test_request.py::TestLegacyRequest::test_path_info_pop_empty",
"tests/test_request.py::TestLegacyRequest::test_path_info_pop_just_leading_slash",
"tests/test_request.py::TestLegacyRequest::test_path_info_pop_non_empty_no_pattern",
"tests/test_request.py::TestLegacyRequest::test_path_info_pop_non_empty_w_pattern_miss",
"tests/test_request.py::TestLegacyRequest::test_path_info_pop_non_empty_w_pattern_hit",
"tests/test_request.py::TestLegacyRequest::test_path_info_pop_skips_empty_elements",
"tests/test_request.py::TestLegacyRequest::test_path_info_peek_empty",
"tests/test_request.py::TestLegacyRequest::test_path_info_peek_just_leading_slash",
"tests/test_request.py::TestLegacyRequest::test_path_info_peek_non_empty",
"tests/test_request.py::TestLegacyRequest::test_is_xhr_no_header",
"tests/test_request.py::TestLegacyRequest::test_is_xhr_header_miss",
"tests/test_request.py::TestLegacyRequest::test_is_xhr_header_hit",
"tests/test_request.py::TestLegacyRequest::test_host_getter_w_HTTP_HOST",
"tests/test_request.py::TestLegacyRequest::test_host_getter_wo_HTTP_HOST",
"tests/test_request.py::TestLegacyRequest::test_host_setter",
"tests/test_request.py::TestLegacyRequest::test_host_deleter_hit",
"tests/test_request.py::TestLegacyRequest::test_host_deleter_miss",
"tests/test_request.py::TestLegacyRequest::test_encget_raises_without_default",
"tests/test_request.py::TestLegacyRequest::test_encget_doesnt_raises_with_default",
"tests/test_request.py::TestLegacyRequest::test_encget_with_encattr",
"tests/test_request.py::TestLegacyRequest::test_encget_no_encattr",
"tests/test_request.py::TestLegacyRequest::test_relative_url",
"tests/test_request.py::TestLegacyRequest::test_header_getter",
"tests/test_request.py::TestLegacyRequest::test_json_body",
"tests/test_request.py::TestLegacyRequest::test_host_get_w_http_host",
"tests/test_request.py::TestLegacyRequest::test_host_get_w_no_http_host",
"tests/test_request.py::TestRequestConstructorWarnings::test_ctor_w_unicode_errors",
"tests/test_request.py::TestRequestConstructorWarnings::test_ctor_w_decode_param_names",
"tests/test_request.py::TestRequestWithAdhocAttr::test_adhoc_attrs_set",
"tests/test_request.py::TestRequestWithAdhocAttr::test_adhoc_attrs_set_nonadhoc",
"tests/test_request.py::TestRequestWithAdhocAttr::test_adhoc_attrs_get",
"tests/test_request.py::TestRequestWithAdhocAttr::test_adhoc_attrs_get_missing",
"tests/test_request.py::TestRequestWithAdhocAttr::test_adhoc_attrs_del",
"tests/test_request.py::TestRequestWithAdhocAttr::test_adhoc_attrs_del_missing",
"tests/test_request.py::TestRequest_functional::test_gets",
"tests/test_request.py::TestRequest_functional::test_gets_with_query_string",
"tests/test_request.py::TestRequest_functional::test_language_parsing1",
"tests/test_request.py::TestRequest_functional::test_language_parsing2",
"tests/test_request.py::TestRequest_functional::test_language_parsing3",
"tests/test_request.py::TestRequest_functional::test_mime_parsing1",
"tests/test_request.py::TestRequest_functional::test_mime_parsing2",
"tests/test_request.py::TestRequest_functional::test_mime_parsing3",
"tests/test_request.py::TestRequest_functional::test_accept_best_match",
"tests/test_request.py::TestRequest_functional::test_from_mimeparse",
"tests/test_request.py::TestRequest_functional::test_headers",
"tests/test_request.py::TestRequest_functional::test_bad_cookie",
"tests/test_request.py::TestRequest_functional::test_cookie_quoting",
"tests/test_request.py::TestRequest_functional::test_path_quoting",
"tests/test_request.py::TestRequest_functional::test_path_quoting_pct_encodes",
"tests/test_request.py::TestRequest_functional::test_params",
"tests/test_request.py::TestRequest_functional::test_copy_body",
"tests/test_request.py::TestRequest_functional::test_already_consumed_stream",
"tests/test_request.py::TestRequest_functional::test_none_field_name",
"tests/test_request.py::TestRequest_functional::test_broken_seek",
"tests/test_request.py::TestRequest_functional::test_set_body",
"tests/test_request.py::TestRequest_functional::test_broken_clen_header",
"tests/test_request.py::TestRequest_functional::test_nonstr_keys",
"tests/test_request.py::TestRequest_functional::test_authorization",
"tests/test_request.py::TestRequest_functional::test_as_bytes",
"tests/test_request.py::TestRequest_functional::test_as_text",
"tests/test_request.py::TestRequest_functional::test_req_kw_none_val",
"tests/test_request.py::TestRequest_functional::test_env_keys",
"tests/test_request.py::TestRequest_functional::test_repr_nodefault",
"tests/test_request.py::TestRequest_functional::test_request_noenviron_param",
"tests/test_request.py::TestRequest_functional::test_unexpected_kw",
"tests/test_request.py::TestRequest_functional::test_conttype_set_del",
"tests/test_request.py::TestRequest_functional::test_headers2",
"tests/test_request.py::TestRequest_functional::test_host_url",
"tests/test_request.py::TestRequest_functional::test_path_info_p",
"tests/test_request.py::TestRequest_functional::test_urlvars_property",
"tests/test_request.py::TestRequest_functional::test_urlargs_property",
"tests/test_request.py::TestRequest_functional::test_host_property",
"tests/test_request.py::TestRequest_functional::test_body_property",
"tests/test_request.py::TestRequest_functional::test_repr_invalid",
"tests/test_request.py::TestRequest_functional::test_from_garbage_file",
"tests/test_request.py::TestRequest_functional::test_from_file_patch",
"tests/test_request.py::TestRequest_functional::test_from_bytes",
"tests/test_request.py::TestRequest_functional::test_from_text",
"tests/test_request.py::TestRequest_functional::test_blank",
"tests/test_request.py::TestRequest_functional::test_post_does_not_reparse",
"tests/test_request.py::TestRequest_functional::test_middleware_body",
"tests/test_request.py::TestRequest_functional::test_body_file_noseek",
"tests/test_request.py::TestRequest_functional::test_cgi_escaping_fix",
"tests/test_request.py::TestRequest_functional::test_content_type_none",
"tests/test_request.py::TestRequest_functional::test_body_file_seekable",
"tests/test_request.py::TestRequest_functional::test_request_init",
"tests/test_request.py::TestRequest_functional::test_request_query_and_POST_vars",
"tests/test_request.py::TestRequest_functional::test_request_put",
"tests/test_request.py::TestRequest_functional::test_request_patch",
"tests/test_request.py::TestRequest_functional::test_call_WSGI_app",
"tests/test_request.py::TestRequest_functional::test_call_WSGI_app_204",
"tests/test_request.py::TestRequest_functional::test_call_WSGI_app_no_content_type",
"tests/test_request.py::TestRequest_functional::test_get_response_catch_exc_info_true",
"tests/test_request.py::TestFakeCGIBody::test_encode_multipart_value_type_options",
"tests/test_request.py::TestFakeCGIBody::test_encode_multipart_no_boundary",
"tests/test_request.py::TestFakeCGIBody::test_repr",
"tests/test_request.py::TestFakeCGIBody::test_fileno",
"tests/test_request.py::TestFakeCGIBody::test_iter",
"tests/test_request.py::TestFakeCGIBody::test_readline",
"tests/test_request.py::TestFakeCGIBody::test_read_bad_content_type",
"tests/test_request.py::TestFakeCGIBody::test_read_urlencoded",
"tests/test_request.py::TestFakeCGIBody::test_readable",
"tests/test_request.py::Test_cgi_FieldStorage__repr__patch::test_with_file",
"tests/test_request.py::Test_cgi_FieldStorage__repr__patch::test_without_file",
"tests/test_request.py::TestLimitedLengthFile::test_fileno",
"tests/test_request.py::Test_environ_from_url::test_environ_from_url",
"tests/test_request.py::Test_environ_from_url::test_environ_from_url_highorder_path_info",
"tests/test_request.py::Test_environ_from_url::test_fileupload_mime_type_detection",
"tests/test_request.py::TestRequestMultipart::test_multipart_with_charset"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2017-06-30T20:28:31Z" | mit |
|
Pylons__webob-372 | diff --git a/CHANGES.txt b/CHANGES.txt
index fd34d21..7ccc765 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -33,3 +33,10 @@ Bugfix
MIMEAccept to behave more like the old version. See
https://github.com/Pylons/webob/pull/356
+- ``acceptparse.AcceptValidHeader``, ``acceptparse.AcceptInvalidHeader``, and
+ ``acceptparse.AcceptNoHeader`` will now always ignore offers that do not
+ match the required media type grammar when calling ``.acceptable_offers()``.
+ Previous versions raised a ``ValueError`` for invalid offers in
+ ``AcceptValidHeader`` and returned them as acceptable in the others.
+ See https://github.com/Pylons/webob/pull/372
+
diff --git a/src/webob/acceptparse.py b/src/webob/acceptparse.py
index d1d9d6f..0000667 100644
--- a/src/webob/acceptparse.py
+++ b/src/webob/acceptparse.py
@@ -408,6 +408,26 @@ class Accept(object):
)
return generator(value=value)
+ def _parse_and_normalize_offers(self, offers):
+ """
+ Throw out any offers that do not match the media type ABNF.
+
+ :return: A list of offers split into the format ``[offer_index,
+ offer_type_subtype, offer_media_type_params]``.
+
+ """
+ lowercased_offers_parsed = []
+ for index, offer in enumerate(offers):
+ match = self.media_type_compiled_re.match(offer.lower())
+ # we're willing to try to match any offer that matches the
+ # media type grammar can parse, but we'll throw out anything
+ # that doesn't fit the correct syntax - this is not saying that
+ # the media type is actually a real media type, just that it looks
+ # like one
+ if match:
+ lowercased_offers_parsed.append([index] + list(match.groups()))
+ return lowercased_offers_parsed
+
class AcceptValidHeader(Accept):
"""
@@ -771,6 +791,8 @@ class AcceptValidHeader(Accept):
This uses the matching rules described in :rfc:`RFC 7231, section 5.3.2
<7231#section-5.3.2>`.
+ Any offers that do not match the media type grammar will be ignored.
+
:param offers: ``iterable`` of ``str`` media types (media types can
include media type parameters)
:return: A list of tuples of the form (media type, qvalue), in
@@ -793,21 +815,12 @@ class AcceptValidHeader(Accept):
for media_range, qvalue, media_type_params, extension_params in
parsed
]
- lowercased_offers = [offer.lower() for offer in offers]
-
- lowercased_offers_parsed = []
- for offer in lowercased_offers:
- match = self.media_type_compiled_re.match(offer)
- # The regex here is only used for parsing, and not intended to
- # validate the offer
- if not match:
- raise ValueError(repr(offer) + ' is not a media type.')
- lowercased_offers_parsed.append(match.groups())
+ lowercased_offers_parsed = self._parse_and_normalize_offers(offers)
acceptable_offers_n_quality_factors = {}
for (
- offer_index, (offer_type_subtype, offer_media_type_params)
- ) in enumerate(lowercased_offers_parsed):
+ offer_index, offer_type_subtype, offer_media_type_params
+ ) in lowercased_offers_parsed:
offer_media_type_params = self._parse_media_type_params(
media_type_params_segment=offer_media_type_params,
)
@@ -1242,6 +1255,8 @@ class _AcceptInvalidOrNoHeader(Accept):
"""
Return the offers that are acceptable according to the header.
+ Any offers that do not match the media type grammar will be ignored.
+
:param offers: ``iterable`` of ``str`` media types (media types can
include media type parameters)
:return: When the header is invalid, or there is no ``Accept`` header
@@ -1250,7 +1265,14 @@ class _AcceptInvalidOrNoHeader(Accept):
where each offer in `offers` is paired with the qvalue of 1.0,
in the same order as in `offers`.
"""
- return [(offer, 1.0) for offer in offers]
+ return [
+ (offers[offer_index], 1.0)
+ for offer_index, _, _
+ # avoid returning any offers that don't match the grammar so
+ # that the return values here are consistent with what would be
+ # returned in AcceptValidHeader
+ in self._parse_and_normalize_offers(offers)
+ ]
def best_match(self, offers, default_match=None):
"""
| Pylons/webob | d2b3a966f577918352a7d2abceebfe0fa7bf9dc8 | diff --git a/tests/test_acceptparse.py b/tests/test_acceptparse.py
index e9f3935..b8c0620 100644
--- a/tests/test_acceptparse.py
+++ b/tests/test_acceptparse.py
@@ -909,16 +909,30 @@ class TestAcceptValidHeader(object):
instance = AcceptValidHeader(header_value=header_value)
assert instance.accepts_html is returned
- @pytest.mark.parametrize('offers', [
- ['text/html;p=1;q=0.5'],
- ['text/html;q=0.5'],
- ['text/html;q=0.5;e=1'],
- ['text/html', 'text/plain;p=1;q=0.5;e=1'],
+ @pytest.mark.parametrize('header, offers, expected_returned', [
+ (AcceptValidHeader('text/html'), ['text/html;p=1;q=0.5'], []),
+ (AcceptValidHeader('text/html'), ['text/html;q=0.5'], []),
+ (AcceptValidHeader('text/html'), ['text/html;q=0.5;e=1'], []),
+ (
+ AcceptValidHeader('text/html'),
+ ['text/html', 'text/plain;p=1;q=0.5;e=1', 'foo'],
+ [('text/html', 1.0)],
+ ),
+ (
+ AcceptInvalidHeader('foo'),
+ ['text/html', 'text/plain;p=1;q=0.5;e=1', 'foo'],
+ [('text/html', 1.0)],
+ ),
+ (
+ AcceptNoHeader(),
+ ['text/html', 'text/plain;p=1;q=0.5;e=1', 'foo'],
+ [('text/html', 1.0)],
+ ),
])
- def test_acceptable_offers__invalid_offers(self, offers):
- instance = AcceptValidHeader(header_value='text/html')
- with pytest.raises(ValueError):
- instance.acceptable_offers(offers=offers)
+ def test_acceptable_offers__invalid_offers(
+ self, header, offers, expected_returned,
+ ):
+ assert header.acceptable_offers(offers=offers) == expected_returned
@pytest.mark.parametrize('header_value, offers, expected_returned', [
# RFC 7231, section 5.3.2
| validate media types consistently in acceptable_offers
```python
>>> create_accept_header('').acceptable_offers(['foo'])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/michael/work/oss/pyramid/env/lib/python3.6/site-packages/webob/acceptparse.py", line 804, in acceptable_offers
raise ValueError(repr(offer) + ' is not a media type.')
ValueError: 'foo' is not a media type.
>>> create_accept_header('*/*').acceptable_offers(['foo'])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/michael/work/oss/pyramid/env/lib/python3.6/site-packages/webob/acceptparse.py", line 804, in acceptable_offers
raise ValueError(repr(offer) + ' is not a media type.')
ValueError: 'foo' is not a media type.
>>> create_accept_header('invalid/x/y').acceptable_offers(['foo'])
[('foo', 1.0)]
>>> create_accept_header(None).acceptable_offers(['foo'])
[('foo', 1.0)]
```
It's not ok to raise here in some scenarios and not in others. The offer is server-side and webob should handle it consistently by validating those parameters the same always.
I went backward and found out that webob < 1.5 actually did this consistently but after that it stopped calling `_check_offer` in `MIMEAccept` but kept calling it in `MIMENilAccept`. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_acceptparse.py::TestAcceptValidHeader::test_acceptable_offers__invalid_offers[header0-offers0-expected_returned0]",
"tests/test_acceptparse.py::TestAcceptValidHeader::test_acceptable_offers__invalid_offers[header1-offers1-expected_returned1]",
"tests/test_acceptparse.py::TestAcceptValidHeader::test_acceptable_offers__invalid_offers[header2-offers2-expected_returned2]",
"tests/test_acceptparse.py::TestAcceptValidHeader::test_acceptable_offers__invalid_offers[header3-offers3-expected_returned3]",
"tests/test_acceptparse.py::TestAcceptValidHeader::test_acceptable_offers__invalid_offers[header4-offers4-expected_returned4]",
"tests/test_acceptparse.py::TestAcceptValidHeader::test_acceptable_offers__invalid_offers[header5-offers5-expected_returned5]"
] | [
"tests/test_acceptparse.py::Test_ItemNWeightRe::test_invalid[q=]",
"tests/test_acceptparse.py::Test_ItemNWeightRe::test_invalid[q=1]",
"tests/test_acceptparse.py::Test_ItemNWeightRe::test_invalid[;q]",
"tests/test_acceptparse.py::Test_ItemNWeightRe::test_invalid[;q=]",
"tests/test_acceptparse.py::Test_ItemNWeightRe::test_invalid[;q=1]",
"tests/test_acceptparse.py::Test_ItemNWeightRe::test_invalid[foo;]",
"tests/test_acceptparse.py::Test_ItemNWeightRe::test_invalid[foo;q]",
"tests/test_acceptparse.py::Test_ItemNWeightRe::test_invalid[foo;q1]",
"tests/test_acceptparse.py::Test_ItemNWeightRe::test_invalid[foo;q=]",
"tests/test_acceptparse.py::Test_ItemNWeightRe::test_invalid[foo;q=-1]",
"tests/test_acceptparse.py::Test_ItemNWeightRe::test_invalid[foo;q=2]",
"tests/test_acceptparse.py::Test_ItemNWeightRe::test_invalid[foo;q=1.001]",
"tests/test_acceptparse.py::Test_ItemNWeightRe::test_invalid[foo;q=0.0001]",
"tests/test_acceptparse.py::Test_ItemNWeightRe::test_invalid[foo;q=00]",
"tests/test_acceptparse.py::Test_ItemNWeightRe::test_invalid[foo;q=01]",
"tests/test_acceptparse.py::Test_ItemNWeightRe::test_invalid[foo;q=00.1]",
"tests/test_acceptparse.py::Test_ItemNWeightRe::test_invalid[foo,q=0.1]",
"tests/test_acceptparse.py::Test_ItemNWeightRe::test_invalid[foo;q",
"tests/test_acceptparse.py::Test_ItemNWeightRe::test_invalid[foo;q=",
"tests/test_acceptparse.py::Test_ItemNWeightRe::test_valid[foo-groups0]",
"tests/test_acceptparse.py::Test_ItemNWeightRe::test_valid[foo;q=0-groups1]",
"tests/test_acceptparse.py::Test_ItemNWeightRe::test_valid[foo;q=0.0-groups2]",
"tests/test_acceptparse.py::Test_ItemNWeightRe::test_valid[foo;q=0.00-groups3]",
"tests/test_acceptparse.py::Test_ItemNWeightRe::test_valid[foo;q=0.000-groups4]",
"tests/test_acceptparse.py::Test_ItemNWeightRe::test_valid[foo;q=1-groups5]",
"tests/test_acceptparse.py::Test_ItemNWeightRe::test_valid[foo;q=1.0-groups6]",
"tests/test_acceptparse.py::Test_ItemNWeightRe::test_valid[foo;q=1.00-groups7]",
"tests/test_acceptparse.py::Test_ItemNWeightRe::test_valid[foo;q=1.000-groups8]",
"tests/test_acceptparse.py::Test_ItemNWeightRe::test_valid[foo;q=0.1-groups9]",
"tests/test_acceptparse.py::Test_ItemNWeightRe::test_valid[foo;q=0.87-groups10]",
"tests/test_acceptparse.py::Test_ItemNWeightRe::test_valid[foo;q=0.382-groups11]",
"tests/test_acceptparse.py::Test_ItemNWeightRe::test_valid[foo;Q=0.382-groups12]",
"tests/test_acceptparse.py::Test_ItemNWeightRe::test_valid[foo",
"tests/test_acceptparse.py::Test_ItemNWeightRe::test_valid[foo;",
"tests/test_acceptparse.py::Test_List1OrMoreCompiledRe::test_invalid[,]",
"tests/test_acceptparse.py::Test_List1OrMoreCompiledRe::test_invalid[,",
"tests/test_acceptparse.py::Test_List1OrMoreCompiledRe::test_invalid[foo",
"tests/test_acceptparse.py::Test_List1OrMoreCompiledRe::test_invalid[",
"tests/test_acceptparse.py::Test_List1OrMoreCompiledRe::test_invalid[,foo",
"tests/test_acceptparse.py::Test_List1OrMoreCompiledRe::test_invalid[\\tfoo",
"tests/test_acceptparse.py::Test_List1OrMoreCompiledRe::test_invalid[\\t,foo",
"tests/test_acceptparse.py::Test_List1OrMoreCompiledRe::test_valid[foo,bar]",
"tests/test_acceptparse.py::Test_List1OrMoreCompiledRe::test_valid[foo,",
"tests/test_acceptparse.py::Test_List1OrMoreCompiledRe::test_valid[foo",
"tests/test_acceptparse.py::Test_List1OrMoreCompiledRe::test_valid[,foo",
"tests/test_acceptparse.py::Test_List1OrMoreCompiledRe::test_valid[,\\t",
"tests/test_acceptparse.py::TestAccept::test_parse__invalid_header[,",
"tests/test_acceptparse.py::TestAccept::test_parse__invalid_header[noslash]",
"tests/test_acceptparse.py::TestAccept::test_parse__invalid_header[/]",
"tests/test_acceptparse.py::TestAccept::test_parse__invalid_header[text/]",
"tests/test_acceptparse.py::TestAccept::test_parse__invalid_header[/html]",
"tests/test_acceptparse.py::TestAccept::test_parse__invalid_header[text/html;]",
"tests/test_acceptparse.py::TestAccept::test_parse__invalid_header[text/html;param]",
"tests/test_acceptparse.py::TestAccept::test_parse__invalid_header[text/html;param=]",
"tests/test_acceptparse.py::TestAccept::test_parse__invalid_header[text/html",
"tests/test_acceptparse.py::TestAccept::test_parse__invalid_header[text/html;",
"tests/test_acceptparse.py::TestAccept::test_parse__invalid_header[text/html;param=val;]",
"tests/test_acceptparse.py::TestAccept::test_parse__invalid_header[text/html;param=\\x19]",
"tests/test_acceptparse.py::TestAccept::test_parse__invalid_header[text/html;param=\"]",
"tests/test_acceptparse.py::TestAccept::test_parse__invalid_header[text/html;param=\\\\]",
"tests/test_acceptparse.py::TestAccept::test_parse__invalid_header[text/html;param=\\x7f]",
"tests/test_acceptparse.py::TestAccept::test_parse__invalid_header[text/html;param=\"\\\\\"]",
"tests/test_acceptparse.py::TestAccept::test_parse__invalid_header[text/html;param=\"\\\\\\\\\\\\\"]",
"tests/test_acceptparse.py::TestAccept::test_parse__invalid_header[text/html;param=\"\\\\\\\\\"\"]",
"tests/test_acceptparse.py::TestAccept::test_parse__invalid_header[text/html;param=\"\\\\\\x19\"]",
"tests/test_acceptparse.py::TestAccept::test_parse__invalid_header[text/html;param=\"\\\\\\x7f\"]",
"tests/test_acceptparse.py::TestAccept::test_parse__invalid_header[text/html;q]",
"tests/test_acceptparse.py::TestAccept::test_parse__invalid_header[text/html;q=]",
"tests/test_acceptparse.py::TestAccept::test_parse__invalid_header[text/html;q=-1]",
"tests/test_acceptparse.py::TestAccept::test_parse__invalid_header[text/html;q=2]",
"tests/test_acceptparse.py::TestAccept::test_parse__invalid_header[text/html;q=1.001]",
"tests/test_acceptparse.py::TestAccept::test_parse__invalid_header[text/html;q=0.0001]",
"tests/test_acceptparse.py::TestAccept::test_parse__invalid_header[text/html;q=00]",
"tests/test_acceptparse.py::TestAccept::test_parse__invalid_header[text/html;q=01]",
"tests/test_acceptparse.py::TestAccept::test_parse__invalid_header[text/html;q=00.1]",
"tests/test_acceptparse.py::TestAccept::test_parse__invalid_header[text/html,q=0.1]",
"tests/test_acceptparse.py::TestAccept::test_parse__invalid_header[text/html;q",
"tests/test_acceptparse.py::TestAccept::test_parse__invalid_header[text/html;q=",
"tests/test_acceptparse.py::TestAccept::test_parse__invalid_header[text/html;q=1;]",
"tests/test_acceptparse.py::TestAccept::test_parse__invalid_header[text/html;param;q=1]",
"tests/test_acceptparse.py::TestAccept::test_parse__invalid_header[text/html;q=1;extparam;]",
"tests/test_acceptparse.py::TestAccept::test_parse__invalid_header[text/html;q=1;extparam=val;]",
"tests/test_acceptparse.py::TestAccept::test_parse__invalid_header[text/html;q=1;extparam=\"val\";]",
"tests/test_acceptparse.py::TestAccept::test_parse__invalid_header[text/html;q=1;extparam=\"0]",
"tests/test_acceptparse.py::TestAccept::test_parse__invalid_header[text/html;q=1;extparam=\"val]",
"tests/test_acceptparse.py::TestAccept::test_parse__invalid_header[text/html;q=1;extparam=val\"]",
"tests/test_acceptparse.py::TestAccept::test_parse__invalid_header[text/html;q=1;extparam=\\x19]",
"tests/test_acceptparse.py::TestAccept::test_parse__invalid_header[text/html;q=1;extparam=\"1]",
"tests/test_acceptparse.py::TestAccept::test_parse__invalid_header[text/html;q=1;extparam=\\\\]",
"tests/test_acceptparse.py::TestAccept::test_parse__invalid_header[text/html;q=1;extparam=\\x7f]",
"tests/test_acceptparse.py::TestAccept::test_parse__invalid_header[text/html;q=1;extparam=\"\\\\\"]",
"tests/test_acceptparse.py::TestAccept::test_parse__invalid_header[text/html;q=1;extparam=\"\\\\\\\\\\\\\"]",
"tests/test_acceptparse.py::TestAccept::test_parse__invalid_header[text/html;q=1;extparam=\"\\\\\\\\\"\"]",
"tests/test_acceptparse.py::TestAccept::test_parse__invalid_header[text/html;q=1;extparam=\"\\\\\\x19\"]",
"tests/test_acceptparse.py::TestAccept::test_parse__invalid_header[text/html;q=1;extparam=\"\\\\\\x7f\"]",
"tests/test_acceptparse.py::TestAccept::test_parse__invalid_header[text/html;param=\\x19;q=1;extparam]",
"tests/test_acceptparse.py::TestAccept::test_parse__invalid_header[text/html;param=val;q=1;extparam=\\x19]",
"tests/test_acceptparse.py::TestAccept::test_parse__valid_header[audio/*;",
"tests/test_acceptparse.py::TestAccept::test_parse__valid_header[text/plain;",
"tests/test_acceptparse.py::TestAccept::test_parse__valid_header[text/*,",
"tests/test_acceptparse.py::TestAccept::test_parse__valid_header[text/*;q=0.3,",
"tests/test_acceptparse.py::TestAccept::test_parse__valid_header[-expected_list4]",
"tests/test_acceptparse.py::TestAccept::test_parse__valid_header[,-expected_list5]",
"tests/test_acceptparse.py::TestAccept::test_parse__valid_header[,",
"tests/test_acceptparse.py::TestAccept::test_parse__valid_header[*/*,",
"tests/test_acceptparse.py::TestAccept::test_parse__valid_header[*/html-expected_list8]",
"tests/test_acceptparse.py::TestAccept::test_parse__valid_header[text/html",
"tests/test_acceptparse.py::TestAccept::test_parse__valid_header[text/html;param=!#$%&'*+-.^_`|~09AZaz-expected_list10]",
"tests/test_acceptparse.py::TestAccept::test_parse__valid_header[text/html;param=\"\"-expected_list11]",
"tests/test_acceptparse.py::TestAccept::test_parse__valid_header[text/html;param=\"\\t",
"tests/test_acceptparse.py::TestAccept::test_parse__valid_header[text/html;param=\"\\x80\\x81\\xfe\\xff\\\\\"\\\\\\\\\"-expected_list13]",
"tests/test_acceptparse.py::TestAccept::test_parse__valid_header[text/html;param=\"\\\\\\t\\\\",
"tests/test_acceptparse.py::TestAccept::test_parse__valid_header[text/html;param='val'-expected_list15]",
"tests/test_acceptparse.py::TestAccept::test_parse__valid_header[text/html;q=0.9-expected_list16]",
"tests/test_acceptparse.py::TestAccept::test_parse__valid_header[text/html;q=0-expected_list17]",
"tests/test_acceptparse.py::TestAccept::test_parse__valid_header[text/html;q=0.0-expected_list18]",
"tests/test_acceptparse.py::TestAccept::test_parse__valid_header[text/html;q=0.00-expected_list19]",
"tests/test_acceptparse.py::TestAccept::test_parse__valid_header[text/html;q=0.000-expected_list20]",
"tests/test_acceptparse.py::TestAccept::test_parse__valid_header[text/html;q=1-expected_list21]",
"tests/test_acceptparse.py::TestAccept::test_parse__valid_header[text/html;q=1.0-expected_list22]",
"tests/test_acceptparse.py::TestAccept::test_parse__valid_header[text/html;q=1.00-expected_list23]",
"tests/test_acceptparse.py::TestAccept::test_parse__valid_header[text/html;q=1.000-expected_list24]",
"tests/test_acceptparse.py::TestAccept::test_parse__valid_header[text/html;q=0.1-expected_list25]",
"tests/test_acceptparse.py::TestAccept::test_parse__valid_header[text/html;q=0.87-expected_list26]",
"tests/test_acceptparse.py::TestAccept::test_parse__valid_header[text/html;q=0.382-expected_list27]",
"tests/test_acceptparse.py::TestAccept::test_parse__valid_header[text/html;Q=0.382-expected_list28]",
"tests/test_acceptparse.py::TestAccept::test_parse__valid_header[text/html;",
"tests/test_acceptparse.py::TestAccept::test_parse__valid_header[text/html;q=0.9;q=0.8-expected_list32]",
"tests/test_acceptparse.py::TestAccept::test_parse__valid_header[text/html;q=1;q=1;q=1-expected_list33]",
"tests/test_acceptparse.py::TestAccept::test_parse__valid_header[text/html;q=0.9;extparam1;extparam2=val2;extparam3=\"val3\"-expected_list34]",
"tests/test_acceptparse.py::TestAccept::test_parse__valid_header[text/html;q=1;extparam=!#$%&'*+-.^_`|~09AZaz-expected_list35]",
"tests/test_acceptparse.py::TestAccept::test_parse__valid_header[text/html;q=1;extparam=\"\"-expected_list36]",
"tests/test_acceptparse.py::TestAccept::test_parse__valid_header[text/html;q=1;extparam=\"\\t",
"tests/test_acceptparse.py::TestAccept::test_parse__valid_header[text/html;q=1;extparam=\"\\x80\\x81\\xfe\\xff\\\\\"\\\\\\\\\"-expected_list38]",
"tests/test_acceptparse.py::TestAccept::test_parse__valid_header[text/html;q=1;extparam=\"\\\\\\t\\\\",
"tests/test_acceptparse.py::TestAccept::test_parse__valid_header[text/html;q=1;extparam='val'-expected_list40]",
"tests/test_acceptparse.py::TestAccept::test_parse__valid_header[text/html;param1=\"val1\";param2=val2;q=0.9;extparam1=\"val1\";extparam2;extparam3=val3-expected_list41]",
"tests/test_acceptparse.py::TestAccept::test_parse__valid_header[,\\t",
"tests/test_acceptparse.py::TestAcceptValidHeader::test_parse__inherited",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___init___invalid_header[,",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___init___invalid_header[text/html;param=val;q=1;extparam=\\x19]",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___init___valid_header",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___add___None",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___add___invalid_value[,",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___add___invalid_value[right_operand1]",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___add___invalid_value[right_operand2]",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___add___invalid_value[right_operand3]",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___add___invalid_value[right_operand4]",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___add___invalid_value[a/b,",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___add___invalid_value[right_operand6]",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___add___invalid_value[right_operand7]",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___add___invalid_value[right_operand8]",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___add___invalid_value[right_operand9]",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___add___other_type_with_invalid___str__[,",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___add___other_type_with_invalid___str__[a/b,",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___add___valid_empty_value[]",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___add___valid_empty_value[value1]",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___add___valid_empty_value[value2]",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___add___valid_empty_value[value3]",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___add___other_type_with_valid___str___empty",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___add___valid_value[a/b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___add___valid_value[value1-a/b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___add___valid_value[value2-a/b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___add___valid_value[value3-a/b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___add___valid_value[value4-a/b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___add___valid_value[value5-a/b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___add___valid_value[value6-a/b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___add___valid_value[value7-a/b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___add___valid_value[value8-a/b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___add___valid_value[value9-e/f;p1=1;q=1;e1=1;e2=2,",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___add___other_type_with_valid___str___not_empty",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___add___AcceptValidHeader_header_value_empty",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___add___AcceptValidHeader_header_value_not_empty",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___add___AcceptNoHeader",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___add___AcceptInvalidHeader[,",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___add___AcceptInvalidHeader[a/b;p1=1;p2=2;q=0.8;e1;e2=\"]",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___bool__",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___contains__",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___iter__",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___radd___None",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___radd___invalid_value[,",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___radd___invalid_value[left_operand1]",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___radd___invalid_value[left_operand2]",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___radd___invalid_value[left_operand3]",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___radd___invalid_value[left_operand4]",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___radd___invalid_value[a/b,",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___radd___invalid_value[left_operand6]",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___radd___invalid_value[left_operand7]",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___radd___invalid_value[left_operand8]",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___radd___invalid_value[left_operand9]",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___radd___other_type_with_invalid___str__[,",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___radd___other_type_with_invalid___str__[a/b,",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___radd___valid_empty_value[]",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___radd___valid_empty_value[value1]",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___radd___valid_empty_value[value2]",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___radd___valid_empty_value[value3]",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___radd___other_type_with_valid___str___empty",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___radd___valid_non_empty_value[a/b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___radd___valid_non_empty_value[value1-a/b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___radd___valid_non_empty_value[value2-a/b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___radd___valid_non_empty_value[value3-a/b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___radd___valid_non_empty_value[value4-a/b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___radd___valid_non_empty_value[value5-a/b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___radd___valid_non_empty_value[value6-a/b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___radd___valid_non_empty_value[value7-a/b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___radd___valid_non_empty_value[value8-a/b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___radd___valid_non_empty_value[value9-e/f;p1=1;q=1;e1=1;e2=2,",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___radd___other_type_with_valid___str___not_empty",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___repr__[-<AcceptValidHeader",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___repr__[,,text/html",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___repr__[,\\t,",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___str__[-]",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___str__[,,text/html",
"tests/test_acceptparse.py::TestAcceptValidHeader::test___str__[,\\t,",
"tests/test_acceptparse.py::TestAcceptValidHeader::test__old_match",
"tests/test_acceptparse.py::TestAcceptValidHeader::test__old_match_wildcard_matching",
"tests/test_acceptparse.py::TestAcceptValidHeader::test_accept_html[tExt/HtMl-True]",
"tests/test_acceptparse.py::TestAcceptValidHeader::test_accept_html[APPlication/XHTML+xml-True]",
"tests/test_acceptparse.py::TestAcceptValidHeader::test_accept_html[appliCATION/xMl-True]",
"tests/test_acceptparse.py::TestAcceptValidHeader::test_accept_html[TeXt/XmL-True]",
"tests/test_acceptparse.py::TestAcceptValidHeader::test_accept_html[image/jpg-False]",
"tests/test_acceptparse.py::TestAcceptValidHeader::test_accept_html[TeXt/Plain-False]",
"tests/test_acceptparse.py::TestAcceptValidHeader::test_accept_html[image/jpg,",
"tests/test_acceptparse.py::TestAcceptValidHeader::test_accepts_html[tExt/HtMl-True]",
"tests/test_acceptparse.py::TestAcceptValidHeader::test_accepts_html[APPlication/XHTML+xml-True]",
"tests/test_acceptparse.py::TestAcceptValidHeader::test_accepts_html[appliCATION/xMl-True]",
"tests/test_acceptparse.py::TestAcceptValidHeader::test_accepts_html[TeXt/XmL-True]",
"tests/test_acceptparse.py::TestAcceptValidHeader::test_accepts_html[image/jpg-False]",
"tests/test_acceptparse.py::TestAcceptValidHeader::test_accepts_html[TeXt/Plain-False]",
"tests/test_acceptparse.py::TestAcceptValidHeader::test_accepts_html[image/jpg,",
"tests/test_acceptparse.py::TestAcceptValidHeader::test_acceptable_offers__valid_offers[audio/*;",
"tests/test_acceptparse.py::TestAcceptValidHeader::test_acceptable_offers__valid_offers[text/plain;",
"tests/test_acceptparse.py::TestAcceptValidHeader::test_acceptable_offers__valid_offers[text/*;q=0.3,",
"tests/test_acceptparse.py::TestAcceptValidHeader::test_acceptable_offers__valid_offers[teXT/*;Q=0.5,",
"tests/test_acceptparse.py::TestAcceptValidHeader::test_acceptable_offers__valid_offers[text/html,",
"tests/test_acceptparse.py::TestAcceptValidHeader::test_acceptable_offers__valid_offers[text/html",
"tests/test_acceptparse.py::TestAcceptValidHeader::test_acceptable_offers__valid_offers[-offers6-expected_returned6]",
"tests/test_acceptparse.py::TestAcceptValidHeader::test_acceptable_offers__valid_offers[text/html;p1=1;p2=2;p3=\"\\\\\"\"-offers8-expected_returned8]",
"tests/test_acceptparse.py::TestAcceptValidHeader::test_acceptable_offers__valid_offers[text/html;p1=1-offers9-expected_returned9]",
"tests/test_acceptparse.py::TestAcceptValidHeader::test_acceptable_offers__valid_offers[text/html-offers10-expected_returned10]",
"tests/test_acceptparse.py::TestAcceptValidHeader::test_acceptable_offers__valid_offers[text/html;p1=1-offers11-expected_returned11]",
"tests/test_acceptparse.py::TestAcceptValidHeader::test_acceptable_offers__valid_offers[text/html-offers12-expected_returned12]",
"tests/test_acceptparse.py::TestAcceptValidHeader::test_acceptable_offers__valid_offers[text/*-offers13-expected_returned13]",
"tests/test_acceptparse.py::TestAcceptValidHeader::test_acceptable_offers__valid_offers[*/*-offers14-expected_returned14]",
"tests/test_acceptparse.py::TestAcceptValidHeader::test_acceptable_offers__valid_offers[text/*-offers15-expected_returned15]",
"tests/test_acceptparse.py::TestAcceptValidHeader::test_acceptable_offers__valid_offers[*/*-offers16-expected_returned16]",
"tests/test_acceptparse.py::TestAcceptValidHeader::test_acceptable_offers__valid_offers[text/html;p1=1;q=0-offers17-expected_returned17]",
"tests/test_acceptparse.py::TestAcceptValidHeader::test_acceptable_offers__valid_offers[text/html;q=0-offers18-expected_returned18]",
"tests/test_acceptparse.py::TestAcceptValidHeader::test_acceptable_offers__valid_offers[text/*;q=0-offers19-expected_returned19]",
"tests/test_acceptparse.py::TestAcceptValidHeader::test_acceptable_offers__valid_offers[*/*;q=0-offers20-expected_returned20]",
"tests/test_acceptparse.py::TestAcceptValidHeader::test_acceptable_offers__valid_offers[*/*;q=0,",
"tests/test_acceptparse.py::TestAcceptValidHeader::test_acceptable_offers__valid_offers[text/html;p1=1,",
"tests/test_acceptparse.py::TestAcceptValidHeader::test_acceptable_offers__valid_offers[text/*,",
"tests/test_acceptparse.py::TestAcceptValidHeader::test_acceptable_offers__valid_offers[text/html;q=0,",
"tests/test_acceptparse.py::TestAcceptValidHeader::test_acceptable_offers__valid_offers[text/html-offers26-expected_returned26]",
"tests/test_acceptparse.py::TestAcceptValidHeader::test_best_match",
"tests/test_acceptparse.py::TestAcceptValidHeader::test_best_match_with_one_lower_q",
"tests/test_acceptparse.py::TestAcceptValidHeader::test_best_match_with_complex_q",
"tests/test_acceptparse.py::TestAcceptValidHeader::test_best_match_json",
"tests/test_acceptparse.py::TestAcceptValidHeader::test_best_match_mixedcase",
"tests/test_acceptparse.py::TestAcceptValidHeader::test_best_match_zero_quality",
"tests/test_acceptparse.py::TestAcceptValidHeader::test_quality",
"tests/test_acceptparse.py::TestAcceptValidHeader::test_quality_not_found",
"tests/test_acceptparse.py::TestAcceptNoHeader::test_parse__inherited",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___init__",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___add___None",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___add___invalid_value[,",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___add___invalid_value[right_operand1]",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___add___invalid_value[right_operand2]",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___add___invalid_value[right_operand3]",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___add___invalid_value[right_operand4]",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___add___invalid_value[a/b,",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___add___invalid_value[right_operand6]",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___add___invalid_value[right_operand7]",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___add___invalid_value[right_operand8]",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___add___invalid_value[right_operand9]",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___add___other_type_with_invalid___str__[,",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___add___other_type_with_invalid___str__[a/b,",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___add___valid_empty_value[]",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___add___valid_empty_value[value1]",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___add___valid_empty_value[value2]",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___add___valid_empty_value[value3]",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___add___other_type_with_valid___str___empty",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___add___valid_value[a/b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___add___valid_value[value1-a/b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___add___valid_value[value2-a/b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___add___valid_value[value3-a/b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___add___valid_value[value4-a/b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___add___valid_value[value5-a/b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___add___valid_value[value6-a/b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___add___valid_value[value7-a/b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___add___valid_value[value8-a/b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___add___valid_value[value9-e/f;p1=1;q=1;e1=1;e2=2,",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___add___other_type_with_valid___str___not_empty",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___add___AcceptValidHeader_header_value_empty",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___add___AcceptValidHeader_header_value_not_empty",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___add___AcceptNoHeader",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___add___AcceptInvalidHeader[,",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___add___AcceptInvalidHeader[a/b;p1=1;p2=2;q=0.8;e1;e2=\"]",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___bool__",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___contains__",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___iter__",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___radd___None",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___radd___invalid_value[,",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___radd___invalid_value[left_operand1]",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___radd___invalid_value[left_operand2]",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___radd___invalid_value[left_operand3]",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___radd___invalid_value[left_operand4]",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___radd___invalid_value[a/b,",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___radd___invalid_value[left_operand6]",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___radd___invalid_value[left_operand7]",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___radd___invalid_value[left_operand8]",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___radd___invalid_value[left_operand9]",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___radd___other_type_with_invalid___str__[,",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___radd___other_type_with_invalid___str__[a/b,",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___radd___valid_empty_value[]",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___radd___valid_empty_value[value1]",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___radd___valid_empty_value[value2]",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___radd___valid_empty_value[value3]",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___radd___other_type_with_valid___str___empty",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___radd___valid_non_empty_value[a/b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___radd___valid_non_empty_value[value1-a/b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___radd___valid_non_empty_value[value2-a/b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___radd___valid_non_empty_value[value3-a/b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___radd___valid_non_empty_value[value4-a/b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___radd___valid_non_empty_value[value5-a/b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___radd___valid_non_empty_value[value6-a/b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___radd___valid_non_empty_value[value7-a/b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___radd___valid_non_empty_value[value8-a/b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___radd___valid_non_empty_value[value9-e/f;p1=1;q=1;e1=1;e2=2,",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___radd___other_type_with_valid___str___not_empty",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___repr__",
"tests/test_acceptparse.py::TestAcceptNoHeader::test___str__",
"tests/test_acceptparse.py::TestAcceptNoHeader::test_accept_html",
"tests/test_acceptparse.py::TestAcceptNoHeader::test_accepts_html",
"tests/test_acceptparse.py::TestAcceptNoHeader::test_acceptable_offers",
"tests/test_acceptparse.py::TestAcceptNoHeader::test_best_match",
"tests/test_acceptparse.py::TestAcceptNoHeader::test_quality",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test_parse__inherited",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___init__",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___add___None",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___add___invalid_value[,",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___add___invalid_value[right_operand1]",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___add___invalid_value[right_operand2]",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___add___invalid_value[right_operand3]",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___add___invalid_value[right_operand4]",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___add___invalid_value[a/b,",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___add___invalid_value[right_operand6]",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___add___invalid_value[right_operand7]",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___add___invalid_value[right_operand8]",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___add___invalid_value[right_operand9]",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___add___other_type_with_invalid___str__[,",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___add___other_type_with_invalid___str__[a/b,",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___add___valid_empty_value[]",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___add___valid_empty_value[value1]",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___add___valid_empty_value[value2]",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___add___valid_empty_value[value3]",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___add___other_type_with_valid___str___empty",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___add___valid_value[a/b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___add___valid_value[value1-a/b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___add___valid_value[value2-a/b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___add___valid_value[value3-a/b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___add___valid_value[value4-a/b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___add___valid_value[value5-a/b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___add___valid_value[value6-a/b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___add___valid_value[value7-a/b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___add___valid_value[value8-a/b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___add___valid_value[value9-e/f;p1=1;q=1;e1=1;e2=2,",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___add___other_type_with_valid___str___not_empty",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___add___AcceptValidHeader_header_value_empty",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___add___AcceptValidHeader_header_value_not_empty",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___add___AcceptNoHeader",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___add___AcceptInvalidHeader[,",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___add___AcceptInvalidHeader[a/b;p1=1;p2=2;q=0.8;e1;e2=\"]",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___bool__",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___contains__",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___iter__",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___radd___None",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___radd___invalid_value[,",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___radd___invalid_value[left_operand1]",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___radd___invalid_value[left_operand2]",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___radd___invalid_value[left_operand3]",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___radd___invalid_value[left_operand4]",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___radd___invalid_value[a/b,",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___radd___invalid_value[left_operand6]",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___radd___invalid_value[left_operand7]",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___radd___invalid_value[left_operand8]",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___radd___invalid_value[left_operand9]",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___radd___other_type_with_invalid___str__[,",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___radd___other_type_with_invalid___str__[a/b,",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___radd___valid_empty_value[]",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___radd___valid_empty_value[value1]",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___radd___valid_empty_value[value2]",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___radd___valid_empty_value[value3]",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___radd___other_type_with_valid___str___empty",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___radd___valid_non_empty_value[a/b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___radd___valid_non_empty_value[value1-a/b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___radd___valid_non_empty_value[value2-a/b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___radd___valid_non_empty_value[value3-a/b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___radd___valid_non_empty_value[value4-a/b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___radd___valid_non_empty_value[value5-a/b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___radd___valid_non_empty_value[value6-a/b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___radd___valid_non_empty_value[value7-a/b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___radd___valid_non_empty_value[value8-a/b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___radd___valid_non_empty_value[value9-e/f;p1=1;q=1;e1=1;e2=2,",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___radd___other_type_with_valid___str___not_empty",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___repr__",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test___str__",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test_accept_html",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test_accepts_html",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test_acceptable_offers",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test_best_match",
"tests/test_acceptparse.py::TestAcceptInvalidHeader::test_quality",
"tests/test_acceptparse.py::TestCreateAcceptHeader::test_header_value_is_None",
"tests/test_acceptparse.py::TestCreateAcceptHeader::test_header_value_is_valid",
"tests/test_acceptparse.py::TestCreateAcceptHeader::test_header_value_is_invalid[,",
"tests/test_acceptparse.py::TestCreateAcceptHeader::test_header_value_is_invalid[noslash]",
"tests/test_acceptparse.py::TestAcceptProperty::test_fget_header_is_valid",
"tests/test_acceptparse.py::TestAcceptProperty::test_fget_header_is_None",
"tests/test_acceptparse.py::TestAcceptProperty::test_fget_header_is_invalid",
"tests/test_acceptparse.py::TestAcceptProperty::test_fset_value_is_valid",
"tests/test_acceptparse.py::TestAcceptProperty::test_fset_value_is_None",
"tests/test_acceptparse.py::TestAcceptProperty::test_fset_value_is_invalid",
"tests/test_acceptparse.py::TestAcceptProperty::test_fset_value_types[-]",
"tests/test_acceptparse.py::TestAcceptProperty::test_fset_value_types[value1-]",
"tests/test_acceptparse.py::TestAcceptProperty::test_fset_value_types[value2-]",
"tests/test_acceptparse.py::TestAcceptProperty::test_fset_value_types[value3-]",
"tests/test_acceptparse.py::TestAcceptProperty::test_fset_value_types[a/b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptProperty::test_fset_value_types[value5-a/b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptProperty::test_fset_value_types[value6-a/b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptProperty::test_fset_value_types[value7-a/b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptProperty::test_fset_value_types[value8-a/b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptProperty::test_fset_value_types[value9-a/b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptProperty::test_fset_value_types[value10-a/b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptProperty::test_fset_value_types[value11-a/b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptProperty::test_fset_value_types[value12-a/b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptProperty::test_fset_value_types[value13-e/f;p1=1;q=1;e1=1;e2=2,",
"tests/test_acceptparse.py::TestAcceptProperty::test_fset_other_type_with___str__[]",
"tests/test_acceptparse.py::TestAcceptProperty::test_fset_other_type_with___str__[a/b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptProperty::test_fset_AcceptValidHeader",
"tests/test_acceptparse.py::TestAcceptProperty::test_fset_AcceptNoHeader",
"tests/test_acceptparse.py::TestAcceptProperty::test_fset_AcceptInvalidHeader",
"tests/test_acceptparse.py::TestAcceptProperty::test_fdel_header_key_in_environ",
"tests/test_acceptparse.py::TestAcceptProperty::test_fdel_header_key_not_in_environ",
"tests/test_acceptparse.py::TestAcceptCharset::test_parse__invalid_header[]",
"tests/test_acceptparse.py::TestAcceptCharset::test_parse__invalid_header[\"]",
"tests/test_acceptparse.py::TestAcceptCharset::test_parse__invalid_header[(]",
"tests/test_acceptparse.py::TestAcceptCharset::test_parse__invalid_header[)]",
"tests/test_acceptparse.py::TestAcceptCharset::test_parse__invalid_header[/]",
"tests/test_acceptparse.py::TestAcceptCharset::test_parse__invalid_header[:]",
"tests/test_acceptparse.py::TestAcceptCharset::test_parse__invalid_header[;]",
"tests/test_acceptparse.py::TestAcceptCharset::test_parse__invalid_header[<]",
"tests/test_acceptparse.py::TestAcceptCharset::test_parse__invalid_header[=]",
"tests/test_acceptparse.py::TestAcceptCharset::test_parse__invalid_header[>]",
"tests/test_acceptparse.py::TestAcceptCharset::test_parse__invalid_header[?]",
"tests/test_acceptparse.py::TestAcceptCharset::test_parse__invalid_header[@]",
"tests/test_acceptparse.py::TestAcceptCharset::test_parse__invalid_header[[]",
"tests/test_acceptparse.py::TestAcceptCharset::test_parse__invalid_header[\\\\]",
"tests/test_acceptparse.py::TestAcceptCharset::test_parse__invalid_header[]]",
"tests/test_acceptparse.py::TestAcceptCharset::test_parse__invalid_header[{]",
"tests/test_acceptparse.py::TestAcceptCharset::test_parse__invalid_header[}]",
"tests/test_acceptparse.py::TestAcceptCharset::test_parse__invalid_header[foo,",
"tests/test_acceptparse.py::TestAcceptCharset::test_parse__invalid_header[foo",
"tests/test_acceptparse.py::TestAcceptCharset::test_parse__valid_header[*-expected_list0]",
"tests/test_acceptparse.py::TestAcceptCharset::test_parse__valid_header[!#$%&'*+-.^_`|~;q=0.5-expected_list1]",
"tests/test_acceptparse.py::TestAcceptCharset::test_parse__valid_header[0123456789-expected_list2]",
"tests/test_acceptparse.py::TestAcceptCharset::test_parse__valid_header[,\\t",
"tests/test_acceptparse.py::TestAcceptCharset::test_parse__valid_header[iso-8859-5;q=0.372,unicode-1-1;q=0.977,UTF-8,",
"tests/test_acceptparse.py::TestAcceptCharset::test_parse__valid_header[foo,bar-expected_list5]",
"tests/test_acceptparse.py::TestAcceptCharset::test_parse__valid_header[foo,",
"tests/test_acceptparse.py::TestAcceptCharset::test_parse__valid_header[foo",
"tests/test_acceptparse.py::TestAcceptCharsetValidHeader::test_parse__inherited",
"tests/test_acceptparse.py::TestAcceptCharsetValidHeader::test___init___invalid_header[]",
"tests/test_acceptparse.py::TestAcceptCharsetValidHeader::test___init___invalid_header[,",
"tests/test_acceptparse.py::TestAcceptCharsetValidHeader::test___init___valid_header",
"tests/test_acceptparse.py::TestAcceptCharsetValidHeader::test___add___None",
"tests/test_acceptparse.py::TestAcceptCharsetValidHeader::test___add___invalid_value[]",
"tests/test_acceptparse.py::TestAcceptCharsetValidHeader::test___add___invalid_value[right_operand1]",
"tests/test_acceptparse.py::TestAcceptCharsetValidHeader::test___add___invalid_value[right_operand2]",
"tests/test_acceptparse.py::TestAcceptCharsetValidHeader::test___add___invalid_value[right_operand3]",
"tests/test_acceptparse.py::TestAcceptCharsetValidHeader::test___add___invalid_value[UTF/8]",
"tests/test_acceptparse.py::TestAcceptCharsetValidHeader::test___add___invalid_value[right_operand5]",
"tests/test_acceptparse.py::TestAcceptCharsetValidHeader::test___add___invalid_value[right_operand6]",
"tests/test_acceptparse.py::TestAcceptCharsetValidHeader::test___add___invalid_value[right_operand7]",
"tests/test_acceptparse.py::TestAcceptCharsetValidHeader::test___add___other_type_with_invalid___str__[]",
"tests/test_acceptparse.py::TestAcceptCharsetValidHeader::test___add___other_type_with_invalid___str__[UTF/8]",
"tests/test_acceptparse.py::TestAcceptCharsetValidHeader::test___add___valid_value[UTF-7;q=0.5,",
"tests/test_acceptparse.py::TestAcceptCharsetValidHeader::test___add___valid_value[value1-UTF-7;q=0.5,",
"tests/test_acceptparse.py::TestAcceptCharsetValidHeader::test___add___valid_value[value2-UTF-7;q=0.5,",
"tests/test_acceptparse.py::TestAcceptCharsetValidHeader::test___add___valid_value[value3-UTF-8,",
"tests/test_acceptparse.py::TestAcceptCharsetValidHeader::test___add___other_type_with_valid___str__",
"tests/test_acceptparse.py::TestAcceptCharsetValidHeader::test___add___AcceptCharsetValidHeader",
"tests/test_acceptparse.py::TestAcceptCharsetValidHeader::test___add___AcceptCharsetNoHeader",
"tests/test_acceptparse.py::TestAcceptCharsetValidHeader::test___add___AcceptCharsetInvalidHeader[]",
"tests/test_acceptparse.py::TestAcceptCharsetValidHeader::test___add___AcceptCharsetInvalidHeader[utf/8]",
"tests/test_acceptparse.py::TestAcceptCharsetValidHeader::test___bool__",
"tests/test_acceptparse.py::TestAcceptCharsetValidHeader::test___contains__",
"tests/test_acceptparse.py::TestAcceptCharsetValidHeader::test___contains___not",
"tests/test_acceptparse.py::TestAcceptCharsetValidHeader::test___contains___zero_quality",
"tests/test_acceptparse.py::TestAcceptCharsetValidHeader::test___iter__",
"tests/test_acceptparse.py::TestAcceptCharsetValidHeader::test___radd___None",
"tests/test_acceptparse.py::TestAcceptCharsetValidHeader::test___radd___invalid_value[]",
"tests/test_acceptparse.py::TestAcceptCharsetValidHeader::test___radd___invalid_value[left_operand1]",
"tests/test_acceptparse.py::TestAcceptCharsetValidHeader::test___radd___invalid_value[left_operand2]",
"tests/test_acceptparse.py::TestAcceptCharsetValidHeader::test___radd___invalid_value[left_operand3]",
"tests/test_acceptparse.py::TestAcceptCharsetValidHeader::test___radd___invalid_value[UTF/8]",
"tests/test_acceptparse.py::TestAcceptCharsetValidHeader::test___radd___invalid_value[left_operand5]",
"tests/test_acceptparse.py::TestAcceptCharsetValidHeader::test___radd___invalid_value[left_operand6]",
"tests/test_acceptparse.py::TestAcceptCharsetValidHeader::test___radd___invalid_value[left_operand7]",
"tests/test_acceptparse.py::TestAcceptCharsetValidHeader::test___radd___other_type_with_invalid___str__[]",
"tests/test_acceptparse.py::TestAcceptCharsetValidHeader::test___radd___other_type_with_invalid___str__[UTF/8]",
"tests/test_acceptparse.py::TestAcceptCharsetValidHeader::test___radd___valid_value[UTF-7;q=0.5,",
"tests/test_acceptparse.py::TestAcceptCharsetValidHeader::test___radd___valid_value[value1-UTF-7;q=0.5,",
"tests/test_acceptparse.py::TestAcceptCharsetValidHeader::test___radd___valid_value[value2-UTF-7;q=0.5,",
"tests/test_acceptparse.py::TestAcceptCharsetValidHeader::test___radd___valid_value[value3-UTF-8,",
"tests/test_acceptparse.py::TestAcceptCharsetValidHeader::test___radd___other_type_with_valid___str__",
"tests/test_acceptparse.py::TestAcceptCharsetValidHeader::test___repr__",
"tests/test_acceptparse.py::TestAcceptCharsetValidHeader::test___str__",
"tests/test_acceptparse.py::TestAcceptCharsetValidHeader::test_acceptable_offers[UTF-7,",
"tests/test_acceptparse.py::TestAcceptCharsetValidHeader::test_acceptable_offers[utf-8,",
"tests/test_acceptparse.py::TestAcceptCharsetValidHeader::test_acceptable_offers[utF-8;q=0.2,",
"tests/test_acceptparse.py::TestAcceptCharsetValidHeader::test_acceptable_offers[*-offers4-returned4]",
"tests/test_acceptparse.py::TestAcceptCharsetValidHeader::test_acceptable_offers[*;q=0.8-offers5-returned5]",
"tests/test_acceptparse.py::TestAcceptCharsetValidHeader::test_acceptable_offers[UTF-7;q=0.5,",
"tests/test_acceptparse.py::TestAcceptCharsetValidHeader::test_acceptable_offers[UTF-8,",
"tests/test_acceptparse.py::TestAcceptCharsetValidHeader::test_acceptable_offers[UTF-8;q=0,",
"tests/test_acceptparse.py::TestAcceptCharsetValidHeader::test_acceptable_offers[UTF-8;q=0.5,",
"tests/test_acceptparse.py::TestAcceptCharsetValidHeader::test_acceptable_offers[UTF-8;q=0.8,",
"tests/test_acceptparse.py::TestAcceptCharsetValidHeader::test_best_match",
"tests/test_acceptparse.py::TestAcceptCharsetValidHeader::test_best_match_with_one_lower_q",
"tests/test_acceptparse.py::TestAcceptCharsetValidHeader::test_best_match_with_complex_q",
"tests/test_acceptparse.py::TestAcceptCharsetValidHeader::test_best_match_mixedcase",
"tests/test_acceptparse.py::TestAcceptCharsetValidHeader::test_best_match_zero_quality",
"tests/test_acceptparse.py::TestAcceptCharsetValidHeader::test_quality",
"tests/test_acceptparse.py::TestAcceptCharsetValidHeader::test_quality_not_found",
"tests/test_acceptparse.py::TestAcceptCharsetNoHeader::test_parse__inherited",
"tests/test_acceptparse.py::TestAcceptCharsetNoHeader::test___init__",
"tests/test_acceptparse.py::TestAcceptCharsetNoHeader::test___add___None",
"tests/test_acceptparse.py::TestAcceptCharsetNoHeader::test___add___invalid_value[]",
"tests/test_acceptparse.py::TestAcceptCharsetNoHeader::test___add___invalid_value[right_operand1]",
"tests/test_acceptparse.py::TestAcceptCharsetNoHeader::test___add___invalid_value[right_operand2]",
"tests/test_acceptparse.py::TestAcceptCharsetNoHeader::test___add___invalid_value[right_operand3]",
"tests/test_acceptparse.py::TestAcceptCharsetNoHeader::test___add___invalid_value[UTF/8]",
"tests/test_acceptparse.py::TestAcceptCharsetNoHeader::test___add___invalid_value[right_operand5]",
"tests/test_acceptparse.py::TestAcceptCharsetNoHeader::test___add___invalid_value[right_operand6]",
"tests/test_acceptparse.py::TestAcceptCharsetNoHeader::test___add___invalid_value[right_operand7]",
"tests/test_acceptparse.py::TestAcceptCharsetNoHeader::test___add___other_type_with_invalid___str__[]",
"tests/test_acceptparse.py::TestAcceptCharsetNoHeader::test___add___other_type_with_invalid___str__[UTF/8]",
"tests/test_acceptparse.py::TestAcceptCharsetNoHeader::test___add___valid_value[UTF-7;q=0.5,",
"tests/test_acceptparse.py::TestAcceptCharsetNoHeader::test___add___valid_value[value1-UTF-7;q=0.5,",
"tests/test_acceptparse.py::TestAcceptCharsetNoHeader::test___add___valid_value[value2-UTF-7;q=0.5,",
"tests/test_acceptparse.py::TestAcceptCharsetNoHeader::test___add___valid_value[value3-UTF-8,",
"tests/test_acceptparse.py::TestAcceptCharsetNoHeader::test___add___other_type_with_valid___str__",
"tests/test_acceptparse.py::TestAcceptCharsetNoHeader::test___add___AcceptCharsetValidHeader",
"tests/test_acceptparse.py::TestAcceptCharsetNoHeader::test___add___AcceptCharsetNoHeader",
"tests/test_acceptparse.py::TestAcceptCharsetNoHeader::test___add___AcceptCharsetInvalidHeader[]",
"tests/test_acceptparse.py::TestAcceptCharsetNoHeader::test___add___AcceptCharsetInvalidHeader[utf/8]",
"tests/test_acceptparse.py::TestAcceptCharsetNoHeader::test___bool__",
"tests/test_acceptparse.py::TestAcceptCharsetNoHeader::test___contains__",
"tests/test_acceptparse.py::TestAcceptCharsetNoHeader::test___iter__",
"tests/test_acceptparse.py::TestAcceptCharsetNoHeader::test___radd___None",
"tests/test_acceptparse.py::TestAcceptCharsetNoHeader::test___radd___invalid_value[]",
"tests/test_acceptparse.py::TestAcceptCharsetNoHeader::test___radd___invalid_value[left_operand1]",
"tests/test_acceptparse.py::TestAcceptCharsetNoHeader::test___radd___invalid_value[left_operand2]",
"tests/test_acceptparse.py::TestAcceptCharsetNoHeader::test___radd___invalid_value[left_operand3]",
"tests/test_acceptparse.py::TestAcceptCharsetNoHeader::test___radd___invalid_value[UTF/8]",
"tests/test_acceptparse.py::TestAcceptCharsetNoHeader::test___radd___invalid_value[left_operand5]",
"tests/test_acceptparse.py::TestAcceptCharsetNoHeader::test___radd___invalid_value[left_operand6]",
"tests/test_acceptparse.py::TestAcceptCharsetNoHeader::test___radd___invalid_value[left_operand7]",
"tests/test_acceptparse.py::TestAcceptCharsetNoHeader::test___radd___other_type_with_invalid___str__[]",
"tests/test_acceptparse.py::TestAcceptCharsetNoHeader::test___radd___other_type_with_invalid___str__[UTF/8]",
"tests/test_acceptparse.py::TestAcceptCharsetNoHeader::test___radd___valid_value[UTF-7;q=0.5,",
"tests/test_acceptparse.py::TestAcceptCharsetNoHeader::test___radd___valid_value[value1-UTF-7;q=0.5,",
"tests/test_acceptparse.py::TestAcceptCharsetNoHeader::test___radd___valid_value[value2-UTF-7;q=0.5,",
"tests/test_acceptparse.py::TestAcceptCharsetNoHeader::test___radd___valid_value[value3-UTF-8,",
"tests/test_acceptparse.py::TestAcceptCharsetNoHeader::test___radd___other_type_with_valid___str__",
"tests/test_acceptparse.py::TestAcceptCharsetNoHeader::test___repr__",
"tests/test_acceptparse.py::TestAcceptCharsetNoHeader::test___str__",
"tests/test_acceptparse.py::TestAcceptCharsetNoHeader::test_acceptable_offers",
"tests/test_acceptparse.py::TestAcceptCharsetNoHeader::test_best_match",
"tests/test_acceptparse.py::TestAcceptCharsetNoHeader::test_quality",
"tests/test_acceptparse.py::TestAcceptCharsetInvalidHeader::test_parse__inherited",
"tests/test_acceptparse.py::TestAcceptCharsetInvalidHeader::test___init__",
"tests/test_acceptparse.py::TestAcceptCharsetInvalidHeader::test___add___None",
"tests/test_acceptparse.py::TestAcceptCharsetInvalidHeader::test___add___invalid_value[]",
"tests/test_acceptparse.py::TestAcceptCharsetInvalidHeader::test___add___invalid_value[right_operand1]",
"tests/test_acceptparse.py::TestAcceptCharsetInvalidHeader::test___add___invalid_value[right_operand2]",
"tests/test_acceptparse.py::TestAcceptCharsetInvalidHeader::test___add___invalid_value[right_operand3]",
"tests/test_acceptparse.py::TestAcceptCharsetInvalidHeader::test___add___invalid_value[UTF/8]",
"tests/test_acceptparse.py::TestAcceptCharsetInvalidHeader::test___add___invalid_value[right_operand5]",
"tests/test_acceptparse.py::TestAcceptCharsetInvalidHeader::test___add___invalid_value[right_operand6]",
"tests/test_acceptparse.py::TestAcceptCharsetInvalidHeader::test___add___invalid_value[right_operand7]",
"tests/test_acceptparse.py::TestAcceptCharsetInvalidHeader::test___add___other_type_with_invalid___str__[]",
"tests/test_acceptparse.py::TestAcceptCharsetInvalidHeader::test___add___other_type_with_invalid___str__[UTF/8]",
"tests/test_acceptparse.py::TestAcceptCharsetInvalidHeader::test___add___valid_header_value[UTF-7;q=0.5,",
"tests/test_acceptparse.py::TestAcceptCharsetInvalidHeader::test___add___valid_header_value[value1-UTF-7;q=0.5,",
"tests/test_acceptparse.py::TestAcceptCharsetInvalidHeader::test___add___valid_header_value[value2-UTF-7;q=0.5,",
"tests/test_acceptparse.py::TestAcceptCharsetInvalidHeader::test___add___valid_header_value[value3-UTF-8,",
"tests/test_acceptparse.py::TestAcceptCharsetInvalidHeader::test___add___other_type_valid_header_value",
"tests/test_acceptparse.py::TestAcceptCharsetInvalidHeader::test___add___AcceptCharsetValidHeader",
"tests/test_acceptparse.py::TestAcceptCharsetInvalidHeader::test___add___AcceptCharsetNoHeader",
"tests/test_acceptparse.py::TestAcceptCharsetInvalidHeader::test___add___AcceptCharsetInvalidHeader",
"tests/test_acceptparse.py::TestAcceptCharsetInvalidHeader::test___bool__",
"tests/test_acceptparse.py::TestAcceptCharsetInvalidHeader::test___contains__",
"tests/test_acceptparse.py::TestAcceptCharsetInvalidHeader::test___iter__",
"tests/test_acceptparse.py::TestAcceptCharsetInvalidHeader::test___radd___None",
"tests/test_acceptparse.py::TestAcceptCharsetInvalidHeader::test___radd___invalid_value[]",
"tests/test_acceptparse.py::TestAcceptCharsetInvalidHeader::test___radd___invalid_value[left_operand1]",
"tests/test_acceptparse.py::TestAcceptCharsetInvalidHeader::test___radd___invalid_value[left_operand2]",
"tests/test_acceptparse.py::TestAcceptCharsetInvalidHeader::test___radd___invalid_value[left_operand3]",
"tests/test_acceptparse.py::TestAcceptCharsetInvalidHeader::test___radd___invalid_value[UTF/8]",
"tests/test_acceptparse.py::TestAcceptCharsetInvalidHeader::test___radd___invalid_value[left_operand5]",
"tests/test_acceptparse.py::TestAcceptCharsetInvalidHeader::test___radd___invalid_value[left_operand6]",
"tests/test_acceptparse.py::TestAcceptCharsetInvalidHeader::test___radd___invalid_value[left_operand7]",
"tests/test_acceptparse.py::TestAcceptCharsetInvalidHeader::test___radd___other_type_with_invalid___str__[]",
"tests/test_acceptparse.py::TestAcceptCharsetInvalidHeader::test___radd___other_type_with_invalid___str__[UTF/8]",
"tests/test_acceptparse.py::TestAcceptCharsetInvalidHeader::test___radd___valid_header_value[UTF-7;q=0.5,",
"tests/test_acceptparse.py::TestAcceptCharsetInvalidHeader::test___radd___valid_header_value[value1-UTF-7;q=0.5,",
"tests/test_acceptparse.py::TestAcceptCharsetInvalidHeader::test___radd___valid_header_value[value2-UTF-7;q=0.5,",
"tests/test_acceptparse.py::TestAcceptCharsetInvalidHeader::test___radd___valid_header_value[value3-UTF-8,",
"tests/test_acceptparse.py::TestAcceptCharsetInvalidHeader::test___radd___other_type_valid_header_value",
"tests/test_acceptparse.py::TestAcceptCharsetInvalidHeader::test___repr__",
"tests/test_acceptparse.py::TestAcceptCharsetInvalidHeader::test___str__",
"tests/test_acceptparse.py::TestAcceptCharsetInvalidHeader::test_acceptable_offers",
"tests/test_acceptparse.py::TestAcceptCharsetInvalidHeader::test_best_match",
"tests/test_acceptparse.py::TestAcceptCharsetInvalidHeader::test_quality",
"tests/test_acceptparse.py::TestCreateAcceptCharsetHeader::test_header_value_is_valid",
"tests/test_acceptparse.py::TestCreateAcceptCharsetHeader::test_header_value_is_None",
"tests/test_acceptparse.py::TestCreateAcceptCharsetHeader::test_header_value_is_invalid[]",
"tests/test_acceptparse.py::TestCreateAcceptCharsetHeader::test_header_value_is_invalid[iso-8859-5,",
"tests/test_acceptparse.py::TestAcceptCharsetProperty::test_fget_header_is_None",
"tests/test_acceptparse.py::TestAcceptCharsetProperty::test_fget_header_is_valid",
"tests/test_acceptparse.py::TestAcceptCharsetProperty::test_fget_header_is_invalid",
"tests/test_acceptparse.py::TestAcceptCharsetProperty::test_fset_value_is_None",
"tests/test_acceptparse.py::TestAcceptCharsetProperty::test_fset_value_is_invalid",
"tests/test_acceptparse.py::TestAcceptCharsetProperty::test_fset_value_is_valid",
"tests/test_acceptparse.py::TestAcceptCharsetProperty::test_fset_value_types[utf-8;q=0.5,",
"tests/test_acceptparse.py::TestAcceptCharsetProperty::test_fset_value_types[value1-utf-8;q=0.5,",
"tests/test_acceptparse.py::TestAcceptCharsetProperty::test_fset_value_types[value2-utf-8;q=0.5,",
"tests/test_acceptparse.py::TestAcceptCharsetProperty::test_fset_value_types[value3-utf-7,",
"tests/test_acceptparse.py::TestAcceptCharsetProperty::test_fset_other_type_with_valid___str__",
"tests/test_acceptparse.py::TestAcceptCharsetProperty::test_fset_AcceptCharsetNoHeader",
"tests/test_acceptparse.py::TestAcceptCharsetProperty::test_fset_AcceptCharsetValidHeader",
"tests/test_acceptparse.py::TestAcceptCharsetProperty::test_fset_AcceptCharsetInvalidHeader",
"tests/test_acceptparse.py::TestAcceptCharsetProperty::test_fdel_header_key_in_environ",
"tests/test_acceptparse.py::TestAcceptCharsetProperty::test_fdel_header_key_not_in_environ",
"tests/test_acceptparse.py::TestAcceptEncoding::test_parse__invalid_header[\"]",
"tests/test_acceptparse.py::TestAcceptEncoding::test_parse__invalid_header[(]",
"tests/test_acceptparse.py::TestAcceptEncoding::test_parse__invalid_header[)]",
"tests/test_acceptparse.py::TestAcceptEncoding::test_parse__invalid_header[/]",
"tests/test_acceptparse.py::TestAcceptEncoding::test_parse__invalid_header[:]",
"tests/test_acceptparse.py::TestAcceptEncoding::test_parse__invalid_header[;]",
"tests/test_acceptparse.py::TestAcceptEncoding::test_parse__invalid_header[<]",
"tests/test_acceptparse.py::TestAcceptEncoding::test_parse__invalid_header[=]",
"tests/test_acceptparse.py::TestAcceptEncoding::test_parse__invalid_header[>]",
"tests/test_acceptparse.py::TestAcceptEncoding::test_parse__invalid_header[?]",
"tests/test_acceptparse.py::TestAcceptEncoding::test_parse__invalid_header[@]",
"tests/test_acceptparse.py::TestAcceptEncoding::test_parse__invalid_header[[]",
"tests/test_acceptparse.py::TestAcceptEncoding::test_parse__invalid_header[\\\\]",
"tests/test_acceptparse.py::TestAcceptEncoding::test_parse__invalid_header[]]",
"tests/test_acceptparse.py::TestAcceptEncoding::test_parse__invalid_header[{]",
"tests/test_acceptparse.py::TestAcceptEncoding::test_parse__invalid_header[}]",
"tests/test_acceptparse.py::TestAcceptEncoding::test_parse__invalid_header[,",
"tests/test_acceptparse.py::TestAcceptEncoding::test_parse__invalid_header[gzip;q=1.0,",
"tests/test_acceptparse.py::TestAcceptEncoding::test_parse__valid_header[,-expected_list0]",
"tests/test_acceptparse.py::TestAcceptEncoding::test_parse__valid_header[,",
"tests/test_acceptparse.py::TestAcceptEncoding::test_parse__valid_header[*-expected_list2]",
"tests/test_acceptparse.py::TestAcceptEncoding::test_parse__valid_header[!#$%&'*+-.^_`|~;q=0.5-expected_list3]",
"tests/test_acceptparse.py::TestAcceptEncoding::test_parse__valid_header[0123456789-expected_list4]",
"tests/test_acceptparse.py::TestAcceptEncoding::test_parse__valid_header[,,\\t",
"tests/test_acceptparse.py::TestAcceptEncoding::test_parse__valid_header[compress,",
"tests/test_acceptparse.py::TestAcceptEncoding::test_parse__valid_header[-expected_list7]",
"tests/test_acceptparse.py::TestAcceptEncoding::test_parse__valid_header[*-expected_list8]",
"tests/test_acceptparse.py::TestAcceptEncoding::test_parse__valid_header[compress;q=0.5,",
"tests/test_acceptparse.py::TestAcceptEncoding::test_parse__valid_header[gzip;q=1.0,",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test_parse__inherited",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test___init___invalid_header[,",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test___init___invalid_header[gzip;q=1.0,",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test___init___valid_header",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test___add___None",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test___add___invalid_value[,",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test___add___invalid_value[right_operand1]",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test___add___invalid_value[right_operand2]",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test___add___invalid_value[right_operand3]",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test___add___other_type_with_invalid___str__",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test___add___valid_empty_value[]",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test___add___valid_empty_value[value1]",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test___add___valid_empty_value[value2]",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test___add___valid_empty_value[value3]",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test___add___other_type_with_valid___str___empty",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test___add___valid_value[compress;q=0.5,",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test___add___valid_value[value1-compress;q=0.5,",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test___add___valid_value[value2-compress;q=0.5,",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test___add___valid_value[value3-compress;q=0.5,",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test___add___valid_value[value4-compress;q=0.5,",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test___add___valid_value[value5-*,",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test___add___other_type_with_valid___str___not_empty",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test___add___AcceptEncodingValidHeader_header_value_empty",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test___add___AcceptEncodingValidHeader_header_value_not_empty",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test___add___AcceptEncodingNoHeader",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test___add___AcceptEncodingInvalidHeader[,",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test___add___AcceptEncodingInvalidHeader[compress;q=1.001]",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test___bool__",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test___contains__",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test___iter__",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test___radd___None",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test___radd___invalid_value[,",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test___radd___invalid_value[left_operand1]",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test___radd___invalid_value[left_operand2]",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test___radd___invalid_value[left_operand3]",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test___radd___other_type_with_invalid___str__",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test___radd___valid_empty_value[]",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test___radd___valid_empty_value[value1]",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test___radd___valid_empty_value[value2]",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test___radd___valid_empty_value[value3]",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test___radd___other_type_with_valid___str___empty",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test___radd___valid_non_empty_value[compress;q=0.5,",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test___radd___valid_non_empty_value[value1-compress;q=0.5,",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test___radd___valid_non_empty_value[value2-compress;q=0.5,",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test___radd___valid_non_empty_value[value3-compress;q=0.5,",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test___radd___valid_non_empty_value[value4-compress;q=0.5,",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test___radd___valid_non_empty_value[value5-*,",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test___radd___other_type_with_valid___str___not_empty",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test___repr__[-<AcceptEncodingValidHeader",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test___repr__[,\\t,",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test___str__[-]",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test___str__[,\\t,",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test_acceptable_offers[-offers0-expected_returned0]",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test_acceptable_offers[gzip,",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test_acceptable_offers[-offers2-expected_returned2]",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test_acceptable_offers[-offers3-expected_returned3]",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test_acceptable_offers[compress,",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test_acceptable_offers[*;q=0-offers6-expected_returned6]",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test_acceptable_offers[*;q=0,",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test_acceptable_offers[IDentity;q=0.5,",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test_acceptable_offers[compress;q=0,",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test_best_match",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test_best_match_with_one_lower_q",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test_best_match_with_complex_q",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test_best_match_mixedcase",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test_best_match_zero_quality",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test_quality",
"tests/test_acceptparse.py::TestAcceptEncodingValidHeader::test_quality_not_found",
"tests/test_acceptparse.py::TestAcceptEncodingNoHeader::test_parse__inherited",
"tests/test_acceptparse.py::TestAcceptEncodingNoHeader::test___init__",
"tests/test_acceptparse.py::TestAcceptEncodingNoHeader::test___add___None",
"tests/test_acceptparse.py::TestAcceptEncodingNoHeader::test___add___invalid_value[,",
"tests/test_acceptparse.py::TestAcceptEncodingNoHeader::test___add___invalid_value[right_operand1]",
"tests/test_acceptparse.py::TestAcceptEncodingNoHeader::test___add___invalid_value[right_operand2]",
"tests/test_acceptparse.py::TestAcceptEncodingNoHeader::test___add___invalid_value[right_operand3]",
"tests/test_acceptparse.py::TestAcceptEncodingNoHeader::test___add___other_type_with_invalid___str__",
"tests/test_acceptparse.py::TestAcceptEncodingNoHeader::test___add___valid_empty_value[]",
"tests/test_acceptparse.py::TestAcceptEncodingNoHeader::test___add___valid_empty_value[value1]",
"tests/test_acceptparse.py::TestAcceptEncodingNoHeader::test___add___valid_empty_value[value2]",
"tests/test_acceptparse.py::TestAcceptEncodingNoHeader::test___add___valid_empty_value[value3]",
"tests/test_acceptparse.py::TestAcceptEncodingNoHeader::test___add___other_type_with_valid___str___empty",
"tests/test_acceptparse.py::TestAcceptEncodingNoHeader::test___add___valid_value[compress;q=0.5,",
"tests/test_acceptparse.py::TestAcceptEncodingNoHeader::test___add___valid_value[value1-compress;q=0.5,",
"tests/test_acceptparse.py::TestAcceptEncodingNoHeader::test___add___valid_value[value2-compress;q=0.5,",
"tests/test_acceptparse.py::TestAcceptEncodingNoHeader::test___add___valid_value[value3-compress;q=0.5,",
"tests/test_acceptparse.py::TestAcceptEncodingNoHeader::test___add___valid_value[value4-compress;q=0.5,",
"tests/test_acceptparse.py::TestAcceptEncodingNoHeader::test___add___valid_value[value5-*,",
"tests/test_acceptparse.py::TestAcceptEncodingNoHeader::test___add___other_type_with_valid___str___not_empty",
"tests/test_acceptparse.py::TestAcceptEncodingNoHeader::test___add___AcceptEncodingValidHeader_header_value_empty",
"tests/test_acceptparse.py::TestAcceptEncodingNoHeader::test___add___AcceptEncodingValidHeader_header_value_not_empty",
"tests/test_acceptparse.py::TestAcceptEncodingNoHeader::test___add___AcceptEncodingNoHeader",
"tests/test_acceptparse.py::TestAcceptEncodingNoHeader::test___add___AcceptEncodingInvalidHeader[,",
"tests/test_acceptparse.py::TestAcceptEncodingNoHeader::test___add___AcceptEncodingInvalidHeader[compress;q=1.001]",
"tests/test_acceptparse.py::TestAcceptEncodingNoHeader::test___bool__",
"tests/test_acceptparse.py::TestAcceptEncodingNoHeader::test___contains__",
"tests/test_acceptparse.py::TestAcceptEncodingNoHeader::test___iter__",
"tests/test_acceptparse.py::TestAcceptEncodingNoHeader::test___radd___None",
"tests/test_acceptparse.py::TestAcceptEncodingNoHeader::test___radd___invalid_value[,",
"tests/test_acceptparse.py::TestAcceptEncodingNoHeader::test___radd___invalid_value[left_operand1]",
"tests/test_acceptparse.py::TestAcceptEncodingNoHeader::test___radd___invalid_value[left_operand2]",
"tests/test_acceptparse.py::TestAcceptEncodingNoHeader::test___radd___invalid_value[left_operand3]",
"tests/test_acceptparse.py::TestAcceptEncodingNoHeader::test___radd___other_type_with_invalid___str__",
"tests/test_acceptparse.py::TestAcceptEncodingNoHeader::test___radd___valid_empty_value[]",
"tests/test_acceptparse.py::TestAcceptEncodingNoHeader::test___radd___valid_empty_value[value1]",
"tests/test_acceptparse.py::TestAcceptEncodingNoHeader::test___radd___valid_empty_value[value2]",
"tests/test_acceptparse.py::TestAcceptEncodingNoHeader::test___radd___valid_empty_value[value3]",
"tests/test_acceptparse.py::TestAcceptEncodingNoHeader::test___radd___other_type_with_valid___str___empty",
"tests/test_acceptparse.py::TestAcceptEncodingNoHeader::test___radd___valid_non_empty_value[compress;q=0.5,",
"tests/test_acceptparse.py::TestAcceptEncodingNoHeader::test___radd___valid_non_empty_value[value1-compress;q=0.5,",
"tests/test_acceptparse.py::TestAcceptEncodingNoHeader::test___radd___valid_non_empty_value[value2-compress;q=0.5,",
"tests/test_acceptparse.py::TestAcceptEncodingNoHeader::test___radd___valid_non_empty_value[value3-compress;q=0.5,",
"tests/test_acceptparse.py::TestAcceptEncodingNoHeader::test___radd___valid_non_empty_value[value4-compress;q=0.5,",
"tests/test_acceptparse.py::TestAcceptEncodingNoHeader::test___radd___valid_non_empty_value[value5-*,",
"tests/test_acceptparse.py::TestAcceptEncodingNoHeader::test___radd___other_type_with_valid___str___not_empty",
"tests/test_acceptparse.py::TestAcceptEncodingNoHeader::test___repr__",
"tests/test_acceptparse.py::TestAcceptEncodingNoHeader::test___str__",
"tests/test_acceptparse.py::TestAcceptEncodingNoHeader::test_acceptable_offers",
"tests/test_acceptparse.py::TestAcceptEncodingNoHeader::test_best_match",
"tests/test_acceptparse.py::TestAcceptEncodingNoHeader::test_quality",
"tests/test_acceptparse.py::TestAcceptEncodingInvalidHeader::test_parse__inherited",
"tests/test_acceptparse.py::TestAcceptEncodingInvalidHeader::test___init__",
"tests/test_acceptparse.py::TestAcceptEncodingInvalidHeader::test___add___None",
"tests/test_acceptparse.py::TestAcceptEncodingInvalidHeader::test___add___invalid_value[,",
"tests/test_acceptparse.py::TestAcceptEncodingInvalidHeader::test___add___invalid_value[right_operand1]",
"tests/test_acceptparse.py::TestAcceptEncodingInvalidHeader::test___add___invalid_value[right_operand2]",
"tests/test_acceptparse.py::TestAcceptEncodingInvalidHeader::test___add___invalid_value[right_operand3]",
"tests/test_acceptparse.py::TestAcceptEncodingInvalidHeader::test___add___other_type_with_invalid___str__",
"tests/test_acceptparse.py::TestAcceptEncodingInvalidHeader::test___add___valid_empty_value[]",
"tests/test_acceptparse.py::TestAcceptEncodingInvalidHeader::test___add___valid_empty_value[value1]",
"tests/test_acceptparse.py::TestAcceptEncodingInvalidHeader::test___add___valid_empty_value[value2]",
"tests/test_acceptparse.py::TestAcceptEncodingInvalidHeader::test___add___valid_empty_value[value3]",
"tests/test_acceptparse.py::TestAcceptEncodingInvalidHeader::test___add___other_type_with_valid___str___empty",
"tests/test_acceptparse.py::TestAcceptEncodingInvalidHeader::test___add___valid_value[compress;q=0.5,",
"tests/test_acceptparse.py::TestAcceptEncodingInvalidHeader::test___add___valid_value[value1-compress;q=0.5,",
"tests/test_acceptparse.py::TestAcceptEncodingInvalidHeader::test___add___valid_value[value2-compress;q=0.5,",
"tests/test_acceptparse.py::TestAcceptEncodingInvalidHeader::test___add___valid_value[value3-compress;q=0.5,",
"tests/test_acceptparse.py::TestAcceptEncodingInvalidHeader::test___add___valid_value[value4-compress;q=0.5,",
"tests/test_acceptparse.py::TestAcceptEncodingInvalidHeader::test___add___valid_value[value5-*,",
"tests/test_acceptparse.py::TestAcceptEncodingInvalidHeader::test___add___other_type_with_valid___str___not_empty",
"tests/test_acceptparse.py::TestAcceptEncodingInvalidHeader::test___add___AcceptEncodingValidHeader_header_value_empty",
"tests/test_acceptparse.py::TestAcceptEncodingInvalidHeader::test___add___AcceptEncodingValidHeader_header_value_not_empty",
"tests/test_acceptparse.py::TestAcceptEncodingInvalidHeader::test___add___AcceptEncodingNoHeader",
"tests/test_acceptparse.py::TestAcceptEncodingInvalidHeader::test___add___AcceptEncodingInvalidHeader[,",
"tests/test_acceptparse.py::TestAcceptEncodingInvalidHeader::test___add___AcceptEncodingInvalidHeader[compress;q=1.001]",
"tests/test_acceptparse.py::TestAcceptEncodingInvalidHeader::test___bool__",
"tests/test_acceptparse.py::TestAcceptEncodingInvalidHeader::test___contains__",
"tests/test_acceptparse.py::TestAcceptEncodingInvalidHeader::test___iter__",
"tests/test_acceptparse.py::TestAcceptEncodingInvalidHeader::test___radd___None",
"tests/test_acceptparse.py::TestAcceptEncodingInvalidHeader::test___radd___invalid_value[,",
"tests/test_acceptparse.py::TestAcceptEncodingInvalidHeader::test___radd___invalid_value[left_operand1]",
"tests/test_acceptparse.py::TestAcceptEncodingInvalidHeader::test___radd___invalid_value[left_operand2]",
"tests/test_acceptparse.py::TestAcceptEncodingInvalidHeader::test___radd___invalid_value[left_operand3]",
"tests/test_acceptparse.py::TestAcceptEncodingInvalidHeader::test___radd___other_type_with_invalid___str__",
"tests/test_acceptparse.py::TestAcceptEncodingInvalidHeader::test___radd___valid_empty_value[]",
"tests/test_acceptparse.py::TestAcceptEncodingInvalidHeader::test___radd___valid_empty_value[value1]",
"tests/test_acceptparse.py::TestAcceptEncodingInvalidHeader::test___radd___valid_empty_value[value2]",
"tests/test_acceptparse.py::TestAcceptEncodingInvalidHeader::test___radd___valid_empty_value[value3]",
"tests/test_acceptparse.py::TestAcceptEncodingInvalidHeader::test___radd___other_type_with_valid___str___empty",
"tests/test_acceptparse.py::TestAcceptEncodingInvalidHeader::test___radd___valid_non_empty_value[compress;q=0.5,",
"tests/test_acceptparse.py::TestAcceptEncodingInvalidHeader::test___radd___valid_non_empty_value[value1-compress;q=0.5,",
"tests/test_acceptparse.py::TestAcceptEncodingInvalidHeader::test___radd___valid_non_empty_value[value2-compress;q=0.5,",
"tests/test_acceptparse.py::TestAcceptEncodingInvalidHeader::test___radd___valid_non_empty_value[value3-compress;q=0.5,",
"tests/test_acceptparse.py::TestAcceptEncodingInvalidHeader::test___radd___valid_non_empty_value[value4-compress;q=0.5,",
"tests/test_acceptparse.py::TestAcceptEncodingInvalidHeader::test___radd___valid_non_empty_value[value5-*,",
"tests/test_acceptparse.py::TestAcceptEncodingInvalidHeader::test___radd___other_type_with_valid___str___not_empty",
"tests/test_acceptparse.py::TestAcceptEncodingInvalidHeader::test___repr__",
"tests/test_acceptparse.py::TestAcceptEncodingInvalidHeader::test___str__",
"tests/test_acceptparse.py::TestAcceptEncodingInvalidHeader::test_acceptable_offers",
"tests/test_acceptparse.py::TestAcceptEncodingInvalidHeader::test_best_match",
"tests/test_acceptparse.py::TestAcceptEncodingInvalidHeader::test_quality",
"tests/test_acceptparse.py::TestCreateAcceptEncodingHeader::test_header_value_is_None",
"tests/test_acceptparse.py::TestCreateAcceptEncodingHeader::test_header_value_is_valid",
"tests/test_acceptparse.py::TestCreateAcceptEncodingHeader::test_header_value_is_invalid[,",
"tests/test_acceptparse.py::TestCreateAcceptEncodingHeader::test_header_value_is_invalid[gzip;q=",
"tests/test_acceptparse.py::TestAcceptEncodingProperty::test_fget_header_is_None",
"tests/test_acceptparse.py::TestAcceptEncodingProperty::test_fget_header_is_valid",
"tests/test_acceptparse.py::TestAcceptEncodingProperty::test_fget_header_is_invalid",
"tests/test_acceptparse.py::TestAcceptEncodingProperty::test_fset_value_is_None",
"tests/test_acceptparse.py::TestAcceptEncodingProperty::test_fset_value_is_invalid",
"tests/test_acceptparse.py::TestAcceptEncodingProperty::test_fset_value_is_valid",
"tests/test_acceptparse.py::TestAcceptEncodingProperty::test_fset_value_types[gzip;q=0.5,",
"tests/test_acceptparse.py::TestAcceptEncodingProperty::test_fset_value_types[value1-gzip;q=0.5,",
"tests/test_acceptparse.py::TestAcceptEncodingProperty::test_fset_value_types[value2-gzip;q=0.5,",
"tests/test_acceptparse.py::TestAcceptEncodingProperty::test_fset_value_types[value3-deflate,",
"tests/test_acceptparse.py::TestAcceptEncodingProperty::test_fset_other_type_with_valid___str__",
"tests/test_acceptparse.py::TestAcceptEncodingProperty::test_fset_AcceptEncodingNoHeader",
"tests/test_acceptparse.py::TestAcceptEncodingProperty::test_fset_AcceptEncodingValidHeader",
"tests/test_acceptparse.py::TestAcceptEncodingProperty::test_fset_AcceptEncodingInvalidHeader",
"tests/test_acceptparse.py::TestAcceptEncodingProperty::test_fdel_header_key_in_environ",
"tests/test_acceptparse.py::TestAcceptEncodingProperty::test_fdel_header_key_not_in_environ",
"tests/test_acceptparse.py::TestAcceptLanguage::test_parse__invalid_header[]",
"tests/test_acceptparse.py::TestAcceptLanguage::test_parse__invalid_header[*s]",
"tests/test_acceptparse.py::TestAcceptLanguage::test_parse__invalid_header[*-a]",
"tests/test_acceptparse.py::TestAcceptLanguage::test_parse__invalid_header[a-*]",
"tests/test_acceptparse.py::TestAcceptLanguage::test_parse__invalid_header[aaaaaaaaa]",
"tests/test_acceptparse.py::TestAcceptLanguage::test_parse__invalid_header[a-aaaaaaaaa]",
"tests/test_acceptparse.py::TestAcceptLanguage::test_parse__invalid_header[a-a-aaaaaaaaa]",
"tests/test_acceptparse.py::TestAcceptLanguage::test_parse__invalid_header[-]",
"tests/test_acceptparse.py::TestAcceptLanguage::test_parse__invalid_header[a-]",
"tests/test_acceptparse.py::TestAcceptLanguage::test_parse__invalid_header[-a]",
"tests/test_acceptparse.py::TestAcceptLanguage::test_parse__invalid_header[---]",
"tests/test_acceptparse.py::TestAcceptLanguage::test_parse__invalid_header[--a]",
"tests/test_acceptparse.py::TestAcceptLanguage::test_parse__invalid_header[1-a]",
"tests/test_acceptparse.py::TestAcceptLanguage::test_parse__invalid_header[1-a-a]",
"tests/test_acceptparse.py::TestAcceptLanguage::test_parse__invalid_header[en_gb]",
"tests/test_acceptparse.py::TestAcceptLanguage::test_parse__invalid_header[en/gb]",
"tests/test_acceptparse.py::TestAcceptLanguage::test_parse__invalid_header[foo,",
"tests/test_acceptparse.py::TestAcceptLanguage::test_parse__invalid_header[foo",
"tests/test_acceptparse.py::TestAcceptLanguage::test_parse__valid_header[*-expected_list0]",
"tests/test_acceptparse.py::TestAcceptLanguage::test_parse__valid_header[fR;q=0.5-expected_list1]",
"tests/test_acceptparse.py::TestAcceptLanguage::test_parse__valid_header[zh-Hant;q=0.500-expected_list2]",
"tests/test_acceptparse.py::TestAcceptLanguage::test_parse__valid_header[zh-Hans-CN;q=1-expected_list3]",
"tests/test_acceptparse.py::TestAcceptLanguage::test_parse__valid_header[de-CH-x-phonebk;q=1.0-expected_list4]",
"tests/test_acceptparse.py::TestAcceptLanguage::test_parse__valid_header[az-Arab-x-AZE-derbend;q=1.00-expected_list5]",
"tests/test_acceptparse.py::TestAcceptLanguage::test_parse__valid_header[zh-CN-a-myExt-x-private;q=1.000-expected_list6]",
"tests/test_acceptparse.py::TestAcceptLanguage::test_parse__valid_header[aaaaaaaa-expected_list7]",
"tests/test_acceptparse.py::TestAcceptLanguage::test_parse__valid_header[aaaaaaaa-a-expected_list8]",
"tests/test_acceptparse.py::TestAcceptLanguage::test_parse__valid_header[aaaaaaaa-aaaaaaaa-expected_list9]",
"tests/test_acceptparse.py::TestAcceptLanguage::test_parse__valid_header[a-aaaaaaaa-aaaaaaaa-expected_list10]",
"tests/test_acceptparse.py::TestAcceptLanguage::test_parse__valid_header[aaaaaaaa-a-aaaaaaaa-expected_list11]",
"tests/test_acceptparse.py::TestAcceptLanguage::test_parse__valid_header[zh-Hant;q=0.372,zh-CN-a-myExt-x-private;q=0.977,de,*;q=0.000-expected_list12]",
"tests/test_acceptparse.py::TestAcceptLanguage::test_parse__valid_header[,\\t",
"tests/test_acceptparse.py::TestAcceptLanguage::test_parse__valid_header[foo,bar-expected_list14]",
"tests/test_acceptparse.py::TestAcceptLanguage::test_parse__valid_header[foo,",
"tests/test_acceptparse.py::TestAcceptLanguage::test_parse__valid_header[foo",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___init___invalid_header[]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___init___invalid_header[,",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___init___valid_header",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___add___None",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___add___invalid_value[]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___add___invalid_value[right_operand1]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___add___invalid_value[right_operand2]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___add___invalid_value[right_operand3]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___add___invalid_value[en_gb]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___add___invalid_value[right_operand5]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___add___invalid_value[right_operand6]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___add___invalid_value[right_operand7]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___add___invalid_value[,]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___add___invalid_value[right_operand9]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___add___invalid_value[right_operand10]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___add___invalid_value[right_operand11]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___add___other_type_with_invalid___str__[]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___add___other_type_with_invalid___str__[en_gb]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___add___other_type_with_invalid___str__[,]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___add___valid_value[en-gb;q=0.5,",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___add___valid_value[value1-en-gb;q=0.5,",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___add___valid_value[value2-en-gb;q=0.5,",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___add___valid_value[value3-es,",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___add___other_type_with_valid___str__",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___add___AcceptLanguageValidHeader",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___add___AcceptLanguageNoHeader",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___add___AcceptLanguageInvalidHeader[]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___add___AcceptLanguageInvalidHeader[en_gb]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___add___AcceptLanguageInvalidHeader[,]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___bool__",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___contains___in[*-da]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___contains___in[da-DA]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___contains___in[en-en-gb]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___contains___in[en-gb-en-gb]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___contains___in[en-gb-en]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___contains___in[en-gb-en_GB]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___contains___not_in[en-gb-en-us]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___contains___not_in[en-gb-fr-fr]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___contains___not_in[en-gb-fr]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___contains___not_in[en-fr-fr]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___iter__[fr;q=0,",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___iter__[en-gb,",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___iter__[en-gb;q=0.5,",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___iter__[de;q=0.8,",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___iter__[en-gb;q=0,",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___iter__[de,",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___radd___None",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___radd___invalid_value[]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___radd___invalid_value[left_operand1]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___radd___invalid_value[left_operand2]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___radd___invalid_value[left_operand3]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___radd___invalid_value[en_gb]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___radd___invalid_value[left_operand5]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___radd___invalid_value[left_operand6]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___radd___invalid_value[left_operand7]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___radd___invalid_value[,]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___radd___invalid_value[left_operand9]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___radd___invalid_value[left_operand10]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___radd___invalid_value[left_operand11]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___radd___other_type_with_invalid___str__[]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___radd___other_type_with_invalid___str__[en_gb]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___radd___other_type_with_invalid___str__[,]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___radd___valid_value[en-gb;q=0.5,",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___radd___valid_value[value1-en-gb;q=0.5,",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___radd___valid_value[value2-en-gb;q=0.5,",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___radd___valid_value[value3-es,",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___radd___other_type_with_valid___str__",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___repr__",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test___str__",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test_basic_filtering[de-de-language_tags0-expected_returned0]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test_basic_filtering[a-language_tags1-expected_returned1]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test_basic_filtering[a,",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test_basic_filtering[a-b;q=0.9,",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test_basic_filtering[foO,",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test_basic_filtering[b-c,",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test_basic_filtering[d-e-f-language_tags6-expected_returned6]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test_basic_filtering[a-b-c-d,",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test_basic_filtering[*-language_tags8-expected_returned8]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test_basic_filtering[*;q=0.2,",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test_basic_filtering[a;q=0.5,",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test_basic_filtering[a-b-c;q=0.7,",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test_basic_filtering[a;q=0.7,",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test_basic_filtering[a-language_tags16-expected_returned16]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test_basic_filtering[a-b;q=0.5,",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test_best_match[bar,",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test_best_match[en-gb,",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test_best_match[en-gb;q=0.5,",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test_lookup_default_tag_and_default_cannot_both_be_None",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test_lookup_default_range_cannot_be_asterisk",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test_lookup[aA;q=0.3,",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test_lookup[bB-Cc;q=0.8,",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test_lookup[de-ch-language_tags2-None-default-tag-None-de-CH]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test_lookup[de-ch-language_tags3-None-default-tag-None-de]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test_lookup[zh-Hant-CN-x-private1-private2-language_tags4-None-default-tag-None-zh-Hant-CN-x-private1-private2]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test_lookup[zh-Hant-CN-x-private1-private2-language_tags5-None-default-tag-None-zh-Hant-CN-x-private1]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test_lookup[zh-Hant-CN-x-private1-private2-language_tags6-None-default-tag-None-zh-Hant-CN]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test_lookup[zh-Hant-CN-x-private1-private2-language_tags7-None-default-tag-None-zh-Hant-CN]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test_lookup[zh-Hant-CN-x-private1-private2-language_tags8-None-default-tag-None-zh-Hant]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test_lookup[zh-Hant-CN-x-private1-private2-language_tags9-None-default-tag-None-zh]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test_lookup[zh-Hant-CN-x-private1-private2-language_tags10-None-default-tag-None-default-tag]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test_lookup[AA-T-subtag-language_tags11-None-default-tag-None-aA]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test_lookup[AA-1-subtag-language_tags12-None-default-tag-None-aA]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test_lookup[Aa-P-subtag-8-subtag-language_tags13-None-default-tag-None-aA]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test_lookup[aA-3-subTag-C-subtag-language_tags14-None-default-tag-None-aA]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test_lookup[T-subtag-language_tags15-None-default-tag-None-t-SubTag]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test_lookup[T-subtag-language_tags16-None-default-tag-None-default-tag]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test_lookup[*,",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test_lookup[*-language_tags18-None-default-tag-None-default-tag]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test_lookup[dd,",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test_lookup[aa,",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test_lookup[fr-FR,",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test_lookup[aa-bb,",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test_lookup[aa-language_tags42-None-None-0-0]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test_lookup[Aa,",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test_lookup[aa-language_tags44-None-None-<lambda>-callable",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test_lookup[range-language_tags50-None-default-tag-None-default-tag]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test_lookup[range-language_tags51--default-tag-None-default-tag]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test_lookup[range-language_tags52--default-tag-None-default-tag]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test_lookup[range-language_tags53---None-]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test_lookup[range-language_tags54-default-range--None-]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test_quality[en-gb-en-gb-1]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test_quality[en-gb;q=0.5-en-gb-0.5]",
"tests/test_acceptparse.py::TestAcceptLanguageValidHeader::test_quality[en-gb-sr-Cyrl-None]",
"tests/test_acceptparse.py::TestAcceptLanguageNoHeader::test___init__",
"tests/test_acceptparse.py::TestAcceptLanguageNoHeader::test___add___None",
"tests/test_acceptparse.py::TestAcceptLanguageNoHeader::test___add___invalid_value[]",
"tests/test_acceptparse.py::TestAcceptLanguageNoHeader::test___add___invalid_value[right_operand1]",
"tests/test_acceptparse.py::TestAcceptLanguageNoHeader::test___add___invalid_value[right_operand2]",
"tests/test_acceptparse.py::TestAcceptLanguageNoHeader::test___add___invalid_value[right_operand3]",
"tests/test_acceptparse.py::TestAcceptLanguageNoHeader::test___add___invalid_value[en_gb]",
"tests/test_acceptparse.py::TestAcceptLanguageNoHeader::test___add___invalid_value[right_operand5]",
"tests/test_acceptparse.py::TestAcceptLanguageNoHeader::test___add___invalid_value[right_operand6]",
"tests/test_acceptparse.py::TestAcceptLanguageNoHeader::test___add___invalid_value[right_operand7]",
"tests/test_acceptparse.py::TestAcceptLanguageNoHeader::test___add___other_type_with_invalid___str__[]",
"tests/test_acceptparse.py::TestAcceptLanguageNoHeader::test___add___other_type_with_invalid___str__[en_gb]",
"tests/test_acceptparse.py::TestAcceptLanguageNoHeader::test___add___valid_value[en-gb;q=0.5,",
"tests/test_acceptparse.py::TestAcceptLanguageNoHeader::test___add___valid_value[value1-en-gb;q=0.5,",
"tests/test_acceptparse.py::TestAcceptLanguageNoHeader::test___add___valid_value[value2-en-gb;q=0.5,",
"tests/test_acceptparse.py::TestAcceptLanguageNoHeader::test___add___valid_value[value3-es,",
"tests/test_acceptparse.py::TestAcceptLanguageNoHeader::test___add___other_type_with_valid___str__",
"tests/test_acceptparse.py::TestAcceptLanguageNoHeader::test___add___AcceptLanguageValidHeader",
"tests/test_acceptparse.py::TestAcceptLanguageNoHeader::test___add___AcceptLanguageNoHeader",
"tests/test_acceptparse.py::TestAcceptLanguageNoHeader::test___add___AcceptLanguageInvalidHeader[]",
"tests/test_acceptparse.py::TestAcceptLanguageNoHeader::test___add___AcceptLanguageInvalidHeader[en_gb]",
"tests/test_acceptparse.py::TestAcceptLanguageNoHeader::test___bool__",
"tests/test_acceptparse.py::TestAcceptLanguageNoHeader::test___contains__",
"tests/test_acceptparse.py::TestAcceptLanguageNoHeader::test___iter__",
"tests/test_acceptparse.py::TestAcceptLanguageNoHeader::test___radd___None",
"tests/test_acceptparse.py::TestAcceptLanguageNoHeader::test___radd___invalid_value[]",
"tests/test_acceptparse.py::TestAcceptLanguageNoHeader::test___radd___invalid_value[left_operand1]",
"tests/test_acceptparse.py::TestAcceptLanguageNoHeader::test___radd___invalid_value[left_operand2]",
"tests/test_acceptparse.py::TestAcceptLanguageNoHeader::test___radd___invalid_value[left_operand3]",
"tests/test_acceptparse.py::TestAcceptLanguageNoHeader::test___radd___invalid_value[en_gb]",
"tests/test_acceptparse.py::TestAcceptLanguageNoHeader::test___radd___invalid_value[left_operand5]",
"tests/test_acceptparse.py::TestAcceptLanguageNoHeader::test___radd___invalid_value[left_operand6]",
"tests/test_acceptparse.py::TestAcceptLanguageNoHeader::test___radd___invalid_value[left_operand7]",
"tests/test_acceptparse.py::TestAcceptLanguageNoHeader::test___radd___other_type_with_invalid___str__[]",
"tests/test_acceptparse.py::TestAcceptLanguageNoHeader::test___radd___other_type_with_invalid___str__[en_gb]",
"tests/test_acceptparse.py::TestAcceptLanguageNoHeader::test___radd___other_type_with_invalid___str__[,]",
"tests/test_acceptparse.py::TestAcceptLanguageNoHeader::test___radd___valid_value[en-gb;q=0.5,",
"tests/test_acceptparse.py::TestAcceptLanguageNoHeader::test___radd___valid_value[value1-en-gb;q=0.5,",
"tests/test_acceptparse.py::TestAcceptLanguageNoHeader::test___radd___valid_value[value2-en-gb;q=0.5,",
"tests/test_acceptparse.py::TestAcceptLanguageNoHeader::test___radd___valid_value[value3-es,",
"tests/test_acceptparse.py::TestAcceptLanguageNoHeader::test___radd___other_type_with_valid___str__",
"tests/test_acceptparse.py::TestAcceptLanguageNoHeader::test___repr__",
"tests/test_acceptparse.py::TestAcceptLanguageNoHeader::test___str__",
"tests/test_acceptparse.py::TestAcceptLanguageNoHeader::test_basic_filtering",
"tests/test_acceptparse.py::TestAcceptLanguageNoHeader::test_best_match[offers0-None-foo]",
"tests/test_acceptparse.py::TestAcceptLanguageNoHeader::test_best_match[offers1-None-foo]",
"tests/test_acceptparse.py::TestAcceptLanguageNoHeader::test_best_match[offers2-None-bar]",
"tests/test_acceptparse.py::TestAcceptLanguageNoHeader::test_best_match[offers3-None-bar]",
"tests/test_acceptparse.py::TestAcceptLanguageNoHeader::test_best_match[offers4-default_match4-bar]",
"tests/test_acceptparse.py::TestAcceptLanguageNoHeader::test_best_match[offers5-fallback-fallback]",
"tests/test_acceptparse.py::TestAcceptLanguageNoHeader::test_lookup_default_tag_and_default_cannot_both_be_None",
"tests/test_acceptparse.py::TestAcceptLanguageNoHeader::test_lookup[default-tag-default-default-tag]",
"tests/test_acceptparse.py::TestAcceptLanguageNoHeader::test_lookup[None-0-0]",
"tests/test_acceptparse.py::TestAcceptLanguageNoHeader::test_lookup[None-<lambda>-callable",
"tests/test_acceptparse.py::TestAcceptLanguageNoHeader::test_quality",
"tests/test_acceptparse.py::TestAcceptLanguageInvalidHeader::test___init__",
"tests/test_acceptparse.py::TestAcceptLanguageInvalidHeader::test___add___None",
"tests/test_acceptparse.py::TestAcceptLanguageInvalidHeader::test___add___invalid_value[]",
"tests/test_acceptparse.py::TestAcceptLanguageInvalidHeader::test___add___invalid_value[right_operand1]",
"tests/test_acceptparse.py::TestAcceptLanguageInvalidHeader::test___add___invalid_value[right_operand2]",
"tests/test_acceptparse.py::TestAcceptLanguageInvalidHeader::test___add___invalid_value[right_operand3]",
"tests/test_acceptparse.py::TestAcceptLanguageInvalidHeader::test___add___invalid_value[en_gb]",
"tests/test_acceptparse.py::TestAcceptLanguageInvalidHeader::test___add___invalid_value[right_operand5]",
"tests/test_acceptparse.py::TestAcceptLanguageInvalidHeader::test___add___invalid_value[right_operand6]",
"tests/test_acceptparse.py::TestAcceptLanguageInvalidHeader::test___add___invalid_value[right_operand7]",
"tests/test_acceptparse.py::TestAcceptLanguageInvalidHeader::test___add___other_type_with_invalid___str__[]",
"tests/test_acceptparse.py::TestAcceptLanguageInvalidHeader::test___add___other_type_with_invalid___str__[en_gb]",
"tests/test_acceptparse.py::TestAcceptLanguageInvalidHeader::test___add___valid_header_value[en]",
"tests/test_acceptparse.py::TestAcceptLanguageInvalidHeader::test___add___valid_header_value[value1]",
"tests/test_acceptparse.py::TestAcceptLanguageInvalidHeader::test___add___valid_header_value[value2]",
"tests/test_acceptparse.py::TestAcceptLanguageInvalidHeader::test___add___valid_header_value[value3]",
"tests/test_acceptparse.py::TestAcceptLanguageInvalidHeader::test___add___other_type_valid_header_value",
"tests/test_acceptparse.py::TestAcceptLanguageInvalidHeader::test___add___AcceptLanguageValidHeader",
"tests/test_acceptparse.py::TestAcceptLanguageInvalidHeader::test___add___AcceptLanguageNoHeader",
"tests/test_acceptparse.py::TestAcceptLanguageInvalidHeader::test___add___AcceptLanguageInvalidHeader",
"tests/test_acceptparse.py::TestAcceptLanguageInvalidHeader::test___bool__",
"tests/test_acceptparse.py::TestAcceptLanguageInvalidHeader::test___contains__",
"tests/test_acceptparse.py::TestAcceptLanguageInvalidHeader::test___iter__",
"tests/test_acceptparse.py::TestAcceptLanguageInvalidHeader::test___radd___None",
"tests/test_acceptparse.py::TestAcceptLanguageInvalidHeader::test___radd___invalid_value[]",
"tests/test_acceptparse.py::TestAcceptLanguageInvalidHeader::test___radd___invalid_value[left_operand1]",
"tests/test_acceptparse.py::TestAcceptLanguageInvalidHeader::test___radd___invalid_value[left_operand2]",
"tests/test_acceptparse.py::TestAcceptLanguageInvalidHeader::test___radd___invalid_value[left_operand3]",
"tests/test_acceptparse.py::TestAcceptLanguageInvalidHeader::test___radd___invalid_value[en_gb]",
"tests/test_acceptparse.py::TestAcceptLanguageInvalidHeader::test___radd___invalid_value[left_operand5]",
"tests/test_acceptparse.py::TestAcceptLanguageInvalidHeader::test___radd___invalid_value[left_operand6]",
"tests/test_acceptparse.py::TestAcceptLanguageInvalidHeader::test___radd___invalid_value[left_operand7]",
"tests/test_acceptparse.py::TestAcceptLanguageInvalidHeader::test___radd___other_type_with_invalid___str__[]",
"tests/test_acceptparse.py::TestAcceptLanguageInvalidHeader::test___radd___other_type_with_invalid___str__[en_gb]",
"tests/test_acceptparse.py::TestAcceptLanguageInvalidHeader::test___radd___valid_header_value[en]",
"tests/test_acceptparse.py::TestAcceptLanguageInvalidHeader::test___radd___valid_header_value[value1]",
"tests/test_acceptparse.py::TestAcceptLanguageInvalidHeader::test___radd___valid_header_value[value2]",
"tests/test_acceptparse.py::TestAcceptLanguageInvalidHeader::test___radd___valid_header_value[value3]",
"tests/test_acceptparse.py::TestAcceptLanguageInvalidHeader::test___radd___other_type_valid_header_value",
"tests/test_acceptparse.py::TestAcceptLanguageInvalidHeader::test___repr__",
"tests/test_acceptparse.py::TestAcceptLanguageInvalidHeader::test___str__",
"tests/test_acceptparse.py::TestAcceptLanguageInvalidHeader::test_basic_filtering",
"tests/test_acceptparse.py::TestAcceptLanguageInvalidHeader::test_best_match[offers0-None-foo]",
"tests/test_acceptparse.py::TestAcceptLanguageInvalidHeader::test_best_match[offers1-None-foo]",
"tests/test_acceptparse.py::TestAcceptLanguageInvalidHeader::test_best_match[offers2-None-bar]",
"tests/test_acceptparse.py::TestAcceptLanguageInvalidHeader::test_best_match[offers3-None-bar]",
"tests/test_acceptparse.py::TestAcceptLanguageInvalidHeader::test_best_match[offers4-default_match4-bar]",
"tests/test_acceptparse.py::TestAcceptLanguageInvalidHeader::test_best_match[offers5-fallback-fallback]",
"tests/test_acceptparse.py::TestAcceptLanguageInvalidHeader::test_lookup_default_tag_and_default_cannot_both_be_None",
"tests/test_acceptparse.py::TestAcceptLanguageInvalidHeader::test_lookup[default-tag-default-default-tag]",
"tests/test_acceptparse.py::TestAcceptLanguageInvalidHeader::test_lookup[None-0-0]",
"tests/test_acceptparse.py::TestAcceptLanguageInvalidHeader::test_lookup[None-<lambda>-callable",
"tests/test_acceptparse.py::TestAcceptLanguageInvalidHeader::test_quality",
"tests/test_acceptparse.py::TestCreateAcceptLanguageHeader::test_header_value_is_None",
"tests/test_acceptparse.py::TestCreateAcceptLanguageHeader::test_header_value_is_valid",
"tests/test_acceptparse.py::TestCreateAcceptLanguageHeader::test_header_value_is_invalid[]",
"tests/test_acceptparse.py::TestCreateAcceptLanguageHeader::test_header_value_is_invalid[en_gb]",
"tests/test_acceptparse.py::TestAcceptLanguageProperty::test_fget_header_is_None",
"tests/test_acceptparse.py::TestAcceptLanguageProperty::test_fget_header_is_valid",
"tests/test_acceptparse.py::TestAcceptLanguageProperty::test_fget_header_is_invalid",
"tests/test_acceptparse.py::TestAcceptLanguageProperty::test_fset_value_is_None",
"tests/test_acceptparse.py::TestAcceptLanguageProperty::test_fset_value_is_invalid",
"tests/test_acceptparse.py::TestAcceptLanguageProperty::test_fset_value_is_valid",
"tests/test_acceptparse.py::TestAcceptLanguageProperty::test_fset_value_types[en-gb;q=0.5,",
"tests/test_acceptparse.py::TestAcceptLanguageProperty::test_fset_value_types[value1-en-gb;q=0.5,",
"tests/test_acceptparse.py::TestAcceptLanguageProperty::test_fset_value_types[value2-en-gb;q=0.5,",
"tests/test_acceptparse.py::TestAcceptLanguageProperty::test_fset_value_types[value3-es,",
"tests/test_acceptparse.py::TestAcceptLanguageProperty::test_fset_other_type_with_valid___str__",
"tests/test_acceptparse.py::TestAcceptLanguageProperty::test_fset_AcceptLanguageNoHeader",
"tests/test_acceptparse.py::TestAcceptLanguageProperty::test_fset_AcceptLanguageValidHeader",
"tests/test_acceptparse.py::TestAcceptLanguageProperty::test_fset_AcceptLanguageInvalidHeader",
"tests/test_acceptparse.py::TestAcceptLanguageProperty::test_fdel_header_key_in_environ",
"tests/test_acceptparse.py::TestAcceptLanguageProperty::test_fdel_header_key_not_in_environ",
"tests/test_acceptparse.py::test_MIMEAccept_init_warns",
"tests/test_acceptparse.py::test_MIMEAccept_init",
"tests/test_acceptparse.py::test_MIMEAccept_parse",
"tests/test_acceptparse.py::test_MIMEAccept_accept_html",
"tests/test_acceptparse.py::test_MIMEAccept_contains",
"tests/test_acceptparse.py::test_MIMEAccept_json",
"tests/test_acceptparse.py::test_MIMEAccept_no_raise_invalid",
"tests/test_acceptparse.py::test_MIMEAccept_iter",
"tests/test_acceptparse.py::test_MIMEAccept_str",
"tests/test_acceptparse.py::test_MIMEAccept_add",
"tests/test_acceptparse.py::test_MIMEAccept_radd",
"tests/test_acceptparse.py::test_MIMEAccept_repr",
"tests/test_acceptparse.py::test_MIMEAccept_quality"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2018-09-03T18:45:44Z" | mit |
|
QB3__sparse-ho-67 | diff --git a/doc/api.rst b/doc/api.rst
index 6cde70a..55810a7 100644
--- a/doc/api.rst
+++ b/doc/api.rst
@@ -44,7 +44,7 @@ Criterion
:toctree: generated/
HeldOutMSE
- SmoothedSURE
+ FiniteDiffMonteCarloSure
HeldOutLogistic
diff --git a/sparse_ho/criterion/__init__.py b/sparse_ho/criterion/__init__.py
index 1402e4e..8e96d7e 100644
--- a/sparse_ho/criterion/__init__.py
+++ b/sparse_ho/criterion/__init__.py
@@ -1,11 +1,11 @@
from sparse_ho.criterion.held_out import HeldOutMSE, HeldOutLogistic
from sparse_ho.criterion.cross_val import CrossVal
-from sparse_ho.criterion.sure import SmoothedSURE
+from sparse_ho.criterion.sure import FiniteDiffMonteCarloSure
from sparse_ho.criterion.held_out import HeldOutSmoothedHinge
from sparse_ho.criterion.multiclass_logreg import LogisticMulticlass
__all__ = ['CrossVal',
- 'SmoothedSURE',
+ 'FiniteDiffMonteCarloSure',
'HeldOutMSE',
'HeldOutLogistic',
'HeldOutSmoothedHinge',
diff --git a/sparse_ho/criterion/sure.py b/sparse_ho/criterion/sure.py
index 3719b75..980ad11 100644
--- a/sparse_ho/criterion/sure.py
+++ b/sparse_ho/criterion/sure.py
@@ -5,7 +5,7 @@ from sparse_ho.algo.forward import get_beta_jac_iterdiff
from sparse_ho.criterion.base import BaseCriterion
-class SmoothedSURE(BaseCriterion):
+class FiniteDiffMonteCarloSure(BaseCriterion):
"""Smoothed version of the Stein Unbiased Risk Estimator (SURE).
Implements the iterative Finite-Difference Monte-Carlo approximation of the
| QB3/sparse-ho | 59197a06f2ba62b4fd67b9d8950dc62674eed2a1 | diff --git a/sparse_ho/tests/test_grad_search.py b/sparse_ho/tests/test_grad_search.py
index 492c04b..a8537f7 100644
--- a/sparse_ho/tests/test_grad_search.py
+++ b/sparse_ho/tests/test_grad_search.py
@@ -10,7 +10,7 @@ from sparse_ho.models import Lasso
from sparse_ho import Forward
from sparse_ho import ImplicitForward
from sparse_ho import Implicit
-from sparse_ho.criterion import HeldOutMSE, SmoothedSURE
+from sparse_ho.criterion import HeldOutMSE, FiniteDiffMonteCarloSure
from sparse_ho.ho import grad_search
from sparse_ho.optimizers import LineSearch
@@ -64,7 +64,7 @@ def test_grad_search(model, crit):
criterion = HeldOutMSE(idx_train, idx_val)
else:
n_outer = 2
- criterion = SmoothedSURE(sigma_star)
+ criterion = FiniteDiffMonteCarloSure(sigma_star)
# TODO MM@QBE if else scheme surprising
criterion = HeldOutMSE(idx_train, idx_val)
diff --git a/sparse_ho/tests/test_grid_search.py b/sparse_ho/tests/test_grid_search.py
index 2e1d6c6..4df0ff7 100644
--- a/sparse_ho/tests/test_grid_search.py
+++ b/sparse_ho/tests/test_grid_search.py
@@ -6,7 +6,7 @@ from sparse_ho.utils import Monitor
from sparse_ho.datasets import get_synt_data
from sparse_ho.models import Lasso
from sparse_ho import Forward
-from sparse_ho.criterion import HeldOutMSE, SmoothedSURE
+from sparse_ho.criterion import HeldOutMSE, FiniteDiffMonteCarloSure
from sparse_ho.grid_search import grid_search
@@ -69,7 +69,7 @@ def test_grid_search():
monitor_grid = Monitor()
model = Lasso(estimator=estimator)
- criterion = SmoothedSURE(sigma=sigma_star)
+ criterion = FiniteDiffMonteCarloSure(sigma=sigma_star)
algo = Forward()
log_alpha_opt_grid, _ = grid_search(
algo, criterion, model, X, y, log_alpha_min, log_alpha_max,
@@ -77,7 +77,7 @@ def test_grid_search():
tol=1e-5, samp="grid")
monitor_random = Monitor()
- criterion = SmoothedSURE(sigma=sigma_star)
+ criterion = FiniteDiffMonteCarloSure(sigma=sigma_star)
algo = Forward()
log_alpha_opt_random, _ = grid_search(
algo, criterion, model, X, y, log_alpha_min, log_alpha_max,
diff --git a/sparse_ho/tests/test_lasso.py b/sparse_ho/tests/test_lasso.py
index 8852e2d..8553435 100644
--- a/sparse_ho/tests/test_lasso.py
+++ b/sparse_ho/tests/test_lasso.py
@@ -13,7 +13,7 @@ from sparse_ho import Forward
from sparse_ho import ImplicitForward
from sparse_ho import Implicit
from sparse_ho import Backward
-from sparse_ho.criterion import HeldOutMSE, SmoothedSURE
+from sparse_ho.criterion import HeldOutMSE, FiniteDiffMonteCarloSure
n_samples = 100
n_features = 100
@@ -160,22 +160,22 @@ def test_val_grad():
for key in models.keys():
log_alpha = dict_log_alpha[key]
model = models[key]
- criterion = SmoothedSURE(sigma_star)
+ criterion = FiniteDiffMonteCarloSure(sigma_star)
algo = Forward()
val_fwd, grad_fwd = criterion.get_val_grad(
model, X, y, log_alpha, algo.get_beta_jac_v, tol=tol)
- criterion = SmoothedSURE(sigma_star)
+ criterion = FiniteDiffMonteCarloSure(sigma_star)
algo = ImplicitForward(tol_jac=1e-8, n_iter_jac=5000)
val_imp_fwd, grad_imp_fwd = criterion.get_val_grad(
model, X, y, log_alpha, algo.get_beta_jac_v, tol=tol)
- criterion = SmoothedSURE(sigma_star)
+ criterion = FiniteDiffMonteCarloSure(sigma_star)
algo = Implicit(criterion)
val_imp, grad_imp = criterion.get_val_grad(
model, X, y, log_alpha, algo.get_beta_jac_v, tol=tol)
- criterion = SmoothedSURE(sigma_star)
+ criterion = FiniteDiffMonteCarloSure(sigma_star)
algo = Backward()
val_bwd, grad_bwd = criterion.get_val_grad(
model, X, y, log_alpha, algo.get_beta_jac_v, tol=tol)
| SURE naming / API / generalization
Consider renaming `SURE` to something more in adequation with the
implementation. The current implementation follows [(Figure 3, Deledalle et al. 2020)](https://samuelvaiter.com/publications/deledalle2014sugar.pdf) by
implementing a smoothed version using Finite Difference Monte Carlo (FDMC)
method. A user testing the class might be confused to see that in low dimension,
a SURE implemented manually does not provide the same value as our `SURE` class.
I believe there is three possible options:
1. _Keep the current name._ This is probably the best way to not confuse people
not familiar with the SURE. But in this case the documentation should reflect
precisely why a user could observe a difference with a handcraft SURE.
2. _Change the name to one relevant to the litterature._ The more exact would be
to use `FdmcSure` but this is a bit obscure for people and
`FiniteDifferenceMonteCarloSure` maybe too explicit. Another option is to use
SUGAR as it is easy to search. The issue is that SUGAR relates to the
gradient of the criterion, which could be also confusing.
3. _Change the name to something clearer._ Maybe a `Smooth[ed]Sure` could be a
candidate, but this is not a terminology which appears in papers.
### Parameters
- I don't understand why `SURE` takes `X_test` and `X_test` as parameters.
- Regarding `C` and `gamma_sure`. I believe it is not useful to expose them as
parameters. Either the user does not want to play with it and two optional
parameters are too much, or he really wants to control the finite difference
step and it would be easier to directly access the member `epsilon`. The power
law is advocated in the SUGAR paper, but different strategies could be used.
### Generalised SURE
It does not seem to be a priority, but this class could implements
generalization of the SURE to approximate the prediction risk and/or estimation
risk depending on the properties of `X`, which could be of interest for some use
(imaging for instance).
WDYT? | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"sparse_ho/tests/test_grid_search.py::test_grid_search"
] | [] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2021-01-11T11:34:40Z" | bsd-3-clause |
|
QualiSystemsLab__colony-cli-37 | diff --git a/colony/branch_utils.py b/colony/branch_utils.py
index 6487cc6..4d84c1b 100644
--- a/colony/branch_utils.py
+++ b/colony/branch_utils.py
@@ -66,10 +66,8 @@ def figure_out_branches(user_defined_branch, blueprint_name):
except BadBlueprintRepo as e:
working_branch = None
- logger.warning(
- f"Branch could not be identified/used from the working directory; "
- f"reason: {e}. The Blueprints Repository branch attached to Colony Space will be used"
- )
+ logger.error(f"Branch could not be identified/used from the working directory; reason: {e}.")
+ success = False
# Checking if:
# 1) User has specified not use local (specified a branch)
@@ -88,7 +86,7 @@ def figure_out_branches(user_defined_branch, blueprint_name):
f"(This shall include any uncommitted changes but and/or untracked files)"
)
except Exception as e:
- logger.warning(f"Was not able push your latest changes to temp branch for validation. Reason: {str(e)}")
+ logger.error(f"Was not able push your latest changes to temp branch for validation. Reason: {str(e)}")
success = False
return repo, working_branch, temp_working_branch, stashed_flag, success
diff --git a/colony/utils.py b/colony/utils.py
index f91064f..5fa3675 100644
--- a/colony/utils.py
+++ b/colony/utils.py
@@ -24,6 +24,9 @@ class BlueprintRepo(Repo):
if self.bare:
raise BadBlueprintRepo("Cannot get folder tree structure. Repo is bare")
+ if not self.remotes:
+ raise BadBlueprintRepo("Local repository not connected to the remote space repository")
+
self.blueprints = self._fetch_blueprints_list()
def repo_has_blueprint(self, blueprint_name) -> bool:
@@ -34,21 +37,19 @@ class BlueprintRepo(Repo):
return self.head.is_detached
def current_branch_exists_on_remote(self) -> bool:
- try:
- local_branch_name = self.active_branch.name
- remote_branches = self._get_remote_branches_names()
- return local_branch_name in remote_branches
- except Exception as e:
- logger.error(f"Failed to get remote branches names: {str(e)}")
- return False
+ local_branch_name = self.active_branch.name
+ remote_branches = self._get_remote_branches_names()
+ return local_branch_name in remote_branches
def is_current_branch_synced(self) -> bool:
"""Check if last commit in local and remote branch is the same"""
local_branch = self.active_branch
+ if local_branch.name not in self._get_remote_branches_names():
+ return False
+
for remote in self.remote().refs:
if local_branch.name == remote.remote_head:
return local_branch.commit.__eq__(remote.commit)
- return False
# (TODO:ddovbii): must be moved to separated class (BlueprintYamlHandler or smth)
def get_blueprint_artifacts(self, blueprint_name: str) -> dict:
@@ -108,7 +109,10 @@ class BlueprintRepo(Repo):
return bps
def _get_remote_branches_names(self):
- return [ref.remote_head for ref in self.remote().refs]
+ if self.remotes:
+ return [ref.remote_head for ref in self.remote().refs]
+ else:
+ return []
def get_active_branch(self) -> str:
return self._active_branch
diff --git a/version.txt b/version.txt
index c4fb769..192def2 100644
--- a/version.txt
+++ b/version.txt
@@ -1,1 +1,1 @@
-1.2.10-beta
+1.2.11-beta
| QualiSystemsLab/colony-cli | a4dc8a364832163bf66b7af2442473a61dca3c29 | diff --git a/tests/test_utils.py b/tests/test_utils.py
index 1bd49dc..475fc82 100644
--- a/tests/test_utils.py
+++ b/tests/test_utils.py
@@ -73,13 +73,25 @@ class TestBlueprintRepo(unittest.TestCase):
Repo.init(wrong_dir, bare=True)
self.assertRaises(BadBlueprintRepo, BlueprintRepo, wrong_dir)
+ def test_raise_on_repo_without_blueprints_dir(self):
+ with tempfile.TemporaryDirectory() as temp_dir:
+ Repo.init(temp_dir)
+ self.assertRaises(BadBlueprintRepo, BlueprintRepo, temp_dir)
+
+ def test_raise_on_repo_without_remotes(self):
+ with tempfile.TemporaryDirectory() as temp_dir:
+ Repo.init(temp_dir)
+ os.mkdir(f"{temp_dir}/blueprints")
+ self.assertRaises(BadBlueprintRepo, BlueprintRepo, temp_dir)
+
def test_has_remote_branch(self):
self.assertTrue(self.bp_repo.current_branch_exists_on_remote())
def test_no_branch_on_remote(self):
local_branch = "my_super_branch"
- current = self.bp_repo.create_head(local_branch)
- current.checkout()
+ new_branch = self.bp_repo.create_head(local_branch)
+ assert self.bp_repo.active_branch != new_branch
+ new_branch.checkout()
self.assertFalse(self.bp_repo.current_branch_exists_on_remote())
def test_is_synced(self):
| If remote branch is not configured, received unhandled exception
STR:
Initialize git repo locally and develop a blueprint, don't connect to remote repo yet, try to use bp validate.
Expected behavior: Message "Local repository not connected to the remote space repository"
Error:
PS C:\Users\ronid\projects\clitest\blueprints> colony bp validate test
Traceback (most recent call last):
File "c:\users\ronid\appdata\local\programs\python\python39\lib\runpy.py", line 197, in _run_module_as_main
return _run_code(code, main_globals, None,
File "c:\users\ronid\appdata\local\programs\python\python39\lib\runpy.py", line 87, in _run_code
exec(code, run_globals)
File "C:\Users\ronid\AppData\Local\Programs\Python\Python39\Scripts\colony.exe\__main__.py", line 7, in <module>
File "c:\users\ronid\appdata\local\programs\python\python39\lib\site-packages\colony\shell.py", line 96, in main
command.execute()
File "c:\users\ronid\appdata\local\programs\python\python39\lib\site-packages\colony\commands\base.py", line 38, in execute
actions_table[action]()
File "c:\users\ronid\appdata\local\programs\python\python39\lib\site-packages\colony\commands\bp.py", line 44, in do_validate
repo, working_branch, temp_working_branch = figure_out_branches(branch, blueprint_name)
File "c:\users\ronid\appdata\local\programs\python\python39\lib\site-packages\colony\branch_utils.py", line 66, in figure_out_branches
examine_blueprint_working_branch(repo, blueprint_name=blueprint_name)
File "c:\users\ronid\appdata\local\programs\python\python39\lib\site-packages\colony\branch_utils.py", line 28, in examine_blueprint_working_branch
if not repo.current_branch_exists_on_remote():
File "c:\users\ronid\appdata\local\programs\python\python39\lib\site-packages\colony\utils.py", line 38, in current_branch_exists_on_remote
remote_branches = self._get_remote_branches_names()
File "c:\users\ronid\appdata\local\programs\python\python39\lib\site-packages\colony\utils.py", line 108, in _get_remote_branches_names
return [ref.remote_head for ref in self.remote().refs]
File "c:\users\ronid\appdata\local\programs\python\python39\lib\site-packages\git\repo\base.py", line 325, in remote
r = Remote(self, name)
File "c:\users\ronid\appdata\local\programs\python\python39\lib\site-packages\git\remote.py", line 418, in __init__
dir(self)
File "c:\users\ronid\appdata\local\programs\python\python39\lib\site-packages\git\remote.py", line 430, in __getattr__
return self._config_reader.get(attr)
File "c:\users\ronid\appdata\local\programs\python\python39\lib\site-packages\git\config.py", line 127, in <lambda>
return lambda *args, **kwargs: self._call_config(attr, *args, **kwargs)
File "c:\users\ronid\appdata\local\programs\python\python39\lib\site-packages\git\config.py", line 133, in _call_config
return getattr(self._config, method)(self._section_name, *args, **kwargs)
File "c:\users\ronid\appdata\local\programs\python\python39\lib\site-packages\git\config.py", line 82, in assure_data_present
return func(self, *args, **kwargs)
File "c:\users\ronid\appdata\local\programs\python\python39\lib\configparser.py", line 781, in get
d = self._unify_values(section, vars)
File "c:\users\ronid\appdata\local\programs\python\python39\lib\configparser.py", line 1149, in _unify_values
raise NoSectionError(section) from None
configparser.NoSectionError: No section: 'remote "origin"' | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_utils.py::TestBlueprintRepo::test_raise_on_repo_without_remotes"
] | [
"tests/test_utils.py::TestParseParamString::test_is_result_dict",
"tests/test_utils.py::TestParseParamString::test_raise_exception_on_colon",
"tests/test_utils.py::TestParseParamString::test_raise_exception_on_space_del",
"tests/test_utils.py::TestParseParamString::test_return_empty_dict",
"tests/test_utils.py::TestParseParamString::test_trailing_spaces",
"tests/test_utils.py::TestBlueprintRepo::test_blueprint_repo_has_blueprints",
"tests/test_utils.py::TestBlueprintRepo::test_create_repo_from_non_git_dir",
"tests/test_utils.py::TestBlueprintRepo::test_has_blueprint",
"tests/test_utils.py::TestBlueprintRepo::test_has_non_existing_blueprint",
"tests/test_utils.py::TestBlueprintRepo::test_has_remote_branch",
"tests/test_utils.py::TestBlueprintRepo::test_is_synced",
"tests/test_utils.py::TestBlueprintRepo::test_no_branch_on_remote",
"tests/test_utils.py::TestBlueprintRepo::test_raise_on_bare_repo",
"tests/test_utils.py::TestBlueprintRepo::test_raise_on_repo_without_blueprints_dir",
"tests/test_utils.py::TestBlueprintRepo::test_repo_not_synced"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
} | "2021-03-19T18:12:44Z" | apache-2.0 |
|
QualiSystems__cloudshell-networking-juniper-48 | diff --git a/.gitignore b/.gitignore
index 4d86431..a1ea7c8 100644
--- a/.gitignore
+++ b/.gitignore
@@ -63,3 +63,5 @@ target/
.pypirc
.DS_Store
+
+.idea/
diff --git a/cloudshell/networking/juniper/autoload/juniper_snmp_autoload.py b/cloudshell/networking/juniper/autoload/juniper_snmp_autoload.py
index aea017e..30f6513 100755
--- a/cloudshell/networking/juniper/autoload/juniper_snmp_autoload.py
+++ b/cloudshell/networking/juniper/autoload/juniper_snmp_autoload.py
@@ -294,7 +294,7 @@ class JuniperSnmpAutoload(object):
model = ''
os_version = ''
sys_obj_id = self.snmp_handler.get_property('SNMPv2-MIB', 'sysObjectID', 0)
- model_search = re.search('^(?P<vendor>\w+)-\S+jnxProductName(?P<model>\S+)', sys_obj_id)
+ model_search = re.search('^(?P<vendor>\w+)-\S+jnxProduct(?:Name)?(?P<model>\S+)', sys_obj_id)
if model_search:
vendor = model_search.groupdict()['vendor'].capitalize()
model = model_search.groupdict()['model']
diff --git a/version.txt b/version.txt
index 2d2d681..30b26df 100644
--- a/version.txt
+++ b/version.txt
@@ -1,1 +1,1 @@
-4.0.10
+4.0.11
| QualiSystems/cloudshell-networking-juniper | 118ac36e83190764bb65ded2c431aa129451687c | diff --git a/tests/networking/juniper/autoload/test_juniper_snmp_autoload.py b/tests/networking/juniper/autoload/test_juniper_snmp_autoload.py
index e80ff56..9d4baa1 100644
--- a/tests/networking/juniper/autoload/test_juniper_snmp_autoload.py
+++ b/tests/networking/juniper/autoload/test_juniper_snmp_autoload.py
@@ -159,6 +159,34 @@ class TestJuniperSnmpAutoload(TestCase):
call('SNMPv2-MIB', 'sysLocation', '0')]
self._snmp_handler.get_property.assert_has_calls(calls)
+ def test_build_root2(self):
+ vendor = 'Test_Vendor'
+ model = 'Tets_Model'
+ version = '12.1R6.5'
+ contact_name = Mock()
+ system_name = Mock()
+ location = Mock()
+ self._snmp_handler.get_property.side_effect = [
+ "{0}-testjnxProduct{1}".format(vendor, model),
+ "TEst JUNOS {} #/test".format(version),
+ contact_name,
+ system_name,
+ location
+ ]
+
+ self._autoload_operations_instance._build_root()
+
+ self.assertIs(self._autoload_operations_instance.resource.contact_name, contact_name)
+ self.assertIs(self._autoload_operations_instance.resource.system_name, system_name)
+ self.assertIs(self._autoload_operations_instance.resource.location, location)
+ self.assertEqual(self._resource.os_version, version)
+ self.assertEqual(self._resource.vendor, vendor.capitalize())
+ self.assertEqual(self._resource.model, model)
+ calls = [call('SNMPv2-MIB', 'sysObjectID', 0), call('SNMPv2-MIB', 'sysDescr', '0'),
+ call('SNMPv2-MIB', 'sysContact', '0'), call('SNMPv2-MIB', 'sysName', '0'),
+ call('SNMPv2-MIB', 'sysLocation', '0')]
+ self._snmp_handler.get_property.assert_has_calls(calls)
+
def test_get_content_indexes(self):
index1 = 1
index2 = 2
| Vendor and Model attributes sometimes empty
In some cases, vendor and Model attributes are empty during the autoload. For example when sysObjectID = jnxProductQFX520032C32Q. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/networking/juniper/autoload/test_juniper_snmp_autoload.py::TestJuniperSnmpAutoload::test_build_root2"
] | [
"tests/networking/juniper/autoload/test_juniper_snmp_autoload.py::TestJuniperSnmpAutoload::test_build_root",
"tests/networking/juniper/autoload/test_juniper_snmp_autoload.py::TestJuniperSnmpAutoload::test_ipv4_table_prop",
"tests/networking/juniper/autoload/test_juniper_snmp_autoload.py::TestJuniperSnmpAutoload::test_initialize_snmp_handler",
"tests/networking/juniper/autoload/test_juniper_snmp_autoload.py::TestJuniperSnmpAutoload::test_logger_property",
"tests/networking/juniper/autoload/test_juniper_snmp_autoload.py::TestJuniperSnmpAutoload::test_init",
"tests/networking/juniper/autoload/test_juniper_snmp_autoload.py::TestJuniperSnmpAutoload::test_snm_handler_property",
"tests/networking/juniper/autoload/test_juniper_snmp_autoload.py::TestJuniperSnmpAutoload::test_discover",
"tests/networking/juniper/autoload/test_juniper_snmp_autoload.py::TestJuniperSnmpAutoload::test_content_indexes_prop",
"tests/networking/juniper/autoload/test_juniper_snmp_autoload.py::TestJuniperSnmpAutoload::test_if_indexes",
"tests/networking/juniper/autoload/test_juniper_snmp_autoload.py::TestJuniperSnmpAutoload::test_lldp_keys_prop",
"tests/networking/juniper/autoload/test_juniper_snmp_autoload.py::TestJuniperSnmpAutoload::test_ipv6_table_prop"
] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2018-07-20T15:20:13Z" | apache-2.0 |
|
QuantStack__py2vega-25 | diff --git a/py2vega/main.py b/py2vega/main.py
index fa865dd..d00a21a 100644
--- a/py2vega/main.py
+++ b/py2vega/main.py
@@ -21,6 +21,10 @@ operator_mapping = {
}
+class Py2VegaSyntaxError(SyntaxError):
+ pass
+
+
def check_validity(nodes, origin_node):
"""Check whether or not a list of nodes is valid.
@@ -30,16 +34,16 @@ def check_validity(nodes, origin_node):
- everything but the last element is not an `if` statement or a `return` statement
"""
if len(nodes) == 0:
- raise RuntimeError(
+ raise Py2VegaSyntaxError(
'A `{}` node body must contain at least one `if` statement or one `return` statement'.format(
origin_node.__class__.__name__))
for node in nodes[:-1]:
if isinstance(node, ast.If) or isinstance(node, ast.Return):
- raise RuntimeError(
+ raise Py2VegaSyntaxError(
'A `{}` node body cannot contain an `if` or `return` statement if it is not the last element of the body'.format(
origin_node.__class__.__name__))
if not isinstance(nodes[-1], ast.If) and not isinstance(nodes[-1], ast.Return):
- raise RuntimeError(
+ raise Py2VegaSyntaxError(
'The last element of a `{}` node body must be an `if` or `return` statement, but a value of {} was found'.format(
origin_node.__class__.__name__, nodes[-1].__class__.__name__))
@@ -53,7 +57,7 @@ class VegaExpressionVisitor(ast.NodeVisitor):
def generic_visit(self, node):
"""Throwing an error by default."""
- raise RuntimeError('Unsupported {} node, only a subset of Python is supported'.format(node.__class__.__name__))
+ raise Py2VegaSyntaxError('Unsupported {} node, only a subset of Python is supported'.format(node.__class__.__name__))
def visit_Return(self, node):
"""Turn a Python return statement into a Vega-expression."""
@@ -124,7 +128,7 @@ class VegaExpressionVisitor(ast.NodeVisitor):
for target in node.targets:
if not isinstance(target, ast.Name):
- raise RuntimeError('Unsupported target {} for the assignment'.format(target.__class__.__name__))
+ raise Py2VegaSyntaxError('Unsupported target {} for the assignment'.format(target.__class__.__name__))
self.scope[target.id] = value
@@ -140,7 +144,7 @@ class VegaExpressionVisitor(ast.NodeVisitor):
if isinstance(node.op, ast.UAdd):
return '+{}'.format(self.visit(node.operand))
- raise RuntimeError('Unsupported {} operator, only a subset of Python is supported'.format(node.op.__class__.__name__))
+ raise Py2VegaSyntaxError('Unsupported {} operator, only a subset of Python is supported'.format(node.op.__class__.__name__))
def visit_BoolOp(self, node):
"""Turn a Python boolop expression into a Vega-expression."""
@@ -164,7 +168,7 @@ class VegaExpressionVisitor(ast.NodeVisitor):
operator = operator_mapping.get(op.__class__)
if operator is None:
- raise RuntimeError('Unsupported {} operator, only a subset of Python is supported'.format(op.__class__.__name__))
+ raise Py2VegaSyntaxError('Unsupported {} operator, only a subset of Python is supported'.format(op.__class__.__name__))
return '{} {} {}'.format(left, operator, right)
| QuantStack/py2vega | 4f892d5d9144f714522c6c7c2e88490652d89af5 | diff --git a/test/test_py2vega.py b/test/test_py2vega.py
index 677a018..ea54940 100644
--- a/test/test_py2vega.py
+++ b/test/test_py2vega.py
@@ -1,6 +1,7 @@
import pytest
from py2vega import py2vega
+from py2vega.main import Py2VegaSyntaxError
from py2vega.functions.math import isNaN
whitelist = ['value', 'x', 'y', 'height', 'width', 'row', 'column']
@@ -142,22 +143,22 @@ def invalid_func4(value):
def test_invalid1():
- with pytest.raises(RuntimeError):
+ with pytest.raises(Py2VegaSyntaxError):
py2vega(invalid_func1)
def test_invalid2():
- with pytest.raises(RuntimeError, match='A `FunctionDef` node body cannot contain an `if` or `return` statement if it is not the last element of the body'):
+ with pytest.raises(Py2VegaSyntaxError, match='A `FunctionDef` node body cannot contain an `if` or `return` statement if it is not the last element of the body'):
py2vega(invalid_func2)
def test_invalid3():
- with pytest.raises(RuntimeError, match='A `FunctionDef` node body cannot contain an `if` or `return` statement if it is not the last element of the body'):
+ with pytest.raises(Py2VegaSyntaxError, match='A `FunctionDef` node body cannot contain an `if` or `return` statement if it is not the last element of the body'):
py2vega(invalid_func3)
def test_invalid4():
- with pytest.raises(RuntimeError, match='A `If` node body cannot contain an `if` or `return` statement if it is not the last element of the body'):
+ with pytest.raises(Py2VegaSyntaxError, match='A `If` node body cannot contain an `if` or `return` statement if it is not the last element of the body'):
py2vega(invalid_func4)
| Use SyntaxError instead of RuntimeError
As pointed out by @serge-sans-paille, it might be better to use SyntaxError or a custom Py2VegaSyntaxError class instead of RuntimeError | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/test_py2vega.py::test_nameconstant",
"test/test_py2vega.py::test_num",
"test/test_py2vega.py::test_str",
"test/test_py2vega.py::test_tuple",
"test/test_py2vega.py::test_list",
"test/test_py2vega.py::test_dict",
"test/test_py2vega.py::test_unary",
"test/test_py2vega.py::test_binary",
"test/test_py2vega.py::test_ternary",
"test/test_py2vega.py::test_compare",
"test/test_py2vega.py::test_function",
"test/test_py2vega.py::test_whitelist",
"test/test_py2vega.py::test_math",
"test/test_py2vega.py::test_invalid1",
"test/test_py2vega.py::test_invalid2",
"test/test_py2vega.py::test_invalid3",
"test/test_py2vega.py::test_invalid4",
"test/test_py2vega.py::test_lambda",
"test/test_py2vega.py::test_if_stmt",
"test/test_py2vega.py::test_assign1",
"test/test_py2vega.py::test_assign2",
"test/test_py2vega.py::test_assign3",
"test/test_py2vega.py::test_assign4",
"test/test_py2vega.py::test_assign5",
"test/test_py2vega.py::test_assign6",
"test/test_py2vega.py::test_assign7",
"test/test_py2vega.py::test_assign8",
"test/test_py2vega.py::test_assign9"
] | [] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
} | "2019-08-27T09:00:14Z" | bsd-3-clause |
|
QuantStack__py2vega-29 | diff --git a/py2vega/main.py b/py2vega/main.py
index d00a21a..f153309 100644
--- a/py2vega/main.py
+++ b/py2vega/main.py
@@ -20,6 +20,16 @@ operator_mapping = {
ast.Mod: '%'
}
+# Note that built-in functions like `abs`, `min`, `max` which already have an equivalent in
+# Vega expressions are already supported automatically
+builtin_function_mapping = {
+ 'bool': '(isValid({args}) ? toBoolean({args}) : false)',
+ 'float': 'toNumber({args})',
+ 'int': 'floor(toNumber({args}))',
+ 'len': 'length({args})',
+ 'str': 'toString({args})'
+}
+
class Py2VegaSyntaxError(SyntaxError):
pass
@@ -220,11 +230,13 @@ class VegaExpressionVisitor(ast.NodeVisitor):
if isinstance(node.func, ast.Attribute):
func_name = node.func.attr
+ args = ', '.join([self.visit(arg) for arg in node.args])
+
+ if func_name in builtin_function_mapping:
+ return builtin_function_mapping[func_name].format(args=args)
+
if func_name in vega_functions:
- return '{}({})'.format(
- func_name,
- ', '.join([self.visit(arg) for arg in node.args])
- )
+ return '{func_name}({args})'.format(func_name=func_name, args=args)
raise NameError('name \'{}\' is not defined, only a subset of Python is supported'.format(func_name))
| QuantStack/py2vega | 207593c5e81f948d02e24f72d2d12cff2434ebcb | diff --git a/test/test_py2vega.py b/test/test_py2vega.py
index ea54940..4fbbb57 100644
--- a/test/test_py2vega.py
+++ b/test/test_py2vega.py
@@ -93,6 +93,35 @@ def test_compare():
assert py2vega(code, whitelist) == '(indexof(value, \'chevrolet\') == -1)'
+def test_call():
+ code = 'toBoolean(3)'
+ assert py2vega(code, whitelist) == 'toBoolean(3)'
+
+ code = 'bool(3)'
+ assert py2vega(code, whitelist) == '(isValid(3) ? toBoolean(3) : false)'
+
+ code = 'toString(3)'
+ assert py2vega(code, whitelist) == 'toString(3)'
+
+ code = 'str(3)'
+ assert py2vega(code, whitelist) == 'toString(3)'
+
+ code = 'toNumber("3")'
+ assert py2vega(code, whitelist) == 'toNumber(\'3\')'
+
+ code = 'float("3")'
+ assert py2vega(code, whitelist) == 'toNumber(\'3\')'
+
+ code = 'int("3")'
+ assert py2vega(code, whitelist) == 'floor(toNumber(\'3\'))'
+
+ code = 'length(value)'
+ assert py2vega(code, whitelist) == 'length(value)'
+
+ code = 'len(value)'
+ assert py2vega(code, whitelist) == 'length(value)'
+
+
def foo(value):
return 'red' if value < 150 else 'green'
| Built-in functions
The Python built-in `len` function could be mapped to the Vega `length` function
The Python built-in `slice` function could be mapped to the Vega `slice` function
The Python built-in `str` function could be mapped to the Vega `toString` function
... | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/test_py2vega.py::test_call"
] | [
"test/test_py2vega.py::test_nameconstant",
"test/test_py2vega.py::test_num",
"test/test_py2vega.py::test_str",
"test/test_py2vega.py::test_tuple",
"test/test_py2vega.py::test_list",
"test/test_py2vega.py::test_dict",
"test/test_py2vega.py::test_unary",
"test/test_py2vega.py::test_binary",
"test/test_py2vega.py::test_ternary",
"test/test_py2vega.py::test_compare",
"test/test_py2vega.py::test_function",
"test/test_py2vega.py::test_whitelist",
"test/test_py2vega.py::test_math",
"test/test_py2vega.py::test_invalid1",
"test/test_py2vega.py::test_invalid2",
"test/test_py2vega.py::test_invalid3",
"test/test_py2vega.py::test_invalid4",
"test/test_py2vega.py::test_lambda",
"test/test_py2vega.py::test_if_stmt",
"test/test_py2vega.py::test_assign1",
"test/test_py2vega.py::test_assign2",
"test/test_py2vega.py::test_assign3",
"test/test_py2vega.py::test_assign4",
"test/test_py2vega.py::test_assign5",
"test/test_py2vega.py::test_assign6",
"test/test_py2vega.py::test_assign7",
"test/test_py2vega.py::test_assign8",
"test/test_py2vega.py::test_assign9"
] | {
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
} | "2019-08-28T08:55:32Z" | bsd-3-clause |
|
RDFLib__rdflib-1012 | diff --git a/rdflib/plugins/parsers/notation3.py b/rdflib/plugins/parsers/notation3.py
index 4b6ff5d1..c57f5bcf 100755
--- a/rdflib/plugins/parsers/notation3.py
+++ b/rdflib/plugins/parsers/notation3.py
@@ -349,9 +349,7 @@ ws = re.compile(r'[ \t]*') # Whitespace not including NL
signed_integer = re.compile(r'[-+]?[0-9]+') # integer
integer_syntax = re.compile(r'[-+]?[0-9]+')
decimal_syntax = re.compile(r'[-+]?[0-9]*\.[0-9]+')
-exponent_syntax = re.compile(r'[-+]?(?:[0-9]+\.[0-9]*(?:e|E)[-+]?[0-9]+|'+
- r'\.[0-9](?:e|E)[-+]?[0-9]+|'+
- r'[0-9]+(?:e|E)[-+]?[0-9]+)')
+exponent_syntax = re.compile(r'[-+]?(?:[0-9]+\.[0-9]*|\.[0-9]+|[0-9]+)(?:e|E)[-+]?[0-9]+')
digitstring = re.compile(r'[0-9]+') # Unsigned integer
interesting = re.compile(r"""[\\\r\n\"\']""")
langcode = re.compile(r'[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*')
diff --git a/setup.py b/setup.py
index d10513be..d611fe45 100644
--- a/setup.py
+++ b/setup.py
@@ -6,11 +6,12 @@ from setuptools import setup, find_packages
kwargs = {}
kwargs['install_requires'] = [ 'six', 'isodate', 'pyparsing']
-kwargs['tests_require'] = ['html5lib', 'networkx']
+kwargs['tests_require'] = ['html5lib', 'networkx', 'nose', 'doctest-ignore-unicode']
kwargs['test_suite'] = "nose.collector"
kwargs['extras_require'] = {
'html': ['html5lib'],
'sparql': ['requests'],
+ 'tests': kwargs['tests_require'],
'docs': ['sphinx < 3', 'sphinxcontrib-apidoc']
}
| RDFLib/rdflib | 39d07c4a5c9395f1322a269982e69b63cbf4db22 | diff --git a/test/test_n3.py b/test/test_n3.py
index 5d447732..5cdc74b5 100644
--- a/test/test_n3.py
+++ b/test/test_n3.py
@@ -1,7 +1,8 @@
from rdflib.graph import Graph, ConjunctiveGraph
import unittest
from rdflib.term import Literal, URIRef
-from rdflib.plugins.parsers.notation3 import BadSyntax
+from rdflib.plugins.parsers.notation3 import BadSyntax, exponent_syntax
+import itertools
from six import b
from six.moves.urllib.error import URLError
@@ -164,6 +165,31 @@ foo-bar:Ex foo-bar:name "Test" . """
g = Graph()
g.parse("test/n3/issue156.n3", format="n3")
+ def testIssue999(self):
+ """
+ Make sure the n3 parser does recognize exponent and leading dot in ".171e-11"
+ """
+ data = """
+@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
+
+<http://qudt.org/vocab/unit/MilliM-PER-YR>
+ a <http://qudt.org/schema/qudt/Unit> ;
+ <http://qudt.org/schema/qudt/conversionMultiplier> .171e-11 ;
+ <http://qudt.org/schema/qudt/conversionOffset> 0e+00 ;
+ <http://qudt.org/schema/qudt/description> "0.001-fold of the SI base unit metre divided by the unit year" ;
+ <http://qudt.org/schema/qudt/hasQuantityKind> <http://qudt.org/vocab/quantitykind/Velocity> ;
+ <http://qudt.org/schema/qudt/iec61360Code> "0112/2///62720#UAA868" ;
+ <http://qudt.org/schema/qudt/uneceCommonCode> "H66" ;
+ rdfs:isDefinedBy <http://qudt.org/2.1/vocab/unit> ;
+ rdfs:isDefinedBy <http://qudt.org/vocab/unit> ;
+ rdfs:label "MilliM PER YR" ;
+ <http://www.w3.org/2004/02/skos/core#prefLabel> "millimetre per year" ;
+.
+ """
+ g = Graph()
+ g.parse(data=data, format="n3")
+ g.parse(data=data, format="turtle")
+
def testDotInPrefix(self):
g = Graph()
g.parse(
@@ -226,5 +252,24 @@ foo-bar:Ex foo-bar:name "Test" . """
g2), 'Document with declared empty prefix must match default #'
+class TestRegularExpressions(unittest.TestCase):
+ def testExponents(self):
+ signs = ("", "+", "-")
+ mantissas = ("1", "1.", ".1",
+ "12", "12.", "1.2", ".12",
+ "123", "123.", "12.3", "1.23", ".123")
+ es = "eE"
+ exps = ("1", "12", "+1", "-1", "+12", "-12")
+ for parts in itertools.product(signs, mantissas, es, exps):
+ expstring = "".join(parts)
+ self.assertTrue(exponent_syntax.match(expstring))
+
+ def testInvalidExponents(self):
+ # Add test cases as needed
+ invalid = (".e1",)
+ for expstring in invalid:
+ self.assertFalse(exponent_syntax.match(expstring))
+
+
if __name__ == '__main__':
unittest.main()
| Turtle parser fails with leading dot in decimal value
Input file `test.ttl`:
```
prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>
<http://qudt.org/vocab/unit/MilliM-PER-YR>
a <http://qudt.org/schema/qudt/Unit> ;
<http://qudt.org/schema/qudt/conversionMultiplier> .171e-11 ;
<http://qudt.org/schema/qudt/conversionOffset> 0e+00 ;
<http://qudt.org/schema/qudt/description> "0.001-fold of the SI base unit metre divided by the unit year" ;
<http://qudt.org/schema/qudt/hasQuantityKind> <http://qudt.org/vocab/quantitykind/Velocity> ;
<http://qudt.org/schema/qudt/iec61360Code> "0112/2///62720#UAA868" ;
<http://qudt.org/schema/qudt/uneceCommonCode> "H66" ;
rdfs:isDefinedBy <http://qudt.org/2.1/vocab/unit> ;
rdfs:isDefinedBy <http://qudt.org/vocab/unit> ;
rdfs:label "MilliM PER YR" ;
<http://www.w3.org/2004/02/skos/core#prefLabel> "millimetre per year" ;
.
```
Traceback:
```
>>> from rdflib import Graph
INFO:rdflib:RDFLib Version: 4.2.2
>>> g = Graph().parse('test.ttl', format='turtle')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.7/site-packages/rdflib/graph.py", line 1043, in parse
parser.parse(source, self, **args)
File "/usr/local/lib/python3.7/site-packages/rdflib/plugins/parsers/notation3.py", line 1870, in parse
p.loadStream(source.getByteStream())
File "/usr/local/lib/python3.7/site-packages/rdflib/plugins/parsers/notation3.py", line 434, in loadStream
return self.loadBuf(stream.read()) # Not ideal
File "/usr/local/lib/python3.7/site-packages/rdflib/plugins/parsers/notation3.py", line 440, in loadBuf
self.feed(buf)
File "/usr/local/lib/python3.7/site-packages/rdflib/plugins/parsers/notation3.py", line 466, in feed
i = self.directiveOrStatement(s, j)
File "/usr/local/lib/python3.7/site-packages/rdflib/plugins/parsers/notation3.py", line 489, in directiveOrStatement
return self.checkDot(argstr, j)
File "/usr/local/lib/python3.7/site-packages/rdflib/plugins/parsers/notation3.py", line 1159, in checkDot
"expected '.' or '}' or ']' at end of statement")
File "/usr/local/lib/python3.7/site-packages/rdflib/plugins/parsers/notation3.py", line 1615, in BadSyntax
raise BadSyntax(self._thisDoc, self.lines, argstr, i, msg)
rdflib.plugins.parsers.notation3.BadSyntax: at line 5 of <>:
Bad syntax (expected '.' or '}' or ']' at end of statement) at ^ in:
"...b' ;\n <http://qudt.org/schema/qudt/conversionMultiplier> .171'^b'e-11 ;\n <http://qudt.org/schema/qudt/conversionOffset> 0e+0'..."
>>> exit()
```
The parser is having issue with this line in the input file: `<http://qudt.org/schema/qudt/conversionMultiplier> .171e-11 ;`
Not very familiar with the code but probably some additional checks are required in `directiveOrStatement()` or `checkDot()`. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/test_n3.py::TestN3Case::testIssue999",
"test/test_n3.py::TestRegularExpressions::testExponents"
] | [
"test/test_n3.py::TestN3Case::testBaseCumulative",
"test/test_n3.py::TestN3Case::testBaseExplicit",
"test/test_n3.py::TestN3Case::testBaseSerialize",
"test/test_n3.py::TestN3Case::testDotInPrefix",
"test/test_n3.py::TestN3Case::testEmptyPrefix",
"test/test_n3.py::TestN3Case::testIssue156",
"test/test_n3.py::TestN3Case::testIssue23",
"test/test_n3.py::TestN3Case::testIssue29",
"test/test_n3.py::TestN3Case::testIssue68",
"test/test_n3.py::TestN3Case::testModel",
"test/test_n3.py::TestN3Case::testParse",
"test/test_n3.py::TestN3Case::testQuotedSerialization",
"test/test_n3.py::TestN3Case::testSingleQuotedLiterals",
"test/test_n3.py::TestRegularExpressions::testInvalidExponents"
] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2020-04-17T17:18:04Z" | bsd-3-clause |
|
RDFLib__rdflib-1022 | diff --git a/.travis.yml b/.travis.yml
index f37f0750..2d2ada1d 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,5 +1,4 @@
# http://travis-ci.org/#!/RDFLib/rdflib
-sudo: false
language: python
branches:
only:
@@ -10,16 +9,14 @@ git:
depth: 3
python:
- - 2.7
- - 3.4
- 3.5
- 3.6
+ - 3.7
-matrix:
+jobs:
include:
- - python: 3.7
+ - python: 3.8
dist: xenial
- sudo: true
before_install:
- pip install -U setuptools pip # seems travis comes with a too old setuptools for html5lib
diff --git a/README.md b/README.md
index 3160930d..e4c8a2eb 100644
--- a/README.md
+++ b/README.md
@@ -8,7 +8,7 @@ RDFLib
[![PyPI](https://img.shields.io/pypi/v/rdflib.svg)](https://pypi.python.org/pypi/rdflib)
[![PyPI](https://img.shields.io/pypi/pyversions/rdflib.svg)](https://pypi.python.org/pypi/rdflib)
-RDFLib is a pure Python package work working with [RDF](http://www.w3.org/RDF/). RDFLib contains most things you need to work with RDF, including:
+RDFLib is a pure Python package for working with [RDF](http://www.w3.org/RDF/). RDFLib contains most things you need to work with RDF, including:
* parsers and serializers for RDF/XML, N3, NTriples, N-Quads, Turtle, TriX, Trig and JSON-LD (via a plugin).
* a Graph interface which can be backed by any one of a number of Store implementations
diff --git a/docs/sphinx-requirements.txt b/docs/sphinx-requirements.txt
index 55809050..45583540 100644
--- a/docs/sphinx-requirements.txt
+++ b/docs/sphinx-requirements.txt
@@ -1,3 +1,3 @@
-sphinx==3.0.2
+sphinx==3.0.3
sphinxcontrib-apidoc
git+https://github.com/gniezen/n3pygments.git
diff --git a/rdflib/extras/external_graph_libs.py b/rdflib/extras/external_graph_libs.py
index 8617b370..25c745c0 100644
--- a/rdflib/extras/external_graph_libs.py
+++ b/rdflib/extras/external_graph_libs.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python2.7
+#!/usr/bin/env
# encoding: utf-8
from __future__ import absolute_import
from __future__ import division
diff --git a/rdflib/plugins/stores/sparqlconnector.py b/rdflib/plugins/stores/sparqlconnector.py
index ee981419..abb69a55 100644
--- a/rdflib/plugins/stores/sparqlconnector.py
+++ b/rdflib/plugins/stores/sparqlconnector.py
@@ -87,6 +87,7 @@ class SPARQLConnector(object):
if self.method == 'GET':
args['params'].update(params)
elif self.method == 'POST':
+ args['headers'].update({'Content-Type': 'application/sparql-query'})
args['data'] = params
else:
raise SPARQLConnectorException("Unknown method %s" % self.method)
@@ -106,7 +107,10 @@ class SPARQLConnector(object):
if default_graph:
params["using-graph-uri"] = default_graph
- headers = {'Accept': _response_mime_types[self.returnFormat]}
+ headers = {
+ 'Accept': _response_mime_types[self.returnFormat],
+ 'Content-Type': 'application/sparql-update',
+ }
args = dict(self.kwargs)
diff --git a/setup.py b/setup.py
index c115f068..8bba18d2 100644
--- a/setup.py
+++ b/setup.py
@@ -43,15 +43,14 @@ setup(
url="https://github.com/RDFLib/rdflib",
license="BSD-3-Clause",
platforms=["any"],
+ python_requires='>=3.5',
classifiers=[
"Programming Language :: Python",
- "Programming Language :: Python :: 2",
"Programming Language :: Python :: 3",
- "Programming Language :: Python :: 2.7",
- "Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
+ "Programming Language :: Python :: 3.8",
"License :: OSI Approved :: BSD License",
"Topic :: Software Development :: Libraries :: Python Modules",
"Operating System :: OS Independent",
diff --git a/tox.ini b/tox.ini
index ee712287..b5b588fb 100644
--- a/tox.ini
+++ b/tox.ini
@@ -1,6 +1,6 @@
[tox]
envlist =
- py27,py34,py35,py36
+ py35,py36,py37,py38
[testenv]
setenv =
@@ -20,7 +20,7 @@ deps =
[testenv:cover]
basepython =
- python2.7
+ python3.7
commands =
{envpython} run_tests.py --where=./ \
--with-coverage --cover-html --cover-html-dir=./coverage \
| RDFLib/rdflib | 3f0401dc527ef70abb1f0b76bdd281972ae2655c | diff --git a/test/test_sparqlstore.py b/test/test_sparqlstore.py
index 26a69460..a0a93b57 100644
--- a/test/test_sparqlstore.py
+++ b/test/test_sparqlstore.py
@@ -4,7 +4,10 @@ import os
import unittest
from nose import SkipTest
from requests import HTTPError
-
+from http.server import BaseHTTPRequestHandler, HTTPServer
+import socket
+from threading import Thread
+import requests
try:
assert len(urlopen("http://dbpedia.org/sparql").read()) > 0
@@ -67,5 +70,78 @@ class SPARQLStoreDBPediaTestCase(unittest.TestCase):
assert type(i[0]) == Literal, i[0].n3()
+class SPARQLStoreUpdateTestCase(unittest.TestCase):
+ def setUp(self):
+ port = self.setup_mocked_endpoint()
+ self.graph = Graph(store="SPARQLUpdateStore", identifier=URIRef("urn:ex"))
+ self.graph.open(("http://localhost:{port}/query".format(port=port),
+ "http://localhost:{port}/update".format(port=port)), create=False)
+ ns = list(self.graph.namespaces())
+ assert len(ns) > 0, ns
+
+ def setup_mocked_endpoint(self):
+ # Configure mock server.
+ s = socket.socket(socket.AF_INET, type=socket.SOCK_STREAM)
+ s.bind(('localhost', 0))
+ address, port = s.getsockname()
+ s.close()
+ mock_server = HTTPServer(('localhost', port), SPARQL11ProtocolStoreMock)
+
+ # Start running mock server in a separate thread.
+ # Daemon threads automatically shut down when the main process exits.
+ mock_server_thread = Thread(target=mock_server.serve_forever)
+ mock_server_thread.setDaemon(True)
+ mock_server_thread.start()
+ print("Started mocked sparql endpoint on http://localhost:{port}/".format(port=port))
+ return port
+
+ def tearDown(self):
+ self.graph.close()
+
+ def test_Query(self):
+ query = "insert data {<urn:s> <urn:p> <urn:o>}"
+ res = self.graph.update(query)
+ print(res)
+
+
+class SPARQL11ProtocolStoreMock(BaseHTTPRequestHandler):
+ def do_POST(self):
+ """
+ If the body should be analysed as well, just use:
+ ```
+ body = self.rfile.read(int(self.headers['Content-Length'])).decode()
+ print(body)
+ ```
+ """
+ contenttype = self.headers.get("Content-Type")
+ if self.path == "/query":
+ if self.headers.get("Content-Type") == "application/sparql-query":
+ pass
+ elif self.headers.get("Content-Type") == "application/x-www-form-urlencoded":
+ pass
+ else:
+ self.send_response(requests.codes.not_acceptable)
+ self.end_headers()
+ elif self.path == "/update":
+ if self.headers.get("Content-Type") == "application/sparql-update":
+ pass
+ elif self.headers.get("Content-Type") == "application/x-www-form-urlencoded":
+ pass
+ else:
+ self.send_response(requests.codes.not_acceptable)
+ self.end_headers()
+ else:
+ self.send_response(requests.codes.not_found)
+ self.end_headers()
+ self.send_response(requests.codes.ok)
+ self.end_headers()
+ return
+
+ def do_GET(self):
+ # Process an HTTP GET request and return a response with an HTTP 200 status.
+ self.send_response(requests.codes.ok)
+ self.end_headers()
+ return
+
if __name__ == '__main__':
unittest.main()
| Missing Content-Type header for SPARQLConnector update method (?)
In rdflib 4.2.2 the SPARQLWrapper added an applicable content-type header when sending queries and updates to a SPARQL endpoint.
The 5.0.0 the SPARQLConnector does not add a content-type and, since the GraphDB we use as SPARQL endpoint rejects update requests when Content-Type: application/sparql-update is not added to the header, I had to monkey patch the update method to forcebily add the content type to the header.
I also tried to add a headers parameter with the content-type to the SPARQLUpdateStore parameter when constructing a SPARQLUpdateStore instance, but this then the content type is also used for query request, which results in rejected query requests in case the store instance is used for querying.
Should the the content type be added by the SPARQLConnector like the SPARQLWrapper did or am i missing an other intended solution?
Best regards,
Arnoud
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/test_sparqlstore.py::SPARQLStoreUpdateTestCase::test_Query"
] | [
"test/test_sparqlstore.py::SPARQLStoreDBPediaTestCase::test_noinitNs"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2020-04-24T15:38:26Z" | bsd-3-clause |
|
RDFLib__rdflib-1046 | diff --git a/rdflib/graph.py b/rdflib/graph.py
index 12d18dce..145224b8 100644
--- a/rdflib/graph.py
+++ b/rdflib/graph.py
@@ -2,6 +2,8 @@ from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
+from xml.sax import SAXParseException
+
from rdflib.term import Literal # required for doctests
from rdflib.namespace import Namespace # required for doctests
@@ -21,6 +23,7 @@ from rdflib.parser import create_input_source
from rdflib.namespace import NamespaceManager
from rdflib.resource import Resource
from rdflib.collection import Collection
+import rdflib.util # avoid circular dependency
import os
import shutil
@@ -31,6 +34,7 @@ from urllib.parse import urlparse
assert Literal # avoid warning
assert Namespace # avoid warning
+
logger = logging.getLogger(__name__)
@@ -1066,13 +1070,24 @@ class Graph(Node):
)
if format is None:
format = source.content_type
+ assumed_xml = False
if format is None:
- # raise Exception("Could not determine format for %r. You can" + \
- # "expicitly specify one with the format argument." % source)
- format = "application/rdf+xml"
+ if (hasattr(source, "file")
+ and getattr(source.file, "name", None)
+ and isinstance(source.file.name, str)):
+ format = rdflib.util.guess_format(source.file.name)
+ if format is None:
+ format = "application/rdf+xml"
+ assumed_xml = True
parser = plugin.get(format, Parser)()
try:
parser.parse(source, self, **args)
+ except SAXParseException as saxpe:
+ if assumed_xml:
+ logger.warning(
+ "Could not guess format for %r, so assumed xml."
+ " You can explicitly specify format using the format argument." % source)
+ raise saxpe
finally:
if source.auto_close:
source.close()
diff --git a/rdflib/util.py b/rdflib/util.py
index 57b20915..92996ec7 100644
--- a/rdflib/util.py
+++ b/rdflib/util.py
@@ -47,8 +47,7 @@ from rdflib.exceptions import ContextTypeError
from rdflib.exceptions import ObjectTypeError
from rdflib.exceptions import PredicateTypeError
from rdflib.exceptions import SubjectTypeError
-from rdflib.graph import Graph
-from rdflib.graph import QuotedGraph
+import rdflib.graph # avoid circular dependency
from rdflib.namespace import Namespace
from rdflib.namespace import NamespaceManager
from rdflib.term import BNode
@@ -161,7 +160,7 @@ def from_n3(s, default=None, backend=None, nsm=None):
>>> from rdflib import RDFS
>>> from_n3('rdfs:label') == RDFS['label']
True
- >>> nsm = NamespaceManager(Graph())
+ >>> nsm = NamespaceManager(rdflib.graph.Graph())
>>> nsm.bind('dbpedia', 'http://dbpedia.org/resource/')
>>> berlin = URIRef('http://dbpedia.org/resource/Berlin')
>>> from_n3('dbpedia:Berlin', nsm=nsm) == berlin
@@ -207,16 +206,16 @@ def from_n3(s, default=None, backend=None, nsm=None):
return Literal(int(s))
elif s.startswith("{"):
identifier = from_n3(s[1:-1])
- return QuotedGraph(backend, identifier)
+ return rdflib.graph.QuotedGraph(backend, identifier)
elif s.startswith("["):
identifier = from_n3(s[1:-1])
- return Graph(backend, identifier)
+ return rdflib.graph.Graph(backend, identifier)
elif s.startswith("_:"):
return BNode(s[2:])
elif ":" in s:
if nsm is None:
# instantiate default NamespaceManager and rely on its defaults
- nsm = NamespaceManager(Graph())
+ nsm = NamespaceManager(rdflib.graph.Graph())
prefix, last_part = s.split(":", 1)
ns = dict(nsm.namespaces())[prefix]
return Namespace(ns)[last_part]
| RDFLib/rdflib | 037ea51e5f4863a7f98ff59972fcd34d39a7ed97 | diff --git a/test/test_parse_file_guess_format.py b/test/test_parse_file_guess_format.py
new file mode 100644
index 00000000..abb039df
--- /dev/null
+++ b/test/test_parse_file_guess_format.py
@@ -0,0 +1,32 @@
+import unittest
+from pathlib import Path
+from shutil import copyfile
+from tempfile import TemporaryDirectory
+
+from xml.sax import SAXParseException
+
+from rdflib import Graph, logger as graph_logger
+
+
+class FileParserGuessFormatTest(unittest.TestCase):
+ def test_ttl(self):
+ g = Graph()
+ self.assertIsInstance(g.parse("test/w3c/turtle/IRI_subject.ttl"), Graph)
+
+ def test_n3(self):
+ g = Graph()
+ self.assertIsInstance(g.parse("test/n3/example-lots_of_graphs.n3"), Graph)
+
+ def test_warning(self):
+ g = Graph()
+ with TemporaryDirectory() as tmpdirname:
+ newpath = Path(tmpdirname).joinpath("no_file_ext")
+ copyfile("test/w3c/turtle/IRI_subject.ttl", str(newpath))
+ with self.assertLogs(graph_logger, "WARNING") as log_cm:
+ with self.assertRaises(SAXParseException):
+ g.parse(str(newpath))
+ self.assertTrue(any("Could not guess format" in msg for msg in log_cm.output))
+
+
+if __name__ == '__main__':
+ unittest.main()
| Auto-detect RDF type from file extension in parse()
`Graph().parse("some-file.ttl", format="turtle")` is a common way to load RDF into an rdflib Graph. We have methods such as `rdflib.util.guess_format()` to guess `format` from the file extensions so what we need now is for `guess_format()` to be triggered automatically if `format` is not given so `parse()` can be used like this:
```
Graph().parse("some-file.ttl")
``` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/test_parse_file_guess_format.py::FileParserGuessFormatTest::test_n3",
"test/test_parse_file_guess_format.py::FileParserGuessFormatTest::test_ttl",
"test/test_parse_file_guess_format.py::FileParserGuessFormatTest::test_warning"
] | [] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
} | "2020-05-11T19:58:48Z" | bsd-3-clause |
|
RDFLib__rdflib-1054 | diff --git a/rdflib/plugins/parsers/notation3.py b/rdflib/plugins/parsers/notation3.py
index 089efff8..6d3f4c24 100755
--- a/rdflib/plugins/parsers/notation3.py
+++ b/rdflib/plugins/parsers/notation3.py
@@ -39,7 +39,7 @@ from decimal import Decimal
from uuid import uuid4
-from exceptions import ParserError
+from rdflib.exceptions import ParserError
from rdflib.term import URIRef, BNode, Literal, Variable, _XSD_PFX, _unique_id
from rdflib.graph import QuotedGraph, ConjunctiveGraph, Graph
from rdflib.compat import long_type
diff --git a/rdflib/term.py b/rdflib/term.py
index 32ec6af4..ac69c3bd 100644
--- a/rdflib/term.py
+++ b/rdflib/term.py
@@ -1259,10 +1259,9 @@ class Literal(Identifier):
return sub("\\.?0*e", "e", "%e" % float(self))
elif self.datatype == _XSD_DECIMAL:
s = "%s" % self
- if "." not in s:
+ if "." not in s and "e" not in s and "E" not in s:
s += ".0"
return s
-
elif self.datatype == _XSD_BOOLEAN:
return ("%s" % self).lower()
else:
| RDFLib/rdflib | 845c28171626fe312128f63a4e9f2112ad107d6c | diff --git a/test/test_issue1043.py b/test/test_issue1043.py
new file mode 100644
index 00000000..db202d77
--- /dev/null
+++ b/test/test_issue1043.py
@@ -0,0 +1,33 @@
+import decimal
+import unittest
+import io
+import sys
+
+from rdflib import Graph, Namespace, XSD, RDFS, Literal
+
+
+class TestIssue1043(unittest.TestCase):
+
+ def test_issue_1043(self):
+ expected = """@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
+@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
+
+<http://example.org/number> rdfs:label 4e-08 .
+
+
+"""
+ capturedOutput = io.StringIO()
+ sys.stdout = capturedOutput
+ g = Graph()
+ g.bind('xsd', XSD)
+ g.bind('rdfs', RDFS)
+ n = Namespace("http://example.org/")
+ g.add((n.number, RDFS.label, Literal(0.00000004, datatype=XSD.decimal)))
+ print(g.serialize(format="turtle").decode("utf-8"))
+ sys.stdout = sys.__stdout__
+ self.assertEqual(capturedOutput.getvalue(), expected)
+
+
+
+if __name__ == "__main__":
+ unittest.main()
\ No newline at end of file
| Incorrect turtle serialization of decimal values
I am using rdflib to serialize to ttl files, rdflib = 5.0.0
Here is a sample output,
```
wd:Q29722949 a wikibase:Item ;
p:P2020013 wds:Q29722949-9ef7c6be-2c5e-4c64-8e44-a3af6725596e ;
p:P2020014 wds:Q29722949-5570794f-5918-45b8-936f-9a2e24a6a61d ;
p:P2020015 wds:Q29722949-62e5de90-74ab-47bd-a8b5-13323986c20b ;
p:P2020016 wds:Q29722949-daa7b2f2-3646-4e78-bdb3-eb01c745d502 ;
p:P2020017 wds:Q29722949-0e7cb2f1-a13b-47a0-b6a9-c24908c0edcf ;
wdtn:P2020013 wdv:Quantityc1c0c0c0 ;
wdtn:P2020014 wdv:Quantityc0c0c0c0 ;
wdtn:P2020015 wdv:Quantityc0-000000216c0c0c0 ;
wdtn:P2020016 wdv:Quantityc0c0c0c0 ;
wdtn:P2020017 wdv:Quantityc0-0000000000000005c0c0c0 ;
wdt:P2020013 1.0 ;
wdt:P2020014 0.0 ;
wdt:P2020015 2.16E-7 ;
wdt:P2020016 0.0 ;
wdt:P2020017 5E-16.0 .
```
notice that the line `wdt:P2020015 2.16E-7` is correct while, ` wdt:P2020017 5E-16.0 ` is incorrect as it has a `.0` at the end, which is invalid.
Please take a look, this seems to be happening randomly | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/test_issue1043.py::TestIssue1043::test_issue_1043"
] | [] | {
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2020-05-19T05:57:12Z" | bsd-3-clause |
|
RDFLib__rdflib-1130 | diff --git a/examples/conjunctive_graphs.py b/examples/conjunctive_graphs.py
index f714d9ff..a66a3aa8 100644
--- a/examples/conjunctive_graphs.py
+++ b/examples/conjunctive_graphs.py
@@ -33,7 +33,7 @@ if __name__ == "__main__":
gmary.add((mary, ns["hasName"], Literal("Mary")))
gmary.add((mary, ns["loves"], john))
- # add a graph for Mary's facts to the Conjunctive Graph
+ # add a graph for John's facts to the Conjunctive Graph
gjohn = Graph(store=store, identifier=cjohn)
# John's graph contains his cute name
gjohn.add((john, ns["hasCuteName"], Literal("Johnny Boy")))
diff --git a/rdflib/namespace.py b/rdflib/namespace.py
index 84cbe508..27f6d9ea 100644
--- a/rdflib/namespace.py
+++ b/rdflib/namespace.py
@@ -804,7 +804,7 @@ class NamespaceManager(object):
NAME_START_CATEGORIES = ["Ll", "Lu", "Lo", "Lt", "Nl"]
SPLIT_START_CATEGORIES = NAME_START_CATEGORIES + ["Nd"]
NAME_CATEGORIES = NAME_START_CATEGORIES + ["Mc", "Me", "Mn", "Lm", "Nd"]
-ALLOWED_NAME_CHARS = [u"\u00B7", u"\u0387", u"-", u".", u"_", u":"]
+ALLOWED_NAME_CHARS = [u"\u00B7", u"\u0387", u"-", u".", u"_", u":", u"%"]
# http://www.w3.org/TR/REC-xml-names/#NT-NCName
| RDFLib/rdflib | e4fe0fdbd4de7e1183418f302315b51a14602e03 | diff --git a/test/test_issue801.py b/test/test_issue801.py
new file mode 100644
index 00000000..ae27f346
--- /dev/null
+++ b/test/test_issue801.py
@@ -0,0 +1,19 @@
+"""
+Issue 801 - Problem with prefixes created for URIs containing %20
+"""
+from rdflib import Namespace, Graph, BNode, Literal
+import unittest
+
+class TestIssue801(unittest.TestCase):
+
+ def test_issue_801(self):
+ g = Graph()
+ example = Namespace('http://example.org/')
+ g.bind('', example)
+ node = BNode()
+ g.add((node, example['first%20name'], Literal('John')))
+ self.assertEqual(g.serialize(format="turtle").decode().split("\n")[-3],
+ '[] :first%20name "John" .')
+
+if __name__ == "__main__":
+ unittest.main()
| Minor typo(?) in example
I think the comment on line 36 is wrong and should read
```
# add a graph for John's facts to the Conjunctive Graph
```
https://github.com/RDFLib/rdflib/blob/e4fe0fdbd4de7e1183418f302315b51a14602e03/examples/conjunctive_graphs.py#L36-L37
No big deal, but it may be confusing to learners. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/test_issue801.py::TestIssue801::test_issue_801"
] | [] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2020-07-03T07:58:45Z" | bsd-3-clause |
|
RDFLib__rdflib-1293 | diff --git a/docs/sphinx-requirements.txt b/docs/sphinx-requirements.txt
index cf0382e8..403eec52 100644
--- a/docs/sphinx-requirements.txt
+++ b/docs/sphinx-requirements.txt
@@ -1,3 +1,3 @@
-sphinx==3.5.3
+sphinx==3.5.4
sphinxcontrib-apidoc
git+https://github.com/gniezen/n3pygments.git
diff --git a/rdflib/namespace.py b/rdflib/namespace.py
index bdb0000a..3563b8c1 100644
--- a/rdflib/namespace.py
+++ b/rdflib/namespace.py
@@ -184,7 +184,7 @@ class ClosedNamespace(object):
"""
A namespace with a closed list of members
- Trying to create terms not listen is an error
+ Trying to create terms not listed is an error
"""
def __init__(self, uri, terms):
@@ -897,7 +897,7 @@ class NamespaceManager(object):
NAME_START_CATEGORIES = ["Ll", "Lu", "Lo", "Lt", "Nl"]
SPLIT_START_CATEGORIES = NAME_START_CATEGORIES + ["Nd"]
NAME_CATEGORIES = NAME_START_CATEGORIES + ["Mc", "Me", "Mn", "Lm", "Nd"]
-ALLOWED_NAME_CHARS = ["\u00B7", "\u0387", "-", ".", "_", "%"]
+ALLOWED_NAME_CHARS = ["\u00B7", "\u0387", "-", ".", "_", "%", "(", ")"]
# http://www.w3.org/TR/REC-xml-names/#NT-NCName
| RDFLib/rdflib | 45034056789fb0efff37f632e52d9d564f5d957b | diff --git a/test/test_namespace.py b/test/test_namespace.py
index 5c73d223..3c321f8c 100644
--- a/test/test_namespace.py
+++ b/test/test_namespace.py
@@ -31,16 +31,24 @@ class NamespacePrefixTest(unittest.TestCase):
g.compute_qname(URIRef("http://foo/bar/")),
("ns1", URIRef("http://foo/bar/"), ""),
)
+
# should compute qnames of URNs correctly as well
self.assertEqual(
g.compute_qname(URIRef("urn:ISSN:0167-6423")),
("ns5", URIRef("urn:ISSN:"), "0167-6423"),
)
+
self.assertEqual(
g.compute_qname(URIRef("urn:ISSN:")),
("ns5", URIRef("urn:ISSN:"), ""),
)
+ # should compute qnames with parenthesis correctly
+ self.assertEqual(
+ g.compute_qname(URIRef("http://foo/bar/name_with_(parenthesis)")),
+ ("ns1", URIRef("http://foo/bar/"), "name_with_(parenthesis)"),
+ )
+
def test_reset(self):
data = (
"@prefix a: <http://example.org/a> .\n"
diff --git a/test/test_turtle_serialize.py b/test/test_turtle_serialize.py
index 3725bcd0..9e6f0b63 100644
--- a/test/test_turtle_serialize.py
+++ b/test/test_turtle_serialize.py
@@ -81,6 +81,7 @@ def test_turtle_namespace():
graph.bind("RO", "http://purl.obolibrary.org/obo/RO_")
graph.bind("RO_has_phenotype", "http://purl.obolibrary.org/obo/RO_0002200")
graph.bind("SERIAL", "urn:ISSN:")
+ graph.bind("EX", "http://example.org/")
graph.add(
(
URIRef("http://example.org"),
@@ -93,7 +94,13 @@ def test_turtle_namespace():
URIRef("urn:ISSN:0167-6423"),
RDFS.label,
Literal("Science of Computer Programming"),
-
+ )
+ )
+ graph.add(
+ (
+ URIRef("http://example.org/name_with_(parenthesis)"),
+ RDFS.label,
+ Literal("URI with parenthesis"),
)
)
output = [
@@ -105,6 +112,7 @@ def test_turtle_namespace():
assert "RO_has_phenotype:" in output
assert "GENO:0000385" in output
assert "SERIAL:0167-6423" in output
+ assert "EX:name_with_(parenthesis)" in output
if __name__ == "__main__":
| Docstring for ClosedNamespace has a typo
The word "listen" is used instead of "listed". | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/test_namespace.py::NamespacePrefixTest::test_compute_qname",
"test/test_turtle_serialize.py::test_turtle_namespace"
] | [
"test/test_namespace.py::NamespacePrefixTest::test_closed_namespace",
"test/test_namespace.py::NamespacePrefixTest::test_contains_method",
"test/test_namespace.py::NamespacePrefixTest::test_n3",
"test/test_namespace.py::NamespacePrefixTest::test_n32",
"test/test_namespace.py::NamespacePrefixTest::test_reset",
"test/test_namespace.py::NamespacePrefixTest::test_reset_preserve_prefixes",
"test/test_turtle_serialize.py::testTurtleFinalDot",
"test/test_turtle_serialize.py::testTurtleBoolList",
"test/test_turtle_serialize.py::testUnicodeEscaping",
"test/test_turtle_serialize.py::test_turtle_valid_list"
] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2021-04-20T18:54:40Z" | bsd-3-clause |
|
RDFLib__rdflib-1309 | diff --git a/rdflib/graph.py b/rdflib/graph.py
index 86b7ccb8..f90b3acb 100644
--- a/rdflib/graph.py
+++ b/rdflib/graph.py
@@ -19,6 +19,7 @@ from rdflib.exceptions import ParserError
import os
import shutil
import tempfile
+import pathlib
from io import BytesIO, BufferedIOBase
from urllib.parse import urlparse
@@ -1065,7 +1066,10 @@ class Graph(Node):
stream = cast(BufferedIOBase, destination)
serializer.serialize(stream, base=base, encoding=encoding, **args)
else:
- location = cast(str, destination)
+ if isinstance(destination, pathlib.PurePath):
+ location = str(destination)
+ else:
+ location = cast(str, destination)
scheme, netloc, path, params, _query, fragment = urlparse(location)
if netloc != "":
print(
diff --git a/rdflib/parser.py b/rdflib/parser.py
index aa622ee0..ce4e5a2d 100644
--- a/rdflib/parser.py
+++ b/rdflib/parser.py
@@ -238,7 +238,7 @@ def create_input_source(
else:
if isinstance(source, str):
location = source
- elif isinstance(source, pathlib.Path):
+ elif isinstance(source, pathlib.PurePath):
location = str(source)
elif isinstance(source, bytes):
data = source
| RDFLib/rdflib | 5d77b14de48275bbba07746ebd7bfbd3c23ee52c | diff --git a/test/test_serialize.py b/test/test_serialize.py
new file mode 100644
index 00000000..cfc8a9d7
--- /dev/null
+++ b/test/test_serialize.py
@@ -0,0 +1,43 @@
+import unittest
+from rdflib import Graph, URIRef
+from tempfile import NamedTemporaryFile, TemporaryDirectory
+from pathlib import Path, PurePath
+
+
+class TestSerialize(unittest.TestCase):
+ def setUp(self) -> None:
+
+ graph = Graph()
+ subject = URIRef("example:subject")
+ predicate = URIRef("example:predicate")
+ object = URIRef("example:object")
+ self.triple = (
+ subject,
+ predicate,
+ object,
+ )
+ graph.add(self.triple)
+ self.graph = graph
+ return super().setUp()
+
+ def test_serialize_to_purepath(self):
+ with TemporaryDirectory() as td:
+ tfpath = PurePath(td) / "out.nt"
+ self.graph.serialize(destination=tfpath, format="nt")
+ graph_check = Graph()
+ graph_check.parse(source=tfpath, format="nt")
+
+ self.assertEqual(self.triple, next(iter(graph_check)))
+
+ def test_serialize_to_path(self):
+ with NamedTemporaryFile() as tf:
+ tfpath = Path(tf.name)
+ self.graph.serialize(destination=tfpath, format="nt")
+ graph_check = Graph()
+ graph_check.parse(source=tfpath, format="nt")
+
+ self.assertEqual(self.triple, next(iter(graph_check)))
+
+
+if __name__ == "__main__":
+ unittest.main()
| graph.serialize(destination=) should accept a pathlib Path
If you try:
```python
g.serialize(destination=pathib.Path(__file__).parent / "some" / "path" / "to" / "a" / "file.ttl", format="ttl")
```
You get a:
```python
AttributeError: 'PosixPath' object has no attribute 'decode'
```
You have to do:
```python
g.serialize(destination=str(pathib.Path(__file__).parent / "some" / "path" / "to" / "a" / "file.ttl"), format="ttl")
```
We should allow a Path to be used like this. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/test_serialize.py::TestSerialize::test_serialize_to_path",
"test/test_serialize.py::TestSerialize::test_serialize_to_purepath"
] | [] | {
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2021-05-13T19:48:09Z" | bsd-3-clause |
|
RDFLib__rdflib-1315 | diff --git a/docs/intro_to_sparql.rst b/docs/intro_to_sparql.rst
index 97c7f281..8c7efd34 100644
--- a/docs/intro_to_sparql.rst
+++ b/docs/intro_to_sparql.rst
@@ -17,56 +17,62 @@ Queries can be evaluated against a graph with the
:meth:`rdflib.graph.Graph.update`.
The query method returns a :class:`rdflib.query.Result` instance. For
-SELECT queries, iterating over this return
+SELECT queries, iterating over this returns
:class:`rdflib.query.ResultRow` instances, each containing a set of
variable bindings. For CONSTRUCT/DESCRIBE queries, iterating over the
-result object gives the triples. For ASK queries, iterating will yield
-the single boolean answer, or evaluating the result object in a
-boolean-context (i.e. ``bool(result)``)
+result object yields triples. For ASK queries, the single Boolean
+answer is obtained by iterating over the result object or by
+evaluating the result object in a Boolean context
+(i.e. ``bool(result)``).
-Continuing the example...
+Consider the example...
.. code-block:: python
import rdflib
-
g = rdflib.Graph()
+ g.parse("http://danbri.org/foaf.rdf#")
- # ... add some triples to g somehow ...
- g.parse("some_foaf_file.rdf")
-
- qres = g.query(
- """SELECT DISTINCT ?aname ?bname
- WHERE {
- ?a foaf:knows ?b .
- ?a foaf:name ?aname .
- ?b foaf:name ?bname .
- }""")
+ knows_query = """
+ SELECT DISTINCT ?aname ?bname
+ WHERE {
+ ?a foaf:knows ?b .
+ ?a foaf:name ?aname .
+ ?b foaf:name ?bname .
+ }"""
- for row in qres:
+ for row in g.query(knows_query):
print("%s knows %s" % row)
The results are tuples of values in the same order as your SELECT
-arguments. Alternatively, the values can be accessed by variable
-name, either as attributes, or as items: ``row.b`` and ``row["b"]`` is
-equivalent.
+arguments. The values can be accessed individually by variable
+name, either as attributes (``row.b``) or as items (``row["b"]``).
.. code-block:: text
- Timothy Berners-Lee knows Edd Dumbill
- Timothy Berners-Lee knows Jennifer Golbeck
- Timothy Berners-Lee knows Nicholas Gibbins
- Timothy Berners-Lee knows Nigel Shadbolt
- Dan Brickley knows binzac
- Timothy Berners-Lee knows Eric Miller
- Drew Perttula knows David McClosky
- Timothy Berners-Lee knows Dan Connolly
+ Dan Brickley knows Tim Berners-Lee
+ Dan Brickley knows Dean Jackson
+ Dan Brickley knows Mischa Tuffield
+ Dan Brickley knows Ludovic Hirlimann
+ Dan Brickley knows Libby Miller
...
As an alternative to using ``PREFIX`` in the SPARQL query, namespace
-bindings can be passed in with the ``initNs`` kwarg, see
-:doc:`namespaces_and_bindings`.
+bindings can be passed in with the ``initNs`` kwarg (see
+:doc:`namespaces_and_bindings`):
+.. code-block:: python
+
+ import rdflib
+ from rdflib import FOAF
+ g = rdflib.Graph()
+ g.parse("http://danbri.org/foaf.rdf#")
+
+ result = g.query(knows_query, initNs={ 'foaf': FOAF })
+
+ for row in result:
+ print(f"{row.aname} knows {row['bname']}")
+
Variables can also be pre-bound, using ``initBindings`` kwarg can be
used to pass in a ``dict`` of initial bindings, this is particularly
useful for prepared queries, as described below.
diff --git a/docs/sphinx-requirements.txt b/docs/sphinx-requirements.txt
index 48ba7549..b4f0ddd9 100644
--- a/docs/sphinx-requirements.txt
+++ b/docs/sphinx-requirements.txt
@@ -1,3 +1,3 @@
-sphinx==4.0.1
+sphinx==4.0.2
sphinxcontrib-apidoc
git+https://github.com/gniezen/n3pygments.git
diff --git a/rdflib/term.py b/rdflib/term.py
index 0f627e69..d9e06d82 100644
--- a/rdflib/term.py
+++ b/rdflib/term.py
@@ -1437,6 +1437,8 @@ _XSD_YEARMONTHDURATION = URIRef(_XSD_PFX + "yearMonthDuration")
_OWL_RATIONAL = URIRef("http://www.w3.org/2002/07/owl#rational")
_XSD_B64BINARY = URIRef(_XSD_PFX + "base64Binary")
_XSD_HEXBINARY = URIRef(_XSD_PFX + "hexBinary")
+_XSD_GYEAR = URIRef(_XSD_PFX + "gYear")
+_XSD_GYEARMONTH = URIRef(_XSD_PFX + "gYearMonth")
# TODO: gYearMonth, gYear, gMonthDay, gDay, gMonth
_NUMERIC_LITERAL_TYPES = (
@@ -1558,6 +1560,8 @@ _GenericPythonToXSDRules = [
]
_SpecificPythonToXSDRules = [
+ ((date, _XSD_GYEAR), lambda val: val.strftime("%04Y")),
+ ((date, _XSD_GYEARMONTH), lambda val: val.strftime("%04Y-%02m")),
((str, _XSD_HEXBINARY), hexlify),
((bytes, _XSD_HEXBINARY), hexlify),
((str, _XSD_B64BINARY), b64encode),
| RDFLib/rdflib | a9aaef18c86f4bb645ee791a50c805bf0d9cecd0 | diff --git a/test/test_issue977.py b/test/test_issue977.py
new file mode 100644
index 00000000..26f61c5a
--- /dev/null
+++ b/test/test_issue977.py
@@ -0,0 +1,30 @@
+import unittest
+
+from rdflib import Graph, XSD, RDF, RDFS, URIRef, Literal
+
+
+class TestIssue977(unittest.TestCase):
+
+ def setUp(self):
+ self.graph = Graph()
+ # Bind prefixes.
+ self.graph.bind('isbn', 'urn:isbn:')
+ self.graph.bind('webn', 'http://w3c.org/example/isbn/')
+ # Populate graph.
+ self.graph.add((URIRef('urn:isbn:1503280780'), RDFS.label, Literal('Moby Dick')))
+ self.graph.add((URIRef('http://w3c.org/example/isbn/1503280780'), RDFS.label, Literal('Moby Dick')))
+
+ def test_namespace_manager(self):
+ assert 'isbn', 'urn:isbn:' in tuple(self.graph.namespaces())
+ assert 'webn', 'http://w3c.org/example/isbn/' in tuple(self.graph.namespaces())
+
+ def test_turtle_serialization(self):
+ serialization = self.graph.serialize(None, format='turtle')
+ print(f'Test Issue 977, serialization output:\n---\n{serialization}---')
+ # Test serialization.
+ assert '@prefix webn:' in serialization, "Prefix webn not found in serialization!"
+ assert '@prefix isbn:' in serialization, "Prefix isbn not found in serialization!"
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/test/test_literal.py b/test/test_literal.py
index 656bfb10..98cd18a8 100644
--- a/test/test_literal.py
+++ b/test/test_literal.py
@@ -1,7 +1,9 @@
import unittest
+import datetime
import rdflib # needed for eval(repr(...)) below
from rdflib.term import Literal, URIRef, _XSD_DOUBLE, bind, _XSD_BOOLEAN
+from rdflib.namespace import XSD
def uformat(s):
@@ -188,5 +190,79 @@ class TestBindings(unittest.TestCase):
self.assertEqual(specific_l.datatype, datatype)
+class TestXsdLiterals(unittest.TestCase):
+ def test_make_literals(self):
+ """
+ Tests literal construction.
+ """
+ inputs = [
+ # these literals do not get conerted to python types
+ ("ABCD", XSD.integer, None),
+ ("ABCD", XSD.gYear, None),
+ ("-10000", XSD.gYear, None),
+ ("-1921-00", XSD.gYearMonth, None),
+ ("1921-00", XSD.gMonthDay, None),
+ ("1921-13", XSD.gMonthDay, None),
+ ("-1921-00", XSD.gMonthDay, None),
+ ("10", XSD.gDay, None),
+ ("-1", XSD.gDay, None),
+ ("0000", XSD.gYear, None),
+ ("0000-00-00", XSD.date, None),
+ ("NOT A VALID HEX STRING", XSD.hexBinary, None),
+ ("NOT A VALID BASE64 STRING", XSD.base64Binary, None),
+ # these literals get converted to python types
+ ("1921-05-01", XSD.date, datetime.date),
+ ("1921-05-01T00:00:00", XSD.dateTime, datetime.datetime),
+ ("1921-05", XSD.gYearMonth, datetime.date),
+ ("0001-01", XSD.gYearMonth, datetime.date),
+ ("0001-12", XSD.gYearMonth, datetime.date),
+ ("2002-01", XSD.gYearMonth, datetime.date),
+ ("9999-01", XSD.gYearMonth, datetime.date),
+ ("9999-12", XSD.gYearMonth, datetime.date),
+ ("1921", XSD.gYear, datetime.date),
+ ("2000", XSD.gYear, datetime.date),
+ ("0001", XSD.gYear, datetime.date),
+ ("9999", XSD.gYear, datetime.date),
+ ("1982", XSD.gYear, datetime.date),
+ ("2002", XSD.gYear, datetime.date),
+ ("1921-05-01T00:00:00+00:30", XSD.dateTime, datetime.datetime),
+ ("1921-05-01T00:00:00-00:30", XSD.dateTime, datetime.datetime),
+ ("abcdef0123", XSD.hexBinary, bytes),
+ ("", XSD.hexBinary, bytes),
+ ("UkRGTGli", XSD.base64Binary, bytes),
+ ("", XSD.base64Binary, bytes),
+ ]
+ self.check_make_literals(inputs)
+
+ @unittest.expectedFailure
+ def test_make_literals_ki(self):
+ """
+ Known issues with literal construction.
+ """
+ inputs = [
+ ("1921-01Z", XSD.gYearMonth, datetime.date),
+ ("1921Z", XSD.gYear, datetime.date),
+ ("1921-00", XSD.gYearMonth, datetime.date),
+ ("1921-05-01Z", XSD.date, datetime.date),
+ ("1921-05-01+00:30", XSD.date, datetime.date),
+ ("1921-05-01+00:30", XSD.date, datetime.date),
+ ("1921-05-01+00:00", XSD.date, datetime.date),
+ ("1921-05-01+00:00", XSD.date, datetime.date),
+ ("1921-05-01T00:00:00Z", XSD.dateTime, datetime.datetime),
+ ]
+ self.check_make_literals(inputs)
+
+ def check_make_literals(self, inputs):
+ for literal_pair in inputs:
+ (lexical, type, value_cls) = literal_pair
+ with self.subTest(f"tesing {literal_pair}"):
+ literal = Literal(lexical, datatype=type)
+ if value_cls is not None:
+ self.assertIsInstance(literal.value, value_cls)
+ else:
+ self.assertIsNone(literal.value)
+ self.assertEqual(lexical, f"{literal}")
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/test/test_parser.py b/test/test_parser.py
index e337969c..da38ea91 100644
--- a/test/test_parser.py
+++ b/test/test_parser.py
@@ -44,5 +44,47 @@ class ParserTestCase(unittest.TestCase):
self.assertEqual(type, RDFS.Class)
+class TestGitHubIssues(unittest.TestCase):
+ def test_issue_1228_a(self):
+ data = """
+ PREFIX sdo: <https://schema.org/>
+ PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
+
+ <x:> sdo:startDate "1982"^^xsd:gYear .
+ """
+
+ g = Graph().parse(data=data, format="ttl")
+ self.assertNotIn("1982-01-01", data)
+ self.assertNotIn("1982-01-01", g.serialize(format="ttl"))
+
+ def test_issue_1228_b(self):
+ data = """\
+<?xml version="1.0" encoding="UTF-8"?>
+ <rdf:RDF
+ xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
+ xmlns:sdo="https://schema.org/"
+ >
+ <rdf:Description rdf:about="x:">
+ <sdo:startDate
+ rdf:datatype="http://www.w3.org/2001/XMLSchema#gYear">1982</sdo:startDate>
+ </rdf:Description>
+</rdf:RDF>"""
+
+ g = Graph().parse(data=data, format="xml")
+ self.assertNotIn("1982-01-01", data)
+ self.assertNotIn("1982-01-01", g.serialize(format="xml"))
+
+ def test_issue_806(self):
+ data = (
+ "<http://dbpedia.org/resource/Australian_Labor_Party> "
+ "<http://dbpedia.org/ontology/formationYear> "
+ '"1891"^^<http://www.w3.org/2001/XMLSchema#gYear> .'
+ )
+ g = Graph()
+ g.parse(data=data, format="nt")
+ for _, _, o in g:
+ self.assertNotIn("1891-01-01", o.n3())
+
+
if __name__ == "__main__":
unittest.main()
| Turtle de/serialize incorrectly interprets gYear
In 5.0.0, when a `gYear` is parsed and then re-serialised, from any format to any other format, RDFlib adds "-01-01" to the literal so, for example, `"1982"^^xsd:gYear` goes to `"1982-01-01"^^xsd:gYear` which is invalid.
Testing code:
```python
from rdflib import Graph
data = """
PREFIX sdo: <https://schema.org/>
PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
<x:> sdo:startDate "1982"^^xsd:gYear .
"""
g = Graph().parse(data=data, format="ttl")
assert "1982-01-01" not in g.serialize(format="ttl").decode()
data2 = """<?xml version="1.0" encoding="UTF-8"?>
<rdf:RDF
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:sdo="https://schema.org/"
>
<rdf:Description rdf:about="x:">
<sdo:startDate rdf:datatype="http://www.w3.org/2001/XMLSchema#gYear">1982</sdo:startDate>
</rdf:Description>
</rdf:RDF>"""
g2 = Graph().parse(data=data2, format="xml")
assert "1982-01-01" not in g2.serialize(format="xml").decode()
``` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/test_literal.py::TestXsdLiterals::test_make_literals",
"test/test_parser.py::TestGitHubIssues::test_issue_1228_a",
"test/test_parser.py::TestGitHubIssues::test_issue_1228_b",
"test/test_parser.py::TestGitHubIssues::test_issue_806"
] | [
"test/test_issue977.py::TestIssue977::test_namespace_manager",
"test/test_issue977.py::TestIssue977::test_turtle_serialization",
"test/test_literal.py::TestLiteral::test_backslash",
"test/test_literal.py::TestLiteral::test_literal_from_bool",
"test/test_literal.py::TestLiteral::test_repr_apostrophe",
"test/test_literal.py::TestLiteral::test_repr_quote",
"test/test_literal.py::TestNew::testCantPassLangAndDatatype",
"test/test_literal.py::TestNew::testDatatypeGetsAutoURIRefConversion",
"test/test_literal.py::TestNew::testFromOtherLiteral",
"test/test_literal.py::TestRepr::testOmitsMissingDatatype",
"test/test_literal.py::TestRepr::testOmitsMissingDatatypeAndLang",
"test/test_literal.py::TestRepr::testOmitsMissingLang",
"test/test_literal.py::TestRepr::testSubclassNameAppearsInRepr",
"test/test_literal.py::TestDoubleOutput::testNoDanglingPoint",
"test/test_literal.py::TestParseBoolean::testFalseBoolean",
"test/test_literal.py::TestParseBoolean::testNonFalseBoolean",
"test/test_literal.py::TestParseBoolean::testTrueBoolean",
"test/test_literal.py::TestBindings::testBinding",
"test/test_literal.py::TestBindings::testSpecificBinding",
"test/test_parser.py::ParserTestCase::testNoPathWithHash"
] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2021-05-15T02:13:40Z" | bsd-3-clause |
|
RDFLib__rdflib-1382 | diff --git a/docs/intro_to_sparql.rst b/docs/intro_to_sparql.rst
index ef7aab78..72a87c66 100644
--- a/docs/intro_to_sparql.rst
+++ b/docs/intro_to_sparql.rst
@@ -39,7 +39,8 @@ For example...
?a foaf:name ?aname .
?b foaf:name ?bname .
}"""
-
+
+ qres = g.query(knows_query)
for row in qres:
print(f"{row.aname} knows {row.bname}")
diff --git a/docs/sphinx-requirements.txt b/docs/sphinx-requirements.txt
index 7096a117..f5e39519 100644
--- a/docs/sphinx-requirements.txt
+++ b/docs/sphinx-requirements.txt
@@ -1,3 +1,3 @@
-sphinx==4.1.1
+sphinx==4.1.2
sphinxcontrib-apidoc
git+https://github.com/gniezen/n3pygments.git
diff --git a/rdflib/graph.py b/rdflib/graph.py
index a689b35a..b25765ac 100644
--- a/rdflib/graph.py
+++ b/rdflib/graph.py
@@ -1,4 +1,4 @@
-from typing import Optional, Union, Type, cast, overload
+from typing import Optional, Union, Type, cast, overload, Generator, Tuple
import logging
from warnings import warn
import random
@@ -29,6 +29,9 @@ assert Namespace # avoid warning
logger = logging.getLogger(__name__)
+# Type aliases to make unpacking what's going on a little more human friendly
+ContextNode = Union[BNode, URIRef]
+DatasetQuad = Tuple[Node, URIRef, Node, Optional[ContextNode]]
__doc__ = """\
@@ -1759,8 +1762,8 @@ class Dataset(ConjunctiveGraph):
rdflib.term.URIRef("http://example.org/y"),
rdflib.term.Literal("bar"))
>>>
- >>> # querying quads return quads; the fourth argument can be unrestricted
- >>> # or restricted to a graph
+ >>> # querying quads() return quads; the fourth argument can be unrestricted
+ >>> # (None) or restricted to a graph
>>> for q in ds.quads((None, None, None, None)): # doctest: +SKIP
... print(q) # doctest: +NORMALIZE_WHITESPACE
(rdflib.term.URIRef("http://example.org/a"),
@@ -1776,7 +1779,24 @@ class Dataset(ConjunctiveGraph):
rdflib.term.Literal("foo-bar"),
rdflib.term.URIRef("http://www.example.com/gr"))
>>>
- >>> for q in ds.quads((None,None,None,g)): # doctest: +SKIP
+ >>> # unrestricted looping is equivalent to iterating over the entire Dataset
+ >>> for q in ds: # doctest: +SKIP
+ ... print(q) # doctest: +NORMALIZE_WHITESPACE
+ (rdflib.term.URIRef("http://example.org/a"),
+ rdflib.term.URIRef("http://www.example.org/b"),
+ rdflib.term.Literal("foo"),
+ None)
+ (rdflib.term.URIRef("http://example.org/x"),
+ rdflib.term.URIRef("http://example.org/y"),
+ rdflib.term.Literal("bar"),
+ rdflib.term.URIRef("http://www.example.com/gr"))
+ (rdflib.term.URIRef("http://example.org/x"),
+ rdflib.term.URIRef("http://example.org/z"),
+ rdflib.term.Literal("foo-bar"),
+ rdflib.term.URIRef("http://www.example.com/gr"))
+ >>>
+ >>> # resticting iteration to a graph:
+ >>> for q in ds.quads((None, None, None, g)): # doctest: +SKIP
... print(q) # doctest: +NORMALIZE_WHITESPACE
(rdflib.term.URIRef("http://example.org/x"),
rdflib.term.URIRef("http://example.org/y"),
@@ -1896,6 +1916,11 @@ class Dataset(ConjunctiveGraph):
else:
yield s, p, o, c.identifier
+ def __iter__(self) -> Generator[DatasetQuad, None, None]:
+ """Iterates over all quads in the store"""
+ return self.quads((None, None, None, None))
+
+
class QuotedGraph(Graph):
"""
diff --git a/rdflib/namespace/_RDF.py b/rdflib/namespace/_RDF.py
index 61bc4a58..f79d75a7 100644
--- a/rdflib/namespace/_RDF.py
+++ b/rdflib/namespace/_RDF.py
@@ -16,6 +16,7 @@ class RDF(DefinedNamespace):
"""
_fail = True
+ _underscore_num = True
# http://www.w3.org/1999/02/22-rdf-syntax-ns#List
nil: URIRef # The empty list, with no items in it. If the rest of a list is nil then the list has no more items in it.
diff --git a/rdflib/namespace/__init__.py b/rdflib/namespace/__init__.py
index 62a2a946..23f4ec0e 100644
--- a/rdflib/namespace/__init__.py
+++ b/rdflib/namespace/__init__.py
@@ -288,71 +288,6 @@ class ClosedNamespace(Namespace):
return dir(self)
-class _RDFNamespace(ClosedNamespace):
- """
- Closed namespace for RDF terms
- """
-
- def __new__(cls):
- return super().__new__(
- cls,
- "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
- terms=[
- # Syntax Names
- "RDF",
- "Description",
- "ID",
- "about",
- "parseType",
- "resource",
- "li",
- "nodeID",
- "datatype",
- # RDF Classes
- "Seq",
- "Bag",
- "Alt",
- "Statement",
- "Property",
- "List",
- "PlainLiteral",
- # RDF Properties
- "subject",
- "predicate",
- "object",
- "type",
- "value",
- "first",
- "rest",
- # and _n where n is a non-negative integer
- # RDF Resources
- "nil",
- # Added in RDF 1.1
- "XMLLiteral",
- "HTML",
- "langString",
- # Added in JSON-LD 1.1
- "JSON",
- "CompoundLiteral",
- "language",
- "direction",
- ],
- )
-
- def term(self, name):
- # Container membership properties
- if name.startswith("_"):
- try:
- i = int(name[1:])
- except ValueError:
- pass
- else:
- if i > 0:
- return URIRef(f"{self}_{i}")
-
- return super().term(name)
-
-
XMLNS = Namespace("http://www.w3.org/XML/1998/namespace")
diff --git a/rdflib/plugin.py b/rdflib/plugin.py
index 1605b0bb..719c7eaf 100644
--- a/rdflib/plugin.py
+++ b/rdflib/plugin.py
@@ -205,7 +205,7 @@ register("application/n-triples", Parser, "rdflib.plugins.parsers.ntriples", "NT
register("ntriples", Parser, "rdflib.plugins.parsers.ntriples", "NTParser")
register("nt", Parser, "rdflib.plugins.parsers.ntriples", "NTParser")
register("nt11", Parser, "rdflib.plugins.parsers.ntriples", "NTParser")
-register("application/json+ld", Parser, "rdflib.plugins.parsers.jsonld", "JsonLDParser")
+register("application/ld+json", Parser, "rdflib.plugins.parsers.jsonld", "JsonLDParser")
register("json-ld", Parser, "rdflib.plugins.parsers.jsonld", "JsonLDParser")
| RDFLib/rdflib | 038af4547e799845e08986867b24acafcbe72d48 | diff --git a/test/test_dataset.py b/test/test_dataset.py
index 734b58cd..4860b9c3 100644
--- a/test/test_dataset.py
+++ b/test/test_dataset.py
@@ -167,7 +167,36 @@ class DatasetTestCase(unittest.TestCase):
self.assertEqual(list(self.graph.objects(self.tarek, None)), [])
self.assertEqual(list(g1.objects(self.tarek, None)), [self.pizza])
-
+ def testIter(self):
+ """PR 1382: adds __iter__ to Dataset"""
+ d = Dataset()
+ uri_a = URIRef("https://example.com/a")
+ uri_b = URIRef("https://example.com/b")
+ uri_c = URIRef("https://example.com/c")
+ uri_d = URIRef("https://example.com/d")
+
+ d.add_graph(URIRef("https://example.com/g1"))
+ d.add((uri_a, uri_b, uri_c, URIRef("https://example.com/g1")))
+ d.add((uri_a, uri_b, uri_c, URIRef(
+ "https://example.com/g1"))) # pointless addition: duplicates above
+
+ d.add_graph(URIRef("https://example.com/g2"))
+ d.add((uri_a, uri_b, uri_c, URIRef("https://example.com/g2")))
+ d.add((uri_a, uri_b, uri_d, URIRef("https://example.com/g1"))) # new, uri_d
+
+ # traditional iterator
+ i_trad = 0
+ for t in d.quads((None, None, None)):
+ i_trad += 1
+
+ # new Dataset.__iter__ iterator
+ i_new = 0
+ for t in d:
+ i_new += 1
+
+ self.assertEqual(i_new, i_trad) # both should be 3
+
+
# dynamically create classes for each registered Store
pluginname = None
diff --git a/test/test_namespace.py b/test/test_namespace.py
index 23fdb1e2..76f5bbf1 100644
--- a/test/test_namespace.py
+++ b/test/test_namespace.py
@@ -241,4 +241,7 @@ class NamespacePrefixTest(unittest.TestCase):
)
ref = URIRef("http://www.w3.org/1999/02/22-rdf-syntax-ns#type")
- self.assertTrue(ref in RDF, "_RDFNamespace does not include rdf:type")
+ self.assertTrue(ref in RDF, "RDF does not include rdf:type")
+
+ ref = URIRef("http://www.w3.org/1999/02/22-rdf-syntax-ns#_1")
+ self.assertTrue(ref in RDF, "RDF does not include rdf:_1")
| Add __iter__ method to Dataset
#### Motivation
It is convenient to be able to iterate over all triples in a `Graph` instance without invoking `graph.triples((None, None, None))`. When working with a small instance of `Dataset`, there are occasions where one will want to observe all of the quads in a similar manner.
#### Notes
This is trivial to implement by simply having an introduced `__iter__` method invoke `self.quads((None, None, None, None))` in exactly [the same way that it is done in `Graph`](https://github.com/RDFLib/rdflib/blob/538446e08f992b7fc333151367dd216611dcd8e3/rdflib/graph.py#L500). | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/test_dataset.py::DatasetTestCase::testIter",
"test/test_namespace.py::NamespacePrefixTest::test_contains_method"
] | [
"test/test_dataset.py::DatasetTestCase::testDefaultGraph",
"test/test_dataset.py::DatasetTestCase::testGraphAware",
"test/test_dataset.py::DatasetTestCase::testNotUnion",
"test/test_namespace.py::NamespaceTest::test_dcterms_title",
"test/test_namespace.py::NamespaceTest::test_iri",
"test/test_namespace.py::NamespaceTest::test_member",
"test/test_namespace.py::NamespaceTest::test_repr",
"test/test_namespace.py::NamespaceTest::test_str",
"test/test_namespace.py::ClosedNamespaceTest::test_member",
"test/test_namespace.py::ClosedNamespaceTest::test_missing_member",
"test/test_namespace.py::ClosedNamespaceTest::test_repr",
"test/test_namespace.py::ClosedNamespaceTest::test_str",
"test/test_namespace.py::URIPatternTest::test_format",
"test/test_namespace.py::URIPatternTest::test_repr",
"test/test_namespace.py::NamespacePrefixTest::test_closed_namespace",
"test/test_namespace.py::NamespacePrefixTest::test_compute_qname",
"test/test_namespace.py::NamespacePrefixTest::test_n3",
"test/test_namespace.py::NamespacePrefixTest::test_n32",
"test/test_namespace.py::NamespacePrefixTest::test_reset",
"test/test_namespace.py::NamespacePrefixTest::test_reset_preserve_prefixes"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2021-07-29T19:54:51Z" | bsd-3-clause |
|
RDFLib__rdflib-1386 | diff --git a/docs/intro_to_sparql.rst b/docs/intro_to_sparql.rst
index ef7aab78..72a87c66 100644
--- a/docs/intro_to_sparql.rst
+++ b/docs/intro_to_sparql.rst
@@ -39,7 +39,8 @@ For example...
?a foaf:name ?aname .
?b foaf:name ?bname .
}"""
-
+
+ qres = g.query(knows_query)
for row in qres:
print(f"{row.aname} knows {row.bname}")
diff --git a/docs/sphinx-requirements.txt b/docs/sphinx-requirements.txt
index 7096a117..f5e39519 100644
--- a/docs/sphinx-requirements.txt
+++ b/docs/sphinx-requirements.txt
@@ -1,3 +1,3 @@
-sphinx==4.1.1
+sphinx==4.1.2
sphinxcontrib-apidoc
git+https://github.com/gniezen/n3pygments.git
diff --git a/rdflib/namespace/_RDF.py b/rdflib/namespace/_RDF.py
index 61bc4a58..f79d75a7 100644
--- a/rdflib/namespace/_RDF.py
+++ b/rdflib/namespace/_RDF.py
@@ -16,6 +16,7 @@ class RDF(DefinedNamespace):
"""
_fail = True
+ _underscore_num = True
# http://www.w3.org/1999/02/22-rdf-syntax-ns#List
nil: URIRef # The empty list, with no items in it. If the rest of a list is nil then the list has no more items in it.
diff --git a/rdflib/namespace/__init__.py b/rdflib/namespace/__init__.py
index 62a2a946..23f4ec0e 100644
--- a/rdflib/namespace/__init__.py
+++ b/rdflib/namespace/__init__.py
@@ -288,71 +288,6 @@ class ClosedNamespace(Namespace):
return dir(self)
-class _RDFNamespace(ClosedNamespace):
- """
- Closed namespace for RDF terms
- """
-
- def __new__(cls):
- return super().__new__(
- cls,
- "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
- terms=[
- # Syntax Names
- "RDF",
- "Description",
- "ID",
- "about",
- "parseType",
- "resource",
- "li",
- "nodeID",
- "datatype",
- # RDF Classes
- "Seq",
- "Bag",
- "Alt",
- "Statement",
- "Property",
- "List",
- "PlainLiteral",
- # RDF Properties
- "subject",
- "predicate",
- "object",
- "type",
- "value",
- "first",
- "rest",
- # and _n where n is a non-negative integer
- # RDF Resources
- "nil",
- # Added in RDF 1.1
- "XMLLiteral",
- "HTML",
- "langString",
- # Added in JSON-LD 1.1
- "JSON",
- "CompoundLiteral",
- "language",
- "direction",
- ],
- )
-
- def term(self, name):
- # Container membership properties
- if name.startswith("_"):
- try:
- i = int(name[1:])
- except ValueError:
- pass
- else:
- if i > 0:
- return URIRef(f"{self}_{i}")
-
- return super().term(name)
-
-
XMLNS = Namespace("http://www.w3.org/XML/1998/namespace")
diff --git a/rdflib/plugin.py b/rdflib/plugin.py
index 1605b0bb..719c7eaf 100644
--- a/rdflib/plugin.py
+++ b/rdflib/plugin.py
@@ -205,7 +205,7 @@ register("application/n-triples", Parser, "rdflib.plugins.parsers.ntriples", "NT
register("ntriples", Parser, "rdflib.plugins.parsers.ntriples", "NTParser")
register("nt", Parser, "rdflib.plugins.parsers.ntriples", "NTParser")
register("nt11", Parser, "rdflib.plugins.parsers.ntriples", "NTParser")
-register("application/json+ld", Parser, "rdflib.plugins.parsers.jsonld", "JsonLDParser")
+register("application/ld+json", Parser, "rdflib.plugins.parsers.jsonld", "JsonLDParser")
register("json-ld", Parser, "rdflib.plugins.parsers.jsonld", "JsonLDParser")
| RDFLib/rdflib | 038af4547e799845e08986867b24acafcbe72d48 | diff --git a/test/test_namespace.py b/test/test_namespace.py
index 23fdb1e2..76f5bbf1 100644
--- a/test/test_namespace.py
+++ b/test/test_namespace.py
@@ -241,4 +241,7 @@ class NamespacePrefixTest(unittest.TestCase):
)
ref = URIRef("http://www.w3.org/1999/02/22-rdf-syntax-ns#type")
- self.assertTrue(ref in RDF, "_RDFNamespace does not include rdf:type")
+ self.assertTrue(ref in RDF, "RDF does not include rdf:type")
+
+ ref = URIRef("http://www.w3.org/1999/02/22-rdf-syntax-ns#_1")
+ self.assertTrue(ref in RDF, "RDF does not include rdf:_1")
| RDF namespace does not allow rdf:Seq valid terms
Hi,
According to the [RDFS recommendation](https://www.w3.org/TR/rdf-schema/#ch_collectionvocab), elements of an rdf:Seq can be ordered by using predicates of the form:
`C rdf:_nnn O`
"where `nnn` is the decimal representation of an integer greater than 0 with no leading zeros". However in rdflibish notation these do not work:
```
>>> RDF["_1"]
Exception: term '_1' not in namespace 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'
>>> RDF._1
Exception: term '_1' not in namespace 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'
```
My current workaround is to mint new URIRefs for these, but I guess a more elegant solution could be provided?
Thanks,
Albert
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/test_namespace.py::NamespacePrefixTest::test_contains_method"
] | [
"test/test_namespace.py::NamespaceTest::test_dcterms_title",
"test/test_namespace.py::NamespaceTest::test_iri",
"test/test_namespace.py::NamespaceTest::test_member",
"test/test_namespace.py::NamespaceTest::test_repr",
"test/test_namespace.py::NamespaceTest::test_str",
"test/test_namespace.py::ClosedNamespaceTest::test_member",
"test/test_namespace.py::ClosedNamespaceTest::test_missing_member",
"test/test_namespace.py::ClosedNamespaceTest::test_repr",
"test/test_namespace.py::ClosedNamespaceTest::test_str",
"test/test_namespace.py::URIPatternTest::test_format",
"test/test_namespace.py::URIPatternTest::test_repr",
"test/test_namespace.py::NamespacePrefixTest::test_closed_namespace",
"test/test_namespace.py::NamespacePrefixTest::test_compute_qname",
"test/test_namespace.py::NamespacePrefixTest::test_n3",
"test/test_namespace.py::NamespacePrefixTest::test_n32",
"test/test_namespace.py::NamespacePrefixTest::test_reset",
"test/test_namespace.py::NamespacePrefixTest::test_reset_preserve_prefixes"
] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2021-08-05T01:56:13Z" | bsd-3-clause |
|
RDFLib__rdflib-1496 | diff --git a/rdflib/store.py b/rdflib/store.py
index 96390171..44c01e28 100644
--- a/rdflib/store.py
+++ b/rdflib/store.py
@@ -158,7 +158,6 @@ class Store(object):
from rdflib.term import Literal
from rdflib.graph import Graph, QuotedGraph
from rdflib.term import Variable
- from rdflib.term import Statement
self.__node_pickler = np = NodePickler()
np.register(self, "S")
@@ -168,7 +167,6 @@ class Store(object):
np.register(Graph, "G")
np.register(QuotedGraph, "Q")
np.register(Variable, "V")
- np.register(Statement, "s")
return self.__node_pickler
node_pickler = property(__get_node_pickler)
diff --git a/rdflib/term.py b/rdflib/term.py
index 796a76b3..9f2255e5 100644
--- a/rdflib/term.py
+++ b/rdflib/term.py
@@ -32,7 +32,6 @@ __all__ = [
"BNode",
"Literal",
"Variable",
- "Statement",
]
import logging
@@ -446,7 +445,7 @@ class BNode(Identifier):
if basepath is None:
basepath = rdflib_skolem_genid
skolem = "%s%s" % (basepath, str(self))
- return URIRef(urljoin(authority, skolem))
+ return RDFLibGenid(urljoin(authority, skolem))
class Literal(Identifier):
@@ -1739,24 +1738,6 @@ class Variable(Identifier):
return (Variable, (str(self),))
-class Statement(Node, tuple):
- def __new__(cls, triple, context):
- subject, predicate, object = triple
- warnings.warn(
- "Class Statement is deprecated, and will be removed in "
- + "the future. If you use this please let rdflib-dev know!",
- category=DeprecationWarning,
- stacklevel=2,
- )
- return tuple.__new__(cls, ((subject, predicate, object), context))
-
- def __reduce__(self):
- return (Statement, (self[0], self[1]))
-
- def toPython(self):
- return (self[0], self[1])
-
-
# Nodes are ordered like this
# See http://www.w3.org/TR/sparql11-query/#modOrderBy
# we leave "space" for more subclasses of Node elsewhere
| RDFLib/rdflib | 327de4ecc9e7a9a7c73b55d1b59b6e1e600f64ed | diff --git a/test/test_980.py b/test/test_980.py
new file mode 100644
index 00000000..3c60a849
--- /dev/null
+++ b/test/test_980.py
@@ -0,0 +1,28 @@
+from rdflib import Graph
+
+
+def test_980():
+ """
+ The problem that this test ensures rdflib solves is that, previous to PR #1108, the
+ parsing of two triples with the same n-triples Blank Nodes IDs, here _:0, would
+ result in triples with the same rdflib internal BN IDs, e.g.
+ rdflib.term.BNode('Ne3fd8261b37741fca22d502483d88964'), see the Issue #980. They
+ should have different IDs.
+ """
+ graph1 = """
+ _:0 <http://purl.obolibrary.org/obo/RO_0002350> <http://www.gbif.org/species/0000001> .
+ """
+ graph2 = """
+ _:0 <http://purl.obolibrary.org/obo/RO_0002350> <http://www.gbif.org/species/0000002> .
+ """
+
+ g = Graph()
+ g.parse(data=graph1, format="nt")
+ g.parse(data=graph2, format="nt")
+
+ subs = 0
+ for s in g.subjects(None, None):
+ subs += 1
+
+ # we must see two different BN subjects
+ assert subs == 2
diff --git a/test/test_issue1404.py b/test/test_issue1404.py
new file mode 100644
index 00000000..469f713e
--- /dev/null
+++ b/test/test_issue1404.py
@@ -0,0 +1,42 @@
+from rdflib import Graph, URIRef, FOAF
+from rdflib.term import RDFLibGenid
+from rdflib.compare import isomorphic
+
+
+def test_skolem_de_skolem_roundtrip():
+ """Test round-trip of skolemization/de-skolemization of data.
+
+ Issue: https://github.com/RDFLib/rdflib/issues/1404
+ """
+
+ ttl = '''
+ @prefix wd: <http://www.wikidata.org/entity/> .
+ @prefix foaf: <http://xmlns.com/foaf/0.1/> .
+
+ wd:Q1203 foaf:knows [ a foaf:Person;
+ foaf:name "Ringo" ].
+ '''
+
+ graph = Graph()
+ graph.parse(data=ttl, format='turtle')
+
+ query = {"subject": URIRef("http://www.wikidata.org/entity/Q1203"), "predicate": FOAF.knows}
+
+ # Save the original bnode id.
+ bnode_id = graph.value(**query)
+
+ skolemized_graph = graph.skolemize()
+
+ # Check the BNode is now an RDFLibGenid after skolemization.
+ skolem_bnode = skolemized_graph.value(**query)
+ assert type(skolem_bnode) == RDFLibGenid
+
+ # Check that the original bnode id exists somewhere in the uri.
+ assert bnode_id in skolem_bnode
+
+ # Check that the original data is not isomorphic with the skolemized data.
+ assert not isomorphic(graph, skolemized_graph)
+
+ # Check that the original graph data is the same as the de-skolemized data.
+ de_skolemized_graph = skolemized_graph.de_skolemize()
+ assert isomorphic(graph, de_skolemized_graph)
| Resolve .term.Statement deprecation
`.term.Statement` has been deprecated since 2012. Is there any plan to actually remove it or un-deprecate it?
https://github.com/RDFLib/rdflib/blob/master/rdflib/term.py#L1699 | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/test_issue1404.py::test_skolem_de_skolem_roundtrip"
] | [
"test/test_980.py::test_980"
] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2021-12-10T13:12:12Z" | bsd-3-clause |
|
RDFLib__rdflib-1894 | diff --git a/rdflib/plugins/sparql/evaluate.py b/rdflib/plugins/sparql/evaluate.py
index edd322e5..49bff943 100644
--- a/rdflib/plugins/sparql/evaluate.py
+++ b/rdflib/plugins/sparql/evaluate.py
@@ -405,18 +405,26 @@ def _yieldBindingsFromServiceCallResult(
res_dict: Dict[Variable, Identifier] = {}
for var in variables:
if var in r and r[var]:
- if r[var]["type"] == "uri":
- res_dict[Variable(var)] = URIRef(r[var]["value"])
- elif r[var]["type"] == "bnode":
- res_dict[Variable(var)] = BNode(r[var]["value"])
- elif r[var]["type"] == "literal" and "datatype" in r[var]:
+ var_binding = r[var]
+ var_type = var_binding["type"]
+ if var_type == "uri":
+ res_dict[Variable(var)] = URIRef(var_binding["value"])
+ elif var_type == "literal":
res_dict[Variable(var)] = Literal(
- r[var]["value"], datatype=r[var]["datatype"]
+ var_binding["value"],
+ datatype=var_binding.get("datatype"),
+ lang=var_binding.get("xml:lang"),
)
- elif r[var]["type"] == "literal" and "xml:lang" in r[var]:
+ # This is here because of
+ # https://www.w3.org/TR/2006/NOTE-rdf-sparql-json-res-20061004/#variable-binding-results
+ elif var_type == "typed-literal":
res_dict[Variable(var)] = Literal(
- r[var]["value"], lang=r[var]["xml:lang"]
+ var_binding["value"], datatype=URIRef(var_binding["datatype"])
)
+ elif var_type == "bnode":
+ res_dict[Variable(var)] = BNode(var_binding["value"])
+ else:
+ raise ValueError(f"invalid type {var_type!r} for variable {var!r}")
yield FrozenBindings(ctx, res_dict)
| RDFLib/rdflib | 246c887531d392ba475fb48ba6d21917f510abfe | diff --git a/test/test_sparql/test_service.py b/test/test_sparql/test_service.py
index 9798f3df..31ba6e8a 100644
--- a/test/test_sparql/test_service.py
+++ b/test/test_sparql/test_service.py
@@ -1,8 +1,31 @@
+import json
+from contextlib import ExitStack
from test.utils import helper
+from test.utils.httpservermock import (
+ MethodName,
+ MockHTTPResponse,
+ ServedBaseHTTPServerMock,
+)
+from typing import (
+ Dict,
+ FrozenSet,
+ Generator,
+ List,
+ Mapping,
+ Optional,
+ Sequence,
+ Tuple,
+ Type,
+ Union,
+)
+
+import pytest
from rdflib import Graph, Literal, URIRef, Variable
from rdflib.compare import isomorphic
+from rdflib.namespace import XSD
from rdflib.plugins.sparql import prepareQuery
+from rdflib.term import BNode, Identifier
def test_service():
@@ -135,13 +158,171 @@ def test_service_with_implicit_select_and_allcaps():
assert len(results) == 3
-# def test_with_fixture(httpserver):
-# httpserver.expect_request("/sparql/?query=SELECT * WHERE ?s ?p ?o").respond_with_json({"vars": ["s","p","o"], "bindings":[]})
-# test_server = httpserver.url_for('/sparql')
-# g = Graph()
-# q = 'SELECT * WHERE {SERVICE <'+test_server+'>{?s ?p ?o} . ?s ?p ?o .}'
-# results = g.query(q)
-# assert len(results) == 0
+def freeze_bindings(
+ bindings: Sequence[Mapping[Variable, Identifier]]
+) -> FrozenSet[FrozenSet[Tuple[Variable, Identifier]]]:
+ result = []
+ for binding in bindings:
+ result.append(frozenset(((key, value)) for key, value in binding.items()))
+ return frozenset(result)
+
+
+def test_simple_not_null():
+ """Test service returns simple literals not as NULL.
+
+ Issue: https://github.com/RDFLib/rdflib/issues/1278
+ """
+
+ g = Graph()
+ q = """SELECT ?s ?p ?o
+WHERE {
+ SERVICE <https://DBpedia.org/sparql> {
+ VALUES (?s ?p ?o) {(<http://example.org/a> <http://example.org/b> "c")}
+ }
+}"""
+ results = helper.query_with_retry(g, q)
+ assert results.bindings[0].get(Variable("o")) == Literal("c")
+
+
+def test_service_node_types():
+ """Test if SERVICE properly returns different types of nodes:
+ - URI;
+ - Simple Literal;
+ - Literal with datatype ;
+ - Literal with language tag .
+ """
+
+ g = Graph()
+ q = """
+SELECT ?o
+WHERE {
+ SERVICE <https://dbpedia.org/sparql> {
+ VALUES (?s ?p ?o) {
+ (<http://example.org/a> <http://example.org/uri> <http://example.org/URI>)
+ (<http://example.org/a> <http://example.org/simpleLiteral> "Simple Literal")
+ (<http://example.org/a> <http://example.org/dataType> "String Literal"^^xsd:string)
+ (<http://example.org/a> <http://example.org/language> "String Language"@en)
+ (<http://example.org/a> <http://example.org/language> "String Language"@en)
+ }
+ }
+ FILTER( ?o IN (<http://example.org/URI>, "Simple Literal", "String Literal"^^xsd:string, "String Language"@en) )
+}"""
+ results = helper.query_with_retry(g, q)
+
+ expected = freeze_bindings(
+ [
+ {Variable('o'): URIRef('http://example.org/URI')},
+ {Variable('o'): Literal('Simple Literal')},
+ {
+ Variable('o'): Literal(
+ 'String Literal',
+ datatype=URIRef('http://www.w3.org/2001/XMLSchema#string'),
+ )
+ },
+ {Variable('o'): Literal('String Language', lang='en')},
+ ]
+ )
+ assert expected == freeze_bindings(results.bindings)
+
+
[email protected](scope="module")
+def module_httpmock() -> Generator[ServedBaseHTTPServerMock, None, None]:
+ with ServedBaseHTTPServerMock() as httpmock:
+ yield httpmock
+
+
[email protected](scope="function")
+def httpmock(
+ module_httpmock: ServedBaseHTTPServerMock,
+) -> Generator[ServedBaseHTTPServerMock, None, None]:
+ module_httpmock.reset()
+ yield module_httpmock
+
+
[email protected](
+ ("response_bindings", "expected_result"),
+ [
+ (
+ [
+ {"type": "uri", "value": "http://example.org/uri"},
+ {"type": "literal", "value": "literal without type or lang"},
+ {"type": "literal", "value": "literal with lang", "xml:lang": "en"},
+ {
+ "type": "typed-literal",
+ "value": "typed-literal with datatype",
+ "datatype": f"{XSD.string}",
+ },
+ {
+ "type": "literal",
+ "value": "literal with datatype",
+ "datatype": f"{XSD.string}",
+ },
+ {"type": "bnode", "value": "ohci6Te6aidooNgo"},
+ ],
+ [
+ URIRef('http://example.org/uri'),
+ Literal('literal without type or lang'),
+ Literal('literal with lang', lang='en'),
+ Literal(
+ 'typed-literal with datatype',
+ datatype=URIRef('http://www.w3.org/2001/XMLSchema#string'),
+ ),
+ Literal('literal with datatype', datatype=XSD.string),
+ BNode('ohci6Te6aidooNgo'),
+ ],
+ ),
+ (
+ [
+ {"type": "invalid-type"},
+ ],
+ ValueError,
+ ),
+ ],
+)
+def test_with_mock(
+ httpmock: ServedBaseHTTPServerMock,
+ response_bindings: List[Dict[str, str]],
+ expected_result: Union[List[Identifier], Type[Exception]],
+) -> None:
+ """
+ This tests that bindings for a variable named var
+ """
+ graph = Graph()
+ query = """
+ PREFIX ex: <http://example.org/>
+ SELECT ?var
+ WHERE {
+ SERVICE <REMOTE_URL> {
+ ex:s ex:p ?var
+ }
+ }
+ """
+ query = query.replace("REMOTE_URL", httpmock.url)
+ response = {
+ "head": {"vars": ["var"]},
+ "results": {"bindings": [{"var": item} for item in response_bindings]},
+ }
+ httpmock.responses[MethodName.GET].append(
+ MockHTTPResponse(
+ 200,
+ "OK",
+ json.dumps(response).encode("utf-8"),
+ {"Content-Type": ["application/sparql-results+json"]},
+ )
+ )
+ catcher: Optional[pytest.ExceptionInfo[Exception]] = None
+
+ with ExitStack() as xstack:
+ if isinstance(expected_result, type) and issubclass(expected_result, Exception):
+ catcher = xstack.enter_context(pytest.raises(expected_result))
+ else:
+ expected_bindings = [{Variable("var"): item} for item in expected_result]
+ bindings = graph.query(query).bindings
+ if catcher is not None:
+ assert catcher is not None
+ assert catcher.value is not None
+ else:
+ assert expected_bindings == bindings
if __name__ == "__main__":
@@ -151,3 +332,4 @@ if __name__ == "__main__":
test_service_with_implicit_select()
test_service_with_implicit_select_and_prefix()
test_service_with_implicit_select_and_base()
+ test_service_node_types()
| In using SERVICE, "string" variables get retrieved as NULL
I was testing the federated SPARQL queries using "service". There are two issues:
* only low-case "service" is accepted, i.e., SPARQL with "SERVICE" would fail. This was fixed for next release.
* "string" variables get retrieved as null. This is new.
Sorry, I do not have time to create a small reproducible example.
Below, two examples of querying the same SPARQL endpoint, one with
from pandas import DataFrame
from rdflib.plugins.sparql.processor import SPARQLResult
def sparql_results_to_df(results: SPARQLResult) -> DataFrame:
return DataFrame(
data=([None if x is None else x.toPython() for x in row] for row in results),
columns=[str(x) for x in results.vars],
)
qf="""
PREFIX tsmodel: <http://siemens.com/tsmodel/>
PREFIX vobj: <http://siemens.com/tsmodel/VAROBJECTS#>
SELECT ?x ?node_name ?idx
{
service <http://localhost:8080/sparql>
{
?x a tsmodel:VAROBJECTS .
?x vobj:idx ?idx .
?x vobj:node_name ?node_name .
}
}
"""
results=graph.query(qf)
df=sparql_results_to_df(results)
df.head(20)
x node_name idx
0 http://siemens.com/tsmodel/VAROBJECTS/idx=1 None 1
1 http://siemens.com/tsmodel/VAROBJECTS/idx=2 None 2
2 http://siemens.com/tsmodel/VAROBJECTS/idx=3 None 3
3 http://siemens.com/tsmodel/VAROBJECTS/idx=4 None 4
4 http://siemens.com/tsmodel/VAROBJECTS/idx=5 None 5
import sparql_dataframe
endpoint = "http://localhost:8080/sparql"
q = """
PREFIX tsmodel: <http://siemens.com/tsmodel/>
PREFIX vobj: <http://siemens.com/tsmodel/VAROBJECTS#>
SELECT ?x ?node_name ?idx {
?x a tsmodel:VAROBJECTS .
?x vobj:idx ?idx .
?x vobj:node_name ?node_name .
}
"""
df = sparql_dataframe.get(endpoint, q)
df.head()
x node_name idx
0 http://siemens.com/tsmodel/VAROBJECTS/idx=1 ns=3;s="ultrasonicLeft" 1
1 http://siemens.com/tsmodel/VAROBJECTS/idx=2 ns=3;s="voltageL1-N" 2
2 http://siemens.com/tsmodel/VAROBJECTS/idx=3 ns=3;s="voltageL2-N" 3
3 http://siemens.com/tsmodel/VAROBJECTS/idx=4 ns=3;s="voltageL3-N" 4
4 http://siemens.com/tsmodel/VAROBJECTS/idx=5 ns=3;s="currentL1" 5
I do have more examples like this. As I have checked, "int", "float", "datetime" work fine. But, "string" variables are always get "NULL".
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/test_sparql/test_service.py::test_simple_not_null",
"test/test_sparql/test_service.py::test_service_node_types",
"test/test_sparql/test_service.py::test_with_mock[response_bindings0-expected_result0]",
"test/test_sparql/test_service.py::test_with_mock[response_bindings1-ValueError]"
] | [
"test/test_sparql/test_service.py::test_service",
"test/test_sparql/test_service.py::test_service_with_bind",
"test/test_sparql/test_service.py::test_service_with_values",
"test/test_sparql/test_service.py::test_service_with_implicit_select",
"test/test_sparql/test_service.py::test_service_with_implicit_select_and_prefix",
"test/test_sparql/test_service.py::test_service_with_implicit_select_and_base",
"test/test_sparql/test_service.py::test_service_with_implicit_select_and_allcaps"
] | {
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
} | "2022-05-08T09:23:24Z" | bsd-3-clause |
|
RDFLib__rdflib-1902 | diff --git a/pyproject.toml b/pyproject.toml
index 8cb4f5a8..39178818 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -25,6 +25,8 @@ pep8-naming = ["-N802", "-N803", "-N806", "-N815"]
pep8-naming = ["-N802", "-N803", "-N806", "-N816"]
[tool.flakeheaven.exceptions."rdflib/plugins/serializers/turtle.py"]
pep8-naming = ["-N802", "-N806", "-N815"]
+[tool.flakeheaven.exceptions."rdflib/__init__.py"]
+pycodestyle = ["-E402"]
[tool.black]
diff --git a/rdflib/__init__.py b/rdflib/__init__.py
index 2dbba042..47b3d146 100644
--- a/rdflib/__init__.py
+++ b/rdflib/__init__.py
@@ -84,6 +84,8 @@ __all__ = [
"VOID",
"XSD",
"util",
+ "plugin",
+ "query",
]
import logging
@@ -157,7 +159,7 @@ In particular, this determines how the rich comparison operators for
Literal work, eq, __neq__, __lt__, etc.
"""
-from rdflib import plugin, query
+
from rdflib.graph import ConjunctiveGraph, Dataset, Graph
from rdflib.namespace import (
BRICK,
@@ -190,9 +192,5 @@ from rdflib.namespace import (
)
from rdflib.term import BNode, IdentifiedNode, Literal, URIRef, Variable
-# tedious sop to flake8
-assert plugin
-assert query
-
-from rdflib import util
-from rdflib.container import *
+from rdflib import plugin, query, util # isort:skip
+from rdflib.container import * # isort:skip # noqa:F401,F403
diff --git a/rdflib/graph.py b/rdflib/graph.py
index 401b14a7..eb1dc7bc 100644
--- a/rdflib/graph.py
+++ b/rdflib/graph.py
@@ -24,8 +24,11 @@ from urllib.parse import urlparse
from urllib.request import url2pathname
from warnings import warn
+import rdflib.exceptions as exceptions
+import rdflib.namespace as namespace # noqa: F401 # This is here because it is used in a docstring.
+import rdflib.plugin as plugin
+import rdflib.query as query
import rdflib.util # avoid circular dependency
-from rdflib import exceptions, namespace, plugin, query
from rdflib.collection import Collection
from rdflib.exceptions import ParserError
from rdflib.namespace import RDF, Namespace, NamespaceManager
@@ -120,13 +123,13 @@ Instantiating Graphs with default store (Memory) and default identifier
<class 'rdflib.term.BNode'>
Instantiating Graphs with a Memory store and an identifier -
-<http://rdflib.net>:
+<https://rdflib.github.io>:
- >>> g = Graph('Memory', URIRef("http://rdflib.net"))
+ >>> g = Graph('Memory', URIRef("https://rdflib.github.io"))
>>> g.identifier
- rdflib.term.URIRef('http://rdflib.net')
+ rdflib.term.URIRef('https://rdflib.github.io')
>>> str(g) # doctest: +NORMALIZE_WHITESPACE
- "<http://rdflib.net> a rdfg:Graph;rdflib:storage
+ "<https://rdflib.github.io> a rdfg:Graph;rdflib:storage
[a rdflib:Store;rdfs:label 'Memory']."
Creating a ConjunctiveGraph - The top level container for all named Graphs
@@ -146,7 +149,7 @@ via triple pattern:
>>> g.add((statementId, RDF.type, RDF.Statement)) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g.add((statementId, RDF.subject,
- ... URIRef("http://rdflib.net/store/ConjunctiveGraph"))) # doctest: +ELLIPSIS
+ ... URIRef("https://rdflib.github.io/store/ConjunctiveGraph"))) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g.add((statementId, RDF.predicate, namespace.RDFS.label)) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
@@ -217,7 +220,7 @@ the same store:
>>> g1.add((stmt1, RDF.type, RDF.Statement)) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g1.add((stmt1, RDF.subject,
- ... URIRef('http://rdflib.net/store/ConjunctiveGraph'))) # doctest: +ELLIPSIS
+ ... URIRef('https://rdflib.github.io/store/ConjunctiveGraph'))) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g1.add((stmt1, RDF.predicate, namespace.RDFS.label)) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
@@ -226,7 +229,7 @@ the same store:
>>> g2.add((stmt2, RDF.type, RDF.Statement)) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g2.add((stmt2, RDF.subject,
- ... URIRef('http://rdflib.net/store/ConjunctiveGraph'))) # doctest: +ELLIPSIS
+ ... URIRef('https://rdflib.github.io/store/ConjunctiveGraph'))) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g2.add((stmt2, RDF.predicate, RDF.type)) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
@@ -235,7 +238,7 @@ the same store:
>>> g3.add((stmt3, RDF.type, RDF.Statement)) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g3.add((stmt3, RDF.subject,
- ... URIRef('http://rdflib.net/store/ConjunctiveGraph'))) # doctest: +ELLIPSIS
+ ... URIRef('https://rdflib.github.io/store/ConjunctiveGraph'))) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g3.add((stmt3, RDF.predicate, namespace.RDFS.comment)) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
@@ -272,7 +275,7 @@ Parsing N3 from a string
... @prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
... @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
... [ a rdf:Statement ;
- ... rdf:subject <http://rdflib.net/store#ConjunctiveGraph>;
+ ... rdf:subject <https://rdflib.github.io/store#ConjunctiveGraph>;
... rdf:predicate rdfs:label;
... rdf:object "Conjunctive Graph" ] .
... '''
@@ -282,11 +285,11 @@ Parsing N3 from a string
Using Namespace class:
- >>> RDFLib = Namespace("http://rdflib.net/")
+ >>> RDFLib = Namespace("https://rdflib.github.io/")
>>> RDFLib.ConjunctiveGraph
- rdflib.term.URIRef('http://rdflib.net/ConjunctiveGraph')
+ rdflib.term.URIRef('https://rdflib.github.io/ConjunctiveGraph')
>>> RDFLib["Graph"]
- rdflib.term.URIRef('http://rdflib.net/Graph')
+ rdflib.term.URIRef('https://rdflib.github.io/Graph')
"""
@@ -2002,7 +2005,7 @@ class Dataset(ConjunctiveGraph):
>>> for c in ds.graphs(): # doctest: +SKIP
... print(c) # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS
DEFAULT
- http://rdlib.net/.well-known/genid/rdflib/N...
+ https://rdflib.github.io/.well-known/genid/rdflib/N...
http://www.example.com/gr
>>> # Note that the Dataset.graphs() call returns names of empty graphs,
>>> # too. This can be restricted:
@@ -2046,10 +2049,12 @@ class Dataset(ConjunctiveGraph):
def graph(self, identifier=None, base=None):
if identifier is None:
- from rdflib.term import rdflib_skolem_genid
+ from rdflib.term import _SKOLEM_DEFAULT_AUTHORITY, rdflib_skolem_genid
self.bind(
- "genid", "http://rdflib.net" + rdflib_skolem_genid, override=False
+ "genid",
+ _SKOLEM_DEFAULT_AUTHORITY + rdflib_skolem_genid,
+ override=False,
)
identifier = BNode().skolemize()
diff --git a/rdflib/parser.py b/rdflib/parser.py
index 6bce4842..ceee51d4 100644
--- a/rdflib/parser.py
+++ b/rdflib/parser.py
@@ -31,6 +31,7 @@ from urllib.parse import urljoin
from urllib.request import Request, url2pathname, urlopen
from xml.sax import xmlreader
+import rdflib.util
from rdflib import __version__
from rdflib.namespace import Namespace
from rdflib.term import URIRef
@@ -183,7 +184,8 @@ class StringInputSource(InputSource):
headers = {
- "User-agent": "rdflib-%s (http://rdflib.net/; [email protected])" % __version__
+ "User-agent": "rdflib-%s (https://rdflib.github.io/; [email protected])"
+ % __version__
}
@@ -447,7 +449,7 @@ def _create_input_source_from_location(
base = pathlib.Path.cwd().as_uri()
- absolute_location = URIRef(location, base=base)
+ absolute_location = URIRef(rdflib.util._iri2uri(location), base=base)
if absolute_location.startswith("file:///"):
filename = url2pathname(absolute_location.replace("file:///", "/"))
diff --git a/rdflib/term.py b/rdflib/term.py
index 30dd7fc6..c82df3d5 100644
--- a/rdflib/term.py
+++ b/rdflib/term.py
@@ -75,6 +75,8 @@ if TYPE_CHECKING:
from .namespace import NamespaceManager
from .paths import AlternativePath, InvPath, NegatedPath, Path, SequencePath
+_SKOLEM_DEFAULT_AUTHORITY = "https://rdflib.github.io"
+
logger = logging.getLogger(__name__)
skolem_genid = "/.well-known/genid/"
rdflib_skolem_genid = "/.well-known/genid/rdflib/"
@@ -482,7 +484,7 @@ class BNode(IdentifiedNode):
.. versionadded:: 4.0
"""
if authority is None:
- authority = "http://rdlib.net/"
+ authority = _SKOLEM_DEFAULT_AUTHORITY
if basepath is None:
basepath = rdflib_skolem_genid
skolem = "%s%s" % (basepath, str(self))
diff --git a/rdflib/util.py b/rdflib/util.py
index 246b5cc8..b73a9594 100644
--- a/rdflib/util.py
+++ b/rdflib/util.py
@@ -36,6 +36,7 @@ from typing import (
Tuple,
TypeVar,
)
+from urllib.parse import quote, urlsplit, urlunsplit
import rdflib.graph # avoid circular dependency
from rdflib.compat import sign
@@ -58,6 +59,7 @@ __all__ = [
"find_roots",
"get_tree",
"_coalesce",
+ "_iri2uri",
]
@@ -476,3 +478,36 @@ def _coalesce(*args: Optional[_AnyT]) -> Optional[_AnyT]:
if arg is not None:
return arg
return None
+
+
+def _iri2uri(iri: str) -> str:
+ """
+ Convert an IRI to a URI (Python 3).
+ https://stackoverflow.com/a/42309027
+ https://stackoverflow.com/a/40654295
+ netloc should be encoded using IDNA;
+ non-ascii URL path should be encoded to UTF-8 and then percent-escaped;
+ non-ascii query parameters should be encoded to the encoding of a page
+ URL was extracted from (or to the encoding server uses), then
+ percent-escaped.
+ >>> _iri2uri("https://dbpedia.org/resource/Almería")
+ 'https://dbpedia.org/resource/Almer%C3%ADa'
+ """
+
+ (scheme, netloc, path, query, fragment) = urlsplit(iri)
+
+ # Just support http/https, otherwise return the iri unmolested
+ if scheme not in ["http", "https"]:
+ return iri
+
+ scheme = quote(scheme)
+ netloc = quote(netloc.encode("idna").decode("utf-8"))
+ path = quote(path)
+ query = quote(query)
+ fragment = quote(fragment)
+ uri = urlunsplit((scheme, netloc, path, query, fragment))
+
+ if iri.endswith("#") and not uri.endswith("#"):
+ uri += "#"
+
+ return uri
| RDFLib/rdflib | ccb9c4a56e6bfcf1474480552e62a21461b85239 | diff --git a/test/jsonld/test_localsuite.py b/test/jsonld/test_localsuite.py
index 8088e07c..117efe8c 100644
--- a/test/jsonld/test_localsuite.py
+++ b/test/jsonld/test_localsuite.py
@@ -8,7 +8,7 @@ from rdflib.term import URIRef
from . import runner
-TC_BASE = "http://rdflib.net/rdflib-jsonld/local-testsuite/"
+TC_BASE = "https://rdflib.github.io/rdflib-jsonld/local-testsuite/"
testsuite_dir = p.join(p.abspath(p.dirname(__file__)), "local-suite")
diff --git a/test/test_dataset/test_dataset.py b/test/test_dataset/test_dataset.py
index f09bcb61..577e289c 100644
--- a/test/test_dataset/test_dataset.py
+++ b/test/test_dataset/test_dataset.py
@@ -7,7 +7,7 @@ from test.data import context1, likes, pizza, tarek
import pytest
from rdflib import URIRef, plugin
-from rdflib.graph import DATASET_DEFAULT_GRAPH_ID, Dataset
+from rdflib.graph import DATASET_DEFAULT_GRAPH_ID, Dataset, Graph, Namespace
# Will also run SPARQLUpdateStore tests against local SPARQL1.1 endpoint if
# available. This assumes SPARQL1.1 query/update endpoints running locally at
@@ -231,3 +231,38 @@ def test_iter(get_dataset):
i_new += 1
assert i_new == i_trad # both should be 3
+
+
+EGSCHEMA = Namespace("example:")
+
+
+def test_subgraph_without_identifier() -> None:
+ """
+ Graphs with no identifies assigned are identified by Skolem IRIs with a
+ prefix that is bound to `genid`.
+
+ TODO: This is somewhat questionable and arbitrary behaviour and should be
+ reviewed at some point.
+ """
+
+ dataset = Dataset()
+
+ nman = dataset.namespace_manager
+
+ genid_prefix = URIRef("https://rdflib.github.io/.well-known/genid/rdflib/")
+
+ namespaces = set(nman.namespaces())
+ assert (
+ next((namespace for namespace in namespaces if namespace[0] == "genid"), None)
+ is None
+ )
+
+ subgraph: Graph = dataset.graph()
+ subgraph.add((EGSCHEMA["subject"], EGSCHEMA["predicate"], EGSCHEMA["object"]))
+
+ namespaces = set(nman.namespaces())
+ assert next(
+ (namespace for namespace in namespaces if namespace[0] == "genid"), None
+ ) == ("genid", genid_prefix)
+
+ assert f"{subgraph.identifier}".startswith(genid_prefix)
diff --git a/test/test_graph/test_graph_http.py b/test/test_graph/test_graph_http.py
index 1ef2fea8..1ae203d0 100644
--- a/test/test_graph/test_graph_http.py
+++ b/test/test_graph/test_graph_http.py
@@ -1,12 +1,15 @@
import re
from http.server import BaseHTTPRequestHandler
+from test.data import TEST_DATA_DIR
from test.utils import GraphHelper
+from test.utils.graph import cached_graph
from test.utils.httpservermock import (
MethodName,
MockHTTPResponse,
ServedBaseHTTPServerMock,
ctx_http_server,
)
+from typing import Generator
from urllib.error import HTTPError
import pytest
@@ -227,3 +230,37 @@ class TestGraphHTTP:
graph.parse(location=url, format="turtle")
assert raised.value.code == 500
+
+
[email protected](scope="module")
+def module_httpmock() -> Generator[ServedBaseHTTPServerMock, None, None]:
+ with ServedBaseHTTPServerMock() as httpmock:
+ yield httpmock
+
+
[email protected](scope="function")
+def httpmock(
+ module_httpmock: ServedBaseHTTPServerMock,
+) -> Generator[ServedBaseHTTPServerMock, None, None]:
+ module_httpmock.reset()
+ yield module_httpmock
+
+
+def test_iri_source(httpmock: ServedBaseHTTPServerMock) -> None:
+ diverse_triples_path = TEST_DATA_DIR / "variants/diverse_triples.ttl"
+
+ httpmock.responses[MethodName.GET].append(
+ MockHTTPResponse(
+ 200,
+ "OK",
+ diverse_triples_path.read_bytes(),
+ {"Content-Type": ["text/turtle"]},
+ )
+ )
+ g = Graph()
+ g.parse(f"{httpmock.url}/resource/Almería")
+ assert httpmock.call_count == 1
+ GraphHelper.assert_triple_sets_equals(cached_graph((diverse_triples_path,)), g)
+
+ req = httpmock.requests[MethodName.GET].pop(0)
+ assert req.path == "/resource/Almer%C3%ADa"
diff --git a/test/test_graph/test_skolemization.py b/test/test_graph/test_skolemization.py
index f045bf8d..aee86bae 100644
--- a/test/test_graph/test_skolemization.py
+++ b/test/test_graph/test_skolemization.py
@@ -22,10 +22,15 @@ base_triples = {
[
(URIRef("http://example.com"), None),
(Literal("some string in here ..."), None),
- (BNode("GMeng4V7"), "http://rdlib.net/.well-known/genid/rdflib/GMeng4V7"),
+ (
+ BNode("GMeng4V7"),
+ "https://rdflib.github.io/.well-known/genid/rdflib/GMeng4V7",
+ ),
(
BNode(),
- re.compile("^" + re.escape("http://rdlib.net/.well-known/genid/rdflib/")),
+ re.compile(
+ "^" + re.escape("https://rdflib.github.io/.well-known/genid/rdflib/")
+ ),
),
],
)
@@ -61,9 +66,9 @@ def test_skolemization(
[
("http://example.com", None),
("http://example.com/not/.well-known/genid/1", None),
- ("http://rdlib.net/not/.well-known/genid/1", None),
+ ("https://rdflib.github.io/not/.well-known/genid/1", None),
("http://example.com/.well-known/genid/1", re.compile("^N")),
- ("http://rdlib.net/.well-known/genid/rdflib/GMeng4V7", "GMeng4V7"),
+ ("https://rdflib.github.io/.well-known/genid/rdflib/GMeng4V7", "GMeng4V7"),
],
)
def test_deskolemization(
diff --git a/test/test_skolem_genid.py b/test/test_skolem_genid.py
index 7123fba4..ee88f5a8 100644
--- a/test/test_skolem_genid.py
+++ b/test/test_skolem_genid.py
@@ -4,7 +4,7 @@ from rdflib.term import Genid, RDFLibGenid
def test_skolem_genid_and_rdflibgenid():
rdflib_genid = URIRef(
- "http://rdflib.net/.well-known/genid/rdflib/N97c39b957bc444949a82793519348dc2"
+ "https://rdflib.github.io/.well-known/genid/rdflib/N97c39b957bc444949a82793519348dc2"
)
custom_genid = URIRef(
"http://example.com/.well-known/genid/example/Ne864c0e3684044f381d518fdac652f2e"
diff --git a/test/test_util.py b/test/test_util.py
index 16ecbcb3..3ca54270 100644
--- a/test/test_util.py
+++ b/test/test_util.py
@@ -15,7 +15,7 @@ from rdflib import XSD, util
from rdflib.graph import ConjunctiveGraph, Graph, QuotedGraph
from rdflib.namespace import RDF, RDFS
from rdflib.term import BNode, IdentifiedNode, Literal, Node, URIRef
-from rdflib.util import _coalesce, find_roots, get_tree
+from rdflib.util import _coalesce, _iri2uri, find_roots, get_tree
n3source = """\
@prefix : <http://www.w3.org/2000/10/swap/Primer#>.
@@ -547,3 +547,80 @@ def test_get_tree(
assert catcher.value is not None
else:
assert expected_result == result
+
+
[email protected](
+ ["iri", "expected_result"],
+ [
+ (
+ "https://example.com/resource/Almería",
+ {
+ "https://example.com/resource/Almer%C3%ADa",
+ },
+ ),
+ (
+ "https://example.com/resource/Almeria",
+ {
+ "https://example.com/resource/Almeria",
+ },
+ ),
+ (
+ "https://åæø.example.com/",
+ {
+ "https://xn--5cac8c.example.com/",
+ },
+ ),
+ (
+ # Note: expected result is the same because the function only works
+ # for http and https.
+ "example:é",
+ {
+ "example:é",
+ },
+ ),
+ (
+ # Note: expected result is the same because the function only works
+ # for http and https.
+ "urn:example:é",
+ {
+ "urn:example:é",
+ },
+ ),
+ (
+ "http://example.com/?é=1",
+ {
+ "http://example.com/?%C3%A9=1",
+ "http://example.com/?%C3%A9%3D1",
+ },
+ ),
+ (
+ "http://example.com/#é",
+ {
+ "http://example.com/#%C3%A9",
+ },
+ ),
+ (
+ "http://example.com/é#",
+ {
+ "http://example.com/%C3%A9#",
+ },
+ ),
+ ],
+)
+def test_iri2uri(iri: str, expected_result: Union[Set[str], Type[Exception]]) -> None:
+ """
+ Tests that
+ """
+ catcher: Optional[pytest.ExceptionInfo[Exception]] = None
+
+ with ExitStack() as xstack:
+ if isinstance(expected_result, type) and issubclass(expected_result, Exception):
+ catcher = xstack.enter_context(pytest.raises(expected_result))
+ result = _iri2uri(iri)
+ logging.debug("result = %s", result)
+ if catcher is not None:
+ assert catcher is not None
+ assert catcher.value is not None
+ else:
+ assert isinstance(expected_result, set)
+ assert result in expected_result
diff --git a/test/test_w3c_spec/test_rdfxml_w3c.py b/test/test_w3c_spec/test_rdfxml_w3c.py
index 9a5a4c6a..cfd940d2 100644
--- a/test/test_w3c_spec/test_rdfxml_w3c.py
+++ b/test/test_w3c_spec/test_rdfxml_w3c.py
@@ -230,7 +230,7 @@ FOAF = Namespace("http://xmlns.com/foaf/0.1/")
results = Graph()
system = BNode("system")
-results.add((system, FOAF["homepage"], URIRef("http://rdflib.net/")))
+results.add((system, FOAF["homepage"], URIRef("https://rdflib.github.io/")))
results.add((system, RDFS.label, Literal("RDFLib")))
results.add((system, RDFS.comment, Literal("")))
| Graph parse module does not handle URI / IRI with non-ascii characters
To reproduce behavior:
```python
from rdflib import Graph
g = Graph()
g.parse("https://dbpedia.org/page/Almería")
```
I was able to bypass it locally by editing the function in `parser.py`
```python
def _create_input_source_from_location(file, format, input_source, location):
# Fix for Windows problem https://github.com/RDFLib/rdflib/issues/145
path = pathlib.Path(location)
if path.exists():
location = path.absolute().as_uri()
base = pathlib.Path.cwd().as_uri()
concept = location.split('/')[-1] # I added this line and the line below
location = location.replace(concept, quote(concept))
absolute_location = URIRef(location, base=base)
if absolute_location.startswith("file:///"):
filename = url2pathname(absolute_location.replace("file:///", "/"))
file = open(filename, "rb")
else:
input_source = URLInputSource(absolute_location, format)
auto_close = True
# publicID = publicID or absolute_location # Further to fix
# for issue 130
return absolute_location, auto_close, file, input_source
```
according to the help [here](https://stackoverflow.com/questions/4389572/how-to-fetch-a-non-ascii-url-with-urlopen)
Is there a better way to deal with this scenario or should this be a PR? | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/jsonld/test_localsuite.py::test_suite[https://rdflib.github.io/rdflib-jsonld/local-testsuite/toRdf-manifest.jsonld#ttwoidnodes-do_test_parser-https://rdflib.github.io/rdflib-jsonld/local-testsuite/-toRdf-twoidnodes-toRdf-twoidnodes-in.jsonld-toRdf-twoidnodes-out.nq-False-options0]",
"test/jsonld/test_localsuite.py::test_suite[https://rdflib.github.io/rdflib-jsonld/local-testsuite/sample-manifest.jsonld#turn-do_test_parser-https://rdflib.github.io/rdflib-jsonld/local-testsuite/-sample-urn-sample-urn-in.jsonld-sample-urn-out.nq-False-options1]",
"test/test_dataset/test_dataset.py::test_graph_aware[default]",
"test/test_dataset/test_dataset.py::test_default_graph[default]",
"test/test_dataset/test_dataset.py::test_not_union[default]",
"test/test_dataset/test_dataset.py::test_iter[default]",
"test/test_dataset/test_dataset.py::test_subgraph_without_identifier",
"test/test_graph/test_graph_http.py::TestGraphHTTP::test_content_negotiation",
"test/test_graph/test_graph_http.py::TestGraphHTTP::test_content_negotiation_no_format",
"test/test_graph/test_graph_http.py::TestGraphHTTP::test_source",
"test/test_graph/test_graph_http.py::TestGraphHTTP::test_3xx",
"test/test_graph/test_graph_http.py::TestGraphHTTP::test_5xx",
"test/test_graph/test_graph_http.py::test_iri_source",
"test/test_graph/test_skolemization.py::test_skolemization[http://example.com-None]",
"test/test_graph/test_skolemization.py::test_skolemization[some",
"test/test_graph/test_skolemization.py::test_skolemization[GMeng4V7-https://rdflib.github.io/.well-known/genid/rdflib/GMeng4V7]",
"test/test_graph/test_skolemization.py::test_skolemization[N6bc8fb5ed00844a4815254521b1588c8-^https://rdflib\\\\.github\\\\.io/\\\\.well\\\\-known/genid/rdflib/]",
"test/test_graph/test_skolemization.py::test_deskolemization[http://example.com-None]",
"test/test_graph/test_skolemization.py::test_deskolemization[http://example.com/not/.well-known/genid/1-None]",
"test/test_graph/test_skolemization.py::test_deskolemization[https://rdflib.github.io/not/.well-known/genid/1-None]",
"test/test_graph/test_skolemization.py::test_deskolemization[http://example.com/.well-known/genid/1-^N]",
"test/test_graph/test_skolemization.py::test_deskolemization[https://rdflib.github.io/.well-known/genid/rdflib/GMeng4V7-GMeng4V7]",
"test/test_skolem_genid.py::test_skolem_genid_and_rdflibgenid",
"test/test_util.py::TestUtilMisc::test_util_list2set",
"test/test_util.py::TestUtilMisc::test_util_uniq",
"test/test_util.py::TestUtilDateTime::test_util_date_time_tisnoneandnotz",
"test/test_util.py::TestUtilDateTime::test_util_date_time_tisnonebuttz",
"test/test_util.py::TestUtilDateTime::test_util_date_time_tistime",
"test/test_util.py::TestUtilDateTime::test_util_date_time_tistimewithtz",
"test/test_util.py::TestUtilDateTime::test_util_parse_date_time",
"test/test_util.py::TestUtilDateTime::test_util_parse_date_timewithtz",
"test/test_util.py::TestUtilDateTime::test_util_date_timewithtoutz",
"test/test_util.py::TestUtilTermConvert::test_util_to_term_sisNone",
"test/test_util.py::TestUtilTermConvert::test_util_to_term_sisstr",
"test/test_util.py::TestUtilTermConvert::test_util_to_term_sisurl",
"test/test_util.py::TestUtilTermConvert::test_util_to_term_sisbnode",
"test/test_util.py::TestUtilTermConvert::test_util_to_term_sisunknown",
"test/test_util.py::TestUtilTermConvert::test_util_to_term_sisnotstr",
"test/test_util.py::TestUtilTermConvert::test_util_from_n3_sisnonenodefault",
"test/test_util.py::TestUtilTermConvert::test_util_from_n3_sisnonewithdefault",
"test/test_util.py::TestUtilTermConvert::test_util_from_n3_expectdefaultbnode",
"test/test_util.py::TestUtilTermConvert::test_util_from_n3_expectbnode",
"test/test_util.py::TestUtilTermConvert::test_util_from_n3_expectliteral",
"test/test_util.py::TestUtilTermConvert::test_util_from_n3_expecturiref",
"test/test_util.py::TestUtilTermConvert::test_util_from_n3_expectliteralandlang",
"test/test_util.py::TestUtilTermConvert::test_util_from_n3_expectliteralandlangdtype",
"test/test_util.py::TestUtilTermConvert::test_util_from_n3_expectliteralanddtype",
"test/test_util.py::TestUtilTermConvert::test_util_from_n3_expectliteralwithdatatypefromint",
"test/test_util.py::TestUtilTermConvert::test_util_from_n3_expectliteralwithdatatypefrombool",
"test/test_util.py::TestUtilTermConvert::test_util_from_n3_expectliteralmultiline",
"test/test_util.py::TestUtilTermConvert::test_util_from_n3_expectliteralwithescapedquote",
"test/test_util.py::TestUtilTermConvert::test_util_from_n3_expectliteralwithtrailingbackslash",
"test/test_util.py::TestUtilTermConvert::test_util_from_n3_expectpartialidempotencewithn3",
"test/test_util.py::TestUtilTermConvert::test_util_from_n3_expectsameasn3parser",
"test/test_util.py::TestUtilTermConvert::test_util_from_n3_expectquotedgraph",
"test/test_util.py::TestUtilTermConvert::test_util_from_n3_expectgraph",
"test/test_util.py::TestUtilTermConvert::test_util_from_n3_escapes[\\\\t-\\t]",
"test/test_util.py::TestUtilTermConvert::test_util_from_n3_escapes[\\\\b-\\x08]",
"test/test_util.py::TestUtilTermConvert::test_util_from_n3_escapes[\\\\n-\\n]",
"test/test_util.py::TestUtilTermConvert::test_util_from_n3_escapes[\\\\r-\\r]",
"test/test_util.py::TestUtilTermConvert::test_util_from_n3_escapes[\\\\f-\\x0c]",
"test/test_util.py::TestUtilTermConvert::test_util_from_n3_escapes[\\\\\"-\"]",
"test/test_util.py::TestUtilTermConvert::test_util_from_n3_escapes[\\\\'-']",
"test/test_util.py::TestUtilTermConvert::test_util_from_n3_escapes[\\\\\\\\-\\\\]",
"test/test_util.py::TestUtilTermConvert::test_util_from_n3_escapes[\\\\u00F6-\\xf6]",
"test/test_util.py::TestUtilTermConvert::test_util_from_n3_escapes[\\\\U000000F6-\\xf6]",
"test/test_util.py::TestUtilTermConvert::test_util_from_n3_not_escapes[j\\xf6rn]",
"test/test_util.py::TestUtilTermConvert::test_util_from_n3_not_escapes[j\\\\xf6rn]",
"test/test_util.py::TestUtilTermConvert::test_util_from_n3_not_escapes[\\\\I]",
"test/test_util.py::test__coalesce[params0-None]",
"test/test_util.py::test__coalesce[params1-something]",
"test/test_util.py::test__coalesce[params2-False]",
"test/test_util.py::test__coalesce[params3-]",
"test/test_util.py::test__coalesce[params4-0]",
"test/test_util.py::test__coalesce[params5-something]",
"test/test_util.py::test__coalesce[params6-something]",
"test/test_util.py::test_find_roots[graph_sources0-http://www.w3.org/2000/01/rdf-schema#subClassOf-None-expected_result0]",
"test/test_util.py::test_find_roots[graph_sources1-http://www.w3.org/2000/01/rdf-schema#subClassOf-None-expected_result1]",
"test/test_util.py::test_find_roots[graph_sources2-http://www.w3.org/2000/01/rdf-schema#subClassOf-None-expected_result2]",
"test/test_util.py::test_find_roots[graph_sources3-http://www.w3.org/2000/01/rdf-schema#subClassOf-None-expected_result3]",
"test/test_util.py::test_find_roots[graph_sources4-http://www.w3.org/2000/01/rdf-schema#subClassOf-roots4-expected_result4]",
"test/test_util.py::test_get_tree[graph_sources0-http://www.w3.org/ns/rdftest#TestTurtlePositiveSyntax-http://www.w3.org/2000/01/rdf-schema#subClassOf-down-expected_result0]",
"test/test_util.py::test_get_tree[graph_sources1-http://www.w3.org/ns/rdftest#TestTurtlePositiveSyntax-http://www.w3.org/2000/01/rdf-schema#subClassOf-up-expected_result1]",
"test/test_util.py::test_get_tree[graph_sources2-http://www.w3.org/2000/01/rdf-schema#Resource-http://www.w3.org/2000/01/rdf-schema#subClassOf-down-expected_result2]",
"test/test_util.py::test_get_tree[graph_sources3-http://www.w3.org/2000/01/rdf-schema#Resource-http://www.w3.org/2000/01/rdf-schema#subClassOf-up-expected_result3]",
"test/test_util.py::test_get_tree[graph_sources4-http://www.w3.org/ns/rdftest#Test-http://www.w3.org/2000/01/rdf-schema#subClassOf-down-expected_result4]",
"test/test_util.py::test_get_tree[graph_sources5-http://www.w3.org/ns/rdftest#Test-http://www.w3.org/2000/01/rdf-schema#subClassOf-up-expected_result5]",
"test/test_util.py::test_iri2uri[https://example.com/resource/Almer\\xeda-expected_result0]",
"test/test_util.py::test_iri2uri[https://example.com/resource/Almeria-expected_result1]",
"test/test_util.py::test_iri2uri[https://\\xe5\\xe6\\xf8.example.com/-expected_result2]",
"test/test_util.py::test_iri2uri[example:\\xe9-expected_result3]",
"test/test_util.py::test_iri2uri[urn:example:\\xe9-expected_result4]",
"test/test_util.py::test_iri2uri[http://example.com/?\\xe9=1-expected_result5]",
"test/test_util.py::test_iri2uri[http://example.com/#\\xe9-expected_result6]",
"test/test_util.py::test_iri2uri[http://example.com/\\xe9#-expected_result7]",
"test/test_w3c_spec/test_rdfxml_w3c.py::ParserTestCase::testNegative",
"test/test_w3c_spec/test_rdfxml_w3c.py::ParserTestCase::testPositive"
] | [] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2022-05-09T18:39:15Z" | bsd-3-clause |
|
RDFLib__rdflib-2112 | diff --git a/rdflib/plugins/stores/sparqlconnector.py b/rdflib/plugins/stores/sparqlconnector.py
index 1d03c6fe..55fdfd15 100644
--- a/rdflib/plugins/stores/sparqlconnector.py
+++ b/rdflib/plugins/stores/sparqlconnector.py
@@ -167,7 +167,7 @@ class SPARQLConnector(object):
headers = {
"Accept": _response_mime_types[self.returnFormat],
- "Content-Type": "application/sparql-update",
+ "Content-Type": "application/sparql-update; charset=UTF-8",
}
args = dict(self.kwargs) # other QSAs
| RDFLib/rdflib | bcd05e93c0325854b2c44447996cb4bf91cc830c | diff --git a/test/test_store/test_store_sparqlstore.py b/test/test_store/test_store_sparqlstore.py
index 39a7d3cd..fa98b956 100644
--- a/test/test_store/test_store_sparqlstore.py
+++ b/test/test_store/test_store_sparqlstore.py
@@ -1,3 +1,4 @@
+import logging
import re
import socket
from http.server import BaseHTTPRequestHandler, HTTPServer
@@ -457,23 +458,22 @@ class SPARQL11ProtocolStoreMock(BaseHTTPRequestHandler):
print(body)
```
"""
- contenttype = self.headers.get("Content-Type")
+ contenttype = [
+ part.strip() for part in f"{self.headers.get('Content-Type')}".split(";")
+ ]
+ logging.debug("contenttype = %s", contenttype)
if self.path == "/query" or self.path == "/query?":
- if self.headers.get("Content-Type") == "application/sparql-query":
+ if "application/sparql-query" in contenttype:
pass
- elif (
- self.headers.get("Content-Type") == "application/x-www-form-urlencoded"
- ):
+ elif "application/x-www-form-urlencoded" in contenttype:
pass
else:
self.send_response(406, "Not Acceptable")
self.end_headers()
elif self.path == "/update" or self.path == "/update?":
- if self.headers.get("Content-Type") == "application/sparql-update":
+ if "application/sparql-update" in contenttype:
pass
- elif (
- self.headers.get("Content-Type") == "application/x-www-form-urlencoded"
- ):
+ elif "application/x-www-form-urlencoded" in contenttype:
pass
else:
self.send_response(406, "Not Acceptable")
diff --git a/test/test_store/test_store_sparqlupdatestore_mock.py b/test/test_store/test_store_sparqlupdatestore_mock.py
index 11a4983f..be8f0fae 100644
--- a/test/test_store/test_store_sparqlupdatestore_mock.py
+++ b/test/test_store/test_store_sparqlupdatestore_mock.py
@@ -58,3 +58,26 @@ class TestSPARQLConnector:
req = self.httpmock.requests[MethodName.POST].pop(0)
assert req.parsed_path.path == self.update_path
assert "application/sparql-update" in req.headers.get("content-type")
+
+ def test_update_encoding(self):
+ graph = ConjunctiveGraph("SPARQLUpdateStore")
+ graph.open((self.query_endpoint, self.update_endpoint))
+ update_statement = f"INSERT DATA {{ {EG['subj']} {EG['pred']} {EG['obj']}. }}"
+
+ self.httpmock.responses[MethodName.POST].append(
+ MockHTTPResponse(
+ 200,
+ "OK",
+ b"Update succeeded",
+ {"Content-Type": ["text/plain; charset=UTF-8"]},
+ )
+ )
+
+ # This test assumes that updates are performed using POST
+ # at the moment this is the only supported way for SPARQLUpdateStore
+ # to do updates.
+ graph.update(update_statement)
+ assert self.httpmock.call_count == 1
+ req = self.httpmock.requests[MethodName.POST].pop(0)
+ assert req.parsed_path.path == self.update_path
+ assert "charset=UTF-8" in req.headers.get("content-type")
| SPARQLConnector.update should set ContentType charset
I use rdflib to connect to a Blazegraph triplestore using the SPARQLUpdateStore.
When I add data containing non-ASCII characters using `addN()` it results in garbled data in the triplestore (UTF-8 interpreted as ISO-8859).
The problem seems to be that SPARQLConnector.update() does not set "charset=UTF-8" in the Content-Type header:
https://github.com/RDFLib/rdflib/blob/a70a9c82649f9345c3691d69df6f1108e9e05871/rdflib/plugins/stores/sparqlconnector.py#L170
but it does use UTF-8 in `data=query.encode()` in line 183.
The problem goes away if I patch the Content-Type to be "application/sparql-update; charset=UTF-8".
I can provide a PR with this one-line change if you like. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/test_store/test_store_sparqlupdatestore_mock.py::TestSPARQLConnector::test_update_encoding"
] | [
"test/test_store/test_store_sparqlstore.py::TestSPARQLStoreGraph::test_graph_modify_fails[<lambda>-TypeError]",
"test/test_store/test_store_sparqlstore.py::TestSPARQLStoreFakeDBPedia::test_Query",
"test/test_store/test_store_sparqlstore.py::TestSPARQLStoreFakeDBPedia::test_initNs",
"test/test_store/test_store_sparqlstore.py::TestSPARQLStoreFakeDBPedia::test_noinitNs",
"test/test_store/test_store_sparqlstore.py::TestSPARQLStoreFakeDBPedia::test_query_with_added_prolog",
"test/test_store/test_store_sparqlstore.py::TestSPARQLStoreFakeDBPedia::test_query_with_added_rdf_prolog",
"test/test_store/test_store_sparqlstore.py::TestSPARQLStoreFakeDBPedia::test_counting_graph_and_store_queries",
"test/test_store/test_store_sparqlstore.py::TestSPARQLStoreUpdate::test_Query",
"test/test_store/test_store_sparqlstore.py::TestSPARQLMock::test_query",
"test/test_store/test_store_sparqlupdatestore_mock.py::TestSPARQLConnector::test_graph_update"
] | {
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
} | "2022-09-09T16:03:39Z" | bsd-3-clause |
|
RDFLib__rdflib-2160 | diff --git a/rdflib/plugins/serializers/trig.py b/rdflib/plugins/serializers/trig.py
index 0fa62b71..d4052b29 100644
--- a/rdflib/plugins/serializers/trig.py
+++ b/rdflib/plugins/serializers/trig.py
@@ -34,6 +34,9 @@ class TrigSerializer(TurtleSerializer):
def preprocess(self):
for context in self.contexts:
+ # do not write unnecessary prefix (ex: for an empty default graph)
+ if len(context) == 0:
+ continue
self.store = context
self.getQName(context.identifier)
self._subjects = {}
| RDFLib/rdflib | 8213b7465783e636a394c86fd2387a44523d9c2f | diff --git a/test/test_trig.py b/test/test_trig.py
index dbb1adbf..30bff634 100644
--- a/test/test_trig.py
+++ b/test/test_trig.py
@@ -192,3 +192,9 @@ def test_prefixes():
assert "ns2: <http://ex.org/docs/".encode("latin-1") in data, data
assert "<ns2:document1>".encode("latin-1") not in data, data
assert "ns2:document1".encode("latin-1") in data, data
+
+
+def test_issue_2154():
+ ds = rdflib.Dataset()
+ sg = ds.serialize(format="trig")
+ assert "prefix" not in sg, sg
| can't get rid of default prefix definition in trig serialization
I have a trig file with just one graph like this:
```trig
@prefix adm: <http://purl.bdrc.io/ontology/admin/> .
@prefix bda: <http://purl.bdrc.io/admindata/> .
@prefix bdg: <http://purl.bdrc.io/graph/> .
bdg:W1NLM5228 {
bda:W1NLM5228 a adm:AdminData ;
adm:status bda:StatusReleased .
}
```
In my use case I need to be able to read it, modify it and then write it with the same prefix definitions, but when I do something very simple like
```python
import rdflib
from rdflib import Literal, Graph, Dataset, URIRef
import os
ds = Dataset()
ds.parse("bug.trig", format="trig", publicID=URIRef("http://purl.bdrc.io/graph/W1NLM5228"))
ds.remove_graph(URIRef("urn:x-rdflib:default")) # doesn't work
ds.serialize(filepath+"-bug", format="trig")
```
the output I get is
```trig
@prefix adm: <http://purl.bdrc.io/ontology/admin/> .
@prefix bda: <http://purl.bdrc.io/admindata/> .
@prefix bdg: <http://purl.bdrc.io/graph/> .
@prefix ns1: <urn:x-rdflib:> .
bdg:W1NLM5228 {
bda:W1NLM5228 a adm:AdminData ;
adm:status bda:StatusReleased .
}
```
and I seem unable to remove the `ns1: <urn:x-rdflib:>` prefix definition. Is there any way to do so? Thanks! | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/test_trig.py::test_issue_2154"
] | [
"test/test_trig.py::test_empty",
"test/test_trig.py::test_repeat_triples",
"test/test_trig.py::test_same_subject",
"test/test_trig.py::test_remember_namespace",
"test/test_trig.py::test_graph_qname_syntax",
"test/test_trig.py::test_graph_uri_syntax",
"test/test_trig.py::test_blank_graph_identifier",
"test/test_trig.py::test_graph_parsing",
"test/test_trig.py::test_default_graph_serializes_without_name",
"test/test_trig.py::test_prefixes"
] | {
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
} | "2022-11-18T14:08:25Z" | bsd-3-clause |
|
RDFLib__rdflib-2221 | diff --git a/rdflib/plugins/sparql/algebra.py b/rdflib/plugins/sparql/algebra.py
index 1429012b..5f6a774a 100644
--- a/rdflib/plugins/sparql/algebra.py
+++ b/rdflib/plugins/sparql/algebra.py
@@ -335,7 +335,11 @@ def translateGroupGraphPattern(graphPattern: CompValue) -> CompValue:
"""
if graphPattern.name == "SubSelect":
- return ToMultiSet(translate(graphPattern)[0])
+ # The first output from translate cannot be None for a subselect query
+ # as it can only be None for certain DESCRIBE queries.
+ # type error: Argument 1 to "ToMultiSet" has incompatible type "Optional[CompValue]";
+ # expected "Union[List[Dict[Variable, str]], CompValue]"
+ return ToMultiSet(translate(graphPattern)[0]) # type: ignore[arg-type]
if not graphPattern.part:
graphPattern.part = [] # empty { }
@@ -623,7 +627,7 @@ def translateValues(
return Values(res)
-def translate(q: CompValue) -> Tuple[CompValue, List[Variable]]:
+def translate(q: CompValue) -> Tuple[Optional[CompValue], List[Variable]]:
"""
http://www.w3.org/TR/sparql11-query/#convertSolMod
@@ -635,9 +639,27 @@ def translate(q: CompValue) -> Tuple[CompValue, List[Variable]]:
# TODO: Var scope test
VS: Set[Variable] = set()
- traverse(q.where, functools.partial(_findVars, res=VS))
- # all query types have a where part
+ # All query types have a WHERE clause EXCEPT some DESCRIBE queries
+ # where only explicit IRIs are provided.
+ if q.name == "DescribeQuery":
+ # For DESCRIBE queries, use the vars provided in q.var.
+ # If there is no WHERE clause, vars should be explicit IRIs to describe.
+ # If there is a WHERE clause, vars can be any combination of explicit IRIs
+ # and variables.
+ VS = set(q.var)
+
+ # If there is no WHERE clause, just return the vars projected
+ if q.where is None:
+ return None, list(VS)
+
+ # Otherwise, evaluate the WHERE clause like SELECT DISTINCT
+ else:
+ q.modifier = "DISTINCT"
+
+ else:
+ traverse(q.where, functools.partial(_findVars, res=VS))
+
# depth-first recursive generation of mapped query tree
M = translateGroupGraphPattern(q.where)
diff --git a/rdflib/plugins/sparql/evaluate.py b/rdflib/plugins/sparql/evaluate.py
index aafd0fe7..06fc170d 100644
--- a/rdflib/plugins/sparql/evaluate.py
+++ b/rdflib/plugins/sparql/evaluate.py
@@ -309,7 +309,7 @@ def evalPart(ctx: QueryContext, part: CompValue):
return evalServiceQuery(ctx, part)
elif part.name == "DescribeQuery":
- raise Exception("DESCRIBE not implemented")
+ return evalDescribeQuery(ctx, part)
else:
raise Exception("I dont know: %s" % part.name)
@@ -585,6 +585,41 @@ def evalConstructQuery(ctx: QueryContext, query) -> Dict[str, Union[str, Graph]]
return res
+def evalDescribeQuery(ctx: QueryContext, query) -> Dict[str, Union[str, Graph]]:
+ # Create a result graph and bind namespaces from the graph being queried
+ graph = Graph()
+ # type error: Item "None" of "Optional[Graph]" has no attribute "namespaces"
+ for pfx, ns in ctx.graph.namespaces(): # type: ignore[union-attr]
+ graph.bind(pfx, ns)
+
+ to_describe = set()
+
+ # Explicit IRIs may be provided to a DESCRIBE query.
+ # If there is a WHERE clause, explicit IRIs may be provided in
+ # addition to projected variables. Find those explicit IRIs and
+ # prepare to describe them.
+ for iri in query.PV:
+ if isinstance(iri, URIRef):
+ to_describe.add(iri)
+
+ # If there is a WHERE clause, evaluate it then find the unique set of
+ # resources to describe across all bindings and projected variables
+ if query.p is not None:
+ bindings = evalPart(ctx, query.p)
+ to_describe.update(*(set(binding.values()) for binding in bindings))
+
+ # Get a CBD for all resources identified to describe
+ for resource in to_describe:
+ # type error: Item "None" of "Optional[Graph]" has no attribute "cbd"
+ graph += ctx.graph.cbd(resource) # type: ignore[union-attr]
+
+ res: Dict[str, Union[str, Graph]] = {}
+ res["type_"] = "DESCRIBE"
+ res["graph"] = graph
+
+ return res
+
+
def evalQuery(graph: Graph, query: Query, initBindings, base=None):
initBindings = dict((Variable(k), v) for k, v in initBindings.items())
diff --git a/rdflib/plugins/sparql/parser.py b/rdflib/plugins/sparql/parser.py
index 2035b4f0..2a897f82 100644
--- a/rdflib/plugins/sparql/parser.py
+++ b/rdflib/plugins/sparql/parser.py
@@ -1479,7 +1479,7 @@ DescribeQuery = Comp(
"DescribeQuery",
Keyword("DESCRIBE")
+ (OneOrMore(ParamList("var", VarOrIri)) | "*")
- + Param("datasetClause", ZeroOrMore(DatasetClause))
+ + ZeroOrMore(ParamList("datasetClause", DatasetClause))
+ Optional(WhereClause)
+ SolutionModifier
+ ValuesClause,
| RDFLib/rdflib | 9625ed0b432c9085e2d9dda1fd8acf707b9022ab | diff --git a/test/test_sparql/test_sparql.py b/test/test_sparql/test_sparql.py
index 32cc82d7..7d66f2c1 100644
--- a/test/test_sparql/test_sparql.py
+++ b/test/test_sparql/test_sparql.py
@@ -867,3 +867,95 @@ def test_queries(
result = rdfs_graph.query(query)
logging.debug("result = %s", result)
assert expected_bindings == result.bindings
+
+
[email protected](
+ ["query_string", "expected_subjects", "expected_size"],
+ [
+ pytest.param(
+ """
+ DESCRIBE rdfs:Class
+ """,
+ {RDFS.Class},
+ 5,
+ id="1-explicit",
+ ),
+ pytest.param(
+ """
+ DESCRIBE rdfs:Class rdfs:subClassOf
+ """,
+ {RDFS.Class, RDFS.subClassOf},
+ 11,
+ id="2-explict",
+ ),
+ pytest.param(
+ """
+ DESCRIBE rdfs:Class rdfs:subClassOf owl:Class
+ """,
+ {RDFS.Class, RDFS.subClassOf},
+ 11,
+ id="3-explict-1-missing",
+ ),
+ pytest.param(
+ """
+ DESCRIBE ?prop
+ WHERE {
+ ?prop a rdf:Property
+ }
+ """,
+ {
+ RDFS.seeAlso,
+ RDFS.member,
+ RDFS.subPropertyOf,
+ RDFS.subClassOf,
+ RDFS.domain,
+ RDFS.range,
+ RDFS.label,
+ RDFS.comment,
+ RDFS.isDefinedBy,
+ },
+ 55,
+ id="1-var",
+ ),
+ pytest.param(
+ """
+ DESCRIBE ?s
+ WHERE {
+ ?s a ?type ;
+ rdfs:subClassOf rdfs:Class .
+ }
+ """,
+ {RDFS.Datatype},
+ 5,
+ id="2-var-1-projected",
+ ),
+ pytest.param(
+ """
+ DESCRIBE ?s rdfs:Class
+ WHERE {
+ ?s a ?type ;
+ rdfs:subClassOf rdfs:Class .
+ }
+ """,
+ {RDFS.Datatype, RDFS.Class},
+ 10,
+ id="2-var-1-projected-1-explicit",
+ ),
+ pytest.param("DESCRIBE ?s", set(), 0, id="empty"),
+ ],
+)
+def test_sparql_describe(
+ query_string: str,
+ expected_subjects: set,
+ expected_size: int,
+ rdfs_graph: Graph,
+) -> None:
+ """
+ Check results of DESCRIBE queries against rdfs.ttl to ensure
+ the subjects described and the number of triples returned are correct.
+ """
+ r = rdfs_graph.query(query_string)
+ assert r.graph is not None
+ subjects = {s for s in r.graph.subjects() if not isinstance(s, BNode)}
+ assert subjects == expected_subjects
+ assert len(r.graph) == expected_size
| DESCRIBE query not working
Apparently DESCRIBE queries are not fully implemented yet? This is what I get with two different queries:
######
1) g.query('DESCRIBE http://www.example.org/a')
...
/usr/lib/python2.7/site-packages/rdflib/plugins/sparql/algebra.pyc in translate(q)
530
531 # all query types have a where part
--> 532 M = translateGroupGraphPattern(q.where)
533
534 aggregate = False
/usr/lib/python2.7/site-packages/rdflib/plugins/sparql/algebra.pyc in translateGroupGraphPattern(graphPattern)
261 """
262
--> 263 if graphPattern.name == 'SubSelect':
264 return ToMultiSet(translate(graphPattern)[0])
265
AttributeError: 'NoneType' object has no attribute 'name'
2) g.query('DESCRIBE ?s WHERE {?s ?p ?o FILTER (?s = http://www.example.org/a)}')
...
/usr/lib/python2.7/site-packages/rdflib/plugins/sparql/evaluate.pyc in evalPart(ctx, part)
260
261 elif part.name == 'DescribeQuery':
--> 262 raise Exception('DESCRIBE not implemented')
263
264 else:
Exception: DESCRIBE not implemented
######
The graph is created via this sequence:
import rdflib
from rdflib import RDF
ex = rdflib.Namespace('http://www.example.org/')
g = rdflib.Graph()
g.add((ex['a'], RDF['type'], ex['Cl']))
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/test_sparql/test_sparql.py::test_sparql_describe[1-explicit]",
"test/test_sparql/test_sparql.py::test_sparql_describe[2-explict]",
"test/test_sparql/test_sparql.py::test_sparql_describe[3-explict-1-missing]",
"test/test_sparql/test_sparql.py::test_sparql_describe[1-var]",
"test/test_sparql/test_sparql.py::test_sparql_describe[2-var-1-projected]",
"test/test_sparql/test_sparql.py::test_sparql_describe[2-var-1-projected-1-explicit]",
"test/test_sparql/test_sparql.py::test_sparql_describe[empty]"
] | [
"test/test_sparql/test_sparql.py::test_graph_prefix",
"test/test_sparql/test_sparql.py::test_variable_order",
"test/test_sparql/test_sparql.py::test_sparql_bnodelist",
"test/test_sparql/test_sparql.py::test_complex_sparql_construct",
"test/test_sparql/test_sparql.py::test_sparql_update_with_bnode",
"test/test_sparql/test_sparql.py::test_sparql_update_with_bnode_serialize_parse",
"test/test_sparql/test_sparql.py::test_bindings",
"test/test_sparql/test_sparql.py::test_named_filter_graph_query",
"test/test_sparql/test_sparql.py::test_txtresult",
"test/test_sparql/test_sparql.py::test_property_bindings",
"test/test_sparql/test_sparql.py::test_call_function",
"test/test_sparql/test_sparql.py::test_custom_eval",
"test/test_sparql/test_sparql.py::test_custom_eval_exception[len+TypeError]",
"test/test_sparql/test_sparql.py::test_custom_eval_exception[len+RuntimeError]",
"test/test_sparql/test_sparql.py::test_custom_eval_exception[list+RuntimeError]",
"test/test_sparql/test_sparql.py::test_operator_exception[len+TypeError]",
"test/test_sparql/test_sparql.py::test_operator_exception[len+RuntimeError]",
"test/test_sparql/test_sparql.py::test_operator_exception[list+RuntimeError]",
"test/test_sparql/test_sparql.py::test_queries[select-optional]",
"test/test_sparql/test_sparql.py::test_queries[select-bind-sha256]",
"test/test_sparql/test_sparql.py::test_queries[select-bind-plus]",
"test/test_sparql/test_sparql.py::test_queries[select-optional-const]",
"test/test_sparql/test_sparql.py::test_queries[select-filter-exists-const-false]",
"test/test_sparql/test_sparql.py::test_queries[select-filter-notexists-const-false]",
"test/test_sparql/test_sparql.py::test_queries[select-filter-exists-const-true]",
"test/test_sparql/test_sparql.py::test_queries[select-filter-notexists-const-true]",
"test/test_sparql/test_sparql.py::test_queries[select-filter-exists-var-false]",
"test/test_sparql/test_sparql.py::test_queries[select-filter-exists-var-true]",
"test/test_sparql/test_sparql.py::test_queries[select-bind-exists-const-false]",
"test/test_sparql/test_sparql.py::test_queries[select-bind-exists-const-true]",
"test/test_sparql/test_sparql.py::test_queries[select-bind-exists-var-true]",
"test/test_sparql/test_sparql.py::test_queries[select-bind-exists-var-false]",
"test/test_sparql/test_sparql.py::test_queries[select-bind-notexists-const-false]",
"test/test_sparql/test_sparql.py::test_queries[select-bind-notexists-const-true]",
"test/test_sparql/test_sparql.py::test_queries[select-group-concat-optional-one]",
"test/test_sparql/test_sparql.py::test_queries[select-group-concat-optional-many0]",
"test/test_sparql/test_sparql.py::test_queries[select-group-concat-optional-many1]"
] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2023-02-02T15:55:33Z" | bsd-3-clause |
|
RDFLib__rdflib-2474 | diff --git a/rdflib/plugins/sparql/aggregates.py b/rdflib/plugins/sparql/aggregates.py
index d4a7d659..84ac8936 100644
--- a/rdflib/plugins/sparql/aggregates.py
+++ b/rdflib/plugins/sparql/aggregates.py
@@ -245,11 +245,16 @@ class Sample(Accumulator):
class GroupConcat(Accumulator):
- def __init__(self, aggregation):
+ value: List[Literal]
+
+ def __init__(self, aggregation: CompValue):
super(GroupConcat, self).__init__(aggregation)
# only GROUPCONCAT needs to have a list as accumulator
self.value = []
- self.separator = aggregation.separator or " "
+ if aggregation.separator is None:
+ self.separator = " "
+ else:
+ self.separator = aggregation.separator
def update(self, row: FrozenBindings, aggregator: "Aggregator") -> None:
try:
| RDFLib/rdflib | 0ea6ca579442219d67ffb1fc7313f05fd16d8d49 | diff --git a/test/test_sparql/test_translate_algebra.py b/test/test_sparql/test_translate_algebra.py
index 20b23327..ca9e67bd 100644
--- a/test/test_sparql/test_translate_algebra.py
+++ b/test/test_sparql/test_translate_algebra.py
@@ -11,6 +11,7 @@ from _pytest.mark.structures import Mark, MarkDecorator, ParameterSet
import rdflib.plugins.sparql.algebra as algebra
import rdflib.plugins.sparql.parser as parser
+from rdflib import Graph, Literal, URIRef
from rdflib.plugins.sparql.algebra import translateAlgebra
@@ -304,3 +305,25 @@ def test_roundtrip(test_spec: AlgebraTest, data_path: Path) -> None:
# TODO: Execute the raw query (query_text) and the reconstituted query
# (query_from_query_from_algebra) against a well defined graph and ensure
# they yield the same result.
+
+
+def test_sparql_group_concat():
+ """Tests if GROUP_CONCAT correctly uses the separator keyword"""
+ query = """
+ PREFIX : <http://example.org/>
+
+ SELECT ?subject (GROUP_CONCAT(?object; separator="")
+ AS ?concatenatedObjects)
+ WHERE {
+ VALUES (?subject ?object) {
+ (:pred "a")
+ (:pred "b")
+ (:pred "c")
+ }
+ }
+ GROUP BY ?subject
+ """
+
+ g = Graph()
+ q = dict(g.query(query))
+ assert q[URIRef("http://example.org/pred")] == Literal("abc")
| Separator in group_concat function with explicit empty string incorrectly defaults to 'space' character
Using the group_concat function with the separator indicating an _empty string_ ("") leads incorrectly to the default use of a space character as separator (" ").
**Example code:**
```
PREFIX : <http://example.org/>
SELECT ?subject (GROUP_CONCAT(?object; separator="") AS ?concatenatedObjects)
WHERE {
VALUES (?subject ?object) {
(:subject1 "a")
(:subject1 "b")
(:subject1 "c")
}
}
GROUP BY ?subject
```
**Expected outcome for concatenatedObjects:**
`abc`
**Instead we get:**
`a b c` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/test_sparql/test_translate_algebra.py::test_sparql_group_concat"
] | [
"test/test_sparql/test_translate_algebra.py::test_all_files_used",
"test/test_sparql/test_translate_algebra.py::test_roundtrip[test_functions__functional_forms]",
"test/test_sparql/test_translate_algebra.py::test_roundtrip[test_functions__functional_forms_not_exists]",
"test/test_sparql/test_translate_algebra.py::test_roundtrip[test_functions__functions_on_dates_and_time]",
"test/test_sparql/test_translate_algebra.py::test_roundtrip[test_functions__functions_on_numerics]",
"test/test_sparql/test_translate_algebra.py::test_roundtrip[test_functions__functions_on_rdf_terms]",
"test/test_sparql/test_translate_algebra.py::test_roundtrip[test_functions__functions_on_strings]",
"test/test_sparql/test_translate_algebra.py::test_roundtrip[test_functions__hash_functions]",
"test/test_sparql/test_translate_algebra.py::test_roundtrip[test_graph_patterns__aggregate_join]",
"test/test_sparql/test_translate_algebra.py::test_roundtrip[test_graph_patterns__bgp]",
"test/test_sparql/test_translate_algebra.py::test_roundtrip[test_graph_patterns__extend]",
"test/test_sparql/test_translate_algebra.py::test_roundtrip[test_graph_patterns__filter]",
"test/test_sparql/test_translate_algebra.py::test_roundtrip[test_graph_patterns__graph]",
"test/test_sparql/test_translate_algebra.py::test_roundtrip[test_graph_patterns__group]",
"test/test_sparql/test_translate_algebra.py::test_roundtrip[test_graph_patterns__group_and_substr]",
"test/test_sparql/test_translate_algebra.py::test_roundtrip[test_graph_patterns__group_and_nested_concat]",
"test/test_sparql/test_translate_algebra.py::test_roundtrip[test_graph_patterns__having]",
"test/test_sparql/test_translate_algebra.py::test_roundtrip[test_graph_patterns__join]",
"test/test_sparql/test_translate_algebra.py::test_roundtrip[test_graph_patterns__left_join]",
"test/test_sparql/test_translate_algebra.py::test_roundtrip[test_graph_patterns__minus]",
"test/test_sparql/test_translate_algebra.py::test_roundtrip[test_graph_patterns__union]",
"test/test_sparql/test_translate_algebra.py::test_roundtrip[test_integration__complex_query1]",
"test/test_sparql/test_translate_algebra.py::test_roundtrip[test_operators__arithmetics]",
"test/test_sparql/test_translate_algebra.py::test_roundtrip[test_operators__conditional_and]",
"test/test_sparql/test_translate_algebra.py::test_roundtrip[test_operators__conditional_or]",
"test/test_sparql/test_translate_algebra.py::test_roundtrip[test_operators__relational]",
"test/test_sparql/test_translate_algebra.py::test_roundtrip[test_operators__unary]",
"test/test_sparql/test_translate_algebra.py::test_roundtrip[test_other__service2]",
"test/test_sparql/test_translate_algebra.py::test_roundtrip[test_other__values]",
"test/test_sparql/test_translate_algebra.py::test_roundtrip[test_property_path__alternative_path]",
"test/test_sparql/test_translate_algebra.py::test_roundtrip[test_property_path__inverse_path]",
"test/test_sparql/test_translate_algebra.py::test_roundtrip[test_property_path__one_or_more_path]",
"test/test_sparql/test_translate_algebra.py::test_roundtrip[test_property_path__sequence_path]",
"test/test_sparql/test_translate_algebra.py::test_roundtrip[test_property_path__zero_or_more_path]",
"test/test_sparql/test_translate_algebra.py::test_roundtrip[test_property_path__zero_or_one_path]",
"test/test_sparql/test_translate_algebra.py::test_roundtrip[test_solution_modifiers__distinct]",
"test/test_sparql/test_translate_algebra.py::test_roundtrip[test_solution_modifiers__order_by]",
"test/test_sparql/test_translate_algebra.py::test_roundtrip[test_solution_modifiers__reduced]",
"test/test_sparql/test_translate_algebra.py::test_roundtrip[test_solution_modifiers__slice]",
"test/test_sparql/test_translate_algebra.py::test_roundtrip[test_solution_modifiers__to_multiset]"
] | {
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
} | "2023-07-07T18:38:06Z" | bsd-3-clause |
|
RDFLib__rdflib-2504 | diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 5f0c147c..e0f9d821 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -18,7 +18,7 @@ repos:
- repo: https://github.com/psf/black
# WARNING: version should be the same as in `pyproject.toml`
# Using git ref spec because of https://github.com/psf/black/issues/2493
- rev: 'refs/tags/23.3.0:refs/tags/23.3.0'
+ rev: 'refs/tags/23.7.0:refs/tags/23.7.0'
hooks:
- id: black
pass_filenames: false
diff --git a/CITATION.cff b/CITATION.cff
new file mode 100644
index 00000000..a9046a1c
--- /dev/null
+++ b/CITATION.cff
@@ -0,0 +1,75 @@
+cff-version: 1.2.0
+message: "If you use this software, please cite it as below."
+authors:
+- family-names: "Krech"
+ given-names: "Daniel"
+- family-names: "Grimnes"
+ given-names: "Gunnar AAstrand"
+- family-names: "Higgins"
+ given-names: "Graham"
+- family-names: "Hees"
+ given-names: "Jörn"
+ orcid: "https://orcid.org/0000-0002-0084-8998"
+- family-names: "Aucamp"
+ given-names: "Iwan"
+ orcid: "https://orcid.org/0000-0002-7325-3231"
+- family-names: "Lindström"
+ given-names: "Niklas"
+- family-names: "Arndt"
+ given-names: "Natanael"
+ orcid: "https://orcid.org/0000-0002-8130-8677"
+- family-names: "Sommer"
+ given-names: "Ashley"
+ orcid: "https://orcid.org/0000-0003-0590-0131"
+- family-names: "Chuc"
+ given-names: "Edmond"
+ orcid: "https://orcid.org/0000-0002-6047-9864"
+- family-names: "Herman"
+ given-names: "Ivan"
+ orcid: "https://orcid.org/0000-0003-0782-2704"
+- family-names: "Nelson"
+ given-names: "Alex"
+- family-names: "McCusker"
+ given-names: "Jamie"
+ orcid: "https://orcid.org/0000-0003-1085-6059"
+- family-names: "Gillespie"
+ given-names: "Tom"
+- family-names: "Kluyver"
+ given-names: "Thomas"
+ orcid: "https://orcid.org/0000-0003-4020-6364"
+- family-names: "Ludwig"
+ given-names: "Florian"
+- family-names: "Champin"
+ given-names: "Pierre-Antoine"
+ orcid: "https://orcid.org/0000-0001-7046-4474"
+- family-names: "Watts"
+ given-names: "Mark"
+- family-names: "Holzer"
+ given-names: "Urs"
+- family-names: "Summers"
+ given-names: "Ed"
+- family-names: "Morriss"
+ given-names: "Whit"
+- family-names: "Winston"
+ given-names: "Donny"
+- family-names: "Perttula"
+ given-names: "Drew"
+- family-names: "Kovacevic"
+ given-names: "Filip"
+ orcid: "https://orcid.org/0000-0002-2854-0434"
+- family-names: "Chateauneu"
+ given-names: "Remi"
+ orcid: "https://orcid.org/0000-0002-7505-8149"
+- family-names: "Solbrig"
+ given-names: "Harold"
+ orcid: "https://orcid.org/0000-0002-5928-3071"
+- family-names: "Cogrel"
+ given-names: "Benjamin"
+ orcid: "https://orcid.org/0000-0002-7566-4077"
+- family-names: "Stuart"
+ given-names: "Veyndan"
+title: "RDFLib"
+version: 6.3.2
+date-released: 2023-03-26
+url: "https://github.com/RDFLib/rdflib"
+doi: 10.5281/zenodo.6845245
diff --git a/docker/unstable/Dockerfile b/docker/unstable/Dockerfile
index 183c1190..7a2671db 100644
--- a/docker/unstable/Dockerfile
+++ b/docker/unstable/Dockerfile
@@ -1,4 +1,4 @@
-FROM docker.io/library/python:3.11.4-slim@sha256:364ee1a9e029fb7b60102ae56ff52153ccc929ceab9aa387402fe738432d24cc
+FROM docker.io/library/python:3.11.4-slim@sha256:36b544be6e796eb5caa0bf1ab75a17d2e20211cad7f66f04f6f5c9eeda930ef5
# This file is generated from docker:unstable in Taskfile.yml
COPY var/requirements.txt /var/tmp/build/
diff --git a/poetry.lock b/poetry.lock
index 0d4d5250..ebc588c5 100644
--- a/poetry.lock
+++ b/poetry.lock
@@ -37,36 +37,33 @@ files = [
[[package]]
name = "black"
-version = "23.3.0"
+version = "23.7.0"
description = "The uncompromising code formatter."
optional = false
-python-versions = ">=3.7"
+python-versions = ">=3.8"
files = [
- {file = "black-23.3.0-cp310-cp310-macosx_10_16_arm64.whl", hash = "sha256:0945e13506be58bf7db93ee5853243eb368ace1c08a24c65ce108986eac65915"},
- {file = "black-23.3.0-cp310-cp310-macosx_10_16_universal2.whl", hash = "sha256:67de8d0c209eb5b330cce2469503de11bca4085880d62f1628bd9972cc3366b9"},
- {file = "black-23.3.0-cp310-cp310-macosx_10_16_x86_64.whl", hash = "sha256:7c3eb7cea23904399866c55826b31c1f55bbcd3890ce22ff70466b907b6775c2"},
- {file = "black-23.3.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:32daa9783106c28815d05b724238e30718f34155653d4d6e125dc7daec8e260c"},
- {file = "black-23.3.0-cp310-cp310-win_amd64.whl", hash = "sha256:35d1381d7a22cc5b2be2f72c7dfdae4072a3336060635718cc7e1ede24221d6c"},
- {file = "black-23.3.0-cp311-cp311-macosx_10_16_arm64.whl", hash = "sha256:a8a968125d0a6a404842fa1bf0b349a568634f856aa08ffaff40ae0dfa52e7c6"},
- {file = "black-23.3.0-cp311-cp311-macosx_10_16_universal2.whl", hash = "sha256:c7ab5790333c448903c4b721b59c0d80b11fe5e9803d8703e84dcb8da56fec1b"},
- {file = "black-23.3.0-cp311-cp311-macosx_10_16_x86_64.whl", hash = "sha256:a6f6886c9869d4daae2d1715ce34a19bbc4b95006d20ed785ca00fa03cba312d"},
- {file = "black-23.3.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6f3c333ea1dd6771b2d3777482429864f8e258899f6ff05826c3a4fcc5ce3f70"},
- {file = "black-23.3.0-cp311-cp311-win_amd64.whl", hash = "sha256:11c410f71b876f961d1de77b9699ad19f939094c3a677323f43d7a29855fe326"},
- {file = "black-23.3.0-cp37-cp37m-macosx_10_16_x86_64.whl", hash = "sha256:1d06691f1eb8de91cd1b322f21e3bfc9efe0c7ca1f0e1eb1db44ea367dff656b"},
- {file = "black-23.3.0-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:50cb33cac881766a5cd9913e10ff75b1e8eb71babf4c7104f2e9c52da1fb7de2"},
- {file = "black-23.3.0-cp37-cp37m-win_amd64.whl", hash = "sha256:e114420bf26b90d4b9daa597351337762b63039752bdf72bf361364c1aa05925"},
- {file = "black-23.3.0-cp38-cp38-macosx_10_16_arm64.whl", hash = "sha256:48f9d345675bb7fbc3dd85821b12487e1b9a75242028adad0333ce36ed2a6d27"},
- {file = "black-23.3.0-cp38-cp38-macosx_10_16_universal2.whl", hash = "sha256:714290490c18fb0126baa0fca0a54ee795f7502b44177e1ce7624ba1c00f2331"},
- {file = "black-23.3.0-cp38-cp38-macosx_10_16_x86_64.whl", hash = "sha256:064101748afa12ad2291c2b91c960be28b817c0c7eaa35bec09cc63aa56493c5"},
- {file = "black-23.3.0-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:562bd3a70495facf56814293149e51aa1be9931567474993c7942ff7d3533961"},
- {file = "black-23.3.0-cp38-cp38-win_amd64.whl", hash = "sha256:e198cf27888ad6f4ff331ca1c48ffc038848ea9f031a3b40ba36aced7e22f2c8"},
- {file = "black-23.3.0-cp39-cp39-macosx_10_16_arm64.whl", hash = "sha256:3238f2aacf827d18d26db07524e44741233ae09a584273aa059066d644ca7b30"},
- {file = "black-23.3.0-cp39-cp39-macosx_10_16_universal2.whl", hash = "sha256:f0bd2f4a58d6666500542b26354978218a9babcdc972722f4bf90779524515f3"},
- {file = "black-23.3.0-cp39-cp39-macosx_10_16_x86_64.whl", hash = "sha256:92c543f6854c28a3c7f39f4d9b7694f9a6eb9d3c5e2ece488c327b6e7ea9b266"},
- {file = "black-23.3.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3a150542a204124ed00683f0db1f5cf1c2aaaa9cc3495b7a3b5976fb136090ab"},
- {file = "black-23.3.0-cp39-cp39-win_amd64.whl", hash = "sha256:6b39abdfb402002b8a7d030ccc85cf5afff64ee90fa4c5aebc531e3ad0175ddb"},
- {file = "black-23.3.0-py3-none-any.whl", hash = "sha256:ec751418022185b0c1bb7d7736e6933d40bbb14c14a0abcf9123d1b159f98dd4"},
- {file = "black-23.3.0.tar.gz", hash = "sha256:1c7b8d606e728a41ea1ccbd7264677e494e87cf630e399262ced92d4a8dac940"},
+ {file = "black-23.7.0-cp310-cp310-macosx_10_16_arm64.whl", hash = "sha256:5c4bc552ab52f6c1c506ccae05681fab58c3f72d59ae6e6639e8885e94fe2587"},
+ {file = "black-23.7.0-cp310-cp310-macosx_10_16_universal2.whl", hash = "sha256:552513d5cd5694590d7ef6f46e1767a4df9af168d449ff767b13b084c020e63f"},
+ {file = "black-23.7.0-cp310-cp310-macosx_10_16_x86_64.whl", hash = "sha256:86cee259349b4448adb4ef9b204bb4467aae74a386bce85d56ba4f5dc0da27be"},
+ {file = "black-23.7.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:501387a9edcb75d7ae8a4412bb8749900386eaef258f1aefab18adddea1936bc"},
+ {file = "black-23.7.0-cp310-cp310-win_amd64.whl", hash = "sha256:fb074d8b213749fa1d077d630db0d5f8cc3b2ae63587ad4116e8a436e9bbe995"},
+ {file = "black-23.7.0-cp311-cp311-macosx_10_16_arm64.whl", hash = "sha256:b5b0ee6d96b345a8b420100b7d71ebfdd19fab5e8301aff48ec270042cd40ac2"},
+ {file = "black-23.7.0-cp311-cp311-macosx_10_16_universal2.whl", hash = "sha256:893695a76b140881531062d48476ebe4a48f5d1e9388177e175d76234ca247cd"},
+ {file = "black-23.7.0-cp311-cp311-macosx_10_16_x86_64.whl", hash = "sha256:c333286dc3ddca6fdff74670b911cccedacb4ef0a60b34e491b8a67c833b343a"},
+ {file = "black-23.7.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:831d8f54c3a8c8cf55f64d0422ee875eecac26f5f649fb6c1df65316b67c8926"},
+ {file = "black-23.7.0-cp311-cp311-win_amd64.whl", hash = "sha256:7f3bf2dec7d541b4619b8ce526bda74a6b0bffc480a163fed32eb8b3c9aed8ad"},
+ {file = "black-23.7.0-cp38-cp38-macosx_10_16_arm64.whl", hash = "sha256:f9062af71c59c004cd519e2fb8f5d25d39e46d3af011b41ab43b9c74e27e236f"},
+ {file = "black-23.7.0-cp38-cp38-macosx_10_16_universal2.whl", hash = "sha256:01ede61aac8c154b55f35301fac3e730baf0c9cf8120f65a9cd61a81cfb4a0c3"},
+ {file = "black-23.7.0-cp38-cp38-macosx_10_16_x86_64.whl", hash = "sha256:327a8c2550ddc573b51e2c352adb88143464bb9d92c10416feb86b0f5aee5ff6"},
+ {file = "black-23.7.0-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6d1c6022b86f83b632d06f2b02774134def5d4d4f1dac8bef16d90cda18ba28a"},
+ {file = "black-23.7.0-cp38-cp38-win_amd64.whl", hash = "sha256:27eb7a0c71604d5de083757fbdb245b1a4fae60e9596514c6ec497eb63f95320"},
+ {file = "black-23.7.0-cp39-cp39-macosx_10_16_arm64.whl", hash = "sha256:8417dbd2f57b5701492cd46edcecc4f9208dc75529bcf76c514864e48da867d9"},
+ {file = "black-23.7.0-cp39-cp39-macosx_10_16_universal2.whl", hash = "sha256:47e56d83aad53ca140da0af87678fb38e44fd6bc0af71eebab2d1f59b1acf1d3"},
+ {file = "black-23.7.0-cp39-cp39-macosx_10_16_x86_64.whl", hash = "sha256:25cc308838fe71f7065df53aedd20327969d05671bac95b38fdf37ebe70ac087"},
+ {file = "black-23.7.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:642496b675095d423f9b8448243336f8ec71c9d4d57ec17bf795b67f08132a91"},
+ {file = "black-23.7.0-cp39-cp39-win_amd64.whl", hash = "sha256:ad0014efc7acf0bd745792bd0d8857413652979200ab924fbf239062adc12491"},
+ {file = "black-23.7.0-py3-none-any.whl", hash = "sha256:9fd59d418c60c0348505f2ddf9609c1e1de8e7493eab96198fc89d9f865e7a96"},
+ {file = "black-23.7.0.tar.gz", hash = "sha256:022a582720b0d9480ed82576c920a8c1dde97cc38ff11d8d8859b3bd6ca9eedb"},
]
[package.dependencies]
@@ -1143,22 +1140,22 @@ test = ["cython", "filelock", "html5lib", "pytest (>=4.6)"]
[[package]]
name = "sphinx-autodoc-typehints"
-version = "1.23.0"
+version = "1.24.0"
description = "Type hints (PEP 484) support for the Sphinx autodoc extension"
optional = false
-python-versions = ">=3.7"
+python-versions = ">=3.8"
files = [
- {file = "sphinx_autodoc_typehints-1.23.0-py3-none-any.whl", hash = "sha256:ac099057e66b09e51b698058ba7dd76e57e1fe696cd91b54e121d3dad188f91d"},
- {file = "sphinx_autodoc_typehints-1.23.0.tar.gz", hash = "sha256:5d44e2996633cdada499b6d27a496ddf9dbc95dd1f0f09f7b37940249e61f6e9"},
+ {file = "sphinx_autodoc_typehints-1.24.0-py3-none-any.whl", hash = "sha256:6a73c0c61a9144ce2ed5ef2bed99d615254e5005c1cc32002017d72d69fb70e6"},
+ {file = "sphinx_autodoc_typehints-1.24.0.tar.gz", hash = "sha256:94e440066941bb237704bb880785e2d05e8ae5406c88674feefbb938ad0dc6af"},
]
[package.dependencies]
-sphinx = ">=5.3"
+sphinx = ">=7.0.1"
[package.extras]
-docs = ["furo (>=2022.12.7)", "sphinx (>=6.1.3)", "sphinx-autodoc-typehints (>=1.23.4)"]
-testing = ["covdefaults (>=2.2.2)", "coverage (>=7.2.2)", "diff-cover (>=7.5)", "nptyping (>=2.5)", "pytest (>=7.2.2)", "pytest-cov (>=4)", "sphobjinv (>=2.3.1)", "typing-extensions (>=4.5)"]
-type-comment = ["typed-ast (>=1.5.4)"]
+docs = ["furo (>=2023.5.20)", "sphinx (>=7.0.1)"]
+numpy = ["nptyping (>=2.5)"]
+testing = ["covdefaults (>=2.3)", "coverage (>=7.2.7)", "diff-cover (>=7.5)", "pytest (>=7.3.1)", "pytest-cov (>=4.1)", "sphobjinv (>=2.3.1)", "typing-extensions (>=4.6.3)"]
[[package]]
name = "sphinxcontrib-apidoc"
@@ -1288,13 +1285,13 @@ files = [
[[package]]
name = "types-setuptools"
-version = "68.0.0.2"
+version = "68.0.0.3"
description = "Typing stubs for setuptools"
optional = false
python-versions = "*"
files = [
- {file = "types-setuptools-68.0.0.2.tar.gz", hash = "sha256:fede8b46862dd9fe68a12f11a8444c3d240d11178eba7d584d6f22ca3114b894"},
- {file = "types_setuptools-68.0.0.2-py3-none-any.whl", hash = "sha256:311a14819416716029d1113c7452143e2fa857e6cc19186bb6830aff69379c48"},
+ {file = "types-setuptools-68.0.0.3.tar.gz", hash = "sha256:d57ae6076100b5704b3cc869fdefc671e1baf4c2cd6643f84265dfc0b955bf05"},
+ {file = "types_setuptools-68.0.0.3-py3-none-any.whl", hash = "sha256:fec09e5c18264c5c09351c00be01a34456fb7a88e457abe97401325f84ad9d36"},
]
[[package]]
@@ -1359,4 +1356,4 @@ networkx = ["networkx"]
[metadata]
lock-version = "2.0"
python-versions = "^3.8.1"
-content-hash = "2976433b559075bf2b607420b7e80e07b248d630aad915ef0a1ba39bf13e4c8e"
+content-hash = "99e9e88546065df26605b1240b641588740efe954ade7c7b82c20e0b4f38686d"
diff --git a/pyproject.toml b/pyproject.toml
index 29fee25b..dae4e35f 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -47,7 +47,7 @@ html5lib = {version = "^1.0", optional = true}
lxml = {version = "^4.3.0", optional = true}
[tool.poetry.group.dev.dependencies]
-black = "23.3.0"
+black = "23.7.0"
isort = "^5.10.0"
mypy = "^1.1.0"
lxml-stubs = "^0.4.0"
@@ -120,7 +120,7 @@ pyflakes = ["-F821"]
[tool.black]
-required-version = "23.3.0"
+required-version = "23.7.0"
line-length = "88"
target-version = ['py37']
include = '\.pyi?$'
diff --git a/rdflib/paths.py b/rdflib/paths.py
index df713617..9f953878 100644
--- a/rdflib/paths.py
+++ b/rdflib/paths.py
@@ -213,6 +213,15 @@ OneOrMore = "+"
ZeroOrOne = "?"
+def _n3(
+ arg: Union["URIRef", "Path"], namespace_manager: Optional["NamespaceManager"] = None
+) -> str:
+ # type error: Item "Path" of "Union[Path, URIRef]" has no attribute "n3" [union-attr]
+ if isinstance(arg, (SequencePath, AlternativePath)) and len(arg.args) > 1:
+ return "(%s)" % arg.n3(namespace_manager)
+ return arg.n3(namespace_manager) # type: ignore[union-attr]
+
+
@total_ordering
class Path:
__or__: Callable[["Path", Union["URIRef", "Path"]], "AlternativePath"]
@@ -260,8 +269,7 @@ class InvPath(Path):
return "Path(~%s)" % (self.arg,)
def n3(self, namespace_manager: Optional["NamespaceManager"] = None) -> str:
- # type error: Item "Path" of "Union[Path, URIRef]" has no attribute "n3" [union-attr]
- return "^%s" % self.arg.n3(namespace_manager) # type: ignore[union-attr]
+ return "^%s" % _n3(self.arg, namespace_manager)
class SequencePath(Path):
@@ -318,8 +326,7 @@ class SequencePath(Path):
return "Path(%s)" % " / ".join(str(x) for x in self.args)
def n3(self, namespace_manager: Optional["NamespaceManager"] = None) -> str:
- # type error: Item "Path" of "Union[Path, URIRef]" has no attribute "n3" [union-attr]
- return "/".join(a.n3(namespace_manager) for a in self.args) # type: ignore[union-attr]
+ return "/".join(_n3(a, namespace_manager) for a in self.args)
class AlternativePath(Path):
@@ -345,8 +352,7 @@ class AlternativePath(Path):
return "Path(%s)" % " | ".join(str(x) for x in self.args)
def n3(self, namespace_manager: Optional["NamespaceManager"] = None) -> str:
- # type error: Item "Path" of "Union[Path, URIRef]" has no attribute "n3" [union-attr]
- return "|".join(a.n3(namespace_manager) for a in self.args) # type: ignore[union-attr]
+ return "|".join(_n3(a, namespace_manager) for a in self.args)
class MulPath(Path):
@@ -470,8 +476,7 @@ class MulPath(Path):
return "Path(%s%s)" % (self.path, self.mod)
def n3(self, namespace_manager: Optional["NamespaceManager"] = None) -> str:
- # type error: Item "Path" of "Union[Path, URIRef]" has no attribute "n3" [union-attr]
- return "%s%s" % (self.path.n3(namespace_manager), self.mod) # type: ignore[union-attr]
+ return "%s%s" % (_n3(self.path, namespace_manager), self.mod)
class NegatedPath(Path):
@@ -505,8 +510,7 @@ class NegatedPath(Path):
return "Path(! %s)" % ",".join(str(x) for x in self.args)
def n3(self, namespace_manager: Optional["NamespaceManager"] = None) -> str:
- # type error: Item "Path" of "Union[Path, URIRef]" has no attribute "n3" [union-attr]
- return "!(%s)" % ("|".join(arg.n3(namespace_manager) for arg in self.args)) # type: ignore[union-attr]
+ return "!(%s)" % ("|".join(_n3(arg, namespace_manager) for arg in self.args))
class PathList(list):
diff --git a/rdflib/plugins/serializers/trig.py b/rdflib/plugins/serializers/trig.py
index 18bee3f2..6f2aa50a 100644
--- a/rdflib/plugins/serializers/trig.py
+++ b/rdflib/plugins/serializers/trig.py
@@ -40,7 +40,8 @@ class TrigSerializer(TurtleSerializer):
if len(context) == 0:
continue
self.store = context
- self.getQName(context.identifier)
+ # Don't generate a new prefix for a graph URI if one already exists
+ self.getQName(context.identifier, False)
self._subjects = {}
for triple in context:
@@ -97,7 +98,8 @@ class TrigSerializer(TurtleSerializer):
if isinstance(store.identifier, BNode):
iri = store.identifier.n3()
else:
- iri = self.getQName(store.identifier)
+ # Show the full graph URI if a prefix for it doesn't already exist
+ iri = self.getQName(store.identifier, False)
if iri is None:
# type error: "IdentifiedNode" has no attribute "n3"
iri = store.identifier.n3() # type: ignore[attr-defined]
| RDFLib/rdflib | bdd574eee3a9d1eaf5e78d7245f65f5b191e75bd | diff --git a/test/test_path.py b/test/test_path.py
index ad967849..97040523 100644
--- a/test/test_path.py
+++ b/test/test_path.py
@@ -54,15 +54,40 @@ nsm = g.namespace_manager
"rdfs:subClassOf?",
),
(
- RDF.type / RDFS.subClassOf * "*",
+ RDF.type / MulPath(RDFS.subClassOf, "*"),
f"<{RDF.type}>/<{RDFS.subClassOf}>*",
"rdf:type/rdfs:subClassOf*",
),
+ (
+ RDF.type / ((SequencePath(RDFS.subClassOf)) * "*"),
+ f"<{RDF.type}>/<{RDFS.subClassOf}>*",
+ "rdf:type/rdfs:subClassOf*",
+ ),
+ (
+ RDF.type / RDFS.subClassOf * "*",
+ f"(<{RDF.type}>/<{RDFS.subClassOf}>)*",
+ "(rdf:type/rdfs:subClassOf)*",
+ ),
(
-(RDF.type | RDFS.subClassOf),
f"!(<{RDF.type}>|<{RDFS.subClassOf}>)",
"!(rdf:type|rdfs:subClassOf)",
),
+ (
+ -(RDF.type | ((SequencePath(RDFS.subClassOf)) * "*")),
+ f"!(<{RDF.type}>|<{RDFS.subClassOf}>*)",
+ "!(rdf:type|rdfs:subClassOf*)",
+ ),
+ (
+ SequencePath(RDFS.subClassOf),
+ f"<{RDFS.subClassOf}>",
+ "rdfs:subClassOf",
+ ),
+ (
+ AlternativePath(RDFS.subClassOf),
+ f"<{RDFS.subClassOf}>",
+ "rdfs:subClassOf",
+ ),
],
)
def test_paths_n3(
diff --git a/test/test_trig.py b/test/test_trig.py
index de5c2108..1c158fa8 100644
--- a/test/test_trig.py
+++ b/test/test_trig.py
@@ -60,15 +60,15 @@ def test_remember_namespace():
# prefix for the graph but later serialize() calls would work.
first_out = g.serialize(format="trig", encoding="latin-1")
second_out = g.serialize(format="trig", encoding="latin-1")
- assert b"@prefix ns1: <http://example.com/> ." in second_out
- assert b"@prefix ns1: <http://example.com/> ." in first_out
+ assert b"@prefix ns1: <http://example.com/> ." not in second_out
+ assert b"@prefix ns1: <http://example.com/> ." not in first_out
def test_graph_qname_syntax():
g = rdflib.ConjunctiveGraph()
g.add(TRIPLE + (rdflib.URIRef("http://example.com/graph1"),))
out = g.serialize(format="trig", encoding="latin-1")
- assert b"ns1:graph1 {" in out
+ assert b"ns1:graph1 {" not in out
def test_graph_uri_syntax():
@@ -178,9 +178,9 @@ def test_prefixes():
cg.parse(data=data, format="trig")
data = cg.serialize(format="trig", encoding="latin-1")
- assert "ns2: <http://ex.org/docs/".encode("latin-1") in data, data
+ assert "ns2: <http://ex.org/docs/".encode("latin-1") not in data, data
assert "<ns2:document1>".encode("latin-1") not in data, data
- assert "ns2:document1".encode("latin-1") in data, data
+ assert "ns2:document1".encode("latin-1") not in data, data
def test_issue_2154():
| N3 method for path objects is bugged
The n3 method for path objects returns invalid/unexpected paths for non-trivial paths.
Example:
```
import rdflib
import rdflib.paths
path = rdflib.RDF.type / rdflib.paths.AlternativePath(rdflib.SKOS.note, rdflib.RDFS.comment)
```
Calling `path.n3()` here returns `<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>/<http://www.w3.org/2004/02/skos/core#note>|<http://www.w3.org/2000/01/rdf-schema#comment>` (essentially `rdf:type/skos:note|rdfs:comment`).
However, it the method should rather return `<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>/(<http://www.w3.org/2004/02/skos/core#note>|<http://www.w3.org/2000/01/rdf-schema#comment>)` (thus `rdf:type/(skos:note|rdfs:comment)`).
The n3 method ignores all groups as it never introduces any brackets.
Related to https://github.com/RDFLib/rdflib/issues/421 | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/test_path.py::test_paths_n3[path9-(<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>/<http://www.w3.org/2000/01/rdf-schema#subClassOf>)*-(rdf:type/rdfs:subClassOf)*]",
"test/test_trig.py::test_remember_namespace",
"test/test_trig.py::test_graph_qname_syntax",
"test/test_trig.py::test_prefixes"
] | [
"test/test_path.py::test_paths_n3[path0-^<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>-^rdf:type]",
"test/test_path.py::test_paths_n3[path1-<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>/<http://www.w3.org/2000/01/rdf-schema#subClassOf>-rdf:type/rdfs:subClassOf]",
"test/test_path.py::test_paths_n3[path2-<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>|<http://www.w3.org/2000/01/rdf-schema#subClassOf>-rdf:type|rdfs:subClassOf]",
"test/test_path.py::test_paths_n3[path3-!(<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>)-!(rdf:type)]",
"test/test_path.py::test_paths_n3[path4-<http://www.w3.org/2000/01/rdf-schema#subClassOf>*-rdfs:subClassOf*]",
"test/test_path.py::test_paths_n3[path5-<http://www.w3.org/2000/01/rdf-schema#subClassOf>+-rdfs:subClassOf+]",
"test/test_path.py::test_paths_n3[path6-<http://www.w3.org/2000/01/rdf-schema#subClassOf>?-rdfs:subClassOf?]",
"test/test_path.py::test_paths_n3[path7-<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>/<http://www.w3.org/2000/01/rdf-schema#subClassOf>*-rdf:type/rdfs:subClassOf*]",
"test/test_path.py::test_paths_n3[path8-<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>/<http://www.w3.org/2000/01/rdf-schema#subClassOf>*-rdf:type/rdfs:subClassOf*]",
"test/test_path.py::test_paths_n3[path10-!(<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>|<http://www.w3.org/2000/01/rdf-schema#subClassOf>)-!(rdf:type|rdfs:subClassOf)]",
"test/test_path.py::test_paths_n3[path11-!(<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>|<http://www.w3.org/2000/01/rdf-schema#subClassOf>*)-!(rdf:type|rdfs:subClassOf*)]",
"test/test_path.py::test_paths_n3[path12-<http://www.w3.org/2000/01/rdf-schema#subClassOf>-rdfs:subClassOf]",
"test/test_path.py::test_paths_n3[path13-<http://www.w3.org/2000/01/rdf-schema#subClassOf>-rdfs:subClassOf]",
"test/test_path.py::test_mulpath_n3",
"test/test_path.py::test_eq[lhs0-rhs0]",
"test/test_path.py::test_eq[lhs1-rhs1]",
"test/test_path.py::test_hash[lhs0-rhs0]",
"test/test_path.py::test_hash[lhs1-rhs1]",
"test/test_path.py::test_dict_key[insert_path0-check_path0]",
"test/test_path.py::test_dict_key[insert_path1-check_path1]",
"test/test_trig.py::test_empty",
"test/test_trig.py::test_repeat_triples",
"test/test_trig.py::test_same_subject",
"test/test_trig.py::test_graph_uri_syntax",
"test/test_trig.py::test_blank_graph_identifier",
"test/test_trig.py::test_graph_parsing",
"test/test_trig.py::test_round_trips",
"test/test_trig.py::test_default_graph_serializes_without_name",
"test/test_trig.py::test_issue_2154"
] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2023-07-30T12:14:21Z" | bsd-3-clause |
|
RDFLib__rdflib-730 | diff --git a/rdflib/compare.py b/rdflib/compare.py
index 5e3f5994..97de047b 100644
--- a/rdflib/compare.py
+++ b/rdflib/compare.py
@@ -194,6 +194,10 @@ class Color:
self.hashfunc = hashfunc
self._hash_color = None
+ def __str__(self):
+ nodes, color = self.key()
+ return "Color %s (%s nodes)" % (color, nodes)
+
def key(self):
return (len(self.nodes), self.hash_color())
@@ -277,7 +281,7 @@ class _TripleCanonicalizer(object):
others = set()
self._neighbors = defaultdict(set)
for s, p, o in self.graph:
- nodes = set([s, o])
+ nodes = set([s, p, o])
b = set([x for x in nodes if isinstance(x, BNode)])
if len(b) > 0:
others |= nodes - b
@@ -286,6 +290,9 @@ class _TripleCanonicalizer(object):
self._neighbors[s].add(o)
if isinstance(o, BNode):
self._neighbors[o].add(s)
+ if isinstance(p, BNode):
+ self._neighbors[p].add(s)
+ self._neighbors[p].add(p)
if len(bnodes) > 0:
return [
Color(list(bnodes), self.hashfunc, hash_cache=self._hash_cache)
@@ -317,7 +324,7 @@ class _TripleCanonicalizer(object):
while len(sequence) > 0 and not self._discrete(coloring):
W = sequence.pop()
for c in coloring[:]:
- if len(c.nodes) > 1:
+ if len(c.nodes) > 1 or isinstance(c.nodes[0], BNode):
colors = sorted(c.distinguish(W, self.graph),
key=lambda x: x.key(),
reverse=True)
@@ -328,8 +335,17 @@ class _TripleCanonicalizer(object):
sequence = sequence[:si] + colors + sequence[si+1:]
except ValueError:
sequence = colors[1:] + sequence
-
- return coloring
+ combined_colors = []
+ combined_color_map = dict()
+ for color in coloring:
+ color_hash = color.hash_color()
+ # This is a hash collision, and be combined into a single color for individuation.
+ if color_hash in combined_color_map:
+ combined_color_map[color_hash].nodes.extend(color.nodes)
+ else:
+ combined_colors.append(color)
+ combined_color_map[color_hash] = color
+ return combined_colors
@_runtime("to_hash_runtime")
def to_hash(self, stats=None):
@@ -515,14 +531,14 @@ def isomorphic(graph1, graph2):
-def to_canonical_graph(g1):
+def to_canonical_graph(g1, stats=None):
"""Creates a canonical, read-only graph.
Creates a canonical, read-only graph where all bnode id:s are based on
deterministical SHA-256 checksums, correlated with the graph contents.
"""
graph = Graph()
- graph += _TripleCanonicalizer(g1).canonical_triples()
+ graph += _TripleCanonicalizer(g1).canonical_triples(stats=stats)
return ReadOnlyGraphAggregate([graph])
| RDFLib/rdflib | af230076e7796c368ec4c912404fe3baf44761e5 | diff --git a/test/test_canonicalization.py b/test/test_canonicalization.py
index b64059e7..515756a4 100644
--- a/test/test_canonicalization.py
+++ b/test/test_canonicalization.py
@@ -1,6 +1,9 @@
from rdflib import Graph, RDF, BNode, URIRef, Namespace, ConjunctiveGraph, Literal
from rdflib.compare import to_isomorphic, to_canonical_graph
+
+import rdflib
from rdflib.plugins.memory import IOMemory
+
from six import text_type
from io import StringIO
@@ -154,6 +157,130 @@ def negative_graph_match_test():
for inputs in testInputs:
yield fn, inputs[0], inputs[1], inputs[2]
+def test_issue725_collapsing_bnodes():
+ g = rdflib.Graph()
+ g += [
+ (rdflib.term.BNode('N0a76d42406b84fe4b8029d0a7fa04244'),
+ rdflib.term.URIRef(u'http://www.w3.org/1999/02/22-rdf-syntax-ns#object'),
+ rdflib.term.BNode('v2')),
+ (rdflib.term.BNode('N0a76d42406b84fe4b8029d0a7fa04244'),
+ rdflib.term.URIRef(u'http://www.w3.org/1999/02/22-rdf-syntax-ns#predicate'),
+ rdflib.term.BNode('v0')),
+ (rdflib.term.BNode('N0a76d42406b84fe4b8029d0a7fa04244'),
+ rdflib.term.URIRef(u'http://www.w3.org/1999/02/22-rdf-syntax-ns#subject'),
+ rdflib.term.URIRef(u'urn:gp_learner:fixed_var:target')),
+ (rdflib.term.BNode('N0a76d42406b84fe4b8029d0a7fa04244'),
+ rdflib.term.URIRef(u'http://www.w3.org/1999/02/22-rdf-syntax-ns#type'),
+ rdflib.term.URIRef(u'http://www.w3.org/1999/02/22-rdf-syntax-ns#Statement')),
+ (rdflib.term.BNode('N2f62af5936b94a8eb4b1e4bfa8e11d95'),
+ rdflib.term.URIRef(u'http://www.w3.org/1999/02/22-rdf-syntax-ns#object'),
+ rdflib.term.BNode('v1')),
+ (rdflib.term.BNode('N2f62af5936b94a8eb4b1e4bfa8e11d95'),
+ rdflib.term.URIRef(u'http://www.w3.org/1999/02/22-rdf-syntax-ns#predicate'),
+ rdflib.term.BNode('v0')),
+ (rdflib.term.BNode('N2f62af5936b94a8eb4b1e4bfa8e11d95'),
+ rdflib.term.URIRef(u'http://www.w3.org/1999/02/22-rdf-syntax-ns#subject'),
+ rdflib.term.URIRef(u'urn:gp_learner:fixed_var:target')),
+ (rdflib.term.BNode('N2f62af5936b94a8eb4b1e4bfa8e11d95'),
+ rdflib.term.URIRef(u'http://www.w3.org/1999/02/22-rdf-syntax-ns#type'),
+ rdflib.term.URIRef(u'http://www.w3.org/1999/02/22-rdf-syntax-ns#Statement')),
+ (rdflib.term.BNode('N5ae541f93e1d4e5880450b1bdceb6404'),
+ rdflib.term.URIRef(u'http://www.w3.org/1999/02/22-rdf-syntax-ns#object'),
+ rdflib.term.BNode('v5')),
+ (rdflib.term.BNode('N5ae541f93e1d4e5880450b1bdceb6404'),
+ rdflib.term.URIRef(u'http://www.w3.org/1999/02/22-rdf-syntax-ns#predicate'),
+ rdflib.term.BNode('v4')),
+ (rdflib.term.BNode('N5ae541f93e1d4e5880450b1bdceb6404'),
+ rdflib.term.URIRef(u'http://www.w3.org/1999/02/22-rdf-syntax-ns#subject'),
+ rdflib.term.URIRef(u'urn:gp_learner:fixed_var:target')),
+ (rdflib.term.BNode('N5ae541f93e1d4e5880450b1bdceb6404'),
+ rdflib.term.URIRef(u'http://www.w3.org/1999/02/22-rdf-syntax-ns#type'),
+ rdflib.term.URIRef(u'http://www.w3.org/1999/02/22-rdf-syntax-ns#Statement')),
+ (rdflib.term.BNode('N86ac7ca781f546ae939b8963895f672e'),
+ rdflib.term.URIRef(u'http://www.w3.org/1999/02/22-rdf-syntax-ns#object'),
+ rdflib.term.URIRef(u'urn:gp_learner:fixed_var:source')),
+ (rdflib.term.BNode('N86ac7ca781f546ae939b8963895f672e'),
+ rdflib.term.URIRef(u'http://www.w3.org/1999/02/22-rdf-syntax-ns#predicate'),
+ rdflib.term.BNode('v0')),
+ (rdflib.term.BNode('N86ac7ca781f546ae939b8963895f672e'),
+ rdflib.term.URIRef(u'http://www.w3.org/1999/02/22-rdf-syntax-ns#subject'),
+ rdflib.term.URIRef(u'urn:gp_learner:fixed_var:target')),
+ (rdflib.term.BNode('N86ac7ca781f546ae939b8963895f672e'),
+ rdflib.term.URIRef(u'http://www.w3.org/1999/02/22-rdf-syntax-ns#type'),
+ rdflib.term.URIRef(u'http://www.w3.org/1999/02/22-rdf-syntax-ns#Statement')),
+ (rdflib.term.BNode('Nac82b883ca3849b5ab6820b7ac15e490'),
+ rdflib.term.URIRef(u'http://www.w3.org/1999/02/22-rdf-syntax-ns#object'),
+ rdflib.term.BNode('v1')),
+ (rdflib.term.BNode('Nac82b883ca3849b5ab6820b7ac15e490'),
+ rdflib.term.URIRef(u'http://www.w3.org/1999/02/22-rdf-syntax-ns#predicate'),
+ rdflib.term.BNode('v3')),
+ (rdflib.term.BNode('Nac82b883ca3849b5ab6820b7ac15e490'),
+ rdflib.term.URIRef(u'http://www.w3.org/1999/02/22-rdf-syntax-ns#subject'),
+ rdflib.term.URIRef(u'urn:gp_learner:fixed_var:target')),
+ (rdflib.term.BNode('Nac82b883ca3849b5ab6820b7ac15e490'),
+ rdflib.term.URIRef(u'http://www.w3.org/1999/02/22-rdf-syntax-ns#type'),
+ rdflib.term.URIRef(u'http://www.w3.org/1999/02/22-rdf-syntax-ns#Statement'))
+ ]
+
+ turtle = '''
+@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
+@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
+@prefix xml: <http://www.w3.org/XML/1998/namespace> .
+@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
+
+[] a rdf:Statement ;
+ rdf:object [ ] ;
+ rdf:predicate _:v0 ;
+ rdf:subject <urn:gp_learner:fixed_var:target> .
+
+[] a rdf:Statement ;
+ rdf:object _:v1 ;
+ rdf:predicate _:v0 ;
+ rdf:subject <urn:gp_learner:fixed_var:target> .
+
+[] a rdf:Statement ;
+ rdf:object [ ] ;
+ rdf:predicate [ ] ;
+ rdf:subject <urn:gp_learner:fixed_var:target> .
+
+[] a rdf:Statement ;
+ rdf:object <urn:gp_learner:fixed_var:source> ;
+ rdf:predicate _:v0 ;
+ rdf:subject <urn:gp_learner:fixed_var:target> .
+
+[] a rdf:Statement ;
+ rdf:object _:v1 ;
+ rdf:predicate [ ] ;
+ rdf:subject <urn:gp_learner:fixed_var:target> .'''
+
+ #g = Graph()
+ #g.parse(data=turtle, format='turtle')
+
+ stats = {}
+ cg = rdflib.compare.to_canonical_graph(g, stats=stats)
+
+ print ('graph g length: %d, nodes: %d' % (len(g), len(g.all_nodes())))
+ print ('triple_bnode degrees:')
+ for triple_bnode in g.subjects(rdflib.RDF['type'], rdflib.RDF['Statement']):
+ print (len(list(g.triples([triple_bnode, None, None]))))
+ print ('all node out-degrees:')
+ print (sorted([len(list(g.triples([node, None, None]))) for node in g.all_nodes()]))
+ print ('all node in-degrees:')
+ print (sorted([len(list(g.triples([None, None, node]))) for node in g.all_nodes()]))
+ print(g.serialize(format='n3'))
+
+ print ('graph cg length: %d, nodes: %d' % (len(cg), len(cg.all_nodes())))
+ print ('triple_bnode degrees:')
+ for triple_bnode in cg.subjects(rdflib.RDF['type'], rdflib.RDF['Statement']):
+ print (len(list(cg.triples([triple_bnode, None, None]))))
+ print ('all node out-degrees:')
+ print (sorted([len(list(cg.triples([node, None, None]))) for node in cg.all_nodes()]))
+ print ('all node in-degrees:')
+ print (sorted([len(list(cg.triples([None, None, node]))) for node in cg.all_nodes()]))
+ print(cg.serialize(format='n3'))
+
+ assert(len(g.all_nodes()) == len(cg.all_nodes()))
+
def test_issue494_collapsing_bnodes():
"""Test for https://github.com/RDFLib/rdflib/issues/494 collapsing BNodes"""
g = Graph()
| RGDA1 graph canonicalization sometimes still collapses distinct BNodes
During the [evaluation of my graph pattern learner](https://github.com/RDFLib/graph-pattern-learner/blob/master/eval.py#L433) i'm currently trying to generate all possible (different) SPARQL BGPs of a given length (5 at the moment). With up to 11 variables, enumerating all of those graphs might be stretching it a bit, but i'm nearly there. However, to do this, i need the canonical representations of SPARQL BGPs. As discussed before (#483), i'm reducing SPARQL BGPs (and especially their variables) to RDF graphs with BNodes (see [here](https://github.com/RDFLib/graph-pattern-learner/blob/master/graph_pattern.py#L189) if interested), then run RGDA1 on it, and map the canonical BNode labels to the SPARQL Variables.
Similarly to #494, I noticed that sometimes during this process i still lose nodes. Minimal test-case below (PR with test will follow):
```python
g = rdflib.Graph()
g += [
(rdflib.term.BNode('N0a76d42406b84fe4b8029d0a7fa04244'),
rdflib.term.URIRef(u'http://www.w3.org/1999/02/22-rdf-syntax-ns#object'),
rdflib.term.BNode('v2')),
(rdflib.term.BNode('N0a76d42406b84fe4b8029d0a7fa04244'),
rdflib.term.URIRef(u'http://www.w3.org/1999/02/22-rdf-syntax-ns#predicate'),
rdflib.term.BNode('v0')),
(rdflib.term.BNode('N0a76d42406b84fe4b8029d0a7fa04244'),
rdflib.term.URIRef(u'http://www.w3.org/1999/02/22-rdf-syntax-ns#subject'),
rdflib.term.URIRef(u'urn:gp_learner:fixed_var:target')),
(rdflib.term.BNode('N0a76d42406b84fe4b8029d0a7fa04244'),
rdflib.term.URIRef(u'http://www.w3.org/1999/02/22-rdf-syntax-ns#type'),
rdflib.term.URIRef(u'http://www.w3.org/1999/02/22-rdf-syntax-ns#Statement')),
(rdflib.term.BNode('N2f62af5936b94a8eb4b1e4bfa8e11d95'),
rdflib.term.URIRef(u'http://www.w3.org/1999/02/22-rdf-syntax-ns#object'),
rdflib.term.BNode('v1')),
(rdflib.term.BNode('N2f62af5936b94a8eb4b1e4bfa8e11d95'),
rdflib.term.URIRef(u'http://www.w3.org/1999/02/22-rdf-syntax-ns#predicate'),
rdflib.term.BNode('v0')),
(rdflib.term.BNode('N2f62af5936b94a8eb4b1e4bfa8e11d95'),
rdflib.term.URIRef(u'http://www.w3.org/1999/02/22-rdf-syntax-ns#subject'),
rdflib.term.URIRef(u'urn:gp_learner:fixed_var:target')),
(rdflib.term.BNode('N2f62af5936b94a8eb4b1e4bfa8e11d95'),
rdflib.term.URIRef(u'http://www.w3.org/1999/02/22-rdf-syntax-ns#type'),
rdflib.term.URIRef(u'http://www.w3.org/1999/02/22-rdf-syntax-ns#Statement')),
(rdflib.term.BNode('N5ae541f93e1d4e5880450b1bdceb6404'),
rdflib.term.URIRef(u'http://www.w3.org/1999/02/22-rdf-syntax-ns#object'),
rdflib.term.BNode('v5')),
(rdflib.term.BNode('N5ae541f93e1d4e5880450b1bdceb6404'),
rdflib.term.URIRef(u'http://www.w3.org/1999/02/22-rdf-syntax-ns#predicate'),
rdflib.term.BNode('v4')),
(rdflib.term.BNode('N5ae541f93e1d4e5880450b1bdceb6404'),
rdflib.term.URIRef(u'http://www.w3.org/1999/02/22-rdf-syntax-ns#subject'),
rdflib.term.URIRef(u'urn:gp_learner:fixed_var:target')),
(rdflib.term.BNode('N5ae541f93e1d4e5880450b1bdceb6404'),
rdflib.term.URIRef(u'http://www.w3.org/1999/02/22-rdf-syntax-ns#type'),
rdflib.term.URIRef(u'http://www.w3.org/1999/02/22-rdf-syntax-ns#Statement')),
(rdflib.term.BNode('N86ac7ca781f546ae939b8963895f672e'),
rdflib.term.URIRef(u'http://www.w3.org/1999/02/22-rdf-syntax-ns#object'),
rdflib.term.URIRef(u'urn:gp_learner:fixed_var:source')),
(rdflib.term.BNode('N86ac7ca781f546ae939b8963895f672e'),
rdflib.term.URIRef(u'http://www.w3.org/1999/02/22-rdf-syntax-ns#predicate'),
rdflib.term.BNode('v0')),
(rdflib.term.BNode('N86ac7ca781f546ae939b8963895f672e'),
rdflib.term.URIRef(u'http://www.w3.org/1999/02/22-rdf-syntax-ns#subject'),
rdflib.term.URIRef(u'urn:gp_learner:fixed_var:target')),
(rdflib.term.BNode('N86ac7ca781f546ae939b8963895f672e'),
rdflib.term.URIRef(u'http://www.w3.org/1999/02/22-rdf-syntax-ns#type'),
rdflib.term.URIRef(u'http://www.w3.org/1999/02/22-rdf-syntax-ns#Statement')),
(rdflib.term.BNode('Nac82b883ca3849b5ab6820b7ac15e490'),
rdflib.term.URIRef(u'http://www.w3.org/1999/02/22-rdf-syntax-ns#object'),
rdflib.term.BNode('v1')),
(rdflib.term.BNode('Nac82b883ca3849b5ab6820b7ac15e490'),
rdflib.term.URIRef(u'http://www.w3.org/1999/02/22-rdf-syntax-ns#predicate'),
rdflib.term.BNode('v3')),
(rdflib.term.BNode('Nac82b883ca3849b5ab6820b7ac15e490'),
rdflib.term.URIRef(u'http://www.w3.org/1999/02/22-rdf-syntax-ns#subject'),
rdflib.term.URIRef(u'urn:gp_learner:fixed_var:target')),
(rdflib.term.BNode('Nac82b883ca3849b5ab6820b7ac15e490'),
rdflib.term.URIRef(u'http://www.w3.org/1999/02/22-rdf-syntax-ns#type'),
rdflib.term.URIRef(u'http://www.w3.org/1999/02/22-rdf-syntax-ns#Statement'))]
cg = rdflib.compare.to_canonical_graph(g)
```
for `g` we will get the following "stats":
```python
print 'graph length: %d, nodes: %d' % (len(g), len(g.all_nodes()))
print 'triple_bnode degrees:'
for triple_bnode in g.subjects(rdflib.RDF['type'], rdflib.RDF['Statement']):
print len(list(g.triples([triple_bnode, None, None])))
print 'all node out-degrees:'
print sorted([len(list(g.triples([node, None, None]))) for node in g.all_nodes()])
print 'all node in-degrees:'
print sorted([len(list(g.triples([None, None, node]))) for node in g.all_nodes()])
```
> output:
> ```
> graph length: 20, nodes: 14
> triple_bnode degrees:
> 4
> 4
> 4
> 4
> 4
> all node out-degrees:
> [0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 4, 4]
> all node in-degrees:
> [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 3, 5, 5]
> ```
for `cg` we'll get the following:
```python
print 'graph length: %d, nodes: %d' % (len(cg), len(cg.all_nodes()))
print 'triple_bnode degrees:'
for triple_bnode in cg.subjects(rdflib.RDF['type'], rdflib.RDF['Statement']):
print len(list(cg.triples([triple_bnode, None, None])))
print 'all node out-degrees:'
print sorted([len(list(cg.triples([node, None, None]))) for node in cg.all_nodes()])
print 'all node in-degrees:'
print sorted([len(list(cg.triples([None, None, node]))) for node in cg.all_nodes()])
```
> output:
> ```
> graph length: 20, nodes: 13
> triple_bnode degrees:
> 4
> 4
> 4
> 4
> 4
> all node out-degrees:
> [0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 4, 4]
> all node in-degrees:
> [0, 0, 0, 0, 0, 1, 1, 1, 1, 3, 3, 5, 5]
> ```
@jimmccusker could you maybe have another look? | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/test_canonicalization.py::test_issue725_collapsing_bnodes"
] | [
"test/test_canonicalization.py::test_issue494_collapsing_bnodes",
"test/test_canonicalization.py::test_issue682_signing_named_graphs"
] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_issue_reference",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2017-04-09T17:25:59Z" | bsd-3-clause |
|
RDFLib__rdflib-995 | diff --git a/rdflib/term.py b/rdflib/term.py
index 3d290258..125210df 100644
--- a/rdflib/term.py
+++ b/rdflib/term.py
@@ -1383,6 +1383,16 @@ def _unhexlify(value):
value = value.encode()
return unhexlify(value)
+def _parseBoolean(value):
+ true_accepted_values = ['1', 'true']
+ false_accepted_values = ['0', 'false']
+ new_value = value.lower()
+ if new_value in true_accepted_values:
+ return True
+ if new_value not in false_accepted_values:
+ warnings.warn('Parsing weird boolean, % r does not map to True or False' % value, category = DeprecationWarning)
+ return False
+
# Cannot import Namespace/XSD because of circular dependencies
_XSD_PFX = 'http://www.w3.org/2001/XMLSchema#'
_RDF_PFX = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'
@@ -1552,7 +1562,7 @@ XSDToPython = {
URIRef(_XSD_PFX + 'normalizedString'): None,
URIRef(_XSD_PFX + 'token'): None,
URIRef(_XSD_PFX + 'language'): None,
- URIRef(_XSD_PFX + 'boolean'): lambda i: i.lower() == 'true',
+ URIRef(_XSD_PFX + 'boolean'): _parseBoolean,
URIRef(_XSD_PFX + 'decimal'): Decimal,
URIRef(_XSD_PFX + 'integer'): long_type,
URIRef(_XSD_PFX + 'nonPositiveInteger'): int,
| RDFLib/rdflib | 4b114b33808cd48c5d299c5a4391d2a13eeb5ea5 | diff --git a/test/test_literal.py b/test/test_literal.py
index dae2d187..3ed62d11 100644
--- a/test/test_literal.py
+++ b/test/test_literal.py
@@ -1,7 +1,7 @@
import unittest
import rdflib # needed for eval(repr(...)) below
-from rdflib.term import Literal, URIRef, _XSD_DOUBLE, bind
+from rdflib.term import Literal, URIRef, _XSD_DOUBLE, bind, _XSD_BOOLEAN
from six import integer_types, PY3, string_types
@@ -100,6 +100,29 @@ class TestDoubleOutput(unittest.TestCase):
out = vv._literal_n3(use_plain=True)
self.assertTrue(out in ["8.8e-01", "0.88"], out)
+class TestParseBoolean(unittest.TestCase):
+ """confirms the fix for https://github.com/RDFLib/rdflib/issues/913"""
+ def testTrueBoolean(self):
+ test_value = Literal("tRue", datatype = _XSD_BOOLEAN)
+ self.assertTrue(test_value.value)
+ test_value = Literal("1",datatype = _XSD_BOOLEAN)
+ self.assertTrue(test_value.value)
+
+ def testFalseBoolean(self):
+ test_value = Literal("falsE", datatype = _XSD_BOOLEAN)
+ self.assertFalse(test_value.value)
+ test_value = Literal("0",datatype = _XSD_BOOLEAN)
+ self.assertFalse(test_value.value)
+
+ def testNonFalseBoolean(self):
+ test_value = Literal("abcd", datatype = _XSD_BOOLEAN)
+ self.assertRaises(DeprecationWarning)
+ self.assertFalse(test_value.value)
+ test_value = Literal("10",datatype = _XSD_BOOLEAN)
+ self.assertRaises(DeprecationWarning)
+ self.assertFalse(test_value.value)
+
+
class TestBindings(unittest.TestCase):
| Update Lexical-to-value mapping for xsd:boolean
Hi,
I think the function for evaluating literals with datatype ```xsd:boolean``` should be updated.
https://github.com/RDFLib/rdflib/blob/5fa18be1231a5e4dfc86ec28f2f754158c6f6f0b/rdflib/term.py#L1484
Currently, any string which is not equal to "true" or "1" is mapped to "false". However, according to [the spec](https://www.w3.org/TR/xmlschema11-2/#boolean) the lexical space for boolean is only "0", "1", "true", "false". As a result, in case any other lexical value occurs, the parser should raise an Error and not parse it to a Literal with value "false".
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/test_literal.py::TestParseBoolean::testTrueBoolean"
] | [
"test/test_literal.py::TestLiteral::test_backslash",
"test/test_literal.py::TestLiteral::test_literal_from_bool",
"test/test_literal.py::TestLiteral::test_repr_apostrophe",
"test/test_literal.py::TestLiteral::test_repr_quote",
"test/test_literal.py::TestNew::testCantPassLangAndDatatype",
"test/test_literal.py::TestNew::testDatatypeGetsAutoURIRefConversion",
"test/test_literal.py::TestNew::testFromOtherLiteral",
"test/test_literal.py::TestRepr::testOmitsMissingDatatype",
"test/test_literal.py::TestRepr::testOmitsMissingDatatypeAndLang",
"test/test_literal.py::TestRepr::testOmitsMissingLang",
"test/test_literal.py::TestRepr::testSubclassNameAppearsInRepr",
"test/test_literal.py::TestDoubleOutput::testNoDanglingPoint",
"test/test_literal.py::TestParseBoolean::testFalseBoolean",
"test/test_literal.py::TestParseBoolean::testNonFalseBoolean",
"test/test_literal.py::TestBindings::testBinding",
"test/test_literal.py::TestBindings::testSpecificBinding"
] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
} | "2020-04-05T05:50:52Z" | bsd-3-clause |
|
RPing__influx-prompt-17 | diff --git a/influx_prompt/main.py b/influx_prompt/main.py
index 302b02b..4e95b6f 100644
--- a/influx_prompt/main.py
+++ b/influx_prompt/main.py
@@ -34,17 +34,17 @@ class InfluxPrompt(object):
('blue', 'o'),
('indigo', 'm'),
('purple', 'e'),
- ('', '!')
+ ('', '! ')
]), end='')
print_formatted_text(FormattedText([
- ('', 'Any issue please post to '),
+ ('', 'Open an issue here: '),
('ansibrightgreen', 'https://github.com/RPing/influx-prompt/issues'),
]))
if self.args['database'] is None:
print_formatted_text(FormattedText([
('ansibrightyellow', '[Warning] '),
]), end='')
- print('You havn\'t set database. '
+ print('You haven\'t set database. '
'use "use <database>" to specify database.')
session = PromptSession(
diff --git a/influx_prompt/tabular.py b/influx_prompt/tabular.py
index 149f2fc..aadfcd9 100644
--- a/influx_prompt/tabular.py
+++ b/influx_prompt/tabular.py
@@ -20,9 +20,9 @@ def json_to_tabular_result(j):
series_list = rr.series.r(default=None)
for series in series_list:
- name = series['name']
- columns = series['columns']
- values = series['values']
+ name = series.get('name')
+ columns = series.get('columns')
+ values = series.get('values', [])
column_amount = len(columns)
longest_value_len = [0] * column_amount
| RPing/influx-prompt | 4650137ccfaf665816622a332574bd192ce8147c | diff --git a/tests/test_tabular.py b/tests/test_tabular.py
index 74445c8..57d4bae 100644
--- a/tests/test_tabular.py
+++ b/tests/test_tabular.py
@@ -16,6 +16,41 @@ def test_error_in_json():
]
+def test_no_value_key():
+ j = {
+ 'results': [{
+ 'statement_id': 0,
+ 'series': [
+ {'name': '_internal', 'columns': ['name', 'query']},
+ {'name': 'NOAA_water_database', 'columns': ['name', 'query']},
+ ]
+ }]
+ }
+ result = json_to_tabular_result(j)
+ assert result == [
+ ('', 'name: '),
+ ('ansibrightgreen', '_internal'),
+ ('', '\n'),
+ ('orange', 'name '),
+ ('orange', 'query '),
+ ('', '\n'),
+ ('orange', '--- '),
+ ('orange', '--- '),
+ ('', '\n'),
+ ('', '\n'),
+ ('', 'name: '),
+ ('ansibrightgreen', 'NOAA_water_database'),
+ ('', '\n'),
+ ('orange', 'name '),
+ ('orange', 'query '),
+ ('', '\n'),
+ ('orange', '--- '),
+ ('orange', '--- '),
+ ('', '\n'),
+ ('', '\n'),
+ ]
+
+
def test_ordinary_json():
j = {
'results': [{
| Empty values bug
influx-prompt
```
root> SHOW CONTINUOUS QUERIES
Traceback (most recent call last):
File "/home/rpchen1228/.pyenv/versions/3.6.4/bin/influx-prompt", line 8, in <module>
sys.exit(cli())
File "/home/rpchen1228/.pyenv/versions/3.6.4/lib/python3.6/site-packages/influx_prompt/main.py", line 176, in cli
influx_prompt.run_cli()
File "/home/rpchen1228/.pyenv/versions/3.6.4/lib/python3.6/site-packages/influx_prompt/main.py", line 95, in run_cli
arr = json_to_tabular_result(result)
File "/home/rpchen1228/.pyenv/versions/3.6.4/lib/python3.6/site-packages/influx_prompt/tabular.py", line 27, in json_to_tabular_result
values = series['values']
KeyError: 'values'
```
Official cli
```
> SHOW CONTINUOUS QUERIES
name: _internal
name query
---- -----
name: NOAA_water_database
name query
---- -----
>
``` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_tabular.py::test_no_value_key"
] | [
"tests/test_tabular.py::test_error_in_json",
"tests/test_tabular.py::test_ordinary_json",
"tests/test_tabular.py::test_empty_value_in_json",
"tests/test_tabular.py::test_multiple_series_json"
] | {
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2020-09-24T16:02:39Z" | mit |
|
RWTH-EBC__pyCity-248 | diff --git a/pycity_base/classes/building.py b/pycity_base/classes/building.py
index 39c4f19..1eb81ee 100644
--- a/pycity_base/classes/building.py
+++ b/pycity_base/classes/building.py
@@ -182,7 +182,11 @@ class Building(object):
"""
# Initialize array with zeros
- space_heat_power = np.zeros(len(self.apartments[0].demand_space_heating.get_power(currentValues=currentValues)))
+ if currentValues:
+ timesteps = self.environment.timer.timesteps_horizon
+ else:
+ timesteps = self.environment.timer.timesteps_total
+ space_heat_power = np.zeros(timesteps)
# Get power curves of each apartment
for apartment in self.apartments:
@@ -209,8 +213,11 @@ class Building(object):
"""
# Initialize array with zeros
- space_cooling_power = np.zeros(len(self.apartments[0].demand_space_cooling.
- get_power(currentValues=currentValues)))
+ if currentValues:
+ timesteps = self.environment.timer.timesteps_horizon
+ else:
+ timesteps = self.environment.timer.timesteps_total
+ space_cooling_power = np.zeros(timesteps)
# Get power curves of each apartment
for apartment in self.apartments:
@@ -237,7 +244,11 @@ class Building(object):
"""
# Initialize array with zeros
- el_power_curve = np.zeros(len(self.apartments[0].power_el.get_power(currentValues=currentValues)))
+ if currentValues:
+ timesteps = self.environment.timer.timesteps_horizon
+ else:
+ timesteps = self.environment.timer.timesteps_total
+ el_power_curve = np.zeros(timesteps)
# Get power curves of each apartment
for apartment in self.apartments:
@@ -264,9 +275,11 @@ class Building(object):
"""
# Initialize array with zeros
- dhw_heat_power = \
- np.zeros(len(self.apartments[0].demand_domestic_hot_water.
- get_power(currentValues=currentValues, returnTemperature=False)))
+ if currentValues:
+ timesteps = self.environment.timer.timesteps_horizon
+ else:
+ timesteps = self.environment.timer.timesteps_total
+ dhw_heat_power = np.zeros(timesteps)
# Get power curves of each apartment
for apartment in self.apartments:
| RWTH-EBC/pyCity | 5f3b62f6b17c29c344238e2237408bb40d6e19a3 | diff --git a/pycity_base/test/test_building.py b/pycity_base/test/test_building.py
index 8031999..a79e3df 100644
--- a/pycity_base/test/test_building.py
+++ b/pycity_base/test/test_building.py
@@ -6,6 +6,8 @@ Building test.
from __future__ import division
+import numpy as np
+
import pycity_base.classes.demand.apartment as apart
import pycity_base.classes.building as build
import pycity_base.classes.supply.building_energy_system as bes
@@ -78,3 +80,19 @@ class TestBuilding():
assert building.get_number_of_apartments() == 2
assert building.get_number_of_occupants() == 2
assert building.get_net_floor_area_of_building() == 50
+
+ def test_get_power_no_load(self, create_environment):
+ building = build.Building(environment=create_environment)
+
+ bes_unit = bes.BES(environment=create_environment)
+
+ building.addEntity(entity=bes_unit)
+
+ assert all(building.get_space_heating_power_curve(currentValues=False) == 0)
+ assert all(building.get_space_heating_power_curve(currentValues=True) == 0)
+ assert all(building.get_space_cooling_power_curve(currentValues=False) == 0)
+ assert all(building.get_space_cooling_power_curve(currentValues=True) == 0)
+ assert all(building.get_electric_power_curve(currentValues=False) == 0)
+ assert all(building.get_electric_power_curve(currentValues=True) == 0)
+ assert all(building.get_dhw_power_curve(currentValues=False) == 0)
+ assert all(building.get_dhw_power_curve(currentValues=True) == 0)
| Make Building getter methods more robust
Currently the functions `get_space_heating_power_curve`, `get_electric_power_curve` and `get_dhw_power_curve` of the `Building` class return inconsistent results when used in edge cases.
When no loads are given in the apartments they return empty arrays.
Instead they should return arrays of propper length filled with zeros. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"pycity_base/test/test_building.py::TestBuilding::test_get_power_no_load[900]"
] | [
"pycity_base/test/test_building.py::TestBuilding::test_init_building[900]"
] | {
"failed_lite_validators": [
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2019-05-10T10:42:12Z" | mit |
|
Rackspace-DOT__nova-agent-51 | diff --git a/novaagent/libs/centos.py b/novaagent/libs/centos.py
index cfe1afb..b39f9a6 100644
--- a/novaagent/libs/centos.py
+++ b/novaagent/libs/centos.py
@@ -5,6 +5,7 @@ from __future__ import absolute_import
import logging
import os
+import re
from subprocess import Popen
@@ -32,7 +33,12 @@ class ServerOS(DefaultOS):
self.interface_file_prefix,
ifname
)
+ # Check and see if there are extra arguments in ifcfg file
+ extra_args = self._check_for_extra_settings(interface_file)
+
+ # Backup the interface file
utils.backup_file(interface_file)
+
with open(interface_file, 'w') as iffile:
iffile.write('# Automatically generated, do not edit\n\n')
iffile.write('# Label {0}\n'.format(iface['label']))
@@ -92,6 +98,33 @@ class ServerOS(DefaultOS):
iffile.write('ONBOOT=yes\n')
iffile.write('NM_CONTROLLED=no\n')
+ if len(extra_args) > 0:
+ for argument in extra_args:
+ iffile.write('{0}\n'.format(argument))
+
+ def _check_for_extra_settings(self, interface_file):
+ add_args = []
+
+ # The below setting are set in _setup_interface and also ignoring lines
+ # that start with # (comments) and lines with spaces at the beginning
+ known_settings = [
+ '^BOOTPROTO=', '^DEVICE=', '^GATEWAY=', '^IPV6INIT=', '^IPV6ADDR=',
+ '^IPV6_DEFAULTGW=', '^ONBOOT=', '^NM_CONTROLLED=', '^DNS\d+?=',
+ '^IPADDR\d+?=', '^NETMASK\d+?=', '^#', '^\s+'
+ ]
+ log.debug('Checking for additional arguments for ifcfg')
+ pattern = re.compile('|'.join(known_settings))
+ with open(interface_file, 'r') as file:
+ for line in file:
+ if not pattern.search(line):
+ add_args.append(line.strip())
+
+ log.debug(
+ 'Found {0} extra arguments to '
+ 'add to ifcfg file'.format(len(add_args))
+ )
+ return add_args
+
def _setup_routes(self, ifname, iface):
route_file = '{0}/{1}-{2}'.format(
self.netconfig_dir,
| Rackspace-DOT/nova-agent | ac0432fd9a26550d10ece479f39b15ecad464265 | diff --git a/tests/fixtures/network.py b/tests/fixtures/network.py
index a33fe7b..02d4878 100644
--- a/tests/fixtures/network.py
+++ b/tests/fixtures/network.py
@@ -17,7 +17,9 @@ CENTOS_IFCFG_ETH1 = [
'IPADDR=10.208.227.239\n',
'NETMASK=255.255.224.0\n',
'ONBOOT=yes\n',
- 'NM_CONTROLLED=no\n'
+ 'NM_CONTROLLED=no\n',
+ 'ZONE=TestFirewalldZone\n',
+ 'TEST_OPTION=TEST_VALUE\n'
]
CENTOS_IFCFG_ETH0 = [
@@ -38,7 +40,9 @@ CENTOS_IFCFG_ETH0 = [
'DNS1=69.20.0.164\n',
'DNS2=69.20.0.196\n',
'ONBOOT=yes\n',
- 'NM_CONTROLLED=no\n'
+ 'NM_CONTROLLED=no\n',
+ 'ZONE=TestFirewalldZone\n',
+ 'TEST_OPTION=TEST_VALUE\n'
]
ETH0_INTERFACE = {
diff --git a/tests/tests_libs_centos.py b/tests/tests_libs_centos.py
index 697d643..82b3248 100644
--- a/tests/tests_libs_centos.py
+++ b/tests/tests_libs_centos.py
@@ -46,7 +46,14 @@ class TestHelpers(TestCase):
def setup_temp_interface_config(self, interface):
with open('/tmp/ifcfg-{0}'.format(interface), 'a+') as f:
- f.write('This is a test file')
+ f.write(
+ 'IPADDR999=1.1.1.1\n'
+ 'ZONE=TestFirewalldZone\n'
+ '# Comment in file\n'
+ ' Starts with a space\n'
+ ' # Mulitple spaces\n'
+ 'TEST_OPTION=TEST_VALUE\n'
+ )
def setup_temp_hostname(self):
with open('/tmp/hostname', 'a+') as f:
@@ -120,17 +127,20 @@ class TestHelpers(TestCase):
) as ifcfg_files:
ifcfg_files.return_value = ['/tmp/ifcfg-eth1']
with mock.patch(
- 'novaagent.libs.centos.Popen'
- ) as p:
- p.return_value.communicate.return_value = (
- 'out', 'error'
- )
- p.return_value.returncode = 0
- result = temp.resetnetwork(
- 'name',
- 'value',
- 'dummy_client'
- )
+ 'novaagent.libs.centos.ServerOS.'
+ '_check_for_extra_settings'
+ ) as check:
+ check.return_value = []
+ with mock.patch(
+ 'novaagent.libs.centos.Popen'
+ ) as p:
+ p.return_value.communicate.return_value = ('out', 'error') # noqa
+ p.return_value.returncode = 0
+ result = temp.resetnetwork(
+ 'name',
+ 'value',
+ 'dummy_client'
+ )
self.assertEqual(
result,
@@ -197,29 +207,33 @@ class TestHelpers(TestCase):
'novaagent.utils.get_ifcfg_files_to_remove'
) as ifcfg_files:
ifcfg_files.return_value = ['/tmp/ifcfg-eth1']
-
- mock_popen = mock.Mock()
- mock_comm = mock.Mock()
- mock_comm.return_value = ('out', 'error')
- mock_popen.side_effect = [
- mock.Mock(
- returncode=1,
- communicate=mock_comm
- ),
- mock.Mock(
- returncode=0,
- communicate=mock_comm
- )
- ]
with mock.patch(
- 'novaagent.libs.centos.Popen',
- side_effect=mock_popen
- ):
- result = temp.resetnetwork(
- 'name',
- 'value',
- 'dummy_client'
- )
+ 'novaagent.libs.centos.ServerOS.'
+ '_check_for_extra_settings'
+ ) as check:
+ check.return_value = []
+ mock_popen = mock.Mock()
+ mock_comm = mock.Mock()
+ mock_comm.return_value = ('out', 'error')
+ mock_popen.side_effect = [
+ mock.Mock(
+ returncode=1,
+ communicate=mock_comm
+ ),
+ mock.Mock(
+ returncode=0,
+ communicate=mock_comm
+ )
+ ]
+ with mock.patch(
+ 'novaagent.libs.centos.Popen',
+ side_effect=mock_popen
+ ):
+ result = temp.resetnetwork(
+ 'name',
+ 'value',
+ 'dummy_client'
+ )
self.assertEqual(
result,
@@ -287,17 +301,20 @@ class TestHelpers(TestCase):
) as ifcfg_files:
ifcfg_files.return_value = ['/tmp/ifcfg-eth1']
with mock.patch(
- 'novaagent.libs.centos.Popen'
- ) as p:
- p.return_value.communicate.return_value = (
- 'out', 'error'
- )
- p.return_value.returncode = 0
- result = temp.resetnetwork(
- 'name',
- 'value',
- 'dummy_client'
- )
+ 'novaagent.libs.centos.ServerOS.'
+ '_check_for_extra_settings'
+ ) as check:
+ check.return_value = []
+ with mock.patch(
+ 'novaagent.libs.centos.Popen'
+ ) as p:
+ p.return_value.communicate.return_value = ('out', 'error') # noqa
+ p.return_value.returncode = 0
+ result = temp.resetnetwork(
+ 'name',
+ 'value',
+ 'dummy_client'
+ )
self.assertEqual(
result,
@@ -358,17 +375,20 @@ class TestHelpers(TestCase):
) as ifcfg_files:
ifcfg_files.return_value = ['/tmp/ifcfg-eth1']
with mock.patch(
- 'novaagent.libs.centos.Popen'
- ) as p:
- p.return_value.communicate.return_value = (
- 'out', 'error'
- )
- p.return_value.returncode = 1
- result = temp.resetnetwork(
- 'name',
- 'value',
- 'dummy_client'
- )
+ 'novaagent.libs.centos.ServerOS.'
+ '_check_for_extra_settings'
+ ) as check:
+ check.return_value = []
+ with mock.patch(
+ 'novaagent.libs.centos.Popen'
+ ) as p:
+ p.return_value.communicate.return_value = ('out', 'error') # noqa
+ p.return_value.returncode = 1
+ result = temp.resetnetwork(
+ 'name',
+ 'value',
+ 'dummy_client'
+ )
self.assertEqual(
result,
@@ -446,15 +466,20 @@ class TestHelpers(TestCase):
'/tmp/ifcfg-eth1'
]
with mock.patch(
- 'novaagent.libs.centos.Popen'
- ) as p:
- p.return_value.communicate.return_value = ('out', 'error') # noqa
- p.return_value.returncode = 0
- result = temp.resetnetwork(
- 'name',
- 'value',
- 'dummy_client'
- )
+ 'novaagent.libs.centos.ServerOS.'
+ '_check_for_extra_settings'
+ ) as check:
+ check.return_value = []
+ with mock.patch(
+ 'novaagent.libs.centos.Popen'
+ ) as p:
+ p.return_value.communicate.return_value = ('out', 'error') # noqa
+ p.return_value.returncode = 0
+ result = temp.resetnetwork(
+ 'name',
+ 'value',
+ 'dummy_client'
+ )
self.assertEqual(
result,
@@ -531,15 +556,20 @@ class TestHelpers(TestCase):
'/tmp/ifcfg-eth1'
]
with mock.patch(
- 'novaagent.libs.centos.Popen'
- ) as p:
- p.return_value.communicate.return_value = ('out', 'error') # noqa
- p.return_value.returncode = 1
- result = temp.resetnetwork(
- 'name',
- 'value',
- 'dummy_client'
- )
+ 'novaagent.libs.centos.ServerOS.'
+ '_check_for_extra_settings'
+ ) as check:
+ check.return_value = []
+ with mock.patch(
+ 'novaagent.libs.centos.Popen'
+ ) as p:
+ p.return_value.communicate.return_value = ('out', 'error') # noqa
+ p.return_value.returncode = 1
+ result = temp.resetnetwork(
+ 'name',
+ 'value',
+ 'dummy_client'
+ )
self.assertEqual(
result,
@@ -571,6 +601,23 @@ class TestHelpers(TestCase):
'Localhost ifcfg file was moved out of the way and should not have'
)
+ def test_check_extra_args(self):
+ self.setup_temp_interface_config('eth1')
+ temp = centos.ServerOS()
+ interface_file = '/tmp/ifcfg-eth1'
+
+ extra_args = temp._check_for_extra_settings(interface_file)
+ self.assertEqual(
+ len(extra_args),
+ 2,
+ 'Did not get proper number of arguments from check'
+ )
+ self.assertEqual(
+ extra_args,
+ ['ZONE=TestFirewalldZone', 'TEST_OPTION=TEST_VALUE'],
+ 'Did not get proper extra arguments from check'
+ )
+
def test_setup_routes(self):
self.setup_temp_route()
temp = centos.ServerOS()
| preserve firewalld zone
Firewalld is used in the Red Hat ecosystem (Fedora, RHEL, and CentOS). To bind a network interface to a firewalld zone involves add `ZONE=zonename` to the ifcfg-ethX file. It would be great if nova-agent can preserve zones in those files when making it's changes. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/tests_libs_centos.py::TestHelpers::test_check_extra_args",
"tests/tests_libs_centos.py::TestHelpers::test_reset_network_error",
"tests/tests_libs_centos.py::TestHelpers::test_reset_network_error_systemctl",
"tests/tests_libs_centos.py::TestHelpers::test_reset_network_flush_failure",
"tests/tests_libs_centos.py::TestHelpers::test_reset_network_hostname_failure",
"tests/tests_libs_centos.py::TestHelpers::test_reset_network_success",
"tests/tests_libs_centos.py::TestHelpers::test_reset_network_success_systemctl"
] | [
"tests/tests_libs_centos.py::TestHelpers::test_initialization",
"tests/tests_libs_centos.py::TestHelpers::test_setup_hostname_hostname_failure",
"tests/tests_libs_centos.py::TestHelpers::test_setup_hostname_hostname_success",
"tests/tests_libs_centos.py::TestHelpers::test_setup_hostname_hostnamectl_failure",
"tests/tests_libs_centos.py::TestHelpers::test_setup_hostname_hostnamectl_success",
"tests/tests_libs_centos.py::TestHelpers::test_setup_interfaces_eth0",
"tests/tests_libs_centos.py::TestHelpers::test_setup_interfaces_eth1",
"tests/tests_libs_centos.py::TestHelpers::test_setup_routes"
] | {
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
} | "2018-06-28T19:27:05Z" | apache-2.0 |
|
RadioAstronomySoftwareGroup__pyradiosky-134 | diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6402c66..50163c0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,11 +3,13 @@
## [Unreleased]
### Added
+- Support for ring / nested healpix ordering.
- New `SkyModel.concat` method to support concatenating catalogs.
- A new optional parameters `stokes_error` to track errors on the fluxes reported by catalogs.
### Fixed
- Some bugs related to writing & reading skyh5 files after converting object using `healpix_to_point` method.
+
## [0.1.1] - 2021-02-17
### Added
diff --git a/pyradiosky/skymodel.py b/pyradiosky/skymodel.py
index 7c5ce17..4a00dd9 100644
--- a/pyradiosky/skymodel.py
+++ b/pyradiosky/skymodel.py
@@ -153,6 +153,9 @@ class SkyModel(UVBase):
nside parameter for HEALPix maps.
hpx_inds : array_like of int
Indices for HEALPix maps, only used if nside is set.
+ hpx_order : str
+ For HEALPix maps, pixel ordering parameter. Can be "ring" or "nested".
+ Defaults to "ring" if unset in init keywords.
extended_model_group : array_like of str
Identifier that groups components of an extended source model.
Empty string for point sources, shape (Ncomponents,).
@@ -192,6 +195,7 @@ class SkyModel(UVBase):
nside=None,
hpx_inds=None,
stokes_error=None,
+ hpx_order=None,
extended_model_group=None,
beam_amp=None,
history="",
@@ -262,8 +266,19 @@ class SkyModel(UVBase):
expected_type=int,
required=False,
)
+ desc = (
+ "Healpix pixel ordering (ring or nested). Only required for HEALPix maps."
+ )
+ self._hpx_order = UVParameter(
+ "hpx_order",
+ description=desc,
+ value=None,
+ expected_type=str,
+ required=False,
+ acceptable_vals=["ring", "nested"],
+ )
- desc = "Healpix index, only reqired for HEALPix maps. shape (Ncomponents,)"
+ desc = "Healpix indices, only required for HEALPix maps."
self._hpx_inds = UVParameter(
"hpx_inds",
description=desc,
@@ -464,7 +479,7 @@ class SkyModel(UVBase):
self._set_component_type_params("point")
if self.component_type == "healpix":
- req_args = ["nside", "hpx_inds", "stokes", "spectral_type"]
+ req_args = ["nside", "hpx_inds", "stokes", "spectral_type", "hpx_order"]
args_set_req = [
nside is not None,
hpx_inds is not None,
@@ -508,16 +523,27 @@ class SkyModel(UVBase):
self.nside = nside
if hpx_inds is not None:
self.hpx_inds = np.atleast_1d(hpx_inds)
+ if hpx_order is not None:
+ self.hpx_order = str(hpx_order).lower()
+
+ # Ensure that the value can be used in healpix_to_lonlat below.
+ self._hpx_order.check_acceptability()
if self.component_type == "healpix":
- self.Ncomponents = self.hpx_inds.size
try:
import astropy_healpix
except ImportError as e:
raise ImportError(
"The astropy-healpix module must be installed to use HEALPix methods"
) from e
- ra, dec = astropy_healpix.healpix_to_lonlat(hpx_inds, nside)
+
+ if self.hpx_order is None:
+ self.hpx_order = "ring"
+
+ self.Ncomponents = self.hpx_inds.size
+ ra, dec = astropy_healpix.healpix_to_lonlat(
+ hpx_inds, nside, order=self.hpx_order
+ )
self.ra = ra
self.dec = dec
@@ -3770,7 +3796,7 @@ def write_healpix_hdf5(filename, hpmap, indices, freqs, nside=None, history=None
fileobj.attrs[k] = d
-def healpix_to_sky(hpmap, indices, freqs):
+def healpix_to_sky(hpmap, indices, freqs, hpx_order="ring"):
"""
Convert a healpix map in K to a set of point source components in Jy.
@@ -3785,6 +3811,9 @@ def healpix_to_sky(hpmap, indices, freqs):
Corresponding HEALPix indices for hpmap.
freqs : array_like, float
Frequencies in Hz. Shape (Nfreqs)
+ hpx_order : str
+ HEALPix map ordering parameter: ring or nested.
+ Defaults to ring.
Returns
-------
@@ -3808,10 +3837,13 @@ def healpix_to_sky(hpmap, indices, freqs):
"This function will be removed in version 0.2.0.",
category=DeprecationWarning,
)
+ hpx_order = str(hpx_order).lower()
+ if hpx_order not in ["ring", "nested"]:
+ raise ValueError("order must be 'nested' or 'ring'")
nside = int(astropy_healpix.npix_to_nside(hpmap.shape[-1]))
- ra, dec = astropy_healpix.healpix_to_lonlat(indices, nside)
+ ra, dec = astropy_healpix.healpix_to_lonlat(indices, nside, order=hpx_order)
freq = Quantity(freqs, "hertz")
stokes = Quantity(np.zeros((4, len(freq), len(indices))), "K")
@@ -3825,6 +3857,7 @@ def healpix_to_sky(hpmap, indices, freqs):
freq_array=freq,
nside=nside,
hpx_inds=indices,
+ hpx_order=hpx_order,
)
return sky
| RadioAstronomySoftwareGroup/pyradiosky | 638e72e3852a1676242be4deeb68f0dbd58b3952 | diff --git a/pyradiosky/tests/test_skymodel.py b/pyradiosky/tests/test_skymodel.py
index d5d122b..cd9b717 100644
--- a/pyradiosky/tests/test_skymodel.py
+++ b/pyradiosky/tests/test_skymodel.py
@@ -1607,6 +1607,30 @@ def test_units_healpix_to_sky(healpix_data, healpix_disk_old):
assert units.quantity.allclose(sky.stokes[0, 0], stokes[0])
[email protected]("ignore:This method reads an old 'healvis' style healpix")
[email protected]("hpx_order", ["none", "ring", "nested"])
+def test_order_healpix_to_sky(healpix_data, hpx_order):
+
+ inds = np.arange(healpix_data["npix"])
+ hmap_orig = np.zeros_like(inds)
+ hmap_orig[healpix_data["ipix_disc"]] = healpix_data["npix"] - 1
+ hmap_orig = np.repeat(hmap_orig[None, :], 10, axis=0)
+ with pytest.warns(
+ DeprecationWarning,
+ match="This function is deprecated, use `SkyModel.read_skyh5` or `SkyModel.read_healpix_hdf5` instead.",
+ ):
+ if hpx_order == "none":
+ with pytest.raises(ValueError, match="order must be 'nested' or 'ring'"):
+ sky = skymodel.healpix_to_sky(
+ hmap_orig, inds, healpix_data["frequencies"], hpx_order=hpx_order
+ )
+ else:
+ sky = skymodel.healpix_to_sky(
+ hmap_orig, inds, healpix_data["frequencies"], hpx_order=hpx_order
+ )
+ assert sky.hpx_order == hpx_order
+
+
@pytest.mark.filterwarnings("ignore:recarray flux columns will no longer be labeled")
def test_healpix_recarray_loop(healpix_data, healpix_disk_new):
@@ -3059,3 +3083,37 @@ def test_skyh5_read_errors_oldstyle_healpix():
def test_healpix_hdf5_read_errors_newstyle_healpix():
with pytest.raises(ValueError, match="This is a skyh5 file"):
SkyModel.from_healpix_hdf5(os.path.join(SKY_DATA_PATH, "healpix_disk.skyh5"))
+
+
+def test_hpx_ordering():
+ # Setting the hpx_order parameter
+ pytest.importorskip("astropy_healpix")
+ nside = 16
+ npix = 12 * nside ** 2
+ stokes = np.zeros((4, 1, npix)) * units.K
+
+ with pytest.raises(ValueError, match="order must be 'nested' or 'ring'"):
+ sky = SkyModel(
+ hpx_inds=np.arange(npix),
+ nside=nside,
+ hpx_order="none",
+ stokes=stokes,
+ spectral_type="flat",
+ )
+
+ sky = SkyModel(
+ hpx_inds=np.arange(npix),
+ nside=16,
+ hpx_order="Ring",
+ stokes=stokes,
+ spectral_type="flat",
+ )
+ assert sky.hpx_order == "ring"
+ sky = SkyModel(
+ hpx_inds=np.arange(npix),
+ nside=16,
+ hpx_order="NESTED",
+ stokes=stokes,
+ spectral_type="flat",
+ )
+ assert sky.hpx_order == "nested"
| healpix should support either ring or nested ordering
Currently there is no order parameter and it is apparently assumed to be ring (according to @aelanman). Order should be a required parameter for healpix type objects. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"pyradiosky/tests/test_skymodel.py::test_order_healpix_to_sky[none]",
"pyradiosky/tests/test_skymodel.py::test_order_healpix_to_sky[ring]",
"pyradiosky/tests/test_skymodel.py::test_order_healpix_to_sky[nested]",
"pyradiosky/tests/test_skymodel.py::test_hpx_ordering"
] | [
"pyradiosky/tests/test_skymodel.py::test_set_spectral_params",
"pyradiosky/tests/test_skymodel.py::test_init_error",
"pyradiosky/tests/test_skymodel.py::test_init_error_freqparams[spectral_index]",
"pyradiosky/tests/test_skymodel.py::test_init_error_freqparams[full]",
"pyradiosky/tests/test_skymodel.py::test_init_error_freqparams[subband]",
"pyradiosky/tests/test_skymodel.py::test_check_errors",
"pyradiosky/tests/test_skymodel.py::test_source_zenith_from_icrs",
"pyradiosky/tests/test_skymodel.py::test_source_zenith",
"pyradiosky/tests/test_skymodel.py::test_init_lists_errors[flat-ra-All",
"pyradiosky/tests/test_skymodel.py::test_init_lists_errors[flat-ra_lat-All",
"pyradiosky/tests/test_skymodel.py::test_init_lists_errors[flat-dec-All",
"pyradiosky/tests/test_skymodel.py::test_init_lists_errors[flat-dec_lon-All",
"pyradiosky/tests/test_skymodel.py::test_init_lists_errors[flat-stokes-Stokes",
"pyradiosky/tests/test_skymodel.py::test_init_lists_errors[flat-stokes_obj-Stokes",
"pyradiosky/tests/test_skymodel.py::test_init_lists_errors[spectral_index-reference_frequency-If",
"pyradiosky/tests/test_skymodel.py::test_init_lists_errors[spectral_index-reference_frequency_jy-'Jy'\\\\",
"pyradiosky/tests/test_skymodel.py::test_init_lists_errors[spectral_index-reference_frequency_obj-If",
"pyradiosky/tests/test_skymodel.py::test_init_lists_errors[subband-freq_array-If",
"pyradiosky/tests/test_skymodel.py::test_init_lists_errors[subband-freq_array_ang-'deg'\\\\",
"pyradiosky/tests/test_skymodel.py::test_init_lists_errors[subband-freq_array_obj-If",
"pyradiosky/tests/test_skymodel.py::test_skymodel_init_errors",
"pyradiosky/tests/test_skymodel.py::test_jansky_to_kelvin_errors",
"pyradiosky/tests/test_skymodel.py::test_healpix_to_point_errors",
"pyradiosky/tests/test_skymodel.py::test_update_position_errors",
"pyradiosky/tests/test_skymodel.py::test_coherency_calc_errors",
"pyradiosky/tests/test_skymodel.py::test_calc_basis_rotation_matrix",
"pyradiosky/tests/test_skymodel.py::test_calc_vector_rotation",
"pyradiosky/tests/test_skymodel.py::test_pol_rotator[flat]",
"pyradiosky/tests/test_skymodel.py::test_pol_rotator[full]",
"pyradiosky/tests/test_skymodel.py::test_polarized_source_visibilities",
"pyradiosky/tests/test_skymodel.py::test_polarized_source_smooth_visibilities",
"pyradiosky/tests/test_skymodel.py::test_concat_overlap_errors[point]",
"pyradiosky/tests/test_skymodel.py::test_concat_overlap_errors[healpix]",
"pyradiosky/tests/test_skymodel.py::test_read_healpix_hdf5_old",
"pyradiosky/tests/test_skymodel.py::test_units_healpix_to_sky",
"pyradiosky/tests/test_skymodel.py::test_read_write_healpix_oldfunction",
"pyradiosky/tests/test_skymodel.py::test_write_healpix_error",
"pyradiosky/tests/test_skymodel.py::test_healpix_import_err",
"pyradiosky/tests/test_skymodel.py::test_healpix_positions",
"pyradiosky/tests/test_skymodel.py::test_flux_cuts[flat-init_kwargs0-cut_kwargs0]",
"pyradiosky/tests/test_skymodel.py::test_flux_cuts[flat-init_kwargs1-cut_kwargs1]",
"pyradiosky/tests/test_skymodel.py::test_flux_cuts[full-init_kwargs2-cut_kwargs2]",
"pyradiosky/tests/test_skymodel.py::test_flux_cuts[subband-init_kwargs3-cut_kwargs3]",
"pyradiosky/tests/test_skymodel.py::test_flux_cuts[subband-init_kwargs4-cut_kwargs4]",
"pyradiosky/tests/test_skymodel.py::test_flux_cuts[flat-init_kwargs5-cut_kwargs5]",
"pyradiosky/tests/test_skymodel.py::test_source_cut_error[spectral_index-init_kwargs0-cut_kwargs0-NotImplementedError-Flux",
"pyradiosky/tests/test_skymodel.py::test_source_cut_error[full-init_kwargs1-cut_kwargs1-ValueError-freq_range",
"pyradiosky/tests/test_skymodel.py::test_source_cut_error[subband-init_kwargs2-cut_kwargs2-ValueError-freq_range",
"pyradiosky/tests/test_skymodel.py::test_source_cut_error[subband-init_kwargs3-cut_kwargs3-ValueError-No",
"pyradiosky/tests/test_skymodel.py::test_circumpolar_nonrising",
"pyradiosky/tests/test_skymodel.py::test_get_matching_fields[gle-name_list0-kwargs0-GLEAM]",
"pyradiosky/tests/test_skymodel.py::test_get_matching_fields[raj2000-name_list1-kwargs1-RAJ2000]",
"pyradiosky/tests/test_skymodel.py::test_get_matching_fields[ra-name_list2-kwargs2-RAJ2000]",
"pyradiosky/tests/test_skymodel.py::test_get_matching_fields[foo-name_list3-kwargs3-None]",
"pyradiosky/tests/test_skymodel.py::test_get_matching_fields_errors[j2000-name_list0-More",
"pyradiosky/tests/test_skymodel.py::test_get_matching_fields_errors[foo-name_list1-No",
"pyradiosky/tests/test_skymodel.py::test_read_gleam[flat]",
"pyradiosky/tests/test_skymodel.py::test_read_gleam[subband]",
"pyradiosky/tests/test_skymodel.py::test_read_gleam_errors",
"pyradiosky/tests/test_skymodel.py::test_read_deprecated_votable",
"pyradiosky/tests/test_skymodel.py::test_read_votable_errors",
"pyradiosky/tests/test_skymodel.py::test_fhd_catalog_reader_extended_sources",
"pyradiosky/tests/test_skymodel.py::test_fhd_catalog_reader_beam_values",
"pyradiosky/tests/test_skymodel.py::test_fhd_catalog_reader_beam_values_extended",
"pyradiosky/tests/test_skymodel.py::test_fhd_catalog_reader_labeling_extended_sources",
"pyradiosky/tests/test_skymodel.py::test_point_catalog_reader",
"pyradiosky/tests/test_skymodel.py::test_write_text_catalog_error",
"pyradiosky/tests/test_skymodel.py::test_read_text_source_cuts[flat]",
"pyradiosky/tests/test_skymodel.py::test_read_text_source_cuts[subband]",
"pyradiosky/tests/test_skymodel.py::test_pyuvsim_mock_catalog_read",
"pyradiosky/tests/test_skymodel.py::test_read_text_errors",
"pyradiosky/tests/test_skymodel.py::test_zenith_on_moon",
"pyradiosky/tests/test_skymodel.py::test_source_motion",
"pyradiosky/tests/test_skymodel.py::test_stokes_eval[full-True]",
"pyradiosky/tests/test_skymodel.py::test_stokes_eval[full-False]",
"pyradiosky/tests/test_skymodel.py::test_stokes_eval[subband-True]",
"pyradiosky/tests/test_skymodel.py::test_stokes_eval[spectral_index-True]",
"pyradiosky/tests/test_skymodel.py::test_stokes_eval[spectral_index-False]",
"pyradiosky/tests/test_skymodel.py::test_stokes_eval[flat-True]",
"pyradiosky/tests/test_skymodel.py::test_stokes_eval[flat-False]",
"pyradiosky/tests/test_skymodel.py::test_skyh5_read_errors[name-None-Component",
"pyradiosky/tests/test_skymodel.py::test_skyh5_read_errors[Ncomponents-5-Ncomponents",
"pyradiosky/tests/test_skymodel.py::test_skyh5_read_errors[Nfreqs-10-Nfreqs",
"pyradiosky/tests/test_skymodel.py::test_skyh5_read_errors_healpix[nside-None-Component",
"pyradiosky/tests/test_skymodel.py::test_skyh5_read_errors_healpix[hpx_inds-None-Component",
"pyradiosky/tests/test_skymodel.py::test_skyh5_read_errors_healpix[Ncomponents-10-Ncomponents",
"pyradiosky/tests/test_skymodel.py::test_skyh5_read_errors_oldstyle_healpix",
"pyradiosky/tests/test_skymodel.py::test_healpix_hdf5_read_errors_newstyle_healpix"
] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
} | "2021-04-05T16:30:40Z" | bsd-2-clause |
|
RadioAstronomySoftwareGroup__pyradiosky-152 | diff --git a/pyradiosky/skymodel.py b/pyradiosky/skymodel.py
index 8b03268..882b2ed 100644
--- a/pyradiosky/skymodel.py
+++ b/pyradiosky/skymodel.py
@@ -4,8 +4,8 @@
"""Define SkyModel class and helper functions."""
import warnings
-
import os
+
import h5py
import numpy as np
from scipy.linalg import orthogonal_procrustes as ortho_procr
@@ -15,15 +15,11 @@ from astropy.time import Time
import astropy.units as units
from astropy.units import Quantity
from astropy.io import votable
+
from pyuvdata.uvbase import UVBase
from pyuvdata.parameter import UVParameter
import pyuvdata.utils as uvutils
-
-try:
- from pyuvdata.uvbeam.cst_beam import CSTBeam
-except ImportError: # pragma: no cover
- # backwards compatility for older pyuvdata versions
- from pyuvdata.cst_beam import CSTBeam
+from pyuvdata.uvbeam.cst_beam import CSTBeam
from . import utils as skyutils
from . import spherical_coords_transforms as sct
@@ -446,7 +442,7 @@ class SkyModel(UVBase):
# initialize the underlying UVBase properties
super(SkyModel, self).__init__()
- # String to add to history of any files written with this version of pyuvdata
+ # String to add to history of any files written with this version of pyradiosky
self.pyradiosky_version_str = (
" Read/written with pyradiosky version: " + __version__ + "."
)
@@ -713,6 +709,15 @@ class SkyModel(UVBase):
if self.Ncomponents == 1:
self.stokes = self.stokes.reshape(4, self.Nfreqs, 1)
+ stokes_eshape = self._stokes.expected_shape(self)
+ if self.stokes.shape != stokes_eshape:
+ # Check this here to give a clear error. Otherwise this shape
+ # propagates to coherency_radec and gives a confusing error message.
+ raise ValueError(
+ "stokes is not the correct shape. stokes shape is "
+ f"{self.stokes.shape}, expected shape is {stokes_eshape}."
+ )
+
if stokes_error is not None:
self.stokes_error = stokes_error
if self.Ncomponents == 1:
| RadioAstronomySoftwareGroup/pyradiosky | 12a0e78207fc0dc84d87b4547c8d74da8d24e12e | diff --git a/.github/workflows/testsuite.yaml b/.github/workflows/testsuite.yaml
index 2da4e94..e5ebf6f 100644
--- a/.github/workflows/testsuite.yaml
+++ b/.github/workflows/testsuite.yaml
@@ -91,7 +91,7 @@ jobs:
# pytest --pyargs pyradiosky --cov=pyradiosky --cov-config=../.coveragerc --cov-report xml:../coverage.xml --junitxml=../test-reports/xunit.xml
# cd ..
- - uses: codecov/[email protected]
+ - uses: codecov/[email protected]
if: success()
with:
token: ${{secrets.CODECOV_TOKEN}} #required
@@ -139,7 +139,7 @@ jobs:
run: |
python -m pytest -v --cov=pyradiosky --cov-config=.coveragerc --cov-report xml:./coverage.xml --junitxml=test-reports/xunit.xml
- - uses: codecov/[email protected]
+ - uses: codecov/[email protected]
if: success()
with:
token: ${{secrets.CODECOV_TOKEN}} #required
diff --git a/pyradiosky/tests/test_skymodel.py b/pyradiosky/tests/test_skymodel.py
index 3aef7e8..014563b 100644
--- a/pyradiosky/tests/test_skymodel.py
+++ b/pyradiosky/tests/test_skymodel.py
@@ -646,6 +646,16 @@ def test_skymodel_init_errors(zenith_skycoord):
freq_array=[1e8] * units.Hz,
)
+ with pytest.raises(ValueError, match=("stokes is not the correct shape.")):
+ SkyModel(
+ name=["icrs_zen0", "icrs_zen0", "icrs_zen0"],
+ ra=[ra] * 3,
+ dec=[dec] * 3,
+ stokes=[1.0, 0, 0, 0] * units.Jy,
+ spectral_type="flat",
+ freq_array=[1e8] * units.Hz,
+ )
+
with pytest.raises(
ValueError, match=("For point component types, the coherency_radec")
):
| Error message with SkyModel input lengths
When a SkyModel is passed multiple inputs and one is of different length, the error message reads:
`ValueError: UVParameter <pyuvdata.parameter.UVParameter object at 0x7fe0a97efe80> is not expected shape. Parameter shape is (699,), expected shape is (26734,).`
This could be more intuitive to solve if the error indicated which input is of an incorrect length. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"pyradiosky/tests/test_skymodel.py::test_skymodel_init_errors"
] | [
"pyradiosky/tests/test_skymodel.py::test_set_spectral_params",
"pyradiosky/tests/test_skymodel.py::test_init_error",
"pyradiosky/tests/test_skymodel.py::test_init_error_freqparams[spectral_index]",
"pyradiosky/tests/test_skymodel.py::test_init_error_freqparams[full]",
"pyradiosky/tests/test_skymodel.py::test_init_error_freqparams[subband]",
"pyradiosky/tests/test_skymodel.py::test_check_errors",
"pyradiosky/tests/test_skymodel.py::test_source_zenith_from_icrs",
"pyradiosky/tests/test_skymodel.py::test_source_zenith",
"pyradiosky/tests/test_skymodel.py::test_init_lists_errors[flat-ra-All",
"pyradiosky/tests/test_skymodel.py::test_init_lists_errors[flat-ra_lat-All",
"pyradiosky/tests/test_skymodel.py::test_init_lists_errors[flat-dec-All",
"pyradiosky/tests/test_skymodel.py::test_init_lists_errors[flat-dec_lon-All",
"pyradiosky/tests/test_skymodel.py::test_init_lists_errors[flat-stokes-Stokes",
"pyradiosky/tests/test_skymodel.py::test_init_lists_errors[flat-stokes_obj-Stokes",
"pyradiosky/tests/test_skymodel.py::test_init_lists_errors[spectral_index-reference_frequency-If",
"pyradiosky/tests/test_skymodel.py::test_init_lists_errors[spectral_index-reference_frequency_jy-'Jy'\\\\",
"pyradiosky/tests/test_skymodel.py::test_init_lists_errors[spectral_index-reference_frequency_obj-If",
"pyradiosky/tests/test_skymodel.py::test_init_lists_errors[subband-freq_array-If",
"pyradiosky/tests/test_skymodel.py::test_init_lists_errors[subband-freq_array_ang-'deg'\\\\",
"pyradiosky/tests/test_skymodel.py::test_init_lists_errors[subband-freq_array_obj-If",
"pyradiosky/tests/test_skymodel.py::test_jansky_to_kelvin_errors",
"pyradiosky/tests/test_skymodel.py::test_healpix_to_point_errors",
"pyradiosky/tests/test_skymodel.py::test_healpix_to_point_source_cuts",
"pyradiosky/tests/test_skymodel.py::test_update_position_errors",
"pyradiosky/tests/test_skymodel.py::test_coherency_calc_errors",
"pyradiosky/tests/test_skymodel.py::test_calc_basis_rotation_matrix",
"pyradiosky/tests/test_skymodel.py::test_calc_vector_rotation",
"pyradiosky/tests/test_skymodel.py::test_pol_rotator[flat]",
"pyradiosky/tests/test_skymodel.py::test_pol_rotator[full]",
"pyradiosky/tests/test_skymodel.py::test_polarized_source_visibilities",
"pyradiosky/tests/test_skymodel.py::test_polarized_source_smooth_visibilities",
"pyradiosky/tests/test_skymodel.py::test_concat_overlap_errors[point]",
"pyradiosky/tests/test_skymodel.py::test_concat_overlap_errors[healpix]",
"pyradiosky/tests/test_skymodel.py::test_read_healpix_hdf5_old",
"pyradiosky/tests/test_skymodel.py::test_units_healpix_to_sky",
"pyradiosky/tests/test_skymodel.py::test_order_healpix_to_sky[none]",
"pyradiosky/tests/test_skymodel.py::test_order_healpix_to_sky[ring]",
"pyradiosky/tests/test_skymodel.py::test_order_healpix_to_sky[nested]",
"pyradiosky/tests/test_skymodel.py::test_read_write_healpix_oldfunction",
"pyradiosky/tests/test_skymodel.py::test_write_healpix_error",
"pyradiosky/tests/test_skymodel.py::test_healpix_import_err",
"pyradiosky/tests/test_skymodel.py::test_healpix_positions",
"pyradiosky/tests/test_skymodel.py::test_flux_cuts[flat-init_kwargs0-cut_kwargs0]",
"pyradiosky/tests/test_skymodel.py::test_flux_cuts[flat-init_kwargs1-cut_kwargs1]",
"pyradiosky/tests/test_skymodel.py::test_flux_cuts[full-init_kwargs2-cut_kwargs2]",
"pyradiosky/tests/test_skymodel.py::test_flux_cuts[subband-init_kwargs3-cut_kwargs3]",
"pyradiosky/tests/test_skymodel.py::test_flux_cuts[subband-init_kwargs4-cut_kwargs4]",
"pyradiosky/tests/test_skymodel.py::test_flux_cuts[flat-init_kwargs5-cut_kwargs5]",
"pyradiosky/tests/test_skymodel.py::test_source_cut_error[spectral_index-init_kwargs0-cut_kwargs0-NotImplementedError-Flux",
"pyradiosky/tests/test_skymodel.py::test_source_cut_error[full-init_kwargs1-cut_kwargs1-ValueError-freq_range",
"pyradiosky/tests/test_skymodel.py::test_source_cut_error[subband-init_kwargs2-cut_kwargs2-ValueError-freq_range",
"pyradiosky/tests/test_skymodel.py::test_source_cut_error[subband-init_kwargs3-cut_kwargs3-ValueError-No",
"pyradiosky/tests/test_skymodel.py::test_circumpolar_nonrising",
"pyradiosky/tests/test_skymodel.py::test_get_matching_fields[gle-name_list0-kwargs0-GLEAM]",
"pyradiosky/tests/test_skymodel.py::test_get_matching_fields[raj2000-name_list1-kwargs1-RAJ2000]",
"pyradiosky/tests/test_skymodel.py::test_get_matching_fields[ra-name_list2-kwargs2-RAJ2000]",
"pyradiosky/tests/test_skymodel.py::test_get_matching_fields[foo-name_list3-kwargs3-None]",
"pyradiosky/tests/test_skymodel.py::test_get_matching_fields_errors[j2000-name_list0-More",
"pyradiosky/tests/test_skymodel.py::test_get_matching_fields_errors[foo-name_list1-No",
"pyradiosky/tests/test_skymodel.py::test_read_gleam[flat]",
"pyradiosky/tests/test_skymodel.py::test_read_gleam[subband]",
"pyradiosky/tests/test_skymodel.py::test_read_gleam_errors",
"pyradiosky/tests/test_skymodel.py::test_read_deprecated_votable",
"pyradiosky/tests/test_skymodel.py::test_read_votable_errors",
"pyradiosky/tests/test_skymodel.py::test_fhd_catalog_reader_extended_sources",
"pyradiosky/tests/test_skymodel.py::test_fhd_catalog_reader_beam_values",
"pyradiosky/tests/test_skymodel.py::test_fhd_catalog_reader_beam_values_extended",
"pyradiosky/tests/test_skymodel.py::test_fhd_catalog_reader_labeling_extended_sources",
"pyradiosky/tests/test_skymodel.py::test_point_catalog_reader",
"pyradiosky/tests/test_skymodel.py::test_write_text_catalog_error",
"pyradiosky/tests/test_skymodel.py::test_read_text_source_cuts[flat]",
"pyradiosky/tests/test_skymodel.py::test_read_text_source_cuts[subband]",
"pyradiosky/tests/test_skymodel.py::test_pyuvsim_mock_catalog_read",
"pyradiosky/tests/test_skymodel.py::test_read_text_errors",
"pyradiosky/tests/test_skymodel.py::test_zenith_on_moon",
"pyradiosky/tests/test_skymodel.py::test_source_motion",
"pyradiosky/tests/test_skymodel.py::test_stokes_eval[full-True]",
"pyradiosky/tests/test_skymodel.py::test_stokes_eval[full-False]",
"pyradiosky/tests/test_skymodel.py::test_stokes_eval[subband-True]",
"pyradiosky/tests/test_skymodel.py::test_stokes_eval[spectral_index-True]",
"pyradiosky/tests/test_skymodel.py::test_stokes_eval[spectral_index-False]",
"pyradiosky/tests/test_skymodel.py::test_stokes_eval[flat-True]",
"pyradiosky/tests/test_skymodel.py::test_stokes_eval[flat-False]",
"pyradiosky/tests/test_skymodel.py::test_skyh5_read_errors[name-None-Component",
"pyradiosky/tests/test_skymodel.py::test_skyh5_read_errors[Ncomponents-5-Ncomponents",
"pyradiosky/tests/test_skymodel.py::test_skyh5_read_errors[Nfreqs-10-Nfreqs",
"pyradiosky/tests/test_skymodel.py::test_skyh5_read_errors_healpix[nside-None-Component",
"pyradiosky/tests/test_skymodel.py::test_skyh5_read_errors_healpix[hpx_inds-None-Component",
"pyradiosky/tests/test_skymodel.py::test_skyh5_read_errors_healpix[Ncomponents-10-Ncomponents",
"pyradiosky/tests/test_skymodel.py::test_skyh5_read_errors_oldstyle_healpix",
"pyradiosky/tests/test_skymodel.py::test_healpix_hdf5_read_errors_newstyle_healpix",
"pyradiosky/tests/test_skymodel.py::test_hpx_ordering",
"pyradiosky/tests/test_skymodel.py::test_healpix_coordinate_init_override",
"pyradiosky/tests/test_skymodel.py::test_healpix_coordinate_init_override_lists",
"pyradiosky/tests/test_skymodel.py::test_healpix_coordinate_init_no_override",
"pyradiosky/tests/test_skymodel.py::test_healpix_init_override_errors[ra-10-All",
"pyradiosky/tests/test_skymodel.py::test_healpix_init_override_errors[dec-10-All",
"pyradiosky/tests/test_skymodel.py::test_write_clobber_error"
] | {
"failed_lite_validators": [
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
} | "2021-07-30T18:24:40Z" | bsd-2-clause |