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
stringclasses 1
value | environment_setup_commit
stringlengths 40
40
| FAIL_TO_PASS
listlengths 1
4.94k
| PASS_TO_PASS
listlengths 0
7.82k
| meta
dict | created_at
stringlengths 25
25
| license
stringclasses 8
values | __index_level_0__
int64 0
6.41k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
santoshphilip__eppy-286
|
diff --git a/eppy/bunch_subclass.py b/eppy/bunch_subclass.py
index ba78e47..f44c648 100644
--- a/eppy/bunch_subclass.py
+++ b/eppy/bunch_subclass.py
@@ -1,5 +1,6 @@
# Copyright (c) 2012 Santosh Philip
# Copyright (c) 2016 Jamie Bull
+# Copyright (c) 2020 Cheng Cui
# =======================================================================
# Distributed under the MIT License.
# (See accompanying file LICENSE or copy at
diff --git a/eppy/function_helpers.py b/eppy/function_helpers.py
index 140e569..25b8c4d 100644
--- a/eppy/function_helpers.py
+++ b/eppy/function_helpers.py
@@ -1,4 +1,5 @@
# Copyright (c) 2012 Santosh Philip
+# Copyright (c) 2020 Cheng Cui
# =======================================================================
# Distributed under the MIT License.
# (See accompanying file LICENSE or copy at
@@ -58,12 +59,18 @@ def azimuth(ddtt):
def true_azimuth(ddtt):
- """azimuth of the surface"""
+ """true azimuth of the surface"""
idf = ddtt.theidf
- building_north_axis = idf.idfobjects["building".upper()][0].North_Axis
- coords = getcoords(ddtt)
- surface_azimuth = g_surface.azimuth(coords)
- return g_surface.true_azimuth(building_north_axis, surface_azimuth)
+ zone_name = ddtt.Zone_Name
+
+ building_north_axis = idf.idfobjects["building"][0].North_Axis
+ zone_direction_of_relative_north = idf.getobject(
+ "zone", zone_name
+ ).Direction_of_Relative_North
+ surface_azimuth = azimuth(ddtt)
+ return g_surface.true_azimuth(
+ building_north_axis, zone_direction_of_relative_north, surface_azimuth
+ )
def tilt(ddtt):
diff --git a/eppy/geometry/surface.py b/eppy/geometry/surface.py
index 8d2bfb9..1fb822d 100644
--- a/eppy/geometry/surface.py
+++ b/eppy/geometry/surface.py
@@ -1,4 +1,5 @@
# Copyright (c) 2012 Tuan Tran
+# Copyright (c) 2020 Cheng Cui
# This file is part of eppy.
# =======================================================================
@@ -131,10 +132,19 @@ def azimuth(poly):
return angle2vecs(vec_azi, vec_n)
-def true_azimuth(building_north_axis, surface_azimuth):
+def true_azimuth(
+ building_north_axis, zone_direction_of_relative_north, surface_azimuth
+):
"""True azimuth of a polygon poly"""
building_north_axis = 0 if building_north_axis == "" else building_north_axis
- return (building_north_axis + surface_azimuth) % 360
+ zone_direction_of_relative_north = (
+ 0
+ if zone_direction_of_relative_north == ""
+ else zone_direction_of_relative_north
+ )
+ return (
+ building_north_axis + zone_direction_of_relative_north + surface_azimuth
+ ) % 360
def tilt(poly):
|
santoshphilip/eppy
|
43068da6e3769f187aecfa7256ad9f94c08b5115
|
diff --git a/eppy/tests/geometry_tests/test_surface.py b/eppy/tests/geometry_tests/test_surface.py
index 6d5b32c..a1aeba4 100644
--- a/eppy/tests/geometry_tests/test_surface.py
+++ b/eppy/tests/geometry_tests/test_surface.py
@@ -1,4 +1,5 @@
# Copyright (c) 2012 Tuan Tran
+# Copyright (c) 2020 Cheng Cui
# =======================================================================
# Distributed under the MIT License.
# (See accompanying file LICENSE or copy at
@@ -109,13 +110,21 @@ def test_azimuth():
def test_true_azimuth():
"""test the true azimuth of a polygon poly"""
data = (
- ("", 180, 180),
- # building_north_axis, surface_azimuth, answer,
- (20, 0, 20),
- (240, 180, 60),
+ (45, 30, 0, 75),
+ # building_north_axis, zone_direction_of_relative_north, surface_azimuth, answer,
+ ("", 0, 180, 180),
+ (20, "", 20, 40),
+ (240, 90, 180, 150),
)
- for building_north_axis, surface_azimuth, answer in data:
- result = surface.true_azimuth(building_north_axis, surface_azimuth)
+ for (
+ building_north_axis,
+ zone_direction_of_relative_north,
+ surface_azimuth,
+ answer,
+ ) in data:
+ result = surface.true_azimuth(
+ building_north_axis, zone_direction_of_relative_north, surface_azimuth
+ )
assert almostequal(answer, result, places=3) == True
diff --git a/eppy/tests/test_function_helpers.py b/eppy/tests/test_function_helpers.py
index e69de29..3d503c8 100644
--- a/eppy/tests/test_function_helpers.py
+++ b/eppy/tests/test_function_helpers.py
@@ -0,0 +1,162 @@
+# Copyright (c) 2020 Cheng Cui
+# =======================================================================
+# Distributed under the MIT License.
+# (See accompanying file LICENSE or copy at
+# http://opensource.org/licenses/MIT)
+# =======================================================================
+
+"""py.test for function_helpers"""
+
+from __future__ import absolute_import
+from __future__ import division
+from __future__ import print_function
+from __future__ import unicode_literals
+
+from six import StringIO
+
+import eppy.function_helpers as fh
+from eppy.iddcurrent import iddcurrent
+from eppy.modeleditor import IDF
+from eppy.pytest_helpers import almostequal
+
+iddtxt = iddcurrent.iddtxt
+iddfhandle = StringIO(iddcurrent.iddtxt)
+if IDF.getiddname() == None:
+ IDF.setiddname(iddfhandle)
+
+idftxt = """
+ Version,8.0;
+
+ Building,
+ Simple One Zone, !- Name
+ ; !- North Axis {deg}
+
+ Zone,
+ ZONE ONE, !- Name
+ , !- Direction of Relative North {deg}
+ 0, 0, 0; !- X,Y,Z {m}
+
+ GlobalGeometryRules,
+ UpperLeftCorner, !- Starting Vertex Position
+ CounterClockWise, !- Vertex Entry Direction
+ World; !- Coordinate System
+
+ BuildingSurface:Detailed,
+ Zn001:Wall001, !- Name
+ Wall, !- Surface Type
+ R13WALL, !- Construction Name
+ ZONE ONE, !- Zone Name
+ Outdoors, !- Outside Boundary Condition
+ , !- Outside Boundary Condition Object
+ SunExposed, !- Sun Exposure
+ WindExposed, !- Wind Exposure
+ 0.5000000, !- View Factor to Ground
+ 4, !- Number of Vertices
+ 0, 0, 4.572000, !- X,Y,Z 1 {m}
+ 0, 0, 0, !- X,Y,Z 2 {m}
+ 15.24000, 0, 0, !- X,Y,Z 3 {m}
+ 15.24000, 0, 4.572000; !- X,Y,Z 4 {m}
+
+ BuildingSurface:Detailed,
+ Zn001:Wall002, !- Name
+ Wall, !- Surface Type
+ R13WALL, !- Construction Name
+ ZONE ONE, !- Zone Name
+ Outdoors, !- Outside Boundary Condition
+ , !- Outside Boundary Condition Object
+ SunExposed, !- Sun Exposure
+ WindExposed, !- Wind Exposure
+ 0.5000000, !- View Factor to Ground
+ 4, !- Number of Vertices
+ 15.24000, 0, 4.572000, !- X,Y,Z 1 {m}
+ 15.24000, 0, 0, !- X,Y,Z 2 {m}
+ 15.24000, 15.24000, 0, !- X,Y,Z 3 {m}
+ 15.24000, 15.24000, 4.572000; !- X,Y,Z 4 {m}
+
+ BuildingSurface:Detailed,
+ Zn001:Wall003, !- Name
+ Wall, !- Surface Type
+ R13WALL, !- Construction Name
+ ZONE ONE, !- Zone Name
+ Outdoors, !- Outside Boundary Condition
+ , !- Outside Boundary Condition Object
+ SunExposed, !- Sun Exposure
+ WindExposed, !- Wind Exposure
+ 0.5000000, !- View Factor to Ground
+ 4, !- Number of Vertices
+ 15.24000, 15.24000, 4.572000, !- X,Y,Z 1 {m}
+ 15.24000, 15.24000, 0, !- X,Y,Z 2 {m}
+ 0, 15.24000, 0, !- X,Y,Z 3 {m}
+ 0, 15.24000, 4.572000; !- X,Y,Z 4 {m}
+
+ BuildingSurface:Detailed,
+ Zn001:Wall004, !- Name
+ Wall, !- Surface Type
+ R13WALL, !- Construction Name
+ ZONE ONE, !- Zone Name
+ Outdoors, !- Outside Boundary Condition
+ , !- Outside Boundary Condition Object
+ SunExposed, !- Sun Exposure
+ WindExposed, !- Wind Exposure
+ 0.5000000, !- View Factor to Ground
+ 4, !- Number of Vertices
+ 0, 15.24000, 4.572000, !- X,Y,Z 1 {m}
+ 0, 15.24000, 0, !- X,Y,Z 2 {m}
+ 0, 0, 0, !- X,Y,Z 3 {m}
+ 0, 0, 4.572000; !- X,Y,Z 4 {m}
+
+ BuildingSurface:Detailed,
+ Zn001:Flr001, !- Name
+ Floor, !- Surface Type
+ FLOOR, !- Construction Name
+ ZONE ONE, !- Zone Name
+ Adiabatic, !- Outside Boundary Condition
+ , !- Outside Boundary Condition Object
+ NoSun, !- Sun Exposure
+ NoWind, !- Wind Exposure
+ 1.000000, !- View Factor to Ground
+ 4, !- Number of Vertices
+ 15.24000, 0.000000, 0.0, !- X,Y,Z 1 {m}
+ 0.000000, 0.000000, 0.0, !- X,Y,Z 2 {m}
+ 0.000000, 15.24000, 0.0, !- X,Y,Z 3 {m}
+ 15.24000, 15.24000, 0.0; !- X,Y,Z 4 {m}
+
+ BuildingSurface:Detailed,
+ Zn001:Roof001, !- Name
+ Roof, !- Surface Type
+ ROOF31, !- Construction Name
+ ZONE ONE, !- Zone Name
+ Outdoors, !- Outside Boundary Condition
+ , !- Outside Boundary Condition Object
+ SunExposed, !- Sun Exposure
+ WindExposed, !- Wind Exposure
+ 0, !- View Factor to Ground
+ 4, !- Number of Vertices
+ 0.000000, 15.24000, 4.572, !- X,Y,Z 1 {m}
+ 0.000000, 0.000000, 4.572, !- X,Y,Z 2 {m}
+ 15.24000, 0.000000, 4.572, !- X,Y,Z 3 {m}
+ 15.24000, 15.24000, 4.572; !- X,Y,Z 4 {m}
+"""
+
+
+def test_true_azimuth():
+ """py.test for true_azimuth"""
+ data = (
+ (45, 30, 255),
+ # building_north_axis, zone_direction_of_relative_north, answer,
+ ("", 0, 180),
+ (20, "", 200),
+ (240, 90, 150),
+ )
+
+ fhandle = StringIO(idftxt)
+ idf = IDF(fhandle)
+ building = idf.idfobjects["Building"][0]
+ zone = idf.idfobjects["Zone"][0]
+ surface = idf.idfobjects["BuildingSurface:Detailed"][0]
+
+ for building_north_axis, zone_direction_of_relative_north, answer in data:
+ building.North_Axis = building_north_axis
+ zone.Direction_of_Relative_North = zone_direction_of_relative_north
+ result = fh.true_azimuth(surface)
+ assert almostequal(answer, result, places=3) == True
|
surface.true_azimuth does not take into account the zone.Direction_of_Relative_North
This issue has been opened to further address the issue of `surface.true_azimuth` discussed in #282 and #283, where `zone.Direction_of_Relative_North` has yet to be included in the calculation.
|
0.0
|
43068da6e3769f187aecfa7256ad9f94c08b5115
|
[
"eppy/tests/geometry_tests/test_surface.py::test_true_azimuth",
"eppy/tests/test_function_helpers.py::test_true_azimuth"
] |
[
"eppy/tests/geometry_tests/test_surface.py::test_area",
"eppy/tests/geometry_tests/test_surface.py::test_height",
"eppy/tests/geometry_tests/test_surface.py::test_width",
"eppy/tests/geometry_tests/test_surface.py::test_azimuth",
"eppy/tests/geometry_tests/test_surface.py::test_tilt"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_issue_reference",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-06-08 15:59:05+00:00
|
mit
| 5,335 |
|
sarugaku__pip-shims-20
|
diff --git a/README.rst b/README.rst
index e7d7a33..bf5d542 100644
--- a/README.rst
+++ b/README.rst
@@ -124,6 +124,14 @@ index parse_version
download path_to_url
__version__ pip_version
exceptions PipError
+exceptions InstallationError
+exceptions UninstallationError
+exceptions DistributionNotFound
+exceptions RequirementsFileParseError
+exceptions BestVersionAlreadyInstalled
+exceptions BadCommand
+exceptions CommandError
+exceptions PreviousBuildDirError
operations.prepare RequirementPreparer
operations.freeze FrozenRequirement <`__init__`>
req.req_set RequirementSet
diff --git a/docs/quickstart.rst b/docs/quickstart.rst
index d70c0e6..e21b15c 100644
--- a/docs/quickstart.rst
+++ b/docs/quickstart.rst
@@ -127,6 +127,14 @@ index parse_version
download path_to_url
__version__ pip_version
exceptions PipError
+exceptions InstallationError
+exceptions UninstallationError
+exceptions DistributionNotFound
+exceptions RequirementsFileParseError
+exceptions BestVersionAlreadyInstalled
+exceptions BadCommand
+exceptions CommandError
+exceptions PreviousBuildDirError
operations.prepare RequirementPreparer
operations.freeze FrozenRequirement <`__init__`>
req.req_set RequirementSet
diff --git a/news/19.feature.rst b/news/19.feature.rst
new file mode 100644
index 0000000..4eccda6
--- /dev/null
+++ b/news/19.feature.rst
@@ -0,0 +1,9 @@
+Added shims for the following:
+ * ``InstallationError``
+ * ``UninstallationError``
+ * ``DistributionNotFound``
+ * ``RequirementsFileParseError``
+ * ``BestVersionAlreadyInstalled``
+ * ``BadCommand``
+ * ``CommandError``
+ * ``PreviousBuildDirError``
diff --git a/src/pip_shims/shims.py b/src/pip_shims/shims.py
index 656ff7f..7b81a60 100644
--- a/src/pip_shims/shims.py
+++ b/src/pip_shims/shims.py
@@ -32,12 +32,15 @@ class _shims(object):
return list(self._locations.keys())
def __init__(self):
- from .utils import _parse, get_package, STRING_TYPES
- self._parse = _parse
- self.get_package = get_package
- self.STRING_TYPES = STRING_TYPES
+ # from .utils import _parse, get_package, STRING_TYPES
+ from . import utils
+ self.utils = utils
+ self._parse = utils._parse
+ self.get_package = utils.get_package
+ self.STRING_TYPES = utils.STRING_TYPES
self._modules = {
- "pip": importlib.import_module("pip"),
+ "pip": importlib.import_module(self.BASE_IMPORT_PATH),
+ "pip_shims.utils": utils
}
self.pip_version = getattr(self._modules["pip"], "__version__")
self.parsed_pip_version = self._parse(self.pip_version)
@@ -85,6 +88,14 @@ class _shims(object):
("cmdoptions.index_group", "7.0.0", "18.0")
),
"InstallRequirement": ("req.req_install.InstallRequirement", "7.0.0", "9999"),
+ "InstallationError": ("exceptions.InstallationError", "7.0.0", "9999"),
+ "UninstallationError": ("exceptions.UninstallationError", "7.0.0", "9999"),
+ "DistributionNotFound": ("exceptions.DistributionNotFound", "7.0.0", "9999"),
+ "RequirementsFileParseError": ("exceptions.RequirementsFileParseError", "7.0.0", "9999"),
+ "BestVersionAlreadyInstalled": ("exceptions.BestVersionAlreadyInstalled", "7.0.0", "9999"),
+ "BadCommand": ("exceptions.BadCommand", "7.0.0", "9999"),
+ "CommandError": ("exceptions.CommandError", "7.0.0", "9999"),
+ "PreviousBuildDirError": ("exceptions.PreviousBuildDirError", "7.0.0", "9999"),
"install_req_from_editable": (
("req.constructors.install_req_from_editable", "18.1", "9999"),
("req.req_install.InstallRequirement.from_editable", "7.0.0", "18.0")
|
sarugaku/pip-shims
|
91f09eff45fcb3e0b5a27277b49e3d42b7fdc685
|
diff --git a/tests/test_instances.py b/tests/test_instances.py
index 3dceafb..0a96f86 100644
--- a/tests/test_instances.py
+++ b/tests/test_instances.py
@@ -38,7 +38,17 @@ from pip_shims import (
WheelBuilder,
install_req_from_editable,
install_req_from_line,
- FrozenRequirement
+ FrozenRequirement,
+ DistributionNotFound,
+ PipError,
+ InstallationError,
+ UninstallationError,
+ DistributionNotFound,
+ RequirementsFileParseError,
+ BestVersionAlreadyInstalled,
+ BadCommand,
+ CommandError,
+ PreviousBuildDirError,
)
import pytest
import six
@@ -80,7 +90,19 @@ def test_configparser(PipCommand):
@pytest.mark.parametrize(
"exceptionclass, baseclass",
- [(DistributionNotFound, Exception), (PipError, Exception)],
+ [
+ (DistributionNotFound, Exception),
+ (PipError, Exception),
+ (InstallationError, Exception),
+ (UninstallationError, Exception),
+ (DistributionNotFound, Exception),
+ (RequirementsFileParseError, Exception),
+ (BestVersionAlreadyInstalled, Exception),
+ (BadCommand, Exception),
+ (CommandError, Exception),
+ (PreviousBuildDirError, Exception),
+ ],
+
)
def test_exceptions(exceptionclass, baseclass):
assert issubclass(exceptionclass, baseclass)
|
Add more shims for exceptions and errors
@techalchemy commented on [Sat Oct 06 2018](https://github.com/sarugaku/vistir/issues/15)
Include long-supported errors such as `InstallationError`, `UninstallationError`, etc
|
0.0
|
91f09eff45fcb3e0b5a27277b49e3d42b7fdc685
|
[
"tests/test_instances.py::test_strip_extras",
"tests/test_instances.py::test_cmdoptions",
"tests/test_instances.py::test_exceptions[DistributionNotFound-Exception0]",
"tests/test_instances.py::test_exceptions[PipError-Exception]",
"tests/test_instances.py::test_exceptions[InstallationError-Exception]",
"tests/test_instances.py::test_exceptions[DistributionNotFound-Exception1]",
"tests/test_instances.py::test_exceptions[RequirementsFileParseError-Exception]",
"tests/test_instances.py::test_exceptions[BestVersionAlreadyInstalled-Exception]",
"tests/test_instances.py::test_exceptions[BadCommand-Exception]",
"tests/test_instances.py::test_exceptions[CommandError-Exception]",
"tests/test_instances.py::test_exceptions[PreviousBuildDirError-Exception]",
"tests/test_instances.py::test_favorite_hash",
"tests/test_instances.py::test_format_control",
"tests/test_instances.py::test_is_installable",
"tests/test_instances.py::test_frozen_req"
] |
[] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks",
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-10-06 21:35:51+00:00
|
isc
| 5,336 |
|
sarugaku__pip-shims-22
|
diff --git a/news/21.feature.rst b/news/21.feature.rst
new file mode 100644
index 0000000..7b9a196
--- /dev/null
+++ b/news/21.feature.rst
@@ -0,0 +1,1 @@
+Added access to ``pip._internal.models.index.PyPI``.
diff --git a/src/pip_shims/shims.py b/src/pip_shims/shims.py
index 77895b1..34de690 100644
--- a/src/pip_shims/shims.py
+++ b/src/pip_shims/shims.py
@@ -143,6 +143,7 @@ class _shims(object):
("wheel.WheelCache", "7", "9.0.3")
),
"WheelBuilder": ("wheel.WheelBuilder", "7.0.0", "9999"),
+ "PyPI": ("models.index.PyPI", "7.0.0", "9999"),
}
def _ensure_methods(self, cls, classname, *methods):
|
sarugaku/pip-shims
|
cac8c4c8988f72f362645eb51d61ab921e2411a1
|
diff --git a/tests/test_instances.py b/tests/test_instances.py
index 0a96f86..0d02c96 100644
--- a/tests/test_instances.py
+++ b/tests/test_instances.py
@@ -49,6 +49,7 @@ from pip_shims import (
BadCommand,
CommandError,
PreviousBuildDirError,
+ PyPI,
)
import pytest
import six
@@ -391,3 +392,7 @@ def test_wheelbuilder(tmpdir, PipCommand):
builder = WheelBuilder(finder, preparer, wheel_cache)
output_file = builder._build_one(ireq, output_dir.strpath)
assert output_file, output_file
+
+
+def test_pypi():
+ assert "pypi.org" in PyPI.url or "pypi.python.org" in PyPI.url
|
Provide API for PyPI model access
`pip._internal.models.index.PyPI` and `pip.models.index.PyPI` (pre pip 10)
|
0.0
|
cac8c4c8988f72f362645eb51d61ab921e2411a1
|
[
"tests/test_instances.py::test_strip_extras",
"tests/test_instances.py::test_cmdoptions",
"tests/test_instances.py::test_exceptions[DistributionNotFound-Exception0]",
"tests/test_instances.py::test_exceptions[PipError-Exception]",
"tests/test_instances.py::test_exceptions[InstallationError-Exception]",
"tests/test_instances.py::test_exceptions[DistributionNotFound-Exception1]",
"tests/test_instances.py::test_exceptions[RequirementsFileParseError-Exception]",
"tests/test_instances.py::test_exceptions[BestVersionAlreadyInstalled-Exception]",
"tests/test_instances.py::test_exceptions[BadCommand-Exception]",
"tests/test_instances.py::test_exceptions[CommandError-Exception]",
"tests/test_instances.py::test_exceptions[PreviousBuildDirError-Exception]",
"tests/test_instances.py::test_favorite_hash",
"tests/test_instances.py::test_format_control",
"tests/test_instances.py::test_is_installable",
"tests/test_instances.py::test_frozen_req",
"tests/test_instances.py::test_pypi"
] |
[] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_added_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-10-27 05:16:41+00:00
|
isc
| 5,337 |
|
sarugaku__resolvelib-111
|
diff --git a/news/91.bugfix.rst b/news/91.bugfix.rst
new file mode 100644
index 0000000..6b16158
--- /dev/null
+++ b/news/91.bugfix.rst
@@ -0,0 +1,6 @@
+Some valid states that were previously rejected are now accepted. This affects
+states where multiple candidates for the same dependency conflict with each
+other. The ``information`` argument passed to
+``AbstractProvider.get_preference`` may now contain empty iterators. This has
+always been allowed by the method definition but it was previously not possible
+in practice.
diff --git a/src/resolvelib/resolvers.py b/src/resolvelib/resolvers.py
index be8d5f0..49e30c7 100644
--- a/src/resolvelib/resolvers.py
+++ b/src/resolvelib/resolvers.py
@@ -173,6 +173,31 @@ class Resolution(object):
raise RequirementsConflicted(criterion)
criteria[identifier] = criterion
+ def _remove_information_from_criteria(self, criteria, parents):
+ """Remove information from parents of criteria.
+
+ Concretely, removes all values from each criterion's ``information``
+ field that have one of ``parents`` as provider of the requirement.
+
+ :param criteria: The criteria to update.
+ :param parents: Identifiers for which to remove information from all criteria.
+ """
+ if not parents:
+ return
+ for key, criterion in criteria.items():
+ criteria[key] = Criterion(
+ criterion.candidates,
+ [
+ information
+ for information in criterion.information
+ if (
+ information[1] is None
+ or self._p.identify(information[1]) not in parents
+ )
+ ],
+ criterion.incompatibilities,
+ )
+
def _get_preference(self, name):
return self._p.get_preference(
identifier=name,
@@ -367,6 +392,11 @@ class Resolution(object):
self._r.ending(state=self.state)
return self.state
+ # keep track of satisfied names to calculate diff after pinning
+ satisfied_names = set(self.state.criteria.keys()) - set(
+ unsatisfied_names
+ )
+
# Choose the most preferred unpinned criterion to try.
name = min(unsatisfied_names, key=self._get_preference)
failure_causes = self._attempt_to_pin_criterion(name)
@@ -383,6 +413,17 @@ class Resolution(object):
if not success:
raise ResolutionImpossible(self.state.backtrack_causes)
else:
+ # discard as information sources any invalidated names
+ # (unsatisfied names that were previously satisfied)
+ newly_unsatisfied_names = {
+ key
+ for key, criterion in self.state.criteria.items()
+ if key in satisfied_names
+ and not self._is_current_pin_satisfying(key, criterion)
+ }
+ self._remove_information_from_criteria(
+ self.state.criteria, newly_unsatisfied_names
+ )
# Pinning was successful. Push a new state to do another pin.
self._push_new_state()
diff --git a/src/resolvelib/resolvers.pyi b/src/resolvelib/resolvers.pyi
index 0eb5b21..528a1a2 100644
--- a/src/resolvelib/resolvers.pyi
+++ b/src/resolvelib/resolvers.pyi
@@ -55,6 +55,18 @@ class ResolutionImpossible(ResolutionError, Generic[RT, CT]):
class ResolutionTooDeep(ResolutionError):
round_count: int
+# This should be a NamedTuple, but Python 3.6 has a bug that prevents it.
+# https://stackoverflow.com/a/50531189/1376863
+class State(tuple, Generic[RT, CT, KT]):
+ mapping: Mapping[KT, CT]
+ criteria: Mapping[KT, Criterion[RT, CT, KT]]
+ backtrack_causes: Collection[RequirementInformation[RT, CT]]
+
+class Resolution(Generic[RT, CT, KT]):
+ def resolve(
+ self, requirements: Iterable[RT], max_rounds: int
+ ) -> State[RT, CT, KT]: ...
+
class Result(Generic[RT, CT, KT]):
mapping: Mapping[KT, CT]
graph: DirectedGraph[Optional[KT]]
|
sarugaku/resolvelib
|
7f0bd82aa61669af72c609c0bfdf85856c2a7db2
|
diff --git a/tests/functional/python/inputs/index/same-package.json b/tests/functional/python/inputs/index/same-package.json
index 0090db0..c0fc125 100644
--- a/tests/functional/python/inputs/index/same-package.json
+++ b/tests/functional/python/inputs/index/same-package.json
@@ -2,37 +2,37 @@
"package-a": {
"0.1.0": {
"dependencies": [
- "package-x=='0.1.0'; extra == 'x'",
- "package-y=='0.1.0'; extra == 'y'",
- "package-z=='0.1.0'; extra == 'z'"
+ "package-x==0.1.0; extra == 'x'",
+ "package-y==0.1.0; extra == 'y'",
+ "package-z==0.1.0; extra == 'z'"
]
},
"1.0.0": {
"dependencies": [
- "package-x=='1.0.0'; extra == 'x'",
- "package-y=='1.0.0'; extra == 'y'",
- "package-z=='1.0.0'; extra == 'z'"
+ "package-x==1.0.0; extra == 'x'",
+ "package-y==1.0.0; extra == 'y'",
+ "package-z==1.0.0; extra == 'z'"
]
},
"1.1.0": {
"dependencies": [
- "package-x=='1.1.0'; extra == 'x'",
- "package-y=='1.1.0'; extra == 'y'",
- "package-z=='1.1.0'; extra == 'z'"
+ "package-x==1.1.0; extra == 'x'",
+ "package-y==1.1.0; extra == 'y'",
+ "package-z==1.1.0; extra == 'z'"
]
},
"1.2.0": {
"dependencies": [
- "package-x=='1.2.0'; extra == 'x'",
- "package-y=='1.2.0'; extra == 'y'",
- "package-z=='1.2.0'; extra == 'z'"
+ "package-x==1.2.0; extra == 'x'",
+ "package-y==1.2.0; extra == 'y'",
+ "package-z==1.2.0; extra == 'z'"
]
},
"1.3.0": {
"dependencies": [
- "package-x=='1.3.0'; extra == 'x'",
- "package-y=='1.3.0'; extra == 'y'",
- "package-z=='1.3.0'; extra == 'z'"
+ "package-x==1.3.0; extra == 'x'",
+ "package-y==1.3.0; extra == 'y'",
+ "package-z==1.3.0; extra == 'z'"
]
}
},
diff --git a/tests/functional/python/test_resolvers_python.py b/tests/functional/python/test_resolvers_python.py
index 4904615..2b6de36 100644
--- a/tests/functional/python/test_resolvers_python.py
+++ b/tests/functional/python/test_resolvers_python.py
@@ -129,7 +129,6 @@ CASE_NAMES = [name for name in os.listdir(CASE_DIR) if name.endswith(".json")]
XFAIL_CASES = {
"pyrex-1.9.8.json": "Too many rounds (>500)",
- "same-package-extras.json": "State not cleaned up correctly",
}
diff --git a/tests/test_resolvers.py b/tests/test_resolvers.py
index 8af925a..176108f 100644
--- a/tests/test_resolvers.py
+++ b/tests/test_resolvers.py
@@ -1,4 +1,18 @@
+from typing import (
+ Any,
+ Iterable,
+ Iterator,
+ List,
+ Mapping,
+ Sequence,
+ Set,
+ Tuple,
+ Union,
+)
+
import pytest
+from packaging.requirements import Requirement
+from packaging.version import Version
from resolvelib import (
AbstractProvider,
@@ -7,6 +21,12 @@ from resolvelib import (
ResolutionImpossible,
Resolver,
)
+from resolvelib.resolvers import (
+ Criterion,
+ RequirementInformation,
+ RequirementsConflicted,
+ Resolution,
+)
def test_candidate_inconsistent_error():
@@ -143,3 +163,109 @@ def test_resolving_conflicts():
backtracking_causes = run_resolver([("a", {1, 2}), ("b", {1})])
exception_causes = run_resolver([("a", {2}), ("b", {1})])
assert exception_causes == backtracking_causes
+
+
+def test_pin_conflict_with_self(monkeypatch, reporter):
+ # type: (Any, BaseReporter) -> None
+ """
+ Verify correct behavior of attempting to pin a candidate version that conflicts
+ with a previously pinned (now invalidated) version for that same candidate (#91).
+ """
+ Candidate = Tuple[
+ str, Version, Sequence[str]
+ ] # name, version, requirements
+ all_candidates = {
+ "parent": [("parent", Version("1"), ["child<2"])],
+ "child": [
+ ("child", Version("2"), ["grandchild>=2"]),
+ ("child", Version("1"), ["grandchild<2"]),
+ ("child", Version("0.1"), ["grandchild"]),
+ ],
+ "grandchild": [
+ ("grandchild", Version("2"), []),
+ ("grandchild", Version("1"), []),
+ ],
+ } # type: Mapping[str, Sequence[Candidate]]
+
+ class Provider(AbstractProvider): # AbstractProvider[str, Candidate, str]
+ def identify(self, requirement_or_candidate):
+ # type: (Union[str, Candidate]) -> str
+ result = (
+ Requirement(requirement_or_candidate).name
+ if isinstance(requirement_or_candidate, str)
+ else requirement_or_candidate[0]
+ )
+ assert result in all_candidates, "unknown requirement_or_candidate"
+ return result
+
+ def get_preference(self, identifier, *args, **kwargs):
+ # type: (str, *object, **object) -> str
+ # prefer child over parent (alphabetically)
+ return identifier
+
+ def get_dependencies(self, candidate):
+ # type: (Candidate) -> Sequence[str]
+ return candidate[2]
+
+ def find_matches(
+ self,
+ identifier, # type: str
+ requirements, # type: Mapping[str, Iterator[str]]
+ incompatibilities, # type: Mapping[str, Iterator[Candidate]]
+ ):
+ # type: (...) -> Iterator[Candidate]
+ return (
+ candidate
+ for candidate in all_candidates[identifier]
+ if all(
+ self.is_satisfied_by(req, candidate)
+ for req in requirements[identifier]
+ )
+ if candidate not in incompatibilities[identifier]
+ )
+
+ def is_satisfied_by(self, requirement, candidate):
+ # type: (str, Candidate) -> bool
+ return candidate[1] in Requirement(requirement).specifier
+
+ # patch Resolution._get_updated_criteria to collect rejected states
+ rejected_criteria = [] # type: List[Criterion]
+ get_updated_criteria_orig = (
+ Resolution._get_updated_criteria # type: ignore[attr-defined]
+ )
+
+ def get_updated_criteria_patch(self, candidate):
+ try:
+ return get_updated_criteria_orig(self, candidate)
+ except RequirementsConflicted as e:
+ rejected_criteria.append(e.criterion)
+ raise
+
+ monkeypatch.setattr(
+ Resolution, "_get_updated_criteria", get_updated_criteria_patch
+ )
+
+ resolver = Resolver(
+ Provider(), reporter
+ ) # type: Resolver[str, Candidate, str]
+ result = resolver.resolve(["child", "parent"])
+
+ def get_child_versions(information):
+ # type: (Iterable[RequirementInformation[str, Candidate]]) -> Set[str]
+ return {
+ str(inf.parent[1])
+ for inf in information
+ if inf.parent is not None and inf.parent[0] == "child"
+ }
+
+ # verify that none of the rejected criteria are based on more than one candidate for
+ # child
+ assert not any(
+ len(get_child_versions(criterion.information)) > 1
+ for criterion in rejected_criteria
+ )
+
+ assert set(result.mapping) == {"parent", "child", "grandchild"}
+ assert result.mapping["parent"][1] == Version("1")
+ assert result.mapping["child"][1] == Version("1")
+ assert result.mapping["grandchild"][1] == Version("1")
|
criteria compatibility check while backtracking includes dependencies for version we're backtracking on
# Context
While using pip, which makes use of this library, I noticed that `pip install flake8 flake8-isort` resulted in backtracking over all flake8's versions, not finding a suitable candidate, followed by backtracking over flake8-isort's versions until a suitable (but very old) candidate was found there. When I looked at these projects I didn't see any reason why none of the flake8 versions would be compatible with the latest flake8-isort. Indeed, reversing the order (`pip install flake8-isort`) installs the latest flake8-isort and a compatible flake8 as expected, only having to backtrack once on flake8.
When I noticed this seemingly inconsistent behavior I added some breakpoints to this library's code and tried to get a grasp of what was going on. I should note as a disclaimer that I haven't worked with this code before, so I might just be missing something.
# Concrete
Here's a timeline of what I believe happens for `pip install flake8 flake8-isort`:
1. The latest flake8 (`4.0.1` at the time of writing) gets selected.
2. The latest flake8-isort gets selected
3. The flake8-isort candidate requires `flake8<4`, which isn't compatible with the flake8 candidate, so we backtrack on flake8.
4. For each flake8 version, we check if its dependencies are compatible with the current criteria: https://github.com/sarugaku/resolvelib/blob/62c56b587c69a42c8f006e032bbf17a63df54d45/src/resolvelib/resolvers.py#L203-L204
5. This fails with
```
> /home/sander/.virtualenvs/temp/lib/python3.9/site-packages/pip/_vendor/resolvelib/resolvers.py(218)_attempt_to_pin_criterion()
-> continue
(Pdb) l
213 try:
214 criteria = self._get_updated_criteria(candidate)
215 except RequirementsConflicted as e:
216 causes.append(e.criterion)
217 breakpoint()
218 -> continue
219
220 # Check the newly-pinned candidate actually works. This should
221 # always pass under normal circumstances, but in the case of a
222 # faulty provider, we will raise an error to notify the implementer
223 # to fix find_matches() and/or is_satisfied_by().
(Pdb) e.criterion
Criterion((SpecifierRequirement('pyflakes<2.5.0,>=2.4.0'), via=LinkCandidate('https://files.pythonhosted.org/packages/34/39/cde2c8a227abb4f9ce62fe55586b920f438f1d2903a1a22514d0b982c333/flake8-4.0.1-py2.py3-none-any.whl#sha256=479b1304f72536a55948cb40a32dce8bb0ffe3501e26eaf292c7e60eb5e0428d (from https://pypi.org/simple/flake8/) (requires-python:>=3.6)')), (SpecifierRequirement('pyflakes<2.4.0,>=2.3.0'), via=LinkCandidate('https://files.pythonhosted.org/packages/fc/80/35a0716e5d5101e643404dabd20f07f5528a21f3ef4032d31a49c913237b/flake8-3.9.2-py2.py3-none-any.whl#sha256=bf8fd333346d844f616e8d47905ef3a3384edae6b4e9beb0c5101e25e3110907 (from https://pypi.org/simple/flake8/) (requires-python:!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,>=2.7)')))
```
This seems to indicate that the dependency compatibility check includes the dependencies of the version we're backtracking on. Since the currently selected flake8 has a dependency constraint which is incompatible with the constraints for all older versions, backtracking fails. In practice, the latest `flake8<4` is compatible with the rest of the current criteria.
|
0.0
|
7f0bd82aa61669af72c609c0bfdf85856c2a7db2
|
[
"tests/test_resolvers.py::test_pin_conflict_with_self"
] |
[
"tests/functional/python/test_resolvers_python.py::test_resolver[with-without-extras]",
"tests/functional/python/test_resolvers_python.py::test_resolver[same-package-extras]",
"tests/functional/python/test_resolvers_python.py::test_resolver[cheroot]",
"tests/functional/python/test_resolvers_python.py::test_resolver[different-extras]",
"tests/functional/python/test_resolvers_python.py::test_resolver[conflict-with-dependency]",
"tests/functional/python/test_resolvers_python.py::test_resolver[same-package]",
"tests/functional/python/test_resolvers_python.py::test_resolver[chalice]",
"tests/test_resolvers.py::test_candidate_inconsistent_error",
"tests/test_resolvers.py::test_candidate_depends_on_requirements_of_same_identifier[specifiers0]",
"tests/test_resolvers.py::test_candidate_depends_on_requirements_of_same_identifier[specifiers1]",
"tests/test_resolvers.py::test_resolving_conflicts"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-10-12 20:43:03+00:00
|
isc
| 5,338 |
|
sarugaku__resolvelib-22
|
diff --git a/news/4.bugfix.rst b/news/4.bugfix.rst
new file mode 100644
index 0000000..071d5ae
--- /dev/null
+++ b/news/4.bugfix.rst
@@ -0,0 +1,3 @@
+Ensure the result returned by the resolver only contains candidates that are
+actually needed. This is done by tracing the graph after resolution completes,
+snipping nodes that don’t have a route to the root.
diff --git a/src/resolvelib/resolvers.py b/src/resolvelib/resolvers.py
index e733124..183b002 100644
--- a/src/resolvelib/resolvers.py
+++ b/src/resolvelib/resolvers.py
@@ -105,7 +105,7 @@ class ResolutionTooDeep(ResolutionError):
# Resolution state in a round.
-State = collections.namedtuple("State", "mapping graph criteria")
+State = collections.namedtuple("State", "mapping criteria")
class Resolution(object):
@@ -136,14 +136,10 @@ class Resolution(object):
try:
base = self._states[-1]
except IndexError:
- graph = DirectedGraph()
- graph.add(None) # Sentinel as root dependencies' parent.
- state = State(mapping={}, graph=graph, criteria={})
+ state = State(mapping={}, criteria={})
else:
state = State(
- mapping=base.mapping.copy(),
- graph=base.graph.copy(),
- criteria=base.criteria.copy(),
+ mapping=base.mapping.copy(), criteria=base.criteria.copy(),
)
self._states.append(state)
@@ -178,41 +174,16 @@ class Resolution(object):
def _check_pinnability(self, candidate, dependencies):
backup = self.state.criteria.copy()
- contributed = set()
try:
for subdep in dependencies:
key = self._p.identify(subdep)
self._contribute_to_criteria(key, subdep, parent=candidate)
- contributed.add(key)
except RequirementsConflicted:
criteria = self.state.criteria
criteria.clear()
criteria.update(backup)
- return None
- return contributed
-
- def _pin_candidate(self, name, criterion, candidate, child_names):
- try:
- self.state.graph.remove(name)
- except KeyError:
- pass
- self.state.mapping[name] = candidate
- self.state.graph.add(name)
- for parent in criterion.iter_parent():
- parent_name = None if parent is None else self._p.identify(parent)
- try:
- self.state.graph.connect(parent_name, name)
- except KeyError:
- # Parent is not yet pinned. Skip now; this edge will be
- # connected when the parent is being pinned.
- pass
- for child_name in child_names:
- try:
- self.state.graph.connect(name, child_name)
- except KeyError:
- # Child is not yet pinned. Skip now; this edge will be
- # connected when the child is being pinned.
- pass
+ return False
+ return True
def _pin_criteria(self):
criteria = self.state.criteria
@@ -233,15 +204,11 @@ class Resolution(object):
if self._is_current_pin_satisfying(name, criterion):
# If the current pin already works, just use it.
continue
- candidates = list(criterion.candidates)
- while candidates:
- candidate = candidates.pop()
+ for candidate in reversed(criterion.candidates):
dependencies = self._p.get_dependencies(candidate)
- child_names = self._check_pinnability(candidate, dependencies)
- if child_names is None:
- continue
- self._pin_candidate(name, criterion, candidate, child_names)
- break
+ if self._check_pinnability(candidate, dependencies):
+ self.state.mapping[name] = candidate
+ break
else:
# All candidates tried, nothing works. This criterion is a dead
# end, signal for backtracking.
@@ -324,6 +291,56 @@ class Resolution(object):
raise ResolutionTooDeep(max_rounds)
+def _has_route_to_root(criteria, key, all_keys, connected):
+ if key in connected:
+ return True
+ for p in criteria[key].iter_parent():
+ try:
+ pkey = all_keys[id(p)]
+ except KeyError:
+ continue
+ if pkey in connected:
+ connected.add(key)
+ return True
+ if _has_route_to_root(criteria, pkey, all_keys, connected):
+ connected.add(key)
+ return True
+ return False
+
+
+Result = collections.namedtuple("Result", "mapping graph criteria")
+
+
+def _build_result(state):
+ mapping = state.mapping
+ all_keys = {id(v): k for k, v in mapping.items()}
+ all_keys[id(None)] = None
+
+ graph = DirectedGraph()
+ graph.add(None) # Sentinel as root dependencies' parent.
+
+ connected = {None}
+ for key, criterion in state.criteria.items():
+ if not _has_route_to_root(state.criteria, key, all_keys, connected):
+ continue
+ if key not in graph:
+ graph.add(key)
+ for p in criterion.iter_parent():
+ try:
+ pkey = all_keys[id(p)]
+ except KeyError:
+ continue
+ if pkey not in graph:
+ graph.add(pkey)
+ graph.connect(pkey, key)
+
+ return Result(
+ mapping={k: v for k, v in mapping.items() if k in connected},
+ graph=graph,
+ criteria=state.criteria,
+ )
+
+
class Resolver(AbstractResolver):
"""The thing that performs the actual resolution work.
"""
@@ -358,4 +375,4 @@ class Resolver(AbstractResolver):
"""
resolution = Resolution(self.provider, self.reporter)
resolution.resolve(requirements, max_rounds=max_rounds)
- return resolution.state
+ return _build_result(resolution.state)
|
sarugaku/resolvelib
|
b6963a9af16346cf908bd2f7cacec80112835880
|
diff --git a/tests/functional/cocoapods/test_resolvers_cocoapods.py b/tests/functional/cocoapods/test_resolvers_cocoapods.py
index 6e8b68b..428e17a 100644
--- a/tests/functional/cocoapods/test_resolvers_cocoapods.py
+++ b/tests/functional/cocoapods/test_resolvers_cocoapods.py
@@ -84,6 +84,10 @@ class CocoaPodsInputProvider(AbstractProvider):
Requirement(key, _parse_specifier_set(spec))
for key, spec in case_data["requested"].items()
]
+ self.preferred_versions = {
+ entry["name"]: packaging.version.parse(entry["version"])
+ for entry in case_data["base"]
+ }
self.expected_resolution = dict(_iter_resolved(case_data["resolved"]))
self.expected_conflicts = case_data["conflicts"]
@@ -111,9 +115,16 @@ class CocoaPodsInputProvider(AbstractProvider):
yield Candidate(entry["name"], version, dependencies)
def find_matches(self, requirement):
- return sorted(
- self._iter_matches(requirement), key=operator.attrgetter("ver"),
- )
+ mapping = {c.ver: c for c in self._iter_matches(requirement)}
+ try:
+ version = self.preferred_versions[requirement.name]
+ preferred_candidate = mapping.pop(version)
+ except KeyError:
+ preferred_candidate = None
+ candidates = sorted(mapping.values(), key=operator.attrgetter("ver"))
+ if preferred_candidate:
+ candidates.append(preferred_candidate)
+ return candidates
def is_satisfied_by(self, requirement, candidate):
return candidate.ver in requirement.spec
@@ -123,6 +134,7 @@ class CocoaPodsInputProvider(AbstractProvider):
XFAIL_CASES = {
+ "circular.json": "different resolution",
"complex_conflict.json": "different resolution",
"complex_conflict_unwinding.json": "different resolution",
"conflict_on_child.json": "different resolution",
@@ -131,9 +143,7 @@ XFAIL_CASES = {
"previous_conflict.json": "different resolution",
"pruned_unresolved_orphan.json": "different resolution",
"shared_parent_dependency_with_swapping.json": "KeyError: 'fog'",
- "simple_with_base.json": "different resolution",
"spapping_and_rewinding.json": "different resolution",
- "swapping_children_with_successors.json": "different resolution",
}
@@ -157,13 +167,10 @@ def test_resolver(provider, base_reporter):
resolver = Resolver(provider, base_reporter)
result = resolver.resolve(provider.root_requirements)
- if provider.expected_conflicts:
- return
-
display = {
identifier: str(candidate.ver)
for identifier, candidate in result.mapping.items()
}
assert display == provider.expected_resolution
- # TODO: Handle errors and assert conflicts.
+ # TODO: Assert conflicts.
|
Clean up graph after resolution
Resolver should clean up the graph to purge dead subtrees, and maping to remove unneeded pins after resolution (or maybe after each round?).
|
0.0
|
b6963a9af16346cf908bd2f7cacec80112835880
|
[
"tests/functional/cocoapods/test_resolvers_cocoapods.py::test_resolver[swapping_children_with_successors]"
] |
[
"tests/functional/cocoapods/test_resolvers_cocoapods.py::test_resolver[unresolvable_child]",
"tests/functional/cocoapods/test_resolvers_cocoapods.py::test_resolver[swapping_changes_transitive_dependency]",
"tests/functional/cocoapods/test_resolvers_cocoapods.py::test_resolver[previous_primary_conflict]",
"tests/functional/cocoapods/test_resolvers_cocoapods.py::test_resolver[conflict]",
"tests/functional/cocoapods/test_resolvers_cocoapods.py::test_resolver[contiguous_grouping]",
"tests/functional/cocoapods/test_resolvers_cocoapods.py::test_resolver[simple_with_shared_dependencies]",
"tests/functional/cocoapods/test_resolvers_cocoapods.py::test_resolver[simple_with_base]",
"tests/functional/cocoapods/test_resolvers_cocoapods.py::test_resolver[root_conflict_on_child]",
"tests/functional/cocoapods/test_resolvers_cocoapods.py::test_resolver[simple_with_dependencies]",
"tests/functional/cocoapods/test_resolvers_cocoapods.py::test_resolver[simple]",
"tests/functional/cocoapods/test_resolvers_cocoapods.py::test_resolver[three_way_conflict]",
"tests/functional/cocoapods/test_resolvers_cocoapods.py::test_resolver[empty]"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_added_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-02-02 16:03:41+00:00
|
isc
| 5,339 |
|
sarugaku__resolvelib-49
|
diff --git a/examples/pypi_wheel_provider.py b/examples/pypi_wheel_provider.py
index 027eb03..4d3dba6 100644
--- a/examples/pypi_wheel_provider.py
+++ b/examples/pypi_wheel_provider.py
@@ -1,9 +1,10 @@
-import platform
+from email.message import EmailMessage
+from email.parser import BytesParser
from io import BytesIO
+from operator import attrgetter
+from platform import python_version
from urllib.parse import urlparse
from zipfile import ZipFile
-from email.parser import BytesParser
-from email.message import EmailMessage
import requests
import html5lib
@@ -14,7 +15,7 @@ from packaging.utils import canonicalize_name
from extras_provider import ExtrasProvider
-PYTHON_VERSION = Version(platform.python_version())
+PYTHON_VERSION = Version(python_version())
class Candidate:
@@ -123,19 +124,23 @@ class PyPIProvider(ExtrasProvider):
def get_preference(self, resolution, candidates, information):
return len(candidates)
- def find_matches(self, requirement):
- candidates = []
- name = requirement.name
- extras = requirement.extras
+ def find_matches(self, requirements):
+ assert requirements, "resolver promises at least one requirement"
+ assert not any(
+ r.extras for r in requirements[1:]
+ ), "extras not supported in this example"
+
+ name = canonicalize_name(requirements[0].name)
# Need to pass the extras to the search, so they
# are added to the candidate at creation - we
# treat candidates as immutable once created.
- for c in get_project_from_pypi(name, extras):
+ candidates = []
+ for c in get_project_from_pypi(name, set()):
version = c.version
- if version in requirement.specifier:
+ if all(version in r.specifier for r in requirements):
candidates.append(c)
- return candidates
+ return sorted(candidates, key=attrgetter("version"), reverse=True)
def is_satisfied_by(self, requirement, candidate):
if canonicalize_name(requirement.name) != candidate.name:
diff --git a/examples/reporter_demo.py b/examples/reporter_demo.py
index 8d10582..cce2e2a 100644
--- a/examples/reporter_demo.py
+++ b/examples/reporter_demo.py
@@ -50,14 +50,10 @@ class Provider(resolvelib.AbstractProvider):
def get_preference(self, resolution, candidates, information):
return len(candidates)
- def find_matches(self, requirement):
- deps = [
- (n, v)
- for (n, v) in sorted(self.candidates, reverse=True)
- if n == requirement[0] and v in requirement[1]
- ]
- deps.sort()
- return deps
+ def find_matches(self, requirements):
+ for n, v in sorted(self.candidates, reverse=True):
+ if all(n == r[0] and v in r[1] for r in requirements):
+ yield (n, v)
def is_satisfied_by(self, requirement, candidate):
assert candidate[0] == requirement[0]
diff --git a/setup.cfg b/setup.cfg
index a60e435..7a21627 100644
--- a/setup.cfg
+++ b/setup.cfg
@@ -8,20 +8,20 @@ author_email = [email protected]
long_description = file: README.rst
license = ISC License
keywords =
- dependency
- resolution
+ dependency
+ resolution
classifier =
- Development Status :: 3 - Alpha
- Intended Audience :: Developers
- License :: OSI Approved :: ISC License (ISCL)
- Operating System :: OS Independent
- Programming Language :: Python :: 2
- Programming Language :: Python :: 3
- Topic :: Software Development :: Libraries :: Python Modules
+ Development Status :: 3 - Alpha
+ Intended Audience :: Developers
+ License :: OSI Approved :: ISC License (ISCL)
+ Operating System :: OS Independent
+ Programming Language :: Python :: 2
+ Programming Language :: Python :: 3
+ Topic :: Software Development :: Libraries :: Python Modules
[options]
package_dir =
- = src
+ = src
packages = find:
include_package_data = true
zip_safe = false
@@ -31,19 +31,19 @@ where = src
[options.extras_require]
examples =
- html5lib
- packaging
- requests
+ html5lib
+ packaging
+ requests
lint =
black
flake8
test =
- commentjson
- packaging
- pytest
+ commentjson
+ packaging
+ pytest
release =
setl
- towncrier
+ towncrier
[bdist_wheel]
universal = 1
@@ -51,8 +51,8 @@ universal = 1
[flake8]
max-line-length = 80
exclude =
- .git,
- .venvs,
- __pycache__,
- build,
- dist,
+ .git,
+ .venvs,
+ __pycache__,
+ build,
+ dist,
diff --git a/src/resolvelib/compat/__init__.py b/src/resolvelib/compat/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/src/resolvelib/compat/collections_abc.py b/src/resolvelib/compat/collections_abc.py
new file mode 100644
index 0000000..366cc5e
--- /dev/null
+++ b/src/resolvelib/compat/collections_abc.py
@@ -0,0 +1,6 @@
+__all__ = ["Sequence"]
+
+try:
+ from collections.abc import Sequence
+except ImportError:
+ from collections import Sequence
diff --git a/src/resolvelib/providers.py b/src/resolvelib/providers.py
index ba86512..326b1ec 100644
--- a/src/resolvelib/providers.py
+++ b/src/resolvelib/providers.py
@@ -48,17 +48,19 @@ class AbstractProvider(object):
"""
raise NotImplementedError
- def find_matches(self, requirement):
- """Find all possible candidates that satisfy a requirement.
+ def find_matches(self, requirements):
+ """Find all possible candidates that satisfy the given requirements.
- This should try to get candidates based on the requirement's type.
+ This should try to get candidates based on the requirements' types.
For VCS, local, and archive requirements, the one-and-only match is
returned, and for a "named" requirement, the index(es) should be
consulted to find concrete candidates for this requirement.
- The returned candidates should be sorted by reversed preference, e.g.
- the most preferred should be LAST. This is done so list-popping can be
- as efficient as possible.
+ :param requirements: A collection of requirements which all of the the
+ returned candidates must match. All requirements are guaranteed to
+ have the same identifier. The collection is never empty.
+ :returns: An iterable that orders candidates by preference, e.g. the
+ most preferred candidate should come first.
"""
raise NotImplementedError
diff --git a/src/resolvelib/resolvers.py b/src/resolvelib/resolvers.py
index e45f5a1..4497f97 100644
--- a/src/resolvelib/resolvers.py
+++ b/src/resolvelib/resolvers.py
@@ -1,5 +1,6 @@
import collections
+from .compat import collections_abc
from .providers import AbstractResolver
from .structs import DirectedGraph
@@ -77,7 +78,9 @@ class Criterion(object):
def from_requirement(cls, provider, requirement, parent):
"""Build an instance from a requirement.
"""
- candidates = provider.find_matches(requirement)
+ candidates = provider.find_matches([requirement])
+ if not isinstance(candidates, collections_abc.Sequence):
+ candidates = list(candidates)
criterion = cls(
candidates=candidates,
information=[RequirementInformation(requirement, parent)],
@@ -98,11 +101,9 @@ class Criterion(object):
"""
infos = list(self.information)
infos.append(RequirementInformation(requirement, parent))
- candidates = [
- c
- for c in self.candidates
- if provider.is_satisfied_by(requirement, c)
- ]
+ candidates = provider.find_matches([r for r, _ in infos])
+ if not isinstance(candidates, collections_abc.Sequence):
+ candidates = list(candidates)
criterion = type(self)(candidates, infos, list(self.incompatibilities))
if not candidates:
raise RequirementsConflicted(criterion)
@@ -218,7 +219,7 @@ class Resolution(object):
def _attempt_to_pin_criterion(self, name, criterion):
causes = []
- for candidate in reversed(criterion.candidates):
+ for candidate in criterion.candidates:
try:
criteria = self._get_criteria_to_update(candidate)
except RequirementsConflicted as e:
|
sarugaku/resolvelib
|
63cd586d042f3f915922dc849fe77a0b4b48e733
|
diff --git a/tests/functional/cocoapods/test_resolvers_cocoapods.py b/tests/functional/cocoapods/test_resolvers_cocoapods.py
index 19d5b9f..25ac872 100644
--- a/tests/functional/cocoapods/test_resolvers_cocoapods.py
+++ b/tests/functional/cocoapods/test_resolvers_cocoapods.py
@@ -106,14 +106,14 @@ class CocoaPodsInputProvider(AbstractProvider):
def get_preference(self, resolution, candidates, information):
return len(candidates)
- def _iter_matches(self, requirement):
+ def _iter_matches(self, name, requirements):
try:
- data = self.index[requirement.name]
+ data = self.index[name]
except KeyError:
return
for entry in data:
version = packaging.version.parse(entry["version"])
- if version not in requirement.spec:
+ if any(version not in r.spec for r in requirements):
continue
# Some fixtures incorrectly set dependencies to an empty list.
dependencies = entry["dependencies"] or {}
@@ -123,13 +123,18 @@ class CocoaPodsInputProvider(AbstractProvider):
]
yield Candidate(entry["name"], version, dependencies)
- def find_matches(self, requirement):
- mapping = {c.ver: c for c in self._iter_matches(requirement)}
- try:
- version = self.pinned_versions[requirement.name]
- except KeyError:
- return sorted(mapping.values(), key=operator.attrgetter("ver"))
- return [mapping.pop(version)]
+ def find_matches(self, requirements):
+ name = requirements[0].name
+ candidates = sorted(
+ self._iter_matches(name, requirements),
+ key=operator.attrgetter("ver"),
+ reverse=True,
+ )
+ pinned = self.pinned_versions.get(name)
+ for c in candidates:
+ if pinned is not None and c.ver != pinned:
+ continue
+ yield c
def is_satisfied_by(self, requirement, candidate):
return candidate.ver in requirement.spec
diff --git a/tests/functional/python/test_resolvers_python.py b/tests/functional/python/test_resolvers_python.py
index 1acf0ac..4c702f8 100644
--- a/tests/functional/python/test_resolvers_python.py
+++ b/tests/functional/python/test_resolvers_python.py
@@ -67,26 +67,28 @@ class PythonInputProvider(AbstractProvider):
def get_preference(self, resolution, candidates, information):
return len(candidates)
- def _iter_matches(self, requirement):
- name = packaging.utils.canonicalize_name(requirement.name)
-
+ def _iter_matches(self, name, requirements):
+ extras = {e for r in requirements for e in r.extras}
for key, value in self.index[name].items():
version = packaging.version.parse(key)
- if version not in requirement.specifier:
+ if any(version not in r.specifier for r in requirements):
continue
yield Candidate(
- name=requirement.name,
- version=version,
- extras=requirement.extras,
+ name=name, version=version, extras=extras,
)
- def find_matches(self, requirement):
- mapping = {c.version: c for c in self._iter_matches(requirement)}
- try:
- version = self.pinned_versions[requirement.name]
- except KeyError:
- return sorted(mapping.values(), key=operator.attrgetter("version"))
- return [mapping.pop(version)]
+ def find_matches(self, requirements):
+ name = packaging.utils.canonicalize_name(requirements[0].name)
+ candidates = sorted(
+ (c for c in self._iter_matches(name, requirements)),
+ key=operator.attrgetter("version"),
+ reverse=True,
+ )
+ pinned = self.pinned_versions.get(name)
+ for candidate in candidates:
+ if pinned is not None and pinned != candidate.version:
+ continue
+ yield candidate
def is_satisfied_by(self, requirement, candidate):
return candidate.version in requirement.specifier
diff --git a/tests/functional/swift-package-manager/test_resolvers_swift.py b/tests/functional/swift-package-manager/test_resolvers_swift.py
index ce0a340..51b5f46 100644
--- a/tests/functional/swift-package-manager/test_resolvers_swift.py
+++ b/tests/functional/swift-package-manager/test_resolvers_swift.py
@@ -84,21 +84,27 @@ class SwiftInputProvider(AbstractProvider):
def get_preference(self, resolution, candidates, information):
return len(candidates)
- def _iter_matches(self, requirement):
- container = requirement.container
- constraint_requirement = requirement.constraint["requirement"]
+ def _iter_matches(self, requirements):
+ container = requirements[0].container
for version in container["versions"]:
- parsed_version = _parse_version(version)
- if not _is_version_allowed(parsed_version, constraint_requirement):
+ ver = _parse_version(version)
+ satisfied = all(
+ _is_version_allowed(ver, r.constraint["requirement"])
+ for r in requirements
+ )
+ if not satisfied:
continue
- preference = _calculate_preference(parsed_version)
+ preference = _calculate_preference(ver)
yield (preference, Candidate(container, version))
- def find_matches(self, requirement):
+ def find_matches(self, requirements):
matches = sorted(
- self._iter_matches(requirement), key=operator.itemgetter(0),
+ self._iter_matches(requirements),
+ key=operator.itemgetter(0),
+ reverse=True,
)
- return [candidate for _, candidate in matches]
+ for _, candidate in matches:
+ yield candidate
def is_satisfied_by(self, requirement, candidate):
return _is_version_allowed(
diff --git a/tests/test_resolvers.py b/tests/test_resolvers.py
index a6cbde8..b0c2d38 100644
--- a/tests/test_resolvers.py
+++ b/tests/test_resolvers.py
@@ -23,8 +23,8 @@ def test_candidate_inconsistent_error():
def get_dependencies(self, _):
return []
- def find_matches(self, r):
- assert r is requirement
+ def find_matches(self, rs):
+ assert len(rs) == 1 and rs[0] is requirement
return [candidate]
def is_satisfied_by(self, r, c):
|
Resolving depends on the order of the root requirements in some cases
The following test fails.
```python
def test_requirements_different_candidate_sets():
requirements = {
"r1": ["c1"],
"r2": ["c2"],
}
class Provider(AbstractProvider):
def identify(self, d):
return "r" if d.startswith("r") else d
def get_preference(self, *_):
return 0
def get_dependencies(self, _):
return []
def find_matches(self, r):
return requirements.get(r, [])
def is_satisfied_by(self, r, c):
if r == "r1":
return c in requirements[r]
elif r == "r2":
# r2 accepts anything, even stuff it doesn't
# return in find_matches
return True
return False
resolver = Resolver(Provider(), BaseReporter())
result = resolver.resolve(["r1", "r2"])
assert result.mapping["r"] == "c1"
resolver = Resolver(Provider(), BaseReporter())
result = resolver.resolve(["r2", "r1"])
assert result.mapping["r"] == "c1"
```
Note that the two tests at the end are the same request, just with the order of the requirements reversed.
The requirements have been constructed so that:
1. They are both for the same "project".
2. r1 is a normal sort of requirement.
3. r2 accepts the candidate r1 returns as well as its own one, but *doesn't* return that candidate in `find_matches`.
This specific configuration came up in https://github.com/pypa/pip/pull/8136.
I don't think the result of a `resolve()` call should be order-dependent like this, even if we argue that the provider is pathological. If we don't want to support providers like this, we need to document precisely what rules the provider has to follow - and we should validate them and produce a proper error, not just return an incorrect result.
(Personally, I'd like to get this case to work, as it's far easier to implement pip's constraints if we can).
|
0.0
|
63cd586d042f3f915922dc849fe77a0b4b48e733
|
[
"tests/functional/cocoapods/test_resolvers_cocoapods.py::test_resolver[unresolvable_child]",
"tests/functional/cocoapods/test_resolvers_cocoapods.py::test_resolver[swapping_changes_transitive_dependency]",
"tests/functional/cocoapods/test_resolvers_cocoapods.py::test_resolver[previous_primary_conflict]",
"tests/functional/cocoapods/test_resolvers_cocoapods.py::test_resolver[conflict]",
"tests/functional/cocoapods/test_resolvers_cocoapods.py::test_resolver[contiguous_grouping]",
"tests/functional/cocoapods/test_resolvers_cocoapods.py::test_resolver[simple_with_shared_dependencies]",
"tests/functional/cocoapods/test_resolvers_cocoapods.py::test_resolver[simple_with_base]",
"tests/functional/cocoapods/test_resolvers_cocoapods.py::test_resolver[swapping_children_with_successors]",
"tests/functional/cocoapods/test_resolvers_cocoapods.py::test_resolver[root_conflict_on_child]",
"tests/functional/cocoapods/test_resolvers_cocoapods.py::test_resolver[complex_conflict_unwinding]",
"tests/functional/cocoapods/test_resolvers_cocoapods.py::test_resolver[conflict_on_child]",
"tests/functional/cocoapods/test_resolvers_cocoapods.py::test_resolver[previous_conflict]",
"tests/functional/cocoapods/test_resolvers_cocoapods.py::test_resolver[simple_with_dependencies]",
"tests/functional/cocoapods/test_resolvers_cocoapods.py::test_resolver[simple]",
"tests/functional/cocoapods/test_resolvers_cocoapods.py::test_resolver[complex_conflict]",
"tests/functional/cocoapods/test_resolvers_cocoapods.py::test_resolver[three_way_conflict]",
"tests/functional/python/test_resolvers_python.py::test_resolver[with-without-extras]",
"tests/functional/python/test_resolvers_python.py::test_resolver[conflict-with-dependency]",
"tests/functional/python/test_resolvers_python.py::test_resolver[chalice]",
"tests/functional/swift-package-manager/test_resolvers_swift.py::test_resolver[ZewoHTTPServer]",
"tests/functional/swift-package-manager/test_resolvers_swift.py::test_resolver[kitura]",
"tests/functional/swift-package-manager/test_resolvers_swift.py::test_resolver[SourceKitten]",
"tests/functional/swift-package-manager/test_resolvers_swift.py::test_resolver[PerfectHTTPServer]",
"tests/test_resolvers.py::test_candidate_inconsistent_error"
] |
[
"tests/functional/cocoapods/test_resolvers_cocoapods.py::test_resolver[empty]"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-04-28 23:29:19+00:00
|
isc
| 5,340 |
|
sayanarijit__expandvars-2
|
diff --git a/.travis.yml b/.travis.yml
index 08ae868..333a0fb 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -9,8 +9,9 @@ matrix:
dist: xenial
sudo: true
install:
- - pip install -e '.[testing]'
+ - pip install --upgrade setuptools
+ - pip uninstall -y pytest
script:
- - pytest --cov=expandvars
+ - python setup.py test
after_success:
- bash <(curl -s https://codecov.io/bash)
diff --git a/dev-requirements.txt b/dev-requirements.txt
new file mode 100644
index 0000000..678e8e5
--- /dev/null
+++ b/dev-requirements.txt
@@ -0,0 +1,1 @@
+-e .[dev,testing]
\ No newline at end of file
diff --git a/expandvars.py b/expandvars.py
index c93fb3a..d1e763a 100644
--- a/expandvars.py
+++ b/expandvars.py
@@ -11,6 +11,9 @@ __license__ = "MIT"
__all__ = ["Expander", "expandvars"]
+ESCAPE_CHAR = "\\"
+
+
def _valid_char(char):
return char.isalnum() or char == "_"
@@ -45,7 +48,7 @@ class Expander(object):
return
variter = iter(vars_)
c = next(variter)
- if c == "\\":
+ if c == ESCAPE_CHAR:
self.escape(variter)
return
if c == "$":
@@ -66,10 +69,12 @@ class Expander(object):
try:
c = next(variter)
except StopIteration:
- raise ValueError("escape chracter is not escaping anything")
+ raise ValueError("escape character is not escaping anything")
if c == "$":
self._result.append(c)
c = self._next_or_done(variter)
+ else:
+ self._result.append(ESCAPE_CHAR)
self.expand_val(variter, c)
def process_buffr(self):
@@ -150,7 +155,7 @@ class Expander(object):
if not c:
self._result.append("$")
return
- if c == "\\":
+ if c == ESCAPE_CHAR:
self.expand_val(variter, "$\\")
return
@@ -161,7 +166,7 @@ class Expander(object):
while _valid_char(c):
self._buffr.append(c)
c = self._next_or_done(variter)
- if c == "\\":
+ if c == ESCAPE_CHAR:
self.escape(variter)
return
if not c:
@@ -198,7 +203,7 @@ class Expander(object):
while c and c != "$":
self._result.append(c)
c = self._next_or_done(variter)
- if c == "\\":
+ if c == ESCAPE_CHAR:
self.escape(variter)
return
if c:
diff --git a/requirements.txt b/requirements.txt
new file mode 100644
index 0000000..ecf975e
--- /dev/null
+++ b/requirements.txt
@@ -0,0 +1,1 @@
+-e .
\ No newline at end of file
diff --git a/setup.cfg b/setup.cfg
new file mode 100644
index 0000000..a1a2277
--- /dev/null
+++ b/setup.cfg
@@ -0,0 +1,5 @@
+[aliases]
+test=pytest
+
+[tools.pytest]
+addopts=-s --ignore=setup.py --cov=expandvars
\ No newline at end of file
diff --git a/setup.py b/setup.py
index 99b7ab9..6d5f61f 100644
--- a/setup.py
+++ b/setup.py
@@ -1,3 +1,4 @@
+import sys
from codecs import open
from os import path
@@ -12,6 +13,16 @@ here = path.abspath(path.dirname(__file__))
with open(path.join(here, "README.md"), encoding="utf-8") as f:
long_description = f.read()
+setup_requires = [
+ 'pytest-runner'
+]
+
+tests_require = ['pytest', 'pytest-cov']
+
+dev_requires = ['tox']
+
+install_requires = []
+
setup(
name="expandvars",
version=__version__,
@@ -49,6 +60,8 @@ setup(
platforms=["Any"],
keywords="expand system variables",
packages=find_packages(exclude=["contrib", "docs", "tests", "examples"]),
- install_requires=[],
- extras_require={"testing": ["pytest>=4.4.1", 'pytest-cov>=2.7.1']},
+ install_requires=install_requires,
+ setup_requires=setup_requires,
+ tests_require=tests_require,
+ extras_require={"testing": tests_require, "dev": dev_requires},
)
diff --git a/tox.ini b/tox.ini
new file mode 100644
index 0000000..1e40975
--- /dev/null
+++ b/tox.ini
@@ -0,0 +1,6 @@
+[tox]
+envlist = py27,py33,py34,py35,py36,py37
+
+[testenv]
+commands =
+ {envpython} setup.py test
\ No newline at end of file
|
sayanarijit/expandvars
|
0aa46b8bdc7d89f907783c2c42bb473db6685314
|
diff --git a/tests/test_expandvars.py b/tests/test_expandvars.py
index c871055..93729f4 100644
--- a/tests/test_expandvars.py
+++ b/tests/test_expandvars.py
@@ -85,12 +85,16 @@ def test_offset_length():
def test_escape():
- os.environ.update({"FOO": "foo"})
- assert expandvars("$FOO\\" + "$bar") == "foo$bar"
- assert expandvars("$FOO\\" + "\\" + "\\" + "$bar") == "foo" + "\\" + "$bar"
- assert expandvars("$FOO\\" + "$") == "foo$"
- assert expandvars("$\\" + "FOO") == "$\\" + "FOO"
+ os.environ.update({"FOO": "foo", "BAR": "bar"})
+ assert expandvars("$FOO" + "$BAR") == "foobar"
+ assert expandvars("\\" + "$FOO" + "\\" + "$BAR") == "$FOO$BAR"
+ assert expandvars("$FOO" + "\\" + "$BAR") == "foo$BAR"
+ assert expandvars("\\" + "$FOO" + "$BAR") == "$FOObar"
+ assert expandvars("$FOO" + "\\" + "\\" + "\\" + "$BAR") == "foo" + "\\" + "\\" + "$BAR"
+ assert expandvars("$FOO" + "\\" + "$") == "foo$"
+ assert expandvars("$" + "\\" + "FOO") == "$" + "\\" + "FOO"
assert expandvars("\\" + "$FOO") == "$FOO"
+ assert expandvars("D:\\some\\windows\\path") == "D:\\some\\windows\\path"
def test_corner_cases():
@@ -103,7 +107,7 @@ def test_escape_not_followed_err():
os.environ.update({"FOO": "foo"})
with pytest.raises(ValueError) as e:
expandvars("$FOO\\")
- assert str(e.value) == "escape chracter is not escaping anything"
+ assert str(e.value) == "escape character is not escaping anything"
def test_invalid_length_err():
|
String "\" is replaced by ""
```
>>> import expandvars
>>> expandvars.expandvars('D:\\test')
'D:test'
```
|
0.0
|
0aa46b8bdc7d89f907783c2c42bb473db6685314
|
[
"tests/test_expandvars.py::test_escape",
"tests/test_expandvars.py::test_escape_not_followed_err"
] |
[
"tests/test_expandvars.py::test_expandvars_constant",
"tests/test_expandvars.py::test_expandvars_empty",
"tests/test_expandvars.py::test_expandvars_simple",
"tests/test_expandvars.py::test_expandvars_combo",
"tests/test_expandvars.py::test_expandvars_get_default",
"tests/test_expandvars.py::test_expandvars_update_default",
"tests/test_expandvars.py::test_expandvars_substitute",
"tests/test_expandvars.py::test_offset",
"tests/test_expandvars.py::test_offset_length",
"tests/test_expandvars.py::test_corner_cases",
"tests/test_expandvars.py::test_invalid_length_err",
"tests/test_expandvars.py::test_bad_syntax_err",
"tests/test_expandvars.py::test_brace_never_closed_err",
"tests/test_expandvars.py::test_invalid_operand_err"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-05-27 21:23:28+00:00
|
mit
| 5,341 |
|
sayanarijit__expandvars-29
|
diff --git a/README.md b/README.md
index cf76261..f7d6317 100644
--- a/README.md
+++ b/README.md
@@ -19,6 +19,7 @@ my_secret_access_code = "${ACCESS_CODE:-default_access_code}"
my_important_variable = "${IMPORTANT_VARIABLE:?}"
my_updated_path = "$PATH:$HOME/.bin"
my_process_id = "$$"
+my_nested_variable = "${!NESTED}
```
> NOTE: Although this module copies most of the common behaviours of bash,
diff --git a/expandvars.py b/expandvars.py
index adae76c..e8b3ee8 100644
--- a/expandvars.py
+++ b/expandvars.py
@@ -96,16 +96,26 @@ def _isint(val):
return False
-def getenv(var, nounset):
+def getenv(var, nounset, indirect, default=None):
"""Get value from environment variable.
When nounset is True, it behaves like bash's "set -o nounset" or "set -u"
and raises UnboundVariable exception.
+
+ When indirect is True, it will use the value of the resolved variable as
+ the name of the final variable.
"""
val = environ.get(var)
+ if val is not None and indirect:
+ val = environ.get(val)
+
if val is not None:
return val
+
+ if default is not None:
+ return default
+
if nounset:
if RECOVER_NULL is not None:
return RECOVER_NULL
@@ -154,47 +164,59 @@ def expand_var(vars_, nounset):
buff.append(c)
else:
n = len(buff)
- return getenv("".join(buff), nounset=nounset) + expandvars(
+ return getenv("".join(buff), nounset=nounset, indirect=False) + expandvars(
vars_[n:], nounset=nounset
)
- return getenv("".join(buff), nounset=nounset)
+ return getenv("".join(buff), nounset=nounset, indirect=False)
def expand_modifier_var(vars_, nounset):
"""Expand variables with modifier."""
- if len(vars_) == 1:
+ if len(vars_) <= 1:
raise BadSubstitution(vars_)
+ if vars_[0] == "!":
+ indirect = True
+ vars_ = vars_[1:]
+ else:
+ indirect = False
+
buff = []
for c in vars_:
if _valid_char(c):
buff.append(c)
elif c == "}":
n = len(buff) + 1
- return getenv("".join(buff), nounset=nounset) + expandvars(
- vars_[n:], nounset=nounset
- )
- elif c == ":":
- n = len(buff) + 1
- return expand_advanced("".join(buff), vars_[n:], nounset=nounset)
+ return getenv(
+ "".join(buff), nounset=nounset, indirect=indirect
+ ) + expandvars(vars_[n:], nounset=nounset)
else:
n = len(buff)
- return expand_advanced("".join(buff), vars_[n:], nounset=nounset)
+ if c == ":":
+ n += 1
+ return expand_advanced(
+ "".join(buff), vars_[n:], nounset=nounset, indirect=indirect
+ )
+
raise MissingClosingBrace("".join(buff))
-def expand_advanced(var, vars_, nounset):
+def expand_advanced(var, vars_, nounset, indirect):
"""Expand substitution."""
if len(vars_) == 0:
raise MissingClosingBrace(var)
if vars_[0] == "-":
- return expand_default(var, vars_[1:], set_=False, nounset=nounset)
+ return expand_default(
+ var, vars_[1:], set_=False, nounset=nounset, indirect=indirect
+ )
if vars_[0] == "=":
- return expand_default(var, vars_[1:], set_=True, nounset=nounset)
+ return expand_default(
+ var, vars_[1:], set_=True, nounset=nounset, indirect=indirect
+ )
if vars_[0] == "+":
return expand_substitute(var, vars_[1:], nounset=nounset)
@@ -249,7 +271,7 @@ def expand_offset(var, vars_, nounset):
raise OperandExpected(var, offset_str)
else:
offset = int(offset_str)
- return getenv(var, nounset=nounset)[offset:] + expandvars(
+ return getenv(var, nounset=nounset, indirect=False)[offset:] + expandvars(
vars_[n:], nounset=nounset
)
buff.append(c)
@@ -280,9 +302,9 @@ def expand_length(var, vars_, offset, nounset):
else:
width = offset + length
- return getenv(var, nounset=nounset)[offset:width] + expandvars(
- vars_[n:], nounset=nounset
- )
+ return getenv(var, nounset=nounset, indirect=False)[
+ offset:width
+ ] + expandvars(vars_[n:], nounset=nounset)
buff.append(c)
raise MissingClosingBrace("".join(buff))
@@ -302,7 +324,7 @@ def expand_substitute(var, vars_, nounset):
raise MissingClosingBrace("".join(sub))
-def expand_default(var, vars_, set_, nounset):
+def expand_default(var, vars_, set_, nounset, indirect):
"""Expand var or return default."""
default = []
@@ -312,7 +334,10 @@ def expand_default(var, vars_, set_, nounset):
default_ = "".join(default)
if set_ and var not in environ:
environ.update({var: default_})
- return environ.get(var, default_) + expandvars(vars_[n:], nounset=nounset)
+ return getenv(
+ var, nounset=nounset, indirect=indirect, default=default_
+ ) + expandvars(vars_[n:], nounset=nounset)
+
default.append(c)
raise MissingClosingBrace("".join(default))
|
sayanarijit/expandvars
|
80ab319905dfe861907b3c4de69c7de8d66a2b2c
|
diff --git a/tests/test_expandvars.py b/tests/test_expandvars.py
index 1df755c..eaf9b1d 100644
--- a/tests/test_expandvars.py
+++ b/tests/test_expandvars.py
@@ -61,6 +61,7 @@ def test_expandvars_pid():
assert expandvars.expandvars("$$") == str(getpid())
assert expandvars.expandvars("PID( $$ )") == "PID( {0} )".format(getpid())
+
@patch.dict(env, {})
def test_expandvars_get_default():
importlib.reload(expandvars)
@@ -128,6 +129,16 @@ def test_offset_length():
assert expandvars.expandvars("${FOO:-3:1}:bar") == "damnbigfoobar:bar"
[email protected](env, {"FOO": "X", "X": "foo"})
+def test_expandvars_indirection():
+ importlib.reload(expandvars)
+
+ assert expandvars.expandvars("${!FOO}:${FOO}") == "foo:X"
+ assert expandvars.expandvars("${!FOO-default}") == "foo"
+ assert expandvars.expandvars("${!BAR-default}") == "default"
+ assert expandvars.expandvars("${!X-default}") == "default"
+
+
@patch.dict(env, {"FOO": "foo", "BAR": "bar"})
def test_escape():
importlib.reload(expandvars)
@@ -201,7 +212,7 @@ def test_invalid_length_err():
importlib.reload(expandvars)
with pytest.raises(
- expandvars.ExpandvarsException, match="FOO: -3: substring expression < 0",
+ expandvars.ExpandvarsException, match="FOO: -3: substring expression < 0"
) as e:
expandvars.expandvars("${FOO:1:-3}")
assert isinstance(e.value, expandvars.NegativeSubStringExpression)
|
Add support for `$$` (pid) and `${!VAR}` syntax.
`$$` expands to `os.getpid()` and `${!VAR}` helps with nesting variables.
|
0.0
|
80ab319905dfe861907b3c4de69c7de8d66a2b2c
|
[
"tests/test_expandvars.py::test_expandvars_indirection"
] |
[
"tests/test_expandvars.py::test_expandvars_constant",
"tests/test_expandvars.py::test_expandvars_empty",
"tests/test_expandvars.py::test_expandvars_simple",
"tests/test_expandvars.py::test_expandvars_from_file",
"tests/test_expandvars.py::test_expandvars_combo",
"tests/test_expandvars.py::test_expandvars_pid",
"tests/test_expandvars.py::test_expandvars_get_default",
"tests/test_expandvars.py::test_expandvars_update_default",
"tests/test_expandvars.py::test_expandvars_substitute",
"tests/test_expandvars.py::test_offset",
"tests/test_expandvars.py::test_offset_length",
"tests/test_expandvars.py::test_escape",
"tests/test_expandvars.py::test_corner_cases",
"tests/test_expandvars.py::test_strict_parsing",
"tests/test_expandvars.py::test_missing_escapped_character",
"tests/test_expandvars.py::test_invalid_length_err",
"tests/test_expandvars.py::test_bad_substitution_err",
"tests/test_expandvars.py::test_brace_never_closed_err",
"tests/test_expandvars.py::test_invalid_operand_err"
] |
{
"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
}
|
2020-09-05 08:41:31+00:00
|
mit
| 5,342 |
|
sayanarijit__expandvars-41
|
diff --git a/expandvars.py b/expandvars.py
index 0f3254a..ae1f4aa 100644
--- a/expandvars.py
+++ b/expandvars.py
@@ -392,7 +392,7 @@ def expand_default(var, vars_, set_, nounset, indirect, environ, var_symbol):
for c in vars_:
if c == "}":
n = len(default) + 1
- default_ = "".join(default)
+ default_ = expand("".join(default))
if set_ and var not in environ:
environ.update({var: default_})
return getenv(
|
sayanarijit/expandvars
|
128143fb31af000679e71d7cee876b71879fe664
|
diff --git a/tests/test_expandvars.py b/tests/test_expandvars.py
index 49f5e21..b95d639 100644
--- a/tests/test_expandvars.py
+++ b/tests/test_expandvars.py
@@ -62,7 +62,7 @@ def test_expandvars_pid():
assert expandvars.expandvars("PID( $$ )") == "PID( {0} )".format(getpid())
[email protected](env, {})
[email protected](env, {"ALTERNATE": "Alternate"})
def test_expandvars_get_default():
importlib.reload(expandvars)
@@ -70,6 +70,7 @@ def test_expandvars_get_default():
assert expandvars.expandvars("${FOO:-default}") == "default"
assert expandvars.expandvars("${FOO:-}") == ""
assert expandvars.expandvars("${FOO:-foo}:${FOO-bar}") == "foo:bar"
+ assert expandvars.expandvars("${FOO:-$ALTERNATE}") == "Alternate"
@patch.dict(env, {})
|
Right Hand Side Variable Not Expanded with the '-' Operator
Take the example that I got from some random website
```
VAR1=1
VAR2=2
# var3 is unset.
echo ${VAR1-$VAR2} # 1
echo ${VAR3-$VAR2} # 2
```
This seems to be normal bash behaviour, but in the above example expandvars will output `1` and `$VAR2` respectively. Here is the Python code
```python
import os
from expandvars import expandvars
os.environ['VAR1'] = '1'
os.environ['VAR2'] = '2'
v = '${VAR1-$VAR2}'
print(f'{v} expands to "{expandvars(v)}"') # ${VAR1-$VAR2} expands to "1"
v = '${VAR3-$VAR2}'
print(f'{v} expands to "{expandvars(v)}"') # ${VAR3-$VAR2} expands to "$VAR2"
```
|
0.0
|
128143fb31af000679e71d7cee876b71879fe664
|
[
"tests/test_expandvars.py::test_expandvars_get_default"
] |
[
"tests/test_expandvars.py::test_expandvars_constant",
"tests/test_expandvars.py::test_expandvars_empty",
"tests/test_expandvars.py::test_expandvars_simple",
"tests/test_expandvars.py::test_expandvars_from_file",
"tests/test_expandvars.py::test_expandvars_combo",
"tests/test_expandvars.py::test_expandvars_pid",
"tests/test_expandvars.py::test_expandvars_update_default",
"tests/test_expandvars.py::test_expandvars_substitute",
"tests/test_expandvars.py::test_offset",
"tests/test_expandvars.py::test_offset_length",
"tests/test_expandvars.py::test_expandvars_indirection",
"tests/test_expandvars.py::test_escape",
"tests/test_expandvars.py::test_corner_cases",
"tests/test_expandvars.py::test_strict_parsing",
"tests/test_expandvars.py::test_missing_escapped_character",
"tests/test_expandvars.py::test_invalid_length_err",
"tests/test_expandvars.py::test_bad_substitution_err",
"tests/test_expandvars.py::test_brace_never_closed_err",
"tests/test_expandvars.py::test_invalid_operand_err",
"tests/test_expandvars.py::test_expand_var_symbol[%]",
"tests/test_expandvars.py::test_expand_var_symbol[&]",
"tests/test_expandvars.py::test_expand_var_symbol[\\xa3]",
"tests/test_expandvars.py::test_expand_var_symbol[=]"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2021-04-08 17:36:25+00:00
|
mit
| 5,343 |
|
scalableminds__cluster_tools-93
|
diff --git a/cluster_tools/schedulers/cluster_executor.py b/cluster_tools/schedulers/cluster_executor.py
index 68d4cd1..304588a 100644
--- a/cluster_tools/schedulers/cluster_executor.py
+++ b/cluster_tools/schedulers/cluster_executor.py
@@ -10,9 +10,7 @@ import time
from abc import abstractmethod
import logging
from typing import Union
-from ..util import local_filename
from cluster_tools.tailf import Tail
-from logging import getLogger
class RemoteException(Exception):
def __init__(self, error, job_id):
@@ -249,6 +247,9 @@ class ClusterExecutor(futures.Executor):
def map_to_futures(self, fun, allArgs, output_pickle_path_getter=None):
self.ensure_not_shutdown()
allArgs = list(allArgs)
+ if len(allArgs) == 0:
+ return []
+
should_keep_output = output_pickle_path_getter is not None
futs_with_output_paths = []
|
scalableminds/cluster_tools
|
fc6855fc512f922f771532affde79e5a4b4f9807
|
diff --git a/test.py b/test.py
index 0eb4662..05c00d3 100644
--- a/test.py
+++ b/test.py
@@ -1,8 +1,6 @@
import cluster_tools
-import subprocess
import concurrent.futures
import time
-import sys
import logging
from enum import Enum
from functools import partial
@@ -163,6 +161,12 @@ def test_map_to_futures():
for duration, result in zip(durations, results):
assert result == duration
+def test_empty_map_to_futures():
+ for exc in get_executors():
+ with exc:
+ futures = exc.map_to_futures(sleep, [])
+ results = [f.result() for f in futures]
+ assert len(results) == 0
def output_pickle_path_getter(tmp_dir, chunk):
@@ -170,8 +174,6 @@ def output_pickle_path_getter(tmp_dir, chunk):
def test_map_to_futures_with_pickle_paths():
- dir_path = Path("").resolve()
-
for exc in get_executors():
with tempfile.TemporaryDirectory(dir=".") as tmp_dir:
with exc:
|
map_to_futures with empty list crashes, should return empty list
The resumable executor of voxelytics checks what needs to be re-run. If that list becomes empty, map_to_futures crashes
|
0.0
|
fc6855fc512f922f771532affde79e5a4b4f9807
|
[
"test.py::test_empty_map_to_futures"
] |
[
"test.py::test_executor_args",
"test.py::test_cloudpickle_serialization"
] |
{
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-04-29 07:47:24+00:00
|
mit
| 5,344 |
|
scanapi__scanapi-173
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ceb2670..1414143 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,6 +12,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Changed
- Unified keys validation in a single method [#151](https://github.com/scanapi/scanapi/pull/151)
+- Change default template to html [#173](https://github.com/scanapi/scanapi/pull/173)
## [0.1.0] - 2020-05-14
### Added
diff --git a/scanapi/settings.py b/scanapi/settings.py
index 115ac2b..c5d77ab 100644
--- a/scanapi/settings.py
+++ b/scanapi/settings.py
@@ -8,7 +8,7 @@ DEFAULT_CONFIG_PATH = ".scanapi.yaml"
class Settings(dict):
def __init__(self):
self["spec_path"] = "api.yaml"
- self["reporter"] = "markdown"
+ self["reporter"] = "html"
self["output_path"] = None
self["template"] = None
|
scanapi/scanapi
|
d50fdd1cd04612907c77f8e1b27935da70ef58ad
|
diff --git a/tests/unit/test_settings.py b/tests/unit/test_settings.py
index a8f2554..d52a58e 100644
--- a/tests/unit/test_settings.py
+++ b/tests/unit/test_settings.py
@@ -8,7 +8,7 @@ class TestSettings:
class TestInit:
def test_should_init_with_default_values(self):
assert settings["spec_path"] == "api.yaml"
- assert settings["reporter"] == "markdown"
+ assert settings["reporter"] == "html"
assert settings["output_path"] is None
assert settings["template"] is None
@@ -53,7 +53,7 @@ class TestSettings:
assert settings == {
"spec_path": "path/spec-path",
- "reporter": "markdown",
+ "reporter": "html",
"output_path": "path/output-path",
"template": None,
"config_path": "path/config-path",
|
Change HTML report to default
Change HTML report to default. Current it is markdown, but HTML is way more popular and our html report is [beautiful](https://github.com/scanapi/scanapi/pull/157) now
Here is where we need to change it: https://github.com/scanapi/scanapi/blob/master/scanapi/settings.py#L11
|
0.0
|
d50fdd1cd04612907c77f8e1b27935da70ef58ad
|
[
"tests/unit/test_settings.py::TestSettings::TestInit::test_should_init_with_default_values",
"tests/unit/test_settings.py::TestSettings::TestSaveClickPreferences::test_should_clean_and_save_preferences"
] |
[
"tests/unit/test_settings.py::TestSettings::TestSavePreferences::TestWhenConfigPathIsInClickPreferences::test_should_pass_config_path",
"tests/unit/test_settings.py::TestSettings::TestSavePreferences::TestWhenConfigPathIsNotInClickPreferences::test_should_pass_config_path_as_none",
"tests/unit/test_settings.py::TestSettings::TestSaveConfigFilePreferences::TestWithoutCustomConfigPath::TestWithDefaultConfigFile::test_should_save_preferences",
"tests/unit/test_settings.py::TestSettings::TestSaveConfigFilePreferences::TestWithoutCustomConfigPath::TestWithoutDefaultConfigFile::test_should_not_change_preferences",
"tests/unit/test_settings.py::TestSettings::TestSaveConfigFilePreferences::TestWithCustomConfigPath::TestWithConfigFile::test_should_save_preferences",
"tests/unit/test_settings.py::TestSettings::TestSaveConfigFilePreferences::TestWithCustomConfigPath::TestWithoutConfigFile::test_should_raise_exception"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-06-08 22:33:49+00:00
|
mit
| 5,345 |
|
scanapi__scanapi-183
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a7f7c20..2cf3de0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -19,6 +19,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Entry point to `scanapi:main` [#172](https://github.com/scanapi/scanapi/pull/172)
- `--spec-path` option to argument [#172](https://github.com/scanapi/scanapi/pull/172)
+### Fixed
+- Duplicated status code row from report [#183](https://github.com/scanapi/scanapi/pull/183)
+- Sensitive information render on report [#183](https://github.com/scanapi/scanapi/pull/183)
+
### Removed
- Console Report [#175](https://github.com/scanapi/scanapi/pull/175)
- Markdown Report [#179](https://github.com/scanapi/scanapi/pull/179)
diff --git a/scanapi/templates/html.jinja b/scanapi/templates/html.jinja
index 4ba5dc6..ce6ace4 100644
--- a/scanapi/templates/html.jinja
+++ b/scanapi/templates/html.jinja
@@ -311,17 +311,6 @@
<section class="endpoint__response">
<h3>Response</h3>
<table>
- <thead>
- <tr>
- <td>
- status code
- </td>
- <td>
- {{ response.status_code }}
- </td>
- </tr>
- </thead>
-
<tbody>
<tr>
<td>
diff --git a/scanapi/utils.py b/scanapi/utils.py
index de284e2..67b5e95 100644
--- a/scanapi/utils.py
+++ b/scanapi/utils.py
@@ -56,4 +56,4 @@ def _override_info(http_msg, http_attr, secret_field):
secret_field in getattr(http_msg, http_attr)
and http_attr in ALLOWED_ATTRS_TO_HIDE
):
- getattr(http_msg, http_attr)[secret_field] = "<sensitive_information>"
+ getattr(http_msg, http_attr)[secret_field] = "SENSITIVE_INFORMATION"
|
scanapi/scanapi
|
a5f9efc307b941f67c4132d86235f5637ec994e1
|
diff --git a/tests/unit/test_utils.py b/tests/unit/test_utils.py
index 103328b..c7c7e05 100644
--- a/tests/unit/test_utils.py
+++ b/tests/unit/test_utils.py
@@ -163,7 +163,7 @@ class TestOverrideInfo:
_override_info(response, http_attr, secret_field)
- assert response.headers["abc"] == "<sensitive_information>"
+ assert response.headers["abc"] == "SENSITIVE_INFORMATION"
def test_when_http_attr_is_not_allowed(self, response, mocker):
mocker.patch("scanapi.utils.ALLOWED_ATTRS_TO_HIDE", ["body"])
|
Duplicated row `status code` on Report
Duplicated row `status code` on Report

|
0.0
|
a5f9efc307b941f67c4132d86235f5637ec994e1
|
[
"tests/unit/test_utils.py::TestOverrideInfo::test_overrides"
] |
[
"tests/unit/test_utils.py::TestJoinUrls::test_build_url_properly[http://demo.scanapi.dev/api/-health-http://demo.scanapi.dev/api/health]",
"tests/unit/test_utils.py::TestJoinUrls::test_build_url_properly[http://demo.scanapi.dev/api/-/health-http://demo.scanapi.dev/api/health]",
"tests/unit/test_utils.py::TestJoinUrls::test_build_url_properly[http://demo.scanapi.dev/api/-/health/-http://demo.scanapi.dev/api/health/]",
"tests/unit/test_utils.py::TestJoinUrls::test_build_url_properly[http://demo.scanapi.dev/api-health-http://demo.scanapi.dev/api/health]",
"tests/unit/test_utils.py::TestJoinUrls::test_build_url_properly[http://demo.scanapi.dev/api-/health-http://demo.scanapi.dev/api/health]",
"tests/unit/test_utils.py::TestJoinUrls::test_build_url_properly[http://demo.scanapi.dev/api-/health/-http://demo.scanapi.dev/api/health/]",
"tests/unit/test_utils.py::TestJoinUrls::test_build_url_properly[-http://demo.scanapi.dev/api/health/-http://demo.scanapi.dev/api/health/]",
"tests/unit/test_utils.py::TestJoinUrls::test_build_url_properly[http://demo.scanapi.dev/api/health/--http://demo.scanapi.dev/api/health/]",
"tests/unit/test_utils.py::TestJoinUrls::test_build_url_properly[--]",
"tests/unit/test_utils.py::TestValidateKeys::TestThereIsAnInvalidKey::test_should_raise_an_exception",
"tests/unit/test_utils.py::TestValidateKeys::TestMissingMandatoryKey::test_should_raise_an_exception",
"tests/unit/test_utils.py::TestValidateKeys::TestThereIsNotAnInvalidKeysOrMissingMandotoryKeys::test_should_not_raise_an_exception",
"tests/unit/test_utils.py::TestHideSensitiveInfo::test_calls__hide[settings0-request_settings0-response_settings0]",
"tests/unit/test_utils.py::TestHideSensitiveInfo::test_calls__hide[settings1-request_settings1-response_settings1]",
"tests/unit/test_utils.py::TestHideSensitiveInfo::test_calls__hide[settings2-request_settings2-response_settings2]",
"tests/unit/test_utils.py::TestHideSensitiveInfo::test_calls__hide[settings3-request_settings3-response_settings3]",
"tests/unit/test_utils.py::TestHide::test_calls__override_info[settings0-calls0]",
"tests/unit/test_utils.py::TestHide::test_calls__override_info[settings1-calls1]",
"tests/unit/test_utils.py::TestHide::test_calls__override_info[settings2-calls2]",
"tests/unit/test_utils.py::TestOverrideInfo::test_when_http_attr_is_not_allowed",
"tests/unit/test_utils.py::TestOverrideInfo::test_when_http_attr_does_not_have_the_field"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks",
"has_media",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-06-17 16:53:48+00:00
|
mit
| 5,346 |
|
scanapi__scanapi-185
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 567c5f7..446716b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,6 +12,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- `-h` alias for `--help` option [#172](https://github.com/scanapi/scanapi/pull/172)
- Test results to report [#177](https://github.com/scanapi/scanapi/pull/177)
- Add test errors to the report [#187](https://github.com/scanapi/scanapi/pull/187)
+- Hides sensitive info in URL [#185](https://github.com/scanapi/scanapi/pull/185)
### Changed
- Unified keys validation in a single method [#151](https://github.com/scanapi/scanapi/pull/151)
diff --git a/scanapi/hide_utils.py b/scanapi/hide_utils.py
new file mode 100644
index 0000000..25a1572
--- /dev/null
+++ b/scanapi/hide_utils.py
@@ -0,0 +1,41 @@
+from scanapi.settings import settings
+
+HEADERS = "headers"
+BODY = "body"
+URL = "url"
+
+ALLOWED_ATTRS_TO_HIDE = (HEADERS, BODY, URL)
+SENSITIVE_INFO_SUBSTITUTION_FLAG = "SENSITIVE_INFORMATION"
+
+
+def hide_sensitive_info(response):
+ report_settings = settings.get("report", {})
+ request = response.request
+ request_settings = report_settings.get("hide-request", {})
+ response_settings = report_settings.get("hide-response", {})
+
+ _hide(request, request_settings)
+ _hide(response, response_settings)
+
+
+def _hide(http_msg, hide_settings):
+ for http_attr in hide_settings:
+ secret_fields = hide_settings[http_attr]
+ for field in secret_fields:
+ _override_info(http_msg, http_attr, field)
+
+
+def _override_info(http_msg, http_attr, secret_field):
+ if (
+ secret_field in getattr(http_msg, http_attr)
+ and http_attr in ALLOWED_ATTRS_TO_HIDE
+ ):
+ if http_attr == URL:
+ new_url = getattr(http_msg, http_attr).replace(
+ secret_field, SENSITIVE_INFO_SUBSTITUTION_FLAG
+ )
+ setattr(http_msg, http_attr, new_url)
+ else:
+ getattr(http_msg, http_attr)[
+ secret_field
+ ] = SENSITIVE_INFO_SUBSTITUTION_FLAG
diff --git a/scanapi/tree/request_node.py b/scanapi/tree/request_node.py
index 7ae0ab8..6e04786 100644
--- a/scanapi/tree/request_node.py
+++ b/scanapi/tree/request_node.py
@@ -15,7 +15,8 @@ from scanapi.tree.tree_keys import (
TESTS_KEY,
VARS_KEY,
)
-from scanapi.utils import join_urls, hide_sensitive_info, validate_keys
+from scanapi.utils import join_urls, validate_keys
+from scanapi.hide_utils import hide_sensitive_info
logger = logging.getLogger(__name__)
diff --git a/scanapi/utils.py b/scanapi/utils.py
index 67b5e95..ad53343 100644
--- a/scanapi/utils.py
+++ b/scanapi/utils.py
@@ -1,7 +1,4 @@
from scanapi.errors import InvalidKeyError, MissingMandatoryKeyError
-from scanapi.settings import settings
-
-ALLOWED_ATTRS_TO_HIDE = ("headers body").split()
def join_urls(first_url, second_url):
@@ -22,16 +19,6 @@ def validate_keys(keys, available_keys, required_keys, scope):
_validate_required_keys(keys, required_keys, scope)
-def hide_sensitive_info(response):
- report_settings = settings.get("report", {})
- request = response.request
- request_settings = report_settings.get("hide-request", {})
- response_settings = report_settings.get("hide-response", {})
-
- _hide(request, request_settings)
- _hide(response, response_settings)
-
-
def _validate_allowed_keys(keys, available_keys, scope):
for key in keys:
if not key in available_keys:
@@ -42,18 +29,3 @@ def _validate_required_keys(keys, required_keys, scope):
if not set(required_keys) <= set(keys):
missing_keys = set(required_keys) - set(keys)
raise MissingMandatoryKeyError(missing_keys, scope)
-
-
-def _hide(http_msg, hide_settings):
- for http_attr in hide_settings:
- secret_fields = hide_settings[http_attr]
- for field in secret_fields:
- _override_info(http_msg, http_attr, field)
-
-
-def _override_info(http_msg, http_attr, secret_field):
- if (
- secret_field in getattr(http_msg, http_attr)
- and http_attr in ALLOWED_ATTRS_TO_HIDE
- ):
- getattr(http_msg, http_attr)[secret_field] = "SENSITIVE_INFORMATION"
|
scanapi/scanapi
|
b38ebbb5773cff60faa6901fe4052bbdcdf6021e
|
diff --git a/tests/unit/test_hide_utils.py b/tests/unit/test_hide_utils.py
new file mode 100644
index 0000000..44720ab
--- /dev/null
+++ b/tests/unit/test_hide_utils.py
@@ -0,0 +1,109 @@
+import pytest
+import requests
+
+from scanapi.hide_utils import hide_sensitive_info, _hide, _override_info
+
+
[email protected]
+def response(requests_mock):
+ requests_mock.get("http://test.com", text="data")
+ return requests.get("http://test.com")
+
+
+class TestHideSensitiveInfo:
+ @pytest.fixture
+ def mock__hide(self, mocker):
+ return mocker.patch("scanapi.hide_utils._hide")
+
+ test_data = [
+ ({}, {}, {}),
+ ({"report": {"abc": "def"}}, {}, {}),
+ ({"report": {"hide-request": {"url": ["abc"]}}}, {"url": ["abc"]}, {}),
+ ({"report": {"hide-request": {"headers": ["abc"]}}}, {"headers": ["abc"]}, {}),
+ ({"report": {"hide-response": {"headers": ["abc"]}}}, {}, {"headers": ["abc"]}),
+ ]
+
+ @pytest.mark.parametrize("settings, request_settings, response_settings", test_data)
+ def test_calls__hide(
+ self,
+ settings,
+ request_settings,
+ response_settings,
+ mocker,
+ response,
+ mock__hide,
+ ):
+ mocker.patch("scanapi.hide_utils.settings", settings)
+ hide_sensitive_info(response)
+
+ calls = [
+ mocker.call(response.request, request_settings),
+ mocker.call(response, response_settings),
+ ]
+
+ mock__hide.assert_has_calls(calls)
+
+
+class TestHide:
+ @pytest.fixture
+ def mock__override_info(self, mocker):
+ return mocker.patch("scanapi.hide_utils._override_info")
+
+ test_data = [
+ ({}, []),
+ ({"headers": ["abc", "def"]}, [("headers", "abc"), ("headers", "def")]),
+ ({"headers": ["abc"]}, [("headers", "abc")]),
+ ({"url": ["abc"]}, []),
+ ]
+
+ @pytest.mark.parametrize("settings, calls", test_data)
+ def test_calls__override_info(
+ self, settings, calls, mocker, response, mock__override_info
+ ):
+ _hide(response, settings)
+ calls = [mocker.call(response, call[0], call[1]) for call in calls]
+
+ mock__override_info.assert_has_calls(calls)
+
+
+class TestOverrideInfo:
+ def test_overrides(self, response):
+ response.headers = {"abc": "123"}
+ http_attr = "headers"
+ secret_field = "abc"
+
+ _override_info(response, http_attr, secret_field)
+
+ assert response.headers["abc"] == "SENSITIVE_INFORMATION"
+
+ def test_overrides_sensitive_info_url(self, response):
+ secret_key = "129e8cb2-d19c-51ad-9921-cea329bed7fa"
+ response.url = (
+ f"http://test.com/users/129e8cb2-d19c-51ad-9921-cea329bed7fa/details"
+ )
+ http_attr = "url"
+ secret_field = secret_key
+
+ _override_info(response, http_attr, secret_field)
+
+ assert response.url == "http://test.com/users/SENSITIVE_INFORMATION/details"
+
+ def test_when_http_attr_is_not_allowed(self, response, mocker):
+ mocker.patch("scanapi.hide_utils.ALLOWED_ATTRS_TO_HIDE", ["body"])
+ response.headers = {"abc": "123"}
+ http_attr = "headers"
+ secret_field = "abc"
+
+ _override_info(response, http_attr, secret_field)
+
+ assert response.headers["abc"] == "123"
+
+ def test_when_http_attr_does_not_have_the_field(self, response, mocker):
+ mocker.patch("scanapi.hide_utils.ALLOWED_ATTRS_TO_HIDE", ["body"])
+ response.headers = {"abc": "123"}
+ http_attr = "headers"
+ secret_field = "def"
+
+ _override_info(response, http_attr, secret_field)
+
+ assert response.headers == {"abc": "123"}
diff --git a/tests/unit/test_utils.py b/tests/unit/test_utils.py
index c7c7e05..2e6468a 100644
--- a/tests/unit/test_utils.py
+++ b/tests/unit/test_utils.py
@@ -3,12 +3,10 @@ import requests
from scanapi.errors import InvalidKeyError, MissingMandatoryKeyError
from scanapi.utils import (
- _hide,
- _override_info,
- hide_sensitive_info,
join_urls,
validate_keys,
)
+from scanapi.hide_utils import hide_sensitive_info, _hide, _override_info
@pytest.fixture
@@ -99,88 +97,3 @@ class TestValidateKeys:
scope = "endpoint"
validate_keys(keys, available_keys, mandatory_keys, scope)
-
-
-class TestHideSensitiveInfo:
- @pytest.fixture
- def mock__hide(self, mocker):
- return mocker.patch("scanapi.utils._hide")
-
- test_data = [
- ({}, {}, {}),
- ({"report": {"abc": "def"}}, {}, {}),
- ({"report": {"hide-request": {"headers": ["abc"]}}}, {"headers": ["abc"]}, {}),
- ({"report": {"hide-response": {"headers": ["abc"]}}}, {}, {"headers": ["abc"]}),
- ]
-
- @pytest.mark.parametrize("settings, request_settings, response_settings", test_data)
- def test_calls__hide(
- self,
- settings,
- request_settings,
- response_settings,
- mocker,
- response,
- mock__hide,
- ):
- mocker.patch("scanapi.utils.settings", settings)
- hide_sensitive_info(response)
-
- calls = [
- mocker.call(response.request, request_settings),
- mocker.call(response, response_settings),
- ]
-
- mock__hide.assert_has_calls(calls)
-
-
-class TestHide:
- @pytest.fixture
- def mock__override_info(self, mocker):
- return mocker.patch("scanapi.utils._override_info")
-
- test_data = [
- ({}, []),
- ({"headers": ["abc", "def"]}, [("headers", "abc"), ("headers", "def")]),
- ({"headers": ["abc"]}, [("headers", "abc")]),
- ]
-
- @pytest.mark.parametrize("settings, calls", test_data)
- def test_calls__override_info(
- self, settings, calls, mocker, response, mock__override_info
- ):
- _hide(response, settings)
- calls = [mocker.call(response, call[0], call[1]) for call in calls]
-
- mock__override_info.assert_has_calls(calls)
-
-
-class TestOverrideInfo:
- def test_overrides(self, response):
- response.headers = {"abc": "123"}
- http_attr = "headers"
- secret_field = "abc"
-
- _override_info(response, http_attr, secret_field)
-
- assert response.headers["abc"] == "SENSITIVE_INFORMATION"
-
- def test_when_http_attr_is_not_allowed(self, response, mocker):
- mocker.patch("scanapi.utils.ALLOWED_ATTRS_TO_HIDE", ["body"])
- response.headers = {"abc": "123"}
- http_attr = "headers"
- secret_field = "abc"
-
- _override_info(response, http_attr, secret_field)
-
- assert response.headers["abc"] == "123"
-
- def test_when_http_attr_does_not_have_the_field(self, response, mocker):
- mocker.patch("scanapi.utils.ALLOWED_ATTRS_TO_HIDE", ["body"])
- response.headers = {"abc": "123"}
- http_attr = "headers"
- secret_field = "def"
-
- _override_info(response, http_attr, secret_field)
-
- assert response.headers == {"abc": "123"}
|
Hide tokens and authorization info in the generated report
## Description
Add the possibility to hide tokens and authorization info in the generated report to avoid expose sensitive information via [configuration file](https://github.com/scanapi/scanapi/blob/124983ca0365e4552f7ad56a6f9523a829c6c293/scanapi/settings.py#L5) (usually `.scanapi.yaml`).
Change the sensitive information value to `<sensitive_information>`
Configuration Options:
- `report`
-- `hide-response` or `hide-request`
--- `headers` or `body` or `url`
---- list of keys to hide
Example:
```yaml
report:
hide-response:
headers:
- Authorization
- api-key
hide-response:
body:
- api-key
```
The logic is implemented inside the [hide_sensitive_info method](https://github.com/scanapi/scanapi/blob/124983ca0365e4552f7ad56a6f9523a829c6c293/scanapi/utils.py#L25)
Example of how this should be rendered in the reports:

- [x] header for request
- [x] header for response
- [x] body for request
- [x] body for response
- [ ] url for request
- [ ] url for response
|
0.0
|
b38ebbb5773cff60faa6901fe4052bbdcdf6021e
|
[
"tests/unit/test_hide_utils.py::TestHideSensitiveInfo::test_calls__hide[settings0-request_settings0-response_settings0]",
"tests/unit/test_hide_utils.py::TestHideSensitiveInfo::test_calls__hide[settings1-request_settings1-response_settings1]",
"tests/unit/test_hide_utils.py::TestHideSensitiveInfo::test_calls__hide[settings2-request_settings2-response_settings2]",
"tests/unit/test_hide_utils.py::TestHideSensitiveInfo::test_calls__hide[settings3-request_settings3-response_settings3]",
"tests/unit/test_hide_utils.py::TestHideSensitiveInfo::test_calls__hide[settings4-request_settings4-response_settings4]",
"tests/unit/test_hide_utils.py::TestHide::test_calls__override_info[settings0-calls0]",
"tests/unit/test_hide_utils.py::TestHide::test_calls__override_info[settings1-calls1]",
"tests/unit/test_hide_utils.py::TestHide::test_calls__override_info[settings2-calls2]",
"tests/unit/test_hide_utils.py::TestHide::test_calls__override_info[settings3-calls3]",
"tests/unit/test_hide_utils.py::TestOverrideInfo::test_overrides",
"tests/unit/test_hide_utils.py::TestOverrideInfo::test_overrides_sensitive_info_url",
"tests/unit/test_hide_utils.py::TestOverrideInfo::test_when_http_attr_is_not_allowed",
"tests/unit/test_hide_utils.py::TestOverrideInfo::test_when_http_attr_does_not_have_the_field",
"tests/unit/test_utils.py::TestJoinUrls::test_build_url_properly[http://demo.scanapi.dev/api/-health-http://demo.scanapi.dev/api/health]",
"tests/unit/test_utils.py::TestJoinUrls::test_build_url_properly[http://demo.scanapi.dev/api/-/health-http://demo.scanapi.dev/api/health]",
"tests/unit/test_utils.py::TestJoinUrls::test_build_url_properly[http://demo.scanapi.dev/api/-/health/-http://demo.scanapi.dev/api/health/]",
"tests/unit/test_utils.py::TestJoinUrls::test_build_url_properly[http://demo.scanapi.dev/api-health-http://demo.scanapi.dev/api/health]",
"tests/unit/test_utils.py::TestJoinUrls::test_build_url_properly[http://demo.scanapi.dev/api-/health-http://demo.scanapi.dev/api/health]",
"tests/unit/test_utils.py::TestJoinUrls::test_build_url_properly[http://demo.scanapi.dev/api-/health/-http://demo.scanapi.dev/api/health/]",
"tests/unit/test_utils.py::TestJoinUrls::test_build_url_properly[-http://demo.scanapi.dev/api/health/-http://demo.scanapi.dev/api/health/]",
"tests/unit/test_utils.py::TestJoinUrls::test_build_url_properly[http://demo.scanapi.dev/api/health/--http://demo.scanapi.dev/api/health/]",
"tests/unit/test_utils.py::TestJoinUrls::test_build_url_properly[--]",
"tests/unit/test_utils.py::TestValidateKeys::TestThereIsAnInvalidKey::test_should_raise_an_exception",
"tests/unit/test_utils.py::TestValidateKeys::TestMissingMandatoryKey::test_should_raise_an_exception",
"tests/unit/test_utils.py::TestValidateKeys::TestThereIsNotAnInvalidKeysOrMissingMandotoryKeys::test_should_not_raise_an_exception"
] |
[] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_media",
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-06-19 19:41:32+00:00
|
mit
| 5,347 |
|
schuderer__mllaunchpad-69
|
diff --git a/AUTHORS.rst b/AUTHORS.rst
index b107270..a030315 100644
--- a/AUTHORS.rst
+++ b/AUTHORS.rst
@@ -13,6 +13,7 @@ Contributors
* Elisa Partodikromo <https://github.com/planeetjupyter>
* Gosia Rorat <https://github.com/gosiarorat>
* Bart Driessen <https://github.com/Bart92>
+* Bob Platte <https://github.com/bobplatte>
Apache License 2.0
diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index 51d7a14..c8ccdda 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -25,6 +25,10 @@ and this project adheres to `Semantic Versioning <https://semver.org/spec/v2.0.0
Unreleased
------------------------------------------------------------------------------
+* |Fixed| Fix misleading error message at WSGI entry point if model could
+ not be loaded,
+ `issue #61 <https://github.com/schuderer/mllaunchpad/issues/61>`_,
+ by `Bob Platte <https://github.com/bobplatte>`_.
* |Enhancement| Config file is now being checked for omitted required keys,
(no issue), by `Andreas Schuderer <https://github.com/schuderer>`_.
* |Fixed| Use correct reference to werkzeug's FileStorage,
diff --git a/mllaunchpad/wsgi.py b/mllaunchpad/wsgi.py
index f0247ab..e1284a3 100644
--- a/mllaunchpad/wsgi.py
+++ b/mllaunchpad/wsgi.py
@@ -25,24 +25,27 @@ logger = logging.getLogger(__name__)
# necessary to wrap the preparatory code in a try:except: statement.
try:
conf = config.get_validated_config()
-
- # if you change the name of the application variable, you need to
- # specify it explicitly for gunicorn: gunicorn ... launchpad.wsgi:appname
- application = Flask(__name__, root_path=conf["api"].get("root_path"))
-
- ModelApi(conf, application)
except FileNotFoundError:
logger.error(
"Config file could not be loaded. Starting the Flask application "
"will fail."
)
+ conf = None
-if __name__ == "__main__":
- logger.warning(
- "Starting Flask debug server.\nIn production, please use a WSGI server, "
- + "e.g. 'gunicorn -w 4 -b 127.0.0.1:5000 mllaunchpad.wsgi:application'"
- )
- application.run(debug=True)
+ # if you change the name of the application variable, you need to
+ # specify it explicitly for gunicorn: gunicorn ... launchpad.wsgi:appname
+if conf:
+ application = Flask(__name__, root_path=conf["api"].get("root_path"))
+ ModelApi(conf, application)
+
+ if __name__ == "__main__":
+ logger.warning(
+ "Starting Flask debug server.\nIn production, please use a WSGI server, "
+ + "e.g. 'gunicorn -w 4 -b 127.0.0.1:5000 mllaunchpad.wsgi:application'"
+ )
+ # Flask apps must not be run in debug mode in production, because this allows for arbitrary code execution.
+ # We know that and advise the user that this is only for debugging, so this is not a security issue (marked nosec):
+ application.run(debug=True) # nosec
# To start an instance of production server with 4 workers:
# 1. Set environment variables if required
|
schuderer/mllaunchpad
|
4be60428b8091c3fb37e5cac01fdddef1b50180b
|
diff --git a/tests/test_api.py b/tests/test_api.py
index db17a5c..53c3cb9 100644
--- a/tests/test_api.py
+++ b/tests/test_api.py
@@ -1,7 +1,7 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
-"""Tests for `mllaunchpad.config` module."""
+"""Tests for `mllaunchpad.api` module."""
# Stdlib imports
from tempfile import NamedTemporaryFile
diff --git a/tests/test_wsgi.py b/tests/test_wsgi.py
new file mode 100644
index 0000000..6d9f4f3
--- /dev/null
+++ b/tests/test_wsgi.py
@@ -0,0 +1,52 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+"""Tests for `mllaunchpad.wsgi` module."""
+
+# Stdlib imports
+from importlib import reload
+from unittest.mock import patch
+
+# Third-party imports
+import pytest
+
+
+@patch("mllaunchpad.config.get_validated_config")
+def test_log_error_on_config_filenotfound(mock_get_cfg, caplog):
+ """Test that a FileNotFoundError on loading the config does
+ not cause an exception, but only log a 'not found, will fail' error.
+ """
+ mock_get_cfg.side_effect = FileNotFoundError
+
+ # This import is just to make sure the 'wsgi' symbol is known.
+ # We will ignore what happens and afterwards reload (re-import).
+ try:
+ import mllaunchpad.wsgi as wsgi # pylint: disable=unused-import
+ except FileNotFoundError:
+ pass
+ # The proper "import" test:
+ reload(wsgi)
+ assert "will fail".lower() in caplog.text.lower()
+
+
+@patch("mllaunchpad.api.ModelApi")
+@patch("mllaunchpad.config.get_validated_config")
+def test_regression_61_misleading(mock_get_cfg, mock_get_api, caplog):
+ """Test that a FileNotFoundError on loading the Model does
+ cause a proper exception and not merely log a 'config not found' error.
+ https://github.com/schuderer/mllaunchpad/issues/61
+ """
+ mock_get_cfg.return_value = {"api": {}}
+ mock_get_api.side_effect = FileNotFoundError
+
+ # This import is just to make sure the 'wsgi' symbol is known.
+ # We will ignore what happens and afterwards reload (re-import).
+ try:
+ import mllaunchpad.wsgi as wsgi # pylint: disable=unused-import
+ except FileNotFoundError:
+ pass
+ # The proper "import" test:
+ with pytest.raises(FileNotFoundError):
+ reload(wsgi)
+ assert "will fail".lower() not in caplog.text.lower()
+ assert mock_get_cfg.called
|
Misleading error message "mllaunchpad.wsgi: Config file could not be loaded"
This error also occurs if loading a previous model fails during the the ModelApi initialization. The try-catch block in the wsgi module mistakenly assumes that FileNotFoundError can only occur when loading the config, but it can also occur on initializing ModelApi (if the model could not be loaded from the model store). See:
https://github.com/schuderer/mllaunchpad/blob/cc378e1f1935d5211addf385075323a68253e746/mllaunchpad/wsgi.py#L33
Should probably be handled separately.
|
0.0
|
4be60428b8091c3fb37e5cac01fdddef1b50180b
|
[
"tests/test_wsgi.py::test_regression_61_misleading"
] |
[
"tests/test_api.py::test_model_api_init",
"tests/test_api.py::test_model_api_fileraml",
"tests/test_wsgi.py::test_log_error_on_config_filenotfound"
] |
{
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-02-20 11:34:51+00:00
|
apache-2.0
| 5,348 |
|
scieloorg__catalogmanager-44
|
diff --git a/catalog_persistence/databases.py b/catalog_persistence/databases.py
index cce5884..954921e 100644
--- a/catalog_persistence/databases.py
+++ b/catalog_persistence/databases.py
@@ -87,7 +87,9 @@ class InMemoryDBManager(BaseDBManager):
return doc
def update(self, id, document):
- self.database.update({id: document})
+ _document = self.read(id)
+ _document.update(document)
+ self.database.update({id: _document})
def delete(self, id):
self.read(id)
@@ -151,11 +153,7 @@ class InMemoryDBManager(BaseDBManager):
return list(doc.get(self._attachments_key, {}).keys())
def attachment_exists(self, id, file_id):
- doc = self.read(id)
- return (
- doc.get(self._attachments_key) and
- doc[self._attachments_key].get(file_id)
- )
+ return file_id in self.list_attachments(id)
class CouchDBManager(BaseDBManager):
@@ -255,11 +253,7 @@ class CouchDBManager(BaseDBManager):
return list(doc.get(self._attachments_key, {}).keys())
def attachment_exists(self, id, file_id):
- doc = self.read(id)
- return (
- doc.get(self._attachments_key) and
- doc[self._attachments_key].get(file_id)
- )
+ return file_id in self.list_attachments(id)
class DatabaseService:
@@ -398,17 +392,18 @@ class DatabaseService:
Erro:
DocumentNotFound: documento não encontrado na base de dados.
"""
- read_record = self.db_manager.read(document_id)
self.db_manager.put_attachment(document_id,
file_id,
content,
file_properties)
+ document = self.db_manager.read(document_id)
document_record = {
- 'document_id': read_record['document_id'],
- 'document_type': read_record['document_type'],
- 'created_date': read_record['created_date'],
+ 'document_id': document['document_id'],
+ 'document_type': document['document_type'],
+ 'content': document['content'],
+ 'created_date': document['created_date']
}
- self._register_change(document_record, ChangeType.UPDATE, file_id)
+ self.update(document_id, document_record)
def get_attachment(self, document_id, file_id):
"""
|
scieloorg/catalogmanager
|
cdd91564b0be09f1bd55d9664be81ab64f3f04d1
|
diff --git a/catalog_persistence/tests/test_databases.py b/catalog_persistence/tests/test_databases.py
index 575d003..9916c25 100644
--- a/catalog_persistence/tests/test_databases.py
+++ b/catalog_persistence/tests/test_databases.py
@@ -201,22 +201,48 @@ def test_put_attachment_to_document(setup, database_service, xml_test):
)
[email protected](DatabaseService, '_register_change')
-def test_put_attachment_to_document_register_change(mocked_register_change,
[email protected](DatabaseService, 'update')
+def test_put_attachment_to_document_update(mocked_update,
setup,
database_service,
xml_test):
- article_record = get_article_record({'Test': 'Test7'})
+ article_record = get_article_record({'Test': 'Test9'})
database_service.register(
article_record['document_id'],
article_record
)
+ attachment_id = "filename"
+ database_service.put_attachment(
+ document_id=article_record['document_id'],
+ file_id=attachment_id,
+ content=xml_test.encode('utf-8'),
+ file_properties={
+ 'content_type': "text/xml",
+ 'content_size': len(xml_test)
+ }
+ )
record = database_service.read(article_record['document_id'])
document_record = {
'document_id': record['document_id'],
'document_type': record['document_type'],
- 'created_date': record['created_date'],
+ 'content': record['content'],
+ 'created_date': record['created_date']
}
+ mocked_update.assert_called_with(
+ article_record['document_id'], document_record)
+
+
+def test_put_attachment_to_document_update_dates(setup,
+ database_service,
+ xml_test):
+ article_record = get_article_record({'Test': 'Test9'})
+ database_service.register(
+ article_record['document_id'],
+ article_record
+ )
+ record_v1 = database_service.read(article_record['document_id'])
+ dates_v1 = record_v1.get('created_date'), record_v1.get('updated_date')
+
attachment_id = "filename"
database_service.put_attachment(
document_id=article_record['document_id'],
@@ -228,9 +254,11 @@ def test_put_attachment_to_document_register_change(mocked_register_change,
}
)
- mocked_register_change.assert_called_with(document_record,
- ChangeType.UPDATE,
- attachment_id)
+ record_v2 = database_service.read(article_record['document_id'])
+ dates_v2 = record_v2.get('created_date'), record_v2.get('updated_date')
+ assert dates_v1[0] == dates_v2[0]
+ assert dates_v1[1] is None
+ assert dates_v2[1] > dates_v1[0]
def test_put_attachment_to_document_not_found(setup,
@@ -250,55 +278,6 @@ def test_put_attachment_to_document_not_found(setup,
)
[email protected](DatabaseService, '_register_change')
-def test_update_attachment_register_change_if_it_exists(mocked_register_change,
- setup,
- database_service,
- xml_test):
- article_record = get_article_record({'Test': 'Test9'})
- database_service.register(
- article_record['document_id'],
- article_record
- )
- attachment_id = "filename"
- database_service.put_attachment(
- document_id=article_record['document_id'],
- file_id=attachment_id,
- content=xml_test.encode('utf-8'),
- file_properties={
- 'content_type': "text/xml",
- 'content_size': len(xml_test)
- }
- )
- record = database_service.read(article_record['document_id'])
- document_record = {
- 'document_id': record['document_id'],
- 'document_type': record['document_type'],
- 'created_date': record['created_date'],
- }
- database_service.put_attachment(
- document_id=article_record['document_id'],
- file_id=attachment_id,
- content=xml_test.encode('utf-8'),
- file_properties={
- 'content_type': "text/xml",
- 'content_size': len(xml_test)
- }
- )
-
- record_check = dict(
- database_service.db_manager.database[article_record['document_id']]
- )
- assert record_check is not None
- assert database_service.db_manager.attachment_exists(
- article_record['document_id'],
- attachment_id
- )
- mocked_register_change.assert_called_with(document_record,
- ChangeType.UPDATE,
- attachment_id)
-
-
def test_read_document_with_attachments(setup, database_service, xml_test):
article_record = get_article_record({'Test': 'Test10'})
file_id = "href_file"
|
Corrigir put_attachment

Bug:
- Não precisar executar `self.db_manager.read` porque dentro de self.db_manager.put_attachment já está sendo executado isso.
- `self.db_manager.read` deve ser executado após `self.db_manager.put_attachment` para ter os dados atualizado com o resultado da ação de `self.db_manager.put_attachment`
relacionado com #2 e #6
|
0.0
|
cdd91564b0be09f1bd55d9664be81ab64f3f04d1
|
[
"catalog_persistence/tests/test_databases.py::test_put_attachment_to_document_update[InMemoryDBManager]",
"catalog_persistence/tests/test_databases.py::test_put_attachment_to_document_update_dates[InMemoryDBManager]"
] |
[
"catalog_persistence/tests/test_databases.py::test_register_document[InMemoryDBManager]",
"catalog_persistence/tests/test_databases.py::test_register_document_register_change[InMemoryDBManager]",
"catalog_persistence/tests/test_databases.py::test_read_document[InMemoryDBManager]",
"catalog_persistence/tests/test_databases.py::test_read_document_not_found[InMemoryDBManager]",
"catalog_persistence/tests/test_databases.py::test_update_document[InMemoryDBManager]",
"catalog_persistence/tests/test_databases.py::test_update_document_register_change[InMemoryDBManager]",
"catalog_persistence/tests/test_databases.py::test_update_document_not_found[InMemoryDBManager]",
"catalog_persistence/tests/test_databases.py::test_delete_document[InMemoryDBManager]",
"catalog_persistence/tests/test_databases.py::test_delete_document_register_change[InMemoryDBManager]",
"catalog_persistence/tests/test_databases.py::test_delete_document_not_found[InMemoryDBManager]",
"catalog_persistence/tests/test_databases.py::test_put_attachment_to_document[InMemoryDBManager]",
"catalog_persistence/tests/test_databases.py::test_put_attachment_to_document_not_found[InMemoryDBManager]",
"catalog_persistence/tests/test_databases.py::test_read_document_with_attachments[InMemoryDBManager]",
"catalog_persistence/tests/test_databases.py::test_get_attachment_from_document[InMemoryDBManager]",
"catalog_persistence/tests/test_databases.py::test_get_attachment_from_document_not_found[InMemoryDBManager]",
"catalog_persistence/tests/test_databases.py::test_get_attachment_not_found[InMemoryDBManager]",
"catalog_persistence/tests/test_databases.py::test_sort_result"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_issue_reference",
"has_media",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-04-16 19:35:26+00:00
|
bsd-2-clause
| 5,349 |
|
scieloorg__catalogmanager-50
|
diff --git a/catalog_persistence/databases.py b/catalog_persistence/databases.py
index 954921e..9dd6f9a 100644
--- a/catalog_persistence/databases.py
+++ b/catalog_persistence/databases.py
@@ -55,16 +55,13 @@ class BaseDBManager(metaclass=abc.ABCMeta):
def list_attachments(self, id) -> list:
return NotImplemented
- @abc.abstractmethod
- def attachment_exists(self, id, file_id) -> bool:
- return NotImplemented
-
class InMemoryDBManager(BaseDBManager):
def __init__(self, **kwargs):
self._database_name = kwargs['database_name']
self._attachments_key = 'attachments'
+ self._attachments_properties_key = 'attachments_properties'
self._database = {}
@property
@@ -103,7 +100,7 @@ class InMemoryDBManager(BaseDBManager):
selector: criterio para selecionar campo com determinados valores
Ex.: {'type': 'ART'}
fields: lista de campos para retornar. Ex.: ['name']
- sort: lista de dict com nome de campo e sua ordenacao. [{'name': 'asc'}]
+ sort: lista de dict com nome de campo e sua ordenacao.[{'name': 'asc'}]
Retorno:
Lista de registros de documento registrados na base de dados
@@ -141,6 +138,18 @@ class InMemoryDBManager(BaseDBManager):
content_properties['content_size']
self.database.update({id: doc})
+ def _add_attachment_properties(self, record, file_id, file_properties):
+ """
+ """
+ if not record.get(self._attachments_properties_key):
+ record[self._attachments_properties_key] = {}
+ if not record[self._attachments_properties_key].get(file_id):
+ record[self._attachments_properties_key][file_id] = {}
+
+ record[self._attachments_properties_key][file_id].update(
+ file_properties)
+ return record
+
def get_attachment(self, id, file_id):
doc = self.read(id)
if (doc.get(self._attachments_key) and
@@ -152,15 +161,13 @@ class InMemoryDBManager(BaseDBManager):
doc = self.read(id)
return list(doc.get(self._attachments_key, {}).keys())
- def attachment_exists(self, id, file_id):
- return file_id in self.list_attachments(id)
-
class CouchDBManager(BaseDBManager):
def __init__(self, **kwargs):
self._database_name = kwargs['database_name']
self._attachments_key = '_attachments'
+ self._attachments_properties_key = 'attachments_properties'
self._database = None
self._db_server = couchdb.Server(kwargs['database_uri'])
self._db_server.resource.credentials = (
@@ -215,7 +222,7 @@ class CouchDBManager(BaseDBManager):
selector: criterio para selecionar campo com determinados valores
Ex.: {'type': 'ART'}
fields: lista de campos para retornar. Ex.: ['name']
- sort: lista de dict com nome de campo e sua ordenacao. [{'name': 'asc'}]
+ sort: lista de dict com nome de campo e sua ordenacao.[{'name': 'asc'}]
Retorno:
Lista de registros de documento registrados na base de dados
@@ -225,7 +232,10 @@ class CouchDBManager(BaseDBManager):
'fields': fields,
'sort': sort,
}
- return [dict(document) for document in self.database.find(selection_criteria)]
+ return [
+ dict(document)
+ for document in self.database.find(selection_criteria)
+ ]
def put_attachment(self, id, file_id, content, content_properties):
"""
@@ -241,6 +251,18 @@ class CouchDBManager(BaseDBManager):
content_type=content_properties.get('content_type')
)
+ def _add_attachment_properties(self, record, file_id, file_properties):
+ """
+ """
+ if not record.get(self._attachments_properties_key):
+ record[self._attachments_properties_key] = {}
+ if not record[self._attachments_properties_key].get(file_id):
+ record[self._attachments_properties_key][file_id] = {}
+
+ record[self._attachments_properties_key][file_id].update(
+ file_properties)
+ return record
+
def get_attachment(self, id, file_id):
doc = self.read(id)
attachment = self.database.get_attachment(doc, file_id)
@@ -252,9 +274,6 @@ class CouchDBManager(BaseDBManager):
doc = self.read(id)
return list(doc.get(self._attachments_key, {}).keys())
- def attachment_exists(self, id, file_id):
- return file_id in self.list_attachments(id)
-
class DatabaseService:
"""
@@ -371,7 +390,7 @@ class DatabaseService:
selector: criterio para selecionar campo com determinados valores
Ex.: {'type': 'ART'}
fields: lista de campos para retornar. Ex.: ['name']
- sort: lista de dict com nome de campo e sua ordenacao. [{'name': 'asc'}]
+ sort: lista de dict com nome de campo e sua ordenacao.[{'name': 'asc'}]
Retorno:
Lista de registros de documento registrados na base de dados
@@ -403,6 +422,11 @@ class DatabaseService:
'content': document['content'],
'created_date': document['created_date']
}
+ document_record = self.db_manager._add_attachment_properties(
+ document_record,
+ file_id,
+ file_properties
+ )
self.update(document_id, document_record)
def get_attachment(self, document_id, file_id):
|
scieloorg/catalogmanager
|
44cfb62ab0b690413bcd04265e4b5abb516d5b09
|
diff --git a/catalog_persistence/tests/test_databases.py b/catalog_persistence/tests/test_databases.py
index 9916c25..46ef971 100644
--- a/catalog_persistence/tests/test_databases.py
+++ b/catalog_persistence/tests/test_databases.py
@@ -181,9 +181,10 @@ def test_put_attachment_to_document(setup, database_service, xml_test):
article_record['document_id'],
article_record
)
+ file_id = "href_file"
database_service.put_attachment(
document_id=article_record['document_id'],
- file_id="href_file",
+ file_id=file_id,
content=xml_test.encode('utf-8'),
file_properties={
'content_type': "text/xml",
@@ -195,17 +196,16 @@ def test_put_attachment_to_document(setup, database_service, xml_test):
database_service.db_manager.database[article_record['document_id']]
)
assert record_check is not None
- assert database_service.db_manager.attachment_exists(
- article_record['document_id'],
- "href_file"
+ assert file_id in database_service.db_manager.list_attachments(
+ article_record['document_id']
)
@patch.object(DatabaseService, 'update')
def test_put_attachment_to_document_update(mocked_update,
- setup,
- database_service,
- xml_test):
+ setup,
+ database_service,
+ xml_test):
article_record = get_article_record({'Test': 'Test9'})
database_service.register(
article_record['document_id'],
@@ -226,15 +226,23 @@ def test_put_attachment_to_document_update(mocked_update,
'document_id': record['document_id'],
'document_type': record['document_type'],
'content': record['content'],
- 'created_date': record['created_date']
+ 'created_date': record['created_date'],
+ database_service.db_manager._attachments_properties_key:
+ {
+ attachment_id:
+ {
+ 'content_type': "text/xml",
+ 'content_size': len(xml_test)
+ }
+ }
}
mocked_update.assert_called_with(
article_record['document_id'], document_record)
def test_put_attachment_to_document_update_dates(setup,
- database_service,
- xml_test):
+ database_service,
+ xml_test):
article_record = get_article_record({'Test': 'Test9'})
database_service.register(
article_record['document_id'],
@@ -441,3 +449,26 @@ def test_sort_result():
expected.append({'name': 'Ana', 'num': 200, 'type': 'B'})
got = sort_results(results, sort)
assert expected == got
+
+
+def test_add_attachment_properties(setup, database_service, xml_test):
+ expected = {
+ database_service.db_manager._attachments_properties_key:
+ {
+ 'href_file':
+ {
+ 'content_type': "text/xml",
+ 'content_size': len(xml_test)
+ }
+ }
+ }
+ file_properties = {
+ 'content_type': "text/xml",
+ 'content_size': len(xml_test)
+ }
+ record = {}
+ assert expected == database_service.db_manager._add_attachment_properties(
+ record,
+ 'href_file',
+ file_properties
+ )
|
Incluir no registro de attachments as propriedades do arquivo
Para retornar os ativos digitais, foi detectado a falta do content_type. Para solucionar isso, precisamos armazenar este dados, explicitamente.
Relacionado com #2
|
0.0
|
44cfb62ab0b690413bcd04265e4b5abb516d5b09
|
[
"catalog_persistence/tests/test_databases.py::test_put_attachment_to_document_update[InMemoryDBManager]",
"catalog_persistence/tests/test_databases.py::test_add_attachment_properties[InMemoryDBManager]"
] |
[
"catalog_persistence/tests/test_databases.py::test_register_document[InMemoryDBManager]",
"catalog_persistence/tests/test_databases.py::test_register_document_register_change[InMemoryDBManager]",
"catalog_persistence/tests/test_databases.py::test_read_document[InMemoryDBManager]",
"catalog_persistence/tests/test_databases.py::test_read_document_not_found[InMemoryDBManager]",
"catalog_persistence/tests/test_databases.py::test_update_document[InMemoryDBManager]",
"catalog_persistence/tests/test_databases.py::test_update_document_register_change[InMemoryDBManager]",
"catalog_persistence/tests/test_databases.py::test_update_document_not_found[InMemoryDBManager]",
"catalog_persistence/tests/test_databases.py::test_delete_document[InMemoryDBManager]",
"catalog_persistence/tests/test_databases.py::test_delete_document_register_change[InMemoryDBManager]",
"catalog_persistence/tests/test_databases.py::test_delete_document_not_found[InMemoryDBManager]",
"catalog_persistence/tests/test_databases.py::test_put_attachment_to_document[InMemoryDBManager]",
"catalog_persistence/tests/test_databases.py::test_put_attachment_to_document_update_dates[InMemoryDBManager]",
"catalog_persistence/tests/test_databases.py::test_put_attachment_to_document_not_found[InMemoryDBManager]",
"catalog_persistence/tests/test_databases.py::test_read_document_with_attachments[InMemoryDBManager]",
"catalog_persistence/tests/test_databases.py::test_get_attachment_from_document[InMemoryDBManager]",
"catalog_persistence/tests/test_databases.py::test_get_attachment_from_document_not_found[InMemoryDBManager]",
"catalog_persistence/tests/test_databases.py::test_get_attachment_not_found[InMemoryDBManager]",
"catalog_persistence/tests/test_databases.py::test_sort_result"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_issue_reference",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-04-18 12:45:49+00:00
|
bsd-2-clause
| 5,350 |
|
scieloorg__catalogmanager-60
|
diff --git a/catalog_persistence/databases.py b/catalog_persistence/databases.py
index 9dd6f9a..66ae954 100644
--- a/catalog_persistence/databases.py
+++ b/catalog_persistence/databases.py
@@ -19,6 +19,8 @@ class ChangeType(Enum):
class BaseDBManager(metaclass=abc.ABCMeta):
+ _attachments_properties_key = 'attachments_properties'
+
@abc.abstractmethod
def drop_database(self) -> None:
return NotImplemented
@@ -55,6 +57,46 @@ class BaseDBManager(metaclass=abc.ABCMeta):
def list_attachments(self, id) -> list:
return NotImplemented
+ def add_attachment_properties_to_document_record(self,
+ document_id,
+ file_id,
+ file_properties):
+ """
+ Acrescenta propriedades (file_properties) do arquivo (file_id)
+ ao registro (record)
+ Retorna registro (record) atualizado
+ """
+ _file_properties = {
+ k: v
+ for k, v in file_properties.items()
+ if k not in ['content', 'filename']
+ }
+ document = self.read(document_id)
+ document_record = {
+ 'document_id': document['document_id'],
+ 'document_type': document['document_type'],
+ 'content': document['content'],
+ 'created_date': document['created_date'],
+ }
+ properties = document.get(self._attachments_properties_key, {})
+ if file_id not in properties.keys():
+ properties[file_id] = {}
+
+ properties[file_id].update(
+ _file_properties)
+
+ document_record.update(
+ {
+ self._attachments_properties_key:
+ properties
+ }
+ )
+ return document_record
+
+ def get_attachment_properties(self, id, file_id):
+ doc = self.read(id)
+ return doc.get(self._attachments_properties_key, {}).get(file_id)
+
class InMemoryDBManager(BaseDBManager):
@@ -138,18 +180,6 @@ class InMemoryDBManager(BaseDBManager):
content_properties['content_size']
self.database.update({id: doc})
- def _add_attachment_properties(self, record, file_id, file_properties):
- """
- """
- if not record.get(self._attachments_properties_key):
- record[self._attachments_properties_key] = {}
- if not record[self._attachments_properties_key].get(file_id):
- record[self._attachments_properties_key][file_id] = {}
-
- record[self._attachments_properties_key][file_id].update(
- file_properties)
- return record
-
def get_attachment(self, id, file_id):
doc = self.read(id)
if (doc.get(self._attachments_key) and
@@ -251,18 +281,6 @@ class CouchDBManager(BaseDBManager):
content_type=content_properties.get('content_type')
)
- def _add_attachment_properties(self, record, file_id, file_properties):
- """
- """
- if not record.get(self._attachments_properties_key):
- record[self._attachments_properties_key] = {}
- if not record[self._attachments_properties_key].get(file_id):
- record[self._attachments_properties_key][file_id] = {}
-
- record[self._attachments_properties_key][file_id].update(
- file_properties)
- return record
-
def get_attachment(self, id, file_id):
doc = self.read(id)
attachment = self.database.get_attachment(doc, file_id)
@@ -415,15 +433,9 @@ class DatabaseService:
file_id,
content,
file_properties)
- document = self.db_manager.read(document_id)
- document_record = {
- 'document_id': document['document_id'],
- 'document_type': document['document_type'],
- 'content': document['content'],
- 'created_date': document['created_date']
- }
- document_record = self.db_manager._add_attachment_properties(
- document_record,
+ document_record = self.db_manager. \
+ add_attachment_properties_to_document_record(
+ document_id,
file_id,
file_properties
)
@@ -445,6 +457,22 @@ class DatabaseService:
"""
return self.db_manager.get_attachment(document_id, file_id)
+ def get_attachment_properties(self, document_id, file_id):
+ """
+ Recupera arquivo anexos ao registro de um documento pelo ID do
+ documento e ID do anexo.
+ Params:
+ document_id: ID do documento ao qual o arquivo está anexado
+ file_id: identificação do arquivo anexado a ser recuperado
+
+ Retorno:
+ Arquivo anexo
+
+ Erro:
+ DocumentNotFound: documento não encontrado na base de dados.
+ """
+ return self.db_manager.get_attachment_properties(document_id, file_id)
+
def sort_results(results, sort):
scores = [list() for i in results]
diff --git a/catalogmanager/__init__.py b/catalogmanager/__init__.py
index 544aa3c..72d9f45 100644
--- a/catalogmanager/__init__.py
+++ b/catalogmanager/__init__.py
@@ -49,6 +49,14 @@ def get_article_file(article_id, db_host, db_port, username, password):
return article_services.get_article_file(article_id)
+def get_asset_file(article_id, asset_id, db_host, db_port, username, password):
+ article_services = _get_article_service(db_host,
+ db_port,
+ username,
+ password)
+ return article_services.get_asset_file(article_id, asset_id)
+
+
def set_assets_public_url(article_id, xml_content, assets_filenames,
public_url):
article = Article(article_id)
diff --git a/catalogmanager/article_services.py b/catalogmanager/article_services.py
index 798e737..6fb9ef3 100644
--- a/catalogmanager/article_services.py
+++ b/catalogmanager/article_services.py
@@ -8,7 +8,6 @@ from catalog_persistence.databases import (
DatabaseService,
DocumentNotFound
)
-from .data_services import DataServices
from .models.article_model import (
Article,
)
@@ -41,7 +40,6 @@ class ArticleServicesMissingAssetFileException(Exception):
class ArticleServices:
def __init__(self, articles_db_manager, changes_db_manager):
- self.article_data_services = DataServices('articles')
self.article_db_service = DatabaseService(
articles_db_manager, changes_db_manager)
@@ -130,13 +128,23 @@ class ArticleServices:
missing.append(file_id)
return asset_files, missing
- def get_asset_file(self, article_id, file_id):
+ def get_asset_file(self, article_id, asset_id):
try:
- return self.article_db_service.get_attachment(
+ content = self.article_db_service.get_attachment(
document_id=article_id,
- file_id=file_id
+ file_id=asset_id
)
+ properties = self.article_db_service.get_attachment_properties(
+ document_id=article_id,
+ file_id=asset_id
+ )
+ content_type = '' if properties is None else properties.get(
+ 'content_type',
+ ''
+ )
+ return content_type, content
except DocumentNotFound:
raise ArticleServicesException(
- 'Missing asset file: {}. '.format(file_id)
+ 'Asset file {} (Article {}) not found. '.format(
+ asset_id, article_id)
)
diff --git a/catalogmanager/data_services.py b/catalogmanager/data_services.py
deleted file mode 100644
index 628787e..0000000
--- a/catalogmanager/data_services.py
+++ /dev/null
@@ -1,10 +0,0 @@
-# coding = utf-8
-
-
-class DataServices:
-
- def __init__(self, name):
- self.name = name
-
- def location(self, record_id):
- return '/{}/{}'.format(self.name, record_id)
diff --git a/catalogmanager_api/__init__.py b/catalogmanager_api/__init__.py
index 16c7e28..2333542 100644
--- a/catalogmanager_api/__init__.py
+++ b/catalogmanager_api/__init__.py
@@ -29,6 +29,7 @@ def main(global_config, **settings):
config.include(includeme)
config.add_route('home', '/')
config.add_route('get_article_xml', '/articles/{id}/xml')
+ config.add_route('get_asset_file', '/articles/{id}/{asset_id}')
ini_settings = get_appsettings(global_config['__file__'])
config.registry.settings['database_host'] = \
diff --git a/catalogmanager_api/views/article.py b/catalogmanager_api/views/article.py
index 513b7c4..eff8aab 100644
--- a/catalogmanager_api/views/article.py
+++ b/catalogmanager_api/views/article.py
@@ -94,3 +94,20 @@ class Article:
"message": e.message
}
)
+
+ @view_config(route_name='get_asset_file')
+ def get_asset_file(self):
+ try:
+ content_type, content = catalogmanager.get_asset_file(
+ article_id=self.request.matchdict['id'],
+ asset_id=self.request.matchdict['asset_id'],
+ **self.db_settings
+ )
+ return Response(content_type=content_type, body=content)
+ except catalogmanager.article_services.ArticleServicesException as e:
+ return Response(
+ json={
+ "error": "404",
+ "message": e.message
+ }
+ )
|
scieloorg/catalogmanager
|
2ed6b83ac1c018368ca8303406afb7ac2564594f
|
diff --git a/catalog_persistence/tests/test_databases.py b/catalog_persistence/tests/test_databases.py
index 46ef971..33e0bfb 100644
--- a/catalog_persistence/tests/test_databases.py
+++ b/catalog_persistence/tests/test_databases.py
@@ -452,23 +452,59 @@ def test_sort_result():
def test_add_attachment_properties(setup, database_service, xml_test):
- expected = {
- database_service.db_manager._attachments_properties_key:
- {
- 'href_file':
- {
- 'content_type': "text/xml",
- 'content_size': len(xml_test)
- }
- }
+ file_properties1 = {
+ 'content_type': "text/xml",
+ 'content_size': len(xml_test)
}
+ key = database_service.db_manager._attachments_properties_key
+ expected = {}
+ expected[key] = {
+ 'file1': file_properties1,
+ }
+
+ article_record = get_article_record({'Test': 'Test13'})
+ database_service.register(
+ article_record['document_id'],
+ article_record
+ )
+
+ document_record = database_service.db_manager \
+ .add_attachment_properties_to_document_record(
+ article_record['document_id'],
+ 'file1',
+ file_properties1
+ )
+ assert expected[key] == document_record[key]
+
+
+def test_get_attachment_properties(setup, database_service, xml_test):
+
+ article_record = get_article_record({'Test': 'Test11'})
+ database_service.register(
+ article_record['document_id'],
+ article_record
+ )
file_properties = {
'content_type': "text/xml",
'content_size': len(xml_test)
}
- record = {}
- assert expected == database_service.db_manager._add_attachment_properties(
- record,
- 'href_file',
- file_properties
+
+ database_service.put_attachment(
+ document_id=article_record['document_id'],
+ file_id='href_file',
+ content=xml_test.encode('utf-8'),
+ file_properties=file_properties
+ )
+
+ database_service.put_attachment(
+ document_id=article_record['document_id'],
+ file_id='href_file2',
+ content=xml_test.encode('utf-8'),
+ file_properties=file_properties
+ )
+ expected = file_properties
+ assert expected == \
+ database_service.db_manager.get_attachment_properties(
+ article_record['document_id'],
+ 'href_file'
)
diff --git a/catalogmanager/tests/test_article_model.py b/catalogmanager/tests/test_article_model.py
index 4ab89d1..b055a40 100644
--- a/catalogmanager/tests/test_article_model.py
+++ b/catalogmanager/tests/test_article_model.py
@@ -98,6 +98,4 @@ def test_update_href(test_package_A, test_packA_filenames,
]
assert len(items) == 1
- assert items[0].href == new_href
- assert items[0].name == filename
- assert not article.xml_tree.content == content
+ assert not article.xml_tree.compare(content)
diff --git a/catalogmanager/tests/test_article_services.py b/catalogmanager/tests/test_article_services.py
index 604354c..510f525 100644
--- a/catalogmanager/tests/test_article_services.py
+++ b/catalogmanager/tests/test_article_services.py
@@ -198,7 +198,9 @@ def test_get_asset_file(change_service, test_package_A, test_packA_filenames,
content=xml_file.content,
content_size=xml_file.size)
for file in test_package_A[1:]:
- assert file.content == article_services.get_asset_file('ID', file.name)
+ content_type, content = article_services.get_asset_file(
+ 'ID', file.name)
+ assert file.content == content
def test_get_asset_files(change_service, test_package_A,
@@ -211,7 +213,12 @@ def test_get_asset_files(change_service, test_package_A,
content=xml_file.content,
content_size=xml_file.size)
items, msg = article_services.get_asset_files('ID')
+ asset_contents = [
+ asset_data[1]
+ for name, asset_data in items.items()
+ if len(asset_data) == 2
+ ]
assert len(items) == len(files)
assert len(msg) == 0
for asset in files:
- assert asset.content in items.values()
+ assert asset.content in asset_contents
diff --git a/catalogmanager_api/tests/test_article.py b/catalogmanager_api/tests/test_article.py
index 09654f9..1f5abef 100644
--- a/catalogmanager_api/tests/test_article.py
+++ b/catalogmanager_api/tests/test_article.py
@@ -341,3 +341,52 @@ def test_http_article_put_article_with_assets(mocked_put_article,
assets_files=expected_assets_properties,
**db_settings
)
+
+
[email protected](catalogmanager, 'get_asset_file')
+def test_http_get_asset_file_calls_get_asset_file(mocked_get_asset_file,
+ db_settings,
+ testapp):
+
+ article_id = 'ID123456'
+ asset_id = 'ID123456'
+ mocked_get_asset_file.return_value = '', b'123456Test'
+ testapp.get('/articles/{}/{}'.format(article_id, asset_id))
+ mocked_get_asset_file.assert_called_once_with(
+ article_id=article_id,
+ asset_id=asset_id,
+ **db_settings
+ )
+
+
[email protected](catalogmanager, 'get_asset_file')
+def test_http_get_asset_file_not_found(mocked_get_asset_file,
+ testapp):
+ article_id = 'ID123456'
+ asset_id = 'a.jpg'
+ error_msg = 'Asset {} (Article {}) not found'.format(asset_id, article_id)
+ mocked_get_asset_file.side_effect = \
+ catalogmanager.article_services.ArticleServicesException(
+ message=error_msg
+ )
+ expected = {
+ "error": "404",
+ "message": error_msg
+ }
+ result = testapp.get('/articles/{}/{}'.format(article_id, asset_id))
+ assert result.status == '200 OK'
+ assert result.json == expected
+
+
[email protected](catalogmanager, 'get_asset_file')
+def test_http_get_asset_file_succeeded(mocked_get_asset_file,
+ testapp,
+ test_xml_file):
+ article_id = 'ID123456'
+ asset_id = 'a.jpg'
+ expected = 'text/xml', test_xml_file.encode('utf-8')
+ mocked_get_asset_file.return_value = expected
+ result = testapp.get('/articles/{}/{}'.format(article_id, asset_id))
+ assert result.status == '200 OK'
+ assert result.body == expected[1]
+ assert result.content_type == expected[0]
|
Recuperar ativo digital vinculado ao artigo.
Deve ser possível recuperar um único ativo digital vinculado a um artigo por meio da sua URL pública.
|
0.0
|
2ed6b83ac1c018368ca8303406afb7ac2564594f
|
[
"catalog_persistence/tests/test_databases.py::test_add_attachment_properties[InMemoryDBManager]",
"catalog_persistence/tests/test_databases.py::test_get_attachment_properties[InMemoryDBManager]",
"catalogmanager/tests/test_article_services.py::test_get_asset_file",
"catalogmanager/tests/test_article_services.py::test_get_asset_files"
] |
[
"catalog_persistence/tests/test_databases.py::test_register_document[InMemoryDBManager]",
"catalog_persistence/tests/test_databases.py::test_register_document_register_change[InMemoryDBManager]",
"catalog_persistence/tests/test_databases.py::test_read_document[InMemoryDBManager]",
"catalog_persistence/tests/test_databases.py::test_read_document_not_found[InMemoryDBManager]",
"catalog_persistence/tests/test_databases.py::test_update_document[InMemoryDBManager]",
"catalog_persistence/tests/test_databases.py::test_update_document_register_change[InMemoryDBManager]",
"catalog_persistence/tests/test_databases.py::test_update_document_not_found[InMemoryDBManager]",
"catalog_persistence/tests/test_databases.py::test_delete_document[InMemoryDBManager]",
"catalog_persistence/tests/test_databases.py::test_delete_document_register_change[InMemoryDBManager]",
"catalog_persistence/tests/test_databases.py::test_delete_document_not_found[InMemoryDBManager]",
"catalog_persistence/tests/test_databases.py::test_put_attachment_to_document[InMemoryDBManager]",
"catalog_persistence/tests/test_databases.py::test_put_attachment_to_document_update[InMemoryDBManager]",
"catalog_persistence/tests/test_databases.py::test_put_attachment_to_document_update_dates[InMemoryDBManager]",
"catalog_persistence/tests/test_databases.py::test_put_attachment_to_document_not_found[InMemoryDBManager]",
"catalog_persistence/tests/test_databases.py::test_read_document_with_attachments[InMemoryDBManager]",
"catalog_persistence/tests/test_databases.py::test_get_attachment_from_document[InMemoryDBManager]",
"catalog_persistence/tests/test_databases.py::test_get_attachment_from_document_not_found[InMemoryDBManager]",
"catalog_persistence/tests/test_databases.py::test_get_attachment_not_found[InMemoryDBManager]",
"catalog_persistence/tests/test_databases.py::test_sort_result",
"catalogmanager/tests/test_article_model.py::test_article",
"catalogmanager/tests/test_article_model.py::test_missing_files_list",
"catalogmanager/tests/test_article_model.py::test_unexpected_files_list",
"catalogmanager/tests/test_article_model.py::test_update_href",
"catalogmanager/tests/test_article_services.py::test_receive_xml_file",
"catalogmanager/tests/test_article_services.py::test_receive_package",
"catalogmanager/tests/test_article_services.py::test_get_article_in_database",
"catalogmanager/tests/test_article_services.py::test_get_article_in_database_not_found",
"catalogmanager/tests/test_article_services.py::test_get_article_record",
"catalogmanager/tests/test_article_services.py::test_get_article_file_in_database",
"catalogmanager/tests/test_article_services.py::test_get_article_file_not_found",
"catalogmanager/tests/test_article_services.py::test_get_article_file",
"catalogmanager/tests/test_article_services.py::test_get_asset_file_not_found"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_removed_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-04-20 13:38:17+00:00
|
bsd-2-clause
| 5,351 |
|
scieloorg__catalogmanager-68
|
diff --git a/catalogmanager/__init__.py b/catalogmanager/__init__.py
index 2d81a0a..666a2d3 100644
--- a/catalogmanager/__init__.py
+++ b/catalogmanager/__init__.py
@@ -1,7 +1,7 @@
from catalogmanager.article_services import (
ArticleServices
)
-from catalogmanager.models.article_model import Article
+from catalogmanager.models.article_model import ArticleDocument
from catalogmanager.models.file import File
from catalog_persistence.databases import CouchDBManager
@@ -63,7 +63,7 @@ def get_asset_file(article_id, asset_id, db_host, db_port, username, password):
def set_assets_public_url(article_id, xml_content, assets_filenames,
public_url):
- article = Article(article_id)
+ article = ArticleDocument(article_id)
article.xml_file = File(file_name="xml_file.xml", content=xml_content)
for name in article.assets:
if name in assets_filenames:
diff --git a/catalogmanager/article_services.py b/catalogmanager/article_services.py
index 4cec8b0..c86d550 100644
--- a/catalogmanager/article_services.py
+++ b/catalogmanager/article_services.py
@@ -7,7 +7,7 @@ from catalog_persistence.models import (
from catalog_persistence.databases import DocumentNotFound
from catalog_persistence.services import DatabaseService
from .models.article_model import (
- Article,
+ ArticleDocument,
)
from .models.file import File
@@ -37,7 +37,7 @@ class ArticleServices:
return article.unexpected_files_list, article.missing_files_list
def receive_xml_file(self, id, xml_file):
- article = Article(id)
+ article = ArticleDocument(id)
article.xml_file = xml_file
article_record = Record(
@@ -78,12 +78,12 @@ class ArticleServices:
return article_record
except DocumentNotFound:
raise ArticleServicesException(
- 'Article {} not found'.format(article_id)
+ 'ArticleDocument {} not found'.format(article_id)
)
def get_article_file(self, article_id):
article_record = self.get_article_data(article_id)
- article = Article(article_id)
+ article = ArticleDocument(article_id)
try:
attachment = self.article_db_service.get_attachment(
document_id=article_id,
@@ -126,6 +126,6 @@ class ArticleServices:
return content_type, content
except DocumentNotFound:
raise ArticleServicesException(
- 'Asset file {} (Article {}) not found. '.format(
+ 'AssetDocument file {} (ArticleDocument {}) not found.'.format(
asset_id, article_id)
)
diff --git a/catalogmanager/models/article_model.py b/catalogmanager/models/article_model.py
index f998926..1a065f8 100644
--- a/catalogmanager/models/article_model.py
+++ b/catalogmanager/models/article_model.py
@@ -8,7 +8,7 @@ from .file import (
)
-class Asset:
+class AssetDocument:
def __init__(self, asset_node):
self.file = None
@@ -26,7 +26,7 @@ class Asset:
self.node.href = value
-class Article:
+class ArticleDocument:
def __init__(self, article_id):
self.id = article_id
@@ -43,7 +43,7 @@ class Article:
self.xml_tree = ArticleXMLTree()
self.xml_tree.content = self._xml_file.content
self.assets = {
- name: Asset(node)
+ name: AssetDocument(node)
for name, node in self.xml_tree.asset_nodes.items()
}
|
scieloorg/catalogmanager
|
dff657cc8a52defe284942174fbcb47acd514030
|
diff --git a/catalogmanager/tests/test_article_model.py b/catalogmanager/tests/test_article_model.py
index 8324e83..5afd84a 100644
--- a/catalogmanager/tests/test_article_model.py
+++ b/catalogmanager/tests/test_article_model.py
@@ -1,6 +1,6 @@
from catalogmanager.models.article_model import (
- Article,
+ ArticleDocument,
)
from catalogmanager.xml.xml_tree import (
XMLTree,
@@ -8,7 +8,7 @@ from catalogmanager.xml.xml_tree import (
def test_article(test_package_A, test_packA_filenames):
- article = Article('ID')
+ article = ArticleDocument('ID')
xml_file = test_package_A[0]
article.xml_file = xml_file
article.update_asset_files(test_package_A[1:])
@@ -28,7 +28,7 @@ def test_article(test_package_A, test_packA_filenames):
def test_missing_files_list(test_package_B):
- article = Article('ID')
+ article = ArticleDocument('ID')
article.xml_file = test_package_B[0]
article.update_asset_files(test_package_B[1:])
@@ -47,7 +47,7 @@ def test_missing_files_list(test_package_B):
def test_unexpected_files_list(test_package_C, test_packC_filenames):
- article = Article('ID')
+ article = ArticleDocument('ID')
article.xml_file = test_package_C[0]
article.update_asset_files(test_package_C[1:])
@@ -67,7 +67,7 @@ def test_unexpected_files_list(test_package_C, test_packC_filenames):
def test_update_href(test_package_A, test_packA_filenames):
new_href = 'novo href'
filename = '0034-8910-rsp-S01518-87872016050006741-gf01.jpg'
- article = Article('ID')
+ article = ArticleDocument('ID')
article.xml_file = test_package_A[0]
article.update_asset_files(test_package_A[1:])
content = article.xml_tree.content
|
Alterar o nome de "Article" para "ArticleDocument"
Como o conceito de Artigo é mais amplo do que somente o documento bruto, as especificidades dele não estarão todas na persistência do Catalog Manager e, por isso, é necessário identificá-lo como um documento de artigo.
|
0.0
|
dff657cc8a52defe284942174fbcb47acd514030
|
[
"catalogmanager/tests/test_article_model.py::test_article",
"catalogmanager/tests/test_article_model.py::test_missing_files_list",
"catalogmanager/tests/test_article_model.py::test_unexpected_files_list",
"catalogmanager/tests/test_article_model.py::test_update_href"
] |
[] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-04-24 18:22:16+00:00
|
bsd-2-clause
| 5,352 |
|
scieloorg__catalogmanager-97
|
diff --git a/managers/__init__.py b/managers/__init__.py
index 38728b9..6cac9ea 100644
--- a/managers/__init__.py
+++ b/managers/__init__.py
@@ -138,8 +138,8 @@ def set_assets_public_url(article_id, xml_content, assets_filenames,
:returns: conteúdo do XML atualizado
"""
- article = ArticleDocument(article_id)
- article.xml_file = File(file_name="xml_file.xml", content=xml_content)
+ xml_file = File(file_name="xml_file.xml", content=xml_content)
+ article = ArticleDocument(article_id, xml_file)
for name in article.assets:
if name in assets_filenames:
article.assets[name].href = public_url.format(article_id,
diff --git a/managers/article_manager.py b/managers/article_manager.py
index 3baa212..7c58fa4 100644
--- a/managers/article_manager.py
+++ b/managers/article_manager.py
@@ -37,8 +37,7 @@ class ArticleManager:
return article.unexpected_files_list, article.missing_files_list
def receive_xml_file(self, id, xml_file):
- article = ArticleDocument(id)
- article.xml_file = xml_file
+ article = ArticleDocument(id, xml_file)
article_record = Record(
document_id=article.id,
@@ -83,18 +82,17 @@ class ArticleManager:
def get_article_file(self, article_id):
article_record = self.get_article_data(article_id)
- article = ArticleDocument(article_id)
try:
attachment = self.article_db_service.get_attachment(
document_id=article_id,
file_id=article_record['content']['xml']
)
- article.xml_file = File(file_name=article_record['content']['xml'],
- content=attachment)
- return article.xml_file.content
+ xml_file = File(file_name=article_record['content']['xml'],
+ content=attachment)
+ return xml_file.content
except DocumentNotFound:
raise ArticleManagerException(
- 'Missing XML file {}'.format(article_id)
+ 'XML file {} not found'.format(article_id)
)
def get_asset_files(self, article_id):
diff --git a/managers/models/article_model.py b/managers/models/article_model.py
index 5ff3847..7d9d8ba 100644
--- a/managers/models/article_model.py
+++ b/managers/models/article_model.py
@@ -5,7 +5,6 @@ from ..xml.article_xml_tree import ArticleXMLTree
class AssetDocument:
"""Metadados de um documento do tipo Ativo Digital.
-
Um Ativo Digital é um arquivo associado a um documento do tipo Artigo
por meio de uma referência interna na estrutura da sua representação em
XML.
@@ -18,8 +17,6 @@ class AssetDocument:
#gerenciado pela instância mas pelo seu cliente.
self.file = None
self.node = asset_node
- #XXX :attr:`.name` e :attr:`.href` perdem integridade após atribuição
- #em :attr:`.href`.
self.name = asset_node.href
@property
@@ -39,21 +36,18 @@ class AssetDocument:
class ArticleDocument:
"""Metadados de um documento do tipo Artigo.
- Os metadados contam com uma referência ao Artigo codificado em XML e
+ Os metadados contam com uma referência ao Artigo codificado em XML e
referências aos seus ativos digitais.
Exemplo de uso:
- #XXX note que a inicialização da instância não é feita por completo no
- #momento devido.
-
- >>> doc = ArticleDocument('art01')
- >>> doc.xml_file = <instância de File>
+ >>> doc = ArticleDocument('art01', <instância de File>)
"""
- def __init__(self, article_id):
+ def __init__(self, article_id, xml_file):
self.id = article_id
self.assets = {}
self.unexpected_files_list = []
+ self.xml_file = xml_file
@property
def xml_file(self):
@@ -62,7 +56,7 @@ class ArticleDocument:
um novo documento Artigo resultará na identificação dos seus ativos,
i.e., o valor do atributo :attr:`.assets` será modificado.
- Adicionalmente, a definição de um novo documento Artigo causará a
+ Adicionalmente, a definição de um novo documento Artigo causará a
definição do atributo :attr:`.xml_tree`.
O acesso ao documento Artigo antes que este seja inicializado resultará
@@ -73,11 +67,7 @@ class ArticleDocument:
@xml_file.setter
def xml_file(self, xml_file):
self._xml_file = xml_file
- #XXX o atributo não é definido até que :meth:`xml_file` seja
- #executado definindo um documento Artigo, i.e., a API do objeto
- #varia de acordo com o seu ciclo de vida.
- self.xml_tree = ArticleXMLTree()
- self.xml_tree.content = self._xml_file.content
+ self.xml_tree = ArticleXMLTree(self._xml_file.content)
self.assets = {
name: AssetDocument(node)
for name, node in self.xml_tree.asset_nodes.items()
@@ -99,11 +89,11 @@ class ArticleDocument:
"""Associa o ativo ``file`` aos metadados de um Artigo, sobrescrevendo
valores associados anteriormente.
- Retorna instância de :class:`AssetDocument` no caso de sucesso, ou
- ``None`` caso contrário. Caso o valor retornado seja ``None`` você
+ Retorna instância de :class:`AssetDocument` no caso de sucesso, ou
+ ``None`` caso contrário. Caso o valor retornado seja ``None`` você
poderá inspecionar o atributo :attr:`.unexpected_files_list` para
saber se trata-se de um ativo desconhecido pelo Artigo ou se trata-se
- de um artigo que não possui o atributo ``name``.
+ de um artigo que não possui o atributo ``name``.
"""
name = file.name
if name:
diff --git a/managers/xml/xml_tree.py b/managers/xml/xml_tree.py
index 21d0d51..a1283b2 100644
--- a/managers/xml/xml_tree.py
+++ b/managers/xml/xml_tree.py
@@ -1,7 +1,10 @@
# coding=utf-8
from lxml import etree
-from io import BytesIO
+from io import (
+ BytesIO,
+ StringIO,
+)
namespaces = {}
@@ -15,14 +18,14 @@ for namespace_id, namespace_link in namespaces.items():
class XMLTree:
- def __init__(self):
+ def __init__(self, xml_content):
self.tree = None
self.xml_error = None
+ self.content = xml_content
@property
def content(self):
- if self.tree is not None:
- return etree.tostring(self.tree.getroot(), encoding='utf-8')
+ return self.otimized
@content.setter
def content(self, xml_content):
@@ -39,4 +42,28 @@ class XMLTree:
return (r, message)
def compare(self, xml_content):
- return self.content == xml_content
+ return self.content == XMLTree(xml_content).content
+
+ @property
+ def tostring(self):
+ if self.tree is not None:
+ return etree.tostring(self.tree.getroot(), encoding='utf-8')
+
+ @property
+ def pretty(self):
+ return etree.tostring(
+ self.tree.getroot(),
+ encoding='utf-8',
+ pretty_print=True)
+
+ @property
+ def otimized(self):
+ parser = etree.XMLParser(remove_blank_text=True)
+ content = self.tostring
+ if content is not None:
+ root = etree.XML(content.decode('utf-8'), parser)
+ b = etree.tostring(root, encoding='utf-8')
+ s = b.decode('utf-8')
+ while ' '*2 in s:
+ s = s.replace(' '*2, ' ')
+ return s.encode('utf-8')
|
scieloorg/catalogmanager
|
1fb4aca5191f0668604213d72eac29bdbda200d5
|
diff --git a/managers/tests/test_article_manager.py b/managers/tests/test_article_manager.py
index 6356300..e391079 100644
--- a/managers/tests/test_article_manager.py
+++ b/managers/tests/test_article_manager.py
@@ -148,8 +148,7 @@ def test_get_article_file(setup,
)
article_check = article_manager.get_article_file('ID')
assert article_check is not None
- xml_tree = XMLTree()
- xml_tree.content = test_package_A[0].content
+ xml_tree = XMLTree(test_package_A[0].content)
assert xml_tree.compare(article_check)
diff --git a/managers/tests/test_article_model.py b/managers/tests/test_article_model.py
index 93378ff..cbd8551 100644
--- a/managers/tests/test_article_model.py
+++ b/managers/tests/test_article_model.py
@@ -8,28 +8,21 @@ from managers.xml.xml_tree import (
def test_article(test_package_A, test_packA_filenames):
- article = ArticleDocument('ID')
- xml_file = test_package_A[0]
- article.xml_file = xml_file
+ article = ArticleDocument('ID', test_package_A[0])
article.update_asset_files(test_package_A[1:])
expected = {
'assets': [asset for asset in test_packA_filenames[1:]],
'xml': test_packA_filenames[0],
}
assert article.xml_file.name == test_packA_filenames[0]
+ assert article.xml_file.content == test_package_A[0].content
assert article.xml_tree.xml_error is None
+ assert article.xml_tree.compare(test_package_A[0].content)
assert article.get_record_content() == expected
- assert article.xml_file.content == xml_file.content
- xml_from_file = XMLTree()
- xml_from_file.content = article.xml_file.content
- xml_from_tree = XMLTree()
- xml_from_tree.content = article.xml_tree.content
- assert xml_from_file.content == xml_from_tree.content
def test_missing_files_list(test_package_B):
- article = ArticleDocument('ID')
- article.xml_file = test_package_B[0]
+ article = ArticleDocument('ID', test_package_B[0])
article.update_asset_files(test_package_B[1:])
assert len(article.assets) == 3
@@ -47,8 +40,7 @@ def test_missing_files_list(test_package_B):
def test_unexpected_files_list(test_package_C, test_packC_filenames):
- article = ArticleDocument('ID')
- article.xml_file = test_package_C[0]
+ article = ArticleDocument('ID', test_package_C[0])
article.update_asset_files(test_package_C[1:])
assert len(article.assets) == 2
@@ -67,8 +59,7 @@ def test_unexpected_files_list(test_package_C, test_packC_filenames):
def test_update_href(test_package_A, test_packA_filenames):
new_href = 'novo href'
filename = '0034-8910-rsp-S01518-87872016050006741-gf01.jpg'
- article = ArticleDocument('ID')
- article.xml_file = test_package_A[0]
+ article = ArticleDocument('ID', test_package_A[0])
article.update_asset_files(test_package_A[1:])
content = article.xml_tree.content
asset = article.assets.get(filename)
diff --git a/managers/tests/test_xml_tree.py b/managers/tests/test_xml_tree.py
index 9379912..e75a1f2 100644
--- a/managers/tests/test_xml_tree.py
+++ b/managers/tests/test_xml_tree.py
@@ -6,17 +6,15 @@ from managers.xml.xml_tree import (
def test_good_xml():
xml = b'<article id="a1">\n<text/>\n</article>'
- xml_tree = XMLTree()
- xml_tree.content = xml
- assert xml == xml_tree.content
+ xml_tree = XMLTree(xml)
+ assert xml_tree.compare(xml)
assert xml_tree.xml_error is None
assert xml_tree.tree is not None
def test_bad_xml():
xml = b'<article id="a1">\n<text>\n</article>'
- xml_tree = XMLTree()
- xml_tree.content = xml
+ xml_tree = XMLTree(xml)
assert xml_tree.content is None
assert xml_tree.xml_error is not None
assert xml_tree.tree is None
@@ -24,8 +22,7 @@ def test_bad_xml():
def test_compare_equal_xml():
xml = b'<article id="a2">\n<text/>\n</article>'
- xml_tree = XMLTree()
- xml_tree.content = xml
+ xml_tree = XMLTree(xml)
assert xml_tree.content is not None
assert xml_tree.compare(
b'<article id="a2">\n<text/>\n</article>'
@@ -34,9 +31,88 @@ def test_compare_equal_xml():
def test_compare_not_equal_xml():
xml = b'<article id="a2">\n<text/>\n</article>'
- xml_tree = XMLTree()
- xml_tree.content = xml
+ xml_tree = XMLTree(xml)
assert xml_tree.content is not None
assert not xml_tree.compare(
b'<article id="a1">\n<text/>\n</article>'
)
+
+
+def test_pretty():
+ s_xml = """<article><p>A ljllj <bold>kjjflajfa,</bold> """ \
+ """<italic>djajflaj</italic></p><p>Parágrafo 2</p></article>"""
+ s_expected = """<article>\n <p>A ljllj <bold>kjjflajfa,</bold> """ \
+ """<italic>djajflaj</italic></p>\n <p>Parágrafo 2</p>\n</article>\n"""
+
+ xml = s_xml.encode('utf-8')
+ expected = s_expected.encode('utf-8')
+ xml_tree = XMLTree(xml)
+ assert xml_tree.content is not None
+ assert xml_tree.pretty == expected
+
+
+def otimize(s_xml, s_expected):
+ b_xml = s_xml.encode('utf-8')
+ b_expected = s_expected.encode('utf-8')
+ xml_tree = XMLTree(b_xml)
+ assert xml_tree.content is not None
+ assert xml_tree.otimized == b_expected
+
+
+def test_otimized_preserva_tab_linebreak_em_elementos_que_contenham_texto():
+ s_xml = '<article>' \
+ '\n <body>' \
+ '\n <p>A ljllj' \
+ '\n <bold>kjjflajfa,</bold>' \
+ '\n <italic>djajflaj</italic>' \
+ '\n </p>' \
+ '\n a ' \
+ '\n <p>Parágrafo 2</p>' \
+ '\n </body>' \
+ '\n</article>'
+
+ s_expected = '<article>' \
+ '<body>' \
+ '<p>A ljllj' \
+ '\n <bold>kjjflajfa,</bold>' \
+ '\n <italic>djajflaj</italic>' \
+ '\n </p>' \
+ '\n a ' \
+ '\n <p>Parágrafo 2</p>' \
+ '\n </body></article>'
+ otimize(s_xml, s_expected)
+
+
+def test_otimized_preserva_tab_linebreak_em_elementos_que_contenham_texto2():
+ s_xml = '<article> ' \
+ '\nA ljllj\n \t\t \n \t ' \
+ '\nkjjflajfa, ' \
+ '\ndjajflaj ' \
+ '\na ' \
+ '\nParágrafo 2 ' \
+ '\n</article>'
+ s_expected = '<article> ' \
+ '\nA ljllj\n \t\t \n \t ' \
+ '\nkjjflajfa, ' \
+ '\ndjajflaj ' \
+ '\na ' \
+ '\nParágrafo 2 ' \
+ '\n</article>'
+ otimize(s_xml, s_expected)
+
+
+def test_otimized_estilos():
+ s_xml = '<article><b>Bold</b> <i>itálico</i></article>'
+ s_expected = '<article><b>Bold</b><i>itálico</i></article>'
+ otimize(s_xml, s_expected)
+
+
+def test_otimized_elimina_tab_linebreak_em_elementos_que_nao_contem_texto():
+ s_xml = """
+ <article> \n\t
+ <p>A ljllj </p>
+ <p>Parágrafo 2</p>\n\n\n\n
+ </article>\n
+ """
+ s_expected = '<article><p>A ljllj </p><p>Parágrafo 2</p></article>'
+ otimize(s_xml, s_expected)
|
Armazenar o XML sem espaços entre tags (minificado).
Devemos testar a hipótese de que: cada caractere em branco (espaço) no UTF-8 ocupa 1 byte, o que pode se tornar dispendioso em termos de consumo de disco e tráfego de rede, se levarmos em conta o volume de dados do sistema.
|
0.0
|
1fb4aca5191f0668604213d72eac29bdbda200d5
|
[
"managers/tests/test_article_manager.py::test_get_article_file",
"managers/tests/test_article_model.py::test_article",
"managers/tests/test_article_model.py::test_missing_files_list",
"managers/tests/test_article_model.py::test_unexpected_files_list",
"managers/tests/test_article_model.py::test_update_href",
"managers/tests/test_xml_tree.py::test_good_xml",
"managers/tests/test_xml_tree.py::test_bad_xml",
"managers/tests/test_xml_tree.py::test_compare_equal_xml",
"managers/tests/test_xml_tree.py::test_compare_not_equal_xml",
"managers/tests/test_xml_tree.py::test_pretty",
"managers/tests/test_xml_tree.py::test_otimized_preserva_tab_linebreak_em_elementos_que_contenham_texto",
"managers/tests/test_xml_tree.py::test_otimized_preserva_tab_linebreak_em_elementos_que_contenham_texto2",
"managers/tests/test_xml_tree.py::test_otimized_estilos",
"managers/tests/test_xml_tree.py::test_otimized_elimina_tab_linebreak_em_elementos_que_nao_contem_texto"
] |
[
"managers/tests/test_article_manager.py::test_receive_xml_file",
"managers/tests/test_article_manager.py::test_receive_package",
"managers/tests/test_article_manager.py::test_get_article_in_database",
"managers/tests/test_article_manager.py::test_get_article_in_database_not_found",
"managers/tests/test_article_manager.py::test_get_article_record",
"managers/tests/test_article_manager.py::test_get_article_file_in_database",
"managers/tests/test_article_manager.py::test_get_article_file_not_found",
"managers/tests/test_article_manager.py::test_get_asset_file_not_found",
"managers/tests/test_article_manager.py::test_get_asset_file",
"managers/tests/test_article_manager.py::test_get_asset_files"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-05-23 20:11:58+00:00
|
bsd-2-clause
| 5,353 |
|
scieloorg__xylose-158
|
diff --git a/xylose/scielodocument.py b/xylose/scielodocument.py
index da4d426..27af27d 100644
--- a/xylose/scielodocument.py
+++ b/xylose/scielodocument.py
@@ -1,7 +1,6 @@
# encoding: utf-8
import sys
from functools import wraps
-import warnings
import re
import unicodedata
import datetime
@@ -3063,13 +3062,40 @@ class Citation(object):
ma = self.monographic_authors or []
return aa + ma
+ @property
+ def analytic_person_authors(self):
+ """
+ It retrieves the analytic person authors of a reference,
+ no matter the publication type of the reference.
+ It is not desirable to restrict the conditioned return to the
+ publication type, because some reference standards are very peculiar
+ and not only articles or books have person authors.
+ IT REPLACES analytic_authors
+ """
+ authors = []
+ for author in self.data.get('v10', []):
+ authordict = {}
+ if 's' in author:
+ authordict['surname'] = html_decode(author['s'])
+ if 'n' in author:
+ authordict['given_names'] = html_decode(author['n'])
+ if 's' in author or 'n' in author:
+ authors.append(authordict)
+ if len(authors) > 0:
+ return authors
+
@property
def analytic_authors(self):
"""
This method retrieves the authors of the given citation. These authors
may correspond to an article, book analytic, link or thesis.
+ IT WILL BE DEPRECATED. Use analytic_person_authors instead
"""
-
+ warn_future_deprecation(
+ 'analytic_authors',
+ 'analytic_person_authors',
+ 'analytic_person_authors is more suitable name'
+ )
authors = []
if 'v10' in self.data:
for author in self.data['v10']:
@@ -3084,13 +3110,41 @@ class Citation(object):
if len(authors) > 0:
return authors
+ @property
+ def monographic_person_authors(self):
+ """
+ It retrieves the monographic person authors of a reference,
+ no matter the publication type of the reference.
+ It is not desirable to restrict the conditioned return to the
+ publication type, because some reference standards are very peculiar
+ and not only articles or books have person authors.
+ IT REPLACES monographic_authors
+ """
+ authors = []
+ for author in self.data.get('v16', []):
+ authordict = {}
+ if 's' in author:
+ authordict['surname'] = html_decode(author['s'])
+ if 'n' in author:
+ authordict['given_names'] = html_decode(author['n'])
+ if 's' in author or 'n' in author:
+ authors.append(authordict)
+ if len(authors) > 0:
+ return authors
+
@property
def monographic_authors(self):
"""
- This method retrieves the authors of the given book citation. These authors may
+ This method retrieves the authors of the given book citation.
+ These authors may
correspond to a book monography citation.
+ IT WILL BE DEPRECATED. Use monographic_person_authors instead.
"""
-
+ warn_future_deprecation(
+ 'monographic_authors',
+ 'monographic_person_authors',
+ 'monographic_person_authors is more suitable name'
+ )
authors = []
if 'v16' in self.data:
for author in self.data['v16']:
|
scieloorg/xylose
|
135018ec4be1a30320d1f59caee922ee4a730f41
|
diff --git a/tests/test_document.py b/tests/test_document.py
index b2b37dd..46738b9 100644
--- a/tests/test_document.py
+++ b/tests/test_document.py
@@ -4386,6 +4386,112 @@ class CitationTest(unittest.TestCase):
self.assertEqual(citation.authors, [])
+ def test_analytic_person_authors(self):
+ json_citation = {}
+
+ json_citation['v18'] = [{u'_': u'It is the book title'}]
+ json_citation['v12'] = [{u'_': u'It is the chapter title'}]
+ json_citation['v10'] = [{u's': u'Sullivan', u'n': u'Mike'},
+ {u's': u'Hurricane Carter', u'n': u'Rubin'},
+ {u's': u'Maguila Rodrigues', u'n': u'Adilson'},
+ {u'n': u'Acelino Popó Freitas'},
+ {u's': u'Zé Marreta'}]
+
+ expected = [{u'given_names': u'Mike', u'surname': u'Sullivan'},
+ {u'given_names': u'Rubin', u'surname': u'Hurricane Carter'},
+ {u'given_names': u'Adilson', u'surname': u'Maguila Rodrigues'},
+ {u'given_names': u'Acelino Popó Freitas'},
+ {u'surname': u'Zé Marreta'}]
+
+ citation = Citation(json_citation)
+
+ self.assertEqual(citation.analytic_person_authors, expected)
+
+ def test_without_analytic_person_authors(self):
+ json_citation = {}
+
+ json_citation['v18'] = [{u'_': u'It is the book title'}]
+ json_citation['v12'] = [{u'_': u'It is the chapter title'}]
+
+ citation = Citation(json_citation)
+
+ self.assertEqual(citation.analytic_person_authors, None)
+
+ def test_without_analytic_person_authors_but_not_a_book_citation(self):
+ json_citation = {}
+
+ json_citation['v30'] = [{u'_': u'It is the journal title'}]
+ json_citation['v12'] = [{u'_': u'It is the article title'}]
+ json_citation['v10'] = [{u's': u'Sullivan', u'n': u'Mike'},
+ {u's': u'Hurricane Carter', u'n': u'Rubin'},
+ {u's': u'Maguila Rodrigues', u'n': u'Adilson'},
+ {u'n': u'Acelino Popó Freitas'},
+ {u's': u'Zé Marreta'}]
+
+ expected = [{u'given_names': u'Mike', u'surname': u'Sullivan'},
+ {u'given_names': u'Rubin', u'surname': u'Hurricane Carter'},
+ {u'given_names': u'Adilson', u'surname': u'Maguila Rodrigues'},
+ {u'given_names': u'Acelino Popó Freitas'},
+ {u'surname': u'Zé Marreta'}]
+
+ citation = Citation(json_citation)
+
+ self.assertEqual(citation.analytic_person_authors, expected)
+
+ def test_monographic_person_authors(self):
+ json_citation = {}
+
+ json_citation['v18'] = [{u'_': u'It is the book title'}]
+ json_citation['v16'] = [{u's': u'Sullivan', u'n': u'Mike'},
+ {u's': u'Hurricane Carter', u'n': u'Rubin'},
+ {u's': u'Maguila Rodrigues', u'n': u'Adilson'},
+ {u'n': u'Acelino Popó Freitas'},
+ {u's': u'Zé Marreta'}]
+
+ expected = [{u'given_names': u'Mike', u'surname': u'Sullivan'},
+ {u'given_names': u'Rubin', u'surname': u'Hurricane Carter'},
+ {u'given_names': u'Adilson', u'surname': u'Maguila Rodrigues'},
+ {u'given_names': u'Acelino Popó Freitas'},
+ {u'surname': u'Zé Marreta'}]
+
+ citation = Citation(json_citation)
+
+ self.assertEqual(citation.monographic_person_authors, expected)
+
+ def test_without_monographic_person_authors(self):
+ json_citation = {}
+
+ json_citation['v18'] = [{u'_': u'It is the book title'}]
+ json_citation['v16'] = []
+
+ citation = Citation(json_citation)
+
+ self.assertEqual(citation.monographic_person_authors, None)
+
+ def test_without_monographic_person_authors_but_not_a_book_citation(self):
+ json_citation = {}
+
+ json_citation['v30'] = [{u'_': u'It is the journal title'}]
+ json_citation['v12'] = [{u'_': u'It is the article title'}]
+
+ citation = Citation(json_citation)
+
+ self.assertEqual(citation.monographic_person_authors, None)
+
+ def test_pending_deprecation_warning_of_analytic_authors(self):
+ citation = Citation({})
+ with warnings.catch_warnings(record=True) as w:
+ assert citation.analytic_authors is None
+ assert len(w) == 1
+ assert issubclass(w[-1].category, PendingDeprecationWarning)
+
+ def test_pending_deprecation_warning_of_monographic_authors(self):
+ citation = Citation({})
+ with warnings.catch_warnings(record=True) as w:
+ self.assertEqual(citation.monographic_authors, None)
+ assert len(w) == 1
+ assert issubclass(w[-1].category, PendingDeprecationWarning)
+
def test_monographic_authors(self):
json_citation = {}
|
[referências] Trocar o nome dos atributos analytic_authors e monographic_authors
- De analytic_authors para analytic_person_authors
- De monographic_authors para monographic_person_authors
Indicar obsolescência
```
@property
def analytic_authors(self):
"""
This method retrieves the authors of the given citation. These authors
may correspond to an article, book analytic, link or thesis.
"""
authors = []
if 'v10' in self.data:
for author in self.data['v10']:
authordict = {}
if 's' in author:
authordict['surname'] = html_decode(author['s'])
if 'n' in author:
authordict['given_names'] = html_decode(author['n'])
if 's' in author or 'n' in author:
authors.append(authordict)
if len(authors) > 0:
return authors
@property
def monographic_authors(self):
"""
This method retrieves the authors of the given book citation. These authors may
correspond to a book monography citation.
"""
authors = []
if 'v16' in self.data:
for author in self.data['v16']:
authordict = {}
if 's' in author:
authordict['surname'] = html_decode(author['s'])
if 'n' in author:
authordict['given_names'] = html_decode(author['n'])
if 's' in author or 'n' in author:
authors.append(authordict)
if len(authors) > 0:
return authors
```
|
0.0
|
135018ec4be1a30320d1f59caee922ee4a730f41
|
[
"tests/test_document.py::CitationTest::test_analytic_person_authors",
"tests/test_document.py::CitationTest::test_monographic_person_authors",
"tests/test_document.py::CitationTest::test_pending_deprecation_warning_of_analytic_authors",
"tests/test_document.py::CitationTest::test_pending_deprecation_warning_of_monographic_authors",
"tests/test_document.py::CitationTest::test_without_analytic_person_authors",
"tests/test_document.py::CitationTest::test_without_analytic_person_authors_but_not_a_book_citation",
"tests/test_document.py::CitationTest::test_without_monographic_person_authors",
"tests/test_document.py::CitationTest::test_without_monographic_person_authors_but_not_a_book_citation"
] |
[
"tests/test_document.py::ToolsTests::test_creative_commons_html_1",
"tests/test_document.py::ToolsTests::test_creative_commons_html_2",
"tests/test_document.py::ToolsTests::test_creative_commons_html_3",
"tests/test_document.py::ToolsTests::test_creative_commons_html_4",
"tests/test_document.py::ToolsTests::test_creative_commons_html_5",
"tests/test_document.py::ToolsTests::test_creative_commons_html_6",
"tests/test_document.py::ToolsTests::test_creative_commons_text_1",
"tests/test_document.py::ToolsTests::test_creative_commons_text_2",
"tests/test_document.py::ToolsTests::test_creative_commons_text_3",
"tests/test_document.py::ToolsTests::test_creative_commons_text_4",
"tests/test_document.py::ToolsTests::test_creative_commons_text_5",
"tests/test_document.py::ToolsTests::test_creative_commons_text_6",
"tests/test_document.py::ToolsTests::test_creative_commons_text_7",
"tests/test_document.py::ToolsTests::test_creative_commons_text_8",
"tests/test_document.py::ToolsTests::test_get_date_wrong_day",
"tests/test_document.py::ToolsTests::test_get_date_wrong_day_month",
"tests/test_document.py::ToolsTests::test_get_date_wrong_day_month_not_int",
"tests/test_document.py::ToolsTests::test_get_date_wrong_day_not_int",
"tests/test_document.py::ToolsTests::test_get_date_wrong_month_not_int",
"tests/test_document.py::ToolsTests::test_get_date_year",
"tests/test_document.py::ToolsTests::test_get_date_year_day",
"tests/test_document.py::ToolsTests::test_get_date_year_month",
"tests/test_document.py::ToolsTests::test_get_date_year_month_day",
"tests/test_document.py::ToolsTests::test_get_date_year_month_day_31",
"tests/test_document.py::ToolsTests::test_get_language_iso639_1_defined",
"tests/test_document.py::ToolsTests::test_get_language_iso639_1_undefined",
"tests/test_document.py::ToolsTests::test_get_language_iso639_2_defined",
"tests/test_document.py::ToolsTests::test_get_language_iso639_2_undefined",
"tests/test_document.py::ToolsTests::test_get_language_without_iso_format",
"tests/test_document.py::IssueTests::test_assets_code_month",
"tests/test_document.py::IssueTests::test_collection_acronym",
"tests/test_document.py::IssueTests::test_creation_date",
"tests/test_document.py::IssueTests::test_creation_date_1",
"tests/test_document.py::IssueTests::test_creation_date_2",
"tests/test_document.py::IssueTests::test_ctrl_vocabulary",
"tests/test_document.py::IssueTests::test_ctrl_vocabulary_out_of_choices",
"tests/test_document.py::IssueTests::test_is_ahead",
"tests/test_document.py::IssueTests::test_is_ahead_1",
"tests/test_document.py::IssueTests::test_is_marked_up",
"tests/test_document.py::IssueTests::test_is_press_release_false_1",
"tests/test_document.py::IssueTests::test_is_press_release_false_2",
"tests/test_document.py::IssueTests::test_is_press_release_true",
"tests/test_document.py::IssueTests::test_issue",
"tests/test_document.py::IssueTests::test_issue_journal_without_journal_metadata",
"tests/test_document.py::IssueTests::test_issue_label",
"tests/test_document.py::IssueTests::test_issue_url",
"tests/test_document.py::IssueTests::test_order",
"tests/test_document.py::IssueTests::test_permission_from_journal",
"tests/test_document.py::IssueTests::test_permission_id",
"tests/test_document.py::IssueTests::test_permission_t0",
"tests/test_document.py::IssueTests::test_permission_t1",
"tests/test_document.py::IssueTests::test_permission_t2",
"tests/test_document.py::IssueTests::test_permission_t3",
"tests/test_document.py::IssueTests::test_permission_t4",
"tests/test_document.py::IssueTests::test_permission_text",
"tests/test_document.py::IssueTests::test_permission_url",
"tests/test_document.py::IssueTests::test_permission_without_v540",
"tests/test_document.py::IssueTests::test_permission_without_v540_t",
"tests/test_document.py::IssueTests::test_processing_date",
"tests/test_document.py::IssueTests::test_processing_date_1",
"tests/test_document.py::IssueTests::test_publication_date",
"tests/test_document.py::IssueTests::test_sections",
"tests/test_document.py::IssueTests::test_standard",
"tests/test_document.py::IssueTests::test_standard_out_of_choices",
"tests/test_document.py::IssueTests::test_start_end_month",
"tests/test_document.py::IssueTests::test_start_end_month_1",
"tests/test_document.py::IssueTests::test_start_end_month_2",
"tests/test_document.py::IssueTests::test_start_end_month_3",
"tests/test_document.py::IssueTests::test_start_end_month_4",
"tests/test_document.py::IssueTests::test_start_end_month_5",
"tests/test_document.py::IssueTests::test_start_end_month_6",
"tests/test_document.py::IssueTests::test_supplement_number",
"tests/test_document.py::IssueTests::test_supplement_volume",
"tests/test_document.py::IssueTests::test_title_titles",
"tests/test_document.py::IssueTests::test_title_titles_1",
"tests/test_document.py::IssueTests::test_title_without_titles",
"tests/test_document.py::IssueTests::test_total_documents",
"tests/test_document.py::IssueTests::test_total_documents_without_data",
"tests/test_document.py::IssueTests::test_type_pressrelease",
"tests/test_document.py::IssueTests::test_type_regular",
"tests/test_document.py::IssueTests::test_type_supplement_1",
"tests/test_document.py::IssueTests::test_type_supplement_2",
"tests/test_document.py::IssueTests::test_update_date",
"tests/test_document.py::IssueTests::test_update_date_1",
"tests/test_document.py::IssueTests::test_update_date_2",
"tests/test_document.py::IssueTests::test_update_date_3",
"tests/test_document.py::IssueTests::test_volume",
"tests/test_document.py::IssueTests::test_without_ctrl_vocabulary",
"tests/test_document.py::IssueTests::test_without_ctrl_vocabulary_also_in_journal",
"tests/test_document.py::IssueTests::test_without_issue",
"tests/test_document.py::IssueTests::test_without_processing_date",
"tests/test_document.py::IssueTests::test_without_publication_date",
"tests/test_document.py::IssueTests::test_without_standard",
"tests/test_document.py::IssueTests::test_without_standard_also_in_journal",
"tests/test_document.py::IssueTests::test_without_suplement_number",
"tests/test_document.py::IssueTests::test_without_supplement_volume",
"tests/test_document.py::IssueTests::test_without_volume",
"tests/test_document.py::JournalTests::test_abstract_languages",
"tests/test_document.py::JournalTests::test_abstract_languages_without_v350",
"tests/test_document.py::JournalTests::test_any_issn_priority_electronic",
"tests/test_document.py::JournalTests::test_any_issn_priority_electronic_without_electronic",
"tests/test_document.py::JournalTests::test_any_issn_priority_print",
"tests/test_document.py::JournalTests::test_any_issn_priority_print_without_print",
"tests/test_document.py::JournalTests::test_cnn_code",
"tests/test_document.py::JournalTests::test_collection_acronym",
"tests/test_document.py::JournalTests::test_creation_date",
"tests/test_document.py::JournalTests::test_ctrl_vocabulary",
"tests/test_document.py::JournalTests::test_ctrl_vocabulary_out_of_choices",
"tests/test_document.py::JournalTests::test_current_status",
"tests/test_document.py::JournalTests::test_current_status_lots_of_changes_study_case_1",
"tests/test_document.py::JournalTests::test_current_status_some_changes",
"tests/test_document.py::JournalTests::test_current_without_v51",
"tests/test_document.py::JournalTests::test_editor_address",
"tests/test_document.py::JournalTests::test_editor_address_without_data",
"tests/test_document.py::JournalTests::test_editor_email",
"tests/test_document.py::JournalTests::test_editor_email_without_data",
"tests/test_document.py::JournalTests::test_first_number",
"tests/test_document.py::JournalTests::test_first_number_1",
"tests/test_document.py::JournalTests::test_first_volume",
"tests/test_document.py::JournalTests::test_first_volume_1",
"tests/test_document.py::JournalTests::test_first_year",
"tests/test_document.py::JournalTests::test_first_year_1",
"tests/test_document.py::JournalTests::test_first_year_2",
"tests/test_document.py::JournalTests::test_first_year_3",
"tests/test_document.py::JournalTests::test_first_year_4",
"tests/test_document.py::JournalTests::test_in_ahci",
"tests/test_document.py::JournalTests::test_in_scie",
"tests/test_document.py::JournalTests::test_in_ssci",
"tests/test_document.py::JournalTests::test_institutional_url",
"tests/test_document.py::JournalTests::test_is_publishing_model_continuous",
"tests/test_document.py::JournalTests::test_is_publishing_model_continuous_false_with_field_regular",
"tests/test_document.py::JournalTests::test_is_publishing_model_continuous_false_with_field_undefined",
"tests/test_document.py::JournalTests::test_is_publishing_model_continuous_false_without_field",
"tests/test_document.py::JournalTests::test_is_publishing_model_continuous_true",
"tests/test_document.py::JournalTests::test_is_publishing_model_regular_1",
"tests/test_document.py::JournalTests::test_is_publishing_model_regular_2",
"tests/test_document.py::JournalTests::test_journal",
"tests/test_document.py::JournalTests::test_journal_abbreviated_title",
"tests/test_document.py::JournalTests::test_journal_acronym",
"tests/test_document.py::JournalTests::test_journal_copyrighter",
"tests/test_document.py::JournalTests::test_journal_copyrighter_without_copyright",
"tests/test_document.py::JournalTests::test_journal_fulltitle",
"tests/test_document.py::JournalTests::test_journal_fulltitle_without_subtitle",
"tests/test_document.py::JournalTests::test_journal_fulltitle_without_title",
"tests/test_document.py::JournalTests::test_journal_mission",
"tests/test_document.py::JournalTests::test_journal_mission_without_language_key",
"tests/test_document.py::JournalTests::test_journal_mission_without_mission",
"tests/test_document.py::JournalTests::test_journal_mission_without_mission_text",
"tests/test_document.py::JournalTests::test_journal_mission_without_mission_text_and_language",
"tests/test_document.py::JournalTests::test_journal_other_title_without_other_titles",
"tests/test_document.py::JournalTests::test_journal_other_titles",
"tests/test_document.py::JournalTests::test_journal_publisher_country",
"tests/test_document.py::JournalTests::test_journal_publisher_country_not_findable_code",
"tests/test_document.py::JournalTests::test_journal_publisher_country_without_country",
"tests/test_document.py::JournalTests::test_journal_sponsors",
"tests/test_document.py::JournalTests::test_journal_sponsors_with_empty_items",
"tests/test_document.py::JournalTests::test_journal_sponsors_without_sponsors",
"tests/test_document.py::JournalTests::test_journal_subtitle",
"tests/test_document.py::JournalTests::test_journal_title",
"tests/test_document.py::JournalTests::test_journal_title_nlm",
"tests/test_document.py::JournalTests::test_journal_url",
"tests/test_document.py::JournalTests::test_journal_without_subtitle",
"tests/test_document.py::JournalTests::test_languages",
"tests/test_document.py::JournalTests::test_languages_without_v350",
"tests/test_document.py::JournalTests::test_last_cnn_code_1",
"tests/test_document.py::JournalTests::test_last_number",
"tests/test_document.py::JournalTests::test_last_number_1",
"tests/test_document.py::JournalTests::test_last_volume",
"tests/test_document.py::JournalTests::test_last_volume_1",
"tests/test_document.py::JournalTests::test_last_year",
"tests/test_document.py::JournalTests::test_last_year_1",
"tests/test_document.py::JournalTests::test_last_year_2",
"tests/test_document.py::JournalTests::test_last_year_3",
"tests/test_document.py::JournalTests::test_last_year_4",
"tests/test_document.py::JournalTests::test_load_issn_with_v435",
"tests/test_document.py::JournalTests::test_load_issn_with_v935_and_v35_ONLINE",
"tests/test_document.py::JournalTests::test_load_issn_with_v935_and_v35_PRINT",
"tests/test_document.py::JournalTests::test_load_issn_with_v935_equal_v400_and_v35_ONLINE",
"tests/test_document.py::JournalTests::test_load_issn_with_v935_equal_v400_and_v35_PRINT",
"tests/test_document.py::JournalTests::test_load_issn_with_v935_without_v35",
"tests/test_document.py::JournalTests::test_load_issn_without_v935_and_v35_ONLINE",
"tests/test_document.py::JournalTests::test_load_issn_without_v935_and_v35_PRINT",
"tests/test_document.py::JournalTests::test_load_issn_without_v935_without_v35",
"tests/test_document.py::JournalTests::test_periodicity",
"tests/test_document.py::JournalTests::test_periodicity_in_months",
"tests/test_document.py::JournalTests::test_periodicity_in_months_out_of_choices",
"tests/test_document.py::JournalTests::test_periodicity_out_of_choices",
"tests/test_document.py::JournalTests::test_permission_id",
"tests/test_document.py::JournalTests::test_permission_t0",
"tests/test_document.py::JournalTests::test_permission_t1",
"tests/test_document.py::JournalTests::test_permission_t2",
"tests/test_document.py::JournalTests::test_permission_t3",
"tests/test_document.py::JournalTests::test_permission_t4",
"tests/test_document.py::JournalTests::test_permission_text",
"tests/test_document.py::JournalTests::test_permission_url",
"tests/test_document.py::JournalTests::test_permission_without_v540",
"tests/test_document.py::JournalTests::test_permission_without_v540_t",
"tests/test_document.py::JournalTests::test_plevel",
"tests/test_document.py::JournalTests::test_plevel_out_of_choices",
"tests/test_document.py::JournalTests::test_previous_title",
"tests/test_document.py::JournalTests::test_previous_title_without_data",
"tests/test_document.py::JournalTests::test_publisher_city",
"tests/test_document.py::JournalTests::test_publisher_loc",
"tests/test_document.py::JournalTests::test_publisher_name",
"tests/test_document.py::JournalTests::test_publisher_state",
"tests/test_document.py::JournalTests::test_scielo_issn",
"tests/test_document.py::JournalTests::test_secs_code",
"tests/test_document.py::JournalTests::test_standard",
"tests/test_document.py::JournalTests::test_standard_out_of_choices",
"tests/test_document.py::JournalTests::test_status",
"tests/test_document.py::JournalTests::test_status_lots_of_changes",
"tests/test_document.py::JournalTests::test_status_lots_of_changes_study_case_1",
"tests/test_document.py::JournalTests::test_status_lots_of_changes_with_reason",
"tests/test_document.py::JournalTests::test_status_some_changes",
"tests/test_document.py::JournalTests::test_status_without_v51",
"tests/test_document.py::JournalTests::test_subject_areas",
"tests/test_document.py::JournalTests::test_subject_descriptors",
"tests/test_document.py::JournalTests::test_subject_index_coverage",
"tests/test_document.py::JournalTests::test_submission_url",
"tests/test_document.py::JournalTests::test_update_date",
"tests/test_document.py::JournalTests::test_without_ctrl_vocabulary",
"tests/test_document.py::JournalTests::test_without_index_coverage",
"tests/test_document.py::JournalTests::test_without_institutional_url",
"tests/test_document.py::JournalTests::test_without_journal_abbreviated_title",
"tests/test_document.py::JournalTests::test_without_journal_acronym",
"tests/test_document.py::JournalTests::test_without_journal_title",
"tests/test_document.py::JournalTests::test_without_journal_title_nlm",
"tests/test_document.py::JournalTests::test_without_journal_url",
"tests/test_document.py::JournalTests::test_without_periodicity",
"tests/test_document.py::JournalTests::test_without_periodicity_in_months",
"tests/test_document.py::JournalTests::test_without_plevel",
"tests/test_document.py::JournalTests::test_without_publisher_city",
"tests/test_document.py::JournalTests::test_without_publisher_loc",
"tests/test_document.py::JournalTests::test_without_publisher_name",
"tests/test_document.py::JournalTests::test_without_publisher_state",
"tests/test_document.py::JournalTests::test_without_scielo_domain",
"tests/test_document.py::JournalTests::test_without_scielo_domain_title_v690",
"tests/test_document.py::JournalTests::test_without_secs_code",
"tests/test_document.py::JournalTests::test_without_standard",
"tests/test_document.py::JournalTests::test_without_subject_areas",
"tests/test_document.py::JournalTests::test_without_subject_descriptors",
"tests/test_document.py::JournalTests::test_without_wos_citation_indexes",
"tests/test_document.py::JournalTests::test_without_wos_subject_areas",
"tests/test_document.py::JournalTests::test_wos_citation_indexes",
"tests/test_document.py::JournalTests::test_wos_subject_areas",
"tests/test_document.py::ArticleTests::test_abstracts",
"tests/test_document.py::ArticleTests::test_abstracts_iso639_2",
"tests/test_document.py::ArticleTests::test_abstracts_without_v83",
"tests/test_document.py::ArticleTests::test_acceptance_date",
"tests/test_document.py::ArticleTests::test_affiliation_just_with_affiliation_name",
"tests/test_document.py::ArticleTests::test_affiliation_with_country_iso_3166",
"tests/test_document.py::ArticleTests::test_affiliation_without_affiliation_name",
"tests/test_document.py::ArticleTests::test_affiliations",
"tests/test_document.py::ArticleTests::test_ahead_publication_date",
"tests/test_document.py::ArticleTests::test_article",
"tests/test_document.py::ArticleTests::test_author_with_two_affiliations",
"tests/test_document.py::ArticleTests::test_author_with_two_role",
"tests/test_document.py::ArticleTests::test_author_without_affiliations",
"tests/test_document.py::ArticleTests::test_author_without_surname_and_given_names",
"tests/test_document.py::ArticleTests::test_authors",
"tests/test_document.py::ArticleTests::test_collection_acronym",
"tests/test_document.py::ArticleTests::test_collection_acronym_priorizing_collection",
"tests/test_document.py::ArticleTests::test_collection_acronym_retrieving_v992",
"tests/test_document.py::ArticleTests::test_collection_name_brazil",
"tests/test_document.py::ArticleTests::test_collection_name_undefined",
"tests/test_document.py::ArticleTests::test_corporative_authors",
"tests/test_document.py::ArticleTests::test_creation_date",
"tests/test_document.py::ArticleTests::test_creation_date_1",
"tests/test_document.py::ArticleTests::test_creation_date_2",
"tests/test_document.py::ArticleTests::test_data_model_version_html",
"tests/test_document.py::ArticleTests::test_data_model_version_html_1",
"tests/test_document.py::ArticleTests::test_data_model_version_xml",
"tests/test_document.py::ArticleTests::test_document_type",
"tests/test_document.py::ArticleTests::test_document_without_issue_metadata",
"tests/test_document.py::ArticleTests::test_document_without_journal_metadata",
"tests/test_document.py::ArticleTests::test_doi",
"tests/test_document.py::ArticleTests::test_doi_clean_1",
"tests/test_document.py::ArticleTests::test_doi_clean_2",
"tests/test_document.py::ArticleTests::test_doi_v237",
"tests/test_document.py::ArticleTests::test_e_location",
"tests/test_document.py::ArticleTests::test_end_page_loaded_crazy_legacy_way_1",
"tests/test_document.py::ArticleTests::test_end_page_loaded_crazy_legacy_way_2",
"tests/test_document.py::ArticleTests::test_end_page_loaded_through_xml",
"tests/test_document.py::ArticleTests::test_file_code",
"tests/test_document.py::ArticleTests::test_file_code_crazy_slashs_1",
"tests/test_document.py::ArticleTests::test_file_code_crazy_slashs_2",
"tests/test_document.py::ArticleTests::test_first_author",
"tests/test_document.py::ArticleTests::test_first_author_without_author",
"tests/test_document.py::ArticleTests::test_fulltexts_field_fulltexts",
"tests/test_document.py::ArticleTests::test_fulltexts_without_field_fulltexts",
"tests/test_document.py::ArticleTests::test_html_url",
"tests/test_document.py::ArticleTests::test_invalid_document_type",
"tests/test_document.py::ArticleTests::test_issue_url",
"tests/test_document.py::ArticleTests::test_journal_abbreviated_title",
"tests/test_document.py::ArticleTests::test_keywords",
"tests/test_document.py::ArticleTests::test_keywords_iso639_2",
"tests/test_document.py::ArticleTests::test_keywords_with_undefined_language",
"tests/test_document.py::ArticleTests::test_keywords_without_subfield_k",
"tests/test_document.py::ArticleTests::test_keywords_without_subfield_l",
"tests/test_document.py::ArticleTests::test_languages_field_fulltexts",
"tests/test_document.py::ArticleTests::test_languages_field_v40",
"tests/test_document.py::ArticleTests::test_last_page",
"tests/test_document.py::ArticleTests::test_mixed_affiliations_1",
"tests/test_document.py::ArticleTests::test_normalized_affiliations",
"tests/test_document.py::ArticleTests::test_normalized_affiliations_undefined_ISO_3166_CODE",
"tests/test_document.py::ArticleTests::test_normalized_affiliations_without_p",
"tests/test_document.py::ArticleTests::test_order",
"tests/test_document.py::ArticleTests::test_original_abstract_with_just_one_language_defined",
"tests/test_document.py::ArticleTests::test_original_abstract_with_language_defined",
"tests/test_document.py::ArticleTests::test_original_abstract_with_language_defined_but_different_of_the_article_original_language",
"tests/test_document.py::ArticleTests::test_original_abstract_without_language_defined",
"tests/test_document.py::ArticleTests::test_original_html_field_body",
"tests/test_document.py::ArticleTests::test_original_language_invalid_iso639_2",
"tests/test_document.py::ArticleTests::test_original_language_iso639_2",
"tests/test_document.py::ArticleTests::test_original_language_original",
"tests/test_document.py::ArticleTests::test_original_section_field_v49",
"tests/test_document.py::ArticleTests::test_original_title_subfield_t",
"tests/test_document.py::ArticleTests::test_original_title_with_just_one_language_defined",
"tests/test_document.py::ArticleTests::test_original_title_with_language_defined",
"tests/test_document.py::ArticleTests::test_original_title_with_language_defined_but_different_of_the_article_original_language",
"tests/test_document.py::ArticleTests::test_original_title_without_language_defined",
"tests/test_document.py::ArticleTests::test_pdf_url",
"tests/test_document.py::ArticleTests::test_processing_date",
"tests/test_document.py::ArticleTests::test_processing_date_1",
"tests/test_document.py::ArticleTests::test_project_name",
"tests/test_document.py::ArticleTests::test_project_sponsors",
"tests/test_document.py::ArticleTests::test_publication_contract",
"tests/test_document.py::ArticleTests::test_publication_date_with_article_date",
"tests/test_document.py::ArticleTests::test_publication_date_without_article_date",
"tests/test_document.py::ArticleTests::test_publisher_ahead_id",
"tests/test_document.py::ArticleTests::test_publisher_ahead_id_none",
"tests/test_document.py::ArticleTests::test_publisher_id",
"tests/test_document.py::ArticleTests::test_receive_date",
"tests/test_document.py::ArticleTests::test_review_date",
"tests/test_document.py::ArticleTests::test_section_code_field_v49",
"tests/test_document.py::ArticleTests::test_section_code_nd_field_v49",
"tests/test_document.py::ArticleTests::test_section_code_without_field_v49",
"tests/test_document.py::ArticleTests::test_section_field_v49",
"tests/test_document.py::ArticleTests::test_section_nd_field_v49",
"tests/test_document.py::ArticleTests::test_section_without_field_section",
"tests/test_document.py::ArticleTests::test_section_without_field_v49",
"tests/test_document.py::ArticleTests::test_start_page",
"tests/test_document.py::ArticleTests::test_start_page_loaded_crazy_legacy_way_1",
"tests/test_document.py::ArticleTests::test_start_page_loaded_crazy_legacy_way_2",
"tests/test_document.py::ArticleTests::test_start_page_loaded_through_xml",
"tests/test_document.py::ArticleTests::test_start_page_sec",
"tests/test_document.py::ArticleTests::test_start_page_sec_0",
"tests/test_document.py::ArticleTests::test_start_page_sec_0_loaded_through_xml",
"tests/test_document.py::ArticleTests::test_start_page_sec_loaded_through_xml",
"tests/test_document.py::ArticleTests::test_subject_areas",
"tests/test_document.py::ArticleTests::test_thesis_degree",
"tests/test_document.py::ArticleTests::test_thesis_organization",
"tests/test_document.py::ArticleTests::test_thesis_organization_and_division",
"tests/test_document.py::ArticleTests::test_thesis_organization_without_name",
"tests/test_document.py::ArticleTests::test_translated_abstracts",
"tests/test_document.py::ArticleTests::test_translated_abstracts_without_v83",
"tests/test_document.py::ArticleTests::test_translated_abtracts_iso639_2",
"tests/test_document.py::ArticleTests::test_translated_htmls_field_body",
"tests/test_document.py::ArticleTests::test_translated_section_field_v49",
"tests/test_document.py::ArticleTests::test_translated_titles",
"tests/test_document.py::ArticleTests::test_translated_titles_iso639_2",
"tests/test_document.py::ArticleTests::test_translated_titles_without_v12",
"tests/test_document.py::ArticleTests::test_update_date",
"tests/test_document.py::ArticleTests::test_update_date_1",
"tests/test_document.py::ArticleTests::test_update_date_2",
"tests/test_document.py::ArticleTests::test_update_date_3",
"tests/test_document.py::ArticleTests::test_whitwout_acceptance_date",
"tests/test_document.py::ArticleTests::test_whitwout_ahead_publication_date",
"tests/test_document.py::ArticleTests::test_whitwout_receive_date",
"tests/test_document.py::ArticleTests::test_whitwout_review_date",
"tests/test_document.py::ArticleTests::test_without_affiliations",
"tests/test_document.py::ArticleTests::test_without_authors",
"tests/test_document.py::ArticleTests::test_without_citations",
"tests/test_document.py::ArticleTests::test_without_collection_acronym",
"tests/test_document.py::ArticleTests::test_without_corporative_authors",
"tests/test_document.py::ArticleTests::test_without_document_type",
"tests/test_document.py::ArticleTests::test_without_doi",
"tests/test_document.py::ArticleTests::test_without_e_location",
"tests/test_document.py::ArticleTests::test_without_html_url",
"tests/test_document.py::ArticleTests::test_without_issue_url",
"tests/test_document.py::ArticleTests::test_without_journal_abbreviated_title",
"tests/test_document.py::ArticleTests::test_without_keywords",
"tests/test_document.py::ArticleTests::test_without_last_page",
"tests/test_document.py::ArticleTests::test_without_normalized_affiliations",
"tests/test_document.py::ArticleTests::test_without_order",
"tests/test_document.py::ArticleTests::test_without_original_abstract",
"tests/test_document.py::ArticleTests::test_without_original_title",
"tests/test_document.py::ArticleTests::test_without_pages",
"tests/test_document.py::ArticleTests::test_without_pdf_url",
"tests/test_document.py::ArticleTests::test_without_processing_date",
"tests/test_document.py::ArticleTests::test_without_project_name",
"tests/test_document.py::ArticleTests::test_without_project_sponsor",
"tests/test_document.py::ArticleTests::test_without_publication_contract",
"tests/test_document.py::ArticleTests::test_without_publication_date",
"tests/test_document.py::ArticleTests::test_without_publisher_id",
"tests/test_document.py::ArticleTests::test_without_scielo_domain",
"tests/test_document.py::ArticleTests::test_without_scielo_domain_article_v69",
"tests/test_document.py::ArticleTests::test_without_scielo_domain_article_v69_and_with_title_v690",
"tests/test_document.py::ArticleTests::test_without_scielo_domain_title_v690",
"tests/test_document.py::ArticleTests::test_without_start_page",
"tests/test_document.py::ArticleTests::test_without_subject_areas",
"tests/test_document.py::ArticleTests::test_without_thesis_degree",
"tests/test_document.py::ArticleTests::test_without_thesis_organization",
"tests/test_document.py::ArticleTests::test_without_wos_citation_indexes",
"tests/test_document.py::ArticleTests::test_without_wos_subject_areas",
"tests/test_document.py::ArticleTests::test_wos_citation_indexes",
"tests/test_document.py::ArticleTests::test_wos_subject_areas",
"tests/test_document.py::CitationTest::test_a_link_access_date",
"tests/test_document.py::CitationTest::test_a_link_access_date_absent_v65",
"tests/test_document.py::CitationTest::test_analytic_institution_authors_for_a_book_citation",
"tests/test_document.py::CitationTest::test_analytic_institution_authors_for_an_article_citation",
"tests/test_document.py::CitationTest::test_analytic_institution_for_a_article_citation",
"tests/test_document.py::CitationTest::test_analytic_institution_for_a_book_citation",
"tests/test_document.py::CitationTest::test_article_title",
"tests/test_document.py::CitationTest::test_article_without_title",
"tests/test_document.py::CitationTest::test_authors_article",
"tests/test_document.py::CitationTest::test_authors_book",
"tests/test_document.py::CitationTest::test_authors_link",
"tests/test_document.py::CitationTest::test_authors_thesis",
"tests/test_document.py::CitationTest::test_book_chapter_title",
"tests/test_document.py::CitationTest::test_book_edition",
"tests/test_document.py::CitationTest::test_book_volume",
"tests/test_document.py::CitationTest::test_book_without_chapter_title",
"tests/test_document.py::CitationTest::test_citation_sample_congress",
"tests/test_document.py::CitationTest::test_citation_sample_link",
"tests/test_document.py::CitationTest::test_citation_sample_link_without_comment",
"tests/test_document.py::CitationTest::test_conference_edition",
"tests/test_document.py::CitationTest::test_conference_name",
"tests/test_document.py::CitationTest::test_conference_sponsor",
"tests/test_document.py::CitationTest::test_conference_without_name",
"tests/test_document.py::CitationTest::test_conference_without_sponsor",
"tests/test_document.py::CitationTest::test_date",
"tests/test_document.py::CitationTest::test_doi",
"tests/test_document.py::CitationTest::test_editor",
"tests/test_document.py::CitationTest::test_elocation_14",
"tests/test_document.py::CitationTest::test_elocation_514",
"tests/test_document.py::CitationTest::test_end_page_14",
"tests/test_document.py::CitationTest::test_end_page_514",
"tests/test_document.py::CitationTest::test_end_page_withdout_data",
"tests/test_document.py::CitationTest::test_first_author_article",
"tests/test_document.py::CitationTest::test_first_author_book",
"tests/test_document.py::CitationTest::test_first_author_link",
"tests/test_document.py::CitationTest::test_first_author_thesis",
"tests/test_document.py::CitationTest::test_first_author_without_monographic_authors",
"tests/test_document.py::CitationTest::test_first_author_without_monographic_authors_but_not_a_book_citation",
"tests/test_document.py::CitationTest::test_index_number",
"tests/test_document.py::CitationTest::test_institutions_all_fields",
"tests/test_document.py::CitationTest::test_institutions_v11",
"tests/test_document.py::CitationTest::test_institutions_v17",
"tests/test_document.py::CitationTest::test_institutions_v29",
"tests/test_document.py::CitationTest::test_institutions_v50",
"tests/test_document.py::CitationTest::test_institutions_v58",
"tests/test_document.py::CitationTest::test_invalid_edition",
"tests/test_document.py::CitationTest::test_isbn",
"tests/test_document.py::CitationTest::test_isbn_but_not_a_book",
"tests/test_document.py::CitationTest::test_issn",
"tests/test_document.py::CitationTest::test_issn_but_not_an_article",
"tests/test_document.py::CitationTest::test_issue_part",
"tests/test_document.py::CitationTest::test_issue_title",
"tests/test_document.py::CitationTest::test_journal_issue",
"tests/test_document.py::CitationTest::test_journal_volume",
"tests/test_document.py::CitationTest::test_link",
"tests/test_document.py::CitationTest::test_link_title",
"tests/test_document.py::CitationTest::test_link_without_title",
"tests/test_document.py::CitationTest::test_mixed_citation_1",
"tests/test_document.py::CitationTest::test_mixed_citation_10",
"tests/test_document.py::CitationTest::test_mixed_citation_11",
"tests/test_document.py::CitationTest::test_mixed_citation_12",
"tests/test_document.py::CitationTest::test_mixed_citation_13",
"tests/test_document.py::CitationTest::test_mixed_citation_14",
"tests/test_document.py::CitationTest::test_mixed_citation_15",
"tests/test_document.py::CitationTest::test_mixed_citation_16",
"tests/test_document.py::CitationTest::test_mixed_citation_17",
"tests/test_document.py::CitationTest::test_mixed_citation_18",
"tests/test_document.py::CitationTest::test_mixed_citation_19",
"tests/test_document.py::CitationTest::test_mixed_citation_2",
"tests/test_document.py::CitationTest::test_mixed_citation_3",
"tests/test_document.py::CitationTest::test_mixed_citation_4",
"tests/test_document.py::CitationTest::test_mixed_citation_5",
"tests/test_document.py::CitationTest::test_mixed_citation_6",
"tests/test_document.py::CitationTest::test_mixed_citation_7",
"tests/test_document.py::CitationTest::test_mixed_citation_8",
"tests/test_document.py::CitationTest::test_mixed_citation_9",
"tests/test_document.py::CitationTest::test_mixed_citation_without_data",
"tests/test_document.py::CitationTest::test_monographic_authors",
"tests/test_document.py::CitationTest::test_monographic_first_author",
"tests/test_document.py::CitationTest::test_monographic_institution_authors_for_a_book_citation",
"tests/test_document.py::CitationTest::test_monographic_institution_authors_for_an_article_citation",
"tests/test_document.py::CitationTest::test_pages_14",
"tests/test_document.py::CitationTest::test_pages_514",
"tests/test_document.py::CitationTest::test_pages_withdout_data",
"tests/test_document.py::CitationTest::test_pending_deprecation_warning_of_analytic_institution",
"tests/test_document.py::CitationTest::test_pending_deprecation_warning_of_monographic_institution",
"tests/test_document.py::CitationTest::test_publication_type_article",
"tests/test_document.py::CitationTest::test_publication_type_book",
"tests/test_document.py::CitationTest::test_publication_type_book_chapter",
"tests/test_document.py::CitationTest::test_publication_type_conference",
"tests/test_document.py::CitationTest::test_publication_type_link",
"tests/test_document.py::CitationTest::test_publication_type_thesis",
"tests/test_document.py::CitationTest::test_publication_type_undefined",
"tests/test_document.py::CitationTest::test_publisher",
"tests/test_document.py::CitationTest::test_publisher_address",
"tests/test_document.py::CitationTest::test_publisher_address_without_e",
"tests/test_document.py::CitationTest::test_series_book",
"tests/test_document.py::CitationTest::test_series_but_neither_journal_book_or_conference_citation",
"tests/test_document.py::CitationTest::test_series_conference",
"tests/test_document.py::CitationTest::test_series_journal",
"tests/test_document.py::CitationTest::test_source_book_title",
"tests/test_document.py::CitationTest::test_source_journal",
"tests/test_document.py::CitationTest::test_source_journal_without_journal_title",
"tests/test_document.py::CitationTest::test_sponsor",
"tests/test_document.py::CitationTest::test_start_page_14",
"tests/test_document.py::CitationTest::test_start_page_514",
"tests/test_document.py::CitationTest::test_start_page_withdout_data",
"tests/test_document.py::CitationTest::test_thesis_institution",
"tests/test_document.py::CitationTest::test_thesis_title",
"tests/test_document.py::CitationTest::test_thesis_without_title",
"tests/test_document.py::CitationTest::test_title_when_article_citation",
"tests/test_document.py::CitationTest::test_title_when_conference_citation",
"tests/test_document.py::CitationTest::test_title_when_link_citation",
"tests/test_document.py::CitationTest::test_title_when_thesis_citation",
"tests/test_document.py::CitationTest::test_with_volume_but_not_a_journal_article_neither_a_book",
"tests/test_document.py::CitationTest::test_without_analytic_institution",
"tests/test_document.py::CitationTest::test_without_authors",
"tests/test_document.py::CitationTest::test_without_date",
"tests/test_document.py::CitationTest::test_without_doi",
"tests/test_document.py::CitationTest::test_without_edition",
"tests/test_document.py::CitationTest::test_without_editor",
"tests/test_document.py::CitationTest::test_without_first_author",
"tests/test_document.py::CitationTest::test_without_index_number",
"tests/test_document.py::CitationTest::test_without_institutions",
"tests/test_document.py::CitationTest::test_without_issue",
"tests/test_document.py::CitationTest::test_without_issue_part",
"tests/test_document.py::CitationTest::test_without_issue_title",
"tests/test_document.py::CitationTest::test_without_link",
"tests/test_document.py::CitationTest::test_without_monographic_authors",
"tests/test_document.py::CitationTest::test_without_monographic_authors_but_not_a_book_citation",
"tests/test_document.py::CitationTest::test_without_publisher",
"tests/test_document.py::CitationTest::test_without_publisher_address",
"tests/test_document.py::CitationTest::test_without_series",
"tests/test_document.py::CitationTest::test_without_sponsor",
"tests/test_document.py::CitationTest::test_without_thesis_institution",
"tests/test_document.py::CitationTest::test_without_volume"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2018-08-02 17:20:25+00:00
|
bsd-2-clause
| 5,354 |
|
scikit-build__scikit-build-105
|
diff --git a/skbuild/cmaker.py b/skbuild/cmaker.py
index 9030c1e..2c7d7f5 100644
--- a/skbuild/cmaker.py
+++ b/skbuild/cmaker.py
@@ -9,6 +9,8 @@ import shlex
import sys
import sysconfig
+from subprocess import CalledProcessError
+
from .platform_specifics import get_platform
from .exceptions import SKBuildError
@@ -62,10 +64,11 @@ def _touch_init(folder):
class CMaker(object):
def __init__(self, **defines):
- if platform.system() != 'Windows':
- rtn = subprocess.call(['which', 'cmake'])
- if rtn != 0:
- sys.exit('CMake is not installed, aborting build.')
+ # verify that CMake is installed
+ try:
+ subprocess.check_call(['cmake', '--version'])
+ except (OSError, CalledProcessError):
+ raise SKBuildError('CMake is not installed, aborting build.')
self.platform = get_platform()
@@ -93,8 +96,9 @@ class CMaker(object):
generator_id = self.platform.get_best_generator(generator_id)
if generator_id is None:
- sys.exit("Could not get working generator for your system."
- " Aborting build.")
+ raise SKBuildError(
+ "Could not get working generator for your system."
+ " Aborting build.")
if not os.path.exists(CMAKE_BUILD_DIR):
os.makedirs(CMAKE_BUILD_DIR)
@@ -137,11 +141,20 @@ class CMaker(object):
# changes dir to cmake_build and calls cmake's configure step
# to generate makefile
- rtn = subprocess.check_call(cmd, cwd=CMAKE_BUILD_DIR)
+ rtn = subprocess.call(cmd, cwd=CMAKE_BUILD_DIR)
if rtn != 0:
- raise RuntimeError("Could not successfully configure "
- "your project. Please see CMake's "
- "output for more information.")
+ raise SKBuildError(
+ "An error occurred while configuring with CMake.\n"
+ " Command:\n"
+ " {}\n"
+ " Source directory:\n"
+ " {}\n"
+ " Working directory:\n"
+ " {}\n"
+ "Please see CMake's output for more information.".format(
+ self._formatArgsForDisplay(cmd),
+ os.path.abspath(cwd),
+ os.path.abspath(CMAKE_BUILD_DIR)))
CMaker.check_for_bad_installs()
@@ -335,7 +348,6 @@ class CMaker(object):
if bad_installs:
raise SKBuildError("\n".join((
- "",
" CMake-installed files must be within the project root.",
" Project Root:",
" " + install_dir,
@@ -349,7 +361,7 @@ class CMaker(object):
"""
clargs, config = pop_arg('--config', clargs, config)
if not os.path.exists(CMAKE_BUILD_DIR):
- raise RuntimeError(("CMake build folder ({}) does not exist. "
+ raise SKBuildError(("CMake build folder ({}) does not exist. "
"Did you forget to run configure before "
"make?").format(CMAKE_BUILD_DIR))
@@ -361,8 +373,20 @@ class CMaker(object):
shlex.split(os.environ.get("SKBUILD_BUILD_OPTIONS", "")))
)
- rtn = subprocess.check_call(cmd, cwd=CMAKE_BUILD_DIR)
- return rtn
+ rtn = subprocess.call(cmd, cwd=CMAKE_BUILD_DIR)
+ if rtn != 0:
+ raise SKBuildError(
+ "An error occurred while building with CMake.\n"
+ " Command:\n"
+ " {}\n"
+ " Source directory:\n"
+ " {}\n"
+ " Working directory:\n"
+ " {}\n"
+ "Please see CMake's output for more information.".format(
+ self._formatArgsForDisplay(cmd),
+ os.path.abspath(source_dir),
+ os.path.abspath(CMAKE_BUILD_DIR)))
def install(self):
"""Returns a list of tuples of (install location, file list) to install
@@ -377,3 +401,14 @@ class CMaker(object):
return [_remove_cwd_prefix(path) for path in manifest]
return []
+
+ @staticmethod
+ def _formatArgsForDisplay(args):
+ """Format a list of arguments appropriately for display. When formatting
+ a command and its arguments, the user should be able to execute the
+ command by copying and pasting the output directly into a shell.
+
+ Currently, the only formatting is naively surrounding each argument with
+ quotation marks.
+ """
+ return ' '.join("\"{}\"".format(arg) for arg in args)
diff --git a/skbuild/exceptions.py b/skbuild/exceptions.py
index 4a0e074..2b8f8b1 100644
--- a/skbuild/exceptions.py
+++ b/skbuild/exceptions.py
@@ -1,3 +1,6 @@
-class SKBuildError(Exception):
+class SKBuildError(RuntimeError):
+ """Exception raised when an error occurs while configuring or building a
+ project.
+ """
pass
diff --git a/skbuild/setuptools_wrap.py b/skbuild/setuptools_wrap.py
index 0fbd86f..54efdb3 100644
--- a/skbuild/setuptools_wrap.py
+++ b/skbuild/setuptools_wrap.py
@@ -131,12 +131,56 @@ def setup(*args, **kw):
reverse=True
))
- cmkr = cmaker.CMaker()
- cmkr.configure(cmake_args)
- cmkr.make(make_args)
+ try:
+ cmkr = cmaker.CMaker()
+ cmkr.configure(cmake_args)
+ cmkr.make(make_args)
+ except SKBuildError as e:
+ import traceback
+ print("Traceback (most recent call last):")
+ traceback.print_tb(sys.exc_info()[2])
+ print()
+ sys.exit(e)
+
+ _classify_files(cmkr.install(), package_data, package_prefixes, py_modules,
+ scripts, new_scripts, data_files)
+
+ kw['package_data'] = package_data
+ kw['package_dir'] = {
+ package: os.path.join(cmaker.CMAKE_INSTALL_DIR, prefix)
+ for prefix, package in package_prefixes
+ }
+
+ kw['py_modules'] = py_modules
+
+ kw['scripts'] = [
+ os.path.join(cmaker.CMAKE_INSTALL_DIR, script) if mask else script
+ for script, mask in new_scripts.items()
+ ]
+
+ kw['data_files'] = [
+ (parent_dir, list(file_set))
+ for parent_dir, file_set in data_files.items()
+ ]
+
+ # work around https://bugs.python.org/issue1011113
+ # (patches provided, but no updates since 2014)
+ cmdclass = kw.get('cmdclass', {})
+ cmdclass['build'] = cmdclass.get('build', build.build)
+ cmdclass['install'] = cmdclass.get('install', install.install)
+ cmdclass['clean'] = cmdclass.get('clean', clean.clean)
+ cmdclass['bdist'] = cmdclass.get('bdist', bdist.bdist)
+ cmdclass['bdist_wheel'] = cmdclass.get(
+ 'bdist_wheel', bdist_wheel.bdist_wheel)
+ kw['cmdclass'] = cmdclass
+
+ return upstream_setup(*args, **kw)
+
+def _classify_files(install_paths, package_data, package_prefixes, py_modules,
+ scripts, new_scripts, data_files):
install_root = os.path.join(os.getcwd(), cmaker.CMAKE_INSTALL_DIR)
- for path in cmkr.install():
+ for path in install_paths:
found_package = False
found_module = False
found_script = False
@@ -204,34 +248,3 @@ def setup(*args, **kw):
data_files[parent_dir] = file_set
file_set.add(os.path.join(cmaker.CMAKE_INSTALL_DIR, path))
del parent_dir, file_set
-
- kw['package_data'] = package_data
- kw['package_dir'] = {
- package: os.path.join(cmaker.CMAKE_INSTALL_DIR, prefix)
- for prefix, package in package_prefixes
- }
-
- kw['py_modules'] = py_modules
-
- kw['scripts'] = [
- os.path.join(cmaker.CMAKE_INSTALL_DIR, script) if mask else script
- for script, mask in new_scripts.items()
- ]
-
- kw['data_files'] = [
- (parent_dir, list(file_set))
- for parent_dir, file_set in data_files.items()
- ]
-
- # work around https://bugs.python.org/issue1011113
- # (patches provided, but no updates since 2014)
- cmdclass = kw.get('cmdclass', {})
- cmdclass['build'] = cmdclass.get('build', build.build)
- cmdclass['install'] = cmdclass.get('install', install.install)
- cmdclass['clean'] = cmdclass.get('clean', clean.clean)
- cmdclass['bdist'] = cmdclass.get('bdist', bdist.bdist)
- cmdclass['bdist_wheel'] = cmdclass.get(
- 'bdist_wheel', bdist_wheel.bdist_wheel)
- kw['cmdclass'] = cmdclass
-
- return upstream_setup(*args, **kw)
|
scikit-build/scikit-build
|
abaaeee43e0456ef9da7d4878f0310c569bd6525
|
diff --git a/tests/test_outside_project_root.py b/tests/test_outside_project_root.py
index 9500a4d..d67baa4 100644
--- a/tests/test_outside_project_root.py
+++ b/tests/test_outside_project_root.py
@@ -5,7 +5,8 @@
----------------------------------
Tries to build the `fail-outside-project-root` sample project. Ensures that the
-attempt fails with an SKBuildError exception.
+attempt fails with a SystemExit exception that has an SKBuildError exception as
+its value.
"""
from skbuild.exceptions import SKBuildError
@@ -23,10 +24,10 @@ def test_outside_project_root_fails():
def should_fail():
pass
- exception_thrown = False
+ failed = False
try:
should_fail()
- except SKBuildError:
- exception_thrown = True
+ except SystemExit as e:
+ failed = isinstance(e.code, SKBuildError)
- assert exception_thrown
+ assert failed
|
Improve cmaker exception
When there is a problem building python module, report "human-friendly" error
|
0.0
|
abaaeee43e0456ef9da7d4878f0310c569bd6525
|
[
"tests/test_outside_project_root.py::test_outside_project_root_fails"
] |
[] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2016-07-22 19:35:31+00:00
|
mit
| 5,355 |
|
scikit-build__scikit-ci-11
|
diff --git a/appveyor.yml b/appveyor.yml
index 55b5f23..9d2d11c 100644
--- a/appveyor.yml
+++ b/appveyor.yml
@@ -31,13 +31,13 @@ install:
build_script:
- python -m ci before_build
- - python -m ci build"
+ - python -m ci build
test_script:
- - python -m ci test"
+ - python -m ci test
after_test:
- - python -m ci after_test"
+ - python -m ci after_test
# scikit-ci-yml.rst: end
on_finish:
diff --git a/ci/__main__.py b/ci/__main__.py
index fc661ea..236b426 100644
--- a/ci/__main__.py
+++ b/ci/__main__.py
@@ -9,29 +9,25 @@ import ci
import os
-class _OptionalChoices(argparse.Action):
- """Custom action making a positional argument with choices optional.
-
- Possible choices should be set with:
- - ``default`` attribute set as a list
- - ``nargs`` attribute set to ``'*'``
+class _OptionalStep(argparse.Action):
+ """Custom action making the ``step`` positional argument with choices
+ optional.
Setting the ``choices`` attribute will fail with an *invalid choice* error.
Adapted from http://stackoverflow.com/questions/8526675/python-argparse-optional-append-argument-with-choices/8527629#8527629
""" # noqa: E501
- def __call__(self, parser, namespace, values, option_string=None):
- if values:
- for value in values:
- if value not in self.default:
- message = ("invalid choice: {0!r} (choose from {1})"
- .format(value,
- ', '.join([repr(action)
- for action in
- self.default])))
+ def __call__(self, parser, namespace, value, option_string=None):
+ if value:
+ if value not in ci.STEPS:
+ message = ("invalid choice: {0!r} (choose from {1})"
+ .format(value,
+ ', '.join([repr(action)
+ for action in
+ ci.STEPS])))
- raise argparse.ArgumentError(self, message)
- setattr(namespace, self.dest, values)
+ raise argparse.ArgumentError(self, message)
+ setattr(namespace, self.dest, value)
def main():
@@ -45,21 +41,29 @@ def main():
parser = argparse.ArgumentParser(description=ci.__doc__)
parser.add_argument(
- "steps", type=str, nargs='*', default=ci.STEPS,
- action=_OptionalChoices, metavar='STEP',
- help="name of the steps to execute. "
+ "step", type=str, nargs='?', default=ci.STEPS[-1],
+ action=_OptionalStep, metavar='STEP',
+ help="name of the step to execute. "
"Choose from: {}. "
- "If not steps are specified, all are executed.".format(", ".join(
+ "If no step is specified, all are executed.".format(", ".join(
[repr(action) for action in ci.STEPS]))
)
+ parser.add_argument(
+ "--force", action="store_true",
+ help="always execute the steps"
+ )
+ parser.add_argument(
+ "--without-deps", action="store_false",
+ help="do not execute dependent steps", dest='with_dependencies'
+ )
parser.add_argument(
"--version", action="version",
version=version_str,
help="display scikit-ci version and import information.")
args = parser.parse_args()
- for step in args.steps:
- ci.execute_step(step)
+ ci.execute_step(
+ args.step, force=args.force, with_dependencies=args.with_dependencies)
if __name__ == '__main__':
diff --git a/ci/driver.py b/ci/driver.py
index 5ce0f01..6713d1a 100644
--- a/ci/driver.py
+++ b/ci/driver.py
@@ -28,7 +28,7 @@ class DriverContext(object):
def __exit__(self, exc_type, exc_value, traceback):
if exc_type is None and exc_value is None and traceback is None:
- self.driver.save_env()
+ self.driver.save_env(self.driver.env, self.env_file)
self.driver.unload_env()
@@ -43,6 +43,13 @@ class Driver(object):
print(" ".join(s))
sys.stdout.flush()
+ @staticmethod
+ def read_env(env_file="env.json"):
+ if not os.path.exists(env_file):
+ return {}
+ with open(env_file) as _file:
+ return json.load(_file)
+
def load_env(self, env_file="env.json"):
if self.env is not None:
self.unload_env()
@@ -52,16 +59,14 @@ class Driver(object):
self._env_file = env_file
if os.path.exists(self._env_file):
- self.env.update(json.load(open(self._env_file)))
+ self.env.update(self.read_env(self._env_file))
self.env = {str(k): str(v) for k, v in self.env.items()}
- def save_env(self, env_file=None):
- if env_file is None:
- env_file = self._env_file
-
- with open(env_file, "w") as env:
- json.dump(self.env, env, indent=4)
+ @staticmethod
+ def save_env(env, env_file="env.json"):
+ with open(env_file, "w") as _file:
+ json.dump(env, _file, indent=4)
def unload_env(self):
self.env = None
@@ -266,14 +271,45 @@ class Driver(object):
self.check_call(cmd.replace("\\\\", "\\\\\\\\"), env=self.env)
-def execute_step(step):
+def dependent_steps(step):
+ if step not in STEPS: # pragma: no cover
+ raise KeyError("invalid step: {}".format(step))
+ step_index = STEPS.index(step)
+ if step_index == 0:
+ return []
+ return STEPS[0:step_index]
+
+
+def execute_step(step, force=False, with_dependencies=True):
if not os.path.exists(SCIKIT_CI_CONFIG): # pragma: no cover
raise OSError(errno.ENOENT, "Couldn't find %s" % SCIKIT_CI_CONFIG)
if step not in STEPS: # pragma: no cover
- raise KeyError("invalid stage: {}".format(step))
+ raise KeyError("invalid step: {}".format(step))
+
+ depends = dependent_steps(step)
+
+ # If forcing execution, remove SCIKIT_CI_<step> env. variables
+ if force:
+ env = Driver.read_env()
+ steps = [step]
+ if with_dependencies:
+ steps += depends
+ for _step in steps:
+ if 'SCIKIT_CI_%s' % _step.upper() in env:
+ del env['SCIKIT_CI_%s' % _step.upper()]
+ Driver.save_env(env)
+
+ # Skip step if it has already been executed
+ if 'SCIKIT_CI_%s' % step.upper() in Driver.read_env():
+ return
+
+ # Recursively execute dependent steps
+ if with_dependencies and depends:
+ execute_step(depends[-1], with_dependencies=with_dependencies)
d = Driver()
with d.env_context():
d.execute_commands(step)
+ d.env['SCIKIT_CI_%s' % step.upper()] = '1'
|
scikit-build/scikit-ci
|
18244599cf4b4a97875a9cf755821f66c4c5894e
|
diff --git a/tests/test_scikit_ci.py b/tests/test_scikit_ci.py
index 4b0c02f..bf957ea 100644
--- a/tests/test_scikit_ci.py
+++ b/tests/test_scikit_ci.py
@@ -9,8 +9,8 @@ import textwrap
from ruamel.yaml.compat import ordereddict
from . import captured_lines, display_captured_text, push_dir, push_env
-from ci.constants import SERVICES, SERVICES_ENV_VAR
-from ci.driver import Driver, execute_step
+from ci.constants import SERVICES, SERVICES_ENV_VAR, STEPS
+from ci.driver import Driver, dependent_steps, execute_step
from ci.utils import current_service, current_operating_system
"""Indicate if the system has a Windows command line interpreter"""
@@ -55,6 +55,11 @@ def scikit_steps(tmpdir, service):
``(step, system, environment)`` for all supported steps.
"""
+ # Remove environment variables of the form 'SCIKIT_CI_<STEP>`
+ for step in STEPS:
+ if 'SCIKIT_CI_%s' % step.lower() in os.environ:
+ del os.environ['SCIKIT_CI_%s' % step.lower()]
+
# By default, a service is associated with only one "implicit" operating
# system.
# Service supporting multiple operating system (e.g travis) should be
@@ -80,13 +85,7 @@ def scikit_steps(tmpdir, service):
environment = os.environ
enable_service(service, environment, system)
- for step in [
- 'before_install',
- 'install',
- 'before_build',
- 'build',
- 'test',
- 'after_test']:
+ for step in STEPS:
yield step, system, environment
@@ -153,13 +152,7 @@ def _generate_scikit_yml_content(service):
[textwrap.dedent(template_step).format(
what=step,
command_0=commands[0],
- command_1=commands[1]) for step in
- ['before_install',
- 'install',
- 'before_build',
- 'build',
- 'test',
- 'after_test']
+ command_1=commands[1]) for step in STEPS
]
)
)
@@ -212,6 +205,16 @@ def test_driver(service, tmpdir, capfd):
raise
+def test_dependent_steps():
+ step = "before_install"
+ expected = []
+ assert dependent_steps(step) == expected
+
+ step = "build"
+ expected = ['before_install', 'install', 'before_build']
+ assert dependent_steps(step) == expected
+
+
def test_shell_command(tmpdir, capfd):
if platform.system().lower() == "windows":
@@ -356,7 +359,7 @@ def test_cli(tmpdir):
assert tmpdir.join("install-done").exists()
-def test_cli_multiple_steps(tmpdir):
+def test_cli_force_and_without_deps(tmpdir):
tmpdir.join('scikit-ci.yml').write(textwrap.dedent(
r"""
schema_version: "{version}"
@@ -376,17 +379,90 @@ def test_cli_multiple_steps(tmpdir):
root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
environment['PYTHONPATH'] = root
+ #
+ # Execute without --force
+ #
subprocess.check_call(
- "python -m ci before_install install",
+ "python -m ci install",
shell=True,
env=environment,
stderr=subprocess.STDOUT,
cwd=str(tmpdir)
)
+ # Check that steps were executed
assert tmpdir.join("before_install-done").exists()
assert tmpdir.join("install-done").exists()
+ tmpdir.join("before_install-done").remove()
+ tmpdir.join("install-done").remove()
+
+ #
+ # Execute without --force
+ #
+ subprocess.check_call(
+ "python -m ci install",
+ shell=True,
+ env=environment,
+ stderr=subprocess.STDOUT,
+ cwd=str(tmpdir)
+ )
+
+ # Check that steps were NOT re-executed
+ assert not tmpdir.join("before_install-done").exists()
+ assert not tmpdir.join("install-done").exists()
+
+ #
+ # Execute with --force
+ #
+ subprocess.check_call(
+ "python -m ci install --force",
+ shell=True,
+ env=environment,
+ stderr=subprocess.STDOUT,
+ cwd=str(tmpdir)
+ )
+
+ # Check that steps were re-executed
+ assert tmpdir.join("before_install-done").exists()
+ assert tmpdir.join("install-done").exists()
+
+ tmpdir.join("before_install-done").remove()
+ tmpdir.join("install-done").remove()
+
+ #
+ # Execute with --force and --without-deps
+ #
+ subprocess.check_call(
+ "python -m ci install --force --without-deps",
+ shell=True,
+ env=environment,
+ stderr=subprocess.STDOUT,
+ cwd=str(tmpdir)
+ )
+
+ # Check that only specified step was re-executed
+ assert not tmpdir.join("before_install-done").exists()
+ assert tmpdir.join("install-done").exists()
+
+ tmpdir.join("install-done").remove()
+ tmpdir.join("env.json").remove()
+
+ #
+ # Execute with --without-deps
+ #
+ subprocess.check_call(
+ "python -m ci install --without-deps",
+ shell=True,
+ env=environment,
+ stderr=subprocess.STDOUT,
+ cwd=str(tmpdir)
+ )
+
+ # Check that only specified step was executed
+ assert not tmpdir.join("before_install-done").exists()
+ assert tmpdir.join("install-done").exists()
+
def test_cli_execute_all_steps(tmpdir):
tmpdir.join('scikit-ci.yml').write(textwrap.dedent(
@@ -699,3 +775,143 @@ def test_ci_name_reserved_environment_variable(tmpdir):
failed = True
assert failed
+
+
+def test_step_ordering_and_dependency(tmpdir):
+ quote = "" if HAS_COMSPEC else "\""
+ tmpdir.join('scikit-ci.yml').write(textwrap.dedent(
+ r"""
+ schema_version: "{version}"
+ before_install:
+ commands:
+ - "python -c \"with open('before_install', 'w') as file: file.write('')\""
+ install:
+ commands:
+ - "python -c \"with open('install', 'w') as file: file.write('')\""
+ before_build:
+ commands:
+ - "python -c \"with open('before_build', 'w') as file: file.write('')\""
+ build:
+ commands:
+ - "python -c \"with open('build', 'w') as file: file.write('')\""
+ test:
+ commands:
+ - "python -c \"exit(1)\""
+ after_test:
+ commands:
+ - "python -c \"with open('after_test', 'w') as file: file.write('')\""
+ """ # noqa: E501
+ ).format(quote=quote, version=SCHEMA_VERSION))
+ service = 'circle'
+
+ environment = dict(os.environ)
+ enable_service(service, environment)
+
+ with push_dir(str(tmpdir)), push_env(**environment):
+
+ execute_step("install")
+
+ #
+ # Check that steps `before_install` and `install` were executed
+ #
+ env = Driver.read_env()
+ assert env['SCIKIT_CI_BEFORE_INSTALL'] == '1'
+ assert env['SCIKIT_CI_INSTALL'] == '1'
+ assert tmpdir.join('before_install').exists()
+ assert tmpdir.join('install').exists()
+
+ # Remove files - This will to make sure the steps are not re-executed
+ tmpdir.join('before_install').remove()
+ tmpdir.join('install').remove()
+
+ # Check files have been removed
+ assert not tmpdir.join('before_install').exists()
+ assert not tmpdir.join('install').exists()
+
+ execute_step("build")
+
+ #
+ # Check that only `before_build` and `build` steps were executed
+ #
+ env = Driver.read_env()
+ assert env['SCIKIT_CI_BEFORE_INSTALL'] == '1'
+ assert env['SCIKIT_CI_INSTALL'] == '1'
+ assert env['SCIKIT_CI_BEFORE_BUILD'] == '1'
+ assert env['SCIKIT_CI_BUILD'] == '1'
+
+ assert not tmpdir.join('before_install').exists()
+ assert not tmpdir.join('install').exists()
+ assert tmpdir.join('before_build').exists()
+ assert tmpdir.join('build').exists()
+
+ # Remove files - This will to make sure the steps are not re-executed
+ tmpdir.join('before_build').remove()
+ tmpdir.join('build').remove()
+
+ failed = False
+ try:
+ execute_step("after_test")
+ except subprocess.CalledProcessError as e:
+ failed = "exit(1)" in e.cmd
+
+ #
+ # Check that `after_test` step was NOT executed. It should not be
+ # execute because `test` step is failing.
+ #
+ assert failed
+ env = Driver.read_env()
+ assert env['SCIKIT_CI_BEFORE_INSTALL'] == '1'
+ assert env['SCIKIT_CI_INSTALL'] == '1'
+ assert env['SCIKIT_CI_BEFORE_BUILD'] == '1'
+ assert env['SCIKIT_CI_BUILD'] == '1'
+ assert 'SCIKIT_CI_TEST' not in env
+ assert 'SCIKIT_CI_AFTER_TEST' not in env
+
+ assert not tmpdir.join('before_install').exists()
+ assert not tmpdir.join('install').exists()
+ assert not tmpdir.join('before_install').exists()
+ assert not tmpdir.join('install').exists()
+ assert not tmpdir.join('test').exists()
+ assert not tmpdir.join('after_test').exists()
+
+ #
+ # Check `force=True` works as expected
+ #
+ execute_step("install", force=True)
+
+ # Check that steps `before_install` and `install` were re-executed
+ env = Driver.read_env()
+ assert env['SCIKIT_CI_BEFORE_INSTALL'] == '1'
+ assert env['SCIKIT_CI_INSTALL'] == '1'
+ assert tmpdir.join('before_install').exists()
+ assert tmpdir.join('install').exists()
+
+ tmpdir.join('before_install').remove()
+ tmpdir.join('install').remove()
+
+ #
+ # Check `force=True` and `with_dependencies=True` work as expected
+ #
+ execute_step("install", force=True, with_dependencies=False)
+
+ # Check that only step `install` was re-executed
+ env = Driver.read_env()
+ assert env['SCIKIT_CI_BEFORE_INSTALL'] == '1'
+ assert env['SCIKIT_CI_INSTALL'] == '1'
+ assert not tmpdir.join('before_install').exists()
+ assert tmpdir.join('install').exists()
+
+ tmpdir.join('install').remove()
+
+ #
+ # Check `force=False` and `with_dependencies=True` work as expected
+ #
+ tmpdir.join('env.json').remove()
+ execute_step("install", with_dependencies=False)
+
+ # Check that only step `install` was executed
+ env = Driver.read_env()
+ assert 'SCIKIT_CI_BEFORE_INSTALL' not in env
+ assert env['SCIKIT_CI_INSTALL'] == '1'
+ assert not tmpdir.join('before_install').exists()
+ assert tmpdir.join('install').exists()
|
Introduce expclit step ordering and dependency
In the current implementation all steps have to be explicitly executed. There are no concept of dependencies and/or order.
Considering the implicit order of all `step(n)` is the following:
* `before_install` -> `step(1)`
* `install` -> `step(2)`
* `before_build` -> `step(3)`
* `build` -> `step(4)`
* `test` -> `step(5)`
* `after_test` -> `step(6)`
The proposal is to ensure that executing any `step(n)` using `ci step(n)` ensures that `step(n-1)` has been executed before.
Doing so will allow to update configuration like this one:
```yml
dependencies:
override:
- ci before_install
- ci install
test:
override:
- ci before_build
- ci build
- ci test
deployment:
master:
branch: master
commands:
- ci after_test
```
into
```yml
dependencies:
override:
- ci install
test:
override:
- ci test
deployment:
master:
branch: master
commands:
- ci after_test
```
|
0.0
|
18244599cf4b4a97875a9cf755821f66c4c5894e
|
[
"tests/test_scikit_ci.py::test_current_service[appveyor]",
"tests/test_scikit_ci.py::test_current_service[circle]",
"tests/test_scikit_ci.py::test_current_service[travis]",
"tests/test_scikit_ci.py::test_dependent_steps",
"tests/test_scikit_ci.py::test_expand_command[echo",
"tests/test_scikit_ci.py::test_expand_command_with_newline[echo",
"tests/test_scikit_ci.py::test_recursively_expand_environment_vars[step_env0-global_env0-expected_step_env0-3]",
"tests/test_scikit_ci.py::test_recursively_expand_environment_vars[step_env1-global_env1-expected_step_env1-3]",
"tests/test_scikit_ci.py::test_recursively_expand_environment_vars[step_env2-global_env2-expected_step_env2-7]",
"tests/test_scikit_ci.py::test_recursively_expand_environment_vars[step_env3-global_env3-expected_step_env3-1]"
] |
[] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2016-10-28 05:45:53+00:00
|
apache-2.0
| 5,356 |
|
scikit-hep__cabinetry-359
|
diff --git a/src/cabinetry/schemas/config.json b/src/cabinetry/schemas/config.json
index d841da9..62704b7 100644
--- a/src/cabinetry/schemas/config.json
+++ b/src/cabinetry/schemas/config.json
@@ -198,6 +198,10 @@
"description": "if it is a data sample",
"type": "boolean"
},
+ "DisableStaterror": {
+ "description": "whether to disable the automatic inclusion of staterror modifiers for this sample, defaults to False",
+ "type": "boolean"
+ },
"Regions": {
"description": "region(s) that contain the sample, defaults to all regions",
"$ref": "#/definitions/regions_setting"
diff --git a/src/cabinetry/workspace.py b/src/cabinetry/workspace.py
index 4f3d0a1..e6729ec 100644
--- a/src/cabinetry/workspace.py
+++ b/src/cabinetry/workspace.py
@@ -286,11 +286,15 @@ class WorkspaceBuilder:
modifiers = []
# gammas
- gammas = {}
- gammas.update({"name": "staterror_" + region["Name"].replace(" ", "-")})
- gammas.update({"type": "staterror"})
- gammas.update({"data": sample_hist.stdev.tolist()})
- modifiers.append(gammas)
+ if not sample.get("DisableStaterror", False):
+ # staterror modifiers are added unless DisableStaterror is True
+ gammas = {}
+ gammas.update(
+ {"name": "staterror_" + region["Name"].replace(" ", "-")}
+ )
+ gammas.update({"type": "staterror"})
+ gammas.update({"data": sample_hist.stdev.tolist()})
+ modifiers.append(gammas)
# modifiers can have region and sample dependence, which is checked
# check if normfactors affect sample in region, add modifiers as needed
|
scikit-hep/cabinetry
|
96b15c3e7822056cd47a932fd221538e00b58779
|
diff --git a/tests/test_workspace.py b/tests/test_workspace.py
index 27c5cce..8cfa0af 100644
--- a/tests/test_workspace.py
+++ b/tests/test_workspace.py
@@ -256,7 +256,9 @@ def test_WorkspaceBuilder_sys_modifiers(mock_norm, mock_norm_shape):
"cabinetry.workspace.histo.Histogram.from_config",
return_value=histo.Histogram.from_arrays([0, 1, 2], [1.0, 2.0], [0.1, 0.1]),
)
[email protected]("cabinetry.configuration.region_contains_sample", side_effect=[True, False])
[email protected](
+ "cabinetry.configuration.region_contains_sample", side_effect=[True, False, True]
+)
def test_WorkspaceBuilder_channels(mock_contains, mock_histogram):
# should mock normfactor_modifiers / sys_modifiers
example_config = {
@@ -314,6 +316,17 @@ def test_WorkspaceBuilder_channels(mock_contains, mock_histogram):
# no calls to read histogram content
assert mock_histogram.call_count == 1
+ # staterror creation disabled
+ example_config = {
+ "General": {"HistogramFolder": "path"},
+ "Regions": [{"Name": "region_1"}],
+ "Samples": [{"Name": "signal", "DisableStaterror": True}],
+ "NormFactors": [],
+ }
+ ws_builder = workspace.WorkspaceBuilder(example_config)
+ channels = ws_builder.channels()
+ assert channels[0]["samples"][0]["modifiers"] == []
+
def test_WorkspaceBuilder_measurements():
example_config = {
|
Config changes to disable adding staterror systematics?
It would be great to have a way to have the cabinetry example build a workspace similar to the `pyhf.simplemodels` from ntuples without having to change it too much (e.g. to use `lumi` or strip `staterror`).
|
0.0
|
96b15c3e7822056cd47a932fd221538e00b58779
|
[
"tests/test_workspace.py::test_WorkspaceBuilder_channels"
] |
[
"tests/test_workspace.py::test_WorkspaceBuilder",
"tests/test_workspace.py::test_WorkspaceBuilder__data_sample",
"tests/test_workspace.py::test_WorkspaceBuilder__constant_parameter_setting",
"tests/test_workspace.py::test_WorkspaceBuilder_normfactor_modifiers",
"tests/test_workspace.py::test_WorkspaceBuilder_normalization_modifier",
"tests/test_workspace.py::test_WorkspaceBuilder_normplusshape_modifiers",
"tests/test_workspace.py::test_WorkspaceBuilder_sys_modifiers",
"tests/test_workspace.py::test_WorkspaceBuilder_measurements",
"tests/test_workspace.py::test_WorkspaceBuilder_observations",
"tests/test_workspace.py::test_WorkspaceBuilder_build",
"tests/test_workspace.py::test_build",
"tests/test_workspace.py::test_validate",
"tests/test_workspace.py::test_save",
"tests/test_workspace.py::test_load"
] |
{
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-08-28 20:38:16+00:00
|
bsd-3-clause
| 5,357 |
|
scikit-hep__cabinetry-396
|
diff --git a/src/cabinetry/model_utils.py b/src/cabinetry/model_utils.py
index cc6285e..f336e60 100644
--- a/src/cabinetry/model_utils.py
+++ b/src/cabinetry/model_utils.py
@@ -179,19 +179,19 @@ def prefit_uncertainties(model: pyhf.pdf.Model) -> np.ndarray:
"""
pre_fit_unc = [] # pre-fit uncertainties for parameters
for parameter in model.config.par_order:
- # obtain pre-fit uncertainty for constrained, non-fixed parameters
- if (
- model.config.param_set(parameter).constrained
- and not model.config.param_set(parameter).suggested_fixed_as_bool
- ):
- pre_fit_unc += model.config.param_set(parameter).width()
+ if model.config.param_set(parameter).constrained:
+ # pre-fit uncertainty for constrained parameters (if fixed, set to 0.0)
+ widths = [
+ width if not fixed else 0.0
+ for width, fixed in zip(
+ model.config.param_set(parameter).width(),
+ model.config.param_set(parameter).suggested_fixed,
+ )
+ ]
+ pre_fit_unc += widths
else:
- if model.config.param_set(parameter).n_parameters == 1:
- # unconstrained normfactor or fixed parameter, uncertainty is 0
- pre_fit_unc.append(0.0)
- else:
- # shapefactor
- pre_fit_unc += [0.0] * model.config.param_set(parameter).n_parameters
+ # unconstrained: normfactor or shapefactor, uncertainty is 0
+ pre_fit_unc += [0.0] * model.config.param_set(parameter).n_parameters
return np.asarray(pre_fit_unc)
@@ -476,11 +476,9 @@ def unconstrained_parameter_count(model: pyhf.pdf.Model) -> int:
"""
n_pars = 0
for parname in model.config.par_order:
- if (
- not model.config.param_set(parname).constrained
- and not model.config.param_set(parname).suggested_fixed_as_bool
- ):
- n_pars += model.config.param_set(parname).n_parameters
+ if not model.config.param_set(parname).constrained:
+ # only consider non-constant parameters
+ n_pars += model.config.param_set(parname).suggested_fixed.count(False)
return n_pars
|
scikit-hep/cabinetry
|
67f7fd6082157d5a1b80d7ba70434c7b57f8e2be
|
diff --git a/tests/conftest.py b/tests/conftest.py
index aeb3cbf..eda236e 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -379,6 +379,43 @@ def example_spec_modifiers():
return spec
[email protected]
+def example_spec_zero_staterror():
+ spec = {
+ "channels": [
+ {
+ "name": "SR",
+ "samples": [
+ {
+ "data": [5.0, 0.0],
+ "modifiers": [
+ {"data": None, "name": "mu", "type": "normfactor"},
+ {
+ "data": [1.0, 0.0],
+ "name": "staterror_SR",
+ "type": "staterror",
+ },
+ ],
+ "name": "Signal",
+ }
+ ],
+ }
+ ],
+ "measurements": [
+ {
+ "config": {
+ "parameters": [],
+ "poi": "mu",
+ },
+ "name": "zero staterror",
+ }
+ ],
+ "observations": [{"data": [5, 0], "name": "SR"}],
+ "version": "1.0.0",
+ }
+ return spec
+
+
# code below allows marking tests as slow and adds --runslow to run them
# implemented following https://docs.pytest.org/en/6.2.x/example/simple.html
def pytest_addoption(parser):
diff --git a/tests/test_model_utils.py b/tests/test_model_utils.py
index 257a00d..b1369d6 100644
--- a/tests/test_model_utils.py
+++ b/tests/test_model_utils.py
@@ -147,7 +147,10 @@ def test_asimov_parameters(example_spec, example_spec_shapefactor, example_spec_
def test_prefit_uncertainties(
- example_spec, example_spec_multibin, example_spec_shapefactor
+ example_spec,
+ example_spec_multibin,
+ example_spec_shapefactor,
+ example_spec_zero_staterror,
):
model = pyhf.Workspace(example_spec).model()
unc = model_utils.prefit_uncertainties(model)
@@ -161,6 +164,10 @@ def test_prefit_uncertainties(
unc = model_utils.prefit_uncertainties(model)
assert np.allclose(unc, [0.0, 0.0, 0.0])
+ model = pyhf.Workspace(example_spec_zero_staterror).model()
+ unc = model_utils.prefit_uncertainties(model)
+ assert np.allclose(unc, [0.0, 0.2, 0.0]) # partially fixed staterror
+
def test__hashable_model_key(example_spec):
# key matches for two models built from the same spec
|
Handle partially fixed parameters in `model_utils` API
The support for partially fixed parameters (such as `staterror` with zeros in some bins) in `pyhf` 0.7 can result in scenarios where the behavior of `suggested_fixed_as_bool` is undefined, see https://github.com/scikit-hep/pyhf/issues/1944.
This currently breaks `model_utils.prefit_uncertainties` in `cabinetry` (and also affects `model_utils.unconstrained_parameter_count`). Working around this should be possible by iterating bin by bin for affected parameters and using the `suggested_fixed` API instead.
|
0.0
|
67f7fd6082157d5a1b80d7ba70434c7b57f8e2be
|
[
"tests/test_model_utils.py::test_prefit_uncertainties"
] |
[
"tests/test_model_utils.py::test_ModelPrediction",
"tests/test_model_utils.py::test_model_and_data",
"tests/test_model_utils.py::test_asimov_data",
"tests/test_model_utils.py::test_asimov_parameters",
"tests/test_model_utils.py::test__hashable_model_key",
"tests/test_model_utils.py::test_yield_stdev",
"tests/test_model_utils.py::test_prediction",
"tests/test_model_utils.py::test_unconstrained_parameter_count",
"tests/test_model_utils.py::test__parameter_index",
"tests/test_model_utils.py::test__poi_index",
"tests/test_model_utils.py::test__strip_auxdata",
"tests/test_model_utils.py::test__data_per_channel",
"tests/test_model_utils.py::test__filter_channels",
"tests/test_model_utils.py::test_match_fit_results",
"tests/test_model_utils.py::test_modifier_map",
"tests/test_model_utils.py::test__parameters_maximizing_constraint_term"
] |
{
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-03-30 19:02:41+00:00
|
bsd-3-clause
| 5,358 |
|
scikit-hep__cabinetry-398
|
diff --git a/src/cabinetry/workspace.py b/src/cabinetry/workspace.py
index e6729ec..8521c5e 100644
--- a/src/cabinetry/workspace.py
+++ b/src/cabinetry/workspace.py
@@ -126,7 +126,9 @@ class WorkspaceBuilder:
provides the `histosys` and `normsys` modifiers for ``pyhf`` (in `HistFactory`
language, this corresponds to a `HistoSys` and an `OverallSys`). Symmetrization
could happen either at this stage (this is the case currently), or somewhere
- earlier, such as during template postprocessing.
+ earlier, such as during template postprocessing. A `histosys` modifier is not
+ created for single-bin channels, as it has no effect in this case (everything is
+ handled by the `normsys` modifier already).
Args:
region (Dict[str, Any]): region the systematic variation acts in
@@ -200,13 +202,15 @@ class WorkspaceBuilder:
modifiers.append(norm_modifier)
# add the shape part in a histosys
- shape_modifier = {}
- shape_modifier.update({"name": modifier_name})
- shape_modifier.update({"type": "histosys"})
- shape_modifier.update(
- {"data": {"hi_data": histo_yield_up, "lo_data": histo_yield_down}}
- )
- modifiers.append(shape_modifier)
+ if len(histogram_nominal.yields) > 1:
+ # only relevant if there is more than one bin, otherwise there is no "shape"
+ shape_modifier = {}
+ shape_modifier.update({"name": modifier_name})
+ shape_modifier.update({"type": "histosys"})
+ shape_modifier.update(
+ {"data": {"hi_data": histo_yield_up, "lo_data": histo_yield_down}}
+ )
+ modifiers.append(shape_modifier)
return modifiers
def sys_modifiers(
|
scikit-hep/cabinetry
|
03f274f0028944dce406b43b92350738808a312b
|
diff --git a/tests/test_workspace.py b/tests/test_workspace.py
index 8cfa0af..f4902d5 100644
--- a/tests/test_workspace.py
+++ b/tests/test_workspace.py
@@ -136,6 +136,9 @@ def test_WorkspaceBuilder_normalization_modifier():
# for test of symmetrization: up and nominal
histo.Histogram.from_arrays([0, 1, 2], [26.0, 24.0], [0.1, 0.1]),
histo.Histogram.from_arrays([0, 1, 2], [20.0, 20.0], [0.1, 0.1]),
+ # single bin for test of histosys being skipped (up and nominal)
+ histo.Histogram.from_arrays([0, 1], [26.0], [0.1]),
+ histo.Histogram.from_arrays([0, 1], [20.0], [0.1]),
],
)
def test_WorkspaceBuilder_normplusshape_modifiers(mock_histogram):
@@ -194,6 +197,12 @@ def test_WorkspaceBuilder_normplusshape_modifiers(mock_histogram):
((pathlib.Path("path"), region, sample, {}), {"modified": True}),
]
+ # single bin, causing histosys being skipped
+ modifiers = ws_builder.normplusshape_modifiers(region, sample, systematic)
+ assert modifiers == [
+ {"name": "mod_name", "type": "normsys", "data": {"hi": 1.3, "lo": 0.7}},
+ ]
+
@mock.patch(
"cabinetry.workspace.WorkspaceBuilder.normplusshape_modifiers",
|
Skip histosys modifiers for single-bin regions
Since `cabinetry` uses normalized `histosys` modifiers when constructing models, there is no need to have `histosys` modifiers for channels with a single bin: all information is contained in the correlated `normsys` modifier. The `histosys` modifiers should be skipped in the workspace construction in this case.
|
0.0
|
03f274f0028944dce406b43b92350738808a312b
|
[
"tests/test_workspace.py::test_WorkspaceBuilder_normplusshape_modifiers"
] |
[
"tests/test_workspace.py::test_WorkspaceBuilder",
"tests/test_workspace.py::test_WorkspaceBuilder__data_sample",
"tests/test_workspace.py::test_WorkspaceBuilder__constant_parameter_setting",
"tests/test_workspace.py::test_WorkspaceBuilder_normfactor_modifiers",
"tests/test_workspace.py::test_WorkspaceBuilder_normalization_modifier",
"tests/test_workspace.py::test_WorkspaceBuilder_sys_modifiers",
"tests/test_workspace.py::test_WorkspaceBuilder_channels",
"tests/test_workspace.py::test_WorkspaceBuilder_measurements",
"tests/test_workspace.py::test_WorkspaceBuilder_observations",
"tests/test_workspace.py::test_WorkspaceBuilder_build",
"tests/test_workspace.py::test_build",
"tests/test_workspace.py::test_validate",
"tests/test_workspace.py::test_save",
"tests/test_workspace.py::test_load"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2023-04-01 15:50:45+00:00
|
bsd-3-clause
| 5,359 |
|
scikit-hep__cabinetry-399
|
diff --git a/src/cabinetry/visualize/__init__.py b/src/cabinetry/visualize/__init__.py
index 3f53b86..91e40fb 100644
--- a/src/cabinetry/visualize/__init__.py
+++ b/src/cabinetry/visualize/__init__.py
@@ -56,6 +56,8 @@ def data_mc_from_histograms(
figure_folder: Union[str, pathlib.Path] = "figures",
log_scale: Optional[bool] = None,
log_scale_x: bool = False,
+ channels: Optional[Union[str, List[str]]] = None,
+ colors: Optional[Dict[str, str]] = None,
close_figure: bool = False,
save_figure: bool = True,
) -> List[Dict[str, Any]]:
@@ -71,11 +73,18 @@ def data_mc_from_histograms(
defaults to None (automatically determine whether to use linear/log scale)
log_scale_x (bool, optional): whether to use logarithmic horizontal axis,
defaults to False
+ channels (Optional[Union[str, List[str]]], optional): name of channel to show,
+ or list of names to include, defaults to None (uses all channels)
+ colors (Optional[Dict[str, str]], optional): map of sample names and colors to
+ use in plot, defaults to None (uses default colors)
close_figure (bool, optional): whether to close each figure, defaults to False
(enable when producing many figures to avoid memory issues, prevents
automatic rendering in notebooks)
save_figure (bool, optional): whether to save figures, defaults to True
+ Raises:
+ ValueError: if color specification is incomplete
+
Returns:
List[Dict[str, Any]]: list of dictionaries, where each dictionary contains a
figure and the associated region name
@@ -83,7 +92,24 @@ def data_mc_from_histograms(
log.info("visualizing histogram")
histogram_folder = pathlib.Path(config["General"]["HistogramFolder"])
figure_dict_list = []
+
+ # if custom colors are provided, ensure that they cover all samples
+ if colors is not None:
+ c_missing = {
+ sample["Name"] for sample in config["Samples"] if not sample.get("Data")
+ }.difference(colors.keys())
+ if c_missing:
+ raise ValueError(
+ f"colors need to be provided for all samples, missing for {c_missing}"
+ )
+
+ # create a list of channels to process
+ if channels is not None and isinstance(channels, str):
+ channels = [channels]
+
for region in config["Regions"]:
+ if channels is not None and region["Name"] not in channels:
+ continue # skip region
histogram_dict_list = []
model_stdevs = []
# loop over samples in reverse order, such that samples that appear first in the
@@ -119,6 +145,7 @@ def data_mc_from_histograms(
log_scale=log_scale,
log_scale_x=log_scale_x,
label=label,
+ colors=colors,
close_figure=close_figure,
)
figure_dict_list.append({"figure": fig, "region": region["Name"]})
@@ -134,6 +161,7 @@ def data_mc(
log_scale: Optional[bool] = None,
log_scale_x: bool = False,
channels: Optional[Union[str, List[str]]] = None,
+ colors: Optional[Dict[str, str]] = None,
close_figure: bool = False,
save_figure: bool = True,
) -> Optional[List[Dict[str, Any]]]:
@@ -159,11 +187,16 @@ def data_mc(
defaults to False
channels (Optional[Union[str, List[str]]], optional): name of channel to show,
or list of names to include, defaults to None (uses all channels)
+ colors (Optional[Dict[str, str]], optional): map of sample names and colors to
+ use in plot, defaults to None (uses default colors)
close_figure (bool, optional): whether to close each figure, defaults to False
(enable when producing many figures to avoid memory issues, prevents
automatic rendering in notebooks)
save_figure (bool, optional): whether to save figures, defaults to True
+ Raises:
+ ValueError: if color specification is incomplete
+
Returns:
Optional[List[Dict[str, Any]]]: list of dictionaries, where each dictionary
contains a figure and the associated region name, or None if no figure was
@@ -172,11 +205,19 @@ def data_mc(
# strip off auxdata (if needed) and obtain data indexed by channel (and bin)
data_yields = model_utils._data_per_channel(model_prediction.model, data)
- # channels to include in table, with optional filtering applied
+ # if custom colors are provided, ensure that they cover all samples
+ if colors is not None:
+ c_missing = set(model_prediction.model.config.samples).difference(colors.keys())
+ if c_missing:
+ raise ValueError(
+ f"colors need to be provided for all samples, missing for {c_missing}"
+ )
+
+ # channels to include in plot, with optional filtering applied
filtered_channels = model_utils._filter_channels(model_prediction.model, channels)
if filtered_channels == []:
- # nothing to include in tables, warning already raised via _filter_channels
+ # nothing to include in plots, warning already raised via _filter_channels
return None
# indices of included channels
@@ -241,6 +282,7 @@ def data_mc(
log_scale=log_scale,
log_scale_x=log_scale_x,
label=label,
+ colors=colors,
close_figure=close_figure,
)
figure_dict_list.append({"figure": fig, "region": channel_name})
diff --git a/src/cabinetry/visualize/plot_model.py b/src/cabinetry/visualize/plot_model.py
index 4ae8357..dda23ce 100644
--- a/src/cabinetry/visualize/plot_model.py
+++ b/src/cabinetry/visualize/plot_model.py
@@ -30,6 +30,7 @@ def data_mc(
log_scale: Optional[bool] = None,
log_scale_x: bool = False,
label: str = "",
+ colors: Optional[Dict[str, str]] = None,
close_figure: bool = False,
) -> mpl.figure.Figure:
"""Draws a data/MC histogram with uncertainty bands and ratio panel.
@@ -48,6 +49,8 @@ def data_mc(
log_scale_x (bool, optional): whether to use logarithmic horizontal axis,
defaults to False
label (str, optional): label written on the figure, defaults to ""
+ colors (Optional[Dict[str, str]], optional): map of sample names and colors to
+ use in plot, defaults to None (uses default colors)
close_figure (bool, optional): whether to close each figure immediately after
saving it, defaults to False (enable when producing many figures to avoid
memory issues, prevents rendering in notebooks)
@@ -102,9 +105,13 @@ def data_mc(
else bin_centers
)
mc_containers = []
- for mc_sample_yield in mc_histograms_yields:
+ for mc_sample_yield, sample_label in zip(mc_histograms_yields, mc_labels):
mc_container = ax1.bar(
- bin_centers, mc_sample_yield, width=bin_width, bottom=total_yield
+ bin_centers,
+ mc_sample_yield,
+ width=bin_width,
+ bottom=total_yield,
+ color=colors[sample_label] if colors else None,
)
mc_containers.append(mc_container)
|
scikit-hep/cabinetry
|
d761e302a5dc2b535cb336340234090afb2b1d52
|
diff --git a/tests/visualize/test_visualize.py b/tests/visualize/test_visualize.py
index 7ece48b..10c2394 100644
--- a/tests/visualize/test_visualize.py
+++ b/tests/visualize/test_visualize.py
@@ -105,17 +105,21 @@ def test_data_mc_from_histograms(mock_load, mock_draw, mock_stdev):
"log_scale": None,
"log_scale_x": False,
"label": "reg_1\npre-fit",
+ "colors": None,
"close_figure": False,
},
)
]
- # custom log scale settings, close figure, do not save figure
+ # custom log scale settings, close figure, do not save figure, channel specified,
+ # custom colors
_ = visualize.data_mc_from_histograms(
config,
figure_folder=figure_folder,
log_scale=True,
log_scale_x=True,
+ channels=["reg_1"],
+ colors={"sample_1": "red"},
close_figure=True,
save_figure=False,
)
@@ -124,9 +128,20 @@ def test_data_mc_from_histograms(mock_load, mock_draw, mock_stdev):
"log_scale": True,
"log_scale_x": True,
"label": "reg_1\npre-fit",
+ "colors": {"sample_1": "red"},
"close_figure": True,
}
+ # no matching channels
+ assert visualize.data_mc_from_histograms(config, channels="abc") == []
+
+ # incomplete color specification
+ with pytest.raises(
+ ValueError,
+ match="colors need to be provided for all samples, missing for {'sample_1'}",
+ ):
+ _ = visualize.data_mc_from_histograms(config, colors={})
+
@mock.patch(
"cabinetry.visualize.plot_model.data_mc", return_value=matplotlib.figure.Figure()
@@ -191,12 +206,13 @@ def test_data_mc(mock_data, mock_filter, mock_dict, mock_bins, mock_draw, exampl
"log_scale": None,
"log_scale_x": False,
"label": "Signal Region\npre-fit",
+ "colors": None,
"close_figure": False,
}
# post-fit plot (different label in model prediction), custom scale, close figure,
- # do not save figure, histogram input mode: no binning or variable specified (via
- # side effect)
+ # do not save figure, custom colors, histogram input mode: no binning or variable
+ # specified (via side effect)
model_pred = model_utils.ModelPrediction(
model, [[[11.0]]], [[[0.2], [0.2]]], [[0.2, 0.2]], "post-fit"
)
@@ -206,6 +222,7 @@ def test_data_mc(mock_data, mock_filter, mock_dict, mock_bins, mock_draw, exampl
config=config,
figure_folder=figure_folder,
log_scale=False,
+ colors={"Signal": "red"},
close_figure=True,
save_figure=False,
)
@@ -224,6 +241,7 @@ def test_data_mc(mock_data, mock_filter, mock_dict, mock_bins, mock_draw, exampl
"log_scale": False,
"log_scale_x": False,
"label": "Signal Region\npost-fit",
+ "colors": {"Signal": "red"},
"close_figure": True,
}
@@ -239,6 +257,13 @@ def test_data_mc(mock_data, mock_filter, mock_dict, mock_bins, mock_draw, exampl
assert mock_filter.call_args == ((model, "abc"), {})
assert mock_draw.call_count == 3 # no new call
+ # incomplete color specification
+ with pytest.raises(
+ ValueError,
+ match="colors need to be provided for all samples, missing for {'Signal'}",
+ ):
+ _ = visualize.data_mc(model_pred, data, colors={})
+
@mock.patch(
"cabinetry.histo.Histogram.from_path",
diff --git a/tests/visualize/test_visualize_plot_model.py b/tests/visualize/test_visualize_plot_model.py
index a6e49f5..2de5908 100644
--- a/tests/visualize/test_visualize_plot_model.py
+++ b/tests/visualize/test_visualize_plot_model.py
@@ -1,6 +1,7 @@
import copy
from unittest import mock
+import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.testing.compare import compare_images
import numpy as np
@@ -103,19 +104,30 @@ def test_data_mc(tmp_path, caplog):
# do not save figure, but close it
# one bin with zero model prediction
+ # custom histogram colors
histo_dict_list[0]["yields"] = np.asarray([0, 14])
histo_dict_list[1]["yields"] = np.asarray([0, 5])
caplog.clear()
with mock.patch("cabinetry.visualize.utils._save_and_close") as mock_close_safe:
with pytest.warns() as warn_record:
- fig = fig = plot_model.data_mc(
+ fig = plot_model.data_mc(
histo_dict_list,
total_model_unc_log,
bin_edges_log,
label="",
+ colors={"Background": "blue", "Signal": "red"},
close_figure=True,
)
assert mock_close_safe.call_args_list == [((fig, None, True), {})]
+ # custom colors propagated to histogram
+ assert (
+ fig.axes[0].containers[0].patches[0].get_facecolor()
+ == mpl.colors.to_rgba_array("blue")
+ ).all()
+ assert (
+ fig.axes[0].containers[1].patches[0].get_facecolor()
+ == mpl.colors.to_rgba_array("red")
+ ).all()
assert "predicted yield is zero in 1 bin(s), excluded from ratio plot" in [
rec.message for rec in caplog.records
|
Histogram colors in stacks - user interface creation
Hi!
It would be great to set colors of histograms in data / MC stack plots as soon as those are [created](https://github.com/scikit-hep/cabinetry/blob/master/src/cabinetry/visualize/plot_model.py#L24) .
Maybe a good way to do it is to add an argument to the function call, namely a dictionary like {sample name: color} ?
|
0.0
|
d761e302a5dc2b535cb336340234090afb2b1d52
|
[
"tests/visualize/test_visualize.py::test_data_mc_from_histograms",
"tests/visualize/test_visualize.py::test_data_mc",
"tests/visualize/test_visualize_plot_model.py::test_data_mc"
] |
[
"tests/visualize/test_visualize.py::test__figure_name[test_input0-SR_prefit.pdf]",
"tests/visualize/test_visualize.py::test__figure_name[test_input1-SR_postfit.pdf]",
"tests/visualize/test_visualize.py::test__figure_name[test_input2-SR-1_prefit.pdf]",
"tests/visualize/test_visualize.py::test__figure_name[test_input3-SR-1_postfit.pdf]",
"tests/visualize/test_visualize.py::test__total_yield_uncertainty",
"tests/visualize/test_visualize.py::test_templates",
"tests/visualize/test_visualize.py::test_correlation_matrix",
"tests/visualize/test_visualize.py::test_pulls",
"tests/visualize/test_visualize.py::test_ranking",
"tests/visualize/test_visualize.py::test_scan",
"tests/visualize/test_visualize.py::test_limit",
"tests/visualize/test_visualize.py::test_modifier_grid",
"tests/visualize/test_visualize_plot_model.py::test_templates",
"tests/visualize/test_visualize_plot_model.py::test_modifier_grid"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-04-02 12:00:56+00:00
|
bsd-3-clause
| 5,360 |
|
scikit-hep__cabinetry-436
|
diff --git a/setup.py b/setup.py
index 4788201..fc7609e 100644
--- a/setup.py
+++ b/setup.py
@@ -16,7 +16,7 @@ extras_require["test"] = sorted(
"mypy",
"types-tabulate",
"types-PyYAML",
- "typeguard>=4.0.0,!=4.0.1,!=4.1.0,!=4.1.1", # cabinetry#391, cabinetry#428
+ "typeguard>=4.0.0,!=4.0.1,!=4.1.*", # cabinetry#391, cabinetry#428
"black",
]
)
diff --git a/src/cabinetry/histo.py b/src/cabinetry/histo.py
index 578591e..5a6d132 100644
--- a/src/cabinetry/histo.py
+++ b/src/cabinetry/histo.py
@@ -79,11 +79,10 @@ class Histogram(bh.Histogram, family=cabinetry):
if modified:
histo_path_modified = histo_path.parent / (histo_path.name + "_modified")
if not histo_path_modified.with_suffix(".npz").exists():
- log.warning(
- f"the modified histogram {histo_path_modified.with_suffix('.npz')} "
- "does not exist"
+ log.info(
+ f"no modified histogram {histo_path_modified.with_suffix('.npz')} "
+ "found, loading un-modified histogram"
)
- log.warning("loading the un-modified histogram instead!")
else:
histo_path = histo_path_modified
histogram_npz = np.load(histo_path.with_suffix(".npz"))
|
scikit-hep/cabinetry
|
a0638e18a6b7940c015c177a5b93f3167237e793
|
diff --git a/tests/test_histo.py b/tests/test_histo.py
index a1e607f..71a5ea1 100644
--- a/tests/test_histo.py
+++ b/tests/test_histo.py
@@ -122,13 +122,11 @@ def test_Histogram_from_path(tmp_path, caplog, example_histograms, histogram_hel
# try loading a modified one, without success since it does not exist
h_from_path_modified = histo.Histogram.from_path(tmp_path, modified=True)
- expected_warning = (
- f"the modified histogram {str(tmp_path)}_modified.npz does not exist"
+ expected_info = (
+ f"no modified histogram {str(tmp_path)}_modified.npz found, "
+ "loading un-modified histogram"
)
- assert expected_warning in [rec.message for rec in caplog.records]
- assert "loading the un-modified histogram instead!" in [
- rec.message for rec in caplog.records
- ]
+ assert expected_info in [rec.message for rec in caplog.records]
caplog.clear()
# successfully load a modified histogram
|
Warnings about missing post-processed histograms
Warnings like
```
WARNING - cabinetry.histo - the modified histogram histograms/CR-Wy_RECAST_Signal_modified.npz does not exist
WARNING - cabinetry.histo - loading the un-modified histogram instead!
```
appear when `cabinetry.templates.postprocess(config)` is not called. The `WARNING` log level seems a bit high for this, it is really more of an information so should be updated accordingly.
cc @lukasheinrich for raising this (thanks!)
|
0.0
|
a0638e18a6b7940c015c177a5b93f3167237e793
|
[
"tests/test_histo.py::test_Histogram_from_path"
] |
[
"tests/test_histo.py::test_Histogram",
"tests/test_histo.py::test_Histogram_from_arrays",
"tests/test_histo.py::test_Histogram_from_config",
"tests/test_histo.py::test_Histogram_save",
"tests/test_histo.py::test_Histogram_normalize_to_yield",
"tests/test_histo.py::test_name"
] |
{
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-09-19 09:52:35+00:00
|
bsd-3-clause
| 5,361 |
|
scikit-hep__hist-129
|
diff --git a/README.md b/README.md
index fb17fe3..00c2c63 100644
--- a/README.md
+++ b/README.md
@@ -41,6 +41,8 @@ Hist currently provides everything boost-histogram provides, and the following e
- The `Hist` class augments `bh.Histogram` with reduced typing construction:
- Optional import-free construction system
- `flow=False` is a fast way to turn off flow
+ - Storages can be given by string
+ - `storage=` can be omitted
- Hist implements UHI+; an extension to the UHI (Unified Histogram Indexing) system designed for import-free interactivity:
- Uses `j` suffix to switch to data coordinates in access or slices
diff --git a/docs/changelog.rst b/docs/changelog.rst
index 20da761..77c373c 100644
--- a/docs/changelog.rst
+++ b/docs/changelog.rst
@@ -4,12 +4,17 @@ Changelog
Version 2.1.0
--------------------
+* Support shortcuts for setting storages by string or position
+ `#129 <https://github.com/scikit-hep/hist/pull/129>`_
+
Updated dependencies:
-- `boost-histogram` 0.11.0 to 0.13.0.
- - major new features, including PlottableProtocol
-- `histoprint` >=1.4 to >=1.6.
-- `mplhep` >=0.2.16 when `[plot]` given
+* ``boost-histogram`` 0.11.0 to 0.13.0.
+ * Major new features, including PlottableProtocol
+
+* ``histoprint`` >=1.4 to >=1.6.
+
+* ``mplhep`` >=0.2.16 when ``[plot]`` given
Version 2.0.1
diff --git a/src/hist/basehist.py b/src/hist/basehist.py
index c1c2bdf..0304057 100644
--- a/src/hist/basehist.py
+++ b/src/hist/basehist.py
@@ -2,6 +2,7 @@ from .axestuple import NamedAxesTuple
from .quick_construct import MetaConstructor
from .utils import set_family, HIST_FAMILY
from .storage import Storage
+from .axis import AxisProtocol
import warnings
import functools
@@ -36,15 +37,31 @@ def _proc_kw_for_lw(kwargs):
class BaseHist(bh.Histogram, metaclass=MetaConstructor):
__slots__ = ()
- def __init__(self, *args, storage: Optional[Storage] = None, metadata=None):
+ def __init__(
+ self,
+ *args: Union[AxisProtocol, Storage, str, Tuple[int, float, float]],
+ storage: Optional[Union[Storage, str]] = None,
+ metadata=None,
+ ):
"""
Initialize BaseHist object. Axis params can contain the names.
"""
self._hist: Any = None
self.axes: NamedAxesTuple
- if len(args):
- if isinstance(storage, type):
+ if args and storage is None and isinstance(args[-1], (Storage, str)):
+ storage = args[-1]
+ args = args[:-1]
+
+ if args:
+ if isinstance(storage, str):
+ storage_str = storage.title()
+ if storage_str == "Atomicint64":
+ storage_str = "AtomicInt64"
+ elif storage_str == "Weightedmean":
+ storage_str = "WeightedMean"
+ storage = getattr(bh.storage, storage_str)()
+ elif isinstance(storage, type):
msg = (
f"Please use '{storage.__name__}()' instead of '{storage.__name__}'"
)
|
scikit-hep/hist
|
d8a1f8e256d7f8fe3b31ba13b38f5a37976c1d56
|
diff --git a/tests/test_general.py b/tests/test_general.py
index b9495b5..627527e 100644
--- a/tests/test_general.py
+++ b/tests/test_general.py
@@ -1,4 +1,4 @@
-from hist import Hist, axis
+from hist import Hist, axis, storage
import boost_histogram as bh
import pytest
@@ -432,6 +432,19 @@ class TestGeneralStorageProxy:
with pytest.raises(Exception):
h.Double()
+ assert (
+ Hist(axis.Regular(10, 0, 1, name="x"), "double")._storage_type
+ == storage.Double
+ )
+ assert (
+ Hist(axis.Regular(10, 0, 1, name="x"), storage="DouBle")._storage_type
+ == storage.Double
+ )
+ assert (
+ Hist(axis.Regular(10, 0, 1, name="x"), storage.Double())._storage_type
+ == storage.Double
+ )
+
def test_int64(self):
h = Hist.new.Reg(10, 0, 1, name="x").Int64().fill([0.5, 0.5])
assert h[0.5j] == 2
@@ -441,6 +454,19 @@ class TestGeneralStorageProxy:
with pytest.raises(Exception):
h.Int64()
+ assert (
+ Hist(axis.Regular(10, 0, 1, name="x"), "int64")._storage_type
+ == storage.Int64
+ )
+ assert (
+ Hist(axis.Regular(10, 0, 1, name="x"), storage="INT64")._storage_type
+ == storage.Int64
+ )
+ assert (
+ Hist(axis.Regular(10, 0, 1, name="x"), storage.Int64())._storage_type
+ == storage.Int64
+ )
+
def test_atomic_int64(self):
h = Hist.new.Reg(10, 0, 1, name="x").AtomicInt64().fill([0.5, 0.5])
assert h[0.5j] == 2
@@ -450,6 +476,19 @@ class TestGeneralStorageProxy:
with pytest.raises(Exception):
h.AtomicInt64()
+ assert (
+ Hist(axis.Regular(10, 0, 1, name="x"), "atomicint64")._storage_type
+ == storage.AtomicInt64
+ )
+ assert (
+ Hist(axis.Regular(10, 0, 1, name="x"), storage="AtomicINT64")._storage_type
+ == storage.AtomicInt64
+ )
+ assert (
+ Hist(axis.Regular(10, 0, 1, name="x"), storage.AtomicInt64())._storage_type
+ == storage.AtomicInt64
+ )
+
def test_weight(self):
h = Hist.new.Reg(10, 0, 1, name="x").Weight().fill([0.5, 0.5])
assert h[0.5j].variance == 2
@@ -459,6 +498,19 @@ class TestGeneralStorageProxy:
with pytest.raises(Exception):
h.Weight()
+ assert (
+ Hist(axis.Regular(10, 0, 1, name="x"), "WeighT")._storage_type
+ == storage.Weight
+ )
+ assert (
+ Hist(axis.Regular(10, 0, 1, name="x"), storage="weight")._storage_type
+ == storage.Weight
+ )
+ assert (
+ Hist(axis.Regular(10, 0, 1, name="x"), storage.Weight())._storage_type
+ == storage.Weight
+ )
+
def test_mean(self):
h = (
Hist.new.Reg(10, 0, 1, name="x")
@@ -473,6 +525,18 @@ class TestGeneralStorageProxy:
with pytest.raises(Exception):
h.Mean()
+ assert (
+ Hist(axis.Regular(10, 0, 1, name="x"), "MEAn")._storage_type == storage.Mean
+ )
+ assert (
+ Hist(axis.Regular(10, 0, 1, name="x"), storage="mean")._storage_type
+ == storage.Mean
+ )
+ assert (
+ Hist(axis.Regular(10, 0, 1, name="x"), storage.Mean())._storage_type
+ == storage.Mean
+ )
+
def test_weighted_mean(self):
h = (
Hist.new.Reg(10, 0, 1, name="x")
@@ -488,6 +552,19 @@ class TestGeneralStorageProxy:
with pytest.raises(Exception):
h.WeightedMean()
+ assert (
+ Hist(axis.Regular(10, 0, 1, name="x"), "WeighTEDMEAn")._storage_type
+ == storage.WeightedMean
+ )
+ assert (
+ Hist(axis.Regular(10, 0, 1, name="x"), storage="weightedMean")._storage_type
+ == storage.WeightedMean
+ )
+ assert (
+ Hist(axis.Regular(10, 0, 1, name="x"), storage.WeightedMean())._storage_type
+ == storage.WeightedMean
+ )
+
def test_unlimited(self):
h = Hist.new.Reg(10, 0, 1, name="x").Unlimited().fill([0.5, 0.5])
assert h[0.5j] == 2
@@ -496,6 +573,19 @@ class TestGeneralStorageProxy:
with pytest.raises(Exception):
h.Unlimited()
+ assert (
+ Hist(axis.Regular(10, 0, 1, name="x"), "unlimited")._storage_type
+ == storage.Unlimited
+ )
+ assert (
+ Hist(axis.Regular(10, 0, 1, name="x"), storage="UNLImited")._storage_type
+ == storage.Unlimited
+ )
+ assert (
+ Hist(axis.Regular(10, 0, 1, name="x"), storage.Unlimited())._storage_type
+ == storage.Unlimited
+ )
+
def test_general_transform_proxy():
"""
|
[FEATURE] storage string aliases
**Describe the feature you'd like**
I'm not sure if there are technical reason that would prevent this, but it would be nice if you could add string aliases for the storage options. So for example
```python
import hist
from hist import Hist
# Supported
h1 = Hist.new.Reg(100, -10, 10, name="x").Double()
h2 = Hist(hist.axis.Regular(100, -10, 10, name="x"), storage=hist.storage.Double())
# Feature request
h3 = Hist(hist.axis.Regular(100, -10, 10, name="x"), storage="double")
```
would all create equivalent histograms.
|
0.0
|
d8a1f8e256d7f8fe3b31ba13b38f5a37976c1d56
|
[
"tests/test_general.py::TestGeneralStorageProxy::test_double",
"tests/test_general.py::TestGeneralStorageProxy::test_int64",
"tests/test_general.py::TestGeneralStorageProxy::test_atomic_int64",
"tests/test_general.py::TestGeneralStorageProxy::test_weight",
"tests/test_general.py::TestGeneralStorageProxy::test_mean",
"tests/test_general.py::TestGeneralStorageProxy::test_weighted_mean",
"tests/test_general.py::TestGeneralStorageProxy::test_unlimited"
] |
[
"tests/test_general.py::test_no_named_init[Hist]",
"tests/test_general.py::test_no_named_init[BaseHist]",
"tests/test_general.py::test_duplicated_names_init[Hist]",
"tests/test_general.py::test_duplicated_names_init[BaseHist]",
"tests/test_general.py::test_duplicated_names_init[NamedHist]",
"tests/test_general.py::test_general_access",
"tests/test_general.py::test_general_project",
"tests/test_general.py::test_general_transform_proxy",
"tests/test_general.py::test_hist_proxy_matches[Hist]",
"tests/test_general.py::test_hist_proxy_matches[BaseHist]",
"tests/test_general.py::test_hist_proxy_matches[NamedHist]",
"tests/test_general.py::test_general_density",
"tests/test_general.py::test_general_axestuple"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-02-20 19:39:43+00:00
|
bsd-3-clause
| 5,362 |
|
scikit-hep__hist-134
|
diff --git a/docs/changelog.rst b/docs/changelog.rst
index 77c373c..38adcb2 100644
--- a/docs/changelog.rst
+++ b/docs/changelog.rst
@@ -1,6 +1,14 @@
Changelog
====================
+
+Version 2.1.1
+--------------------
+
+* Fix density (and density based previews)
+ `#134 <https://github.com/scikit-hep/hist/pull/134>`_
+
+
Version 2.1.0
--------------------
@@ -26,7 +34,7 @@ Version 2.0.1
* Fixed ``plot2d_full`` incorrectly mirroring the y-axis.
`#105 <https://github.com/scikit-hep/hist/pull/105>`_
-* `Hist.plot_pull`: more suitable bands in the pull bands 1sigma, 2 sigma, etc.
+* ``Hist.plot_pull``: more suitable bands in the pull bands 1sigma, 2 sigma, etc.
`#102 <https://github.com/scikit-hep/hist/pull/102>`_
* Fixed classichist's usage of `get_terminal_size` to support not running in a terminal
diff --git a/src/hist/basehist.py b/src/hist/basehist.py
index 26afbf1..e24df4b 100644
--- a/src/hist/basehist.py
+++ b/src/hist/basehist.py
@@ -214,7 +214,7 @@ class BaseHist(bh.Histogram, metaclass=MetaConstructor):
"""
Density numpy array.
"""
- total = self.sum() * functools.reduce(operator.mul, self.axes.widths)
+ total = np.sum(self.values()) * functools.reduce(operator.mul, self.axes.widths)
return self.values() / np.where(total > 0, total, 1)
def show(self, **kwargs):
|
scikit-hep/hist
|
5a9499484993eb082ed9fb6a8687cff2949ec3ad
|
diff --git a/tests/test_general.py b/tests/test_general.py
index 627527e..e59c315 100644
--- a/tests/test_general.py
+++ b/tests/test_general.py
@@ -759,6 +759,14 @@ def test_general_density():
assert pytest.approx(sum(h.density()), 2) == pytest.approx(10 / 6, 2)
+def test_weighted_density():
+ for data in range(10, 20, 10):
+ h = Hist(axis.Regular(10, -3, 3, name="x"), storage="weight").fill(
+ np.random.randn(data)
+ )
+ assert pytest.approx(sum(h.density()), 2) == pytest.approx(10 / 6, 2)
+
+
def test_general_axestuple():
"""
Test general axes tuple -- whether Hist axes tuple work properly.
|
[BUG] SVG repr doesn’t support Weight storage
**Describe the bug**
I've already talked with @henryiii and so he has identified the Issue as described in the title, but I would not have known this from inspection as naively I assumed this was about `dtype` conversion. @henryiii had mentioned that there was a similar issue on `boost-histogram` but I'm not sure which one that is, so cc @HDembinski here too. @jpivarski has mentioned this is a combined issue that also will need coordination with `uproot4`.
**To Reproduce**
I [made a Gist](https://gist.github.com/matthewfeickert/2afe18c6b06ed14d889c3102513a621a) but you can also demo all of it in Binder: [](https://mybinder.org/v2/gist/matthewfeickert/2afe18c6b06ed14d889c3102513a621a/master?urlpath=lab/tree/minimal-failing.ipynb)
```
$ git clone [email protected]:2afe18c6b06ed14d889c3102513a621a.git hist-issue
$ cd hist-issue
$ python3 -m venv hist-issue
$ . hist-issue/bin/activate
(hist-issue) $ cat requirements.txt
hist[plot]==2.0.1
uproot4==0.0.27
uproot~=3.12
jupyter~=1.0
jupyterlab~=2.2
(hist-issue) $ python -m pip install -q -r requirements.txt
(hist-issue) $ python minimal-failing.py
hists in file: ['mass;1']
Traceback (most recent call last):
File "minimal-failing.py", line 100, in <module>
main()
File "minimal-failing.py", line 96, in main
minimal_failing(root_file)
File "minimal-failing.py", line 73, in minimal_failing
hist_mass.plot()
File "/home/feickert/.venvs/hist-issue/lib/python3.7/site-packages/hist/basehist.py", line 204, in plot
return self.plot1d(*args, **kwargs)
File "/home/feickert/.venvs/hist-issue/lib/python3.7/site-packages/hist/basehist.py", line 222, in plot1d
return hist.plot.histplot(self, ax=ax, **kwargs)
File "/home/feickert/.venvs/hist-issue/lib/python3.7/site-packages/mplhep/plot.py", line 132, in histplot
h = np.asarray(h).astype(float)
TypeError: Cannot cast array data from dtype([('value', '<f8'), ('variance', '<f8')]) to dtype('float64') according to the rule 'unsafe'
```
where the TL;DR is
```python
import uproot4 as uproot
import hist
from hist import Hist
root_file = uproot.open("example.root")
hist_mass = root_file["mass"].to_hist()
hist_mass.plot()
```
errors and similarly in the Jupyter repr for
```python
hist_mass
```
one gets
```pytb
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~/.venvs/JC-example/lib/python3.7/site-packages/IPython/core/formatters.py in __call__(self, obj)
343 method = get_real_method(obj, self.print_method)
344 if method is not None:
--> 345 return method()
346 return None
347 else:
~/.venvs/JC-example/lib/python3.7/site-packages/hist/basehist.py in _repr_html_(self)
64 return str(html_hist(self, svg_hist_1d_c))
65 else:
---> 66 return str(html_hist(self, svg_hist_1d))
67 elif self.ndim == 2:
68 return str(html_hist(self, svg_hist_2d))
~/.venvs/JC-example/lib/python3.7/site-packages/hist/svgplots.py in html_hist(h, function)
20
21 def html_hist(h, function):
---> 22 left_column = div(function(h), style="width:290px;")
23 right_column = div(_desc_hist(h), style="flex=grow:1;")
24
~/.venvs/JC-example/lib/python3.7/site-packages/hist/svgplots.py in svg_hist_1d(h)
53 (edges,) = h.axes.edges
54 norm_edges = (edges - edges[0]) / (edges[-1] - edges[0])
---> 55 density = h.density()
56 max_dens = np.max(density) or 1
57 norm_vals = density / max_dens
~/.venvs/JC-example/lib/python3.7/site-packages/hist/basehist.py in density(self)
187 Density numpy array.
188 """
--> 189 total = self.sum() * functools.reduce(operator.mul, self.axes.widths)
190 return self.view() / np.where(total > 0, total, 1)
191
TypeError: invalid type promotion
```
**Expected behavior**
The same output possible as
```
(hist-issue) $ python minimal-failing.py pass
```
|
0.0
|
5a9499484993eb082ed9fb6a8687cff2949ec3ad
|
[
"tests/test_general.py::test_weighted_density"
] |
[
"tests/test_general.py::test_no_named_init[Hist]",
"tests/test_general.py::test_no_named_init[BaseHist]",
"tests/test_general.py::test_duplicated_names_init[Hist]",
"tests/test_general.py::test_duplicated_names_init[BaseHist]",
"tests/test_general.py::test_duplicated_names_init[NamedHist]",
"tests/test_general.py::test_general_access",
"tests/test_general.py::test_general_project",
"tests/test_general.py::TestGeneralStorageProxy::test_double",
"tests/test_general.py::TestGeneralStorageProxy::test_int64",
"tests/test_general.py::TestGeneralStorageProxy::test_atomic_int64",
"tests/test_general.py::TestGeneralStorageProxy::test_weight",
"tests/test_general.py::TestGeneralStorageProxy::test_mean",
"tests/test_general.py::TestGeneralStorageProxy::test_weighted_mean",
"tests/test_general.py::TestGeneralStorageProxy::test_unlimited",
"tests/test_general.py::test_general_transform_proxy",
"tests/test_general.py::test_hist_proxy_matches[Hist]",
"tests/test_general.py::test_hist_proxy_matches[BaseHist]",
"tests/test_general.py::test_hist_proxy_matches[NamedHist]",
"tests/test_general.py::test_general_density",
"tests/test_general.py::test_general_axestuple"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_media",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-03-02 05:26:01+00:00
|
bsd-3-clause
| 5,363 |
|
scikit-hep__hist-247
|
diff --git a/src/hist/basehist.py b/src/hist/basehist.py
index a862c51..2158e49 100644
--- a/src/hist/basehist.py
+++ b/src/hist/basehist.py
@@ -343,7 +343,12 @@ class BaseHist(bh.Histogram, metaclass=MetaConstructor, family=hist):
"""
Plot method for BaseHist object.
"""
- _has_categorical = np.sum([ax.traits.discrete for ax in self.axes]) == 1
+ _has_categorical = 0
+ if (
+ np.sum(self.axes.traits.ordered) == 1
+ and np.sum(self.axes.traits.discrete) == 1
+ ):
+ _has_categorical = 1
_project = _has_categorical or overlay is not None
if self.ndim == 1 or (self.ndim == 2 and _project):
return self.plot1d(*args, overlay=overlay, **kwargs)
|
scikit-hep/hist
|
c659501e9cdd7f0eba3fec7b1bcebce7ca82b196
|
diff --git a/tests/test_mock_plot.py b/tests/test_mock_plot.py
new file mode 100644
index 0000000..7407712
--- /dev/null
+++ b/tests/test_mock_plot.py
@@ -0,0 +1,41 @@
+import numpy as np
+import pytest
+
+from hist import Hist
+
+
[email protected](autouse=True)
+def mock_test(monkeypatch):
+ monkeypatch.setattr(Hist, "plot1d", plot1d_mock)
+ monkeypatch.setattr(Hist, "plot2d", plot2d_mock)
+
+
+def plot1d_mock(*args, **kwargs):
+ return "called plot1d"
+
+
+def plot2d_mock(*args, **kwargs):
+ return "called plot2d"
+
+
+def test_categorical_plot():
+ testCat = (
+ Hist.new.StrCat("", name="dataset", growth=True)
+ .Reg(10, 0, 10, name="good", label="y-axis")
+ .Int64()
+ )
+
+ testCat.fill(dataset="A", good=np.random.normal(5, 9, 27))
+
+ assert testCat.plot() == "called plot1d"
+
+
+def test_integer_plot():
+ testInt = (
+ Hist.new.Int(1, 10, name="nice", label="x-axis")
+ .Reg(10, 0, 10, name="good", label="y-axis")
+ .Int64()
+ )
+ testInt.fill(nice=np.random.normal(5, 1, 10), good=np.random.normal(5, 1, 10))
+
+ assert testInt.plot() == "called plot2d"
|
[BUG] Integer axes counts as category for plot
The categorical plotting from #174 tried to trigger on integer axes and breaks.
|
0.0
|
c659501e9cdd7f0eba3fec7b1bcebce7ca82b196
|
[
"tests/test_mock_plot.py::test_integer_plot"
] |
[
"tests/test_mock_plot.py::test_categorical_plot"
] |
{
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-06-30 09:35:29+00:00
|
bsd-3-clause
| 5,364 |
|
scikit-hep__hist-388
|
diff --git a/src/hist/basehist.py b/src/hist/basehist.py
index 4c1a710..b68a7f8 100644
--- a/src/hist/basehist.py
+++ b/src/hist/basehist.py
@@ -16,7 +16,7 @@ from .axestuple import NamedAxesTuple
from .axis import AxisProtocol
from .quick_construct import MetaConstructor
from .storage import Storage
-from .svgplots import html_hist, svg_hist_1d, svg_hist_1d_c, svg_hist_2d, svg_hist_nd
+from .svgplots import html_hist, svg_hist_1d, svg_hist_1d_c, svg_hist_2d
from .typing import ArrayLike, Protocol, SupportsIndex
if typing.TYPE_CHECKING:
@@ -87,37 +87,37 @@ class BaseHist(bh.Histogram, metaclass=MetaConstructor, family=hist):
for a in args
]
- if args:
- if isinstance(storage, str):
- storage_str = storage.title()
- if storage_str == "Atomicint64":
- storage_str = "AtomicInt64"
- elif storage_str == "Weightedmean":
- storage_str = "WeightedMean"
- storage = getattr(bh.storage, storage_str)()
- elif isinstance(storage, type):
- msg = (
- f"Please use '{storage.__name__}()' instead of '{storage.__name__}'"
+ if isinstance(storage, str):
+ storage_str = storage.title()
+ if storage_str == "Atomicint64":
+ storage_str = "AtomicInt64"
+ elif storage_str == "Weightedmean":
+ storage_str = "WeightedMean"
+ storage = getattr(bh.storage, storage_str)()
+ elif isinstance(storage, type):
+ msg = f"Please use '{storage.__name__}()' instead of '{storage.__name__}'"
+ warnings.warn(msg)
+ storage = storage()
+
+ super().__init__(*args, storage=storage, metadata=metadata) # type: ignore[call-overload]
+
+ disallowed_names = {"weight", "sample", "threads"}
+ for ax in self.axes:
+ if ax.name in disallowed_names:
+ disallowed_warning = (
+ f"{ax.name} is a protected keyword and cannot be used as axis name"
)
- warnings.warn(msg)
- storage = storage()
- super().__init__(*args, storage=storage, metadata=metadata) # type: ignore[call-overload]
-
- disallowed_names = {"weight", "sample", "threads"}
- for ax in self.axes:
- if ax.name in disallowed_names:
- disallowed_warning = f"{ax.name} is a protected keyword and cannot be used as axis name"
- warnings.warn(disallowed_warning)
-
- valid_names = [ax.name for ax in self.axes if ax.name]
- if len(valid_names) != len(set(valid_names)):
- raise KeyError(
- f"{self.__class__.__name__} instance cannot contain axes with duplicated names"
- )
- for i, ax in enumerate(self.axes):
- # label will return name if label is not set, so this is safe
- if not ax.label:
- ax.label = f"Axis {i}"
+ warnings.warn(disallowed_warning)
+
+ valid_names = [ax.name for ax in self.axes if ax.name]
+ if len(valid_names) != len(set(valid_names)):
+ raise KeyError(
+ f"{self.__class__.__name__} instance cannot contain axes with duplicated names"
+ )
+ for i, ax in enumerate(self.axes):
+ # label will return name if label is not set, so this is safe
+ if not ax.label:
+ ax.label = f"Axis {i}"
if data is not None:
self[...] = data
@@ -130,19 +130,24 @@ class BaseHist(bh.Histogram, metaclass=MetaConstructor, family=hist):
return NamedAxesTuple(self._axis(i) for i in range(self.ndim))
- def _repr_html_(self) -> str:
+ def _repr_html_(self) -> str | None:
if self.size == 0:
- return str(self)
+ return None
+
if self.ndim == 1:
- if self.axes[0].traits.circular:
- return str(html_hist(self, svg_hist_1d_c))
- return str(html_hist(self, svg_hist_1d))
+ if len(self.axes[0]) <= 1000:
+ return str(
+ html_hist(
+ self,
+ svg_hist_1d_c if self.axes[0].traits.circular else svg_hist_1d,
+ )
+ )
+
if self.ndim == 2:
- return str(html_hist(self, svg_hist_2d))
- if self.ndim > 2:
- return str(html_hist(self, svg_hist_nd))
+ if len(self.axes[0]) <= 200 and len(self.axes[1]) <= 200:
+ return str(html_hist(self, svg_hist_2d))
- return str(self)
+ return None
def _name_to_index(self, name: str) -> int:
"""
diff --git a/src/hist/svgplots.py b/src/hist/svgplots.py
index 8bfe8b9..5086b5e 100644
--- a/src/hist/svgplots.py
+++ b/src/hist/svgplots.py
@@ -193,32 +193,3 @@ def svg_hist_2d(h: hist.BaseHist) -> svg:
]
return svg(*texts, *boxes, viewBox=f"{-20} {-height - 20} {width+40} {height+40}")
-
-
-def svg_hist_nd(h: hist.BaseHist) -> svg:
- assert h.ndim > 2, "Must be more than 2D"
-
- width = 200
- height = 200
-
- boxes = [
- rect(
- x=20 * i,
- y=20 * i,
- width=width - 40,
- height=height - 40,
- style="fill:white;opacity:.5;stroke-width:2;stroke:currentColor;",
- )
- for i in range(3)
- ]
-
- nd = text(
- f"{h.ndim}D",
- x=height / 2 + 20,
- y=width / 2 + 20,
- style="font-size: 26pt; font-family: verdana; font-style: bold; fill: black;",
- text_anchor="middle",
- alignment_baseline="middle",
- )
-
- return svg(*boxes, nd, viewBox=f"-10 -10 {height + 20} {width + 20}")
|
scikit-hep/hist
|
4e7d5992be68294acde5e36892f08a0616abb19d
|
diff --git a/tests/test_reprs.py b/tests/test_reprs.py
index 4d44171..ad4c70a 100644
--- a/tests/test_reprs.py
+++ b/tests/test_reprs.py
@@ -81,13 +81,18 @@ def test_ND_empty_repr(named_hist):
.Double()
)
html = h._repr_html_()
- assert html
- assert "name='x'" in repr(h)
- assert "name='p'" in repr(h)
- assert "name='a'" in repr(h)
- assert "label='y'" in repr(h)
- assert "label='q'" in repr(h)
- assert "label='b'" in repr(h)
+ assert html is None
+
+
+def test_empty_mega_repr(named_hist):
+
+ h = named_hist.new.Reg(1001, -1, 1, name="x").Double()
+ html = h._repr_html_()
+ assert html is None
+
+ h = named_hist.new.Reg(201, -1, 1, name="x").Reg(100, 0, 1, name="y").Double()
+ html = h._repr_html_()
+ assert html is None
def test_stack_repr(named_hist):
|
chore: convert to mime bundle for IPython reprs
Let's convert `_repr_svg_` (and any extras) to `_repr_mimebundle_`. See https://github.com/scikit-hep/decaylanguage/pull/213.
|
0.0
|
4e7d5992be68294acde5e36892f08a0616abb19d
|
[
"tests/test_reprs.py::test_ND_empty_repr[Hist]",
"tests/test_reprs.py::test_ND_empty_repr[BaseHist]",
"tests/test_reprs.py::test_ND_empty_repr[NamedHist]",
"tests/test_reprs.py::test_empty_mega_repr[Hist]",
"tests/test_reprs.py::test_empty_mega_repr[BaseHist]",
"tests/test_reprs.py::test_empty_mega_repr[NamedHist]"
] |
[
"tests/test_reprs.py::test_1D_empty_repr[Hist]",
"tests/test_reprs.py::test_1D_empty_repr[BaseHist]",
"tests/test_reprs.py::test_1D_empty_repr[NamedHist]",
"tests/test_reprs.py::test_1D_var_empty_repr[Hist]",
"tests/test_reprs.py::test_1D_var_empty_repr[BaseHist]",
"tests/test_reprs.py::test_1D_var_empty_repr[NamedHist]",
"tests/test_reprs.py::test_1D_int_empty_repr[Hist]",
"tests/test_reprs.py::test_1D_int_empty_repr[BaseHist]",
"tests/test_reprs.py::test_1D_int_empty_repr[NamedHist]",
"tests/test_reprs.py::test_1D_intcat_empty_repr[Hist]",
"tests/test_reprs.py::test_1D_intcat_empty_repr[BaseHist]",
"tests/test_reprs.py::test_1D_intcat_empty_repr[NamedHist]",
"tests/test_reprs.py::test_1D_strcat_empty_repr[Hist]",
"tests/test_reprs.py::test_1D_strcat_empty_repr[BaseHist]",
"tests/test_reprs.py::test_1D_strcat_empty_repr[NamedHist]",
"tests/test_reprs.py::test_2D_empty_repr[Hist]",
"tests/test_reprs.py::test_2D_empty_repr[BaseHist]",
"tests/test_reprs.py::test_2D_empty_repr[NamedHist]",
"tests/test_reprs.py::test_1D_circ_empty_repr[Hist]",
"tests/test_reprs.py::test_1D_circ_empty_repr[BaseHist]",
"tests/test_reprs.py::test_1D_circ_empty_repr[NamedHist]",
"tests/test_reprs.py::test_stack_repr[Hist]",
"tests/test_reprs.py::test_stack_repr[BaseHist]",
"tests/test_reprs.py::test_stack_repr[NamedHist]"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-03-10 22:18:50+00:00
|
bsd-3-clause
| 5,365 |
|
scikit-hep__particle-494
|
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 3856a5d..46130ae 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -24,13 +24,13 @@ repos:
- id: black-jupyter
- repo: https://github.com/charliermarsh/ruff-pre-commit
- rev: "v0.0.265"
+ rev: "v0.0.269"
hooks:
- id: ruff
args: ["--fix", "--show-fixes"]
- repo: https://github.com/pre-commit/mirrors-mypy
- rev: v1.2.0
+ rev: v1.3.0
hooks:
- id: mypy
files: src
diff --git a/src/particle/pdgid/functions.py b/src/particle/pdgid/functions.py
index 7208195..8d52ddb 100644
--- a/src/particle/pdgid/functions.py
+++ b/src/particle/pdgid/functions.py
@@ -703,17 +703,27 @@ def j_spin(pdgid: PDGID_TYPE) -> int | None:
return None
if _fundamental_id(pdgid) > 0:
fund = _fundamental_id(pdgid)
- if 0 < fund < 7: # 4th generation quarks not dealt with !
- return 2
- if (
- fund == 9
- ): # Alternative ID for the gluon in codes for glueballs to allow a notation in close analogy with that of hadrons
- return 3
- if 10 < fund < 17: # 4th generation leptons not dealt with !
- return 2
- if 20 < fund < 25:
- return 3
- return None
+ if is_SUSY(pdgid): # susy particles
+ if 0 < fund < 17:
+ return 1
+ if fund == 21:
+ return 2
+ if 22 <= fund < 38:
+ return 2
+ if fund == 39:
+ return 4
+ else: # other particles
+ if 0 < fund < 7: # 4th generation quarks not dealt with !
+ return 2
+ if (
+ fund == 9
+ ): # Alternative ID for the gluon in codes for glueballs to allow a notation in close analogy with that of hadrons
+ return 3
+ if 10 < fund < 17: # 4th generation leptons not dealt with !
+ return 2
+ if 20 < fund < 25:
+ return 3
+ return None
if abs(int(pdgid)) in {1000000010, 1000010010}: # neutron, proton
return 2
if _extra_bits(pdgid) > 0:
|
scikit-hep/particle
|
3e2cf4bb0f0cd3eefd0c3f4ab86ff58c8a3feb5d
|
diff --git a/tests/conftest.py b/tests/conftest.py
index 91fe687..95aa0d5 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -112,6 +112,8 @@ class PDGIDsEnum(IntEnum):
Gravitino = 1000039
STildeL = 1000003
CTildeR = 2000004
+ Neutralino_1 = 1000022
+ Chargino_1 = 1000024
# R-hadrons
R0_1000017 = 1000017
RPlus_TTildeDbar = 1000612
diff --git a/tests/pdgid/test_functions.py b/tests/pdgid/test_functions.py
index 8992ef3..e4d850c 100644
--- a/tests/pdgid/test_functions.py
+++ b/tests/pdgid/test_functions.py
@@ -431,6 +431,8 @@ def test_is_SUSY(PDGIDs):
PDGIDs.Gravitino,
PDGIDs.STildeL,
PDGIDs.CTildeR,
+ PDGIDs.Chargino_1,
+ PDGIDs.Neutralino_1,
PDGIDs.R0_1000017,
)
_non_susy = [pid for pid in PDGIDs if pid not in _susy]
@@ -611,6 +613,7 @@ def test_has_fundamental_anti(PDGIDs):
PDGIDs.AntiElectronStar,
PDGIDs.STildeL,
PDGIDs.CTildeR,
+ PDGIDs.Chargino_1,
PDGIDs.AntiCHadron,
PDGIDs.R0_1000017,
)
@@ -767,7 +770,8 @@ def test_JSL_badly_known_mesons(PDGIDs):
def test_J_non_mesons(PDGIDs):
# TODO: test special particles, supersymmetric particles, R-hadrons, di-quarks, nuclei and pentaquarks
- _J_eq_0 = ()
+ _J_eq_0 = (PDGIDs.STildeL, PDGIDs.CTildeR)
+
_J_eq_1 = (
PDGIDs.Gluon,
PDGIDs.Photon,
@@ -803,10 +807,11 @@ def test_J_non_mesons(PDGIDs):
PDGIDs.LcPlus,
PDGIDs.Lb,
PDGIDs.LtPlus,
- PDGIDs.STildeL,
- PDGIDs.CTildeR,
+ PDGIDs.Gluino,
+ PDGIDs.Neutralino_1,
+ PDGIDs.Chargino_1,
)
- _J_eq_3over2 = (PDGIDs.OmegaMinus,)
+ _J_eq_3over2 = (PDGIDs.OmegaMinus, PDGIDs.Gravitino)
_invalid_pdgids = (PDGIDs.Invalid1, PDGIDs.Invalid2)
# cases not dealt with in the code, where None is returned
_J_eq_None = (PDGIDs.TauPrime, PDGIDs.BPrimeQuark, PDGIDs.TPrimeQuark)
|
spin of SUSY partners
While checking out the package, I found that some of the SUSY partners of the SM quarks are assigned a spin value of 2 (that in the 2s+1 scheme represents a spin-1/2 particle). For instance, the left-handed partner of up-quark `suL`, which is usually represented by id 1000002, is assigned a value of 2 for its `j_spin`.
But the squarks are bosons, so their spins are integral and should be 1 or 3.
Am I missing something? Please let me know if this is a known (and intentional) issue.
|
0.0
|
3e2cf4bb0f0cd3eefd0c3f4ab86ff58c8a3feb5d
|
[
"tests/pdgid/test_functions.py::test_J_non_mesons"
] |
[
"tests/pdgid/test_functions.py::test_charge",
"tests/pdgid/test_functions.py::test_three_charge",
"tests/pdgid/test_functions.py::test_is_valid",
"tests/pdgid/test_functions.py::test_is_quark",
"tests/pdgid/test_functions.py::test_is_sm_quark",
"tests/pdgid/test_functions.py::test_is_lepton",
"tests/pdgid/test_functions.py::test_is_sm_lepton",
"tests/pdgid/test_functions.py::test_is_meson",
"tests/pdgid/test_functions.py::test_is_meson_B_mass_eigenstates",
"tests/pdgid/test_functions.py::test_is_baryon",
"tests/pdgid/test_functions.py::test_is_baryon_old_codes_diffractive",
"tests/pdgid/test_functions.py::test_is_hadron",
"tests/pdgid/test_functions.py::test_is_pentaquark",
"tests/pdgid/test_functions.py::test_pentaquarks_are_baryons",
"tests/pdgid/test_functions.py::test_is_gauge_boson_or_higgs",
"tests/pdgid/test_functions.py::test_is_sm_gauge_boson_or_higgs",
"tests/pdgid/test_functions.py::test_is_generator_specific",
"tests/pdgid/test_functions.py::test_is_special_particle",
"tests/pdgid/test_functions.py::test_is_nucleus",
"tests/pdgid/test_functions.py::test_is_diquark",
"tests/pdgid/test_functions.py::test_is_Rhadron",
"tests/pdgid/test_functions.py::test_is_Qball",
"tests/pdgid/test_functions.py::test_is_dyon",
"tests/pdgid/test_functions.py::test_is_SUSY",
"tests/pdgid/test_functions.py::test_is_technicolor",
"tests/pdgid/test_functions.py::test_is_excited_quark_or_lepton",
"tests/pdgid/test_functions.py::test_has_down",
"tests/pdgid/test_functions.py::test_has_up",
"tests/pdgid/test_functions.py::test_has_strange",
"tests/pdgid/test_functions.py::test_has_charm",
"tests/pdgid/test_functions.py::test_has_bottom",
"tests/pdgid/test_functions.py::test_has_top",
"tests/pdgid/test_functions.py::test_has_fundamental_anti",
"tests/pdgid/test_functions.py::test_JSL_mesons",
"tests/pdgid/test_functions.py::test_JSL_badly_known_mesons",
"tests/pdgid/test_functions.py::test_S_non_mesons",
"tests/pdgid/test_functions.py::test_L_non_mesons",
"tests/pdgid/test_functions.py::test_A",
"tests/pdgid/test_functions.py::test_Z"
] |
{
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-05-09 10:42:30+00:00
|
bsd-3-clause
| 5,366 |
|
scikit-hep__scikit-hep-333
|
diff --git a/skhep/utils/_show_versions.py b/skhep/utils/_show_versions.py
index c552207..5d2108f 100644
--- a/skhep/utils/_show_versions.py
+++ b/skhep/utils/_show_versions.py
@@ -8,10 +8,10 @@ Heavily inspired from :func:`sklearn.show_versions`.
import platform
import sys
-import importlib
+import importlib.metadata
-scipy_deps = ["pip", "setuptools", "numpy", "scipy", "pandas", "matplotlib"]
+scipy_deps = ["setuptools", "pip", "numpy", "scipy", "pandas", "matplotlib"]
skhep_deps = [
@@ -67,13 +67,8 @@ def _get_deps_info(pkgs_list):
for modname in pkgs_list:
try:
- if modname in sys.modules:
- mod = sys.modules[modname]
- else:
- mod = importlib.import_module(modname)
- ver = mod.__version__
- deps_info[modname] = ver
- except ImportError:
+ deps_info[modname] = importlib.metadata.version(modname)
+ except ModuleNotFoundError:
deps_info[modname] = None
return deps_info
|
scikit-hep/scikit-hep
|
f21294fde0072fb49bd1d6effd3f61ed2a30142d
|
diff --git a/tests/utils/test_utils.py b/tests/utils/test_utils.py
new file mode 100644
index 0000000..d6cfe41
--- /dev/null
+++ b/tests/utils/test_utils.py
@@ -0,0 +1,6 @@
+# -*- coding: utf-8 -*-
+from skhep import show_versions
+
+
+def test_show_versions():
+ show_versions()
|
skhep.show_versions() is broken
```python
(scikit-hep) [...]$ python
Python 3.11.6 | packaged by conda-forge | (main, Oct 3 2023, 10:40:35) [GCC 12.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import skhep
>>> skhep.show_versions()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/.../micromamba/envs/scikit-hep/lib/python3.11/site-packages/skhep/utils/_show_versions.py", line 89, in show_versions
deps_info = _get_deps_info(scipy_deps)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/.../micromamba/envs/scikit-hep/lib/python3.11/site-packages/skhep/utils/_show_versions.py", line 73, in _get_deps_info
mod = importlib.import_module(modname)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/.../micromamba/envs/scikit-hep/lib/python3.11/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "<frozen importlib._bootstrap>", line 1204, in _gcd_import
File "<frozen importlib._bootstrap>", line 1176, in _find_and_load
File "<frozen importlib._bootstrap>", line 1147, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 690, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 940, in exec_module
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "/.../micromamba/envs/scikit-hep/lib/python3.11/site-packages/setuptools/__init__.py", line 7, in <module>
import _distutils_hack.override # noqa: F401
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/.../micromamba/envs/scikit-hep/lib/python3.11/site-packages/_distutils_hack/override.py", line 1, in <module>
__import__('_distutils_hack').do_override()
File "/.../micromamba/envs/scikit-hep/lib/python3.11/site-packages/_distutils_hack/__init__.py", line 77, in do_override
ensure_local_distutils()
File "/.../micromamba/envs/scikit-hep/lib/python3.11/site-packages/_distutils_hack/__init__.py", line 64, in ensure_local_distutils
assert '_distutils' in core.__file__, core.__file__
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: /.../micromamba/envs/scikit-hep/lib/python3.11/distutils/core.py
>>>
```
|
0.0
|
f21294fde0072fb49bd1d6effd3f61ed2a30142d
|
[
"tests/utils/test_utils.py::test_show_versions"
] |
[] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2023-11-16 17:26:11+00:00
|
bsd-3-clause
| 5,367 |
|
scikit-hep__vector-319
|
diff --git a/src/vector/_methods.py b/src/vector/_methods.py
index 85befae..c95d5e9 100644
--- a/src/vector/_methods.py
+++ b/src/vector/_methods.py
@@ -2966,32 +2966,103 @@ class Vector2D(Vector, VectorProtocolPlanar):
theta: float | None = None,
eta: float | None = None,
) -> VectorProtocolSpatial:
+ """
+ Converts a 2D vector to 3D vector.
+
+ The scalar longitudinal coordinate is broadcasted for NumPy and Awkward
+ vectors. Only a single longitudinal coordinate should be provided. Generic
+ coordinate counterparts should be provided for the momentum coordinates.
+
+ Examples:
+ >>> import vector
+ >>> vec = vector.VectorObject2D(x=1, y=2)
+ >>> vec.to_Vector3D(z=1)
+ VectorObject3D(x=1, y=2, z=1)
+ >>> vec = vector.MomentumObject2D(px=1, py=2)
+ >>> vec.to_Vector3D(z=4)
+ MomentumObject3D(px=1, py=2, pz=4)
+ """
if sum(x is not None for x in (z, theta, eta)) > 1:
- raise TypeError("Only one non-None parameter allowed")
+ raise TypeError(
+ "At most one longitudinal coordinate (`z`, `theta`, or `eta`) may be assigned (non-None)"
+ )
- coord_value = 0.0
+ l_value = 0.0
l_type: type[Longitudinal] = LongitudinalZ
if z is not None:
- coord_value = z
+ l_value = z
elif eta is not None:
- coord_value = eta
+ l_value = eta
l_type = LongitudinalEta
elif theta is not None:
- coord_value = theta
+ l_value = theta
l_type = LongitudinalTheta
return self._wrap_result(
type(self),
- (*self.azimuthal.elements, coord_value),
+ (*self.azimuthal.elements, l_value),
[_aztype(self), l_type, None],
1,
)
- def to_Vector4D(self) -> VectorProtocolLorentz:
+ def to_Vector4D(
+ self,
+ *,
+ z: float | None = None,
+ theta: float | None = None,
+ eta: float | None = None,
+ t: float | None = None,
+ tau: float | None = None,
+ ) -> VectorProtocolLorentz:
+ """
+ Converts a 2D vector to 4D vector.
+
+ The scalar longitudinal and temporal coordinates are broadcasted for NumPy and
+ Awkward vectors. Only a single longitudinal and temporal coordinate should be
+ provided. Generic coordinate counterparts should be provided for the momentum
+ coordinates.
+
+ Examples:
+ >>> import vector
+ >>> vec = vector.VectorObject2D(x=1, y=2)
+ >>> vec.to_Vector4D(z=3, t=4)
+ VectorObject4D(x=1, y=2, z=3, t=4)
+ >>> vec = vector.MomentumObject2D(px=1, py=2)
+ >>> vec.to_Vector4D(z=4, t=4)
+ MomentumObject4D(px=1, py=2, pz=4, E=4)
+ """
+ if sum(x is not None for x in (z, theta, eta)) > 1:
+ raise TypeError(
+ "At most one longitudinal coordinate (`z`, `theta`, or `eta`) may be assigned (non-None)"
+ )
+ elif sum(x is not None for x in (t, tau)) > 1:
+ raise TypeError(
+ "At most one longitudinal coordinate (`t`, `tau`) may be assigned (non-None)"
+ )
+
+ t_value = 0.0
+ t_type: type[Temporal] = TemporalT
+ if t is not None:
+ t_value = t
+ elif tau is not None:
+ t_value = tau
+ t_type = TemporalTau
+
+ l_value = 0.0
+ l_type: type[Longitudinal] = LongitudinalZ
+ if z is not None:
+ l_value = z
+ elif eta is not None:
+ l_value = eta
+ l_type = LongitudinalEta
+ elif theta is not None:
+ l_value = theta
+ l_type = LongitudinalTheta
+
return self._wrap_result(
type(self),
- (*self.azimuthal.elements, 0, 0),
- [_aztype(self), LongitudinalZ, TemporalT],
+ (*self.azimuthal.elements, l_value, t_value),
+ [_aztype(self), l_type, t_type],
1,
)
@@ -3008,11 +3079,45 @@ class Vector3D(Vector, VectorProtocolSpatial):
def to_Vector3D(self) -> VectorProtocolSpatial:
return self
- def to_Vector4D(self) -> VectorProtocolLorentz:
+ def to_Vector4D(
+ self,
+ *,
+ t: float | None = None,
+ tau: float | None = None,
+ ) -> VectorProtocolLorentz:
+ """
+ Converts a 3D vector to 4D vector.
+
+ The scalar temporal coordinate are broadcasted for NumPy and Awkward vectors.
+ Only a single temporal coordinate should be provided. Generic coordinate
+ counterparts should be provided for the momentum coordinates.
+
+ Examples:
+ >>> import vector
+ >>> vec = vector.VectorObject3D(x=1, y=2, z=3)
+ >>> vec.to_Vector4D(t=4)
+ VectorObject4D(x=1, y=2, z=3, t=4)
+ >>> vec = vector.MomentumObject3D(px=1, py=2, pz=3)
+ >>> vec.to_Vector4D(tau=4)
+ MomentumObject4D(px=1, py=2, pz=3, mass=4)
+ """
+ if sum(x is not None for x in (t, tau)) > 1:
+ raise TypeError(
+ "At most one longitudinal coordinate (`t`, `tau`) may be assigned (non-None)"
+ )
+
+ t_value = 0.0
+ t_type: type[Temporal] = TemporalT
+ if t is not None:
+ t_value = t
+ elif tau is not None:
+ t_value = tau
+ t_type = TemporalTau
+
return self._wrap_result(
type(self),
- self.azimuthal.elements + self.longitudinal.elements + (0,),
- [_aztype(self), _ltype(self), TemporalT],
+ (*self.azimuthal.elements, *self.longitudinal.elements, t_value),
+ [_aztype(self), _ltype(self), t_type],
1,
)
diff --git a/src/vector/backends/object.py b/src/vector/backends/object.py
index 6891a07..0f44ce5 100644
--- a/src/vector/backends/object.py
+++ b/src/vector/backends/object.py
@@ -1259,7 +1259,7 @@ class MomentumObject3D(SpatialMomentum, VectorObject3D):
for x in lnames:
y = _repr_generic_to_momentum.get(x, x)
out.append(f"{y}={getattr(self.longitudinal, x)}")
- return "vector.MomentumObject3D(" + ", ".join(out) + ")"
+ return "MomentumObject3D(" + ", ".join(out) + ")"
def __array__(self) -> FloatArray:
from vector.backends.numpy import MomentumNumpy3D
|
scikit-hep/vector
|
17af58fb958145da2b2c2e3acf1192b633575ad1
|
diff --git a/tests/backends/test_awkward.py b/tests/backends/test_awkward.py
index 6ad8766..c8e043c 100644
--- a/tests/backends/test_awkward.py
+++ b/tests/backends/test_awkward.py
@@ -9,11 +9,58 @@ import pytest
import vector
-pytest.importorskip("awkward")
+ak = pytest.importorskip("awkward")
pytestmark = pytest.mark.awkward
+def test_dimension_conversion():
+ # 2D -> 3D
+ vec = vector.Array(
+ [
+ [{"x": 1, "y": 1.1}, {"x": 2, "y": 2.1}],
+ [],
+ ]
+ )
+ assert ak.all(vec.to_Vector3D(z=1).z == 1)
+ assert ak.all(vec.to_Vector3D(eta=1).eta == 1)
+ assert ak.all(vec.to_Vector3D(theta=1).theta == 1)
+
+ assert ak.all(vec.to_Vector3D(z=1).x == vec.x)
+ assert ak.all(vec.to_Vector3D(z=1).y == vec.y)
+
+ # 2D -> 4D
+ assert ak.all(vec.to_Vector4D(z=1, t=1).t == 1)
+ assert ak.all(vec.to_Vector4D(z=1, t=1).z == 1)
+ assert ak.all(vec.to_Vector4D(eta=1, t=1).eta == 1)
+ assert ak.all(vec.to_Vector4D(eta=1, t=1).t == 1)
+ assert ak.all(vec.to_Vector4D(theta=1, t=1).theta == 1)
+ assert ak.all(vec.to_Vector4D(theta=1, t=1).t == 1)
+ assert ak.all(vec.to_Vector4D(z=1, tau=1).z == 1)
+ assert ak.all(vec.to_Vector4D(z=1, tau=1).tau == 1)
+ assert ak.all(vec.to_Vector4D(eta=1, tau=1).eta == 1)
+ assert ak.all(vec.to_Vector4D(eta=1, tau=1).tau == 1)
+ assert ak.all(vec.to_Vector4D(theta=1, tau=1).theta == 1)
+ assert ak.all(vec.to_Vector4D(theta=1, tau=1).tau == 1)
+
+ assert ak.all(vec.to_Vector4D(z=1, t=1).x == vec.x)
+ assert ak.all(vec.to_Vector4D(z=1, t=1).y == vec.y)
+
+ # 3D -> 4D
+ vec = vector.Array(
+ [
+ [{"x": 1, "y": 1.1, "z": 1.2}, {"x": 2, "y": 2.1, "z": 2.2}],
+ [],
+ ]
+ )
+ assert ak.all(vec.to_Vector4D(t=1).t == 1)
+ assert ak.all(vec.to_Vector4D(tau=1).tau == 1)
+
+ assert ak.all(vec.to_Vector4D(t=1).x == vec.x)
+ assert ak.all(vec.to_Vector4D(t=1).y == vec.y)
+ assert ak.all(vec.to_Vector4D(t=1).z == vec.z)
+
+
def test_type_checks():
with pytest.raises(TypeError):
vector.Array(
diff --git a/tests/backends/test_numpy.py b/tests/backends/test_numpy.py
index 89d433e..47a5272 100644
--- a/tests/backends/test_numpy.py
+++ b/tests/backends/test_numpy.py
@@ -14,6 +14,49 @@ import pytest
import vector.backends.numpy
+def test_dimension_conversion():
+ # 2D -> 3D
+ vec = vector.VectorNumpy2D(
+ [(1.0, 1.0), (2.0, 2.0)],
+ dtype=[("x", float), ("y", float)],
+ )
+ assert all(vec.to_Vector3D(z=1).z == 1)
+ assert all(vec.to_Vector3D(eta=1).eta == 1)
+ assert all(vec.to_Vector3D(theta=1).theta == 1)
+
+ assert all(vec.to_Vector3D(z=1).x == vec.x)
+ assert all(vec.to_Vector3D(z=1).y == vec.y)
+
+ # 2D -> 4D
+ assert all(vec.to_Vector4D(z=1, t=1).t == 1)
+ assert all(vec.to_Vector4D(z=1, t=1).z == 1)
+ assert all(vec.to_Vector4D(eta=1, t=1).eta == 1)
+ assert all(vec.to_Vector4D(eta=1, t=1).t == 1)
+ assert all(vec.to_Vector4D(theta=1, t=1).theta == 1)
+ assert all(vec.to_Vector4D(theta=1, t=1).t == 1)
+ assert all(vec.to_Vector4D(z=1, tau=1).z == 1)
+ assert all(vec.to_Vector4D(z=1, tau=1).tau == 1)
+ assert all(vec.to_Vector4D(eta=1, tau=1).eta == 1)
+ assert all(vec.to_Vector4D(eta=1, tau=1).tau == 1)
+ assert all(vec.to_Vector4D(theta=1, tau=1).theta == 1)
+ assert all(vec.to_Vector4D(theta=1, tau=1).tau == 1)
+
+ assert all(vec.to_Vector4D(z=1, t=1).x == vec.x)
+ assert all(vec.to_Vector4D(z=1, t=1).y == vec.y)
+
+ # 3D -> 4D
+ vec = vector.VectorNumpy3D(
+ [(1.0, 1.0, 1.0), (2.0, 2.0, 2.0)],
+ dtype=[("x", float), ("y", float), ("z", float)],
+ )
+ assert all(vec.to_Vector4D(t=1).t == 1)
+ assert all(vec.to_Vector4D(tau=1).tau == 1)
+
+ assert all(vec.to_Vector4D(t=1).x == vec.x)
+ assert all(vec.to_Vector4D(t=1).y == vec.y)
+ assert all(vec.to_Vector4D(t=1).z == vec.z)
+
+
def test_type_checks():
with pytest.raises(TypeError):
vector.backends.numpy.VectorNumpy2D(
diff --git a/tests/backends/test_object.py b/tests/backends/test_object.py
index bad9574..a976611 100644
--- a/tests/backends/test_object.py
+++ b/tests/backends/test_object.py
@@ -11,6 +11,43 @@ import pytest
import vector
+def test_dimension_conversion():
+ # 2D -> 3D
+ vec = vector.VectorObject2D(x=1, y=2)
+ assert vec.to_Vector3D(z=1).z == 1
+ assert vec.to_Vector3D(eta=1).eta == 1
+ assert vec.to_Vector3D(theta=1).theta == 1
+
+ assert vec.to_Vector3D(z=1).x == vec.x
+ assert vec.to_Vector3D(z=1).y == vec.y
+
+ # 2D -> 4D
+ assert vec.to_Vector4D(z=1, t=1).z == 1
+ assert vec.to_Vector4D(z=1, t=1).t == 1
+ assert vec.to_Vector4D(eta=1, t=1).eta == 1
+ assert vec.to_Vector4D(eta=1, t=1).t == 1
+ assert vec.to_Vector4D(theta=1, t=1).theta == 1
+ assert vec.to_Vector4D(theta=1, t=1).t == 1
+ assert vec.to_Vector4D(z=1, tau=1).z == 1
+ assert vec.to_Vector4D(z=1, tau=1).tau == 1
+ assert vec.to_Vector4D(eta=1, tau=1).eta == 1
+ assert vec.to_Vector4D(eta=1, tau=1).tau == 1
+ assert vec.to_Vector4D(theta=1, tau=1).theta == 1
+ assert vec.to_Vector4D(theta=1, tau=1).tau == 1
+
+ assert vec.to_Vector4D(z=1, t=1).x == vec.x
+ assert vec.to_Vector4D(z=1, t=1).y == vec.y
+
+ # 3D -> 4D
+ vec = vector.VectorObject3D(x=1, y=2, z=3)
+ assert vec.to_Vector4D(t=1).t == 1
+ assert vec.to_Vector4D(tau=1).tau == 1
+
+ assert vec.to_Vector4D(t=1).x == vec.x
+ assert vec.to_Vector4D(t=1).y == vec.y
+ assert vec.to_Vector4D(t=1).z == vec.z
+
+
def test_constructors_2D():
vec = vector.VectorObject2D(x=1, y=2)
assert vec.x == 1
|
Allow users to pass new coordinate values in `to_Vector{X}D` and `to_{new coordinate names}`
### Describe the potential feature
Right now users can convert a 2D vector to 3D or 4D using `to_Vector3D()` and `to_Vector4D()`, but the returned vector always possesses 0 as the value of the new generated coordinate.
Example:
```py
In [1]: import vector
In [2]: v = vector.obj(x=1, y=2)
In [3]: v.to_Vector3D()
Out[3]: VectorObject3D(x=1, y=2, z=0)
In [4]: v.to_Vector3D(z=1)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In [4], line 1
----> 1 v.to_Vector3D(z=1)
TypeError: to_Vector3D() got an unexpected keyword argument 'z'
```
This can be extended such that the users can pass in the value of the newly added coordinate.
Example:
```py
In [1]: import vector
In [2]: v = vector.obj(x=1, y=2)
In [3]: v
Out[3]: VectorObject2D(x=1, y=2)
In [4]: v.to_Vector3D(z=1)
Out[4]: VectorObject3D(x=1, y=2, z=1)
```
Similarly for 3D and 4D vectors. This can then be further propagated to the `to_{new coordinate name}` (`to_xyzt`, `to_rhophi`, ...) methods.
### Motivation
The discussion on gitter (between @jpivarski and @henryiii). Quoting a part here -
> For 3D and 4D vectors, you probably want a specialized function, since that 4th dimension is qualitatively different from the other 3. Maybe something like scale_spatial(-1). (There's already a scale; it does the same thing as multiplication by a scalar.)
>
> But even without that, it would also be nice if functions like to_Vector4D, which is increasing the dimensionality of the 3D vector (x.to_Vector3D()) in this case, could take parameters like E= or mass= to assign a value to the new dimension. As it is, to_Vector4D applied to a 3D vector creates a 4th dimension whose value is 0 in Cartesian coordinates. To get the original x.E in it, I had to add vectors. If the coordinate were expressed as a mass, the above trick wouldn't work with x.mass because it would add after assigning a mass; non-Cartesian coordinates don't commute.
### Possible Implementation
Changing this -
https://github.com/scikit-hep/vector/blob/93cb78a017707f42b961b3a74e34ffb79c37f85d/src/vector/_methods.py#L1701-L1707
to this -
```py
def to_Vector3D(self, **coord) -> VectorProtocolSpatial:
if len(coord) > 1:
raise ArgumentError(coord, "can be `z`, `theta`, or `eta`")
coord_type, coord_value = list(coord.keys())[0], list(coord.values())[0]
if coord_type == "z":
l_type = LongitudinalZ
elif coord_type == "eta":
l_type = LongitudinalEta
elif coord_type == "theta":
l_type = LongitudinalTheta
return self._wrap_result(
type(self),
self.azimuthal.elements + (coord_value,),
[_aztype(self), l_type, None],
1,
)
```
works -
```py
In [1]: import vector
In [2]: v = vector.obj(x=1, py=2)
In [3]: v.to_Vector3D(z=3)
Out[3]: vector.MomentumObject3D(px=1, py=2, pz=3)
In [4]: v.to_Vector3D(eta=3)
Out[4]: vector.MomentumObject3D(px=1, py=2, eta=3)
In [5]: v.to_Vector3D(theta=3)
Out[5]: vector.MomentumObject3D(px=1, py=2, theta=3)
```
|
0.0
|
17af58fb958145da2b2c2e3acf1192b633575ad1
|
[
"tests/backends/test_awkward.py::test_dimension_conversion",
"tests/backends/test_numpy.py::test_dimension_conversion",
"tests/backends/test_object.py::test_dimension_conversion"
] |
[
"tests/backends/test_awkward.py::test_type_checks",
"tests/backends/test_awkward.py::test_basic",
"tests/backends/test_awkward.py::test_rotateZ",
"tests/backends/test_awkward.py::test_projection",
"tests/backends/test_awkward.py::test_add",
"tests/backends/test_awkward.py::test_ufuncs",
"tests/backends/test_awkward.py::test_zip",
"tests/backends/test_numpy.py::test_type_checks",
"tests/backends/test_numpy.py::test_xy",
"tests/backends/test_numpy.py::test_rhophi",
"tests/backends/test_numpy.py::test_pickle_vector_numpy_2d",
"tests/backends/test_numpy.py::test_pickle_momentum_numpy_2d",
"tests/backends/test_numpy.py::test_pickle_vector_numpy_3d",
"tests/backends/test_numpy.py::test_pickle_momentum_numpy_3d",
"tests/backends/test_numpy.py::test_pickle_vector_numpy_4d",
"tests/backends/test_numpy.py::test_pickle_momentum_numpy_4d",
"tests/backends/test_object.py::test_constructors_2D",
"tests/backends/test_object.py::test_constructors_3D",
"tests/backends/test_object.py::test_array_casting"
] |
{
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-02-22 19:50:37+00:00
|
bsd-3-clause
| 5,368 |
|
scikit-hep__vector-376
|
diff --git a/src/vector/backends/numpy.py b/src/vector/backends/numpy.py
index 2060228..a64d08b 100644
--- a/src/vector/backends/numpy.py
+++ b/src/vector/backends/numpy.py
@@ -68,7 +68,7 @@ def _reduce_sum(
axis: int | None = None,
dtype: typing.Any = None,
out: typing.Any = None,
- keepdims: bool | None = None,
+ keepdims: bool = False,
initial: typing.Any = None,
where: typing.Any = None,
) -> T:
@@ -753,7 +753,7 @@ class VectorNumpy(Vector, GetItem):
axis: int | None = None,
dtype: numpy.dtype[typing.Any] | str | None = None,
out: ArrayLike | None = None,
- keepdims: bool | None = None,
+ keepdims: bool = False,
initial: typing.Any = None,
where: typing.Any = None,
) -> SameVectorNumpyType:
|
scikit-hep/vector
|
bb92f086de4c4242a7845c19e63cad539d55d50f
|
diff --git a/tests/backends/test_numpy.py b/tests/backends/test_numpy.py
index d7bc78a..0eea351 100644
--- a/tests/backends/test_numpy.py
+++ b/tests/backends/test_numpy.py
@@ -247,7 +247,7 @@ def test_sum_2d():
[[(1, 0.1), (4, 0.2), (0, 0)], [(1, 0.3), (4, 0.4), (1, 0.1)]],
dtype=[("rho", numpy.float64), ("phi", numpy.float64)],
)
- assert numpy.sum(v, axis=0, keepdims=True).allclose(
+ assert numpy.sum(v, axis=0, keepdims=False).allclose(
vector.VectorNumpy2D(
[
[
@@ -269,6 +269,20 @@ def test_sum_2d():
dtype=[("x", numpy.float64), ("y", numpy.float64)],
)
)
+ assert numpy.sum(v, axis=0).allclose(
+ vector.VectorNumpy2D(
+ [
+ (1.950340654403632, 0.3953536233081677),
+ (7.604510287376507, 2.3523506924148467),
+ (0.9950041652780258, 0.09983341664682815),
+ ],
+ dtype=[("x", numpy.float64), ("y", numpy.float64)],
+ )
+ )
+ assert numpy.sum(v, axis=0, keepdims=False).shape == (3,)
+ assert numpy.sum(v, axis=0, keepdims=True).shape == (1, 3)
+ assert numpy.sum(v, axis=0).shape == (3,)
+
assert numpy.sum(v, axis=1, keepdims=True).allclose(
vector.VectorNumpy2D(
[[(4.91527048, 0.89451074)], [(5.63458463, 1.95302699)]],
@@ -281,6 +295,15 @@ def test_sum_2d():
dtype=[("x", numpy.float64), ("y", numpy.float64)],
)
)
+ assert numpy.sum(v, axis=1).allclose(
+ vector.VectorNumpy2D(
+ [(4.91527048, 0.89451074), (5.63458463, 1.95302699)],
+ dtype=[("x", numpy.float64), ("y", numpy.float64)],
+ )
+ )
+ assert numpy.sum(v, axis=1, keepdims=False).shape == (2,)
+ assert numpy.sum(v, axis=1, keepdims=True).shape == (2, 1)
+ assert numpy.sum(v, axis=1).shape == (2,)
def test_sum_3d():
@@ -317,6 +340,20 @@ def test_sum_3d():
dtype=[("x", numpy.float64), ("y", numpy.float64), ("z", numpy.float64)],
)
)
+ assert numpy.sum(v, axis=0).allclose(
+ vector.VectorNumpy3D(
+ [
+ (2.0, 4.0, 25.55454594),
+ (8.0, 10.0, 33.36521103),
+ (1.0, 1.0, -0.48314535),
+ ],
+ dtype=[("x", numpy.float64), ("y", numpy.float64), ("z", numpy.float64)],
+ )
+ )
+ assert numpy.sum(v, axis=0, keepdims=False).shape == (3,)
+ assert numpy.sum(v, axis=0, keepdims=True).shape == (1, 3)
+ assert numpy.sum(v, axis=0).shape == (3,)
+
assert numpy.sum(v, axis=1, keepdims=True).allclose(
vector.VectorNumpy3D(
[[(5.0, 7.0, 53.87369799)], [(6.0, 8.0, 4.56291362)]],
@@ -329,6 +366,15 @@ def test_sum_3d():
dtype=[("x", numpy.float64), ("y", numpy.float64), ("z", numpy.float64)],
)
)
+ assert numpy.sum(v, axis=1).allclose(
+ vector.VectorNumpy3D(
+ [(5.0, 7.0, 53.87369799), (6.0, 8.0, 4.56291362)],
+ dtype=[("x", numpy.float64), ("y", numpy.float64), ("z", numpy.float64)],
+ )
+ )
+ assert numpy.sum(v, axis=1, keepdims=False).shape == (2,)
+ assert numpy.sum(v, axis=1, keepdims=True).shape == (2, 1)
+ assert numpy.sum(v, axis=1).shape == (2,)
def test_sum_4d():
@@ -352,6 +398,15 @@ def test_sum_4d():
(8, 10, 12, 2),
(1, 1, 1, 3),
]
+ assert numpy.sum(v, axis=0).tolist() == [
+ (2, 4, 6, 12),
+ (8, 10, 12, 2),
+ (1, 1, 1, 3),
+ ]
+ assert numpy.sum(v, axis=0, keepdims=False).shape == (3,)
+ assert numpy.sum(v, axis=0, keepdims=True).shape == (1, 3)
+ assert numpy.sum(v, axis=0).shape == (3,)
+
assert numpy.sum(v, axis=1, keepdims=True).tolist() == [
[(5, 7, 9, 9)],
[(6, 8, 10, 8)],
@@ -360,6 +415,13 @@ def test_sum_4d():
(5, 7, 9, 9),
(6, 8, 10, 8),
]
+ assert numpy.sum(v, axis=1).tolist() == [
+ (5, 7, 9, 9),
+ (6, 8, 10, 8),
+ ]
+ assert numpy.sum(v, axis=1, keepdims=False).shape == (2,)
+ assert numpy.sum(v, axis=1, keepdims=True).shape == (2, 1)
+ assert numpy.sum(v, axis=1).shape == (2,)
def test_count_nonzero_2d():
|
Summation of Vectors (defined from px,py,pz,M data) does not work as expected
### Vector Version
1.1.0
### Python Version
3.11
### OS / Environment
Mac OS
### Describe the bug
I had a (I thought) fairly simple use case
* generate events with 10 particles iwth random momenta for particle of known mass 1
* determine the total 4 vector
and I expected this to work
```
p = np.random.uniform(size = (123,10,3))
m = np.zeros((123,10,1))
V = np.concatenate([p,m],axis=-1)
vecs = vector.array({
'px': V[:,:,0],
'py': V[:,:,1],
'pz': V[:,:,2],
'M': V[:,:,3]
})
vecs.sum(axis=1)
```
but I got this error message
```
File ~/.pyenv/versions/3.11.4/envs/garbargeml/lib/python3.11/site-packages/numpy/core/fromnumeric.py:88, in _wrapreduction(obj, ufunc, method, axis, dtype, out, **kwargs)
85 else:
86 return reduction(axis=axis, out=out, **passkwargs)
---> 88 return ufunc.reduce(obj, axis, dtype, out, **passkwargs)
TypeError: 'NoneType' object cannot be interpreted as an integer
```
To me that seems like sth that would be in scope for `vector`
@jpivarski came up with this solution using awkward, but this should not require awkward
```
>>> import awkward as ak, numpy as np
>>> import vector
>>> vector.register_awkward()
>>> p = np.random.uniform(size = (123,10,3))
>>> m = np.zeros((123,10,1))
>>> V = np.concatenate([p,m],axis=-1)
>>> vecs = ak.zip({
... 'px': V[:,:,0],
... 'py': V[:,:,1],
... 'pz': V[:,:,2],
... 'M': V[:,:,3]
... }, with_name="Momentum4D")
>>> ak.sum(vecs, axis=1)
<MomentumArray4D [{t: 7.77, z: 3.4, x: 3.08, ...}, ...] type='123 * Momentu...'>
```
### Any additional but relevant log output
_No response_
|
0.0
|
bb92f086de4c4242a7845c19e63cad539d55d50f
|
[
"tests/backends/test_numpy.py::test_sum_2d",
"tests/backends/test_numpy.py::test_sum_3d",
"tests/backends/test_numpy.py::test_sum_4d"
] |
[
"tests/backends/test_numpy.py::test_dimension_conversion",
"tests/backends/test_numpy.py::test_type_checks",
"tests/backends/test_numpy.py::test_xy",
"tests/backends/test_numpy.py::test_rhophi",
"tests/backends/test_numpy.py::test_pickle_vector_numpy_2d",
"tests/backends/test_numpy.py::test_pickle_momentum_numpy_2d",
"tests/backends/test_numpy.py::test_pickle_vector_numpy_3d",
"tests/backends/test_numpy.py::test_pickle_momentum_numpy_3d",
"tests/backends/test_numpy.py::test_pickle_vector_numpy_4d",
"tests/backends/test_numpy.py::test_pickle_momentum_numpy_4d",
"tests/backends/test_numpy.py::test_count_nonzero_2d",
"tests/backends/test_numpy.py::test_count_nonzero_3d",
"tests/backends/test_numpy.py::test_count_nonzero_4d"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2023-09-06 15:40:24+00:00
|
bsd-3-clause
| 5,369 |
|
scikit-hep__vector-438
|
diff --git a/src/vector/backends/awkward.py b/src/vector/backends/awkward.py
index eefb1e1..f29bc03 100644
--- a/src/vector/backends/awkward.py
+++ b/src/vector/backends/awkward.py
@@ -673,7 +673,13 @@ class VectorAwkward:
fields = ak.fields(self)
if num_vecargs == 1:
for name in fields:
- if name not in ("x", "y", "rho", "phi"):
+ if name not in (
+ "x",
+ "y",
+ "rho",
+ "pt",
+ "phi",
+ ):
names.append(name)
arrays.append(self[name])
@@ -720,12 +726,20 @@ class VectorAwkward:
"x",
"y",
"rho",
+ "pt",
"phi",
"z",
+ "pz",
"theta",
"eta",
"t",
"tau",
+ "m",
+ "M",
+ "mass",
+ "e",
+ "E",
+ "energy",
):
names.append(name)
arrays.append(self[name])
@@ -774,7 +788,17 @@ class VectorAwkward:
fields = ak.fields(self)
if num_vecargs == 1:
for name in fields:
- if name not in ("x", "y", "rho", "phi", "z", "theta", "eta"):
+ if name not in (
+ "x",
+ "y",
+ "rho",
+ "pt",
+ "phi",
+ "z",
+ "pz",
+ "theta",
+ "eta",
+ ):
names.append(name)
arrays.append(self[name])
@@ -831,12 +855,20 @@ class VectorAwkward:
"x",
"y",
"rho",
+ "pt",
"phi",
"z",
+ "pz",
"theta",
"eta",
"t",
"tau",
+ "m",
+ "M",
+ "mass",
+ "e",
+ "E",
+ "energy",
):
names.append(name)
arrays.append(self[name])
@@ -897,12 +929,20 @@ class VectorAwkward:
"x",
"y",
"rho",
+ "pt",
"phi",
"z",
+ "pz",
"theta",
"eta",
"t",
"tau",
+ "m",
+ "M",
+ "mass",
+ "e",
+ "E",
+ "energy",
):
names.append(name)
arrays.append(self[name])
|
scikit-hep/vector
|
b907615f5035b4bdad2335f2c8d319fff8fd3d9f
|
diff --git a/tests/backends/test_awkward.py b/tests/backends/test_awkward.py
index 85caa2c..0ad09c4 100644
--- a/tests/backends/test_awkward.py
+++ b/tests/backends/test_awkward.py
@@ -6,7 +6,9 @@
from __future__ import annotations
import importlib.metadata
+import numbers
+import numpy as np
import packaging.version
import pytest
@@ -895,3 +897,39 @@ def test_momentum_preservation():
# 4D + 3D.like(4D) = 4D
assert isinstance(v3 + v2.like(v3), MomentumAwkward4D)
assert isinstance(v2.like(v3) + v3, MomentumAwkward4D)
+
+
+def test_subclass_fields():
+ @ak.mixin_class(vector.backends.awkward.behavior)
+ class TwoVector(MomentumAwkward2D):
+ pass
+
+ @ak.mixin_class(vector.backends.awkward.behavior)
+ class ThreeVector(MomentumAwkward3D):
+ pass
+
+ @ak.mixin_class(vector.backends.awkward.behavior)
+ class LorentzVector(MomentumAwkward4D):
+ @ak.mixin_class_method(np.divide, {numbers.Number})
+ def divide(self, factor):
+ return self.scale(1 / factor)
+
+ LorentzVectorArray.ProjectionClass2D = TwoVectorArray # noqa: F821
+ LorentzVectorArray.ProjectionClass3D = ThreeVectorArray # noqa: F821
+ LorentzVectorArray.ProjectionClass4D = LorentzVectorArray # noqa: F821
+ LorentzVectorArray.MomentumClass = LorentzVectorArray # noqa: F821
+
+ vec = ak.zip(
+ {
+ "pt": [[1, 2], [], [3], [4]],
+ "eta": [[1.2, 1.4], [], [1.6], [3.4]],
+ "phi": [[0.3, 0.4], [], [0.5], [0.6]],
+ "energy": [[50, 51], [], [52], [60]],
+ },
+ with_name="LorentzVector",
+ behavior=vector.backends.awkward.behavior,
+ )
+
+ assert vec.like(vector.obj(x=1, y=2)).fields == ["rho", "phi"]
+ assert vec.like(vector.obj(x=1, y=2, z=3)).fields == ["rho", "phi", "eta"]
+ assert (vec / 2).fields == ["rho", "phi", "eta", "t"]
|
Preserve field alias under addition
A user [asked a question](https://stackoverflow.com/questions/72906846/can-i-recalculate-the-energy-of-an-awkward-array-of-vectors-by-declaring-a-new-m/72929486?noredirect=1#comment128831169_72929486) about using Vector, and in answering I realised that field aliases are not preserved under addition. I assume this generalises to all operations given [the source that I think is responsible](
https://github.com/scikit-hep/vector/blob/4e756fe2cd8a3430260e1cf4cf008874cfc1bb3c/src/vector/backends/awkward.py#L886-L888) currently hard-codes the name.
I think we should try to preserve the existing aliasing where possible. At present, users need to know that a particular alias is "canonical", and that their array could change fields under any operation.
|
0.0
|
b907615f5035b4bdad2335f2c8d319fff8fd3d9f
|
[
"tests/backends/test_awkward.py::test_subclass_fields"
] |
[
"tests/backends/test_awkward.py::test_dimension_conversion",
"tests/backends/test_awkward.py::test_type_checks",
"tests/backends/test_awkward.py::test_basic",
"tests/backends/test_awkward.py::test_rotateZ",
"tests/backends/test_awkward.py::test_projection",
"tests/backends/test_awkward.py::test_add",
"tests/backends/test_awkward.py::test_ufuncs",
"tests/backends/test_awkward.py::test_zip",
"tests/backends/test_awkward.py::test_sum_2d",
"tests/backends/test_awkward.py::test_sum_3d",
"tests/backends/test_awkward.py::test_sum_4d",
"tests/backends/test_awkward.py::test_count_nonzero_2d",
"tests/backends/test_awkward.py::test_count_nonzero_3d",
"tests/backends/test_awkward.py::test_count_nonzero_4d",
"tests/backends/test_awkward.py::test_count_2d",
"tests/backends/test_awkward.py::test_count_3d",
"tests/backends/test_awkward.py::test_count_4d",
"tests/backends/test_awkward.py::test_like",
"tests/backends/test_awkward.py::test_handler_of",
"tests/backends/test_awkward.py::test_momentum_coordinate_transforms",
"tests/backends/test_awkward.py::test_momentum_preservation"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2024-03-14 14:02:14+00:00
|
bsd-3-clause
| 5,370 |
|
scikit-hep__vector-444
|
diff --git a/src/vector/backends/object.py b/src/vector/backends/object.py
index ddc44ca..18a202b 100644
--- a/src/vector/backends/object.py
+++ b/src/vector/backends/object.py
@@ -387,7 +387,7 @@ class VectorObject(Vector):
return _replace_data(self, numpy.true_divide(self, other)) # type: ignore[call-overload]
def __pow__(self, other: float) -> float:
- return numpy.power(self, other) # type: ignore[call-overload]
+ return numpy.square(self) if other == 2 else numpy.power(self, other) # type: ignore[call-overload]
def __matmul__(self, other: VectorProtocol) -> float:
return numpy.matmul(self, other) # type: ignore[call-overload]
|
scikit-hep/vector
|
06a733784d8df77d2fe4ad0f87051f725fd6a831
|
diff --git a/tests/compute/test_isclose.py b/tests/compute/test_isclose.py
index 62c9449..a101046 100644
--- a/tests/compute/test_isclose.py
+++ b/tests/compute/test_isclose.py
@@ -62,8 +62,6 @@ def test_spatial_object():
for t1 in "xyz", "xytheta", "xyeta", "rhophiz", "rhophitheta", "rhophieta":
for t2 in "xyz", "xytheta", "xyeta", "rhophiz", "rhophitheta", "rhophieta":
- print(t1, t2)
-
transformed1, transformed2 = (
getattr(v1, "to_" + t1)(),
getattr(v2, "to_" + t2)(),
diff --git a/tests/test_issues.py b/tests/test_issues.py
index d0be1ce..c1d509e 100644
--- a/tests/test_issues.py
+++ b/tests/test_issues.py
@@ -8,6 +8,7 @@ from __future__ import annotations
import os
import pickle
+import numpy as np
import pytest
import vector
@@ -47,3 +48,16 @@ def test_issue_161():
with open(file_path, "rb") as f:
a = ak.from_buffers(*pickle.load(f))
repro(generator_like_jet_constituents=a.constituents)
+
+
+def test_issue_443():
+ ak = pytest.importorskip("awkward")
+ vector.register_awkward()
+
+ assert vector.array({"E": [1], "px": [1], "py": [1], "pz": [1]}) ** 2 == np.array(
+ [-2.0]
+ )
+ assert ak.zip(
+ {"E": [1], "px": [1], "py": [1], "pz": [1]}, with_name="Momentum4D"
+ ) ** 2 == ak.Array([-2])
+ assert vector.obj(E=1, px=1, py=1, pz=1) ** 2 == -2
|
`q**2` is always positive for vector.MomentumObject4D
### Vector Version
1.3.1
### Python Version
3.11.4
### OS / Environment
Kubuntu 22.04
vector is installed via pip inside a conda environment
### Describe the bug
When calculating `q**2` of a 4-vector that is created from `vector.obj`, the value is always positive, even when it should not be:
```python
>>> vector.obj(E=1, px=1, py=1, pz=1)**2
2.0000000000000004
```
For numpy vector arrays, the behavior is correct and as expected:
```python
>>> vector.array({"E": [1], "px": [1], "py": [1], "pz": [1]})**2
array([-2.])
```
I have not tested other backends (e.g. awkward).
### Any additional but relevant log output
_No response_
|
0.0
|
06a733784d8df77d2fe4ad0f87051f725fd6a831
|
[
"tests/test_issues.py::test_issue_443"
] |
[
"tests/compute/test_isclose.py::test_planar_object",
"tests/compute/test_isclose.py::test_planar_numpy",
"tests/compute/test_isclose.py::test_spatial_object",
"tests/compute/test_isclose.py::test_spatial_numpy",
"tests/compute/test_isclose.py::test_lorentz_object",
"tests/compute/test_isclose.py::test_lorentz_numpy",
"tests/test_issues.py::test_issue_99",
"tests/test_issues.py::test_issue_161"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2024-03-21 19:49:36+00:00
|
bsd-3-clause
| 5,371 |
|
scipp__plopp-35
|
diff --git a/src/plopp/core/graph.py b/src/plopp/core/graph.py
index 5c4d1f9..12ff700 100644
--- a/src/plopp/core/graph.py
+++ b/src/plopp/core/graph.py
@@ -18,7 +18,7 @@ def _make_graphviz_digraph(*args, **kwargs):
def _add_graph_edges(dot, node, inventory, hide_views):
name = node.id
inventory.append(name)
- dot.node(name, label=escape(str(node.func)))
+ dot.node(name, label=escape(str(node.func)) + '\nid = ' + name)
for child in node.children:
key = child.id
if key not in inventory:
diff --git a/src/plopp/core/model.py b/src/plopp/core/model.py
index 6db54de..db33f0e 100644
--- a/src/plopp/core/model.py
+++ b/src/plopp/core/model.py
@@ -19,6 +19,7 @@ class Node:
self.kwparents = dict(kwparents)
for parent in chain(self.parents, self.kwparents.values()):
parent.add_child(self)
+ self._data = None
def remove(self):
if self.children:
@@ -33,9 +34,14 @@ class Node:
self.kwparents.clear()
def request_data(self):
- args = (parent.request_data() for parent in self.parents)
- kwargs = {key: parent.request_data() for key, parent in self.kwparents.items()}
- return self.func(*args, **kwargs)
+ if self._data is None:
+ args = (parent.request_data() for parent in self.parents)
+ kwargs = {
+ key: parent.request_data()
+ for key, parent in self.kwparents.items()
+ }
+ self._data = self.func(*args, **kwargs)
+ return self._data
def add_child(self, child):
self.children.append(child)
@@ -44,6 +50,7 @@ class Node:
self.views.append(view)
def notify_children(self, message):
+ self._data = None
self.notify_views(message)
for child in self.children:
child.notify_children(message)
|
scipp/plopp
|
b005b5278bd6ae7c2c925aded5f0bd1a48e6c476
|
diff --git a/tests/core/model_test.py b/tests/core/model_test.py
index 21d65bc..4ae1189 100644
--- a/tests/core/model_test.py
+++ b/tests/core/model_test.py
@@ -2,6 +2,7 @@
# Copyright (c) 2022 Scipp contributors (https://github.com/scipp)
from plopp import Node, node, View
+from functools import partial
import pytest
@@ -96,6 +97,34 @@ def test_two_children_request_data():
assert cv.data == 7
+def test_data_request_is_cached():
+ global log
+ log = ''
+
+ def log_and_call(n, f, x=None):
+ global log
+ log += n
+ if x is None:
+ return f()
+ else:
+ return f(x)
+
+ a = Node(partial(log_and_call, n='a', f=lambda: 5))
+ b = node(partial(log_and_call, n='b', f=lambda x: x - 2))(x=a)
+ c = node(partial(log_and_call, n='c', f=lambda x: x + 2))(x=a)
+ d = node(partial(log_and_call, n='d', f=lambda x: x**2))(x=c)
+ av = DataView(a) # noqa: F841
+ bv = DataView(b) # noqa: F841
+ cv = DataView(c) # noqa: F841
+ dv = DataView(d) # noqa: F841
+
+ a.notify_children(message='hello from a')
+ assert log == 'abcd' # 'a' should only appear once in the log
+ log = ''
+ c.notify_children(message='hello from c')
+ assert log == 'cd' # 'c' requests data from 'a' but 'a' is cached so no 'a' in log
+
+
def test_remove_node():
a = Node(lambda: 5)
b = node(lambda x: x - 2)(x=a)
|
Implement caching in graph nodes
Currently, when a change in a node triggers an update in multiple nodes below, all nodes generate a request that travels all the way to the top of the node tree.
This can make things very slow.
We should implement some caching mecanism where a node only get data from its parents if it is not up to date.
This should significantly improve the performance of some interactions.
|
0.0
|
b005b5278bd6ae7c2c925aded5f0bd1a48e6c476
|
[
"tests/core/model_test.py::test_data_request_is_cached"
] |
[
"tests/core/model_test.py::test_two_nodes_notify_children",
"tests/core/model_test.py::test_two_nodes_parent_child",
"tests/core/model_test.py::test_cannot_remove_node_with_children",
"tests/core/model_test.py::test_remove_node",
"tests/core/model_test.py::test_two_children_notify_children",
"tests/core/model_test.py::test_two_children_request_data"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-10-05 16:34:40+00:00
|
bsd-3-clause
| 5,372 |
|
scitokens__scitokens-193
|
diff --git a/src/scitokens/scitokens.py b/src/scitokens/scitokens.py
index bf9cd74..b88b638 100644
--- a/src/scitokens/scitokens.py
+++ b/src/scitokens/scitokens.py
@@ -598,9 +598,7 @@ class Enforcer(object):
return False
elif self._audience == "ANY":
return False
- elif value == "ANY":
- return True
-
+
# Convert the value and self._audience both to sets
# Then perform set intersection
values = []
@@ -609,6 +607,11 @@ class Enforcer(object):
else:
values = value
set_value = set(values)
+
+ # Check if "ANY" is in the set_value, and always accept if that is true
+ if "ANY" in set_value:
+ return True
+
audiences = []
if not isinstance(self._audience, list):
audiences = [self._audience]
|
scitokens/scitokens
|
2be3e7dc5781b8f24ed20b21a6b660c5cb80a814
|
diff --git a/tests/test_scitokens.py b/tests/test_scitokens.py
index 92ecac4..11a435e 100644
--- a/tests/test_scitokens.py
+++ b/tests/test_scitokens.py
@@ -142,6 +142,14 @@ class TestEnforcer(unittest.TestCase):
self._token2["aud"] = "ANY"
self.assertTrue(enf.test(self._token2, "read", "/foo/bar"), msg=enf.last_failure)
+ # Now set the audience to ANY
+ self._token2["aud"] = ["ANY"]
+ self.assertTrue(enf.test(self._token2, "read", "/foo/bar"), msg=enf.last_failure)
+
+ # Now set the audience to ANY
+ self._token2["aud"] = ["notathing.com", "ANY"]
+ self.assertTrue(enf.test(self._token2, "read", "/foo/bar"), msg=enf.last_failure)
+
# Now to the correct audience
self._token2["aud"] = "https://example.unl.edu"
self.assertTrue(enf.test(self._token2, "read", "/foo/bar"), msg=enf.last_failure)
|
aud value ANY not accepted when in an array
A token with audience value:
```
["ANY"]
```
is not accepted as valid. Should it be?
In [the _validate_aud method on the Enforcer object](https://github.com/scitokens/scitokens/blob/2be3e7dc5781b8f24ed20b21a6b660c5cb80a814/src/scitokens/scitokens.py#L596C2-L602C24) it looks like `ANY` is only treated as special if it is a stand-alone string.
If this is not the desired behavior, I think it would work to test if `value` is a list and, if so, return `True` if the list contains the string `"ANY"`.
|
0.0
|
2be3e7dc5781b8f24ed20b21a6b660c5cb80a814
|
[
"tests/test_scitokens.py::TestEnforcer::test_v2"
] |
[
"tests/test_scitokens.py::TestValidation::test_valid",
"tests/test_scitokens.py::TestEnforcer::test_aud",
"tests/test_scitokens.py::TestEnforcer::test_enforce",
"tests/test_scitokens.py::TestEnforcer::test_enforce_scope",
"tests/test_scitokens.py::TestEnforcer::test_enforce_v2",
"tests/test_scitokens.py::TestEnforcer::test_gen_acls",
"tests/test_scitokens.py::TestEnforcer::test_getitem",
"tests/test_scitokens.py::TestEnforcer::test_multiple_aud",
"tests/test_scitokens.py::TestEnforcer::test_sub"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2024-04-04 17:06:08+00:00
|
apache-2.0
| 5,373 |
|
scitokens__scitokens-35
|
diff --git a/src/scitokens/scitokens.py b/src/scitokens/scitokens.py
index 7fc173e..68ecaa9 100644
--- a/src/scitokens/scitokens.py
+++ b/src/scitokens/scitokens.py
@@ -138,10 +138,34 @@ class SciToken(object):
"""
self._claims[claim] = value
+ def __getitem__(self, claim):
+ """
+ Access the value corresponding to a particular claim; will
+ return claims from both the verified and unverified claims.
+
+ If a claim is not present, then a KeyError is thrown.
+ """
+ if claim in self._claims:
+ return self._claims[claim]
+ if claim in self._verified_claims:
+ return self._verified_claims[claim]
+ raise KeyError(claim)
+
+ def get(self, claim, default=None, verified_only=False):
+ """
+ Return the value associated with a claim, returning the
+ default if the claim is not present. If `verified_only` is
+ True, then a claim is returned only if it is in the verified claims
+ """
+ if verified_only:
+ return self._verified_claims.get(claim, default)
+ return self._claims.get(claim, self._verified_claims.get(claim, default))
+
def clone_chain(self):
"""
Return a new, empty SciToken
"""
+ raise NotImplementedError()
def _deserialize_key(self, key_serialized, unverified_headers):
"""
|
scitokens/scitokens
|
d0cd927709952237b90727b30a41f1a0503f13e9
|
diff --git a/tests/test_scitokens.py b/tests/test_scitokens.py
index fb30675..1fa48a2 100644
--- a/tests/test_scitokens.py
+++ b/tests/test_scitokens.py
@@ -4,6 +4,9 @@ import sys
import time
import unittest
+import cryptography.hazmat.backends
+import cryptography.hazmat.primitives.asymmetric.rsa
+
# Allow unittests to be run from within the project base.
if os.path.exists("src"):
sys.path.append("src")
@@ -37,7 +40,12 @@ class TestEnforcer(unittest.TestCase):
def setUp(self):
now = time.time()
- self._token = scitokens.SciToken()
+ private_key = cryptography.hazmat.primitives.asymmetric.rsa.generate_private_key(
+ public_exponent=65537,
+ key_size=2048,
+ backend=cryptography.hazmat.backends.default_backend()
+ )
+ self._token = scitokens.SciToken(key=private_key)
self._token["foo"] = "bar"
self._token["iat"] = int(now)
self._token["exp"] = int(now + 600)
@@ -45,7 +53,9 @@ class TestEnforcer(unittest.TestCase):
self._token["nbf"] = int(now)
def test_enforce(self):
-
+ """
+ Test the Enforcer object.
+ """
def always_accept(value):
if value or not value:
return True
@@ -72,6 +82,25 @@ class TestEnforcer(unittest.TestCase):
enf.add_validator("foo", always_accept)
self.assertTrue(enf.test(self._token, "read", "/foo/bar"), msg=enf.last_failure)
+ def test_getitem(self):
+ """
+ Test the getters for the SciTokens object.
+ """
+ self.assertEqual(self._token['foo'], 'bar')
+ with self.assertRaises(KeyError):
+ self._token['bar']
+ self.assertEqual(self._token.get('baz'), None)
+ self.assertEqual(self._token.get('foo', 'baz'), 'bar')
+ self.assertEqual(self._token.get('foo', 'baz', verified_only=True), 'baz')
+ self._token.serialize()
+ self.assertEqual(self._token['foo'], 'bar')
+ self.assertEqual(self._token.get('foo', 'baz'), 'bar')
+ self.assertEqual(self._token.get('bar', 'baz'), 'baz')
+ self.assertEqual(self._token.get('bar', 'baz', verified_only=True), 'baz')
+ self._token['bar'] = '1'
+ self.assertEqual(self._token.get('bar', 'baz', verified_only=False), '1')
+ self.assertEqual(self._token.get('bar', 'baz', verified_only=True), 'baz')
+
if __name__ == '__main__':
unittest.main()
|
Implement `__getitem__`
We should provide a `__getitem__` to allow access of claims.
Open question: should we allow access to verified claims only -- or all claims?
|
0.0
|
d0cd927709952237b90727b30a41f1a0503f13e9
|
[
"tests/test_scitokens.py::TestEnforcer::test_getitem"
] |
[
"tests/test_scitokens.py::TestValidation::test_valid",
"tests/test_scitokens.py::TestEnforcer::test_enforce"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2017-09-24 02:38:23+00:00
|
apache-2.0
| 5,374 |
|
scitokens__scitokens-80
|
diff --git a/src/scitokens/scitokens.py b/src/scitokens/scitokens.py
index 7fa6923..2959731 100644
--- a/src/scitokens/scitokens.py
+++ b/src/scitokens/scitokens.py
@@ -21,6 +21,7 @@ from .utils import keycache as KeyCache
from .utils import config
from .utils.errors import MissingIssuerException, InvalidTokenFormat, MissingKeyException, UnsupportedKeyException
from cryptography.hazmat.primitives.serialization import load_pem_public_key
+from cryptography.hazmat.primitives.asymmetric import rsa, ec
class SciToken(object):
"""
@@ -41,10 +42,28 @@ class SciToken(object):
raise NotImplementedError()
self._key = key
+ derived_alg = None
+ if key:
+ derived_alg = self._derive_algorithm(key)
# Make sure we support the key algorithm
+ if key and not algorithm and not derived_alg:
+ # We don't know the key algorithm
+ raise UnsupportedKeyException("Key was given for SciToken, but algorithm was not "
+ "passed to SciToken creation and it cannot be derived "
+ "from the provided key")
+ elif derived_alg and not algorithm:
+ self._key_alg = derived_alg
+ elif derived_alg and algorithm and derived_alg != algorithm:
+ error_str = ("Key provided reports algorithm type: {0}, ".format(derived_alg) +
+ "while scitoken creation argument was {0}".format(algorithm))
+ raise UnsupportedKeyException(error_str)
+ elif key and algorithm:
+ self._key_alg = algorithm
+ else:
+ # If key is not specified, and neither is algorithm
+ self._key_alg = algorithm if algorithm is not None else config.get('default_alg')
- self._key_alg = algorithm if algorithm is not None else config.get('default_alg')
if self._key_alg not in ["RS256", "ES256"]:
raise UnsupportedKeyException()
self._key_id = key_id
@@ -54,6 +73,24 @@ class SciToken(object):
self.insecure = False
self._serialized_token = None
+ @staticmethod
+ def _derive_algorithm(key):
+ """
+ Derive the algorithm type from the PEM contents of the key
+
+ returns: Key algorithm if known, otherwise None
+ """
+
+ if isinstance(key, rsa.RSAPrivateKey):
+ return "RS256"
+ elif isinstance(key, ec.EllipticCurvePrivateKey):
+ if key.curve.name == "secp256r1":
+ return "ES256"
+
+ # If it gets here, we don't know what type of key
+ return None
+
+
def claims(self):
"""
Return an iterator of (key, value) pairs of claims, starting
|
scitokens/scitokens
|
7943cda4957d4b783602efc204f48b486c2383ce
|
diff --git a/tests/test_create_scitoken.py b/tests/test_create_scitoken.py
index 89157e7..43defcf 100644
--- a/tests/test_create_scitoken.py
+++ b/tests/test_create_scitoken.py
@@ -262,6 +262,37 @@ class TestCreation(unittest.TestCase):
with self.assertRaises(UnsupportedKeyException):
scitokens.SciToken(key = self._private_key, algorithm="doesnotexist")
+ def test_autodetect_keytype(self):
+ """
+ Test the autodetection of the key type
+ """
+ private_key = generate_private_key(
+ public_exponent=65537,
+ key_size=2048,
+ backend=default_backend()
+ )
+
+ ec_private_key = ec.generate_private_key(
+ ec.SECP256R1(), default_backend()
+ )
+
+ # Test when we give it the wrong algorithm type
+ with self.assertRaises(scitokens.scitokens.UnsupportedKeyException):
+ token = scitokens.SciToken(key = private_key, algorithm="ES256")
+
+ # Test when we give it the wrong algorithm type
+ with self.assertRaises(scitokens.scitokens.UnsupportedKeyException):
+ token = scitokens.SciToken(key = ec_private_key, algorithm="RS256")
+
+ # Test when we give an unsupported algorithm
+ unsupported_private_key = ec.generate_private_key(
+ ec.SECP192R1(), default_backend()
+ )
+ with self.assertRaises(scitokens.scitokens.UnsupportedKeyException):
+ token = scitokens.SciToken(key = unsupported_private_key)
+
+ token = scitokens.SciToken(key = ec_private_key, algorithm="ES256")
+ token.serialize(issuer="local")
if __name__ == '__main__':
unittest.main()
|
Auto-detect signing algorithm
We have two potential signing algorithms - RS256 and ES256 - for SciTokens. However, the private key for these two are not interchangeable - a RSA key cannot be used to sign ES256.
Since we can probe the key type, we should be able to correctly select the algorithm.
|
0.0
|
7943cda4957d4b783602efc204f48b486c2383ce
|
[
"tests/test_create_scitoken.py::TestCreation::test_create_to_validate",
"tests/test_create_scitoken.py::TestCreation::test_opt",
"tests/test_create_scitoken.py::TestCreation::test_ec_public_key",
"tests/test_create_scitoken.py::TestCreation::test_autodetect_keytype",
"tests/test_create_scitoken.py::TestCreation::test_create",
"tests/test_create_scitoken.py::TestCreation::test_multiple_scopes",
"tests/test_create_scitoken.py::TestCreation::test_ver",
"tests/test_create_scitoken.py::TestCreation::test_unsupported_key",
"tests/test_create_scitoken.py::TestCreation::test_ec_create",
"tests/test_create_scitoken.py::TestCreation::test_serialize",
"tests/test_create_scitoken.py::TestCreation::test_aud",
"tests/test_create_scitoken.py::TestCreation::test_contains",
"tests/test_create_scitoken.py::TestCreation::test_no_kid",
"tests/test_create_scitoken.py::TestCreation::test_public_key"
] |
[] |
{
"failed_lite_validators": [
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-07-27 18:25:23+00:00
|
apache-2.0
| 5,375 |
|
sciunto-org__python-bibtexparser-162
|
diff --git a/bibtexparser/latexenc.py b/bibtexparser/latexenc.py
index e225de4..b4ac36d 100644
--- a/bibtexparser/latexenc.py
+++ b/bibtexparser/latexenc.py
@@ -85,6 +85,9 @@ def latex_to_unicode(string):
# to normalize to the latter.
cleaned_string = unicodedata.normalize("NFC", "".join(cleaned_string))
+ # Remove any left braces
+ cleaned_string = cleaned_string.replace("{", "").replace("}", "")
+
return cleaned_string
|
sciunto-org/python-bibtexparser
|
19051fdaeb3eea869aef1f7534d0a678f12f1b8c
|
diff --git a/bibtexparser/tests/test_customization.py b/bibtexparser/tests/test_customization.py
index e38c078..d6d42b5 100644
--- a/bibtexparser/tests/test_customization.py
+++ b/bibtexparser/tests/test_customization.py
@@ -89,7 +89,16 @@ class TestBibtexParserMethod(unittest.TestCase):
# From issue 121
record = {'title': '{Two Gedenk\\"uberlieferung der Angelsachsen}'}
result = convert_to_unicode(record)
- expected = {'title': '{Two Gedenküberlieferung der Angelsachsen}'}
+ expected = {'title': 'Two Gedenküberlieferung der Angelsachsen'}
+ self.assertEqual(result, expected)
+ # From issue 161
+ record = {'title': r"p\^{a}t\'{e}"}
+ result = convert_to_unicode(record)
+ expected = {'title': "pâté"}
+ self.assertEqual(result, expected)
+ record = {'title': r"\^{i}le"}
+ result = convert_to_unicode(record)
+ expected = {'title': "île"}
self.assertEqual(result, expected)
###########
|
Inconsistent results using `bibtexparser.latex_to_unicode`
Thanks for writing and maintaining this package!
I found that using `bibtexparser.latex_to_unicode` yields inconsistent results:
>>> latex_to_unicode(r"p\^{a}t\'{e}")
'pâté'
>>> latex_to_unicode(r"\^{i}le")
'{î}le'
Why are there braces around i-circumflex but not around a-circumflex or e-acut?
|
0.0
|
19051fdaeb3eea869aef1f7534d0a678f12f1b8c
|
[
"bibtexparser/tests/test_customization.py::TestBibtexParserMethod::test_convert_to_unicode"
] |
[
"bibtexparser/tests/test_customization.py::TestBibtexParserMethod::test_add_plaintext_fields",
"bibtexparser/tests/test_customization.py::TestBibtexParserMethod::test_getnames",
"bibtexparser/tests/test_customization.py::TestBibtexParserMethod::test_homogenize",
"bibtexparser/tests/test_customization.py::TestBibtexParserMethod::test_keywords",
"bibtexparser/tests/test_customization.py::TestBibtexParserMethod::test_page_double_hyphen_alreadyOK",
"bibtexparser/tests/test_customization.py::TestBibtexParserMethod::test_page_double_hyphen_nothing",
"bibtexparser/tests/test_customization.py::TestBibtexParserMethod::test_page_double_hyphen_simple",
"bibtexparser/tests/test_customization.py::TestBibtexParserMethod::test_page_double_hyphen_space"
] |
{
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false
}
|
2017-05-22 14:53:54+00:00
|
mit
| 5,376 |
|
sciunto-org__python-bibtexparser-316
|
diff --git a/bibtexparser/bwriter.py b/bibtexparser/bwriter.py
index 67190e6..3dd609b 100644
--- a/bibtexparser/bwriter.py
+++ b/bibtexparser/bwriter.py
@@ -5,7 +5,7 @@
import logging
from enum import Enum, auto
-from typing import Dict, Callable, Iterable
+from typing import Dict, Callable, Iterable, Union
from bibtexparser.bibdatabase import (BibDatabase, COMMON_STRINGS,
BibDataString,
BibDataStringExpression)
@@ -15,6 +15,9 @@ logger = logging.getLogger(__name__)
__all__ = ['BibTexWriter']
+# A list of entries that should not be included in the content (key = value) of a BibTex entry
+ENTRY_TO_BIBTEX_IGNORE_ENTRIES = ['ENTRYTYPE', 'ID']
+
class SortingStrategy(Enum):
"""
@@ -89,9 +92,12 @@ class BibTexWriter(object):
self.contents = ['comments', 'preambles', 'strings', 'entries']
#: Character(s) for indenting BibTeX field-value pairs. Default: single space.
self.indent = ' '
- #: Align values. Determines the maximal number of characters used in any fieldname and aligns all values
- # according to that by filling up with single spaces. Default: False
- self.align_values = False
+ #: Align values. Aligns all values according to a given length by padding with single spaces.
+ # If align_values is true, the maximum number of characters used in any field name is used as the length.
+ # If align_values is a number, the greater of the specified value or the number of characters used in the
+ # field name is used as the length.
+ # Default: False
+ self.align_values: Union[int, bool] = False
#: Align multi-line values. Formats a multi-line value such that the text is aligned exactly
# on top of each other. Default: False
self.align_multiline_values = False
@@ -112,7 +118,7 @@ class BibTexWriter(object):
#: BibTeX syntax allows the comma to be optional at the end of the last field in an entry.
#: Use this to enable writing this last comma in the bwriter output. Defaults: False.
self.add_trailing_comma = False
- #: internal variable used if self.align_values = True
+ #: internal variable used if self.align_values = True or self.align_values = <number>
self._max_field_width = 0
#: Whether common strings are written
self.common_strings = write_common_strings
@@ -143,10 +149,13 @@ class BibTexWriter(object):
else:
entries = bib_database.entries
- if self.align_values:
+ if self.align_values is True:
# determine maximum field width to be used
- widths = [max(map(len, entry.keys())) for entry in entries]
+ widths = [len(ele) for entry in entries for ele in entry if ele not in ENTRY_TO_BIBTEX_IGNORE_ENTRIES]
self._max_field_width = max(widths)
+ elif type(self.align_values) == int:
+ # Use specified value
+ self._max_field_width = self.align_values
return self.entry_separator.join(self._entry_to_bibtex(entry) for entry in entries)
@@ -165,7 +174,8 @@ class BibTexWriter(object):
else:
field_fmt = u",\n{indent}{field:<{field_max_w}} = {value}"
# Write field = value lines
- for field in [i for i in display_order if i not in ['ENTRYTYPE', 'ID']]:
+ for field in [i for i in display_order if i not in ENTRY_TO_BIBTEX_IGNORE_ENTRIES]:
+ max_field_width = max(len(field), self._max_field_width)
try:
value = _str_or_expr_to_bibtex(entry[field])
@@ -176,12 +186,7 @@ class BibTexWriter(object):
# World}
# Calculate the indent of "World":
# Left of field (whitespaces before e.g. 'title')
- value_indent = len(self.indent)
- # Field itself (e.g. len('title'))
- if self._max_field_width > 0:
- value_indent += self._max_field_width
- else:
- value_indent += len(field)
+ value_indent = len(self.indent) + max_field_width
# Right of field ' = ' (<- 3 chars) + '{' (<- 1 char)
value_indent += 3 + 1
@@ -190,7 +195,7 @@ class BibTexWriter(object):
bibtex += field_fmt.format(
indent=self.indent,
field=field,
- field_max_w=self._max_field_width,
+ field_max_w=max_field_width,
value=value)
except TypeError:
raise TypeError(u"The field %s in entry %s must be a string"
|
sciunto-org/python-bibtexparser
|
a9c47a665ba465c65503703aa4cc6305501a2426
|
diff --git a/bibtexparser/tests/test_bibtexwriter.py b/bibtexparser/tests/test_bibtexwriter.py
index 1c875fe..256bbea 100644
--- a/bibtexparser/tests/test_bibtexwriter.py
+++ b/bibtexparser/tests/test_bibtexwriter.py
@@ -70,7 +70,7 @@ class TestBibTexWriter(unittest.TestCase):
"""
self.assertEqual(result, expected)
- def test_align(self):
+ def test_align_bool(self):
bib_database = BibDatabase()
bib_database.entries = [{'ID': 'abc123',
'ENTRYTYPE': 'book',
@@ -87,6 +87,22 @@ class TestBibTexWriter(unittest.TestCase):
"""
self.assertEqual(result, expected)
+ bib_database = BibDatabase()
+ bib_database.entries = [{'ID': 'veryveryverylongID',
+ 'ENTRYTYPE': 'book',
+ 'a': 'test',
+ 'bb': 'longvalue'}]
+ writer = BibTexWriter()
+ writer.align_values = True
+ result = bibtexparser.dumps(bib_database, writer)
+ expected = \
+"""@book{veryveryverylongID,
+ a = {test},
+ bb = {longvalue}
+}
+"""
+ self.assertEqual(result, expected)
+
with open('bibtexparser/tests/data/multiple_entries_and_comments.bib') as bibtex_file:
bib_database = bibtexparser.load(bibtex_file)
writer = BibTexWriter()
@@ -121,6 +137,70 @@ class TestBibTexWriter(unittest.TestCase):
"""
self.assertEqual(result, expected)
+ def test_align_int(self):
+ bib_database = BibDatabase()
+ bib_database.entries = [{'ID': 'abc123',
+ 'ENTRYTYPE': 'book',
+ 'author': 'test',
+ 'thisisaverylongkey': 'longvalue'}]
+ # Negative value should have no effect
+ writer = BibTexWriter()
+ writer.align_values = -20
+ result = bibtexparser.dumps(bib_database, writer)
+ expected = \
+"""@book{abc123,
+ author = {test},
+ thisisaverylongkey = {longvalue}
+}
+"""
+ self.assertEqual(result, expected)
+
+ # Value smaller than longest field name should only impact the "short" field names
+ writer = BibTexWriter()
+ writer.align_values = 10
+ result = bibtexparser.dumps(bib_database, writer)
+ expected = \
+"""@book{abc123,
+ author = {test},
+ thisisaverylongkey = {longvalue}
+}
+"""
+ self.assertEqual(result, expected)
+
+
+ with open('bibtexparser/tests/data/multiple_entries_and_comments.bib') as bibtex_file:
+ bib_database = bibtexparser.load(bibtex_file)
+ writer = BibTexWriter()
+ writer.contents = ['entries']
+ writer.align_values = 15
+ result = bibtexparser.dumps(bib_database, writer)
+ expected = \
+"""@book{Toto3000,
+ author = {Toto, A and Titi, B},
+ title = {A title}
+}
+
+@article{Wigner1938,
+ author = {Wigner, E.},
+ doi = {10.1039/TF9383400029},
+ issn = {0014-7672},
+ journal = {Trans. Faraday Soc.},
+ owner = {fr},
+ pages = {29--41},
+ publisher = {The Royal Society of Chemistry},
+ title = {The transition state method},
+ volume = {34},
+ year = {1938}
+}
+
+@book{Yablon2005,
+ author = {Yablon, A.D.},
+ publisher = {Springer},
+ title = {Optical fiber fusion slicing},
+ year = {2005}
+}
+"""
+ self.assertEqual(result, expected)
def test_entry_separator(self):
bib_database = BibDatabase()
@@ -206,17 +286,17 @@ class TestBibTexWriter(unittest.TestCase):
result = bibtexparser.dumps(bib_database, writer)
expected = \
"""@article{Cesar2013,
- author = {Jean César},
- title = {A mutline line title is very amazing. It should be
- long enough to test multilines... with two lines or should we
- even test three lines... What an amazing title.},
- year = {2013},
- journal = {Nice Journal},
- abstract = {This is an abstract. This line should be long enough to test
- multilines... and with a french érudit word},
- comments = {A comment},
- keyword = {keyword1, keyword2,
- multiline-keyword1, multiline-keyword2}
+ author = {Jean César},
+ title = {A mutline line title is very amazing. It should be
+ long enough to test multilines... with two lines or should we
+ even test three lines... What an amazing title.},
+ year = {2013},
+ journal = {Nice Journal},
+ abstract = {This is an abstract. This line should be long enough to test
+ multilines... and with a french érudit word},
+ comments = {A comment},
+ keyword = {keyword1, keyword2,
+ multiline-keyword1, multiline-keyword2}
}
"""
self.assertEqual(result, expected)
@@ -331,17 +411,17 @@ class TestBibTexWriter(unittest.TestCase):
result = bibtexparser.dumps(bib_database, writer)
expected = \
"""@article{Cesar2013,
- author = {Jean César},
- title = {A mutline line title is very amazing. It should be
- long enough to test multilines... with two lines or should we
- even test three lines... What an amazing title.},
- year = {2013},
- journal = {Nice Journal},
- abstract = {This is an abstract. This line should be long enough to test
- multilines... and with a french érudit word},
- comments = {A comment},
- keyword = {keyword1, keyword2,
- multiline-keyword1, multiline-keyword2}
+ author = {Jean César},
+ title = {A mutline line title is very amazing. It should be
+ long enough to test multilines... with two lines or should we
+ even test three lines... What an amazing title.},
+ year = {2013},
+ journal = {Nice Journal},
+ abstract = {This is an abstract. This line should be long enough to test
+ multilines... and with a french érudit word},
+ comments = {A comment},
+ keyword = {keyword1, keyword2,
+ multiline-keyword1, multiline-keyword2}
}
"""
self.assertEqual(result, expected)
|
`align_values` has minimum `_max_field_width ` due to `ENTRYPOINT` pseudo field.
When using `align_values`, the minimum `_max_field_width` is always 9 as `ENTRYPOINT` (9 chars) is in the list of `entries`:
https://github.com/sciunto-org/python-bibtexparser/blob/006f463a8601dc8065f02f3199210c70f24ac4f9/bibtexparser/bwriter.py#L108
Therefore, this tests works fine:
```
def test_align2(self):
bib_database = BibDatabase()
bib_database.entries = [{'ID': 'abc123',
'ENTRYTYPE': 'book',
'abc': 'test'}]
writer = BibTexWriter()
writer.align_values = True
result = bibtexparser.dumps(bib_database, writer)
expected = \
"""@book{abc123,
abc = {test}
}
"""
self.assertEqual(result, expected)
```
Shouldn't the result be:
```
def test_align2(self):
bib_database = BibDatabase()
bib_database.entries = [{'ID': 'abc123',
'ENTRYTYPE': 'book',
'abc': 'test'}]
writer = BibTexWriter()
writer.align_values = True
result = bibtexparser.dumps(bib_database, writer)
expected = \
"""@book{abc123,
abc = {test}
}
"""
self.assertEqual(result, expected)
```
This is also the behavior when having multiple short named keys.
|
0.0
|
a9c47a665ba465c65503703aa4cc6305501a2426
|
[
"bibtexparser/tests/test_bibtexwriter.py::TestBibTexWriter::test_align_bool",
"bibtexparser/tests/test_bibtexwriter.py::TestBibTexWriter::test_align_int",
"bibtexparser/tests/test_bibtexwriter.py::TestBibTexWriter::test_align_multiline_values_with_align",
"bibtexparser/tests/test_bibtexwriter.py::TestBibTexWriter::test_align_multiline_values_with_align_with_indent"
] |
[
"bibtexparser/tests/test_bibtexwriter.py::TestBibTexWriter::test_align_multiline_values",
"bibtexparser/tests/test_bibtexwriter.py::TestBibTexWriter::test_align_multiline_values_with_indent",
"bibtexparser/tests/test_bibtexwriter.py::TestBibTexWriter::test_content_comment_only",
"bibtexparser/tests/test_bibtexwriter.py::TestBibTexWriter::test_content_entries_only",
"bibtexparser/tests/test_bibtexwriter.py::TestBibTexWriter::test_display_order",
"bibtexparser/tests/test_bibtexwriter.py::TestBibTexWriter::test_display_order_sorting",
"bibtexparser/tests/test_bibtexwriter.py::TestBibTexWriter::test_entry_separator",
"bibtexparser/tests/test_bibtexwriter.py::TestBibTexWriter::test_indent",
"bibtexparser/tests/test_bibtexwriter.py::TestEntrySorting::test_sort_default",
"bibtexparser/tests/test_bibtexwriter.py::TestEntrySorting::test_sort_id",
"bibtexparser/tests/test_bibtexwriter.py::TestEntrySorting::test_sort_missing_field",
"bibtexparser/tests/test_bibtexwriter.py::TestEntrySorting::test_sort_none",
"bibtexparser/tests/test_bibtexwriter.py::TestEntrySorting::test_sort_type",
"bibtexparser/tests/test_bibtexwriter.py::TestEntrySorting::test_sort_type_id",
"bibtexparser/tests/test_bibtexwriter.py::TestEntrySorting::test_unicode_problems"
] |
{
"failed_lite_validators": [
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-09-05 19:45:12+00:00
|
mit
| 5,377 |
|
sciunto-org__python-bibtexparser-379
|
diff --git a/bibtexparser/library.py b/bibtexparser/library.py
index e2cfa6e..296b7fc 100644
--- a/bibtexparser/library.py
+++ b/bibtexparser/library.py
@@ -2,7 +2,7 @@ from typing import Dict, List, Union
from .model import (
Block,
- DuplicateEntryKeyBlock,
+ DuplicateBlockKeyBlock,
Entry,
ExplicitComment,
ImplicitComment,
@@ -37,6 +37,7 @@ class Library:
blocks = [blocks]
for block in blocks:
+ # This may replace block with a DuplicateEntryKeyBlock
block = self._add_to_dicts(block)
self._blocks.append(block)
@@ -77,7 +78,7 @@ class Library:
if (
new_block is not block_after_add
- and isinstance(new_block, DuplicateEntryKeyBlock)
+ and isinstance(new_block, DuplicateBlockKeyBlock)
and fail_on_duplicate_key
):
# Revert changes to old_block
@@ -104,7 +105,7 @@ class Library:
prev_block_with_same_key.key == duplicate.key
), "Internal BibtexParser Error. Duplicate blocks have different keys."
- return DuplicateEntryKeyBlock(
+ return DuplicateBlockKeyBlock(
start_line=duplicate.start_line,
raw=duplicate.raw,
key=duplicate.key,
@@ -116,25 +117,23 @@ class Library:
"""Safely add block references to private dict structures.
:param block: Block to add.
- :returns: The block that was added to the library, except if a block
- of same type and with same key already exists, in which case a
- DuplicateKeyBlock is returned.
+ :returns: The block that was added to the library. If a block
+ of same type and with same key already existed, a
+ DuplicateKeyBlock is returned (not added to dict).
"""
if isinstance(block, Entry):
try:
prev_block_with_same_key = self._entries_by_key[block.key]
block = self._cast_to_duplicate(prev_block_with_same_key, block)
except KeyError:
- pass # No previous entry with same key
- finally:
+ # No duplicate found
self._entries_by_key[block.key] = block
elif isinstance(block, String):
try:
prev_block_with_same_key = self._strings_by_key[block.key]
block = self._cast_to_duplicate(prev_block_with_same_key, block)
except KeyError:
- pass # No previous string with same key
- finally:
+ # No duplicate found
self._strings_by_key[block.key] = block
return block
diff --git a/bibtexparser/model.py b/bibtexparser/model.py
index ba12aec..d3b99be 100644
--- a/bibtexparser/model.py
+++ b/bibtexparser/model.py
@@ -386,7 +386,7 @@ class MiddlewareErrorBlock(ParsingFailedBlock):
)
-class DuplicateEntryKeyBlock(ParsingFailedBlock):
+class DuplicateBlockKeyBlock(ParsingFailedBlock):
"""An error-indicating block created for blocks with keys present in the library already.
To get the block that caused this error, call `block.ignore_error_block`."""
|
sciunto-org/python-bibtexparser
|
7e69b8e05ac47cfe44ec534715d2cb1c20230885
|
diff --git a/tests/splitter_tests/test_splitter_basic.py b/tests/splitter_tests/test_splitter_basic.py
index 1b11a89..c65a601 100644
--- a/tests/splitter_tests/test_splitter_basic.py
+++ b/tests/splitter_tests/test_splitter_basic.py
@@ -263,3 +263,59 @@ def test_failed_block():
'Was still looking for field-value closing `"`'
in failed_block.error.abort_reason
)
+
+
+duplicate_bibtex_entry_keys = """
+@article{duplicate,
+ author = {Duplicate, A.},
+ title = {Duplicate article 1},
+ year = {2021},
+}
+@article{duplicate,
+ author = {Duplicate, B.},
+ title = {Duplicate article 2},
+ year = {2022},
+}"""
+
+
+def test_handles_duplicate_entries():
+ """Makes sure that duplicate keys are handled correctly."""
+ import bibtexparser
+
+ lib = bibtexparser.parse_string(duplicate_bibtex_entry_keys)
+ assert len(lib.blocks) == 2
+ assert len(lib.entries) == 1
+ assert len(lib.entries_dict) == 1
+ assert len(lib.failed_blocks) == 1
+
+ assert lib.entries[0]["title"] == "Duplicate article 1"
+ assert isinstance(lib.failed_blocks[0], bibtexparser.model.DuplicateBlockKeyBlock)
+ assert lib.failed_blocks[0].previous_block["title"] == "Duplicate article 1"
+ assert lib.failed_blocks[0].ignore_error_block["title"] == "{Duplicate article 2}"
+ assert isinstance(lib.failed_blocks[0].ignore_error_block, bibtexparser.model.Entry)
+
+
+duplicate_bibtex_string_keys = """
+@string{duplicate = "Duplicate string 1"}
+@string{duplicate = "Duplicate string 2"}
+@string{duplicate = "Duplicate string 3"}
+"""
+
+
+def test_handles_duplicate_strings():
+ """Makes sure that duplicate string keys are handled correctly."""
+ import bibtexparser
+
+ lib = bibtexparser.parse_string(duplicate_bibtex_string_keys)
+ assert len(lib.blocks) == 3
+ assert len(lib.strings) == 1
+ assert len(lib.strings_dict) == 1
+ assert len(lib.failed_blocks) == 2
+
+ assert lib.strings[0].value == "Duplicate string 1"
+ assert isinstance(lib.failed_blocks[0], bibtexparser.model.DuplicateBlockKeyBlock)
+ assert lib.failed_blocks[0].previous_block.value == "Duplicate string 1"
+ assert lib.failed_blocks[0].ignore_error_block.value == '"Duplicate string 2"'
+ assert isinstance(
+ lib.failed_blocks[0].ignore_error_block, bibtexparser.model.String
+ )
|
Parsing fails when bibtex contains duplicates
Based on the v2 docs, it seems bibtexparser should be able to process bibtex files with duplicates. However, if a bibtex file contains duplicates, an error is produced:
```python
import bibtexparser
str = """@article{duplicate,
author = {Duplicate, A.},
title = {Duplicate article},
year = {2022},
}
@article{duplicate,
author = {Duplicate, A.},
title = {Duplicate article},
year = {2022},
}"""
bibtexparser.parse_string(str)
```
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "~/.local/lib/python3.10/site-packages/bibtexparser/entrypoint.py", line 93, in parse_string
library = middleware.transform(library=library)
File "~/.local/lib/python3.10/site-packages/bibtexparser/middlewares/interpolate.py", line 60, in transform
for field in entry.fields:
AttributeError: 'DuplicateEntryKeyBlock' object has no attribute 'fields'
|
0.0
|
7e69b8e05ac47cfe44ec534715d2cb1c20230885
|
[
"tests/splitter_tests/test_splitter_basic.py::test_handles_duplicate_entries",
"tests/splitter_tests/test_splitter_basic.py::test_handles_duplicate_strings"
] |
[
"tests/splitter_tests/test_splitter_basic.py::test_entry[expected0]",
"tests/splitter_tests/test_splitter_basic.py::test_entry[expected1]",
"tests/splitter_tests/test_splitter_basic.py::test_strings[expected0]",
"tests/splitter_tests/test_splitter_basic.py::test_strings[expected1]",
"tests/splitter_tests/test_splitter_basic.py::test_preamble",
"tests/splitter_tests/test_splitter_basic.py::test_comments[expected0]",
"tests/splitter_tests/test_splitter_basic.py::test_comments[expected1]",
"tests/splitter_tests/test_splitter_basic.py::test_comments[expected2]",
"tests/splitter_tests/test_splitter_basic.py::test_failed_block"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-06-01 11:26:34+00:00
|
mit
| 5,378 |
|
sciunto-org__python-bibtexparser-385
|
diff --git a/bibtexparser/splitter.py b/bibtexparser/splitter.py
index 712e0fe..ce2e55f 100644
--- a/bibtexparser/splitter.py
+++ b/bibtexparser/splitter.py
@@ -348,16 +348,24 @@ class Splitter:
"but no closing bracket was found."
)
comma_mark = self._next_mark(accept_eof=False)
- if comma_mark.group(0) != ",":
+ if comma_mark.group(0) == "}":
+ # This is an entry without any comma after the key, and with no fields
+ # Used e.g. by RefTeX (see issue #384)
+ key = self.bibstr[m.end() + 1 : comma_mark.start()].strip()
+ fields, end_index, duplicate_keys = [], comma_mark.end(), []
+ elif comma_mark.group(0) != ",":
self._unaccepted_mark = comma_mark
raise BlockAbortedException(
abort_reason="Expected comma after entry key,"
f" but found {comma_mark.group(0)}",
end_index=comma_mark.end(),
)
- self._open_brackets += 1
- key = self.bibstr[m.end() + 1 : comma_mark.start()].strip()
- fields, end_index, duplicate_keys = self._move_to_end_of_entry(comma_mark.end())
+ else:
+ self._open_brackets += 1
+ key = self.bibstr[m.end() + 1 : comma_mark.start()].strip()
+ fields, end_index, duplicate_keys = self._move_to_end_of_entry(
+ comma_mark.end()
+ )
entry = Entry(
start_line=start_line,
|
sciunto-org/python-bibtexparser
|
573ed18c9ed36f0af0a958a6af846778a65b298f
|
diff --git a/tests/splitter_tests/test_splitter_entry.py b/tests/splitter_tests/test_splitter_entry.py
index 4fa6443..c0f26db 100644
--- a/tests/splitter_tests/test_splitter_entry.py
+++ b/tests/splitter_tests/test_splitter_entry.py
@@ -173,3 +173,26 @@ def test_multiple_identical_field_keys():
journal_field = [f for f in block.ignore_error_block.fields if f.key == "journal"]
assert len(journal_field) == 1
assert journal_field[0].value == "{Some journal}"
+
+
[email protected](
+ "entry_without_fields",
+ [
+ # common in revtex, see issue #384
+ pytest.param("@article{articleTestKey}", id="without comma"),
+ pytest.param("@article{articleTestKey,}", id="with comma"),
+ ],
+)
+def test_entry_without_fields(entry_without_fields: str):
+ """For motivation why we need this, please see issue #384"""
+ subsequent_article = "@Article{subsequentArticle, title = {Some title}}"
+ full_bibtex = f"{entry_without_fields}\n\n{subsequent_article}"
+ library: Library = Splitter(full_bibtex).split()
+ assert len(library.entries) == 2
+ assert len(library.failed_blocks) == 0
+
+ assert library.entries[0].key == "articleTestKey"
+ assert len(library.entries[0].fields) == 0
+
+ assert library.entries[1].key == "subsequentArticle"
+ assert len(library.entries[1].fields) == 1
|
`@CONTROL{REVTEX41Control}` statement ignored
The [AIP LaTeX template](https://www.overleaf.com/latex/templates/template-for-submission-to-aip-publishing-journals/xhsskcchtbxf) produces an extra bib file, typically named `articleNotes.bib` (when the main tex file is `article.tex`). It contains the following two lines:
```bibtex
@CONTROL{REVTEX41Control}
@CONTROL{aip41Control,pages="1",title="0"}
```
The first line seems to be ignored by python-bibtexparser, while `bibtex` can properly handle it.
Minimal example to reproduce the issue:
```python
import bibtexparser
btp = bibtexparser.bparser.BibTexParser(ignore_nonstandard_types=False)
print(bibtexparser.load(open("articleNotes.bib"), btp).entries)
```
This only prints out the entry corresponding to the second control line:
```python
[{'title': '0', 'pages': '1', 'ENTRYTYPE': 'control', 'ID': 'aip41Control'}]
```
|
0.0
|
573ed18c9ed36f0af0a958a6af846778a65b298f
|
[
"tests/splitter_tests/test_splitter_entry.py::test_entry_without_fields[without"
] |
[
"tests/splitter_tests/test_splitter_entry.py::test_field_enclosings[year-2019-1]",
"tests/splitter_tests/test_splitter_entry.py::test_field_enclosings[month-1-2]",
"tests/splitter_tests/test_splitter_entry.py::test_field_enclosings[author-\"John",
"tests/splitter_tests/test_splitter_entry.py::test_field_enclosings[journal-someJournalReference-4]",
"tests/splitter_tests/test_splitter_entry.py::test_entry_type[@article-article]",
"tests/splitter_tests/test_splitter_entry.py::test_entry_type[@ARTICLE-article]",
"tests/splitter_tests/test_splitter_entry.py::test_entry_type[@Article-article]",
"tests/splitter_tests/test_splitter_entry.py::test_entry_type[@book-book]",
"tests/splitter_tests/test_splitter_entry.py::test_entry_type[@BOOK-book]",
"tests/splitter_tests/test_splitter_entry.py::test_entry_type[@Book-book]",
"tests/splitter_tests/test_splitter_entry.py::test_entry_type[@inbook-inbook]",
"tests/splitter_tests/test_splitter_entry.py::test_entry_type[@INBOOK-inbook]",
"tests/splitter_tests/test_splitter_entry.py::test_entry_type[@Inbook-inbook]",
"tests/splitter_tests/test_splitter_entry.py::test_entry_type[@incollection-incollection]",
"tests/splitter_tests/test_splitter_entry.py::test_entry_type[@INCOLLECTION-incollection]",
"tests/splitter_tests/test_splitter_entry.py::test_entry_type[@Incollection-incollection]",
"tests/splitter_tests/test_splitter_entry.py::test_entry_type[@inproceedings-inproceedings]",
"tests/splitter_tests/test_splitter_entry.py::test_entry_type[@INPROCEEDINGS-inproceedings]",
"tests/splitter_tests/test_splitter_entry.py::test_entry_type[@InprocEEdings-inproceedings]",
"tests/splitter_tests/test_splitter_entry.py::test_field_value[double_quotes-John",
"tests/splitter_tests/test_splitter_entry.py::test_field_value[double_quotes-\\xe0",
"tests/splitter_tests/test_splitter_entry.py::test_field_value[double_quotes-{\\\\`a}",
"tests/splitter_tests/test_splitter_entry.py::test_field_value[double_quotes-Two",
"tests/splitter_tests/test_splitter_entry.py::test_field_value[double_quotes-\\\\texttimes{}{\\\\texttimes}\\\\texttimes]",
"tests/splitter_tests/test_splitter_entry.py::test_field_value[double_quotes-p\\\\^{a}t\\\\'{e}Title",
"tests/splitter_tests/test_splitter_entry.py::test_field_value[double_quotes-Title",
"tests/splitter_tests/test_splitter_entry.py::test_field_value[curly_braces-John",
"tests/splitter_tests/test_splitter_entry.py::test_field_value[curly_braces-\\xe0",
"tests/splitter_tests/test_splitter_entry.py::test_field_value[curly_braces-{\\\\`a}",
"tests/splitter_tests/test_splitter_entry.py::test_field_value[curly_braces-Two",
"tests/splitter_tests/test_splitter_entry.py::test_field_value[curly_braces-\\\\texttimes{}{\\\\texttimes}\\\\texttimes]",
"tests/splitter_tests/test_splitter_entry.py::test_field_value[curly_braces-p\\\\^{a}t\\\\'{e}Title",
"tests/splitter_tests/test_splitter_entry.py::test_field_value[curly_braces-Title",
"tests/splitter_tests/test_splitter_entry.py::test_trailing_comma[double_quotes]",
"tests/splitter_tests/test_splitter_entry.py::test_trailing_comma[curly_braces]",
"tests/splitter_tests/test_splitter_entry.py::test_trailing_comma[no",
"tests/splitter_tests/test_splitter_entry.py::test_multiple_identical_field_keys",
"tests/splitter_tests/test_splitter_entry.py::test_entry_without_fields[with"
] |
{
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-06-20 12:02:37+00:00
|
mit
| 5,379 |
|
sciunto-org__python-bibtexparser-387
|
diff --git a/bibtexparser/middlewares/middleware.py b/bibtexparser/middlewares/middleware.py
index d7e0d16..2329eb9 100644
--- a/bibtexparser/middlewares/middleware.py
+++ b/bibtexparser/middlewares/middleware.py
@@ -74,7 +74,29 @@ class BlockMiddleware(Middleware, abc.ABC):
# docstr-coverage: inherited
def transform(self, library: "Library") -> "Library":
# TODO Multiprocessing (only for large library and if allow_multi..)
- blocks = [self.transform_block(b, library) for b in library.blocks]
+ blocks = []
+ for b in library.blocks:
+ transformed = self.transform_block(b, library)
+ # Case 1: None. Skip it.
+ if transformed is None:
+ pass
+ # Case 2: A single block. Add it to the list.
+ elif isinstance(transformed, Block):
+ blocks.append(transformed)
+ # Case 3: A collection. Append all the elements.
+ elif isinstance(transformed, Collection):
+ # check that all the items are indeed blocks
+ for item in transformed:
+ if not isinstance(item, Block):
+ raise TypeError(
+ f"Non-Block type found in transformed collection: {type(item)}"
+ )
+ blocks.extend(transformed)
+ # Case 4: Something else. Error.
+ else:
+ raise TypeError(
+ f"Illegal output type from transform_block: {type(transformed)}"
+ )
return Library(blocks=blocks)
def transform_block(
|
sciunto-org/python-bibtexparser
|
6ac6f92b8740a809101053ac83842b0acbc01d2c
|
diff --git a/tests/middleware_tests/test_block_middleware.py b/tests/middleware_tests/test_block_middleware.py
new file mode 100644
index 0000000..eef9cce
--- /dev/null
+++ b/tests/middleware_tests/test_block_middleware.py
@@ -0,0 +1,115 @@
+import pytest
+
+from bibtexparser import Library
+from bibtexparser.middlewares.middleware import BlockMiddleware
+from bibtexparser.model import Entry, ExplicitComment, ImplicitComment, Preamble, String
+
+BLOCKS = [
+ ExplicitComment("explicit_comment_a"),
+ String("string_b", "value_b"),
+ String("string_a", "value_a"),
+ ImplicitComment("% implicit_comment_a"),
+ ExplicitComment("explicit_comment_b"),
+ Entry("article", "entry_a", fields=[]),
+ ImplicitComment("% implicit_comment_b"),
+ Entry("article", "entry_b", fields=[]),
+ Entry("article", "entry_d", fields=[]),
+ Entry("article", "entry_c", fields=[]),
+ Preamble("preamble_a"),
+ ImplicitComment("% implicit_comment_c"),
+]
+
+
+class ConstantBlockMiddleware(BlockMiddleware):
+ """A middleware that always returns the same result for every block."""
+
+ def __init__(self, const):
+ self._const = const
+ super().__init__(allow_parallel_execution=True, allow_inplace_modification=True)
+
+ def transform_block(self, block, library):
+ return self._const
+
+ def metadata_key():
+ return "ConstantBlockMiddleware"
+
+
+class LambdaBlockMiddleware(BlockMiddleware):
+ """A middleware that applies a lambda to the input block"""
+
+ def __init__(self, f):
+ self._f = f
+ super().__init__(allow_parallel_execution=True, allow_inplace_modification=True)
+
+ def transform_block(self, block, library):
+ return self._f(block)
+
+ def metadata_key():
+ return "LambdaBlockMiddleware"
+
+
[email protected](
+ ("middleware", "expected"),
+ [
+ (ConstantBlockMiddleware(None), []),
+ (ConstantBlockMiddleware([]), []),
+ (LambdaBlockMiddleware(lambda b: [b]), BLOCKS),
+ ],
+)
+def test_successful_transform(middleware, expected):
+ library = Library(blocks=BLOCKS)
+ library = middleware.transform(library)
+
+ assert library.blocks == expected
+
+
+def test_returning_list_adds_all():
+ library = Library(blocks=BLOCKS)
+ library = LambdaBlockMiddleware(
+ lambda b: [ImplicitComment("% Block"), b]
+ ).transform(library)
+
+ expected = [
+ ImplicitComment("% Block"),
+ ExplicitComment("explicit_comment_a"),
+ ImplicitComment("% Block"),
+ String("string_b", "value_b"),
+ ImplicitComment("% Block"),
+ String("string_a", "value_a"),
+ ImplicitComment("% Block"),
+ ImplicitComment("% implicit_comment_a"),
+ ImplicitComment("% Block"),
+ ExplicitComment("explicit_comment_b"),
+ ImplicitComment("% Block"),
+ Entry("article", "entry_a", fields=[]),
+ ImplicitComment("% Block"),
+ ImplicitComment("% implicit_comment_b"),
+ ImplicitComment("% Block"),
+ Entry("article", "entry_b", fields=[]),
+ ImplicitComment("% Block"),
+ Entry("article", "entry_d", fields=[]),
+ ImplicitComment("% Block"),
+ Entry("article", "entry_c", fields=[]),
+ ImplicitComment("% Block"),
+ Preamble("preamble_a"),
+ ImplicitComment("% Block"),
+ ImplicitComment("% implicit_comment_c"),
+ ]
+
+ assert library.blocks == expected
+
+
[email protected](
+ "middleware",
+ [
+ ConstantBlockMiddleware(True),
+ ConstantBlockMiddleware([True]),
+ LambdaBlockMiddleware(
+ lambda block: (b for b in [block])
+ ), # generators are not collections
+ ],
+)
+def test_returning_invalid_raises_error(middleware):
+ library = Library(blocks=BLOCKS)
+ with pytest.raises(TypeError):
+ middleware.transform(library)
|
BlockMiddlewareTransformer does not handle `None` or collections
According to documentation, transformers implementing `BlockMiddlewareTransformer` can return `None`, a single entry, or a collection of entries for the `transform_block` function. But returning anything other than a single entry results in a crash. The problem seems to stem from this code in `middleware.py`:
```python3
def transform(self, library: "Library") -> "Library":
# TODO Multiprocessing (only for large library and if allow_multi..)
blocks = [self.transform_block(b, library) for b in library.blocks]
return Library(blocks=blocks)
```
It doesn't handle cases where `transform_block` does not return an entry.
|
0.0
|
6ac6f92b8740a809101053ac83842b0acbc01d2c
|
[
"tests/middleware_tests/test_block_middleware.py::test_successful_transform[middleware0-expected0]",
"tests/middleware_tests/test_block_middleware.py::test_successful_transform[middleware1-expected1]",
"tests/middleware_tests/test_block_middleware.py::test_successful_transform[middleware2-expected2]",
"tests/middleware_tests/test_block_middleware.py::test_returning_list_adds_all",
"tests/middleware_tests/test_block_middleware.py::test_returning_invalid_raises_error[middleware0]",
"tests/middleware_tests/test_block_middleware.py::test_returning_invalid_raises_error[middleware1]",
"tests/middleware_tests/test_block_middleware.py::test_returning_invalid_raises_error[middleware2]"
] |
[] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2023-07-06 21:10:31+00:00
|
mit
| 5,380 |
|
sciunto-org__python-bibtexparser-392
|
diff --git a/bibtexparser/splitter.py b/bibtexparser/splitter.py
index ce2e55f..fd831a9 100644
--- a/bibtexparser/splitter.py
+++ b/bibtexparser/splitter.py
@@ -231,7 +231,7 @@ class Splitter:
The library with the added blocks.
"""
self._markiter = re.finditer(
- r"(?<!\\)[\{\}\",=\n]|(?<=\n)@[\w]*(?={)", self.bibstr, re.MULTILINE
+ r"(?<!\\)[\{\}\",=\n]|(?<=\n)@[\w]*( |\t)*(?={)", self.bibstr, re.MULTILINE
)
if library is None:
@@ -337,7 +337,7 @@ class Splitter:
def _handle_entry(self, m, m_val) -> Union[Entry, ParsingFailedBlock]:
"""Handle entry block. Return end index"""
start_line = self._current_line
- entry_type = m_val[1:]
+ entry_type = m_val[1:].strip()
start_bracket_mark = self._next_mark(accept_eof=False)
if start_bracket_mark.group(0) != "{":
self._unaccepted_mark = start_bracket_mark
diff --git a/dev-utilities/bibtex-nameparsing/parsename.py b/dev-utilities/bibtex-nameparsing/parsename.py
index d3a5809..0c80e89 100644
--- a/dev-utilities/bibtex-nameparsing/parsename.py
+++ b/dev-utilities/bibtex-nameparsing/parsename.py
@@ -12,11 +12,14 @@ try:
from tempfile import TemporaryDirectory
except ImportError:
from tempfile import mkdtemp
+
class TemporaryDirectory(object):
def __init__(self):
self.name = mkdtemp()
+
def __enter__(self):
return self.name
+
def __exit__(self, exc, value, tb):
shutil.rmtree(self.name)
@@ -42,12 +45,16 @@ def evaluate_bibtex_parsename(tempdir, names):
# Write entries for each string in the list.
with open(os.path.join(tempdir, "parsename.bib"), "w") as bibfile:
for i, name in enumerate(names):
- bibfile.write('@parsename{{case{0:d}, author={{{1:s}}}}}\n'.format(i, name))
+ bibfile.write("@parsename{{case{0:d}, author={{{1:s}}}}}\n".format(i, name))
# Run BibTeX.
- proc = subprocess.Popen(["bibtex", "parsename"], cwd=tempdir,
- stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
- universal_newlines=True)
+ proc = subprocess.Popen(
+ ["bibtex", "parsename"],
+ cwd=tempdir,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT,
+ universal_newlines=True,
+ )
proc.wait()
# Error.
diff --git a/dev-utilities/bibtex-nameparsing/splitnames.py b/dev-utilities/bibtex-nameparsing/splitnames.py
index e3c8839..ea64534 100644
--- a/dev-utilities/bibtex-nameparsing/splitnames.py
+++ b/dev-utilities/bibtex-nameparsing/splitnames.py
@@ -12,11 +12,14 @@ try:
from tempfile import TemporaryDirectory
except ImportError:
from tempfile import mkdtemp
+
class TemporaryDirectory(object):
def __init__(self):
self.name = mkdtemp()
+
def __enter__(self):
return self.name
+
def __exit__(self, exc, value, tb):
shutil.rmtree(self.name)
@@ -42,12 +45,18 @@ def evaluate_bibtex_splitnames(tempdir, names):
# Write entries for each string in the list.
with open(os.path.join(tempdir, "splitnames.bib"), "w") as bibfile:
for i, name in enumerate(names):
- bibfile.write('@splitnames{{case{0:d}, author={{{1:s}}}}}\n'.format(i, name))
+ bibfile.write(
+ "@splitnames{{case{0:d}, author={{{1:s}}}}}\n".format(i, name)
+ )
# Run BibTeX.
- proc = subprocess.Popen(["bibtex", "splitnames"], cwd=tempdir,
- stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
- universal_newlines=True)
+ proc = subprocess.Popen(
+ ["bibtex", "splitnames"],
+ cwd=tempdir,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT,
+ universal_newlines=True,
+ )
proc.wait()
# Error.
|
sciunto-org/python-bibtexparser
|
bc444509826678fc9e101730cc8181a144494f90
|
diff --git a/tests/splitter_tests/test_splitter_entry.py b/tests/splitter_tests/test_splitter_entry.py
index c0f26db..9f2806d 100644
--- a/tests/splitter_tests/test_splitter_entry.py
+++ b/tests/splitter_tests/test_splitter_entry.py
@@ -196,3 +196,38 @@ def test_entry_without_fields(entry_without_fields: str):
assert library.entries[1].key == "subsequentArticle"
assert len(library.entries[1].fields) == 1
+
+
[email protected](
+ "entry",
+ [
+ # common in revtex, see issue #384
+ pytest.param(
+ "@Article {articleTestKey, title = {Some title}}", id="single whitespace"
+ ),
+ pytest.param(
+ "@Article {articleTestKey, title = {Some title}}", id="double whitespace"
+ ),
+ pytest.param("@Article\t{articleTestKey, title = {Some title}}", id="tab"),
+ pytest.param(
+ "@Article \t {articleTestKey, title = {Some title}}",
+ id="tab and whitespaces",
+ ),
+ ],
+)
+def test_entry_with_space_before_bracket(entry: str):
+ """For motivation why we need this, please see issue #391"""
+ some_previous_entry = "@article{normal_entry, title = {The first title}, author = {The first author} }"
+
+ full_bibtex = f"{some_previous_entry}\n\n{entry}\n\n"
+ library: Library = Splitter(full_bibtex).split()
+ assert len(library.blocks) == 2
+ assert len(library.entries) == 2
+ assert len(library.failed_blocks) == 0
+
+ assert library.entries[0].key == "normal_entry"
+ assert len(library.entries[0].fields) == 2
+
+ assert library.entries[1].entry_type == "article"
+ assert library.entries[1].key == "articleTestKey"
+ assert len(library.entries[1].fields) == 1
|
Cannot match if there is a space between `@inproceedings` and `{`
for this bibtex copied from usenix website: (notice the space in `@inproceedings {xxx`)
```
@inproceedings {251572,
author = {Shravan Narayan and Craig Disselkoen and Tal Garfinkel and Nathan Froyd and Eric Rahm and Sorin Lerner and Hovav Shacham and Deian Stefan},
title = {Retrofitting Fine Grain Isolation in the Firefox Renderer},
booktitle = {29th USENIX Security Symposium (USENIX Security 20)},
year = {2020},
isbn = {978-1-939133-17-5},
pages = {699--716},
url = {https://www.usenix.org/conference/usenixsecurity20/presentation/narayan},
publisher = {USENIX Association},
month = aug,
abstract = {Firefox and other major browsers rely on dozens of third-party libraries to render audio, video, images, and other content. These libraries are a frequent source of vulnerabilities. To mitigate this threat, we are migrating Firefox to an architecture that isolates these libraries in lightweight sandboxes, dramatically reducing the impact of a compromise. Retrofitting isolation can be labor-intensive, very prone to security bugs, and requires critical attention to performance. To help, we developed RLBox, a framework that minimizes the burden of converting Firefox to securely and efficiently use untrusted code. To enable this, RLBox employs static information flow enforcement, and lightweight dynamic checks, expressed directly in the C++ type system. RLBox supports efficient sandboxing through either software-based-fault isolation or multi-core process isolation. Performance overheads are modest and transient, and have only minor impact on page latency. We demonstrate this by sandboxing performance-sensitive image decoding libraries (libjpeg and libpng), video decoding libraries (libtheora and libvpx), the libvorbis audio decoding library, and the zlib decompression library. RLBox, using a WebAssembly sandbox, has been integrated into production Firefox to sandbox the libGraphite font shaping library.}
}
```
Everything becomes `ImplicitComment`.

I don't know if this is expected, but there is also no warning or error reported.
|
0.0
|
bc444509826678fc9e101730cc8181a144494f90
|
[
"tests/splitter_tests/test_splitter_entry.py::test_entry_with_space_before_bracket[single",
"tests/splitter_tests/test_splitter_entry.py::test_entry_with_space_before_bracket[double",
"tests/splitter_tests/test_splitter_entry.py::test_entry_with_space_before_bracket[tab]",
"tests/splitter_tests/test_splitter_entry.py::test_entry_with_space_before_bracket[tab"
] |
[
"tests/splitter_tests/test_splitter_entry.py::test_field_enclosings[year-2019-1]",
"tests/splitter_tests/test_splitter_entry.py::test_field_enclosings[month-1-2]",
"tests/splitter_tests/test_splitter_entry.py::test_field_enclosings[author-\"John",
"tests/splitter_tests/test_splitter_entry.py::test_field_enclosings[journal-someJournalReference-4]",
"tests/splitter_tests/test_splitter_entry.py::test_entry_type[@article-article]",
"tests/splitter_tests/test_splitter_entry.py::test_entry_type[@ARTICLE-article]",
"tests/splitter_tests/test_splitter_entry.py::test_entry_type[@Article-article]",
"tests/splitter_tests/test_splitter_entry.py::test_entry_type[@book-book]",
"tests/splitter_tests/test_splitter_entry.py::test_entry_type[@BOOK-book]",
"tests/splitter_tests/test_splitter_entry.py::test_entry_type[@Book-book]",
"tests/splitter_tests/test_splitter_entry.py::test_entry_type[@inbook-inbook]",
"tests/splitter_tests/test_splitter_entry.py::test_entry_type[@INBOOK-inbook]",
"tests/splitter_tests/test_splitter_entry.py::test_entry_type[@Inbook-inbook]",
"tests/splitter_tests/test_splitter_entry.py::test_entry_type[@incollection-incollection]",
"tests/splitter_tests/test_splitter_entry.py::test_entry_type[@INCOLLECTION-incollection]",
"tests/splitter_tests/test_splitter_entry.py::test_entry_type[@Incollection-incollection]",
"tests/splitter_tests/test_splitter_entry.py::test_entry_type[@inproceedings-inproceedings]",
"tests/splitter_tests/test_splitter_entry.py::test_entry_type[@INPROCEEDINGS-inproceedings]",
"tests/splitter_tests/test_splitter_entry.py::test_entry_type[@InprocEEdings-inproceedings]",
"tests/splitter_tests/test_splitter_entry.py::test_field_value[double_quotes-John",
"tests/splitter_tests/test_splitter_entry.py::test_field_value[double_quotes-\\xe0",
"tests/splitter_tests/test_splitter_entry.py::test_field_value[double_quotes-{\\\\`a}",
"tests/splitter_tests/test_splitter_entry.py::test_field_value[double_quotes-Two",
"tests/splitter_tests/test_splitter_entry.py::test_field_value[double_quotes-\\\\texttimes{}{\\\\texttimes}\\\\texttimes]",
"tests/splitter_tests/test_splitter_entry.py::test_field_value[double_quotes-p\\\\^{a}t\\\\'{e}Title",
"tests/splitter_tests/test_splitter_entry.py::test_field_value[double_quotes-Title",
"tests/splitter_tests/test_splitter_entry.py::test_field_value[curly_braces-John",
"tests/splitter_tests/test_splitter_entry.py::test_field_value[curly_braces-\\xe0",
"tests/splitter_tests/test_splitter_entry.py::test_field_value[curly_braces-{\\\\`a}",
"tests/splitter_tests/test_splitter_entry.py::test_field_value[curly_braces-Two",
"tests/splitter_tests/test_splitter_entry.py::test_field_value[curly_braces-\\\\texttimes{}{\\\\texttimes}\\\\texttimes]",
"tests/splitter_tests/test_splitter_entry.py::test_field_value[curly_braces-p\\\\^{a}t\\\\'{e}Title",
"tests/splitter_tests/test_splitter_entry.py::test_field_value[curly_braces-Title",
"tests/splitter_tests/test_splitter_entry.py::test_trailing_comma[double_quotes]",
"tests/splitter_tests/test_splitter_entry.py::test_trailing_comma[curly_braces]",
"tests/splitter_tests/test_splitter_entry.py::test_trailing_comma[no",
"tests/splitter_tests/test_splitter_entry.py::test_multiple_identical_field_keys",
"tests/splitter_tests/test_splitter_entry.py::test_entry_without_fields[without",
"tests/splitter_tests/test_splitter_entry.py::test_entry_without_fields[with"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-08-15 13:49:11+00:00
|
mit
| 5,381 |
|
sciunto-org__python-bibtexparser-424
|
diff --git a/bibtexparser/library.py b/bibtexparser/library.py
index 296b7fc..db01748 100644
--- a/bibtexparser/library.py
+++ b/bibtexparser/library.py
@@ -73,19 +73,19 @@ class Library:
except ValueError:
raise ValueError("Block to replace is not in library.")
- self._blocks.insert(index, new_block)
block_after_add = self._add_to_dicts(new_block)
+ self._blocks.insert(index, block_after_add)
if (
new_block is not block_after_add
- and isinstance(new_block, DuplicateBlockKeyBlock)
+ and isinstance(block_after_add, DuplicateBlockKeyBlock)
and fail_on_duplicate_key
):
# Revert changes to old_block
# Don't fail on duplicate key, as this would lead to an infinite recursion
# (should never happen for a clean library, but could happen if the user
# tampered with the internals of the library).
- self.replace(new_block, old_block, fail_on_duplicate_key=False)
+ self.replace(block_after_add, old_block, fail_on_duplicate_key=False)
raise ValueError("Duplicate key found.")
@staticmethod
@@ -160,7 +160,9 @@ class Library:
@property
def entries(self) -> List[Entry]:
"""All entry (@article, ...) blocks in the library, preserving order of insertion."""
- return list(self._entries_by_key.values())
+ # Note: Taking this from the entries dict would be faster, but does not preserve order
+ # e.g. in cases where `replace` has been called.
+ return [b for b in self._blocks if isinstance(b, Entry)]
@property
def entries_dict(self) -> Dict[str, Entry]:
|
sciunto-org/python-bibtexparser
|
d670c188ce79cb3d7c6e43d4f461b4ca2daa4f31
|
diff --git a/tests/test_library.py b/tests/test_library.py
new file mode 100644
index 0000000..239f76f
--- /dev/null
+++ b/tests/test_library.py
@@ -0,0 +1,66 @@
+from copy import deepcopy
+
+import pytest
+
+from bibtexparser import Library
+from bibtexparser.model import Entry, Field
+
+
+def get_dummy_entry():
+ return Entry(
+ entry_type="article",
+ key="duplicateKey",
+ fields=[
+ Field(key="title", value="A title"),
+ Field(key="author", value="An author"),
+ ],
+ )
+
+
+def test_replace_with_duplicates():
+ """Test that replace() works when there are duplicate values. See issue 404."""
+ library = Library()
+ library.add(get_dummy_entry())
+ library.add(get_dummy_entry())
+ # Test precondition
+ assert len(library.blocks) == 2
+ assert len(library.failed_blocks) == 1
+
+ replacement_entry = get_dummy_entry()
+ replacement_entry.fields_dict["title"].value = "A new title"
+
+ library.replace(
+ library.failed_blocks[0], replacement_entry, fail_on_duplicate_key=False
+ )
+ assert len(library.blocks) == 2
+ assert len(library.failed_blocks) == 1
+ assert library.failed_blocks[0].ignore_error_block["title"] == "A new title"
+
+ replacement_entry_2 = get_dummy_entry()
+ replacement_entry_2.fields_dict["title"].value = "Another new title"
+
+ library.replace(
+ library.entries[0], replacement_entry_2, fail_on_duplicate_key=False
+ )
+ assert len(library.blocks) == 2
+ assert len(library.failed_blocks) == 1
+ # The new block replaces the previous "non-duplicate" and should thus not become a duplicate itself
+ assert library.entries[0].fields_dict["title"].value == "Another new title"
+
+
+def test_replace_fail_on_duplicate():
+ library = Library()
+ replaceable_entry = get_dummy_entry()
+ replaceable_entry.key = "Just a regular entry, to be replaced"
+ future_duplicate_entry = get_dummy_entry()
+ library.add([replaceable_entry, future_duplicate_entry])
+
+ with pytest.raises(ValueError):
+ library.replace(
+ replaceable_entry, get_dummy_entry(), fail_on_duplicate_key=True
+ )
+
+ assert len(library.blocks) == 2
+ assert len(library.failed_blocks) == 0
+ assert library.entries[0].key == "Just a regular entry, to be replaced"
+ assert library.entries[1].key == "duplicateKey"
|
library.replace() method is not working properly when duplicates exist
**Describe the bug**
In order to workaround #401 and checking for failed blocks after adding one (and then replacing them), I came across this new bug.
**Reproducing**
Version: Newest from PyPI *(EDIT BY MAINTAINER: v2.0.0b2)*
Code:
```python
import bibtexparser
from bibtexparser import *
bib_library = bibtexparser.Library()
for i in range(3):
fields = []
fields.append(bibtexparser.model.Field("author", "ö" + str(i)))
entry = bibtexparser.model.Entry("ARTICLE", "test", fields)
bib_library.add(entry)
# print(bib_library.failed_blocks)
# print(len(bib_library.failed_blocks))
# Check whether the addition was successful or resulted in a duplicate block that needs fixing.
for i in range(26):
failed_blocks = bib_library.failed_blocks
if failed_blocks:
failed_block = failed_blocks[0]
# Add any additional ending, so that the slicing also works for first iteration.
if i == 0:
entry.key += "a"
entry.key = entry.key[:-1] + chr(ord("a") + i)
if type(failed_block) == bibtexparser.model.DuplicateBlockKeyBlock:
bib_library.replace(failed_block, entry, fail_on_duplicate_key=False)
# This works:
# bib_library.remove(failed_block)
# bib_library.add(entry)
else:
break
print(bib_library.failed_blocks)
print(bib_library.entries_dict)
bibtex_format = bibtexparser.BibtexFormat()
bibtex_format.indent = ' '
print(bibtexparser.write_string(bib_library, bibtex_format=bibtex_format))
bibtexparser.write_file("my_new_file.bib", bib_library, bibtex_format=bibtex_format)
```
**Workaround**
For me right now, removing the old block and adding the new one seems to work.
**Remaining Questions (Optional)**
Please tick all that apply:
- [ ] I would be willing to to contribute a PR to fix this issue.
- [ ] This issue is a blocker, I'd be greatful for an early fix.
|
0.0
|
d670c188ce79cb3d7c6e43d4f461b4ca2daa4f31
|
[
"tests/test_library.py::test_replace_with_duplicates",
"tests/test_library.py::test_replace_fail_on_duplicate"
] |
[] |
{
"failed_lite_validators": [
"has_issue_reference"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-11-24 05:17:35+00:00
|
mit
| 5,382 |
|
sciunto-org__python-bibtexparser-425
|
diff --git a/bibtexparser/library.py b/bibtexparser/library.py
index db01748..2f6a425 100644
--- a/bibtexparser/library.py
+++ b/bibtexparser/library.py
@@ -24,7 +24,9 @@ class Library:
if blocks is not None:
self.add(blocks)
- def add(self, blocks: Union[List[Block], Block]):
+ def add(
+ self, blocks: Union[List[Block], Block], fail_on_duplicate_key: bool = False
+ ):
"""Add blocks to library.
The adding is key-safe, i.e., it is made sure that no duplicate keys are added.
@@ -32,14 +34,30 @@ class Library:
a DuplicateKeyBlock.
:param blocks: Block or list of blocks to add.
+ :param fail_on_duplicate_key: If True, raises ValueError if a block was replaced with a DuplicateKeyBlock.
"""
if isinstance(blocks, Block):
blocks = [blocks]
+ _added_blocks = []
for block in blocks:
# This may replace block with a DuplicateEntryKeyBlock
block = self._add_to_dicts(block)
self._blocks.append(block)
+ _added_blocks.append(block)
+
+ if fail_on_duplicate_key:
+ duplicate_keys = []
+ for original, added in zip(blocks, _added_blocks):
+ if not original is added and isinstance(added, DuplicateBlockKeyBlock):
+ duplicate_keys.append(added.key)
+
+ if len(duplicate_keys) > 0:
+ raise ValueError(
+ f"Duplicate keys found: {duplicate_keys}. "
+ f"Duplicate entries have been added to the library as DuplicateBlockKeyBlock."
+ f"Use `library.failed_blocks` to access them. "
+ )
def remove(self, blocks: Union[List[Block], Block]):
"""Remove blocks from library.
|
sciunto-org/python-bibtexparser
|
40db93bd458d908215fa2498d927fda36007e20a
|
diff --git a/tests/test_library.py b/tests/test_library.py
index 239f76f..e02597e 100644
--- a/tests/test_library.py
+++ b/tests/test_library.py
@@ -64,3 +64,12 @@ def test_replace_fail_on_duplicate():
assert len(library.failed_blocks) == 0
assert library.entries[0].key == "Just a regular entry, to be replaced"
assert library.entries[1].key == "duplicateKey"
+
+
+def test_fail_on_duplicate_add():
+ library = Library()
+ library.add(get_dummy_entry())
+ with pytest.raises(ValueError):
+ library.add(get_dummy_entry(), fail_on_duplicate_key=True)
+ assert len(library.blocks) == 2
+ assert len(library.failed_blocks) == 1
|
Improve duplicate entry (or in general block) handling
**Is your feature request related to a problem? Please describe.**
Right now, when adding something to the library, it seems to always silently deal with duplicate keys.
Doing this silently is not that perfect.
Right now, it might also cause another issue when actually trying to write such a library: #400
**Describe the solution you'd like**
Ideally, the handling can be improved (like adding some suffix to the key, as typical for such cases in BibTeX).
**Use cases**
Sometimes one does just want to add a valid entry and doesn't want to deal with making sure that it could be added successfully.
**Describe alternatives you've considered**
Manually checking whether the entry has been successfully added after *every* addition of an entry (or at the end).
**Remaining Questions (Optional)**
Please tick all that apply:
- [ ] I would be willing to to contribute a PR to fix this issue.
- [ ] This issue is a blocker, I'd be greatful for an early fix.
|
0.0
|
40db93bd458d908215fa2498d927fda36007e20a
|
[
"tests/test_library.py::test_fail_on_duplicate_add"
] |
[
"tests/test_library.py::test_replace_with_duplicates",
"tests/test_library.py::test_replace_fail_on_duplicate"
] |
{
"failed_lite_validators": [
"has_issue_reference"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-11-24 06:25:57+00:00
|
mit
| 5,383 |
|
sciunto-org__python-bibtexparser-442
|
diff --git a/bibtexparser/model.py b/bibtexparser/model.py
index d3b99be..b53876a 100644
--- a/bibtexparser/model.py
+++ b/bibtexparser/model.py
@@ -318,6 +318,14 @@ class Entry(Block):
return self.key
return self.fields_dict[key].value
+ def __setitem__(self, key: str, value: Any):
+ """Dict-mimicking index.
+
+ This serves for partial v1.x backwards compatibility,
+ as well as for a shorthand for `set_field`.
+ """
+ self.set_field(Field(key, value))
+
def items(self):
"""Dict-mimicking, for partial v1.x backwards compatibility.
|
sciunto-org/python-bibtexparser
|
2f2aa2c8b5012c12e9cbae9c158b9219b4eca54d
|
diff --git a/tests/test_model.py b/tests/test_model.py
index a52894e..a2d5c3b 100644
--- a/tests/test_model.py
+++ b/tests/test_model.py
@@ -290,3 +290,24 @@ def test_entry_str():
)
assert str(entry) == expected
+
+
+def test_entry_fields_shorthand():
+ entry = Entry(
+ entry_type="article",
+ key="myEntry",
+ fields=[
+ Field("myFirstField", "firstValue"),
+ Field("mySecondField", "secondValue"),
+ ],
+ )
+
+ entry["myFirstField"] = "changed_value"
+ assert entry["myFirstField"] == "changed_value"
+ assert entry.fields_dict["myFirstField"].value == "changed_value"
+
+ entry["myNewField"] = "new_value"
+ assert entry["myNewField"] == "new_value"
+ assert entry.fields_dict["myNewField"].key == "myNewField"
+ assert entry.fields_dict["myNewField"].value == "new_value"
+ assert entry.fields_dict["myNewField"].start_line is None
|
Implement `__setitem__` on entries
For easier compatiblitiy with (and migration from), we should add a `__setitem__` shorthand on entries, allowing to create new fields and add them to their entry.
Specifically, `myentry["somekey"] = some_value` should create a new field with key `"somekey"` (string type) and value `some_value` (any type), and then add it to the entry using `set_field`
|
0.0
|
2f2aa2c8b5012c12e9cbae9c158b9219b4eca54d
|
[
"tests/test_model.py::test_entry_fields_shorthand"
] |
[
"tests/test_model.py::test_entry_equality",
"tests/test_model.py::test_entry_copy",
"tests/test_model.py::test_entry_deepcopy",
"tests/test_model.py::test_string_equality",
"tests/test_model.py::test_string_copy",
"tests/test_model.py::test_string_deepcopy",
"tests/test_model.py::test_preamble_equality",
"tests/test_model.py::test_preamble_copy",
"tests/test_model.py::test_preable_deepcopy",
"tests/test_model.py::test_implicit_comment_equality",
"tests/test_model.py::test_implicit_comment_copy",
"tests/test_model.py::test_implicit_comment_deepcopy",
"tests/test_model.py::test_explicit_comment_equality",
"tests/test_model.py::test_explicit_comment_copy",
"tests/test_model.py::test_explicit_comment_deepcopy",
"tests/test_model.py::test_implicit_and_explicit_comment_equality",
"tests/test_model.py::test_string_str",
"tests/test_model.py::test_preable_str",
"tests/test_model.py::test_implicit_comment_str",
"tests/test_model.py::test_explicit_comment_str",
"tests/test_model.py::test_field_str",
"tests/test_model.py::test_entry_str"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2024-01-18 19:33:29+00:00
|
mit
| 5,384 |
|
sciunto-org__python-bibtexparser-473
|
diff --git a/bibtexparser/middlewares/__init__.py b/bibtexparser/middlewares/__init__.py
index 89b0af1..3fd1a36 100644
--- a/bibtexparser/middlewares/__init__.py
+++ b/bibtexparser/middlewares/__init__.py
@@ -1,5 +1,6 @@
from bibtexparser.middlewares.enclosing import AddEnclosingMiddleware
from bibtexparser.middlewares.enclosing import RemoveEnclosingMiddleware
+from bibtexparser.middlewares.fieldkeys import NormalizeFieldKeys
from bibtexparser.middlewares.interpolate import ResolveStringReferencesMiddleware
from bibtexparser.middlewares.latex_encoding import LatexDecodingMiddleware
from bibtexparser.middlewares.latex_encoding import LatexEncodingMiddleware
diff --git a/bibtexparser/middlewares/fieldkeys.py b/bibtexparser/middlewares/fieldkeys.py
new file mode 100644
index 0000000..edb5a7e
--- /dev/null
+++ b/bibtexparser/middlewares/fieldkeys.py
@@ -0,0 +1,52 @@
+import logging
+from typing import Dict
+from typing import List
+from typing import Set
+
+from bibtexparser.library import Library
+from bibtexparser.model import Entry
+from bibtexparser.model import Field
+
+from .middleware import BlockMiddleware
+
+
+class NormalizeFieldKeys(BlockMiddleware):
+ """Normalize field keys to lowercase.
+
+ In case of conflicts (e.g. both 'author' and 'Author' exist in the same entry),
+ a warning is emitted, and the last value wins.
+
+ Some other middlewares, such as `SeparateCoAuthors`, assume lowercase key names.
+ """
+
+ def __init__(self, allow_inplace_modification: bool = True):
+ super().__init__(
+ allow_inplace_modification=allow_inplace_modification,
+ allow_parallel_execution=True,
+ )
+
+ # docstr-coverage: inherited
+ def transform_entry(self, entry: Entry, library: "Library") -> Entry:
+ seen_normalized_keys: Set[str] = set()
+ new_fields_dict: Dict[str, Field] = {}
+ for field in entry.fields:
+ normalized_key: str = field.key.lower()
+ # if the normalized key is already present, apply "last one wins"
+ # otherwise preserve insertion order
+ # if a key is overwritten, emit a detailed warning
+ # if performance is a concern, we could emit a warning with only {entry.key}
+ # to remove "seen_normalized_keys" and this if statement
+ if normalized_key in seen_normalized_keys:
+ logging.warning(
+ f"NormalizeFieldKeys: in entry '{entry.key}': "
+ + f"duplicate normalized key '{normalized_key}' "
+ + f"(original '{field.key}'); overriding previous value"
+ )
+ seen_normalized_keys.add(normalized_key)
+ field.key = normalized_key
+ new_fields_dict[normalized_key] = field
+
+ new_fields: List[Field] = list(new_fields_dict.values())
+ entry.fields = new_fields
+
+ return entry
|
sciunto-org/python-bibtexparser
|
53843c0055dcee91cdf4b24b38f9bc4620235849
|
diff --git a/tests/middleware_tests/test_fieldkeys.py b/tests/middleware_tests/test_fieldkeys.py
new file mode 100644
index 0000000..acff042
--- /dev/null
+++ b/tests/middleware_tests/test_fieldkeys.py
@@ -0,0 +1,68 @@
+import re
+
+from bibtexparser import Library
+from bibtexparser.middlewares.fieldkeys import NormalizeFieldKeys
+from bibtexparser.model import Entry
+from bibtexparser.model import Field
+
+entries = {
+ "article": {
+ "author": '"Smith, J."',
+ "title": '"A Test Article"',
+ "journal": '"J. of Testing"',
+ "month": '"jan"',
+ "year": '"2022"',
+ },
+ "book": {
+ "author": '"Doe, J."',
+ "title": '"A Test Book"',
+ "publisher": '"Test Pub."',
+ "year": '"2021"',
+ "month": "apr",
+ },
+ "inproceedings": {
+ "author": '"Jones, R."',
+ "title": '"A Test Conf. Paper"',
+ "booktitle": '"Proc. of the Intl. Test Conf."',
+ "year": '"2023"',
+ "month": "8",
+ },
+}
+
+ref = Library()
+for i, (entry_type, fields) in enumerate(entries.items()):
+ f = [Field(key=k, value=v) for k, v in fields.items()]
+ ref.add(Entry(entry_type=entry_type, key=f"entry{i}", fields=f))
+
+
+def test_normalize_fieldkeys():
+ """
+ Check library with lowercase field keys.
+ """
+
+ lib = Library()
+ for i, (entry_type, fields) in enumerate(entries.items()):
+ f = [Field(key=k, value=v) for k, v in fields.items()]
+ lib.add(Entry(entry_type=entry_type, key=f"entry{i}", fields=f))
+
+ lib = NormalizeFieldKeys().transform(lib)
+
+ for key in lib.entries_dict:
+ assert lib.entries_dict[key] == ref.entries_dict[key]
+
+
+def test_normalize_fieldkeys_force_last(caplog):
+ """
+ Check library with uppercase field keys and duplicate normalized keys.
+ """
+ lib = Library()
+ for i, (entry_type, fields) in enumerate(entries.items()):
+ f = [Field(key=k.lower(), value="dummyvalue") for k in fields]
+ f += [Field(key=k.upper(), value=v) for k, v in fields.items()]
+ lib.add(Entry(entry_type=entry_type, key=f"entry{i}", fields=f))
+
+ lib = NormalizeFieldKeys().transform(lib)
+ assert re.match(r"(WARNING\s*)(\w*\:\w*\.py\:[0-9]*\s*)(NormalizeFieldKeys)(.*)", caplog.text)
+
+ for key in lib.entries_dict:
+ assert lib.entries_dict[key] == ref.entries_dict[key]
|
Normalize field keys (to lowercase)
**Describe the bug**
I have several .bib files that contain (mixed) field keys that are either in lowercase or start with a capital letter, such as "Author" and "Title". No other tooling complains about this.
SeparateCoAuthors does not work and I cannot uniformy access the fields using e.g. `entry['title']`
A normalization to lowercase of the field keys was conducted in v1.
Maybe this can be fixed using a middleware? I would be really grateful!
**Reproducing**
Version: e3757c13abf2784bda612464843ab30256317e6c
Code:
```python
#!/usr/bin/python
import bibtexparser
import bibtexparser.middlewares as m
layers = [
m.LatexDecodingMiddleware(),
m.MonthIntMiddleware(True), # Months should be represented as int (0-12)
m.SeparateCoAuthors(True), # Co-authors should be separated as list of strings
m.SplitNameParts(True), # Individual Names should be split into first, von, last, jr parts
m.MergeNameParts("last", True) # Individual Names should be merged oto Last, First...
]
bib_database = bibtexparser.parse_file('data/Survey.bib', append_middleware=layers)
for entry in bib_database.entries:
print(entry['title']);
```
Bibtex:
```
@InCollection{Name2006,
Title = {A Title},
Author = {Name, First and Name, Second},
Booktitle = {ITS},
Publisher = {Some publisher},
Year = {2006},
Pages = {61--70}
}
```
**Remaining Questions (Optional)**
Please tick all that apply:
- [ ] I would be willing to contribute a PR to fix this issue.
- [ ] This issue is a blocker, I'd be grateful for an early fix.
|
0.0
|
53843c0055dcee91cdf4b24b38f9bc4620235849
|
[
"tests/middleware_tests/test_fieldkeys.py::test_normalize_fieldkeys",
"tests/middleware_tests/test_fieldkeys.py::test_normalize_fieldkeys_force_last"
] |
[] |
{
"failed_lite_validators": [
"has_git_commit_hash",
"has_added_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2024-02-19 11:46:29+00:00
|
mit
| 5,385 |
|
sclorg__spec2scl-22
|
diff --git a/spec2scl/transformers/generic.py b/spec2scl/transformers/generic.py
index dcf3615..622d004 100644
--- a/spec2scl/transformers/generic.py
+++ b/spec2scl/transformers/generic.py
@@ -17,7 +17,7 @@ class GenericTransformer(transformer.Transformer):
@matches(r'(?<!d)(Conflicts:\s*)([^\s]+)', sections=settings.METAINFO_SECTIONS) # avoid BuildConflicts
@matches(r'(BuildConflicts:\s*)([^\s]+)', sections=settings.METAINFO_SECTIONS)
- @matches(r'(Provides:\s*)([^\s]+)', sections=settings.METAINFO_SECTIONS)
+ @matches(r'(Provides:\s*)(?!bundled\()([^\s]+)', sections=settings.METAINFO_SECTIONS)
@matches(r'(Obsoletes:\s*)([^\s]+)', sections=settings.METAINFO_SECTIONS)
def handle_dependency_tag(self, original_spec, pattern, text, scl_deps_effect=False):
tag = text[0:text.find(':') + 1]
@@ -45,7 +45,7 @@ class GenericTransformer(transformer.Transformer):
@matches(r'(?<!d)(Requires:\s*)(?!\w*/\w*)([^[\s]+)', sections=settings.METAINFO_SECTIONS) # avoid BuildRequires
@matches(r'(BuildRequires:\s*)(?!\w*/\w*)([^\s]+)', sections=settings.METAINFO_SECTIONS)
def handle_dependency_tag_modified_by_list(self, original_spec, pattern, text):
- return self.handle_dependency_tag(pattern, original_spec, text, True)
+ return self.handle_dependency_tag(original_spec, pattern, text, True)
@matches(r'(%package\s+-n\s+)([^\s]+)', sections=['%package'])
@matches(r'(%description\s+-n\s+)([^\s]+)', sections=['%description'])
|
sclorg/spec2scl
|
02c275cab61c480a7ba24be9cc92c846cb375616
|
diff --git a/tests/test_generic_transformer.py b/tests/test_generic_transformer.py
index 30c7114..98f043c 100644
--- a/tests/test_generic_transformer.py
+++ b/tests/test_generic_transformer.py
@@ -23,13 +23,17 @@ class TestGenericTransformer(TransformerTestCase):
('Conflicts:spam', 'Conflicts:%{?scl_prefix}spam'),
('BuildConflicts: \t spam', 'BuildConflicts: \t %{?scl_prefix}spam'),
('Provides: spam < 3.0', 'Provides: %{?scl_prefix}spam < 3.0'),
+ ('Provides: bundled(libname)', 'Provides: bundled(libname)'),
('Conflicts: spam > 2.0-1', 'Conflicts: %{?scl_prefix}spam > 2.0-1'),
('Obsoletes: spam, blah, foo', 'Obsoletes: %{?scl_prefix}spam, %{?scl_prefix}blah, %{?scl_prefix}foo'),
('Obsoletes: spam blah foo', 'Obsoletes: %{?scl_prefix}spam %{?scl_prefix}blah %{?scl_prefix}foo'),
])
def test_handle_dependency_tag(self, spec, expected):
- handler = self.t.handle_dependency_tag
- assert self.t.handle_dependency_tag(spec, self.get_pattern_for_spec(handler, spec), spec) == expected
+ pattern = self.get_pattern_for_spec(self.t.handle_dependency_tag, spec)
+ if pattern:
+ assert self.t.handle_dependency_tag(spec, pattern, spec) == expected
+ else:
+ assert spec == expected
@pytest.mark.parametrize(('spec', 'expected'), [
('Requires: perl(:MODULE_COMPAT_%(eval "`perl -V:version`"; echo $version))',
|
Provides: bundled should not have scl prefix
Originally reported by: **Anonymous**
----------------------------------------
Provides: %{?scl_prefix}bundled(libname)
should be
Provides: bundled(libname)
----------------------------------------
- Bitbucket: https://bitbucket.org/bkabrda/spec2scl/issue/18
|
0.0
|
02c275cab61c480a7ba24be9cc92c846cb375616
|
[
"tests/test_generic_transformer.py::TestGenericTransformer::test_handle_dependency_tag[Provides:"
] |
[
"tests/test_generic_transformer.py::TestGenericTransformer::test_insert_scl_init[-%{?scl:%scl_package",
"tests/test_generic_transformer.py::TestGenericTransformer::test_insert_scl_init[Name:spam-%{?scl:%scl_package",
"tests/test_generic_transformer.py::TestGenericTransformer::test_insert_scl_init[Name:",
"tests/test_generic_transformer.py::TestGenericTransformer::test_handle_dependency_tag[Conflicts:spam-Conflicts:%{?scl_prefix}spam]",
"tests/test_generic_transformer.py::TestGenericTransformer::test_handle_dependency_tag[BuildConflicts:",
"tests/test_generic_transformer.py::TestGenericTransformer::test_handle_dependency_tag[Conflicts:",
"tests/test_generic_transformer.py::TestGenericTransformer::test_handle_dependency_tag[Obsoletes:",
"tests/test_generic_transformer.py::TestGenericTransformer::test_handle_dependency_tag_with_spaces_in_brackets[Requires:",
"tests/test_generic_transformer.py::TestGenericTransformer::test_handle_dependency_tag_with_path[Requires:",
"tests/test_generic_transformer.py::TestGenericTransformer::test_handle_dependency_tag_modified_scl_deps[Requires:",
"tests/test_generic_transformer.py::TestGenericTransformer::test_handle_dependency_tag_modified_scl_deps[BuildRequires:",
"tests/test_generic_transformer.py::TestGenericTransformer::test_handle_subpackages_should_sclize[%package",
"tests/test_generic_transformer.py::TestGenericTransformer::test_handle_subpackages_should_sclize[%description",
"tests/test_generic_transformer.py::TestGenericTransformer::test_handle_subpackages_should_sclize[%files",
"tests/test_generic_transformer.py::TestGenericTransformer::test_handle_subpackages_should_not_sclize[%package",
"tests/test_generic_transformer.py::TestGenericTransformer::test_handle_subpackages_should_not_sclize[%description",
"tests/test_generic_transformer.py::TestGenericTransformer::test_handle_subpackages_should_not_sclize[%files",
"tests/test_generic_transformer.py::TestGenericTransformer::test_handle_setup_macro_should_sclize[%setup-%setup",
"tests/test_generic_transformer.py::TestGenericTransformer::test_handle_setup_macro_should_sclize[%setup",
"tests/test_generic_transformer.py::TestGenericTransformer::test_handle_setup_macro_should_not_sclize[%setup",
"tests/test_generic_transformer.py::TestGenericTransformer::test_handle_name_tag[Name:",
"tests/test_generic_transformer.py::TestGenericTransformer::test_handle_name_tag[Name:spam-Name:%{?scl_prefix}spam]",
"tests/test_generic_transformer.py::TestGenericTransformer::test_handle_name_macro[%{name}-%{pkg_name}]",
"tests/test_generic_transformer.py::TestGenericTransformer::test_handle_name_macro[%{pkg_name}-%{pkg_name}]",
"tests/test_generic_transformer.py::TestGenericTransformer::test_handle_name_macro[%{name_spam}-%{name_spam}]",
"tests/test_generic_transformer.py::TestGenericTransformer::test_handle_meta_deps[Requires:-True-True-Requires:]",
"tests/test_generic_transformer.py::TestGenericTransformer::test_handle_meta_deps[Requires:-False-True-%{?scl:Requires:",
"tests/test_generic_transformer.py::TestGenericTransformer::test_handle_meta_deps[Requires:-True-False-%{?scl:BuildRequires:",
"tests/test_generic_transformer.py::TestGenericTransformer::test_handle_meta_deps[Requires:-False-False-%{?scl:Requires:",
"tests/test_generic_transformer.py::TestGenericTransformer::test_handle_configure_make[configure\\n-%{?scl:scl",
"tests/test_generic_transformer.py::TestGenericTransformer::test_handle_configure_make[%configure",
"tests/test_generic_transformer.py::TestGenericTransformer::test_handle_configure_make[make"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
}
|
2017-01-10 17:51:37+00:00
|
mit
| 5,386 |
|
scottstanie__sentineleof-11
|
diff --git a/eof/cli.py b/eof/cli.py
index e5a2432..948c96c 100644
--- a/eof/cli.py
+++ b/eof/cli.py
@@ -35,7 +35,13 @@ from eof import log
type=click.Choice(["S1A", "S1B"]),
help="Optionally specify Sentinel satellite to download (default: gets both S1A and S1B)",
)
-def cli(search_path, save_dir, sentinel_file, date, mission):
[email protected](
+ "--use-scihub",
+ is_flag=True,
+ default=False,
+ help="Use SciHub as primary provider to download orbits (default: False)",
+)
+def cli(search_path, save_dir, sentinel_file, date, mission, use_scihub):
"""Download Sentinel precise orbit files.
Saves files to `save-dir` (default = current directory)
@@ -51,4 +57,5 @@ def cli(search_path, save_dir, sentinel_file, date, mission):
sentinel_file=sentinel_file,
mission=mission,
date=date,
+ use_scihub=use_scihub,
)
diff --git a/eof/download.py b/eof/download.py
index ab06273..b9db51e 100644
--- a/eof/download.py
+++ b/eof/download.py
@@ -45,7 +45,8 @@ PRECISE_ORBIT = "POEORB"
RESTITUTED_ORBIT = "RESORB"
-def download_eofs(orbit_dts=None, missions=None, sentinel_file=None, save_dir="."):
+def download_eofs(orbit_dts=None, missions=None, sentinel_file=None, save_dir=".",
+ use_scihub: bool = False):
"""Downloads and saves EOF files for specific dates
Args:
@@ -54,6 +55,8 @@ def download_eofs(orbit_dts=None, missions=None, sentinel_file=None, save_dir=".
No input downloads both, must be same len as orbit_dts
sentinel_file (str): path to Sentinel-1 filename to download one .EOF for
save_dir (str): directory to save the EOF files into
+ use_scihub (bool): use SciHub to download orbits
+ (if False SciHUb is used only as a fallback)
Returns:
list[str]: all filenames of saved orbit files
@@ -76,18 +79,51 @@ def download_eofs(orbit_dts=None, missions=None, sentinel_file=None, save_dir=".
# First make sures all are datetimes if given string
orbit_dts = [parse(dt) if isinstance(dt, str) else dt for dt in orbit_dts]
- # Download and save all links in parallel
- pool = ThreadPool(processes=MAX_WORKERS)
- result_dt_dict = {
- pool.apply_async(_download_and_write, (mission, dt, save_dir)): dt
- for mission, dt in zip(missions, orbit_dts)
- }
filenames = []
- for result in result_dt_dict:
- cur_filenames = result.get()
- dt = result_dt_dict[result]
- logger.info("Finished {}, saved to {}".format(dt.date(), cur_filenames))
- filenames.extend(cur_filenames)
+
+ if not use_scihub:
+ # Download and save all links in parallel
+ pool = ThreadPool(processes=MAX_WORKERS)
+ result_dt_dict = {
+ pool.apply_async(_download_and_write, (mission, dt, save_dir)): dt
+ for mission, dt in zip(missions, orbit_dts)
+ }
+
+ for result in result_dt_dict:
+ cur_filenames = result.get()
+ if cur_filenames is None:
+ use_scihub = True
+ continue
+ dt = result_dt_dict[result]
+ logger.info("Finished {}, saved to {}".format(dt.date(), cur_filenames))
+ filenames.extend(cur_filenames)
+
+ if use_scihub:
+ # try to search on scihub
+ from .scihubclient import ScihubGnssClient
+ client = ScihubGnssClient()
+ query = {}
+ if sentinel_file:
+ query.update(client.query_orbit_for_product(sentinel_file))
+ else:
+ for mission, dt in zip(missions, orbit_dts):
+ result = client.query_orbit(dt, dt + timedelta(days=1),
+ mission, product_type='AUX_POEORB')
+ if result:
+ query.update(result)
+ else:
+ # try with RESORB
+ result = client.query_orbit(dt, dt + timedelta(minutes=1),
+ mission,
+ product_type='AUX_RESORB')
+ query.update(result)
+
+ if query:
+ result = client.download_all(query)
+ filenames.extend(
+ item['path'] for item in result.downloaded.values()
+ )
+
return filenames
@@ -299,7 +335,8 @@ def find_scenes_to_download(search_path="./", save_dir="./"):
return orbit_dts, missions
-def main(search_path=".", save_dir=",", sentinel_file=None, mission=None, date=None):
+def main(search_path=".", save_dir=",", sentinel_file=None, mission=None, date=None,
+ use_scihub: bool = False):
"""Function used for entry point to download eofs"""
if not os.path.exists(save_dir):
@@ -331,4 +368,5 @@ def main(search_path=".", save_dir=",", sentinel_file=None, mission=None, date=N
missions=missions,
sentinel_file=sentinel_file,
save_dir=save_dir,
+ use_scihub=use_scihub,
)
diff --git a/eof/scihubclient.py b/eof/scihubclient.py
new file mode 100644
index 0000000..9060ea8
--- /dev/null
+++ b/eof/scihubclient.py
@@ -0,0 +1,143 @@
+"""sentinelsat based client to get orbit files form scihub.copernicu.eu."""
+
+
+import re
+import logging
+import datetime
+import operator
+import collections
+from typing import NamedTuple, Sequence
+
+from .products import Sentinel as S1Product
+
+from sentinelsat import SentinelAPI
+
+
+_log = logging.getLogger(__name__)
+
+
+DATE_FMT = '%Y%m%dT%H%M%S'
+
+
+class ValidityError(ValueError):
+ pass
+
+
+class ValidityInfo(NamedTuple):
+ product_id: str
+ generation_date: datetime.datetime
+ start_validity: datetime.datetime
+ stop_validity: datetime.datetime
+
+
+def get_validity_info(products: Sequence[str],
+ pattern=None) -> Sequence[ValidityInfo]:
+ if pattern is None:
+ # use a generic pattern
+ pattern = re.compile(
+ r'S1\w+_(?P<generation_date>\d{8}T\d{6})_'
+ r'V(?P<start_validity>\d{8}T\d{6})_'
+ r'(?P<stop_validity>\d{8}T\d{6})\w*')
+
+ keys = ('generation_date', 'start_validity', 'stop_validity')
+ out = []
+ for product_id in products:
+ mobj = pattern.match(product_id)
+ if mobj:
+ validity_data = {
+ name: datetime.datetime.strptime(mobj.group(name), DATE_FMT)
+ for name in keys
+ }
+ out.append(ValidityInfo(product_id, **validity_data))
+ else:
+ raise ValueError(
+ f'"{product_id}" does not math the regular expression '
+ f'for validity')
+
+ return out
+
+
+def lastval_cover(t0: datetime.datetime, t1: datetime.datetime,
+ data: Sequence[ValidityInfo]) -> str:
+ candidates = [
+ item for item in data
+ if item.start_validity <= t0 and item.stop_validity >= t1
+ ]
+ if not candidates:
+ raise ValidityError(
+ f'none of the input products completely covers the requested '
+ f'time interval: [t0={t0}, t1={t1}]')
+
+ candidates.sort(key=operator.attrgetter('generation_date'), reverse=True)
+
+ return candidates[0].product_id
+
+
+class OrbitSelectionError(RuntimeError):
+ pass
+
+
+class ScihubGnssClient:
+ T0 = datetime.timedelta(days=1)
+ T1 = datetime.timedelta(days=1)
+
+ def __init__(self, user: str = "gnssguest", password: str = "gnssguest",
+ api_url: str = "https://scihub.copernicus.eu/gnss/",
+ **kwargs):
+ self._api = SentinelAPI(user=user, password=password, api_url=api_url,
+ **kwargs)
+
+ def query_orbit(self, t0, t1, satellite_id: str,
+ product_type: str = 'AUX_POEORB'):
+ assert satellite_id in {'S1A', 'S1B'}
+ assert product_type in {'AUX_POEORB', 'AUX_RESORB'}
+
+ query_padams = dict(
+ producttype=product_type,
+ platformserialidentifier=satellite_id[1:],
+ date=[t0, t1],
+ )
+ _log.debug('query parameter: %s', query_padams)
+ products = self._api.query(**query_padams)
+ return products
+
+ @staticmethod
+ def _select_orbit(products, t0, t1):
+ orbit_products = [p['identifier'] for p in products.values()]
+ validity_info = get_validity_info(orbit_products)
+ product_id = lastval_cover(t0, t1, validity_info)
+ return collections.OrderedDict(
+ (k, v) for k, v in products.items()
+ if v['identifier'] == product_id
+ )
+
+ def query_orbit_for_product(self, product,
+ product_type: str = 'AUX_POEORB',
+ t0_margin: datetime.timedelta = T0,
+ t1_margin: datetime.timedelta = T1):
+ if isinstance(product, str):
+ product = S1Product(product)
+
+ t0 = product.start_time
+ t1 = product.stop_time
+
+ products = self.query_orbit(t0 - t0_margin, t1 + t1_margin,
+ satellite_id=product.mission,
+ product_type=product_type)
+ return self._select_orbit(products, t0, t1)
+
+ def download(self, uuid, **kwargs):
+ """Download a single orbit product.
+
+ See sentinelsat.SentinelAPI.download for a detailed description
+ of arguments.
+ """
+ return self._api.download(uuid, **kwargs)
+
+ def download_all(self, products, **kwargs):
+ """Download all the specified orbit products.
+
+ See sentinelsat.SentinelAPI.download_all for a detailed description
+ of arguments.
+ """
+ return self._api.download_all(products, **kwargs)
diff --git a/requirements.txt b/requirements.txt
index e5ecbfe..18eaad6 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -1,3 +1,4 @@
python-dateutil==2.5.1
requests>=2.20.0
click==6.7
+sentinelsat>=1.0
diff --git a/setup.py b/setup.py
index fd829be..e82e843 100644
--- a/setup.py
+++ b/setup.py
@@ -20,6 +20,7 @@ setuptools.setup(
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
+ "Programming Language :: Python :: 3.9",
"Programming Language :: C",
"License :: OSI Approved :: MIT License",
"Topic :: Scientific/Engineering",
@@ -29,6 +30,7 @@ setuptools.setup(
"requests",
"click",
"python-dateutil",
+ "sentinelsat >= 1.0",
],
entry_points={
"console_scripts": [
|
scottstanie/sentineleof
|
59aba730a2f07bba25351abe51017bdaa4085c10
|
diff --git a/eof/tests/test_eof.py b/eof/tests/test_eof.py
index e89c9be..6ac9b68 100644
--- a/eof/tests/test_eof.py
+++ b/eof/tests/test_eof.py
@@ -159,4 +159,5 @@ class TestEOF(unittest.TestCase):
orbit_dts=["20200101"],
sentinel_file=None,
save_dir=",",
+ use_scihub=False,
)
|
https://qc.sentinel1.eo.esa.int discontinued
The old S1-QC site has been discontinued.
The alternative service https://qc.sentinel1.copernicus.eu should have the same API but it seems that currently it does not provided orbit files.
The recommended alternative is https://scihub.copernicus.eu/gnss which has a different API and requires authentication.
See also https://github.com/johntruckenbrodt/pyroSAR/pull/130.
|
0.0
|
59aba730a2f07bba25351abe51017bdaa4085c10
|
[
"eof/tests/test_eof.py::TestEOF::test_mission"
] |
[
"eof/tests/test_eof.py::TestEOF::test_find_scenes_to_download",
"eof/tests/test_eof.py::TestEOF::test_download_eofs_errors",
"eof/tests/test_eof.py::TestEOF::test_main_error_args",
"eof/tests/test_eof.py::TestEOF::test_main_nothing_found"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-04-30 19:13:02+00:00
|
mit
| 5,387 |
|
scottwernervt__favicon-17
|
diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index d1cc7ff..f17f3d6 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -1,6 +1,11 @@
Changelog
=========
+0.5.1 (2018-11-05)
+------------------
+
+* Fix 'NoneType' object has no attribute 'lower' for meta tags (`#16 <https://github.com/scottwernervt/favicon/issues/16>`_).
+
0.5.0 (2018-11-05)
------------------
diff --git a/src/favicon/favicon.py b/src/favicon/favicon.py
index cd18532..df5eaf7 100644
--- a/src/favicon/favicon.py
+++ b/src/favicon/favicon.py
@@ -120,9 +120,10 @@ def tags(url, html):
meta_tags = set()
for meta_tag in soup.find_all('meta', attrs={'content': True}):
- meta_type = meta_tag.get('name') or meta_tag.get('property')
+ meta_type = meta_tag.get('name') or meta_tag.get('property') or ''
+ meta_type = meta_type.lower()
for name in META_NAMES:
- if meta_type.lower() == name.lower():
+ if meta_type == name.lower():
meta_tags.add(meta_tag)
icons = set()
|
scottwernervt/favicon
|
77632d6431d0c4b75a86f1b7476a612f5bb98f7a
|
diff --git a/tests/test_favicon.py b/tests/test_favicon.py
index 6551313..ffa32c0 100644
--- a/tests/test_favicon.py
+++ b/tests/test_favicon.py
@@ -116,6 +116,15 @@ def test_meta_content_attribute(m, meta_tag):
assert icons
+def test_invalid_meta_tag(m):
+ m.head('http://mock.com/favicon.ico', text='Not Found', status_code=404)
+ m.get('http://mock.com/',
+ text='<meta content="en-US" data-rh="true" itemprop="inLanguage"/>')
+
+ icons = favicon.get('http://mock.com/')
+ assert not icons
+
+
@pytest.mark.parametrize('url,expected', [
('http://mock.com/favicon.ico', True),
('favicon.ico', False),
|
AttributeError: 'NoneType' object has no attribute 'lower'
The following tag `<meta content="en-US" data-rh="true" itemprop="inLanguage"/>` causes an exception because it does not have `name` or `proprety` attribute.
```python
Traceback (most recent call last):
File "/opt/pycharm-professional/helpers/pydev/pydevd.py", line 1664, in <module>
main()
File "/opt/pycharm-professional/helpers/pydev/pydevd.py", line 1658, in main
globals = debugger.run(setup['file'], None, None, is_module)
File "/opt/pycharm-professional/helpers/pydev/pydevd.py", line 1068, in run
pydev_imports.execfile(file, globals, locals) # execute the script
File "/opt/pycharm-professional/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "/home/swerner/development/projects/favicon/debug.py", line 3, in <module>
fav_icons = favicon.get('https://www.nytimes.com/')
File "/home/swerner/development/projects/favicon/src/favicon/favicon.py", line 69, in get
link_icons = tags(response.url, response.text)
File "/home/swerner/development/projects/favicon/src/favicon/favicon.py", line 125, in tags
if meta_type.lower() == name.lower():
AttributeError: 'NoneType' object has no attribute 'lower'
```
|
0.0
|
77632d6431d0c4b75a86f1b7476a612f5bb98f7a
|
[
"tests/test_favicon.py::test_default",
"tests/test_favicon.py::test_is_absolute[/favicon.ico-False]",
"tests/test_favicon.py::test_meta_content_attribute[og:image]",
"tests/test_favicon.py::test_link_sizes_attribute[64x64",
"tests/test_favicon.py::test_meta_content_attribute[msapplication-tileimage]",
"tests/test_favicon.py::test_link_rel_attribute[apple-touch-icon]",
"tests/test_favicon.py::test_link_sizes_attribute[any]",
"tests/test_favicon.py::test_meta_content_attribute[msapplication-TileImage]",
"tests/test_favicon.py::test_link_rel_attribute[ICON",
"tests/test_favicon.py::test_link_href_attribute[https]",
"tests/test_favicon.py::test_link_rel_attribute[icon]",
"tests/test_favicon.py::test_is_absolute[favicon.ico-False]",
"tests/test_favicon.py::test_link_sizes_attribute[16x16]",
"tests/test_favicon.py::test_link_rel_attribute[apple-touch-icon-precomposed]",
"tests/test_favicon.py::test_link_rel_attribute[shortcut",
"tests/test_favicon.py::test_link_sizes_attribute[24x24+]",
"tests/test_favicon.py::test_link_href_attribute[relative]",
"tests/test_favicon.py::test_link_href_attribute[query",
"tests/test_favicon.py::test_link_href_attribute[forward",
"tests/test_favicon.py::test_link_sizes_attribute[32x32",
"tests/test_favicon.py::test_invalid_meta_tag",
"tests/test_favicon.py::test_link_href_attribute[filename",
"tests/test_favicon.py::test_link_sizes_attribute[new",
"tests/test_favicon.py::test_link_href_attribute[filename]",
"tests/test_favicon.py::test_link_sizes_attribute[logo-128x128.png]",
"tests/test_favicon.py::test_is_absolute[http://mock.com/favicon.ico-True]"
] |
[] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-11-05 16:04:53+00:00
|
mit
| 5,388 |
|
scoutapp__scout_apm_python-147
|
diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md
index 7901ca5..501be10 100644
--- a/DEVELOPMENT.md
+++ b/DEVELOPMENT.md
@@ -89,7 +89,7 @@ for example 2.7 and 3.7. In that case, do the whole setup for each virtualenv.
Install all test dependencies:
- $ pip install bottle celery Django elasticsearch flask flask-sqlalchemy jinja2 mock psutil pymongo pyramid pytest pytest-travis-fold pytest-cov PyYAML redis requests sqlalchemy urllib3 webtest
+ $ pip install bottle celery Django elasticsearch flask flask-sqlalchemy jinja2 mock psutil pymongo pyramid pytest pytest-travis-fold pytest-cov redis requests sqlalchemy urllib3 webtest
Run tests with:
diff --git a/requirements.txt b/requirements.txt
index bc5d83f..75d1bd2 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -1,3 +1,2 @@
psutil
-PyYAML
requests
diff --git a/setup.py b/setup.py
index 790d135..143fa10 100644
--- a/setup.py
+++ b/setup.py
@@ -37,7 +37,7 @@ setup_args = {
"core-agent-manager = scout_apm.core.cli.core_agent_manager:main"
]
},
- "install_requires": ["psutil", "PyYAML", "requests"],
+ "install_requires": ["psutil", "requests"],
"keywords": "apm performance monitoring development",
"classifiers": [
"Development Status :: 5 - Production/Stable",
diff --git a/src/scout_apm/core/config.py b/src/scout_apm/core/config.py
index 56b60c7..9c6be33 100644
--- a/src/scout_apm/core/config.py
+++ b/src/scout_apm/core/config.py
@@ -6,6 +6,7 @@ import sys
from scout_apm.core.git_revision import GitRevision
from scout_apm.core.platform_detection import PlatformDetection
+from scout_apm.core.util import octal
logger = logging.getLogger(__name__)
@@ -58,6 +59,7 @@ class ScoutConfig(object):
"core_agent_dir",
"core_agent_download",
"core_agent_launch",
+ "core_agent_permissions",
"core_agent_version",
"disabled_instruments",
"download_url",
@@ -73,6 +75,17 @@ class ScoutConfig(object):
"socket_path",
]
+ def core_agent_permissions(self):
+ try:
+ return octal(self.value("core_agent_permissions"))
+ except ValueError as e:
+ logger.error(
+ "Invalid core_agent_permissions value: %s." " Using default: %s",
+ repr(e),
+ 0o700,
+ )
+ return 0o700
+
@classmethod
def set(cls, **kwargs):
"""
@@ -195,6 +208,7 @@ class ScoutConfigDefaults(object):
"core_agent_dir": "/tmp/scout_apm_core",
"core_agent_download": True,
"core_agent_launch": True,
+ "core_agent_permissions": 700,
"core_agent_version": "v1.1.8", # can be an exact tag name, or 'latest'
"disabled_instruments": [],
"download_url": "https://s3-us-west-1.amazonaws.com/scout-public-downloads/apm_core_agent/release", # noqa: E501
diff --git a/src/scout_apm/core/core_agent_manager.py b/src/scout_apm/core/core_agent_manager.py
index d40e7d7..eb096df 100644
--- a/src/scout_apm/core/core_agent_manager.py
+++ b/src/scout_apm/core/core_agent_manager.py
@@ -146,7 +146,9 @@ class CoreAgentDownloader(object):
def create_core_agent_dir(self):
try:
- os.makedirs(self.destination, 0o700)
+ os.makedirs(
+ self.destination, AgentContext.instance.config.core_agent_permissions()
+ )
except OSError:
pass
diff --git a/src/scout_apm/core/util.py b/src/scout_apm/core/util.py
new file mode 100644
index 0000000..f4d233b
--- /dev/null
+++ b/src/scout_apm/core/util.py
@@ -0,0 +1,8 @@
+from __future__ import absolute_import, division, print_function, unicode_literals
+
+
+# Takes an integer or a string containing an integer and returns
+# the octal value.
+# Raises a ValueError if the value cannot be converted to octal.
+def octal(value):
+ return int("{}".format(value), 8)
diff --git a/tox.ini b/tox.ini
index 76eaf53..6e54753 100644
--- a/tox.ini
+++ b/tox.ini
@@ -42,7 +42,6 @@ deps =
pytest
pytest-travis-fold
pytest-cov
- PyYAML
redis
requests
sqlalchemy
|
scoutapp/scout_apm_python
|
db11c2b2a548e18b726f41da41cfbf79a437685f
|
diff --git a/tests/unit/core/test_config.py b/tests/unit/core/test_config.py
index c8ebfca..ed0535d 100644
--- a/tests/unit/core/test_config.py
+++ b/tests/unit/core/test_config.py
@@ -76,6 +76,29 @@ def test_log_config():
ScoutConfig.reset_all()
+def test_core_agent_permissions_default():
+ config = ScoutConfig()
+ assert 0o700 == config.core_agent_permissions()
+
+
+def test_core_agent_permissions_custom():
+ ScoutConfig.set(core_agent_permissions=770)
+ config = ScoutConfig()
+ try:
+ assert 0o770 == config.core_agent_permissions()
+ finally:
+ ScoutConfig.reset_all()
+
+
+def test_core_agent_permissions_invalid_uses_default():
+ ScoutConfig.set(core_agent_permissions="THIS IS INVALID")
+ config = ScoutConfig()
+ try:
+ assert 0o700 == config.core_agent_permissions()
+ finally:
+ ScoutConfig.reset_all()
+
+
def test_null_config_name():
# For coverage... this is never called elsewhere.
ScoutConfigNull().name()
diff --git a/tests/unit/core/test_util.py b/tests/unit/core/test_util.py
new file mode 100644
index 0000000..42e6f7a
--- /dev/null
+++ b/tests/unit/core/test_util.py
@@ -0,0 +1,18 @@
+from __future__ import absolute_import, division, print_function, unicode_literals
+
+from scout_apm.core.util import octal
+
+
+def test_octal_with_valid_integer():
+ assert 0o700 == octal(700)
+
+
+def test_octal_with_valid_string():
+ assert 0o700 == octal("700")
+
+
+def test_octal_raises_valueerror_on_invalid_value():
+ try:
+ octal("THIS IS INVALID")
+ except ValueError:
+ pass
|
set /tmp/scout_apm_core directory perms from config
Right now, directory permissions are set with:
https://github.com/scoutapp/scout_apm_python/blob/cab4f2218cfada275a45c355269e61a8945fa581/src/scout_apm/core/core_agent_manager.py#L144
Which obviously results in `700` perms on `/tmp/scout_apm_core/*`.
In my setup, this ends up requiring `root` to clear these files. If I could set the perms to `770` from a configuration option, it would make it a lot easier to clear these files out.
|
0.0
|
db11c2b2a548e18b726f41da41cfbf79a437685f
|
[
"tests/unit/core/test_config.py::test_get_config_value_from_env",
"tests/unit/core/test_config.py::test_get_config_value_from_python",
"tests/unit/core/test_config.py::test_get_derived_config_value",
"tests/unit/core/test_config.py::test_get_default_config_value",
"tests/unit/core/test_config.py::test_get_undefined_config_value",
"tests/unit/core/test_config.py::test_env_outranks_python",
"tests/unit/core/test_config.py::test_log_config",
"tests/unit/core/test_config.py::test_core_agent_permissions_default",
"tests/unit/core/test_config.py::test_core_agent_permissions_custom",
"tests/unit/core/test_config.py::test_core_agent_permissions_invalid_uses_default",
"tests/unit/core/test_config.py::test_null_config_name",
"tests/unit/core/test_config.py::test_boolean_conversion_from_env",
"tests/unit/core/test_config.py::test_boolean_conversion_from_python[True-True0]",
"tests/unit/core/test_config.py::test_boolean_conversion_from_python[Yes-True]",
"tests/unit/core/test_config.py::test_boolean_conversion_from_python[1-True]",
"tests/unit/core/test_config.py::test_boolean_conversion_from_python[True-True1]",
"tests/unit/core/test_config.py::test_boolean_conversion_from_python[False-False0]",
"tests/unit/core/test_config.py::test_boolean_conversion_from_python[No-False]",
"tests/unit/core/test_config.py::test_boolean_conversion_from_python[0-False]",
"tests/unit/core/test_config.py::test_boolean_conversion_from_python[False-False1]",
"tests/unit/core/test_config.py::test_boolean_conversion_from_python[original8-False]",
"tests/unit/core/test_config.py::test_list_conversion_from_env",
"tests/unit/core/test_config.py::test_list_conversion_from_python[pymongo,",
"tests/unit/core/test_config.py::test_list_conversion_from_python[original1-converted1]",
"tests/unit/core/test_config.py::test_list_conversion_from_python[original2-converted2]",
"tests/unit/core/test_config.py::test_list_conversion_from_python[-converted3]",
"tests/unit/core/test_config.py::test_list_conversion_from_python[original4-converted4]",
"tests/unit/core/test_util.py::test_octal_with_valid_integer",
"tests/unit/core/test_util.py::test_octal_with_valid_string",
"tests/unit/core/test_util.py::test_octal_raises_valueerror_on_invalid_value"
] |
[] |
{
"failed_lite_validators": [
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-01-07 19:05:00+00:00
|
mit
| 5,389 |
|
scrapinghub__number-parser-60
|
diff --git a/README.rst b/README.rst
index b18ce13..1f1f62e 100644
--- a/README.rst
+++ b/README.rst
@@ -20,10 +20,10 @@ number-parser requires Python 3.6+.
Usage
=====
-The library provides three major APIs which corresponds to the following common usages.
+The library provides the following common usages.
-Interface #1: Multiple numbers
-------------------------------
+Converting numbers in-place
+---------------------------
Identifying the numbers in a text string, converting them to corresponding numeric values while ignoring non-numeric words.
This also supports ordinal number conversion (for English only).
@@ -36,9 +36,9 @@ This also supports ordinal number conversion (for English only).
>>> parse("First day of year two thousand")
'1 day of year 2000'
+Parsing a number
+----------------
-Interface #2: Single number
---------------------------------
Converting a single number written in words to it's corresponding integer.
>>> from number_parser import parse_number
@@ -46,11 +46,10 @@ Converting a single number written in words to it's corresponding integer.
2020
>>> parse_number("not_a_number")
+Parsing an ordinal
+------------------
-Interface #3: Single number Ordinal
--------------------------------------
-
-Converting a single ordinal number written in words to it's corresponding integer. (Support for only English)
+Converting a single ordinal number written in words to its corresponding integer. (Support for English only)
>>> from number_parser import parse_ordinal
>>> parse_ordinal("twenty third")
@@ -58,6 +57,19 @@ Converting a single ordinal number written in words to it's corresponding intege
>>> parse_ordinal("seventy fifth")
75
+Parsing a fraction
+------------------
+
+Converting a fractional number written in words to its corresponding integral fraction. (Support for English only)
+
+>>> from number_parser import parse_fraction
+>>> parse_fraction("forty two divided by five hundred and six")
+'42/506'
+>>> parse_fraction("one over two")
+'1/2'
+>>> parse_fraction("forty two / one million")
+'42/1000000'
+
Language Support
----------------
diff --git a/number_parser/__init__.py b/number_parser/__init__.py
index 8efbc8a..472179e 100644
--- a/number_parser/__init__.py
+++ b/number_parser/__init__.py
@@ -1,1 +1,1 @@
-from number_parser.parser import parse, parse_number, parse_ordinal
+from number_parser.parser import parse, parse_number, parse_ordinal, parse_fraction
diff --git a/number_parser/parser.py b/number_parser/parser.py
index 2afbf3a..e0d67c2 100644
--- a/number_parser/parser.py
+++ b/number_parser/parser.py
@@ -268,6 +268,36 @@ def parse_number(input_string, language=None):
return None
+def parse_fraction(input_string, language=None):
+ """Converts a single number written in fraction to a numeric type"""
+ if not input_string.strip():
+ return None
+
+ if language is None:
+ language = _valid_tokens_by_language(input_string)
+
+ FRACTION_SEPARATORS = ["divided by", "over", "by", "/"]
+
+ for separator in FRACTION_SEPARATORS:
+ position_of_separator = input_string.find(separator)
+
+ if position_of_separator == -1:
+ continue
+
+ string_before_separator = input_string[:position_of_separator]
+ string_after_separator = input_string[position_of_separator + len(separator):]
+
+ number_before_separator = parse_number(string_before_separator, language)
+ number_after_separator = parse_number(string_after_separator, language)
+
+ if number_before_separator is None or number_after_separator is None:
+ return None
+
+ return f'{number_before_separator}/{number_after_separator}'
+
+ return None
+
+
def parse(input_string, language=None):
"""
Converts all the numbers in a sentence written in natural language to their numeric type while keeping
|
scrapinghub/number-parser
|
18aa8531af4a89567f3d10e9aea0975c6a2a599c
|
diff --git a/tests/test_number_parsing.py b/tests/test_number_parsing.py
index 216bfd6..2de6d09 100644
--- a/tests/test_number_parsing.py
+++ b/tests/test_number_parsing.py
@@ -1,5 +1,5 @@
import pytest
-from number_parser import parse, parse_number
+from number_parser import parse, parse_number, parse_fraction
from number_parser.parser import LanguageData, parse_ordinal
@@ -121,6 +121,33 @@ def test_parse_sentences_ordinal(expected, test_input, lang):
assert parse(test_input, lang) == expected
+
[email protected](
+ "test_input,expected,lang",
+ [
+ # empty / not-a-number
+ ('', None, None),
+ ('example of sentence', None, None),
+ # numeric
+ ('32', None, None),
+ (' 3 ', None, None),
+ # en
+ ('eleven', None, 'en'),
+ ('one hundred and forty two by a sentence', None, 'en'),
+ ('sentence / eleven', None, 'en'),
+ ('one hundred and forty two by eleven', '142/11', 'en'),
+ ('one hundred and forty two divided by eleven', '142/11', 'en'),
+ ('one hundred and forty two / eleven', '142/11', 'en'),
+ ('one hundred and forty two over eleven', '142/11', 'en'),
+ ('two million three thousand and nineteen/two thousand and nineteen', '2003019/2019', 'en'),
+ ('billion over nineteen billion and nineteen', '1000000000/19000000019', 'en'),
+
+ ]
+)
+def test_parse_fraction(expected, test_input, lang):
+ assert parse_fraction(test_input, language=lang) == expected
+
+
def test_LanguageData_unsupported_language():
with pytest.raises(ValueError):
LanguageData('xxxx')
|
Support for simple fractions
We can add support for the simple fractions as well like three-fourth, half, etc.
Example:
> parse("I have a three-fourth cup of glass.")
I have a 3/4 cup of glass.
> parse_number("half")
1/2
|
0.0
|
18aa8531af4a89567f3d10e9aea0975c6a2a599c
|
[
"tests/test_number_parsing.py::test_parse_number[-None-None]",
"tests/test_number_parsing.py::test_parse_number[example",
"tests/test_number_parsing.py::test_parse_number[32-32-None]",
"tests/test_number_parsing.py::test_parse_number[",
"tests/test_number_parsing.py::test_parse_number[eleven-11-en]",
"tests/test_number_parsing.py::test_parse_number[one",
"tests/test_number_parsing.py::test_parse_number[two",
"tests/test_number_parsing.py::test_parse_number[billion-1000000000-en]",
"tests/test_number_parsing.py::test_parse_number[nineteen",
"tests/test_number_parsing.py::test_parse_number[\\u091b\\u0939",
"tests/test_number_parsing.py::test_parse_number[\\u090f\\u0915",
"tests/test_number_parsing.py::test_parse_number[\\u091a\\u094c\\u0926\\u0939",
"tests/test_number_parsing.py::test_parse_number[\\u043f\\u044f\\u0442\\u044c\\u0441\\u043e\\u0442",
"tests/test_number_parsing.py::test_parse_number[\\u043f\\u044f\\u0442\\u044c\\u044e\\u0441\\u0442\\u0430\\u043c\\u0438",
"tests/test_number_parsing.py::test_parse_number[\\u043f\\u044f\\u0442\\u0438\\u0441\\u0442\\u0430\\u0445",
"tests/test_number_parsing.py::test_parse_number[\\u0442\\u044b\\u0441\\u044f\\u0447\\u0435-1000-ru]",
"tests/test_number_parsing.py::test_parse_number[Dos",
"tests/test_number_parsing.py::test_parse_number[tres",
"tests/test_number_parsing.py::test_parse_basic_sentences[twenty-five",
"tests/test_number_parsing.py::test_parse_basic_sentences[I",
"tests/test_number_parsing.py::test_parse_basic_sentences[thirty",
"tests/test_number_parsing.py::test_parse_basic_sentences[the",
"tests/test_number_parsing.py::test_parse_basic_sentences[dos",
"tests/test_number_parsing.py::test_parse_basic_sentences[doscientos",
"tests/test_number_parsing.py::test_parse_case_of_string[OnE",
"tests/test_number_parsing.py::test_parse_case_of_string[SeVentY",
"tests/test_number_parsing.py::test_parse_case_of_string[Twelve",
"tests/test_number_parsing.py::test_parse_ordinal[eleventh-11-en]",
"tests/test_number_parsing.py::test_parse_ordinal[nineteenth-19-en]",
"tests/test_number_parsing.py::test_parse_ordinal[hundredth-100-en]",
"tests/test_number_parsing.py::test_parse_ordinal[one",
"tests/test_number_parsing.py::test_parse_ordinal[thousandth-1000-en]",
"tests/test_number_parsing.py::test_parse_ordinal[two",
"tests/test_number_parsing.py::test_parse_ordinal[millionth-1000000-en]",
"tests/test_number_parsing.py::test_parse_ordinal[billionth-1000000000-en]",
"tests/test_number_parsing.py::test_parse_ordinal[with",
"tests/test_number_parsing.py::test_parse_ordinal[th",
"tests/test_number_parsing.py::test_parse_ordinal[fifth",
"tests/test_number_parsing.py::test_parse_ordinal[fiftieth",
"tests/test_number_parsing.py::test_parse_ordinal[fifty",
"tests/test_number_parsing.py::test_parse_sentences_ordinal[eleventh",
"tests/test_number_parsing.py::test_parse_sentences_ordinal[nineteenth",
"tests/test_number_parsing.py::test_parse_sentences_ordinal[hundredth",
"tests/test_number_parsing.py::test_parse_sentences_ordinal[one",
"tests/test_number_parsing.py::test_parse_sentences_ordinal[five",
"tests/test_number_parsing.py::test_parse_sentences_ordinal[thirty",
"tests/test_number_parsing.py::test_parse_sentences_ordinal[eighth",
"tests/test_number_parsing.py::test_parse_sentences_ordinal[He",
"tests/test_number_parsing.py::test_parse_sentences_ordinal[twentieth",
"tests/test_number_parsing.py::test_parse_fraction[-None-None]",
"tests/test_number_parsing.py::test_parse_fraction[example",
"tests/test_number_parsing.py::test_parse_fraction[32-None-None]",
"tests/test_number_parsing.py::test_parse_fraction[",
"tests/test_number_parsing.py::test_parse_fraction[eleven-None-en]",
"tests/test_number_parsing.py::test_parse_fraction[one",
"tests/test_number_parsing.py::test_parse_fraction[sentence",
"tests/test_number_parsing.py::test_parse_fraction[two",
"tests/test_number_parsing.py::test_parse_fraction[billion",
"tests/test_number_parsing.py::test_LanguageData_unsupported_language"
] |
[] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-02-25 04:47:06+00:00
|
bsd-3-clause
| 5,390 |
|
scrapinghub__number-parser-79
|
diff --git a/README.rst b/README.rst
index 1f1f62e..169db0a 100644
--- a/README.rst
+++ b/README.rst
@@ -7,7 +7,7 @@ number-parser
``number-parser`` is a simple library that allows you to convert numbers written in the natural
language to it's equivalent numeric forms. It currently supports cardinal numbers in the following
-languages - English, Hindi, Spanish and Russian and ordinal numbers in English.
+languages - English, Hindi, Spanish, Ukrainian and Russian and ordinal numbers in English.
Installation
============
@@ -76,7 +76,7 @@ Language Support
The default language is English, you can pass the language parameter with corresponding locale for other languages.
It currently supports cardinal numbers in the following
-languages - English, Hindi, Spanish and Russian and ordinal numbers in English.
+languages - English, Hindi, Spanish, Ukrainian and Russian and ordinal numbers in English.
>>> from number_parser import parse, parse_number
>>> parse("Hay tres gallinas y veintitrés patos", language='es')
diff --git a/number_parser/data/uk.py b/number_parser/data/uk.py
index 22be0c8..7198298 100644
--- a/number_parser/data/uk.py
+++ b/number_parser/data/uk.py
@@ -1,18 +1,53 @@
info = {
"UNIT_NUMBERS": {
"нуль": 0,
+ "нулю": 0,
"один": 1,
"одна": 1,
"одне": 1,
+ "одним": 1,
+ "одними": 1,
+ "одного": 1,
+ "одному": 1,
+ "одну": 1,
+ "одні": 1,
+ "одній": 1,
"два": 2,
+ "двом": 2,
+ "двома": 2,
+ "двох": 2,
+ "двоє": 2,
+ "двум": 2,
"дві": 2,
"три": 3,
+ "троє": 3,
+ "трьом": 3,
+ "трьома": 3,
+ "трьох": 3,
+ "четверо": 4,
"чотири": 4,
+ "чотирьом": 4,
+ "чотирьома": 4,
+ "чотирьох": 4,
+ "пʼятеро": 5,
+ "пʼяти": 5,
+ "пʼятих": 5,
"пʼять": 5,
+ "пʼятьма": 5,
+ "пять": 5,
+ "шести": 6,
"шість": 6,
+ "шістьма": 6,
+ "семи": 7,
"сім": 7,
+ "сімма": 7,
+ "восьми": 8,
+ "восьмима": 8,
"вісім": 8,
- "девʼять": 9
+ "девʼяти": 9,
+ "девʼять": 9,
+ "девʼятьма": 9,
+ "девять": 9
},
"DIRECT_NUMBERS": {
"десять": 10,
@@ -21,29 +56,36 @@ info = {
"тринадцять": 13,
"чотирнадцять": 14,
"пʼятнадцять": 15,
+ "пятнадцять": 15,
"шістнадцять": 16,
"сімнадцять": 17,
"вісімнадцять": 18,
- "девʼятнадцять": 19
+ "девʼятнадцять": 19,
+ "девятнадцять": 19
},
"TENS": {
"двадцять": 20,
"тридцять": 30,
"сорок": 40,
"пʼятдесят": 50,
+ "пятдесят": 50,
"шістдесят": 60,
"сімдесят": 70,
"вісімдесят": 80,
- "девʼяносто": 90
+ "девʼяносто": 90,
+ "девяносто": 90
},
"HUNDREDS": {
+ "сто": 100,
"двісті": 200,
"триста": 300,
"чотириста": 400,
+ "п'ятсот": 500,
"пʼятсот": 500,
"шістсот": 600,
"сімсот": 700,
"вісімсот": 800,
+ "дев'ятсот": 900,
"девʼятсот": 900
},
"BIG_POWERS_OF_TEN": {
@@ -53,15 +95,79 @@ info = {
"мільйон": 1000000,
"мільйони": 1000000,
"мільйонів": 1000000,
+ "міліон": 1000000,
"мільярд": 1000000000,
"мільярди": 1000000000,
"мільярдів": 1000000000,
+ "міліярд": 1000000000,
"більйон": 1000000000000,
"більйони": 1000000000000,
"більйонів": 1000000000000,
+ "трильйон": 1000000000000,
+ "триліон": 1000000000000,
"більярд": 1000000000000000,
"більярди": 1000000000000000,
- "більярдів": 1000000000000000
+ "більярдів": 1000000000000000,
+ "квадрильйон": 1000000000000000,
+ "квадриліон": 1000000000000000,
+ "квінтильйон": 1000000000000000000,
+ "квінтиліон": 1000000000000000000,
+ "секстильйон": 1000000000000000000000,
+ "секстиліон": 1000000000000000000000,
+ "септильйон": 1000000000000000000000000,
+ "септиліон": 1000000000000000000000000,
+ "октильйон": 1000000000000000000000000000,
+ "октиліон": 1000000000000000000000000000,
+ "нонильйон": 1000000000000000000000000000000,
+ "нонільйон": 1000000000000000000000000000000,
+ "ноніліон": 1000000000000000000000000000000,
+ "децильйон": 1000000000000000000000000000000000,
+ "дециліон": 1000000000000000000000000000000000,
+ "децільйон": 1000000000000000000000000000000000,
+ "ундецильйон": 1000000000000000000000000000000000000,
+ "ундециліон": 1000000000000000000000000000000000000,
+ "ундецільйон": 1000000000000000000000000000000000000,
+ "дуодецильйон": 1000000000000000000000000000000000000000,
+ "дуодециліон": 1000000000000000000000000000000000000000,
+ "дуодецільйон": 1000000000000000000000000000000000000000,
+ "тредецильйон": 1000000000000000000000000000000000000000000,
+ "тредециліон": 1000000000000000000000000000000000000000000,
+ "тредецільйон": 1000000000000000000000000000000000000000000,
+ "кваттуордецильйон": 1000000000000000000000000000000000000000000000,
+ "кваттуордециліон": 1000000000000000000000000000000000000000000000,
+ "квіндецильйон": 1000000000000000000000000000000000000000000000000,
+ "квіндециліон": 1000000000000000000000000000000000000000000000000,
+ "сексдецильйон": 1000000000000000000000000000000000000000000000000000,
+ "сексдециліон": 1000000000000000000000000000000000000000000000000000,
+ "септендецильйон": 1000000000000000000000000000000000000000000000000000000,
+ "септендециліон": 1000000000000000000000000000000000000000000000000000000,
+ "октодецильйон": 1000000000000000000000000000000000000000000000000000000000,
+ "октодециліон": 1000000000000000000000000000000000000000000000000000000000,
+ "новемдецильйон": 1000000000000000000000000000000000000000000000000000000000000,
+ "новемдециліон": 1000000000000000000000000000000000000000000000000000000000000,
+ "вігінтільйон": 1000000000000000000000000000000000000000000000000000000000000000,
+ "унвігінтільйон": 1000000000000000000000000000000000000000000000000000000000000000000,
+ "дуовігінтільйон": 1000000000000000000000000000000000000000000000000000000000000000000000,
+ "тревігінтільйон": 1000000000000000000000000000000000000000000000000000000000000000000000000,
+ "кваттуорвігінтільйон": 1000000000000000000000000000000000000000000000000000000000000000000000000000,
+ "квінвігінтільйон": 1000000000000000000000000000000000000000000000000000000000000000000000000000000,
+ "сексвігінтільйон": 1000000000000000000000000000000000000000000000000000000000000000000000000000000000,
+ "септемвігінтільйон": 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000,
+ "октовігінтільйон": 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,
+ "новемвігінтільйон": 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,
+ "тригінтільйон": 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,
+ "унтригінтільйон": 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,
+ "дуотригінтільйон": 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,
+ "третригінтільйон": 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,
+ "кваттуортригінтільйон": 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,
+ "квінтригінтільйон": 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,
+ "секстригінтільйон": 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,
+ "септентригінтільйон": 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,
+ "октотригінтільйон": 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,
+ "новемтригінтільйон": 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,
+ "квадрагінтільйон": 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,
+ "унквадрагінтільйон": 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,
+ "дуоквадрагінтільйон": 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
},
"SKIP_TOKENS": [],
"USE_LONG_SCALE": False
diff --git a/number_parser/parser.py b/number_parser/parser.py
index e0d67c2..9bb65a5 100644
--- a/number_parser/parser.py
+++ b/number_parser/parser.py
@@ -2,7 +2,7 @@ import re
from importlib import import_module
import unicodedata
SENTENCE_SEPARATORS = [".", ","]
-SUPPORTED_LANGUAGES = ['en', 'es', 'hi', 'ru']
+SUPPORTED_LANGUAGES = ['en', 'es', 'hi', 'ru', 'uk']
RE_BUG_LANGUAGES = ['hi']
diff --git a/number_parser_data/supplementary_translation_data/uk.json b/number_parser_data/supplementary_translation_data/uk.json
index ff8bd15..23eb0e3 100644
--- a/number_parser_data/supplementary_translation_data/uk.json
+++ b/number_parser_data/supplementary_translation_data/uk.json
@@ -1,9 +1,160 @@
{
- "UNIT_NUMBERS": {},
- "DIRECT_NUMBERS": {},
- "TENS": {},
- "HUNDREDS": {},
- "BIG_POWERS_OF_TEN": {},
+ "UNIT_NUMBERS": {
+ "нуль": 0,
+ "нулю": 0,
+ "один": 1,
+ "одному": 1,
+ "одним": 1,
+ "одними": 1,
+ "одну": 1,
+ "одного": 1,
+ "одне": 1,
+ "одні": 1,
+ "одна": 1,
+ "одній": 1,
+ "два": 2,
+ "двом": 2,
+ "двох": 2,
+ "двома": 2,
+ "дві": 2,
+ "двоє": 2,
+ "двум": 2,
+ "три": 3,
+ "трьом": 3,
+ "трьох": 3,
+ "троє": 3,
+ "трьома": 3,
+ "чотири": 4,
+ "четверо": 4,
+ "чотирьом": 4,
+ "чотирьох": 4,
+ "чотирьома": 4,
+ "пять": 5,
+ "пʼять": 5,
+ "пʼятеро": 5,
+ "пʼяти": 5,
+ "пʼятих": 5,
+ "пʼятьма": 5,
+ "шість": 6,
+ "шести": 6,
+ "шістьма": 6,
+ "сім": 7,
+ "семи": 7,
+ "сімма": 7,
+ "вісім": 8,
+ "восьми": 8,
+ "восьмима": 8,
+ "девʼять": 9,
+ "девять": 9,
+ "девʼяти": 9,
+ "девʼятьма": 9
+ },
+ "DIRECT_NUMBERS": {
+ "десять": 10,
+ "одинадцять": 11,
+ "дванадцять": 12,
+ "тринадцять": 13,
+ "чотирнадцять": 14,
+ "пʼятнадцять": 15,
+ "пятнадцять": 15,
+ "шістнадцять": 16,
+ "сімнадцять": 17,
+ "вісімнадцять": 18,
+ "девʼятнадцять": 19,
+ "девятнадцять": 19
+ },
+ "TENS": {
+ "двадцять": 20,
+ "тридцять": 30,
+ "сорок": 40,
+ "пʼятдесят": 50,
+ "пятдесят": 50,
+ "шістдесят": 60,
+ "сімдесят": 70,
+ "вісімдесят": 80,
+ "девʼяносто": 90,
+ "девяносто": 90
+ },
+ "HUNDREDS": {
+ "сто": 100,
+ "двісті": 200,
+ "триста": 300,
+ "чотириста": 400,
+ "п'ятсот": 500,
+ "шістсот": 600,
+ "сімсот": 700,
+ "вісімсот": 800,
+ "дев'ятсот": 900
+ },
+ "BIG_POWERS_OF_TEN": {
+ "тисяча": 1000,
+ "мільйон": 1000000,
+ "міліон": 1000000,
+ "мільярд": 1000000000,
+ "міліярд": 1000000000,
+ "трильйон": 1000000000000,
+ "триліон": 1000000000000,
+ "квадрильйон": 1000000000000000,
+ "квадриліон": 1000000000000000,
+ "квінтильйон": 1000000000000000000,
+ "квінтиліон": 1000000000000000000,
+ "секстильйон": 1000000000000000000000,
+ "секстиліон": 1000000000000000000000,
+ "септильйон": 1000000000000000000000000,
+ "септиліон": 1000000000000000000000000,
+ "октильйон": 1000000000000000000000000000,
+ "октиліон": 1000000000000000000000000000,
+ "нонільйон": 1000000000000000000000000000000,
+ "нонильйон": 1000000000000000000000000000000,
+ "ноніліон": 1000000000000000000000000000000,
+ "децильйон": 1000000000000000000000000000000000,
+ "децільйон": 1000000000000000000000000000000000,
+ "дециліон": 1000000000000000000000000000000000,
+ "ундецільйон": 1000000000000000000000000000000000000,
+ "ундецильйон": 1000000000000000000000000000000000000,
+ "ундециліон": 1000000000000000000000000000000000000,
+ "дуодецильйон": 1000000000000000000000000000000000000000,
+ "дуодецільйон": 1000000000000000000000000000000000000000,
+ "дуодециліон": 1000000000000000000000000000000000000000,
+ "тредецильйон": 1000000000000000000000000000000000000000000,
+ "тредециліон": 1000000000000000000000000000000000000000000,
+ "тредецільйон": 1000000000000000000000000000000000000000000,
+ "кваттуордецильйон": 1000000000000000000000000000000000000000000000,
+ "кваттуордециліон": 1000000000000000000000000000000000000000000000,
+ "квіндецильйон": 1000000000000000000000000000000000000000000000000,
+ "квіндециліон": 1000000000000000000000000000000000000000000000000,
+ "сексдецильйон": 1000000000000000000000000000000000000000000000000000,
+ "сексдециліон": 1000000000000000000000000000000000000000000000000000,
+ "септендецильйон": 1000000000000000000000000000000000000000000000000000000,
+ "септендециліон": 1000000000000000000000000000000000000000000000000000000,
+ "октодецильйон": 1000000000000000000000000000000000000000000000000000000000,
+ "октодециліон": 1000000000000000000000000000000000000000000000000000000000,
+ "новемдецильйон": 1000000000000000000000000000000000000000000000000000000000000,
+ "новемдециліон": 1000000000000000000000000000000000000000000000000000000000000,
+ "вігінтільйон": 1000000000000000000000000000000000000000000000000000000000000000,
+ "унвігінтільйон": 1000000000000000000000000000000000000000000000000000000000000000000,
+ "дуовігінтільйон": 1000000000000000000000000000000000000000000000000000000000000000000000,
+ "тревігінтільйон": 1000000000000000000000000000000000000000000000000000000000000000000000000,
+ "кваттуорвігінтільйон": 1000000000000000000000000000000000000000000000000000000000000000000000000000,
+ "квінвігінтільйон": 1000000000000000000000000000000000000000000000000000000000000000000000000000000,
+ "сексвігінтільйон": 1000000000000000000000000000000000000000000000000000000000000000000000000000000000,
+ "септемвігінтільйон": 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000,
+ "октовігінтільйон": 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,
+ "новемвігінтільйон": 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,
+ "тригінтільйон": 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,
+ "унтригінтільйон": 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,
+ "дуотригінтільйон": 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,
+ "третригінтільйон": 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,
+ "кваттуортригінтільйон": 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,
+ "квінтригінтільйон": 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,
+ "секстригінтільйон": 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,
+ "септентригінтільйон": 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,
+ "октотригінтільйон": 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,
+ "новемтригінтільйон": 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,
+ "квадрагінтільйон": 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,
+ "унквадрагінтільйон": 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,
+ "дуоквадрагінтільйон": 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
+ },
"SKIP_TOKENS": [],
"USE_LONG_SCALE": false
}
\ No newline at end of file
|
scrapinghub/number-parser
|
8367865ed29a9b221809aed0aa40963361709c0d
|
diff --git a/tests/test_language_uk.py b/tests/test_language_uk.py
new file mode 100644
index 0000000..74ae589
--- /dev/null
+++ b/tests/test_language_uk.py
@@ -0,0 +1,121 @@
+import pytest
+from number_parser import parse_number
+from tests import HUNDREDS_DIRECTORY, PERMUTATION_DIRECTORY
+from tests import _test_files
+
+LANG = 'uk'
+
+
[email protected](
+ "test_input,expected",
+ [
+ ("нуль", 0),
+ ("нулю", 0),
+ ("один", 1),
+ ("одному", 1),
+ ("одним", 1),
+ ("одне", 1),
+ ("одна", 1),
+ ("одні", 1),
+ ("два", 2),
+ ("двох", 2),
+ ("двум", 2),
+ ("двоє", 2),
+ ("три", 3),
+ ("трьох", 3),
+ ("троє", 3),
+ ("чотири", 4),
+ ("четверо", 4),
+ ("пʼять", 5),
+ ("пʼяти", 5),
+ ("пʼятеро", 5),
+ ("шість", 6),
+ ("сім", 7),
+ ("вісім", 8),
+ ("девʼять", 9),
+ ("десять", 10),
+ ("одинадцять", 11),
+ ("дванадцять", 12),
+ ("тринадцять", 13),
+ ("чотирнадцять", 14),
+ ("пʼятнадцять", 15),
+ ("шістнадцять", 16),
+ ("сімнадцять", 17),
+ ("вісімнадцять", 18),
+ ("девʼятнадцять", 19),
+ ("двадцять", 20),
+ ("тридцять", 30),
+ ("сорок", 40),
+ ("пʼятдесят", 50),
+ ("шістдесят", 60),
+ ("сімдесят", 70),
+ ("вісімдесят", 80),
+ ("девʼяносто", 90),
+ ("сто", 100),
+ ("двісті", 200),
+ ("триста", 300),
+ ("чотириста", 400),
+ ("пʼятсот", 500),
+ ("шістсот", 600),
+ ("сімсот", 700),
+ ("вісімсот", 800),
+ ("девʼятсот", 900),
+ ("одна тисяча", 1000),
+ ("одна тисяча один", 1001),
+ ("одна тисяча два", 1002),
+ ("одна тисяча три", 1003),
+ ("одна тисяча чотири", 1004),
+ ("одна тисяча пʼять", 1005),
+ ("одна тисяча шість", 1006),
+ ("одна тисяча сім", 1007),
+ ("одна тисяча вісім", 1008),
+ ("одна тисяча девʼять", 1009),
+ ("одна тисяча десять", 1010),
+ ("десять тисяч", 10000),
+ ("сто тисяч", 100000),
+ ("мільйон", 1_000_000),
+ ("міліон", 1_000_000),
+ ("один мільйон", 1000000),
+ ("один мільйон один", 1000001),
+ ("один мільйон два", 1000002),
+ ("один мільйон три", 1000003),
+ ("один мільйон чотири", 1000004),
+ ("один мільйон пʼять", 1000005),
+ ("десять мільйонів", 10000000),
+ ("сто мільйонів", 100000000),
+ ("мільярд", 1_000_000_000),
+ ("один мільярд", 1000000000),
+ ("один мільярд один", 1000000001),
+ ("один мільярд два", 1000000002),
+ ("один мільярд три", 1000000003),
+ ("один мільярд чотири", 1000000004),
+ ("один мільярд пʼять", 1000000005),
+ ("десять мільярдів", 10000000000),
+ ("сто мільярдів", 100000000000),
+ ("трильйон", 1_000_000_000_000),
+ ("один трильйон", 1000000000000),
+ ("один трильйон один", 1000000000001),
+ ("квадрильйон", 1_000_000_000_000_000),
+ ("один квадрильйон", 1000000000000000),
+ ("один квадрильйон один", 1000000000000001),
+ ("квінтильйон", 1_000_000_000_000_000_000),
+ ("секстильйон", 1_000_000_000_000_000_000_000),
+ ("септильйон", 1_000_000_000_000_000_000_000_000),
+ ("октильйон", 1_000_000_000_000_000_000_000_000_000),
+ ("нонільйон", 1_000_000_000_000_000_000_000_000_000_000),
+ ("децільйон", 1_000_000_000_000_000_000_000_000_000_000_000),
+ ("ундецільйон", 1_000_000_000_000_000_000_000_000_000_000_000_000),
+ ("дуодецільйон", 1_000_000_000_000_000_000_000_000_000_000_000_000_000),
+ ("тредецільйон", 1_000_000_000_000_000_000_000_000_000_000_000_000_000_000),
+ ]
+)
+def test_parse_number(expected, test_input):
+ assert parse_number(test_input, LANG) == expected
+
+
+def test_parse_number_till_hundred():
+ _test_files(HUNDREDS_DIRECTORY, LANG)
+
+
+def test_parse_number_permutations():
+ _test_files(PERMUTATION_DIRECTORY, LANG)
|
Doesn't recognize a million in Ukrainian
```
In [11]: parse_number("мільйон") is None
Out[11]: True
In [12]: parse_number("міліон") is None
Out[12]: True
```
http://sum.in.ua/s/miljjon
These are two versions of the writing of the word million in the Ukrainian language.
Is it a problem that Ukrainian is not in supported languages? https://github.com/scrapinghub/number-parser/blob/master/number_parser/parser.py#L5
But I see Ukrainian here https://github.com/scrapinghub/number-parser/blob/master/number_parser/data/uk.py#L53
Thank you.
|
0.0
|
8367865ed29a9b221809aed0aa40963361709c0d
|
[
"tests/test_language_uk.py::test_parse_number[\\u043d\\u0443\\u043b\\u044c-0]",
"tests/test_language_uk.py::test_parse_number[\\u043d\\u0443\\u043b\\u044e-0]",
"tests/test_language_uk.py::test_parse_number[\\u043e\\u0434\\u0438\\u043d-1]",
"tests/test_language_uk.py::test_parse_number[\\u043e\\u0434\\u043d\\u043e\\u043c\\u0443-1]",
"tests/test_language_uk.py::test_parse_number[\\u043e\\u0434\\u043d\\u0438\\u043c-1]",
"tests/test_language_uk.py::test_parse_number[\\u043e\\u0434\\u043d\\u0435-1]",
"tests/test_language_uk.py::test_parse_number[\\u043e\\u0434\\u043d\\u0430-1]",
"tests/test_language_uk.py::test_parse_number[\\u043e\\u0434\\u043d\\u0456-1]",
"tests/test_language_uk.py::test_parse_number[\\u0434\\u0432\\u0430-2]",
"tests/test_language_uk.py::test_parse_number[\\u0434\\u0432\\u043e\\u0445-2]",
"tests/test_language_uk.py::test_parse_number[\\u0434\\u0432\\u0443\\u043c-2]",
"tests/test_language_uk.py::test_parse_number[\\u0434\\u0432\\u043e\\u0454-2]",
"tests/test_language_uk.py::test_parse_number[\\u0442\\u0440\\u0438-3]",
"tests/test_language_uk.py::test_parse_number[\\u0442\\u0440\\u044c\\u043e\\u0445-3]",
"tests/test_language_uk.py::test_parse_number[\\u0442\\u0440\\u043e\\u0454-3]",
"tests/test_language_uk.py::test_parse_number[\\u0447\\u043e\\u0442\\u0438\\u0440\\u0438-4]",
"tests/test_language_uk.py::test_parse_number[\\u0447\\u0435\\u0442\\u0432\\u0435\\u0440\\u043e-4]",
"tests/test_language_uk.py::test_parse_number[\\u043f\\u02bc\\u044f\\u0442\\u044c-5]",
"tests/test_language_uk.py::test_parse_number[\\u043f\\u02bc\\u044f\\u0442\\u0438-5]",
"tests/test_language_uk.py::test_parse_number[\\u043f\\u02bc\\u044f\\u0442\\u0435\\u0440\\u043e-5]",
"tests/test_language_uk.py::test_parse_number[\\u0448\\u0456\\u0441\\u0442\\u044c-6]",
"tests/test_language_uk.py::test_parse_number[\\u0441\\u0456\\u043c-7]",
"tests/test_language_uk.py::test_parse_number[\\u0432\\u0456\\u0441\\u0456\\u043c-8]",
"tests/test_language_uk.py::test_parse_number[\\u0434\\u0435\\u0432\\u02bc\\u044f\\u0442\\u044c-9]",
"tests/test_language_uk.py::test_parse_number[\\u0434\\u0435\\u0441\\u044f\\u0442\\u044c-10]",
"tests/test_language_uk.py::test_parse_number[\\u043e\\u0434\\u0438\\u043d\\u0430\\u0434\\u0446\\u044f\\u0442\\u044c-11]",
"tests/test_language_uk.py::test_parse_number[\\u0434\\u0432\\u0430\\u043d\\u0430\\u0434\\u0446\\u044f\\u0442\\u044c-12]",
"tests/test_language_uk.py::test_parse_number[\\u0442\\u0440\\u0438\\u043d\\u0430\\u0434\\u0446\\u044f\\u0442\\u044c-13]",
"tests/test_language_uk.py::test_parse_number[\\u0447\\u043e\\u0442\\u0438\\u0440\\u043d\\u0430\\u0434\\u0446\\u044f\\u0442\\u044c-14]",
"tests/test_language_uk.py::test_parse_number[\\u043f\\u02bc\\u044f\\u0442\\u043d\\u0430\\u0434\\u0446\\u044f\\u0442\\u044c-15]",
"tests/test_language_uk.py::test_parse_number[\\u0448\\u0456\\u0441\\u0442\\u043d\\u0430\\u0434\\u0446\\u044f\\u0442\\u044c-16]",
"tests/test_language_uk.py::test_parse_number[\\u0441\\u0456\\u043c\\u043d\\u0430\\u0434\\u0446\\u044f\\u0442\\u044c-17]",
"tests/test_language_uk.py::test_parse_number[\\u0432\\u0456\\u0441\\u0456\\u043c\\u043d\\u0430\\u0434\\u0446\\u044f\\u0442\\u044c-18]",
"tests/test_language_uk.py::test_parse_number[\\u0434\\u0435\\u0432\\u02bc\\u044f\\u0442\\u043d\\u0430\\u0434\\u0446\\u044f\\u0442\\u044c-19]",
"tests/test_language_uk.py::test_parse_number[\\u0434\\u0432\\u0430\\u0434\\u0446\\u044f\\u0442\\u044c-20]",
"tests/test_language_uk.py::test_parse_number[\\u0442\\u0440\\u0438\\u0434\\u0446\\u044f\\u0442\\u044c-30]",
"tests/test_language_uk.py::test_parse_number[\\u0441\\u043e\\u0440\\u043e\\u043a-40]",
"tests/test_language_uk.py::test_parse_number[\\u043f\\u02bc\\u044f\\u0442\\u0434\\u0435\\u0441\\u044f\\u0442-50]",
"tests/test_language_uk.py::test_parse_number[\\u0448\\u0456\\u0441\\u0442\\u0434\\u0435\\u0441\\u044f\\u0442-60]",
"tests/test_language_uk.py::test_parse_number[\\u0441\\u0456\\u043c\\u0434\\u0435\\u0441\\u044f\\u0442-70]",
"tests/test_language_uk.py::test_parse_number[\\u0432\\u0456\\u0441\\u0456\\u043c\\u0434\\u0435\\u0441\\u044f\\u0442-80]",
"tests/test_language_uk.py::test_parse_number[\\u0434\\u0435\\u0432\\u02bc\\u044f\\u043d\\u043e\\u0441\\u0442\\u043e-90]",
"tests/test_language_uk.py::test_parse_number[\\u0441\\u0442\\u043e-100]",
"tests/test_language_uk.py::test_parse_number[\\u0434\\u0432\\u0456\\u0441\\u0442\\u0456-200]",
"tests/test_language_uk.py::test_parse_number[\\u0442\\u0440\\u0438\\u0441\\u0442\\u0430-300]",
"tests/test_language_uk.py::test_parse_number[\\u0447\\u043e\\u0442\\u0438\\u0440\\u0438\\u0441\\u0442\\u0430-400]",
"tests/test_language_uk.py::test_parse_number[\\u043f\\u02bc\\u044f\\u0442\\u0441\\u043e\\u0442-500]",
"tests/test_language_uk.py::test_parse_number[\\u0448\\u0456\\u0441\\u0442\\u0441\\u043e\\u0442-600]",
"tests/test_language_uk.py::test_parse_number[\\u0441\\u0456\\u043c\\u0441\\u043e\\u0442-700]",
"tests/test_language_uk.py::test_parse_number[\\u0432\\u0456\\u0441\\u0456\\u043c\\u0441\\u043e\\u0442-800]",
"tests/test_language_uk.py::test_parse_number[\\u0434\\u0435\\u0432\\u02bc\\u044f\\u0442\\u0441\\u043e\\u0442-900]",
"tests/test_language_uk.py::test_parse_number[\\u043e\\u0434\\u043d\\u0430",
"tests/test_language_uk.py::test_parse_number[\\u0434\\u0435\\u0441\\u044f\\u0442\\u044c",
"tests/test_language_uk.py::test_parse_number[\\u0441\\u0442\\u043e",
"tests/test_language_uk.py::test_parse_number[\\u043c\\u0456\\u043b\\u044c\\u0439\\u043e\\u043d-1000000]",
"tests/test_language_uk.py::test_parse_number[\\u043c\\u0456\\u043b\\u0456\\u043e\\u043d-1000000]",
"tests/test_language_uk.py::test_parse_number[\\u043e\\u0434\\u0438\\u043d",
"tests/test_language_uk.py::test_parse_number[\\u043c\\u0456\\u043b\\u044c\\u044f\\u0440\\u0434-1000000000]",
"tests/test_language_uk.py::test_parse_number[\\u0442\\u0440\\u0438\\u043b\\u044c\\u0439\\u043e\\u043d-1000000000000]",
"tests/test_language_uk.py::test_parse_number[\\u043a\\u0432\\u0430\\u0434\\u0440\\u0438\\u043b\\u044c\\u0439\\u043e\\u043d-1000000000000000]",
"tests/test_language_uk.py::test_parse_number[\\u043a\\u0432\\u0456\\u043d\\u0442\\u0438\\u043b\\u044c\\u0439\\u043e\\u043d-1000000000000000000]",
"tests/test_language_uk.py::test_parse_number[\\u0441\\u0435\\u043a\\u0441\\u0442\\u0438\\u043b\\u044c\\u0439\\u043e\\u043d-1000000000000000000000]",
"tests/test_language_uk.py::test_parse_number[\\u0441\\u0435\\u043f\\u0442\\u0438\\u043b\\u044c\\u0439\\u043e\\u043d-1000000000000000000000000]",
"tests/test_language_uk.py::test_parse_number[\\u043e\\u043a\\u0442\\u0438\\u043b\\u044c\\u0439\\u043e\\u043d-1000000000000000000000000000]",
"tests/test_language_uk.py::test_parse_number[\\u043d\\u043e\\u043d\\u0456\\u043b\\u044c\\u0439\\u043e\\u043d-1000000000000000000000000000000]",
"tests/test_language_uk.py::test_parse_number[\\u0434\\u0435\\u0446\\u0456\\u043b\\u044c\\u0439\\u043e\\u043d-1000000000000000000000000000000000]",
"tests/test_language_uk.py::test_parse_number[\\u0443\\u043d\\u0434\\u0435\\u0446\\u0456\\u043b\\u044c\\u0439\\u043e\\u043d-1000000000000000000000000000000000000]",
"tests/test_language_uk.py::test_parse_number[\\u0434\\u0443\\u043e\\u0434\\u0435\\u0446\\u0456\\u043b\\u044c\\u0439\\u043e\\u043d-1000000000000000000000000000000000000000]",
"tests/test_language_uk.py::test_parse_number[\\u0442\\u0440\\u0435\\u0434\\u0435\\u0446\\u0456\\u043b\\u044c\\u0439\\u043e\\u043d-1000000000000000000000000000000000000000000]"
] |
[
"tests/test_language_uk.py::test_parse_number_till_hundred",
"tests/test_language_uk.py::test_parse_number_permutations"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-10-05 11:14:54+00:00
|
bsd-3-clause
| 5,391 |
|
scrapinghub__price-parser-31
|
diff --git a/price_parser/_currencies.py b/price_parser/_currencies.py
index ed0ce46..a6563aa 100644
--- a/price_parser/_currencies.py
+++ b/price_parser/_currencies.py
@@ -648,6 +648,7 @@ CURRENCIES: Dict[str, Dict] = {
"s": "¥",
"n": "Japanese Yen",
"sn": "¥",
+ "sn2": ["円"],
"d": 0,
"r": 0,
"np": "Japanese yen"
@@ -687,7 +688,7 @@ CURRENCIES: Dict[str, Dict] = {
"KPW": {
"s": "₩",
"n": "North Korean Won",
- "sn": "₩",
+ "sn": "원",
"d": 0,
"r": 0,
"np": "North Korean Won"
@@ -695,7 +696,7 @@ CURRENCIES: Dict[str, Dict] = {
"KRW": {
"s": "₩",
"n": "South Korean Won",
- "sn": "₩",
+ "sn": "원",
"d": 0,
"r": 0,
"np": "South Korean won"
|
scrapinghub/price-parser
|
63d033b5e09027f04ad7c3c5d66766e09d6457d1
|
diff --git a/tests/test_price_parsing.py b/tests/test_price_parsing.py
index e7fd9bf..28ee0a3 100644
--- a/tests/test_price_parsing.py
+++ b/tests/test_price_parsing.py
@@ -82,7 +82,11 @@ PRICE_PARSING_EXAMPLES_NEW = [
Example(None, 'AED 8000 (USD 2179)',
'AED', '8000', 8000),
Example(None, '13800 ₶',
- '₶', '13800', 13800)
+ '₶', '13800', 13800),
+ Example(None, '12,000원',
+ '원', '12,000', 12000),
+ Example(None, '3,500円',
+ '円', '3,500', 3500)
]
|
It can't parse Asian text currency like '원', '円'.
Korean, and Japanese uses each specific money character like '₩', '¥'.
But that country also using their text based money character to represent currency.
Korean uses '원', Japanese uses '円'.
but this parser can't parse that character.
Thank you.
|
0.0
|
63d033b5e09027f04ad7c3c5d66766e09d6457d1
|
[
"tests/test_price_parsing.py::test_parsing[example12]",
"tests/test_price_parsing.py::test_parsing[example13]"
] |
[
"tests/test_price_parsing.py::test_parsing[example0]",
"tests/test_price_parsing.py::test_parsing[example1]",
"tests/test_price_parsing.py::test_parsing[example2]",
"tests/test_price_parsing.py::test_parsing[example3]",
"tests/test_price_parsing.py::test_parsing[example4]",
"tests/test_price_parsing.py::test_parsing[example5]",
"tests/test_price_parsing.py::test_parsing[example6]",
"tests/test_price_parsing.py::test_parsing[example7]",
"tests/test_price_parsing.py::test_parsing[example8]",
"tests/test_price_parsing.py::test_parsing[example9]",
"tests/test_price_parsing.py::test_parsing[example10]",
"tests/test_price_parsing.py::test_parsing[example11]",
"tests/test_price_parsing.py::test_parsing[example14]",
"tests/test_price_parsing.py::test_parsing[example15]",
"tests/test_price_parsing.py::test_parsing[example16]",
"tests/test_price_parsing.py::test_parsing[example17]",
"tests/test_price_parsing.py::test_parsing[example18]",
"tests/test_price_parsing.py::test_parsing[example19]",
"tests/test_price_parsing.py::test_parsing[example20]",
"tests/test_price_parsing.py::test_parsing[example21]",
"tests/test_price_parsing.py::test_parsing[example22]",
"tests/test_price_parsing.py::test_parsing[example23]",
"tests/test_price_parsing.py::test_parsing[example24]",
"tests/test_price_parsing.py::test_parsing[example25]",
"tests/test_price_parsing.py::test_parsing[example26]",
"tests/test_price_parsing.py::test_parsing[example27]",
"tests/test_price_parsing.py::test_parsing[example28]",
"tests/test_price_parsing.py::test_parsing[example29]",
"tests/test_price_parsing.py::test_parsing[example30]",
"tests/test_price_parsing.py::test_parsing[example31]",
"tests/test_price_parsing.py::test_parsing[example32]",
"tests/test_price_parsing.py::test_parsing[example33]",
"tests/test_price_parsing.py::test_parsing[example34]",
"tests/test_price_parsing.py::test_parsing[example35]",
"tests/test_price_parsing.py::test_parsing[example36]",
"tests/test_price_parsing.py::test_parsing[example37]",
"tests/test_price_parsing.py::test_parsing[example38]",
"tests/test_price_parsing.py::test_parsing[example39]",
"tests/test_price_parsing.py::test_parsing[example40]",
"tests/test_price_parsing.py::test_parsing[example41]",
"tests/test_price_parsing.py::test_parsing[example42]",
"tests/test_price_parsing.py::test_parsing[example43]",
"tests/test_price_parsing.py::test_parsing[example44]",
"tests/test_price_parsing.py::test_parsing[example45]",
"tests/test_price_parsing.py::test_parsing[example46]",
"tests/test_price_parsing.py::test_parsing[example47]",
"tests/test_price_parsing.py::test_parsing[example48]",
"tests/test_price_parsing.py::test_parsing[example49]",
"tests/test_price_parsing.py::test_parsing[example50]",
"tests/test_price_parsing.py::test_parsing[example51]",
"tests/test_price_parsing.py::test_parsing[example52]",
"tests/test_price_parsing.py::test_parsing[example53]",
"tests/test_price_parsing.py::test_parsing[example54]",
"tests/test_price_parsing.py::test_parsing[example55]",
"tests/test_price_parsing.py::test_parsing[example56]",
"tests/test_price_parsing.py::test_parsing[example57]",
"tests/test_price_parsing.py::test_parsing[example58]",
"tests/test_price_parsing.py::test_parsing[example59]",
"tests/test_price_parsing.py::test_parsing[example60]",
"tests/test_price_parsing.py::test_parsing[example61]",
"tests/test_price_parsing.py::test_parsing[example62]",
"tests/test_price_parsing.py::test_parsing[example63]",
"tests/test_price_parsing.py::test_parsing[example64]",
"tests/test_price_parsing.py::test_parsing[example65]",
"tests/test_price_parsing.py::test_parsing[example66]",
"tests/test_price_parsing.py::test_parsing[example67]",
"tests/test_price_parsing.py::test_parsing[example68]",
"tests/test_price_parsing.py::test_parsing[example69]",
"tests/test_price_parsing.py::test_parsing[example70]",
"tests/test_price_parsing.py::test_parsing[example71]",
"tests/test_price_parsing.py::test_parsing[example72]",
"tests/test_price_parsing.py::test_parsing[example73]",
"tests/test_price_parsing.py::test_parsing[example74]",
"tests/test_price_parsing.py::test_parsing[example75]",
"tests/test_price_parsing.py::test_parsing[example76]",
"tests/test_price_parsing.py::test_parsing[example77]",
"tests/test_price_parsing.py::test_parsing[example78]",
"tests/test_price_parsing.py::test_parsing[example79]",
"tests/test_price_parsing.py::test_parsing[example80]",
"tests/test_price_parsing.py::test_parsing[example81]",
"tests/test_price_parsing.py::test_parsing[example82]",
"tests/test_price_parsing.py::test_parsing[example83]",
"tests/test_price_parsing.py::test_parsing[example84]",
"tests/test_price_parsing.py::test_parsing[example85]",
"tests/test_price_parsing.py::test_parsing[example86]",
"tests/test_price_parsing.py::test_parsing[example87]",
"tests/test_price_parsing.py::test_parsing[example88]",
"tests/test_price_parsing.py::test_parsing[example89]",
"tests/test_price_parsing.py::test_parsing[example90]",
"tests/test_price_parsing.py::test_parsing[example91]",
"tests/test_price_parsing.py::test_parsing[example92]",
"tests/test_price_parsing.py::test_parsing[example93]",
"tests/test_price_parsing.py::test_parsing[example94]",
"tests/test_price_parsing.py::test_parsing[example95]",
"tests/test_price_parsing.py::test_parsing[example96]",
"tests/test_price_parsing.py::test_parsing[example97]",
"tests/test_price_parsing.py::test_parsing[example98]",
"tests/test_price_parsing.py::test_parsing[example99]",
"tests/test_price_parsing.py::test_parsing[example100]",
"tests/test_price_parsing.py::test_parsing[example101]",
"tests/test_price_parsing.py::test_parsing[example102]",
"tests/test_price_parsing.py::test_parsing[example103]",
"tests/test_price_parsing.py::test_parsing[example104]",
"tests/test_price_parsing.py::test_parsing[example105]",
"tests/test_price_parsing.py::test_parsing[example106]",
"tests/test_price_parsing.py::test_parsing[example107]",
"tests/test_price_parsing.py::test_parsing[example108]",
"tests/test_price_parsing.py::test_parsing[example109]",
"tests/test_price_parsing.py::test_parsing[example110]",
"tests/test_price_parsing.py::test_parsing[example111]",
"tests/test_price_parsing.py::test_parsing[example112]",
"tests/test_price_parsing.py::test_parsing[example113]",
"tests/test_price_parsing.py::test_parsing[example114]",
"tests/test_price_parsing.py::test_parsing[example115]",
"tests/test_price_parsing.py::test_parsing[example116]",
"tests/test_price_parsing.py::test_parsing[example117]",
"tests/test_price_parsing.py::test_parsing[example118]",
"tests/test_price_parsing.py::test_parsing[example119]",
"tests/test_price_parsing.py::test_parsing[example120]",
"tests/test_price_parsing.py::test_parsing[example121]",
"tests/test_price_parsing.py::test_parsing[example122]",
"tests/test_price_parsing.py::test_parsing[example123]",
"tests/test_price_parsing.py::test_parsing[example124]",
"tests/test_price_parsing.py::test_parsing[example125]",
"tests/test_price_parsing.py::test_parsing[example126]",
"tests/test_price_parsing.py::test_parsing[example127]",
"tests/test_price_parsing.py::test_parsing[example128]",
"tests/test_price_parsing.py::test_parsing[example129]",
"tests/test_price_parsing.py::test_parsing[example130]",
"tests/test_price_parsing.py::test_parsing[example131]",
"tests/test_price_parsing.py::test_parsing[example132]",
"tests/test_price_parsing.py::test_parsing[example133]",
"tests/test_price_parsing.py::test_parsing[example134]",
"tests/test_price_parsing.py::test_parsing[example135]",
"tests/test_price_parsing.py::test_parsing[example136]",
"tests/test_price_parsing.py::test_parsing[example137]",
"tests/test_price_parsing.py::test_parsing[example138]",
"tests/test_price_parsing.py::test_parsing[example139]",
"tests/test_price_parsing.py::test_parsing[example140]",
"tests/test_price_parsing.py::test_parsing[example141]",
"tests/test_price_parsing.py::test_parsing[example142]",
"tests/test_price_parsing.py::test_parsing[example143]",
"tests/test_price_parsing.py::test_parsing[example144]",
"tests/test_price_parsing.py::test_parsing[example145]",
"tests/test_price_parsing.py::test_parsing[example146]",
"tests/test_price_parsing.py::test_parsing[example147]",
"tests/test_price_parsing.py::test_parsing[example148]",
"tests/test_price_parsing.py::test_parsing[example149]",
"tests/test_price_parsing.py::test_parsing[example150]",
"tests/test_price_parsing.py::test_parsing[example151]",
"tests/test_price_parsing.py::test_parsing[example152]",
"tests/test_price_parsing.py::test_parsing[example153]",
"tests/test_price_parsing.py::test_parsing[example154]",
"tests/test_price_parsing.py::test_parsing[example155]",
"tests/test_price_parsing.py::test_parsing[example156]",
"tests/test_price_parsing.py::test_parsing[example157]",
"tests/test_price_parsing.py::test_parsing[example158]",
"tests/test_price_parsing.py::test_parsing[example159]",
"tests/test_price_parsing.py::test_parsing[example160]",
"tests/test_price_parsing.py::test_parsing[example161]",
"tests/test_price_parsing.py::test_parsing[example162]",
"tests/test_price_parsing.py::test_parsing[example163]",
"tests/test_price_parsing.py::test_parsing[example164]",
"tests/test_price_parsing.py::test_parsing[example165]",
"tests/test_price_parsing.py::test_parsing[example166]",
"tests/test_price_parsing.py::test_parsing[example167]",
"tests/test_price_parsing.py::test_parsing[example168]",
"tests/test_price_parsing.py::test_parsing[example169]",
"tests/test_price_parsing.py::test_parsing[example170]",
"tests/test_price_parsing.py::test_parsing[example171]",
"tests/test_price_parsing.py::test_parsing[example172]",
"tests/test_price_parsing.py::test_parsing[example173]",
"tests/test_price_parsing.py::test_parsing[example174]",
"tests/test_price_parsing.py::test_parsing[example175]",
"tests/test_price_parsing.py::test_parsing[example176]",
"tests/test_price_parsing.py::test_parsing[example177]",
"tests/test_price_parsing.py::test_parsing[example178]",
"tests/test_price_parsing.py::test_parsing[example179]",
"tests/test_price_parsing.py::test_parsing[example180]",
"tests/test_price_parsing.py::test_parsing[example181]",
"tests/test_price_parsing.py::test_parsing[example182]",
"tests/test_price_parsing.py::test_parsing[example183]",
"tests/test_price_parsing.py::test_parsing[example184]",
"tests/test_price_parsing.py::test_parsing[example185]",
"tests/test_price_parsing.py::test_parsing[example186]",
"tests/test_price_parsing.py::test_parsing[example187]",
"tests/test_price_parsing.py::test_parsing[example188]",
"tests/test_price_parsing.py::test_parsing[example189]",
"tests/test_price_parsing.py::test_parsing[example190]",
"tests/test_price_parsing.py::test_parsing[example191]",
"tests/test_price_parsing.py::test_parsing[example192]",
"tests/test_price_parsing.py::test_parsing[example193]",
"tests/test_price_parsing.py::test_parsing[example194]",
"tests/test_price_parsing.py::test_parsing[example195]",
"tests/test_price_parsing.py::test_parsing[example196]",
"tests/test_price_parsing.py::test_parsing[example197]",
"tests/test_price_parsing.py::test_parsing[example198]",
"tests/test_price_parsing.py::test_parsing[example199]",
"tests/test_price_parsing.py::test_parsing[example200]",
"tests/test_price_parsing.py::test_parsing[example201]",
"tests/test_price_parsing.py::test_parsing[example202]",
"tests/test_price_parsing.py::test_parsing[example203]",
"tests/test_price_parsing.py::test_parsing[example204]",
"tests/test_price_parsing.py::test_parsing[example205]",
"tests/test_price_parsing.py::test_parsing[example206]",
"tests/test_price_parsing.py::test_parsing[example207]",
"tests/test_price_parsing.py::test_parsing[example208]",
"tests/test_price_parsing.py::test_parsing[example209]",
"tests/test_price_parsing.py::test_parsing[example210]",
"tests/test_price_parsing.py::test_parsing[example211]",
"tests/test_price_parsing.py::test_parsing[example212]",
"tests/test_price_parsing.py::test_parsing[example213]",
"tests/test_price_parsing.py::test_parsing[example214]",
"tests/test_price_parsing.py::test_parsing[example215]",
"tests/test_price_parsing.py::test_parsing[example216]",
"tests/test_price_parsing.py::test_parsing[example217]",
"tests/test_price_parsing.py::test_parsing[example218]",
"tests/test_price_parsing.py::test_parsing[example219]",
"tests/test_price_parsing.py::test_parsing[example220]",
"tests/test_price_parsing.py::test_parsing[example221]",
"tests/test_price_parsing.py::test_parsing[example222]",
"tests/test_price_parsing.py::test_parsing[example223]",
"tests/test_price_parsing.py::test_parsing[example224]",
"tests/test_price_parsing.py::test_parsing[example225]",
"tests/test_price_parsing.py::test_parsing[example226]",
"tests/test_price_parsing.py::test_parsing[example227]",
"tests/test_price_parsing.py::test_parsing[example228]",
"tests/test_price_parsing.py::test_parsing[example229]",
"tests/test_price_parsing.py::test_parsing[example230]",
"tests/test_price_parsing.py::test_parsing[example231]",
"tests/test_price_parsing.py::test_parsing[example232]",
"tests/test_price_parsing.py::test_parsing[example233]",
"tests/test_price_parsing.py::test_parsing[example234]",
"tests/test_price_parsing.py::test_parsing[example235]",
"tests/test_price_parsing.py::test_parsing[example236]",
"tests/test_price_parsing.py::test_parsing[example237]",
"tests/test_price_parsing.py::test_parsing[example238]",
"tests/test_price_parsing.py::test_parsing[example239]",
"tests/test_price_parsing.py::test_parsing[example240]",
"tests/test_price_parsing.py::test_parsing[example241]",
"tests/test_price_parsing.py::test_parsing[example242]",
"tests/test_price_parsing.py::test_parsing[example243]",
"tests/test_price_parsing.py::test_parsing[example244]",
"tests/test_price_parsing.py::test_parsing[example245]",
"tests/test_price_parsing.py::test_parsing[example246]",
"tests/test_price_parsing.py::test_parsing[example247]",
"tests/test_price_parsing.py::test_parsing[example248]",
"tests/test_price_parsing.py::test_parsing[example249]",
"tests/test_price_parsing.py::test_parsing[example250]",
"tests/test_price_parsing.py::test_parsing[example251]",
"tests/test_price_parsing.py::test_parsing[example252]",
"tests/test_price_parsing.py::test_parsing[example253]",
"tests/test_price_parsing.py::test_parsing[example254]",
"tests/test_price_parsing.py::test_parsing[example255]",
"tests/test_price_parsing.py::test_parsing[example256]",
"tests/test_price_parsing.py::test_parsing[example257]",
"tests/test_price_parsing.py::test_parsing[example258]",
"tests/test_price_parsing.py::test_parsing[example259]",
"tests/test_price_parsing.py::test_parsing[example260]",
"tests/test_price_parsing.py::test_parsing[example261]",
"tests/test_price_parsing.py::test_parsing[example262]",
"tests/test_price_parsing.py::test_parsing[example263]",
"tests/test_price_parsing.py::test_parsing[example264]",
"tests/test_price_parsing.py::test_parsing[example265]",
"tests/test_price_parsing.py::test_parsing[example266]",
"tests/test_price_parsing.py::test_parsing[example267]",
"tests/test_price_parsing.py::test_parsing[example268]",
"tests/test_price_parsing.py::test_parsing[example269]",
"tests/test_price_parsing.py::test_parsing[example270]",
"tests/test_price_parsing.py::test_parsing[example271]",
"tests/test_price_parsing.py::test_parsing[example272]",
"tests/test_price_parsing.py::test_parsing[example273]",
"tests/test_price_parsing.py::test_parsing[example274]",
"tests/test_price_parsing.py::test_parsing[example275]",
"tests/test_price_parsing.py::test_parsing[example276]",
"tests/test_price_parsing.py::test_parsing[example277]",
"tests/test_price_parsing.py::test_parsing[example278]",
"tests/test_price_parsing.py::test_parsing[example279]",
"tests/test_price_parsing.py::test_parsing[example280]",
"tests/test_price_parsing.py::test_parsing[example281]",
"tests/test_price_parsing.py::test_parsing[example282]",
"tests/test_price_parsing.py::test_parsing[example283]",
"tests/test_price_parsing.py::test_parsing[example284]",
"tests/test_price_parsing.py::test_parsing[example285]",
"tests/test_price_parsing.py::test_parsing[example286]",
"tests/test_price_parsing.py::test_parsing[example287]",
"tests/test_price_parsing.py::test_parsing[example288]",
"tests/test_price_parsing.py::test_parsing[example289]",
"tests/test_price_parsing.py::test_parsing[example290]",
"tests/test_price_parsing.py::test_parsing[example291]",
"tests/test_price_parsing.py::test_parsing[example292]",
"tests/test_price_parsing.py::test_parsing[example293]",
"tests/test_price_parsing.py::test_parsing[example294]",
"tests/test_price_parsing.py::test_parsing[example295]",
"tests/test_price_parsing.py::test_parsing[example296]",
"tests/test_price_parsing.py::test_parsing[example297]",
"tests/test_price_parsing.py::test_parsing[example298]",
"tests/test_price_parsing.py::test_parsing[example299]",
"tests/test_price_parsing.py::test_parsing[example300]",
"tests/test_price_parsing.py::test_parsing[example301]",
"tests/test_price_parsing.py::test_parsing[example302]",
"tests/test_price_parsing.py::test_parsing[example303]",
"tests/test_price_parsing.py::test_parsing[example304]",
"tests/test_price_parsing.py::test_parsing[example305]",
"tests/test_price_parsing.py::test_parsing[example306]",
"tests/test_price_parsing.py::test_parsing[example307]",
"tests/test_price_parsing.py::test_parsing[example308]",
"tests/test_price_parsing.py::test_parsing[example309]",
"tests/test_price_parsing.py::test_parsing[example310]",
"tests/test_price_parsing.py::test_parsing[example311]",
"tests/test_price_parsing.py::test_parsing[example312]",
"tests/test_price_parsing.py::test_parsing[example313]",
"tests/test_price_parsing.py::test_parsing[example314]",
"tests/test_price_parsing.py::test_parsing[example315]",
"tests/test_price_parsing.py::test_parsing[example316]",
"tests/test_price_parsing.py::test_parsing[example317]",
"tests/test_price_parsing.py::test_parsing[example318]",
"tests/test_price_parsing.py::test_parsing[example319]",
"tests/test_price_parsing.py::test_parsing[example320]",
"tests/test_price_parsing.py::test_parsing[example321]",
"tests/test_price_parsing.py::test_parsing[example322]",
"tests/test_price_parsing.py::test_parsing[example323]",
"tests/test_price_parsing.py::test_parsing[example324]",
"tests/test_price_parsing.py::test_parsing[example325]",
"tests/test_price_parsing.py::test_parsing[example326]",
"tests/test_price_parsing.py::test_parsing[example327]",
"tests/test_price_parsing.py::test_parsing[example328]",
"tests/test_price_parsing.py::test_parsing[example329]",
"tests/test_price_parsing.py::test_parsing[example330]",
"tests/test_price_parsing.py::test_parsing[example331]",
"tests/test_price_parsing.py::test_parsing[example332]",
"tests/test_price_parsing.py::test_parsing[example333]",
"tests/test_price_parsing.py::test_parsing[example334]",
"tests/test_price_parsing.py::test_parsing[example335]",
"tests/test_price_parsing.py::test_parsing[example336]",
"tests/test_price_parsing.py::test_parsing[example337]",
"tests/test_price_parsing.py::test_parsing[example338]",
"tests/test_price_parsing.py::test_parsing[example339]",
"tests/test_price_parsing.py::test_parsing[example340]",
"tests/test_price_parsing.py::test_parsing[example341]",
"tests/test_price_parsing.py::test_parsing[example342]",
"tests/test_price_parsing.py::test_parsing[example343]",
"tests/test_price_parsing.py::test_parsing[example344]",
"tests/test_price_parsing.py::test_parsing[example345]",
"tests/test_price_parsing.py::test_parsing[example346]",
"tests/test_price_parsing.py::test_parsing[example347]",
"tests/test_price_parsing.py::test_parsing[example348]",
"tests/test_price_parsing.py::test_parsing[example349]",
"tests/test_price_parsing.py::test_parsing[example350]",
"tests/test_price_parsing.py::test_parsing[example351]",
"tests/test_price_parsing.py::test_parsing[example352]",
"tests/test_price_parsing.py::test_parsing[example353]",
"tests/test_price_parsing.py::test_parsing[example354]",
"tests/test_price_parsing.py::test_parsing[example355]",
"tests/test_price_parsing.py::test_parsing[example356]",
"tests/test_price_parsing.py::test_parsing[example357]",
"tests/test_price_parsing.py::test_parsing[example358]",
"tests/test_price_parsing.py::test_parsing[example359]",
"tests/test_price_parsing.py::test_parsing[example360]",
"tests/test_price_parsing.py::test_parsing[example361]",
"tests/test_price_parsing.py::test_parsing[example362]",
"tests/test_price_parsing.py::test_parsing[example363]",
"tests/test_price_parsing.py::test_parsing[example364]",
"tests/test_price_parsing.py::test_parsing[example365]",
"tests/test_price_parsing.py::test_parsing[example366]",
"tests/test_price_parsing.py::test_parsing[example367]",
"tests/test_price_parsing.py::test_parsing[example368]",
"tests/test_price_parsing.py::test_parsing[example369]",
"tests/test_price_parsing.py::test_parsing[example370]",
"tests/test_price_parsing.py::test_parsing[example371]",
"tests/test_price_parsing.py::test_parsing[example372]",
"tests/test_price_parsing.py::test_parsing[example373]",
"tests/test_price_parsing.py::test_parsing[example374]",
"tests/test_price_parsing.py::test_parsing[example375]",
"tests/test_price_parsing.py::test_parsing[example376]",
"tests/test_price_parsing.py::test_parsing[example377]",
"tests/test_price_parsing.py::test_parsing[example378]",
"tests/test_price_parsing.py::test_parsing[example379]",
"tests/test_price_parsing.py::test_parsing[example380]",
"tests/test_price_parsing.py::test_parsing[example381]",
"tests/test_price_parsing.py::test_parsing[example382]",
"tests/test_price_parsing.py::test_parsing[example383]",
"tests/test_price_parsing.py::test_parsing[example384]",
"tests/test_price_parsing.py::test_parsing[example385]",
"tests/test_price_parsing.py::test_parsing[example386]",
"tests/test_price_parsing.py::test_parsing[example387]",
"tests/test_price_parsing.py::test_parsing[example388]",
"tests/test_price_parsing.py::test_parsing[example389]",
"tests/test_price_parsing.py::test_parsing[example390]",
"tests/test_price_parsing.py::test_parsing[example391]",
"tests/test_price_parsing.py::test_parsing[example392]",
"tests/test_price_parsing.py::test_parsing[example393]",
"tests/test_price_parsing.py::test_parsing[example394]",
"tests/test_price_parsing.py::test_parsing[example395]",
"tests/test_price_parsing.py::test_parsing[example396]",
"tests/test_price_parsing.py::test_parsing[example397]",
"tests/test_price_parsing.py::test_parsing[example398]",
"tests/test_price_parsing.py::test_parsing[example399]",
"tests/test_price_parsing.py::test_parsing[example400]",
"tests/test_price_parsing.py::test_parsing[example401]",
"tests/test_price_parsing.py::test_parsing[example402]",
"tests/test_price_parsing.py::test_parsing[example403]",
"tests/test_price_parsing.py::test_parsing[example404]",
"tests/test_price_parsing.py::test_parsing[example405]",
"tests/test_price_parsing.py::test_parsing[example406]",
"tests/test_price_parsing.py::test_parsing[example407]",
"tests/test_price_parsing.py::test_parsing[example408]",
"tests/test_price_parsing.py::test_parsing[example409]",
"tests/test_price_parsing.py::test_parsing[example410]",
"tests/test_price_parsing.py::test_parsing[example411]",
"tests/test_price_parsing.py::test_parsing[example412]",
"tests/test_price_parsing.py::test_parsing[example413]",
"tests/test_price_parsing.py::test_parsing[example414]",
"tests/test_price_parsing.py::test_parsing[example415]",
"tests/test_price_parsing.py::test_parsing[example416]",
"tests/test_price_parsing.py::test_parsing[example417]",
"tests/test_price_parsing.py::test_parsing[example418]",
"tests/test_price_parsing.py::test_parsing[example419]",
"tests/test_price_parsing.py::test_parsing[example420]",
"tests/test_price_parsing.py::test_parsing[example421]",
"tests/test_price_parsing.py::test_parsing[example422]",
"tests/test_price_parsing.py::test_parsing[example423]",
"tests/test_price_parsing.py::test_parsing[example424]",
"tests/test_price_parsing.py::test_parsing[example425]",
"tests/test_price_parsing.py::test_parsing[example426]",
"tests/test_price_parsing.py::test_parsing[example427]",
"tests/test_price_parsing.py::test_parsing[example428]",
"tests/test_price_parsing.py::test_parsing[example429]",
"tests/test_price_parsing.py::test_parsing[example430]",
"tests/test_price_parsing.py::test_parsing[example431]",
"tests/test_price_parsing.py::test_parsing[example432]",
"tests/test_price_parsing.py::test_parsing[example433]",
"tests/test_price_parsing.py::test_parsing[example434]",
"tests/test_price_parsing.py::test_parsing[example435]",
"tests/test_price_parsing.py::test_parsing[example436]",
"tests/test_price_parsing.py::test_parsing[example437]",
"tests/test_price_parsing.py::test_parsing[example438]",
"tests/test_price_parsing.py::test_parsing[example439]",
"tests/test_price_parsing.py::test_parsing[example440]",
"tests/test_price_parsing.py::test_parsing[example441]",
"tests/test_price_parsing.py::test_parsing[example442]",
"tests/test_price_parsing.py::test_parsing[example443]",
"tests/test_price_parsing.py::test_parsing[example444]",
"tests/test_price_parsing.py::test_parsing[example445]",
"tests/test_price_parsing.py::test_parsing[example446]",
"tests/test_price_parsing.py::test_parsing[example447]",
"tests/test_price_parsing.py::test_parsing[example448]",
"tests/test_price_parsing.py::test_parsing[example449]",
"tests/test_price_parsing.py::test_parsing[example450]",
"tests/test_price_parsing.py::test_parsing[example451]",
"tests/test_price_parsing.py::test_parsing[example452]",
"tests/test_price_parsing.py::test_parsing[example453]",
"tests/test_price_parsing.py::test_parsing[example454]",
"tests/test_price_parsing.py::test_parsing[example455]",
"tests/test_price_parsing.py::test_parsing[example456]",
"tests/test_price_parsing.py::test_parsing[example457]",
"tests/test_price_parsing.py::test_parsing[example458]",
"tests/test_price_parsing.py::test_parsing[example459]",
"tests/test_price_parsing.py::test_parsing[example460]",
"tests/test_price_parsing.py::test_parsing[example461]",
"tests/test_price_parsing.py::test_parsing[example462]",
"tests/test_price_parsing.py::test_parsing[example463]",
"tests/test_price_parsing.py::test_parsing[example464]",
"tests/test_price_parsing.py::test_parsing[example465]",
"tests/test_price_parsing.py::test_parsing[example466]",
"tests/test_price_parsing.py::test_parsing[example467]",
"tests/test_price_parsing.py::test_parsing[example468]",
"tests/test_price_parsing.py::test_parsing[example469]",
"tests/test_price_parsing.py::test_parsing[example470]",
"tests/test_price_parsing.py::test_parsing[example471]",
"tests/test_price_parsing.py::test_parsing[example472]",
"tests/test_price_parsing.py::test_parsing[example473]",
"tests/test_price_parsing.py::test_parsing[example474]",
"tests/test_price_parsing.py::test_parsing[example475]",
"tests/test_price_parsing.py::test_parsing[example476]",
"tests/test_price_parsing.py::test_parsing[example477]",
"tests/test_price_parsing.py::test_parsing[example478]",
"tests/test_price_parsing.py::test_parsing[example479]",
"tests/test_price_parsing.py::test_parsing[example480]",
"tests/test_price_parsing.py::test_parsing[example481]",
"tests/test_price_parsing.py::test_parsing[example482]",
"tests/test_price_parsing.py::test_parsing[example483]",
"tests/test_price_parsing.py::test_parsing[example484]",
"tests/test_price_parsing.py::test_parsing[example485]",
"tests/test_price_parsing.py::test_parsing[example486]",
"tests/test_price_parsing.py::test_parsing[example487]",
"tests/test_price_parsing.py::test_parsing[example488]",
"tests/test_price_parsing.py::test_parsing[example489]",
"tests/test_price_parsing.py::test_parsing[example490]",
"tests/test_price_parsing.py::test_parsing[example491]",
"tests/test_price_parsing.py::test_parsing[example492]",
"tests/test_price_parsing.py::test_parsing[example493]",
"tests/test_price_parsing.py::test_parsing[example494]",
"tests/test_price_parsing.py::test_parsing[example495]",
"tests/test_price_parsing.py::test_parsing[example496]",
"tests/test_price_parsing.py::test_parsing[example497]",
"tests/test_price_parsing.py::test_parsing[example498]",
"tests/test_price_parsing.py::test_parsing[example499]",
"tests/test_price_parsing.py::test_parsing[example500]",
"tests/test_price_parsing.py::test_parsing[example501]",
"tests/test_price_parsing.py::test_parsing[example502]",
"tests/test_price_parsing.py::test_parsing[example503]",
"tests/test_price_parsing.py::test_parsing[example504]",
"tests/test_price_parsing.py::test_parsing[example505]",
"tests/test_price_parsing.py::test_parsing[example506]",
"tests/test_price_parsing.py::test_parsing[example507]",
"tests/test_price_parsing.py::test_parsing[example508]",
"tests/test_price_parsing.py::test_parsing[example509]",
"tests/test_price_parsing.py::test_parsing[example510]",
"tests/test_price_parsing.py::test_parsing[example511]",
"tests/test_price_parsing.py::test_parsing[example512]",
"tests/test_price_parsing.py::test_parsing[example513]",
"tests/test_price_parsing.py::test_parsing[example514]",
"tests/test_price_parsing.py::test_parsing[example515]",
"tests/test_price_parsing.py::test_parsing[example516]",
"tests/test_price_parsing.py::test_parsing[example517]",
"tests/test_price_parsing.py::test_parsing[example518]",
"tests/test_price_parsing.py::test_parsing[example519]",
"tests/test_price_parsing.py::test_parsing[example520]",
"tests/test_price_parsing.py::test_parsing[example521]",
"tests/test_price_parsing.py::test_parsing[example522]",
"tests/test_price_parsing.py::test_parsing[example523]",
"tests/test_price_parsing.py::test_parsing[example524]",
"tests/test_price_parsing.py::test_parsing[example525]",
"tests/test_price_parsing.py::test_parsing[example526]",
"tests/test_price_parsing.py::test_parsing[example527]",
"tests/test_price_parsing.py::test_parsing[example528]",
"tests/test_price_parsing.py::test_parsing[example529]",
"tests/test_price_parsing.py::test_parsing[example530]",
"tests/test_price_parsing.py::test_parsing[example531]",
"tests/test_price_parsing.py::test_parsing[example532]",
"tests/test_price_parsing.py::test_parsing[example533]",
"tests/test_price_parsing.py::test_parsing[example534]",
"tests/test_price_parsing.py::test_parsing[example535]",
"tests/test_price_parsing.py::test_parsing[example536]",
"tests/test_price_parsing.py::test_parsing[example537]",
"tests/test_price_parsing.py::test_parsing[example538]",
"tests/test_price_parsing.py::test_parsing[example539]",
"tests/test_price_parsing.py::test_parsing[example540]",
"tests/test_price_parsing.py::test_parsing[example541]",
"tests/test_price_parsing.py::test_parsing[example542]",
"tests/test_price_parsing.py::test_parsing[example543]",
"tests/test_price_parsing.py::test_parsing[example544]",
"tests/test_price_parsing.py::test_parsing[example545]",
"tests/test_price_parsing.py::test_parsing[example546]",
"tests/test_price_parsing.py::test_parsing[example547]",
"tests/test_price_parsing.py::test_parsing[example548]",
"tests/test_price_parsing.py::test_parsing[example549]",
"tests/test_price_parsing.py::test_parsing[example550]",
"tests/test_price_parsing.py::test_parsing[example551]",
"tests/test_price_parsing.py::test_parsing[example552]",
"tests/test_price_parsing.py::test_parsing[example553]",
"tests/test_price_parsing.py::test_parsing[example554]",
"tests/test_price_parsing.py::test_parsing[example555]",
"tests/test_price_parsing.py::test_parsing[example556]",
"tests/test_price_parsing.py::test_parsing[example557]",
"tests/test_price_parsing.py::test_parsing[example558]",
"tests/test_price_parsing.py::test_parsing[example559]",
"tests/test_price_parsing.py::test_parsing[example560]",
"tests/test_price_parsing.py::test_parsing[example561]",
"tests/test_price_parsing.py::test_parsing[example562]",
"tests/test_price_parsing.py::test_parsing[example563]",
"tests/test_price_parsing.py::test_parsing[example564]",
"tests/test_price_parsing.py::test_parsing[example565]",
"tests/test_price_parsing.py::test_parsing[example566]",
"tests/test_price_parsing.py::test_parsing[example567]",
"tests/test_price_parsing.py::test_parsing[example568]",
"tests/test_price_parsing.py::test_parsing[example569]",
"tests/test_price_parsing.py::test_parsing[example570]",
"tests/test_price_parsing.py::test_parsing[example571]",
"tests/test_price_parsing.py::test_parsing[example572]",
"tests/test_price_parsing.py::test_parsing[example573]",
"tests/test_price_parsing.py::test_parsing[example574]",
"tests/test_price_parsing.py::test_parsing[example575]",
"tests/test_price_parsing.py::test_parsing[example576]",
"tests/test_price_parsing.py::test_parsing[example577]",
"tests/test_price_parsing.py::test_parsing[example578]",
"tests/test_price_parsing.py::test_parsing[example579]",
"tests/test_price_parsing.py::test_parsing[example580]",
"tests/test_price_parsing.py::test_parsing[example581]",
"tests/test_price_parsing.py::test_parsing[example582]",
"tests/test_price_parsing.py::test_parsing[example583]",
"tests/test_price_parsing.py::test_parsing[example584]",
"tests/test_price_parsing.py::test_parsing[example585]",
"tests/test_price_parsing.py::test_parsing[example586]",
"tests/test_price_parsing.py::test_parsing[example587]",
"tests/test_price_parsing.py::test_parsing[example588]",
"tests/test_price_parsing.py::test_parsing[example589]",
"tests/test_price_parsing.py::test_parsing[example590]",
"tests/test_price_parsing.py::test_parsing[example591]",
"tests/test_price_parsing.py::test_parsing[example592]",
"tests/test_price_parsing.py::test_parsing[example593]",
"tests/test_price_parsing.py::test_parsing[example594]",
"tests/test_price_parsing.py::test_parsing[example595]",
"tests/test_price_parsing.py::test_parsing[example596]",
"tests/test_price_parsing.py::test_parsing[example597]",
"tests/test_price_parsing.py::test_parsing[example598]",
"tests/test_price_parsing.py::test_parsing[example599]",
"tests/test_price_parsing.py::test_parsing[example600]",
"tests/test_price_parsing.py::test_parsing[example601]",
"tests/test_price_parsing.py::test_parsing[example602]",
"tests/test_price_parsing.py::test_parsing[example603]",
"tests/test_price_parsing.py::test_parsing[example604]",
"tests/test_price_parsing.py::test_parsing[example605]",
"tests/test_price_parsing.py::test_parsing[example606]",
"tests/test_price_parsing.py::test_parsing[example607]",
"tests/test_price_parsing.py::test_parsing[example608]",
"tests/test_price_parsing.py::test_parsing[example609]",
"tests/test_price_parsing.py::test_parsing[example610]",
"tests/test_price_parsing.py::test_parsing[example611]",
"tests/test_price_parsing.py::test_parsing[example612]",
"tests/test_price_parsing.py::test_parsing[example613]",
"tests/test_price_parsing.py::test_parsing[example614]",
"tests/test_price_parsing.py::test_parsing[example615]",
"tests/test_price_parsing.py::test_parsing[example616]",
"tests/test_price_parsing.py::test_parsing[example617]",
"tests/test_price_parsing.py::test_parsing[example618]",
"tests/test_price_parsing.py::test_parsing[example619]",
"tests/test_price_parsing.py::test_parsing[example620]",
"tests/test_price_parsing.py::test_parsing[example621]",
"tests/test_price_parsing.py::test_parsing[example622]",
"tests/test_price_parsing.py::test_parsing[example623]",
"tests/test_price_parsing.py::test_parsing[example624]",
"tests/test_price_parsing.py::test_parsing[example625]",
"tests/test_price_parsing.py::test_parsing[example626]",
"tests/test_price_parsing.py::test_parsing[example627]",
"tests/test_price_parsing.py::test_parsing[example628]",
"tests/test_price_parsing.py::test_parsing[example629]",
"tests/test_price_parsing.py::test_parsing[example630]",
"tests/test_price_parsing.py::test_parsing[example631]",
"tests/test_price_parsing.py::test_parsing[example632]",
"tests/test_price_parsing.py::test_parsing[example633]",
"tests/test_price_parsing.py::test_parsing[example634]",
"tests/test_price_parsing.py::test_parsing[example635]",
"tests/test_price_parsing.py::test_parsing[example636]",
"tests/test_price_parsing.py::test_parsing[example637]",
"tests/test_price_parsing.py::test_parsing[example638]",
"tests/test_price_parsing.py::test_parsing[example639]",
"tests/test_price_parsing.py::test_parsing[example640]",
"tests/test_price_parsing.py::test_parsing[example641]",
"tests/test_price_parsing.py::test_parsing[example642]",
"tests/test_price_parsing.py::test_parsing[example643]",
"tests/test_price_parsing.py::test_parsing[example644]",
"tests/test_price_parsing.py::test_parsing[example645]",
"tests/test_price_parsing.py::test_parsing[example646]",
"tests/test_price_parsing.py::test_parsing[example647]",
"tests/test_price_parsing.py::test_parsing[example648]",
"tests/test_price_parsing.py::test_parsing[example649]",
"tests/test_price_parsing.py::test_parsing[example650]",
"tests/test_price_parsing.py::test_parsing[example651]",
"tests/test_price_parsing.py::test_parsing[example652]",
"tests/test_price_parsing.py::test_parsing[example653]",
"tests/test_price_parsing.py::test_parsing[example654]",
"tests/test_price_parsing.py::test_parsing[example655]",
"tests/test_price_parsing.py::test_parsing[example656]",
"tests/test_price_parsing.py::test_parsing[example657]",
"tests/test_price_parsing.py::test_parsing[example658]",
"tests/test_price_parsing.py::test_parsing[example659]",
"tests/test_price_parsing.py::test_parsing[example660]",
"tests/test_price_parsing.py::test_parsing[example661]",
"tests/test_price_parsing.py::test_parsing[example662]",
"tests/test_price_parsing.py::test_parsing[example663]",
"tests/test_price_parsing.py::test_parsing[example664]",
"tests/test_price_parsing.py::test_parsing[example665]",
"tests/test_price_parsing.py::test_parsing[example666]",
"tests/test_price_parsing.py::test_parsing[example667]",
"tests/test_price_parsing.py::test_parsing[example668]",
"tests/test_price_parsing.py::test_parsing[example669]",
"tests/test_price_parsing.py::test_parsing[example670]",
"tests/test_price_parsing.py::test_parsing[example671]",
"tests/test_price_parsing.py::test_parsing[example672]",
"tests/test_price_parsing.py::test_parsing[example673]",
"tests/test_price_parsing.py::test_parsing[example674]",
"tests/test_price_parsing.py::test_parsing[example675]",
"tests/test_price_parsing.py::test_parsing[example676]",
"tests/test_price_parsing.py::test_parsing[example677]",
"tests/test_price_parsing.py::test_parsing[example678]",
"tests/test_price_parsing.py::test_parsing[example679]",
"tests/test_price_parsing.py::test_parsing[example680]",
"tests/test_price_parsing.py::test_parsing[example681]",
"tests/test_price_parsing.py::test_parsing[example682]",
"tests/test_price_parsing.py::test_parsing[example683]",
"tests/test_price_parsing.py::test_parsing[example684]",
"tests/test_price_parsing.py::test_parsing[example685]",
"tests/test_price_parsing.py::test_parsing[example686]",
"tests/test_price_parsing.py::test_parsing[example687]",
"tests/test_price_parsing.py::test_parsing[example688]",
"tests/test_price_parsing.py::test_parsing[example689]",
"tests/test_price_parsing.py::test_parsing[example690]",
"tests/test_price_parsing.py::test_parsing[example691]",
"tests/test_price_parsing.py::test_parsing[example692]",
"tests/test_price_parsing.py::test_parsing[example693]",
"tests/test_price_parsing.py::test_parsing[example694]",
"tests/test_price_parsing.py::test_parsing[example695]",
"tests/test_price_parsing.py::test_parsing[example696]",
"tests/test_price_parsing.py::test_parsing[example697]",
"tests/test_price_parsing.py::test_parsing[example698]",
"tests/test_price_parsing.py::test_parsing[example699]",
"tests/test_price_parsing.py::test_parsing[example700]",
"tests/test_price_parsing.py::test_parsing[example701]",
"tests/test_price_parsing.py::test_parsing[example702]",
"tests/test_price_parsing.py::test_parsing[example703]",
"tests/test_price_parsing.py::test_parsing[example704]",
"tests/test_price_parsing.py::test_parsing[example705]",
"tests/test_price_parsing.py::test_parsing[example706]",
"tests/test_price_parsing.py::test_parsing[example707]",
"tests/test_price_parsing.py::test_parsing[example708]",
"tests/test_price_parsing.py::test_parsing[example709]",
"tests/test_price_parsing.py::test_parsing[example710]",
"tests/test_price_parsing.py::test_parsing[example711]",
"tests/test_price_parsing.py::test_parsing[example712]",
"tests/test_price_parsing.py::test_parsing[example713]",
"tests/test_price_parsing.py::test_parsing[example714]",
"tests/test_price_parsing.py::test_parsing[example715]",
"tests/test_price_parsing.py::test_parsing[example716]",
"tests/test_price_parsing.py::test_parsing[example717]",
"tests/test_price_parsing.py::test_parsing[example718]",
"tests/test_price_parsing.py::test_parsing[example719]",
"tests/test_price_parsing.py::test_parsing[example720]",
"tests/test_price_parsing.py::test_parsing[example721]",
"tests/test_price_parsing.py::test_parsing[example722]",
"tests/test_price_parsing.py::test_parsing[example723]",
"tests/test_price_parsing.py::test_parsing[example724]",
"tests/test_price_parsing.py::test_parsing[example725]",
"tests/test_price_parsing.py::test_parsing[example726]",
"tests/test_price_parsing.py::test_parsing[example727]",
"tests/test_price_parsing.py::test_parsing[example728]",
"tests/test_price_parsing.py::test_parsing[example729]",
"tests/test_price_parsing.py::test_parsing[example730]",
"tests/test_price_parsing.py::test_parsing[example731]",
"tests/test_price_parsing.py::test_parsing[example732]",
"tests/test_price_parsing.py::test_parsing[example733]",
"tests/test_price_parsing.py::test_parsing[example734]",
"tests/test_price_parsing.py::test_parsing[example735]",
"tests/test_price_parsing.py::test_parsing[example736]",
"tests/test_price_parsing.py::test_parsing[example737]",
"tests/test_price_parsing.py::test_parsing[example738]",
"tests/test_price_parsing.py::test_parsing[example739]",
"tests/test_price_parsing.py::test_parsing[example740]",
"tests/test_price_parsing.py::test_parsing[example741]",
"tests/test_price_parsing.py::test_parsing[example742]",
"tests/test_price_parsing.py::test_parsing[example743]",
"tests/test_price_parsing.py::test_parsing[example744]",
"tests/test_price_parsing.py::test_parsing[example745]",
"tests/test_price_parsing.py::test_parsing[example746]",
"tests/test_price_parsing.py::test_parsing[example747]",
"tests/test_price_parsing.py::test_parsing[example748]",
"tests/test_price_parsing.py::test_parsing[example749]",
"tests/test_price_parsing.py::test_parsing[example750]",
"tests/test_price_parsing.py::test_parsing[example751]",
"tests/test_price_parsing.py::test_parsing[example752]",
"tests/test_price_parsing.py::test_parsing[example753]",
"tests/test_price_parsing.py::test_parsing[example754]",
"tests/test_price_parsing.py::test_parsing[example755]",
"tests/test_price_parsing.py::test_parsing[example756]",
"tests/test_price_parsing.py::test_parsing[example757]",
"tests/test_price_parsing.py::test_parsing[example758]",
"tests/test_price_parsing.py::test_parsing[example759]",
"tests/test_price_parsing.py::test_parsing[example760]",
"tests/test_price_parsing.py::test_parsing[example761]",
"tests/test_price_parsing.py::test_parsing[example762]",
"tests/test_price_parsing.py::test_parsing[example763]",
"tests/test_price_parsing.py::test_parsing[example764]",
"tests/test_price_parsing.py::test_parsing[example765]",
"tests/test_price_parsing.py::test_parsing[example766]",
"tests/test_price_parsing.py::test_parsing[example767]",
"tests/test_price_parsing.py::test_parsing[example768]",
"tests/test_price_parsing.py::test_parsing[example769]",
"tests/test_price_parsing.py::test_parsing[example770]",
"tests/test_price_parsing.py::test_parsing[example771]",
"tests/test_price_parsing.py::test_parsing[example772]",
"tests/test_price_parsing.py::test_parsing[example773]",
"tests/test_price_parsing.py::test_parsing[example774]",
"tests/test_price_parsing.py::test_parsing[example775]",
"tests/test_price_parsing.py::test_parsing[example776]",
"tests/test_price_parsing.py::test_parsing[example777]",
"tests/test_price_parsing.py::test_parsing[example778]",
"tests/test_price_parsing.py::test_parsing[example779]",
"tests/test_price_parsing.py::test_parsing[example780]",
"tests/test_price_parsing.py::test_parsing[example781]",
"tests/test_price_parsing.py::test_parsing[example782]",
"tests/test_price_parsing.py::test_parsing[example783]",
"tests/test_price_parsing.py::test_parsing[example784]",
"tests/test_price_parsing.py::test_parsing[example785]",
"tests/test_price_parsing.py::test_parsing[example786]",
"tests/test_price_parsing.py::test_parsing[example787]",
"tests/test_price_parsing.py::test_parsing[example788]",
"tests/test_price_parsing.py::test_parsing[example789]",
"tests/test_price_parsing.py::test_parsing[example790]",
"tests/test_price_parsing.py::test_parsing[example791]",
"tests/test_price_parsing.py::test_parsing[example792]",
"tests/test_price_parsing.py::test_parsing[example793]",
"tests/test_price_parsing.py::test_parsing[example794]",
"tests/test_price_parsing.py::test_parsing[example795]",
"tests/test_price_parsing.py::test_parsing[example796]",
"tests/test_price_parsing.py::test_parsing[example797]",
"tests/test_price_parsing.py::test_parsing[example798]",
"tests/test_price_parsing.py::test_parsing[example799]",
"tests/test_price_parsing.py::test_parsing[example800]",
"tests/test_price_parsing.py::test_parsing[example801]",
"tests/test_price_parsing.py::test_parsing[example802]",
"tests/test_price_parsing.py::test_parsing[example803]",
"tests/test_price_parsing.py::test_parsing[example804]",
"tests/test_price_parsing.py::test_parsing[example805]",
"tests/test_price_parsing.py::test_parsing[example806]",
"tests/test_price_parsing.py::test_parsing[example807]",
"tests/test_price_parsing.py::test_parsing[example808]",
"tests/test_price_parsing.py::test_parsing[example809]",
"tests/test_price_parsing.py::test_parsing[example810]",
"tests/test_price_parsing.py::test_parsing[example811]",
"tests/test_price_parsing.py::test_parsing[example812]",
"tests/test_price_parsing.py::test_parsing[example813]",
"tests/test_price_parsing.py::test_parsing[example814]",
"tests/test_price_parsing.py::test_parsing[example815]",
"tests/test_price_parsing.py::test_parsing[example816]",
"tests/test_price_parsing.py::test_parsing[example817]",
"tests/test_price_parsing.py::test_parsing[example818]",
"tests/test_price_parsing.py::test_parsing[example819]",
"tests/test_price_parsing.py::test_parsing[example820]",
"tests/test_price_parsing.py::test_parsing[example821]",
"tests/test_price_parsing.py::test_parsing[example822]",
"tests/test_price_parsing.py::test_parsing[example823]",
"tests/test_price_parsing.py::test_parsing[example824]",
"tests/test_price_parsing.py::test_parsing[example825]",
"tests/test_price_parsing.py::test_parsing[example826]",
"tests/test_price_parsing.py::test_parsing[example827]",
"tests/test_price_parsing.py::test_parsing[example828]",
"tests/test_price_parsing.py::test_parsing[example829]",
"tests/test_price_parsing.py::test_parsing[example830]",
"tests/test_price_parsing.py::test_parsing[example831]",
"tests/test_price_parsing.py::test_parsing[example832]",
"tests/test_price_parsing.py::test_parsing[example833]",
"tests/test_price_parsing.py::test_parsing[example834]",
"tests/test_price_parsing.py::test_parsing[example835]",
"tests/test_price_parsing.py::test_parsing[example836]",
"tests/test_price_parsing.py::test_parsing[example837]",
"tests/test_price_parsing.py::test_parsing[example838]",
"tests/test_price_parsing.py::test_parsing[example839]",
"tests/test_price_parsing.py::test_parsing[example840]",
"tests/test_price_parsing.py::test_parsing[example841]",
"tests/test_price_parsing.py::test_parsing[example842]",
"tests/test_price_parsing.py::test_parsing[example843]",
"tests/test_price_parsing.py::test_parsing[example844]",
"tests/test_price_parsing.py::test_parsing[example845]",
"tests/test_price_parsing.py::test_parsing[example846]",
"tests/test_price_parsing.py::test_parsing[example847]",
"tests/test_price_parsing.py::test_parsing[example848]",
"tests/test_price_parsing.py::test_parsing[example849]",
"tests/test_price_parsing.py::test_parsing[example850]",
"tests/test_price_parsing.py::test_parsing[example851]",
"tests/test_price_parsing.py::test_parsing[example852]",
"tests/test_price_parsing.py::test_parsing[example853]",
"tests/test_price_parsing.py::test_parsing[example854]",
"tests/test_price_parsing.py::test_parsing[example855]",
"tests/test_price_parsing.py::test_parsing[example856]",
"tests/test_price_parsing.py::test_parsing[example857]",
"tests/test_price_parsing.py::test_parsing[example858]",
"tests/test_price_parsing.py::test_parsing[example859]",
"tests/test_price_parsing.py::test_parsing[example860]",
"tests/test_price_parsing.py::test_parsing[example861]",
"tests/test_price_parsing.py::test_parsing[example862]",
"tests/test_price_parsing.py::test_parsing[example863]",
"tests/test_price_parsing.py::test_parsing[example864]",
"tests/test_price_parsing.py::test_parsing[example865]",
"tests/test_price_parsing.py::test_parsing[example866]",
"tests/test_price_parsing.py::test_parsing[example867]",
"tests/test_price_parsing.py::test_parsing[example868]",
"tests/test_price_parsing.py::test_parsing[example869]",
"tests/test_price_parsing.py::test_parsing[example870]",
"tests/test_price_parsing.py::test_parsing[example871]",
"tests/test_price_parsing.py::test_parsing[example872]",
"tests/test_price_parsing.py::test_parsing[example873]",
"tests/test_price_parsing.py::test_parsing[example874]",
"tests/test_price_parsing.py::test_parsing[example875]",
"tests/test_price_parsing.py::test_parsing[example876]",
"tests/test_price_parsing.py::test_parsing[example877]",
"tests/test_price_parsing.py::test_parsing[example878]",
"tests/test_price_parsing.py::test_parsing[example879]",
"tests/test_price_parsing.py::test_parsing[example880]",
"tests/test_price_parsing.py::test_parsing[example881]",
"tests/test_price_parsing.py::test_parsing[example882]",
"tests/test_price_parsing.py::test_parsing[example883]",
"tests/test_price_parsing.py::test_parsing[example884]",
"tests/test_price_parsing.py::test_parsing[example885]",
"tests/test_price_parsing.py::test_parsing[example886]",
"tests/test_price_parsing.py::test_parsing[example887]",
"tests/test_price_parsing.py::test_parsing[example888]",
"tests/test_price_parsing.py::test_parsing[example889]",
"tests/test_price_parsing.py::test_parsing[example890]",
"tests/test_price_parsing.py::test_parsing[example891]",
"tests/test_price_parsing.py::test_parsing[example892]",
"tests/test_price_parsing.py::test_parsing[example893]",
"tests/test_price_parsing.py::test_parsing[example894]",
"tests/test_price_parsing.py::test_parsing[example895]",
"tests/test_price_parsing.py::test_parsing[example896]",
"tests/test_price_parsing.py::test_parsing[example897]",
"tests/test_price_parsing.py::test_parsing[example898]",
"tests/test_price_parsing.py::test_parsing[example899]",
"tests/test_price_parsing.py::test_parsing[example900]",
"tests/test_price_parsing.py::test_parsing[example901]",
"tests/test_price_parsing.py::test_parsing[example902]",
"tests/test_price_parsing.py::test_parsing[example903]",
"tests/test_price_parsing.py::test_parsing[example904]",
"tests/test_price_parsing.py::test_parsing[example905]",
"tests/test_price_parsing.py::test_parsing[example906]",
"tests/test_price_parsing.py::test_parsing[example907]",
"tests/test_price_parsing.py::test_parsing[example908]",
"tests/test_price_parsing.py::test_parsing[example909]",
"tests/test_price_parsing.py::test_parsing[example910]",
"tests/test_price_parsing.py::test_parsing[example911]",
"tests/test_price_parsing.py::test_parsing[example912]",
"tests/test_price_parsing.py::test_parsing[example913]",
"tests/test_price_parsing.py::test_parsing[example914]",
"tests/test_price_parsing.py::test_parsing[example915]",
"tests/test_price_parsing.py::test_parsing[example916]",
"tests/test_price_parsing.py::test_parsing[example917]",
"tests/test_price_parsing.py::test_parsing[example918]",
"tests/test_price_parsing.py::test_parsing[example919]",
"tests/test_price_parsing.py::test_price_amount_float[None-None]",
"tests/test_price_parsing.py::test_price_amount_float[amount1-1.23]",
"tests/test_price_parsing.py::test_price_decimal_separator[140.000-None-expected_result0]",
"tests/test_price_parsing.py::test_price_decimal_separator[140.000-,-expected_result1]",
"tests/test_price_parsing.py::test_price_decimal_separator[140.000-.-expected_result2]",
"tests/test_price_parsing.py::test_price_decimal_separator[140\\u20ac33-\\u20ac-expected_result3]",
"tests/test_price_parsing.py::test_price_decimal_separator[140,000\\u20ac33-\\u20ac-expected_result4]",
"tests/test_price_parsing.py::test_price_decimal_separator[140.000\\u20ac33-\\u20ac-expected_result5]"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2020-01-26 12:00:35+00:00
|
bsd-3-clause
| 5,392 |
|
scrapinghub__price-parser-42
|
diff --git a/price_parser/parser.py b/price_parser/parser.py
index 364ab2c..d1051e4 100644
--- a/price_parser/parser.py
+++ b/price_parser/parser.py
@@ -188,6 +188,8 @@ def extract_price_text(price: str) -> Optional[str]:
>>> extract_price_text("50%")
>>> extract_price_text("50")
'50'
+ >>> extract_price_text("$.75")
+ '.75'
"""
if price.count('€') == 1:
m = re.search(r"""
@@ -198,14 +200,20 @@ def extract_price_text(price: str) -> Optional[str]:
""", price, re.VERBOSE)
if m:
return m.group(0).replace(' ', '')
+
m = re.search(r"""
- (\d[\d\s.,]*) # number, probably with thousand separators
- \s*? # skip whitespace
- (?:[^%\d]|$) # capture next symbol - it shouldn't be %
+ ([.]?\d[\d\s.,]*) # number, probably with thousand separators
+ \s*? # skip whitespace
+ (?:[^%\d]|$) # capture next symbol - it shouldn't be %
""", price, re.VERBOSE)
if m:
- return m.group(1).strip(',.').strip()
+ price_text = m.group(1).rstrip(',.')
+ return (
+ price_text.strip()
+ if price_text.count('.') == 1
+ else price_text.lstrip(',.').strip()
+ )
if 'free' in price.lower():
return '0'
return None
@@ -213,7 +221,7 @@ def extract_price_text(price: str) -> Optional[str]:
# NOTE: Keep supported separators in sync with parse_number()
_search_decimal_sep = re.compile(r"""
-\d # at least one digit (there can be more before it)
+\d* # null or more digits (there can be more before it)
([.,€]) # decimal separator
(?: # 1,2 or 4+ digits. 3 digits is likely to be a thousand separator.
\d{1,2}?|
@@ -237,6 +245,8 @@ def get_decimal_separator(price: str) -> Optional[str]:
','
>>> get_decimal_separator("1,235€99")
'€'
+ >>> get_decimal_separator(".75")
+ '.'
"""
m = _search_decimal_sep(price)
if m:
|
scrapinghub/price-parser
|
4e5a9d3262e34d0746638ce7d5f799103a77fda7
|
diff --git a/tests/test_price_parsing.py b/tests/test_price_parsing.py
index 4aee1cc..8ef2b11 100644
--- a/tests/test_price_parsing.py
+++ b/tests/test_price_parsing.py
@@ -429,6 +429,16 @@ PRICE_PARSING_EXAMPLES = [
'€', '11,76', 11.76),
Example('$99.99', '$99.99',
'$', '99.99', 99.99),
+ Example(None, '.75 €',
+ '€', '.75', 0.75),
+ Example('$.75', '$.75',
+ '$', '.75', 0.75),
+ Example('$..75', '$..75',
+ '$', '.75', 0.75),
+ Example('$.75,333', '$.75,333',
+ '$', '.75,333', 75333),
+ Example('$.750.30', '$.750.30',
+ '$', '750.30', 750.30),
Example('i', 'i',
None, None, None),
]
@@ -1977,6 +1987,18 @@ PRICE_PARSING_DECIMAL_SEPARATOR_EXAMPLES = [
'€', '1250€60', 1250.60, "€"),
Example(None, '1250€600',
'€', '1250€600', 1250.600, "€"),
+ Example(None, '.75 €',
+ '€', '.75', 0.75, '.'),
+ Example('$.75', '$.75',
+ '$', '.75', 0.75, '.'),
+ Example('$..75', '$..75',
+ '$', '.75', 0.75, '.'),
+ Example('$..75,333', '$..75,333',
+ '$', '.75,333', 0.75333, '.'),
+ Example('$..75,333', '$..75,333',
+ '$', '.75,333', 75.333, ','),
+ Example('$.750.30', '$.750.30',
+ '$', '750.30', 750.30, '.')
]
|
Incorrect parsing when input doesn't contain digits before decimal point
'$ .75' is incorrectly parsed as 75
|
0.0
|
4e5a9d3262e34d0746638ce7d5f799103a77fda7
|
[
"tests/test_price_parsing.py::test_parsing[example183]",
"tests/test_price_parsing.py::test_parsing[example184]",
"tests/test_price_parsing.py::test_parsing[example185]",
"tests/test_price_parsing.py::test_parsing[example186]",
"tests/test_price_parsing.py::test_parsing[example925]",
"tests/test_price_parsing.py::test_parsing[example926]",
"tests/test_price_parsing.py::test_parsing[example927]",
"tests/test_price_parsing.py::test_parsing[example928]",
"tests/test_price_parsing.py::test_parsing[example929]"
] |
[
"tests/test_price_parsing.py::test_parsing[example0]",
"tests/test_price_parsing.py::test_parsing[example1]",
"tests/test_price_parsing.py::test_parsing[example2]",
"tests/test_price_parsing.py::test_parsing[example3]",
"tests/test_price_parsing.py::test_parsing[example4]",
"tests/test_price_parsing.py::test_parsing[example5]",
"tests/test_price_parsing.py::test_parsing[example6]",
"tests/test_price_parsing.py::test_parsing[example7]",
"tests/test_price_parsing.py::test_parsing[example8]",
"tests/test_price_parsing.py::test_parsing[example9]",
"tests/test_price_parsing.py::test_parsing[example10]",
"tests/test_price_parsing.py::test_parsing[example11]",
"tests/test_price_parsing.py::test_parsing[example12]",
"tests/test_price_parsing.py::test_parsing[example13]",
"tests/test_price_parsing.py::test_parsing[example14]",
"tests/test_price_parsing.py::test_parsing[example15]",
"tests/test_price_parsing.py::test_parsing[example16]",
"tests/test_price_parsing.py::test_parsing[example17]",
"tests/test_price_parsing.py::test_parsing[example18]",
"tests/test_price_parsing.py::test_parsing[example19]",
"tests/test_price_parsing.py::test_parsing[example20]",
"tests/test_price_parsing.py::test_parsing[example21]",
"tests/test_price_parsing.py::test_parsing[example22]",
"tests/test_price_parsing.py::test_parsing[example23]",
"tests/test_price_parsing.py::test_parsing[example24]",
"tests/test_price_parsing.py::test_parsing[example25]",
"tests/test_price_parsing.py::test_parsing[example26]",
"tests/test_price_parsing.py::test_parsing[example27]",
"tests/test_price_parsing.py::test_parsing[example28]",
"tests/test_price_parsing.py::test_parsing[example29]",
"tests/test_price_parsing.py::test_parsing[example30]",
"tests/test_price_parsing.py::test_parsing[example31]",
"tests/test_price_parsing.py::test_parsing[example32]",
"tests/test_price_parsing.py::test_parsing[example33]",
"tests/test_price_parsing.py::test_parsing[example34]",
"tests/test_price_parsing.py::test_parsing[example35]",
"tests/test_price_parsing.py::test_parsing[example36]",
"tests/test_price_parsing.py::test_parsing[example37]",
"tests/test_price_parsing.py::test_parsing[example38]",
"tests/test_price_parsing.py::test_parsing[example39]",
"tests/test_price_parsing.py::test_parsing[example40]",
"tests/test_price_parsing.py::test_parsing[example41]",
"tests/test_price_parsing.py::test_parsing[example42]",
"tests/test_price_parsing.py::test_parsing[example43]",
"tests/test_price_parsing.py::test_parsing[example44]",
"tests/test_price_parsing.py::test_parsing[example45]",
"tests/test_price_parsing.py::test_parsing[example46]",
"tests/test_price_parsing.py::test_parsing[example47]",
"tests/test_price_parsing.py::test_parsing[example48]",
"tests/test_price_parsing.py::test_parsing[example49]",
"tests/test_price_parsing.py::test_parsing[example50]",
"tests/test_price_parsing.py::test_parsing[example51]",
"tests/test_price_parsing.py::test_parsing[example52]",
"tests/test_price_parsing.py::test_parsing[example53]",
"tests/test_price_parsing.py::test_parsing[example54]",
"tests/test_price_parsing.py::test_parsing[example55]",
"tests/test_price_parsing.py::test_parsing[example56]",
"tests/test_price_parsing.py::test_parsing[example57]",
"tests/test_price_parsing.py::test_parsing[example58]",
"tests/test_price_parsing.py::test_parsing[example59]",
"tests/test_price_parsing.py::test_parsing[example60]",
"tests/test_price_parsing.py::test_parsing[example61]",
"tests/test_price_parsing.py::test_parsing[example62]",
"tests/test_price_parsing.py::test_parsing[example63]",
"tests/test_price_parsing.py::test_parsing[example64]",
"tests/test_price_parsing.py::test_parsing[example65]",
"tests/test_price_parsing.py::test_parsing[example66]",
"tests/test_price_parsing.py::test_parsing[example67]",
"tests/test_price_parsing.py::test_parsing[example68]",
"tests/test_price_parsing.py::test_parsing[example69]",
"tests/test_price_parsing.py::test_parsing[example70]",
"tests/test_price_parsing.py::test_parsing[example71]",
"tests/test_price_parsing.py::test_parsing[example72]",
"tests/test_price_parsing.py::test_parsing[example73]",
"tests/test_price_parsing.py::test_parsing[example74]",
"tests/test_price_parsing.py::test_parsing[example75]",
"tests/test_price_parsing.py::test_parsing[example76]",
"tests/test_price_parsing.py::test_parsing[example77]",
"tests/test_price_parsing.py::test_parsing[example78]",
"tests/test_price_parsing.py::test_parsing[example79]",
"tests/test_price_parsing.py::test_parsing[example80]",
"tests/test_price_parsing.py::test_parsing[example81]",
"tests/test_price_parsing.py::test_parsing[example82]",
"tests/test_price_parsing.py::test_parsing[example83]",
"tests/test_price_parsing.py::test_parsing[example84]",
"tests/test_price_parsing.py::test_parsing[example85]",
"tests/test_price_parsing.py::test_parsing[example86]",
"tests/test_price_parsing.py::test_parsing[example87]",
"tests/test_price_parsing.py::test_parsing[example88]",
"tests/test_price_parsing.py::test_parsing[example89]",
"tests/test_price_parsing.py::test_parsing[example90]",
"tests/test_price_parsing.py::test_parsing[example91]",
"tests/test_price_parsing.py::test_parsing[example92]",
"tests/test_price_parsing.py::test_parsing[example93]",
"tests/test_price_parsing.py::test_parsing[example94]",
"tests/test_price_parsing.py::test_parsing[example95]",
"tests/test_price_parsing.py::test_parsing[example96]",
"tests/test_price_parsing.py::test_parsing[example97]",
"tests/test_price_parsing.py::test_parsing[example98]",
"tests/test_price_parsing.py::test_parsing[example99]",
"tests/test_price_parsing.py::test_parsing[example100]",
"tests/test_price_parsing.py::test_parsing[example101]",
"tests/test_price_parsing.py::test_parsing[example102]",
"tests/test_price_parsing.py::test_parsing[example103]",
"tests/test_price_parsing.py::test_parsing[example104]",
"tests/test_price_parsing.py::test_parsing[example105]",
"tests/test_price_parsing.py::test_parsing[example106]",
"tests/test_price_parsing.py::test_parsing[example107]",
"tests/test_price_parsing.py::test_parsing[example108]",
"tests/test_price_parsing.py::test_parsing[example109]",
"tests/test_price_parsing.py::test_parsing[example110]",
"tests/test_price_parsing.py::test_parsing[example111]",
"tests/test_price_parsing.py::test_parsing[example112]",
"tests/test_price_parsing.py::test_parsing[example113]",
"tests/test_price_parsing.py::test_parsing[example114]",
"tests/test_price_parsing.py::test_parsing[example115]",
"tests/test_price_parsing.py::test_parsing[example116]",
"tests/test_price_parsing.py::test_parsing[example117]",
"tests/test_price_parsing.py::test_parsing[example118]",
"tests/test_price_parsing.py::test_parsing[example119]",
"tests/test_price_parsing.py::test_parsing[example120]",
"tests/test_price_parsing.py::test_parsing[example121]",
"tests/test_price_parsing.py::test_parsing[example122]",
"tests/test_price_parsing.py::test_parsing[example123]",
"tests/test_price_parsing.py::test_parsing[example124]",
"tests/test_price_parsing.py::test_parsing[example125]",
"tests/test_price_parsing.py::test_parsing[example126]",
"tests/test_price_parsing.py::test_parsing[example127]",
"tests/test_price_parsing.py::test_parsing[example128]",
"tests/test_price_parsing.py::test_parsing[example129]",
"tests/test_price_parsing.py::test_parsing[example130]",
"tests/test_price_parsing.py::test_parsing[example131]",
"tests/test_price_parsing.py::test_parsing[example132]",
"tests/test_price_parsing.py::test_parsing[example133]",
"tests/test_price_parsing.py::test_parsing[example134]",
"tests/test_price_parsing.py::test_parsing[example135]",
"tests/test_price_parsing.py::test_parsing[example136]",
"tests/test_price_parsing.py::test_parsing[example137]",
"tests/test_price_parsing.py::test_parsing[example138]",
"tests/test_price_parsing.py::test_parsing[example139]",
"tests/test_price_parsing.py::test_parsing[example140]",
"tests/test_price_parsing.py::test_parsing[example141]",
"tests/test_price_parsing.py::test_parsing[example142]",
"tests/test_price_parsing.py::test_parsing[example143]",
"tests/test_price_parsing.py::test_parsing[example144]",
"tests/test_price_parsing.py::test_parsing[example145]",
"tests/test_price_parsing.py::test_parsing[example146]",
"tests/test_price_parsing.py::test_parsing[example147]",
"tests/test_price_parsing.py::test_parsing[example148]",
"tests/test_price_parsing.py::test_parsing[example149]",
"tests/test_price_parsing.py::test_parsing[example150]",
"tests/test_price_parsing.py::test_parsing[example151]",
"tests/test_price_parsing.py::test_parsing[example152]",
"tests/test_price_parsing.py::test_parsing[example153]",
"tests/test_price_parsing.py::test_parsing[example154]",
"tests/test_price_parsing.py::test_parsing[example155]",
"tests/test_price_parsing.py::test_parsing[example156]",
"tests/test_price_parsing.py::test_parsing[example157]",
"tests/test_price_parsing.py::test_parsing[example158]",
"tests/test_price_parsing.py::test_parsing[example159]",
"tests/test_price_parsing.py::test_parsing[example160]",
"tests/test_price_parsing.py::test_parsing[example161]",
"tests/test_price_parsing.py::test_parsing[example162]",
"tests/test_price_parsing.py::test_parsing[example163]",
"tests/test_price_parsing.py::test_parsing[example164]",
"tests/test_price_parsing.py::test_parsing[example165]",
"tests/test_price_parsing.py::test_parsing[example166]",
"tests/test_price_parsing.py::test_parsing[example167]",
"tests/test_price_parsing.py::test_parsing[example168]",
"tests/test_price_parsing.py::test_parsing[example169]",
"tests/test_price_parsing.py::test_parsing[example170]",
"tests/test_price_parsing.py::test_parsing[example171]",
"tests/test_price_parsing.py::test_parsing[example172]",
"tests/test_price_parsing.py::test_parsing[example173]",
"tests/test_price_parsing.py::test_parsing[example174]",
"tests/test_price_parsing.py::test_parsing[example175]",
"tests/test_price_parsing.py::test_parsing[example176]",
"tests/test_price_parsing.py::test_parsing[example177]",
"tests/test_price_parsing.py::test_parsing[example178]",
"tests/test_price_parsing.py::test_parsing[example179]",
"tests/test_price_parsing.py::test_parsing[example180]",
"tests/test_price_parsing.py::test_parsing[example181]",
"tests/test_price_parsing.py::test_parsing[example182]",
"tests/test_price_parsing.py::test_parsing[example187]",
"tests/test_price_parsing.py::test_parsing[example188]",
"tests/test_price_parsing.py::test_parsing[example189]",
"tests/test_price_parsing.py::test_parsing[example190]",
"tests/test_price_parsing.py::test_parsing[example191]",
"tests/test_price_parsing.py::test_parsing[example192]",
"tests/test_price_parsing.py::test_parsing[example193]",
"tests/test_price_parsing.py::test_parsing[example194]",
"tests/test_price_parsing.py::test_parsing[example195]",
"tests/test_price_parsing.py::test_parsing[example196]",
"tests/test_price_parsing.py::test_parsing[example197]",
"tests/test_price_parsing.py::test_parsing[example198]",
"tests/test_price_parsing.py::test_parsing[example199]",
"tests/test_price_parsing.py::test_parsing[example200]",
"tests/test_price_parsing.py::test_parsing[example201]",
"tests/test_price_parsing.py::test_parsing[example202]",
"tests/test_price_parsing.py::test_parsing[example203]",
"tests/test_price_parsing.py::test_parsing[example204]",
"tests/test_price_parsing.py::test_parsing[example205]",
"tests/test_price_parsing.py::test_parsing[example206]",
"tests/test_price_parsing.py::test_parsing[example207]",
"tests/test_price_parsing.py::test_parsing[example208]",
"tests/test_price_parsing.py::test_parsing[example209]",
"tests/test_price_parsing.py::test_parsing[example210]",
"tests/test_price_parsing.py::test_parsing[example211]",
"tests/test_price_parsing.py::test_parsing[example212]",
"tests/test_price_parsing.py::test_parsing[example213]",
"tests/test_price_parsing.py::test_parsing[example214]",
"tests/test_price_parsing.py::test_parsing[example215]",
"tests/test_price_parsing.py::test_parsing[example216]",
"tests/test_price_parsing.py::test_parsing[example217]",
"tests/test_price_parsing.py::test_parsing[example218]",
"tests/test_price_parsing.py::test_parsing[example219]",
"tests/test_price_parsing.py::test_parsing[example220]",
"tests/test_price_parsing.py::test_parsing[example221]",
"tests/test_price_parsing.py::test_parsing[example222]",
"tests/test_price_parsing.py::test_parsing[example223]",
"tests/test_price_parsing.py::test_parsing[example224]",
"tests/test_price_parsing.py::test_parsing[example225]",
"tests/test_price_parsing.py::test_parsing[example226]",
"tests/test_price_parsing.py::test_parsing[example227]",
"tests/test_price_parsing.py::test_parsing[example228]",
"tests/test_price_parsing.py::test_parsing[example229]",
"tests/test_price_parsing.py::test_parsing[example230]",
"tests/test_price_parsing.py::test_parsing[example231]",
"tests/test_price_parsing.py::test_parsing[example232]",
"tests/test_price_parsing.py::test_parsing[example233]",
"tests/test_price_parsing.py::test_parsing[example234]",
"tests/test_price_parsing.py::test_parsing[example235]",
"tests/test_price_parsing.py::test_parsing[example236]",
"tests/test_price_parsing.py::test_parsing[example237]",
"tests/test_price_parsing.py::test_parsing[example238]",
"tests/test_price_parsing.py::test_parsing[example239]",
"tests/test_price_parsing.py::test_parsing[example240]",
"tests/test_price_parsing.py::test_parsing[example241]",
"tests/test_price_parsing.py::test_parsing[example242]",
"tests/test_price_parsing.py::test_parsing[example243]",
"tests/test_price_parsing.py::test_parsing[example244]",
"tests/test_price_parsing.py::test_parsing[example245]",
"tests/test_price_parsing.py::test_parsing[example246]",
"tests/test_price_parsing.py::test_parsing[example247]",
"tests/test_price_parsing.py::test_parsing[example248]",
"tests/test_price_parsing.py::test_parsing[example249]",
"tests/test_price_parsing.py::test_parsing[example250]",
"tests/test_price_parsing.py::test_parsing[example251]",
"tests/test_price_parsing.py::test_parsing[example252]",
"tests/test_price_parsing.py::test_parsing[example253]",
"tests/test_price_parsing.py::test_parsing[example254]",
"tests/test_price_parsing.py::test_parsing[example255]",
"tests/test_price_parsing.py::test_parsing[example256]",
"tests/test_price_parsing.py::test_parsing[example257]",
"tests/test_price_parsing.py::test_parsing[example258]",
"tests/test_price_parsing.py::test_parsing[example259]",
"tests/test_price_parsing.py::test_parsing[example260]",
"tests/test_price_parsing.py::test_parsing[example261]",
"tests/test_price_parsing.py::test_parsing[example262]",
"tests/test_price_parsing.py::test_parsing[example263]",
"tests/test_price_parsing.py::test_parsing[example264]",
"tests/test_price_parsing.py::test_parsing[example265]",
"tests/test_price_parsing.py::test_parsing[example266]",
"tests/test_price_parsing.py::test_parsing[example267]",
"tests/test_price_parsing.py::test_parsing[example268]",
"tests/test_price_parsing.py::test_parsing[example269]",
"tests/test_price_parsing.py::test_parsing[example270]",
"tests/test_price_parsing.py::test_parsing[example271]",
"tests/test_price_parsing.py::test_parsing[example272]",
"tests/test_price_parsing.py::test_parsing[example273]",
"tests/test_price_parsing.py::test_parsing[example274]",
"tests/test_price_parsing.py::test_parsing[example275]",
"tests/test_price_parsing.py::test_parsing[example276]",
"tests/test_price_parsing.py::test_parsing[example277]",
"tests/test_price_parsing.py::test_parsing[example278]",
"tests/test_price_parsing.py::test_parsing[example279]",
"tests/test_price_parsing.py::test_parsing[example280]",
"tests/test_price_parsing.py::test_parsing[example281]",
"tests/test_price_parsing.py::test_parsing[example282]",
"tests/test_price_parsing.py::test_parsing[example283]",
"tests/test_price_parsing.py::test_parsing[example284]",
"tests/test_price_parsing.py::test_parsing[example285]",
"tests/test_price_parsing.py::test_parsing[example286]",
"tests/test_price_parsing.py::test_parsing[example287]",
"tests/test_price_parsing.py::test_parsing[example288]",
"tests/test_price_parsing.py::test_parsing[example289]",
"tests/test_price_parsing.py::test_parsing[example290]",
"tests/test_price_parsing.py::test_parsing[example291]",
"tests/test_price_parsing.py::test_parsing[example292]",
"tests/test_price_parsing.py::test_parsing[example293]",
"tests/test_price_parsing.py::test_parsing[example294]",
"tests/test_price_parsing.py::test_parsing[example295]",
"tests/test_price_parsing.py::test_parsing[example296]",
"tests/test_price_parsing.py::test_parsing[example297]",
"tests/test_price_parsing.py::test_parsing[example298]",
"tests/test_price_parsing.py::test_parsing[example299]",
"tests/test_price_parsing.py::test_parsing[example300]",
"tests/test_price_parsing.py::test_parsing[example301]",
"tests/test_price_parsing.py::test_parsing[example302]",
"tests/test_price_parsing.py::test_parsing[example303]",
"tests/test_price_parsing.py::test_parsing[example304]",
"tests/test_price_parsing.py::test_parsing[example305]",
"tests/test_price_parsing.py::test_parsing[example306]",
"tests/test_price_parsing.py::test_parsing[example307]",
"tests/test_price_parsing.py::test_parsing[example308]",
"tests/test_price_parsing.py::test_parsing[example309]",
"tests/test_price_parsing.py::test_parsing[example310]",
"tests/test_price_parsing.py::test_parsing[example311]",
"tests/test_price_parsing.py::test_parsing[example312]",
"tests/test_price_parsing.py::test_parsing[example313]",
"tests/test_price_parsing.py::test_parsing[example314]",
"tests/test_price_parsing.py::test_parsing[example315]",
"tests/test_price_parsing.py::test_parsing[example316]",
"tests/test_price_parsing.py::test_parsing[example317]",
"tests/test_price_parsing.py::test_parsing[example318]",
"tests/test_price_parsing.py::test_parsing[example319]",
"tests/test_price_parsing.py::test_parsing[example320]",
"tests/test_price_parsing.py::test_parsing[example321]",
"tests/test_price_parsing.py::test_parsing[example322]",
"tests/test_price_parsing.py::test_parsing[example323]",
"tests/test_price_parsing.py::test_parsing[example324]",
"tests/test_price_parsing.py::test_parsing[example325]",
"tests/test_price_parsing.py::test_parsing[example326]",
"tests/test_price_parsing.py::test_parsing[example327]",
"tests/test_price_parsing.py::test_parsing[example328]",
"tests/test_price_parsing.py::test_parsing[example329]",
"tests/test_price_parsing.py::test_parsing[example330]",
"tests/test_price_parsing.py::test_parsing[example331]",
"tests/test_price_parsing.py::test_parsing[example332]",
"tests/test_price_parsing.py::test_parsing[example333]",
"tests/test_price_parsing.py::test_parsing[example334]",
"tests/test_price_parsing.py::test_parsing[example335]",
"tests/test_price_parsing.py::test_parsing[example336]",
"tests/test_price_parsing.py::test_parsing[example337]",
"tests/test_price_parsing.py::test_parsing[example338]",
"tests/test_price_parsing.py::test_parsing[example339]",
"tests/test_price_parsing.py::test_parsing[example340]",
"tests/test_price_parsing.py::test_parsing[example341]",
"tests/test_price_parsing.py::test_parsing[example342]",
"tests/test_price_parsing.py::test_parsing[example343]",
"tests/test_price_parsing.py::test_parsing[example344]",
"tests/test_price_parsing.py::test_parsing[example345]",
"tests/test_price_parsing.py::test_parsing[example346]",
"tests/test_price_parsing.py::test_parsing[example347]",
"tests/test_price_parsing.py::test_parsing[example348]",
"tests/test_price_parsing.py::test_parsing[example349]",
"tests/test_price_parsing.py::test_parsing[example350]",
"tests/test_price_parsing.py::test_parsing[example351]",
"tests/test_price_parsing.py::test_parsing[example352]",
"tests/test_price_parsing.py::test_parsing[example353]",
"tests/test_price_parsing.py::test_parsing[example354]",
"tests/test_price_parsing.py::test_parsing[example355]",
"tests/test_price_parsing.py::test_parsing[example356]",
"tests/test_price_parsing.py::test_parsing[example357]",
"tests/test_price_parsing.py::test_parsing[example358]",
"tests/test_price_parsing.py::test_parsing[example359]",
"tests/test_price_parsing.py::test_parsing[example360]",
"tests/test_price_parsing.py::test_parsing[example361]",
"tests/test_price_parsing.py::test_parsing[example362]",
"tests/test_price_parsing.py::test_parsing[example363]",
"tests/test_price_parsing.py::test_parsing[example364]",
"tests/test_price_parsing.py::test_parsing[example365]",
"tests/test_price_parsing.py::test_parsing[example366]",
"tests/test_price_parsing.py::test_parsing[example367]",
"tests/test_price_parsing.py::test_parsing[example368]",
"tests/test_price_parsing.py::test_parsing[example369]",
"tests/test_price_parsing.py::test_parsing[example370]",
"tests/test_price_parsing.py::test_parsing[example371]",
"tests/test_price_parsing.py::test_parsing[example372]",
"tests/test_price_parsing.py::test_parsing[example373]",
"tests/test_price_parsing.py::test_parsing[example374]",
"tests/test_price_parsing.py::test_parsing[example375]",
"tests/test_price_parsing.py::test_parsing[example376]",
"tests/test_price_parsing.py::test_parsing[example377]",
"tests/test_price_parsing.py::test_parsing[example378]",
"tests/test_price_parsing.py::test_parsing[example379]",
"tests/test_price_parsing.py::test_parsing[example380]",
"tests/test_price_parsing.py::test_parsing[example381]",
"tests/test_price_parsing.py::test_parsing[example382]",
"tests/test_price_parsing.py::test_parsing[example383]",
"tests/test_price_parsing.py::test_parsing[example384]",
"tests/test_price_parsing.py::test_parsing[example385]",
"tests/test_price_parsing.py::test_parsing[example386]",
"tests/test_price_parsing.py::test_parsing[example387]",
"tests/test_price_parsing.py::test_parsing[example388]",
"tests/test_price_parsing.py::test_parsing[example389]",
"tests/test_price_parsing.py::test_parsing[example390]",
"tests/test_price_parsing.py::test_parsing[example391]",
"tests/test_price_parsing.py::test_parsing[example392]",
"tests/test_price_parsing.py::test_parsing[example393]",
"tests/test_price_parsing.py::test_parsing[example394]",
"tests/test_price_parsing.py::test_parsing[example395]",
"tests/test_price_parsing.py::test_parsing[example396]",
"tests/test_price_parsing.py::test_parsing[example397]",
"tests/test_price_parsing.py::test_parsing[example398]",
"tests/test_price_parsing.py::test_parsing[example399]",
"tests/test_price_parsing.py::test_parsing[example400]",
"tests/test_price_parsing.py::test_parsing[example401]",
"tests/test_price_parsing.py::test_parsing[example402]",
"tests/test_price_parsing.py::test_parsing[example403]",
"tests/test_price_parsing.py::test_parsing[example404]",
"tests/test_price_parsing.py::test_parsing[example405]",
"tests/test_price_parsing.py::test_parsing[example406]",
"tests/test_price_parsing.py::test_parsing[example407]",
"tests/test_price_parsing.py::test_parsing[example408]",
"tests/test_price_parsing.py::test_parsing[example409]",
"tests/test_price_parsing.py::test_parsing[example410]",
"tests/test_price_parsing.py::test_parsing[example411]",
"tests/test_price_parsing.py::test_parsing[example412]",
"tests/test_price_parsing.py::test_parsing[example413]",
"tests/test_price_parsing.py::test_parsing[example414]",
"tests/test_price_parsing.py::test_parsing[example415]",
"tests/test_price_parsing.py::test_parsing[example416]",
"tests/test_price_parsing.py::test_parsing[example417]",
"tests/test_price_parsing.py::test_parsing[example418]",
"tests/test_price_parsing.py::test_parsing[example419]",
"tests/test_price_parsing.py::test_parsing[example420]",
"tests/test_price_parsing.py::test_parsing[example421]",
"tests/test_price_parsing.py::test_parsing[example422]",
"tests/test_price_parsing.py::test_parsing[example423]",
"tests/test_price_parsing.py::test_parsing[example424]",
"tests/test_price_parsing.py::test_parsing[example425]",
"tests/test_price_parsing.py::test_parsing[example426]",
"tests/test_price_parsing.py::test_parsing[example427]",
"tests/test_price_parsing.py::test_parsing[example428]",
"tests/test_price_parsing.py::test_parsing[example429]",
"tests/test_price_parsing.py::test_parsing[example430]",
"tests/test_price_parsing.py::test_parsing[example431]",
"tests/test_price_parsing.py::test_parsing[example432]",
"tests/test_price_parsing.py::test_parsing[example433]",
"tests/test_price_parsing.py::test_parsing[example434]",
"tests/test_price_parsing.py::test_parsing[example435]",
"tests/test_price_parsing.py::test_parsing[example436]",
"tests/test_price_parsing.py::test_parsing[example437]",
"tests/test_price_parsing.py::test_parsing[example438]",
"tests/test_price_parsing.py::test_parsing[example439]",
"tests/test_price_parsing.py::test_parsing[example440]",
"tests/test_price_parsing.py::test_parsing[example441]",
"tests/test_price_parsing.py::test_parsing[example442]",
"tests/test_price_parsing.py::test_parsing[example443]",
"tests/test_price_parsing.py::test_parsing[example444]",
"tests/test_price_parsing.py::test_parsing[example445]",
"tests/test_price_parsing.py::test_parsing[example446]",
"tests/test_price_parsing.py::test_parsing[example447]",
"tests/test_price_parsing.py::test_parsing[example448]",
"tests/test_price_parsing.py::test_parsing[example449]",
"tests/test_price_parsing.py::test_parsing[example450]",
"tests/test_price_parsing.py::test_parsing[example451]",
"tests/test_price_parsing.py::test_parsing[example452]",
"tests/test_price_parsing.py::test_parsing[example453]",
"tests/test_price_parsing.py::test_parsing[example454]",
"tests/test_price_parsing.py::test_parsing[example455]",
"tests/test_price_parsing.py::test_parsing[example456]",
"tests/test_price_parsing.py::test_parsing[example457]",
"tests/test_price_parsing.py::test_parsing[example458]",
"tests/test_price_parsing.py::test_parsing[example459]",
"tests/test_price_parsing.py::test_parsing[example460]",
"tests/test_price_parsing.py::test_parsing[example461]",
"tests/test_price_parsing.py::test_parsing[example462]",
"tests/test_price_parsing.py::test_parsing[example463]",
"tests/test_price_parsing.py::test_parsing[example464]",
"tests/test_price_parsing.py::test_parsing[example465]",
"tests/test_price_parsing.py::test_parsing[example466]",
"tests/test_price_parsing.py::test_parsing[example467]",
"tests/test_price_parsing.py::test_parsing[example468]",
"tests/test_price_parsing.py::test_parsing[example469]",
"tests/test_price_parsing.py::test_parsing[example470]",
"tests/test_price_parsing.py::test_parsing[example471]",
"tests/test_price_parsing.py::test_parsing[example472]",
"tests/test_price_parsing.py::test_parsing[example473]",
"tests/test_price_parsing.py::test_parsing[example474]",
"tests/test_price_parsing.py::test_parsing[example475]",
"tests/test_price_parsing.py::test_parsing[example476]",
"tests/test_price_parsing.py::test_parsing[example477]",
"tests/test_price_parsing.py::test_parsing[example478]",
"tests/test_price_parsing.py::test_parsing[example479]",
"tests/test_price_parsing.py::test_parsing[example480]",
"tests/test_price_parsing.py::test_parsing[example481]",
"tests/test_price_parsing.py::test_parsing[example482]",
"tests/test_price_parsing.py::test_parsing[example483]",
"tests/test_price_parsing.py::test_parsing[example484]",
"tests/test_price_parsing.py::test_parsing[example485]",
"tests/test_price_parsing.py::test_parsing[example486]",
"tests/test_price_parsing.py::test_parsing[example487]",
"tests/test_price_parsing.py::test_parsing[example488]",
"tests/test_price_parsing.py::test_parsing[example489]",
"tests/test_price_parsing.py::test_parsing[example490]",
"tests/test_price_parsing.py::test_parsing[example491]",
"tests/test_price_parsing.py::test_parsing[example492]",
"tests/test_price_parsing.py::test_parsing[example493]",
"tests/test_price_parsing.py::test_parsing[example494]",
"tests/test_price_parsing.py::test_parsing[example495]",
"tests/test_price_parsing.py::test_parsing[example496]",
"tests/test_price_parsing.py::test_parsing[example497]",
"tests/test_price_parsing.py::test_parsing[example498]",
"tests/test_price_parsing.py::test_parsing[example499]",
"tests/test_price_parsing.py::test_parsing[example500]",
"tests/test_price_parsing.py::test_parsing[example501]",
"tests/test_price_parsing.py::test_parsing[example502]",
"tests/test_price_parsing.py::test_parsing[example503]",
"tests/test_price_parsing.py::test_parsing[example504]",
"tests/test_price_parsing.py::test_parsing[example505]",
"tests/test_price_parsing.py::test_parsing[example506]",
"tests/test_price_parsing.py::test_parsing[example507]",
"tests/test_price_parsing.py::test_parsing[example508]",
"tests/test_price_parsing.py::test_parsing[example509]",
"tests/test_price_parsing.py::test_parsing[example510]",
"tests/test_price_parsing.py::test_parsing[example511]",
"tests/test_price_parsing.py::test_parsing[example512]",
"tests/test_price_parsing.py::test_parsing[example513]",
"tests/test_price_parsing.py::test_parsing[example514]",
"tests/test_price_parsing.py::test_parsing[example515]",
"tests/test_price_parsing.py::test_parsing[example516]",
"tests/test_price_parsing.py::test_parsing[example517]",
"tests/test_price_parsing.py::test_parsing[example518]",
"tests/test_price_parsing.py::test_parsing[example519]",
"tests/test_price_parsing.py::test_parsing[example520]",
"tests/test_price_parsing.py::test_parsing[example521]",
"tests/test_price_parsing.py::test_parsing[example522]",
"tests/test_price_parsing.py::test_parsing[example523]",
"tests/test_price_parsing.py::test_parsing[example524]",
"tests/test_price_parsing.py::test_parsing[example525]",
"tests/test_price_parsing.py::test_parsing[example526]",
"tests/test_price_parsing.py::test_parsing[example527]",
"tests/test_price_parsing.py::test_parsing[example528]",
"tests/test_price_parsing.py::test_parsing[example529]",
"tests/test_price_parsing.py::test_parsing[example530]",
"tests/test_price_parsing.py::test_parsing[example531]",
"tests/test_price_parsing.py::test_parsing[example532]",
"tests/test_price_parsing.py::test_parsing[example533]",
"tests/test_price_parsing.py::test_parsing[example534]",
"tests/test_price_parsing.py::test_parsing[example535]",
"tests/test_price_parsing.py::test_parsing[example536]",
"tests/test_price_parsing.py::test_parsing[example537]",
"tests/test_price_parsing.py::test_parsing[example538]",
"tests/test_price_parsing.py::test_parsing[example539]",
"tests/test_price_parsing.py::test_parsing[example540]",
"tests/test_price_parsing.py::test_parsing[example541]",
"tests/test_price_parsing.py::test_parsing[example542]",
"tests/test_price_parsing.py::test_parsing[example543]",
"tests/test_price_parsing.py::test_parsing[example544]",
"tests/test_price_parsing.py::test_parsing[example545]",
"tests/test_price_parsing.py::test_parsing[example546]",
"tests/test_price_parsing.py::test_parsing[example547]",
"tests/test_price_parsing.py::test_parsing[example548]",
"tests/test_price_parsing.py::test_parsing[example549]",
"tests/test_price_parsing.py::test_parsing[example550]",
"tests/test_price_parsing.py::test_parsing[example551]",
"tests/test_price_parsing.py::test_parsing[example552]",
"tests/test_price_parsing.py::test_parsing[example553]",
"tests/test_price_parsing.py::test_parsing[example554]",
"tests/test_price_parsing.py::test_parsing[example555]",
"tests/test_price_parsing.py::test_parsing[example556]",
"tests/test_price_parsing.py::test_parsing[example557]",
"tests/test_price_parsing.py::test_parsing[example558]",
"tests/test_price_parsing.py::test_parsing[example559]",
"tests/test_price_parsing.py::test_parsing[example560]",
"tests/test_price_parsing.py::test_parsing[example561]",
"tests/test_price_parsing.py::test_parsing[example562]",
"tests/test_price_parsing.py::test_parsing[example563]",
"tests/test_price_parsing.py::test_parsing[example564]",
"tests/test_price_parsing.py::test_parsing[example565]",
"tests/test_price_parsing.py::test_parsing[example566]",
"tests/test_price_parsing.py::test_parsing[example567]",
"tests/test_price_parsing.py::test_parsing[example568]",
"tests/test_price_parsing.py::test_parsing[example569]",
"tests/test_price_parsing.py::test_parsing[example570]",
"tests/test_price_parsing.py::test_parsing[example571]",
"tests/test_price_parsing.py::test_parsing[example572]",
"tests/test_price_parsing.py::test_parsing[example573]",
"tests/test_price_parsing.py::test_parsing[example574]",
"tests/test_price_parsing.py::test_parsing[example575]",
"tests/test_price_parsing.py::test_parsing[example576]",
"tests/test_price_parsing.py::test_parsing[example577]",
"tests/test_price_parsing.py::test_parsing[example578]",
"tests/test_price_parsing.py::test_parsing[example579]",
"tests/test_price_parsing.py::test_parsing[example580]",
"tests/test_price_parsing.py::test_parsing[example581]",
"tests/test_price_parsing.py::test_parsing[example582]",
"tests/test_price_parsing.py::test_parsing[example583]",
"tests/test_price_parsing.py::test_parsing[example584]",
"tests/test_price_parsing.py::test_parsing[example585]",
"tests/test_price_parsing.py::test_parsing[example586]",
"tests/test_price_parsing.py::test_parsing[example587]",
"tests/test_price_parsing.py::test_parsing[example588]",
"tests/test_price_parsing.py::test_parsing[example589]",
"tests/test_price_parsing.py::test_parsing[example590]",
"tests/test_price_parsing.py::test_parsing[example591]",
"tests/test_price_parsing.py::test_parsing[example592]",
"tests/test_price_parsing.py::test_parsing[example593]",
"tests/test_price_parsing.py::test_parsing[example594]",
"tests/test_price_parsing.py::test_parsing[example595]",
"tests/test_price_parsing.py::test_parsing[example596]",
"tests/test_price_parsing.py::test_parsing[example597]",
"tests/test_price_parsing.py::test_parsing[example598]",
"tests/test_price_parsing.py::test_parsing[example599]",
"tests/test_price_parsing.py::test_parsing[example600]",
"tests/test_price_parsing.py::test_parsing[example601]",
"tests/test_price_parsing.py::test_parsing[example602]",
"tests/test_price_parsing.py::test_parsing[example603]",
"tests/test_price_parsing.py::test_parsing[example604]",
"tests/test_price_parsing.py::test_parsing[example605]",
"tests/test_price_parsing.py::test_parsing[example606]",
"tests/test_price_parsing.py::test_parsing[example607]",
"tests/test_price_parsing.py::test_parsing[example608]",
"tests/test_price_parsing.py::test_parsing[example609]",
"tests/test_price_parsing.py::test_parsing[example610]",
"tests/test_price_parsing.py::test_parsing[example611]",
"tests/test_price_parsing.py::test_parsing[example612]",
"tests/test_price_parsing.py::test_parsing[example613]",
"tests/test_price_parsing.py::test_parsing[example614]",
"tests/test_price_parsing.py::test_parsing[example615]",
"tests/test_price_parsing.py::test_parsing[example616]",
"tests/test_price_parsing.py::test_parsing[example617]",
"tests/test_price_parsing.py::test_parsing[example618]",
"tests/test_price_parsing.py::test_parsing[example619]",
"tests/test_price_parsing.py::test_parsing[example620]",
"tests/test_price_parsing.py::test_parsing[example621]",
"tests/test_price_parsing.py::test_parsing[example622]",
"tests/test_price_parsing.py::test_parsing[example623]",
"tests/test_price_parsing.py::test_parsing[example624]",
"tests/test_price_parsing.py::test_parsing[example625]",
"tests/test_price_parsing.py::test_parsing[example626]",
"tests/test_price_parsing.py::test_parsing[example627]",
"tests/test_price_parsing.py::test_parsing[example628]",
"tests/test_price_parsing.py::test_parsing[example629]",
"tests/test_price_parsing.py::test_parsing[example630]",
"tests/test_price_parsing.py::test_parsing[example631]",
"tests/test_price_parsing.py::test_parsing[example632]",
"tests/test_price_parsing.py::test_parsing[example633]",
"tests/test_price_parsing.py::test_parsing[example634]",
"tests/test_price_parsing.py::test_parsing[example635]",
"tests/test_price_parsing.py::test_parsing[example636]",
"tests/test_price_parsing.py::test_parsing[example637]",
"tests/test_price_parsing.py::test_parsing[example638]",
"tests/test_price_parsing.py::test_parsing[example639]",
"tests/test_price_parsing.py::test_parsing[example640]",
"tests/test_price_parsing.py::test_parsing[example641]",
"tests/test_price_parsing.py::test_parsing[example642]",
"tests/test_price_parsing.py::test_parsing[example643]",
"tests/test_price_parsing.py::test_parsing[example644]",
"tests/test_price_parsing.py::test_parsing[example645]",
"tests/test_price_parsing.py::test_parsing[example646]",
"tests/test_price_parsing.py::test_parsing[example647]",
"tests/test_price_parsing.py::test_parsing[example648]",
"tests/test_price_parsing.py::test_parsing[example649]",
"tests/test_price_parsing.py::test_parsing[example650]",
"tests/test_price_parsing.py::test_parsing[example651]",
"tests/test_price_parsing.py::test_parsing[example652]",
"tests/test_price_parsing.py::test_parsing[example653]",
"tests/test_price_parsing.py::test_parsing[example654]",
"tests/test_price_parsing.py::test_parsing[example655]",
"tests/test_price_parsing.py::test_parsing[example656]",
"tests/test_price_parsing.py::test_parsing[example657]",
"tests/test_price_parsing.py::test_parsing[example658]",
"tests/test_price_parsing.py::test_parsing[example659]",
"tests/test_price_parsing.py::test_parsing[example660]",
"tests/test_price_parsing.py::test_parsing[example661]",
"tests/test_price_parsing.py::test_parsing[example662]",
"tests/test_price_parsing.py::test_parsing[example663]",
"tests/test_price_parsing.py::test_parsing[example664]",
"tests/test_price_parsing.py::test_parsing[example665]",
"tests/test_price_parsing.py::test_parsing[example666]",
"tests/test_price_parsing.py::test_parsing[example667]",
"tests/test_price_parsing.py::test_parsing[example668]",
"tests/test_price_parsing.py::test_parsing[example669]",
"tests/test_price_parsing.py::test_parsing[example670]",
"tests/test_price_parsing.py::test_parsing[example671]",
"tests/test_price_parsing.py::test_parsing[example672]",
"tests/test_price_parsing.py::test_parsing[example673]",
"tests/test_price_parsing.py::test_parsing[example674]",
"tests/test_price_parsing.py::test_parsing[example675]",
"tests/test_price_parsing.py::test_parsing[example676]",
"tests/test_price_parsing.py::test_parsing[example677]",
"tests/test_price_parsing.py::test_parsing[example678]",
"tests/test_price_parsing.py::test_parsing[example679]",
"tests/test_price_parsing.py::test_parsing[example680]",
"tests/test_price_parsing.py::test_parsing[example681]",
"tests/test_price_parsing.py::test_parsing[example682]",
"tests/test_price_parsing.py::test_parsing[example683]",
"tests/test_price_parsing.py::test_parsing[example684]",
"tests/test_price_parsing.py::test_parsing[example685]",
"tests/test_price_parsing.py::test_parsing[example686]",
"tests/test_price_parsing.py::test_parsing[example687]",
"tests/test_price_parsing.py::test_parsing[example688]",
"tests/test_price_parsing.py::test_parsing[example689]",
"tests/test_price_parsing.py::test_parsing[example690]",
"tests/test_price_parsing.py::test_parsing[example691]",
"tests/test_price_parsing.py::test_parsing[example692]",
"tests/test_price_parsing.py::test_parsing[example693]",
"tests/test_price_parsing.py::test_parsing[example694]",
"tests/test_price_parsing.py::test_parsing[example695]",
"tests/test_price_parsing.py::test_parsing[example696]",
"tests/test_price_parsing.py::test_parsing[example697]",
"tests/test_price_parsing.py::test_parsing[example698]",
"tests/test_price_parsing.py::test_parsing[example699]",
"tests/test_price_parsing.py::test_parsing[example700]",
"tests/test_price_parsing.py::test_parsing[example701]",
"tests/test_price_parsing.py::test_parsing[example702]",
"tests/test_price_parsing.py::test_parsing[example703]",
"tests/test_price_parsing.py::test_parsing[example704]",
"tests/test_price_parsing.py::test_parsing[example705]",
"tests/test_price_parsing.py::test_parsing[example706]",
"tests/test_price_parsing.py::test_parsing[example707]",
"tests/test_price_parsing.py::test_parsing[example708]",
"tests/test_price_parsing.py::test_parsing[example709]",
"tests/test_price_parsing.py::test_parsing[example710]",
"tests/test_price_parsing.py::test_parsing[example711]",
"tests/test_price_parsing.py::test_parsing[example712]",
"tests/test_price_parsing.py::test_parsing[example713]",
"tests/test_price_parsing.py::test_parsing[example714]",
"tests/test_price_parsing.py::test_parsing[example715]",
"tests/test_price_parsing.py::test_parsing[example716]",
"tests/test_price_parsing.py::test_parsing[example717]",
"tests/test_price_parsing.py::test_parsing[example718]",
"tests/test_price_parsing.py::test_parsing[example719]",
"tests/test_price_parsing.py::test_parsing[example720]",
"tests/test_price_parsing.py::test_parsing[example721]",
"tests/test_price_parsing.py::test_parsing[example722]",
"tests/test_price_parsing.py::test_parsing[example723]",
"tests/test_price_parsing.py::test_parsing[example724]",
"tests/test_price_parsing.py::test_parsing[example725]",
"tests/test_price_parsing.py::test_parsing[example726]",
"tests/test_price_parsing.py::test_parsing[example727]",
"tests/test_price_parsing.py::test_parsing[example728]",
"tests/test_price_parsing.py::test_parsing[example729]",
"tests/test_price_parsing.py::test_parsing[example730]",
"tests/test_price_parsing.py::test_parsing[example731]",
"tests/test_price_parsing.py::test_parsing[example732]",
"tests/test_price_parsing.py::test_parsing[example733]",
"tests/test_price_parsing.py::test_parsing[example734]",
"tests/test_price_parsing.py::test_parsing[example735]",
"tests/test_price_parsing.py::test_parsing[example736]",
"tests/test_price_parsing.py::test_parsing[example737]",
"tests/test_price_parsing.py::test_parsing[example738]",
"tests/test_price_parsing.py::test_parsing[example739]",
"tests/test_price_parsing.py::test_parsing[example740]",
"tests/test_price_parsing.py::test_parsing[example741]",
"tests/test_price_parsing.py::test_parsing[example742]",
"tests/test_price_parsing.py::test_parsing[example743]",
"tests/test_price_parsing.py::test_parsing[example744]",
"tests/test_price_parsing.py::test_parsing[example745]",
"tests/test_price_parsing.py::test_parsing[example746]",
"tests/test_price_parsing.py::test_parsing[example747]",
"tests/test_price_parsing.py::test_parsing[example748]",
"tests/test_price_parsing.py::test_parsing[example749]",
"tests/test_price_parsing.py::test_parsing[example750]",
"tests/test_price_parsing.py::test_parsing[example751]",
"tests/test_price_parsing.py::test_parsing[example752]",
"tests/test_price_parsing.py::test_parsing[example753]",
"tests/test_price_parsing.py::test_parsing[example754]",
"tests/test_price_parsing.py::test_parsing[example755]",
"tests/test_price_parsing.py::test_parsing[example756]",
"tests/test_price_parsing.py::test_parsing[example757]",
"tests/test_price_parsing.py::test_parsing[example758]",
"tests/test_price_parsing.py::test_parsing[example759]",
"tests/test_price_parsing.py::test_parsing[example760]",
"tests/test_price_parsing.py::test_parsing[example761]",
"tests/test_price_parsing.py::test_parsing[example762]",
"tests/test_price_parsing.py::test_parsing[example763]",
"tests/test_price_parsing.py::test_parsing[example764]",
"tests/test_price_parsing.py::test_parsing[example765]",
"tests/test_price_parsing.py::test_parsing[example766]",
"tests/test_price_parsing.py::test_parsing[example767]",
"tests/test_price_parsing.py::test_parsing[example768]",
"tests/test_price_parsing.py::test_parsing[example769]",
"tests/test_price_parsing.py::test_parsing[example770]",
"tests/test_price_parsing.py::test_parsing[example771]",
"tests/test_price_parsing.py::test_parsing[example772]",
"tests/test_price_parsing.py::test_parsing[example773]",
"tests/test_price_parsing.py::test_parsing[example774]",
"tests/test_price_parsing.py::test_parsing[example775]",
"tests/test_price_parsing.py::test_parsing[example776]",
"tests/test_price_parsing.py::test_parsing[example777]",
"tests/test_price_parsing.py::test_parsing[example778]",
"tests/test_price_parsing.py::test_parsing[example779]",
"tests/test_price_parsing.py::test_parsing[example780]",
"tests/test_price_parsing.py::test_parsing[example781]",
"tests/test_price_parsing.py::test_parsing[example782]",
"tests/test_price_parsing.py::test_parsing[example783]",
"tests/test_price_parsing.py::test_parsing[example784]",
"tests/test_price_parsing.py::test_parsing[example785]",
"tests/test_price_parsing.py::test_parsing[example786]",
"tests/test_price_parsing.py::test_parsing[example787]",
"tests/test_price_parsing.py::test_parsing[example788]",
"tests/test_price_parsing.py::test_parsing[example789]",
"tests/test_price_parsing.py::test_parsing[example790]",
"tests/test_price_parsing.py::test_parsing[example791]",
"tests/test_price_parsing.py::test_parsing[example792]",
"tests/test_price_parsing.py::test_parsing[example793]",
"tests/test_price_parsing.py::test_parsing[example794]",
"tests/test_price_parsing.py::test_parsing[example795]",
"tests/test_price_parsing.py::test_parsing[example796]",
"tests/test_price_parsing.py::test_parsing[example797]",
"tests/test_price_parsing.py::test_parsing[example798]",
"tests/test_price_parsing.py::test_parsing[example799]",
"tests/test_price_parsing.py::test_parsing[example800]",
"tests/test_price_parsing.py::test_parsing[example801]",
"tests/test_price_parsing.py::test_parsing[example802]",
"tests/test_price_parsing.py::test_parsing[example803]",
"tests/test_price_parsing.py::test_parsing[example804]",
"tests/test_price_parsing.py::test_parsing[example805]",
"tests/test_price_parsing.py::test_parsing[example806]",
"tests/test_price_parsing.py::test_parsing[example807]",
"tests/test_price_parsing.py::test_parsing[example808]",
"tests/test_price_parsing.py::test_parsing[example809]",
"tests/test_price_parsing.py::test_parsing[example810]",
"tests/test_price_parsing.py::test_parsing[example811]",
"tests/test_price_parsing.py::test_parsing[example812]",
"tests/test_price_parsing.py::test_parsing[example813]",
"tests/test_price_parsing.py::test_parsing[example814]",
"tests/test_price_parsing.py::test_parsing[example815]",
"tests/test_price_parsing.py::test_parsing[example816]",
"tests/test_price_parsing.py::test_parsing[example817]",
"tests/test_price_parsing.py::test_parsing[example818]",
"tests/test_price_parsing.py::test_parsing[example819]",
"tests/test_price_parsing.py::test_parsing[example820]",
"tests/test_price_parsing.py::test_parsing[example821]",
"tests/test_price_parsing.py::test_parsing[example822]",
"tests/test_price_parsing.py::test_parsing[example823]",
"tests/test_price_parsing.py::test_parsing[example824]",
"tests/test_price_parsing.py::test_parsing[example825]",
"tests/test_price_parsing.py::test_parsing[example826]",
"tests/test_price_parsing.py::test_parsing[example827]",
"tests/test_price_parsing.py::test_parsing[example828]",
"tests/test_price_parsing.py::test_parsing[example829]",
"tests/test_price_parsing.py::test_parsing[example830]",
"tests/test_price_parsing.py::test_parsing[example831]",
"tests/test_price_parsing.py::test_parsing[example832]",
"tests/test_price_parsing.py::test_parsing[example833]",
"tests/test_price_parsing.py::test_parsing[example834]",
"tests/test_price_parsing.py::test_parsing[example835]",
"tests/test_price_parsing.py::test_parsing[example836]",
"tests/test_price_parsing.py::test_parsing[example837]",
"tests/test_price_parsing.py::test_parsing[example838]",
"tests/test_price_parsing.py::test_parsing[example839]",
"tests/test_price_parsing.py::test_parsing[example840]",
"tests/test_price_parsing.py::test_parsing[example841]",
"tests/test_price_parsing.py::test_parsing[example842]",
"tests/test_price_parsing.py::test_parsing[example843]",
"tests/test_price_parsing.py::test_parsing[example844]",
"tests/test_price_parsing.py::test_parsing[example845]",
"tests/test_price_parsing.py::test_parsing[example846]",
"tests/test_price_parsing.py::test_parsing[example847]",
"tests/test_price_parsing.py::test_parsing[example848]",
"tests/test_price_parsing.py::test_parsing[example849]",
"tests/test_price_parsing.py::test_parsing[example850]",
"tests/test_price_parsing.py::test_parsing[example851]",
"tests/test_price_parsing.py::test_parsing[example852]",
"tests/test_price_parsing.py::test_parsing[example853]",
"tests/test_price_parsing.py::test_parsing[example854]",
"tests/test_price_parsing.py::test_parsing[example855]",
"tests/test_price_parsing.py::test_parsing[example856]",
"tests/test_price_parsing.py::test_parsing[example857]",
"tests/test_price_parsing.py::test_parsing[example858]",
"tests/test_price_parsing.py::test_parsing[example859]",
"tests/test_price_parsing.py::test_parsing[example860]",
"tests/test_price_parsing.py::test_parsing[example861]",
"tests/test_price_parsing.py::test_parsing[example862]",
"tests/test_price_parsing.py::test_parsing[example863]",
"tests/test_price_parsing.py::test_parsing[example864]",
"tests/test_price_parsing.py::test_parsing[example865]",
"tests/test_price_parsing.py::test_parsing[example866]",
"tests/test_price_parsing.py::test_parsing[example867]",
"tests/test_price_parsing.py::test_parsing[example868]",
"tests/test_price_parsing.py::test_parsing[example869]",
"tests/test_price_parsing.py::test_parsing[example870]",
"tests/test_price_parsing.py::test_parsing[example871]",
"tests/test_price_parsing.py::test_parsing[example872]",
"tests/test_price_parsing.py::test_parsing[example873]",
"tests/test_price_parsing.py::test_parsing[example874]",
"tests/test_price_parsing.py::test_parsing[example875]",
"tests/test_price_parsing.py::test_parsing[example876]",
"tests/test_price_parsing.py::test_parsing[example877]",
"tests/test_price_parsing.py::test_parsing[example878]",
"tests/test_price_parsing.py::test_parsing[example879]",
"tests/test_price_parsing.py::test_parsing[example880]",
"tests/test_price_parsing.py::test_parsing[example881]",
"tests/test_price_parsing.py::test_parsing[example882]",
"tests/test_price_parsing.py::test_parsing[example883]",
"tests/test_price_parsing.py::test_parsing[example884]",
"tests/test_price_parsing.py::test_parsing[example885]",
"tests/test_price_parsing.py::test_parsing[example886]",
"tests/test_price_parsing.py::test_parsing[example887]",
"tests/test_price_parsing.py::test_parsing[example888]",
"tests/test_price_parsing.py::test_parsing[example889]",
"tests/test_price_parsing.py::test_parsing[example890]",
"tests/test_price_parsing.py::test_parsing[example891]",
"tests/test_price_parsing.py::test_parsing[example892]",
"tests/test_price_parsing.py::test_parsing[example893]",
"tests/test_price_parsing.py::test_parsing[example894]",
"tests/test_price_parsing.py::test_parsing[example895]",
"tests/test_price_parsing.py::test_parsing[example896]",
"tests/test_price_parsing.py::test_parsing[example897]",
"tests/test_price_parsing.py::test_parsing[example898]",
"tests/test_price_parsing.py::test_parsing[example899]",
"tests/test_price_parsing.py::test_parsing[example900]",
"tests/test_price_parsing.py::test_parsing[example901]",
"tests/test_price_parsing.py::test_parsing[example902]",
"tests/test_price_parsing.py::test_parsing[example903]",
"tests/test_price_parsing.py::test_parsing[example904]",
"tests/test_price_parsing.py::test_parsing[example905]",
"tests/test_price_parsing.py::test_parsing[example906]",
"tests/test_price_parsing.py::test_parsing[example907]",
"tests/test_price_parsing.py::test_parsing[example908]",
"tests/test_price_parsing.py::test_parsing[example909]",
"tests/test_price_parsing.py::test_parsing[example910]",
"tests/test_price_parsing.py::test_parsing[example911]",
"tests/test_price_parsing.py::test_parsing[example912]",
"tests/test_price_parsing.py::test_parsing[example913]",
"tests/test_price_parsing.py::test_parsing[example914]",
"tests/test_price_parsing.py::test_parsing[example915]",
"tests/test_price_parsing.py::test_parsing[example916]",
"tests/test_price_parsing.py::test_parsing[example917]",
"tests/test_price_parsing.py::test_parsing[example918]",
"tests/test_price_parsing.py::test_parsing[example919]",
"tests/test_price_parsing.py::test_parsing[example920]",
"tests/test_price_parsing.py::test_parsing[example921]",
"tests/test_price_parsing.py::test_parsing[example922]",
"tests/test_price_parsing.py::test_parsing[example923]",
"tests/test_price_parsing.py::test_parsing[example924]",
"tests/test_price_parsing.py::test_parsing[example930]",
"tests/test_price_parsing.py::test_price_amount_float[None-None]",
"tests/test_price_parsing.py::test_price_amount_float[amount1-1.23]",
"tests/test_price_parsing.py::test_price_decimal_separator[140.000-None-expected_result0]",
"tests/test_price_parsing.py::test_price_decimal_separator[140.000-,-expected_result1]",
"tests/test_price_parsing.py::test_price_decimal_separator[140.000-.-expected_result2]",
"tests/test_price_parsing.py::test_price_decimal_separator[140\\u20ac33-\\u20ac-expected_result3]",
"tests/test_price_parsing.py::test_price_decimal_separator[140,000\\u20ac33-\\u20ac-expected_result4]",
"tests/test_price_parsing.py::test_price_decimal_separator[140.000\\u20ac33-\\u20ac-expected_result5]"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-11-19 20:45:37+00:00
|
bsd-3-clause
| 5,393 |
|
scrapinghub__price-parser-43
|
diff --git a/price_parser/parser.py b/price_parser/parser.py
index d1051e4..94e9e9c 100644
--- a/price_parser/parser.py
+++ b/price_parser/parser.py
@@ -188,9 +188,13 @@ def extract_price_text(price: str) -> Optional[str]:
>>> extract_price_text("50%")
>>> extract_price_text("50")
'50'
+ >>> extract_price_text("$1\xa0298,00")
+ '1 298,00'
>>> extract_price_text("$.75")
'.75'
"""
+ price = re.sub(r'\s+', ' ', price) # clean initial text from non-breaking and extra spaces
+
if price.count('€') == 1:
m = re.search(r"""
[\d\s.,]*?\d # number, probably with thousand separators
|
scrapinghub/price-parser
|
7e368bff169b504d9fcb1dd852308e36d5b10f7b
|
diff --git a/tests/test_price_parsing.py b/tests/test_price_parsing.py
index 8ef2b11..a6b3c52 100644
--- a/tests/test_price_parsing.py
+++ b/tests/test_price_parsing.py
@@ -429,6 +429,12 @@ PRICE_PARSING_EXAMPLES = [
'€', '11,76', 11.76),
Example('$99.99', '$99.99',
'$', '99.99', 99.99),
+ Example('1\xa0298,00 €', '1\xa0298,00 €',
+ '€', '1 298,00', 1298.00),
+ Example('$1\xa0298,00', '$1\xa0298,00',
+ '$', '1 298,00', 1298.00),
+ Example('1\xa0298,00', '1\xa0298,00',
+ None, '1 298,00', 1298.00),
Example(None, '.75 €',
'€', '.75', 0.75),
Example('$.75', '$.75',
|
Bug non break space.
Some store show price with non-break space and parser return None.
|
0.0
|
7e368bff169b504d9fcb1dd852308e36d5b10f7b
|
[
"tests/test_price_parsing.py::test_parsing[example183]",
"tests/test_price_parsing.py::test_parsing[example184]",
"tests/test_price_parsing.py::test_parsing[example185]"
] |
[
"tests/test_price_parsing.py::test_parsing[example0]",
"tests/test_price_parsing.py::test_parsing[example1]",
"tests/test_price_parsing.py::test_parsing[example2]",
"tests/test_price_parsing.py::test_parsing[example3]",
"tests/test_price_parsing.py::test_parsing[example4]",
"tests/test_price_parsing.py::test_parsing[example5]",
"tests/test_price_parsing.py::test_parsing[example6]",
"tests/test_price_parsing.py::test_parsing[example7]",
"tests/test_price_parsing.py::test_parsing[example8]",
"tests/test_price_parsing.py::test_parsing[example9]",
"tests/test_price_parsing.py::test_parsing[example10]",
"tests/test_price_parsing.py::test_parsing[example11]",
"tests/test_price_parsing.py::test_parsing[example12]",
"tests/test_price_parsing.py::test_parsing[example13]",
"tests/test_price_parsing.py::test_parsing[example14]",
"tests/test_price_parsing.py::test_parsing[example15]",
"tests/test_price_parsing.py::test_parsing[example16]",
"tests/test_price_parsing.py::test_parsing[example17]",
"tests/test_price_parsing.py::test_parsing[example18]",
"tests/test_price_parsing.py::test_parsing[example19]",
"tests/test_price_parsing.py::test_parsing[example20]",
"tests/test_price_parsing.py::test_parsing[example21]",
"tests/test_price_parsing.py::test_parsing[example22]",
"tests/test_price_parsing.py::test_parsing[example23]",
"tests/test_price_parsing.py::test_parsing[example24]",
"tests/test_price_parsing.py::test_parsing[example25]",
"tests/test_price_parsing.py::test_parsing[example26]",
"tests/test_price_parsing.py::test_parsing[example27]",
"tests/test_price_parsing.py::test_parsing[example28]",
"tests/test_price_parsing.py::test_parsing[example29]",
"tests/test_price_parsing.py::test_parsing[example30]",
"tests/test_price_parsing.py::test_parsing[example31]",
"tests/test_price_parsing.py::test_parsing[example32]",
"tests/test_price_parsing.py::test_parsing[example33]",
"tests/test_price_parsing.py::test_parsing[example34]",
"tests/test_price_parsing.py::test_parsing[example35]",
"tests/test_price_parsing.py::test_parsing[example36]",
"tests/test_price_parsing.py::test_parsing[example37]",
"tests/test_price_parsing.py::test_parsing[example38]",
"tests/test_price_parsing.py::test_parsing[example39]",
"tests/test_price_parsing.py::test_parsing[example40]",
"tests/test_price_parsing.py::test_parsing[example41]",
"tests/test_price_parsing.py::test_parsing[example42]",
"tests/test_price_parsing.py::test_parsing[example43]",
"tests/test_price_parsing.py::test_parsing[example44]",
"tests/test_price_parsing.py::test_parsing[example45]",
"tests/test_price_parsing.py::test_parsing[example46]",
"tests/test_price_parsing.py::test_parsing[example47]",
"tests/test_price_parsing.py::test_parsing[example48]",
"tests/test_price_parsing.py::test_parsing[example49]",
"tests/test_price_parsing.py::test_parsing[example50]",
"tests/test_price_parsing.py::test_parsing[example51]",
"tests/test_price_parsing.py::test_parsing[example52]",
"tests/test_price_parsing.py::test_parsing[example53]",
"tests/test_price_parsing.py::test_parsing[example54]",
"tests/test_price_parsing.py::test_parsing[example55]",
"tests/test_price_parsing.py::test_parsing[example56]",
"tests/test_price_parsing.py::test_parsing[example57]",
"tests/test_price_parsing.py::test_parsing[example58]",
"tests/test_price_parsing.py::test_parsing[example59]",
"tests/test_price_parsing.py::test_parsing[example60]",
"tests/test_price_parsing.py::test_parsing[example61]",
"tests/test_price_parsing.py::test_parsing[example62]",
"tests/test_price_parsing.py::test_parsing[example63]",
"tests/test_price_parsing.py::test_parsing[example64]",
"tests/test_price_parsing.py::test_parsing[example65]",
"tests/test_price_parsing.py::test_parsing[example66]",
"tests/test_price_parsing.py::test_parsing[example67]",
"tests/test_price_parsing.py::test_parsing[example68]",
"tests/test_price_parsing.py::test_parsing[example69]",
"tests/test_price_parsing.py::test_parsing[example70]",
"tests/test_price_parsing.py::test_parsing[example71]",
"tests/test_price_parsing.py::test_parsing[example72]",
"tests/test_price_parsing.py::test_parsing[example73]",
"tests/test_price_parsing.py::test_parsing[example74]",
"tests/test_price_parsing.py::test_parsing[example75]",
"tests/test_price_parsing.py::test_parsing[example76]",
"tests/test_price_parsing.py::test_parsing[example77]",
"tests/test_price_parsing.py::test_parsing[example78]",
"tests/test_price_parsing.py::test_parsing[example79]",
"tests/test_price_parsing.py::test_parsing[example80]",
"tests/test_price_parsing.py::test_parsing[example81]",
"tests/test_price_parsing.py::test_parsing[example82]",
"tests/test_price_parsing.py::test_parsing[example83]",
"tests/test_price_parsing.py::test_parsing[example84]",
"tests/test_price_parsing.py::test_parsing[example85]",
"tests/test_price_parsing.py::test_parsing[example86]",
"tests/test_price_parsing.py::test_parsing[example87]",
"tests/test_price_parsing.py::test_parsing[example88]",
"tests/test_price_parsing.py::test_parsing[example89]",
"tests/test_price_parsing.py::test_parsing[example90]",
"tests/test_price_parsing.py::test_parsing[example91]",
"tests/test_price_parsing.py::test_parsing[example92]",
"tests/test_price_parsing.py::test_parsing[example93]",
"tests/test_price_parsing.py::test_parsing[example94]",
"tests/test_price_parsing.py::test_parsing[example95]",
"tests/test_price_parsing.py::test_parsing[example96]",
"tests/test_price_parsing.py::test_parsing[example97]",
"tests/test_price_parsing.py::test_parsing[example98]",
"tests/test_price_parsing.py::test_parsing[example99]",
"tests/test_price_parsing.py::test_parsing[example100]",
"tests/test_price_parsing.py::test_parsing[example101]",
"tests/test_price_parsing.py::test_parsing[example102]",
"tests/test_price_parsing.py::test_parsing[example103]",
"tests/test_price_parsing.py::test_parsing[example104]",
"tests/test_price_parsing.py::test_parsing[example105]",
"tests/test_price_parsing.py::test_parsing[example106]",
"tests/test_price_parsing.py::test_parsing[example107]",
"tests/test_price_parsing.py::test_parsing[example108]",
"tests/test_price_parsing.py::test_parsing[example109]",
"tests/test_price_parsing.py::test_parsing[example110]",
"tests/test_price_parsing.py::test_parsing[example111]",
"tests/test_price_parsing.py::test_parsing[example112]",
"tests/test_price_parsing.py::test_parsing[example113]",
"tests/test_price_parsing.py::test_parsing[example114]",
"tests/test_price_parsing.py::test_parsing[example115]",
"tests/test_price_parsing.py::test_parsing[example116]",
"tests/test_price_parsing.py::test_parsing[example117]",
"tests/test_price_parsing.py::test_parsing[example118]",
"tests/test_price_parsing.py::test_parsing[example119]",
"tests/test_price_parsing.py::test_parsing[example120]",
"tests/test_price_parsing.py::test_parsing[example121]",
"tests/test_price_parsing.py::test_parsing[example122]",
"tests/test_price_parsing.py::test_parsing[example123]",
"tests/test_price_parsing.py::test_parsing[example124]",
"tests/test_price_parsing.py::test_parsing[example125]",
"tests/test_price_parsing.py::test_parsing[example126]",
"tests/test_price_parsing.py::test_parsing[example127]",
"tests/test_price_parsing.py::test_parsing[example128]",
"tests/test_price_parsing.py::test_parsing[example129]",
"tests/test_price_parsing.py::test_parsing[example130]",
"tests/test_price_parsing.py::test_parsing[example131]",
"tests/test_price_parsing.py::test_parsing[example132]",
"tests/test_price_parsing.py::test_parsing[example133]",
"tests/test_price_parsing.py::test_parsing[example134]",
"tests/test_price_parsing.py::test_parsing[example135]",
"tests/test_price_parsing.py::test_parsing[example136]",
"tests/test_price_parsing.py::test_parsing[example137]",
"tests/test_price_parsing.py::test_parsing[example138]",
"tests/test_price_parsing.py::test_parsing[example139]",
"tests/test_price_parsing.py::test_parsing[example140]",
"tests/test_price_parsing.py::test_parsing[example141]",
"tests/test_price_parsing.py::test_parsing[example142]",
"tests/test_price_parsing.py::test_parsing[example143]",
"tests/test_price_parsing.py::test_parsing[example144]",
"tests/test_price_parsing.py::test_parsing[example145]",
"tests/test_price_parsing.py::test_parsing[example146]",
"tests/test_price_parsing.py::test_parsing[example147]",
"tests/test_price_parsing.py::test_parsing[example148]",
"tests/test_price_parsing.py::test_parsing[example149]",
"tests/test_price_parsing.py::test_parsing[example150]",
"tests/test_price_parsing.py::test_parsing[example151]",
"tests/test_price_parsing.py::test_parsing[example152]",
"tests/test_price_parsing.py::test_parsing[example153]",
"tests/test_price_parsing.py::test_parsing[example154]",
"tests/test_price_parsing.py::test_parsing[example155]",
"tests/test_price_parsing.py::test_parsing[example156]",
"tests/test_price_parsing.py::test_parsing[example157]",
"tests/test_price_parsing.py::test_parsing[example158]",
"tests/test_price_parsing.py::test_parsing[example159]",
"tests/test_price_parsing.py::test_parsing[example160]",
"tests/test_price_parsing.py::test_parsing[example161]",
"tests/test_price_parsing.py::test_parsing[example162]",
"tests/test_price_parsing.py::test_parsing[example163]",
"tests/test_price_parsing.py::test_parsing[example164]",
"tests/test_price_parsing.py::test_parsing[example165]",
"tests/test_price_parsing.py::test_parsing[example166]",
"tests/test_price_parsing.py::test_parsing[example167]",
"tests/test_price_parsing.py::test_parsing[example168]",
"tests/test_price_parsing.py::test_parsing[example169]",
"tests/test_price_parsing.py::test_parsing[example170]",
"tests/test_price_parsing.py::test_parsing[example171]",
"tests/test_price_parsing.py::test_parsing[example172]",
"tests/test_price_parsing.py::test_parsing[example173]",
"tests/test_price_parsing.py::test_parsing[example174]",
"tests/test_price_parsing.py::test_parsing[example175]",
"tests/test_price_parsing.py::test_parsing[example176]",
"tests/test_price_parsing.py::test_parsing[example177]",
"tests/test_price_parsing.py::test_parsing[example178]",
"tests/test_price_parsing.py::test_parsing[example179]",
"tests/test_price_parsing.py::test_parsing[example180]",
"tests/test_price_parsing.py::test_parsing[example181]",
"tests/test_price_parsing.py::test_parsing[example182]",
"tests/test_price_parsing.py::test_parsing[example186]",
"tests/test_price_parsing.py::test_parsing[example187]",
"tests/test_price_parsing.py::test_parsing[example188]",
"tests/test_price_parsing.py::test_parsing[example189]",
"tests/test_price_parsing.py::test_parsing[example190]",
"tests/test_price_parsing.py::test_parsing[example191]",
"tests/test_price_parsing.py::test_parsing[example192]",
"tests/test_price_parsing.py::test_parsing[example193]",
"tests/test_price_parsing.py::test_parsing[example194]",
"tests/test_price_parsing.py::test_parsing[example195]",
"tests/test_price_parsing.py::test_parsing[example196]",
"tests/test_price_parsing.py::test_parsing[example197]",
"tests/test_price_parsing.py::test_parsing[example198]",
"tests/test_price_parsing.py::test_parsing[example199]",
"tests/test_price_parsing.py::test_parsing[example200]",
"tests/test_price_parsing.py::test_parsing[example201]",
"tests/test_price_parsing.py::test_parsing[example202]",
"tests/test_price_parsing.py::test_parsing[example203]",
"tests/test_price_parsing.py::test_parsing[example204]",
"tests/test_price_parsing.py::test_parsing[example205]",
"tests/test_price_parsing.py::test_parsing[example206]",
"tests/test_price_parsing.py::test_parsing[example207]",
"tests/test_price_parsing.py::test_parsing[example208]",
"tests/test_price_parsing.py::test_parsing[example209]",
"tests/test_price_parsing.py::test_parsing[example210]",
"tests/test_price_parsing.py::test_parsing[example211]",
"tests/test_price_parsing.py::test_parsing[example212]",
"tests/test_price_parsing.py::test_parsing[example213]",
"tests/test_price_parsing.py::test_parsing[example214]",
"tests/test_price_parsing.py::test_parsing[example215]",
"tests/test_price_parsing.py::test_parsing[example216]",
"tests/test_price_parsing.py::test_parsing[example217]",
"tests/test_price_parsing.py::test_parsing[example218]",
"tests/test_price_parsing.py::test_parsing[example219]",
"tests/test_price_parsing.py::test_parsing[example220]",
"tests/test_price_parsing.py::test_parsing[example221]",
"tests/test_price_parsing.py::test_parsing[example222]",
"tests/test_price_parsing.py::test_parsing[example223]",
"tests/test_price_parsing.py::test_parsing[example224]",
"tests/test_price_parsing.py::test_parsing[example225]",
"tests/test_price_parsing.py::test_parsing[example226]",
"tests/test_price_parsing.py::test_parsing[example227]",
"tests/test_price_parsing.py::test_parsing[example228]",
"tests/test_price_parsing.py::test_parsing[example229]",
"tests/test_price_parsing.py::test_parsing[example230]",
"tests/test_price_parsing.py::test_parsing[example231]",
"tests/test_price_parsing.py::test_parsing[example232]",
"tests/test_price_parsing.py::test_parsing[example233]",
"tests/test_price_parsing.py::test_parsing[example234]",
"tests/test_price_parsing.py::test_parsing[example235]",
"tests/test_price_parsing.py::test_parsing[example236]",
"tests/test_price_parsing.py::test_parsing[example237]",
"tests/test_price_parsing.py::test_parsing[example238]",
"tests/test_price_parsing.py::test_parsing[example239]",
"tests/test_price_parsing.py::test_parsing[example240]",
"tests/test_price_parsing.py::test_parsing[example241]",
"tests/test_price_parsing.py::test_parsing[example242]",
"tests/test_price_parsing.py::test_parsing[example243]",
"tests/test_price_parsing.py::test_parsing[example244]",
"tests/test_price_parsing.py::test_parsing[example245]",
"tests/test_price_parsing.py::test_parsing[example246]",
"tests/test_price_parsing.py::test_parsing[example247]",
"tests/test_price_parsing.py::test_parsing[example248]",
"tests/test_price_parsing.py::test_parsing[example249]",
"tests/test_price_parsing.py::test_parsing[example250]",
"tests/test_price_parsing.py::test_parsing[example251]",
"tests/test_price_parsing.py::test_parsing[example252]",
"tests/test_price_parsing.py::test_parsing[example253]",
"tests/test_price_parsing.py::test_parsing[example254]",
"tests/test_price_parsing.py::test_parsing[example255]",
"tests/test_price_parsing.py::test_parsing[example256]",
"tests/test_price_parsing.py::test_parsing[example257]",
"tests/test_price_parsing.py::test_parsing[example258]",
"tests/test_price_parsing.py::test_parsing[example259]",
"tests/test_price_parsing.py::test_parsing[example260]",
"tests/test_price_parsing.py::test_parsing[example261]",
"tests/test_price_parsing.py::test_parsing[example262]",
"tests/test_price_parsing.py::test_parsing[example263]",
"tests/test_price_parsing.py::test_parsing[example264]",
"tests/test_price_parsing.py::test_parsing[example265]",
"tests/test_price_parsing.py::test_parsing[example266]",
"tests/test_price_parsing.py::test_parsing[example267]",
"tests/test_price_parsing.py::test_parsing[example268]",
"tests/test_price_parsing.py::test_parsing[example269]",
"tests/test_price_parsing.py::test_parsing[example270]",
"tests/test_price_parsing.py::test_parsing[example271]",
"tests/test_price_parsing.py::test_parsing[example272]",
"tests/test_price_parsing.py::test_parsing[example273]",
"tests/test_price_parsing.py::test_parsing[example274]",
"tests/test_price_parsing.py::test_parsing[example275]",
"tests/test_price_parsing.py::test_parsing[example276]",
"tests/test_price_parsing.py::test_parsing[example277]",
"tests/test_price_parsing.py::test_parsing[example278]",
"tests/test_price_parsing.py::test_parsing[example279]",
"tests/test_price_parsing.py::test_parsing[example280]",
"tests/test_price_parsing.py::test_parsing[example281]",
"tests/test_price_parsing.py::test_parsing[example282]",
"tests/test_price_parsing.py::test_parsing[example283]",
"tests/test_price_parsing.py::test_parsing[example284]",
"tests/test_price_parsing.py::test_parsing[example285]",
"tests/test_price_parsing.py::test_parsing[example286]",
"tests/test_price_parsing.py::test_parsing[example287]",
"tests/test_price_parsing.py::test_parsing[example288]",
"tests/test_price_parsing.py::test_parsing[example289]",
"tests/test_price_parsing.py::test_parsing[example290]",
"tests/test_price_parsing.py::test_parsing[example291]",
"tests/test_price_parsing.py::test_parsing[example292]",
"tests/test_price_parsing.py::test_parsing[example293]",
"tests/test_price_parsing.py::test_parsing[example294]",
"tests/test_price_parsing.py::test_parsing[example295]",
"tests/test_price_parsing.py::test_parsing[example296]",
"tests/test_price_parsing.py::test_parsing[example297]",
"tests/test_price_parsing.py::test_parsing[example298]",
"tests/test_price_parsing.py::test_parsing[example299]",
"tests/test_price_parsing.py::test_parsing[example300]",
"tests/test_price_parsing.py::test_parsing[example301]",
"tests/test_price_parsing.py::test_parsing[example302]",
"tests/test_price_parsing.py::test_parsing[example303]",
"tests/test_price_parsing.py::test_parsing[example304]",
"tests/test_price_parsing.py::test_parsing[example305]",
"tests/test_price_parsing.py::test_parsing[example306]",
"tests/test_price_parsing.py::test_parsing[example307]",
"tests/test_price_parsing.py::test_parsing[example308]",
"tests/test_price_parsing.py::test_parsing[example309]",
"tests/test_price_parsing.py::test_parsing[example310]",
"tests/test_price_parsing.py::test_parsing[example311]",
"tests/test_price_parsing.py::test_parsing[example312]",
"tests/test_price_parsing.py::test_parsing[example313]",
"tests/test_price_parsing.py::test_parsing[example314]",
"tests/test_price_parsing.py::test_parsing[example315]",
"tests/test_price_parsing.py::test_parsing[example316]",
"tests/test_price_parsing.py::test_parsing[example317]",
"tests/test_price_parsing.py::test_parsing[example318]",
"tests/test_price_parsing.py::test_parsing[example319]",
"tests/test_price_parsing.py::test_parsing[example320]",
"tests/test_price_parsing.py::test_parsing[example321]",
"tests/test_price_parsing.py::test_parsing[example322]",
"tests/test_price_parsing.py::test_parsing[example323]",
"tests/test_price_parsing.py::test_parsing[example324]",
"tests/test_price_parsing.py::test_parsing[example325]",
"tests/test_price_parsing.py::test_parsing[example326]",
"tests/test_price_parsing.py::test_parsing[example327]",
"tests/test_price_parsing.py::test_parsing[example328]",
"tests/test_price_parsing.py::test_parsing[example329]",
"tests/test_price_parsing.py::test_parsing[example330]",
"tests/test_price_parsing.py::test_parsing[example331]",
"tests/test_price_parsing.py::test_parsing[example332]",
"tests/test_price_parsing.py::test_parsing[example333]",
"tests/test_price_parsing.py::test_parsing[example334]",
"tests/test_price_parsing.py::test_parsing[example335]",
"tests/test_price_parsing.py::test_parsing[example336]",
"tests/test_price_parsing.py::test_parsing[example337]",
"tests/test_price_parsing.py::test_parsing[example338]",
"tests/test_price_parsing.py::test_parsing[example339]",
"tests/test_price_parsing.py::test_parsing[example340]",
"tests/test_price_parsing.py::test_parsing[example341]",
"tests/test_price_parsing.py::test_parsing[example342]",
"tests/test_price_parsing.py::test_parsing[example343]",
"tests/test_price_parsing.py::test_parsing[example344]",
"tests/test_price_parsing.py::test_parsing[example345]",
"tests/test_price_parsing.py::test_parsing[example346]",
"tests/test_price_parsing.py::test_parsing[example347]",
"tests/test_price_parsing.py::test_parsing[example348]",
"tests/test_price_parsing.py::test_parsing[example349]",
"tests/test_price_parsing.py::test_parsing[example350]",
"tests/test_price_parsing.py::test_parsing[example351]",
"tests/test_price_parsing.py::test_parsing[example352]",
"tests/test_price_parsing.py::test_parsing[example353]",
"tests/test_price_parsing.py::test_parsing[example354]",
"tests/test_price_parsing.py::test_parsing[example355]",
"tests/test_price_parsing.py::test_parsing[example356]",
"tests/test_price_parsing.py::test_parsing[example357]",
"tests/test_price_parsing.py::test_parsing[example358]",
"tests/test_price_parsing.py::test_parsing[example359]",
"tests/test_price_parsing.py::test_parsing[example360]",
"tests/test_price_parsing.py::test_parsing[example361]",
"tests/test_price_parsing.py::test_parsing[example362]",
"tests/test_price_parsing.py::test_parsing[example363]",
"tests/test_price_parsing.py::test_parsing[example364]",
"tests/test_price_parsing.py::test_parsing[example365]",
"tests/test_price_parsing.py::test_parsing[example366]",
"tests/test_price_parsing.py::test_parsing[example367]",
"tests/test_price_parsing.py::test_parsing[example368]",
"tests/test_price_parsing.py::test_parsing[example369]",
"tests/test_price_parsing.py::test_parsing[example370]",
"tests/test_price_parsing.py::test_parsing[example371]",
"tests/test_price_parsing.py::test_parsing[example372]",
"tests/test_price_parsing.py::test_parsing[example373]",
"tests/test_price_parsing.py::test_parsing[example374]",
"tests/test_price_parsing.py::test_parsing[example375]",
"tests/test_price_parsing.py::test_parsing[example376]",
"tests/test_price_parsing.py::test_parsing[example377]",
"tests/test_price_parsing.py::test_parsing[example378]",
"tests/test_price_parsing.py::test_parsing[example379]",
"tests/test_price_parsing.py::test_parsing[example380]",
"tests/test_price_parsing.py::test_parsing[example381]",
"tests/test_price_parsing.py::test_parsing[example382]",
"tests/test_price_parsing.py::test_parsing[example383]",
"tests/test_price_parsing.py::test_parsing[example384]",
"tests/test_price_parsing.py::test_parsing[example385]",
"tests/test_price_parsing.py::test_parsing[example386]",
"tests/test_price_parsing.py::test_parsing[example387]",
"tests/test_price_parsing.py::test_parsing[example388]",
"tests/test_price_parsing.py::test_parsing[example389]",
"tests/test_price_parsing.py::test_parsing[example390]",
"tests/test_price_parsing.py::test_parsing[example391]",
"tests/test_price_parsing.py::test_parsing[example392]",
"tests/test_price_parsing.py::test_parsing[example393]",
"tests/test_price_parsing.py::test_parsing[example394]",
"tests/test_price_parsing.py::test_parsing[example395]",
"tests/test_price_parsing.py::test_parsing[example396]",
"tests/test_price_parsing.py::test_parsing[example397]",
"tests/test_price_parsing.py::test_parsing[example398]",
"tests/test_price_parsing.py::test_parsing[example399]",
"tests/test_price_parsing.py::test_parsing[example400]",
"tests/test_price_parsing.py::test_parsing[example401]",
"tests/test_price_parsing.py::test_parsing[example402]",
"tests/test_price_parsing.py::test_parsing[example403]",
"tests/test_price_parsing.py::test_parsing[example404]",
"tests/test_price_parsing.py::test_parsing[example405]",
"tests/test_price_parsing.py::test_parsing[example406]",
"tests/test_price_parsing.py::test_parsing[example407]",
"tests/test_price_parsing.py::test_parsing[example408]",
"tests/test_price_parsing.py::test_parsing[example409]",
"tests/test_price_parsing.py::test_parsing[example410]",
"tests/test_price_parsing.py::test_parsing[example411]",
"tests/test_price_parsing.py::test_parsing[example412]",
"tests/test_price_parsing.py::test_parsing[example413]",
"tests/test_price_parsing.py::test_parsing[example414]",
"tests/test_price_parsing.py::test_parsing[example415]",
"tests/test_price_parsing.py::test_parsing[example416]",
"tests/test_price_parsing.py::test_parsing[example417]",
"tests/test_price_parsing.py::test_parsing[example418]",
"tests/test_price_parsing.py::test_parsing[example419]",
"tests/test_price_parsing.py::test_parsing[example420]",
"tests/test_price_parsing.py::test_parsing[example421]",
"tests/test_price_parsing.py::test_parsing[example422]",
"tests/test_price_parsing.py::test_parsing[example423]",
"tests/test_price_parsing.py::test_parsing[example424]",
"tests/test_price_parsing.py::test_parsing[example425]",
"tests/test_price_parsing.py::test_parsing[example426]",
"tests/test_price_parsing.py::test_parsing[example427]",
"tests/test_price_parsing.py::test_parsing[example428]",
"tests/test_price_parsing.py::test_parsing[example429]",
"tests/test_price_parsing.py::test_parsing[example430]",
"tests/test_price_parsing.py::test_parsing[example431]",
"tests/test_price_parsing.py::test_parsing[example432]",
"tests/test_price_parsing.py::test_parsing[example433]",
"tests/test_price_parsing.py::test_parsing[example434]",
"tests/test_price_parsing.py::test_parsing[example435]",
"tests/test_price_parsing.py::test_parsing[example436]",
"tests/test_price_parsing.py::test_parsing[example437]",
"tests/test_price_parsing.py::test_parsing[example438]",
"tests/test_price_parsing.py::test_parsing[example439]",
"tests/test_price_parsing.py::test_parsing[example440]",
"tests/test_price_parsing.py::test_parsing[example441]",
"tests/test_price_parsing.py::test_parsing[example442]",
"tests/test_price_parsing.py::test_parsing[example443]",
"tests/test_price_parsing.py::test_parsing[example444]",
"tests/test_price_parsing.py::test_parsing[example445]",
"tests/test_price_parsing.py::test_parsing[example446]",
"tests/test_price_parsing.py::test_parsing[example447]",
"tests/test_price_parsing.py::test_parsing[example448]",
"tests/test_price_parsing.py::test_parsing[example449]",
"tests/test_price_parsing.py::test_parsing[example450]",
"tests/test_price_parsing.py::test_parsing[example451]",
"tests/test_price_parsing.py::test_parsing[example452]",
"tests/test_price_parsing.py::test_parsing[example453]",
"tests/test_price_parsing.py::test_parsing[example454]",
"tests/test_price_parsing.py::test_parsing[example455]",
"tests/test_price_parsing.py::test_parsing[example456]",
"tests/test_price_parsing.py::test_parsing[example457]",
"tests/test_price_parsing.py::test_parsing[example458]",
"tests/test_price_parsing.py::test_parsing[example459]",
"tests/test_price_parsing.py::test_parsing[example460]",
"tests/test_price_parsing.py::test_parsing[example461]",
"tests/test_price_parsing.py::test_parsing[example462]",
"tests/test_price_parsing.py::test_parsing[example463]",
"tests/test_price_parsing.py::test_parsing[example464]",
"tests/test_price_parsing.py::test_parsing[example465]",
"tests/test_price_parsing.py::test_parsing[example466]",
"tests/test_price_parsing.py::test_parsing[example467]",
"tests/test_price_parsing.py::test_parsing[example468]",
"tests/test_price_parsing.py::test_parsing[example469]",
"tests/test_price_parsing.py::test_parsing[example470]",
"tests/test_price_parsing.py::test_parsing[example471]",
"tests/test_price_parsing.py::test_parsing[example472]",
"tests/test_price_parsing.py::test_parsing[example473]",
"tests/test_price_parsing.py::test_parsing[example474]",
"tests/test_price_parsing.py::test_parsing[example475]",
"tests/test_price_parsing.py::test_parsing[example476]",
"tests/test_price_parsing.py::test_parsing[example477]",
"tests/test_price_parsing.py::test_parsing[example478]",
"tests/test_price_parsing.py::test_parsing[example479]",
"tests/test_price_parsing.py::test_parsing[example480]",
"tests/test_price_parsing.py::test_parsing[example481]",
"tests/test_price_parsing.py::test_parsing[example482]",
"tests/test_price_parsing.py::test_parsing[example483]",
"tests/test_price_parsing.py::test_parsing[example484]",
"tests/test_price_parsing.py::test_parsing[example485]",
"tests/test_price_parsing.py::test_parsing[example486]",
"tests/test_price_parsing.py::test_parsing[example487]",
"tests/test_price_parsing.py::test_parsing[example488]",
"tests/test_price_parsing.py::test_parsing[example489]",
"tests/test_price_parsing.py::test_parsing[example490]",
"tests/test_price_parsing.py::test_parsing[example491]",
"tests/test_price_parsing.py::test_parsing[example492]",
"tests/test_price_parsing.py::test_parsing[example493]",
"tests/test_price_parsing.py::test_parsing[example494]",
"tests/test_price_parsing.py::test_parsing[example495]",
"tests/test_price_parsing.py::test_parsing[example496]",
"tests/test_price_parsing.py::test_parsing[example497]",
"tests/test_price_parsing.py::test_parsing[example498]",
"tests/test_price_parsing.py::test_parsing[example499]",
"tests/test_price_parsing.py::test_parsing[example500]",
"tests/test_price_parsing.py::test_parsing[example501]",
"tests/test_price_parsing.py::test_parsing[example502]",
"tests/test_price_parsing.py::test_parsing[example503]",
"tests/test_price_parsing.py::test_parsing[example504]",
"tests/test_price_parsing.py::test_parsing[example505]",
"tests/test_price_parsing.py::test_parsing[example506]",
"tests/test_price_parsing.py::test_parsing[example507]",
"tests/test_price_parsing.py::test_parsing[example508]",
"tests/test_price_parsing.py::test_parsing[example509]",
"tests/test_price_parsing.py::test_parsing[example510]",
"tests/test_price_parsing.py::test_parsing[example511]",
"tests/test_price_parsing.py::test_parsing[example512]",
"tests/test_price_parsing.py::test_parsing[example513]",
"tests/test_price_parsing.py::test_parsing[example514]",
"tests/test_price_parsing.py::test_parsing[example515]",
"tests/test_price_parsing.py::test_parsing[example516]",
"tests/test_price_parsing.py::test_parsing[example517]",
"tests/test_price_parsing.py::test_parsing[example518]",
"tests/test_price_parsing.py::test_parsing[example519]",
"tests/test_price_parsing.py::test_parsing[example520]",
"tests/test_price_parsing.py::test_parsing[example521]",
"tests/test_price_parsing.py::test_parsing[example522]",
"tests/test_price_parsing.py::test_parsing[example523]",
"tests/test_price_parsing.py::test_parsing[example524]",
"tests/test_price_parsing.py::test_parsing[example525]",
"tests/test_price_parsing.py::test_parsing[example526]",
"tests/test_price_parsing.py::test_parsing[example527]",
"tests/test_price_parsing.py::test_parsing[example528]",
"tests/test_price_parsing.py::test_parsing[example529]",
"tests/test_price_parsing.py::test_parsing[example530]",
"tests/test_price_parsing.py::test_parsing[example531]",
"tests/test_price_parsing.py::test_parsing[example532]",
"tests/test_price_parsing.py::test_parsing[example533]",
"tests/test_price_parsing.py::test_parsing[example534]",
"tests/test_price_parsing.py::test_parsing[example535]",
"tests/test_price_parsing.py::test_parsing[example536]",
"tests/test_price_parsing.py::test_parsing[example537]",
"tests/test_price_parsing.py::test_parsing[example538]",
"tests/test_price_parsing.py::test_parsing[example539]",
"tests/test_price_parsing.py::test_parsing[example540]",
"tests/test_price_parsing.py::test_parsing[example541]",
"tests/test_price_parsing.py::test_parsing[example542]",
"tests/test_price_parsing.py::test_parsing[example543]",
"tests/test_price_parsing.py::test_parsing[example544]",
"tests/test_price_parsing.py::test_parsing[example545]",
"tests/test_price_parsing.py::test_parsing[example546]",
"tests/test_price_parsing.py::test_parsing[example547]",
"tests/test_price_parsing.py::test_parsing[example548]",
"tests/test_price_parsing.py::test_parsing[example549]",
"tests/test_price_parsing.py::test_parsing[example550]",
"tests/test_price_parsing.py::test_parsing[example551]",
"tests/test_price_parsing.py::test_parsing[example552]",
"tests/test_price_parsing.py::test_parsing[example553]",
"tests/test_price_parsing.py::test_parsing[example554]",
"tests/test_price_parsing.py::test_parsing[example555]",
"tests/test_price_parsing.py::test_parsing[example556]",
"tests/test_price_parsing.py::test_parsing[example557]",
"tests/test_price_parsing.py::test_parsing[example558]",
"tests/test_price_parsing.py::test_parsing[example559]",
"tests/test_price_parsing.py::test_parsing[example560]",
"tests/test_price_parsing.py::test_parsing[example561]",
"tests/test_price_parsing.py::test_parsing[example562]",
"tests/test_price_parsing.py::test_parsing[example563]",
"tests/test_price_parsing.py::test_parsing[example564]",
"tests/test_price_parsing.py::test_parsing[example565]",
"tests/test_price_parsing.py::test_parsing[example566]",
"tests/test_price_parsing.py::test_parsing[example567]",
"tests/test_price_parsing.py::test_parsing[example568]",
"tests/test_price_parsing.py::test_parsing[example569]",
"tests/test_price_parsing.py::test_parsing[example570]",
"tests/test_price_parsing.py::test_parsing[example571]",
"tests/test_price_parsing.py::test_parsing[example572]",
"tests/test_price_parsing.py::test_parsing[example573]",
"tests/test_price_parsing.py::test_parsing[example574]",
"tests/test_price_parsing.py::test_parsing[example575]",
"tests/test_price_parsing.py::test_parsing[example576]",
"tests/test_price_parsing.py::test_parsing[example577]",
"tests/test_price_parsing.py::test_parsing[example578]",
"tests/test_price_parsing.py::test_parsing[example579]",
"tests/test_price_parsing.py::test_parsing[example580]",
"tests/test_price_parsing.py::test_parsing[example581]",
"tests/test_price_parsing.py::test_parsing[example582]",
"tests/test_price_parsing.py::test_parsing[example583]",
"tests/test_price_parsing.py::test_parsing[example584]",
"tests/test_price_parsing.py::test_parsing[example585]",
"tests/test_price_parsing.py::test_parsing[example586]",
"tests/test_price_parsing.py::test_parsing[example587]",
"tests/test_price_parsing.py::test_parsing[example588]",
"tests/test_price_parsing.py::test_parsing[example589]",
"tests/test_price_parsing.py::test_parsing[example590]",
"tests/test_price_parsing.py::test_parsing[example591]",
"tests/test_price_parsing.py::test_parsing[example592]",
"tests/test_price_parsing.py::test_parsing[example593]",
"tests/test_price_parsing.py::test_parsing[example594]",
"tests/test_price_parsing.py::test_parsing[example595]",
"tests/test_price_parsing.py::test_parsing[example596]",
"tests/test_price_parsing.py::test_parsing[example597]",
"tests/test_price_parsing.py::test_parsing[example598]",
"tests/test_price_parsing.py::test_parsing[example599]",
"tests/test_price_parsing.py::test_parsing[example600]",
"tests/test_price_parsing.py::test_parsing[example601]",
"tests/test_price_parsing.py::test_parsing[example602]",
"tests/test_price_parsing.py::test_parsing[example603]",
"tests/test_price_parsing.py::test_parsing[example604]",
"tests/test_price_parsing.py::test_parsing[example605]",
"tests/test_price_parsing.py::test_parsing[example606]",
"tests/test_price_parsing.py::test_parsing[example607]",
"tests/test_price_parsing.py::test_parsing[example608]",
"tests/test_price_parsing.py::test_parsing[example609]",
"tests/test_price_parsing.py::test_parsing[example610]",
"tests/test_price_parsing.py::test_parsing[example611]",
"tests/test_price_parsing.py::test_parsing[example612]",
"tests/test_price_parsing.py::test_parsing[example613]",
"tests/test_price_parsing.py::test_parsing[example614]",
"tests/test_price_parsing.py::test_parsing[example615]",
"tests/test_price_parsing.py::test_parsing[example616]",
"tests/test_price_parsing.py::test_parsing[example617]",
"tests/test_price_parsing.py::test_parsing[example618]",
"tests/test_price_parsing.py::test_parsing[example619]",
"tests/test_price_parsing.py::test_parsing[example620]",
"tests/test_price_parsing.py::test_parsing[example621]",
"tests/test_price_parsing.py::test_parsing[example622]",
"tests/test_price_parsing.py::test_parsing[example623]",
"tests/test_price_parsing.py::test_parsing[example624]",
"tests/test_price_parsing.py::test_parsing[example625]",
"tests/test_price_parsing.py::test_parsing[example626]",
"tests/test_price_parsing.py::test_parsing[example627]",
"tests/test_price_parsing.py::test_parsing[example628]",
"tests/test_price_parsing.py::test_parsing[example629]",
"tests/test_price_parsing.py::test_parsing[example630]",
"tests/test_price_parsing.py::test_parsing[example631]",
"tests/test_price_parsing.py::test_parsing[example632]",
"tests/test_price_parsing.py::test_parsing[example633]",
"tests/test_price_parsing.py::test_parsing[example634]",
"tests/test_price_parsing.py::test_parsing[example635]",
"tests/test_price_parsing.py::test_parsing[example636]",
"tests/test_price_parsing.py::test_parsing[example637]",
"tests/test_price_parsing.py::test_parsing[example638]",
"tests/test_price_parsing.py::test_parsing[example639]",
"tests/test_price_parsing.py::test_parsing[example640]",
"tests/test_price_parsing.py::test_parsing[example641]",
"tests/test_price_parsing.py::test_parsing[example642]",
"tests/test_price_parsing.py::test_parsing[example643]",
"tests/test_price_parsing.py::test_parsing[example644]",
"tests/test_price_parsing.py::test_parsing[example645]",
"tests/test_price_parsing.py::test_parsing[example646]",
"tests/test_price_parsing.py::test_parsing[example647]",
"tests/test_price_parsing.py::test_parsing[example648]",
"tests/test_price_parsing.py::test_parsing[example649]",
"tests/test_price_parsing.py::test_parsing[example650]",
"tests/test_price_parsing.py::test_parsing[example651]",
"tests/test_price_parsing.py::test_parsing[example652]",
"tests/test_price_parsing.py::test_parsing[example653]",
"tests/test_price_parsing.py::test_parsing[example654]",
"tests/test_price_parsing.py::test_parsing[example655]",
"tests/test_price_parsing.py::test_parsing[example656]",
"tests/test_price_parsing.py::test_parsing[example657]",
"tests/test_price_parsing.py::test_parsing[example658]",
"tests/test_price_parsing.py::test_parsing[example659]",
"tests/test_price_parsing.py::test_parsing[example660]",
"tests/test_price_parsing.py::test_parsing[example661]",
"tests/test_price_parsing.py::test_parsing[example662]",
"tests/test_price_parsing.py::test_parsing[example663]",
"tests/test_price_parsing.py::test_parsing[example664]",
"tests/test_price_parsing.py::test_parsing[example665]",
"tests/test_price_parsing.py::test_parsing[example666]",
"tests/test_price_parsing.py::test_parsing[example667]",
"tests/test_price_parsing.py::test_parsing[example668]",
"tests/test_price_parsing.py::test_parsing[example669]",
"tests/test_price_parsing.py::test_parsing[example670]",
"tests/test_price_parsing.py::test_parsing[example671]",
"tests/test_price_parsing.py::test_parsing[example672]",
"tests/test_price_parsing.py::test_parsing[example673]",
"tests/test_price_parsing.py::test_parsing[example674]",
"tests/test_price_parsing.py::test_parsing[example675]",
"tests/test_price_parsing.py::test_parsing[example676]",
"tests/test_price_parsing.py::test_parsing[example677]",
"tests/test_price_parsing.py::test_parsing[example678]",
"tests/test_price_parsing.py::test_parsing[example679]",
"tests/test_price_parsing.py::test_parsing[example680]",
"tests/test_price_parsing.py::test_parsing[example681]",
"tests/test_price_parsing.py::test_parsing[example682]",
"tests/test_price_parsing.py::test_parsing[example683]",
"tests/test_price_parsing.py::test_parsing[example684]",
"tests/test_price_parsing.py::test_parsing[example685]",
"tests/test_price_parsing.py::test_parsing[example686]",
"tests/test_price_parsing.py::test_parsing[example687]",
"tests/test_price_parsing.py::test_parsing[example688]",
"tests/test_price_parsing.py::test_parsing[example689]",
"tests/test_price_parsing.py::test_parsing[example690]",
"tests/test_price_parsing.py::test_parsing[example691]",
"tests/test_price_parsing.py::test_parsing[example692]",
"tests/test_price_parsing.py::test_parsing[example693]",
"tests/test_price_parsing.py::test_parsing[example694]",
"tests/test_price_parsing.py::test_parsing[example695]",
"tests/test_price_parsing.py::test_parsing[example696]",
"tests/test_price_parsing.py::test_parsing[example697]",
"tests/test_price_parsing.py::test_parsing[example698]",
"tests/test_price_parsing.py::test_parsing[example699]",
"tests/test_price_parsing.py::test_parsing[example700]",
"tests/test_price_parsing.py::test_parsing[example701]",
"tests/test_price_parsing.py::test_parsing[example702]",
"tests/test_price_parsing.py::test_parsing[example703]",
"tests/test_price_parsing.py::test_parsing[example704]",
"tests/test_price_parsing.py::test_parsing[example705]",
"tests/test_price_parsing.py::test_parsing[example706]",
"tests/test_price_parsing.py::test_parsing[example707]",
"tests/test_price_parsing.py::test_parsing[example708]",
"tests/test_price_parsing.py::test_parsing[example709]",
"tests/test_price_parsing.py::test_parsing[example710]",
"tests/test_price_parsing.py::test_parsing[example711]",
"tests/test_price_parsing.py::test_parsing[example712]",
"tests/test_price_parsing.py::test_parsing[example713]",
"tests/test_price_parsing.py::test_parsing[example714]",
"tests/test_price_parsing.py::test_parsing[example715]",
"tests/test_price_parsing.py::test_parsing[example716]",
"tests/test_price_parsing.py::test_parsing[example717]",
"tests/test_price_parsing.py::test_parsing[example718]",
"tests/test_price_parsing.py::test_parsing[example719]",
"tests/test_price_parsing.py::test_parsing[example720]",
"tests/test_price_parsing.py::test_parsing[example721]",
"tests/test_price_parsing.py::test_parsing[example722]",
"tests/test_price_parsing.py::test_parsing[example723]",
"tests/test_price_parsing.py::test_parsing[example724]",
"tests/test_price_parsing.py::test_parsing[example725]",
"tests/test_price_parsing.py::test_parsing[example726]",
"tests/test_price_parsing.py::test_parsing[example727]",
"tests/test_price_parsing.py::test_parsing[example728]",
"tests/test_price_parsing.py::test_parsing[example729]",
"tests/test_price_parsing.py::test_parsing[example730]",
"tests/test_price_parsing.py::test_parsing[example731]",
"tests/test_price_parsing.py::test_parsing[example732]",
"tests/test_price_parsing.py::test_parsing[example733]",
"tests/test_price_parsing.py::test_parsing[example734]",
"tests/test_price_parsing.py::test_parsing[example735]",
"tests/test_price_parsing.py::test_parsing[example736]",
"tests/test_price_parsing.py::test_parsing[example737]",
"tests/test_price_parsing.py::test_parsing[example738]",
"tests/test_price_parsing.py::test_parsing[example739]",
"tests/test_price_parsing.py::test_parsing[example740]",
"tests/test_price_parsing.py::test_parsing[example741]",
"tests/test_price_parsing.py::test_parsing[example742]",
"tests/test_price_parsing.py::test_parsing[example743]",
"tests/test_price_parsing.py::test_parsing[example744]",
"tests/test_price_parsing.py::test_parsing[example745]",
"tests/test_price_parsing.py::test_parsing[example746]",
"tests/test_price_parsing.py::test_parsing[example747]",
"tests/test_price_parsing.py::test_parsing[example748]",
"tests/test_price_parsing.py::test_parsing[example749]",
"tests/test_price_parsing.py::test_parsing[example750]",
"tests/test_price_parsing.py::test_parsing[example751]",
"tests/test_price_parsing.py::test_parsing[example752]",
"tests/test_price_parsing.py::test_parsing[example753]",
"tests/test_price_parsing.py::test_parsing[example754]",
"tests/test_price_parsing.py::test_parsing[example755]",
"tests/test_price_parsing.py::test_parsing[example756]",
"tests/test_price_parsing.py::test_parsing[example757]",
"tests/test_price_parsing.py::test_parsing[example758]",
"tests/test_price_parsing.py::test_parsing[example759]",
"tests/test_price_parsing.py::test_parsing[example760]",
"tests/test_price_parsing.py::test_parsing[example761]",
"tests/test_price_parsing.py::test_parsing[example762]",
"tests/test_price_parsing.py::test_parsing[example763]",
"tests/test_price_parsing.py::test_parsing[example764]",
"tests/test_price_parsing.py::test_parsing[example765]",
"tests/test_price_parsing.py::test_parsing[example766]",
"tests/test_price_parsing.py::test_parsing[example767]",
"tests/test_price_parsing.py::test_parsing[example768]",
"tests/test_price_parsing.py::test_parsing[example769]",
"tests/test_price_parsing.py::test_parsing[example770]",
"tests/test_price_parsing.py::test_parsing[example771]",
"tests/test_price_parsing.py::test_parsing[example772]",
"tests/test_price_parsing.py::test_parsing[example773]",
"tests/test_price_parsing.py::test_parsing[example774]",
"tests/test_price_parsing.py::test_parsing[example775]",
"tests/test_price_parsing.py::test_parsing[example776]",
"tests/test_price_parsing.py::test_parsing[example777]",
"tests/test_price_parsing.py::test_parsing[example778]",
"tests/test_price_parsing.py::test_parsing[example779]",
"tests/test_price_parsing.py::test_parsing[example780]",
"tests/test_price_parsing.py::test_parsing[example781]",
"tests/test_price_parsing.py::test_parsing[example782]",
"tests/test_price_parsing.py::test_parsing[example783]",
"tests/test_price_parsing.py::test_parsing[example784]",
"tests/test_price_parsing.py::test_parsing[example785]",
"tests/test_price_parsing.py::test_parsing[example786]",
"tests/test_price_parsing.py::test_parsing[example787]",
"tests/test_price_parsing.py::test_parsing[example788]",
"tests/test_price_parsing.py::test_parsing[example789]",
"tests/test_price_parsing.py::test_parsing[example790]",
"tests/test_price_parsing.py::test_parsing[example791]",
"tests/test_price_parsing.py::test_parsing[example792]",
"tests/test_price_parsing.py::test_parsing[example793]",
"tests/test_price_parsing.py::test_parsing[example794]",
"tests/test_price_parsing.py::test_parsing[example795]",
"tests/test_price_parsing.py::test_parsing[example796]",
"tests/test_price_parsing.py::test_parsing[example797]",
"tests/test_price_parsing.py::test_parsing[example798]",
"tests/test_price_parsing.py::test_parsing[example799]",
"tests/test_price_parsing.py::test_parsing[example800]",
"tests/test_price_parsing.py::test_parsing[example801]",
"tests/test_price_parsing.py::test_parsing[example802]",
"tests/test_price_parsing.py::test_parsing[example803]",
"tests/test_price_parsing.py::test_parsing[example804]",
"tests/test_price_parsing.py::test_parsing[example805]",
"tests/test_price_parsing.py::test_parsing[example806]",
"tests/test_price_parsing.py::test_parsing[example807]",
"tests/test_price_parsing.py::test_parsing[example808]",
"tests/test_price_parsing.py::test_parsing[example809]",
"tests/test_price_parsing.py::test_parsing[example810]",
"tests/test_price_parsing.py::test_parsing[example811]",
"tests/test_price_parsing.py::test_parsing[example812]",
"tests/test_price_parsing.py::test_parsing[example813]",
"tests/test_price_parsing.py::test_parsing[example814]",
"tests/test_price_parsing.py::test_parsing[example815]",
"tests/test_price_parsing.py::test_parsing[example816]",
"tests/test_price_parsing.py::test_parsing[example817]",
"tests/test_price_parsing.py::test_parsing[example818]",
"tests/test_price_parsing.py::test_parsing[example819]",
"tests/test_price_parsing.py::test_parsing[example820]",
"tests/test_price_parsing.py::test_parsing[example821]",
"tests/test_price_parsing.py::test_parsing[example822]",
"tests/test_price_parsing.py::test_parsing[example823]",
"tests/test_price_parsing.py::test_parsing[example824]",
"tests/test_price_parsing.py::test_parsing[example825]",
"tests/test_price_parsing.py::test_parsing[example826]",
"tests/test_price_parsing.py::test_parsing[example827]",
"tests/test_price_parsing.py::test_parsing[example828]",
"tests/test_price_parsing.py::test_parsing[example829]",
"tests/test_price_parsing.py::test_parsing[example830]",
"tests/test_price_parsing.py::test_parsing[example831]",
"tests/test_price_parsing.py::test_parsing[example832]",
"tests/test_price_parsing.py::test_parsing[example833]",
"tests/test_price_parsing.py::test_parsing[example834]",
"tests/test_price_parsing.py::test_parsing[example835]",
"tests/test_price_parsing.py::test_parsing[example836]",
"tests/test_price_parsing.py::test_parsing[example837]",
"tests/test_price_parsing.py::test_parsing[example838]",
"tests/test_price_parsing.py::test_parsing[example839]",
"tests/test_price_parsing.py::test_parsing[example840]",
"tests/test_price_parsing.py::test_parsing[example841]",
"tests/test_price_parsing.py::test_parsing[example842]",
"tests/test_price_parsing.py::test_parsing[example843]",
"tests/test_price_parsing.py::test_parsing[example844]",
"tests/test_price_parsing.py::test_parsing[example845]",
"tests/test_price_parsing.py::test_parsing[example846]",
"tests/test_price_parsing.py::test_parsing[example847]",
"tests/test_price_parsing.py::test_parsing[example848]",
"tests/test_price_parsing.py::test_parsing[example849]",
"tests/test_price_parsing.py::test_parsing[example850]",
"tests/test_price_parsing.py::test_parsing[example851]",
"tests/test_price_parsing.py::test_parsing[example852]",
"tests/test_price_parsing.py::test_parsing[example853]",
"tests/test_price_parsing.py::test_parsing[example854]",
"tests/test_price_parsing.py::test_parsing[example855]",
"tests/test_price_parsing.py::test_parsing[example856]",
"tests/test_price_parsing.py::test_parsing[example857]",
"tests/test_price_parsing.py::test_parsing[example858]",
"tests/test_price_parsing.py::test_parsing[example859]",
"tests/test_price_parsing.py::test_parsing[example860]",
"tests/test_price_parsing.py::test_parsing[example861]",
"tests/test_price_parsing.py::test_parsing[example862]",
"tests/test_price_parsing.py::test_parsing[example863]",
"tests/test_price_parsing.py::test_parsing[example864]",
"tests/test_price_parsing.py::test_parsing[example865]",
"tests/test_price_parsing.py::test_parsing[example866]",
"tests/test_price_parsing.py::test_parsing[example867]",
"tests/test_price_parsing.py::test_parsing[example868]",
"tests/test_price_parsing.py::test_parsing[example869]",
"tests/test_price_parsing.py::test_parsing[example870]",
"tests/test_price_parsing.py::test_parsing[example871]",
"tests/test_price_parsing.py::test_parsing[example872]",
"tests/test_price_parsing.py::test_parsing[example873]",
"tests/test_price_parsing.py::test_parsing[example874]",
"tests/test_price_parsing.py::test_parsing[example875]",
"tests/test_price_parsing.py::test_parsing[example876]",
"tests/test_price_parsing.py::test_parsing[example877]",
"tests/test_price_parsing.py::test_parsing[example878]",
"tests/test_price_parsing.py::test_parsing[example879]",
"tests/test_price_parsing.py::test_parsing[example880]",
"tests/test_price_parsing.py::test_parsing[example881]",
"tests/test_price_parsing.py::test_parsing[example882]",
"tests/test_price_parsing.py::test_parsing[example883]",
"tests/test_price_parsing.py::test_parsing[example884]",
"tests/test_price_parsing.py::test_parsing[example885]",
"tests/test_price_parsing.py::test_parsing[example886]",
"tests/test_price_parsing.py::test_parsing[example887]",
"tests/test_price_parsing.py::test_parsing[example888]",
"tests/test_price_parsing.py::test_parsing[example889]",
"tests/test_price_parsing.py::test_parsing[example890]",
"tests/test_price_parsing.py::test_parsing[example891]",
"tests/test_price_parsing.py::test_parsing[example892]",
"tests/test_price_parsing.py::test_parsing[example893]",
"tests/test_price_parsing.py::test_parsing[example894]",
"tests/test_price_parsing.py::test_parsing[example895]",
"tests/test_price_parsing.py::test_parsing[example896]",
"tests/test_price_parsing.py::test_parsing[example897]",
"tests/test_price_parsing.py::test_parsing[example898]",
"tests/test_price_parsing.py::test_parsing[example899]",
"tests/test_price_parsing.py::test_parsing[example900]",
"tests/test_price_parsing.py::test_parsing[example901]",
"tests/test_price_parsing.py::test_parsing[example902]",
"tests/test_price_parsing.py::test_parsing[example903]",
"tests/test_price_parsing.py::test_parsing[example904]",
"tests/test_price_parsing.py::test_parsing[example905]",
"tests/test_price_parsing.py::test_parsing[example906]",
"tests/test_price_parsing.py::test_parsing[example907]",
"tests/test_price_parsing.py::test_parsing[example908]",
"tests/test_price_parsing.py::test_parsing[example909]",
"tests/test_price_parsing.py::test_parsing[example910]",
"tests/test_price_parsing.py::test_parsing[example911]",
"tests/test_price_parsing.py::test_parsing[example912]",
"tests/test_price_parsing.py::test_parsing[example913]",
"tests/test_price_parsing.py::test_parsing[example914]",
"tests/test_price_parsing.py::test_parsing[example915]",
"tests/test_price_parsing.py::test_parsing[example916]",
"tests/test_price_parsing.py::test_parsing[example917]",
"tests/test_price_parsing.py::test_parsing[example918]",
"tests/test_price_parsing.py::test_parsing[example919]",
"tests/test_price_parsing.py::test_parsing[example920]",
"tests/test_price_parsing.py::test_parsing[example921]",
"tests/test_price_parsing.py::test_parsing[example922]",
"tests/test_price_parsing.py::test_parsing[example923]",
"tests/test_price_parsing.py::test_parsing[example924]",
"tests/test_price_parsing.py::test_parsing[example925]",
"tests/test_price_parsing.py::test_parsing[example926]",
"tests/test_price_parsing.py::test_parsing[example927]",
"tests/test_price_parsing.py::test_parsing[example928]",
"tests/test_price_parsing.py::test_parsing[example929]",
"tests/test_price_parsing.py::test_parsing[example930]",
"tests/test_price_parsing.py::test_parsing[example931]",
"tests/test_price_parsing.py::test_parsing[example932]",
"tests/test_price_parsing.py::test_parsing[example933]",
"tests/test_price_parsing.py::test_price_amount_float[None-None]",
"tests/test_price_parsing.py::test_price_amount_float[amount1-1.23]",
"tests/test_price_parsing.py::test_price_decimal_separator[140.000-None-expected_result0]",
"tests/test_price_parsing.py::test_price_decimal_separator[140.000-,-expected_result1]",
"tests/test_price_parsing.py::test_price_decimal_separator[140.000-.-expected_result2]",
"tests/test_price_parsing.py::test_price_decimal_separator[140\\u20ac33-\\u20ac-expected_result3]",
"tests/test_price_parsing.py::test_price_decimal_separator[140,000\\u20ac33-\\u20ac-expected_result4]",
"tests/test_price_parsing.py::test_price_decimal_separator[140.000\\u20ac33-\\u20ac-expected_result5]"
] |
{
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-11-21 19:09:38+00:00
|
bsd-3-clause
| 5,394 |
|
scrapinghub__spidermon-234
|
diff --git a/spidermon/contrib/actions/slack/__init__.py b/spidermon/contrib/actions/slack/__init__.py
index 8674c0e..0de8dd4 100644
--- a/spidermon/contrib/actions/slack/__init__.py
+++ b/spidermon/contrib/actions/slack/__init__.py
@@ -194,7 +194,7 @@ class SendSlackMessage(ActionWithTemplates):
return {
"sender_token": crawler.settings.get("SPIDERMON_SLACK_SENDER_TOKEN"),
"sender_name": crawler.settings.get("SPIDERMON_SLACK_SENDER_NAME"),
- "recipients": crawler.settings.get("SPIDERMON_SLACK_RECIPIENTS"),
+ "recipients": crawler.settings.getlist("SPIDERMON_SLACK_RECIPIENTS"),
"message": crawler.settings.get("SPIDERMON_SLACK_MESSAGE"),
"message_template": crawler.settings.get(
"SPIDERMON_SLACK_MESSAGE_TEMPLATE"
|
scrapinghub/spidermon
|
deecd7527971a1dfd3aa646de88acbc81696da81
|
diff --git a/tests/contrib/actions/slack/test_slack_message_manager.py b/tests/contrib/actions/slack/test_slack_message_manager.py
index 1035957..63ee934 100644
--- a/tests/contrib/actions/slack/test_slack_message_manager.py
+++ b/tests/contrib/actions/slack/test_slack_message_manager.py
@@ -1,5 +1,11 @@
import pytest
-from spidermon.contrib.actions.slack import SlackMessageManager
+
+from scrapy.utils.test import get_crawler
+
+from spidermon.contrib.actions.slack import (
+ SlackMessageManager,
+ SendSlackMessage,
+)
@pytest.fixture
@@ -39,3 +45,13 @@ def test_api_call_with_error_should_log_error_msg(mocker, logger_error):
assert logger_error.call_count == 1
assert error_msg in logger_error.call_args_list[0][0]
+
+
[email protected]("recipients", ["foo,bar", ["foo", "bar"]])
+def test_load_recipients_list_from_crawler_settings(recipients):
+ settings = {
+ "SPIDERMON_SLACK_RECIPIENTS": recipients,
+ }
+ crawler = get_crawler(settings_dict=settings)
+ kwargs = SendSlackMessage.from_crawler_kwargs(crawler)
+ assert kwargs["recipients"] == ["foo", "bar"]
|
It's not possible to specify SPIDERMON_SLACK_RECIPIENTS via Scrapy Cloud
We should replace `settings.get` by `settings.getlist`. I'm working on a pull request.
|
0.0
|
deecd7527971a1dfd3aa646de88acbc81696da81
|
[
"tests/contrib/actions/slack/test_slack_message_manager.py::test_load_recipients_list_from_crawler_settings[foo,bar]"
] |
[
"tests/contrib/actions/slack/test_slack_message_manager.py::test_api_call_with_no_error_should_not_log_messages",
"tests/contrib/actions/slack/test_slack_message_manager.py::test_api_call_with_error_should_log_error_msg",
"tests/contrib/actions/slack/test_slack_message_manager.py::test_load_recipients_list_from_crawler_settings[recipients1]"
] |
{
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-11-28 21:40:51+00:00
|
bsd-3-clause
| 5,395 |
|
scrapinghub__spidermon-343
|
diff --git a/docs/source/howto/stats-collection.rst b/docs/source/howto/stats-collection.rst
index a95c32c..60c83bd 100644
--- a/docs/source/howto/stats-collection.rst
+++ b/docs/source/howto/stats-collection.rst
@@ -22,7 +22,7 @@ To enable it, include the following code in your project settings:
# tutorial/settings.py
STATS_CLASS = (
- "spidermon.contrib.stats.statscollectors.LocalStorageStatsHistoryCollector"
+ "spidermon.contrib.stats.statscollectors.local_storage.LocalStorageStatsHistoryCollector"
)
# Stores the stats of the last 10 spider execution (default=100)
@@ -70,12 +70,12 @@ returned in the previous spider executions.
class SpiderCloseMonitorSuite(MonitorSuite):
monitors = [HistoryMonitor]
-When running on `Scrapy Cloud`_ you can use ``spidermon.contrib.stats.statscollectors.DashCollectionsStatsHistoryCollector`` instead.
+When running on `Scrapy Cloud`_ you can use ``spidermon.contrib.stats.statscollectors.sc_collections.ScrapyCloudCollectionsStatsHistoryCollector`` instead.
This will save your stats in a `collection`_ on your scrapy dashboard, named like ``{your_spider_name}_stats_history``. The rest of the sample code presented previously will work unchanged.
.. warning::
- `STATS_CLASS`_ is overriden by default in `Scrapy Cloud`_. You need to manually include ``spidermon.contrib.stats.statscollectors.DashCollectionsStatsHistoryCollector`` in your `spider settings`_.
+ `STATS_CLASS`_ is overriden by default in `Scrapy Cloud`_. You need to manually include ``spidermon.contrib.stats.statscollectors.sc_collections.DashCollectionsStatsHistoryCollector`` in your `spider settings`_.
.. _`STATS_CLASS`: https://docs.scrapy.org/en/latest/topics/settings.html#stats-class
.. _`spider settings`: https://support.zyte.com/support/solutions/articles/22000200670-customizing-scrapy-settings-in-scrapy-cloud
diff --git a/examples/tutorial/tutorial/settings.py b/examples/tutorial/tutorial/settings.py
index b6f9b92..61cc8e2 100644
--- a/examples/tutorial/tutorial/settings.py
+++ b/examples/tutorial/tutorial/settings.py
@@ -19,9 +19,7 @@ SPIDERMON_VALIDATION_MODELS = ("tutorial.validators.QuoteItem",)
SPIDERMON_VALIDATION_ADD_ERRORS_TO_ITEMS = True
-STATS_CLASS = (
- "spidermon.contrib.stats.statscollectors.LocalStorageStatsHistoryCollector"
-)
+STATS_CLASS = "spidermon.contrib.stats.statscollectors.local_storage.LocalStorageStatsHistoryCollector"
SPIDERMON_MAX_STORED_STATS = 10 # Stores the stats of the last 10 spider execution
diff --git a/spidermon/contrib/stats/statscollectors/__init__.py b/spidermon/contrib/stats/statscollectors/__init__.py
new file mode 100644
index 0000000..c2c519b
--- /dev/null
+++ b/spidermon/contrib/stats/statscollectors/__init__.py
@@ -0,0 +1,3 @@
+from spidermon.contrib.stats.statscollectors.local_storage import (
+ LocalStorageStatsHistoryCollector,
+)
diff --git a/spidermon/contrib/stats/statscollectors/local_storage.py b/spidermon/contrib/stats/statscollectors/local_storage.py
new file mode 100644
index 0000000..ae6a99d
--- /dev/null
+++ b/spidermon/contrib/stats/statscollectors/local_storage.py
@@ -0,0 +1,37 @@
+import os
+import pickle
+from collections import deque
+
+from scrapy.statscollectors import StatsCollector
+from scrapy.utils.project import data_path
+
+
+class LocalStorageStatsHistoryCollector(StatsCollector):
+ def _stats_location(self, spider):
+ statsdir = data_path("stats", createdir=True)
+ return os.path.join(statsdir, f"{spider.name}_stats_history")
+
+ def open_spider(self, spider):
+ stats_location = self._stats_location(spider)
+
+ max_stored_stats = spider.crawler.settings.getint(
+ "SPIDERMON_MAX_STORED_STATS", default=100
+ )
+
+ if os.path.isfile(stats_location):
+ with open(stats_location, "rb") as stats_file:
+ _stats_history = pickle.load(stats_file)
+ else:
+ _stats_history = deque([], maxlen=max_stored_stats)
+
+ if _stats_history.maxlen != max_stored_stats:
+ _stats_history = deque(_stats_history, maxlen=max_stored_stats)
+
+ spider.stats_history = _stats_history
+
+ def _persist_stats(self, stats, spider):
+ stats_location = self._stats_location(spider)
+
+ spider.stats_history.appendleft(self._stats)
+ with open(stats_location, "wb") as stats_file:
+ pickle.dump(spider.stats_history, stats_file)
diff --git a/spidermon/contrib/stats/statscollectors.py b/spidermon/contrib/stats/statscollectors/sc_collections.py
similarity index 60%
rename from spidermon/contrib/stats/statscollectors.py
rename to spidermon/contrib/stats/statscollectors/sc_collections.py
index 13cf7cb..2ca98b0 100644
--- a/spidermon/contrib/stats/statscollectors.py
+++ b/spidermon/contrib/stats/statscollectors/sc_collections.py
@@ -1,48 +1,14 @@
import logging
import os
-import pickle
from collections import deque
import scrapinghub
-from scrapy.statscollectors import StatsCollector
-from scrapy.utils.project import data_path
from sh_scrapy.stats import HubStorageStatsCollector
logger = logging.getLogger(__name__)
-class LocalStorageStatsHistoryCollector(StatsCollector):
- def _stats_location(self, spider):
- statsdir = data_path("stats", createdir=True)
- return os.path.join(statsdir, f"{spider.name}_stats_history")
-
- def open_spider(self, spider):
- stats_location = self._stats_location(spider)
-
- max_stored_stats = spider.crawler.settings.getint(
- "SPIDERMON_MAX_STORED_STATS", default=100
- )
-
- if os.path.isfile(stats_location):
- with open(stats_location, "rb") as stats_file:
- _stats_history = pickle.load(stats_file)
- else:
- _stats_history = deque([], maxlen=max_stored_stats)
-
- if _stats_history.maxlen != max_stored_stats:
- _stats_history = deque(_stats_history, maxlen=max_stored_stats)
-
- spider.stats_history = _stats_history
-
- def _persist_stats(self, stats, spider):
- stats_location = self._stats_location(spider)
-
- spider.stats_history.appendleft(self._stats)
- with open(stats_location, "wb") as stats_file:
- pickle.dump(spider.stats_history, stats_file)
-
-
-class DashCollectionsStatsHistoryCollector(HubStorageStatsCollector):
+class ScrapyCloudCollectionsStatsHistoryCollector(HubStorageStatsCollector):
def _open_collection(self, spider):
sh_client = scrapinghub.ScrapinghubClient()
proj_id = os.environ.get("SCRAPY_PROJECT_ID")
|
scrapinghub/spidermon
|
1d2972a88048b9dcf92cdb02f7cf5edb5b42c09b
|
diff --git a/tests/contrib/stats/statscollectors/__init__.py b/tests/contrib/stats/statscollectors/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/tests/contrib/stats/test_localstoragestats.py b/tests/contrib/stats/statscollectors/test_local_storage.py
similarity index 79%
rename from tests/contrib/stats/test_localstoragestats.py
rename to tests/contrib/stats/statscollectors/test_local_storage.py
index bc5d488..1e117cb 100644
--- a/tests/contrib/stats/test_localstoragestats.py
+++ b/tests/contrib/stats/statscollectors/test_local_storage.py
@@ -5,7 +5,9 @@ import pytest
from scrapy import Spider
from scrapy.utils.test import get_crawler
-from spidermon.contrib.stats.statscollectors import LocalStorageStatsHistoryCollector
+from spidermon.contrib.stats.statscollectors.local_storage import (
+ LocalStorageStatsHistoryCollector,
+)
@pytest.fixture
@@ -21,7 +23,7 @@ def stats_temporary_location(monkeypatch, tmp_path):
def test_settings():
return {
"STATS_CLASS": (
- "spidermon.contrib.stats.statscollectors.LocalStorageStatsHistoryCollector"
+ "spidermon.contrib.stats.statscollectors.local_storage.LocalStorageStatsHistoryCollector"
)
}
@@ -126,3 +128,25 @@ def test_spider_limit_number_of_stored_stats(test_settings, stats_temporary_loca
assert "third_execution" in crawler.spider.stats_history[0].keys()
assert "second_execution" in crawler.spider.stats_history[1].keys()
crawler.stop()
+
+
+def test_able_to_import_deprecated_local_storage_stats_collector_module():
+ """
+ To avoid an error when importing this stats collector with the old location
+ in legacy code, we need to ensure that LocalStorageStatsHistoryCollector can
+ be imported as the old module.
+
+ Original module:
+ spidermon.contrib.stats.statscollectors.LocalStorageStatsHistoryCollector
+
+ New module:
+ spidermon.contrib.stats.statscollectors.local_storage.LocalStorageStatsHistoryCollector
+ """
+ try:
+ from spidermon.contrib.stats.statscollectors import (
+ LocalStorageStatsHistoryCollector,
+ )
+ except ModuleNotFoundError:
+ assert (
+ False
+ ), f"Unable to import spidermon.contrib.stats.statscollectors.LocalStorageStatsHistoryCollector"
diff --git a/tests/contrib/stats/test_dashcollectionsstats.py b/tests/contrib/stats/statscollectors/test_sc_collections.py
similarity index 84%
rename from tests/contrib/stats/test_dashcollectionsstats.py
rename to tests/contrib/stats/statscollectors/test_sc_collections.py
index 232c5f7..5741959 100644
--- a/tests/contrib/stats/test_dashcollectionsstats.py
+++ b/tests/contrib/stats/statscollectors/test_sc_collections.py
@@ -6,7 +6,9 @@ import scrapinghub
from scrapy import Spider
from scrapy.utils.test import get_crawler
-from spidermon.contrib.stats.statscollectors import DashCollectionsStatsHistoryCollector
+from spidermon.contrib.stats.statscollectors.sc_collections import (
+ ScrapyCloudCollectionsStatsHistoryCollector,
+)
class StoreMock:
@@ -27,7 +29,7 @@ class StoreMock:
def stats_collection(monkeypatch):
store = StoreMock()
monkeypatch.setattr(
- DashCollectionsStatsHistoryCollector,
+ ScrapyCloudCollectionsStatsHistoryCollector,
"_open_collection",
lambda *args: store,
)
@@ -38,7 +40,7 @@ def stats_collection_not_exist(monkeypatch):
store = StoreMock()
store.raise_iter_error = True
monkeypatch.setattr(
- DashCollectionsStatsHistoryCollector,
+ ScrapyCloudCollectionsStatsHistoryCollector,
"_open_collection",
lambda *args: store,
)
@@ -48,31 +50,31 @@ def stats_collection_not_exist(monkeypatch):
def test_settings():
return {
"STATS_CLASS": (
- "spidermon.contrib.stats.statscollectors.DashCollectionsStatsHistoryCollector"
+ "spidermon.contrib.stats.statscollectors.sc_collections.ScrapyCloudCollectionsStatsHistoryCollector"
)
}
-@patch("spidermon.contrib.stats.statscollectors.scrapinghub")
+@patch("spidermon.contrib.stats.statscollectors.sc_collections.scrapinghub")
def test_open_spider_without_api(scrapinghub_mock, test_settings):
mock_spider = MagicMock()
crawler = get_crawler(Spider, test_settings)
- pipe = DashCollectionsStatsHistoryCollector(crawler)
+ pipe = ScrapyCloudCollectionsStatsHistoryCollector(crawler)
pipe.open_spider(mock_spider)
assert pipe.store is None
-@patch("spidermon.contrib.stats.statscollectors.scrapinghub")
-@patch("spidermon.contrib.stats.statscollectors.os.environ.get")
-def test_open_collection_with_api(scrapinghub_mock, os_enviorn_mock, test_settings):
+@patch("spidermon.contrib.stats.statscollectors.sc_collections.scrapinghub")
+@patch("spidermon.contrib.stats.statscollectors.sc_collections.os.environ.get")
+def test_open_collection_with_api(scrapinghub_mock, os_environ_mock, test_settings):
mock_spider = MagicMock()
mock_spider.name = "test"
- os_enviorn_mock.return_value = 1234
+ os_environ_mock.return_value = 1234
crawler = get_crawler(Spider, test_settings)
- pipe = DashCollectionsStatsHistoryCollector(crawler)
+ pipe = ScrapyCloudCollectionsStatsHistoryCollector(crawler)
store = pipe._open_collection(mock_spider)
@@ -181,7 +183,7 @@ def test_spider_limit_number_of_stored_stats(test_settings, stats_collection):
crawler.stop()
-@patch("spidermon.contrib.stats.statscollectors.os.environ.get")
+@patch("spidermon.contrib.stats.statscollectors.sc_collections.os.environ.get")
def test_job_id_added(mock_os_enviorn_get, test_settings, stats_collection):
mock_os_enviorn_get.return_value = "test/test/test"
crawler = get_crawler(Spider, test_settings)
@@ -195,7 +197,7 @@ def test_job_id_added(mock_os_enviorn_get, test_settings, stats_collection):
)
-@patch("spidermon.contrib.stats.statscollectors.os.environ.get")
+@patch("spidermon.contrib.stats.statscollectors.sc_collections.os.environ.get")
def test_job_id_not_available(mock_os_enviorn_get, test_settings, stats_collection):
mock_os_enviorn_get.return_value = None
crawler = get_crawler(Spider, test_settings)
@@ -206,7 +208,7 @@ def test_job_id_not_available(mock_os_enviorn_get, test_settings, stats_collecti
assert "job_url" not in crawler.spider.stats_history[0]
-@patch("spidermon.contrib.stats.statscollectors.os.environ.get")
+@patch("spidermon.contrib.stats.statscollectors.sc_collections.os.environ.get")
def test_stats_history_when_no_collection(
os_enviorn_mock, stats_collection_not_exist, test_settings
):
@@ -216,6 +218,6 @@ def test_stats_history_when_no_collection(
os_enviorn_mock.return_value = 1234
crawler = get_crawler(Spider, test_settings)
- pipe = DashCollectionsStatsHistoryCollector(crawler)
+ pipe = ScrapyCloudCollectionsStatsHistoryCollector(crawler)
pipe.open_spider(mock_spider)
assert mock_spider.stats_history == deque([], maxlen=100)
|
Fix "ModuleNotFoundError" when adding LocalStorageStatsHistoryCollector
This error only happens when #340 is fixed (we need https://github.com/scrapinghub/spidermon/issues/342 to be merged so we can reproduce this error) and we add the following value for `STATS_CLASS` in our project settings:
```
STATS_CLASS = (
"spidermon.contrib.stats.statscollectors.LocalStorageStatsHistoryCollector"
)
```
Because `DashCollectionsStatsHistoryCollector` uses `scrapinghub` library, we have the following error:
```
2022-03-25 18:02:06 [scrapy.utils.log] INFO: Scrapy 2.6.1 started (bot: tutorial)
2022-03-25 18:02:06 [scrapy.utils.log] INFO: Versions: lxml 4.8.0.0, libxml2 2.9.12, cssselect 1.1.0, parsel 1.6.0, w3lib 1.22.0, Twisted 22.2.0, Python 3.8.10 (default, Nov 26 2021, 20:14:08) - [GCC 9.3.0], pyOpenSSL 22.0.0 (OpenSSL 1.1.1n 15 Mar 2022), cryptography 36.0.2, Platform Linux-5.4.0-105-generic-x86_64-with-glibc2.29
Traceback (most recent call last):
File "/home/renne/.pyenv/versions/spidermon-test-clean-install/bin/scrapy", line 8, in <module>
sys.exit(execute())
File "/home/renne/.pyenv/versions/spidermon-test-clean-install/lib/python3.8/site-packages/scrapy/cmdline.py", line 145, in execute
_run_print_help(parser, _run_command, cmd, args, opts)
File "/home/renne/.pyenv/versions/spidermon-test-clean-install/lib/python3.8/site-packages/scrapy/cmdline.py", line 100, in _run_print_help
func(*a, **kw)
File "/home/renne/.pyenv/versions/spidermon-test-clean-install/lib/python3.8/site-packages/scrapy/cmdline.py", line 153, in _run_command
cmd.run(args, opts)
File "/home/renne/.pyenv/versions/spidermon-test-clean-install/lib/python3.8/site-packages/scrapy/commands/crawl.py", line 22, in run
crawl_defer = self.crawler_process.crawl(spname, **opts.spargs)
File "/home/renne/.pyenv/versions/spidermon-test-clean-install/lib/python3.8/site-packages/scrapy/crawler.py", line 205, in crawl
crawler = self.create_crawler(crawler_or_spidercls)
File "/home/renne/.pyenv/versions/spidermon-test-clean-install/lib/python3.8/site-packages/scrapy/crawler.py", line 238, in create_crawler
return self._create_crawler(crawler_or_spidercls)
File "/home/renne/.pyenv/versions/spidermon-test-clean-install/lib/python3.8/site-packages/scrapy/crawler.py", line 313, in _create_crawler
return Crawler(spidercls, self.settings, init_reactor=True)
File "/home/renne/.pyenv/versions/spidermon-test-clean-install/lib/python3.8/site-packages/scrapy/crawler.py", line 54, in __init__
self.stats = load_object(self.settings['STATS_CLASS'])(self)
File "/home/renne/.pyenv/versions/spidermon-test-clean-install/lib/python3.8/site-packages/scrapy/utils/misc.py", line 61, in load_object
mod = import_module(module)
File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 848, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/home/renne/projects/rennerocha/spidermon/spidermon/contrib/stats/statscollectors.py", line 6, in <module>
import scrapinghub
ModuleNotFoundError: No module named 'scrapinghub'
```
|
0.0
|
1d2972a88048b9dcf92cdb02f7cf5edb5b42c09b
|
[
"tests/contrib/stats/statscollectors/test_local_storage.py::test_spider_has_stats_history_attribute_when_opened_with_collector",
"tests/contrib/stats/statscollectors/test_local_storage.py::test_spider_has_stats_history_queue_with_specified_max_size",
"tests/contrib/stats/statscollectors/test_local_storage.py::test_spider_update_stats_history_queue_max_size[5-2]",
"tests/contrib/stats/statscollectors/test_local_storage.py::test_spider_update_stats_history_queue_max_size[5-10]",
"tests/contrib/stats/statscollectors/test_local_storage.py::test_spider_update_stats_history_queue_max_size[5-5]",
"tests/contrib/stats/statscollectors/test_local_storage.py::test_spider_has_last_stats_history_when_opened_again",
"tests/contrib/stats/statscollectors/test_local_storage.py::test_spider_has_two_last_stats_history_when_opened_third_time",
"tests/contrib/stats/statscollectors/test_local_storage.py::test_spider_limit_number_of_stored_stats",
"tests/contrib/stats/statscollectors/test_local_storage.py::test_able_to_import_deprecated_local_storage_stats_collector_module",
"tests/contrib/stats/statscollectors/test_sc_collections.py::test_open_spider_without_api",
"tests/contrib/stats/statscollectors/test_sc_collections.py::test_open_collection_with_api",
"tests/contrib/stats/statscollectors/test_sc_collections.py::test_spider_has_stats_history_attribute_when_opened_with_collector",
"tests/contrib/stats/statscollectors/test_sc_collections.py::test_spider_has_stats_history_queue_with_specified_max_size",
"tests/contrib/stats/statscollectors/test_sc_collections.py::test_spider_update_stats_history_queue_max_size[5-2]",
"tests/contrib/stats/statscollectors/test_sc_collections.py::test_spider_update_stats_history_queue_max_size[5-10]",
"tests/contrib/stats/statscollectors/test_sc_collections.py::test_spider_update_stats_history_queue_max_size[5-5]",
"tests/contrib/stats/statscollectors/test_sc_collections.py::test_spider_has_last_stats_history_when_opened_again",
"tests/contrib/stats/statscollectors/test_sc_collections.py::test_spider_has_two_last_stats_history_when_opened_third_time",
"tests/contrib/stats/statscollectors/test_sc_collections.py::test_spider_limit_number_of_stored_stats",
"tests/contrib/stats/statscollectors/test_sc_collections.py::test_job_id_added",
"tests/contrib/stats/statscollectors/test_sc_collections.py::test_job_id_not_available",
"tests/contrib/stats/statscollectors/test_sc_collections.py::test_stats_history_when_no_collection"
] |
[] |
{
"failed_lite_validators": [
"has_issue_reference",
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-03-25 21:05:55+00:00
|
bsd-3-clause
| 5,396 |
|
scrapinghub__spidermon-365
|
diff --git a/docs/source/actions/custom-action.rst b/docs/source/actions/custom-action.rst
index b1401f2..81b81b9 100644
--- a/docs/source/actions/custom-action.rst
+++ b/docs/source/actions/custom-action.rst
@@ -13,3 +13,41 @@ the `run_action` method.
def run_action(self):
# Include here the logic of your action
# (...)
+
+
+Fallback Actions
+================
+
+When creating your own custom actions, you can also add a fallback action to run if
+an action throws an unhandled exception. To do this, add a fallback attribute to
+your custom action.
+
+.. code-block:: python
+
+ from spidermon.core.actions import Action
+
+ class MyFallbackAction(Action):
+ def run_action(self):
+ # Include here the logic of your action
+ # Runs if MyCustomAction().run_action() throws an unhandled exception
+ # (...)
+
+ class MyCustomAction(Action):
+ fallback = MyFallbackAction
+ def run_action(self):
+ # Include here the logic of your action
+ # (...)
+
+
+You can also add fallbacks to spidermon built-in actions by subclassing them. For
+example, send an email if a slack message could not be sent.
+
+.. code-block:: python
+
+ from spidermon.core.actions import Action
+ from spidermon.contrib.actions import Slack
+ from spidermon.contrib.actions.email.smtp import SendSmtpEmail
+
+ class MyCustomSlackAction(Slack):
+ fallback = SendSmtpEmail
+
diff --git a/spidermon/core/actions.py b/spidermon/core/actions.py
index a9ae690..c7a0441 100644
--- a/spidermon/core/actions.py
+++ b/spidermon/core/actions.py
@@ -11,9 +11,13 @@ class Action(metaclass=ActionOptionsMetaclass):
Base class for actions.
"""
+ fallback = None
+
def __init__(self):
self.result = None
self.data = None
+ if self.fallback is not None:
+ self.fallback = self.fallback()
@classmethod
def from_crawler(cls, crawler):
@@ -37,6 +41,8 @@ class Action(metaclass=ActionOptionsMetaclass):
result.add_action_skip(self, e.args[0])
except:
result.add_action_error(self, traceback.format_exc())
+ if self.fallback is not None:
+ self.fallback.run(self.result, self.data)
else:
result.add_action_success(self)
data.meta.update(self.get_meta())
|
scrapinghub/spidermon
|
9c2091304779cfb751ed3238f7ce78dbc7e82735
|
diff --git a/tests/test_actions.py b/tests/test_actions.py
new file mode 100644
index 0000000..b2577e5
--- /dev/null
+++ b/tests/test_actions.py
@@ -0,0 +1,94 @@
+from spidermon.core.actions import Action
+from spidermon.exceptions import NotConfigured, SkipAction
+from unittest.mock import MagicMock
+
+
+def test_action_success():
+ class TestAction(Action):
+ def run_action(self):
+ pass
+
+ result_mock = MagicMock()
+ action = TestAction()
+
+ action.run(result_mock, MagicMock())
+
+ result_mock.add_action_success.assert_called()
+
+
+def test_action_fail():
+ class TestAction(Action):
+ def run_action(self):
+ raise Exception
+
+ result_mock = MagicMock()
+ action = TestAction()
+
+ action.run(result_mock, MagicMock())
+
+ result_mock.add_action_error.assert_called()
+ result_mock.add_action_success.assert_not_called()
+
+
+def test_action_skip():
+ class TestAction(Action):
+ def run_action(self):
+ raise SkipAction("Test")
+
+ result_mock = MagicMock()
+ action = TestAction()
+
+ action.run(result_mock, MagicMock())
+
+ result_mock.add_action_skip.assert_called()
+
+
+def test_fallback_action():
+ fallback_mock = MagicMock()
+
+ class TestAction(Action):
+ fallback = fallback_mock
+
+ def run_action(self):
+ raise Exception
+
+ action = TestAction()
+ action.run(MagicMock(), MagicMock())
+
+ fallback_mock.assert_called()
+ fallback_mock().run.assert_called()
+
+
+def test_fallback_skip_action():
+ # fallback not called for SkipAction exception
+ fallback_mock = MagicMock()
+
+ class TestAction(Action):
+ fallback = fallback_mock
+
+ def run_action(self):
+ raise SkipAction("Test")
+
+ action = TestAction()
+
+ action.run(MagicMock(), MagicMock())
+ fallback_mock().run.assert_not_called()
+
+
+def test_fallback_not_configured():
+ # raises not configured error for unconfigured fallback actions
+ fallback_mock = MagicMock()
+ fallback_mock.side_effect = NotConfigured
+
+ class TestAction(Action):
+ fallback = fallback_mock
+
+ def run_action(self):
+ pass
+
+ try:
+ TestAction()
+ except NotConfigured:
+ assert True
+ else:
+ assert False
|
feature: Fallback for actions
This was an idea proposed by Chandral from Zyte to address Sentry downtimes, as important Spidermon alerts might get lost while this happens.
Multiple alert actions can be configured in Spidermon as a workaround to prevent messages from getting lost if one of the services is down, but receiving duplicated alerts would generate a lot of noise. Ideally, we'd like to use a backup alert system as a fallback only if the main alert system didn't work.
/cc @rennerocha @VMRuiz
|
0.0
|
9c2091304779cfb751ed3238f7ce78dbc7e82735
|
[
"tests/test_actions.py::test_fallback_action",
"tests/test_actions.py::test_fallback_not_configured"
] |
[
"tests/test_actions.py::test_action_success",
"tests/test_actions.py::test_action_fail",
"tests/test_actions.py::test_action_skip",
"tests/test_actions.py::test_fallback_skip_action"
] |
{
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-11-02 16:46:41+00:00
|
bsd-3-clause
| 5,397 |
|
scrapinghub__web-poet-142
|
diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index c88ec58..5ab56e4 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -2,6 +2,15 @@
Changelog
=========
+TBR
+---
+
+* Fix the error when calling :meth:`.to_item() <web_poet.pages.ItemPage.to_item>`,
+ :func:`item_from_fields_sync() <web_poet.fields.item_from_fields_sync>`, or
+ :func:`item_from_fields() <web_poet.fields.item_from_fields>` on page objects
+ defined as slotted attrs classes, while setting ``skip_nonitem_fields=True``.
+
+
0.8.0 (2023-02-23)
------------------
diff --git a/web_poet/pages.py b/web_poet/pages.py
index 77b39af..fed2fae 100644
--- a/web_poet/pages.py
+++ b/web_poet/pages.py
@@ -50,21 +50,34 @@ class Returns(typing.Generic[ItemT]):
return get_item_cls(self.__class__, default=dict)
+_NOT_SET = object()
+
+
class ItemPage(Injectable, Returns[ItemT]):
"""Base Page Object, with a default :meth:`to_item` implementation
which supports web-poet fields.
"""
- _skip_nonitem_fields: bool
+ _skip_nonitem_fields = _NOT_SET
+
+ def _get_skip_nonitem_fields(self) -> bool:
+ value = self._skip_nonitem_fields
+ return False if value is _NOT_SET else bool(value)
- def __init_subclass__(cls, skip_nonitem_fields: bool = False, **kwargs):
+ def __init_subclass__(cls, skip_nonitem_fields=_NOT_SET, **kwargs):
super().__init_subclass__(**kwargs)
+ if skip_nonitem_fields is _NOT_SET:
+ # This is a workaround for attrs issue.
+ # See: https://github.com/scrapinghub/web-poet/issues/141
+ return
cls._skip_nonitem_fields = skip_nonitem_fields
async def to_item(self) -> ItemT:
"""Extract an item from a web page"""
return await item_from_fields(
- self, item_cls=self.item_cls, skip_nonitem_fields=self._skip_nonitem_fields
+ self,
+ item_cls=self.item_cls,
+ skip_nonitem_fields=self._get_skip_nonitem_fields(),
)
|
scrapinghub/web-poet
|
a369635f3d4cf1acc22acf967625fe51c8cd57ae
|
diff --git a/tests/test_pages.py b/tests/test_pages.py
index fa3cf8d..d54f094 100644
--- a/tests/test_pages.py
+++ b/tests/test_pages.py
@@ -3,7 +3,7 @@ from typing import Optional
import attrs
import pytest
-from web_poet import HttpResponse, field
+from web_poet import HttpResponse, PageParams, field
from web_poet.pages import (
Injectable,
ItemPage,
@@ -199,11 +199,27 @@ async def test_item_page_change_item_type_remove_fields() -> None:
class Subclass(BasePage, Returns[Item], skip_nonitem_fields=True):
pass
- page = Subclass()
+ # Same as above but a slotted attrs class with dependency.
+ # See: https://github.com/scrapinghub/web-poet/issues/141
+ @attrs.define
+ class SubclassWithDep(BasePage, Returns[Item], skip_nonitem_fields=True):
+ params: PageParams
+
+ # Check if flicking skip_nonitem_fields to False in the subclass works
+ @attrs.define
+ class SubclassSkipFalse(SubclassWithDep, Returns[Item], skip_nonitem_fields=False):
+ pass
+
+ for page in [Subclass(), SubclassWithDep(params=PageParams())]:
+ assert page.item_cls is Item
+ item = await page.to_item()
+ assert isinstance(item, Item)
+ assert item == Item(name="hello")
+
+ page = SubclassSkipFalse(params=PageParams())
assert page.item_cls is Item
- item = await page.to_item()
- assert isinstance(item, Item)
- assert item == Item(name="hello")
+ with pytest.raises(TypeError, match="unexpected keyword argument 'price'"):
+ await page.to_item()
# Item only contains "name", but not "price", but "price" should be passed
class SubclassStrict(BasePage, Returns[Item]):
|
`skip_nonitem_fields=True` doesn't work when the page object is an attrs class
Currently, this works fine:
```python
import attrs
from web_poet import HttpResponse, Returns, ItemPage, field
@attrs.define
class BigItem:
x: int
y: int
class BigPage(ItemPage[BigItem]):
@field
def x(self):
return 1
@field
def y(self):
return 2
@attrs.define
class SmallItem:
x: int
class SmallXPage(BigPage, Returns[SmallItem], skip_nonitem_fields=True):
pass
page = SmallXPage()
item = await page.to_item()
print(page._skip_nonitem_fields) # True
print(item) # SmallItem(x=1)
```
However, if we define an attrs class to have some page dependencies, it doesn't work:
```python
from web_poet import PageParams
@attrs.define
class SmallPage(BigPage, Returns[SmallItem], skip_nonitem_fields=True):
params: PageParams
page = SmallPage(params=PageParams())
print(page._skip_nonitem_fields) # False
item = await page.to_item() # TypeError: __init__() got an unexpected keyword argument 'y'
```
From the examples above, this stems from `page._skip_nonitem_fields` being set to `False` when the page object is defined as an attrs class.
|
0.0
|
a369635f3d4cf1acc22acf967625fe51c8cd57ae
|
[
"tests/test_pages.py::test_item_page_change_item_type_remove_fields"
] |
[
"tests/test_pages.py::test_page_object",
"tests/test_pages.py::test_web_page_object",
"tests/test_pages.py::test_item_web_page_deprecated",
"tests/test_pages.py::test_is_injectable",
"tests/test_pages.py::test_item_page_typed",
"tests/test_pages.py::test_web_page_fields",
"tests/test_pages.py::test_item_page_typed_subclass",
"tests/test_pages.py::test_item_page_fields_typo",
"tests/test_pages.py::test_item_page_required_field_missing",
"tests/test_pages.py::test_item_page_change_item_type_extra_fields"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-02-22 15:11:06+00:00
|
bsd-3-clause
| 5,398 |
|
scrapinghub__web-poet-184
|
diff --git a/docs/page-objects/items.rst b/docs/page-objects/items.rst
index 4fc7980..0526b14 100644
--- a/docs/page-objects/items.rst
+++ b/docs/page-objects/items.rst
@@ -42,6 +42,11 @@ To keep your code maintainable, we recommend you to:
:ref:`page object classes <page-object-classes>`, e.g. using :ref:`field
processors <field-processors>`.
+ Having code that makes item field values different from their counterpart
+ page object field values can subvert the expectations of users of your
+ code, which might need to access page object fields directly, for example
+ for field subset selection.
+
If you are looking for ready-made item classes, check out `zyte-common-items`_.
.. _zyte-common-items: https://zyte-common-items.readthedocs.io/en/latest/index.html
diff --git a/web_poet/_typing.py b/web_poet/_typing.py
deleted file mode 100644
index d7a2c98..0000000
--- a/web_poet/_typing.py
+++ /dev/null
@@ -1,24 +0,0 @@
-"""Utilities for typing"""
-import typing
-
-
-def is_generic_alias(obj) -> bool:
- for attr_name in ["GenericAlias", "_GenericAlias"]:
- if hasattr(typing, attr_name):
- if isinstance(obj, getattr(typing, attr_name)):
- return True
- return False
-
-
-def get_generic_parameter(cls):
- for base in getattr(cls, "__orig_bases__", []):
- if is_generic_alias(base):
- args = typing.get_args(base)
- return args[0]
-
-
-def get_item_cls(cls, default=None):
- param = get_generic_parameter(cls)
- if param is None or isinstance(param, typing.TypeVar): # class is not parametrized
- return default
- return param
diff --git a/web_poet/pages.py b/web_poet/pages.py
index e53a585..e3cd3dc 100644
--- a/web_poet/pages.py
+++ b/web_poet/pages.py
@@ -1,17 +1,21 @@
import abc
import inspect
-import typing
from contextlib import suppress
from functools import wraps
+from typing import Any, Generic, Optional, TypeVar, overload
import attr
import parsel
-from web_poet._typing import get_item_cls
from web_poet.fields import FieldsMixin, item_from_fields
from web_poet.mixins import ResponseShortcutsMixin, SelectorShortcutsMixin
from web_poet.page_inputs import HttpResponse
-from web_poet.utils import CallableT, _create_deprecated_class, cached_method
+from web_poet.utils import (
+ CallableT,
+ _create_deprecated_class,
+ cached_method,
+ get_generic_param,
+)
class Injectable(abc.ABC, FieldsMixin):
@@ -35,25 +39,40 @@ class Injectable(abc.ABC, FieldsMixin):
Injectable.register(type(None))
-def is_injectable(cls: typing.Any) -> bool:
+def is_injectable(cls: Any) -> bool:
"""Return True if ``cls`` is a class which inherits
from :class:`~.Injectable`."""
return isinstance(cls, type) and issubclass(cls, Injectable)
-ItemT = typing.TypeVar("ItemT")
+ItemT = TypeVar("ItemT")
-class Returns(typing.Generic[ItemT]):
+class Returns(Generic[ItemT]):
"""Inherit from this generic mixin to change the item class used by
:class:`~.ItemPage`"""
@property
- def item_cls(self) -> typing.Type[ItemT]:
+ def item_cls(self) -> type:
"""Item class"""
return get_item_cls(self.__class__, default=dict)
+@overload
+def get_item_cls(cls: type, default: type) -> type:
+ ...
+
+
+@overload
+def get_item_cls(cls: type, default: None) -> Optional[type]:
+ ...
+
+
+def get_item_cls(cls: type, default: Optional[type] = None) -> Optional[type]:
+ param = get_generic_param(cls, Returns)
+ return param or default
+
+
_NOT_SET = object()
diff --git a/web_poet/rules.py b/web_poet/rules.py
index 53f3efe..3337bac 100644
--- a/web_poet/rules.py
+++ b/web_poet/rules.py
@@ -22,9 +22,8 @@ from typing import (
import attrs
from url_matcher import Patterns, URLMatcher
-from web_poet._typing import get_item_cls
from web_poet.page_inputs.url import _Url
-from web_poet.pages import ItemPage
+from web_poet.pages import ItemPage, get_item_cls
from web_poet.utils import _create_deprecated_class, as_list, str_to_pattern
Strings = Union[str, Iterable[str]]
diff --git a/web_poet/utils.py b/web_poet/utils.py
index 4eccc99..49d7b8c 100644
--- a/web_poet/utils.py
+++ b/web_poet/utils.py
@@ -1,9 +1,10 @@
import inspect
import weakref
+from collections import deque
from collections.abc import Iterable
from functools import lru_cache, partial, wraps
from types import MethodType
-from typing import Any, Callable, List, Optional, TypeVar, Union
+from typing import Any, Callable, List, Optional, Tuple, TypeVar, Union, get_args
from warnings import warn
import packaging.version
@@ -273,3 +274,25 @@ def str_to_pattern(url_pattern: Union[str, Patterns]) -> Patterns:
if isinstance(url_pattern, Patterns):
return url_pattern
return Patterns([url_pattern])
+
+
+def get_generic_param(
+ cls: type, expected: Union[type, Tuple[type, ...]]
+) -> Optional[type]:
+ """Search the base classes recursively breadth-first for a generic class and return its param.
+
+ Returns the param of the first found class that is a subclass of ``expected``.
+ """
+ visited = set()
+ queue = deque([cls])
+ while queue:
+ node = queue.popleft()
+ visited.add(node)
+ for base in getattr(node, "__orig_bases__", []):
+ origin = getattr(base, "__origin__", None)
+ if origin and issubclass(origin, expected):
+ result = get_args(base)[0]
+ if not isinstance(result, TypeVar):
+ return result
+ queue.append(base)
+ return None
|
scrapinghub/web-poet
|
90eba4b94614b16a75821dfbb3223b5f5d602a77
|
diff --git a/tests/test_pages.py b/tests/test_pages.py
index 9e86583..315569b 100644
--- a/tests/test_pages.py
+++ b/tests/test_pages.py
@@ -1,4 +1,4 @@
-from typing import List, Optional
+from typing import Generic, List, Optional, TypeVar
import attrs
import pytest
@@ -232,6 +232,31 @@ async def test_item_page_change_item_type_remove_fields() -> None:
await page2.to_item()
+def test_returns_inheritance() -> None:
+ @attrs.define
+ class MyItem:
+ name: str
+
+ class BasePage(ItemPage[MyItem]):
+ @field
+ def name(self):
+ return "hello"
+
+ MetadataT = TypeVar("MetadataT")
+
+ class HasMetadata(Generic[MetadataT]):
+ pass
+
+ class DummyMetadata:
+ pass
+
+ class Page(BasePage, HasMetadata[DummyMetadata]):
+ pass
+
+ page = Page()
+ assert page.item_cls is MyItem
+
+
@pytest.mark.asyncio
async def test_extractor(book_list_html_response) -> None:
@attrs.define
diff --git a/tests/test_utils.py b/tests/test_utils.py
index c6f5273..9094fdb 100644
--- a/tests/test_utils.py
+++ b/tests/test_utils.py
@@ -2,12 +2,17 @@ import asyncio
import inspect
import random
import warnings
-from typing import Any
+from typing import Any, Generic, TypeVar
from unittest import mock
import pytest
-from web_poet.utils import _create_deprecated_class, cached_method, ensure_awaitable
+from web_poet.utils import (
+ _create_deprecated_class,
+ cached_method,
+ ensure_awaitable,
+ get_generic_param,
+)
class SomeBaseClass:
@@ -466,3 +471,72 @@ async def test_cached_method_async_race() -> None:
foo.n_called(),
)
assert results == [1, 1, 1, 1, 1]
+
+
+ItemT = TypeVar("ItemT")
+
+
+class Item:
+ pass
+
+
+class Item2:
+ pass
+
+
+class MyGeneric(Generic[ItemT]):
+ pass
+
+
+class MyGeneric2(Generic[ItemT]):
+ pass
+
+
+class Base(MyGeneric[ItemT]):
+ pass
+
+
+class BaseSpecialized(MyGeneric[Item]):
+ pass
+
+
+class BaseAny(MyGeneric):
+ pass
+
+
+class Derived(Base):
+ pass
+
+
+class Specialized(BaseSpecialized):
+ pass
+
+
+class SpecializedAdditionalClass(BaseSpecialized, Item2):
+ pass
+
+
+class SpecializedTwice(BaseSpecialized, Base[Item2]):
+ pass
+
+
+class SpecializedTwoGenerics(MyGeneric2[Item2], BaseSpecialized):
+ pass
+
+
[email protected](
+ ["cls", "param"],
+ [
+ (MyGeneric, None),
+ (Base, None),
+ (BaseAny, None),
+ (Derived, None),
+ (BaseSpecialized, Item),
+ (Specialized, Item),
+ (SpecializedAdditionalClass, Item),
+ (SpecializedTwice, Item2),
+ (SpecializedTwoGenerics, Item),
+ ],
+)
+def test_get_generic_param(cls, param) -> None:
+ assert get_generic_param(cls, expected=MyGeneric) == param
|
Returns doesn't work in some subclasses
Similar to https://github.com/zytedata/zyte-common-items/issues/49, even though the code is different, it's also not recursive and fails on e.g. this:
```python
def test_returns_inheritance() -> None:
@attrs.define
class MyItem:
name: str
class BasePage(ItemPage[MyItem]):
@field
def name(self):
return "hello"
MetadataT = TypeVar("MetadataT")
class HasMetadata(Generic[MetadataT]):
pass
class DummyMetadata:
pass
class Page(BasePage, HasMetadata[DummyMetadata]):
pass
page = Page()
assert page.item_cls is MyItem
```
|
0.0
|
90eba4b94614b16a75821dfbb3223b5f5d602a77
|
[
"tests/test_pages.py::test_page_object",
"tests/test_pages.py::test_web_page_object",
"tests/test_pages.py::test_item_web_page_deprecated",
"tests/test_pages.py::test_is_injectable",
"tests/test_pages.py::test_item_page_typed",
"tests/test_pages.py::test_web_page_fields",
"tests/test_pages.py::test_item_page_typed_subclass",
"tests/test_pages.py::test_item_page_fields_typo",
"tests/test_pages.py::test_item_page_required_field_missing",
"tests/test_pages.py::test_item_page_change_item_type_extra_fields",
"tests/test_pages.py::test_item_page_change_item_type_remove_fields",
"tests/test_pages.py::test_returns_inheritance",
"tests/test_pages.py::test_extractor",
"tests/test_utils.py::test_no_warning_on_definition",
"tests/test_utils.py::test_issubclass",
"tests/test_utils.py::test_isinstance",
"tests/test_utils.py::test_clsdict",
"tests/test_utils.py::test_deprecate_a_class_with_custom_metaclass",
"tests/test_utils.py::test_inspect_stack",
"tests/test_utils.py::test_ensure_awaitable_sync",
"tests/test_utils.py::test_ensure_awaitable_async",
"tests/test_utils.py::test_cached_method_basic",
"tests/test_utils.py::test_cached_method_async",
"tests/test_utils.py::test_cached_method_argument",
"tests/test_utils.py::test_cached_method_argument_async",
"tests/test_utils.py::test_cached_method_unhashable",
"tests/test_utils.py::test_cached_method_unhashable_async",
"tests/test_utils.py::test_cached_method_exception",
"tests/test_utils.py::test_cached_method_exception_async",
"tests/test_utils.py::test_cached_method_async_race",
"tests/test_utils.py::test_get_generic_param[MyGeneric-None]",
"tests/test_utils.py::test_get_generic_param[Base-None]",
"tests/test_utils.py::test_get_generic_param[BaseAny-None]",
"tests/test_utils.py::test_get_generic_param[Derived-None]",
"tests/test_utils.py::test_get_generic_param[BaseSpecialized-Item]",
"tests/test_utils.py::test_get_generic_param[Specialized-Item]",
"tests/test_utils.py::test_get_generic_param[SpecializedAdditionalClass-Item]",
"tests/test_utils.py::test_get_generic_param[SpecializedTwice-Item2]",
"tests/test_utils.py::test_get_generic_param[SpecializedTwoGenerics-Item]"
] |
[] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_removed_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-07-31 11:48:25+00:00
|
bsd-3-clause
| 5,399 |
|
scrapy__itemadapter-18
|
diff --git a/README.md b/README.md
index cf0c7c4..01d95de 100644
--- a/README.md
+++ b/README.md
@@ -122,9 +122,10 @@ for `scrapy.item.Item`s
* [`attr.Attribute.metadata`](https://www.attrs.org/en/stable/examples.html#metadata)
for `attrs`-based items
-`field_names() -> List[str]`
+`field_names() -> KeysView`
-Return a list with the names of all the defined fields for the item.
+Return a [keys view](https://docs.python.org/3/library/collections.abc.html#collections.abc.KeysView)
+with the names of all the defined fields for the item.
### `is_item` function
diff --git a/itemadapter/adapter.py b/itemadapter/adapter.py
index 5e83590..ab7d037 100644
--- a/itemadapter/adapter.py
+++ b/itemadapter/adapter.py
@@ -1,6 +1,6 @@
-from collections.abc import MutableMapping
+from collections.abc import KeysView, MutableMapping
from types import MappingProxyType
-from typing import Any, Iterator, List
+from typing import Any, Iterator, Optional
from .utils import is_item, is_attrs_instance, is_dataclass_instance, is_scrapy_item
@@ -15,6 +15,7 @@ class ItemAdapter(MutableMapping):
if not is_item(item):
raise TypeError("Expected a valid item, got %r instead: %s" % (type(item), item))
self.item = item
+ self._fields_dict = None # type: Optional[dict]
def __repr__(self) -> str:
return "ItemAdapter for type %s: %r" % (self.item.__class__.__name__, self.item)
@@ -98,19 +99,25 @@ class ItemAdapter(MutableMapping):
else:
return MappingProxyType({})
- def field_names(self) -> List[str]:
+ def field_names(self) -> KeysView:
"""
- Return a list with the names of all the defined fields for the item
+ Return read-only key view with the names of all the defined fields for the item
"""
if is_scrapy_item(self.item):
- return list(self.item.fields.keys())
+ return KeysView(self.item.fields)
elif is_dataclass_instance(self.item):
import dataclasses
- return [field.name for field in dataclasses.fields(self.item)]
+ if self._fields_dict is None:
+ self._fields_dict = {field.name: None for field in dataclasses.fields(self.item)}
+ return KeysView(self._fields_dict)
elif is_attrs_instance(self.item):
import attr
- return [field.name for field in attr.fields(self.item.__class__)]
+ if self._fields_dict is None:
+ self._fields_dict = {
+ field.name: None for field in attr.fields(self.item.__class__)
+ }
+ return KeysView(self._fields_dict)
else:
- return list(self.item.keys())
+ return KeysView(self.item)
diff --git a/tox.ini b/tox.ini
index 62f80b4..b806947 100644
--- a/tox.ini
+++ b/tox.ini
@@ -1,5 +1,5 @@
[tox]
-envlist = py35,py36,py37,py38,flake8,typing,black
+envlist = flake8,typing,black,py35,py36,py37,py38
[testenv]
deps =
|
scrapy/itemadapter
|
2cafd11aecd169810471eb5fc3ccb3b7429d6be1
|
diff --git a/tests/test_adapter.py b/tests/test_adapter.py
index 5c84490..1bc7ac0 100644
--- a/tests/test_adapter.py
+++ b/tests/test_adapter.py
@@ -1,5 +1,6 @@
import unittest
from types import MappingProxyType
+from typing import KeysView
from itemadapter.adapter import ItemAdapter
@@ -89,7 +90,7 @@ class BaseTestMixin:
def test_field_names(self):
item = self.item_class(name="asdf", value=1234)
adapter = ItemAdapter(item)
- self.assertIsInstance(adapter.field_names(), list)
+ self.assertIsInstance(adapter.field_names(), KeysView)
self.assertEqual(sorted(adapter.field_names()), ["name", "value"])
@@ -149,6 +150,13 @@ class DictTestCase(unittest.TestCase, BaseTestMixin):
for field_name in ("name", "value", "undefined_field"):
self.assertEqual(adapter.get_field_meta(field_name), MappingProxyType({}))
+ def test_field_names_updated(self):
+ item = self.item_class(name="asdf")
+ field_names = ItemAdapter(item).field_names()
+ self.assertEqual(sorted(field_names), ["name"])
+ item["value"] = 1234
+ self.assertEqual(sorted(field_names), ["name", "value"])
+
class ScrapySubclassedItemTestCase(NonDictTestMixin, unittest.TestCase):
|
Should field_names preserve key views?
Currently .field_names method returns a list always. This is good from a consistency point of view, but it changes the algorithmic complexity of lookup from O(1) to O(N).
I recall we discussed it in past, but maybe there is some solution possible which keeps the API consistent, but doesn't change lookups to O(N).
This is minor, as field name lists should be tiny in a real world.
|
0.0
|
2cafd11aecd169810471eb5fc3ccb3b7429d6be1
|
[
"tests/test_adapter.py::DictTestCase::test_field_names",
"tests/test_adapter.py::DictTestCase::test_field_names_updated",
"tests/test_adapter.py::DataClassItemTestCase::test_field_names"
] |
[
"tests/test_adapter.py::ItemAdapterReprTestCase::test_repr_dataclass",
"tests/test_adapter.py::ItemAdapterReprTestCase::test_repr_dict",
"tests/test_adapter.py::ItemAdapterInitError::test_non_item",
"tests/test_adapter.py::DictTestCase::test_as_dict",
"tests/test_adapter.py::DictTestCase::test_empty_metadata",
"tests/test_adapter.py::DictTestCase::test_get_set_value",
"tests/test_adapter.py::DictTestCase::test_get_value_keyerror",
"tests/test_adapter.py::DictTestCase::test_get_value_keyerror_item_dict",
"tests/test_adapter.py::DataClassItemTestCase::test_as_dict",
"tests/test_adapter.py::DataClassItemTestCase::test_delitem_len_iter",
"tests/test_adapter.py::DataClassItemTestCase::test_get_field_meta_defined_fields",
"tests/test_adapter.py::DataClassItemTestCase::test_get_set_value",
"tests/test_adapter.py::DataClassItemTestCase::test_get_value_keyerror",
"tests/test_adapter.py::DataClassItemTestCase::test_metadata_common",
"tests/test_adapter.py::DataClassItemTestCase::test_set_value_keyerror"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-05-20 22:32:27+00:00
|
bsd-3-clause
| 5,400 |
|
scrapy__itemadapter-35
|
diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml
index dc8bdac..1d26f9a 100644
--- a/.github/workflows/main.yml
+++ b/.github/workflows/main.yml
@@ -39,7 +39,7 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
- python-version: [3.5, 3.6, 3.7, 3.8]
+ python-version: [3.6, 3.7, 3.8]
steps:
- uses: actions/checkout@v2
diff --git a/README.md b/README.md
index ecac8be..da7a53e 100644
--- a/README.md
+++ b/README.md
@@ -19,7 +19,7 @@ Currently supported types are:
## Requirements
-* Python 3.5+
+* Python 3.6+
* [`scrapy`](https://scrapy.org/): optional, needed to interact with `scrapy` items
* `dataclasses` ([stdlib](https://docs.python.org/3/library/dataclasses.html) in Python 3.7+,
or its [backport](https://pypi.org/project/dataclasses/) in Python 3.6): optional, needed
@@ -163,13 +163,23 @@ _`itemadapter.utils.is_item(obj: Any) -> bool`_
Return `True` if the given object belongs to one of the supported types,
`False` otherwise.
+### `get_field_meta_from_class` function
+
+_`itemadapter.utils.get_field_meta_from_class(item_class: type, field_name: str) -> MappingProxyType`_
+
+Given an item class and a field name, return a
+[`MappingProxyType`](https://docs.python.org/3/library/types.html#types.MappingProxyType)
+object, which is a read-only mapping with metadata about the given field. If the item class does not
+support field metadata, or there is no metadata for the given field, an empty object is returned.
+
## Metadata support
`scrapy.item.Item`, `dataclass` and `attrs` objects allow the inclusion of
-arbitrary field metadata, which can be retrieved with the
-`ItemAdapter.get_field_meta` method. The definition procedure depends on the
-underlying type.
+arbitrary field metadata. This can be retrieved from an item instance with the
+`itemadapter.adapter.ItemAdapter.get_field_meta` method, or from an item class
+with the `itemadapter.utils.get_field_meta_from_class` function.
+The definition procedure depends on the underlying type.
#### `scrapy.item.Item` objects
diff --git a/itemadapter/__init__.py b/itemadapter/__init__.py
index 61b5cdd..a066e2d 100644
--- a/itemadapter/__init__.py
+++ b/itemadapter/__init__.py
@@ -1,5 +1,5 @@
from .adapter import ItemAdapter # noqa: F401
-from .utils import is_item # noqa: F401
+from .utils import get_field_meta_from_class, is_item # noqa: F401
__version__ = "0.1.0"
diff --git a/itemadapter/adapter.py b/itemadapter/adapter.py
index 4312f2e..50e9bfa 100644
--- a/itemadapter/adapter.py
+++ b/itemadapter/adapter.py
@@ -2,7 +2,13 @@ from collections.abc import KeysView, MutableMapping
from types import MappingProxyType
from typing import Any, Iterator
-from .utils import is_item, is_attrs_instance, is_dataclass_instance, is_scrapy_item
+from .utils import (
+ get_field_meta_from_class,
+ is_attrs_instance,
+ is_dataclass_instance,
+ is_item,
+ is_scrapy_item,
+)
class ItemAdapter(MutableMapping):
@@ -86,28 +92,7 @@ class ItemAdapter(MutableMapping):
The returned value is an instance of types.MappingProxyType, i.e. a dynamic read-only view
of the original mapping, which gets automatically updated if the original mapping changes.
"""
- if is_scrapy_item(self.item):
- return MappingProxyType(self.item.fields[field_name])
- elif is_dataclass_instance(self.item):
- from dataclasses import fields
-
- for field in fields(self.item):
- if field.name == field_name:
- return field.metadata # type: ignore
- raise KeyError(
- "%s does not support field: %s" % (self.item.__class__.__name__, field_name)
- )
- elif is_attrs_instance(self.item):
- from attr import fields_dict
-
- try:
- return fields_dict(self.item.__class__)[field_name].metadata # type: ignore
- except KeyError:
- raise KeyError(
- "%s does not support field: %s" % (self.item.__class__.__name__, field_name)
- )
- else:
- return MappingProxyType({})
+ return get_field_meta_from_class(self.item.__class__, field_name)
def field_names(self) -> KeysView:
"""
diff --git a/itemadapter/utils.py b/itemadapter/utils.py
index 5c22dd3..6ddd52f 100644
--- a/itemadapter/utils.py
+++ b/itemadapter/utils.py
@@ -1,31 +1,52 @@
+from types import MappingProxyType
from typing import Any
+def _get_scrapy_item_classes() -> tuple:
+ try:
+ import scrapy
+ except ImportError:
+ return ()
+ else:
+ try:
+ _base_item_cls = getattr(scrapy.item, "_BaseItem", scrapy.item.BaseItem) # deprecated
+ return (scrapy.item.Item, _base_item_cls)
+ except AttributeError:
+ return (scrapy.item.Item,)
+
+
+def _is_dataclass(obj: Any) -> bool:
+ try:
+ import dataclasses
+ except ImportError:
+ return False
+ return dataclasses.is_dataclass(obj)
+
+
+def _is_attrs_class(obj: Any) -> bool:
+ try:
+ import attr
+ except ImportError:
+ return False
+ return attr.has(obj)
+
+
def is_dataclass_instance(obj: Any) -> bool:
"""
Return True if the given object is a dataclass object, False otherwise.
- This function always returns False in py35. In py36, it returns False
- if the "dataclasses" backport is not available.
+ In py36, this function returns False if the "dataclasses" backport is not available.
Taken from https://docs.python.org/3/library/dataclasses.html#dataclasses.is_dataclass.
"""
- try:
- import dataclasses
- except ImportError:
- return False
- return dataclasses.is_dataclass(obj) and not isinstance(obj, type)
+ return _is_dataclass(obj) and not isinstance(obj, type)
def is_attrs_instance(obj: Any) -> bool:
"""
Return True if the given object is a attrs-based object, False otherwise.
"""
- try:
- import attr
- except ImportError:
- return False
- return attr.has(obj) and not isinstance(obj, type)
+ return _is_attrs_class(obj) and not isinstance(obj, type)
def is_scrapy_item(obj: Any) -> bool:
@@ -56,3 +77,39 @@ def is_item(obj: Any) -> bool:
or is_dataclass_instance(obj)
or is_attrs_instance(obj)
)
+
+
+def get_field_meta_from_class(item_class: type, field_name: str) -> MappingProxyType:
+ """
+ Return a read-only mapping with metadata for the given field name, within the given item class.
+ If there is no metadata for the field, or the item class does not support field metadata,
+ an empty object is returned.
+
+ Field metadata is taken from different sources, depending on the item type:
+ * scrapy.item.Item: corresponding scrapy.item.Field object
+ * dataclass items: "metadata" attribute for the corresponding field
+ * attrs items: "metadata" attribute for the corresponding field
+
+ The returned value is an instance of types.MappingProxyType, i.e. a dynamic read-only view
+ of the original mapping, which gets automatically updated if the original mapping changes.
+ """
+ if issubclass(item_class, _get_scrapy_item_classes()):
+ return MappingProxyType(item_class.fields[field_name]) # type: ignore
+ elif _is_dataclass(item_class):
+ from dataclasses import fields
+
+ for field in fields(item_class):
+ if field.name == field_name:
+ return field.metadata # type: ignore
+ raise KeyError("%s does not support field: %s" % (item_class.__name__, field_name))
+ elif _is_attrs_class(item_class):
+ from attr import fields_dict
+
+ try:
+ return fields_dict(item_class)[field_name].metadata # type: ignore
+ except KeyError:
+ raise KeyError("%s does not support field: %s" % (item_class.__name__, field_name))
+ elif issubclass(item_class, dict):
+ return MappingProxyType({})
+ else:
+ raise TypeError("%s is not a valid item class" % (item_class,))
diff --git a/setup.py b/setup.py
index 587fe63..76fc982 100644
--- a/setup.py
+++ b/setup.py
@@ -16,11 +16,11 @@ setuptools.setup(
author_email="[email protected]",
url="https://github.com/scrapy/itemadapter",
packages=["itemadapter"],
+ python_requires=">=3.6",
classifiers=[
"Development Status :: 3 - Alpha",
"License :: OSI Approved :: BSD License",
"Programming Language :: Python",
- "Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
diff --git a/tox.ini b/tox.ini
index b806947..bef3467 100644
--- a/tox.ini
+++ b/tox.ini
@@ -1,5 +1,5 @@
[tox]
-envlist = flake8,typing,black,py35,py36,py37,py38
+envlist = flake8,typing,black,py36,py37,py38
[testenv]
deps =
@@ -7,9 +7,6 @@ deps =
commands =
pytest --verbose --cov=itemadapter --cov-report=term-missing --cov-report=html --cov-report=xml {posargs: itemadapter tests}
-[testenv:py35]
-basepython = python3.5
-
[testenv:py36]
basepython = python3.6
|
scrapy/itemadapter
|
755933624695739d0f414b2218bca431a775b301
|
diff --git a/tests/test_adapter.py b/tests/test_adapter.py
index 6589975..adba8f8 100644
--- a/tests/test_adapter.py
+++ b/tests/test_adapter.py
@@ -18,20 +18,14 @@ class ItemAdapterReprTestCase(unittest.TestCase):
def test_repr_dict(self):
item = dict(name="asdf", value=1234)
adapter = ItemAdapter(item)
- # dicts are not guarantied to be sorted in py35
- self.assertTrue(
- repr(adapter) == "<ItemAdapter for dict(name='asdf', value=1234)>"
- or repr(adapter) == "<ItemAdapter for dict(value=1234, name='asdf')>",
- )
+ self.assertEqual(repr(adapter), "<ItemAdapter for dict(name='asdf', value=1234)>")
@unittest.skipIf(not ScrapySubclassedItem, "scrapy module is not available")
def test_repr_scrapy_item(self):
item = ScrapySubclassedItem(name="asdf", value=1234)
adapter = ItemAdapter(item)
- # Scrapy fields are stored in a dict, which is not guarantied to be sorted in py35
- self.assertTrue(
- repr(adapter) == "<ItemAdapter for ScrapySubclassedItem(name='asdf', value=1234)>"
- or repr(adapter) == "<ItemAdapter for ScrapySubclassedItem(value=1234, name='asdf')>",
+ self.assertEqual(
+ repr(adapter), "<ItemAdapter for ScrapySubclassedItem(name='asdf', value=1234)>"
)
@unittest.skipIf(not DataClassItem, "dataclasses module is not available")
diff --git a/tests/test_utils.py b/tests/test_utils.py
index 8c4194a..162e680 100644
--- a/tests/test_utils.py
+++ b/tests/test_utils.py
@@ -1,7 +1,14 @@
import unittest
from unittest import mock
+from types import MappingProxyType
-from itemadapter.utils import is_item, is_attrs_instance, is_dataclass_instance, is_scrapy_item
+from itemadapter.utils import (
+ get_field_meta_from_class,
+ is_attrs_instance,
+ is_dataclass_instance,
+ is_item,
+ is_scrapy_item,
+)
from tests import AttrsItem, DataClassItem, ScrapyItem, ScrapySubclassedItem
@@ -10,6 +17,14 @@ def mocked_import(name, *args, **kwargs):
raise ImportError(name)
+class InvalidItemClassTestCase(unittest.TestCase):
+ def test_invalid_item_class(self):
+ with self.assertRaises(TypeError, msg="1 is not a valid item class"):
+ get_field_meta_from_class(1, "field")
+ with self.assertRaises(TypeError, msg="list is not a valid item class"):
+ get_field_meta_from_class(list, "field")
+
+
class ItemLikeTestCase(unittest.TestCase):
def test_false(self):
self.assertFalse(is_item(int))
@@ -64,11 +79,20 @@ class AttrsTestCase(unittest.TestCase):
@mock.patch("builtins.__import__", mocked_import)
def test_module_not_available(self):
self.assertFalse(is_attrs_instance(AttrsItem(name="asdf", value=1234)))
+ with self.assertRaises(TypeError, msg="AttrsItem is not a valid item class"):
+ get_field_meta_from_class(AttrsItem, "name")
@unittest.skipIf(not AttrsItem, "attrs module is not available")
def test_true(self):
self.assertTrue(is_attrs_instance(AttrsItem()))
self.assertTrue(is_attrs_instance(AttrsItem(name="asdf", value=1234)))
+ # field metadata
+ self.assertEqual(
+ get_field_meta_from_class(AttrsItem, "name"), MappingProxyType({"serializer": str})
+ )
+ self.assertEqual(
+ get_field_meta_from_class(AttrsItem, "value"), MappingProxyType({"serializer": int})
+ )
class DataclassTestCase(unittest.TestCase):
@@ -92,11 +116,21 @@ class DataclassTestCase(unittest.TestCase):
@mock.patch("builtins.__import__", mocked_import)
def test_module_not_available(self):
self.assertFalse(is_dataclass_instance(DataClassItem(name="asdf", value=1234)))
+ with self.assertRaises(TypeError, msg="DataClassItem is not a valid item class"):
+ get_field_meta_from_class(DataClassItem, "name")
@unittest.skipIf(not DataClassItem, "dataclasses module is not available")
def test_true(self):
self.assertTrue(is_dataclass_instance(DataClassItem()))
self.assertTrue(is_dataclass_instance(DataClassItem(name="asdf", value=1234)))
+ # field metadata
+ self.assertEqual(
+ get_field_meta_from_class(DataClassItem, "name"), MappingProxyType({"serializer": str})
+ )
+ self.assertEqual(
+ get_field_meta_from_class(DataClassItem, "value"),
+ MappingProxyType({"serializer": int}),
+ )
class ScrapyItemTestCase(unittest.TestCase):
@@ -118,12 +152,23 @@ class ScrapyItemTestCase(unittest.TestCase):
@mock.patch("builtins.__import__", mocked_import)
def test_module_not_available(self):
self.assertFalse(is_scrapy_item(ScrapySubclassedItem(name="asdf", value=1234)))
+ with self.assertRaises(TypeError, msg="ScrapySubclassedItem is not a valid item class"):
+ get_field_meta_from_class(ScrapySubclassedItem, "name")
@unittest.skipIf(not ScrapySubclassedItem, "scrapy module is not available")
def test_true(self):
self.assertTrue(is_scrapy_item(ScrapyItem()))
self.assertTrue(is_scrapy_item(ScrapySubclassedItem()))
self.assertTrue(is_scrapy_item(ScrapySubclassedItem(name="asdf", value=1234)))
+ # field metadata
+ self.assertEqual(
+ get_field_meta_from_class(ScrapySubclassedItem, "name"),
+ MappingProxyType({"serializer": str}),
+ )
+ self.assertEqual(
+ get_field_meta_from_class(ScrapySubclassedItem, "value"),
+ MappingProxyType({"serializer": int}),
+ )
try:
@@ -161,8 +206,20 @@ class ScrapyDeprecatedBaseItemTestCase(unittest.TestCase):
@unittest.skipIf(scrapy is None, "scrapy module is not available")
def test_removed_baseitem(self):
+ """
+ Mock the scrapy.item module so it does not contain the deprecated _BaseItem class
+ """
+
class MockItemModule:
Item = ScrapyItem
with mock.patch("scrapy.item", MockItemModule):
self.assertFalse(is_scrapy_item(dict()))
+ self.assertEqual(
+ get_field_meta_from_class(ScrapySubclassedItem, "name"),
+ MappingProxyType({"serializer": str}),
+ )
+ self.assertEqual(
+ get_field_meta_from_class(ScrapySubclassedItem, "value"),
+ MappingProxyType({"serializer": int}),
+ )
|
Implement ItemClassAdapter
This would help implementing delayed item object creation in `itemloaders`: https://github.com/scrapy/itemloaders/pull/20#issuecomment-681867612
It should only accept item classes, not objects.
It should implement `get_field_meta` just as `ItemAdapter`.
|
0.0
|
755933624695739d0f414b2218bca431a775b301
|
[
"tests/test_adapter.py::ItemAdapterReprTestCase::test_repr_dataclass",
"tests/test_adapter.py::ItemAdapterReprTestCase::test_repr_dict",
"tests/test_adapter.py::ItemAdapterInitError::test_non_item",
"tests/test_adapter.py::DictTestCase::test_as_dict",
"tests/test_adapter.py::DictTestCase::test_as_dict_nested",
"tests/test_adapter.py::DictTestCase::test_empty_metadata",
"tests/test_adapter.py::DictTestCase::test_field_names",
"tests/test_adapter.py::DictTestCase::test_field_names_updated",
"tests/test_adapter.py::DictTestCase::test_get_set_value",
"tests/test_adapter.py::DictTestCase::test_get_value_keyerror",
"tests/test_adapter.py::DictTestCase::test_get_value_keyerror_item_dict",
"tests/test_adapter.py::DataClassItemTestCase::test_as_dict",
"tests/test_adapter.py::DataClassItemTestCase::test_as_dict_nested",
"tests/test_adapter.py::DataClassItemTestCase::test_delitem_len_iter",
"tests/test_adapter.py::DataClassItemTestCase::test_field_names",
"tests/test_adapter.py::DataClassItemTestCase::test_get_field_meta_defined_fields",
"tests/test_adapter.py::DataClassItemTestCase::test_get_set_value",
"tests/test_adapter.py::DataClassItemTestCase::test_get_value_keyerror",
"tests/test_adapter.py::DataClassItemTestCase::test_metadata_common",
"tests/test_adapter.py::DataClassItemTestCase::test_set_value_keyerror",
"tests/test_utils.py::InvalidItemClassTestCase::test_invalid_item_class",
"tests/test_utils.py::ItemLikeTestCase::test_false",
"tests/test_utils.py::ItemLikeTestCase::test_true_dataclass",
"tests/test_utils.py::ItemLikeTestCase::test_true_dict",
"tests/test_utils.py::DataclassTestCase::test_module_not_available",
"tests/test_utils.py::DataclassTestCase::test_true"
] |
[] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-08-27 18:31:01+00:00
|
bsd-3-clause
| 5,401 |
|
scrapy__itemloaders-22
|
diff --git a/itemloaders/__init__.py b/itemloaders/__init__.py
index 090a73e..07bf48c 100644
--- a/itemloaders/__init__.py
+++ b/itemloaders/__init__.py
@@ -3,7 +3,6 @@ Item Loader
See documentation in docs/topics/loaders.rst
"""
-from collections import defaultdict
from contextlib import suppress
from itemadapter import ItemAdapter
@@ -109,9 +108,10 @@ class ItemLoader:
context['item'] = item
self.context = context
self.parent = parent
- self._local_values = defaultdict(list)
+ self._local_values = {}
# values from initial item
for field_name, value in ItemAdapter(item).items():
+ self._values.setdefault(field_name, [])
self._values[field_name] += arg_to_iter(value)
@property
@@ -207,6 +207,7 @@ class ItemLoader:
value = arg_to_iter(value)
processed_value = self._process_input_value(field_name, value)
if processed_value:
+ self._values.setdefault(field_name, [])
self._values[field_name] += arg_to_iter(processed_value)
def _replace_value(self, field_name, value):
@@ -272,15 +273,16 @@ class ItemLoader:
"""
proc = self.get_output_processor(field_name)
proc = wrap_loader_context(proc, self.context)
+ value = self._values.get(field_name, [])
try:
- return proc(self._values[field_name])
+ return proc(value)
except Exception as e:
raise ValueError("Error with output processor: field=%r value=%r error='%s: %s'" %
- (field_name, self._values[field_name], type(e).__name__, str(e)))
+ (field_name, value, type(e).__name__, str(e)))
def get_collected_values(self, field_name):
"""Return the collected values for the given field."""
- return self._values[field_name]
+ return self._values.get(field_name, [])
def get_input_processor(self, field_name):
proc = getattr(self, '%s_in' % field_name, None)
|
scrapy/itemloaders
|
98ad3a5678d1a2fe373a052266675da1fff9e1f5
|
diff --git a/tests/test_base_loader.py b/tests/test_base_loader.py
index f57d004..fdc3e5f 100644
--- a/tests/test_base_loader.py
+++ b/tests/test_base_loader.py
@@ -403,6 +403,12 @@ class BasicItemLoaderTest(unittest.TestCase):
self.assertRaises(ValueError, il.add_value, 'name',
['marta', 'other'], Compose(float))
+ def test_get_unset_value(self):
+ loader = ItemLoader()
+ self.assertEqual(loader.load_item(), {})
+ self.assertEqual(loader.get_output_value('foo'), [])
+ self.assertEqual(loader.load_item(), {})
+
class BaseNoInputReprocessingLoader(ItemLoader):
title_in = MapCompose(str.upper)
|
Calling get_output_value causes loader to assign an "empty" value to field
# Description
If a field in an ItemLoader has not been set, calling `get_output_value` mistakenly assigns an empty object to that item. See the example bellow.
### Steps to Reproduce
```python
from scrapy.loader import ItemLoader
from scrapy import Item, Field
class MyItem(Item):
field = Field()
loader = ItemLoader(MyItem())
```
Then, simply loading the item correctly produces an empty dict
```python
>>> loader.load_item()
{}
```
But calling `get_output_value` before that instantiates the field:
```python
>>> loader.get_output_value("field")
[]
>>> loader.load_item()
{'field': []}
```
|
0.0
|
98ad3a5678d1a2fe373a052266675da1fff9e1f5
|
[
"tests/test_base_loader.py::BasicItemLoaderTest::test_get_unset_value"
] |
[
"tests/test_base_loader.py::BasicItemLoaderTest::test_add_value",
"tests/test_base_loader.py::BasicItemLoaderTest::test_add_zero",
"tests/test_base_loader.py::BasicItemLoaderTest::test_compose_processor",
"tests/test_base_loader.py::BasicItemLoaderTest::test_default_input_processor",
"tests/test_base_loader.py::BasicItemLoaderTest::test_default_output_processor",
"tests/test_base_loader.py::BasicItemLoaderTest::test_empty_map_compose",
"tests/test_base_loader.py::BasicItemLoaderTest::test_error_input_processor",
"tests/test_base_loader.py::BasicItemLoaderTest::test_error_output_processor",
"tests/test_base_loader.py::BasicItemLoaderTest::test_error_processor_as_argument",
"tests/test_base_loader.py::BasicItemLoaderTest::test_extend_custom_input_processors",
"tests/test_base_loader.py::BasicItemLoaderTest::test_extend_default_input_processors",
"tests/test_base_loader.py::BasicItemLoaderTest::test_get_value",
"tests/test_base_loader.py::BasicItemLoaderTest::test_identity_input_processor",
"tests/test_base_loader.py::BasicItemLoaderTest::test_inherited_default_input_processor",
"tests/test_base_loader.py::BasicItemLoaderTest::test_input_processor_inheritance",
"tests/test_base_loader.py::BasicItemLoaderTest::test_item_passed_to_input_processor_functions",
"tests/test_base_loader.py::BasicItemLoaderTest::test_iter_on_input_processor_input",
"tests/test_base_loader.py::BasicItemLoaderTest::test_load_item_ignore_none_field_values",
"tests/test_base_loader.py::BasicItemLoaderTest::test_load_item_using_custom_loader",
"tests/test_base_loader.py::BasicItemLoaderTest::test_load_item_using_default_loader",
"tests/test_base_loader.py::BasicItemLoaderTest::test_loader_context_on_assign",
"tests/test_base_loader.py::BasicItemLoaderTest::test_loader_context_on_declaration",
"tests/test_base_loader.py::BasicItemLoaderTest::test_loader_context_on_instantiation",
"tests/test_base_loader.py::BasicItemLoaderTest::test_map_compose_filter",
"tests/test_base_loader.py::BasicItemLoaderTest::test_map_compose_filter_multil",
"tests/test_base_loader.py::BasicItemLoaderTest::test_output_processor_error",
"tests/test_base_loader.py::BasicItemLoaderTest::test_output_processor_using_classes",
"tests/test_base_loader.py::BasicItemLoaderTest::test_output_processor_using_function",
"tests/test_base_loader.py::BasicItemLoaderTest::test_partial_processor",
"tests/test_base_loader.py::BasicItemLoaderTest::test_replace_value",
"tests/test_base_loader.py::BasicItemLoaderTest::test_self_referencing_loader",
"tests/test_base_loader.py::NoInputReprocessingFromDictTest::test_avoid_reprocessing_with_initial_values_list",
"tests/test_base_loader.py::NoInputReprocessingFromDictTest::test_avoid_reprocessing_with_initial_values_single",
"tests/test_base_loader.py::NoInputReprocessingFromDictTest::test_avoid_reprocessing_without_initial_values_list",
"tests/test_base_loader.py::NoInputReprocessingFromDictTest::test_avoid_reprocessing_without_initial_values_single"
] |
{
"failed_lite_validators": [
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-09-01 11:46:58+00:00
|
bsd-3-clause
| 5,402 |
|
scrapy__itemloaders-68
|
diff --git a/itemloaders/__init__.py b/itemloaders/__init__.py
index 09bffba..a84da84 100644
--- a/itemloaders/__init__.py
+++ b/itemloaders/__init__.py
@@ -19,7 +19,7 @@ def unbound_method(method):
(no need to define an unused first 'self' argument)
"""
with suppress(AttributeError):
- if '.' not in method.__qualname__:
+ if "." not in method.__qualname__:
return method.__func__
return method
@@ -36,12 +36,12 @@ class ItemLoader:
:param item: The item instance to populate using subsequent calls to
:meth:`~ItemLoader.add_xpath`, :meth:`~ItemLoader.add_css`,
- or :meth:`~ItemLoader.add_value`.
+ :meth:`~ItemLoader.add_jmes` or :meth:`~ItemLoader.add_value`.
:type item: :class:`dict` object
:param selector: The selector to extract data from, when using the
- :meth:`add_xpath` (resp. :meth:`add_css`) or :meth:`replace_xpath`
- (resp. :meth:`replace_css`) method.
+ :meth:`add_xpath` (resp. :meth:`add_css`, :meth:`add_jmes`) or :meth:`replace_xpath`
+ (resp. :meth:`replace_css`, :meth:`replace_jmes`) method.
:type selector: :class:`~parsel.selector.Selector` object
The item, selector and the remaining keyword arguments are
@@ -105,7 +105,7 @@ class ItemLoader:
if item is None:
item = self.default_item_class()
self._local_item = item
- context['item'] = item
+ context["item"] = item
self.context = context
self.parent = parent
self._local_values = {}
@@ -138,9 +138,7 @@ class ItemLoader:
"""
selector = self.selector.xpath(xpath)
context.update(selector=selector)
- subloader = self.__class__(
- item=self.item, parent=self, **context
- )
+ subloader = self.__class__(item=self.item, parent=self, **context)
return subloader
def nested_css(self, css, **context):
@@ -153,9 +151,7 @@ class ItemLoader:
"""
selector = self.selector.css(css)
context.update(selector=selector)
- subloader = self.__class__(
- item=self.item, parent=self, **context
- )
+ subloader = self.__class__(item=self.item, parent=self, **context)
return subloader
def add_value(self, field_name, value, *processors, re=None, **kw):
@@ -246,9 +242,10 @@ class ItemLoader:
try:
value = proc(value)
except Exception as e:
- raise ValueError("Error with processor %s value=%r error='%s: %s'" %
- (_proc.__class__.__name__, value,
- type(e).__name__, str(e)))
+ raise ValueError(
+ "Error with processor %s value=%r error='%s: %s'"
+ % (_proc.__class__.__name__, value, type(e).__name__, str(e))
+ )
return value
def load_item(self):
@@ -276,30 +273,28 @@ class ItemLoader:
try:
return proc(value)
except Exception as e:
- raise ValueError("Error with output processor: field=%r value=%r error='%s: %s'" %
- (field_name, value, type(e).__name__, str(e)))
+ raise ValueError(
+ "Error with output processor: field=%r value=%r error='%s: %s'"
+ % (field_name, value, type(e).__name__, str(e))
+ )
def get_collected_values(self, field_name):
"""Return the collected values for the given field."""
return self._values.get(field_name, [])
def get_input_processor(self, field_name):
- proc = getattr(self, '%s_in' % field_name, None)
+ proc = getattr(self, "%s_in" % field_name, None)
if not proc:
proc = self._get_item_field_attr(
- field_name,
- 'input_processor',
- self.default_input_processor
+ field_name, "input_processor", self.default_input_processor
)
return unbound_method(proc)
def get_output_processor(self, field_name):
- proc = getattr(self, '%s_out' % field_name, None)
+ proc = getattr(self, "%s_out" % field_name, None)
if not proc:
proc = self._get_item_field_attr(
- field_name,
- 'output_processor',
- self.default_output_processor
+ field_name, "output_processor", self.default_output_processor
)
return unbound_method(proc)
@@ -316,8 +311,15 @@ class ItemLoader:
except Exception as e:
raise ValueError(
"Error with input processor %s: field=%r value=%r "
- "error='%s: %s'" % (_proc.__class__.__name__, field_name,
- value, type(e).__name__, str(e)))
+ "error='%s: %s'"
+ % (
+ _proc.__class__.__name__,
+ field_name,
+ value,
+ type(e).__name__,
+ str(e),
+ )
+ )
def _check_selector_method(self):
if self.selector is None:
@@ -439,3 +441,63 @@ class ItemLoader:
self._check_selector_method()
csss = arg_to_iter(csss)
return flatten(self.selector.css(css).getall() for css in csss)
+
+ def add_jmes(self, field_name, jmes, *processors, re=None, **kw):
+ """
+ Similar to :meth:`ItemLoader.add_value` but receives a JMESPath selector
+ instead of a value, which is used to extract a list of unicode strings
+ from the selector associated with this :class:`ItemLoader`.
+
+ See :meth:`get_jmes` for ``kwargs``.
+
+ :param jmes: the JMESPath selector to extract data from
+ :type jmes: str
+
+ Examples::
+
+ # HTML snippet: {"name": "Color TV"}
+ loader.add_jmes('name')
+ # HTML snippet: {"price": the price is $1200"}
+ loader.add_jmes('price', TakeFirst(), re='the price is (.*)')
+ """
+ values = self._get_jmesvalues(jmes)
+ self.add_value(field_name, values, *processors, re=re, **kw)
+
+ def replace_jmes(self, field_name, jmes, *processors, re=None, **kw):
+ """
+ Similar to :meth:`add_jmes` but replaces collected data instead of adding it.
+ """
+ values = self._get_jmesvalues(jmes)
+ self.replace_value(field_name, values, *processors, re=re, **kw)
+
+ def get_jmes(self, jmes, *processors, re=None, **kw):
+ """
+ Similar to :meth:`ItemLoader.get_value` but receives a JMESPath selector
+ instead of a value, which is used to extract a list of unicode strings
+ from the selector associated with this :class:`ItemLoader`.
+
+ :param jmes: the JMESPath selector to extract data from
+ :type jmes: str
+
+ :param re: a regular expression to use for extracting data from the
+ selected JMESPath
+ :type re: str or typing.Pattern
+
+ Examples::
+
+ # HTML snippet: {"name": "Color TV"}
+ loader.get_jmes('name')
+ # HTML snippet: {"price": the price is $1200"}
+ loader.get_jmes('price', TakeFirst(), re='the price is (.*)')
+ """
+ values = self._get_jmesvalues(jmes)
+ return self.get_value(values, *processors, re=re, **kw)
+
+ def _get_jmesvalues(self, jmess):
+ self._check_selector_method()
+ jmess = arg_to_iter(jmess)
+ if not hasattr(self.selector, "jmespath"):
+ raise AttributeError(
+ "Please install parsel >= 1.8.1 to get jmespath support"
+ )
+ return flatten(self.selector.jmespath(jmes).getall() for jmes in jmess)
|
scrapy/itemloaders
|
1458c6786408725c8025346e5b64d95614c6fa42
|
diff --git a/tests/test_selector_loader.py b/tests/test_selector_loader.py
index 170b56f..972de71 100644
--- a/tests/test_selector_loader.py
+++ b/tests/test_selector_loader.py
@@ -1,5 +1,6 @@
import re
import unittest
+from unittest.mock import MagicMock
from parsel import Selector
@@ -23,6 +24,18 @@ class SelectortemLoaderTest(unittest.TestCase):
</html>
""")
+ jmes_selector = Selector(text="""
+ {
+ "name": "marta",
+ "description": "paragraph",
+ "website": {
+ "url": "http://www.scrapy.org",
+ "name": "homepage"
+ },
+ "logo": "/images/logo.png"
+ }
+ """)
+
def test_init_method(self):
loader = CustomItemLoader()
self.assertEqual(loader.selector, None)
@@ -172,3 +185,77 @@ class SelectortemLoaderTest(unittest.TestCase):
self.assertEqual(loader.get_output_value('url'), ['http://www.scrapy.org'])
loader.replace_css('url', 'a::attr(href)', re=r'http://www\.(.+)')
self.assertEqual(loader.get_output_value('url'), ['scrapy.org'])
+
+ def test_jmes_not_installed(self):
+ selector = MagicMock(spec=Selector)
+ del selector.jmespath
+ loader = CustomItemLoader(selector=selector)
+ with self.assertRaises(AttributeError) as err:
+ loader.add_jmes("name", "name", re="ma")
+
+ self.assertEqual(str(err.exception), "Please install parsel >= 1.8.1 to get jmespath support")
+
+ def test_add_jmes_re(self):
+ loader = CustomItemLoader(selector=self.jmes_selector)
+ loader.add_jmes("name", "name", re="ma")
+ self.assertEqual(loader.get_output_value("name"), ["Ma"])
+
+ loader.add_jmes("url", "website.url", re="http://(.+)")
+ self.assertEqual(loader.get_output_value("url"), ["www.scrapy.org"])
+
+ loader = CustomItemLoader(selector=self.jmes_selector)
+ loader.add_jmes("name", "name", re=re.compile("ma"))
+ self.assertEqual(loader.get_output_value("name"), ["Ma"])
+
+ loader.add_jmes("url", "website.url", re=re.compile("http://(.+)"))
+ self.assertEqual(loader.get_output_value("url"), ["www.scrapy.org"])
+
+ def test_get_jmes(self):
+ loader = CustomItemLoader(selector=self.jmes_selector)
+ self.assertEqual(loader.get_jmes("description"), ["paragraph"])
+ self.assertEqual(loader.get_jmes("description", TakeFirst()), "paragraph")
+ self.assertEqual(loader.get_jmes("description", TakeFirst(), re="pa"), "pa")
+
+ self.assertEqual(
+ loader.get_jmes(["description", "name"]), ["paragraph", "marta"]
+ )
+ self.assertEqual(
+ loader.get_jmes(["website.url", "logo"]),
+ ["http://www.scrapy.org", "/images/logo.png"],
+ )
+
+ def test_replace_jmes(self):
+ loader = CustomItemLoader(selector=self.jmes_selector)
+ self.assertTrue(loader.selector)
+ loader.add_jmes("name", "name")
+ self.assertEqual(loader.get_output_value("name"), ["Marta"])
+ loader.replace_jmes("name", "description")
+ self.assertEqual(loader.get_output_value("name"), ["Paragraph"])
+
+ loader.replace_jmes("name", ["description", "name"])
+ self.assertEqual(loader.get_output_value("name"), ["Paragraph", "Marta"])
+
+ loader.add_jmes("url", "website.url", re="http://(.+)")
+ self.assertEqual(loader.get_output_value("url"), ["www.scrapy.org"])
+ loader.replace_jmes("url", "logo")
+ self.assertEqual(loader.get_output_value("url"), ["/images/logo.png"])
+
+ def test_replace_jmes_multi_fields(self):
+ loader = CustomItemLoader(selector=self.jmes_selector)
+ loader.add_jmes(None, 'name', TakeFirst(), lambda x: {'name': x})
+ self.assertEqual(loader.get_output_value('name'), ['Marta'])
+ loader.replace_jmes(None, 'description', TakeFirst(), lambda x: {'name': x})
+ self.assertEqual(loader.get_output_value('name'), ['Paragraph'])
+
+ loader.add_jmes(None, 'website.url', TakeFirst(), lambda x: {'url': x})
+ self.assertEqual(loader.get_output_value('url'), ['http://www.scrapy.org'])
+ loader.replace_jmes(None, 'logo', TakeFirst(), lambda x: {'url': x})
+ self.assertEqual(loader.get_output_value('url'), ['/images/logo.png'])
+
+ def test_replace_jmes_re(self):
+ loader = CustomItemLoader(selector=self.jmes_selector)
+ self.assertTrue(loader.selector)
+ loader.add_jmes('url', 'website.url')
+ self.assertEqual(loader.get_output_value('url'), ['http://www.scrapy.org'])
+ loader.replace_jmes('url', 'website.url', re=r'http://www\.(.+)')
+ self.assertEqual(loader.get_output_value('url'), ['scrapy.org'])
|
Feature Request: Adding "add_jmes" and "replace_jmes" method to ItemLoader
So, currently the `ItemLoader` class has 6 methods for loading values:
`add_xpath()`
`replace_xpath()`
`add_css()`
`replace_css()`
`add_value()`
`replace_value()`
Could we add another 2 more methods for loading data through JmesPath selectors. Currently, I have to use the `SelectJmes` processor to do this. Eventually, it looks really ugly and ends up taking so much line real estate.
I did a hack where I extended the ItemLoader to include those 2 extra methods that are desperately needed.
When there is json data to parse instead of html, JmesPath selectors are the best way to go for parsing, so there should be support for JmesPath selectors in the ItemLoader class as well.
|
0.0
|
1458c6786408725c8025346e5b64d95614c6fa42
|
[
"tests/test_selector_loader.py::SelectortemLoaderTest::test_add_jmes_re",
"tests/test_selector_loader.py::SelectortemLoaderTest::test_get_jmes",
"tests/test_selector_loader.py::SelectortemLoaderTest::test_jmes_not_installed",
"tests/test_selector_loader.py::SelectortemLoaderTest::test_replace_jmes",
"tests/test_selector_loader.py::SelectortemLoaderTest::test_replace_jmes_multi_fields",
"tests/test_selector_loader.py::SelectortemLoaderTest::test_replace_jmes_re"
] |
[
"tests/test_selector_loader.py::SelectortemLoaderTest::test_add_css_re",
"tests/test_selector_loader.py::SelectortemLoaderTest::test_add_xpath_re",
"tests/test_selector_loader.py::SelectortemLoaderTest::test_add_xpath_variables",
"tests/test_selector_loader.py::SelectortemLoaderTest::test_get_css",
"tests/test_selector_loader.py::SelectortemLoaderTest::test_get_xpath",
"tests/test_selector_loader.py::SelectortemLoaderTest::test_init_method",
"tests/test_selector_loader.py::SelectortemLoaderTest::test_init_method_errors",
"tests/test_selector_loader.py::SelectortemLoaderTest::test_init_method_with_selector",
"tests/test_selector_loader.py::SelectortemLoaderTest::test_init_method_with_selector_css",
"tests/test_selector_loader.py::SelectortemLoaderTest::test_replace_css",
"tests/test_selector_loader.py::SelectortemLoaderTest::test_replace_css_multi_fields",
"tests/test_selector_loader.py::SelectortemLoaderTest::test_replace_css_re",
"tests/test_selector_loader.py::SelectortemLoaderTest::test_replace_xpath",
"tests/test_selector_loader.py::SelectortemLoaderTest::test_replace_xpath_multi_fields",
"tests/test_selector_loader.py::SelectortemLoaderTest::test_replace_xpath_re"
] |
{
"failed_lite_validators": [
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-04-19 07:55:49+00:00
|
bsd-3-clause
| 5,403 |
|
scrapy__parsel-141
|
diff --git a/parsel/selector.py b/parsel/selector.py
index bbd4289..666a303 100644
--- a/parsel/selector.py
+++ b/parsel/selector.py
@@ -7,7 +7,7 @@ import sys
import six
from lxml import etree, html
-from .utils import flatten, iflatten, extract_regex
+from .utils import flatten, iflatten, extract_regex, shorten
from .csstranslator import HTMLTranslator, GenericTranslator
@@ -358,6 +358,6 @@ class Selector(object):
__nonzero__ = __bool__
def __str__(self):
- data = repr(self.get()[:40])
+ data = repr(shorten(self.get(), width=40))
return "<%s xpath=%r data=%s>" % (type(self).__name__, self._expr, data)
__repr__ = __str__
diff --git a/parsel/utils.py b/parsel/utils.py
index 56bb105..458bc6c 100644
--- a/parsel/utils.py
+++ b/parsel/utils.py
@@ -80,4 +80,15 @@ def extract_regex(regex, text, replace_entities=True):
strings = flatten(strings)
if not replace_entities:
return strings
- return [w3lib_replace_entities(s, keep=['lt', 'amp']) for s in strings]
\ No newline at end of file
+ return [w3lib_replace_entities(s, keep=['lt', 'amp']) for s in strings]
+
+
+def shorten(text, width, suffix='...'):
+ """Truncate the given text to fit in the given width."""
+ if len(text) <= width:
+ return text
+ if width > len(suffix):
+ return text[:width-len(suffix)] + suffix
+ if width >= 0:
+ return suffix[len(suffix)-width:]
+ raise ValueError('width must be equal or greater than 0')
|
scrapy/parsel
|
1327e0dadef4d825d060e647808ccc01cb8e7f96
|
diff --git a/tests/test_selector.py b/tests/test_selector.py
index e504166..c8845a5 100644
--- a/tests/test_selector.py
+++ b/tests/test_selector.py
@@ -133,9 +133,9 @@ class SelectorTestCase(unittest.TestCase):
body = u"<p><input name='{}' value='\xa9'/></p>".format(50 * 'b')
sel = self.sscls(text=body)
- representation = "<Selector xpath='//input/@name' data='{}'>".format(40 * 'b')
+ representation = "<Selector xpath='//input/@name' data='{}...'>".format(37 * 'b')
if six.PY2:
- representation = "<Selector xpath='//input/@name' data=u'{}'>".format(40 * 'b')
+ representation = "<Selector xpath='//input/@name' data=u'{}...'>".format(37 * 'b')
self.assertEqual(
[repr(it) for it in sel.xpath('//input/@name')],
diff --git a/tests/test_utils.py b/tests/test_utils.py
new file mode 100644
index 0000000..da20ec2
--- /dev/null
+++ b/tests/test_utils.py
@@ -0,0 +1,26 @@
+from parsel.utils import shorten
+
+from pytest import mark, raises
+import six
+
+
[email protected](
+ 'width,expected',
+ (
+ (-1, ValueError),
+ (0, u''),
+ (1, u'.'),
+ (2, u'..'),
+ (3, u'...'),
+ (4, u'f...'),
+ (5, u'fo...'),
+ (6, u'foobar'),
+ (7, u'foobar'),
+ )
+)
+def test_shorten(width, expected):
+ if isinstance(expected, six.string_types):
+ assert shorten(u'foobar', width) == expected
+ else:
+ with raises(expected):
+ shorten(u'foobar', width)
|
Misleading "data=" in Selector representation
Motivation: https://stackoverflow.com/questions/44407581/python-scrapy-output-is-cut-off-hence-wount-let-me-correctly-build-queries
With
```
<Selector xpath='//div[@id="all_game_info"]' data=u'<div id="all_game_info" class="table_wrapper columns'>
```
the user thought that the selector had only extracted `u'<div id="all_game_info" class="table_wrapper columns'`
Suggestions:
* change `data=` to something like `data-preview=`
* or add `...` at the end, indicate the length of extracted data maybe
|
0.0
|
1327e0dadef4d825d060e647808ccc01cb8e7f96
|
[
"tests/test_selector.py::SelectorTestCase::test_accessing_attributes",
"tests/test_selector.py::SelectorTestCase::test_bodies_with_comments_only",
"tests/test_selector.py::SelectorTestCase::test_bool",
"tests/test_selector.py::SelectorTestCase::test_boolean_result",
"tests/test_selector.py::SelectorTestCase::test_check_text_argument_type",
"tests/test_selector.py::SelectorTestCase::test_configure_base_url",
"tests/test_selector.py::SelectorTestCase::test_differences_parsing_xml_vs_html",
"tests/test_selector.py::SelectorTestCase::test_dont_strip",
"tests/test_selector.py::SelectorTestCase::test_empty_bodies_shouldnt_raise_errors",
"tests/test_selector.py::SelectorTestCase::test_error_for_unknown_selector_type",
"tests/test_selector.py::SelectorTestCase::test_extending_selector",
"tests/test_selector.py::SelectorTestCase::test_extract_first",
"tests/test_selector.py::SelectorTestCase::test_extract_first_default",
"tests/test_selector.py::SelectorTestCase::test_http_header_encoding_precedence",
"tests/test_selector.py::SelectorTestCase::test_invalid_xpath",
"tests/test_selector.py::SelectorTestCase::test_invalid_xpath_unicode",
"tests/test_selector.py::SelectorTestCase::test_list_elements_type",
"tests/test_selector.py::SelectorTestCase::test_make_links_absolute",
"tests/test_selector.py::SelectorTestCase::test_mixed_nested_selectors",
"tests/test_selector.py::SelectorTestCase::test_namespaces_adhoc",
"tests/test_selector.py::SelectorTestCase::test_namespaces_adhoc_variables",
"tests/test_selector.py::SelectorTestCase::test_namespaces_multiple",
"tests/test_selector.py::SelectorTestCase::test_namespaces_multiple_adhoc",
"tests/test_selector.py::SelectorTestCase::test_namespaces_simple",
"tests/test_selector.py::SelectorTestCase::test_nested_selectors",
"tests/test_selector.py::SelectorTestCase::test_null_bytes_shouldnt_raise_errors",
"tests/test_selector.py::SelectorTestCase::test_pickle_selector",
"tests/test_selector.py::SelectorTestCase::test_pickle_selector_list",
"tests/test_selector.py::SelectorTestCase::test_re",
"tests/test_selector.py::SelectorTestCase::test_re_first",
"tests/test_selector.py::SelectorTestCase::test_re_intl",
"tests/test_selector.py::SelectorTestCase::test_re_replace_entities",
"tests/test_selector.py::SelectorTestCase::test_remove_attributes_namespaces",
"tests/test_selector.py::SelectorTestCase::test_remove_namespaces",
"tests/test_selector.py::SelectorTestCase::test_replacement_char_from_badly_encoded_body",
"tests/test_selector.py::SelectorTestCase::test_replacement_null_char_from_body",
"tests/test_selector.py::SelectorTestCase::test_representation_slice",
"tests/test_selector.py::SelectorTestCase::test_representation_unicode_query",
"tests/test_selector.py::SelectorTestCase::test_select_on_text_nodes",
"tests/test_selector.py::SelectorTestCase::test_select_on_unevaluable_nodes",
"tests/test_selector.py::SelectorTestCase::test_select_unicode_query",
"tests/test_selector.py::SelectorTestCase::test_selector_get_alias",
"tests/test_selector.py::SelectorTestCase::test_selector_getall_alias",
"tests/test_selector.py::SelectorTestCase::test_selector_over_text",
"tests/test_selector.py::SelectorTestCase::test_selectorlist_get_alias",
"tests/test_selector.py::SelectorTestCase::test_selectorlist_getall_alias",
"tests/test_selector.py::SelectorTestCase::test_simple_selection",
"tests/test_selector.py::SelectorTestCase::test_simple_selection_with_variables",
"tests/test_selector.py::SelectorTestCase::test_simple_selection_with_variables_escape_friendly",
"tests/test_selector.py::SelectorTestCase::test_slicing",
"tests/test_selector.py::SelectorTestCase::test_smart_strings",
"tests/test_selector.py::SelectorTestCase::test_text_or_root_is_required",
"tests/test_selector.py::SelectorTestCase::test_weakref_slots",
"tests/test_selector.py::SelectorTestCase::test_xml_entity_expansion",
"tests/test_selector.py::ExsltTestCase::test_regexp",
"tests/test_selector.py::ExsltTestCase::test_set",
"tests/test_utils.py::test_shorten[-1-ValueError]",
"tests/test_utils.py::test_shorten[0-]",
"tests/test_utils.py::test_shorten[1-.]",
"tests/test_utils.py::test_shorten[2-..]",
"tests/test_utils.py::test_shorten[3-...]",
"tests/test_utils.py::test_shorten[4-f...]",
"tests/test_utils.py::test_shorten[5-fo...]",
"tests/test_utils.py::test_shorten[6-foobar]",
"tests/test_utils.py::test_shorten[7-foobar]"
] |
[] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-07-10 19:57:20+00:00
|
bsd-3-clause
| 5,404 |
|
scrapy__parsel-247
|
diff --git a/docs/usage.rst b/docs/usage.rst
index d0a6fb0..dcef13d 100644
--- a/docs/usage.rst
+++ b/docs/usage.rst
@@ -400,7 +400,7 @@ Removing elements
-----------------
If for any reason you need to remove elements based on a Selector or
-a SelectorList, you can do it with the ``remove()`` method, available for both
+a SelectorList, you can do it with the ``drop()`` method, available for both
classes.
.. warning:: this is a destructive action and cannot be undone. The original
@@ -425,7 +425,7 @@ Example removing an ad from a blog post:
>>> sel = Selector(text=doc)
>>> sel.xpath('//div/text()').getall()
['Content paragraph...', '\n ', '\n Ad content...\n ', '\n ', '\n ', 'More content...']
- >>> sel.xpath('//div[@class="ad"]').remove()
+ >>> sel.xpath('//div[@class="ad"]').drop()
>>> sel.xpath('//div//text()').getall()
['Content paragraph...', 'More content...']
diff --git a/parsel/selector.py b/parsel/selector.py
index e0d5a40..b84b030 100644
--- a/parsel/selector.py
+++ b/parsel/selector.py
@@ -4,13 +4,14 @@ XPath selectors based on lxml
import typing
import warnings
-from typing import Any, Dict, List, Optional, Mapping, Pattern, Union
+from typing import Any, Dict, List, Mapping, Optional, Pattern, Union
+from warnings import warn
from lxml import etree, html
from pkg_resources import parse_version
-from .utils import flatten, iflatten, extract_regex, shorten
-from .csstranslator import HTMLTranslator, GenericTranslator
+from .csstranslator import GenericTranslator, HTMLTranslator
+from .utils import extract_regex, flatten, iflatten, shorten
_SelectorType = typing.TypeVar("_SelectorType", bound="Selector")
@@ -27,6 +28,10 @@ class CannotRemoveElementWithoutParent(Exception):
pass
+class CannotDropElementWithoutParent(CannotRemoveElementWithoutParent):
+ pass
+
+
class SafeXMLParser(etree.XMLParser):
def __init__(self, *args, **kwargs) -> None:
kwargs.setdefault("resolve_entities", False)
@@ -236,9 +241,21 @@ class SelectorList(List[_SelectorType]):
"""
Remove matched nodes from the parent for each element in this list.
"""
+ warn(
+ "Method parsel.selector.SelectorList.remove is deprecated, please use parsel.selector.SelectorList.drop method instead",
+ category=DeprecationWarning,
+ stacklevel=2,
+ )
for x in self:
x.remove()
+ def drop(self) -> None:
+ """
+ Drop matched nodes from the parent for each element in this list.
+ """
+ for x in self:
+ x.drop()
+
class Selector:
"""
@@ -503,6 +520,11 @@ class Selector:
"""
Remove matched nodes from the parent element.
"""
+ warn(
+ "Method parsel.selector.Selector.remove is deprecated, please use parsel.selector.Selector.drop method instead",
+ category=DeprecationWarning,
+ stacklevel=2,
+ )
try:
parent = self.root.getparent()
except AttributeError:
@@ -523,6 +545,30 @@ class Selector:
"are you trying to remove a root element?"
)
+ def drop(self):
+ """
+ Drop matched nodes from the parent element.
+ """
+ try:
+ self.root.getparent()
+ except AttributeError:
+ # 'str' object has no attribute 'getparent'
+ raise CannotRemoveElementWithoutRoot(
+ "The node you're trying to drop has no root, "
+ "are you trying to drop a pseudo-element? "
+ "Try to use 'li' as a selector instead of 'li::text' or "
+ "'//li' instead of '//li/text()', for example."
+ )
+
+ try:
+ self.root.drop_tree()
+ except (AttributeError, AssertionError):
+ # 'NoneType' object has no attribute 'drop'
+ raise CannotDropElementWithoutParent(
+ "The node you're trying to remove has no parent, "
+ "are you trying to remove a root element?"
+ )
+
@property
def attrib(self) -> Dict[str, str]:
"""Return the attributes dictionary for underlying element."""
|
scrapy/parsel
|
96fc3d7b6f0abd4958bc70a4fdc345904caf21c2
|
diff --git a/tests/test_selector.py b/tests/test_selector.py
index 99d9a55..d0bb281 100644
--- a/tests/test_selector.py
+++ b/tests/test_selector.py
@@ -1050,7 +1050,7 @@ class SelectorTestCase(unittest.TestCase):
text="<html><body><ul><li>1</li><li>2</li><li>3</li></ul></body></html>"
)
sel_list = sel.css("li")
- sel_list.remove()
+ sel_list.drop()
self.assertIsSelectorList(sel.css("li"))
self.assertEqual(sel.css("li"), [])
@@ -1059,7 +1059,7 @@ class SelectorTestCase(unittest.TestCase):
text="<html><body><ul><li>1</li><li>2</li><li>3</li></ul></body></html>"
)
sel_list = sel.css("li")
- sel_list[0].remove()
+ sel_list[0].drop()
self.assertIsSelectorList(sel.css("li"))
self.assertEqual(sel.css("li::text").getall(), ["2", "3"])
@@ -1070,7 +1070,7 @@ class SelectorTestCase(unittest.TestCase):
sel_list = sel.css("li::text")
self.assertEqual(sel_list.getall(), ["1", "2", "3"])
with self.assertRaises(CannotRemoveElementWithoutRoot):
- sel_list.remove()
+ sel_list.drop()
self.assertIsSelectorList(sel.css("li"))
self.assertEqual(sel.css("li::text").getall(), ["1", "2", "3"])
@@ -1082,7 +1082,7 @@ class SelectorTestCase(unittest.TestCase):
sel_list = sel.css("li::text")
self.assertEqual(sel_list.getall(), ["1", "2", "3"])
with self.assertRaises(CannotRemoveElementWithoutRoot):
- sel_list[0].remove()
+ sel_list[0].drop()
self.assertIsSelectorList(sel.css("li"))
self.assertEqual(sel.css("li::text").getall(), ["1", "2", "3"])
@@ -1094,15 +1094,15 @@ class SelectorTestCase(unittest.TestCase):
sel_list = sel.css("li::text")
self.assertEqual(sel_list.getall(), ["1", "2", "3"])
with self.assertRaises(CannotRemoveElementWithoutParent):
- sel.remove()
+ sel.drop()
with self.assertRaises(CannotRemoveElementWithoutParent):
- sel.css("html").remove()
+ sel.css("html").drop()
self.assertIsSelectorList(sel.css("li"))
self.assertEqual(sel.css("li::text").getall(), ["1", "2", "3"])
- sel.css("body").remove()
+ sel.css("body").drop()
self.assertEqual(sel.get(), "<html></html>")
def test_deep_nesting(self):
@@ -1316,3 +1316,13 @@ class ExsltTestCase(unittest.TestCase):
).extract(),
["url", "name", "startDate", "location", "offers"],
)
+
+ def test_dont_remove_text_after_deleted_element(self) -> None:
+ sel = self.sscls(
+ text="""<html><body>Text before.<span>Text in.</span> Text after.</body></html>
+ """
+ )
+ sel.css("span").drop()
+ self.assertEqual(
+ sel.get(), "<html><body>Text before. Text after.</body></html>"
+ )
|
.remove() also removes text after the deleted element
I tried removing an element as a way to exclude some repeated text from a website. I used the following code:
```python
import parsel
html = """
<html><body>
Text before.
<span>Text in.</span>
Text after.
</body></html>
"""
s = parsel.Selector(html)
s.css('span').remove()
print(s.get())
```
results in:
```html
<html><body>
Text before.
</body></html>
```
I would expect only the span to be removed, and the text after it to be left as-is, but it always removes the "text after" either until another element is encountered or it hits the end of the parent of the removed one.
|
0.0
|
96fc3d7b6f0abd4958bc70a4fdc345904caf21c2
|
[
"tests/test_selector.py::SelectorTestCase::test_remove_pseudo_element_selector",
"tests/test_selector.py::SelectorTestCase::test_remove_pseudo_element_selector_list",
"tests/test_selector.py::SelectorTestCase::test_remove_root_element_selector",
"tests/test_selector.py::SelectorTestCase::test_remove_selector",
"tests/test_selector.py::SelectorTestCase::test_remove_selector_list",
"tests/test_selector.py::ExsltTestCase::test_dont_remove_text_after_deleted_element"
] |
[
"tests/test_selector.py::SelectorTestCase::test_accessing_attributes",
"tests/test_selector.py::SelectorTestCase::test_bodies_with_comments_only",
"tests/test_selector.py::SelectorTestCase::test_bool",
"tests/test_selector.py::SelectorTestCase::test_boolean_result",
"tests/test_selector.py::SelectorTestCase::test_check_text_argument_type",
"tests/test_selector.py::SelectorTestCase::test_configure_base_url",
"tests/test_selector.py::SelectorTestCase::test_deep_nesting",
"tests/test_selector.py::SelectorTestCase::test_differences_parsing_xml_vs_html",
"tests/test_selector.py::SelectorTestCase::test_dont_strip",
"tests/test_selector.py::SelectorTestCase::test_empty_bodies_shouldnt_raise_errors",
"tests/test_selector.py::SelectorTestCase::test_error_for_unknown_selector_type",
"tests/test_selector.py::SelectorTestCase::test_extending_selector",
"tests/test_selector.py::SelectorTestCase::test_extract_first",
"tests/test_selector.py::SelectorTestCase::test_extract_first_default",
"tests/test_selector.py::SelectorTestCase::test_extract_first_re_default",
"tests/test_selector.py::SelectorTestCase::test_http_header_encoding_precedence",
"tests/test_selector.py::SelectorTestCase::test_invalid_xpath",
"tests/test_selector.py::SelectorTestCase::test_invalid_xpath_unicode",
"tests/test_selector.py::SelectorTestCase::test_list_elements_type",
"tests/test_selector.py::SelectorTestCase::test_make_links_absolute",
"tests/test_selector.py::SelectorTestCase::test_mixed_nested_selectors",
"tests/test_selector.py::SelectorTestCase::test_namespaces_adhoc",
"tests/test_selector.py::SelectorTestCase::test_namespaces_adhoc_variables",
"tests/test_selector.py::SelectorTestCase::test_namespaces_multiple",
"tests/test_selector.py::SelectorTestCase::test_namespaces_multiple_adhoc",
"tests/test_selector.py::SelectorTestCase::test_namespaces_simple",
"tests/test_selector.py::SelectorTestCase::test_nested_selectors",
"tests/test_selector.py::SelectorTestCase::test_null_bytes_shouldnt_raise_errors",
"tests/test_selector.py::SelectorTestCase::test_pickle_selector",
"tests/test_selector.py::SelectorTestCase::test_pickle_selector_list",
"tests/test_selector.py::SelectorTestCase::test_re",
"tests/test_selector.py::SelectorTestCase::test_re_first",
"tests/test_selector.py::SelectorTestCase::test_re_intl",
"tests/test_selector.py::SelectorTestCase::test_re_replace_entities",
"tests/test_selector.py::SelectorTestCase::test_remove_attributes_namespaces",
"tests/test_selector.py::SelectorTestCase::test_remove_namespaces",
"tests/test_selector.py::SelectorTestCase::test_remove_namespaces_embedded",
"tests/test_selector.py::SelectorTestCase::test_replacement_char_from_badly_encoded_body",
"tests/test_selector.py::SelectorTestCase::test_replacement_null_char_from_body",
"tests/test_selector.py::SelectorTestCase::test_representation_slice",
"tests/test_selector.py::SelectorTestCase::test_representation_unicode_query",
"tests/test_selector.py::SelectorTestCase::test_select_on_text_nodes",
"tests/test_selector.py::SelectorTestCase::test_select_on_unevaluable_nodes",
"tests/test_selector.py::SelectorTestCase::test_select_unicode_query",
"tests/test_selector.py::SelectorTestCase::test_selector_get_alias",
"tests/test_selector.py::SelectorTestCase::test_selector_getall_alias",
"tests/test_selector.py::SelectorTestCase::test_selector_over_text",
"tests/test_selector.py::SelectorTestCase::test_selectorlist_get_alias",
"tests/test_selector.py::SelectorTestCase::test_selectorlist_getall_alias",
"tests/test_selector.py::SelectorTestCase::test_simple_selection",
"tests/test_selector.py::SelectorTestCase::test_simple_selection_with_variables",
"tests/test_selector.py::SelectorTestCase::test_simple_selection_with_variables_escape_friendly",
"tests/test_selector.py::SelectorTestCase::test_slicing",
"tests/test_selector.py::SelectorTestCase::test_smart_strings",
"tests/test_selector.py::SelectorTestCase::test_text_or_root_is_required",
"tests/test_selector.py::SelectorTestCase::test_weakref_slots",
"tests/test_selector.py::SelectorTestCase::test_xml_entity_expansion",
"tests/test_selector.py::ExsltTestCase::test_regexp",
"tests/test_selector.py::ExsltTestCase::test_set"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-07-12 01:22:48+00:00
|
bsd-3-clause
| 5,405 |
|
scrapy__protego-27
|
diff --git a/src/protego.py b/src/protego.py
index f859e0c..205e5d5 100644
--- a/src/protego.py
+++ b/src/protego.py
@@ -299,6 +299,8 @@ class Protego(object):
@classmethod
def parse(cls, content):
o = cls()
+ if not isinstance(content, str):
+ raise ValueError(f"Protego.parse expects str, got {type(content).__name__}")
o._parse_robotstxt(content)
return o
|
scrapy/protego
|
17d947446d44809efa65f5a4b727f7d9c9cccb6c
|
diff --git a/tests/test_protego.py b/tests/test_protego.py
index 97ffdfe..6389b02 100644
--- a/tests/test_protego.py
+++ b/tests/test_protego.py
@@ -1059,3 +1059,10 @@ class TestProtego(TestCase):
rp = Protego.parse(content)
self.assertFalse(rp.can_fetch("http://example.com/", "FooBot"))
self.assertFalse(rp.can_fetch("http://example.com", "FooBot"))
+
+ def test_bytestrings(self):
+ content = b"User-Agent: FootBot\nDisallow: /something"
+ with self.assertRaises(ValueError) as context:
+ Protego.parse(content=content)
+
+ self.assertEqual("Protego.parse expects str, got bytes", str(context.exception))
|
Accept robots.txt as bytes
```python
>>> robots_txt = b"User-Agent: *\nDisallow: /\n"
>>> robots_txt_parser = Protego.parse(robots_txt)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/adrian/temporal/venv/lib/python3.9/site-packages/protego.py", line 310, in parse
o._parse_robotstxt(content)
File "/home/adrian/temporal/venv/lib/python3.9/site-packages/protego.py", line 327, in _parse_robotstxt
hash_pos = line.find('#')
TypeError: argument should be integer or bytes-like object, not 'str'
>>> robots_txt = "User-Agent: *\nDisallow: /\n"
>>> robots_txt_parser = Protego.parse(robots_txt)
>>>
```
|
0.0
|
17d947446d44809efa65f5a4b727f7d9c9cccb6c
|
[
"tests/test_protego.py::TestProtego::test_bytestrings"
] |
[
"tests/test_protego.py::TestProtego::test_1994rfc_example",
"tests/test_protego.py::TestProtego::test_1996rfc_examples",
"tests/test_protego.py::TestProtego::test_allowed",
"tests/test_protego.py::TestProtego::test_allowed_wildcards",
"tests/test_protego.py::TestProtego::test_comments",
"tests/test_protego.py::TestProtego::test_crawl_delay",
"tests/test_protego.py::TestProtego::test_default_user_agent",
"tests/test_protego.py::TestProtego::test_directive_case_insensitivity",
"tests/test_protego.py::TestProtego::test_disallow_target_url_path_is_missing",
"tests/test_protego.py::TestProtego::test_empty_disallow_allow_directives",
"tests/test_protego.py::TestProtego::test_empty_record_group",
"tests/test_protego.py::TestProtego::test_empty_response",
"tests/test_protego.py::TestProtego::test_escaped_special_symbols",
"tests/test_protego.py::TestProtego::test_escaped_url",
"tests/test_protego.py::TestProtego::test_generosity",
"tests/test_protego.py::TestProtego::test_grouping_unknown_keys",
"tests/test_protego.py::TestProtego::test_implicit_allow",
"tests/test_protego.py::TestProtego::test_index_html_is_directory",
"tests/test_protego.py::TestProtego::test_length_based_precedence",
"tests/test_protego.py::TestProtego::test_line_endings",
"tests/test_protego.py::TestProtego::test_malformed_crawl_delay",
"tests/test_protego.py::TestProtego::test_malformed_disallow",
"tests/test_protego.py::TestProtego::test_no_crawl_delay",
"tests/test_protego.py::TestProtego::test_no_leading_user_agent",
"tests/test_protego.py::TestProtego::test_no_preferred_host",
"tests/test_protego.py::TestProtego::test_no_request_rate",
"tests/test_protego.py::TestProtego::test_no_sitemaps",
"tests/test_protego.py::TestProtego::test_nonterminal_dollar",
"tests/test_protego.py::TestProtego::test_percentage_encoding",
"tests/test_protego.py::TestProtego::test_request_rate",
"tests/test_protego.py::TestProtego::test_sitemaps",
"tests/test_protego.py::TestProtego::test_sitemaps_come_first",
"tests/test_protego.py::TestProtego::test_skip_malformed_line",
"tests/test_protego.py::TestProtego::test_skip_unknown_directives",
"tests/test_protego.py::TestProtego::test_special_symbols_dual_behaviour",
"tests/test_protego.py::TestProtego::test_unescaped_url",
"tests/test_protego.py::TestProtego::test_unicode_url_and_useragent",
"tests/test_protego.py::TestProtego::test_url_case_sensitivity",
"tests/test_protego.py::TestProtego::test_url_parts",
"tests/test_protego.py::TestProtego::test_user_agent_case_insensitivity",
"tests/test_protego.py::TestProtego::test_user_agent_grouping",
"tests/test_protego.py::TestProtego::test_with_absolute_urls"
] |
{
"failed_lite_validators": [
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-07-04 17:25:43+00:00
|
bsd-3-clause
| 5,406 |
|
scrapy__scrapy-2065
|
diff --git a/scrapy/utils/gz.py b/scrapy/utils/gz.py
index cfb652143..afc7ed128 100644
--- a/scrapy/utils/gz.py
+++ b/scrapy/utils/gz.py
@@ -50,9 +50,12 @@ def gunzip(data):
raise
return output
-_is_gzipped_re = re.compile(br'^application/(x-)?gzip\b', re.I)
+_is_gzipped = re.compile(br'^application/(x-)?gzip\b', re.I).search
+_is_octetstream = re.compile(br'^(application|binary)/octet-stream\b', re.I).search
def is_gzipped(response):
"""Return True if the response is gzipped, or False otherwise"""
ctype = response.headers.get('Content-Type', b'')
- return _is_gzipped_re.search(ctype) is not None
+ cenc = response.headers.get('Content-Encoding', b'').lower()
+ return (_is_gzipped(ctype) or
+ (_is_octetstream(ctype) and cenc in (b'gzip', b'x-gzip')))
|
scrapy/scrapy
|
d43a35735a062a4260b002cfbcd3236c77ef9399
|
diff --git a/tests/test_downloadermiddleware_httpcompression.py b/tests/test_downloadermiddleware_httpcompression.py
index 24955a515..b2426946d 100644
--- a/tests/test_downloadermiddleware_httpcompression.py
+++ b/tests/test_downloadermiddleware_httpcompression.py
@@ -145,6 +145,26 @@ class HttpCompressionTest(TestCase):
self.assertEqual(response.headers['Content-Encoding'], b'gzip')
self.assertEqual(response.headers['Content-Type'], b'application/gzip')
+ def test_process_response_gzip_app_octetstream_contenttype(self):
+ response = self._getresponse('gzip')
+ response.headers['Content-Type'] = 'application/octet-stream'
+ request = response.request
+
+ newresponse = self.mw.process_response(request, response, self.spider)
+ self.assertIs(newresponse, response)
+ self.assertEqual(response.headers['Content-Encoding'], b'gzip')
+ self.assertEqual(response.headers['Content-Type'], b'application/octet-stream')
+
+ def test_process_response_gzip_binary_octetstream_contenttype(self):
+ response = self._getresponse('x-gzip')
+ response.headers['Content-Type'] = 'binary/octet-stream'
+ request = response.request
+
+ newresponse = self.mw.process_response(request, response, self.spider)
+ self.assertIs(newresponse, response)
+ self.assertEqual(response.headers['Content-Encoding'], b'gzip')
+ self.assertEqual(response.headers['Content-Type'], b'binary/octet-stream')
+
def test_process_response_head_request_no_decode_required(self):
response = self._getresponse('gzip')
response.headers['Content-Type'] = 'application/gzip'
|
IOError, 'Not a gzipped file'
while trying to access sitemap from robots.txt , Scrapy fails with **IOError, 'Not a gzipped file'** error
not sure if this issue is related to following issue(s)
https://github.com/scrapy/scrapy/issues/193 -> closed issue
https://github.com/scrapy/scrapy/pull/660 -> merged pull request to address issue 193
https://github.com/scrapy/scrapy/issues/951 -> open issue
> line where code fails in gzip.py at line # 197
```python
def _read_gzip_header(self):
magic = self.fileobj.read(2)
if magic != '\037\213':
raise IOError, 'Not a gzipped file'
```
#Response Header
```
Content-Encoding: gzip
Accept-Ranges: bytes
X-Amz-Request-Id: BFFF010DDE6268DA
Vary: Accept-Encoding
Server: AmazonS3
Last-Modified: Wed, 15 Jun 2016 19:02:20 GMT
Etag: "300bb71d6897cb2a22bba0bd07978c84"
Cache-Control: no-transform
Date: Sun, 19 Jun 2016 10:54:53 GMT
Content-Type: binary/octet-stream
```
Error Log:
```log
Traceback (most recent call last):
File "c:\venv\scrapy1.0\lib\site-packages\scrapy\utils\defer.py", line 102, in iter_errback
yield next(it)
File "c:\venv\scrapy1.0\lib\site-packages\scrapy\spidermiddlewares\offsite.py", line 29, in process_spider_output
for x in result:
File "c:\venv\scrapy1.0\lib\site-packages\scrapy\spidermiddlewares\referer.py", line 22, in <genexpr>
return (_set_referer(r) for r in result or ())
File "c:\venv\scrapy1.0\lib\site-packages\scrapy\spidermiddlewares\urllength.py", line 37, in <genexpr>
return (r for r in result or () if _filter(r))
File "c:\venv\scrapy1.0\lib\site-packages\scrapy\spidermiddlewares\depth.py", line 58, in <genexpr>
return (r for r in result or () if _filter(r))
File "D:\projects\sitemap_spider\sitemap_spider\spiders\mainspider.py", line 31, in _parse_sitemap
body = self._get_sitemap_body(response)
File "c:\venv\scrapy1.0\lib\site-packages\scrapy\spiders\sitemap.py", line 67, in _get_sitemap_body
return gunzip(response.body)
File "c:\venv\scrapy1.0\lib\site-packages\scrapy\utils\gz.py", line 37, in gunzip
chunk = read1(f, 8196)
File "c:\venv\scrapy1.0\lib\site-packages\scrapy\utils\gz.py", line 21, in read1
return gzf.read(size)
File "c:\python27\Lib\gzip.py", line 268, in read
self._read(readsize)
File "c:\python27\Lib\gzip.py", line 303, in _read
self._read_gzip_header()
File "c:\python27\Lib\gzip.py", line 197, in _read_gzip_header
raise IOError, 'Not a gzipped file'
```
i did download file manually and was able to extract the content so it is not like file is corrupted
as an example sitemap url : you can follow amazon robots.txt
|
0.0
|
d43a35735a062a4260b002cfbcd3236c77ef9399
|
[
"tests/test_downloadermiddleware_httpcompression.py::HttpCompressionTest::test_process_response_gzip_app_octetstream_contenttype",
"tests/test_downloadermiddleware_httpcompression.py::HttpCompressionTest::test_process_response_gzip_binary_octetstream_contenttype"
] |
[
"tests/test_downloadermiddleware_httpcompression.py::HttpCompressionTest::test_multipleencodings",
"tests/test_downloadermiddleware_httpcompression.py::HttpCompressionTest::test_process_request",
"tests/test_downloadermiddleware_httpcompression.py::HttpCompressionTest::test_process_response_encoding_inside_body",
"tests/test_downloadermiddleware_httpcompression.py::HttpCompressionTest::test_process_response_force_recalculate_encoding",
"tests/test_downloadermiddleware_httpcompression.py::HttpCompressionTest::test_process_response_gzip",
"tests/test_downloadermiddleware_httpcompression.py::HttpCompressionTest::test_process_response_gzipped_contenttype",
"tests/test_downloadermiddleware_httpcompression.py::HttpCompressionTest::test_process_response_head_request_no_decode_required",
"tests/test_downloadermiddleware_httpcompression.py::HttpCompressionTest::test_process_response_plain",
"tests/test_downloadermiddleware_httpcompression.py::HttpCompressionTest::test_process_response_rawdeflate",
"tests/test_downloadermiddleware_httpcompression.py::HttpCompressionTest::test_process_response_zlibdelate"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2016-06-20 14:49:59+00:00
|
bsd-3-clause
| 5,407 |
|
scrapy__scrapy-2103
|
diff --git a/scrapy/utils/url.py b/scrapy/utils/url.py
index c80fc6e70..406eb5843 100644
--- a/scrapy/utils/url.py
+++ b/scrapy/utils/url.py
@@ -41,9 +41,16 @@ def url_has_any_extension(url, extensions):
def _safe_ParseResult(parts, encoding='utf8', path_encoding='utf8'):
+ # IDNA encoding can fail for too long labels (>63 characters)
+ # or missing labels (e.g. http://.example.com)
+ try:
+ netloc = parts.netloc.encode('idna')
+ except UnicodeError:
+ netloc = parts.netloc
+
return (
to_native_str(parts.scheme),
- to_native_str(parts.netloc.encode('idna')),
+ to_native_str(netloc),
# default encoding for path component SHOULD be UTF-8
quote(to_bytes(parts.path, path_encoding), _safe_chars),
|
scrapy/scrapy
|
0ef490e9ce1b3678cb214755f5fd71a72274f088
|
diff --git a/tests/test_utils_url.py b/tests/test_utils_url.py
index 1fc3a3510..b4819874d 100644
--- a/tests/test_utils_url.py
+++ b/tests/test_utils_url.py
@@ -265,6 +265,20 @@ class CanonicalizeUrlTest(unittest.TestCase):
# without encoding, already canonicalized URL is canonicalized identically
self.assertEqual(canonicalize_url(canonicalized), canonicalized)
+ def test_canonicalize_url_idna_exceptions(self):
+ # missing DNS label
+ self.assertEqual(
+ canonicalize_url(u"http://.example.com/résumé?q=résumé"),
+ "http://.example.com/r%C3%A9sum%C3%A9?q=r%C3%A9sum%C3%A9")
+
+ # DNS label too long
+ self.assertEqual(
+ canonicalize_url(
+ u"http://www.{label}.com/résumé?q=résumé".format(
+ label=u"example"*11)),
+ "http://www.{label}.com/r%C3%A9sum%C3%A9?q=r%C3%A9sum%C3%A9".format(
+ label=u"example"*11))
+
class AddHttpIfNoScheme(unittest.TestCase):
|
Unicode Link Extractor
When using the following to extract all of the links from a response:
```
self.link_extractor = LinkExtractor()
...
links = self.link_extractor.extract_links(response)
```
On rare occasions, the following error is thrown:
```
2016-05-25 12:13:55,432 [root] [ERROR] Error on http://detroit.curbed.com/2016/5/5/11605132/tiny-house-designer-show, traceback: Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/twisted/internet/base.py", line 1203, in mainLoop
self.runUntilCurrent()
File "/usr/local/lib/python2.7/site-packages/twisted/internet/base.py", line 825, in runUntilCurrent
call.func(*call.args, **call.kw)
File "/usr/local/lib/python2.7/site-packages/twisted/internet/defer.py", line 393, in callback
self._startRunCallbacks(result)
File "/usr/local/lib/python2.7/site-packages/twisted/internet/defer.py", line 501, in _startRunCallbacks
self._runCallbacks()
--- <exception caught here> ---
File "/usr/local/lib/python2.7/site-packages/twisted/internet/defer.py", line 588, in _runCallbacks
current.result = callback(current.result, *args, **kw)
File "/var/www/html/DomainCrawler/DomainCrawler/spiders/hybrid_spider.py", line 223, in parse
items.extend(self._extract_requests(response))
File "/var/www/html/DomainCrawler/DomainCrawler/spiders/hybrid_spider.py", line 477, in _extract_requests
links = self.link_extractor.extract_links(response)
File "/usr/local/lib/python2.7/site-packages/scrapy/linkextractors/lxmlhtml.py", line 111, in extract_links
all_links.extend(self._process_links(links))
File "/usr/local/lib/python2.7/site-packages/scrapy/linkextractors/__init__.py", line 103, in _process_links
link.url = canonicalize_url(urlparse(link.url))
File "/usr/local/lib/python2.7/site-packages/scrapy/utils/url.py", line 85, in canonicalize_url
parse_url(url), encoding=encoding)
File "/usr/local/lib/python2.7/site-packages/scrapy/utils/url.py", line 46, in _safe_ParseResult
to_native_str(parts.netloc.encode('idna')),
File "/usr/local/lib/python2.7/encodings/idna.py", line 164, in encode
result.append(ToASCII(label))
File "/usr/local/lib/python2.7/encodings/idna.py", line 73, in ToASCII
raise UnicodeError("label empty or too long")
exceptions.UnicodeError: label empty or too long
```
I was able to find some information concerning the error from [here](http://stackoverflow.com/questions/25103126/label-empty-or-too-long-python-urllib2).
My question is: What is the best way to handle this? Even if there is one bad link in the response, I'd want all of the other good links to be extracted.
|
0.0
|
0ef490e9ce1b3678cb214755f5fd71a72274f088
|
[
"tests/test_utils_url.py::CanonicalizeUrlTest::test_canonicalize_url_idna_exceptions"
] |
[
"tests/test_utils_url.py::UrlUtilsTest::test_url_is_from_any_domain",
"tests/test_utils_url.py::UrlUtilsTest::test_url_is_from_spider",
"tests/test_utils_url.py::UrlUtilsTest::test_url_is_from_spider_class_attributes",
"tests/test_utils_url.py::UrlUtilsTest::test_url_is_from_spider_with_allowed_domains",
"tests/test_utils_url.py::UrlUtilsTest::test_url_is_from_spider_with_allowed_domains_class_attributes",
"tests/test_utils_url.py::CanonicalizeUrlTest::test_append_missing_path",
"tests/test_utils_url.py::CanonicalizeUrlTest::test_canonicalize_idns",
"tests/test_utils_url.py::CanonicalizeUrlTest::test_canonicalize_parse_url",
"tests/test_utils_url.py::CanonicalizeUrlTest::test_canonicalize_url",
"tests/test_utils_url.py::CanonicalizeUrlTest::test_canonicalize_url_idempotence",
"tests/test_utils_url.py::CanonicalizeUrlTest::test_canonicalize_url_unicode_path",
"tests/test_utils_url.py::CanonicalizeUrlTest::test_canonicalize_url_unicode_query_string",
"tests/test_utils_url.py::CanonicalizeUrlTest::test_canonicalize_url_unicode_query_string_wrong_encoding",
"tests/test_utils_url.py::CanonicalizeUrlTest::test_canonicalize_urlparsed",
"tests/test_utils_url.py::CanonicalizeUrlTest::test_domains_are_case_insensitive",
"tests/test_utils_url.py::CanonicalizeUrlTest::test_dont_convert_safe_characters",
"tests/test_utils_url.py::CanonicalizeUrlTest::test_keep_blank_values",
"tests/test_utils_url.py::CanonicalizeUrlTest::test_non_ascii_percent_encoding_in_paths",
"tests/test_utils_url.py::CanonicalizeUrlTest::test_non_ascii_percent_encoding_in_query_arguments",
"tests/test_utils_url.py::CanonicalizeUrlTest::test_normalize_percent_encoding_in_paths",
"tests/test_utils_url.py::CanonicalizeUrlTest::test_normalize_percent_encoding_in_query_arguments",
"tests/test_utils_url.py::CanonicalizeUrlTest::test_quoted_slash_and_question_sign",
"tests/test_utils_url.py::CanonicalizeUrlTest::test_remove_fragments",
"tests/test_utils_url.py::CanonicalizeUrlTest::test_return_str",
"tests/test_utils_url.py::CanonicalizeUrlTest::test_safe_characters_unicode",
"tests/test_utils_url.py::CanonicalizeUrlTest::test_sorting",
"tests/test_utils_url.py::CanonicalizeUrlTest::test_spaces",
"tests/test_utils_url.py::CanonicalizeUrlTest::test_typical_usage",
"tests/test_utils_url.py::CanonicalizeUrlTest::test_urls_with_auth_and_ports",
"tests/test_utils_url.py::AddHttpIfNoScheme::test_add_scheme",
"tests/test_utils_url.py::AddHttpIfNoScheme::test_complete_url",
"tests/test_utils_url.py::AddHttpIfNoScheme::test_fragment",
"tests/test_utils_url.py::AddHttpIfNoScheme::test_path",
"tests/test_utils_url.py::AddHttpIfNoScheme::test_port",
"tests/test_utils_url.py::AddHttpIfNoScheme::test_preserve_ftp",
"tests/test_utils_url.py::AddHttpIfNoScheme::test_preserve_http",
"tests/test_utils_url.py::AddHttpIfNoScheme::test_preserve_http_complete_url",
"tests/test_utils_url.py::AddHttpIfNoScheme::test_preserve_http_fragment",
"tests/test_utils_url.py::AddHttpIfNoScheme::test_preserve_http_path",
"tests/test_utils_url.py::AddHttpIfNoScheme::test_preserve_http_port",
"tests/test_utils_url.py::AddHttpIfNoScheme::test_preserve_http_query",
"tests/test_utils_url.py::AddHttpIfNoScheme::test_preserve_http_username_password",
"tests/test_utils_url.py::AddHttpIfNoScheme::test_preserve_http_without_subdomain",
"tests/test_utils_url.py::AddHttpIfNoScheme::test_preserve_https",
"tests/test_utils_url.py::AddHttpIfNoScheme::test_protocol_relative",
"tests/test_utils_url.py::AddHttpIfNoScheme::test_protocol_relative_complete_url",
"tests/test_utils_url.py::AddHttpIfNoScheme::test_protocol_relative_fragment",
"tests/test_utils_url.py::AddHttpIfNoScheme::test_protocol_relative_path",
"tests/test_utils_url.py::AddHttpIfNoScheme::test_protocol_relative_port",
"tests/test_utils_url.py::AddHttpIfNoScheme::test_protocol_relative_query",
"tests/test_utils_url.py::AddHttpIfNoScheme::test_protocol_relative_username_password",
"tests/test_utils_url.py::AddHttpIfNoScheme::test_protocol_relative_without_subdomain",
"tests/test_utils_url.py::AddHttpIfNoScheme::test_query",
"tests/test_utils_url.py::AddHttpIfNoScheme::test_username_password",
"tests/test_utils_url.py::AddHttpIfNoScheme::test_without_subdomain",
"tests/test_utils_url.py::GuessSchemeTest::test_uri_001",
"tests/test_utils_url.py::GuessSchemeTest::test_uri_002",
"tests/test_utils_url.py::GuessSchemeTest::test_uri_003",
"tests/test_utils_url.py::GuessSchemeTest::test_uri_004",
"tests/test_utils_url.py::GuessSchemeTest::test_uri_005",
"tests/test_utils_url.py::GuessSchemeTest::test_uri_006",
"tests/test_utils_url.py::GuessSchemeTest::test_uri_007",
"tests/test_utils_url.py::GuessSchemeTest::test_uri_008",
"tests/test_utils_url.py::GuessSchemeTest::test_uri_009",
"tests/test_utils_url.py::GuessSchemeTest::test_uri_010",
"tests/test_utils_url.py::GuessSchemeTest::test_uri_011",
"tests/test_utils_url.py::GuessSchemeTest::test_uri_012",
"tests/test_utils_url.py::GuessSchemeTest::test_uri_013",
"tests/test_utils_url.py::GuessSchemeTest::test_uri_014",
"tests/test_utils_url.py::GuessSchemeTest::test_uri_015",
"tests/test_utils_url.py::GuessSchemeTest::test_uri_016",
"tests/test_utils_url.py::GuessSchemeTest::test_uri_017",
"tests/test_utils_url.py::GuessSchemeTest::test_uri_018",
"tests/test_utils_url.py::GuessSchemeTest::test_uri_019",
"tests/test_utils_url.py::GuessSchemeTest::test_uri_020"
] |
{
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
}
|
2016-07-08 10:36:57+00:00
|
bsd-3-clause
| 5,408 |
|
scrapy__scrapy-2327
|
diff --git a/docs/topics/architecture.rst b/docs/topics/architecture.rst
index 91c80acc0..ea0cb0ea7 100644
--- a/docs/topics/architecture.rst
+++ b/docs/topics/architecture.rst
@@ -41,25 +41,26 @@ this:
4. The :ref:`Engine <component-engine>` sends the Requests to the
:ref:`Downloader <component-downloader>`, passing through the
- :ref:`Downloader Middleware <component-downloader-middleware>`
- (requests direction).
+ :ref:`Downloader Middlewares <component-downloader-middleware>` (see
+ :meth:`~scrapy.downloadermiddlewares.DownloaderMiddleware.process_request`).
5. Once the page finishes downloading the
:ref:`Downloader <component-downloader>` generates a Response (with
that page) and sends it to the Engine, passing through the
- :ref:`Downloader Middleware <component-downloader-middleware>`
- (response direction).
+ :ref:`Downloader Middlewares <component-downloader-middleware>` (see
+ :meth:`~scrapy.downloadermiddlewares.DownloaderMiddleware.process_response`).
6. The :ref:`Engine <component-engine>` receives the Response from the
:ref:`Downloader <component-downloader>` and sends it to the
:ref:`Spider <component-spiders>` for processing, passing
- through the :ref:`Spider Middleware <component-spider-middleware>`
- (input direction).
+ through the :ref:`Spider Middleware <component-spider-middleware>` (see
+ :meth:`~scrapy.spidermiddlewares.SpiderMiddleware.process_spider_input`).
7. The :ref:`Spider <component-spiders>` processes the Response and returns
scraped items and new Requests (to follow) to the
:ref:`Engine <component-engine>`, passing through the
- :ref:`Spider Middleware <component-spider-middleware>` (output direction).
+ :ref:`Spider Middleware <component-spider-middleware>` (see
+ :meth:`~scrapy.spidermiddlewares.SpiderMiddleware.process_spider_output`).
8. The :ref:`Engine <component-engine>` sends processed items to
:ref:`Item Pipelines <component-pipelines>`, then send processed Requests to
diff --git a/docs/topics/downloader-middleware.rst b/docs/topics/downloader-middleware.rst
index 31545d548..15069e56e 100644
--- a/docs/topics/downloader-middleware.rst
+++ b/docs/topics/downloader-middleware.rst
@@ -27,7 +27,11 @@ The :setting:`DOWNLOADER_MIDDLEWARES` setting is merged with the
:setting:`DOWNLOADER_MIDDLEWARES_BASE` setting defined in Scrapy (and not meant
to be overridden) and then sorted by order to get the final sorted list of
enabled middlewares: the first middleware is the one closer to the engine and
-the last is the one closer to the downloader.
+the last is the one closer to the downloader. In other words,
+the :meth:`~scrapy.downloadermiddlewares.DownloaderMiddleware.process_request`
+method of each middleware will be invoked in increasing
+middleware order (100, 200, 300, ...) and the :meth:`~scrapy.downloadermiddlewares.DownloaderMiddleware.process_response` method
+of each middleware will be invoked in decreasing order.
To decide which order to assign to your middleware see the
:setting:`DOWNLOADER_MIDDLEWARES_BASE` setting and pick a value according to
diff --git a/docs/topics/item-pipeline.rst b/docs/topics/item-pipeline.rst
index 6b43fe258..8c7aa361f 100644
--- a/docs/topics/item-pipeline.rst
+++ b/docs/topics/item-pipeline.rst
@@ -106,9 +106,12 @@ format::
class JsonWriterPipeline(object):
- def __init__(self):
+ def open_spider(self, spider):
self.file = open('items.jl', 'wb')
+ def close_spider(self, spider):
+ self.file.close()
+
def process_item(self, item, spider):
line = json.dumps(dict(item)) + "\n"
self.file.write(line)
@@ -126,14 +129,7 @@ MongoDB address and database name are specified in Scrapy settings;
MongoDB collection is named after item class.
The main point of this example is to show how to use :meth:`from_crawler`
-method and how to clean up the resources properly.
-
-.. note::
-
- Previous example (JsonWriterPipeline) doesn't clean up resources properly.
- Fixing it is left as an exercise for the reader.
-
-::
+method and how to clean up the resources properly.::
import pymongo
diff --git a/docs/topics/request-response.rst b/docs/topics/request-response.rst
index 75b98d3b3..a45ea6939 100644
--- a/docs/topics/request-response.rst
+++ b/docs/topics/request-response.rst
@@ -507,7 +507,13 @@ Response objects
.. attribute:: Response.headers
- A dictionary-like object which contains the response headers.
+ A dictionary-like object which contains the response headers. Values can
+ be accessed using :meth:`get` to return the first header value with the
+ specified name or :meth:`getlist` to return all header values with the
+ specified name. For example, this call will give you all cookies in the
+ headers::
+
+ response.headers.getlist('Set-Cookie')
.. attribute:: Response.body
diff --git a/docs/topics/spider-middleware.rst b/docs/topics/spider-middleware.rst
index a38c1ab65..604f1864f 100644
--- a/docs/topics/spider-middleware.rst
+++ b/docs/topics/spider-middleware.rst
@@ -28,7 +28,12 @@ The :setting:`SPIDER_MIDDLEWARES` setting is merged with the
:setting:`SPIDER_MIDDLEWARES_BASE` setting defined in Scrapy (and not meant to
be overridden) and then sorted by order to get the final sorted list of enabled
middlewares: the first middleware is the one closer to the engine and the last
-is the one closer to the spider.
+is the one closer to the spider. In other words,
+the :meth:`~scrapy.spidermiddlewares.SpiderMiddleware.process_spider_input`
+method of each middleware will be invoked in increasing
+middleware order (100, 200, 300, ...), and the
+:meth:`~scrapy.spidermiddlewares.SpiderMiddleware.process_spider_output` method
+of each middleware will be invoked in decreasing order.
To decide which order to assign to your middleware see the
:setting:`SPIDER_MIDDLEWARES_BASE` setting and pick a value according to where
diff --git a/docs/topics/spiders.rst b/docs/topics/spiders.rst
index 0e473709a..af676fccd 100644
--- a/docs/topics/spiders.rst
+++ b/docs/topics/spiders.rst
@@ -72,6 +72,8 @@ scrapy.Spider
spider that crawls ``mywebsite.com`` would often be called
``mywebsite``.
+ .. note:: In Python 2 this must be ASCII only.
+
.. attribute:: allowed_domains
An optional list of strings containing domains that this spider is
diff --git a/scrapy/downloadermiddlewares/redirect.py b/scrapy/downloadermiddlewares/redirect.py
index 4ed7e4c24..db276eefb 100644
--- a/scrapy/downloadermiddlewares/redirect.py
+++ b/scrapy/downloadermiddlewares/redirect.py
@@ -1,9 +1,10 @@
import logging
from six.moves.urllib.parse import urljoin
+from w3lib.url import safe_url_string
+
from scrapy.http import HtmlResponse
from scrapy.utils.response import get_meta_refresh
-from scrapy.utils.python import to_native_str
from scrapy.exceptions import IgnoreRequest, NotConfigured
logger = logging.getLogger(__name__)
@@ -65,8 +66,7 @@ class RedirectMiddleware(BaseRedirectMiddleware):
if 'Location' not in response.headers or response.status not in allowed_status:
return response
- # HTTP header is ascii or latin1, redirected url will be percent-encoded utf-8
- location = to_native_str(response.headers['location'].decode('latin1'))
+ location = safe_url_string(response.headers['location'])
redirected_url = urljoin(request.url, location)
|
scrapy/scrapy
|
7e20725eb78cb34db60944cd1f155522fcf3b9f5
|
diff --git a/tests/test_downloadermiddleware_redirect.py b/tests/test_downloadermiddleware_redirect.py
index 9db073cc5..e8c92affa 100644
--- a/tests/test_downloadermiddleware_redirect.py
+++ b/tests/test_downloadermiddleware_redirect.py
@@ -157,15 +157,15 @@ class RedirectMiddlewareTest(unittest.TestCase):
latin1_location = u'/ação'.encode('latin1') # HTTP historically supports latin1
resp = Response('http://scrapytest.org/first', headers={'Location': latin1_location}, status=302)
req_result = self.mw.process_response(req, resp, self.spider)
- perc_encoded_utf8_url = 'http://scrapytest.org/a%C3%A7%C3%A3o'
+ perc_encoded_utf8_url = 'http://scrapytest.org/a%E7%E3o'
self.assertEquals(perc_encoded_utf8_url, req_result.url)
- def test_location_with_wrong_encoding(self):
+ def test_utf8_location(self):
req = Request('http://scrapytest.org/first')
- utf8_location = u'/ação' # header with wrong encoding (utf-8)
+ utf8_location = u'/ação'.encode('utf-8') # header using UTF-8 encoding
resp = Response('http://scrapytest.org/first', headers={'Location': utf8_location}, status=302)
req_result = self.mw.process_response(req, resp, self.spider)
- perc_encoded_utf8_url = 'http://scrapytest.org/a%C3%83%C2%A7%C3%83%C2%A3o'
+ perc_encoded_utf8_url = 'http://scrapytest.org/a%C3%A7%C3%A3o'
self.assertEquals(perc_encoded_utf8_url, req_result.url)
|
Document headers methods such as getlist()
It appears that current documentation does not mention how you can get values from HTTP `Headers` object.
Things like `response.headers.getlist('Set-Cookie')` to get all cookies are not explained (see https://github.com/scrapy/scrapy/issues/2319)
|
0.0
|
7e20725eb78cb34db60944cd1f155522fcf3b9f5
|
[
"tests/test_downloadermiddleware_redirect.py::RedirectMiddlewareTest::test_latin1_location",
"tests/test_downloadermiddleware_redirect.py::RedirectMiddlewareTest::test_utf8_location"
] |
[
"tests/test_downloadermiddleware_redirect.py::RedirectMiddlewareTest::test_dont_redirect",
"tests/test_downloadermiddleware_redirect.py::RedirectMiddlewareTest::test_max_redirect_times",
"tests/test_downloadermiddleware_redirect.py::RedirectMiddlewareTest::test_priority_adjust",
"tests/test_downloadermiddleware_redirect.py::RedirectMiddlewareTest::test_redirect_301",
"tests/test_downloadermiddleware_redirect.py::RedirectMiddlewareTest::test_redirect_302",
"tests/test_downloadermiddleware_redirect.py::RedirectMiddlewareTest::test_redirect_302_head",
"tests/test_downloadermiddleware_redirect.py::RedirectMiddlewareTest::test_redirect_urls",
"tests/test_downloadermiddleware_redirect.py::RedirectMiddlewareTest::test_request_meta_handling",
"tests/test_downloadermiddleware_redirect.py::RedirectMiddlewareTest::test_spider_handling",
"tests/test_downloadermiddleware_redirect.py::RedirectMiddlewareTest::test_ttl",
"tests/test_downloadermiddleware_redirect.py::MetaRefreshMiddlewareTest::test_max_redirect_times",
"tests/test_downloadermiddleware_redirect.py::MetaRefreshMiddlewareTest::test_meta_refresh",
"tests/test_downloadermiddleware_redirect.py::MetaRefreshMiddlewareTest::test_meta_refresh_trough_posted_request",
"tests/test_downloadermiddleware_redirect.py::MetaRefreshMiddlewareTest::test_meta_refresh_with_high_interval",
"tests/test_downloadermiddleware_redirect.py::MetaRefreshMiddlewareTest::test_priority_adjust",
"tests/test_downloadermiddleware_redirect.py::MetaRefreshMiddlewareTest::test_redirect_urls",
"tests/test_downloadermiddleware_redirect.py::MetaRefreshMiddlewareTest::test_ttl"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2016-10-17 20:14:04+00:00
|
bsd-3-clause
| 5,409 |
|
scrapy__scrapy-2410
|
diff --git a/docs/topics/commands.rst b/docs/topics/commands.rst
index 32669104c..6636c30cb 100644
--- a/docs/topics/commands.rst
+++ b/docs/topics/commands.rst
@@ -322,6 +322,14 @@ So this command can be used to "see" how your spider would fetch a certain page.
If used outside a project, no particular per-spider behaviour would be applied
and it will just use the default Scrapy downloader settings.
+Supported options:
+
+* ``--spider=SPIDER``: bypass spider autodetection and force use of specific spider
+
+* ``--headers``: print the response's HTTP headers instead of the response's body
+
+* ``--no-redirect``: do not follow HTTP 3xx redirects (default is to follow them)
+
Usage examples::
$ scrapy fetch --nolog http://www.example.com/some/page.html
@@ -368,11 +376,34 @@ given. Also supports UNIX-style local file paths, either relative with
``./`` or ``../`` prefixes or absolute file paths.
See :ref:`topics-shell` for more info.
+Supported options:
+
+* ``--spider=SPIDER``: bypass spider autodetection and force use of specific spider
+
+* ``-c code``: evaluate the code in the shell, print the result and exit
+
+* ``--no-redirect``: do not follow HTTP 3xx redirects (default is to follow them);
+ this only affects the URL you may pass as argument on the command line;
+ once you are inside the shell, ``fetch(url)`` will still follow HTTP redirects by default.
+
Usage example::
$ scrapy shell http://www.example.com/some/page.html
[ ... scrapy shell starts ... ]
+ $ scrapy shell --nolog http://www.example.com/ -c '(response.status, response.url)'
+ (200, 'http://www.example.com/')
+
+ # shell follows HTTP redirects by default
+ $ scrapy shell --nolog http://httpbin.org/redirect-to?url=http%3A%2F%2Fexample.com%2F -c '(response.status, response.url)'
+ (200, 'http://example.com/')
+
+ # you can disable this with --no-redirect
+ # (only for the URL passed as command line argument)
+ $ scrapy shell --no-redirect --nolog http://httpbin.org/redirect-to?url=http%3A%2F%2Fexample.com%2F -c '(response.status, response.url)'
+ (302, 'http://httpbin.org/redirect-to?url=http%3A%2F%2Fexample.com%2F')
+
+
.. command:: parse
parse
diff --git a/docs/topics/shell.rst b/docs/topics/shell.rst
index da91108b2..ef6aeeed3 100644
--- a/docs/topics/shell.rst
+++ b/docs/topics/shell.rst
@@ -97,8 +97,12 @@ Available Shortcuts
* ``shelp()`` - print a help with the list of available objects and shortcuts
- * ``fetch(request_or_url)`` - fetch a new response from the given request or
- URL and update all related objects accordingly.
+ * ``fetch(url[, redirect=True])`` - fetch a new response from the given
+ URL and update all related objects accordingly. You can optionaly ask for
+ HTTP 3xx redirections to not be followed by passing ``redirect=False``
+
+ * ``fetch(request)`` - fetch a new response from the given request and
+ update all related objects accordingly.
* ``view(response)`` - open the given response in your local web browser, for
inspection. This will add a `\<base\> tag`_ to the response body in order
@@ -157,36 +161,28 @@ list of available objects and useful shortcuts (you'll notice that these lines
all start with the ``[s]`` prefix)::
[s] Available Scrapy objects:
- [s] crawler <scrapy.crawler.Crawler object at 0x1e16b50>
+ [s] scrapy scrapy module (contains scrapy.Request, scrapy.Selector, etc)
+ [s] crawler <scrapy.crawler.Crawler object at 0x7f07395dd690>
[s] item {}
[s] request <GET http://scrapy.org>
- [s] response <200 http://scrapy.org>
- [s] settings <scrapy.settings.Settings object at 0x2bfd650>
- [s] spider <Spider 'default' at 0x20c6f50>
+ [s] response <200 https://scrapy.org/>
+ [s] settings <scrapy.settings.Settings object at 0x7f07395dd710>
+ [s] spider <DefaultSpider 'default' at 0x7f0735891690>
[s] Useful shortcuts:
+ [s] fetch(url[, redirect=True]) Fetch URL and update local objects (by default, redirects are followed)
+ [s] fetch(req) Fetch a scrapy.Request and update local objects
[s] shelp() Shell help (print this help)
- [s] fetch(req_or_url) Fetch request (or URL) and update local objects
[s] view(response) View response in a browser
>>>
+
After that, we can start playing with the objects::
>>> response.xpath('//title/text()').extract_first()
'Scrapy | A Fast and Powerful Scraping and Web Crawling Framework'
>>> fetch("http://reddit.com")
- [s] Available Scrapy objects:
- [s] crawler <scrapy.crawler.Crawler object at 0x7fb3ed9c9c90>
- [s] item {}
- [s] request <GET http://reddit.com>
- [s] response <200 https://www.reddit.com/>
- [s] settings <scrapy.settings.Settings object at 0x7fb3ed9c9c10>
- [s] spider <DefaultSpider 'default' at 0x7fb3ecdd3390>
- [s] Useful shortcuts:
- [s] shelp() Shell help (print this help)
- [s] fetch(req_or_url) Fetch request (or URL) and update local objects
- [s] view(response) View response in a browser
>>> response.xpath('//title/text()').extract()
['reddit: the front page of the internet']
@@ -194,12 +190,36 @@ After that, we can start playing with the objects::
>>> request = request.replace(method="POST")
>>> fetch(request)
- [s] Available Scrapy objects:
- [s] crawler <scrapy.crawler.Crawler object at 0x1e16b50>
- ...
+ >>> response.status
+ 404
+
+ >>> from pprint import pprint
+
+ >>> pprint(response.headers)
+ {'Accept-Ranges': ['bytes'],
+ 'Cache-Control': ['max-age=0, must-revalidate'],
+ 'Content-Type': ['text/html; charset=UTF-8'],
+ 'Date': ['Thu, 08 Dec 2016 16:21:19 GMT'],
+ 'Server': ['snooserv'],
+ 'Set-Cookie': ['loid=KqNLou0V9SKMX4qb4n; Domain=reddit.com; Max-Age=63071999; Path=/; expires=Sat, 08-Dec-2018 16:21:19 GMT; secure',
+ 'loidcreated=2016-12-08T16%3A21%3A19.445Z; Domain=reddit.com; Max-Age=63071999; Path=/; expires=Sat, 08-Dec-2018 16:21:19 GMT; secure',
+ 'loid=vi0ZVe4NkxNWdlH7r7; Domain=reddit.com; Max-Age=63071999; Path=/; expires=Sat, 08-Dec-2018 16:21:19 GMT; secure',
+ 'loidcreated=2016-12-08T16%3A21%3A19.459Z; Domain=reddit.com; Max-Age=63071999; Path=/; expires=Sat, 08-Dec-2018 16:21:19 GMT; secure'],
+ 'Vary': ['accept-encoding'],
+ 'Via': ['1.1 varnish'],
+ 'X-Cache': ['MISS'],
+ 'X-Cache-Hits': ['0'],
+ 'X-Content-Type-Options': ['nosniff'],
+ 'X-Frame-Options': ['SAMEORIGIN'],
+ 'X-Moose': ['majestic'],
+ 'X-Served-By': ['cache-cdg8730-CDG'],
+ 'X-Timer': ['S1481214079.394283,VS0,VE159'],
+ 'X-Ua-Compatible': ['IE=edge'],
+ 'X-Xss-Protection': ['1; mode=block']}
>>>
+
.. _topics-shell-inspect-response:
Invoking the shell from spiders to inspect responses
diff --git a/scrapy/commands/fetch.py b/scrapy/commands/fetch.py
index f09a873c1..7d4840529 100644
--- a/scrapy/commands/fetch.py
+++ b/scrapy/commands/fetch.py
@@ -5,6 +5,7 @@ from w3lib.url import is_url
from scrapy.commands import ScrapyCommand
from scrapy.http import Request
from scrapy.exceptions import UsageError
+from scrapy.utils.datatypes import SequenceExclude
from scrapy.utils.spider import spidercls_for_request, DefaultSpider
class Command(ScrapyCommand):
@@ -27,6 +28,8 @@ class Command(ScrapyCommand):
help="use this spider")
parser.add_option("--headers", dest="headers", action="store_true", \
help="print response HTTP headers instead of body")
+ parser.add_option("--no-redirect", dest="no_redirect", action="store_true", \
+ default=False, help="do not handle HTTP 3xx status codes and print response as-is")
def _print_headers(self, headers, prefix):
for key, values in headers.items():
@@ -50,7 +53,12 @@ class Command(ScrapyCommand):
raise UsageError()
cb = lambda x: self._print_response(x, opts)
request = Request(args[0], callback=cb, dont_filter=True)
- request.meta['handle_httpstatus_all'] = True
+ # by default, let the framework handle redirects,
+ # i.e. command handles all codes expect 3xx
+ if not opts.no_redirect:
+ request.meta['handle_httpstatus_list'] = SequenceExclude(range(300, 400))
+ else:
+ request.meta['handle_httpstatus_all'] = True
spidercls = DefaultSpider
spider_loader = self.crawler_process.spider_loader
diff --git a/scrapy/commands/shell.py b/scrapy/commands/shell.py
index 7be7f7256..40a58d94a 100644
--- a/scrapy/commands/shell.py
+++ b/scrapy/commands/shell.py
@@ -36,6 +36,8 @@ class Command(ScrapyCommand):
help="evaluate the code in the shell, print the result and exit")
parser.add_option("--spider", dest="spider",
help="use this spider")
+ parser.add_option("--no-redirect", dest="no_redirect", action="store_true", \
+ default=False, help="do not handle HTTP 3xx status codes and print response as-is")
def update_vars(self, vars):
"""You can use this function to update the Scrapy objects that will be
@@ -68,7 +70,7 @@ class Command(ScrapyCommand):
self._start_crawler_thread()
shell = Shell(crawler, update_vars=self.update_vars, code=opts.code)
- shell.start(url=url)
+ shell.start(url=url, redirect=not opts.no_redirect)
def _start_crawler_thread(self):
t = Thread(target=self.crawler_process.start,
diff --git a/scrapy/shell.py b/scrapy/shell.py
index 183ee1f70..6f94635a1 100644
--- a/scrapy/shell.py
+++ b/scrapy/shell.py
@@ -20,6 +20,7 @@ from scrapy.item import BaseItem
from scrapy.settings import Settings
from scrapy.spiders import Spider
from scrapy.utils.console import start_python_console
+from scrapy.utils.datatypes import SequenceExclude
from scrapy.utils.misc import load_object
from scrapy.utils.response import open_in_browser
from scrapy.utils.conf import get_config
@@ -40,11 +41,11 @@ class Shell(object):
self.code = code
self.vars = {}
- def start(self, url=None, request=None, response=None, spider=None):
+ def start(self, url=None, request=None, response=None, spider=None, redirect=True):
# disable accidental Ctrl-C key press from shutting down the engine
signal.signal(signal.SIGINT, signal.SIG_IGN)
if url:
- self.fetch(url, spider)
+ self.fetch(url, spider, redirect=redirect)
elif request:
self.fetch(request, spider)
elif response:
@@ -98,14 +99,16 @@ class Shell(object):
self.spider = spider
return spider
- def fetch(self, request_or_url, spider=None):
+ def fetch(self, request_or_url, spider=None, redirect=True, **kwargs):
if isinstance(request_or_url, Request):
request = request_or_url
- url = request.url
else:
url = any_to_uri(request_or_url)
- request = Request(url, dont_filter=True)
- request.meta['handle_httpstatus_all'] = True
+ request = Request(url, dont_filter=True, **kwargs)
+ if redirect:
+ request.meta['handle_httpstatus_list'] = SequenceExclude(range(300, 400))
+ else:
+ request.meta['handle_httpstatus_all'] = True
response = None
try:
response, spider = threads.blockingCallFromThread(
@@ -144,10 +147,13 @@ class Shell(object):
if self._is_relevant(v):
b.append(" %-10s %s" % (k, v))
b.append("Useful shortcuts:")
- b.append(" shelp() Shell help (print this help)")
if self.inthread:
- b.append(" fetch(req_or_url) Fetch request (or URL) and "
- "update local objects")
+ b.append(" fetch(url[, redirect=True]) "
+ "Fetch URL and update local objects "
+ "(by default, redirects are followed)")
+ b.append(" fetch(req) "
+ "Fetch a scrapy.Request and update local objects ")
+ b.append(" shelp() Shell help (print this help)")
b.append(" view(response) View response in a browser")
return "\n".join("[s] %s" % l for l in b)
diff --git a/scrapy/utils/datatypes.py b/scrapy/utils/datatypes.py
index d04b43176..e516185bd 100644
--- a/scrapy/utils/datatypes.py
+++ b/scrapy/utils/datatypes.py
@@ -304,3 +304,13 @@ class LocalCache(OrderedDict):
while len(self) >= self.limit:
self.popitem(last=False)
super(LocalCache, self).__setitem__(key, value)
+
+
+class SequenceExclude(object):
+ """Object to test if an item is NOT within some sequence."""
+
+ def __init__(self, seq):
+ self.seq = seq
+
+ def __contains__(self, item):
+ return item not in self.seq
|
scrapy/scrapy
|
d19c4c1f809aae47f12637ea6f465127f728451c
|
diff --git a/scrapy/utils/testsite.py b/scrapy/utils/testsite.py
index ad0375443..e50a989b3 100644
--- a/scrapy/utils/testsite.py
+++ b/scrapy/utils/testsite.py
@@ -20,12 +20,20 @@ class SiteTest(object):
return urljoin(self.baseurl, path)
+class NoMetaRefreshRedirect(util.Redirect):
+ def render(self, request):
+ content = util.Redirect.render(self, request)
+ return content.replace(b'http-equiv=\"refresh\"',
+ b'http-no-equiv=\"do-not-refresh-me\"')
+
+
def test_site():
r = resource.Resource()
r.putChild(b"text", static.Data(b"Works", "text/plain"))
r.putChild(b"html", static.Data(b"<body><p class='one'>Works</p><p class='two'>World</p></body>", "text/html"))
r.putChild(b"enc-gb18030", static.Data(b"<p>gb18030 encoding</p>", "text/html; charset=gb18030"))
r.putChild(b"redirect", util.Redirect(b"/redirected"))
+ r.putChild(b"redirect-no-meta-refresh", NoMetaRefreshRedirect(b"/redirected"))
r.putChild(b"redirected", static.Data(b"Redirected here", "text/plain"))
return server.Site(r)
diff --git a/tests/test_command_fetch.py b/tests/test_command_fetch.py
index 4843a9a2f..3fa3ed930 100644
--- a/tests/test_command_fetch.py
+++ b/tests/test_command_fetch.py
@@ -14,6 +14,18 @@ class FetchTest(ProcessTest, SiteTest, unittest.TestCase):
_, out, _ = yield self.execute([self.url('/text')])
self.assertEqual(out.strip(), b'Works')
+ @defer.inlineCallbacks
+ def test_redirect_default(self):
+ _, out, _ = yield self.execute([self.url('/redirect')])
+ self.assertEqual(out.strip(), b'Redirected here')
+
+ @defer.inlineCallbacks
+ def test_redirect_disabled(self):
+ _, out, err = yield self.execute(['--no-redirect', self.url('/redirect-no-meta-refresh')])
+ err = err.strip()
+ self.assertIn(b'downloader/response_status_count/302', err, err)
+ self.assertNotIn(b'downloader/response_status_count/200', err, err)
+
@defer.inlineCallbacks
def test_headers(self):
_, out, _ = yield self.execute([self.url('/text'), '--headers'])
diff --git a/tests/test_command_shell.py b/tests/test_command_shell.py
index 7bb7439d6..3e27d6abd 100644
--- a/tests/test_command_shell.py
+++ b/tests/test_command_shell.py
@@ -49,6 +49,35 @@ class ShellTest(ProcessTest, SiteTest, unittest.TestCase):
_, out, _ = yield self.execute([self.url('/redirect'), '-c', 'response.url'])
assert out.strip().endswith(b'/redirected')
+ @defer.inlineCallbacks
+ def test_redirect_follow_302(self):
+ _, out, _ = yield self.execute([self.url('/redirect-no-meta-refresh'), '-c', 'response.status'])
+ assert out.strip().endswith(b'200')
+
+ @defer.inlineCallbacks
+ def test_redirect_not_follow_302(self):
+ _, out, _ = yield self.execute(['--no-redirect', self.url('/redirect-no-meta-refresh'), '-c', 'response.status'])
+ assert out.strip().endswith(b'302')
+
+ @defer.inlineCallbacks
+ def test_fetch_redirect_follow_302(self):
+ """Test that calling `fetch(url)` follows HTTP redirects by default."""
+ url = self.url('/redirect-no-meta-refresh')
+ code = "fetch('{0}')"
+ errcode, out, errout = yield self.execute(['-c', code.format(url)])
+ self.assertEqual(errcode, 0, out)
+ assert b'Redirecting (302)' in errout
+ assert b'Crawled (200)' in errout
+
+ @defer.inlineCallbacks
+ def test_fetch_redirect_not_follow_302(self):
+ """Test that calling `fetch(url, redirect=False)` disables automatic redirects."""
+ url = self.url('/redirect-no-meta-refresh')
+ code = "fetch('{0}', redirect=False)"
+ errcode, out, errout = yield self.execute(['-c', code.format(url)])
+ self.assertEqual(errcode, 0, out)
+ assert b'Crawled (302)' in errout
+
@defer.inlineCallbacks
def test_request_replace(self):
url = self.url('/text')
diff --git a/tests/test_utils_datatypes.py b/tests/test_utils_datatypes.py
index b31d2179c..80f797227 100644
--- a/tests/test_utils_datatypes.py
+++ b/tests/test_utils_datatypes.py
@@ -1,7 +1,7 @@
import copy
import unittest
-from scrapy.utils.datatypes import CaselessDict
+from scrapy.utils.datatypes import CaselessDict, SequenceExclude
__doctests__ = ['scrapy.utils.datatypes']
@@ -128,6 +128,67 @@ class CaselessDictTest(unittest.TestCase):
assert isinstance(h2, CaselessDict)
+class SequenceExcludeTest(unittest.TestCase):
+
+ def test_list(self):
+ seq = [1, 2, 3]
+ d = SequenceExclude(seq)
+ self.assertIn(0, d)
+ self.assertIn(4, d)
+ self.assertNotIn(2, d)
+
+ def test_range(self):
+ seq = range(10, 20)
+ d = SequenceExclude(seq)
+ self.assertIn(5, d)
+ self.assertIn(20, d)
+ self.assertNotIn(15, d)
+
+ def test_six_range(self):
+ import six.moves
+ seq = six.moves.range(10**3, 10**6)
+ d = SequenceExclude(seq)
+ self.assertIn(10**2, d)
+ self.assertIn(10**7, d)
+ self.assertNotIn(10**4, d)
+
+ def test_range_step(self):
+ seq = range(10, 20, 3)
+ d = SequenceExclude(seq)
+ are_not_in = [v for v in range(10, 20, 3) if v in d]
+ self.assertEquals([], are_not_in)
+
+ are_not_in = [v for v in range(10, 20) if v in d]
+ self.assertEquals([11, 12, 14, 15, 17, 18], are_not_in)
+
+ def test_string_seq(self):
+ seq = "cde"
+ d = SequenceExclude(seq)
+ chars = "".join(v for v in "abcdefg" if v in d)
+ self.assertEquals("abfg", chars)
+
+ def test_stringset_seq(self):
+ seq = set("cde")
+ d = SequenceExclude(seq)
+ chars = "".join(v for v in "abcdefg" if v in d)
+ self.assertEquals("abfg", chars)
+
+ def test_set(self):
+ """Anything that is not in the supplied sequence will evaluate as 'in' the container."""
+ seq = set([-3, "test", 1.1])
+ d = SequenceExclude(seq)
+ self.assertIn(0, d)
+ self.assertIn("foo", d)
+ self.assertIn(3.14, d)
+ self.assertIn(set("bar"), d)
+
+ # supplied sequence is a set, so checking for list (non)inclusion fails
+ self.assertRaises(TypeError, (0, 1, 2) in d)
+ self.assertRaises(TypeError, d.__contains__, ['a', 'b', 'c'])
+
+ for v in [-3, "test", 1.1]:
+ self.assertNotIn(v, d)
+
if __name__ == "__main__":
unittest.main()
|
Scrapy should follow redirects on scrapy shell by default
Scrapy shell doesn't follow redirects when you do `fetch('http://google.com')`, but it does if you do ` `fetch(scrapy.Request('http://google.com'))`.
I realize this is a historic behavior, but I'd argue that it breaks the expectations for most users, since the most common expectation is that Scrapy would try to do what a browser would do, so I think we should change it.
In my opinion, not following the redirect should be the exceptional behavior, and so that's what should require the user to build a `scrapy.Request` object.
I think ideally, we would be able to pass a keyword argument to `fetch`, like:
```
fetch('http://google.com', redirect=False)
```
And only for that case it would set handle_httpstatus_all to True as explained by @redapple here: https://github.com/scrapy/scrapy/issues/2177#issuecomment-239430163
|
0.0
|
d19c4c1f809aae47f12637ea6f465127f728451c
|
[
"scrapy/utils/testsite.py::test_site",
"tests/test_utils_datatypes.py::CaselessDictTest::test_caseless",
"tests/test_utils_datatypes.py::CaselessDictTest::test_contains",
"tests/test_utils_datatypes.py::CaselessDictTest::test_copy",
"tests/test_utils_datatypes.py::CaselessDictTest::test_delete",
"tests/test_utils_datatypes.py::CaselessDictTest::test_fromkeys",
"tests/test_utils_datatypes.py::CaselessDictTest::test_getdefault",
"tests/test_utils_datatypes.py::CaselessDictTest::test_init",
"tests/test_utils_datatypes.py::CaselessDictTest::test_normkey",
"tests/test_utils_datatypes.py::CaselessDictTest::test_normvalue",
"tests/test_utils_datatypes.py::CaselessDictTest::test_pop",
"tests/test_utils_datatypes.py::CaselessDictTest::test_setdefault",
"tests/test_utils_datatypes.py::SequenceExcludeTest::test_list",
"tests/test_utils_datatypes.py::SequenceExcludeTest::test_range",
"tests/test_utils_datatypes.py::SequenceExcludeTest::test_range_step",
"tests/test_utils_datatypes.py::SequenceExcludeTest::test_set",
"tests/test_utils_datatypes.py::SequenceExcludeTest::test_six_range",
"tests/test_utils_datatypes.py::SequenceExcludeTest::test_string_seq",
"tests/test_utils_datatypes.py::SequenceExcludeTest::test_stringset_seq"
] |
[] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2016-11-24 12:47:53+00:00
|
bsd-3-clause
| 5,410 |
|
scrapy__scrapy-2530
|
diff --git a/docs/topics/downloader-middleware.rst b/docs/topics/downloader-middleware.rst
index 1ca78ccc6..0ef3fb071 100644
--- a/docs/topics/downloader-middleware.rst
+++ b/docs/topics/downloader-middleware.rst
@@ -681,7 +681,9 @@ HttpProxyMiddleware
* ``no_proxy``
You can also set the meta key ``proxy`` per-request, to a value like
- ``http://some_proxy_server:port``.
+ ``http://some_proxy_server:port`` or ``http://username:password@some_proxy_server:port``.
+ Keep in mind this value will take precedence over ``http_proxy``/``https_proxy``
+ environment variables, and it will also ignore ``no_proxy`` environment variable.
.. _urllib: https://docs.python.org/2/library/urllib.html
.. _urllib2: https://docs.python.org/2/library/urllib2.html
@@ -949,8 +951,16 @@ enable it for :ref:`broad crawls <topics-broad-crawls>`.
HttpProxyMiddleware settings
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+.. setting:: HTTPPROXY_ENABLED
.. setting:: HTTPPROXY_AUTH_ENCODING
+HTTPPROXY_ENABLED
+^^^^^^^^^^^^^^^^^
+
+Default: ``True``
+
+Whether or not to enable the :class:`HttpProxyMiddleware`.
+
HTTPPROXY_AUTH_ENCODING
^^^^^^^^^^^^^^^^^^^^^^^
diff --git a/scrapy/downloadermiddlewares/httpproxy.py b/scrapy/downloadermiddlewares/httpproxy.py
index 98c87aa9c..0d5320bf8 100644
--- a/scrapy/downloadermiddlewares/httpproxy.py
+++ b/scrapy/downloadermiddlewares/httpproxy.py
@@ -20,23 +20,25 @@ class HttpProxyMiddleware(object):
for type, url in getproxies().items():
self.proxies[type] = self._get_proxy(url, type)
- if not self.proxies:
- raise NotConfigured
-
@classmethod
def from_crawler(cls, crawler):
+ if not crawler.settings.getbool('HTTPPROXY_ENABLED'):
+ raise NotConfigured
auth_encoding = crawler.settings.get('HTTPPROXY_AUTH_ENCODING')
return cls(auth_encoding)
+ def _basic_auth_header(self, username, password):
+ user_pass = to_bytes(
+ '%s:%s' % (unquote(username), unquote(password)),
+ encoding=self.auth_encoding)
+ return base64.b64encode(user_pass).strip()
+
def _get_proxy(self, url, orig_type):
proxy_type, user, password, hostport = _parse_proxy(url)
proxy_url = urlunparse((proxy_type or orig_type, hostport, '', '', '', ''))
if user:
- user_pass = to_bytes(
- '%s:%s' % (unquote(user), unquote(password)),
- encoding=self.auth_encoding)
- creds = base64.b64encode(user_pass).strip()
+ creds = self._basic_auth_header(user, password)
else:
creds = None
@@ -45,6 +47,15 @@ class HttpProxyMiddleware(object):
def process_request(self, request, spider):
# ignore if proxy is already set
if 'proxy' in request.meta:
+ if request.meta['proxy'] is None:
+ return
+ # extract credentials if present
+ creds, proxy_url = self._get_proxy(request.meta['proxy'], '')
+ request.meta['proxy'] = proxy_url
+ if creds and not request.headers.get('Proxy-Authorization'):
+ request.headers['Proxy-Authorization'] = b'Basic ' + creds
+ return
+ elif not self.proxies:
return
parsed = urlparse_cached(request)
diff --git a/scrapy/settings/default_settings.py b/scrapy/settings/default_settings.py
index 24714a7a8..cb88bc2bf 100644
--- a/scrapy/settings/default_settings.py
+++ b/scrapy/settings/default_settings.py
@@ -174,6 +174,7 @@ HTTPCACHE_DBM_MODULE = 'anydbm' if six.PY2 else 'dbm'
HTTPCACHE_POLICY = 'scrapy.extensions.httpcache.DummyPolicy'
HTTPCACHE_GZIP = False
+HTTPPROXY_ENABLED = True
HTTPPROXY_AUTH_ENCODING = 'latin-1'
IMAGES_STORE_S3_ACL = 'private'
|
scrapy/scrapy
|
7dd7646e6563798d408b8062059e826f08256b39
|
diff --git a/tests/test_downloadermiddleware_httpproxy.py b/tests/test_downloadermiddleware_httpproxy.py
index 2b26431a4..c77179ceb 100644
--- a/tests/test_downloadermiddleware_httpproxy.py
+++ b/tests/test_downloadermiddleware_httpproxy.py
@@ -1,11 +1,14 @@
import os
import sys
+from functools import partial
from twisted.trial.unittest import TestCase, SkipTest
from scrapy.downloadermiddlewares.httpproxy import HttpProxyMiddleware
from scrapy.exceptions import NotConfigured
from scrapy.http import Response, Request
from scrapy.spiders import Spider
+from scrapy.crawler import Crawler
+from scrapy.settings import Settings
spider = Spider('foo')
@@ -20,9 +23,10 @@ class TestDefaultHeadersMiddleware(TestCase):
def tearDown(self):
os.environ = self._oldenv
- def test_no_proxies(self):
- os.environ = {}
- self.assertRaises(NotConfigured, HttpProxyMiddleware)
+ def test_not_enabled(self):
+ settings = Settings({'HTTPPROXY_ENABLED': False})
+ crawler = Crawler(spider, settings)
+ self.assertRaises(NotConfigured, partial(HttpProxyMiddleware.from_crawler, crawler))
def test_no_enviroment_proxies(self):
os.environ = {'dummy_proxy': 'reset_env_and_do_not_raise'}
@@ -47,6 +51,13 @@ class TestDefaultHeadersMiddleware(TestCase):
self.assertEquals(req.url, url)
self.assertEquals(req.meta.get('proxy'), proxy)
+ def test_proxy_precedence_meta(self):
+ os.environ['http_proxy'] = 'https://proxy.com'
+ mw = HttpProxyMiddleware()
+ req = Request('http://scrapytest.org', meta={'proxy': 'https://new.proxy:3128'})
+ assert mw.process_request(req, spider) is None
+ self.assertEquals(req.meta, {'proxy': 'https://new.proxy:3128'})
+
def test_proxy_auth(self):
os.environ['http_proxy'] = 'https://user:pass@proxy:3128'
mw = HttpProxyMiddleware()
@@ -54,6 +65,11 @@ class TestDefaultHeadersMiddleware(TestCase):
assert mw.process_request(req, spider) is None
self.assertEquals(req.meta, {'proxy': 'https://proxy:3128'})
self.assertEquals(req.headers.get('Proxy-Authorization'), b'Basic dXNlcjpwYXNz')
+ # proxy from request.meta
+ req = Request('http://scrapytest.org', meta={'proxy': 'https://username:password@proxy:3128'})
+ assert mw.process_request(req, spider) is None
+ self.assertEquals(req.meta, {'proxy': 'https://proxy:3128'})
+ self.assertEquals(req.headers.get('Proxy-Authorization'), b'Basic dXNlcm5hbWU6cGFzc3dvcmQ=')
def test_proxy_auth_empty_passwd(self):
os.environ['http_proxy'] = 'https://user:@proxy:3128'
@@ -62,6 +78,11 @@ class TestDefaultHeadersMiddleware(TestCase):
assert mw.process_request(req, spider) is None
self.assertEquals(req.meta, {'proxy': 'https://proxy:3128'})
self.assertEquals(req.headers.get('Proxy-Authorization'), b'Basic dXNlcjo=')
+ # proxy from request.meta
+ req = Request('http://scrapytest.org', meta={'proxy': 'https://username:@proxy:3128'})
+ assert mw.process_request(req, spider) is None
+ self.assertEquals(req.meta, {'proxy': 'https://proxy:3128'})
+ self.assertEquals(req.headers.get('Proxy-Authorization'), b'Basic dXNlcm5hbWU6')
def test_proxy_auth_encoding(self):
# utf-8 encoding
@@ -72,6 +93,12 @@ class TestDefaultHeadersMiddleware(TestCase):
self.assertEquals(req.meta, {'proxy': 'https://proxy:3128'})
self.assertEquals(req.headers.get('Proxy-Authorization'), b'Basic bcOhbjpwYXNz')
+ # proxy from request.meta
+ req = Request('http://scrapytest.org', meta={'proxy': u'https://\u00FCser:pass@proxy:3128'})
+ assert mw.process_request(req, spider) is None
+ self.assertEquals(req.meta, {'proxy': 'https://proxy:3128'})
+ self.assertEquals(req.headers.get('Proxy-Authorization'), b'Basic w7xzZXI6cGFzcw==')
+
# default latin-1 encoding
mw = HttpProxyMiddleware(auth_encoding='latin-1')
req = Request('http://scrapytest.org')
@@ -79,15 +106,21 @@ class TestDefaultHeadersMiddleware(TestCase):
self.assertEquals(req.meta, {'proxy': 'https://proxy:3128'})
self.assertEquals(req.headers.get('Proxy-Authorization'), b'Basic beFuOnBhc3M=')
+ # proxy from request.meta, latin-1 encoding
+ req = Request('http://scrapytest.org', meta={'proxy': u'https://\u00FCser:pass@proxy:3128'})
+ assert mw.process_request(req, spider) is None
+ self.assertEquals(req.meta, {'proxy': 'https://proxy:3128'})
+ self.assertEquals(req.headers.get('Proxy-Authorization'), b'Basic /HNlcjpwYXNz')
+
def test_proxy_already_seted(self):
- os.environ['http_proxy'] = http_proxy = 'https://proxy.for.http:3128'
+ os.environ['http_proxy'] = 'https://proxy.for.http:3128'
mw = HttpProxyMiddleware()
req = Request('http://noproxy.com', meta={'proxy': None})
assert mw.process_request(req, spider) is None
assert 'proxy' in req.meta and req.meta['proxy'] is None
def test_no_proxy(self):
- os.environ['http_proxy'] = http_proxy = 'https://proxy.for.http:3128'
+ os.environ['http_proxy'] = 'https://proxy.for.http:3128'
mw = HttpProxyMiddleware()
os.environ['no_proxy'] = '*'
@@ -104,3 +137,9 @@ class TestDefaultHeadersMiddleware(TestCase):
req = Request('http://noproxy.com')
assert mw.process_request(req, spider) is None
assert 'proxy' not in req.meta
+
+ # proxy from meta['proxy'] takes precedence
+ os.environ['no_proxy'] = '*'
+ req = Request('http://noproxy.com', meta={'proxy': 'http://proxy.com'})
+ assert mw.process_request(req, spider) is None
+ self.assertEquals(req.meta, {'proxy': 'http://proxy.com'})
|
Scrapy ignores proxy credentials when using "proxy" meta key
Code `yield Request(link, meta={'proxy': 'http://user:password@ip:port’})` ignores user:password.
Problem is solved by using header "Proxy-Authorization" with base64, but it is better to implement it inside Scrapy.
|
0.0
|
7dd7646e6563798d408b8062059e826f08256b39
|
[
"tests/test_downloadermiddleware_httpproxy.py::TestDefaultHeadersMiddleware::test_proxy_auth",
"tests/test_downloadermiddleware_httpproxy.py::TestDefaultHeadersMiddleware::test_proxy_auth_empty_passwd",
"tests/test_downloadermiddleware_httpproxy.py::TestDefaultHeadersMiddleware::test_proxy_auth_encoding"
] |
[
"tests/test_downloadermiddleware_httpproxy.py::TestDefaultHeadersMiddleware::test_enviroment_proxies",
"tests/test_downloadermiddleware_httpproxy.py::TestDefaultHeadersMiddleware::test_no_enviroment_proxies",
"tests/test_downloadermiddleware_httpproxy.py::TestDefaultHeadersMiddleware::test_no_proxy",
"tests/test_downloadermiddleware_httpproxy.py::TestDefaultHeadersMiddleware::test_not_enabled",
"tests/test_downloadermiddleware_httpproxy.py::TestDefaultHeadersMiddleware::test_proxy_already_seted",
"tests/test_downloadermiddleware_httpproxy.py::TestDefaultHeadersMiddleware::test_proxy_precedence_meta"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2017-02-03 13:40:44+00:00
|
bsd-3-clause
| 5,411 |
|
scrapy__scrapy-2627
|
diff --git a/scrapy/spidermiddlewares/referer.py b/scrapy/spidermiddlewares/referer.py
index b444e34bb..1ddfb37f4 100644
--- a/scrapy/spidermiddlewares/referer.py
+++ b/scrapy/spidermiddlewares/referer.py
@@ -261,6 +261,9 @@ _policy_classes = {p.name: p for p in (
DefaultReferrerPolicy,
)}
+# Reference: https://www.w3.org/TR/referrer-policy/#referrer-policy-empty-string
+_policy_classes[''] = NoReferrerWhenDowngradePolicy
+
def _load_policy_class(policy, warning_only=False):
"""
@@ -317,8 +320,9 @@ class RefererMiddleware(object):
policy_name = request.meta.get('referrer_policy')
if policy_name is None:
if isinstance(resp_or_url, Response):
- policy_name = to_native_str(
- resp_or_url.headers.get('Referrer-Policy', '').decode('latin1'))
+ policy_header = resp_or_url.headers.get('Referrer-Policy')
+ if policy_header is not None:
+ policy_name = to_native_str(policy_header.decode('latin1'))
if policy_name is None:
return self.default_policy()
|
scrapy/scrapy
|
d7b26edf6b419e379a7a0a425093f02cac2fcf33
|
diff --git a/tests/test_spidermiddleware_referer.py b/tests/test_spidermiddleware_referer.py
index b1c815876..f27f31b74 100644
--- a/tests/test_spidermiddleware_referer.py
+++ b/tests/test_spidermiddleware_referer.py
@@ -526,6 +526,13 @@ class TestPolicyHeaderPredecence003(MixinNoReferrerWhenDowngrade, TestRefererMid
settings = {'REFERRER_POLICY': 'scrapy.spidermiddlewares.referer.OriginWhenCrossOriginPolicy'}
resp_headers = {'Referrer-Policy': POLICY_NO_REFERRER_WHEN_DOWNGRADE.title()}
+class TestPolicyHeaderPredecence004(MixinNoReferrerWhenDowngrade, TestRefererMiddleware):
+ """
+ The empty string means "no-referrer-when-downgrade"
+ """
+ settings = {'REFERRER_POLICY': 'scrapy.spidermiddlewares.referer.OriginWhenCrossOriginPolicy'}
+ resp_headers = {'Referrer-Policy': ''}
+
class TestReferrerOnRedirect(TestRefererMiddleware):
|
lots of warnings `RuntimeWarning: Could not load referrer policy ''` when running tests
Check `tox -e py36 -- tests/test_crawl.py -s` output. @redapple is it a testing issue, or a problem with the warning? I've first noticed it in https://travis-ci.org/scrapy/scrapy/jobs/208185821 output.
|
0.0
|
d7b26edf6b419e379a7a0a425093f02cac2fcf33
|
[
"tests/test_spidermiddleware_referer.py::TestPolicyHeaderPredecence004::test"
] |
[
"tests/test_spidermiddleware_referer.py::TestRefererMiddleware::test",
"tests/test_spidermiddleware_referer.py::TestRefererMiddlewareDefault::test",
"tests/test_spidermiddleware_referer.py::TestSettingsNoReferrer::test",
"tests/test_spidermiddleware_referer.py::TestSettingsNoReferrerWhenDowngrade::test",
"tests/test_spidermiddleware_referer.py::TestSettingsSameOrigin::test",
"tests/test_spidermiddleware_referer.py::TestSettingsOrigin::test",
"tests/test_spidermiddleware_referer.py::TestSettingsStrictOrigin::test",
"tests/test_spidermiddleware_referer.py::TestSettingsOriginWhenCrossOrigin::test",
"tests/test_spidermiddleware_referer.py::TestSettingsStrictOriginWhenCrossOrigin::test",
"tests/test_spidermiddleware_referer.py::TestSettingsUnsafeUrl::test",
"tests/test_spidermiddleware_referer.py::TestSettingsCustomPolicy::test",
"tests/test_spidermiddleware_referer.py::TestRequestMetaDefault::test",
"tests/test_spidermiddleware_referer.py::TestRequestMetaNoReferrer::test",
"tests/test_spidermiddleware_referer.py::TestRequestMetaNoReferrerWhenDowngrade::test",
"tests/test_spidermiddleware_referer.py::TestRequestMetaSameOrigin::test",
"tests/test_spidermiddleware_referer.py::TestRequestMetaOrigin::test",
"tests/test_spidermiddleware_referer.py::TestRequestMetaSrictOrigin::test",
"tests/test_spidermiddleware_referer.py::TestRequestMetaOriginWhenCrossOrigin::test",
"tests/test_spidermiddleware_referer.py::TestRequestMetaStrictOriginWhenCrossOrigin::test",
"tests/test_spidermiddleware_referer.py::TestRequestMetaUnsafeUrl::test",
"tests/test_spidermiddleware_referer.py::TestRequestMetaPredecence001::test",
"tests/test_spidermiddleware_referer.py::TestRequestMetaPredecence002::test",
"tests/test_spidermiddleware_referer.py::TestRequestMetaPredecence003::test",
"tests/test_spidermiddleware_referer.py::TestRequestMetaSettingFallback::test",
"tests/test_spidermiddleware_referer.py::TestSettingsPolicyByName::test_invalid_name",
"tests/test_spidermiddleware_referer.py::TestSettingsPolicyByName::test_valid_name",
"tests/test_spidermiddleware_referer.py::TestSettingsPolicyByName::test_valid_name_casevariants",
"tests/test_spidermiddleware_referer.py::TestPolicyHeaderPredecence001::test",
"tests/test_spidermiddleware_referer.py::TestPolicyHeaderPredecence002::test",
"tests/test_spidermiddleware_referer.py::TestPolicyHeaderPredecence003::test",
"tests/test_spidermiddleware_referer.py::TestReferrerOnRedirect::test",
"tests/test_spidermiddleware_referer.py::TestReferrerOnRedirectNoReferrer::test",
"tests/test_spidermiddleware_referer.py::TestReferrerOnRedirectSameOrigin::test",
"tests/test_spidermiddleware_referer.py::TestReferrerOnRedirectStrictOrigin::test",
"tests/test_spidermiddleware_referer.py::TestReferrerOnRedirectOriginWhenCrossOrigin::test",
"tests/test_spidermiddleware_referer.py::TestReferrerOnRedirectStrictOriginWhenCrossOrigin::test"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
}
|
2017-03-06 15:22:51+00:00
|
bsd-3-clause
| 5,412 |
|
scrapy__scrapy-2847
|
diff --git a/scrapy/downloadermiddlewares/redirect.py b/scrapy/downloadermiddlewares/redirect.py
index 26677e527..30cae3fee 100644
--- a/scrapy/downloadermiddlewares/redirect.py
+++ b/scrapy/downloadermiddlewares/redirect.py
@@ -64,7 +64,7 @@ class RedirectMiddleware(BaseRedirectMiddleware):
request.meta.get('handle_httpstatus_all', False)):
return response
- allowed_status = (301, 302, 303, 307)
+ allowed_status = (301, 302, 303, 307, 308)
if 'Location' not in response.headers or response.status not in allowed_status:
return response
@@ -72,7 +72,7 @@ class RedirectMiddleware(BaseRedirectMiddleware):
redirected_url = urljoin(request.url, location)
- if response.status in (301, 307) or request.method == 'HEAD':
+ if response.status in (301, 307, 308) or request.method == 'HEAD':
redirected = request.replace(url=redirected_url)
return self._redirect(redirected, request, spider, response.status)
|
scrapy/scrapy
|
17bbd71433d3cc3de78b1baf39c36751c1e6fef5
|
diff --git a/tests/test_downloadermiddleware_httpcache.py b/tests/test_downloadermiddleware_httpcache.py
index 12b69860a..22946b98c 100644
--- a/tests/test_downloadermiddleware_httpcache.py
+++ b/tests/test_downloadermiddleware_httpcache.py
@@ -322,6 +322,7 @@ class RFC2616PolicyTest(DefaultStorageTest):
(True, 203, {'Last-Modified': self.yesterday}),
(True, 300, {'Last-Modified': self.yesterday}),
(True, 301, {'Last-Modified': self.yesterday}),
+ (True, 308, {'Last-Modified': self.yesterday}),
(True, 401, {'Last-Modified': self.yesterday}),
(True, 404, {'Cache-Control': 'public, max-age=600'}),
(True, 302, {'Expires': self.tomorrow}),
diff --git a/tests/test_downloadermiddleware_redirect.py b/tests/test_downloadermiddleware_redirect.py
index e8c92affa..35e474418 100644
--- a/tests/test_downloadermiddleware_redirect.py
+++ b/tests/test_downloadermiddleware_redirect.py
@@ -22,12 +22,12 @@ class RedirectMiddlewareTest(unittest.TestCase):
req2 = self.mw.process_response(req, rsp, self.spider)
assert req2.priority > req.priority
- def test_redirect_301(self):
- def _test(method):
- url = 'http://www.example.com/301'
+ def test_redirect_3xx_permanent(self):
+ def _test(method, status=301):
+ url = 'http://www.example.com/{}'.format(status)
url2 = 'http://www.example.com/redirected'
req = Request(url, method=method)
- rsp = Response(url, headers={'Location': url2}, status=301)
+ rsp = Response(url, headers={'Location': url2}, status=status)
req2 = self.mw.process_response(req, rsp, self.spider)
assert isinstance(req2, Request)
@@ -42,6 +42,14 @@ class RedirectMiddlewareTest(unittest.TestCase):
_test('POST')
_test('HEAD')
+ _test('GET', status=307)
+ _test('POST', status=307)
+ _test('HEAD', status=307)
+
+ _test('GET', status=308)
+ _test('POST', status=308)
+ _test('HEAD', status=308)
+
def test_dont_redirect(self):
url = 'http://www.example.com/301'
url2 = 'http://www.example.com/redirected'
|
Redirect 308 missing
I did a check on the RedirectMiddleware and noticed that code 308 is missing. Is there a reason for that?
Some websites don't update their sitemap and have a long list of 308 from http to https.
(side note: is there a way to add "s" before a link is scraped?)
|
0.0
|
17bbd71433d3cc3de78b1baf39c36751c1e6fef5
|
[
"tests/test_downloadermiddleware_redirect.py::RedirectMiddlewareTest::test_redirect_3xx_permanent"
] |
[
"tests/test_downloadermiddleware_redirect.py::RedirectMiddlewareTest::test_dont_redirect",
"tests/test_downloadermiddleware_redirect.py::RedirectMiddlewareTest::test_latin1_location",
"tests/test_downloadermiddleware_redirect.py::RedirectMiddlewareTest::test_max_redirect_times",
"tests/test_downloadermiddleware_redirect.py::RedirectMiddlewareTest::test_priority_adjust",
"tests/test_downloadermiddleware_redirect.py::RedirectMiddlewareTest::test_redirect_302",
"tests/test_downloadermiddleware_redirect.py::RedirectMiddlewareTest::test_redirect_302_head",
"tests/test_downloadermiddleware_redirect.py::RedirectMiddlewareTest::test_redirect_urls",
"tests/test_downloadermiddleware_redirect.py::RedirectMiddlewareTest::test_request_meta_handling",
"tests/test_downloadermiddleware_redirect.py::RedirectMiddlewareTest::test_spider_handling",
"tests/test_downloadermiddleware_redirect.py::RedirectMiddlewareTest::test_ttl",
"tests/test_downloadermiddleware_redirect.py::RedirectMiddlewareTest::test_utf8_location",
"tests/test_downloadermiddleware_redirect.py::MetaRefreshMiddlewareTest::test_max_redirect_times",
"tests/test_downloadermiddleware_redirect.py::MetaRefreshMiddlewareTest::test_meta_refresh",
"tests/test_downloadermiddleware_redirect.py::MetaRefreshMiddlewareTest::test_meta_refresh_trough_posted_request",
"tests/test_downloadermiddleware_redirect.py::MetaRefreshMiddlewareTest::test_meta_refresh_with_high_interval",
"tests/test_downloadermiddleware_redirect.py::MetaRefreshMiddlewareTest::test_priority_adjust",
"tests/test_downloadermiddleware_redirect.py::MetaRefreshMiddlewareTest::test_redirect_urls",
"tests/test_downloadermiddleware_redirect.py::MetaRefreshMiddlewareTest::test_ttl"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2017-07-24 16:13:18+00:00
|
bsd-3-clause
| 5,413 |
|
scrapy__scrapy-2956
|
diff --git a/scrapy/core/scheduler.py b/scrapy/core/scheduler.py
index a54b4daf0..eb790a67e 100644
--- a/scrapy/core/scheduler.py
+++ b/scrapy/core/scheduler.py
@@ -4,7 +4,7 @@ import logging
from os.path import join, exists
from scrapy.utils.reqser import request_to_dict, request_from_dict
-from scrapy.utils.misc import load_object
+from scrapy.utils.misc import load_object, create_instance
from scrapy.utils.job import job_dir
logger = logging.getLogger(__name__)
@@ -26,7 +26,7 @@ class Scheduler(object):
def from_crawler(cls, crawler):
settings = crawler.settings
dupefilter_cls = load_object(settings['DUPEFILTER_CLASS'])
- dupefilter = dupefilter_cls.from_settings(settings)
+ dupefilter = create_instance(dupefilter_cls, settings, crawler)
pqclass = load_object(settings['SCHEDULER_PRIORITY_QUEUE'])
dqclass = load_object(settings['SCHEDULER_DISK_QUEUE'])
mqclass = load_object(settings['SCHEDULER_MEMORY_QUEUE'])
|
scrapy/scrapy
|
895df937a3a18683836ca9e228982e9ea5842aef
|
diff --git a/tests/test_dupefilters.py b/tests/test_dupefilters.py
index 2d1a4bfff..db69597a2 100644
--- a/tests/test_dupefilters.py
+++ b/tests/test_dupefilters.py
@@ -5,11 +5,60 @@ import shutil
from scrapy.dupefilters import RFPDupeFilter
from scrapy.http import Request
+from scrapy.core.scheduler import Scheduler
from scrapy.utils.python import to_bytes
+from scrapy.utils.job import job_dir
+from scrapy.utils.test import get_crawler
+
+
+class FromCrawlerRFPDupeFilter(RFPDupeFilter):
+
+ @classmethod
+ def from_crawler(cls, crawler):
+ debug = crawler.settings.getbool('DUPEFILTER_DEBUG')
+ df = cls(job_dir(crawler.settings), debug)
+ df.method = 'from_crawler'
+ return df
+
+
+class FromSettingsRFPDupeFilter(RFPDupeFilter):
+
+ @classmethod
+ def from_settings(cls, settings):
+ debug = settings.getbool('DUPEFILTER_DEBUG')
+ df = cls(job_dir(settings), debug)
+ df.method = 'from_settings'
+ return df
+
+
+class DirectDupeFilter(object):
+ method = 'n/a'
class RFPDupeFilterTest(unittest.TestCase):
+ def test_df_from_crawler_scheduler(self):
+ settings = {'DUPEFILTER_DEBUG': True,
+ 'DUPEFILTER_CLASS': __name__ + '.FromCrawlerRFPDupeFilter'}
+ crawler = get_crawler(settings_dict=settings)
+ scheduler = Scheduler.from_crawler(crawler)
+ self.assertTrue(scheduler.df.debug)
+ self.assertEqual(scheduler.df.method, 'from_crawler')
+
+ def test_df_from_settings_scheduler(self):
+ settings = {'DUPEFILTER_DEBUG': True,
+ 'DUPEFILTER_CLASS': __name__ + '.FromSettingsRFPDupeFilter'}
+ crawler = get_crawler(settings_dict=settings)
+ scheduler = Scheduler.from_crawler(crawler)
+ self.assertTrue(scheduler.df.debug)
+ self.assertEqual(scheduler.df.method, 'from_settings')
+
+ def test_df_direct_scheduler(self):
+ settings = {'DUPEFILTER_CLASS': __name__ + '.DirectDupeFilter'}
+ crawler = get_crawler(settings_dict=settings)
+ scheduler = Scheduler.from_crawler(crawler)
+ self.assertEqual(scheduler.df.method, 'n/a')
+
def test_filter(self):
dupefilter = RFPDupeFilter()
dupefilter.open()
|
Give `BaseDupeFilter` access to spider-object
I am in a situation where a single item gets defined over a sequence of multiple pages, passing values between the particular callbacks using the `meta`-dict. I believe this is a common approach among scrapy-users.
However, it feels like this approach is difficult to get right. With the default implementation of `RFPDupefilter`, my callback-chain is teared apart quite easy, as fingerprints don't take the meta-dict into account. The corresponding requests are thrown away, the information in the meta-dict which made this request unique is lost.
I have currently implemented by own meta-aware DupeFilter, but I am still facing the problem that it lacks access to the specific spider in use - and only the Spider really knows the meta-attributes that make a request unique. I could now take it a step further and implement my own scheduler, but I'm afraid that all these custom extensions make my code very brittle wrt future versions of scrapy.
|
0.0
|
895df937a3a18683836ca9e228982e9ea5842aef
|
[
"tests/test_dupefilters.py::RFPDupeFilterTest::test_df_direct_scheduler",
"tests/test_dupefilters.py::RFPDupeFilterTest::test_df_from_crawler_scheduler"
] |
[
"tests/test_dupefilters.py::RFPDupeFilterTest::test_df_from_settings_scheduler",
"tests/test_dupefilters.py::RFPDupeFilterTest::test_dupefilter_path",
"tests/test_dupefilters.py::RFPDupeFilterTest::test_filter",
"tests/test_dupefilters.py::RFPDupeFilterTest::test_request_fingerprint"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2017-10-09 15:11:56+00:00
|
bsd-3-clause
| 5,414 |
|
scrapy__scrapy-3283
|
diff --git a/scrapy/core/scheduler.py b/scrapy/core/scheduler.py
index a54b4daf0..eb790a67e 100644
--- a/scrapy/core/scheduler.py
+++ b/scrapy/core/scheduler.py
@@ -4,7 +4,7 @@ import logging
from os.path import join, exists
from scrapy.utils.reqser import request_to_dict, request_from_dict
-from scrapy.utils.misc import load_object
+from scrapy.utils.misc import load_object, create_instance
from scrapy.utils.job import job_dir
logger = logging.getLogger(__name__)
@@ -26,7 +26,7 @@ class Scheduler(object):
def from_crawler(cls, crawler):
settings = crawler.settings
dupefilter_cls = load_object(settings['DUPEFILTER_CLASS'])
- dupefilter = dupefilter_cls.from_settings(settings)
+ dupefilter = create_instance(dupefilter_cls, settings, crawler)
pqclass = load_object(settings['SCHEDULER_PRIORITY_QUEUE'])
dqclass = load_object(settings['SCHEDULER_DISK_QUEUE'])
mqclass = load_object(settings['SCHEDULER_MEMORY_QUEUE'])
diff --git a/scrapy/http/request/form.py b/scrapy/http/request/form.py
index 95b38e990..c2413b431 100644
--- a/scrapy/http/request/form.py
+++ b/scrapy/http/request/form.py
@@ -114,10 +114,12 @@ def _get_form(response, formname, formid, formnumber, formxpath):
def _get_inputs(form, formdata, dont_click, clickdata, response):
try:
- formdata = dict(formdata or ())
+ formdata_keys = dict(formdata or ()).keys()
except (ValueError, TypeError):
raise ValueError('formdata should be a dict or iterable of tuples')
+ if not formdata:
+ formdata = ()
inputs = form.xpath('descendant::textarea'
'|descendant::select'
'|descendant::input[not(@type) or @type['
@@ -128,14 +130,17 @@ def _get_inputs(form, formdata, dont_click, clickdata, response):
"re": "http://exslt.org/regular-expressions"})
values = [(k, u'' if v is None else v)
for k, v in (_value(e) for e in inputs)
- if k and k not in formdata]
+ if k and k not in formdata_keys]
if not dont_click:
clickable = _get_clickable(clickdata, form)
if clickable and clickable[0] not in formdata and not clickable[0] is None:
values.append(clickable)
- values.extend((k, v) for k, v in formdata.items() if v is not None)
+ if isinstance(formdata, dict):
+ formdata = formdata.items()
+
+ values.extend((k, v) for k, v in formdata if v is not None)
return values
|
scrapy/scrapy
|
895df937a3a18683836ca9e228982e9ea5842aef
|
diff --git a/tests/test_dupefilters.py b/tests/test_dupefilters.py
index 2d1a4bfff..db69597a2 100644
--- a/tests/test_dupefilters.py
+++ b/tests/test_dupefilters.py
@@ -5,11 +5,60 @@ import shutil
from scrapy.dupefilters import RFPDupeFilter
from scrapy.http import Request
+from scrapy.core.scheduler import Scheduler
from scrapy.utils.python import to_bytes
+from scrapy.utils.job import job_dir
+from scrapy.utils.test import get_crawler
+
+
+class FromCrawlerRFPDupeFilter(RFPDupeFilter):
+
+ @classmethod
+ def from_crawler(cls, crawler):
+ debug = crawler.settings.getbool('DUPEFILTER_DEBUG')
+ df = cls(job_dir(crawler.settings), debug)
+ df.method = 'from_crawler'
+ return df
+
+
+class FromSettingsRFPDupeFilter(RFPDupeFilter):
+
+ @classmethod
+ def from_settings(cls, settings):
+ debug = settings.getbool('DUPEFILTER_DEBUG')
+ df = cls(job_dir(settings), debug)
+ df.method = 'from_settings'
+ return df
+
+
+class DirectDupeFilter(object):
+ method = 'n/a'
class RFPDupeFilterTest(unittest.TestCase):
+ def test_df_from_crawler_scheduler(self):
+ settings = {'DUPEFILTER_DEBUG': True,
+ 'DUPEFILTER_CLASS': __name__ + '.FromCrawlerRFPDupeFilter'}
+ crawler = get_crawler(settings_dict=settings)
+ scheduler = Scheduler.from_crawler(crawler)
+ self.assertTrue(scheduler.df.debug)
+ self.assertEqual(scheduler.df.method, 'from_crawler')
+
+ def test_df_from_settings_scheduler(self):
+ settings = {'DUPEFILTER_DEBUG': True,
+ 'DUPEFILTER_CLASS': __name__ + '.FromSettingsRFPDupeFilter'}
+ crawler = get_crawler(settings_dict=settings)
+ scheduler = Scheduler.from_crawler(crawler)
+ self.assertTrue(scheduler.df.debug)
+ self.assertEqual(scheduler.df.method, 'from_settings')
+
+ def test_df_direct_scheduler(self):
+ settings = {'DUPEFILTER_CLASS': __name__ + '.DirectDupeFilter'}
+ crawler = get_crawler(settings_dict=settings)
+ scheduler = Scheduler.from_crawler(crawler)
+ self.assertEqual(scheduler.df.method, 'n/a')
+
def test_filter(self):
dupefilter = RFPDupeFilter()
dupefilter.open()
diff --git a/tests/test_http_request.py b/tests/test_http_request.py
index fc89229c6..58326a384 100644
--- a/tests/test_http_request.py
+++ b/tests/test_http_request.py
@@ -406,6 +406,29 @@ class FormRequestTest(RequestTest):
self.assertEqual(fs[u'test2'], [u'xxx µ'])
self.assertEqual(fs[u'six'], [u'seven'])
+ def test_from_response_duplicate_form_key(self):
+ response = _buildresponse(
+ '<form></form>',
+ url='http://www.example.com')
+ req = self.request_class.from_response(response,
+ method='GET',
+ formdata=(('foo', 'bar'), ('foo', 'baz')))
+ self.assertEqual(urlparse(req.url).hostname, 'www.example.com')
+ self.assertEqual(urlparse(req.url).query, 'foo=bar&foo=baz')
+
+ def test_from_response_override_duplicate_form_key(self):
+ response = _buildresponse(
+ """<form action="get.php" method="POST">
+ <input type="hidden" name="one" value="1">
+ <input type="hidden" name="two" value="3">
+ </form>""")
+ req = self.request_class.from_response(
+ response,
+ formdata=(('two', '2'), ('two', '4')))
+ fs = _qs(req)
+ self.assertEqual(fs[b'one'], [b'1'])
+ self.assertEqual(fs[b'two'], [b'2', b'4'])
+
def test_from_response_extra_headers(self):
response = _buildresponse(
"""<form action="post.php" method="POST">
|
`scrapy.FormRequest.from_response` observed to eliminate duplicate keys in `formdata`
This looks good:
```
In [2]: scrapy.FormRequest('http://example.com', method='GET', formdata=(('foo', 'bar'), ('foo', 'baz')))
Out[2]: <GET http://example.com?foo=bar&foo=baz>
```
While here is the issue:
```
In [3]: response = scrapy.http.TextResponse(url='http://example.com', body='<form></form>', encoding='utf8')
In [4]: scrapy.FormRequest.from_response(response, method='GET', formdata=(('foo', 'bar'), ('foo', 'baz')))
Out[4]: <GET http://example.com?foo=baz>
```
(Tested with `Scrapy 1.5.0` and `Python 3.6.5`)
|
0.0
|
895df937a3a18683836ca9e228982e9ea5842aef
|
[
"tests/test_dupefilters.py::RFPDupeFilterTest::test_df_direct_scheduler",
"tests/test_dupefilters.py::RFPDupeFilterTest::test_df_from_crawler_scheduler",
"tests/test_http_request.py::FormRequestTest::test_from_response_duplicate_form_key",
"tests/test_http_request.py::FormRequestTest::test_from_response_override_duplicate_form_key"
] |
[
"tests/test_dupefilters.py::RFPDupeFilterTest::test_df_from_settings_scheduler",
"tests/test_dupefilters.py::RFPDupeFilterTest::test_dupefilter_path",
"tests/test_dupefilters.py::RFPDupeFilterTest::test_filter",
"tests/test_dupefilters.py::RFPDupeFilterTest::test_request_fingerprint",
"tests/test_http_request.py::RequestTest::test_ajax_url",
"tests/test_http_request.py::RequestTest::test_body",
"tests/test_http_request.py::RequestTest::test_callback_is_callable",
"tests/test_http_request.py::RequestTest::test_copy",
"tests/test_http_request.py::RequestTest::test_copy_inherited_classes",
"tests/test_http_request.py::RequestTest::test_eq",
"tests/test_http_request.py::RequestTest::test_errback_is_callable",
"tests/test_http_request.py::RequestTest::test_headers",
"tests/test_http_request.py::RequestTest::test_immutable_attributes",
"tests/test_http_request.py::RequestTest::test_init",
"tests/test_http_request.py::RequestTest::test_method_always_str",
"tests/test_http_request.py::RequestTest::test_replace",
"tests/test_http_request.py::RequestTest::test_url",
"tests/test_http_request.py::RequestTest::test_url_encoding",
"tests/test_http_request.py::RequestTest::test_url_encoding_nonutf8_untouched",
"tests/test_http_request.py::RequestTest::test_url_encoding_other",
"tests/test_http_request.py::RequestTest::test_url_encoding_query",
"tests/test_http_request.py::RequestTest::test_url_encoding_query_latin1",
"tests/test_http_request.py::RequestTest::test_url_no_scheme",
"tests/test_http_request.py::RequestTest::test_url_quoting",
"tests/test_http_request.py::FormRequestTest::test_ajax_url",
"tests/test_http_request.py::FormRequestTest::test_body",
"tests/test_http_request.py::FormRequestTest::test_callback_is_callable",
"tests/test_http_request.py::FormRequestTest::test_copy",
"tests/test_http_request.py::FormRequestTest::test_copy_inherited_classes",
"tests/test_http_request.py::FormRequestTest::test_custom_encoding_bytes",
"tests/test_http_request.py::FormRequestTest::test_custom_encoding_textual_data",
"tests/test_http_request.py::FormRequestTest::test_default_encoding_bytes",
"tests/test_http_request.py::FormRequestTest::test_default_encoding_mixed_data",
"tests/test_http_request.py::FormRequestTest::test_default_encoding_textual_data",
"tests/test_http_request.py::FormRequestTest::test_empty_formdata",
"tests/test_http_request.py::FormRequestTest::test_eq",
"tests/test_http_request.py::FormRequestTest::test_errback_is_callable",
"tests/test_http_request.py::FormRequestTest::test_from_response_ambiguous_clickdata",
"tests/test_http_request.py::FormRequestTest::test_from_response_button_notype",
"tests/test_http_request.py::FormRequestTest::test_from_response_button_novalue",
"tests/test_http_request.py::FormRequestTest::test_from_response_button_submit",
"tests/test_http_request.py::FormRequestTest::test_from_response_case_insensitive",
"tests/test_http_request.py::FormRequestTest::test_from_response_checkbox",
"tests/test_http_request.py::FormRequestTest::test_from_response_clickdata_does_not_ignore_image",
"tests/test_http_request.py::FormRequestTest::test_from_response_css",
"tests/test_http_request.py::FormRequestTest::test_from_response_descendants",
"tests/test_http_request.py::FormRequestTest::test_from_response_dont_click",
"tests/test_http_request.py::FormRequestTest::test_from_response_dont_submit_image_as_input",
"tests/test_http_request.py::FormRequestTest::test_from_response_dont_submit_reset_as_input",
"tests/test_http_request.py::FormRequestTest::test_from_response_drop_params",
"tests/test_http_request.py::FormRequestTest::test_from_response_errors_formnumber",
"tests/test_http_request.py::FormRequestTest::test_from_response_errors_noform",
"tests/test_http_request.py::FormRequestTest::test_from_response_extra_headers",
"tests/test_http_request.py::FormRequestTest::test_from_response_formid_errors_formnumber",
"tests/test_http_request.py::FormRequestTest::test_from_response_formid_exists",
"tests/test_http_request.py::FormRequestTest::test_from_response_formid_notexist",
"tests/test_http_request.py::FormRequestTest::test_from_response_formname_errors_formnumber",
"tests/test_http_request.py::FormRequestTest::test_from_response_formname_exists",
"tests/test_http_request.py::FormRequestTest::test_from_response_formname_notexist",
"tests/test_http_request.py::FormRequestTest::test_from_response_formname_notexists_fallback_formid",
"tests/test_http_request.py::FormRequestTest::test_from_response_get",
"tests/test_http_request.py::FormRequestTest::test_from_response_input_hidden",
"tests/test_http_request.py::FormRequestTest::test_from_response_input_text",
"tests/test_http_request.py::FormRequestTest::test_from_response_input_textarea",
"tests/test_http_request.py::FormRequestTest::test_from_response_invalid_html5",
"tests/test_http_request.py::FormRequestTest::test_from_response_invalid_nr_index_clickdata",
"tests/test_http_request.py::FormRequestTest::test_from_response_multiple_clickdata",
"tests/test_http_request.py::FormRequestTest::test_from_response_multiple_forms_clickdata",
"tests/test_http_request.py::FormRequestTest::test_from_response_noformname",
"tests/test_http_request.py::FormRequestTest::test_from_response_non_matching_clickdata",
"tests/test_http_request.py::FormRequestTest::test_from_response_nr_index_clickdata",
"tests/test_http_request.py::FormRequestTest::test_from_response_override_clickable",
"tests/test_http_request.py::FormRequestTest::test_from_response_override_method",
"tests/test_http_request.py::FormRequestTest::test_from_response_override_params",
"tests/test_http_request.py::FormRequestTest::test_from_response_override_url",
"tests/test_http_request.py::FormRequestTest::test_from_response_post",
"tests/test_http_request.py::FormRequestTest::test_from_response_post_nonascii_bytes_latin1",
"tests/test_http_request.py::FormRequestTest::test_from_response_post_nonascii_bytes_utf8",
"tests/test_http_request.py::FormRequestTest::test_from_response_post_nonascii_unicode",
"tests/test_http_request.py::FormRequestTest::test_from_response_radio",
"tests/test_http_request.py::FormRequestTest::test_from_response_select",
"tests/test_http_request.py::FormRequestTest::test_from_response_submit_first_clickable",
"tests/test_http_request.py::FormRequestTest::test_from_response_submit_not_first_clickable",
"tests/test_http_request.py::FormRequestTest::test_from_response_submit_novalue",
"tests/test_http_request.py::FormRequestTest::test_from_response_unicode_clickdata",
"tests/test_http_request.py::FormRequestTest::test_from_response_unicode_clickdata_latin1",
"tests/test_http_request.py::FormRequestTest::test_from_response_unicode_xpath",
"tests/test_http_request.py::FormRequestTest::test_from_response_xpath",
"tests/test_http_request.py::FormRequestTest::test_headers",
"tests/test_http_request.py::FormRequestTest::test_html_base_form_action",
"tests/test_http_request.py::FormRequestTest::test_immutable_attributes",
"tests/test_http_request.py::FormRequestTest::test_init",
"tests/test_http_request.py::FormRequestTest::test_method_always_str",
"tests/test_http_request.py::FormRequestTest::test_multi_key_values",
"tests/test_http_request.py::FormRequestTest::test_replace",
"tests/test_http_request.py::FormRequestTest::test_spaces_in_action",
"tests/test_http_request.py::FormRequestTest::test_url",
"tests/test_http_request.py::FormRequestTest::test_url_encoding",
"tests/test_http_request.py::FormRequestTest::test_url_encoding_nonutf8_untouched",
"tests/test_http_request.py::FormRequestTest::test_url_encoding_other",
"tests/test_http_request.py::FormRequestTest::test_url_encoding_query",
"tests/test_http_request.py::FormRequestTest::test_url_encoding_query_latin1",
"tests/test_http_request.py::FormRequestTest::test_url_no_scheme",
"tests/test_http_request.py::FormRequestTest::test_url_quoting",
"tests/test_http_request.py::XmlRpcRequestTest::test_ajax_url",
"tests/test_http_request.py::XmlRpcRequestTest::test_body",
"tests/test_http_request.py::XmlRpcRequestTest::test_callback_is_callable",
"tests/test_http_request.py::XmlRpcRequestTest::test_copy",
"tests/test_http_request.py::XmlRpcRequestTest::test_copy_inherited_classes",
"tests/test_http_request.py::XmlRpcRequestTest::test_eq",
"tests/test_http_request.py::XmlRpcRequestTest::test_errback_is_callable",
"tests/test_http_request.py::XmlRpcRequestTest::test_headers",
"tests/test_http_request.py::XmlRpcRequestTest::test_immutable_attributes",
"tests/test_http_request.py::XmlRpcRequestTest::test_init",
"tests/test_http_request.py::XmlRpcRequestTest::test_latin1",
"tests/test_http_request.py::XmlRpcRequestTest::test_method_always_str",
"tests/test_http_request.py::XmlRpcRequestTest::test_replace",
"tests/test_http_request.py::XmlRpcRequestTest::test_url",
"tests/test_http_request.py::XmlRpcRequestTest::test_url_encoding",
"tests/test_http_request.py::XmlRpcRequestTest::test_url_encoding_nonutf8_untouched",
"tests/test_http_request.py::XmlRpcRequestTest::test_url_encoding_other",
"tests/test_http_request.py::XmlRpcRequestTest::test_url_encoding_query",
"tests/test_http_request.py::XmlRpcRequestTest::test_url_encoding_query_latin1",
"tests/test_http_request.py::XmlRpcRequestTest::test_url_no_scheme",
"tests/test_http_request.py::XmlRpcRequestTest::test_url_quoting",
"tests/test_http_request.py::XmlRpcRequestTest::test_xmlrpc_dumps"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-06-08 00:24:44+00:00
|
bsd-3-clause
| 5,415 |
|
scrapy__scrapy-3371
|
diff --git a/scrapy/contracts/__init__.py b/scrapy/contracts/__init__.py
index 5eaee3d11..8315d21d2 100644
--- a/scrapy/contracts/__init__.py
+++ b/scrapy/contracts/__init__.py
@@ -84,7 +84,7 @@ class ContractsManager(object):
def eb_wrapper(failure):
case = _create_testcase(method, 'errback')
- exc_info = failure.value, failure.type, failure.getTracebackObject()
+ exc_info = failure.type, failure.value, failure.getTracebackObject()
results.addError(case, exc_info)
request.callback = cb_wrapper
|
scrapy/scrapy
|
c8f3d07e86dd41074971b5423fb932c2eda6db1e
|
diff --git a/tests/test_contracts.py b/tests/test_contracts.py
index 1cea2afb7..b07cbee1e 100644
--- a/tests/test_contracts.py
+++ b/tests/test_contracts.py
@@ -1,7 +1,9 @@
from unittest import TextTestResult
+from twisted.python import failure
from twisted.trial import unittest
+from scrapy.spidermiddlewares.httperror import HttpError
from scrapy.spiders import Spider
from scrapy.http import Request
from scrapy.item import Item, Field
@@ -185,3 +187,18 @@ class ContractsManagerTest(unittest.TestCase):
self.results)
request.callback(response)
self.should_fail()
+
+ def test_errback(self):
+ spider = TestSpider()
+ response = ResponseMock()
+
+ try:
+ raise HttpError(response, 'Ignoring non-200 response')
+ except HttpError:
+ failure_mock = failure.Failure()
+
+ request = self.conman.from_method(spider.returns_request, self.results)
+ request.errback(failure_mock)
+
+ self.assertFalse(self.results.failures)
+ self.assertTrue(self.results.errors)
|
AttributeError from contract errback
When running a contract with a URL that returns non-200 response, I get the following:
```
2018-08-09 14:40:23 [scrapy.core.scraper] ERROR: Spider error processing <GET https://www.bureauxlocaux.com/annonce/a-louer-bureaux-a-louer-a-nantes--1289-358662> (referer: None)
Traceback (most recent call last):
File "/usr/local/lib/python3.6/site-packages/twisted/internet/defer.py", line 653, in _runCallbacks
current.result = callback(current.result, *args, **kw)
File "/usr/local/lib/python3.6/site-packages/scrapy/contracts/__init__.py", line 89, in eb_wrapper
results.addError(case, exc_info)
File "/usr/local/lib/python3.6/unittest/runner.py", line 67, in addError
super(TextTestResult, self).addError(test, err)
File "/usr/local/lib/python3.6/unittest/result.py", line 17, in inner
return method(self, *args, **kw)
File "/usr/local/lib/python3.6/unittest/result.py", line 115, in addError
self.errors.append((test, self._exc_info_to_string(err, test)))
File "/usr/local/lib/python3.6/unittest/result.py", line 186, in _exc_info_to_string
exctype, value, tb, limit=length, capture_locals=self.tb_locals)
File "/usr/local/lib/python3.6/traceback.py", line 470, in __init__
exc_value.__cause__.__traceback__,
AttributeError: 'getset_descriptor' object has no attribute '__traceback__'
```
Here is how `exc_info` looks like:
```
(HttpError('Ignoring non-200 response',), <class 'scrapy.spidermiddlewares.httperror.HttpError'>, <traceback object at 0x7f4bdca1d948>)
```
|
0.0
|
c8f3d07e86dd41074971b5423fb932c2eda6db1e
|
[
"tests/test_contracts.py::ContractsManagerTest::test_errback"
] |
[
"tests/test_contracts.py::ContractsManagerTest::test_contracts",
"tests/test_contracts.py::ContractsManagerTest::test_returns",
"tests/test_contracts.py::ContractsManagerTest::test_scrapes"
] |
{
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-08-09 18:10:12+00:00
|
bsd-3-clause
| 5,416 |
|
scrapy__scrapy-4052
|
diff --git a/scrapy/extensions/corestats.py b/scrapy/extensions/corestats.py
index 8cc5e18ac..20adfbe4b 100644
--- a/scrapy/extensions/corestats.py
+++ b/scrapy/extensions/corestats.py
@@ -1,14 +1,16 @@
"""
Extension for collecting core stats like items scraped and start/finish times
"""
-import datetime
+from datetime import datetime
from scrapy import signals
+
class CoreStats(object):
def __init__(self, stats):
self.stats = stats
+ self.start_time = None
@classmethod
def from_crawler(cls, crawler):
@@ -21,11 +23,12 @@ class CoreStats(object):
return o
def spider_opened(self, spider):
- self.stats.set_value('start_time', datetime.datetime.utcnow(), spider=spider)
+ self.start_time = datetime.utcnow()
+ self.stats.set_value('start_time', self.start_time, spider=spider)
def spider_closed(self, spider, reason):
- finish_time = datetime.datetime.utcnow()
- elapsed_time = finish_time - self.stats.get_value('start_time')
+ finish_time = datetime.utcnow()
+ elapsed_time = finish_time - self.start_time
elapsed_time_seconds = elapsed_time.total_seconds()
self.stats.set_value('elapsed_time_seconds', elapsed_time_seconds, spider=spider)
self.stats.set_value('finish_time', finish_time, spider=spider)
|
scrapy/scrapy
|
74b4a5c77c0017106f6ba65b21b8bf2a1ed02f7b
|
diff --git a/tests/test_stats.py b/tests/test_stats.py
index 9f950ebc9..2033dbe07 100644
--- a/tests/test_stats.py
+++ b/tests/test_stats.py
@@ -1,10 +1,59 @@
+from datetime import datetime
import unittest
+try:
+ from unittest import mock
+except ImportError:
+ import mock
+
+from scrapy.extensions.corestats import CoreStats
from scrapy.spiders import Spider
from scrapy.statscollectors import StatsCollector, DummyStatsCollector
from scrapy.utils.test import get_crawler
+class CoreStatsExtensionTest(unittest.TestCase):
+
+ def setUp(self):
+ self.crawler = get_crawler(Spider)
+ self.spider = self.crawler._create_spider('foo')
+
+ @mock.patch('scrapy.extensions.corestats.datetime')
+ def test_core_stats_default_stats_collector(self, mock_datetime):
+ fixed_datetime = datetime(2019, 12, 1, 11, 38)
+ mock_datetime.utcnow = mock.Mock(return_value=fixed_datetime)
+ self.crawler.stats = StatsCollector(self.crawler)
+ ext = CoreStats.from_crawler(self.crawler)
+ ext.spider_opened(self.spider)
+ ext.item_scraped({}, self.spider)
+ ext.response_received(self.spider)
+ ext.item_dropped({}, self.spider, ZeroDivisionError())
+ ext.spider_closed(self.spider, 'finished')
+ self.assertEqual(
+ ext.stats._stats,
+ {
+ 'start_time': fixed_datetime,
+ 'finish_time': fixed_datetime,
+ 'item_scraped_count': 1,
+ 'response_received_count': 1,
+ 'item_dropped_count': 1,
+ 'item_dropped_reasons_count/ZeroDivisionError': 1,
+ 'finish_reason': 'finished',
+ 'elapsed_time_seconds': 0.0,
+ }
+ )
+
+ def test_core_stats_dummy_stats_collector(self):
+ self.crawler.stats = DummyStatsCollector(self.crawler)
+ ext = CoreStats.from_crawler(self.crawler)
+ ext.spider_opened(self.spider)
+ ext.item_scraped({}, self.spider)
+ ext.response_received(self.spider)
+ ext.item_dropped({}, self.spider, ZeroDivisionError())
+ ext.spider_closed(self.spider, 'finished')
+ self.assertEqual(ext.stats._stats, {})
+
+
class StatsCollectorTest(unittest.TestCase):
def setUp(self):
|
Exception when using DummyStatsCollector
### Description
Using the DummyStatsCollector results in an exception:
```
2019-09-09 13:51:23 [scrapy.utils.signal] ERROR: Error caught on signal handler: <bound method CoreStats.spider_closed of <scrapy.extensions.corestats.CoreStats object at 0x7f86269cac18>>
Traceback (most recent call last):
File ".../lib/python3.6/site-packages/twisted/internet/defer.py", line 150, in maybeDeferred
result = f(*args, **kw)
File ".../lib/python3.6/site-packages/pydispatch/robustapply.py", line 55, in robustApply
return receiver(*arguments, **named)
File ".../lib/python3.6/site-packages/scrapy/extensions/corestats.py", line 28, in spider_closed
elapsed_time = finish_time - self.stats.get_value('start_time')
TypeError: unsupported operand type(s) for -: 'datetime.datetime' and 'NoneType'
```
This problem has been introduced in aa46e1995cd5cb1099aba17535372b538bd656b3.
### Steps to Reproduce
Set `STATS_CLASS = "scrapy.statscollectors.DummyStatsCollector"` in the settings module as described in the documentation (https://docs.scrapy.org/en/latest/topics/stats.html#dummystatscollector).
**Expected behavior:** no exception
**Actual behavior:** exception thrown
**Reproduces how often:** always
### Versions
At least master as of 534de7395da3a53b5a2c89960db9ec5d8fdab60c
### Fix
A possible fix is to use the elapsed time as a default argument so that `get_value()` does not return None. I can prepare a PR if needed.
```diff
--- a/scrapy/extensions/corestats.py
+++ b/scrapy/extensions/corestats.py
@@ -25,7 +25,7 @@ class CoreStats(object):
def spider_closed(self, spider, reason):
finish_time = datetime.datetime.utcnow()
- elapsed_time = finish_time - self.stats.get_value('start_time')
+ elapsed_time = finish_time - self.stats.get_value('start_time', finish_time)
elapsed_time_seconds = elapsed_time.total_seconds()
self.stats.set_value('elapsed_time_seconds', elapsed_time_seconds, spider=spider)
self.stats.set_value('finish_time', finish_time, spider=spider)
```
|
0.0
|
74b4a5c77c0017106f6ba65b21b8bf2a1ed02f7b
|
[
"tests/test_stats.py::CoreStatsExtensionTest::test_core_stats_default_stats_collector",
"tests/test_stats.py::CoreStatsExtensionTest::test_core_stats_dummy_stats_collector"
] |
[
"tests/test_stats.py::StatsCollectorTest::test_collector",
"tests/test_stats.py::StatsCollectorTest::test_dummy_collector"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_git_commit_hash"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-10-01 15:05:36+00:00
|
bsd-3-clause
| 5,417 |
|
scrapy__scrapy-5118
|
diff --git a/scrapy/mail.py b/scrapy/mail.py
index c11f3898d..237327451 100644
--- a/scrapy/mail.py
+++ b/scrapy/mail.py
@@ -96,10 +96,9 @@ class MailSender:
rcpts.extend(cc)
msg["Cc"] = COMMASPACE.join(cc)
- if charset:
- msg.set_charset(charset)
-
if attachs:
+ if charset:
+ msg.set_charset(charset)
msg.attach(MIMEText(body, "plain", charset or "us-ascii"))
for attach_name, mimetype, f in attachs:
part = MIMEBase(*mimetype.split("/"))
@@ -110,7 +109,7 @@ class MailSender:
)
msg.attach(part)
else:
- msg.set_payload(body)
+ msg.set_payload(body, charset)
if _callback:
_callback(to=to, subject=subject, body=body, cc=cc, attach=attachs, msg=msg)
|
scrapy/scrapy
|
00527fdcbe042ae5b3ea06e93e03a8a353d0524c
|
diff --git a/tests/test_mail.py b/tests/test_mail.py
index 504c78486..2535e58db 100644
--- a/tests/test_mail.py
+++ b/tests/test_mail.py
@@ -111,7 +111,7 @@ class MailSenderTest(unittest.TestCase):
msg = self.catched_msg["msg"]
self.assertEqual(msg["subject"], subject)
- self.assertEqual(msg.get_payload(), body)
+ self.assertEqual(msg.get_payload(decode=True).decode("utf-8"), body)
self.assertEqual(msg.get_charset(), Charset("utf-8"))
self.assertEqual(msg.get("Content-Type"), 'text/plain; charset="utf-8"')
|
Wrong charset handling in MailSender
Looks like passing `charset='utf-8'` makes a plain text message with `Content-Transfer-Encoding: base64` which then can't be read.
At https://github.com/scrapy/scrapy/blob/5a75b14a5fbbbd37c14aa7317761655ac7706b70/scrapy/mail.py#L81 `set_charset` is called but as the payload is not set yet, the underlying class just sets the headers. When later `set_payload` is called, it doesn't do any encoding, but the `Content-Transfer-Encoding` is already set. Looks like the fix should be passing the encoding to `set_payload` too, like was proposed in #3722 (and `set_charset` may be safe to be removed, not sure about this). Note that we have tests but they don't catch this.
Note also, that all of this seems to be compat code according to the Python docs.
|
0.0
|
00527fdcbe042ae5b3ea06e93e03a8a353d0524c
|
[
"tests/test_mail.py::MailSenderTest::test_send_utf8"
] |
[
"tests/test_mail.py::MailSenderTest::test_create_sender_factory_with_host",
"tests/test_mail.py::MailSenderTest::test_send",
"tests/test_mail.py::MailSenderTest::test_send_attach",
"tests/test_mail.py::MailSenderTest::test_send_attach_utf8",
"tests/test_mail.py::MailSenderTest::test_send_html",
"tests/test_mail.py::MailSenderTest::test_send_single_values_to_and_cc"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2021-04-26 19:32:20+00:00
|
bsd-3-clause
| 5,418 |
|
scrapy__scrapy-5384
|
diff --git a/scrapy/settings/__init__.py b/scrapy/settings/__init__.py
index 1fe1e6fd1..6b1ad0828 100644
--- a/scrapy/settings/__init__.py
+++ b/scrapy/settings/__init__.py
@@ -375,9 +375,13 @@ class BaseSettings(MutableMapping):
return len(self.attributes)
def _to_dict(self):
- return {k: (v._to_dict() if isinstance(v, BaseSettings) else v)
+ return {self._get_key(k): (v._to_dict() if isinstance(v, BaseSettings) else v)
for k, v in self.items()}
+ def _get_key(self, key_value):
+ return (key_value if isinstance(key_value, (bool, float, int, str, type(None)))
+ else str(key_value))
+
def copy_to_dict(self):
"""
Make a copy of current settings and convert to a dict.
|
scrapy/scrapy
|
30d5779ea94ed1e9343a4590895a3f5e65e444b9
|
diff --git a/tests/test_cmdline/__init__.py b/tests/test_cmdline/__init__.py
index 591075a98..8233e0101 100644
--- a/tests/test_cmdline/__init__.py
+++ b/tests/test_cmdline/__init__.py
@@ -64,3 +64,7 @@ class CmdlineTest(unittest.TestCase):
settingsdict = json.loads(settingsstr)
self.assertCountEqual(settingsdict.keys(), EXTENSIONS.keys())
self.assertEqual(200, settingsdict[EXT_PATH])
+
+ def test_pathlib_path_as_feeds_key(self):
+ self.assertEqual(self._execute('settings', '--get', 'FEEDS'),
+ json.dumps({"items.csv": {"format": "csv", "fields": ["price", "name"]}}))
diff --git a/tests/test_cmdline/settings.py b/tests/test_cmdline/settings.py
index 8a719ddf2..b0ac6e98b 100644
--- a/tests/test_cmdline/settings.py
+++ b/tests/test_cmdline/settings.py
@@ -1,5 +1,14 @@
+from pathlib import Path
+
EXTENSIONS = {
'tests.test_cmdline.extensions.TestExtension': 0,
}
TEST1 = 'default'
+
+FEEDS = {
+ Path('items.csv'): {
+ 'format': 'csv',
+ 'fields': ['price', 'name'],
+ },
+}
|
Type error when we try to retrieve the `FEEDS` setting via CLI and it has a `Path` objects as a key
<!--
Thanks for taking an interest in Scrapy!
If you have a question that starts with "How to...", please see the Scrapy Community page: https://scrapy.org/community/.
The GitHub issue tracker's purpose is to deal with bug reports and feature requests for the project itself.
Keep in mind that by filing an issue, you are expected to comply with Scrapy's Code of Conduct, including treating everyone with respect: https://github.com/scrapy/scrapy/blob/master/CODE_OF_CONDUCT.md
The following is a suggested template to structure your issue, you can find more guidelines at https://doc.scrapy.org/en/latest/contributing.html#reporting-bugs
-->
### Description
When a `Path` object is used as a key in the `FEEDS` dictionary and we try to obtain the `FEEDS` setting via CLI `scrapy settings --get FEEDS`, a type error is raised:
```
TypeError: keys must be str, int, float, bool or None, not PosixPath
```
A complete stack trace is attached below under "Actual behavior".
`Path` objects as keys are allowed as documented in [the FEEDS section of the Feed exports chapter](https://docs.scrapy.org/en/master/topics/feed-exports.html#feeds).
### Steps to Reproduce
1. In a freshly generated scrapy project (e.g. via `scrapy project feeds_bug`), prepend the following lines to `settings.py`:
```python
from pathlib import Path
FEEDS = {
Path("some_path/file.csv"): {
"format": "csv"
}
}
```
2. Execute `scrapy settings --get FEEDS`
**Expected behavior:** Some string representation of the `FEEDS` setting gets printed to standard out, maybe like this:
```
{"some_path/file.csv": {"format": "csv"}}
```
**Actual behavior:** A type error is raised:
```
Traceback (most recent call last):
File "/Users/paul/Projects/feeds-bug/.direnv/python-3.9.7/bin/scrapy", line 8, in <module>
sys.exit(execute())
File "/Users/paul/Projects/feeds-bug/.direnv/python-3.9.7/lib/python3.9/site-packages/scrapy/cmdline.py", line 145, in execute
_run_print_help(parser, _run_command, cmd, args, opts)
File "/Users/paul/Projects/feeds-bug/.direnv/python-3.9.7/lib/python3.9/site-packages/scrapy/cmdline.py", line 100, in _run_print_help
func(*a, **kw)
File "/Users/paul/Projects/feeds-bug/.direnv/python-3.9.7/lib/python3.9/site-packages/scrapy/cmdline.py", line 153, in _run_command
cmd.run(args, opts)
File "/Users/paul/Projects/feeds-bug/.direnv/python-3.9.7/lib/python3.9/site-packages/scrapy/commands/settings.py", line 37, in run
print(json.dumps(s.copy_to_dict()))
File "/Users/paul/.pyenv/versions/3.9.7/lib/python3.9/json/__init__.py", line 231, in dumps
return _default_encoder.encode(obj)
File "/Users/paul/.pyenv/versions/3.9.7/lib/python3.9/json/encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/Users/paul/.pyenv/versions/3.9.7/lib/python3.9/json/encoder.py", line 257, in iterencode
return _iterencode(o, 0)
TypeError: keys must be str, int, float, bool or None, not PosixPath
```
**Reproduces how often:** 100%
### Versions
```
Scrapy : 2.5.1
lxml : 4.7.1.0
libxml2 : 2.9.12
cssselect : 1.1.0
parsel : 1.6.0
w3lib : 1.22.0
Twisted : 21.7.0
Python : 3.9.7 (default, Dec 11 2021, 11:25:57) - [Clang 13.0.0 (clang-1300.0.29.3)]
pyOpenSSL : 22.0.0 (OpenSSL 1.1.1m 14 Dec 2021)
cryptography : 36.0.1
Platform : macOS-11.6-x86_64-i386-64bit
```
|
0.0
|
30d5779ea94ed1e9343a4590895a3f5e65e444b9
|
[
"tests/test_cmdline/__init__.py::CmdlineTest::test_pathlib_path_as_feeds_key"
] |
[
"tests/test_cmdline/__init__.py::CmdlineTest::test_default_settings",
"tests/test_cmdline/__init__.py::CmdlineTest::test_override_dict_settings",
"tests/test_cmdline/__init__.py::CmdlineTest::test_override_settings_using_envvar",
"tests/test_cmdline/__init__.py::CmdlineTest::test_override_settings_using_set_arg",
"tests/test_cmdline/__init__.py::CmdlineTest::test_profiling"
] |
{
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-01-31 16:35:39+00:00
|
bsd-3-clause
| 5,419 |
|
scrapy__scrapy-5589
|
diff --git a/scrapy/core/engine.py b/scrapy/core/engine.py
index 6602f661d..1228e78da 100644
--- a/scrapy/core/engine.py
+++ b/scrapy/core/engine.py
@@ -257,9 +257,7 @@ class ExecutionEngine:
def download(self, request: Request, spider: Optional[Spider] = None) -> Deferred:
"""Return a Deferred which fires with a Response as result, only downloader middlewares are applied"""
- if spider is None:
- spider = self.spider
- else:
+ if spider is not None:
warnings.warn(
"Passing a 'spider' argument to ExecutionEngine.download is deprecated",
category=ScrapyDeprecationWarning,
@@ -267,7 +265,7 @@ class ExecutionEngine:
)
if spider is not self.spider:
logger.warning("The spider '%s' does not match the open spider", spider.name)
- if spider is None:
+ if self.spider is None:
raise RuntimeError(f"No open spider to crawl: {request}")
return self._download(request, spider).addBoth(self._downloaded, request, spider)
@@ -278,11 +276,14 @@ class ExecutionEngine:
self.slot.remove_request(request)
return self.download(result, spider) if isinstance(result, Request) else result
- def _download(self, request: Request, spider: Spider) -> Deferred:
+ def _download(self, request: Request, spider: Optional[Spider]) -> Deferred:
assert self.slot is not None # typing
self.slot.add_request(request)
+ if spider is None:
+ spider = self.spider
+
def _on_success(result: Union[Response, Request]) -> Union[Response, Request]:
if not isinstance(result, (Response, Request)):
raise TypeError(f"Incorrect type: expected Response or Request, got {type(result)}: {result!r}")
diff --git a/scrapy/downloadermiddlewares/httpproxy.py b/scrapy/downloadermiddlewares/httpproxy.py
index 1deda42bd..dd8a7e797 100644
--- a/scrapy/downloadermiddlewares/httpproxy.py
+++ b/scrapy/downloadermiddlewares/httpproxy.py
@@ -78,4 +78,7 @@ class HttpProxyMiddleware:
del request.headers[b'Proxy-Authorization']
del request.meta['_auth_proxy']
elif b'Proxy-Authorization' in request.headers:
- del request.headers[b'Proxy-Authorization']
+ if proxy_url:
+ request.meta['_auth_proxy'] = proxy_url
+ else:
+ del request.headers[b'Proxy-Authorization']
|
scrapy/scrapy
|
92be5ba2572ec14e2580abe12d276e8aa24247b6
|
diff --git a/tests/test_downloadermiddleware_httpproxy.py b/tests/test_downloadermiddleware_httpproxy.py
index 70eb94d77..44434f90e 100644
--- a/tests/test_downloadermiddleware_httpproxy.py
+++ b/tests/test_downloadermiddleware_httpproxy.py
@@ -400,6 +400,9 @@ class TestHttpProxyMiddleware(TestCase):
self.assertNotIn(b'Proxy-Authorization', request.headers)
def test_proxy_authentication_header_proxy_without_credentials(self):
+ """As long as the proxy URL in request metadata remains the same, the
+ Proxy-Authorization header is used and kept, and may even be
+ changed."""
middleware = HttpProxyMiddleware()
request = Request(
'https://example.com',
@@ -408,7 +411,16 @@ class TestHttpProxyMiddleware(TestCase):
)
assert middleware.process_request(request, spider) is None
self.assertEqual(request.meta['proxy'], 'https://example.com')
- self.assertNotIn(b'Proxy-Authorization', request.headers)
+ self.assertEqual(request.headers['Proxy-Authorization'], b'Basic foo')
+
+ assert middleware.process_request(request, spider) is None
+ self.assertEqual(request.meta['proxy'], 'https://example.com')
+ self.assertEqual(request.headers['Proxy-Authorization'], b'Basic foo')
+
+ request.headers['Proxy-Authorization'] = b'Basic bar'
+ assert middleware.process_request(request, spider) is None
+ self.assertEqual(request.meta['proxy'], 'https://example.com')
+ self.assertEqual(request.headers['Proxy-Authorization'], b'Basic bar')
def test_proxy_authentication_header_proxy_with_same_credentials(self):
middleware = HttpProxyMiddleware()
|
Scrapy warns about itself
I'm using Scrapy 2.6.2. Created a new project, run a spider, and there is
```
2022-08-02 23:50:26 [py.warnings] WARNING: [redacted]/python3.8/site-packages/scrapy/core/engine.py:279: ScrapyDeprecationWarning: Passing a 'spider' argument to ExecutionEngine.download is deprecated
return self.download(result, spider) if isinstance(result, Request) else result
```
message in logs. We also have the same warning in our testing suite, but I haven't realized it's not a test-only issue.
|
0.0
|
92be5ba2572ec14e2580abe12d276e8aa24247b6
|
[
"tests/test_downloadermiddleware_httpproxy.py::TestHttpProxyMiddleware::test_proxy_authentication_header_proxy_without_credentials"
] |
[
"tests/test_downloadermiddleware_httpproxy.py::TestHttpProxyMiddleware::test_add_credentials",
"tests/test_downloadermiddleware_httpproxy.py::TestHttpProxyMiddleware::test_add_proxy_with_credentials",
"tests/test_downloadermiddleware_httpproxy.py::TestHttpProxyMiddleware::test_add_proxy_without_credentials",
"tests/test_downloadermiddleware_httpproxy.py::TestHttpProxyMiddleware::test_change_credentials",
"tests/test_downloadermiddleware_httpproxy.py::TestHttpProxyMiddleware::test_change_proxy_add_credentials",
"tests/test_downloadermiddleware_httpproxy.py::TestHttpProxyMiddleware::test_change_proxy_change_credentials",
"tests/test_downloadermiddleware_httpproxy.py::TestHttpProxyMiddleware::test_change_proxy_keep_credentials",
"tests/test_downloadermiddleware_httpproxy.py::TestHttpProxyMiddleware::test_change_proxy_remove_credentials",
"tests/test_downloadermiddleware_httpproxy.py::TestHttpProxyMiddleware::test_change_proxy_remove_credentials_preremoved_header",
"tests/test_downloadermiddleware_httpproxy.py::TestHttpProxyMiddleware::test_environment_proxies",
"tests/test_downloadermiddleware_httpproxy.py::TestHttpProxyMiddleware::test_no_environment_proxies",
"tests/test_downloadermiddleware_httpproxy.py::TestHttpProxyMiddleware::test_no_proxy",
"tests/test_downloadermiddleware_httpproxy.py::TestHttpProxyMiddleware::test_no_proxy_invalid_values",
"tests/test_downloadermiddleware_httpproxy.py::TestHttpProxyMiddleware::test_not_enabled",
"tests/test_downloadermiddleware_httpproxy.py::TestHttpProxyMiddleware::test_proxy_already_seted",
"tests/test_downloadermiddleware_httpproxy.py::TestHttpProxyMiddleware::test_proxy_auth",
"tests/test_downloadermiddleware_httpproxy.py::TestHttpProxyMiddleware::test_proxy_auth_empty_passwd",
"tests/test_downloadermiddleware_httpproxy.py::TestHttpProxyMiddleware::test_proxy_auth_encoding",
"tests/test_downloadermiddleware_httpproxy.py::TestHttpProxyMiddleware::test_proxy_authentication_header_disabled_proxy",
"tests/test_downloadermiddleware_httpproxy.py::TestHttpProxyMiddleware::test_proxy_authentication_header_proxy_with_different_credentials",
"tests/test_downloadermiddleware_httpproxy.py::TestHttpProxyMiddleware::test_proxy_authentication_header_proxy_with_same_credentials",
"tests/test_downloadermiddleware_httpproxy.py::TestHttpProxyMiddleware::test_proxy_authentication_header_undefined_proxy",
"tests/test_downloadermiddleware_httpproxy.py::TestHttpProxyMiddleware::test_proxy_precedence_meta",
"tests/test_downloadermiddleware_httpproxy.py::TestHttpProxyMiddleware::test_remove_credentials",
"tests/test_downloadermiddleware_httpproxy.py::TestHttpProxyMiddleware::test_remove_proxy_with_credentials",
"tests/test_downloadermiddleware_httpproxy.py::TestHttpProxyMiddleware::test_remove_proxy_without_credentials"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-08-02 23:15:49+00:00
|
bsd-3-clause
| 5,420 |
|
scrapy__scrapy-5917
|
diff --git a/scrapy/http/response/text.py b/scrapy/http/response/text.py
index 73bb811de..d580a7876 100644
--- a/scrapy/http/response/text.py
+++ b/scrapy/http/response/text.py
@@ -100,11 +100,13 @@ class TextResponse(Response):
@memoizemethod_noargs
def _headers_encoding(self):
content_type = self.headers.get(b"Content-Type", b"")
- return http_content_type_encoding(to_unicode(content_type))
+ return http_content_type_encoding(to_unicode(content_type, encoding="latin-1"))
def _body_inferred_encoding(self):
if self._cached_benc is None:
- content_type = to_unicode(self.headers.get(b"Content-Type", b""))
+ content_type = to_unicode(
+ self.headers.get(b"Content-Type", b""), encoding="latin-1"
+ )
benc, ubody = html_to_unicode(
content_type,
self.body,
diff --git a/scrapy/responsetypes.py b/scrapy/responsetypes.py
index f01e9096c..58884f21a 100644
--- a/scrapy/responsetypes.py
+++ b/scrapy/responsetypes.py
@@ -51,7 +51,9 @@ class ResponseTypes:
header"""
if content_encoding:
return Response
- mimetype = to_unicode(content_type).split(";")[0].strip().lower()
+ mimetype = (
+ to_unicode(content_type, encoding="latin-1").split(";")[0].strip().lower()
+ )
return self.from_mimetype(mimetype)
def from_content_disposition(self, content_disposition):
|
scrapy/scrapy
|
b50c032ee9a75d1c9b42f1126637fdc655b141a8
|
diff --git a/tests/test_http_response.py b/tests/test_http_response.py
index dbc9f1fef..a05b702aa 100644
--- a/tests/test_http_response.py
+++ b/tests/test_http_response.py
@@ -448,6 +448,13 @@ class TextResponseTest(BaseResponseTest):
body=codecs.BOM_UTF8 + b"\xc2\xa3",
headers={"Content-type": ["text/html; charset=cp1251"]},
)
+ r9 = self.response_class(
+ "http://www.example.com",
+ body=b"\x80",
+ headers={
+ "Content-type": [b"application/x-download; filename=\x80dummy.txt"]
+ },
+ )
self.assertEqual(r1._headers_encoding(), "utf-8")
self.assertEqual(r2._headers_encoding(), None)
@@ -458,9 +465,12 @@ class TextResponseTest(BaseResponseTest):
self.assertEqual(r4._headers_encoding(), None)
self.assertEqual(r5._headers_encoding(), None)
self.assertEqual(r8._headers_encoding(), "cp1251")
+ self.assertEqual(r9._headers_encoding(), None)
self.assertEqual(r8._declared_encoding(), "utf-8")
+ self.assertEqual(r9._declared_encoding(), None)
self._assert_response_encoding(r5, "utf-8")
self._assert_response_encoding(r8, "utf-8")
+ self._assert_response_encoding(r9, "cp1252")
assert (
r4._body_inferred_encoding() is not None
and r4._body_inferred_encoding() != "ascii"
@@ -470,6 +480,7 @@ class TextResponseTest(BaseResponseTest):
self._assert_response_values(r3, "iso-8859-1", "\xa3")
self._assert_response_values(r6, "gb18030", "\u2015")
self._assert_response_values(r7, "gb18030", "\u2015")
+ self._assert_response_values(r9, "cp1252", "€")
# TextResponse (and subclasses) must be passed a encoding when instantiating with unicode bodies
self.assertRaises(
diff --git a/tests/test_responsetypes.py b/tests/test_responsetypes.py
index 859960518..6e1ed82f0 100644
--- a/tests/test_responsetypes.py
+++ b/tests/test_responsetypes.py
@@ -42,6 +42,7 @@ class ResponseTypesTest(unittest.TestCase):
("application/octet-stream", Response),
("application/x-json; encoding=UTF8;charset=UTF-8", TextResponse),
("application/json-amazonui-streaming;charset=UTF-8", TextResponse),
+ (b"application/x-download; filename=\x80dummy.txt", Response),
]
for source, cls in mappings:
retcls = responsetypes.from_content_type(source)
|
Exception with non-UTF-8 Content-Type
<!--
Thanks for taking an interest in Scrapy!
If you have a question that starts with "How to...", please see the Scrapy Community page: https://scrapy.org/community/.
The GitHub issue tracker's purpose is to deal with bug reports and feature requests for the project itself.
Keep in mind that by filing an issue, you are expected to comply with Scrapy's Code of Conduct, including treating everyone with respect: https://github.com/scrapy/scrapy/blob/master/CODE_OF_CONDUCT.md
The following is a suggested template to structure your issue, you can find more guidelines at https://doc.scrapy.org/en/latest/contributing.html#reporting-bugs
-->
### Description
I am trying to download a document from the link http://pravo.gov.ru/proxy/ips/?savertf=&link_id=0&nd=128284801&intelsearch=&firstDoc=1&page=all
Everything works fine in the browser, but when I try to automate this process through scrapy, everything break down.
### Steps to Reproduce
1.Create new spider `scrapy genspider test pravo.gov.ru`
2. Paste code
```
import scrapy
class TestSpider(scrapy.Spider):
name = "test"
allowed_domains = ["pravo.gov.ru"]
start_urls = ["http://pravo.gov.ru/proxy/ips/"]
def parse(self, response):
yield scrapy.Request(
self.start_urls[0] + f'?savertf=&link_id=0&nd=128284801&intelsearch=&firstDoc=1&page=all',
callback=self.test_parse,
encoding='cp1251') #The same behavior without this line
def test_parse(self, response):
pass
```
4. run
***OR***
run `scrapy fetch http://pravo.gov.ru/proxy/ips/?savertf=&link_id=0&nd=128284801&intelsearch=&firstDoc=1&page=all""`
**Expected behavior:** The document on the link is downloaded
**Actual behavior:**
2023-04-28 00:07:35 [scrapy.core.scraper] ERROR: Error downloading <GET http://pravo.gov.ru/proxy/ips/?savertf=&link_id=0&nd=128284801&intelsearch=&fir
stDoc=1&page=all>
Traceback (most recent call last):
File "C:\Users\Admin\AppData\Roaming\Python\Python310\site-packages\twisted\internet\defer.py", line 1693, in _inlineCallbacks
result = context.run(
File "C:\Users\Admin\AppData\Roaming\Python\Python310\site-packages\twisted\python\failure.py", line 518, in throwExceptionIntoGenerator
return g.throw(self.type, self.value, self.tb)
File "C:\Users\Admin\AppData\Roaming\Python\Python310\site-packages\scrapy\core\downloader\middleware.py", line 52, in process_request
return (yield download_func(request=request, spider=spider))
File "C:\Users\Admin\AppData\Roaming\Python\Python310\site-packages\twisted\internet\defer.py", line 892, in _runCallbacks
current.result = callback( # type: ignore[misc]
File "C:\Users\Admin\AppData\Roaming\Python\Python310\site-packages\scrapy\core\downloader\handlers\http11.py", line 501, in _cb_bodydone
respcls = responsetypes.from_args(headers=headers, url=url, body=result["body"])
File "C:\Users\Admin\AppData\Roaming\Python\Python310\site-packages\scrapy\responsetypes.py", line 113, in from_args
cls = self.from_headers(headers)
File "C:\Users\Admin\AppData\Roaming\Python\Python310\site-packages\scrapy\responsetypes.py", line 75, in from_headers
cls = self.from_content_type(
File "C:\Users\Admin\AppData\Roaming\Python\Python310\site-packages\scrapy\responsetypes.py", line 55, in from_content_type
mimetype = to_unicode(content_type).split(";")[0].strip().lower()
File "C:\Users\Admin\AppData\Roaming\Python\Python310\site-packages\scrapy\utils\python.py", line 97, in to_unicode
return text.decode(encoding, errors)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xcf in position 33: invalid continuation byte
**Reproduces how often:** 100% runs
### Versions
Scrapy : 2.8.0
lxml : 4.9.2.0
libxml2 : 2.9.12
cssselect : 1.2.0
parsel : 1.8.1
w3lib : 2.1.1
Twisted : 22.10.0
Python : 3.10.9 | packaged by Anaconda, Inc. | (main, Mar 1 2023, 18:18:15) [MSC v.1916 64 bit (AMD64)]
pyOpenSSL : 23.1.1 (OpenSSL 3.1.0 14 Mar 2023)
cryptography : 40.0.2
Platform : Windows-10-10.0.19044-SP0
### Additional context
These documents are encoded in cp1251 encoding, which is clearly indicated in their headers :
Content-Transfer-Encoding: quoted-printable
Content-Type: text/html; charset="windows-1251"
The same behavior when trying to save a file using FilesPipeline
|
0.0
|
b50c032ee9a75d1c9b42f1126637fdc655b141a8
|
[
"tests/test_http_response.py::TextResponseTest::test_encoding",
"tests/test_http_response.py::HtmlResponseTest::test_encoding",
"tests/test_http_response.py::XmlResponseTest::test_encoding",
"tests/test_http_response.py::CustomResponseTest::test_encoding",
"tests/test_responsetypes.py::ResponseTypesTest::test_from_content_type"
] |
[
"tests/test_http_response.py::BaseResponseTest::test_copy",
"tests/test_http_response.py::BaseResponseTest::test_copy_cb_kwargs",
"tests/test_http_response.py::BaseResponseTest::test_copy_inherited_classes",
"tests/test_http_response.py::BaseResponseTest::test_copy_meta",
"tests/test_http_response.py::BaseResponseTest::test_follow_None_url",
"tests/test_http_response.py::BaseResponseTest::test_follow_all_absolute",
"tests/test_http_response.py::BaseResponseTest::test_follow_all_empty",
"tests/test_http_response.py::BaseResponseTest::test_follow_all_flags",
"tests/test_http_response.py::BaseResponseTest::test_follow_all_invalid",
"tests/test_http_response.py::BaseResponseTest::test_follow_all_links",
"tests/test_http_response.py::BaseResponseTest::test_follow_all_relative",
"tests/test_http_response.py::BaseResponseTest::test_follow_all_whitespace",
"tests/test_http_response.py::BaseResponseTest::test_follow_all_whitespace_links",
"tests/test_http_response.py::BaseResponseTest::test_follow_flags",
"tests/test_http_response.py::BaseResponseTest::test_follow_link",
"tests/test_http_response.py::BaseResponseTest::test_follow_url_absolute",
"tests/test_http_response.py::BaseResponseTest::test_follow_url_relative",
"tests/test_http_response.py::BaseResponseTest::test_follow_whitespace_link",
"tests/test_http_response.py::BaseResponseTest::test_follow_whitespace_url",
"tests/test_http_response.py::BaseResponseTest::test_immutable_attributes",
"tests/test_http_response.py::BaseResponseTest::test_init",
"tests/test_http_response.py::BaseResponseTest::test_replace",
"tests/test_http_response.py::BaseResponseTest::test_shortcut_attributes",
"tests/test_http_response.py::BaseResponseTest::test_unavailable_cb_kwargs",
"tests/test_http_response.py::BaseResponseTest::test_unavailable_meta",
"tests/test_http_response.py::BaseResponseTest::test_urljoin",
"tests/test_http_response.py::TextResponseTest::test_bom_is_removed_from_body",
"tests/test_http_response.py::TextResponseTest::test_cache_json_response",
"tests/test_http_response.py::TextResponseTest::test_copy",
"tests/test_http_response.py::TextResponseTest::test_copy_cb_kwargs",
"tests/test_http_response.py::TextResponseTest::test_copy_inherited_classes",
"tests/test_http_response.py::TextResponseTest::test_copy_meta",
"tests/test_http_response.py::TextResponseTest::test_declared_encoding_invalid",
"tests/test_http_response.py::TextResponseTest::test_follow_None_url",
"tests/test_http_response.py::TextResponseTest::test_follow_all_absolute",
"tests/test_http_response.py::TextResponseTest::test_follow_all_css",
"tests/test_http_response.py::TextResponseTest::test_follow_all_css_skip_invalid",
"tests/test_http_response.py::TextResponseTest::test_follow_all_empty",
"tests/test_http_response.py::TextResponseTest::test_follow_all_flags",
"tests/test_http_response.py::TextResponseTest::test_follow_all_invalid",
"tests/test_http_response.py::TextResponseTest::test_follow_all_links",
"tests/test_http_response.py::TextResponseTest::test_follow_all_relative",
"tests/test_http_response.py::TextResponseTest::test_follow_all_too_many_arguments",
"tests/test_http_response.py::TextResponseTest::test_follow_all_whitespace",
"tests/test_http_response.py::TextResponseTest::test_follow_all_whitespace_links",
"tests/test_http_response.py::TextResponseTest::test_follow_all_xpath",
"tests/test_http_response.py::TextResponseTest::test_follow_all_xpath_skip_invalid",
"tests/test_http_response.py::TextResponseTest::test_follow_encoding",
"tests/test_http_response.py::TextResponseTest::test_follow_flags",
"tests/test_http_response.py::TextResponseTest::test_follow_link",
"tests/test_http_response.py::TextResponseTest::test_follow_selector",
"tests/test_http_response.py::TextResponseTest::test_follow_selector_attribute",
"tests/test_http_response.py::TextResponseTest::test_follow_selector_invalid",
"tests/test_http_response.py::TextResponseTest::test_follow_selector_list",
"tests/test_http_response.py::TextResponseTest::test_follow_selector_no_href",
"tests/test_http_response.py::TextResponseTest::test_follow_url_absolute",
"tests/test_http_response.py::TextResponseTest::test_follow_url_relative",
"tests/test_http_response.py::TextResponseTest::test_follow_whitespace_link",
"tests/test_http_response.py::TextResponseTest::test_follow_whitespace_selector",
"tests/test_http_response.py::TextResponseTest::test_follow_whitespace_url",
"tests/test_http_response.py::TextResponseTest::test_immutable_attributes",
"tests/test_http_response.py::TextResponseTest::test_init",
"tests/test_http_response.py::TextResponseTest::test_invalid_utf8_encoded_body_with_valid_utf8_BOM",
"tests/test_http_response.py::TextResponseTest::test_json_response",
"tests/test_http_response.py::TextResponseTest::test_replace",
"tests/test_http_response.py::TextResponseTest::test_replace_wrong_encoding",
"tests/test_http_response.py::TextResponseTest::test_selector",
"tests/test_http_response.py::TextResponseTest::test_selector_shortcuts",
"tests/test_http_response.py::TextResponseTest::test_selector_shortcuts_kwargs",
"tests/test_http_response.py::TextResponseTest::test_shortcut_attributes",
"tests/test_http_response.py::TextResponseTest::test_unavailable_cb_kwargs",
"tests/test_http_response.py::TextResponseTest::test_unavailable_meta",
"tests/test_http_response.py::TextResponseTest::test_unicode_body",
"tests/test_http_response.py::TextResponseTest::test_unicode_url",
"tests/test_http_response.py::TextResponseTest::test_urljoin",
"tests/test_http_response.py::TextResponseTest::test_urljoin_with_base_url",
"tests/test_http_response.py::TextResponseTest::test_utf16",
"tests/test_http_response.py::HtmlResponseTest::test_bom_is_removed_from_body",
"tests/test_http_response.py::HtmlResponseTest::test_cache_json_response",
"tests/test_http_response.py::HtmlResponseTest::test_copy",
"tests/test_http_response.py::HtmlResponseTest::test_copy_cb_kwargs",
"tests/test_http_response.py::HtmlResponseTest::test_copy_inherited_classes",
"tests/test_http_response.py::HtmlResponseTest::test_copy_meta",
"tests/test_http_response.py::HtmlResponseTest::test_declared_encoding_invalid",
"tests/test_http_response.py::HtmlResponseTest::test_follow_None_url",
"tests/test_http_response.py::HtmlResponseTest::test_follow_all_absolute",
"tests/test_http_response.py::HtmlResponseTest::test_follow_all_css",
"tests/test_http_response.py::HtmlResponseTest::test_follow_all_css_skip_invalid",
"tests/test_http_response.py::HtmlResponseTest::test_follow_all_empty",
"tests/test_http_response.py::HtmlResponseTest::test_follow_all_flags",
"tests/test_http_response.py::HtmlResponseTest::test_follow_all_invalid",
"tests/test_http_response.py::HtmlResponseTest::test_follow_all_links",
"tests/test_http_response.py::HtmlResponseTest::test_follow_all_relative",
"tests/test_http_response.py::HtmlResponseTest::test_follow_all_too_many_arguments",
"tests/test_http_response.py::HtmlResponseTest::test_follow_all_whitespace",
"tests/test_http_response.py::HtmlResponseTest::test_follow_all_whitespace_links",
"tests/test_http_response.py::HtmlResponseTest::test_follow_all_xpath",
"tests/test_http_response.py::HtmlResponseTest::test_follow_all_xpath_skip_invalid",
"tests/test_http_response.py::HtmlResponseTest::test_follow_encoding",
"tests/test_http_response.py::HtmlResponseTest::test_follow_flags",
"tests/test_http_response.py::HtmlResponseTest::test_follow_link",
"tests/test_http_response.py::HtmlResponseTest::test_follow_selector",
"tests/test_http_response.py::HtmlResponseTest::test_follow_selector_attribute",
"tests/test_http_response.py::HtmlResponseTest::test_follow_selector_invalid",
"tests/test_http_response.py::HtmlResponseTest::test_follow_selector_list",
"tests/test_http_response.py::HtmlResponseTest::test_follow_selector_no_href",
"tests/test_http_response.py::HtmlResponseTest::test_follow_url_absolute",
"tests/test_http_response.py::HtmlResponseTest::test_follow_url_relative",
"tests/test_http_response.py::HtmlResponseTest::test_follow_whitespace_link",
"tests/test_http_response.py::HtmlResponseTest::test_follow_whitespace_selector",
"tests/test_http_response.py::HtmlResponseTest::test_follow_whitespace_url",
"tests/test_http_response.py::HtmlResponseTest::test_html5_meta_charset",
"tests/test_http_response.py::HtmlResponseTest::test_html_encoding",
"tests/test_http_response.py::HtmlResponseTest::test_immutable_attributes",
"tests/test_http_response.py::HtmlResponseTest::test_init",
"tests/test_http_response.py::HtmlResponseTest::test_invalid_utf8_encoded_body_with_valid_utf8_BOM",
"tests/test_http_response.py::HtmlResponseTest::test_json_response",
"tests/test_http_response.py::HtmlResponseTest::test_replace",
"tests/test_http_response.py::HtmlResponseTest::test_replace_wrong_encoding",
"tests/test_http_response.py::HtmlResponseTest::test_selector",
"tests/test_http_response.py::HtmlResponseTest::test_selector_shortcuts",
"tests/test_http_response.py::HtmlResponseTest::test_selector_shortcuts_kwargs",
"tests/test_http_response.py::HtmlResponseTest::test_shortcut_attributes",
"tests/test_http_response.py::HtmlResponseTest::test_unavailable_cb_kwargs",
"tests/test_http_response.py::HtmlResponseTest::test_unavailable_meta",
"tests/test_http_response.py::HtmlResponseTest::test_unicode_body",
"tests/test_http_response.py::HtmlResponseTest::test_unicode_url",
"tests/test_http_response.py::HtmlResponseTest::test_urljoin",
"tests/test_http_response.py::HtmlResponseTest::test_urljoin_with_base_url",
"tests/test_http_response.py::HtmlResponseTest::test_utf16",
"tests/test_http_response.py::XmlResponseTest::test_bom_is_removed_from_body",
"tests/test_http_response.py::XmlResponseTest::test_cache_json_response",
"tests/test_http_response.py::XmlResponseTest::test_copy",
"tests/test_http_response.py::XmlResponseTest::test_copy_cb_kwargs",
"tests/test_http_response.py::XmlResponseTest::test_copy_inherited_classes",
"tests/test_http_response.py::XmlResponseTest::test_copy_meta",
"tests/test_http_response.py::XmlResponseTest::test_declared_encoding_invalid",
"tests/test_http_response.py::XmlResponseTest::test_follow_None_url",
"tests/test_http_response.py::XmlResponseTest::test_follow_all_absolute",
"tests/test_http_response.py::XmlResponseTest::test_follow_all_css",
"tests/test_http_response.py::XmlResponseTest::test_follow_all_css_skip_invalid",
"tests/test_http_response.py::XmlResponseTest::test_follow_all_empty",
"tests/test_http_response.py::XmlResponseTest::test_follow_all_flags",
"tests/test_http_response.py::XmlResponseTest::test_follow_all_invalid",
"tests/test_http_response.py::XmlResponseTest::test_follow_all_links",
"tests/test_http_response.py::XmlResponseTest::test_follow_all_relative",
"tests/test_http_response.py::XmlResponseTest::test_follow_all_too_many_arguments",
"tests/test_http_response.py::XmlResponseTest::test_follow_all_whitespace",
"tests/test_http_response.py::XmlResponseTest::test_follow_all_whitespace_links",
"tests/test_http_response.py::XmlResponseTest::test_follow_all_xpath",
"tests/test_http_response.py::XmlResponseTest::test_follow_all_xpath_skip_invalid",
"tests/test_http_response.py::XmlResponseTest::test_follow_encoding",
"tests/test_http_response.py::XmlResponseTest::test_follow_flags",
"tests/test_http_response.py::XmlResponseTest::test_follow_link",
"tests/test_http_response.py::XmlResponseTest::test_follow_selector",
"tests/test_http_response.py::XmlResponseTest::test_follow_selector_attribute",
"tests/test_http_response.py::XmlResponseTest::test_follow_selector_invalid",
"tests/test_http_response.py::XmlResponseTest::test_follow_selector_list",
"tests/test_http_response.py::XmlResponseTest::test_follow_selector_no_href",
"tests/test_http_response.py::XmlResponseTest::test_follow_url_absolute",
"tests/test_http_response.py::XmlResponseTest::test_follow_url_relative",
"tests/test_http_response.py::XmlResponseTest::test_follow_whitespace_link",
"tests/test_http_response.py::XmlResponseTest::test_follow_whitespace_selector",
"tests/test_http_response.py::XmlResponseTest::test_follow_whitespace_url",
"tests/test_http_response.py::XmlResponseTest::test_immutable_attributes",
"tests/test_http_response.py::XmlResponseTest::test_init",
"tests/test_http_response.py::XmlResponseTest::test_invalid_utf8_encoded_body_with_valid_utf8_BOM",
"tests/test_http_response.py::XmlResponseTest::test_json_response",
"tests/test_http_response.py::XmlResponseTest::test_replace",
"tests/test_http_response.py::XmlResponseTest::test_replace_encoding",
"tests/test_http_response.py::XmlResponseTest::test_replace_wrong_encoding",
"tests/test_http_response.py::XmlResponseTest::test_selector",
"tests/test_http_response.py::XmlResponseTest::test_selector_shortcuts",
"tests/test_http_response.py::XmlResponseTest::test_selector_shortcuts_kwargs",
"tests/test_http_response.py::XmlResponseTest::test_shortcut_attributes",
"tests/test_http_response.py::XmlResponseTest::test_unavailable_cb_kwargs",
"tests/test_http_response.py::XmlResponseTest::test_unavailable_meta",
"tests/test_http_response.py::XmlResponseTest::test_unicode_body",
"tests/test_http_response.py::XmlResponseTest::test_unicode_url",
"tests/test_http_response.py::XmlResponseTest::test_urljoin",
"tests/test_http_response.py::XmlResponseTest::test_urljoin_with_base_url",
"tests/test_http_response.py::XmlResponseTest::test_utf16",
"tests/test_http_response.py::XmlResponseTest::test_xml_encoding",
"tests/test_http_response.py::CustomResponseTest::test_bom_is_removed_from_body",
"tests/test_http_response.py::CustomResponseTest::test_cache_json_response",
"tests/test_http_response.py::CustomResponseTest::test_copy",
"tests/test_http_response.py::CustomResponseTest::test_copy_cb_kwargs",
"tests/test_http_response.py::CustomResponseTest::test_copy_inherited_classes",
"tests/test_http_response.py::CustomResponseTest::test_copy_meta",
"tests/test_http_response.py::CustomResponseTest::test_declared_encoding_invalid",
"tests/test_http_response.py::CustomResponseTest::test_follow_None_url",
"tests/test_http_response.py::CustomResponseTest::test_follow_all_absolute",
"tests/test_http_response.py::CustomResponseTest::test_follow_all_css",
"tests/test_http_response.py::CustomResponseTest::test_follow_all_css_skip_invalid",
"tests/test_http_response.py::CustomResponseTest::test_follow_all_empty",
"tests/test_http_response.py::CustomResponseTest::test_follow_all_flags",
"tests/test_http_response.py::CustomResponseTest::test_follow_all_invalid",
"tests/test_http_response.py::CustomResponseTest::test_follow_all_links",
"tests/test_http_response.py::CustomResponseTest::test_follow_all_relative",
"tests/test_http_response.py::CustomResponseTest::test_follow_all_too_many_arguments",
"tests/test_http_response.py::CustomResponseTest::test_follow_all_whitespace",
"tests/test_http_response.py::CustomResponseTest::test_follow_all_whitespace_links",
"tests/test_http_response.py::CustomResponseTest::test_follow_all_xpath",
"tests/test_http_response.py::CustomResponseTest::test_follow_all_xpath_skip_invalid",
"tests/test_http_response.py::CustomResponseTest::test_follow_encoding",
"tests/test_http_response.py::CustomResponseTest::test_follow_flags",
"tests/test_http_response.py::CustomResponseTest::test_follow_link",
"tests/test_http_response.py::CustomResponseTest::test_follow_selector",
"tests/test_http_response.py::CustomResponseTest::test_follow_selector_attribute",
"tests/test_http_response.py::CustomResponseTest::test_follow_selector_invalid",
"tests/test_http_response.py::CustomResponseTest::test_follow_selector_list",
"tests/test_http_response.py::CustomResponseTest::test_follow_selector_no_href",
"tests/test_http_response.py::CustomResponseTest::test_follow_url_absolute",
"tests/test_http_response.py::CustomResponseTest::test_follow_url_relative",
"tests/test_http_response.py::CustomResponseTest::test_follow_whitespace_link",
"tests/test_http_response.py::CustomResponseTest::test_follow_whitespace_selector",
"tests/test_http_response.py::CustomResponseTest::test_follow_whitespace_url",
"tests/test_http_response.py::CustomResponseTest::test_immutable_attributes",
"tests/test_http_response.py::CustomResponseTest::test_init",
"tests/test_http_response.py::CustomResponseTest::test_invalid_utf8_encoded_body_with_valid_utf8_BOM",
"tests/test_http_response.py::CustomResponseTest::test_json_response",
"tests/test_http_response.py::CustomResponseTest::test_replace",
"tests/test_http_response.py::CustomResponseTest::test_replace_wrong_encoding",
"tests/test_http_response.py::CustomResponseTest::test_selector",
"tests/test_http_response.py::CustomResponseTest::test_selector_shortcuts",
"tests/test_http_response.py::CustomResponseTest::test_selector_shortcuts_kwargs",
"tests/test_http_response.py::CustomResponseTest::test_shortcut_attributes",
"tests/test_http_response.py::CustomResponseTest::test_unavailable_cb_kwargs",
"tests/test_http_response.py::CustomResponseTest::test_unavailable_meta",
"tests/test_http_response.py::CustomResponseTest::test_unicode_body",
"tests/test_http_response.py::CustomResponseTest::test_unicode_url",
"tests/test_http_response.py::CustomResponseTest::test_urljoin",
"tests/test_http_response.py::CustomResponseTest::test_urljoin_with_base_url",
"tests/test_http_response.py::CustomResponseTest::test_utf16",
"tests/test_responsetypes.py::ResponseTypesTest::test_custom_mime_types_loaded",
"tests/test_responsetypes.py::ResponseTypesTest::test_from_args",
"tests/test_responsetypes.py::ResponseTypesTest::test_from_body",
"tests/test_responsetypes.py::ResponseTypesTest::test_from_content_disposition",
"tests/test_responsetypes.py::ResponseTypesTest::test_from_filename",
"tests/test_responsetypes.py::ResponseTypesTest::test_from_headers"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-05-02 15:56:07+00:00
|
bsd-3-clause
| 5,421 |
|
scrapy__scrapyd-432
|
diff --git a/docs/install.rst b/docs/install.rst
index 7ca72d6..9cc265c 100644
--- a/docs/install.rst
+++ b/docs/install.rst
@@ -13,7 +13,7 @@ Scrapyd depends on the following libraries, but the installation process
takes care of installing the missing ones:
* Python 3.6 or above
-* Scrapy 1.2 or above
+* Scrapy 2.0 or above
* Twisted 17.9 or above
Installing Scrapyd (generic way)
diff --git a/setup.py b/setup.py
index 2b1c838..6288079 100644
--- a/setup.py
+++ b/setup.py
@@ -46,7 +46,7 @@ setup_args = {
if using_setuptools:
setup_args['install_requires'] = [
'Twisted>=17.9',
- 'Scrapy>=1.2.0',
+ 'Scrapy>=2.0.0',
'six'
]
setup_args['entry_points'] = {'console_scripts': [
|
scrapy/scrapyd
|
b3f5f9e9af93c3bb9c85b0709e3475b4fbf8d304
|
diff --git a/reqs/requirements-latest.txt b/reqs/requirements-latest.txt
index 438463a..8910a08 100644
--- a/reqs/requirements-latest.txt
+++ b/reqs/requirements-latest.txt
@@ -1,2 +1,2 @@
-Scrapy>=1.1
+Scrapy>=2.0
twisted
|
Replace `FEED_URI` and `FEED_FORMAT` with `FEEDS` in feedexporter
Running Scrapyd + Scrapy 2.5 results in following warning:
```
scrapy/extensions/feedexport.py:247: ScrapyDeprecationWarning: The `FEED_URI` and `FEED_FORMAT` settings have been deprecated in favor of the `FEEDS` setting. Please see the `FEEDS` setting docs for more details
exporter = cls(crawler)
```
[FEEDS were added in 2.1](https://docs.scrapy.org/en/latest/topics/feed-exports.html#feeds). We should pay attention to this warning. This will break compatibility with Scrapy below 2, so would be recommended to aslo update setup.py with note we require > 2.
|
0.0
|
b3f5f9e9af93c3bb9c85b0709e3475b4fbf8d304
|
[
"scrapyd/tests/test_endpoints.py::TestEndpoint::test_auth"
] |
[
"scrapyd/tests/test_webservice.py::TestWebservice::test_list_versions",
"scrapyd/tests/test_webservice.py::TestWebservice::test_schedule",
"scrapyd/tests/test_webservice.py::TestWebservice::test_list_projects",
"scrapyd/tests/test_webservice.py::TestWebservice::test_addversion",
"scrapyd/tests/test_webservice.py::TestWebservice::test_list_spiders",
"scrapyd/tests/test_webservice.py::TestWebservice::test_delete_project",
"scrapyd/tests/test_webservice.py::TestWebservice::test_delete_version",
"scrapyd/tests/test_scheduler.py::SpiderSchedulerTest::test_interface",
"scrapyd/tests/test_scheduler.py::SpiderSchedulerTest::test_list_update_projects",
"scrapyd/tests/test_scheduler.py::SpiderSchedulerTest::test_schedule",
"scrapyd/tests/test_jobstorage.py::SqliteJobsStorageTest::test_add",
"scrapyd/tests/test_jobstorage.py::SqliteJobsStorageTest::test_iter",
"scrapyd/tests/test_jobstorage.py::SqliteJobsStorageTest::test_interface",
"scrapyd/tests/test_jobstorage.py::MemoryJobStorageTest::test_interface",
"scrapyd/tests/test_jobstorage.py::MemoryJobStorageTest::test_add",
"scrapyd/tests/test_jobstorage.py::MemoryJobStorageTest::test_len",
"scrapyd/tests/test_jobstorage.py::MemoryJobStorageTest::test_iter",
"scrapyd/tests/test_poller.py::QueuePollerTest::test_poll_next",
"scrapyd/tests/test_poller.py::QueuePollerTest::test_interface",
"scrapyd/tests/test_endpoints.py::TestEndpoint::test_root",
"scrapyd/tests/test_endpoints.py::TestEndpoint::test_addversion_and_delversion",
"scrapyd/tests/test_endpoints.py::TestEndpoint::test_spider_list_project_no_egg",
"scrapyd/tests/test_endpoints.py::TestEndpoint::test_spider_list_no_project",
"scrapyd/tests/test_endpoints.py::TestEndpoint::test_failed_settings",
"scrapyd/tests/test_endpoints.py::TestEndpoint::test_launch_spider_get",
"scrapyd/tests/test_endpoints.py::TestEndpoint::test_urljoin",
"scrapyd/tests/test_environ.py::EnvironmentTest::test_interface",
"scrapyd/tests/test_environ.py::EnvironmentTest::test_get_environment_with_eggfile",
"scrapyd/tests/test_environ.py::EnvironmentTest::test_get_environment_with_no_items_dir",
"scrapyd/tests/test_eggstorage.py::TestConfigureEggStorage::test_egg_config_application",
"scrapyd/tests/test_eggstorage.py::EggStorageTest::test_put_get_list_delete",
"scrapyd/tests/test_eggstorage.py::EggStorageTest::test_interface",
"scrapyd/tests/test_sqlite.py::SqliteFinishedJobsTest::test_clear_keep_2",
"scrapyd/tests/test_sqlite.py::SqliteFinishedJobsTest::test__iter__",
"scrapyd/tests/test_sqlite.py::SqliteFinishedJobsTest::test_clear_all",
"scrapyd/tests/test_sqlite.py::SqliteFinishedJobsTest::test_add",
"scrapyd/tests/test_sqlite.py::JsonSqlitePriorityQueueTest::test_types",
"scrapyd/tests/test_sqlite.py::JsonSqlitePriorityQueueTest::test_multiple",
"scrapyd/tests/test_sqlite.py::JsonSqlitePriorityQueueTest::test_empty",
"scrapyd/tests/test_sqlite.py::JsonSqlitePriorityQueueTest::test_one",
"scrapyd/tests/test_sqlite.py::JsonSqlitePriorityQueueTest::test_priority",
"scrapyd/tests/test_sqlite.py::JsonSqlitePriorityQueueTest::test_iter_len_clear",
"scrapyd/tests/test_sqlite.py::JsonSqlitePriorityQueueTest::test_remove",
"scrapyd/tests/test_sqlite.py::JsonSqliteDictTest::test_keyerror",
"scrapyd/tests/test_sqlite.py::JsonSqliteDictTest::test_basic_types",
"scrapyd/tests/test_sqlite.py::JsonSqliteDictTest::test_replace",
"scrapyd/tests/test_sqlite.py::JsonSqliteDictTest::test_in",
"scrapyd/tests/test_website.py::TestWebsite::test_render_jobs",
"scrapyd/tests/test_website.py::TestWebsite::test_render_home",
"scrapyd/tests/test_spiderqueue.py::SpiderQueueTest::test_interface",
"scrapyd/tests/test_spiderqueue.py::SpiderQueueTest::test_list",
"scrapyd/tests/test_spiderqueue.py::SpiderQueueTest::test_clear",
"scrapyd/tests/test_spiderqueue.py::SpiderQueueTest::test_add_pop_count",
"scrapyd/tests/test_utils.py::UtilsTest::test_get_crawl_args",
"scrapyd/tests/test_utils.py::UtilsTest::test_get_crawl_args_with_settings",
"scrapyd/tests/test_utils.py::GetSpiderListTest::test_get_spider_list_unicode",
"scrapyd/tests/test_utils.py::GetSpiderListTest::test_get_spider_list",
"scrapyd/tests/test_utils.py::GetSpiderListTest::test_failed_spider_list",
"scrapyd/tests/test_dont_load_settings.py::SettingsSafeModulesTest::test_modules_that_shouldnt_load_settings"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-02-22 20:22:23+00:00
|
bsd-3-clause
| 5,422 |
|
scrapy__scrapyd-467
|
diff --git a/docs/api.rst b/docs/api.rst
index 085f345..b896cf7 100644
--- a/docs/api.rst
+++ b/docs/api.rst
@@ -212,7 +212,9 @@ Example response::
"id": "2f16646cfcaf11e1b0090800272a6d06",
"project": "myproject", "spider": "spider3",
"start_time": "2012-09-12 10:14:03.594664",
- "end_time": "2012-09-12 10:24:03.594664"
+ "end_time": "2012-09-12 10:24:03.594664",
+ "log_url": "/logs/myproject/spider3/2f16646cfcaf11e1b0090800272a6d06.log",
+ "items_url": "/items/myproject/spider3/2f16646cfcaf11e1b0090800272a6d06.jl"
}
]
}
diff --git a/docs/news.rst b/docs/news.rst
index 1e53ed8..6256801 100644
--- a/docs/news.rst
+++ b/docs/news.rst
@@ -9,7 +9,8 @@ Unreleased
Added
~~~~~
-- Python 3.1 support.
+- Add ``item_url`` and ``log_url`` to the response from the listjobs.json webservice. (@mxdev88)
+- Python 3.11 support.
Removed
~~~~~~~
@@ -20,9 +21,9 @@ Removed
Fixed
~~~~~
-- Use ``packaging.version.Version`` instead of ``distutils.LooseVersion``.
-- Print Scrapyd's version instead of Twisted's version with ``--version`` (``-v``) flag.
-- Override Scrapy's ``LOG_STDOUT`` to ``False`` to suppress logging output for listspiders.json webservice.
+- Use ``packaging.version.Version`` instead of ``distutils.LooseVersion``. (@pawelmhm)
+- Print Scrapyd's version instead of Twisted's version with ``--version`` (``-v``) flag. (@niuguy)
+- Override Scrapy's ``LOG_STDOUT`` to ``False`` to suppress logging output for listspiders.json webservice. (@Lucioric2000)
1.3.0 (2022-01-12)
------------------
diff --git a/scrapyd/jobstorage.py b/scrapyd/jobstorage.py
index 565b12d..ffaa950 100644
--- a/scrapyd/jobstorage.py
+++ b/scrapyd/jobstorage.py
@@ -7,6 +7,14 @@ from scrapyd.interfaces import IJobStorage
from scrapyd.sqlite import SqliteFinishedJobs
+def job_log_url(job):
+ return f"/logs/{job.project}/{job.spider}/{job.job}.log"
+
+
+def job_items_url(job):
+ return f"/items/{job.project}/{job.spider}/{job.job}.jl"
+
+
class Job(object):
def __init__(self, project, spider, job=None, start_time=None, end_time=None):
self.project = project
diff --git a/scrapyd/webservice.py b/scrapyd/webservice.py
index b345bc2..f9c2320 100644
--- a/scrapyd/webservice.py
+++ b/scrapyd/webservice.py
@@ -5,6 +5,7 @@ from io import BytesIO
from twisted.python import log
+from scrapyd.jobstorage import job_items_url, job_log_url
from scrapyd.utils import JsonResource, UtilsCache, get_spider_list, native_stringify_dict
@@ -148,7 +149,9 @@ class ListJobs(WsResource):
"project": s.project,
"spider": s.spider, "id": s.job,
"start_time": str(s.start_time),
- "end_time": str(s.end_time)
+ "end_time": str(s.end_time),
+ "log_url": job_log_url(s),
+ "items_url": job_items_url(s),
} for s in self.root.launcher.finished
if project is None or s.project == project
]
diff --git a/scrapyd/website.py b/scrapyd/website.py
index 49bf5c6..f71842e 100644
--- a/scrapyd/website.py
+++ b/scrapyd/website.py
@@ -7,6 +7,7 @@ from twisted.application.service import IServiceCollection
from twisted.web import resource, static
from scrapyd.interfaces import IEggStorage, IPoller, ISpiderScheduler
+from scrapyd.jobstorage import job_items_url, job_log_url
class Root(resource.Resource):
@@ -17,15 +18,15 @@ class Root(resource.Resource):
self.runner = config.get('runner')
logsdir = config.get('logs_dir')
itemsdir = config.get('items_dir')
- local_items = itemsdir and (urlparse(itemsdir).scheme.lower() in ['', 'file'])
+ self.local_items = itemsdir and (urlparse(itemsdir).scheme.lower() in ['', 'file'])
self.app = app
self.nodename = config.get('node_name', socket.gethostname())
- self.putChild(b'', Home(self, local_items))
+ self.putChild(b'', Home(self, self.local_items))
if logsdir:
self.putChild(b'logs', static.File(logsdir.encode('ascii', 'ignore'), 'text/plain'))
- if local_items:
+ if self.local_items:
self.putChild(b'items', static.File(itemsdir, 'text/plain'))
- self.putChild(b'jobs', Jobs(self, local_items))
+ self.putChild(b'jobs', Jobs(self, self.local_items))
services = config.items('services', ())
for servName, servClsName in services:
servCls = load_object(servClsName)
@@ -206,8 +207,8 @@ class Jobs(resource.Resource):
"PID": p.pid,
"Start": microsec_trunc(p.start_time),
"Runtime": microsec_trunc(datetime.now() - p.start_time),
- "Log": '<a href="/logs/%s/%s/%s.log">Log</a>' % (p.project, p.spider, p.job),
- "Items": '<a href="/items/%s/%s/%s.jl">Items</a>' % (p.project, p.spider, p.job),
+ "Log": f'<a href="{job_log_url(p)}">Log</a>',
+ "Items": f'<a href="{job_items_url(p)}">Items</a>',
"Cancel": self.cancel_button(project=p.project, jobid=p.job),
})
for p in self.root.launcher.processes.values()
@@ -222,8 +223,8 @@ class Jobs(resource.Resource):
"Start": microsec_trunc(p.start_time),
"Runtime": microsec_trunc(p.end_time - p.start_time),
"Finish": microsec_trunc(p.end_time),
- "Log": '<a href="/logs/%s/%s/%s.log">Log</a>' % (p.project, p.spider, p.job),
- "Items": '<a href="/items/%s/%s/%s.jl">Items</a>' % (p.project, p.spider, p.job),
+ "Log": f'<a href="{job_log_url(p)}">Log</a>',
+ "Items": f'<a href="{job_items_url(p)}">Items</a>',
})
for p in self.root.launcher.finished
)
|
scrapy/scrapyd
|
2160e5de761229cd92f4a7aa0c6b718011930ae0
|
diff --git a/scrapyd/tests/conftest.py b/scrapyd/tests/conftest.py
index 632957a..e0ef5c9 100644
--- a/scrapyd/tests/conftest.py
+++ b/scrapyd/tests/conftest.py
@@ -47,9 +47,15 @@ def txrequest():
return Request(http_channel)
-def common_app_fixture(request):
- config = Config()
[email protected](params=[None, ('scrapyd', 'items_dir', 'items')], ids=["default", "default_with_local_items"])
+def fxt_config(request):
+ conf = Config()
+ if request.param:
+ conf.cp.set(*request.param)
+ return conf
+
+def common_app_fixture(request, config):
app = application(config)
project, version = 'quotesbot', '0.1'
storage = app.getComponent(IEggStorage)
@@ -65,14 +71,14 @@ def common_app_fixture(request):
@pytest.fixture
-def site_no_egg(request):
- root, storage = common_app_fixture(request)
+def site_no_egg(request, fxt_config):
+ root, storage = common_app_fixture(request, fxt_config)
return root
@pytest.fixture
-def site_with_egg(request):
- root, storage = common_app_fixture(request)
+def site_with_egg(request, fxt_config):
+ root, storage = common_app_fixture(request, fxt_config)
egg_path = Path(__file__).absolute().parent / "quotesbot.egg"
project, version = 'quotesbot', '0.1'
diff --git a/scrapyd/tests/test_webservice.py b/scrapyd/tests/test_webservice.py
index e20fe61..ab4b4e8 100644
--- a/scrapyd/tests/test_webservice.py
+++ b/scrapyd/tests/test_webservice.py
@@ -2,6 +2,11 @@ from pathlib import Path
from unittest import mock
from scrapyd.interfaces import IEggStorage
+from scrapyd.jobstorage import Job
+
+
+def fake_list_jobs(*args, **kwargs):
+ yield Job('proj1', 'spider-a', 'id1234')
def fake_list_spiders(*args, **kwargs):
@@ -49,6 +54,23 @@ class TestWebservice:
assert content['projects'] == ['quotesbot']
+ def test_list_jobs(self, txrequest, site_with_egg):
+ txrequest.args = {}
+ endpoint = b'listjobs.json'
+ content = site_with_egg.children[endpoint].render_GET(txrequest)
+
+ assert set(content) == {'node_name', 'status', 'pending', 'running', 'finished'}
+
+ @mock.patch('scrapyd.jobstorage.MemoryJobStorage.__iter__', new=fake_list_jobs)
+ def test_list_jobs_finished(self, txrequest, site_with_egg):
+ txrequest.args = {}
+ endpoint = b'listjobs.json'
+ content = site_with_egg.children[endpoint].render_GET(txrequest)
+
+ assert set(content['finished'][0]) == {
+ 'project', 'spider', 'id', 'start_time', 'end_time', 'log_url', 'items_url'
+ }
+
def test_delete_version(self, txrequest, site_with_egg):
endpoint = b'delversion.json'
txrequest.args = {
diff --git a/scrapyd/tests/test_website.py b/scrapyd/tests/test_website.py
index 5fa21f2..fad881e 100644
--- a/scrapyd/tests/test_website.py
+++ b/scrapyd/tests/test_website.py
@@ -3,22 +3,37 @@ class TestWebsite:
content = site_no_egg.children[b'jobs'].render(txrequest)
expect_headers = {
b'Content-Type': [b'text/html; charset=utf-8'],
- b'Content-Length': [b'643']
+ b'Content-Length': [b'643'],
}
- headers = txrequest.responseHeaders.getAllRawHeaders()
- initial = (
+ if site_no_egg.local_items:
+ expect_headers[b'Content-Length'] = [b'601']
+
+ headers = dict(txrequest.responseHeaders.getAllRawHeaders())
+
+ assert headers == expect_headers
+ assert content.decode().startswith(
'<html><head><title>Scrapyd</title><style type="text/css">'
'#jobs>thead td {text-align: center; font-weight'
)
-
- assert dict(headers) == expect_headers
- assert content.decode().startswith(initial)
+ if site_no_egg.local_items:
+ assert b'display: none' not in content
+ else:
+ assert b'display: none' in content
def test_render_home(self, txrequest, site_no_egg):
content = site_no_egg.children[b''].render_GET(txrequest)
+ expect_headers = {
+ b'Content-Type': [b'text/html; charset=utf-8'],
+ b'Content-Length': [b'708'],
+ }
+ if site_no_egg.local_items:
+ expect_headers[b'Content-Length'] = [b'744']
+
headers = dict(txrequest.responseHeaders.getAllRawHeaders())
+ assert headers == expect_headers
assert b'Available projects' in content
- assert headers[b'Content-Type'] == [b'text/html; charset=utf-8']
- # content-length different between my localhost and build environment
- assert b'Content-Length' in headers
+ if site_no_egg.local_items:
+ assert b'Items' in content
+ else:
+ assert b'Items' not in content
|
API - add items and logs url to listjobs.json
After making a call to listjobs.json, I'd like to download the items or logs related to the finished jobs. Would it make sense to add something like below?
2 new attributes:
* items_url
* logs_url
```json
{
"status": "ok",
"pending": [],
"running": [],
"finished": [
{
"id": "2f16646cfcaf11e1b0090800272a6d06",
"project": "myproject", "spider": "spider3",
"start_time": "2012-09-12 10:14:03.594664",
"end_time": "2012-09-12 10:24:03.594664",
"items_url": "/items/myproject/spider3/2f16646cfcaf11e1b0090800272a6d06.jl",
"log_url": "/logs/myproject/spider3/2f16646cfcaf11e1b0090800272a6d06.log"
}
]
}
```
If so, I could submit a PR for it.
|
0.0
|
2160e5de761229cd92f4a7aa0c6b718011930ae0
|
[
"scrapyd/tests/test_webservice.py::TestWebservice::test_list_jobs_finished[default]",
"scrapyd/tests/test_webservice.py::TestWebservice::test_list_jobs_finished[default_with_local_items]",
"scrapyd/tests/test_website.py::TestWebsite::test_render_jobs[default]",
"scrapyd/tests/test_website.py::TestWebsite::test_render_jobs[default_with_local_items]",
"scrapyd/tests/test_website.py::TestWebsite::test_render_home[default]",
"scrapyd/tests/test_website.py::TestWebsite::test_render_home[default_with_local_items]"
] |
[
"scrapyd/tests/test_webservice.py::TestWebservice::test_list_spiders[default]",
"scrapyd/tests/test_webservice.py::TestWebservice::test_list_spiders[default_with_local_items]",
"scrapyd/tests/test_webservice.py::TestWebservice::test_list_versions[default]",
"scrapyd/tests/test_webservice.py::TestWebservice::test_list_versions[default_with_local_items]",
"scrapyd/tests/test_webservice.py::TestWebservice::test_list_projects[default]",
"scrapyd/tests/test_webservice.py::TestWebservice::test_list_projects[default_with_local_items]",
"scrapyd/tests/test_webservice.py::TestWebservice::test_list_jobs[default]",
"scrapyd/tests/test_webservice.py::TestWebservice::test_list_jobs[default_with_local_items]",
"scrapyd/tests/test_webservice.py::TestWebservice::test_delete_version[default]",
"scrapyd/tests/test_webservice.py::TestWebservice::test_delete_version[default_with_local_items]",
"scrapyd/tests/test_webservice.py::TestWebservice::test_delete_project[default]",
"scrapyd/tests/test_webservice.py::TestWebservice::test_delete_project[default_with_local_items]",
"scrapyd/tests/test_webservice.py::TestWebservice::test_addversion[default]",
"scrapyd/tests/test_webservice.py::TestWebservice::test_addversion[default_with_local_items]",
"scrapyd/tests/test_webservice.py::TestWebservice::test_schedule[default]",
"scrapyd/tests/test_webservice.py::TestWebservice::test_schedule[default_with_local_items]"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-02-02 12:57:14+00:00
|
bsd-3-clause
| 5,423 |
|
scrapy__scrapyd-469
|
diff --git a/MANIFEST.in b/MANIFEST.in
index a9674f4..1d44276 100644
--- a/MANIFEST.in
+++ b/MANIFEST.in
@@ -7,5 +7,6 @@ recursive-include docs *.txt
recursive-include docs Makefile
recursive-include scrapyd *.py
recursive-include scrapyd *.egg
+recursive-include integration_tests *.py
exclude .pre-commit-config.yaml
exclude .readthedocs.yaml
diff --git a/docs/api.rst b/docs/api.rst
index 719089e..085f345 100644
--- a/docs/api.rst
+++ b/docs/api.rst
@@ -45,13 +45,13 @@ Example response::
{"status": "ok", "spiders": 3}
-.. note:: Scrapyd uses the `distutils LooseVersion`_ to interpret the version numbers you provide.
+.. note:: Scrapyd uses the `packaging Version`_ to interpret the version numbers you provide.
The latest version for a project will be used by default whenever necessary.
schedule.json_ and listspiders.json_ allow you to explicitly set the desired project version.
-.. _distutils LooseVersion: http://epydoc.sourceforge.net/stdlib/distutils.version.LooseVersion-class.html
+.. _packaging Version: https://packaging.pypa.io/en/stable/version.html
.. _scrapyd-schedule:
diff --git a/docs/news.rst b/docs/news.rst
index 866c4bc..1e53ed8 100644
--- a/docs/news.rst
+++ b/docs/news.rst
@@ -20,6 +20,7 @@ Removed
Fixed
~~~~~
+- Use ``packaging.version.Version`` instead of ``distutils.LooseVersion``.
- Print Scrapyd's version instead of Twisted's version with ``--version`` (``-v``) flag.
- Override Scrapy's ``LOG_STDOUT`` to ``False`` to suppress logging output for listspiders.json webservice.
diff --git a/docs/overview.rst b/docs/overview.rst
index fc3934b..7d47658 100644
--- a/docs/overview.rst
+++ b/docs/overview.rst
@@ -12,7 +12,7 @@ spiders.
A common (and useful) convention to use for the version name is the revision
number of the version control tool you're using to track your Scrapy project
code. For example: ``r23``. The versions are not compared alphabetically but
-using a smarter algorithm (the same `distutils`_ uses) so ``r10`` compares
+using a smarter algorithm (the same `packaging`_ uses) so ``r10`` compares
greater to ``r9``, for example.
How Scrapyd works
@@ -68,7 +68,7 @@ and accessing logs) which can be accessed at http://localhost:6800/
Alternatively, you can use `ScrapydWeb`_ to manage your Scrapyd cluster.
-.. _distutils: http://docs.python.org/library/distutils.html
+.. _packaging: https://pypi.org/project/packaging/
.. _Twisted Application Framework: http://twistedmatrix.com/documents/current/core/howto/application.html
.. _server command: http://doc.scrapy.org/en/latest/topics/commands.html#server
.. _ScrapydWeb: https://github.com/my8100/scrapydweb
diff --git a/scrapyd/eggstorage.py b/scrapyd/eggstorage.py
index 5ca8936..5efb67b 100644
--- a/scrapyd/eggstorage.py
+++ b/scrapyd/eggstorage.py
@@ -1,5 +1,4 @@
import re
-from distutils.version import LooseVersion
from glob import glob
from os import listdir, makedirs, path, remove
from shutil import copyfileobj, rmtree
@@ -7,6 +6,7 @@ from shutil import copyfileobj, rmtree
from zope.interface import implementer
from scrapyd.interfaces import IEggStorage
+from scrapyd.utils import sorted_versions
@implementer(IEggStorage)
@@ -35,7 +35,7 @@ class FilesystemEggStorage(object):
eggdir = path.join(self.basedir, project)
versions = [path.splitext(path.basename(x))[0]
for x in glob("%s/*.egg" % eggdir)]
- return sorted(versions, key=LooseVersion)
+ return sorted_versions(versions)
def list_projects(self):
projects = []
diff --git a/scrapyd/utils.py b/scrapyd/utils.py
index 6baff61..bbfd0f5 100644
--- a/scrapyd/utils.py
+++ b/scrapyd/utils.py
@@ -3,6 +3,7 @@ import os
import sys
from subprocess import PIPE, Popen
+from packaging.version import InvalidVersion, Version
from scrapy.utils.misc import load_object
from twisted.web import resource
@@ -156,3 +157,10 @@ def _to_native_str(text, encoding='utf-8', errors='strict'):
'object, got %s' % type(text).__name__)
return text.decode(encoding, errors)
+
+
+def sorted_versions(versions):
+ try:
+ return sorted(versions, key=Version)
+ except InvalidVersion:
+ return sorted(versions)
diff --git a/setup.py b/setup.py
index 40237a0..fcf0742 100644
--- a/setup.py
+++ b/setup.py
@@ -23,6 +23,7 @@ setup(
# The scrapyd command requires the txapp.py to be decompressed. #49
zip_safe=False,
install_requires=[
+ 'packaging',
'twisted>=17.9',
'scrapy>=2.0.0',
'setuptools',
|
scrapy/scrapyd
|
cb9c7c0b3bd1f221d79ad4b453baf02ae84709ea
|
diff --git a/scrapyd/tests/test_dont_load_settings.py b/scrapyd/tests/test_dont_load_settings.py
index 95806ff..ea40d26 100644
--- a/scrapyd/tests/test_dont_load_settings.py
+++ b/scrapyd/tests/test_dont_load_settings.py
@@ -17,8 +17,11 @@ class SettingsSafeModulesTest(unittest.TestCase):
for m in self.SETTINGS_SAFE_MODULES:
__import__(m)
- assert 'scrapy.conf' not in sys.modules, \
+ self.assertNotIn(
+ 'scrapy.conf',
+ sys.modules,
"Module %r must not cause the scrapy.conf module to be loaded" % m
+ )
if __name__ == "__main__":
diff --git a/scrapyd/tests/test_eggstorage.py b/scrapyd/tests/test_eggstorage.py
index 9bbedee..4b8ba3b 100644
--- a/scrapyd/tests/test_eggstorage.py
+++ b/scrapyd/tests/test_eggstorage.py
@@ -1,4 +1,5 @@
from io import BytesIO
+from unittest.mock import patch
from twisted.trial import unittest
from zope.interface import implementer
@@ -39,8 +40,8 @@ class TestConfigureEggStorage(unittest.TestCase):
app = application(config)
app_eggstorage = app.getComponent(IEggStorage)
- assert isinstance(app_eggstorage, SomeFakeEggStorage)
- assert app_eggstorage.list_projects() == ['hello_world']
+ self.assertIsInstance(app_eggstorage, SomeFakeEggStorage)
+ self.assertEqual(app_eggstorage.list_projects(), ['hello_world'])
class EggStorageTest(unittest.TestCase):
@@ -53,6 +54,18 @@ class EggStorageTest(unittest.TestCase):
def test_interface(self):
verifyObject(IEggStorage, self.eggst)
+ @patch('scrapyd.eggstorage.glob', new=lambda x: ['ddd', 'abc', 'bcaa'])
+ def test_list_hashes(self):
+ versions = self.eggst.list('any')
+
+ self.assertEqual(versions, ['abc', 'bcaa', 'ddd'])
+
+ @patch('scrapyd.eggstorage.glob', new=lambda x: ['9', '2', '200', '3', '4'])
+ def test_list_semantic_versions(self):
+ versions = self.eggst.list('any')
+
+ self.assertEqual(versions, ['2', '3', '4', '9', '200'])
+
def test_put_get_list_delete(self):
self.eggst.put(BytesIO(b"egg01"), 'mybot', '01')
self.eggst.put(BytesIO(b"egg03"), 'mybot', '03/ver')
diff --git a/scrapyd/tests/test_sqlite.py b/scrapyd/tests/test_sqlite.py
index 01faad8..c04f6dd 100644
--- a/scrapyd/tests/test_sqlite.py
+++ b/scrapyd/tests/test_sqlite.py
@@ -24,11 +24,11 @@ class JsonSqliteDictTest(unittest.TestCase):
def test_in(self):
d = self.dict_class()
- self.assertFalse('test' in d)
+ self.assertNotIn('test', d)
d['test'] = 123
- self.assertTrue('test' in d)
+ self.assertIn('test', d)
def test_keyerror(self):
d = self.dict_class()
diff --git a/scrapyd/tests/test_utils.py b/scrapyd/tests/test_utils.py
index dc0b0f0..7e1805d 100644
--- a/scrapyd/tests/test_utils.py
+++ b/scrapyd/tests/test_utils.py
@@ -11,7 +11,7 @@ from twisted.trial import unittest
from scrapyd import get_application
from scrapyd.interfaces import IEggStorage
-from scrapyd.utils import UtilsCache, get_crawl_args, get_spider_list
+from scrapyd.utils import UtilsCache, get_crawl_args, get_spider_list, sorted_versions
def get_pythonpath_scrapyd():
@@ -30,14 +30,14 @@ class UtilsTest(unittest.TestCase):
cargs = get_crawl_args(msg)
self.assertEqual(cargs, ['lala', '-a', 'arg1=val1'])
- assert all(isinstance(x, str) for x in cargs), cargs
+ self.assertTrue(all(isinstance(x, str) for x in cargs), cargs)
def test_get_crawl_args_with_settings(self):
msg = {'_project': 'lolo', '_spider': 'lala', 'arg1': u'val1', 'settings': {'ONE': 'two'}}
cargs = get_crawl_args(msg)
self.assertEqual(cargs, ['lala', '-a', 'arg1=val1', '-s', 'ONE=two'])
- assert all(isinstance(x, str) for x in cargs), cargs
+ self.assertTrue(all(isinstance(x, str) for x in cargs), cargs)
class GetSpiderListTest(unittest.TestCase):
@@ -119,3 +119,12 @@ class GetSpiderListTest(unittest.TestCase):
with mock.patch('scrapyd.utils.Popen', wraps=popen_wrapper):
exc = self.assertRaises(RuntimeError, get_spider_list, 'mybot3', pythonpath=pypath)
self.assertRegex(str(exc).rstrip(), r'Exception: This should break the `scrapy list` command$')
+
+
[email protected]("versions,expected", [
+ (['zzz', 'b', 'ddd', 'a', 'x'], ['a', 'b', 'ddd', 'x', 'zzz']),
+ (["10", "1", "9"], ["1", "9", "10"]),
+ (["2.11", "2.01", "2.9"], ["2.01", "2.9", "2.11"])
+])
+def test_sorted_versions(versions, expected):
+ assert sorted_versions(versions) == expected
|
Replace distutils.version.LooseVersion with packaging.version Version
In scrapyd/eggstorage.py we use LooseVersion from distutils https://github.com/scrapy/scrapyd/blob/b45c20547b91f34938ee574f86ba966d4b17b05c/scrapyd/eggstorage.py#L37
The distutils package is deprecated and slated for removal in Python 3.12.
[PEP 632](https://www.python.org/dev/peps/pep-0632/) recommends using [packaging.version](https://packaging.pypa.io/en/latest/version.html). There is one problem, that LooseVersion was designed [as a tool for anarchists](https://github.com/python/cpython/blob/f4c03484da59049eb62a9bf7777b963e2267d187/Lib/distutils/version.py#L269) and packaging.version is not a tool for anarchists, it raises error when version is not matching [PEP 440](https://www.python.org/dev/peps/pep-0440/). I suspect this may break some projects because many projects don't use semantic versioning but just use version control hashes as version numbers.
IMO we should just rewrite this sorting in eggstorage to keep old behavior without distutils, I don't see a problem in hashes as version numbers, so we can just keep old way, but maybe worth discussing how to do it? What community expects here? What are your practices and expectations here?
Expected output here:
- [x] patch that replaces LooseVersion with something else
- [x] unit tests that show that current behavior is preserved and does not break people projects, they can go somewhere here: https://github.com/scrapy/scrapyd/blob/b45c20547b91f34938ee574f86ba966d4b17b05c/scrapyd/tests/test_eggstorage.py
or here if we add separate utility for sorting https://github.com/scrapy/scrapyd/blob/b45c20547b91f34938ee574f86ba966d4b17b05c/scrapyd/tests/test_utils.py
|
0.0
|
cb9c7c0b3bd1f221d79ad4b453baf02ae84709ea
|
[
"scrapyd/tests/test_dont_load_settings.py::SettingsSafeModulesTest::test_modules_that_shouldnt_load_settings",
"scrapyd/tests/test_eggstorage.py::TestConfigureEggStorage::test_egg_config_application",
"scrapyd/tests/test_eggstorage.py::EggStorageTest::test_interface",
"scrapyd/tests/test_eggstorage.py::EggStorageTest::test_list_hashes",
"scrapyd/tests/test_eggstorage.py::EggStorageTest::test_list_semantic_versions",
"scrapyd/tests/test_eggstorage.py::EggStorageTest::test_put_get_list_delete",
"scrapyd/tests/test_sqlite.py::JsonSqliteDictTest::test_basic_types",
"scrapyd/tests/test_sqlite.py::JsonSqliteDictTest::test_in",
"scrapyd/tests/test_sqlite.py::JsonSqliteDictTest::test_keyerror",
"scrapyd/tests/test_sqlite.py::JsonSqliteDictTest::test_replace",
"scrapyd/tests/test_sqlite.py::JsonSqlitePriorityQueueTest::test_empty",
"scrapyd/tests/test_sqlite.py::JsonSqlitePriorityQueueTest::test_iter_len_clear",
"scrapyd/tests/test_sqlite.py::JsonSqlitePriorityQueueTest::test_multiple",
"scrapyd/tests/test_sqlite.py::JsonSqlitePriorityQueueTest::test_one",
"scrapyd/tests/test_sqlite.py::JsonSqlitePriorityQueueTest::test_priority",
"scrapyd/tests/test_sqlite.py::JsonSqlitePriorityQueueTest::test_remove",
"scrapyd/tests/test_sqlite.py::JsonSqlitePriorityQueueTest::test_types",
"scrapyd/tests/test_sqlite.py::SqliteFinishedJobsTest::test__iter__",
"scrapyd/tests/test_sqlite.py::SqliteFinishedJobsTest::test_add",
"scrapyd/tests/test_sqlite.py::SqliteFinishedJobsTest::test_clear_all",
"scrapyd/tests/test_sqlite.py::SqliteFinishedJobsTest::test_clear_keep_2",
"scrapyd/tests/test_utils.py::UtilsTest::test_get_crawl_args",
"scrapyd/tests/test_utils.py::UtilsTest::test_get_crawl_args_with_settings",
"scrapyd/tests/test_utils.py::GetSpiderListTest::test_failed_spider_list",
"scrapyd/tests/test_utils.py::GetSpiderListTest::test_get_spider_list",
"scrapyd/tests/test_utils.py::GetSpiderListTest::test_get_spider_list_unicode",
"scrapyd/tests/test_utils.py::test_sorted_versions[versions0-expected0]",
"scrapyd/tests/test_utils.py::test_sorted_versions[versions1-expected1]",
"scrapyd/tests/test_utils.py::test_sorted_versions[versions2-expected2]"
] |
[] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-02-02 21:02:19+00:00
|
bsd-3-clause
| 5,424 |
|
scrapy__w3lib-100
|
diff --git a/w3lib/http.py b/w3lib/http.py
index accfb5d..c7b94a2 100644
--- a/w3lib/http.py
+++ b/w3lib/http.py
@@ -78,7 +78,7 @@ def headers_dict_to_raw(headers_dict):
return b'\r\n'.join(raw_lines)
-def basic_auth_header(username, password):
+def basic_auth_header(username, password, encoding='ISO-8859-1'):
"""
Return an `Authorization` header field value for `HTTP Basic Access Authentication (RFC 2617)`_
@@ -95,5 +95,5 @@ def basic_auth_header(username, password):
# XXX: RFC 2617 doesn't define encoding, but ISO-8859-1
# seems to be the most widely used encoding here. See also:
# http://greenbytes.de/tech/webdav/draft-ietf-httpauth-basicauth-enc-latest.html
- auth = auth.encode('ISO-8859-1')
+ auth = auth.encode(encoding)
return b'Basic ' + urlsafe_b64encode(auth)
|
scrapy/w3lib
|
ac1b7212b5f9badf2b35aaf6e094d839fb3ba858
|
diff --git a/tests/test_http.py b/tests/test_http.py
index 453624f..01f903e 100644
--- a/tests/test_http.py
+++ b/tests/test_http.py
@@ -1,3 +1,5 @@
+# -*- coding: utf-8 -*-
+
import unittest
from collections import OrderedDict
from w3lib.http import (basic_auth_header,
@@ -14,6 +16,13 @@ class HttpTests(unittest.TestCase):
self.assertEqual(b'Basic c29tZXVzZXI6QDx5dTk-Jm8_UQ==',
basic_auth_header('someuser', '@<yu9>&o?Q'))
+ def test_basic_auth_header_encoding(self):
+ self.assertEqual(b'Basic c29tw6Z1c8Oocjpzw7htZXDDpHNz',
+ basic_auth_header(u'somæusèr', u'sømepäss', encoding='utf8'))
+ # default encoding (ISO-8859-1)
+ self.assertEqual(b'Basic c29t5nVz6HI6c_htZXDkc3M=',
+ basic_auth_header(u'somæusèr', u'sømepäss'))
+
def test_headers_raw_dict_none(self):
self.assertIsNone(headers_raw_to_dict(None))
self.assertIsNone(headers_dict_to_raw(None))
|
allow to customize encoding in w3lib.http.basic_auth_header
See https://github.com/scrapy/scrapy/pull/2530
|
0.0
|
ac1b7212b5f9badf2b35aaf6e094d839fb3ba858
|
[
"tests/test_http.py::HttpTests::test_basic_auth_header_encoding"
] |
[
"tests/test_http.py::HttpTests::test_basic_auth_header",
"tests/test_http.py::HttpTests::test_headers_dict_to_raw",
"tests/test_http.py::HttpTests::test_headers_dict_to_raw_listtuple",
"tests/test_http.py::HttpTests::test_headers_dict_to_raw_wrong_values",
"tests/test_http.py::HttpTests::test_headers_raw_dict_none",
"tests/test_http.py::HttpTests::test_headers_raw_to_dict"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
}
|
2017-12-31 15:12:25+00:00
|
bsd-3-clause
| 5,425 |
|
scrapy__w3lib-112
|
diff --git a/w3lib/url.py b/w3lib/url.py
index 4be74f7..fc9b343 100644
--- a/w3lib/url.py
+++ b/w3lib/url.py
@@ -182,6 +182,8 @@ def url_query_cleaner(url, parameterlist=(), sep='&', kvsep='=', remove=False, u
seen = set()
querylist = []
for ksv in query.split(sep):
+ if not ksv:
+ continue
k, _, _ = ksv.partition(kvsep)
if unique and k in seen:
continue
|
scrapy/w3lib
|
c1a030582ec30423c40215fcd159bc951c851ed7
|
diff --git a/tests/test_url.py b/tests/test_url.py
index 0df5bfd..9476b30 100644
--- a/tests/test_url.py
+++ b/tests/test_url.py
@@ -284,6 +284,10 @@ class UrlTests(unittest.TestCase):
'http://example.com/?version=1&pageurl=test¶m2=value2')
def test_url_query_cleaner(self):
+ self.assertEqual('product.html',
+ url_query_cleaner("product.html?"))
+ self.assertEqual('product.html',
+ url_query_cleaner("product.html?&"))
self.assertEqual('product.html?id=200',
url_query_cleaner("product.html?id=200&foo=bar&name=wired", ['id']))
self.assertEqual('product.html?id=200',
@@ -308,6 +312,10 @@ class UrlTests(unittest.TestCase):
url_query_cleaner("product.html?id=2&foo=bar&name=wired", ['id', 'foo'], remove=True))
self.assertEqual('product.html?foo=bar&name=wired',
url_query_cleaner("product.html?id=2&foo=bar&name=wired", ['id', 'footo'], remove=True))
+ self.assertEqual('product.html',
+ url_query_cleaner("product.html", ['id'], remove=True))
+ self.assertEqual('product.html',
+ url_query_cleaner("product.html?&", ['id'], remove=True))
self.assertEqual('product.html?foo=bar',
url_query_cleaner("product.html?foo=bar&name=wired", 'foo'))
self.assertEqual('product.html?foobar=wired',
|
url_query_cleaner appends ? to urls without a query string
```python
>>> url_query_cleaner('http://domain.tld/', ['bla'], remove=True)
'http://domain.tld/?'
```
This is the code which does it: `url = '?'.join([base, sep.join(querylist)]) if querylist else base` (`querylist==['']`).
|
0.0
|
c1a030582ec30423c40215fcd159bc951c851ed7
|
[
"tests/test_url.py::UrlTests::test_url_query_cleaner"
] |
[
"tests/test_url.py::UrlTests::test_any_to_uri",
"tests/test_url.py::UrlTests::test_file_uri_to_path",
"tests/test_url.py::UrlTests::test_is_url",
"tests/test_url.py::UrlTests::test_path_to_file_uri",
"tests/test_url.py::UrlTests::test_safe_download_url",
"tests/test_url.py::UrlTests::test_safe_url_idna",
"tests/test_url.py::UrlTests::test_safe_url_idna_encoding_failure",
"tests/test_url.py::UrlTests::test_safe_url_port_number",
"tests/test_url.py::UrlTests::test_safe_url_string",
"tests/test_url.py::UrlTests::test_safe_url_string_bytes_input",
"tests/test_url.py::UrlTests::test_safe_url_string_bytes_input_nonutf8",
"tests/test_url.py::UrlTests::test_safe_url_string_misc",
"tests/test_url.py::UrlTests::test_safe_url_string_unsafe_chars",
"tests/test_url.py::UrlTests::test_safe_url_string_with_query",
"tests/test_url.py::UrlTests::test_url_query_cleaner_keep_fragments",
"tests/test_url.py::UrlTests::test_url_query_parameter",
"tests/test_url.py::UrlTests::test_url_query_parameter_2",
"tests/test_url.py::UrlTests::test_urljoin_rfc_deprecated",
"tests/test_url.py::CanonicalizeUrlTest::test_append_missing_path",
"tests/test_url.py::CanonicalizeUrlTest::test_canonicalize_idns",
"tests/test_url.py::CanonicalizeUrlTest::test_canonicalize_parse_url",
"tests/test_url.py::CanonicalizeUrlTest::test_canonicalize_url",
"tests/test_url.py::CanonicalizeUrlTest::test_canonicalize_url_idempotence",
"tests/test_url.py::CanonicalizeUrlTest::test_canonicalize_url_idna_exceptions",
"tests/test_url.py::CanonicalizeUrlTest::test_canonicalize_url_unicode_path",
"tests/test_url.py::CanonicalizeUrlTest::test_canonicalize_url_unicode_query_string",
"tests/test_url.py::CanonicalizeUrlTest::test_canonicalize_url_unicode_query_string_wrong_encoding",
"tests/test_url.py::CanonicalizeUrlTest::test_canonicalize_urlparsed",
"tests/test_url.py::CanonicalizeUrlTest::test_domains_are_case_insensitive",
"tests/test_url.py::CanonicalizeUrlTest::test_dont_convert_safe_characters",
"tests/test_url.py::CanonicalizeUrlTest::test_keep_blank_values",
"tests/test_url.py::CanonicalizeUrlTest::test_non_ascii_percent_encoding_in_paths",
"tests/test_url.py::CanonicalizeUrlTest::test_non_ascii_percent_encoding_in_query_arguments",
"tests/test_url.py::CanonicalizeUrlTest::test_normalize_percent_encoding_in_paths",
"tests/test_url.py::CanonicalizeUrlTest::test_normalize_percent_encoding_in_query_arguments",
"tests/test_url.py::CanonicalizeUrlTest::test_port_number",
"tests/test_url.py::CanonicalizeUrlTest::test_quoted_slash_and_question_sign",
"tests/test_url.py::CanonicalizeUrlTest::test_remove_fragments",
"tests/test_url.py::CanonicalizeUrlTest::test_return_str",
"tests/test_url.py::CanonicalizeUrlTest::test_safe_characters_unicode",
"tests/test_url.py::CanonicalizeUrlTest::test_sorting",
"tests/test_url.py::CanonicalizeUrlTest::test_spaces",
"tests/test_url.py::CanonicalizeUrlTest::test_typical_usage",
"tests/test_url.py::CanonicalizeUrlTest::test_urls_with_auth_and_ports",
"tests/test_url.py::DataURITests::test_base64",
"tests/test_url.py::DataURITests::test_base64_spaces",
"tests/test_url.py::DataURITests::test_bytes_uri",
"tests/test_url.py::DataURITests::test_default_mediatype",
"tests/test_url.py::DataURITests::test_default_mediatype_charset",
"tests/test_url.py::DataURITests::test_mediatype_parameters",
"tests/test_url.py::DataURITests::test_missing_comma",
"tests/test_url.py::DataURITests::test_missing_scheme",
"tests/test_url.py::DataURITests::test_scheme_case_insensitive",
"tests/test_url.py::DataURITests::test_text_charset",
"tests/test_url.py::DataURITests::test_text_uri",
"tests/test_url.py::DataURITests::test_unicode_uri",
"tests/test_url.py::DataURITests::test_wrong_base64_param",
"tests/test_url.py::DataURITests::test_wrong_scheme"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-09-07 19:48:08+00:00
|
bsd-3-clause
| 5,426 |
|
scrapy__w3lib-127
|
diff --git a/w3lib/html.py b/w3lib/html.py
index 9990a35..55fe5e3 100644
--- a/w3lib/html.py
+++ b/w3lib/html.py
@@ -220,7 +220,7 @@ def remove_tags_with_content(text, which_ones=(), encoding=None):
text = to_unicode(text, encoding)
if which_ones:
- tags = '|'.join([r'<%s.*?</%s>|<%s\s*/>' % (tag, tag, tag) for tag in which_ones])
+ tags = '|'.join([r'<%s\b.*?</%s>|<%s\s*/>' % (tag, tag, tag) for tag in which_ones])
retags = re.compile(tags, re.DOTALL | re.IGNORECASE)
text = retags.sub(u'', text)
return text
|
scrapy/w3lib
|
0108fab2f627b2bfdf3d6942a44ed10a78ff443f
|
diff --git a/tests/test_html.py b/tests/test_html.py
index 68133cb..6d6e8ae 100644
--- a/tests/test_html.py
+++ b/tests/test_html.py
@@ -184,6 +184,10 @@ class RemoveTagsWithContentTest(unittest.TestCase):
# text with empty tags
self.assertEqual(remove_tags_with_content(u'<br/>a<br />', which_ones=('br',)), u'a')
+ def test_tags_with_shared_prefix(self):
+ # https://github.com/scrapy/w3lib/issues/114
+ self.assertEqual(remove_tags_with_content(u'<span></span><s></s>', which_ones=('s',)), u'<span></span>')
+
class ReplaceEscapeCharsTest(unittest.TestCase):
def test_returns_unicode(self):
|
remove_tags_with_content bug
use this
`remove_tags_with_content("""<div class="hqimg_related"><div class="to_page"><span>热点栏目</span> <s class='hotSe'></s>""", ("s",))`
get result:
`<div class="hqimg_related"><div class="to_page">`
There may be some mistakes
then modified the expression.
`tags = '|'.join([r'<%s\s+.*?</%s>|<%s\s*/>' % (tag, tag, tag) for tag in which_ones])`
finally,it's work fine
|
0.0
|
0108fab2f627b2bfdf3d6942a44ed10a78ff443f
|
[
"tests/test_html.py::RemoveTagsWithContentTest::test_tags_with_shared_prefix"
] |
[
"tests/test_html.py::RemoveEntitiesTest::test_browser_hack",
"tests/test_html.py::RemoveEntitiesTest::test_encoding",
"tests/test_html.py::RemoveEntitiesTest::test_illegal_entities",
"tests/test_html.py::RemoveEntitiesTest::test_keep_entities",
"tests/test_html.py::RemoveEntitiesTest::test_missing_semicolon",
"tests/test_html.py::RemoveEntitiesTest::test_regular",
"tests/test_html.py::RemoveEntitiesTest::test_returns_unicode",
"tests/test_html.py::ReplaceTagsTest::test_replace_tags",
"tests/test_html.py::ReplaceTagsTest::test_replace_tags_multiline",
"tests/test_html.py::ReplaceTagsTest::test_returns_unicode",
"tests/test_html.py::RemoveCommentsTest::test_no_comments",
"tests/test_html.py::RemoveCommentsTest::test_remove_comments",
"tests/test_html.py::RemoveCommentsTest::test_returns_unicode",
"tests/test_html.py::RemoveTagsTest::test_keep_argument",
"tests/test_html.py::RemoveTagsTest::test_remove_empty_tags",
"tests/test_html.py::RemoveTagsTest::test_remove_tags",
"tests/test_html.py::RemoveTagsTest::test_remove_tags_with_attributes",
"tests/test_html.py::RemoveTagsTest::test_remove_tags_without_tags",
"tests/test_html.py::RemoveTagsTest::test_returns_unicode",
"tests/test_html.py::RemoveTagsTest::test_uppercase_tags",
"tests/test_html.py::RemoveTagsWithContentTest::test_empty_tags",
"tests/test_html.py::RemoveTagsWithContentTest::test_returns_unicode",
"tests/test_html.py::RemoveTagsWithContentTest::test_with_tags",
"tests/test_html.py::RemoveTagsWithContentTest::test_without_tags",
"tests/test_html.py::ReplaceEscapeCharsTest::test_returns_unicode",
"tests/test_html.py::ReplaceEscapeCharsTest::test_with_escape_chars",
"tests/test_html.py::ReplaceEscapeCharsTest::test_without_escape_chars",
"tests/test_html.py::UnquoteMarkupTest::test_returns_unicode",
"tests/test_html.py::UnquoteMarkupTest::test_unquote_markup",
"tests/test_html.py::GetBaseUrlTest::test_attributes_before_href",
"tests/test_html.py::GetBaseUrlTest::test_get_base_url",
"tests/test_html.py::GetBaseUrlTest::test_get_base_url_latin1",
"tests/test_html.py::GetBaseUrlTest::test_get_base_url_latin1_percent",
"tests/test_html.py::GetBaseUrlTest::test_get_base_url_utf8",
"tests/test_html.py::GetBaseUrlTest::test_no_scheme_url",
"tests/test_html.py::GetBaseUrlTest::test_relative_url_with_absolute_path",
"tests/test_html.py::GetBaseUrlTest::test_tag_name",
"tests/test_html.py::GetMetaRefreshTest::test_commented_meta_refresh",
"tests/test_html.py::GetMetaRefreshTest::test_entities_in_redirect_url",
"tests/test_html.py::GetMetaRefreshTest::test_float_refresh_intervals",
"tests/test_html.py::GetMetaRefreshTest::test_get_meta_refresh",
"tests/test_html.py::GetMetaRefreshTest::test_html_comments_with_uncommented_meta_refresh",
"tests/test_html.py::GetMetaRefreshTest::test_inside_noscript",
"tests/test_html.py::GetMetaRefreshTest::test_inside_script",
"tests/test_html.py::GetMetaRefreshTest::test_leading_newline_in_url",
"tests/test_html.py::GetMetaRefreshTest::test_multiline",
"tests/test_html.py::GetMetaRefreshTest::test_nonascii_url_latin1",
"tests/test_html.py::GetMetaRefreshTest::test_nonascii_url_latin1_query",
"tests/test_html.py::GetMetaRefreshTest::test_nonascii_url_utf8",
"tests/test_html.py::GetMetaRefreshTest::test_relative_redirects",
"tests/test_html.py::GetMetaRefreshTest::test_tag_name",
"tests/test_html.py::GetMetaRefreshTest::test_without_url"
] |
{
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-05-09 14:24:16+00:00
|
bsd-3-clause
| 5,427 |
|
scrapy__w3lib-136
|
diff --git a/w3lib/url.py b/w3lib/url.py
index 5feddab..a41446c 100644
--- a/w3lib/url.py
+++ b/w3lib/url.py
@@ -538,6 +538,8 @@ def canonicalize_url(
# UTF-8 can handle all Unicode characters,
# so we should be covered regarding URL normalization,
# if not for proper URL expected by remote website.
+ if isinstance(url, str):
+ url = url.strip()
try:
scheme, netloc, path, params, query, fragment = _safe_ParseResult(
parse_url(url), encoding=encoding or "utf8"
|
scrapy/w3lib
|
4ba3539249cbe33491c9ab6768adab0b57747d52
|
diff --git a/tests/test_url.py b/tests/test_url.py
index c7079c6..9c70805 100644
--- a/tests/test_url.py
+++ b/tests/test_url.py
@@ -1085,6 +1085,17 @@ class CanonicalizeUrlTest(unittest.TestCase):
"http://www.example.com/path/to/%23/foo/bar?url=http%3A%2F%2Fwww.example.com%2F%2Fpath%2Fto%2F%23%2Fbar%2Ffoo#frag",
)
+ def test_strip_spaces(self):
+ self.assertEqual(
+ canonicalize_url(" https://example.com"), "https://example.com/"
+ )
+ self.assertEqual(
+ canonicalize_url("https://example.com "), "https://example.com/"
+ )
+ self.assertEqual(
+ canonicalize_url(" https://example.com "), "https://example.com/"
+ )
+
class DataURITests(unittest.TestCase):
def test_default_mediatype_charset(self):
|
`canonicalize_url` should not accept whitespace at the begin of an URI
Accepting whitespace in the begin of URI introduces a crawling issue. Unique URIs are generated on each depth and crawler gets in a loop.
When a URI is extracted and begins with whitespace it is being considered a relative URI and its concatenated at the end of current URI, which leads to unique URI on each crawler depth.
But, accordingly to RFC2396 [ Page 38], the scheme part of an URI should begin with an ALPHA character.
> "The syntax for URI scheme has been changed to require that all schemes begin with an alpha character."
After further investigation, the core python `urlparse` function doesn't follow RFC strictly, they consider some rules. Like on Python 3.5 they say:
> "Changed in version 3.3: The fragment is now parsed for all URL schemes (unless allow_fragment is false), in accordance with RFC 3986. Previously, a whitelist of schemes that support fragments existed."
However a better implementation should be in accordance with RFC 3986 (which is an update of RFC2396 mentioned before), the `urlparse` should not accept whitespace at the begin of URI.
When compared to the with Ruby implementation of RFC 2396, they don't allow whitespace at the begin of absolute or relative URIs and throws an exception "bad URI(is not URI?)".
In order to fix that on Scrapy level, I suggest the following.
In `scrapy/utils/url.py` add at the begin of `canonicalize_url`:
```
if re.match('[a-zA-Z]', url[:1]) == None:
raise ValueError('Bad URI (is not a valid URI?)')
```
An a test in `tests/test_utils_url.py`:
```
def test_rfc2396_scheme_should_begin_with_alpha(self):
self.assertRaises(ValueError, canonicalize_url," http://www.example.com")
```
But raising an exception breaks a lot of tests and can introduce unexpected behaviors. You could simple `.strip()` url, but won't make it RFC compliant.
|
0.0
|
4ba3539249cbe33491c9ab6768adab0b57747d52
|
[
"tests/test_url.py::CanonicalizeUrlTest::test_strip_spaces"
] |
[
"tests/test_url.py::UrlTests::test_add_or_replace_parameter",
"tests/test_url.py::UrlTests::test_add_or_replace_parameters",
"tests/test_url.py::UrlTests::test_add_or_replace_parameters_does_not_change_input_param",
"tests/test_url.py::UrlTests::test_any_to_uri",
"tests/test_url.py::UrlTests::test_file_uri_to_path",
"tests/test_url.py::UrlTests::test_is_url",
"tests/test_url.py::UrlTests::test_path_to_file_uri",
"tests/test_url.py::UrlTests::test_safe_download_url",
"tests/test_url.py::UrlTests::test_safe_url_idna",
"tests/test_url.py::UrlTests::test_safe_url_idna_encoding_failure",
"tests/test_url.py::UrlTests::test_safe_url_port_number",
"tests/test_url.py::UrlTests::test_safe_url_string",
"tests/test_url.py::UrlTests::test_safe_url_string_bytes_input",
"tests/test_url.py::UrlTests::test_safe_url_string_bytes_input_nonutf8",
"tests/test_url.py::UrlTests::test_safe_url_string_encode_idna_domain_with_port",
"tests/test_url.py::UrlTests::test_safe_url_string_encode_idna_domain_with_username_and_empty_password_and_port_number",
"tests/test_url.py::UrlTests::test_safe_url_string_encode_idna_domain_with_username_password_and_port_number",
"tests/test_url.py::UrlTests::test_safe_url_string_misc",
"tests/test_url.py::UrlTests::test_safe_url_string_preserve_nonfragment_hash",
"tests/test_url.py::UrlTests::test_safe_url_string_quote_path",
"tests/test_url.py::UrlTests::test_safe_url_string_remove_ascii_tab_and_newlines",
"tests/test_url.py::UrlTests::test_safe_url_string_unsafe_chars",
"tests/test_url.py::UrlTests::test_safe_url_string_user_and_pass_percentage_encoded",
"tests/test_url.py::UrlTests::test_safe_url_string_userinfo_unsafe_chars",
"tests/test_url.py::UrlTests::test_safe_url_string_with_query",
"tests/test_url.py::UrlTests::test_url_query_cleaner",
"tests/test_url.py::UrlTests::test_url_query_cleaner_keep_fragments",
"tests/test_url.py::UrlTests::test_url_query_parameter",
"tests/test_url.py::UrlTests::test_url_query_parameter_2",
"tests/test_url.py::CanonicalizeUrlTest::test_append_missing_path",
"tests/test_url.py::CanonicalizeUrlTest::test_canonicalize_idns",
"tests/test_url.py::CanonicalizeUrlTest::test_canonicalize_parse_url",
"tests/test_url.py::CanonicalizeUrlTest::test_canonicalize_url",
"tests/test_url.py::CanonicalizeUrlTest::test_canonicalize_url_idempotence",
"tests/test_url.py::CanonicalizeUrlTest::test_canonicalize_url_idna_exceptions",
"tests/test_url.py::CanonicalizeUrlTest::test_canonicalize_url_unicode_path",
"tests/test_url.py::CanonicalizeUrlTest::test_canonicalize_url_unicode_query_string",
"tests/test_url.py::CanonicalizeUrlTest::test_canonicalize_url_unicode_query_string_wrong_encoding",
"tests/test_url.py::CanonicalizeUrlTest::test_canonicalize_urlparsed",
"tests/test_url.py::CanonicalizeUrlTest::test_domains_are_case_insensitive",
"tests/test_url.py::CanonicalizeUrlTest::test_dont_convert_safe_characters",
"tests/test_url.py::CanonicalizeUrlTest::test_keep_blank_values",
"tests/test_url.py::CanonicalizeUrlTest::test_non_ascii_percent_encoding_in_paths",
"tests/test_url.py::CanonicalizeUrlTest::test_non_ascii_percent_encoding_in_query_arguments",
"tests/test_url.py::CanonicalizeUrlTest::test_normalize_percent_encoding_in_paths",
"tests/test_url.py::CanonicalizeUrlTest::test_normalize_percent_encoding_in_query_arguments",
"tests/test_url.py::CanonicalizeUrlTest::test_port_number",
"tests/test_url.py::CanonicalizeUrlTest::test_preserve_nonfragment_hash",
"tests/test_url.py::CanonicalizeUrlTest::test_quoted_slash_and_question_sign",
"tests/test_url.py::CanonicalizeUrlTest::test_remove_fragments",
"tests/test_url.py::CanonicalizeUrlTest::test_return_str",
"tests/test_url.py::CanonicalizeUrlTest::test_safe_characters_unicode",
"tests/test_url.py::CanonicalizeUrlTest::test_sorting",
"tests/test_url.py::CanonicalizeUrlTest::test_spaces",
"tests/test_url.py::CanonicalizeUrlTest::test_typical_usage",
"tests/test_url.py::CanonicalizeUrlTest::test_urls_with_auth_and_ports",
"tests/test_url.py::DataURITests::test_base64",
"tests/test_url.py::DataURITests::test_base64_spaces",
"tests/test_url.py::DataURITests::test_bytes_uri",
"tests/test_url.py::DataURITests::test_default_mediatype",
"tests/test_url.py::DataURITests::test_default_mediatype_charset",
"tests/test_url.py::DataURITests::test_mediatype_parameters",
"tests/test_url.py::DataURITests::test_missing_comma",
"tests/test_url.py::DataURITests::test_missing_scheme",
"tests/test_url.py::DataURITests::test_scheme_case_insensitive",
"tests/test_url.py::DataURITests::test_text_charset",
"tests/test_url.py::DataURITests::test_text_uri",
"tests/test_url.py::DataURITests::test_unicode_uri",
"tests/test_url.py::DataURITests::test_wrong_base64_param",
"tests/test_url.py::DataURITests::test_wrong_scheme"
] |
{
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-09-17 12:42:26+00:00
|
bsd-3-clause
| 5,428 |
|
scrapy__w3lib-192
|
diff --git a/w3lib/encoding.py b/w3lib/encoding.py
index 35967a5..0879ead 100644
--- a/w3lib/encoding.py
+++ b/w3lib/encoding.py
@@ -227,8 +227,8 @@ def html_to_unicode(
It will try in order:
- * http content type header
* BOM (byte-order mark)
+ * http content type header
* meta or xml tag declarations
* auto-detection, if the `auto_detect_fun` keyword argument is not ``None``
* default encoding in keyword arg (which defaults to utf8)
@@ -281,27 +281,16 @@ def html_to_unicode(
>>>
'''
-
- enc = http_content_type_encoding(content_type_header)
bom_enc, bom = read_bom(html_body_str)
- if enc is not None:
- # remove BOM if it agrees with the encoding
- if enc == bom_enc:
- bom = cast(bytes, bom)
- html_body_str = html_body_str[len(bom) :]
- elif enc == "utf-16" or enc == "utf-32":
- # read endianness from BOM, or default to big endian
- # tools.ietf.org/html/rfc2781 section 4.3
- if bom_enc is not None and bom_enc.startswith(enc):
- enc = bom_enc
- bom = cast(bytes, bom)
- html_body_str = html_body_str[len(bom) :]
- else:
- enc += "-be"
- return enc, to_unicode(html_body_str, enc)
if bom_enc is not None:
bom = cast(bytes, bom)
return bom_enc, to_unicode(html_body_str[len(bom) :], bom_enc)
+
+ enc = http_content_type_encoding(content_type_header)
+ if enc is not None:
+ if enc == "utf-16" or enc == "utf-32":
+ enc += "-be"
+ return enc, to_unicode(html_body_str, enc)
enc = html_body_declared_encoding(html_body_str)
if enc is None and (auto_detect_fun is not None):
enc = auto_detect_fun(html_body_str)
diff --git a/w3lib/http.py b/w3lib/http.py
index e14e434..10d1669 100644
--- a/w3lib/http.py
+++ b/w3lib/http.py
@@ -1,4 +1,4 @@
-from base64 import urlsafe_b64encode
+from base64 import b64encode
from typing import Any, List, MutableMapping, Optional, AnyStr, Sequence, Union, Mapping
from w3lib.util import to_bytes, to_unicode
@@ -101,4 +101,4 @@ def basic_auth_header(
# XXX: RFC 2617 doesn't define encoding, but ISO-8859-1
# seems to be the most widely used encoding here. See also:
# http://greenbytes.de/tech/webdav/draft-ietf-httpauth-basicauth-enc-latest.html
- return b"Basic " + urlsafe_b64encode(to_bytes(auth, encoding=encoding))
+ return b"Basic " + b64encode(to_bytes(auth, encoding=encoding))
|
scrapy/w3lib
|
1c6c96accd3232a32b3c462533fb35c3676d6750
|
diff --git a/tests/test_encoding.py b/tests/test_encoding.py
index 865cf72..be6d447 100644
--- a/tests/test_encoding.py
+++ b/tests/test_encoding.py
@@ -220,13 +220,12 @@ class HtmlConversionTests(unittest.TestCase):
def test_BOM(self):
# utf-16 cases already tested, as is the BOM detection function
- # http header takes precedence, irrespective of BOM
+ # BOM takes precedence, ahead of the http header
bom_be_str = codecs.BOM_UTF16_BE + "hi".encode("utf-16-be")
- expected = "\ufffd\ufffd\x00h\x00i"
- self._assert_encoding("utf-8", bom_be_str, "utf-8", expected)
+ expected = "hi"
+ self._assert_encoding("utf-8", bom_be_str, "utf-16-be", expected)
- # BOM is stripped when it agrees with the encoding, or used to
- # determine encoding
+ # BOM is stripped when present
bom_utf8_str = codecs.BOM_UTF8 + b"hi"
self._assert_encoding("utf-8", bom_utf8_str, "utf-8", "hi")
self._assert_encoding(None, bom_utf8_str, "utf-8", "hi")
diff --git a/tests/test_http.py b/tests/test_http.py
index efabb0a..76a1ff1 100644
--- a/tests/test_http.py
+++ b/tests/test_http.py
@@ -17,7 +17,7 @@ class HttpTests(unittest.TestCase):
)
# Check url unsafe encoded header
self.assertEqual(
- b"Basic c29tZXVzZXI6QDx5dTk-Jm8_UQ==",
+ b"Basic c29tZXVzZXI6QDx5dTk+Jm8/UQ==",
basic_auth_header("someuser", "@<yu9>&o?Q"),
)
@@ -28,7 +28,7 @@ class HttpTests(unittest.TestCase):
)
# default encoding (ISO-8859-1)
self.assertEqual(
- b"Basic c29t5nVz6HI6c_htZXDkc3M=", basic_auth_header("somæusèr", "sømepäss")
+ b"Basic c29t5nVz6HI6c/htZXDkc3M=", basic_auth_header("somæusèr", "sømepäss")
)
def test_headers_raw_dict_none(self):
|
basic_auth_header uses the wrong flavor of base64
I have reason to believe that `basic_auth_header` is wrong in using `urlsafe_b64encode` (which replaces `+/` with `-_`) instead of `b64encode`.
The first specification of HTTP basic auth according to [Wikipedia](https://en.wikipedia.org/wiki/Basic_access_authentication) is [HTTP 1.0](https://www.w3.org/Protocols/HTTP/1.0/spec.html#BasicAA), which does not mention any special flavor of base64, and points for a definition of base64 to RFC-1521, which [describes regular base64](https://datatracker.ietf.org/doc/html/rfc1521). The latest HTTP basic auth specification according to Wikipedia is [RFC-7617](https://datatracker.ietf.org/doc/html/rfc7617), which similarly does not specify any special flavor of base64, and points to [section 4 of RFC-4648](https://datatracker.ietf.org/doc/html/rfc4648#section-4), which also describes the regular base64.
I traced the origin of this bug, and it has been there [at least since the first Git commit of Scrapy](https://github.com/scrapy/scrapy/blame/b45d87d0fe313458d03cd533dee2d3d03e057a04/scrapy/trunk/scrapy/http/request.py#L82).
```python
>>> from w3lib.http import basic_auth_header
```
Actual:
```python
>>> basic_auth_header('aa~aa¿', '')
b'Basic YWF-YWG_Og=='
```
Expected:
```python
>>> basic_auth_header('aa~aa¿', '')
b'Basic YWF+YWG/Og=='
```
I believe this bug only affects ASCII credentials that include the `>`, `?` or `~` characters in certain positions.
For richer encodings like UTF-8, which is what `basic_auth_header` uses (~~and makes sense as a default, but it should be configurable~~ [rightly so](https://datatracker.ietf.org/doc/html/rfc7617#section-2.1)), many more characters can be affected (e.g. `¿` in the example above).
|
0.0
|
1c6c96accd3232a32b3c462533fb35c3676d6750
|
[
"tests/test_encoding.py::HtmlConversionTests::test_BOM",
"tests/test_http.py::HttpTests::test_basic_auth_header",
"tests/test_http.py::HttpTests::test_basic_auth_header_encoding"
] |
[
"tests/test_encoding.py::RequestEncodingTests::test_bom",
"tests/test_encoding.py::RequestEncodingTests::test_html_body_declared_encoding",
"tests/test_encoding.py::RequestEncodingTests::test_html_body_declared_encoding_unicode",
"tests/test_encoding.py::RequestEncodingTests::test_http_encoding_header",
"tests/test_encoding.py::CodecsEncodingTestCase::test_resolve_encoding",
"tests/test_encoding.py::UnicodeDecodingTestCase::test_invalid_utf8",
"tests/test_encoding.py::UnicodeDecodingTestCase::test_utf8",
"tests/test_encoding.py::HtmlConversionTests::test_autodetect",
"tests/test_encoding.py::HtmlConversionTests::test_content_type_and_conversion",
"tests/test_encoding.py::HtmlConversionTests::test_default_encoding",
"tests/test_encoding.py::HtmlConversionTests::test_empty_body",
"tests/test_encoding.py::HtmlConversionTests::test_html_encoding",
"tests/test_encoding.py::HtmlConversionTests::test_invalid_utf8_encoded_body_with_valid_utf8_BOM",
"tests/test_encoding.py::HtmlConversionTests::test_python_crash",
"tests/test_encoding.py::HtmlConversionTests::test_replace_wrong_encoding",
"tests/test_encoding.py::HtmlConversionTests::test_unicode_body",
"tests/test_encoding.py::HtmlConversionTests::test_utf16_32",
"tests/test_encoding.py::HtmlConversionTests::test_utf8_unexpected_end_of_data_with_valid_utf8_BOM",
"tests/test_http.py::HttpTests::test_headers_dict_to_raw",
"tests/test_http.py::HttpTests::test_headers_dict_to_raw_listtuple",
"tests/test_http.py::HttpTests::test_headers_dict_to_raw_wrong_values",
"tests/test_http.py::HttpTests::test_headers_raw_dict_none",
"tests/test_http.py::HttpTests::test_headers_raw_to_dict"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-10-07 12:18:44+00:00
|
bsd-3-clause
| 5,429 |
|
scrapy__w3lib-198
|
diff --git a/w3lib/url.py b/w3lib/url.py
index 5feddab..a41446c 100644
--- a/w3lib/url.py
+++ b/w3lib/url.py
@@ -538,6 +538,8 @@ def canonicalize_url(
# UTF-8 can handle all Unicode characters,
# so we should be covered regarding URL normalization,
# if not for proper URL expected by remote website.
+ if isinstance(url, str):
+ url = url.strip()
try:
scheme, netloc, path, params, query, fragment = _safe_ParseResult(
parse_url(url), encoding=encoding or "utf8"
|
scrapy/w3lib
|
4ba3539249cbe33491c9ab6768adab0b57747d52
|
diff --git a/tests/test_url.py b/tests/test_url.py
index c7079c6..2356c2c 100644
--- a/tests/test_url.py
+++ b/tests/test_url.py
@@ -876,6 +876,12 @@ class CanonicalizeUrlTest(unittest.TestCase):
"http://www.example.com/a%A3do?q=r%E9sum%E9",
)
+ url = "https://example.com/a%23b%2cc#bash"
+ canonical = canonicalize_url(url)
+ # %23 is not accidentally interpreted as a URL fragment separator
+ self.assertEqual(canonical, "https://example.com/a%23b,c")
+ self.assertEqual(canonical, canonicalize_url(canonical))
+
def test_normalize_percent_encoding_in_query_arguments(self):
self.assertEqual(
canonicalize_url("http://www.example.com/do?k=b%a3"),
@@ -1085,6 +1091,17 @@ class CanonicalizeUrlTest(unittest.TestCase):
"http://www.example.com/path/to/%23/foo/bar?url=http%3A%2F%2Fwww.example.com%2F%2Fpath%2Fto%2F%23%2Fbar%2Ffoo#frag",
)
+ def test_strip_spaces(self):
+ self.assertEqual(
+ canonicalize_url(" https://example.com"), "https://example.com/"
+ )
+ self.assertEqual(
+ canonicalize_url("https://example.com "), "https://example.com/"
+ )
+ self.assertEqual(
+ canonicalize_url(" https://example.com "), "https://example.com/"
+ )
+
class DataURITests(unittest.TestCase):
def test_default_mediatype_charset(self):
|
`canonicalize_url` use of `safe_url_string` breaks when an encoded hash character is encountered
`canonicalize_url` will decode all percent encoded elements in a string.
if a hash `#` is present as a percent-encoded entity (`%23`) it will be decoded... however it shouldn't be as it is a rfc delimiter and fundamentally changes the URL structure -- turning the subsequent characters into a fragment. one of the effects is that a canonical url with a safely encoded hash will point to another url; another is that running the canonical on the output will return a different url.
example:
>>> import w3lib.url
>>> url = "https://example.com/path/to/foo%20bar%3a%20biz%20%2376%2c%20bang%202017#bash"
>>> canonical = w3lib.url.canonicalize_url(url)
>>> print canonical
https://example.com/path/to/foo%20bar:%20biz%20#76,%20bang%202017
>>> canonical2 = w3lib.url.canonicalize_url(canonical)
>>> print canonical2
https://example.com/path/to/foo%20bar:%20biz%20
what is presented as a fragment in "canonical": `#76,%20bang%202017` is part of the valid url - not a fragment - and is discarded when `canonicalize_url` is run again.
references:
* https://github.com/scrapy/w3lib/issues/5
|
0.0
|
4ba3539249cbe33491c9ab6768adab0b57747d52
|
[
"tests/test_url.py::CanonicalizeUrlTest::test_strip_spaces"
] |
[
"tests/test_url.py::UrlTests::test_add_or_replace_parameter",
"tests/test_url.py::UrlTests::test_add_or_replace_parameters",
"tests/test_url.py::UrlTests::test_add_or_replace_parameters_does_not_change_input_param",
"tests/test_url.py::UrlTests::test_any_to_uri",
"tests/test_url.py::UrlTests::test_file_uri_to_path",
"tests/test_url.py::UrlTests::test_is_url",
"tests/test_url.py::UrlTests::test_path_to_file_uri",
"tests/test_url.py::UrlTests::test_safe_download_url",
"tests/test_url.py::UrlTests::test_safe_url_idna",
"tests/test_url.py::UrlTests::test_safe_url_idna_encoding_failure",
"tests/test_url.py::UrlTests::test_safe_url_port_number",
"tests/test_url.py::UrlTests::test_safe_url_string",
"tests/test_url.py::UrlTests::test_safe_url_string_bytes_input",
"tests/test_url.py::UrlTests::test_safe_url_string_bytes_input_nonutf8",
"tests/test_url.py::UrlTests::test_safe_url_string_encode_idna_domain_with_port",
"tests/test_url.py::UrlTests::test_safe_url_string_encode_idna_domain_with_username_and_empty_password_and_port_number",
"tests/test_url.py::UrlTests::test_safe_url_string_encode_idna_domain_with_username_password_and_port_number",
"tests/test_url.py::UrlTests::test_safe_url_string_misc",
"tests/test_url.py::UrlTests::test_safe_url_string_preserve_nonfragment_hash",
"tests/test_url.py::UrlTests::test_safe_url_string_quote_path",
"tests/test_url.py::UrlTests::test_safe_url_string_remove_ascii_tab_and_newlines",
"tests/test_url.py::UrlTests::test_safe_url_string_unsafe_chars",
"tests/test_url.py::UrlTests::test_safe_url_string_user_and_pass_percentage_encoded",
"tests/test_url.py::UrlTests::test_safe_url_string_userinfo_unsafe_chars",
"tests/test_url.py::UrlTests::test_safe_url_string_with_query",
"tests/test_url.py::UrlTests::test_url_query_cleaner",
"tests/test_url.py::UrlTests::test_url_query_cleaner_keep_fragments",
"tests/test_url.py::UrlTests::test_url_query_parameter",
"tests/test_url.py::UrlTests::test_url_query_parameter_2",
"tests/test_url.py::CanonicalizeUrlTest::test_append_missing_path",
"tests/test_url.py::CanonicalizeUrlTest::test_canonicalize_idns",
"tests/test_url.py::CanonicalizeUrlTest::test_canonicalize_parse_url",
"tests/test_url.py::CanonicalizeUrlTest::test_canonicalize_url",
"tests/test_url.py::CanonicalizeUrlTest::test_canonicalize_url_idempotence",
"tests/test_url.py::CanonicalizeUrlTest::test_canonicalize_url_idna_exceptions",
"tests/test_url.py::CanonicalizeUrlTest::test_canonicalize_url_unicode_path",
"tests/test_url.py::CanonicalizeUrlTest::test_canonicalize_url_unicode_query_string",
"tests/test_url.py::CanonicalizeUrlTest::test_canonicalize_url_unicode_query_string_wrong_encoding",
"tests/test_url.py::CanonicalizeUrlTest::test_canonicalize_urlparsed",
"tests/test_url.py::CanonicalizeUrlTest::test_domains_are_case_insensitive",
"tests/test_url.py::CanonicalizeUrlTest::test_dont_convert_safe_characters",
"tests/test_url.py::CanonicalizeUrlTest::test_keep_blank_values",
"tests/test_url.py::CanonicalizeUrlTest::test_non_ascii_percent_encoding_in_paths",
"tests/test_url.py::CanonicalizeUrlTest::test_non_ascii_percent_encoding_in_query_arguments",
"tests/test_url.py::CanonicalizeUrlTest::test_normalize_percent_encoding_in_paths",
"tests/test_url.py::CanonicalizeUrlTest::test_normalize_percent_encoding_in_query_arguments",
"tests/test_url.py::CanonicalizeUrlTest::test_port_number",
"tests/test_url.py::CanonicalizeUrlTest::test_preserve_nonfragment_hash",
"tests/test_url.py::CanonicalizeUrlTest::test_quoted_slash_and_question_sign",
"tests/test_url.py::CanonicalizeUrlTest::test_remove_fragments",
"tests/test_url.py::CanonicalizeUrlTest::test_return_str",
"tests/test_url.py::CanonicalizeUrlTest::test_safe_characters_unicode",
"tests/test_url.py::CanonicalizeUrlTest::test_sorting",
"tests/test_url.py::CanonicalizeUrlTest::test_spaces",
"tests/test_url.py::CanonicalizeUrlTest::test_typical_usage",
"tests/test_url.py::CanonicalizeUrlTest::test_urls_with_auth_and_ports",
"tests/test_url.py::DataURITests::test_base64",
"tests/test_url.py::DataURITests::test_base64_spaces",
"tests/test_url.py::DataURITests::test_bytes_uri",
"tests/test_url.py::DataURITests::test_default_mediatype",
"tests/test_url.py::DataURITests::test_default_mediatype_charset",
"tests/test_url.py::DataURITests::test_mediatype_parameters",
"tests/test_url.py::DataURITests::test_missing_comma",
"tests/test_url.py::DataURITests::test_missing_scheme",
"tests/test_url.py::DataURITests::test_scheme_case_insensitive",
"tests/test_url.py::DataURITests::test_text_charset",
"tests/test_url.py::DataURITests::test_text_uri",
"tests/test_url.py::DataURITests::test_unicode_uri",
"tests/test_url.py::DataURITests::test_wrong_base64_param",
"tests/test_url.py::DataURITests::test_wrong_scheme"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_issue_reference"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-10-28 17:47:41+00:00
|
bsd-3-clause
| 5,430 |
|
scrapy__w3lib-202
|
diff --git a/w3lib/html.py b/w3lib/html.py
index a31d42b..0cff2ff 100644
--- a/w3lib/html.py
+++ b/w3lib/html.py
@@ -91,7 +91,7 @@ def replace_entities(
return bytes((number,)).decode("cp1252")
else:
return chr(number)
- except ValueError:
+ except (ValueError, OverflowError):
pass
return "" if remove_illegal and groups.get("semicolon") else m.group(0)
|
scrapy/w3lib
|
fb705667f38bfb93384a23fe8aca7efe532b8b47
|
diff --git a/tests/test_html.py b/tests/test_html.py
index 1e637b0..1cabf6d 100644
--- a/tests/test_html.py
+++ b/tests/test_html.py
@@ -65,6 +65,10 @@ class RemoveEntitiesTest(unittest.TestCase):
self.assertEqual(replace_entities("x≤y"), "x\u2264y")
self.assertEqual(replace_entities("xy"), "xy")
self.assertEqual(replace_entities("xy", remove_illegal=False), "xy")
+ self.assertEqual(replace_entities("�"), "")
+ self.assertEqual(
+ replace_entities("�", remove_illegal=False), "�"
+ )
def test_browser_hack(self):
# check browser hack for numeric character references in the 80-9F range
|
Function `convert_entity` does not catch `OverflowError`
Error:
```
OverflowError
Python int too large to convert to C int
```
`w3lib` version -> `2.0.1`
`Python` version -> `3.8.13`
<img width="1131" alt="Screenshot 2022-10-31 at 10 02 22" src="https://user-images.githubusercontent.com/107861298/198971171-1af35f01-42d2-413a-8c47-9d2c3dc6ece1.png">
|
0.0
|
fb705667f38bfb93384a23fe8aca7efe532b8b47
|
[
"tests/test_html.py::RemoveEntitiesTest::test_illegal_entities"
] |
[
"tests/test_html.py::RemoveEntitiesTest::test_browser_hack",
"tests/test_html.py::RemoveEntitiesTest::test_encoding",
"tests/test_html.py::RemoveEntitiesTest::test_keep_entities",
"tests/test_html.py::RemoveEntitiesTest::test_missing_semicolon",
"tests/test_html.py::RemoveEntitiesTest::test_regular",
"tests/test_html.py::RemoveEntitiesTest::test_returns_unicode",
"tests/test_html.py::ReplaceTagsTest::test_replace_tags",
"tests/test_html.py::ReplaceTagsTest::test_replace_tags_multiline",
"tests/test_html.py::ReplaceTagsTest::test_returns_unicode",
"tests/test_html.py::RemoveCommentsTest::test_no_comments",
"tests/test_html.py::RemoveCommentsTest::test_remove_comments",
"tests/test_html.py::RemoveCommentsTest::test_returns_unicode",
"tests/test_html.py::RemoveTagsTest::test_keep_argument",
"tests/test_html.py::RemoveTagsTest::test_remove_empty_tags",
"tests/test_html.py::RemoveTagsTest::test_remove_tags",
"tests/test_html.py::RemoveTagsTest::test_remove_tags_with_attributes",
"tests/test_html.py::RemoveTagsTest::test_remove_tags_without_tags",
"tests/test_html.py::RemoveTagsTest::test_returns_unicode",
"tests/test_html.py::RemoveTagsTest::test_uppercase_tags",
"tests/test_html.py::RemoveTagsWithContentTest::test_empty_tags",
"tests/test_html.py::RemoveTagsWithContentTest::test_returns_unicode",
"tests/test_html.py::RemoveTagsWithContentTest::test_tags_with_shared_prefix",
"tests/test_html.py::RemoveTagsWithContentTest::test_with_tags",
"tests/test_html.py::RemoveTagsWithContentTest::test_without_tags",
"tests/test_html.py::ReplaceEscapeCharsTest::test_returns_unicode",
"tests/test_html.py::ReplaceEscapeCharsTest::test_with_escape_chars",
"tests/test_html.py::ReplaceEscapeCharsTest::test_without_escape_chars",
"tests/test_html.py::UnquoteMarkupTest::test_returns_unicode",
"tests/test_html.py::UnquoteMarkupTest::test_unquote_markup",
"tests/test_html.py::GetBaseUrlTest::test_attributes_before_href",
"tests/test_html.py::GetBaseUrlTest::test_base_url_in_comment",
"tests/test_html.py::GetBaseUrlTest::test_get_base_url",
"tests/test_html.py::GetBaseUrlTest::test_get_base_url_latin1",
"tests/test_html.py::GetBaseUrlTest::test_get_base_url_latin1_percent",
"tests/test_html.py::GetBaseUrlTest::test_get_base_url_utf8",
"tests/test_html.py::GetBaseUrlTest::test_no_scheme_url",
"tests/test_html.py::GetBaseUrlTest::test_relative_url_with_absolute_path",
"tests/test_html.py::GetBaseUrlTest::test_tag_name",
"tests/test_html.py::GetMetaRefreshTest::test_commented_meta_refresh",
"tests/test_html.py::GetMetaRefreshTest::test_entities_in_redirect_url",
"tests/test_html.py::GetMetaRefreshTest::test_float_refresh_intervals",
"tests/test_html.py::GetMetaRefreshTest::test_get_meta_refresh",
"tests/test_html.py::GetMetaRefreshTest::test_html_comments_with_uncommented_meta_refresh",
"tests/test_html.py::GetMetaRefreshTest::test_inside_noscript",
"tests/test_html.py::GetMetaRefreshTest::test_inside_script",
"tests/test_html.py::GetMetaRefreshTest::test_leading_newline_in_url",
"tests/test_html.py::GetMetaRefreshTest::test_multiline",
"tests/test_html.py::GetMetaRefreshTest::test_nonascii_url_latin1",
"tests/test_html.py::GetMetaRefreshTest::test_nonascii_url_latin1_query",
"tests/test_html.py::GetMetaRefreshTest::test_nonascii_url_utf8",
"tests/test_html.py::GetMetaRefreshTest::test_redirections_in_different_ordering__in_meta_tag",
"tests/test_html.py::GetMetaRefreshTest::test_relative_redirects",
"tests/test_html.py::GetMetaRefreshTest::test_tag_name",
"tests/test_html.py::GetMetaRefreshTest::test_without_url"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks",
"has_media"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-11-09 16:08:34+00:00
|
bsd-3-clause
| 5,431 |
|
scrapy__w3lib-66
|
diff --git a/w3lib/url.py b/w3lib/url.py
index c3d8466..1bd8c7e 100644
--- a/w3lib/url.py
+++ b/w3lib/url.py
@@ -10,7 +10,8 @@ import warnings
import six
from six.moves.urllib.parse import (urljoin, urlsplit, urlunsplit,
urldefrag, urlencode, urlparse,
- quote, parse_qs, parse_qsl)
+ quote, parse_qs, parse_qsl,
+ ParseResult, unquote, urlunparse)
from six.moves.urllib.request import pathname2url, url2pathname
from w3lib.util import to_bytes, to_native_str, to_unicode
@@ -279,3 +280,174 @@ __all__ = ["add_or_replace_parameter", "any_to_uri", "file_uri_to_path",
# this last one is deprecated ; include it to be on the safe side
"urljoin_rfc"]
+
+
+def _safe_ParseResult(parts, encoding='utf8', path_encoding='utf8'):
+ # IDNA encoding can fail for too long labels (>63 characters)
+ # or missing labels (e.g. http://.example.com)
+ try:
+ netloc = parts.netloc.encode('idna')
+ except UnicodeError:
+ netloc = parts.netloc
+
+ return (
+ to_native_str(parts.scheme),
+ to_native_str(netloc),
+
+ # default encoding for path component SHOULD be UTF-8
+ quote(to_bytes(parts.path, path_encoding), _safe_chars),
+ quote(to_bytes(parts.params, path_encoding), _safe_chars),
+
+ # encoding of query and fragment follows page encoding
+ # or form-charset (if known and passed)
+ quote(to_bytes(parts.query, encoding), _safe_chars),
+ quote(to_bytes(parts.fragment, encoding), _safe_chars)
+ )
+
+
+def canonicalize_url(url, keep_blank_values=True, keep_fragments=False,
+ encoding=None):
+ """Canonicalize the given url by applying the following procedures:
+
+ - sort query arguments, first by key, then by value
+ - percent encode paths ; non-ASCII characters are percent-encoded
+ using UTF-8 (RFC-3986)
+ - percent encode query arguments ; non-ASCII characters are percent-encoded
+ using passed `encoding` (UTF-8 by default)
+ - normalize all spaces (in query arguments) '+' (plus symbol)
+ - normalize percent encodings case (%2f -> %2F)
+ - remove query arguments with blank values (unless `keep_blank_values` is True)
+ - remove fragments (unless `keep_fragments` is True)
+
+ The url passed can be bytes or unicode, while the url returned is
+ always a native str (bytes in Python 2, unicode in Python 3).
+
+ For examples see the tests in tests/test_utils_url.py
+ """
+ # If supplied `encoding` is not compatible with all characters in `url`,
+ # fallback to UTF-8 as safety net.
+ # UTF-8 can handle all Unicode characters,
+ # so we should be covered regarding URL normalization,
+ # if not for proper URL expected by remote website.
+ try:
+ scheme, netloc, path, params, query, fragment = _safe_ParseResult(
+ parse_url(url), encoding=encoding)
+ except UnicodeEncodeError as e:
+ scheme, netloc, path, params, query, fragment = _safe_ParseResult(
+ parse_url(url), encoding='utf8')
+
+ # 1. decode query-string as UTF-8 (or keep raw bytes),
+ # sort values,
+ # and percent-encode them back
+ if six.PY2:
+ keyvals = parse_qsl(query, keep_blank_values)
+ else:
+ # Python3's urllib.parse.parse_qsl does not work as wanted
+ # for percent-encoded characters that do not match passed encoding,
+ # they get lost.
+ #
+ # e.g., 'q=b%a3' becomes [('q', 'b\ufffd')]
+ # (ie. with 'REPLACEMENT CHARACTER' (U+FFFD),
+ # instead of \xa3 that you get with Python2's parse_qsl)
+ #
+ # what we want here is to keep raw bytes, and percent encode them
+ # so as to preserve whatever encoding what originally used.
+ #
+ # See https://tools.ietf.org/html/rfc3987#section-6.4:
+ #
+ # For example, it is possible to have a URI reference of
+ # "http://www.example.org/r%E9sum%E9.xml#r%C3%A9sum%C3%A9", where the
+ # document name is encoded in iso-8859-1 based on server settings, but
+ # where the fragment identifier is encoded in UTF-8 according to
+ # [XPointer]. The IRI corresponding to the above URI would be (in XML
+ # notation)
+ # "http://www.example.org/r%E9sum%E9.xml#résumé".
+ # Similar considerations apply to query parts. The functionality of
+ # IRIs (namely, to be able to include non-ASCII characters) can only be
+ # used if the query part is encoded in UTF-8.
+ keyvals = parse_qsl_to_bytes(query, keep_blank_values)
+ keyvals.sort()
+ query = urlencode(keyvals)
+
+ # 2. decode percent-encoded sequences in path as UTF-8 (or keep raw bytes)
+ # and percent-encode path again (this normalizes to upper-case %XX)
+ uqp = _unquotepath(path)
+ path = quote(uqp, _safe_chars) or '/'
+
+ fragment = '' if not keep_fragments else fragment
+
+ # every part should be safe already
+ return urlunparse((scheme, netloc.lower(), path, params, query, fragment))
+
+
+def _unquotepath(path):
+ for reserved in ('2f', '2F', '3f', '3F'):
+ path = path.replace('%' + reserved, '%25' + reserved.upper())
+
+ if six.PY2:
+ # in Python 2, '%a3' becomes '\xa3', which is what we want
+ return unquote(path)
+ else:
+ # in Python 3,
+ # standard lib's unquote() does not work for non-UTF-8
+ # percent-escaped characters, they get lost.
+ # e.g., '%a3' becomes 'REPLACEMENT CHARACTER' (U+FFFD)
+ #
+ # unquote_to_bytes() returns raw bytes instead
+ return unquote_to_bytes(path)
+
+
+def parse_url(url, encoding=None):
+ """Return urlparsed url from the given argument (which could be an already
+ parsed url)
+ """
+ if isinstance(url, ParseResult):
+ return url
+ return urlparse(to_unicode(url, encoding))
+
+
+if not six.PY2:
+ from urllib.parse import _coerce_args, unquote_to_bytes
+
+ def parse_qsl_to_bytes(qs, keep_blank_values=False):
+ """Parse a query given as a string argument.
+
+ Data are returned as a list of name, value pairs as bytes.
+
+ Arguments:
+
+ qs: percent-encoded query string to be parsed
+
+ keep_blank_values: flag indicating whether blank values in
+ percent-encoded queries should be treated as blank strings. A
+ true value indicates that blanks should be retained as blank
+ strings. The default false value indicates that blank values
+ are to be ignored and treated as if they were not included.
+
+ """
+ # This code is the same as Python3's parse_qsl()
+ # (at https://hg.python.org/cpython/rev/c38ac7ab8d9a)
+ # except for the unquote(s, encoding, errors) calls replaced
+ # with unquote_to_bytes(s)
+ qs, _coerce_result = _coerce_args(qs)
+ pairs = [s2 for s1 in qs.split('&') for s2 in s1.split(';')]
+ r = []
+ for name_value in pairs:
+ if not name_value:
+ continue
+ nv = name_value.split('=', 1)
+ if len(nv) != 2:
+ # Handle case of a control-name with no equal sign
+ if keep_blank_values:
+ nv.append('')
+ else:
+ continue
+ if len(nv[1]) or keep_blank_values:
+ name = nv[0].replace('+', ' ')
+ name = unquote_to_bytes(name)
+ name = _coerce_result(name)
+ value = nv[1].replace('+', ' ')
+ value = unquote_to_bytes(value)
+ value = _coerce_result(value)
+ r.append((name, value))
+ return r
|
scrapy/w3lib
|
9952180c8a623ef23881bf7b21f756a745630cfb
|
diff --git a/tests/test_url.py b/tests/test_url.py
index 7ac5d09..bfdd5bd 100644
--- a/tests/test_url.py
+++ b/tests/test_url.py
@@ -4,7 +4,10 @@ import os
import unittest
from w3lib.url import (is_url, safe_url_string, safe_download_url,
url_query_parameter, add_or_replace_parameter, url_query_cleaner,
- file_uri_to_path, path_to_file_uri, any_to_uri, urljoin_rfc)
+ file_uri_to_path, path_to_file_uri, any_to_uri, urljoin_rfc,
+ canonicalize_url, parse_url)
+from six.moves.urllib.parse import urlparse
+
class UrlTests(unittest.TestCase):
@@ -347,6 +350,209 @@ class UrlTests(unittest.TestCase):
self.assertEqual(jurl, b"http://www.example.com/test")
+class CanonicalizeUrlTest(unittest.TestCase):
+
+ def test_canonicalize_url(self):
+ # simplest case
+ self.assertEqual(canonicalize_url("http://www.example.com/"),
+ "http://www.example.com/")
+
+ def test_return_str(self):
+ assert isinstance(canonicalize_url(u"http://www.example.com"), str)
+ assert isinstance(canonicalize_url(b"http://www.example.com"), str)
+
+ def test_append_missing_path(self):
+ self.assertEqual(canonicalize_url("http://www.example.com"),
+ "http://www.example.com/")
+
+ def test_typical_usage(self):
+ self.assertEqual(canonicalize_url("http://www.example.com/do?a=1&b=2&c=3"),
+ "http://www.example.com/do?a=1&b=2&c=3")
+ self.assertEqual(canonicalize_url("http://www.example.com/do?c=1&b=2&a=3"),
+ "http://www.example.com/do?a=3&b=2&c=1")
+ self.assertEqual(canonicalize_url("http://www.example.com/do?&a=1"),
+ "http://www.example.com/do?a=1")
+
+ def test_sorting(self):
+ self.assertEqual(canonicalize_url("http://www.example.com/do?c=3&b=5&b=2&a=50"),
+ "http://www.example.com/do?a=50&b=2&b=5&c=3")
+
+ def test_keep_blank_values(self):
+ self.assertEqual(canonicalize_url("http://www.example.com/do?b=&a=2", keep_blank_values=False),
+ "http://www.example.com/do?a=2")
+ self.assertEqual(canonicalize_url("http://www.example.com/do?b=&a=2"),
+ "http://www.example.com/do?a=2&b=")
+ self.assertEqual(canonicalize_url("http://www.example.com/do?b=&c&a=2", keep_blank_values=False),
+ "http://www.example.com/do?a=2")
+ self.assertEqual(canonicalize_url("http://www.example.com/do?b=&c&a=2"),
+ "http://www.example.com/do?a=2&b=&c=")
+
+ self.assertEqual(canonicalize_url(u'http://www.example.com/do?1750,4'),
+ 'http://www.example.com/do?1750%2C4=')
+
+ def test_spaces(self):
+ self.assertEqual(canonicalize_url("http://www.example.com/do?q=a space&a=1"),
+ "http://www.example.com/do?a=1&q=a+space")
+ self.assertEqual(canonicalize_url("http://www.example.com/do?q=a+space&a=1"),
+ "http://www.example.com/do?a=1&q=a+space")
+ self.assertEqual(canonicalize_url("http://www.example.com/do?q=a%20space&a=1"),
+ "http://www.example.com/do?a=1&q=a+space")
+
+ def test_canonicalize_url_unicode_path(self):
+ self.assertEqual(canonicalize_url(u"http://www.example.com/résumé"),
+ "http://www.example.com/r%C3%A9sum%C3%A9")
+
+ def test_canonicalize_url_unicode_query_string(self):
+ # default encoding for path and query is UTF-8
+ self.assertEqual(canonicalize_url(u"http://www.example.com/résumé?q=résumé"),
+ "http://www.example.com/r%C3%A9sum%C3%A9?q=r%C3%A9sum%C3%A9")
+
+ # passed encoding will affect query string
+ self.assertEqual(canonicalize_url(u"http://www.example.com/résumé?q=résumé", encoding='latin1'),
+ "http://www.example.com/r%C3%A9sum%C3%A9?q=r%E9sum%E9")
+
+ self.assertEqual(canonicalize_url(u"http://www.example.com/résumé?country=Россия", encoding='cp1251'),
+ "http://www.example.com/r%C3%A9sum%C3%A9?country=%D0%EE%F1%F1%E8%FF")
+
+ def test_canonicalize_url_unicode_query_string_wrong_encoding(self):
+ # trying to encode with wrong encoding
+ # fallback to UTF-8
+ self.assertEqual(canonicalize_url(u"http://www.example.com/résumé?currency=€", encoding='latin1'),
+ "http://www.example.com/r%C3%A9sum%C3%A9?currency=%E2%82%AC")
+
+ self.assertEqual(canonicalize_url(u"http://www.example.com/résumé?country=Россия", encoding='latin1'),
+ "http://www.example.com/r%C3%A9sum%C3%A9?country=%D0%A0%D0%BE%D1%81%D1%81%D0%B8%D1%8F")
+
+ def test_normalize_percent_encoding_in_paths(self):
+ self.assertEqual(canonicalize_url("http://www.example.com/r%c3%a9sum%c3%a9"),
+ "http://www.example.com/r%C3%A9sum%C3%A9")
+
+ # non-UTF8 encoded sequences: they should be kept untouched, only upper-cased
+ # 'latin1'-encoded sequence in path
+ self.assertEqual(canonicalize_url("http://www.example.com/a%a3do"),
+ "http://www.example.com/a%A3do")
+
+ # 'latin1'-encoded path, UTF-8 encoded query string
+ self.assertEqual(canonicalize_url("http://www.example.com/a%a3do?q=r%c3%a9sum%c3%a9"),
+ "http://www.example.com/a%A3do?q=r%C3%A9sum%C3%A9")
+
+ # 'latin1'-encoded path and query string
+ self.assertEqual(canonicalize_url("http://www.example.com/a%a3do?q=r%e9sum%e9"),
+ "http://www.example.com/a%A3do?q=r%E9sum%E9")
+
+ def test_normalize_percent_encoding_in_query_arguments(self):
+ self.assertEqual(canonicalize_url("http://www.example.com/do?k=b%a3"),
+ "http://www.example.com/do?k=b%A3")
+
+ self.assertEqual(canonicalize_url("http://www.example.com/do?k=r%c3%a9sum%c3%a9"),
+ "http://www.example.com/do?k=r%C3%A9sum%C3%A9")
+
+ def test_non_ascii_percent_encoding_in_paths(self):
+ self.assertEqual(canonicalize_url("http://www.example.com/a do?a=1"),
+ "http://www.example.com/a%20do?a=1"),
+ self.assertEqual(canonicalize_url("http://www.example.com/a %20do?a=1"),
+ "http://www.example.com/a%20%20do?a=1"),
+ self.assertEqual(canonicalize_url(u"http://www.example.com/a do£.html?a=1"),
+ "http://www.example.com/a%20do%C2%A3.html?a=1")
+ self.assertEqual(canonicalize_url(b"http://www.example.com/a do\xc2\xa3.html?a=1"),
+ "http://www.example.com/a%20do%C2%A3.html?a=1")
+
+ def test_non_ascii_percent_encoding_in_query_arguments(self):
+ self.assertEqual(canonicalize_url(u"http://www.example.com/do?price=£500&a=5&z=3"),
+ u"http://www.example.com/do?a=5&price=%C2%A3500&z=3")
+ self.assertEqual(canonicalize_url(b"http://www.example.com/do?price=\xc2\xa3500&a=5&z=3"),
+ "http://www.example.com/do?a=5&price=%C2%A3500&z=3")
+ self.assertEqual(canonicalize_url(b"http://www.example.com/do?price(\xc2\xa3)=500&a=1"),
+ "http://www.example.com/do?a=1&price%28%C2%A3%29=500")
+
+ def test_urls_with_auth_and_ports(self):
+ self.assertEqual(canonicalize_url(u"http://user:[email protected]:81/do?now=1"),
+ u"http://user:[email protected]:81/do?now=1")
+
+ def test_remove_fragments(self):
+ self.assertEqual(canonicalize_url(u"http://user:[email protected]/do?a=1#frag"),
+ u"http://user:[email protected]/do?a=1")
+ self.assertEqual(canonicalize_url(u"http://user:[email protected]/do?a=1#frag", keep_fragments=True),
+ u"http://user:[email protected]/do?a=1#frag")
+
+ def test_dont_convert_safe_characters(self):
+ # dont convert safe characters to percent encoding representation
+ self.assertEqual(canonicalize_url(
+ "http://www.simplybedrooms.com/White-Bedroom-Furniture/Bedroom-Mirror:-Josephine-Cheval-Mirror.html"),
+ "http://www.simplybedrooms.com/White-Bedroom-Furniture/Bedroom-Mirror:-Josephine-Cheval-Mirror.html")
+
+ def test_safe_characters_unicode(self):
+ # urllib.quote uses a mapping cache of encoded characters. when parsing
+ # an already percent-encoded url, it will fail if that url was not
+ # percent-encoded as utf-8, that's why canonicalize_url must always
+ # convert the urls to string. the following test asserts that
+ # functionality.
+ self.assertEqual(canonicalize_url(u'http://www.example.com/caf%E9-con-leche.htm'),
+ 'http://www.example.com/caf%E9-con-leche.htm')
+
+ def test_domains_are_case_insensitive(self):
+ self.assertEqual(canonicalize_url("http://www.EXAMPLE.com/"),
+ "http://www.example.com/")
+
+ def test_canonicalize_idns(self):
+ self.assertEqual(canonicalize_url(u'http://www.bücher.de?q=bücher'),
+ 'http://www.xn--bcher-kva.de/?q=b%C3%BCcher')
+ # Japanese (+ reordering query parameters)
+ self.assertEqual(canonicalize_url(u'http://はじめよう.みんな/?query=サ&maxResults=5'),
+ 'http://xn--p8j9a0d9c9a.xn--q9jyb4c/?maxResults=5&query=%E3%82%B5')
+
+ def test_quoted_slash_and_question_sign(self):
+ self.assertEqual(canonicalize_url("http://foo.com/AC%2FDC+rocks%3f/?yeah=1"),
+ "http://foo.com/AC%2FDC+rocks%3F/?yeah=1")
+ self.assertEqual(canonicalize_url("http://foo.com/AC%2FDC/"),
+ "http://foo.com/AC%2FDC/")
+
+ def test_canonicalize_urlparsed(self):
+ # canonicalize_url() can be passed an already urlparse'd URL
+ self.assertEqual(canonicalize_url(urlparse(u"http://www.example.com/résumé?q=résumé")),
+ "http://www.example.com/r%C3%A9sum%C3%A9?q=r%C3%A9sum%C3%A9")
+ self.assertEqual(canonicalize_url(urlparse('http://www.example.com/caf%e9-con-leche.htm')),
+ 'http://www.example.com/caf%E9-con-leche.htm')
+ self.assertEqual(canonicalize_url(urlparse("http://www.example.com/a%a3do?q=r%c3%a9sum%c3%a9")),
+ "http://www.example.com/a%A3do?q=r%C3%A9sum%C3%A9")
+
+ def test_canonicalize_parse_url(self):
+ # parse_url() wraps urlparse and is used in link extractors
+ self.assertEqual(canonicalize_url(parse_url(u"http://www.example.com/résumé?q=résumé")),
+ "http://www.example.com/r%C3%A9sum%C3%A9?q=r%C3%A9sum%C3%A9")
+ self.assertEqual(canonicalize_url(parse_url('http://www.example.com/caf%e9-con-leche.htm')),
+ 'http://www.example.com/caf%E9-con-leche.htm')
+ self.assertEqual(canonicalize_url(parse_url("http://www.example.com/a%a3do?q=r%c3%a9sum%c3%a9")),
+ "http://www.example.com/a%A3do?q=r%C3%A9sum%C3%A9")
+
+ def test_canonicalize_url_idempotence(self):
+ for url, enc in [(u'http://www.bücher.de/résumé?q=résumé', 'utf8'),
+ (u'http://www.example.com/résumé?q=résumé', 'latin1'),
+ (u'http://www.example.com/résumé?country=Россия', 'cp1251'),
+ (u'http://はじめよう.みんな/?query=サ&maxResults=5', 'iso2022jp')]:
+ canonicalized = canonicalize_url(url, encoding=enc)
+
+ # if we canonicalize again, we ge the same result
+ self.assertEqual(canonicalize_url(canonicalized, encoding=enc), canonicalized)
+
+ # without encoding, already canonicalized URL is canonicalized identically
+ self.assertEqual(canonicalize_url(canonicalized), canonicalized)
+
+ def test_canonicalize_url_idna_exceptions(self):
+ # missing DNS label
+ self.assertEqual(
+ canonicalize_url(u"http://.example.com/résumé?q=résumé"),
+ "http://.example.com/r%C3%A9sum%C3%A9?q=r%C3%A9sum%C3%A9")
+
+ # DNS label too long
+ self.assertEqual(
+ canonicalize_url(
+ u"http://www.{label}.com/résumé?q=résumé".format(
+ label=u"example"*11)),
+ "http://www.{label}.com/r%C3%A9sum%C3%A9?q=r%C3%A9sum%C3%A9".format(
+ label=u"example"*11))
+
+
if __name__ == "__main__":
unittest.main()
|
Add canonicalize_url() to w3lib.url
The idea is to move scrapy's `canonicalize_url()` helper to `w3lib.url`
Projects like frontera could be interested: see https://github.com/scrapinghub/frontera/pull/168#issuecomment-234558699
|
0.0
|
9952180c8a623ef23881bf7b21f756a745630cfb
|
[
"tests/test_url.py::UrlTests::test_any_to_uri",
"tests/test_url.py::UrlTests::test_file_uri_to_path",
"tests/test_url.py::UrlTests::test_is_url",
"tests/test_url.py::UrlTests::test_path_to_file_uri",
"tests/test_url.py::UrlTests::test_safe_download_url",
"tests/test_url.py::UrlTests::test_safe_url_idna",
"tests/test_url.py::UrlTests::test_safe_url_idna_encoding_failure",
"tests/test_url.py::UrlTests::test_safe_url_string",
"tests/test_url.py::UrlTests::test_safe_url_string_bytes_input",
"tests/test_url.py::UrlTests::test_safe_url_string_bytes_input_nonutf8",
"tests/test_url.py::UrlTests::test_safe_url_string_misc",
"tests/test_url.py::UrlTests::test_safe_url_string_with_query",
"tests/test_url.py::UrlTests::test_url_query_cleaner",
"tests/test_url.py::UrlTests::test_url_query_parameter",
"tests/test_url.py::UrlTests::test_url_query_parameter_2",
"tests/test_url.py::UrlTests::test_urljoin_rfc_deprecated",
"tests/test_url.py::CanonicalizeUrlTest::test_append_missing_path",
"tests/test_url.py::CanonicalizeUrlTest::test_canonicalize_idns",
"tests/test_url.py::CanonicalizeUrlTest::test_canonicalize_parse_url",
"tests/test_url.py::CanonicalizeUrlTest::test_canonicalize_url",
"tests/test_url.py::CanonicalizeUrlTest::test_canonicalize_url_idempotence",
"tests/test_url.py::CanonicalizeUrlTest::test_canonicalize_url_idna_exceptions",
"tests/test_url.py::CanonicalizeUrlTest::test_canonicalize_url_unicode_path",
"tests/test_url.py::CanonicalizeUrlTest::test_canonicalize_url_unicode_query_string",
"tests/test_url.py::CanonicalizeUrlTest::test_canonicalize_url_unicode_query_string_wrong_encoding",
"tests/test_url.py::CanonicalizeUrlTest::test_canonicalize_urlparsed",
"tests/test_url.py::CanonicalizeUrlTest::test_domains_are_case_insensitive",
"tests/test_url.py::CanonicalizeUrlTest::test_dont_convert_safe_characters",
"tests/test_url.py::CanonicalizeUrlTest::test_keep_blank_values",
"tests/test_url.py::CanonicalizeUrlTest::test_non_ascii_percent_encoding_in_paths",
"tests/test_url.py::CanonicalizeUrlTest::test_non_ascii_percent_encoding_in_query_arguments",
"tests/test_url.py::CanonicalizeUrlTest::test_normalize_percent_encoding_in_paths",
"tests/test_url.py::CanonicalizeUrlTest::test_normalize_percent_encoding_in_query_arguments",
"tests/test_url.py::CanonicalizeUrlTest::test_quoted_slash_and_question_sign",
"tests/test_url.py::CanonicalizeUrlTest::test_remove_fragments",
"tests/test_url.py::CanonicalizeUrlTest::test_return_str",
"tests/test_url.py::CanonicalizeUrlTest::test_safe_characters_unicode",
"tests/test_url.py::CanonicalizeUrlTest::test_sorting",
"tests/test_url.py::CanonicalizeUrlTest::test_spaces",
"tests/test_url.py::CanonicalizeUrlTest::test_typical_usage",
"tests/test_url.py::CanonicalizeUrlTest::test_urls_with_auth_and_ports"
] |
[] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
}
|
2016-07-26 12:20:16+00:00
|
bsd-3-clause
| 5,432 |
|
scrapy__w3lib-77
|
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 50f3226..ee3f8e5 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -35,10 +35,10 @@ jobs:
TOXENV: typing
steps:
- - uses: actions/checkout@v2
+ - uses: actions/checkout@v3
- name: Set up Python ${{ matrix.python-version }}
- uses: actions/setup-python@v2
+ uses: actions/setup-python@v4
with:
python-version: ${{ matrix.python-version }}
diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml
index 787f56a..f694f42 100644
--- a/.github/workflows/publish.yml
+++ b/.github/workflows/publish.yml
@@ -10,10 +10,10 @@ jobs:
runs-on: ubuntu-latest
steps:
- - uses: actions/checkout@v2
+ - uses: actions/checkout@v3
- name: Set up Python 3.9
- uses: actions/setup-python@v2
+ uses: actions/setup-python@v4
with:
python-version: 3.9
diff --git a/README.rst b/README.rst
index 13745f8..5664183 100644
--- a/README.rst
+++ b/README.rst
@@ -27,7 +27,7 @@ This is a Python library of web-related functions, such as:
Requirements
============
-Python 3.6+
+Python 3.7+
Install
=======
diff --git a/docs/index.rst b/docs/index.rst
index bd14188..aa1c851 100644
--- a/docs/index.rst
+++ b/docs/index.rst
@@ -28,7 +28,7 @@ Modules
Requirements
============
-Python 3.6+
+Python 3.7+
Install
=======
diff --git a/setup.py b/setup.py
index fe1e5fe..7fdb3b1 100644
--- a/setup.py
+++ b/setup.py
@@ -16,14 +16,13 @@ setup(
include_package_data=True,
zip_safe=False,
platforms=["Any"],
- python_requires=">=3.6",
+ python_requires=">=3.7",
classifiers=[
"Development Status :: 5 - Production/Stable",
"License :: OSI Approved :: BSD License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
- "Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
diff --git a/w3lib/html.py b/w3lib/html.py
index a4be054..a31d42b 100644
--- a/w3lib/html.py
+++ b/w3lib/html.py
@@ -311,7 +311,7 @@ def get_base_url(
"""
- utext = to_unicode(text, encoding)
+ utext: str = remove_comments(text, encoding=encoding)
m = _baseurl_re.search(utext)
if m:
return urljoin(
|
scrapy/w3lib
|
8e19741b6b004d6248fb70b525255a96a1eb1ee6
|
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
index 6bd16ed..031ee7b 100644
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -14,13 +14,13 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
- python-version: ["3.6", "3.7", "3.8", "3.9", "3.10", "3.11.0-rc.2", "pypy3"]
+ python-version: ["3.7", "3.8", "3.9", "3.10", "3.11", "pypy3.7"]
steps:
- - uses: actions/checkout@v2
+ - uses: actions/checkout@v3
- name: Set up Python ${{ matrix.python-version }}
- uses: actions/setup-python@v2
+ uses: actions/setup-python@v4
with:
python-version: ${{ matrix.python-version }}
diff --git a/tests/test_html.py b/tests/test_html.py
index d4861ba..1e637b0 100644
--- a/tests/test_html.py
+++ b/tests/test_html.py
@@ -372,6 +372,30 @@ class GetBaseUrlTest(unittest.TestCase):
get_base_url(text, baseurl.encode("ascii")), "http://example.org/something"
)
+ def test_base_url_in_comment(self):
+ self.assertEqual(
+ get_base_url("""<!-- <base href="http://example.com/"/> -->"""), ""
+ )
+ self.assertEqual(
+ get_base_url("""<!-- <base href="http://example.com/"/>"""), ""
+ )
+ self.assertEqual(
+ get_base_url("""<!-- <base href="http://example.com/"/> --"""), ""
+ )
+ self.assertEqual(
+ get_base_url(
+ """<!-- <!-- <base href="http://example.com/"/> -- --> <base href="http://example_2.com/"/> """
+ ),
+ "http://example_2.com/",
+ )
+
+ self.assertEqual(
+ get_base_url(
+ """<!-- <base href="http://example.com/"/> --> <!-- <base href="http://example_2.com/"/> --> <base href="http://example_3.com/"/>"""
+ ),
+ "http://example_3.com/",
+ )
+
def test_relative_url_with_absolute_path(self):
baseurl = "https://example.org"
text = """\
|
It's not a good idead to parse HTML text using regular expressions
In [`w3lib.html`](https://github.com/scrapy/w3lib/blob/master/w3lib/html.py) regular expressions are used to parse HTML texts:
``` python
_ent_re = re.compile(r'&((?P<named>[a-z\d]+)|#(?P<dec>\d+)|#x(?P<hex>[a-f\d]+))(?P<semicolon>;?)', re.IGNORECASE)
_tag_re = re.compile(r'<[a-zA-Z\/!].*?>', re.DOTALL)
_baseurl_re = re.compile(six.u(r'<base\s[^>]*href\s*=\s*[\"\']\s*([^\"\'\s]+)\s*[\"\']'), re.I)
_meta_refresh_re = re.compile(six.u(r'<meta\s[^>]*http-equiv[^>]*refresh[^>]*content\s*=\s*(?P<quote>["\'])(?P<int>(\d*\.)?\d+)\s*;\s*url=\s*(?P<url>.*?)(?P=quote)'), re.DOTALL | re.IGNORECASE)
_cdata_re = re.compile(r'((?P<cdata_s><!\[CDATA\[)(?P<cdata_d>.*?)(?P<cdata_e>\]\]>))', re.DOTALL)
```
However this is definitely incorrect when it involves commented contents, e.g.
``` python
>>> from w3lib import html
>>> html.get_base_url("""<!-- <base href="http://example.com/" /> -->""")
'http://example.com/'
```
Introducing "heavier" utilities like `lxml` would solve this issue easily, but that might be an awful idea as `w3lib` aims to be lightweight & fast.
Or maybe we could implement some quick parser merely for eliminating the commented parts.
Any ideas?
|
0.0
|
8e19741b6b004d6248fb70b525255a96a1eb1ee6
|
[
"tests/test_html.py::GetBaseUrlTest::test_base_url_in_comment"
] |
[
"tests/test_html.py::RemoveEntitiesTest::test_browser_hack",
"tests/test_html.py::RemoveEntitiesTest::test_encoding",
"tests/test_html.py::RemoveEntitiesTest::test_illegal_entities",
"tests/test_html.py::RemoveEntitiesTest::test_keep_entities",
"tests/test_html.py::RemoveEntitiesTest::test_missing_semicolon",
"tests/test_html.py::RemoveEntitiesTest::test_regular",
"tests/test_html.py::RemoveEntitiesTest::test_returns_unicode",
"tests/test_html.py::ReplaceTagsTest::test_replace_tags",
"tests/test_html.py::ReplaceTagsTest::test_replace_tags_multiline",
"tests/test_html.py::ReplaceTagsTest::test_returns_unicode",
"tests/test_html.py::RemoveCommentsTest::test_no_comments",
"tests/test_html.py::RemoveCommentsTest::test_remove_comments",
"tests/test_html.py::RemoveCommentsTest::test_returns_unicode",
"tests/test_html.py::RemoveTagsTest::test_keep_argument",
"tests/test_html.py::RemoveTagsTest::test_remove_empty_tags",
"tests/test_html.py::RemoveTagsTest::test_remove_tags",
"tests/test_html.py::RemoveTagsTest::test_remove_tags_with_attributes",
"tests/test_html.py::RemoveTagsTest::test_remove_tags_without_tags",
"tests/test_html.py::RemoveTagsTest::test_returns_unicode",
"tests/test_html.py::RemoveTagsTest::test_uppercase_tags",
"tests/test_html.py::RemoveTagsWithContentTest::test_empty_tags",
"tests/test_html.py::RemoveTagsWithContentTest::test_returns_unicode",
"tests/test_html.py::RemoveTagsWithContentTest::test_tags_with_shared_prefix",
"tests/test_html.py::RemoveTagsWithContentTest::test_with_tags",
"tests/test_html.py::RemoveTagsWithContentTest::test_without_tags",
"tests/test_html.py::ReplaceEscapeCharsTest::test_returns_unicode",
"tests/test_html.py::ReplaceEscapeCharsTest::test_with_escape_chars",
"tests/test_html.py::ReplaceEscapeCharsTest::test_without_escape_chars",
"tests/test_html.py::UnquoteMarkupTest::test_returns_unicode",
"tests/test_html.py::UnquoteMarkupTest::test_unquote_markup",
"tests/test_html.py::GetBaseUrlTest::test_attributes_before_href",
"tests/test_html.py::GetBaseUrlTest::test_get_base_url",
"tests/test_html.py::GetBaseUrlTest::test_get_base_url_latin1",
"tests/test_html.py::GetBaseUrlTest::test_get_base_url_latin1_percent",
"tests/test_html.py::GetBaseUrlTest::test_get_base_url_utf8",
"tests/test_html.py::GetBaseUrlTest::test_no_scheme_url",
"tests/test_html.py::GetBaseUrlTest::test_relative_url_with_absolute_path",
"tests/test_html.py::GetBaseUrlTest::test_tag_name",
"tests/test_html.py::GetMetaRefreshTest::test_commented_meta_refresh",
"tests/test_html.py::GetMetaRefreshTest::test_entities_in_redirect_url",
"tests/test_html.py::GetMetaRefreshTest::test_float_refresh_intervals",
"tests/test_html.py::GetMetaRefreshTest::test_get_meta_refresh",
"tests/test_html.py::GetMetaRefreshTest::test_html_comments_with_uncommented_meta_refresh",
"tests/test_html.py::GetMetaRefreshTest::test_inside_noscript",
"tests/test_html.py::GetMetaRefreshTest::test_inside_script",
"tests/test_html.py::GetMetaRefreshTest::test_leading_newline_in_url",
"tests/test_html.py::GetMetaRefreshTest::test_multiline",
"tests/test_html.py::GetMetaRefreshTest::test_nonascii_url_latin1",
"tests/test_html.py::GetMetaRefreshTest::test_nonascii_url_latin1_query",
"tests/test_html.py::GetMetaRefreshTest::test_nonascii_url_utf8",
"tests/test_html.py::GetMetaRefreshTest::test_redirections_in_different_ordering__in_meta_tag",
"tests/test_html.py::GetMetaRefreshTest::test_relative_redirects",
"tests/test_html.py::GetMetaRefreshTest::test_tag_name",
"tests/test_html.py::GetMetaRefreshTest::test_without_url"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2016-10-25 06:37:29+00:00
|
bsd-3-clause
| 5,433 |
|
scverse__scanpy-2859
|
diff --git a/docs/release-notes/1.10.0.md b/docs/release-notes/1.10.0.md
index 7d48d4fd..1bb50c89 100644
--- a/docs/release-notes/1.10.0.md
+++ b/docs/release-notes/1.10.0.md
@@ -18,6 +18,7 @@
* {func}`scanpy.tl.rank_genes_groups` no longer warns that it's default was changed from t-test_overestim_var to t-test {pr}`2798` {smaller}`L Heumos`
* {func}`scanpy.pp.highly_variable_genes` has new flavor `seurat_v3_paper` that is in its implementation consistent with the paper description in Stuart et al 2018. {pr}`2792` {smaller}`E Roellin`
* {func}`scanpy.pp.highly_variable_genes` supports dask for the default `seurat` and `cell_ranger` flavors {pr}`2809` {smaller}`P Angerer`
+* Auto conversion of strings to collections in `scanpy.pp.calculate_qc_metrics` {pr}`2859` {smaller}`N Teyssier`
```{rubric} Docs
```
diff --git a/scanpy/preprocessing/_qc.py b/scanpy/preprocessing/_qc.py
index 241afb32..4d1123f6 100644
--- a/scanpy/preprocessing/_qc.py
+++ b/scanpy/preprocessing/_qc.py
@@ -233,7 +233,7 @@ def calculate_qc_metrics(
*,
expr_type: str = "counts",
var_type: str = "genes",
- qc_vars: Collection[str] = (),
+ qc_vars: Collection[str] | str = (),
percent_top: Collection[int] | None = (50, 100, 200, 500),
layer: str | None = None,
use_raw: bool = False,
@@ -308,6 +308,10 @@ def calculate_qc_metrics(
if issparse(X):
X.eliminate_zeros()
+ # Convert qc_vars to list if str
+ if isinstance(qc_vars, str):
+ qc_vars = [qc_vars]
+
obs_metrics = describe_obs(
adata,
expr_type=expr_type,
|
scverse/scanpy
|
d7607e58f9540a8ae502ecae42db80598771f962
|
diff --git a/scanpy/tests/test_qc_metrics.py b/scanpy/tests/test_qc_metrics.py
index 06a4d0ce..83971fa2 100644
--- a/scanpy/tests/test_qc_metrics.py
+++ b/scanpy/tests/test_qc_metrics.py
@@ -143,6 +143,16 @@ def test_qc_metrics_format(cls):
assert np.allclose(adata.var[col], adata_dense.var[col])
+def test_qc_metrics_format_str_qc_vars():
+ adata_dense, init_var = adata_mito()
+ sc.pp.calculate_qc_metrics(adata_dense, qc_vars="mito", inplace=True)
+ adata = AnnData(X=adata_dense.X, var=init_var.copy())
+ sc.pp.calculate_qc_metrics(adata, qc_vars="mito", inplace=True)
+ assert np.allclose(adata.obs, adata_dense.obs)
+ for col in adata.var: # np.allclose doesn't like mix of types
+ assert np.allclose(adata.var[col], adata_dense.var[col])
+
+
def test_qc_metrics_percentage(): # In response to #421
adata_dense, init_var = adata_mito()
sc.pp.calculate_qc_metrics(adata_dense, percent_top=[])
|
String conversion of `qc_vars` into a `Collection` when a `str` input is provided in `calculate_qc_metrics`
### What kind of feature would you like to request?
Additional function parameters / changed functionality / changed defaults?
### Please describe your wishes
I often make the mistake of providing a single string input to the `qc_vars` argument in `calculate_qc_metrics` which always fails with a `KeyError` because it beings to iterate over the string. This could be a very simple addition to just convert the argument into a `list` if a `str` is provided as input.
|
0.0
|
d7607e58f9540a8ae502ecae42db80598771f962
|
[
"scanpy/tests/test_qc_metrics.py::test_qc_metrics_format_str_qc_vars"
] |
[
"scanpy/tests/test_qc_metrics.py::test_proportions[dense]",
"scanpy/tests/test_qc_metrics.py::test_proportions[sparse]",
"scanpy/tests/test_qc_metrics.py::test_segments_binary",
"scanpy/tests/test_qc_metrics.py::test_top_segments[asarray]",
"scanpy/tests/test_qc_metrics.py::test_top_segments[csr_matrix]",
"scanpy/tests/test_qc_metrics.py::test_top_segments[csc_matrix]",
"scanpy/tests/test_qc_metrics.py::test_top_segments[coo_matrix]",
"scanpy/tests/test_qc_metrics.py::test_qc_metrics",
"scanpy/tests/test_qc_metrics.py::test_qc_metrics_format[asarray]",
"scanpy/tests/test_qc_metrics.py::test_qc_metrics_format[csr_matrix]",
"scanpy/tests/test_qc_metrics.py::test_qc_metrics_format[csc_matrix]",
"scanpy/tests/test_qc_metrics.py::test_qc_metrics_format[coo_matrix]",
"scanpy/tests/test_qc_metrics.py::test_qc_metrics_percentage",
"scanpy/tests/test_qc_metrics.py::test_layer_raw",
"scanpy/tests/test_qc_metrics.py::test_inner_methods"
] |
{
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2024-02-15 18:11:23+00:00
|
bsd-3-clause
| 5,434 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.