instance_id
stringlengths 10
57
| patch
stringlengths 261
37.7k
| repo
stringlengths 7
53
| base_commit
stringlengths 40
40
| hints_text
stringclasses 301
values | test_patch
stringlengths 212
2.22M
| problem_statement
stringlengths 23
37.7k
| version
int64 0
0
| environment_setup_commit
stringclasses 89
values | FAIL_TO_PASS
sequencelengths 1
4.94k
| PASS_TO_PASS
sequencelengths 0
7.82k
| meta
dict | created_at
unknown | license
stringclasses 8
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
RadioAstronomySoftwareGroup__pyuvsim-448 | diff --git a/README.md b/README.md
index 530118e..c5f7d9f 100644
--- a/README.md
+++ b/README.md
@@ -20,6 +20,7 @@ precision necessary for 21cm cosmology science,
1. High level of test coverage including accuracy (design goal is 97%).
2. Testing against analytic calculations, monitored by continuous integration (see memo #XXX)
3. Comparison with external simulations with standardized reference simulations
+
## Usability and extensibility
A secondary goal is a community simulation environment which provides well documented and flexible code to support a diversity of use cases.
Key elements of this approach include:
@@ -41,6 +42,14 @@ Each addition of new physics is validated against analytic calculations and incl
1. Time domain sources (TODO)
1. Ionospheric scintillation (TODO)
+# Citation
+Please cite pyuvsim by citing our JOSS paper:
+
+Lanman et al., (2019). pyuvsim: A comprehensive simulation package for radio
+interferometers in python. Journal of Open Source Software, 4(37), 1234,
+https://doi.org/10.21105/joss.01234
+
+[ADS Link](https://ui.adsabs.harvard.edu/abs/2019JOSS....4.1234L/abstract)
## Installation
@@ -174,9 +183,14 @@ We use a `generation.major.minor` format.
Testing: Backed by unittests, internal model validation, and significant external comparison.
* Major - Adds new physical effect or major computational improvement. Small number of improvements with each release.
Testing: Backed by unittests, internal model validation and limited external comparison.
-* Minor - Bug fixes and small improvements not expected to change physical model.
+* Minor - Bug fixes and small improvements not expected to change physical model
+and which do not include breaking API changes.
Testing: Backed by unittests
+We do our best to provide a significant period (usually 2 major generations) of
+deprecation warnings for all breaking changes to the API.
+We track all changes in our [changelog](https://github.com/RadioAstronomySoftwareGroup/pyuvsim/blob/main/CHANGELOG.md).
+
### Some helpful definitions
* __Physical effects__: things like polarization effects, noise, ionospheric modeling, or nonterrestrial observing positions.
* __Major computational improvement__: Support for new catalog types (e.g, diffuse maps), new analysis tools, changes to parallelization scheme
diff --git a/ci/min_deps.yaml b/ci/min_deps.yaml
index 87e1c5b..60d89a1 100644
--- a/ci/min_deps.yaml
+++ b/ci/min_deps.yaml
@@ -10,6 +10,7 @@ dependencies:
- pip
- pytest
- pytest-cov
+ - pytest-xdist
- pyuvdata>=2.2.10
- pyyaml>=5.1
- scipy>=1.3
diff --git a/ci/min_versions.yaml b/ci/min_versions.yaml
index 13f2305..8b4c7ed 100644
--- a/ci/min_versions.yaml
+++ b/ci/min_versions.yaml
@@ -16,6 +16,7 @@ dependencies:
- python-casacore==3.3.1
- pytest
- pytest-cov
+ - pytest-xdist
- pyuvdata==2.2.10
- pyyaml==5.1.*
- scipy==1.3.*
diff --git a/pyuvsim/simsetup.py b/pyuvsim/simsetup.py
index 8dfb2b1..c7dbf44 100644
--- a/pyuvsim/simsetup.py
+++ b/pyuvsim/simsetup.py
@@ -2028,13 +2028,13 @@ def initialize_uvdata_from_keywords(
# Increment name appropriately:
output_layout_filepath = os.path.join(path_out, output_layout_filename)
output_layout_filename = os.path.basename(
- check_file_exists_and_increment(output_layout_filepath, 'csv')
+ check_file_exists_and_increment(output_layout_filepath)
)
if output_yaml_filename is None:
output_yaml_filename = 'obsparam.yaml'
output_yaml_filename = check_file_exists_and_increment(
- os.path.join(path_out, output_yaml_filename), 'yaml'
+ os.path.join(path_out, output_yaml_filename)
)
if antenna_layout_filepath is not None:
diff --git a/pyuvsim/utils.py b/pyuvsim/utils.py
index d3bc5a2..654d677 100644
--- a/pyuvsim/utils.py
+++ b/pyuvsim/utils.py
@@ -146,43 +146,15 @@ def zenithangle_azimuth_to_altaz(zenith_angle, azimuth):
return altitude, new_azimuth
-def strip_extension(filepath, ext=None):
- """
- Remove extension from file.
-
- Parameters
- ----------
- ext : str
- Extenstion to remove. If not specified, only 'uvfits', 'uvh5', 'yaml' extensions
- are removed.
- """
- if '.' not in filepath:
- return filepath, ''
- file_list = filepath.split('.')
- if ext is not None:
- return filepath[:-len(ext) - 1], '.' + ext
- ext = file_list[-1]
- # miriad files might not have an extension
- # limited list of recognized extensions
- if ext not in ['uvfits', 'uvh5', 'yaml']:
- return filepath, ''
- return ".".join(file_list[:-1]), '.' + file_list[-1]
-
-
-def check_file_exists_and_increment(filepath, extension=None):
+def check_file_exists_and_increment(filepath):
"""
Check for a file and increment the name if it does to ensure a unique name.
Given filepath (path + filename), check if it exists. If so, add a _1
at the end, if that exists add a _2, and so on.
- Parameters
- ----------
- extension : str
- File extension, to be removed before modifying the filename and then added back.
-
"""
- base_filepath, ext = strip_extension(filepath, extension)
+ base_filepath, ext = os.path.splitext(filepath)
bf_list = base_filepath.split('_')
if bf_list[-1].isdigit():
base_filepath = '_'.join(bf_list[:-1])
| RadioAstronomySoftwareGroup/pyuvsim | abb8a87d486730acdbcf42cd67659309f661a364 | diff --git a/.github/workflows/testsuite.yaml b/.github/workflows/testsuite.yaml
index 177c297..5b53ac8 100644
--- a/.github/workflows/testsuite.yaml
+++ b/.github/workflows/testsuite.yaml
@@ -52,7 +52,7 @@ jobs:
- name: Run Tests
run: |
- python -m pytest --cov=pyuvsim --cov-config=.coveragerc --cov-report xml:./coverage.xml --junitxml=test-reports/xunit.xml
+ python -m pytest -n auto --cov=pyuvsim --cov-config=.coveragerc --cov-report xml:./coverage.xml --junitxml=test-reports/xunit.xml
- name: Upload Coverage
uses: codecov/codecov-action@v3
@@ -102,7 +102,7 @@ jobs:
- name: Run Tests
run: |
- python -m pytest --cov=pyuvsim --cov-config=.coveragerc --cov-report xml:./coverage.xml --junitxml=test-reports/xunit.xml
+ python -m pytest -n auto --cov=pyuvsim --cov-config=.coveragerc --cov-report xml:./coverage.xml --junitxml=test-reports/xunit.xml
- uses: codecov/codecov-action@v3
if: success()
@@ -151,7 +151,7 @@ jobs:
- name: Run Tests
run: |
- python -m pytest --cov=pyuvsim --cov-config=.coveragerc --cov-report xml:./coverage.xml --junitxml=test-reports/xunit.xml
+ python -m pytest -n auto --cov=pyuvsim --cov-config=.coveragerc --cov-report xml:./coverage.xml --junitxml=test-reports/xunit.xml
- uses: codecov/codecov-action@v3
if: success()
@@ -200,7 +200,7 @@ jobs:
pip install --no-deps .
- name: Run Tests
- run: |
+ run: | # currently cannot use `-n auto` here because pytest-cov causes warnings when used with pytest-xdist
python -m pytest -W error --cov=pyuvsim --cov-config=.coveragerc --cov-report xml:./coverage.xml --junitxml=test-reports/xunit.xml
- name: Upload Coverage
diff --git a/ci/pyuvsim_tests.yaml b/ci/pyuvsim_tests.yaml
index 21413fb..dffed84 100644
--- a/ci/pyuvsim_tests.yaml
+++ b/ci/pyuvsim_tests.yaml
@@ -14,6 +14,7 @@ dependencies:
- python-casacore>=3.3
- pytest
- pytest-cov
+ - pytest-xdist
- pyuvdata>=2.2.10
- pyyaml>=5.1
- scipy>=1.3
diff --git a/pyuvsim/tests/test_run.py b/pyuvsim/tests/test_run.py
index bc9e912..0c6bbb2 100644
--- a/pyuvsim/tests/test_run.py
+++ b/pyuvsim/tests/test_run.py
@@ -113,8 +113,14 @@ def test_run_paramfile_uvsim(goto_tempdir, paramfile):
@pytest.mark.filterwarnings("ignore:Input ra and dec parameters are being used instead")
@pytest.mark.filterwarnings("ignore:Cannot check consistency of a string-mode BeamList")
@pytest.mark.filterwarnings("ignore:invalid value encountered in divide")
[email protected]('model', ['monopole', 'cosza', 'quaddome', 'monopole-nonflat'])
-def test_analytic_diffuse(model, tmpdir):
+# Set the tolerances as low as we can achieve currently. Ideally these tolerances
+# would be lower, but it's complicated.
+# See Lanman, Murray and Jacobs, 2022, DOI: 10.3847/1538-4365/ac45fd
[email protected](
+ ('model', 'tol'),
+ [('monopole', 3e-4), ('cosza', 2e-4), ('quaddome', 8e-5), ('monopole-nonflat', 3e-4)],
+)
+def test_analytic_diffuse(model, tol, tmpdir):
# Generate the given model and simulate for a few baselines.
# Import from analytic_diffuse (consider moving to rasg_affiliates?)
pytest.importorskip('analytic_diffuse')
@@ -130,7 +136,7 @@ def test_analytic_diffuse(model, tmpdir):
elif model == 'monopole-nonflat':
modname = 'monopole'
use_w = True
- params['order'] = 30 # Expansion order for the non-flat monopole solution.
+ params['order'] = 50 # Expansion order for the non-flat monopole solution.
# Making configuration files for this simulation.
template_path = os.path.join(SIM_DATA_PATH, 'test_config', 'obsparam_diffuse_sky.yaml')
@@ -160,6 +166,9 @@ def test_analytic_diffuse(model, tmpdir):
obspar['telescope']['telescope_config_name'] = herauniform_path
obspar['sources']['diffuse_model'] = modname
obspar['sources'].update(params)
+ if model == "monopole":
+ # use a higher nside for monopole to improve the accuracy
+ obspar['sources']["map_nside"] = 256
obspar['filing']['outfile_name'] = 'diffuse_sim.uvh5'
obspar['filing']['output_format'] = 'uvh5'
obspar['filing']['outdir'] = str(tmpdir)
@@ -174,7 +183,7 @@ def test_analytic_diffuse(model, tmpdir):
soln = analytic_diffuse.get_solution(modname)
uvw_lam = uv_out.uvw_array * uv_out.freq_array[0] / c_ms
ana = soln(uvw_lam, **params)
- assert np.allclose(ana / 2, dat, atol=1e-2)
+ np.testing.assert_allclose(ana / 2, dat, atol=tol, rtol=0)
@pytest.mark.filterwarnings("ignore:Cannot check consistency of a string-mode BeamList")
diff --git a/pyuvsim/tests/test_utils.py b/pyuvsim/tests/test_utils.py
index dd843de..dbd6320 100644
--- a/pyuvsim/tests/test_utils.py
+++ b/pyuvsim/tests/test_utils.py
@@ -103,10 +103,7 @@ def test_file_namer(tmpdir, ext):
f.write(' ')
fnames.append(fname)
existing_file = fnames[0]
- if ext == '.ext':
- new_filepath = simutils.check_file_exists_and_increment(existing_file, 'ext')
- else:
- new_filepath = simutils.check_file_exists_and_increment(existing_file)
+ new_filepath = simutils.check_file_exists_and_increment(existing_file)
assert new_filepath.endswith(f"_111{ext}")
| Paper reference for pyuvsim
I think the JOSS paper reference should be mentioned on the pyuvsim Github and documentation page. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"pyuvsim/tests/test_utils.py::test_file_namer[.ext]"
] | [
"pyuvsim/tests/test_utils.py::test_altaz_to_za_az",
"pyuvsim/tests/test_utils.py::test_single_altaz_to_za_az",
"pyuvsim/tests/test_utils.py::test_za_az_to_altaz",
"pyuvsim/tests/test_utils.py::test_single_za_az_to_altaz",
"pyuvsim/tests/test_utils.py::test_altaz_za_az_errors",
"pyuvsim/tests/test_utils.py::test_file_namer[.uvfits]",
"pyuvsim/tests/test_utils.py::test_file_namer[.uvh5]",
"pyuvsim/tests/test_utils.py::test_file_namer[.yaml]",
"pyuvsim/tests/test_utils.py::test_file_namer[]",
"pyuvsim/tests/test_utils.py::test_write_uvdata[None]",
"pyuvsim/tests/test_utils.py::test_write_uvdata[uvfits]",
"pyuvsim/tests/test_utils.py::test_write_uvdata[miriad]",
"pyuvsim/tests/test_utils.py::test_write_uvdata[uvh5]",
"pyuvsim/tests/test_utils.py::test_write_uvdata_clobber[None]",
"pyuvsim/tests/test_utils.py::test_write_uvdata_clobber[uvfits]",
"pyuvsim/tests/test_utils.py::test_write_uvdata_clobber[miriad]",
"pyuvsim/tests/test_utils.py::test_write_uvdata_clobber[uvh5]",
"pyuvsim/tests/test_utils.py::test_write_fix_autos",
"pyuvsim/tests/test_utils.py::test_write_error_with_no_format",
"pyuvsim/tests/test_utils.py::test_file_format_in_filing_dict"
] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2024-02-15T21:57:39Z" | bsd-3-clause |
|
RasaHQ__rasa-sdk-237 | diff --git a/changelog/237.enhancement.rst b/changelog/237.enhancement.rst
new file mode 100644
index 0000000..d7f3704
--- /dev/null
+++ b/changelog/237.enhancement.rst
@@ -0,0 +1,1 @@
+Only fill other slots if slot mapping contains a role or group restriction.
diff --git a/rasa_sdk/forms.py b/rasa_sdk/forms.py
index 0c8cea9..ced6ba5 100644
--- a/rasa_sdk/forms.py
+++ b/rasa_sdk/forms.py
@@ -190,33 +190,39 @@ class FormAction(Action):
return intent_not_blacklisted or intent in mapping_intents
def entity_is_desired(
- self, requested_slot_mapping: Dict[Text, Any], slot: Text, tracker: "Tracker"
+ self, other_slot_mapping: Dict[Text, Any], other_slot: Text, tracker: "Tracker"
) -> bool:
- """Check whether slot should be filled by an entity in the input or not.
+ """Check whether the other slot should be filled by an entity in the input or
+ not.
Args:
- requested_slot_mapping: Slot mapping.
- slot: The slot to be filled.
+ other_slot_mapping: Slot mapping.
+ other_slot: The other slot to be filled.
tracker: The tracker.
Returns:
- True, if slot should be filled, false otherwise.
+ True, if other slot should be filled, false otherwise.
"""
# slot name is equal to the entity type
- slot_equals_entity = slot == requested_slot_mapping.get("entity")
+ other_slot_equals_entity = other_slot == other_slot_mapping.get("entity")
# use the custom slot mapping 'from_entity' defined by the user to check
# whether we can fill a slot with an entity
- matching_values = self.get_entity_value(
- requested_slot_mapping.get("entity"),
- tracker,
- requested_slot_mapping.get("role"),
- requested_slot_mapping.get("group"),
- )
- slot_fulfils_entity_mapping = matching_values is not None
+ other_slot_fulfils_entity_mapping = False
+ if (
+ other_slot_mapping.get("role") is not None
+ or other_slot_mapping.get("group") is not None
+ ):
+ matching_values = self.get_entity_value(
+ other_slot_mapping.get("entity"),
+ tracker,
+ other_slot_mapping.get("role"),
+ other_slot_mapping.get("group"),
+ )
+ other_slot_fulfils_entity_mapping = matching_values is not None
- return slot_equals_entity or slot_fulfils_entity_mapping
+ return other_slot_equals_entity or other_slot_fulfils_entity_mapping
@staticmethod
def get_entity_value(
| RasaHQ/rasa-sdk | 6514a8aaa2d5c964aace6669d135b8d17a781aef | diff --git a/tests/test_forms.py b/tests/test_forms.py
index d1b9436..e08a7d4 100644
--- a/tests/test_forms.py
+++ b/tests/test_forms.py
@@ -769,7 +769,7 @@ def test_extract_other_slots_with_intent():
None,
[{"entity": "entity_type", "value": "some_value"}],
"some_intent",
- {"some_other_slot": "some_value"},
+ {},
),
],
)
| extracting other slots in the form is broken
<!-- THIS INFORMATION IS MANDATORY - YOUR ISSUE WILL BE CLOSED IF IT IS MISSING. If you don't know your Rasa version, use `rasa --version`.
Please format any code or console output with three ticks ``` above and below.
If you are asking a usage question (e.g. "How do I do xyz") please post your question on https://forum.rasa.com instead -->
**Rasa version**:
**Rasa SDK version**:
**Python version**:
**Operating system** (windows, osx, ...):
**Issue**:
extracting other slot from arbitrary `from_entity` here: https://github.com/RasaHQ/rasa-sdk/blob/9c0433e4ebb4e141e8010fe2221b5d4153b96d09/rasa_sdk/forms.py#L211 breaks the logic. For example in carbon bot it extracts berlin for both slot_values---> {'travel_destination': 'berlin', 'travel_departure': 'berlin'} while requested slot was only travel_departure
**Error (including full traceback)**:
```
```
**Command or request that led to error**:
```
```
**Content of configuration file (config.yml)** (if relevant):
```yml
```
**Content of domain file (domain.yml)** (if relevant):
```yml
```
**Contents of actions.py** (if relevant):
```python
```
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_forms.py::test_extract_other_slots_with_entity[entity_type-None-None-entities7-some_intent-expected_slot_values7]"
] | [
"tests/test_forms.py::test_extract_requested_slot_default",
"tests/test_forms.py::test_extract_requested_slot_from_entity_no_intent",
"tests/test_forms.py::test_extract_requested_slot_from_entity_with_intent",
"tests/test_forms.py::test_extract_requested_slot_from_entity[some_intent-None-None-None-entities0-some_intent-expected_slot_values0]",
"tests/test_forms.py::test_extract_requested_slot_from_entity[None-some_intent-None-None-entities1-some_intent-expected_slot_values1]",
"tests/test_forms.py::test_extract_requested_slot_from_entity[some_intent-None-None-None-entities2-some_other_intent-expected_slot_values2]",
"tests/test_forms.py::test_extract_requested_slot_from_entity[None-None-some_role-None-entities3-some_intent-expected_slot_values3]",
"tests/test_forms.py::test_extract_requested_slot_from_entity[None-None-some_role-None-entities4-some_intent-expected_slot_values4]",
"tests/test_forms.py::test_extract_requested_slot_from_entity[None-None-None-some_group-entities5-some_intent-expected_slot_values5]",
"tests/test_forms.py::test_extract_requested_slot_from_entity[None-None-None-some_group-entities6-some_intent-expected_slot_values6]",
"tests/test_forms.py::test_extract_requested_slot_from_entity[None-None-some_role-some_group-entities7-some_intent-expected_slot_values7]",
"tests/test_forms.py::test_extract_requested_slot_from_entity[None-None-some_role-some_group-entities8-some_intent-expected_slot_values8]",
"tests/test_forms.py::test_extract_requested_slot_from_entity[None-None-None-None-entities9-some_intent-expected_slot_values9]",
"tests/test_forms.py::test_extract_requested_slot_from_intent",
"tests/test_forms.py::test_extract_requested_slot_from_not_intent",
"tests/test_forms.py::test_extract_requested_slot_from_text_no_intent",
"tests/test_forms.py::test_extract_requested_slot_from_text_with_intent",
"tests/test_forms.py::test_extract_requested_slot_from_text_with_not_intent",
"tests/test_forms.py::test_extract_trigger_slots",
"tests/test_forms.py::test_extract_other_slots_no_intent",
"tests/test_forms.py::test_extract_other_slots_with_intent",
"tests/test_forms.py::test_extract_other_slots_with_entity[entity_type-some_role-None-entities0-some_intent-expected_slot_values0]",
"tests/test_forms.py::test_extract_other_slots_with_entity[entity_type-some_role-None-entities1-some_intent-expected_slot_values1]",
"tests/test_forms.py::test_extract_other_slots_with_entity[entity_type-None-some_group-entities2-some_intent-expected_slot_values2]",
"tests/test_forms.py::test_extract_other_slots_with_entity[entity_type-None-some_group-entities3-some_intent-expected_slot_values3]",
"tests/test_forms.py::test_extract_other_slots_with_entity[entity_type-some_role-some_group-entities4-some_intent-expected_slot_values4]",
"tests/test_forms.py::test_extract_other_slots_with_entity[entity_type-None-None-entities5-some_intent-expected_slot_values5]",
"tests/test_forms.py::test_extract_other_slots_with_entity[some_entity-None-None-entities6-some_intent-expected_slot_values6]"
] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_added_files"
],
"has_test_patch": true,
"is_lite": false
} | "2020-07-13T12:34:13Z" | apache-2.0 |
|
ReactiveX__RxPY-357 | diff --git a/rx/core/operators/observeon.py b/rx/core/operators/observeon.py
index d725401b..d1ea4a56 100644
--- a/rx/core/operators/observeon.py
+++ b/rx/core/operators/observeon.py
@@ -22,8 +22,9 @@ def _observe_on(scheduler) -> Callable[[Observable], Observable]:
Returns the source sequence whose observations happen on
the specified scheduler.
"""
- def subscribe(observer, _=None):
- return source.subscribe(ObserveOnObserver(scheduler, observer))
+ def subscribe(observer, subscribe_scheduler=None):
+ return source.subscribe(ObserveOnObserver(scheduler, observer),
+ scheduler=subscribe_scheduler)
return Observable(subscribe)
- return observe_on
\ No newline at end of file
+ return observe_on
| ReactiveX/RxPY | a964eac88787dabef61cbc96ba31801f5a9bbed9 | diff --git a/tests/test_observable/test_observeon.py b/tests/test_observable/test_observeon.py
index 450ed134..09d265b4 100644
--- a/tests/test_observable/test_observeon.py
+++ b/tests/test_observable/test_observeon.py
@@ -2,6 +2,7 @@ import unittest
import rx
from rx import operators as ops
+from rx.concurrency import ImmediateScheduler
from rx.testing import TestScheduler, ReactiveTest
on_next = ReactiveTest.on_next
@@ -75,3 +76,21 @@ class TestObserveOn(unittest.TestCase):
assert results.messages == []
assert xs.subscriptions == [subscribe(200, 1000)]
+
+ def test_observe_on_forward_subscribe_scheduler(self):
+ scheduler = ImmediateScheduler()
+ expected_subscribe_scheduler = ImmediateScheduler()
+
+ actual_subscribe_scheduler = None
+
+ def subscribe(observer, scheduler):
+ nonlocal actual_subscribe_scheduler
+ actual_subscribe_scheduler = scheduler
+ observer.on_completed()
+
+ xs = rx.create(subscribe)
+
+ xs.pipe(ops.observe_on(scheduler)).subscribe(
+ scheduler=expected_subscribe_scheduler)
+
+ assert expected_subscribe_scheduler == actual_subscribe_scheduler
| observe_on operator does not propagate subscription scheduler
The observe_on scheduler drops the scheduler parameter provided during subscription. As a consequence, the default scheduler provided in the pipe operator is lost when observe_on is used in the chain. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_observable/test_observeon.py::TestObserveOn::test_observe_on_forward_subscribe_scheduler"
] | [
"tests/test_observable/test_observeon.py::TestObserveOn::test_observe_on_empty",
"tests/test_observable/test_observeon.py::TestObserveOn::test_observe_on_error",
"tests/test_observable/test_observeon.py::TestObserveOn::test_observe_on_never",
"tests/test_observable/test_observeon.py::TestObserveOn::test_observe_on_normal"
] | {
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false
} | "2019-04-22T22:09:22Z" | apache-2.0 |
|
ReactiveX__RxPY-460 | diff --git a/rx/core/operators/flatmap.py b/rx/core/operators/flatmap.py
index 0f6b73d8..f0262658 100644
--- a/rx/core/operators/flatmap.py
+++ b/rx/core/operators/flatmap.py
@@ -10,11 +10,12 @@ from rx.internal.utils import is_future
def _flat_map_internal(source, mapper=None, mapper_indexed=None):
def projection(x, i):
mapper_result = mapper(x) if mapper else mapper_indexed(x, i)
- if isinstance(mapper_result, collections.abc.Iterable):
+ if is_future(mapper_result):
+ result = from_future(mapper_result)
+ elif isinstance(mapper_result, collections.abc.Iterable):
result = from_(mapper_result)
else:
- result = from_future(mapper_result) if is_future(
- mapper_result) else mapper_result
+ result = mapper_result
return result
return source.pipe(
| ReactiveX/RxPY | 573260422a6e3825c82a1cfbf8260b6514afc7b6 | diff --git a/tests/test_observable/test_flatmap_async.py b/tests/test_observable/test_flatmap_async.py
new file mode 100644
index 00000000..f568638e
--- /dev/null
+++ b/tests/test_observable/test_flatmap_async.py
@@ -0,0 +1,33 @@
+import unittest
+import asyncio
+from rx import operators as ops
+from rx.subject import Subject
+
+from rx.scheduler.eventloop import AsyncIOScheduler
+
+
+class TestFlatMapAsync(unittest.TestCase):
+
+ def test_flat_map_async(self):
+ actual_next = None
+ loop = asyncio.get_event_loop()
+ scheduler = AsyncIOScheduler(loop=loop)
+
+ def mapper(i):
+ async def _mapper(i):
+ return i + 1
+
+ return asyncio.ensure_future(_mapper(i))
+
+ def on_next(i):
+ nonlocal actual_next
+ actual_next = i
+
+ async def test_flat_map():
+ x = Subject()
+ x.pipe(ops.flat_map(mapper)).subscribe(on_next, scheduler=scheduler)
+ x.on_next(10)
+ await asyncio.sleep(0.1)
+
+ loop.run_until_complete(test_flat_map())
+ assert actual_next == 11
| Async function with flat_map()
Observer does not recieve values if there is `flat_map()` operator in chain and mapper returns `Future`.
Rx: v3.0.1-2-g19b19087
Python: 3.7.4
Test code:
```python
from asyncio import get_event_loop, create_task, sleep
from rx import operators as op
from rx.core import Observer
from rx.subject import Subject
from rx.scheduler.eventloop import AsyncIOScheduler
def on_next(value, *args, **kwargs):
print('Recieve', value)
def maptest(value):
async def increase(value):
print('Increasing')
return value + 1
print('Returning task')
return create_task(increase(value))
async def go(loop):
print('Starting, creating stream')
stream = Subject()
tail = stream.pipe(op.flat_map(maptest))
tail.subscribe(Observer(on_next), scheduler=AsyncIOScheduler(loop))
print('Sending value')
stream.on_next(10)
print('Sleeping 5 sec')
await sleep(5)
print('End of sleeping')
loop = get_event_loop()
loop.run_until_complete(go(loop))
print('Happy end')
```
Result output:
```
Starting, creating stream
Sending value
Returning task
Sleeping 5 sec
Increasing
End of sleeping
Happy end
```
This is because of type checking in `_flat_map_internal()` from [flat_map()](../blob/cd3d5a5b833a0df3ecd91116c0243ebaa762578c/rx/core/operators/flatmap.py#L13-L18) operator:
```python
if isinstance(mapper_result, collections.abc.Iterable):
result = from_(mapper_result)
else:
result = from_future(mapper_result) if is_future(
mapper_result) else mapper_result
return result
```
If mapper returns `Future` Observable will create with `from_` operator, not with `from_future` operator, because:
```python
>>> issubclass(asyncio.Future, collections.abc.Iterable)
True
>>> issubclass(asyncio.Task, asyncio.Future)
True
```
So we need rewrite `mapper_result` type checking, for example:
```python
if is_future(mapper_result):
result = from_future(mapper_result)
elif isinstance(mapper_result, collections.abc.Iterable):
result = from_(mapper_result)
else:
result = mapper_result
return result
```
Now all is ok, test output:
```
Starting, creating stream
Sending value
Returning task
Sleeping 5 sec
Increasing
Recieve 11
End of sleeping
Happy end
``` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_observable/test_flatmap_async.py::TestFlatMapAsync::test_flat_map_async"
] | [] | {
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
} | "2019-09-25T20:43:15Z" | mit |
|
ReactiveX__RxPY-492 | diff --git a/rx/core/observable/connectableobservable.py b/rx/core/observable/connectableobservable.py
index f2d3637e..ab0acd51 100644
--- a/rx/core/observable/connectableobservable.py
+++ b/rx/core/observable/connectableobservable.py
@@ -28,7 +28,7 @@ class ConnectableObservable(Observable):
def dispose():
self.has_subscription = False
- subscription = self.source.subscribe(self.subject, scheduler)
+ subscription = self.source.subscribe(self.subject, scheduler=scheduler)
self.subscription = CompositeDisposable(subscription, Disposable(dispose))
return self.subscription
| ReactiveX/RxPY | 5fc2cfb5911e29818adde7dd70ef74ddb085eba4 | diff --git a/tests/test_observable/test_connectableobservable.py b/tests/test_observable/test_connectableobservable.py
index 00709145..8ab7a4e2 100644
--- a/tests/test_observable/test_connectableobservable.py
+++ b/tests/test_observable/test_connectableobservable.py
@@ -241,3 +241,19 @@ class TestConnectableObservable(unittest.TestCase):
subscribe(225, 241),
subscribe(249, 255),
subscribe(275, 295)]
+
+ def test_connectable_observable_forward_scheduler(self):
+ scheduler = TestScheduler()
+ subscribe_scheduler = 'unknown'
+
+ def subscribe(observer, scheduler=None):
+ nonlocal subscribe_scheduler
+ subscribe_scheduler = scheduler
+
+ xs = rx.create(subscribe)
+ subject = MySubject()
+
+ conn = ConnectableObservable(xs, subject)
+ conn.connect(scheduler)
+
+ assert subscribe_scheduler is scheduler
| Scheduler provided in subscribe is not used for all observable factories
We now have `Observable.subcribe(..., scheduler=scheduler)`, which is really nice. Let's take the API all the way.
[The documentation says that](https://rxpy.readthedocs.io/en/latest/get_started.html#default-scheduler):
> Operators that accept a scheduler select the scheduler to use in the following way:
> * If a scheduler is provided for the operator, then use it.
> * If a default scheduler is provided in subscribe, then use it.
> * Otherwise use the default scheduler of the operator.
I know that this applies to operators but I think that it would make sense if it also applied to observable factories. This way, we can finally get rid of all the `scheduler=scheduler` boilerplate. See #183 for additional info.
The `timer` observable factory, for instance, still defaults to the `TimeoutScheduler` .
I guess this is a feature request. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_observable/test_connectableobservable.py::TestConnectableObservable::test_connectable_observable_forward_scheduler"
] | [
"tests/test_observable/test_connectableobservable.py::TestConnectableObservable::test_connectable_observable_connected",
"tests/test_observable/test_connectableobservable.py::TestConnectableObservable::test_connectable_observable_creation",
"tests/test_observable/test_connectableobservable.py::TestConnectableObservable::test_connectable_observable_disconnect_future",
"tests/test_observable/test_connectableobservable.py::TestConnectableObservable::test_connectable_observable_disconnected",
"tests/test_observable/test_connectableobservable.py::TestConnectableObservable::test_connectable_observable_multiple_non_overlapped_connections",
"tests/test_observable/test_connectableobservable.py::TestConnectableObservable::test_connectable_observable_not_connected"
] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_issue_reference"
],
"has_test_patch": true,
"is_lite": false
} | "2020-02-03T12:48:44Z" | mit |
|
ReactiveX__RxPY-507 | diff --git a/.travis.yml b/.travis.yml
index e10f1846..2131a27f 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -23,11 +23,11 @@ matrix:
- xvfb-run -a python3 setup.py test
- - name: "Python 3.8-dev on Linux"
+ - name: "Python 3.8 on Linux"
os: linux
dist: xenial
language: python
- python: 3.8-dev
+ python: 3.8
service:
- xvfb
script:
diff --git a/rx/core/observable/fromfuture.py b/rx/core/observable/fromfuture.py
index fa83acbc..70ab7670 100644
--- a/rx/core/observable/fromfuture.py
+++ b/rx/core/observable/fromfuture.py
@@ -1,3 +1,4 @@
+import asyncio
from asyncio.futures import Future
from typing import Optional
@@ -26,7 +27,7 @@ def _from_future(future: Future) -> Observable:
def done(future):
try:
value = future.result()
- except Exception as ex: # pylint: disable=broad-except
+ except (Exception, asyncio.CancelledError) as ex: # pylint: disable=broad-except
observer.on_error(ex)
else:
observer.on_next(value)
diff --git a/rx/operators/__init__.py b/rx/operators/__init__.py
index c4d5afbe..c2373d76 100644
--- a/rx/operators/__init__.py
+++ b/rx/operators/__init__.py
@@ -870,7 +870,7 @@ def expand(mapper: Mapper) -> Callable[[Observable], Observable]:
def filter(predicate: Predicate) -> Callable[[Observable], Observable]:
"""Filters the elements of an observable sequence based on a
- predicate by incorporating the element's index.
+ predicate.
.. marble::
:alt: filter
@@ -2019,7 +2019,7 @@ def repeat(repeat_count: Optional[int] = None) -> Callable[[Observable], Observa
Returns:
An operator function that takes an observable sources and
- returna an observable sequence producing the elements of the
+ returns an observable sequence producing the elements of the
given sequence repeatedly.
"""
from rx.core.operators.repeat import _repeat
| ReactiveX/RxPY | 4ed60bb5c04aa85de5210e5537a6adfe1b667d50 | diff --git a/tests/test_observable/test_fromfuture.py b/tests/test_observable/test_fromfuture.py
index 17493fcf..f4ac2eb7 100644
--- a/tests/test_observable/test_fromfuture.py
+++ b/tests/test_observable/test_fromfuture.py
@@ -59,6 +59,30 @@ class TestFromFuture(unittest.TestCase):
loop.run_until_complete(go())
assert all(success)
+ def test_future_cancel(self):
+ loop = asyncio.get_event_loop()
+ success = [True, False, True]
+
+ @asyncio.coroutine
+ def go():
+ future = Future()
+ source = rx.from_future(future)
+
+ def on_next(x):
+ success[0] = False
+
+ def on_error(err):
+ success[1] = type(err) == asyncio.CancelledError
+
+ def on_completed():
+ success[2] = False
+
+ source.subscribe(on_next, on_error, on_completed)
+ future.cancel()
+
+ loop.run_until_complete(go())
+ assert all(success)
+
def test_future_dispose(self):
loop = asyncio.get_event_loop()
success = [True, True, True]
| from_future and asyncio.CancelledError
The [`from_future`](https://github.com/ReactiveX/RxPY/blob/master/rx/core/observable/fromfuture.py) operator no longer forwards `asyncio.CancelledError`s. This is due to a [change](https://bugs.python.org/issue32528) in Python 3.8 that makes `asyncio.CancelledError` inherit from `BaseException` (it inherited from `Exception` in previous releases).
The [current implementation](https://github.com/ReactiveX/RxPY/blob/master/rx/core/observable/fromfuture.py#L29) of `from_future` only forwards `Exception`s:
```
def done(future):
try:
value = future.result()
except Exception as ex: # pylint: disable=broad-except
observer.on_error(ex)
else:
observer.on_next(value)
observer.on_completed()
```
I suggest that we either:
* Broaden the exception handler even more, so that `BaseException`s are forwarded.
* Make a specialized version of `from_future` (say `from_coro`) that forwards the relevant cancellation exceptions. I think that the built-in `asyncio.CancelledError` should be supported by default.
* Add argument to `from_future` that specifies the exception types, that we want to forward. E.g., `ops.from_future(fut, exceptions=(Exception, asyncio.CancelledError))`.
---
I got hit by this issue in practice. It gave me a short and non-descriptive stack trace:
```
<27>1 2020-02-10T11:43:55.556901+01:00 zeus1934001 baxter 5680 - - [geist.geist] Stopped due to error:
Traceback (most recent call last):
File "/usr/lib/python3.8/site-packages/baxter/__main__.py", line 40, in main
geist.run(_amain())
File "/usr/lib/python3.8/site-packages/geist/geist.py", line 40, in run
self.loop.run_forever()
File "uvloop/loop.pyx", line 1312, in uvloop.loop.Loop.run_forever
File "uvloop/loop.pyx", line 492, in uvloop.loop.Loop._run
File "uvloop/loop.pyx", line 409, in uvloop.loop.Loop._on_idle
File "uvloop/cbhandles.pyx", line 70, in uvloop.loop.Handle._run
File "usr/lib/python3.8/site-packages/rx/core/observable/fromfuture.py", line 28, in done
asyncio.exceptions.CancelledError
```
There are no indications of which task got cancelled. This makes it very difficult to debug. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_observable/test_fromfuture.py::TestFromFuture::test_future_cancel"
] | [
"tests/test_observable/test_fromfuture.py::TestFromFuture::test_future_dispose",
"tests/test_observable/test_fromfuture.py::TestFromFuture::test_future_failure",
"tests/test_observable/test_fromfuture.py::TestFromFuture::test_future_success"
] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2020-04-18T21:48:18Z" | mit |
|
ReactiveX__RxPY-537 | diff --git a/rx/__init__.py b/rx/__init__.py
index b995f2b2..ce18e050 100644
--- a/rx/__init__.py
+++ b/rx/__init__.py
@@ -6,7 +6,6 @@ from typing import Iterable, Callable, Any, Optional, Union, Mapping
from .core import Observable, pipe, typing
from .internal.utils import alias
-
# Please make sure the version here remains the same as in project.cfg
__version__ = '3.1.1'
@@ -561,8 +560,8 @@ def generate(initial_state: Any,
def hot(string: str,
- timespan: typing.RelativeTime=0.1,
- duetime:typing.AbsoluteOrRelativeTime = 0.0,
+ timespan: typing.RelativeTime = 0.1,
+ duetime: typing.AbsoluteOrRelativeTime = 0.0,
scheduler: Optional[typing.Scheduler] = None,
lookup: Optional[Mapping] = None,
error: Optional[Exception] = None
@@ -1092,8 +1091,8 @@ def zip(*args: Observable) -> Observable:
:alt: zip
--1--2---3-----4---|
- -a----b----c-d-----|
- [ zip() ]
+ -a----b----c-d------|
+ [ zip() ]
--1,a-2,b--3,c-4,d-|
Example:
diff --git a/rx/core/observable/zip.py b/rx/core/observable/zip.py
index 530ab8c8..8b756477 100644
--- a/rx/core/observable/zip.py
+++ b/rx/core/observable/zip.py
@@ -1,11 +1,11 @@
+from threading import RLock
from typing import Optional, List
from rx import from_future
from rx.core import Observable, typing
from rx.disposable import CompositeDisposable, SingleAssignmentDisposable
-from rx.internal.utils import is_future
from rx.internal.concurrency import synchronized
-from threading import RLock
+from rx.internal.utils import is_future
# pylint: disable=redefined-builtin
@@ -29,11 +29,11 @@ def _zip(*args: Observable) -> Observable:
sources = list(args)
- def subscribe(observer: typing.Observer, scheduler: Optional[typing.Scheduler] = None):
+ def subscribe(observer: typing.Observer,
+ scheduler: Optional[typing.Scheduler] = None) -> CompositeDisposable:
n = len(sources)
queues: List[List] = [[] for _ in range(n)]
lock = RLock()
- is_done = [False] * n
@synchronized(lock)
def next(i):
@@ -46,13 +46,6 @@ def _zip(*args: Observable) -> Observable:
return
observer.on_next(res)
- elif all([x for j, x in enumerate(is_done) if j != i]):
- observer.on_completed()
-
- def done(i):
- is_done[i] = True
- if all(is_done):
- observer.on_completed()
subscriptions = [None] * n
@@ -65,7 +58,7 @@ def _zip(*args: Observable) -> Observable:
queues[i].append(x)
next(i)
- sad.disposable = source.subscribe_(on_next, observer.on_error, lambda: done(i), scheduler)
+ sad.disposable = source.subscribe_(on_next, observer.on_error, observer.on_completed, scheduler)
subscriptions[i] = sad
for idx in range(n):
diff --git a/rx/core/operators/tofuture.py b/rx/core/operators/tofuture.py
index 67197888..f0f1d435 100644
--- a/rx/core/operators/tofuture.py
+++ b/rx/core/operators/tofuture.py
@@ -38,18 +38,20 @@ def _to_future(future_ctor: Optional[Callable[[], Future]] = None,
has_value = True
def on_error(err):
- future.set_exception(err)
+ if not future.cancelled():
+ future.set_exception(err)
def on_completed():
nonlocal last_value
- if has_value:
- future.set_result(last_value)
- else:
- future.set_exception(SequenceContainsNoElementsError())
+ if not future.cancelled():
+ if has_value:
+ future.set_result(last_value)
+ else:
+ future.set_exception(SequenceContainsNoElementsError())
last_value = None
- source.subscribe_(on_next, on_error, on_completed, scheduler=scheduler)
+ dis = source.subscribe_(on_next, on_error, on_completed, scheduler=scheduler)
+ future.add_done_callback(lambda _: dis.dispose())
- # No cancellation can be done
return future
return to_future
diff --git a/rx/operators/__init__.py b/rx/operators/__init__.py
index c2373d76..b7da67a4 100644
--- a/rx/operators/__init__.py
+++ b/rx/operators/__init__.py
@@ -3492,8 +3492,8 @@ def zip(*args: Observable) -> Callable[[Observable], Observable]:
:alt: zip
--1--2---3-----4---|
- -a----b----c-d-----|
- [ zip() ]
+ -a----b----c-d------|
+ [ zip() ]
--1,a-2,b--3,c-4,d-|
| ReactiveX/RxPY | f2642a87e6b4d5b3dc9a482323716cf15a6ef570 | diff --git a/tests/test_observable/test_tofuture.py b/tests/test_observable/test_tofuture.py
index 679c92a2..f90fb111 100644
--- a/tests/test_observable/test_tofuture.py
+++ b/tests/test_observable/test_tofuture.py
@@ -6,6 +6,7 @@ import rx
import rx.operators as ops
from rx.internal.exceptions import SequenceContainsNoElementsError
from rx.testing import ReactiveTest
+from rx.subject import Subject
on_next = ReactiveTest.on_next
on_completed = ReactiveTest.on_completed
@@ -79,3 +80,33 @@ class TestToFuture(unittest.TestCase):
loop.run_until_complete(go())
assert result == 42
+
+ def test_cancel(self):
+ loop = asyncio.get_event_loop()
+
+ async def go():
+ source = rx.return_value(42)
+ fut = next(source.__await__())
+ # This used to raise an InvalidStateError before we got
+ # support for cancellation.
+ fut.cancel()
+ await fut
+
+ self.assertRaises(asyncio.CancelledError, loop.run_until_complete, go())
+
+ def test_dispose_on_cancel(self):
+ loop = asyncio.get_event_loop()
+ sub = Subject()
+
+ async def using_sub():
+ # Since the subject never completes, this await statement
+ # will never be complete either. We wait forever.
+ await rx.using(lambda: sub, lambda s: s)
+
+ async def go():
+ await asyncio.wait_for(using_sub(), 0.1)
+
+ self.assertRaises(asyncio.TimeoutError, loop.run_until_complete, go())
+ # When we cancel the future (due to the time-out), the future
+ # automatically disposes the underlying subject.
+ self.assertTrue(sub.is_disposed)
diff --git a/tests/test_observable/test_zip.py b/tests/test_observable/test_zip.py
index 41eda422..fe09b461 100644
--- a/tests/test_observable/test_zip.py
+++ b/tests/test_observable/test_zip.py
@@ -13,7 +13,6 @@ disposed = ReactiveTest.disposed
created = ReactiveTest.created
-
class TestZip(unittest.TestCase):
def test_zip_never_never(self):
@@ -37,7 +36,7 @@ class TestZip(unittest.TestCase):
return o1.pipe(ops.zip(o2))
results = scheduler.start(create)
- assert results.messages == []
+ assert results.messages == [on_completed(210)]
def test_zip_empty_empty(self):
scheduler = TestScheduler()
@@ -67,7 +66,7 @@ class TestZip(unittest.TestCase):
ops.map(sum))
results = scheduler.start(create)
- assert results.messages == [on_completed(215)]
+ assert results.messages == [on_completed(210)]
def test_zip_non_empty_empty(self):
scheduler = TestScheduler()
@@ -82,7 +81,7 @@ class TestZip(unittest.TestCase):
ops.map(sum))
results = scheduler.start(create)
- assert results.messages == [on_completed(215)]
+ assert results.messages == [on_completed(210)]
def test_zip_never_non_empty(self):
scheduler = TestScheduler()
@@ -96,7 +95,7 @@ class TestZip(unittest.TestCase):
ops.map(sum))
results = scheduler.start(create)
- assert results.messages == []
+ assert results.messages == [on_completed(220)]
def test_zip_non_empty_never(self):
scheduler = TestScheduler()
@@ -110,7 +109,7 @@ class TestZip(unittest.TestCase):
ops.map(sum))
results = scheduler.start(create)
- assert results.messages == []
+ assert results.messages == [on_completed(220)]
def test_zip_non_empty_non_empty(self):
scheduler = TestScheduler()
@@ -125,7 +124,7 @@ class TestZip(unittest.TestCase):
ops.map(sum))
results = scheduler.start(create)
- assert results.messages == [on_next(220, 2 + 3), on_completed(240)]
+ assert results.messages == [on_next(220, 2 + 3), on_completed(230)]
def test_zip_empty_error(self):
ex = 'ex'
@@ -246,6 +245,7 @@ class TestZip(unittest.TestCase):
for i in range(5):
results.append(on_next(205 + i * 5, i))
return results
+
msgs1 = msgs1_factory()
def msgs2_factory():
@@ -253,6 +253,7 @@ class TestZip(unittest.TestCase):
for i in range(10):
results.append(on_next(205 + i * 8, i))
return results
+
msgs2 = msgs2_factory()
length = min(len(msgs1), len(msgs2))
@@ -265,13 +266,13 @@ class TestZip(unittest.TestCase):
ops.map(sum))
results = scheduler.start(create).messages
- assert(length == len(results))
+ assert (length == len(results))
for i in range(length):
_sum = msgs1[i].value.value + msgs2[i].value.value
time = max(msgs1[i].time, msgs2[i].time)
- assert(results[i].value.kind == 'N'
- and results[i].time == time
- and results[i].value.value == _sum)
+ assert (results[i].value.kind == 'N'
+ and results[i].time == time
+ and results[i].value.value == _sum)
def test_zip_some_data_asymmetric2(self):
scheduler = TestScheduler()
@@ -282,6 +283,7 @@ class TestZip(unittest.TestCase):
results.append(on_next(205 + i * 5, i))
return results
+
msgs1 = msgs1_factory()
def msgs2_factory():
@@ -289,6 +291,7 @@ class TestZip(unittest.TestCase):
for i in range(5):
results.append(on_next(205 + i * 8, i))
return results
+
msgs2 = msgs2_factory()
length = min(len(msgs1), len(msgs2))
@@ -301,13 +304,13 @@ class TestZip(unittest.TestCase):
ops.map(sum))
results = scheduler.start(create).messages
- assert(length == len(results))
+ assert (length == len(results))
for i in range(length):
_sum = msgs1[i].value.value + msgs2[i].value.value
time = max(msgs1[i].time, msgs2[i].time)
- assert(results[i].value.kind == 'N'
- and results[i].time == time
- and results[i].value.value == _sum)
+ assert (results[i].value.kind == 'N'
+ and results[i].time == time
+ and results[i].value.value == _sum)
def test_zip_some_data_symmetric(self):
scheduler = TestScheduler()
@@ -317,6 +320,7 @@ class TestZip(unittest.TestCase):
for i in range(10):
results.append(on_next(205 + i * 5, i))
return results
+
msgs1 = msgs1_factory()
def msgs2_factory():
@@ -324,6 +328,7 @@ class TestZip(unittest.TestCase):
for i in range(10):
results.append(on_next(205 + i * 8, i))
return results
+
msgs2 = msgs2_factory()
length = min(len(msgs1), len(msgs2))
@@ -336,13 +341,13 @@ class TestZip(unittest.TestCase):
ops.map(sum))
results = scheduler.start(create).messages
- assert(length == len(results))
+ assert (length == len(results))
for i in range(length):
_sum = msgs1[i].value.value + msgs2[i].value.value
time = max(msgs1[i].time, msgs2[i].time)
- assert(results[i].value.kind == 'N'
- and results[i].time == time
- and results[i].value.value == _sum)
+ assert (results[i].value.kind == 'N'
+ and results[i].time == time
+ and results[i].value.value == _sum)
def test_zip_with_iterable_never_empty(self):
scheduler = TestScheduler()
@@ -423,7 +428,7 @@ class TestZip(unittest.TestCase):
def test_zip_with_iterable_non_empty_non_empty(self):
scheduler = TestScheduler()
n1 = scheduler.create_hot_observable(
- on_next(150, 1), on_next(215, 2), on_completed(230))
+ on_next(150, 1), on_next(215, 2), on_completed(230))
n2 = [3]
def create():
| zip operator should complete if a single upstream source completes
The following observable `y` ...
``` python
import rx
from rx import operators as rxop
y = rx.range(2).pipe(
rxop.zip(rx.defer(lambda _: y)),
rxop.merge(rx.just(0)),
rxop.share(),
)
y.subscribe(print, on_completed=lambda: print('completed'))
```
... never completes.
My suggestion: The zip operator should complete if any upstream source completed and the corresponding queue is empty.
That is how it is implemented in [RxJava](https://github.com/ReactiveX/RxJava/blob/3.x/src/main/java/io/reactivex/rxjava3/internal/operators/observable/ObservableZip.java). | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_observable/test_tofuture.py::TestToFuture::test_dispose_on_cancel",
"tests/test_observable/test_zip.py::TestZip::test_zip_empty_non_empty",
"tests/test_observable/test_zip.py::TestZip::test_zip_never_empty",
"tests/test_observable/test_zip.py::TestZip::test_zip_never_non_empty",
"tests/test_observable/test_zip.py::TestZip::test_zip_non_empty_empty",
"tests/test_observable/test_zip.py::TestZip::test_zip_non_empty_never",
"tests/test_observable/test_zip.py::TestZip::test_zip_non_empty_non_empty"
] | [
"tests/test_observable/test_tofuture.py::TestToFuture::test_await_empty_observable",
"tests/test_observable/test_tofuture.py::TestToFuture::test_await_error",
"tests/test_observable/test_tofuture.py::TestToFuture::test_await_success",
"tests/test_observable/test_tofuture.py::TestToFuture::test_await_success_on_sequence",
"tests/test_observable/test_tofuture.py::TestToFuture::test_await_with_delay",
"tests/test_observable/test_tofuture.py::TestToFuture::test_cancel",
"tests/test_observable/test_zip.py::TestZip::test_zip_empty_empty",
"tests/test_observable/test_zip.py::TestZip::test_zip_empty_error",
"tests/test_observable/test_zip.py::TestZip::test_zip_error_empty",
"tests/test_observable/test_zip.py::TestZip::test_zip_error_error",
"tests/test_observable/test_zip.py::TestZip::test_zip_error_never",
"tests/test_observable/test_zip.py::TestZip::test_zip_error_some",
"tests/test_observable/test_zip.py::TestZip::test_zip_never_error",
"tests/test_observable/test_zip.py::TestZip::test_zip_never_never",
"tests/test_observable/test_zip.py::TestZip::test_zip_some_data_asymmetric1",
"tests/test_observable/test_zip.py::TestZip::test_zip_some_data_asymmetric2",
"tests/test_observable/test_zip.py::TestZip::test_zip_some_data_symmetric",
"tests/test_observable/test_zip.py::TestZip::test_zip_some_error",
"tests/test_observable/test_zip.py::TestZip::test_zip_with_iterable_empty_empty",
"tests/test_observable/test_zip.py::TestZip::test_zip_with_iterable_empty_non_empty",
"tests/test_observable/test_zip.py::TestZip::test_zip_with_iterable_error_empty",
"tests/test_observable/test_zip.py::TestZip::test_zip_with_iterable_error_some",
"tests/test_observable/test_zip.py::TestZip::test_zip_with_iterable_never_empty",
"tests/test_observable/test_zip.py::TestZip::test_zip_with_iterable_never_non_empty",
"tests/test_observable/test_zip.py::TestZip::test_zip_with_iterable_non_empty_empty",
"tests/test_observable/test_zip.py::TestZip::test_zip_with_iterable_non_empty_non_empty",
"tests/test_observable/test_zip.py::TestZip::test_zip_with_iterable_some_data_both_sides"
] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
} | "2020-08-09T16:40:37Z" | mit |
|
ReactiveX__RxPY-567 | diff --git a/rx/scheduler/eventloop/asynciothreadsafescheduler.py b/rx/scheduler/eventloop/asynciothreadsafescheduler.py
index 52f6e30d..79880d41 100644
--- a/rx/scheduler/eventloop/asynciothreadsafescheduler.py
+++ b/rx/scheduler/eventloop/asynciothreadsafescheduler.py
@@ -50,6 +50,10 @@ class AsyncIOThreadSafeScheduler(AsyncIOScheduler):
handle = self._loop.call_soon_threadsafe(interval)
def dispose() -> None:
+ if self._on_self_loop_or_not_running():
+ handle.cancel()
+ return
+
future: Future = Future()
def cancel_handle() -> None:
@@ -96,14 +100,21 @@ class AsyncIOThreadSafeScheduler(AsyncIOScheduler):
handle.append(self._loop.call_soon_threadsafe(stage2))
def dispose() -> None:
- future: Future = Future()
-
- def cancel_handle() -> None:
+ def do_cancel_handles():
try:
handle.pop().cancel()
handle.pop().cancel()
except Exception:
pass
+
+ if self._on_self_loop_or_not_running():
+ do_cancel_handles()
+ return
+
+ future: Future = Future()
+
+ def cancel_handle() -> None:
+ do_cancel_handles()
future.set_result(0)
self._loop.call_soon_threadsafe(cancel_handle)
@@ -130,3 +141,22 @@ class AsyncIOThreadSafeScheduler(AsyncIOScheduler):
duetime = self.to_datetime(duetime)
return self.schedule_relative(duetime - self.now, action, state=state)
+
+ def _on_self_loop_or_not_running(self):
+ """
+ Returns True if either self._loop is not running, or we're currently
+ executing on self._loop. In both cases, waiting for a future to be
+ resolved on the loop would result in a deadlock.
+ """
+ if not self._loop.is_running():
+ return True
+ current_loop = None
+ try:
+ # In python 3.7 there asyncio.get_running_loop() is prefered.
+ current_loop = asyncio.get_event_loop()
+ except RuntimeError:
+ # If there is no loop in current thread at all, and it is not main
+ # thread, we get error like:
+ # RuntimeError: There is no current event loop in thread 'Thread-1'
+ pass
+ return self._loop == current_loop
| ReactiveX/RxPY | 1bd44fe68183dcaad1c2a243c2fc4a255e986fbd | diff --git a/tests/test_scheduler/test_eventloop/test_asynciothreadsafescheduler.py b/tests/test_scheduler/test_eventloop/test_asynciothreadsafescheduler.py
index 849b0d3e..e09af2ca 100644
--- a/tests/test_scheduler/test_eventloop/test_asynciothreadsafescheduler.py
+++ b/tests/test_scheduler/test_eventloop/test_asynciothreadsafescheduler.py
@@ -92,3 +92,71 @@ class TestAsyncIOThreadSafeScheduler(unittest.TestCase):
assert ran is False
loop.run_until_complete(go())
+
+ def cancel_same_thread_common(self, test_body):
+ update_state = {
+ 'ran': False,
+ 'dispose_completed': False
+ }
+
+ def action(scheduler, state):
+ update_state['ran'] = True
+
+ # Make the actual test body run in deamon thread, so that in case of
+ # failure it doesn't hang indefinitely.
+ def thread_target():
+ loop = asyncio.new_event_loop()
+ scheduler = AsyncIOThreadSafeScheduler(loop)
+
+ test_body(scheduler, action, update_state)
+
+ @asyncio.coroutine
+ def go():
+ yield from asyncio.sleep(0.2, loop=loop)
+
+ loop.run_until_complete(go())
+
+ thread = threading.Thread(target=thread_target)
+ thread.daemon = True
+ thread.start()
+ thread.join(0.3)
+ assert update_state['dispose_completed'] is True
+ assert update_state['ran'] is False
+
+
+ def test_asyncio_threadsafe_cancel_non_relative_same_thread(self):
+ def test_body(scheduler, action, update_state):
+ d = scheduler.schedule(action)
+
+ # Test case when dispose is called on thread on which loop is not
+ # yet running, and non-relative schedele is used.
+ d.dispose()
+ update_state['dispose_completed'] = True
+
+ self.cancel_same_thread_common(test_body)
+
+
+ def test_asyncio_threadsafe_schedule_action_cancel_same_thread(self):
+ def test_body(scheduler, action, update_state):
+ d = scheduler.schedule_relative(0.05, action)
+
+ # Test case when dispose is called on thread on which loop is not
+ # yet running, and relative schedule is used.
+ d.dispose()
+ update_state['dispose_completed'] = True
+
+ self.cancel_same_thread_common(test_body)
+
+
+ def test_asyncio_threadsafe_schedule_action_cancel_same_loop(self):
+ def test_body(scheduler, action, update_state):
+ d = scheduler.schedule_relative(0.1, action)
+
+ def do_dispose():
+ d.dispose()
+ update_state['dispose_completed'] = True
+
+ # Test case when dispose is called in loop's callback.
+ scheduler._loop.call_soon(do_dispose)
+
+ self.cancel_same_thread_common(test_body)
| Deadlock in AsyncIOThreadSafeScheduler
Fallowing code produces deadlock:
```python
import rx
import rx.operators as ops
from rx.subject.subject import Subject
from rx.scheduler.eventloop import AsyncIOThreadSafeScheduler
import asyncio
import logging
def print_threads_traces(_):
import traceback
print("\n*** STACKTRACE - START ***\n")
code = []
for threadId, stack in sys._current_frames().items():
code.append("\n# ThreadID: %s" % threadId)
for filename, lineno, name, line in traceback.extract_stack(stack):
code.append('File: "%s", line %d, in %s' % (filename,
lineno, name))
if line:
code.append(" %s" % (line.strip()))
for line in code:
print(line)
print("\n*** STACKTRACE - END ***\n")
logging.basicConfig(
level=logging.DEBUG,
format='[%(threadName)s|%(levelname).5s|%(name).32s:%(lineno)d] %(message)s'
)
logger = logging.getLogger('repro')
loop = asyncio.get_event_loop()
scheduler = AsyncIOThreadSafeScheduler(loop)
src = Subject()
def log_and_push_another_one(msg):
logger.info(msg)
src.on_next(msg + "0")
logger.info('Done')
# Two delays are needed to break the cycle of action self-rescheduling in delay.py.
# That will cause setting cancelable.disposable = mad, which will cause previous
# disposable to be disposed, which will cause scheduler to wait for confirmation,
# which causes deadlock.
obs = src.pipe(ops.delay(1.0, scheduler=scheduler), ops.delay(1.0, scheduler=scheduler))
obs.subscribe(log_and_push_another_one)
# After few seconds print stack trace of each thread, in another thread.
rx.of(1).pipe(ops.delay(6.0)).subscribe(print_threads_traces)
loop.call_soon(src.on_next, "Message0")
loop.run_forever()
```
This is where thread waits:
```
File: "main.py", line 58, in <module>
loop.run_forever()
File: "/usr/lib/python3.6/asyncio/base_events.py", line 438, in run_forever
self._run_once()
File: "/usr/lib/python3.6/asyncio/base_events.py", line 1451, in _run_once
handle._run()
File: "/usr/lib/python3.6/asyncio/events.py", line 145, in _run
self._callback(*self._args)
File: "RxPY/rx/scheduler/eventloop/asynciothreadsafescheduler.py", line 87, in interval
sad.disposable = self.invoke_action(action, state=state)
File: "RxPY/rx/scheduler/scheduler.py", line 103, in invoke_action
ret = action(self, state)
File: "RxPY/rx/core/operators/delay.py", line 69, in action
result.accept(observer)
File: "RxPY/rx/core/notification.py", line 37, in accept
return self._accept_observer(on_next)
File: "RxPY/rx/core/notification.py", line 99, in _accept_observer
return observer.on_next(self.value)
File: "RxPY/rx/core/observer/autodetachobserver.py", line 26, in on_next
self._on_next(value)
File: "mamicu.py", line 43, in log_and_push_another_one
src.on_next(msg + "0")
File: "RxPY/rx/subject/subject.py", line 55, in on_next
super().on_next(value)
File: "RxPY/rx/core/observer/observer.py", line 26, in on_next
self._on_next_core(value)
File: "RxPY/rx/subject/subject.py", line 62, in _on_next_core
observer.on_next(value)
File: "RxPY/rx/core/observer/autodetachobserver.py", line 26, in on_next
self._on_next(value)
File: "RxPY/rx/core/operators/materialize.py", line 23, in on_next
observer.on_next(OnNext(value))
File: "RxPY/rx/core/observer/autodetachobserver.py", line 26, in on_next
self._on_next(value)
File: "RxPY/rx/core/operators/map.py", line 41, in on_next
obv.on_next(result)
File: "RxPY/rx/core/observer/autodetachobserver.py", line 26, in on_next
self._on_next(value)
File: "RxPY/rx/core/observer/autodetachobserver.py", line 26, in on_next
self._on_next(value)
File: "RxPY/rx/core/operators/delay.py", line 55, in on_next
cancelable.disposable = mad
File: "RxPY/rx/disposable/serialdisposable.py", line 39, in set_disposable
old.dispose()
File: "RxPY/rx/disposable/multipleassignmentdisposable.py", line 47, in dispose
old.dispose()
File: "RxPY/rx/disposable/compositedisposable.py", line 68, in dispose
disp.dispose()
File: "RxPY/rx/disposable/disposable.py", line 41, in dispose
self.action()
File: "RxPY/rx/scheduler/eventloop/asynciothreadsafescheduler.py", line 110, in dispose
future.result()
File: "/usr/lib/python3.6/concurrent/futures/_base.py", line 427, in result
self._condition.wait(timeout)
File: "/usr/lib/python3.6/threading.py", line 295, in wait
waiter.acquire()
```
It does not have to be two delays in a row, it can be observe_on after delay, or anything that prevents next delay action to be rescheduled immediately (see comment in code example).
It may seem to you that it is not real world use case to push item into observable from the same thread and asyncio loop as observer, but it is really important sometimes to be able to do everything in one thread, including pushing new items sometimes.
It may seem to you that we should use basic AsyncIOScheduler, but if sometimes we still need to do something from other threads, it becomes impossible, I have tried.
To me it seems that scheduler shouldn't really wait for that future, because:
1. Canceling in asyncio is best effort anyway.
2. Other scheduler don't seem to behave like that.
3. If I remove future, all tests pass anyway.
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_scheduler/test_eventloop/test_asynciothreadsafescheduler.py::TestAsyncIOThreadSafeScheduler::test_asyncio_threadsafe_cancel_non_relative_same_thread",
"tests/test_scheduler/test_eventloop/test_asynciothreadsafescheduler.py::TestAsyncIOThreadSafeScheduler::test_asyncio_threadsafe_schedule_action_cancel_same_loop",
"tests/test_scheduler/test_eventloop/test_asynciothreadsafescheduler.py::TestAsyncIOThreadSafeScheduler::test_asyncio_threadsafe_schedule_action_cancel_same_thread"
] | [
"tests/test_scheduler/test_eventloop/test_asynciothreadsafescheduler.py::TestAsyncIOThreadSafeScheduler::test_asyncio_threadsafe_schedule_action",
"tests/test_scheduler/test_eventloop/test_asynciothreadsafescheduler.py::TestAsyncIOThreadSafeScheduler::test_asyncio_threadsafe_schedule_action_cancel",
"tests/test_scheduler/test_eventloop/test_asynciothreadsafescheduler.py::TestAsyncIOThreadSafeScheduler::test_asyncio_threadsafe_schedule_action_due",
"tests/test_scheduler/test_eventloop/test_asynciothreadsafescheduler.py::TestAsyncIOThreadSafeScheduler::test_asyncio_threadsafe_schedule_now",
"tests/test_scheduler/test_eventloop/test_asynciothreadsafescheduler.py::TestAsyncIOThreadSafeScheduler::test_asyncio_threadsafe_schedule_now_units"
] | {
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
} | "2021-04-03T21:54:29Z" | mit |
|
RedHatInsights__insights-core-3193 | diff --git a/insights/formats/__init__.py b/insights/formats/__init__.py
index fc325d2f..ba3d55bc 100644
--- a/insights/formats/__init__.py
+++ b/insights/formats/__init__.py
@@ -87,9 +87,9 @@ class EvaluatorFormatterAdapter(FormatterAdapter):
def configure(p):
p.add_argument("-m", "--missing", help="Show missing requirements.", action="store_true")
p.add_argument("-S", "--show-rules", nargs="+",
- choices=["fail", "info", "pass", "metadata", "fingerprint"],
+ choices=["fail", "info", "pass", "none", "metadata", "fingerprint"],
metavar="TYPE",
- help="Show results per rule type(s).")
+ help="Show results per rule's type: 'fail', 'info', 'pass', 'none', 'metadata', and 'fingerprint'")
p.add_argument("-F", "--fail-only",
help="Show FAIL results only. Conflict with '-m', will be dropped when using them together. This option is deprecated by '-S fail'",
action="store_true")
@@ -104,7 +104,7 @@ class EvaluatorFormatterAdapter(FormatterAdapter):
# Drops the '-F' silently when specifying '-m' and '-F' together
# --> Do NOT break the Format of the output
fail_only = None
- self.show_rules = [] # Empty by default, means show ALL types
+ self.show_rules = [] # Empty by default, means show ALL types (exclude "none")
if not args.show_rules and fail_only:
self.show_rules = ['rule']
elif args.show_rules:
@@ -182,6 +182,9 @@ def get_response_of_types(response, missing=True, show_rules=None):
# - When "-m" is specified but "-S" is NOT specified, show all the loaded rules
# - When neither "-m" nor "-S" is specified, show all the HIT rules (exclude the "skips")
if not show_rules:
+ # - Discard the "make_none" by default when no "-S"
+ # That means show "make_none" rules only when "none" is specified in "-S"
+ response.pop('none') if 'none' in response else None
return response
# - Discard the "medadata" rules when it's not specified in the "-S" option
if 'metadata' not in show_rules and 'metadata' in response.get('system', {}):
@@ -195,6 +198,9 @@ def get_response_of_types(response, missing=True, show_rules=None):
# - Discard the "make_pass" rules when it's not specified in the "-S" option
if 'pass' not in show_rules and 'pass' in response:
response.pop('pass')
+ # - Discard the "make_none" rules when it's not specified in the "-S" option
+ if 'none' not in show_rules and 'none' in response:
+ response.pop('none')
# - Discard the "fingerprint" rules when it's not specified in the "-S" option
if 'fingerprint' not in show_rules and 'fingerprints' in response:
response.pop('fingerprints')
diff --git a/insights/formats/_markdown.py b/insights/formats/_markdown.py
index 90ac235b..c6144908 100644
--- a/insights/formats/_markdown.py
+++ b/insights/formats/_markdown.py
@@ -48,12 +48,13 @@ class MarkdownFormat(Formatter):
self.dropped = dropped
self.show_rules = [] if show_rules is None else show_rules
- self.counts = {'skip': 0, 'pass': 0, 'rule': 0, 'info': 0, 'metadata': 0, 'metadata_key': 0, 'fingerprint': 0, 'exception': 0}
+ self.counts = {'skip': 0, 'pass': 0, 'rule': 0, 'info': 0, 'none': 0, 'metadata': 0, 'metadata_key': 0, 'fingerprint': 0, 'exception': 0}
self.responses = {
'skip': self.response(label="SKIP", title="Missing Deps: "),
'pass': self.response(label="PASS", title="Passed : "),
'rule': self.response(label="FAIL", title="Failed : "),
'info': self.response(label="INFO", title="Info : "),
+ 'none': self.response(label="RETURNED NONE", title="Ret'd None : "),
'metadata': self.response(label="META", title="Metadata : "),
'metadata_key': self.response(label="META", title="Metadata Key: "),
'fingerprint': self.response(label="FINGERPRINT", title="Fingerprint : "),
@@ -148,8 +149,10 @@ class MarkdownFormat(Formatter):
if _type:
if self.missing and _type == 'skip':
print_missing(c, v)
- elif ((self.show_rules and _type in self.show_rules) or
- (not self.show_rules and _type != 'skip')):
+ elif (
+ (self.show_rules and _type in self.show_rules) or
+ (not self.show_rules and _type not in ['skip', 'none'])
+ ):
printit(c, v)
print(file=self.stream)
@@ -184,9 +187,9 @@ class MarkdownFormatAdapter(FormatterAdapter):
p.add_argument("-d", "--dropped", help="Show collected files that weren't processed.", action="store_true")
p.add_argument("-m", "--missing", help="Show missing requirements.", action="store_true")
p.add_argument("-S", "--show-rules", nargs="+",
- choices=["fail", "info", "pass", "metadata", "fingerprint"],
+ choices=["fail", "info", "pass", "none", "metadata", "fingerprint"],
metavar="TYPE",
- help="Show results per rule type(s).")
+ help="Show results per rule's type: 'fail', 'info', 'pass', 'none', 'metadata', and 'fingerprint'")
p.add_argument("-F", "--fail-only",
help="Show FAIL results only. Conflict with '-m', will be dropped when using them together. This option is deprecated by '-S fail'",
action="store_true")
@@ -197,7 +200,7 @@ class MarkdownFormatAdapter(FormatterAdapter):
if args.missing and fail_only:
print('Options conflict: -m and -F, drops -F', file=sys.stderr)
fail_only = None
- self.show_rules = [] # Empty by default, means show ALL types
+ self.show_rules = [] # Empty by default, means show ALL types (exclude "none")
if not args.show_rules and fail_only:
self.show_rules = ['rule']
elif args.show_rules:
diff --git a/insights/formats/text.py b/insights/formats/text.py
index e37e8ed3..f905eb49 100644
--- a/insights/formats/text.py
+++ b/insights/formats/text.py
@@ -89,12 +89,10 @@ class HumanReadableFormat(Formatter):
missing=False,
tracebacks=False,
dropped=False,
- none=False,
show_rules=None,
stream=sys.stdout):
super(HumanReadableFormat, self).__init__(broker, stream=stream)
self.missing = missing
- self.none = none
self.tracebacks = tracebacks
self.dropped = dropped
self.show_rules = [] if show_rules is None else show_rules
@@ -108,16 +106,15 @@ class HumanReadableFormat(Formatter):
def preprocess(self):
response = namedtuple('response', 'color label intl title')
self.responses = {
+ 'skip': response(color=Fore.BLUE, label="SKIP", intl='S', title="Missing Deps: "),
'pass': response(color=Fore.GREEN, label="PASS", intl='P', title="Passed : "),
'rule': response(color=Fore.RED, label="FAIL", intl='F', title="Failed : "),
'info': response(color=Fore.WHITE, label="INFO", intl='I', title="Info : "),
- 'skip': response(color=Fore.BLUE, label="SKIP", intl='S', title="Missing Deps: "),
- 'fingerprint': response(color=Fore.YELLOW, label="FINGERPRINT", intl='P',
- title="Fingerprint : "),
+ 'none': response(color=Fore.BLUE, label="RETURNED NONE", intl='N', title="Ret'd None : "),
'metadata': response(color=Fore.YELLOW, label="META", intl='M', title="Metadata : "),
'metadata_key': response(color=Fore.MAGENTA, label="META", intl='K', title="Metadata Key: "),
+ 'fingerprint': response(color=Fore.YELLOW, label="FINGERPRINT", intl='P', title="Fingerprint : "),
'exception': response(color=Fore.RED, label="EXCEPT", intl='E', title="Exceptions : "),
- 'none': response(color=Fore.BLUE, label="RETURNED NONE", intl='N', title="Ret'd None : ")
}
self.counts = {}
@@ -193,10 +190,11 @@ class HumanReadableFormat(Formatter):
if _type in self.responses:
self.counts[_type] += 1
- if ((self.missing and _type == 'skip') or
+ if (
+ (self.missing and _type == 'skip') or
(self.show_rules and _type in self.show_rules) or
- (self.none and _type == 'none') or
- (not self.show_rules and _type not in ['skip', 'none'])):
+ (not self.show_rules and _type not in ['skip', 'none'])
+ ):
printit(c, v)
print(file=self.stream)
@@ -225,11 +223,10 @@ class HumanReadableFormatAdapter(FormatterAdapter):
p.add_argument("-t", "--tracebacks", help="Show stack traces.", action="store_true")
p.add_argument("-d", "--dropped", help="Show collected files that weren't processed.", action="store_true")
p.add_argument("-m", "--missing", help="Show missing requirements.", action="store_true")
- p.add_argument("-n", "--none", help="Show rules returning None", action="store_true")
p.add_argument("-S", "--show-rules", default=[], nargs="+",
- choices=["fail", "info", "pass", "metadata", "fingerprint"],
+ choices=["fail", "info", "pass", "none", "metadata", "fingerprint"],
metavar="TYPE",
- help="Show results per rule type(s).")
+ help="Show results per rule's type: 'fail', 'info', 'pass', 'none', 'metadata', and 'fingerprint'")
p.add_argument("-F", "--fail-only",
help="Show FAIL results only. Conflict with '-m', will be dropped when using them together. This option is deprecated by '-S fail'",
action="store_true")
@@ -238,12 +235,11 @@ class HumanReadableFormatAdapter(FormatterAdapter):
self.tracebacks = args.tracebacks
self.dropped = args.dropped
self.missing = args.missing
- self.none = args.none
fail_only = args.fail_only
- if (self.missing or self.none) and fail_only:
- print(Fore.YELLOW + 'Options conflict: -m/-n and -F, drops -F', file=sys.stderr)
+ if self.missing and fail_only:
+ print(Fore.YELLOW + 'Options conflict: -m and -F, drops -F', file=sys.stderr)
fail_only = None
- self.show_rules = [] # Empty by default, means show ALL types
+ self.show_rules = [] # Empty by default, means show ALL types (excludes "none")
if not args.show_rules and fail_only:
self.show_rules = ['rule']
elif args.show_rules:
@@ -255,7 +251,6 @@ class HumanReadableFormatAdapter(FormatterAdapter):
self.missing,
self.tracebacks,
self.dropped,
- self.none,
self.show_rules,
)
self.formatter.preprocess()
diff --git a/insights/parsers/ntp_sources.py b/insights/parsers/ntp_sources.py
index 8b1e6ed1..aee9c741 100644
--- a/insights/parsers/ntp_sources.py
+++ b/insights/parsers/ntp_sources.py
@@ -14,23 +14,20 @@ Parsers in this module are:
ChronycSources - command ``/usr/bin/chronyc sources``
-----------------------------------------------------
-NtpqLeap - command ``/usr/sbin/ntpq -c 'rv 0 leap'``
-----------------------------------------------------
-
NtpqPn - command ``/usr/sbin/ntpq -pn``
---------------------------------------
-
+NtpqLeap - command ``/usr/sbin/ntpq -c 'rv 0 leap'``
+----------------------------------------------------
"""
-import re
-from .. import parser, CommandParser
+from insights import parser, CommandParser
from insights.core.dr import SkipComponent
from insights.specs import Specs
@parser(Specs.chronyc_sources)
-class ChronycSources(CommandParser):
+class ChronycSources(CommandParser, list):
"""
Chronyc Sources parser
@@ -49,14 +46,15 @@ class ChronycSources(CommandParser):
Examples:
- >>> sources = shared[ChronycSources].data
- >>> len(sources)
+ >>> type(chrony_sources)
+ <class 'insights.parsers.ntp_sources.ChronycSources'>
+ >>> len(chrony_sources)
4
- >>> sources[0]['source']
+ >>> chrony_sources[0]['source']
'10.20.30.40'
- >>> sources[0]['mode']
+ >>> chrony_sources[0]['mode']
'^'
- >>> sources[0]['state']
+ >>> chrony_sources[0]['state']
'-'
"""
@@ -64,15 +62,34 @@ class ChronycSources(CommandParser):
"""
Get source, mode and state for chrony
"""
- self.data = []
- for row in content[3:]:
- if row.strip():
- values = row.split(" ", 2)
- self.data.append({"source": values[1], "mode": values[0][0], "state": values[0][1]})
+ data = []
+ if len(content) > 3:
+ for row in content[3:]:
+ if row.strip():
+ values = row.split(" ", 2)
+ data.append(
+ {
+ "source": values[1],
+ "mode": values[0][0],
+ "state": values[0][1]
+ }
+ )
+
+ if not data:
+ raise SkipComponent()
+
+ self.extend(data)
+
+ @property
+ def data(self):
+ """
+ Set data as property to keep compatibility
+ """
+ return self
@parser(Specs.ntpq_leap)
-class NtpqLeap(CommandParser):
+class NtpqLeap(CommandParser, dict):
"""
Converts the output of ``ntpq -c 'rv 0 leap'`` into a dictionary in the
``data`` property, and sets the ``leap`` property to the value of the
@@ -84,26 +101,43 @@ class NtpqLeap(CommandParser):
Examples:
- >>> print shared[NtpqLeap].leap # same data
+ >>> type(ntpq)
+ <class 'insights.parsers.ntp_sources.NtpqLeap'>
+ >>> ntpq.leap
'00'
"""
def parse_content(self, content):
- if "Connection refused" in content[0]:
+ if content and "Connection refused" in content[0]:
raise SkipComponent("NTP service is down and connection refused")
- self.data = {}
+
+ leap = None
for line in content:
- m = re.search(r'leap=(\d*)', line)
- if m:
- self.data["leap"] = m.group(1)
+ if 'leap=' in line:
+ leap = line.split('leap=')[1].rstrip()
+
+ if leap is None:
+ raise SkipComponent()
+
+ self.update(leap=leap)
+
+ @property
+ def data(self):
+ """
+ Set data as property to keep compatibility
+ """
+ return self
@property
def leap(self):
- return self.data.get('leap')
+ """
+ Return the value of the 'leap'
+ """
+ return self.get('leap')
@parser(Specs.ntpq_pn)
-class NtpqPn(CommandParser):
+class NtpqPn(CommandParser, list):
"""
Get source and flag for each NTP time source from the output of
``/usr/sbin/ntpq -pn``.
@@ -124,21 +158,36 @@ class NtpqPn(CommandParser):
Examples:
- >>> sources = shared[NtpqPn].data
- >>> len(sources)
+ >>> type(ntp_sources)
+ <class 'insights.parsers.ntp_sources.NtpqPn'>
+ >>> len(ntp_sources)
4
- >>> sources[0]
- {'flag': '*', 'source', '10.20.30.40'}
+ >>> ntp_sources[0]['source']
+ '10.20.30.40'
"""
def parse_content(self, content):
- if "Connection refused" in content[0]:
+ if content and "Connection refused" in content[0]:
raise SkipComponent("NTP service is down and connection refused")
- self.data = []
- for row in content[2:]:
- if row.strip():
- values = row.split(" ", 2)
- if row.startswith(" "):
- self.data.append({"source": values[1], "flag": " "})
- else:
- self.data.append({"source": values[0][1:], "flag": values[0][0]})
+
+ data = []
+ if len(content) > 2:
+ for row in content[2:]:
+ if row.strip():
+ values = row.split(" ", 2)
+ if row.startswith(" "):
+ data.append({"source": values[1], "flag": " "})
+ else:
+ data.append({"source": values[0][1:], "flag": values[0][0]})
+
+ if not data:
+ raise SkipComponent()
+
+ self.extend(data)
+
+ @property
+ def data(self):
+ """
+ Set data as property to keep compatibility
+ """
+ return self
| RedHatInsights/insights-core | b9d1412f8edf09cb9969bb96d96eadbd4bc91e6e | diff --git a/insights/parsers/tests/test_ntp_sources.py b/insights/parsers/tests/test_ntp_sources.py
index 590e5b93..d1249d0d 100644
--- a/insights/parsers/tests/test_ntp_sources.py
+++ b/insights/parsers/tests/test_ntp_sources.py
@@ -1,5 +1,7 @@
import pytest
+import doctest
from insights.core.dr import SkipComponent
+from insights.parsers import ntp_sources
from insights.parsers.ntp_sources import ChronycSources, NtpqPn, NtpqLeap
from insights.tests import context_wrap
@@ -12,6 +14,20 @@ MS Name/IP address Stratum Poll Reach LastRx Last sample
^+ d.e.f 1 6 377 21 -2629us[-2619us] +/- 86ms
""".strip()
+chrony_output_doc = """
+210 Number of sources = 6
+MS Name/IP address Stratum Poll Reach LastRx Last sample
+===============================================================================
+^- 10.20.30.40 2 9 377 95 -1345us[-1345us] +/- 87ms
+^- 10.56.72.8 2 10 377 949 -3449us[-3483us] +/- 120ms
+^* 10.64.108.95 2 10 377 371 -91us[ -128us] +/- 30ms
+^- 10.8.205.17 2 8 377 27 +7161us[+7161us] +/- 52ms
+""".strip()
+
+empty_chrony_source = ""
+
+empty_ntpq_leap = ""
+
ntpq_leap_output = """
leap=00
""".strip()
@@ -32,7 +48,18 @@ ntpd_qn = """
remote refid st t when poll reach delay offset jitter
==============================================================================
202.118.1.81 .INIT. 16 u - 1024 0 0.000 0.000 0.000
-"""
+""".strip()
+
+ntpd_qn_doc = """
+ remote refid st t when poll reach delay offset jitter
+==============================================================================
++10.20.30.40 192.231.203.132 3 u 638 1024 377 0.242 2.461 1.886
+*2001:388:608c:8 .GPS. 1 u 371 1024 377 29.323 1.939 1.312
+-2001:44b8:1::1 216.218.254.202 2 u 396 1024 377 37.869 -3.340 6.458
++150.203.1.10 202.6.131.118 2 u 509 1024 377 20.135 0.800 3.260
+""".strip()
+
+empty_ntpq_pn = ""
ntp_connection_issue = """
/usr/sbin/ntpq: read: Connection refused
@@ -45,6 +72,9 @@ def test_get_chrony_sources():
assert parser_result.data[2].get("state") == "+"
assert parser_result.data[2].get("mode") == "^"
+ with pytest.raises(SkipComponent):
+ NtpqPn(context_wrap(empty_chrony_source))
+
def test_get_ntpq_leap():
parser_result = NtpqLeap(context_wrap(ntpq_leap_output))
@@ -57,6 +87,9 @@ def test_get_ntpq_leap():
NtpqLeap(context_wrap(ntp_connection_issue))
assert "NTP service is down" in str(e)
+ with pytest.raises(SkipComponent):
+ NtpqLeap(context_wrap(empty_ntpq_leap))
+
def test_get_ntpd_sources():
parser_result = NtpqPn(context_wrap(ntpd_output))
@@ -71,3 +104,16 @@ def test_get_ntpd_sources():
with pytest.raises(SkipComponent) as e:
NtpqPn(context_wrap(ntp_connection_issue))
assert "NTP service is down" in str(e)
+
+ with pytest.raises(SkipComponent):
+ NtpqPn(context_wrap(empty_ntpq_pn))
+
+
+def test_ntp_sources_doc_examples():
+ env = {
+ 'chrony_sources': ChronycSources(context_wrap(chrony_output_doc)),
+ 'ntpq': NtpqLeap(context_wrap(ntpq_leap_output)),
+ 'ntp_sources': NtpqPn(context_wrap(ntpd_qn_doc)),
+ }
+ failed, total = doctest.testmod(ntp_sources, globs=env)
+ assert failed == 0
| Parsers in ntp_sources return None when the output is empty
Parsers should be skipped when nothing needs to be parsed.
This issue cause some false positives | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"insights/parsers/tests/test_ntp_sources.py::test_get_chrony_sources",
"insights/parsers/tests/test_ntp_sources.py::test_get_ntpq_leap",
"insights/parsers/tests/test_ntp_sources.py::test_get_ntpd_sources",
"insights/parsers/tests/test_ntp_sources.py::test_ntp_sources_doc_examples"
] | [] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2021-08-17T09:01:11Z" | apache-2.0 |
|
RedHatInsights__insights-core-3486 | diff --git a/docs/custom_datasources_index.rst b/docs/custom_datasources_index.rst
index dd95cb25..deca243a 100644
--- a/docs/custom_datasources_index.rst
+++ b/docs/custom_datasources_index.rst
@@ -11,6 +11,14 @@ insights.specs.datasources
:show-inheritance:
:undoc-members:
+insights.specs.datasources.aws
+------------------------------
+
+.. automodule:: insights.specs.datasources.aws
+ :members: aws_imdsv2_token, LocalSpecs
+ :show-inheritance:
+ :undoc-members:
+
insights.specs.datasources.awx_manage
-------------------------------------
diff --git a/insights/specs/datasources/aws.py b/insights/specs/datasources/aws.py
new file mode 100644
index 00000000..2e32aec5
--- /dev/null
+++ b/insights/specs/datasources/aws.py
@@ -0,0 +1,42 @@
+"""
+Custom datasources for aws information
+"""
+from insights.components.cloud_provider import IsAWS
+from insights.core.context import HostContext
+from insights.core.dr import SkipComponent
+from insights.core.plugins import datasource
+from insights.core.spec_factory import simple_command
+from insights.specs import Specs
+
+
+class LocalSpecs(Specs):
+ """ Local specs used only by aws datasources """
+ aws_imdsv2_token = simple_command(
+ '/usr/bin/curl -s -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 60" --connect-timeout 5',
+ deps=[IsAWS]
+ )
+
+
+@datasource(LocalSpecs.aws_imdsv2_token, HostContext)
+def aws_imdsv2_token(broker):
+ """
+ This datasource provides a session token for use by other specs to collect
+ metadata information on AWS EC2 nodes with IMDSv2 support..
+
+ Typical output of the input spec, which is also the output of this datasource::
+
+ AQAEABcCFaLcKRfXhLV9_ezugiVzra-qMBoPbdWGLrbdfqSLEJzP8w==
+
+ Returns:
+ str: String that is the actual session token to be used in other commands
+
+ Raises:
+ SkipComponent: When an error occurs or no token is generated
+ """
+ try:
+ token = broker[LocalSpecs.aws_imdsv2_token].content[0].strip()
+ if token:
+ return token
+ except Exception as e:
+ raise SkipComponent("Unexpected exception:{e}".format(e=str(e)))
+ raise SkipComponent
diff --git a/insights/specs/default.py b/insights/specs/default.py
index 9744474a..affddbf4 100644
--- a/insights/specs/default.py
+++ b/insights/specs/default.py
@@ -17,13 +17,13 @@ from insights.core.spec_factory import simple_file, simple_command, glob_file
from insights.core.spec_factory import first_of, command_with_args
from insights.core.spec_factory import foreach_collect, foreach_execute
from insights.core.spec_factory import first_file, listdir
-from insights.components.cloud_provider import IsAWS, IsAzure, IsGCP
+from insights.components.cloud_provider import IsAzure, IsGCP
from insights.components.ceph import IsCephMonitor
from insights.components.virtualization import IsBareMetal
from insights.combiners.satellite_version import SatelliteVersion, CapsuleVersion
from insights.specs import Specs
from insights.specs.datasources import (
- awx_manage, cloud_init, candlepin_broker, corosync as corosync_ds,
+ aws, awx_manage, cloud_init, candlepin_broker, corosync as corosync_ds,
dir_list, ethernet, httpd, ipcs, kernel_module_list, lpstat, md5chk,
package_provides, ps as ps_datasource, sap, satellite_missed_queues,
ssl_certificate, system_user_dirs, user_group, yum_updates)
@@ -72,8 +72,8 @@ class DefaultSpecs(Specs):
audit_log = simple_file("/var/log/audit/audit.log")
avc_hash_stats = simple_file("/sys/fs/selinux/avc/hash_stats")
avc_cache_threshold = simple_file("/sys/fs/selinux/avc/cache_threshold")
- aws_instance_id_doc = simple_command("/usr/bin/curl -s http://169.254.169.254/latest/dynamic/instance-identity/document --connect-timeout 5", deps=[IsAWS])
- aws_instance_id_pkcs7 = simple_command("/usr/bin/curl -s http://169.254.169.254/latest/dynamic/instance-identity/pkcs7 --connect-timeout 5", deps=[IsAWS])
+ aws_instance_id_doc = command_with_args('/usr/bin/curl -s -H "X-aws-ec2-metadata-token: %s" http://169.254.169.254/latest/dynamic/instance-identity/document --connect-timeout 5', aws.aws_imdsv2_token, deps=[aws.aws_imdsv2_token])
+ aws_instance_id_pkcs7 = command_with_args('/usr/bin/curl -s -H "X-aws-ec2-metadata-token: %s" http://169.254.169.254/latest/dynamic/instance-identity/pkcs7 --connect-timeout 5', aws.aws_imdsv2_token, deps=[aws.aws_imdsv2_token])
awx_manage_check_license = simple_command("/usr/bin/awx-manage check_license")
awx_manage_check_license_data = awx_manage.awx_manage_check_license_data_datasource
awx_manage_print_settings = simple_command("/usr/bin/awx-manage print_settings INSIGHTS_TRACKING_STATE SYSTEM_UUID INSTALL_UUID TOWER_URL_BASE AWX_CLEANUP_PATHS AWX_PROOT_BASE_PATH LOG_AGGREGATOR_ENABLED LOG_AGGREGATOR_LEVEL --format json")
| RedHatInsights/insights-core | 4e6611a7150507b0d2c8c85c562fd671ee1ac502 | diff --git a/insights/tests/datasources/test_aws.py b/insights/tests/datasources/test_aws.py
new file mode 100644
index 00000000..8de9aff0
--- /dev/null
+++ b/insights/tests/datasources/test_aws.py
@@ -0,0 +1,30 @@
+import pytest
+from mock.mock import Mock
+from insights.core.dr import SkipComponent
+from insights.specs.datasources.aws import aws_imdsv2_token, LocalSpecs
+
+
+TOKEN = "1234567890\n"
+
+
+def test_aws_imdsv2_token():
+ input_spec = Mock()
+ input_spec.content = [TOKEN, ]
+ broker = {LocalSpecs.aws_imdsv2_token: input_spec}
+ results = aws_imdsv2_token(broker)
+ assert results == TOKEN.strip()
+
+
+def test_aws_imdsv2_token_exp():
+ input_spec = Mock()
+ input_spec.content = []
+ broker = {LocalSpecs.aws_imdsv2_token: input_spec}
+ with pytest.raises(Exception) as ex:
+ aws_imdsv2_token(broker)
+ assert "Unexpected" in str(ex)
+
+ input_spec = Mock()
+ input_spec.content = [" ", ]
+ broker = {LocalSpecs.aws_imdsv2_token: input_spec}
+ with pytest.raises(SkipComponent) as ex:
+ aws_imdsv2_token(broker)
| AWS EC2 metadata specs need to support IMDSv2
The current specs to collect metadata from AWS EC2 nodes only supports IMDSv1, and they need to be updated to be compatible with [IMDSv2 sessions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/configuring-instance-metadata-service.html). The problem that this creates is the specs `aws_instance_id_doc` and `aws_instance_id_pkcs7` will execute on an EC2 node with IMDBv2 support only, and they will not generate an error, but no data is returned.
The specs need to support a session token so that they can work with both IMDBv1 and v2. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"insights/tests/datasources/test_aws.py::test_aws_imdsv2_token",
"insights/tests/datasources/test_aws.py::test_aws_imdsv2_token_exp"
] | [] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_added_files",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2022-07-29T17:00:11Z" | apache-2.0 |
|
RedHatInsights__insights-core-3649 | diff --git a/insights/core/dr.py b/insights/core/dr.py
index 664c6811..8bad68be 100644
--- a/insights/core/dr.py
+++ b/insights/core/dr.py
@@ -1013,7 +1013,7 @@ def run_order(graph):
return toposort_flatten(graph, sort=False)
-def _determine_components(components):
+def determine_components(components):
if isinstance(components, dict):
return components
@@ -1033,27 +1033,17 @@ def _determine_components(components):
return COMPONENTS[components]
-def run(components=None, broker=None):
- """
- Executes components in an order that satisfies their dependency
- relationships.
+_determine_components = determine_components
- Keyword Args:
- components: Can be one of a dependency graph, a single component, a
- component group, or a component type. If it's anything other than a
- dependency graph, the appropriate graph is built for you and before
- evaluation.
- broker (Broker): Optionally pass a broker to use for evaluation. One is
- created by default, but it's often useful to seed a broker with an
- initial dependency.
- Returns:
- Broker: The broker after evaluation.
+
+def run_components(ordered_components, components, broker):
"""
- components = components or COMPONENTS[GROUPS.single]
- components = _determine_components(components)
- broker = broker or Broker()
+ Runs a list of preordered components using the provided broker.
- for component in run_order(components):
+ This function allows callers to order components themselves and cache the
+ result so they don't incur the toposort overhead on every run.
+ """
+ for component in ordered_components:
start = time.time()
try:
if (component not in broker and component in components and
@@ -1081,9 +1071,31 @@ def run(components=None, broker=None):
return broker
+def run(components=None, broker=None):
+ """
+ Executes components in an order that satisfies their dependency
+ relationships.
+
+ Keyword Args:
+ components: Can be one of a dependency graph, a single component, a
+ component group, or a component type. If it's anything other than a
+ dependency graph, the appropriate graph is built for you and before
+ evaluation.
+ broker (Broker): Optionally pass a broker to use for evaluation. One is
+ created by default, but it's often useful to seed a broker with an
+ initial dependency.
+ Returns:
+ Broker: The broker after evaluation.
+ """
+ components = components or COMPONENTS[GROUPS.single]
+ components = determine_components(components)
+ broker = broker or Broker()
+ return run_components(run_order(components), components, broker)
+
+
def generate_incremental(components=None, broker=None):
components = components or COMPONENTS[GROUPS.single]
- components = _determine_components(components)
+ components = determine_components(components)
for graph in get_subgraphs(components):
yield graph, broker or Broker()
diff --git a/insights/core/plugins.py b/insights/core/plugins.py
index 2d9c8385..5fa70452 100644
--- a/insights/core/plugins.py
+++ b/insights/core/plugins.py
@@ -34,6 +34,7 @@ from pprint import pformat
from six import StringIO
from insights.core import dr
+from insights.core.context import HostContext
from insights.util.subproc import CalledProcessError
from insights import settings
@@ -97,10 +98,11 @@ class datasource(PluginType):
def invoke(self, broker):
# Grab the timeout from the decorator, or use the default of 120.
- self.timeout = getattr(self, "timeout", 120)
- signal.signal(signal.SIGALRM, self._handle_timeout)
- signal.alarm(self.timeout)
+ if HostContext in broker:
+ self.timeout = getattr(self, "timeout", 120)
+ signal.signal(signal.SIGALRM, self._handle_timeout)
+ signal.alarm(self.timeout)
try:
return self.component(broker)
except ContentException as ce:
@@ -122,7 +124,8 @@ class datasource(PluginType):
broker.add_exception(reg_spec, te, te_tb)
raise dr.SkipComponent()
finally:
- signal.alarm(0)
+ if HostContext in broker:
+ signal.alarm(0)
class parser(PluginType):
diff --git a/insights/core/spec_factory.py b/insights/core/spec_factory.py
index 5ef223e5..20d05bec 100644
--- a/insights/core/spec_factory.py
+++ b/insights/core/spec_factory.py
@@ -303,7 +303,8 @@ class CommandOutputProvider(ContentProvider):
"""
Class used in datasources to return output from commands.
"""
- def __init__(self, cmd, ctx, root="insights_commands", args=None, split=True, keep_rc=False, ds=None, timeout=None, inherit_env=None, signum=None):
+ def __init__(self, cmd, ctx, root="insights_commands", args=None, split=True, keep_rc=False, ds=None, timeout=None,
+ inherit_env=None, override_env=None, signum=None):
super(CommandOutputProvider, self).__init__()
self.cmd = cmd
self.root = root
@@ -313,11 +314,13 @@ class CommandOutputProvider(ContentProvider):
self.keep_rc = keep_rc
self.ds = ds
self.timeout = timeout
- self.inherit_env = inherit_env or []
+ self.inherit_env = inherit_env if inherit_env is not None else []
+ self.override_env = override_env if override_env is not None else dict()
self.signum = signum or signal.SIGKILL
self._misc_settings()
self._content = None
+ self._env = self.create_env()
self.rc = None
self.validate()
@@ -332,7 +335,7 @@ class CommandOutputProvider(ContentProvider):
raise dr.SkipComponent()
cmd = shlex.split(self.cmd)[0]
- if not which(cmd, env=self.create_env()):
+ if not which(cmd, env=self._env):
raise ContentException("Command not found: %s" % cmd)
def create_args(self):
@@ -357,16 +360,21 @@ class CommandOutputProvider(ContentProvider):
def create_env(self):
env = dict(SAFE_ENV)
+
for e in self.inherit_env:
if e in os.environ:
env[e] = os.environ[e]
+
+ for k, v in self.override_env.items():
+ env[k] = v
+
return env
def load(self):
command = self.create_args()
- raw = self.ctx.shell_out(command, split=self.split, keep_rc=self.keep_rc,
- timeout=self.timeout, env=self.create_env(), signum=self.signum)
+ raw = self.ctx.shell_out(command, split=self.split, keep_rc=self.keep_rc, timeout=self.timeout,
+ env=self._env, signum=self.signum)
if self.keep_rc:
self.rc, output = raw
else:
@@ -384,7 +392,7 @@ class CommandOutputProvider(ContentProvider):
yield self._content
else:
args = self.create_args()
- with self.ctx.connect(*args, env=self.create_env(), timeout=self.timeout) as s:
+ with self.ctx.connect(*args, env=self._env, timeout=self.timeout) as s:
yield s
except StopIteration:
raise
@@ -397,7 +405,7 @@ class CommandOutputProvider(ContentProvider):
fs.ensure_path(os.path.dirname(dst))
if args:
timeout = self.timeout or self.ctx.timeout
- p = Pipeline(*args, timeout=timeout, signum=self.signum, env=self.create_env())
+ p = Pipeline(*args, timeout=timeout, signum=self.signum, env=self._env)
return p.write(dst, keep_rc=self.keep_rc)
def __repr__(self):
@@ -405,11 +413,13 @@ class CommandOutputProvider(ContentProvider):
class ContainerProvider(CommandOutputProvider):
- def __init__(self, cmd_path, ctx, image=None, args=None, split=True, keep_rc=False, ds=None, timeout=None, inherit_env=None, signum=None):
+ def __init__(self, cmd_path, ctx, image=None, args=None, split=True, keep_rc=False, ds=None, timeout=None,
+ inherit_env=None, override_env=None, signum=None):
# cmd = "<podman|docker> exec container_id command"
# path = "<podman|docker> exec container_id cat path"
self.image = image
- super(ContainerProvider, self).__init__(cmd_path, ctx, "insights_containers", args, split, keep_rc, ds, timeout, inherit_env, signum)
+ super(ContainerProvider, self).__init__(cmd_path, ctx, "insights_containers", args, split, keep_rc, ds, timeout,
+ inherit_env, override_env, signum)
class ContainerFileProvider(ContainerProvider):
@@ -762,28 +772,33 @@ class simple_command(object):
CalledProcessError is raised. If None, timeout is infinite.
inherit_env (list): The list of environment variables to inherit from the
calling process when the command is invoked.
+ override_env (dict): A dict of environment variables to override from the
+ calling process when the command is invoked.
Returns:
function: A datasource that returns the output of a command that takes
no arguments
"""
-
- def __init__(self, cmd, context=HostContext, deps=[], split=True, keep_rc=False, timeout=None, inherit_env=[], signum=None, **kwargs):
+ def __init__(self, cmd, context=HostContext, deps=None, split=True, keep_rc=False, timeout=None, inherit_env=None,
+ override_env=None, signum=None, **kwargs):
+ deps = deps if deps is not None else []
self.cmd = cmd
self.context = context
self.split = split
self.raw = not split
self.keep_rc = keep_rc
self.timeout = timeout
- self.inherit_env = inherit_env
+ self.inherit_env = inherit_env if inherit_env is not None else []
+ self.override_env = override_env if override_env is not None else dict()
self.signum = signum
self.__name__ = self.__class__.__name__
datasource(self.context, *deps, raw=self.raw, **kwargs)(self)
def __call__(self, broker):
ctx = broker[self.context]
- return CommandOutputProvider(self.cmd, ctx, split=self.split,
- keep_rc=self.keep_rc, ds=self, timeout=self.timeout, inherit_env=self.inherit_env, signum=self.signum)
+ return CommandOutputProvider(self.cmd, ctx, split=self.split, keep_rc=self.keep_rc, ds=self,
+ timeout=self.timeout, inherit_env=self.inherit_env, override_env=self.override_env,
+ signum=self.signum)
class command_with_args(object):
@@ -807,13 +822,15 @@ class command_with_args(object):
CalledProcessError is raised. If None, timeout is infinite.
inherit_env (list): The list of environment variables to inherit from the
calling process when the command is invoked.
+ override_env (dict): A dict of environment variables to override from the
+ calling process when the command is invoked.
Returns:
function: A datasource that returns the output of a command that takes
specified arguments passed by the provider.
"""
-
- def __init__(self, cmd, provider, context=HostContext, deps=None, split=True, keep_rc=False, timeout=None, inherit_env=None, signum=None, **kwargs):
+ def __init__(self, cmd, provider, context=HostContext, deps=None, split=True, keep_rc=False, timeout=None,
+ inherit_env=None, override_env=None, signum=None, **kwargs):
deps = deps if deps is not None else []
self.cmd = cmd
self.provider = provider
@@ -823,6 +840,7 @@ class command_with_args(object):
self.keep_rc = keep_rc
self.timeout = timeout
self.inherit_env = inherit_env if inherit_env is not None else []
+ self.override_env = override_env if override_env is not None else dict()
self.signum = signum
self.__name__ = self.__class__.__name__
datasource(self.provider, self.context, *deps, raw=self.raw, **kwargs)(self)
@@ -831,11 +849,13 @@ class command_with_args(object):
source = broker[self.provider]
ctx = broker[self.context]
if not isinstance(source, (str, tuple)):
- raise ContentException("The provider can only be a single string or a tuple of strings, but got '%s'." % source)
+ raise ContentException("The provider can only be a single string or a tuple of strings, but got '%s'." %
+ source)
try:
self.cmd = self.cmd % source
- return CommandOutputProvider(self.cmd, ctx, split=self.split,
- keep_rc=self.keep_rc, ds=self, timeout=self.timeout, inherit_env=self.inherit_env, signum=self.signum)
+ return CommandOutputProvider(self.cmd, ctx, split=self.split, keep_rc=self.keep_rc, ds=self,
+ timeout=self.timeout, inherit_env=self.inherit_env,
+ override_env=self.override_env, signum=self.signum)
except ContentException as ce:
log.debug(ce)
except Exception:
@@ -869,14 +889,16 @@ class foreach_execute(object):
CalledProcessError is raised. If None, timeout is infinite.
inherit_env (list): The list of environment variables to inherit from the
calling process when the command is invoked.
-
+ override_env (dict): A dict of environment variables to override from the
+ calling process when the command is invoked.
Returns:
function: A datasource that returns a list of outputs for each command
created by substituting each element of provider into the cmd template.
"""
-
- def __init__(self, provider, cmd, context=HostContext, deps=[], split=True, keep_rc=False, timeout=None, inherit_env=[], signum=None, **kwargs):
+ def __init__(self, provider, cmd, context=HostContext, deps=None, split=True, keep_rc=False, timeout=None,
+ inherit_env=None, override_env=None, signum=None, **kwargs):
+ deps = deps if deps is not None else []
self.provider = provider
self.cmd = cmd
self.context = context
@@ -884,7 +906,8 @@ class foreach_execute(object):
self.raw = not split
self.keep_rc = keep_rc
self.timeout = timeout
- self.inherit_env = inherit_env
+ self.inherit_env = inherit_env if inherit_env is not None else []
+ self.override_env = override_env if override_env is not None else dict()
self.signum = signum
self.__name__ = self.__class__.__name__
datasource(self.provider, self.context, *deps, multi_output=True, raw=self.raw, **kwargs)(self)
@@ -900,9 +923,9 @@ class foreach_execute(object):
for e in source:
try:
the_cmd = self.cmd % e
- cop = CommandOutputProvider(the_cmd, ctx, args=e,
- split=self.split, keep_rc=self.keep_rc, ds=self,
- timeout=self.timeout, inherit_env=self.inherit_env, signum=self.signum)
+ cop = CommandOutputProvider(the_cmd, ctx, args=e, split=self.split, keep_rc=self.keep_rc, ds=self,
+ timeout=self.timeout, inherit_env=self.inherit_env,
+ override_env=self.override_env, signum=self.signum)
result.append(cop)
except ContentException as ce:
log.debug(ce)
@@ -1015,9 +1038,10 @@ class container_execute(foreach_execute):
cmd = self.cmd % args if args else self.cmd
# the_cmd = <podman|docker> exec container_id cmd
the_cmd = "/usr/bin/%s exec %s %s" % (engine, cid, cmd)
- ccp = ContainerCommandProvider(the_cmd, ctx, image=image, args=e,
- split=self.split, keep_rc=self.keep_rc, ds=self,
- timeout=self.timeout, inherit_env=self.inherit_env, signum=self.signum)
+ ccp = ContainerCommandProvider(the_cmd, ctx, image=image, args=e, split=self.split,
+ keep_rc=self.keep_rc, ds=self, timeout=self.timeout,
+ inherit_env=self.inherit_env, override_env=self.override_env,
+ signum=self.signum)
result.append(ccp)
except:
log.debug(traceback.format_exc())
@@ -1049,8 +1073,10 @@ class container_collect(foreach_execute):
function: A datasource that returns a list of file contents created by
substituting each element of provider into the path template.
"""
- def __init__(self, provider, path=None, context=HostContext, deps=[], split=True, keep_rc=False, timeout=None, inherit_env=[], signum=None, **kwargs):
- super(container_collect, self).__init__(provider, path, context, deps, split, keep_rc, timeout, inherit_env, signum, **kwargs)
+ def __init__(self, provider, path=None, context=HostContext, deps=None, split=True, keep_rc=False, timeout=None,
+ inherit_env=None, override_env=None, signum=None, **kwargs):
+ super(container_collect, self).__init__(provider, path, context, deps, split, keep_rc, timeout, inherit_env,
+ override_env, signum, **kwargs)
def __call__(self, broker):
result = []
@@ -1073,9 +1099,10 @@ class container_collect(foreach_execute):
# e = (<podman|docker>, container_id)
# the_cmd = <podman|docker> exec container_id cat path
the_cmd = ("/usr/bin/%s exec %s cat " % e) + path
- cfp = ContainerFileProvider(the_cmd, ctx, image=image, args=None,
- split=self.split, keep_rc=self.keep_rc, ds=self,
- timeout=self.timeout, inherit_env=self.inherit_env, signum=self.signum)
+ cfp = ContainerFileProvider(the_cmd, ctx, image=image, args=None, split=self.split,
+ keep_rc=self.keep_rc, ds=self, timeout=self.timeout,
+ inherit_env=self.inherit_env, override_env=self.override_env,
+ signum=self.signum)
result.append(cfp)
except:
log.debug(traceback.format_exc())
diff --git a/insights/specs/default.py b/insights/specs/default.py
index c4629d00..7907d11d 100644
--- a/insights/specs/default.py
+++ b/insights/specs/default.py
@@ -673,7 +673,8 @@ class DefaultSpecs(Specs):
yum_conf = simple_file("/etc/yum.conf")
yum_list_available = simple_command("yum -C --noplugins list available", signum=signal.SIGTERM)
yum_log = simple_file("/var/log/yum.log")
- yum_repolist = simple_command("/usr/bin/yum -C --noplugins repolist", signum=signal.SIGTERM)
+ yum_repolist = simple_command("/usr/bin/yum -C --noplugins repolist", override_env={"LC_ALL": ""},
+ signum=signal.SIGTERM)
yum_repos_d = glob_file("/etc/yum.repos.d/*.repo")
yum_updates = yum_updates.yum_updates
zipl_conf = simple_file("/etc/zipl.conf")
| RedHatInsights/insights-core | 4f03a95b8d5d73367e8a7aa34820fda496517a67 | diff --git a/insights/tests/datasources/test_datasource_timeout.py b/insights/tests/datasources/test_datasource_timeout.py
index 55b503ff..485bbe75 100644
--- a/insights/tests/datasources/test_datasource_timeout.py
+++ b/insights/tests/datasources/test_datasource_timeout.py
@@ -1,6 +1,8 @@
import time
+from insights.core import dr
from insights.core.dr import run
+from insights.core.context import HostContext, SosArchiveContext
from insights.core.plugins import TimeoutException, datasource, make_info, rule
from insights.core.spec_factory import DatasourceProvider, RegistryPoint, SpecSet, foreach_execute
@@ -59,13 +61,17 @@ def timeout_foreach_datasource_hit(foreach_ds_to_1):
def test_timeout_datasource_no_hit():
- broker = run(timeout_datasource_no_timeout)
+ broker = dr.Broker()
+ broker[HostContext] = HostContext
+ broker = run(timeout_datasource_no_timeout, broker=broker)
assert timeout_datasource_no_timeout in broker
assert Specs.spec_ds_timeout_2 not in broker.exceptions
def test_timeout_datasource_hit_def():
- broker = run(timeout_datasource_hit)
+ broker = dr.Broker()
+ broker[HostContext] = HostContext
+ broker = run(timeout_datasource_hit, broker=broker)
assert timeout_datasource_hit in broker
assert Specs.spec_ds_timeout_1 in broker.exceptions
exs = broker.exceptions[Specs.spec_ds_timeout_1]
@@ -73,8 +79,30 @@ def test_timeout_datasource_hit_def():
def test_timeout_foreach_datasource_hit_def():
- broker = run(timeout_foreach_datasource_hit)
+ broker = dr.Broker()
+ broker[HostContext] = HostContext
+ broker = run(timeout_foreach_datasource_hit, broker=broker)
assert timeout_foreach_datasource_hit in broker
assert Specs.spec_foreach_ds_timeout_1 in broker.exceptions
exs = broker.exceptions[Specs.spec_foreach_ds_timeout_1]
assert [ex for ex in exs if isinstance(ex, TimeoutException) and str(ex) == "Datasource spec insights.tests.datasources.test_datasource_timeout.foreach_ds_timeout_1 timed out after 1 seconds!"]
+
+
+def test_not_hostcontext_timeout_datasource_hit_def():
+ broker = dr.Broker()
+ broker[SosArchiveContext] = SosArchiveContext
+ broker = run(timeout_datasource_hit, broker=broker)
+ assert timeout_datasource_hit in broker
+ assert Specs.spec_ds_timeout_1 not in broker.exceptions
+ exs = broker.exceptions[Specs.spec_ds_timeout_1]
+ assert not [ex for ex in exs if isinstance(ex, TimeoutException) and str(ex) != "Datasource spec insights.tests.datasources.test_datasource_timeout.TestSpecs.spec_ds_timeout_1 timed out after 1 seconds!"]
+
+
+def test_not_hostcontext_timeout_foreach_datasource_hit_def():
+ broker = dr.Broker()
+ broker[SosArchiveContext] = SosArchiveContext
+ broker = run(timeout_foreach_datasource_hit, broker=broker)
+ assert timeout_foreach_datasource_hit in broker
+ assert Specs.spec_foreach_ds_timeout_1 not in broker.exceptions
+ exs = broker.exceptions[Specs.spec_foreach_ds_timeout_1]
+ assert not [ex for ex in exs if isinstance(ex, TimeoutException) and str(ex) != "Datasource spec insights.tests.datasources.test_datasource_timeout.foreach_ds_timeout_1 timed out after 1 seconds!"]
| component run order inefficiency
insights-core sorts the loaded components for every archive it analyzes. This is inefficient if there are many components and the library is embedded in a system that analyzes many archives. There should be an option either for the framework itself to sort the components once and know it doesn't have to do it again, or clients should be able to handle component sorting themselves so they can cache the result. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"insights/tests/datasources/test_datasource_timeout.py::test_not_hostcontext_timeout_datasource_hit_def",
"insights/tests/datasources/test_datasource_timeout.py::test_not_hostcontext_timeout_foreach_datasource_hit_def"
] | [
"insights/tests/datasources/test_datasource_timeout.py::test_timeout_datasource_no_hit",
"insights/tests/datasources/test_datasource_timeout.py::test_timeout_datasource_hit_def",
"insights/tests/datasources/test_datasource_timeout.py::test_timeout_foreach_datasource_hit_def"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2023-01-10T02:49:32Z" | apache-2.0 |
|
RedHatInsights__insights-core-3949 | diff --git a/insights/core/filters.py b/insights/core/filters.py
index 7f3cf06d..b23267f9 100644
--- a/insights/core/filters.py
+++ b/insights/core/filters.py
@@ -66,9 +66,9 @@ def add_filter(component, patterns):
patterns (str, [str]): A string, list of strings, or set of strings to
add to the datasource's filters.
"""
- def inner(component, patterns):
- if component in _CACHE:
- del _CACHE[component]
+ def inner(comp, patterns):
+ if comp in _CACHE:
+ del _CACHE[comp]
types = six.string_types + (list, set)
if not isinstance(patterns, types):
@@ -81,18 +81,25 @@ def add_filter(component, patterns):
for pat in patterns:
if not pat:
- raise Exception("Filter patterns must not be empy.")
+ raise Exception("Filter patterns must not be empty.")
- FILTERS[component] |= patterns
+ FILTERS[comp] |= patterns
+
+ def get_dependency_datasources(comp):
+ """"Get (all) the first depended datasource"""
+ dep_ds = set()
+ if plugins.is_datasource(comp):
+ dep_ds.add(comp)
+ return dep_ds
+ for dep in dr.get_dependencies(comp):
+ dep_ds.update(get_dependency_datasources(dep))
+ return dep_ds
if not plugins.is_datasource(component):
- deps = dr.run_order(dr.get_dependency_graph(component))
+ deps = get_dependency_datasources(component)
if deps:
- filterable_deps = [
- dep for dep in deps if (plugins.is_datasource(dep) and
- dr.get_delegate(dep).filterable)
- ]
- # At least one dependency component be filterable
+ filterable_deps = [dep for dep in deps if dr.get_delegate(dep).filterable]
+ # At least one dependency datasource be filterable
if not filterable_deps:
raise Exception("Filters aren't applicable to %s." % dr.get_name(component))
diff --git a/insights/parsers/uname.py b/insights/parsers/uname.py
index fd06f560..72c89402 100644
--- a/insights/parsers/uname.py
+++ b/insights/parsers/uname.py
@@ -119,6 +119,7 @@ rhel_release_map = {
"5.14.0-70": "9.0",
"5.14.0-162": "9.1",
"5.14.0-284": "9.2",
+ "5.14.0-362": "9.3",
}
release_to_kernel_map = dict((v, k) for k, v in rhel_release_map.items())
| RedHatInsights/insights-core | 1d2c1c6ea9500230c0aaacc767297b89141bb41b | diff --git a/insights/tests/test_filters.py b/insights/tests/core/test_filters.py
similarity index 57%
rename from insights/tests/test_filters.py
rename to insights/tests/core/test_filters.py
index a1571b44..536ecd65 100644
--- a/insights/tests/test_filters.py
+++ b/insights/tests/core/test_filters.py
@@ -3,10 +3,10 @@ import sys
from collections import defaultdict
-from insights import datasource
+from insights import parser
from insights.combiners.hostname import Hostname
from insights.core import filters
-from insights.core.spec_factory import DatasourceProvider, RegistryPoint, SpecSet
+from insights.core.spec_factory import RegistryPoint, SpecSet, simple_file
from insights.parsers.ps import PsAux, PsAuxcww
from insights.specs import Specs
from insights.specs.default import DefaultSpecs
@@ -18,10 +18,27 @@ class MySpecs(SpecSet):
class LocalSpecs(MySpecs):
- # The has_filters depends on no_filters
- @datasource(MySpecs.no_filters)
- def has_filters(broker):
- return DatasourceProvider("", "the_data")
+ no_filters = simple_file('no_filters')
+ has_filters = simple_file('has_filters')
+
+
+@parser(MySpecs.has_filters)
+class MySpecsHasFilters(object):
+ pass
+
+
+@parser(LocalSpecs.has_filters)
+class LocalSpecsHasFilters(object):
+ pass
+
+
+@parser(MySpecs.no_filters)
+class LocalSpecsNoFilters(object):
+ pass
+
+#
+# TEST
+#
def setup_function(func):
@@ -37,6 +54,7 @@ def setup_function(func):
def teardown_function(func):
+ filters._CACHE = {}
if func is test_get_filter:
del filters.FILTERS[Specs.ps_aux]
@@ -47,8 +65,16 @@ def teardown_function(func):
if func is test_filter_dumps_loads:
del filters.FILTERS[Specs.ps_aux]
- if func is test_add_filter_to_parser:
+ if func in [
+ test_add_filter_to_MySpecsHasFilters,
+ test_add_filter_to_LocalSpecsHasFilters,
+ ]:
+ del filters.FILTERS[MySpecs.has_filters]
+ del filters.FILTERS[LocalSpecs.has_filters]
+
+ if func is test_add_filter_to_PsAux:
del filters.FILTERS[Specs.ps_aux]
+ del filters.FILTERS[DefaultSpecs.ps_aux]
if func is test_add_filter_to_parser_patterns_list:
del filters.FILTERS[Specs.ps_aux]
@@ -87,12 +113,58 @@ def test_get_filter_registry_point():
assert "MEM" not in f
-def test_add_filter_to_parser():
+# Local Parser
+def test_add_filter_to_MySpecsHasFilters():
+ """
+ "filters" added to MySpecs.x will also add to LocalSpecs.x
+ """
+ filter_string = "bash"
+
+ # Local Parser depends on MySpecs (Specs)
+ filters.add_filter(MySpecsHasFilters, filter_string)
+
+ myspecs_filters = filters.get_filters(MySpecs.has_filters)
+ assert filter_string in myspecs_filters
+ assert filter_string in filters.FILTERS[MySpecs.has_filters]
+
+ localspecs_filters = filters.get_filters(LocalSpecs.has_filters)
+ assert filter_string in localspecs_filters
+ # but there is no key in FILTERS for the LocalSpecs.x
+ assert filter_string not in filters.FILTERS[LocalSpecs.has_filters]
+
+
+def test_add_filter_to_LocalSpecsHasFilters():
+ """
+ "filters" added to LocalSpecs.x will NOT add to Specs.x
+ """
+ filter_string = "bash"
+ filters.add_filter(LocalSpecsHasFilters, filter_string)
+
+ myspecs_filters = filters.get_filters(MySpecs.has_filters)
+ assert filter_string not in myspecs_filters
+ assert filter_string not in filters.FILTERS[MySpecs.has_filters]
+
+ localspecs_filters = filters.get_filters(LocalSpecs.has_filters)
+ assert filter_string in localspecs_filters
+ assert filter_string in filters.FILTERS[LocalSpecs.has_filters]
+
+
+# General Parser
+def test_add_filter_to_PsAux():
+ """
+ "filters" added to Specs.x will add to DefaultSpecs.x
+ """
filter_string = "bash"
filters.add_filter(PsAux, filter_string)
spec_filters = filters.get_filters(Specs.ps_aux)
assert filter_string in spec_filters
+ assert filter_string in filters.FILTERS[Specs.ps_aux]
+
+ default_spec_filters = filters.get_filters(DefaultSpecs.ps_aux)
+ assert filter_string in default_spec_filters # get_filters() works
+ # but there is no key in FILTERS for the LocalSpecs.x
+ assert filter_string not in filters.FILTERS[DefaultSpecs.ps_aux] # empty in FILTERS
parser_filters = filters.get_filters(PsAux)
assert not parser_filters
@@ -109,7 +181,7 @@ def test_add_filter_to_parser_patterns_list():
assert not parser_filters
-def test_add_filter_exception_not_filterable():
+def test_add_filter_exception_spec_not_filterable():
with pytest.raises(Exception):
filters.add_filter(Specs.ps_auxcww, "bash")
@@ -118,6 +190,9 @@ def test_add_filter_exception_parser_non_filterable():
with pytest.raises(Exception):
filters.add_filter(PsAuxcww, 'bash')
+ with pytest.raises(Exception):
+ filters.add_filter(LocalSpecsNoFilters, 'bash')
+
def test_add_filter_exception_combiner_non_filterable():
with pytest.raises(Exception):
| Duplicate "filters" to Specs.spec_name and DefaultSpecs.spec_name in "filters.yaml"
```
insights.specs.Specs.watchdog_logs:
- Connection timed out
insights.specs.Specs.yum_log:
- 'Erased:'
- 'Installed:'
- 'Updated:'
...
insights.specs.default.DefaultSpecs.watchdog_logs:
- Connection timed out
insights.specs.default.DefaultSpecs.yum_log:
- 'Erased:'
```
The "filters" to the DefaultSpecs.xxx are duplicated and useless. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"insights/tests/core/test_filters.py::test_add_filter_to_MySpecsHasFilters",
"insights/tests/core/test_filters.py::test_add_filter_to_PsAux"
] | [
"insights/tests/core/test_filters.py::test_filter_dumps_loads",
"insights/tests/core/test_filters.py::test_get_filter",
"insights/tests/core/test_filters.py::test_get_filter_registry_point",
"insights/tests/core/test_filters.py::test_add_filter_to_LocalSpecsHasFilters",
"insights/tests/core/test_filters.py::test_add_filter_to_parser_patterns_list",
"insights/tests/core/test_filters.py::test_add_filter_exception_spec_not_filterable",
"insights/tests/core/test_filters.py::test_add_filter_exception_parser_non_filterable",
"insights/tests/core/test_filters.py::test_add_filter_exception_combiner_non_filterable",
"insights/tests/core/test_filters.py::test_add_filter_exception_raw",
"insights/tests/core/test_filters.py::test_add_filter_exception_empty",
"insights/tests/core/test_filters.py::test_get_filters"
] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2023-11-08T03:23:38Z" | apache-2.0 |
|
RedHatInsights__insights-core-3984 | diff --git a/docs/shared_parsers_catalog/bootc.rst b/docs/shared_parsers_catalog/bootc.rst
new file mode 100644
index 00000000..4142e636
--- /dev/null
+++ b/docs/shared_parsers_catalog/bootc.rst
@@ -0,0 +1,3 @@
+.. automodule:: insights.parsers.bootc
+ :members:
+ :show-inheritance:
diff --git a/insights/parsers/bootc.py b/insights/parsers/bootc.py
new file mode 100644
index 00000000..d5caf337
--- /dev/null
+++ b/insights/parsers/bootc.py
@@ -0,0 +1,55 @@
+"""
+Bootc - Command ``bootc``
+=========================
+"""
+from insights.core import JSONParser
+from insights.core.plugins import parser
+from insights.specs import Specs
+
+
+@parser(Specs.bootc_status)
+class BootcStatus(JSONParser):
+ """
+ Parses the output of command ``bootc status --json``
+
+ Typical output of the command::
+
+ {
+ "apiVersion":"org.containers.bootc/v1alpha1",
+ "kind":"BootcHost",
+ "metadata":{
+ "name":"host"
+ },
+ "spec":{
+ "image":{
+ "image":"192.168.124.1:5000/bootc-insights:latest",
+ "transport":"registry"
+ }
+ },
+ "status":{
+ "staged":null,
+ "booted":{
+ "image":{
+ "image":{
+ "image":"192.168.124.1:5000/bootc-insights:latest",
+ "transport":"registry"
+ },
+ "version":"stream9.20231213.0",
+ "timestamp":null,
+ },
+ "incompatible":false,
+ "pinned":false,
+ "ostree":{
+ "deploySerial":0
+ }
+ },
+ }
+ }
+
+ Examples:
+ >>> type(bootc_status)
+ <class 'insights.parsers.bootc.BootcStatus'>
+ >>> bootc_status['status']['booted']['image']['version'] == 'stream9.20231213.0'
+ True
+ """
+ pass
diff --git a/insights/parsers/mount.py b/insights/parsers/mount.py
index 74bb1afb..d7cfd4b1 100644
--- a/insights/parsers/mount.py
+++ b/insights/parsers/mount.py
@@ -43,7 +43,7 @@ import os
from insights.core import CommandParser
from insights.core.exceptions import ParseException, SkipComponent
from insights.core.plugins import parser
-from insights.parsers import get_active_lines, keyword_search, optlist_to_dict
+from insights.parsers import get_active_lines, keyword_search
from insights.specs import Specs
@@ -267,7 +267,7 @@ class Mount(MountedFileSystems):
mount['mount_point'] = line_sp[0]
mount['mount_type'] = line_sp[1].split()[0]
line_sp = _customized_split(raw=line, l=mnt_pt_sp[1], sep=None, check=False)
- mount['mount_options'] = MountOpts(optlist_to_dict(line_sp[0].strip('()')))
+ mount['mount_options'] = MountOpts(_parse_mount_options(line_sp[0].strip('()')))
if len(line_sp) == 2:
mount['mount_label'] = line_sp[1]
@@ -333,7 +333,7 @@ class ProcMounts(MountedFileSystems):
line_sp = _customized_split(raw=line, l=line_sp[1], num=3, reverse=True)
mount['mount_label'] = line_sp[-2:]
line_sp = _customized_split(raw=line, l=line_sp[0], reverse=True)
- mount['mount_options'] = MountOpts(optlist_to_dict(line_sp[1]))
+ mount['mount_options'] = MountOpts(_parse_mount_options(line_sp[1]))
line_sp = _customized_split(raw=line, l=line_sp[0], reverse=True)
mount['mount_type'] = mount['filesystem_type'] = line_sp[1]
mount['mount_point'] = line_sp[0]
@@ -400,7 +400,7 @@ class MountInfo(MountedFileSystems):
optional_fields = line_left_sp[5].split()[1] if ' ' in line_left_sp[5] else ''
mntopt = line_left_sp[5].split()[0] if ' ' in line_left_sp[5] else line_left_sp[5]
unioned_options = ','.join([mntopt, line_right_sp[2]])
- mount['mount_options'] = MountOpts(optlist_to_dict(unioned_options))
+ mount['mount_options'] = MountOpts(_parse_mount_options(unioned_options))
mount['mount_addtlinfo'] = MountAddtlInfo({
'mount_id': line_left_sp[0],
'parent_id': line_left_sp[1],
@@ -414,6 +414,43 @@ class MountInfo(MountedFileSystems):
self.mounts = dict([mnt['mount_point'], rows[idx]] for idx, mnt in enumerate(rows))
+def _parse_mount_options(mount_options):
+ """
+ Parse mount options including quoted values with embedded commas.
+
+ Args:
+ mount_options (str): String of comma separated mount options and values
+
+ Returns:
+ dict: Dictionary of mount options
+
+ """
+ opts = dict()
+ sp_opts = mount_options.split(',')
+ start_ndx = 0
+ for i, opt in enumerate(sp_opts):
+ # Look for option="... start of quoted value
+ if '="' in opt:
+ start_ndx = i
+
+ # Look for closing quote of option="..." and if found recombine value
+ elif '"' in opt:
+ last_ndx = i
+ comb_opt = ','.join(sp_opts[start_ndx:last_ndx + 1])
+ opt_name, opt_value = comb_opt.split('=', 1)
+ # Remove leading and trailing quotes
+ opts[opt_name] = opt_value[1:-1]
+
+ # Else just a normal option or option=value
+ else:
+ if '=' in opt:
+ opt_name, opt_value = opt.split('=', 1)
+ opts[opt_name] = opt_value
+ else:
+ opts[opt] = True
+ return opts
+
+
def _customized_split(raw, l, sep=None, num=2, reverse=False, check=True):
if num >= 2:
if reverse is False:
diff --git a/insights/specs/__init__.py b/insights/specs/__init__.py
index f946402c..c5eb6942 100644
--- a/insights/specs/__init__.py
+++ b/insights/specs/__init__.py
@@ -47,6 +47,7 @@ class Specs(SpecSet):
bond = RegistryPoint(multi_output=True)
bond_dynamic_lb = RegistryPoint(multi_output=True)
boot_loader_entries = RegistryPoint(multi_output=True)
+ bootc_status = RegistryPoint()
brctl_show = RegistryPoint()
buddyinfo = RegistryPoint()
candlepin_broker = RegistryPoint()
diff --git a/insights/specs/datasources/kernel_module_list.py b/insights/specs/datasources/kernel_module_list.py
index 122aa09c..7183e25a 100644
--- a/insights/specs/datasources/kernel_module_list.py
+++ b/insights/specs/datasources/kernel_module_list.py
@@ -23,6 +23,6 @@ def kernel_module_filters(broker):
if module_list:
loaded_modules.extend(module_list)
if loaded_modules:
- return ' '.join(loaded_modules)
+ return str(' '.join(loaded_modules))
raise SkipComponent
raise SkipComponent
diff --git a/insights/specs/default.py b/insights/specs/default.py
index bd05d485..84106aca 100644
--- a/insights/specs/default.py
+++ b/insights/specs/default.py
@@ -124,6 +124,7 @@ class DefaultSpecs(Specs):
bond = glob_file("/proc/net/bonding/*")
bond_dynamic_lb = glob_file("/sys/class/net/*/bonding/tlb_dynamic_lb")
boot_loader_entries = glob_file("/boot/loader/entries/*.conf")
+ bootc_status = simple_command("/usr/bin/bootc status --json")
buddyinfo = simple_file("/proc/buddyinfo")
brctl_show = simple_command("/usr/sbin/brctl show")
cciss = glob_file("/proc/driver/cciss/cciss*")
| RedHatInsights/insights-core | 3d3eefea0b90ad00478241c886af3a3c61ffad09 | diff --git a/insights/tests/parsers/test_bootc.py b/insights/tests/parsers/test_bootc.py
new file mode 100644
index 00000000..b2554d7d
--- /dev/null
+++ b/insights/tests/parsers/test_bootc.py
@@ -0,0 +1,81 @@
+import doctest
+import pytest
+
+from insights.core.exceptions import SkipComponent
+from insights.parsers import bootc
+from insights.parsers.bootc import BootcStatus
+from insights.tests import context_wrap
+
+BOOTC_STATUS = '''
+{
+ "apiVersion":"org.containers.bootc/v1alpha1",
+ "kind":"BootcHost",
+ "metadata":{
+ "name":"host"
+ },
+ "spec":{
+ "image":{
+ "image":"192.168.124.1:5000/bootc-insights:latest",
+ "transport":"registry"
+ }
+ },
+ "status":{
+ "staged":null,
+ "booted":{
+ "image":{
+ "image":{
+ "image":"192.168.124.1:5000/bootc-insights:latest",
+ "transport":"registry"
+ },
+ "version":"stream9.20231213.0",
+ "timestamp":null,
+ "imageDigest":"sha256:806d77394f96e47cf99b1233561ce970c94521244a2d8f2affa12c3261961223"
+ },
+ "incompatible":false,
+ "pinned":false,
+ "ostree":{
+ "checksum":"6aa32a312c832e32a2dbfe006f05e5972d9f2b86df54e747128c24e6c1fb129a",
+ "deploySerial":0
+ }
+ },
+ "rollback":{
+ "image":{
+ "image":{
+ "image":"quay.io/centos-boot/fedora-boot-cloud:eln",
+ "transport":"registry"
+ },
+ "version":"39.20231109.3",
+ "timestamp":null,
+ "imageDigest":"sha256:92e476435ced1c148350c660b09c744717defbd300a15d33deda5b50ad6b21a0"
+ },
+ "incompatible":false,
+ "pinned":false,
+ "ostree":{
+ "checksum":"56612a5982b7f12530988c970d750f89b0489f1f9bebf9c2a54244757e184dd8",
+ "deploySerial":0
+ }
+ },
+ "type":"bootcHost"
+ }
+}
+'''.strip()
+
+
+def test_bootc_doc_examples():
+ env = {
+ "bootc_status": BootcStatus(context_wrap(BOOTC_STATUS)),
+ }
+ failed, total = doctest.testmod(bootc, globs=env)
+ assert failed == 0
+
+
+def test_bootc_status_skip():
+ with pytest.raises(SkipComponent) as ex:
+ BootcStatus(context_wrap(""))
+ assert "Empty output." in str(ex)
+
+
+def test_bootc_status():
+ bs = BootcStatus(context_wrap(BOOTC_STATUS))
+ assert bs['apiVersion'] == 'org.containers.bootc/v1alpha1'
+ assert bs['status']['booted']['image']['version'] == 'stream9.20231213.0'
diff --git a/insights/tests/parsers/test_mount.py b/insights/tests/parsers/test_mount.py
index b11290a3..63280ed7 100644
--- a/insights/tests/parsers/test_mount.py
+++ b/insights/tests/parsers/test_mount.py
@@ -58,6 +58,11 @@ sunrpc /var/lib/nfs/rpc_pipefs rpc_pipefs rw,relatime 0 0
/etc/auto.misc /misc autofs rw,relatime,fd=7,pgrp=1936,timeout=300,minproto=5,maxproto=5,indirect 0 0
""".strip()
+PROC_MOUNT_QUOTES = """
+/dev/mapper/rootvg-rootlv / ext4 rw,relatime,barrier=1,data=ordered 0 0
+tmpfs /var/lib/containers/storage/overlay-containers/ff7e79fc09c/userdata/shm tmpfs rw,nosuid,nodev,noexec,relatime,context="system_u:object_r:container_file_t:s0:c184,c371",size=64000k 0 0
+"""
+
PROCMOUNT_ERR_DATA = """
rootfs / rootfs rw 0 0
sysfs /sys sysfs rw,relatime
@@ -266,6 +271,14 @@ def test_proc_mount():
]
+def test_proc_mount_quotes():
+ results = ProcMounts(context_wrap(PROC_MOUNT_QUOTES))
+ assert results is not None
+ assert len(results) == 2
+ device = results['/var/lib/containers/storage/overlay-containers/ff7e79fc09c/userdata/shm']
+ assert device.mount_options.context == "system_u:object_r:container_file_t:s0:c184,c371"
+
+
def test_proc_mount_exception1():
with pytest.raises(SkipComponent) as e:
ProcMounts(context_wrap(PROC_EXCEPTION1))
| Mount options can contain quoted values with embedded commas
If a mount option is quoted and contains embedded commas it will not be parsed correctly. For example context will be split in the current [ProcMounts](https://github.com/RedHatInsights/insights-core/blob/master/insights/parsers/mount.py#L280) parser:
```
tmpfs /var/lib/containers/storage/overlay-containers/ff7e79fc09c/userdata/shm tmpfs rw,nosuid,nodev,noexec,relatime,context="system_u:object_r:container_file_t:s0:c184,c371",size=64000k 0 0
```
The split options will be `[..., 'context="system_u:object_r:container_file_t:s0:c184', 'c371"',...]`.
This is actually caused by the shared function [optlist_to_dict](https://github.com/RedHatInsights/insights-core/blob/master/insights/parsers/__init__.py#L39) which doesn't handle quoted values. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"insights/tests/parsers/test_bootc.py::test_bootc_doc_examples",
"insights/tests/parsers/test_bootc.py::test_bootc_status_skip",
"insights/tests/parsers/test_bootc.py::test_bootc_status",
"insights/tests/parsers/test_mount.py::test_mount",
"insights/tests/parsers/test_mount.py::test_mount_with_special_mnt_point",
"insights/tests/parsers/test_mount.py::test_mount_exception1",
"insights/tests/parsers/test_mount.py::test_mount_exception2",
"insights/tests/parsers/test_mount.py::test_proc_mount",
"insights/tests/parsers/test_mount.py::test_proc_mount_quotes",
"insights/tests/parsers/test_mount.py::test_proc_mount_exception1",
"insights/tests/parsers/test_mount.py::test_proc_mount_exception2",
"insights/tests/parsers/test_mount.py::test_proc_mount_exception3",
"insights/tests/parsers/test_mount.py::test_mountinfo",
"insights/tests/parsers/test_mount.py::test_doc_examples"
] | [] | {
"failed_lite_validators": [
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2024-01-03T23:26:44Z" | apache-2.0 |
|
RemDelaporteMathurin__h-transport-materials-106 | diff --git a/h_transport_materials/property.py b/h_transport_materials/property.py
index d33a6f3..0f16ab4 100644
--- a/h_transport_materials/property.py
+++ b/h_transport_materials/property.py
@@ -236,6 +236,11 @@ class ArrheniusProperty(Property):
if value is None:
self._data_T = value
return
+ if isinstance(value, pint.Quantity):
+ # convert to K
+ value = value.to(ureg.K).magnitude
+ else:
+ warnings.warn(f"no units were given with data_T, assuming {self.units:~}")
if not isinstance(value, (list, np.ndarray)):
raise TypeError("data_T accepts list or np.ndarray")
elif isinstance(value, list):
@@ -255,6 +260,11 @@ class ArrheniusProperty(Property):
if value is None:
self._data_y = value
return
+ if isinstance(value, pint.Quantity):
+ # convert to right units
+ value = value.to(self.units).magnitude
+ else:
+ warnings.warn(f"no units were given with data_y, assuming {self.units:~}")
if not isinstance(value, (list, np.ndarray)):
raise TypeError("data_y accepts list or np.ndarray")
elif isinstance(value, list):
@@ -266,7 +276,11 @@ class ArrheniusProperty(Property):
self._data_y = value[~np.isnan(value)]
def fit(self):
- self.pre_exp, self.act_energy = fit_arhenius(self.data_y, self.data_T)
+ pre_exp, act_energy = fit_arhenius(self.data_y, self.data_T)
+ self.pre_exp, self.act_energy = (
+ pre_exp * self.units,
+ act_energy * DEFAULT_ENERGY_UNITS,
+ )
self.range = (self.data_T.min(), self.data_T.max())
def value(self, T, exp=np.exp):
| RemDelaporteMathurin/h-transport-materials | b4870b7fc221e6912dcfcb4a0019858628ea2479 | diff --git a/tests/test_diffusivity.py b/tests/test_diffusivity.py
index abd97a8..00658d9 100644
--- a/tests/test_diffusivity.py
+++ b/tests/test_diffusivity.py
@@ -16,3 +16,39 @@ def test_act_energy_can_be_quantity():
E_D=0.5 * htm.ureg.kJ * htm.ureg.mol**-1,
)
assert prop.act_energy != 0.5
+
+
+def test_fit_with_units_data_y():
+ """Checks that units are taken into account in data_y"""
+ data_T = [1, 2, 3] * htm.ureg.K
+ data_y_ref = [1, 2, 3] * htm.ureg.m**2 * htm.ureg.s**-1
+ my_prop_ref = htm.Diffusivity(
+ data_T=data_T,
+ data_y=data_y_ref,
+ )
+
+ my_prop_other_units = htm.Diffusivity(
+ data_T=data_T,
+ data_y=data_y_ref.to(htm.ureg.cm**2 * htm.ureg.s**-1),
+ )
+
+ assert my_prop_other_units.pre_exp == my_prop_ref.pre_exp
+ assert my_prop_other_units.act_energy == my_prop_ref.act_energy
+
+
+def test_fit_with_units_data_T():
+ """Checks that units are taken into account in data_T"""
+ data_T_ref = [1, 2, 3] * htm.ureg.K
+ data_y = [1, 2, 3] * htm.ureg.m**2 * htm.ureg.s**-1
+ my_prop_ref = htm.Diffusivity(
+ data_T=data_T_ref,
+ data_y=data_y,
+ )
+
+ my_prop_other_units = htm.Diffusivity(
+ data_T=data_T_ref.to("degC"),
+ data_y=data_y,
+ )
+
+ assert my_prop_other_units.pre_exp == my_prop_ref.pre_exp
+ assert my_prop_other_units.act_energy == my_prop_ref.act_energy
| Pint for temperature range and data_T data_y | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_diffusivity.py::test_fit_with_units_data_y",
"tests/test_diffusivity.py::test_fit_with_units_data_T"
] | [
"tests/test_diffusivity.py::test_pre_exp_can_be_quantity",
"tests/test_diffusivity.py::test_act_energy_can_be_quantity"
] | {
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false
} | "2022-10-22T15:35:23Z" | mit |
|
RemDelaporteMathurin__h-transport-materials-118 | diff --git a/h_transport_materials/plotting.py b/h_transport_materials/plotting.py
index 3c904ac..35cb638 100644
--- a/h_transport_materials/plotting.py
+++ b/h_transport_materials/plotting.py
@@ -1,7 +1,8 @@
import matplotlib.pyplot as plt
import numpy as np
from numpy.typing import ArrayLike
-from h_transport_materials import Property, PropertiesGroup
+import pint
+from h_transport_materials import Property, PropertiesGroup, ureg
import math
import matplotlib as mpl
from typing import Union
@@ -37,6 +38,8 @@ def plot(
else:
range = prop.range
T = np.linspace(*range, num=50)
+ if not isinstance(T, pint.Quantity):
+ T *= ureg.K
if inverse_temperature:
plt.xlabel("1/T (K$^{-1}$)")
x = (1 / T)[::-1]
diff --git a/h_transport_materials/properties_group.py b/h_transport_materials/properties_group.py
index ac2fc03..09ed69f 100644
--- a/h_transport_materials/properties_group.py
+++ b/h_transport_materials/properties_group.py
@@ -1,8 +1,10 @@
import numpy as np
import json
from pybtex.database import BibliographyData
+import pint
from h_transport_materials.fitting import fit_arhenius
+from h_transport_materials import ureg
class PropertiesGroup(list):
@@ -96,6 +98,8 @@ class PropertiesGroup(list):
if prop.range == None:
T_range = default_range
prop_T = np.linspace(T_range[0], T_range[1], num=samples_per_line)
+ if not isinstance(prop_T, pint.Quantity):
+ prop_T = ureg.Quantity(prop_T, ureg.K)
prop_y = prop.value(prop_T)
data_T = np.concatenate((data_T, prop_T))
@@ -103,7 +107,6 @@ class PropertiesGroup(list):
# fit all the data
pre_exp, act_energy = fit_arhenius(data_y, data_T)
-
return pre_exp, act_energy
def export_bib(self, filename: str):
diff --git a/h_transport_materials/property.py b/h_transport_materials/property.py
index 870dcd7..4f7a54f 100644
--- a/h_transport_materials/property.py
+++ b/h_transport_materials/property.py
@@ -297,7 +297,15 @@ class ArrheniusProperty(Property):
self.range = (self.data_T.min(), self.data_T.max())
def value(self, T, exp=np.exp):
- return self.pre_exp * exp(-self.act_energy / k_B / T)
+ if not isinstance(T, pint.Quantity):
+ warnings.warn(f"no units were given with T, assuming {ureg.K}")
+ T = T * ureg.K
+ if not isinstance(self.pre_exp, pint.Quantity):
+ pre_exp = self.pre_exp * self.units
+ if not isinstance(self.act_energy, pint.Quantity):
+ act_energy = self.act_energy * DEFAULT_ENERGY_UNITS
+ k_B_u = k_B * ureg.eV * ureg.particle**-1 * ureg.K**-1
+ return pre_exp * exp(-act_energy / k_B_u / T)
class Solubility(ArrheniusProperty):
| RemDelaporteMathurin/h-transport-materials | 387c90817433e6f4fa5829f3bba0efa5b59f3169 | diff --git a/tests/test_arhenius_property.py b/tests/test_arhenius_property.py
index 75e3256..1264756 100644
--- a/tests/test_arhenius_property.py
+++ b/tests/test_arhenius_property.py
@@ -2,6 +2,7 @@ import pytest
import numpy as np
import h_transport_materials as htm
+import pint
@pytest.mark.parametrize(
@@ -100,3 +101,14 @@ def test_data_y_removes_nan(data):
data_y=data * htm.ureg.dimensionless,
)
assert np.count_nonzero(np.isnan(my_prop.data_y)) == 0
+
+
+def test_value_returns_pint_quantity():
+ my_prop = htm.ArrheniusProperty(
+ pre_exp=1 * htm.ureg.m**2 * htm.ureg.s**-1,
+ act_energy=0.1 * htm.ureg.eV * htm.ureg.particle**-1,
+ )
+
+ T = htm.ureg.Quantity(400, htm.ureg.K)
+
+ assert isinstance(my_prop.value(T), pint.Quantity)
| .value() method should work with units
Users should be able to do:
```python
import h_transport_materials as htm
ureg = htm.ureg
T = ureg.Quantity(900, ureg.K)
D = htm.Diffusivity(1 * ureg.m**2 * ureg.s**-1, 0.1 * ureg.eV)
value = D.value(T)
value.to(ureg.mm**2 * ureg.s**-1)
```
- .value() should return a pint.Quantity object
- .value() should accept a pint.Quantity object for argument | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_arhenius_property.py::test_value_returns_pint_quantity"
] | [
"tests/test_arhenius_property.py::test_fit[data_T0-data_y0]",
"tests/test_arhenius_property.py::test_fit[data_T1-data_y1]",
"tests/test_arhenius_property.py::test_fit[data_T2-data_y2]",
"tests/test_arhenius_property.py::test_fit[data_T3-data_y3]",
"tests/test_arhenius_property.py::test_fit[data_T4-data_y4]",
"tests/test_arhenius_property.py::test_fit[data_T5-data_y5]",
"tests/test_arhenius_property.py::test_fit[data_T6-data_y6]",
"tests/test_arhenius_property.py::test_fit[data_T7-data_y7]",
"tests/test_arhenius_property.py::test_fit[data_T8-data_y8]",
"tests/test_arhenius_property.py::test_fit[data_T9-data_y9]",
"tests/test_arhenius_property.py::test_fit[data_T10-data_y10]",
"tests/test_arhenius_property.py::test_fit[data_T11-data_y11]",
"tests/test_arhenius_property.py::test_fit[data_T12-data_y12]",
"tests/test_arhenius_property.py::test_fit[data_T13-data_y13]",
"tests/test_arhenius_property.py::test_fit[data_T14-data_y14]",
"tests/test_arhenius_property.py::test_fit[data_T15-data_y15]",
"tests/test_arhenius_property.py::test_pre_exp_getter_fit",
"tests/test_arhenius_property.py::test_act_energy_getter_fit",
"tests/test_arhenius_property.py::test_value[300-3-0.2]",
"tests/test_arhenius_property.py::test_value[205-6-0.8]",
"tests/test_arhenius_property.py::test_value[600-100000.0-1.2]",
"tests/test_arhenius_property.py::test_fit_creates_temp_range",
"tests/test_arhenius_property.py::test_data_T_removes_nan[data0]",
"tests/test_arhenius_property.py::test_data_T_removes_nan[data1]",
"tests/test_arhenius_property.py::test_data_y_removes_nan[data0]",
"tests/test_arhenius_property.py::test_data_y_removes_nan[data1]"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2023-01-06T21:56:07Z" | mit |
|
RemDelaporteMathurin__h-transport-materials-121 | diff --git a/h_transport_materials/properties_group.py b/h_transport_materials/properties_group.py
index 2de20fb..9ecec3d 100644
--- a/h_transport_materials/properties_group.py
+++ b/h_transport_materials/properties_group.py
@@ -2,6 +2,7 @@ import numpy as np
import json
from pybtex.database import BibliographyData
import pint
+import warnings
from h_transport_materials.fitting import fit_arhenius
from h_transport_materials import ureg, ArrheniusProperty
@@ -66,7 +67,8 @@ class PropertiesGroup(list):
# append the property to the filtered list
if (match and not exclude) or (not match and exclude):
filtered_props.append(prop)
-
+ if len(filtered_props) == 0:
+ warnings.warn("No property matching the requirements")
return filtered_props
def mean(self, samples_per_line=5, default_range=(300, 1200)):
| RemDelaporteMathurin/h-transport-materials | fdb8f77447762bb38161f86352c0e7d0684ba803 | diff --git a/tests/test_properties_group.py b/tests/test_properties_group.py
index 1d22ba2..f3092bc 100644
--- a/tests/test_properties_group.py
+++ b/tests/test_properties_group.py
@@ -160,3 +160,8 @@ def test_export_to_json():
assert f"{getattr(prop_ref, key):~}" == val
else:
assert getattr(prop_ref, key) == val
+
+
+def test_filter_warns_when_no_props():
+ with pytest.warns(UserWarning):
+ htm.diffusivities.filter(material="material_that_doesn_not_exist")
| Users should be told when filtered group is None | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_properties_group.py::test_filter_warns_when_no_props"
] | [
"tests/test_properties_group.py::test_iterable",
"tests/test_properties_group.py::test_adding_two_groups",
"tests/test_properties_group.py::test_filter_author_lower_case",
"tests/test_properties_group.py::test_filter_isotope_lower_case",
"tests/test_properties_group.py::test_mean[2.0-0.1]",
"tests/test_properties_group.py::test_mean[2.0-1.55]",
"tests/test_properties_group.py::test_mean[2.0-3.0]",
"tests/test_properties_group.py::test_mean[31.0-0.1]",
"tests/test_properties_group.py::test_mean[31.0-1.55]",
"tests/test_properties_group.py::test_mean[31.0-3.0]",
"tests/test_properties_group.py::test_mean[60.0-0.1]",
"tests/test_properties_group.py::test_mean[60.0-1.55]",
"tests/test_properties_group.py::test_mean[60.0-3.0]",
"tests/test_properties_group.py::test_mean_is_type_arrhenius_property",
"tests/test_properties_group.py::test_bibdata",
"tests/test_properties_group.py::test_export_bib",
"tests/test_properties_group.py::test_export_to_json"
] | {
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false
} | "2023-01-09T14:13:50Z" | mit |
|
RemDelaporteMathurin__h-transport-materials-169 | diff --git a/h_transport_materials/properties_group.py b/h_transport_materials/properties_group.py
index ccc4b5f..1099a1b 100644
--- a/h_transport_materials/properties_group.py
+++ b/h_transport_materials/properties_group.py
@@ -92,9 +92,15 @@ class PropertiesGroup(list):
default_range (tuple, optional): temperature range taken if
a Property doesn't have range. Defaults to (300, 1200).
+ Raises:
+ ValueError: When called on a mixed units group
+
Returns:
ArrheniusProperty: the mean arrhenius property
"""
+ if self.units == "mixed units":
+ raise ValueError("Can't compute mean on mixed units groups")
+
# initialise data points
data_T = np.array([])
data_y = np.array([])
diff --git a/h_transport_materials/property.py b/h_transport_materials/property.py
index c2d7cee..b9994e2 100644
--- a/h_transport_materials/property.py
+++ b/h_transport_materials/property.py
@@ -184,6 +184,15 @@ class ArrheniusProperty(Property):
@property
def units(self):
+ # check if data_y is set
+ if hasattr(self, "data_y"):
+ if self.data_y is not None:
+ return self.data_y.units
+ # check if pre_exp is set
+ if hasattr(self, "pre_exp"):
+ return self.pre_exp.units
+
+ # return dimensionless by default
return ureg.dimensionless
@property
| RemDelaporteMathurin/h-transport-materials | 1ccf5a11ffbb6a013c50540c1b20cde2ee5302e5 | diff --git a/tests/test_properties_group.py b/tests/test_properties_group.py
index 31ab5cd..cd40a60 100644
--- a/tests/test_properties_group.py
+++ b/tests/test_properties_group.py
@@ -88,7 +88,7 @@ def test_mean(mean_D_0, mean_E_D):
mean_prop = my_group.mean()
# test
- assert mean_prop.pre_exp == pytest.approx(mean_D_0, rel=0.2)
+ assert mean_prop.pre_exp.magnitude == pytest.approx(mean_D_0, rel=0.2)
assert mean_prop.act_energy.magnitude == pytest.approx(mean_E_D, rel=0.2)
@@ -196,3 +196,20 @@ def test_units_property():
def test_to_latex_table():
htm.diffusivities.to_latex_table()
+
+
+def test_mean_has_units():
+ assert htm.diffusivities.mean().units == htm.ureg.m**2 * htm.ureg.s**-1
+
+
+def test_cannot_compute_mean_on_mixed_groups():
+ prop1 = htm.ArrheniusProperty(
+ 0.1 * htm.ureg.dimensionless, 0.1 * htm.ureg.eV * htm.ureg.particle**-1
+ )
+ prop2 = htm.ArrheniusProperty(
+ 0.1 * htm.ureg.m, 0.1 * htm.ureg.eV * htm.ureg.particle**-1
+ )
+ my_group = htm.PropertiesGroup([prop1, prop2])
+
+ with pytest.raises(ValueError, match="Can't compute mean on mixed units groups"):
+ my_group.mean()
| PropertiesGroup.mean should have units
```python
import h_transport_materials as htm
print(htm.diffusivities.mean().units)
```
Prints
```
dimensionless
``` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_properties_group.py::test_mean_has_units",
"tests/test_properties_group.py::test_cannot_compute_mean_on_mixed_groups"
] | [
"tests/test_properties_group.py::test_iterable",
"tests/test_properties_group.py::test_adding_two_groups",
"tests/test_properties_group.py::test_filter_author_lower_case",
"tests/test_properties_group.py::test_filter_isotope_lower_case",
"tests/test_properties_group.py::test_mean[2.0-0.1]",
"tests/test_properties_group.py::test_mean[2.0-1.55]",
"tests/test_properties_group.py::test_mean[2.0-3.0]",
"tests/test_properties_group.py::test_mean[31.0-0.1]",
"tests/test_properties_group.py::test_mean[31.0-1.55]",
"tests/test_properties_group.py::test_mean[31.0-3.0]",
"tests/test_properties_group.py::test_mean[60.0-0.1]",
"tests/test_properties_group.py::test_mean[60.0-1.55]",
"tests/test_properties_group.py::test_mean[60.0-3.0]",
"tests/test_properties_group.py::test_mean_is_type_arrhenius_property",
"tests/test_properties_group.py::test_bibdata",
"tests/test_properties_group.py::test_export_bib",
"tests/test_properties_group.py::test_export_to_json",
"tests/test_properties_group.py::test_filter_warns_when_no_props",
"tests/test_properties_group.py::test_units_property",
"tests/test_properties_group.py::test_to_latex_table"
] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
} | "2023-03-29T13:43:37Z" | mit |
|
RemDelaporteMathurin__h-transport-materials-185 | diff --git a/h_transport_materials/properties_group.py b/h_transport_materials/properties_group.py
index 1099a1b..6efdd55 100644
--- a/h_transport_materials/properties_group.py
+++ b/h_transport_materials/properties_group.py
@@ -143,33 +143,9 @@ class PropertiesGroup(list):
self.bibdata.to_file(filename)
def export_to_json(self, filename: str):
- keys = [
- "material",
- "pre_exp",
- "act_energy",
- "isotope",
- "author",
- "source",
- "range",
- "doi",
- "units",
- ]
-
data = []
for prop in self:
-
- prop_dict = {key: getattr(prop, key) for key in keys if hasattr(prop, key)}
- if "units" in prop_dict:
- prop_dict["units"] = f"{prop_dict['units']:~}"
- prop_dict["pre_exp"] = prop_dict["pre_exp"].magnitude
- prop_dict["act_energy"] = prop_dict["act_energy"].magnitude
- prop_dict["material"] = prop_dict["material"].name
- if prop_dict["range"]:
- prop_dict["range"] = (
- prop_dict["range"][0].magnitude,
- prop_dict["range"][1].magnitude,
- )
- data.append(prop_dict)
+ data.append(prop.to_json())
with open(filename, "w") as outfile:
json.dump(data, outfile, indent=4)
diff --git a/h_transport_materials/property.py b/h_transport_materials/property.py
index b9994e2..6bf41e2 100644
--- a/h_transport_materials/property.py
+++ b/h_transport_materials/property.py
@@ -36,7 +36,6 @@ class Property:
author: str = "",
note: str = None,
) -> None:
-
self.material = material
self.source = source
self.range = range
@@ -137,6 +136,25 @@ class Property:
self.bibdata.to_file(filename)
+ def to_json(self):
+ """Returns a dictionary with the relevant attributes of the property
+
+ Returns:
+ dict: a dict reprensation of the property
+ """
+ as_json = {}
+ if self.range is not None:
+ as_json["range"] = (self.range[0].magnitude, self.range[1].magnitude)
+ as_json["material"] = self.material.name
+ as_json["source"] = self.source
+ as_json["year"] = self.year
+ as_json["isotope"] = self.isotope
+ as_json["author"] = self.author
+ as_json["note"] = self.note
+ as_json["doi"] = self.doi
+
+ return as_json
+
def value(self, T):
pass
@@ -164,7 +182,6 @@ class ArrheniusProperty(Property):
data_y: list = None,
**kwargs,
) -> None:
-
self.pre_exp = pre_exp
self.act_energy = act_energy
self.data_T = data_T
@@ -340,6 +357,29 @@ class ArrheniusProperty(Property):
T *= ureg.K
return self.pre_exp * exp(-self.act_energy / k_B / T)
+ def to_json(self):
+ """Returns a dictionary with the relevant attributes of the property
+
+ Returns:
+ dict: a dict reprensation of the property
+ """
+ as_json = super().to_json()
+ as_json["pre_exp"] = {}
+ as_json["act_energy"] = {}
+ as_json["pre_exp"]["value"] = self.pre_exp.magnitude
+ as_json["pre_exp"]["units"] = f"{self.pre_exp.units}"
+ as_json["act_energy"]["value"] = self.act_energy.magnitude
+ as_json["act_energy"]["units"] = f"{self.act_energy.units}"
+ if self.data_T is not None:
+ as_json["data_T"] = {}
+ as_json["data_T"]["value"] = self.data_T.magnitude.tolist()
+ as_json["data_T"]["units"] = f"{self.data_T.units}"
+ if self.data_y is not None:
+ as_json["data_y"] = {}
+ as_json["data_y"]["value"] = self.data_y.magnitude.tolist()
+ as_json["data_y"]["units"] = f"{self.data_y.units}"
+ return as_json
+
class Solubility(ArrheniusProperty):
"""Solubility class
@@ -460,7 +500,6 @@ class Permeability(ArrheniusProperty):
law: str = None,
**kwargs,
) -> None:
-
self.law = law
super().__init__(
pre_exp=pre_exp,
diff --git a/h_transport_materials/property_database/cucrzr/cucrzr.py b/h_transport_materials/property_database/cucrzr/cucrzr.py
index 5d58058..40d116b 100644
--- a/h_transport_materials/property_database/cucrzr/cucrzr.py
+++ b/h_transport_materials/property_database/cucrzr/cucrzr.py
@@ -35,7 +35,6 @@ note_serra_diffusivity_h = (
serra_diffusivity_h = Diffusivity(
data_T=1000 / data_diffusivity_serra_h[:, 0] * htm.ureg.K,
data_y=data_diffusivity_serra_h[:, 1] * htm.ureg.m**2 * htm.ureg.s**-1,
- range=(553 * htm.ureg.K, 773 * htm.ureg.K),
source="serra_hydrogen_1998",
isotope="H",
note=note_serra_diffusivity_h,
@@ -49,7 +48,6 @@ note_serra_diffusivity_d = (
serra_diffusivity_d = Diffusivity(
data_T=1000 / data_diffusivity_serra_d[:, 0] * htm.ureg.K,
data_y=data_diffusivity_serra_d[:, 1] * htm.ureg.m**2 * htm.ureg.s**-1,
- range=(553 * htm.ureg.K, 773 * htm.ureg.K),
source="serra_hydrogen_1998",
isotope="D",
note=note_serra_diffusivity_d,
@@ -69,7 +67,6 @@ serra_solubility_h = Solubility(
* htm.ureg.mol
* htm.ureg.m**-3
* htm.ureg.Pa**-0.5,
- range=(553 * htm.ureg.K, 773 * htm.ureg.K),
source="serra_hydrogen_1998",
isotope="H",
)
@@ -80,7 +77,6 @@ serra_solubility_d = Solubility(
* htm.ureg.mol
* htm.ureg.m**-3
* htm.ureg.Pa**-0.5,
- range=(553 * htm.ureg.K, 773 * htm.ureg.K),
source="serra_hydrogen_1998",
isotope="D",
)
diff --git a/h_transport_materials/property_database/lipb/lipb.py b/h_transport_materials/property_database/lipb/lipb.py
index 2691dde..5622be9 100644
--- a/h_transport_materials/property_database/lipb/lipb.py
+++ b/h_transport_materials/property_database/lipb/lipb.py
@@ -123,7 +123,6 @@ reiter_difusivity_data_H = reiter_diffusivity_data[2:, 2:]
reiter_diffusivity_h = Diffusivity(
data_T=1000 / reiter_difusivity_data_H[:, 0] * u.K,
data_y=reiter_difusivity_data_H[:, 1] * u.m**2 * u.s**-1,
- range=(508 * u.K, 700 * u.K),
source="reiter_solubility_1991",
isotope="H",
)
@@ -134,7 +133,6 @@ reiter_difusivity_data_D = reiter_diffusivity_data[2:, :2]
reiter_diffusivity_d = Diffusivity(
data_T=1000 / reiter_difusivity_data_D[:, 0] * u.K,
data_y=reiter_difusivity_data_D[:, 1] * u.m**2 * u.s**-1,
- range=(508 * u.K, 700 * u.K),
source="reiter_solubility_1991",
isotope="D",
)
@@ -154,7 +152,6 @@ reiter_solubility_data_H_y *= atom_density_lipb(nb_li=17, nb_pb=1) # m-3 Pa-1/2
reiter_solubility_h = Solubility(
data_T=1000 / reiter_solubility_data_H[:, 0] * u.K,
data_y=reiter_solubility_data_H_y,
- range=(508 * u.K, 700 * u.K),
source="reiter_solubility_1991",
isotope="H",
)
@@ -171,7 +168,6 @@ reiter_solubility_data_D_y *= atom_density_lipb(nb_li=17, nb_pb=1) # m-3 Pa-1/2
reiter_solubility_d = Solubility(
data_T=reiter_solubility_data_D_T[np.isfinite(reiter_solubility_data_D_T)] * u.K,
data_y=reiter_solubility_data_D_y[np.isfinite(reiter_solubility_data_D_y)],
- range=(508 * u.K, 700 * u.K),
source="reiter_solubility_1991",
isotope="D",
)
@@ -193,7 +189,6 @@ data_aiello = np.genfromtxt(
aiello_solubility = Solubility(
data_T=1000 / data_aiello[:, 0] * u.K,
data_y=data_aiello[:, 1] * u.mol * u.m**-3 * u.Pa**-0.5,
- range=(600 * u.K, 900 * u.K),
source="aiello_determination_2006",
isotope="H",
)
| RemDelaporteMathurin/h-transport-materials | 3c05e8f4aaf833b2b1473022b5fcc3fcc9825bcd | diff --git a/tests/test_properties_group.py b/tests/test_properties_group.py
index cd40a60..4839a9f 100644
--- a/tests/test_properties_group.py
+++ b/tests/test_properties_group.py
@@ -165,7 +165,11 @@ def test_export_to_json():
if key == "units":
assert f"{getattr(prop_ref, key):~}" == val
elif key in ["pre_exp", "act_energy"]:
- assert getattr(prop_ref, key).magnitude == val
+ assert getattr(prop_ref, key).magnitude == val["value"]
+ elif key in ["data_T", "data_y"]:
+ assert np.array_equal(
+ getattr(prop_ref, key).magnitude, val["value"]
+ )
else:
assert getattr(prop_ref, key) == val
| PropertiesGroup need to break down export_to_json
The method export_to_json could be broken down.
This could simplify the export to json in HTM-dashboard. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_properties_group.py::test_export_to_json"
] | [
"tests/test_properties_group.py::test_mean[60.0-1.55]",
"tests/test_properties_group.py::test_bibdata",
"tests/test_properties_group.py::test_mean_has_units",
"tests/test_properties_group.py::test_mean[31.0-3.0]",
"tests/test_properties_group.py::test_to_latex_table",
"tests/test_properties_group.py::test_mean_is_type_arrhenius_property",
"tests/test_properties_group.py::test_adding_two_groups",
"tests/test_properties_group.py::test_mean[2.0-0.1]",
"tests/test_properties_group.py::test_filter_author_lower_case",
"tests/test_properties_group.py::test_cannot_compute_mean_on_mixed_groups",
"tests/test_properties_group.py::test_filter_isotope_lower_case",
"tests/test_properties_group.py::test_iterable",
"tests/test_properties_group.py::test_mean[60.0-3.0]",
"tests/test_properties_group.py::test_mean[2.0-1.55]",
"tests/test_properties_group.py::test_mean[31.0-0.1]",
"tests/test_properties_group.py::test_export_bib",
"tests/test_properties_group.py::test_units_property",
"tests/test_properties_group.py::test_mean[31.0-1.55]",
"tests/test_properties_group.py::test_filter_warns_when_no_props",
"tests/test_properties_group.py::test_mean[60.0-0.1]",
"tests/test_properties_group.py::test_mean[2.0-3.0]"
] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2023-04-27T18:23:58Z" | mit |
|
RemDelaporteMathurin__h-transport-materials-247 | diff --git a/h_transport_materials/properties_group.py b/h_transport_materials/properties_group.py
index 60ba476..7a81f9c 100644
--- a/h_transport_materials/properties_group.py
+++ b/h_transport_materials/properties_group.py
@@ -6,6 +6,8 @@ from textwrap import dedent
from h_transport_materials import ureg, ArrheniusProperty, __version__
+warnings.filterwarnings("always", message="No property matching the requirements")
+
class PropertiesGroup(list):
@property
@@ -94,7 +96,11 @@ class PropertiesGroup(list):
# geometric mean of pre-exponential factor
pre_exps = np.array([prop.pre_exp.magnitude for prop in self])
- pre_exp = pre_exps.prod() ** (1.0 / len(pre_exps))
+ scaling_factor = np.max(pre_exps)
+ pre_exps = pre_exps / scaling_factor # scale pre-exps to avoid inf
+
+ pre_exp = pre_exps.prod() ** (1.0 / len(pre_exps)) # compute mean
+ pre_exp = pre_exp * scaling_factor # re-scale
# arithmetic mean of activation energy
act_energy = np.array([prop.act_energy.magnitude for prop in self]).mean()
diff --git a/h_transport_materials/property_database/iron.py b/h_transport_materials/property_database/iron.py
index 942a7b5..02aef03 100644
--- a/h_transport_materials/property_database/iron.py
+++ b/h_transport_materials/property_database/iron.py
@@ -8,7 +8,9 @@ from h_transport_materials import (
u = htm.ureg
-IRON_MOLAR_VOLUME = 7.09e-6 # m3/mol https://www.aqua-calc.com/calculate/mole-to-volume-and-weight/substance/iron
+# TODO give units to IRON_MOLAR_VOLUME
+# https://www.aqua-calc.com/calculate/mole-to-volume-and-weight/substance/iron
+IRON_MOLAR_VOLUME = 7.09e-6 # m3/mol
volkl_diffusivity = Diffusivity(
D_0=4.00e-8 * u.m**2 * u.s**-1,
diff --git a/h_transport_materials/property_database/steel_316L/steel_316L.py b/h_transport_materials/property_database/steel_316L/steel_316L.py
index d8c2edb..38f3867 100644
--- a/h_transport_materials/property_database/steel_316L/steel_316L.py
+++ b/h_transport_materials/property_database/steel_316L/steel_316L.py
@@ -6,11 +6,17 @@ from h_transport_materials import (
DissociationCoeff,
RecombinationCoeff,
)
-from h_transport_materials.property_database.iron import IRON_MOLAR_VOLUME
import numpy as np
u = htm.ureg
+STEEL_316L_DENSITY = (
+ 8.0 * u.g * u.cm**-3
+) # ref https://doi.org/10.31399/asm.hb.mhde2.9781627081993
+STEEL_316L_MOLAR_MASS = 56.52 * u.g * u.mol**-1 # TODO compute it from composition
+STEEL_316L_MOLAR_VOLUME = STEEL_316L_DENSITY / STEEL_316L_MOLAR_MASS
+
+
reiter_diffusivity = Diffusivity(
D_0=3.70e-7 * u.m**2 * u.s**-1,
E_D=51.9 * u.kJ * u.mol**-1,
@@ -21,7 +27,7 @@ reiter_diffusivity = Diffusivity(
)
reiter_solubility = Solubility(
- S_0=5.8e-6 / IRON_MOLAR_VOLUME * u.mol * u.m**-3 * u.Pa**-0.5,
+ S_0=5.8e-6 * u.Pa**-0.5 * STEEL_316L_MOLAR_VOLUME,
E_S=13.1 * u.kJ * u.mol**-1,
range=(500 * u.K, 1200 * u.K),
isotope="H",
@@ -29,6 +35,57 @@ reiter_solubility = Solubility(
note="this is an average of 5 papers on diffusivity from Reiter compilation review",
)
+# TODO fit this ourselves
+reiter_1985_solubility_h = Solubility(
+ S_0=1.84e-6 * u.Pa**-0.5 * STEEL_316L_MOLAR_VOLUME,
+ E_S=6880 * u.J * u.mol**-1,
+ range=(600 * u.K, 900 * u.K),
+ isotope="h",
+ source="reiter_interaction_1985",
+ note="probably a unit mistake in the activation energies in original paper",
+)
+
+reiter_1985_solubility_d = Solubility(
+ S_0=1.96e-6 * u.Pa**-0.5 * STEEL_316L_MOLAR_VOLUME,
+ E_S=8090 * u.J * u.mol**-1,
+ range=(600 * u.K, 900 * u.K),
+ isotope="d",
+ source="reiter_interaction_1985",
+ note="probably a unit mistake in the activation energies in original paper",
+)
+
+reiter_1985_diffusivity_h = Diffusivity(
+ D_0=2.99e-6 * u.m**2 * u.s**-1,
+ E_D=59700 * u.J * u.mol**-1,
+ range=(600 * u.K, 900 * u.K),
+ isotope="h",
+ source="reiter_interaction_1985",
+ note="probably a unit mistake in the activation energies in original paper",
+)
+
+reiter_1985_diffusivity_d = Diffusivity(
+ D_0=1.74e-6 * u.m**2 * u.s**-1,
+ E_D=58100 * u.J * u.mol**-1,
+ range=(600 * u.K, 900 * u.K),
+ isotope="d",
+ source="reiter_interaction_1985",
+ note="probably a unit mistake in the activation energies in original paper",
+)
+
+reiter_1985_permeability_h = reiter_1985_diffusivity_h * reiter_1985_solubility_h
+reiter_1985_permeability_h.range = reiter_1985_diffusivity_h.range
+reiter_1985_permeability_h.isotope = reiter_1985_diffusivity_h.isotope
+reiter_1985_permeability_h.source = reiter_1985_diffusivity_h.source
+reiter_1985_permeability_h.note = "calculated in HTM"
+
+
+reiter_1985_permeability_d = reiter_1985_diffusivity_d * reiter_1985_solubility_d
+reiter_1985_permeability_d.range = reiter_1985_diffusivity_d.range
+reiter_1985_permeability_d.isotope = reiter_1985_diffusivity_d.isotope
+reiter_1985_permeability_d.source = reiter_1985_diffusivity_d.source
+reiter_1985_permeability_d.note = "calculated in HTM"
+
+
houben_permeability = Permeability(
pre_exp=8e-7 * u.mol * u.m**-1 * u.s**-1 * u.mbar**-0.5,
act_energy=58 * u.kJ * u.mol**-1,
@@ -212,6 +269,88 @@ serra_solubility = Solubility(
source="serra_hydrogen_2004",
)
+
+shan_permeability_h = Permeability(
+ data_T=[500.0, 550.0, 600.0, 650.0, 700.0, 723.0] * u.K,
+ data_y=[8.95e-11, 3.46e-10, 1.07e-9, 2.78e-9, 6.30e-9, 8.84e-9]
+ * u.mol
+ * u.m**-1
+ * u.s**-1
+ * u.MPa**-0.5,
+ isotope="h",
+ source="shan_behavior_1991",
+ note="Table 1",
+)
+
+shan_permeability_t = Permeability(
+ data_T=[500.0, 550.0, 600.0, 650.0, 700.0, 723.0] * u.K,
+ data_y=[1.72e-11, 6.39e-11, 1.91e-10, 4.82e-10, 1.07e-9, 1.48e-9]
+ * u.mol
+ * u.m**-1
+ * u.s**-1
+ * u.MPa**-0.5,
+ isotope="t",
+ source="shan_behavior_1991",
+ note="Table 1",
+)
+
+shan_diffusivity_h = Diffusivity(
+ data_T=[500.0, 550.0, 600.0, 650.0, 700.0, 723.0] * u.K,
+ data_y=[1.39e-12, 4.51e-12, 1.20e-11, 2.76e-11, 5.64e-11, 7.57e-11]
+ * u.m**2
+ * u.s**-1,
+ isotope="h",
+ source="shan_behavior_1991",
+ note="Table 1",
+)
+
+shan_diffusivity_t = Diffusivity(
+ data_T=[500.0, 550.0, 600.0, 650.0, 700.0, 723.0] * u.K,
+ data_y=[6.00e-12, 8.35e-12, 1.10e-11, 1.39e-11, 1.70e-11, 1.84e-11]
+ * u.m**2
+ * u.s**-1,
+ isotope="t",
+ source="shan_behavior_1991",
+ note="Table 1",
+)
+
+shan_solubility_h = Solubility(
+ S_0=shan_permeability_h.pre_exp / shan_diffusivity_h.pre_exp,
+ E_S=shan_permeability_h.act_energy - shan_diffusivity_h.act_energy,
+ range=shan_permeability_h.range,
+ isotope="h",
+ source="shan_behavior_1991",
+ note="calculated in HTM",
+)
+
+
+shan_solubility_t = Solubility(
+ S_0=shan_permeability_t.pre_exp / shan_diffusivity_t.pre_exp,
+ E_S=shan_permeability_t.act_energy - shan_diffusivity_t.act_energy,
+ range=shan_permeability_t.range,
+ isotope="t",
+ source="shan_behavior_1991",
+ note="calculated in HTM",
+)
+
+penzhorn_diffusivity_1 = Diffusivity(
+ D_0=1.9e-2 * u.cm**2 * u.s**-1,
+ E_D=61300 * u.J * u.mol**-1,
+ range=(373.0, 473.0) * u.K,
+ isotope="T",
+ source="penzhorn_distribution_2010",
+ note="Section III.B, temperature range is unclear",
+)
+
+penzhorn_diffusivity_2 = Diffusivity(
+ D_0=1.5e-2 * u.cm**2 * u.s**-1,
+ E_D=57300 * u.J * u.mol**-1,
+ range=(373.0, 473.0) * u.K,
+ isotope="T",
+ source="penzhorn_distribution_2010",
+ note="Section III.C, temperature range is unclear",
+)
+
properties = [
reiter_diffusivity,
reiter_solubility,
@@ -234,6 +373,20 @@ properties = [
serra_permeability,
serra_diffusivity,
serra_solubility,
+ reiter_1985_solubility_h,
+ reiter_1985_solubility_d,
+ reiter_1985_diffusivity_h,
+ reiter_1985_diffusivity_d,
+ reiter_1985_permeability_h,
+ reiter_1985_permeability_d,
+ shan_permeability_h,
+ shan_permeability_t,
+ shan_diffusivity_h,
+ shan_diffusivity_t,
+ shan_solubility_h,
+ shan_solubility_t,
+ penzhorn_diffusivity_1,
+ penzhorn_diffusivity_2,
]
for prop in properties:
diff --git a/h_transport_materials/references.bib b/h_transport_materials/references.bib
index 462c4a8..650d880 100644
--- a/h_transport_materials/references.bib
+++ b/h_transport_materials/references.bib
@@ -2411,3 +2411,40 @@ Publisher: Multidisciplinary Digital Publishing Institute},
year = {1980},
month = {6}
}
+
+@article{reiter_interaction_1985,
+ author = {F. Reiter and J. Camposilvan and M. Caorlin and G. Saibenea and R. Sartoria},
+ title = {Interaction of Hydrogen Isotopes with Stainless Steel 316 L},
+ journal = {Fusion Technology},
+ volume = {8},
+ number = {2P2},
+ pages = {2344-2351},
+ year = {1985},
+ publisher = {Taylor & Francis},
+ doi = {10.13182/FST85-A24629},
+}
+
+@article{shan_behavior_1991,
+ title = {The behavior of diffusion and permeation of tritium through 316L stainless steel},
+ journal = {Journal of Nuclear Materials},
+ volume = {179-181},
+ pages = {322-324},
+ year = {1991},
+ issn = {0022-3115},
+ doi = {https://doi.org/10.1016/0022-3115(91)90091-K},
+ url = {https://www.sciencedirect.com/science/article/pii/002231159190091K},
+ author = {Changqi Shan and Aiju Wu and Qingwang Chen},
+ abstract = {Results on diffusivity, solubility coefficient and permeability of tritium through palladium-plated 316L stainless steel are described. An empirical formula for the diffusivity, the solubility coefficient and the permeability of tritium through palladium-plated 316L stainless steel at various temperatures is presented. The influence of tritium pressure on the permeability, and the isotope effect of diffusivity of hydrogen and tritium in 316L stainless steel is discussed.}
+}
+
+@article{penzhorn_distribution_2010,
+ author = {R.-D. Penzhorn and Y. Torikai and S. Naoe and K. Akaishi and A. Perevezentsev and K. Watanabe and M. Matsuyama},
+ title = {Distribution and Mobility of Tritium in Type 316 Stainless Steel},
+ journal = {Fusion Science and Technology},
+ volume = {57},
+ number = {3},
+ pages = {185-195},
+ year = {2010},
+ publisher = {Taylor & Francis},
+ doi = {10.13182/FST57-3-185},
+}
\ No newline at end of file
| RemDelaporteMathurin/h-transport-materials | bfc9ed605514d9fce7b1faae4744553c9ab5fb6c | diff --git a/tests/test_properties_group.py b/tests/test_properties_group.py
index 711d54f..84f1b21 100644
--- a/tests/test_properties_group.py
+++ b/tests/test_properties_group.py
@@ -215,3 +215,10 @@ def test_cannot_compute_mean_on_mixed_groups():
with pytest.raises(ValueError, match="Can't compute mean on mixed units groups"):
my_group.mean()
+
+
+def test_mean_of_large_numbers_properties():
+ """This test catches bug reported in issue #242"""
+
+ perm = htm.permeabilities.filter(material="steel").mean()
+ assert not np.isinf(perm.pre_exp)
| Entries from HCDB
https://db-amdis.org/hcdb
316L
- [ ] https://doi.org/10.1016/j.ijhydene.2006.05.008 this is a review, will not include in HTM
- [x] https://doi.org/10.13182/FST85-A24629
- [x] https://doi.org/10.1016/0022-3115(85)90056-X already in HTM
- [x] https://doi.org/10.1016/0022-3115(91)90091-K
- [x] https://doi.org/10.13182/FST57-3-185 | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_properties_group.py::test_mean_of_large_numbers_properties"
] | [
"tests/test_properties_group.py::test_iterable",
"tests/test_properties_group.py::test_adding_two_groups",
"tests/test_properties_group.py::test_filter_author_lower_case",
"tests/test_properties_group.py::test_filter_isotope_lower_case",
"tests/test_properties_group.py::test_mean[2.0-0.1]",
"tests/test_properties_group.py::test_mean[2.0-1.55]",
"tests/test_properties_group.py::test_mean[2.0-3.0]",
"tests/test_properties_group.py::test_mean[31.0-0.1]",
"tests/test_properties_group.py::test_mean[31.0-1.55]",
"tests/test_properties_group.py::test_mean[31.0-3.0]",
"tests/test_properties_group.py::test_mean[60.0-0.1]",
"tests/test_properties_group.py::test_mean[60.0-1.55]",
"tests/test_properties_group.py::test_mean[60.0-3.0]",
"tests/test_properties_group.py::test_mean_is_type_arrhenius_property",
"tests/test_properties_group.py::test_bibdata",
"tests/test_properties_group.py::test_export_bib",
"tests/test_properties_group.py::test_export_to_json",
"tests/test_properties_group.py::test_filter_warns_when_no_props",
"tests/test_properties_group.py::test_units_property",
"tests/test_properties_group.py::test_to_latex_table",
"tests/test_properties_group.py::test_mean_has_units",
"tests/test_properties_group.py::test_cannot_compute_mean_on_mixed_groups"
] | {
"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
} | "2023-08-11T15:53:51Z" | mit |
|
RemDelaporteMathurin__h-transport-materials-249 | diff --git a/h_transport_materials/properties_group.py b/h_transport_materials/properties_group.py
index 60ba476..590fe85 100644
--- a/h_transport_materials/properties_group.py
+++ b/h_transport_materials/properties_group.py
@@ -94,7 +94,11 @@ class PropertiesGroup(list):
# geometric mean of pre-exponential factor
pre_exps = np.array([prop.pre_exp.magnitude for prop in self])
- pre_exp = pre_exps.prod() ** (1.0 / len(pre_exps))
+ scaling_factor = np.max(pre_exps)
+ pre_exps = pre_exps / scaling_factor # scale pre-exps to avoid inf
+
+ pre_exp = pre_exps.prod() ** (1.0 / len(pre_exps)) # compute mean
+ pre_exp = pre_exp * scaling_factor # re-scale
# arithmetic mean of activation energy
act_energy = np.array([prop.act_energy.magnitude for prop in self]).mean()
| RemDelaporteMathurin/h-transport-materials | bfc9ed605514d9fce7b1faae4744553c9ab5fb6c | diff --git a/tests/test_properties_group.py b/tests/test_properties_group.py
index 711d54f..84f1b21 100644
--- a/tests/test_properties_group.py
+++ b/tests/test_properties_group.py
@@ -215,3 +215,10 @@ def test_cannot_compute_mean_on_mixed_groups():
with pytest.raises(ValueError, match="Can't compute mean on mixed units groups"):
my_group.mean()
+
+
+def test_mean_of_large_numbers_properties():
+ """This test catches bug reported in issue #242"""
+
+ perm = htm.permeabilities.filter(material="steel").mean()
+ assert not np.isinf(perm.pre_exp)
| Inf pre-exponential factor on mean permeabilities
On HTM 0.13.1:
```python
import h_transport_materials as htm
perm = htm.permeabilities.filter(material="steel").mean()
print(perm)
```
```
C:\Users\remidm\AppData\Roaming\Python\Python311\site-packages\numpy\core\_methods.py:53: RuntimeWarning: overflow encountered in reduce
return umr_prod(a, axis, dtype, out, keepdims, initial, where)
Author:
Material:
Year: None
Isotope: None
Pre-exponential factor: inf particle/Paβ°β
β΅/m/s
Activation energy: 5.73Γ10β»ΒΉ eV/particle
``` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_properties_group.py::test_mean_of_large_numbers_properties"
] | [
"tests/test_properties_group.py::test_iterable",
"tests/test_properties_group.py::test_adding_two_groups",
"tests/test_properties_group.py::test_filter_author_lower_case",
"tests/test_properties_group.py::test_filter_isotope_lower_case",
"tests/test_properties_group.py::test_mean[2.0-0.1]",
"tests/test_properties_group.py::test_mean[2.0-1.55]",
"tests/test_properties_group.py::test_mean[2.0-3.0]",
"tests/test_properties_group.py::test_mean[31.0-0.1]",
"tests/test_properties_group.py::test_mean[31.0-1.55]",
"tests/test_properties_group.py::test_mean[31.0-3.0]",
"tests/test_properties_group.py::test_mean[60.0-0.1]",
"tests/test_properties_group.py::test_mean[60.0-1.55]",
"tests/test_properties_group.py::test_mean[60.0-3.0]",
"tests/test_properties_group.py::test_mean_is_type_arrhenius_property",
"tests/test_properties_group.py::test_bibdata",
"tests/test_properties_group.py::test_export_bib",
"tests/test_properties_group.py::test_export_to_json",
"tests/test_properties_group.py::test_filter_warns_when_no_props",
"tests/test_properties_group.py::test_units_property",
"tests/test_properties_group.py::test_to_latex_table",
"tests/test_properties_group.py::test_mean_has_units",
"tests/test_properties_group.py::test_cannot_compute_mean_on_mixed_groups"
] | {
"failed_lite_validators": [
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
} | "2023-08-14T16:06:18Z" | mit |
|
RemDelaporteMathurin__h-transport-materials-36 | diff --git a/h_transport_materials/property.py b/h_transport_materials/property.py
index 8174d74..4cc3aee 100644
--- a/h_transport_materials/property.py
+++ b/h_transport_materials/property.py
@@ -67,6 +67,16 @@ class ArrheniusProperty(Property):
self.data_y = data_y
super().__init__(**kwargs)
+ @property
+ def range(self):
+ if self._range is None and self.data_T is not None:
+ self.fit()
+ return self._range
+
+ @range.setter
+ def range(self, value):
+ self._range = value
+
@property
def pre_exp(self):
if self._pre_exp is None and self.data_T is not None:
@@ -121,6 +131,7 @@ class ArrheniusProperty(Property):
def fit(self):
self.pre_exp, self.act_energy = fit_arhenius(self.data_y, self.data_T)
+ self.range = (self.data_T.min(), self.data_T.max())
def value(self, T, exp=np.exp):
return self.pre_exp * exp(-self.act_energy / k_B / T)
| RemDelaporteMathurin/h-transport-materials | 9434449539499a14ea2bf0b2c00f2a5080a1c7f7 | diff --git a/tests/test_arhenius_property.py b/tests/test_arhenius_property.py
index 995e830..b030537 100644
--- a/tests/test_arhenius_property.py
+++ b/tests/test_arhenius_property.py
@@ -64,3 +64,14 @@ def test_value(T, pre_exp, act_energy):
computed_value = my_prop.value(T=T)
expected_value = pre_exp * np.exp(-act_energy / htm.k_B / T)
assert expected_value == computed_value
+
+
+def test_fit_creates_temp_range():
+ """Checks that when given data_T and data_y,
+ ArrheniusProperty.range is based on data_T"""
+ my_prop = htm.ArrheniusProperty(
+ data_T=[300, 400, 500],
+ data_y=[1, 2, 3],
+ )
+
+ assert my_prop.range == (300, 500)
| Temperature range should be determined by data_T | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_arhenius_property.py::test_fit_creates_temp_range"
] | [
"tests/test_arhenius_property.py::test_fit[data_T0-data_y0]",
"tests/test_arhenius_property.py::test_fit[data_T1-data_y1]",
"tests/test_arhenius_property.py::test_fit[data_T2-data_y2]",
"tests/test_arhenius_property.py::test_fit[data_T3-data_y3]",
"tests/test_arhenius_property.py::test_fit[data_T4-data_y4]",
"tests/test_arhenius_property.py::test_fit[data_T5-data_y5]",
"tests/test_arhenius_property.py::test_fit[data_T6-data_y6]",
"tests/test_arhenius_property.py::test_fit[data_T7-data_y7]",
"tests/test_arhenius_property.py::test_fit[data_T8-data_y8]",
"tests/test_arhenius_property.py::test_fit[data_T9-data_y9]",
"tests/test_arhenius_property.py::test_fit[data_T10-data_y10]",
"tests/test_arhenius_property.py::test_fit[data_T11-data_y11]",
"tests/test_arhenius_property.py::test_fit[data_T12-data_y12]",
"tests/test_arhenius_property.py::test_fit[data_T13-data_y13]",
"tests/test_arhenius_property.py::test_fit[data_T14-data_y14]",
"tests/test_arhenius_property.py::test_fit[data_T15-data_y15]",
"tests/test_arhenius_property.py::test_pre_exp_getter_fit",
"tests/test_arhenius_property.py::test_act_energy_getter_fit",
"tests/test_arhenius_property.py::test_value[300-3-0.2]",
"tests/test_arhenius_property.py::test_value[205-6-0.8]",
"tests/test_arhenius_property.py::test_value[600-100000.0-1.2]"
] | {
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false
} | "2022-05-24T13:43:36Z" | mit |
|
ReproNim__reproman-488 | diff --git a/reproman/interface/run.py b/reproman/interface/run.py
index 4654d00..e7f2edd 100644
--- a/reproman/interface/run.py
+++ b/reproman/interface/run.py
@@ -11,6 +11,7 @@
from argparse import REMAINDER
import collections
+from collections.abc import Mapping
import glob
import logging
import itertools
@@ -56,7 +57,7 @@ def _combine_job_specs(specs):
Taken from https://stackoverflow.com/a/3233356
"""
for k, v in u.items():
- if isinstance(v, collections.Mapping):
+ if isinstance(v, Mapping):
d[k] = update(d.get(k, {}), v)
else:
d[k] = v
diff --git a/reproman/resource/docker_container.py b/reproman/resource/docker_container.py
index 080d6e6..d9d0b2e 100644
--- a/reproman/resource/docker_container.py
+++ b/reproman/resource/docker_container.py
@@ -30,6 +30,16 @@ import logging
lgr = logging.getLogger('reproman.resource.docker_container')
+def _image_latest_default(image):
+ # Given the restricted character set for names, the presence of ":" or "@"
+ # should be a reliable indication of a tag or digest, respectively. See
+ # - https://docs.docker.com/engine/reference/commandline/tag/#extended-description
+ # - vendor/github.com/docker/distribution/reference/regexp.go
+ if ":" not in image and "@" not in image:
+ image += ":latest"
+ return image
+
+
@attr.s
class DockerContainer(Resource):
"""
@@ -43,8 +53,10 @@ class DockerContainer(Resource):
id = attrib()
type = attrib(default='docker-container')
- image = attrib(default='ubuntu:latest',
- doc="Docker base image ID from which to create the running instance")
+ image = attrib(
+ default='ubuntu:latest',
+ doc="Docker base image ID from which to create the running instance",
+ converter=_image_latest_default)
engine_url = attrib(default='unix:///var/run/docker.sock',
doc="Docker server URL where engine is listening for connections")
seccomp_unconfined = attrib(default=False,
diff --git a/reproman/utils.py b/reproman/utils.py
index 2b435b4..ca84aba 100644
--- a/reproman/utils.py
+++ b/reproman/utils.py
@@ -7,6 +7,7 @@
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
import collections
+from collections.abc import Mapping
import re
import builtins
@@ -1431,7 +1432,7 @@ def parse_kv_list(params):
------
ValueError if item in `params` does not match expected "key=value" format.
"""
- if isinstance(params, collections.Mapping):
+ if isinstance(params, Mapping):
res = params
elif params:
def check_fmt(item):
| ReproNim/reproman | a5da59d720baf3048a30000632b78e1eae215f5f | diff --git a/reproman/resource/tests/test_docker_container.py b/reproman/resource/tests/test_docker_container.py
index 1a9b5a7..3e7238b 100644
--- a/reproman/resource/tests/test_docker_container.py
+++ b/reproman/resource/tests/test_docker_container.py
@@ -175,3 +175,12 @@ def test_container_exists(setup_ubuntu):
from ..docker_container import DockerContainer
assert DockerContainer.is_container_running(setup_ubuntu['name'])
assert not DockerContainer.is_container_running('foo')
+
+
[email protected]_no_docker_dependencies
+def test_image_name_latest_default():
+ from ..docker_container import DockerContainer
+ for img, expected in [("debian:buster", "debian:buster"),
+ ("busybox@ddeeaa", "busybox@ddeeaa"),
+ ("busybox", "busybox:latest")]:
+ assert DockerContainer(name="cname", image=img).image == expected
| create: Default to :latest tag when pulling Docker image
`reproman create` callers that are familiar with the command-line interface to `docker pull` would reasonably expect that, if they omit a tag, the default `:latest` will be used. Instead we download all tags:
```
$ docker images busybox
REPOSITORY TAG IMAGE ID CREATED SIZE
$ reproman create bb -t docker-container -b image=busybox >notag-out 2>&1
$ wc -l notag-out
84 notag-out
$ grep -c "Download complete" notag-out
7
$ tail -n3 notag-out
2019-11-05 15:14:27,259 [INFO] Downloading [====================> ] 924.4kB/2.202MB
ERROR:
Interrupted by user while doing magic
$ docker images busybox
REPOSITORY TAG IMAGE ID CREATED SIZE
busybox 1-musl ff773d70e0ec 5 days ago 1.44MB
busybox 1-glibc 7636bfb4b772 5 days ago 5.2MB
busybox 1-uclibc 020584afccce 5 days ago 1.22MB
busybox 1-ubuntu d34ea343a882 3 years ago 4.35MB
busybox 1.21-ubuntu d34ea343a882 3 years ago 4.35MB
busybox 1.21.0-ubuntu d34ea343a882 3 years ago 4.35MB
busybox 1.23 a84c36ecc374 4 years ago 1.1MB
``` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"reproman/resource/tests/test_docker_container.py::test_image_name_latest_default"
] | [
"reproman/resource/tests/test_docker_container.py::test_dockercontainer_class"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2019-11-19T18:05:07Z" | mit |
|
ReproNim__reproman-508 | diff --git a/reproman/distributions/conda.py b/reproman/distributions/conda.py
index db568e5..4cea4e9 100644
--- a/reproman/distributions/conda.py
+++ b/reproman/distributions/conda.py
@@ -85,9 +85,7 @@ def get_miniconda_url(conda_platform, python_version):
raise ValueError("Unsupported platform %s for conda installation" %
conda_platform)
platform += "-x86_64" if ("64" in conda_platform) else "-x86"
- # FIXME: We need to update this our conda tracer to work with conda's newer
- # than 4.6.14. See gh-443.
- return "https://repo.anaconda.com/miniconda/Miniconda%s-4.6.14-%s.sh" \
+ return "https://repo.anaconda.com/miniconda/Miniconda%s-latest-%s.sh" \
% (python_version[0], platform)
@@ -191,17 +189,15 @@ class CondaDistribution(Distribution):
# NOTE: miniconda.sh makes parent directories automatically
session.execute_command("bash -b %s/miniconda.sh -b -p %s" %
(tmp_dir, self.path))
- ## Update root version of conda
- session.execute_command(
- "%s/bin/conda install -y conda=%s python=%s" %
- (self.path, self.conda_version,
- self.get_simple_python_version(self.python_version)))
-
- # Loop through non-root packages, creating the conda-env config
- for env in self.environments:
+ envs = sorted(
+ self.environments,
+ # Create/update the root environment before handling anything
+ # else.
+ key=lambda x: "_" if x.name == "root" else "_" + x.name)
+ for env in envs:
export_contents = self.create_conda_export(env)
with make_tempfile(export_contents) as local_config:
- remote_config = os.path.join(tmp_dir, env.name)
+ remote_config = os.path.join(tmp_dir, env.name + ".yaml")
session.put(local_config, remote_config)
if not session.isdir(env.path):
try:
@@ -282,6 +278,7 @@ class CondaTracer(DistributionTracer):
def _init(self):
self._get_conda_env_path = PathRoot(self._is_conda_env_path)
+ self._get_conda_dist_path = PathRoot(self._is_conda_dist_path)
def _get_packagefields_for_files(self, files):
raise NotImplementedError("TODO")
@@ -337,20 +334,27 @@ class CondaTracer(DistributionTracer):
# If there are pip dependencies, they'll be listed under a
# {"pip": [...]} entry.
- pip_pkgs = []
+ pip_pkgs = set()
for dep in dependencies:
if isinstance(dep, dict) and "pip" in dep:
# Pip packages are recorded in conda exports as "name (loc)",
# "name==version" or "name (loc)==version".
- pip_pkgs = [p.split("=")[0].split(" ")[0] for p in dep["pip"]]
+ pip_pkgs = {p.split("=")[0].split(" ")[0] for p in dep["pip"]}
break
+ pip = conda_path + "/bin/pip"
+ if not self._session.exists(pip):
+ return {}, {}
+
+ pkgs_editable = set(piputils.get_pip_packages(
+ self._session, pip, restriction="editable"))
+ pip_pkgs.update(pkgs_editable)
+
if not pip_pkgs:
return {}, {}
- pip = conda_path + "/bin/pip"
packages, file_to_package_map = piputils.get_package_details(
- self._session, pip, pip_pkgs)
+ self._session, pip, pip_pkgs, editable_packages=pkgs_editable)
for entry in packages.values():
entry["installer"] = "pip"
return packages, file_to_package_map
@@ -393,6 +397,10 @@ class CondaTracer(DistributionTracer):
def _is_conda_env_path(self, path):
return self._session.exists('%s/conda-meta' % path)
+ def _is_conda_dist_path(self, path):
+ return (self._session.exists(path + "/envs")
+ and self._is_conda_env_path(path))
+
def identify_distributions(self, paths):
conda_paths = set()
root_to_envs = defaultdict(list)
@@ -419,8 +427,7 @@ class CondaTracer(DistributionTracer):
# Find the root path for the environment
# TODO: cache/memoize for those paths which have been considered
# since will be asked again below
- conda_info = self._get_conda_info(conda_path)
- root_path = conda_info.get('root_prefix')
+ root_path = self._get_conda_dist_path(conda_path)
if not root_path:
lgr.warning("Could not find root path for conda environment %s"
% conda_path)
diff --git a/reproman/distributions/piputils.py b/reproman/distributions/piputils.py
index 4e5709a..1bbc872 100644
--- a/reproman/distributions/piputils.py
+++ b/reproman/distributions/piputils.py
@@ -117,7 +117,8 @@ def get_pip_packages(session, which_pip, restriction=None):
return (p["name"] for p in json.loads(out))
-def get_package_details(session, which_pip, packages=None):
+def get_package_details(session, which_pip, packages=None,
+ editable_packages=None):
"""Get package details from `pip show` and `pip list`.
This is similar to `pip_show`, but it uses `pip list` to get information
@@ -132,6 +133,9 @@ def get_package_details(session, which_pip, packages=None):
packages : list of str, optional
Package names. If not given, all packages returned by `pip list` are
used.
+ editable_packages : collection of str
+ If a package name is in this collection, mark it as editable. Passing
+ this saves a call to `which_pip`.
Returns
-------
@@ -140,8 +144,9 @@ def get_package_details(session, which_pip, packages=None):
"""
if packages is None:
packages = list(get_pip_packages(session, which_pip))
- editable_packages = set(
- get_pip_packages(session, which_pip, restriction="editable"))
+ if editable_packages is None:
+ editable_packages = set(
+ get_pip_packages(session, which_pip, restriction="editable"))
details, file_to_pkg = pip_show(session, which_pip, packages)
for pkg in details:
| ReproNim/reproman | 2ffa1759a8ced87169f3422bb2a0b0b9fb8e46b9 | diff --git a/reproman/distributions/tests/test_conda.py b/reproman/distributions/tests/test_conda.py
index 7ccd404..ec662bd 100644
--- a/reproman/distributions/tests/test_conda.py
+++ b/reproman/distributions/tests/test_conda.py
@@ -33,11 +33,11 @@ def test_get_conda_platform_from_python():
def test_get_miniconda_url():
assert get_miniconda_url("linux-64", "2.7") == \
- "https://repo.anaconda.com/miniconda/Miniconda2-4.6.14-Linux-x86_64.sh"
+ "https://repo.anaconda.com/miniconda/Miniconda2-latest-Linux-x86_64.sh"
assert get_miniconda_url("linux-32", "3.4") == \
- "https://repo.anaconda.com/miniconda/Miniconda3-4.6.14-Linux-x86.sh"
+ "https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86.sh"
assert get_miniconda_url("osx-64", "3.5.1") == \
- "https://repo.anaconda.com/miniconda/Miniconda3-4.6.14-MacOSX-x86_64.sh"
+ "https://repo.anaconda.com/miniconda/Miniconda3-latest-MacOSX-x86_64.sh"
def test_get_simple_python_version():
@@ -83,7 +83,7 @@ def test_create_conda_export():
md5=None,
size=None,
url=None,
- files=["lib/python2.7/site-packages/rpaths.py"])],
+ files=["lib/python3.7/site-packages/rpaths.py"])],
channels=[
CondaChannel(
name="conda-forge",
@@ -107,8 +107,8 @@ def test_conda_init_install_and_detect(tmpdir):
dist = CondaDistribution(
name="conda",
path=test_dir,
- conda_version="4.3.31",
- python_version="2.7.14.final.0",
+ conda_version="4.8.2",
+ python_version="3.8.2",
platform=get_conda_platform_from_python(sys.platform) + "-64",
environments=[
CondaEnvironment(
@@ -118,7 +118,7 @@ def test_conda_init_install_and_detect(tmpdir):
CondaPackage(
name="conda",
installer=None,
- version="4.3.31",
+ version="4.8.2",
build=None,
channel_name=None,
md5=None,
@@ -128,7 +128,7 @@ def test_conda_init_install_and_detect(tmpdir):
CondaPackage(
name="pip",
installer=None,
- version="9.0.1",
+ version="20.0.2",
build=None,
channel_name=None,
md5=None,
@@ -159,7 +159,7 @@ def test_conda_init_install_and_detect(tmpdir):
CondaPackage(
name="pip",
installer=None,
- version="9.0.1",
+ version="20.0.2",
build=None,
channel_name=None,
md5=None,
@@ -185,7 +185,7 @@ def test_conda_init_install_and_detect(tmpdir):
md5=None,
size=None,
url=None,
- files=["lib/python2.7/site-packages/rpaths.py"])],
+ files=["lib/python3.8/site-packages/rpaths.py"])],
channels=[
CondaChannel(
name="conda-forge",
| Our tracer is incompatible with latest conda
As described in gh-445:
> [...] our distributions.conda isn't compatible
> with the latest conda in at least two ways. We use an environment
> file that doesn't have an extension that conda now expects. That's an
> easy fix, and there's a patch in gh-443. The bigger issue is that
> environments seem to no longer have their own bin/conda unless conda
> is explicitly installed in the environment. (This mirrors the then
> seemingly hard-to-trigger problem initially described in gh-173.) As
> a result, our method for identifying an environment's root prefix is
> broken. Based on a quick scan of envs/NAME/, there may no longer be
> an easy way to map from an environment to its root prefix.
Re: #443 | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"reproman/distributions/tests/test_conda.py::test_get_miniconda_url"
] | [
"reproman/distributions/tests/test_conda.py::test_get_conda_platform_from_python",
"reproman/distributions/tests/test_conda.py::test_get_simple_python_version",
"reproman/distributions/tests/test_conda.py::test_format_conda_package",
"reproman/distributions/tests/test_conda.py::test_format_pip_package",
"reproman/distributions/tests/test_conda.py::test_create_conda_export",
"reproman/distributions/tests/test_conda.py::test_get_conda_env_export_exceptions",
"reproman/distributions/tests/test_conda.py::test_conda_packages"
] | {
"failed_lite_validators": [
"has_issue_reference",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2020-04-13T20:43:23Z" | mit |
|
ReproNim__reproman-518 | diff --git a/reproman/interface/run.py b/reproman/interface/run.py
index dd9ec19..7a181f6 100644
--- a/reproman/interface/run.py
+++ b/reproman/interface/run.py
@@ -24,6 +24,7 @@ from reproman.interface.base import Interface
from reproman.interface.common_opts import resref_opt
from reproman.interface.common_opts import resref_type_opt
from reproman.support.constraints import EnsureChoice
+from reproman.support.exceptions import JobError
from reproman.support.jobs.local_registry import LocalRegistry
from reproman.support.jobs.orchestrators import Orchestrator
from reproman.support.jobs.orchestrators import ORCHESTRATORS
@@ -439,3 +440,9 @@ class Run(Interface):
manager.delete(res)
orc.fetch(on_remote_finish=remote_fn)
lreg.unregister(orc.jobid)
+ # TODO: this would duplicate what is done in each .fetch
+ # implementation above anyways. We might want to make
+ # fetch return a record with fetched content and failed subjobs
+ failed = orc.get_failed_subjobs()
+ if failed:
+ raise JobError(failed=failed)
diff --git a/reproman/support/exceptions.py b/reproman/support/exceptions.py
index 9d5bc53..0cc1eb5 100644
--- a/reproman/support/exceptions.py
+++ b/reproman/support/exceptions.py
@@ -159,6 +159,23 @@ class OrchestratorError(RuntimeError):
pass
+# Job errors
+class JobError(RuntimeError):
+ """`reproman run` execution related error.
+ """
+ def __init__(self, *args, failed=None):
+ super().__init__(*args)
+ self.failed = failed
+
+ def __str__(self):
+ s = super().__str__()
+ if self.failed:
+ if s:
+ s += ' '
+ s += 'Failed subjobs: %s' % ', '.join(map(str, self.failed))
+ return s
+
+
#
# SSH support errors, largely adopted from starcluster
#
| ReproNim/reproman | afc2b767676cedf8cd37e4a0bc3aadc2e9eb777c | diff --git a/reproman/interface/tests/test_run.py b/reproman/interface/tests/test_run.py
index 035fb3d..c12531a 100644
--- a/reproman/interface/tests/test_run.py
+++ b/reproman/interface/tests/test_run.py
@@ -26,8 +26,11 @@ from reproman.interface.run import _resolve_batch_parameters
from reproman.utils import chpwd
from reproman.utils import swallow_logs
from reproman.utils import swallow_outputs
-from reproman.support.exceptions import OrchestratorError
-from reproman.support.exceptions import ResourceNotFoundError
+from reproman.support.exceptions import (
+ OrchestratorError,
+ ResourceNotFoundError,
+ JobError,
+)
from reproman.tests import fixtures
from reproman.tests.utils import create_tree
@@ -313,8 +316,10 @@ def test_run_and_follow_action(context, action):
run = context["run_fn"]
expect = "does not support the 'stop' feature"
with swallow_logs(new_level=logging.INFO) as log:
- run(command=["false"], resref="myshell",
- follow=action)
+ with pytest.raises(JobError) as ecm:
+ run(command=["false"], resref="myshell",
+ follow=action)
+ assert ecm.value.failed == [0]
if action.endswith("-if-success"):
assert expect not in log.out
else:
| run and jobs --fetch: fail with non-0 exit codes if anything (subjob, fetch, etc) fails | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"reproman/interface/tests/test_run.py::test_run_no_command[None]",
"reproman/interface/tests/test_run.py::test_run_no_command[[]]",
"reproman/interface/tests/test_run.py::test_run_no_resource",
"reproman/interface/tests/test_run.py::test_run_list[-expected0]",
"reproman/interface/tests/test_run.py::test_run_list[submitters-expected1]",
"reproman/interface/tests/test_run.py::test_run_list[orchestrators-expected2]",
"reproman/interface/tests/test_run.py::test_run_list[parameters-expected3]",
"reproman/interface/tests/test_run.py::test_combine_specs[empty]",
"reproman/interface/tests/test_run.py::test_combine_specs[exclusive]",
"reproman/interface/tests/test_run.py::test_combine_specs[simple-update]",
"reproman/interface/tests/test_run.py::test_combine_specs[mapping-to-atom]",
"reproman/interface/tests/test_run.py::test_combine_specs[atom-to-mapping]",
"reproman/interface/tests/test_run.py::test_combine_batch_params[empty]",
"reproman/interface/tests/test_run.py::test_combine_batch_params[one]",
"reproman/interface/tests/test_run.py::test_combine_batch_params[two,",
"reproman/interface/tests/test_run.py::test_combine_batch_params[two",
"reproman/interface/tests/test_run.py::test_combine_batch_params[=",
"reproman/interface/tests/test_run.py::test_combine_batch_params[spaces]",
"reproman/interface/tests/test_run.py::test_combine_batch_params_glob",
"reproman/interface/tests/test_run.py::test_combine_batch_params_repeat_key",
"reproman/interface/tests/test_run.py::test_combine_batch_params_no_equal",
"reproman/interface/tests/test_run.py::test_run_batch_spec_and_params",
"reproman/interface/tests/test_run.py::test_resolve_batch_params_eq[empty]",
"reproman/interface/tests/test_run.py::test_resolve_batch_params_eq[one]",
"reproman/interface/tests/test_run.py::test_resolve_batch_params_eq[two,",
"reproman/interface/tests/test_run.py::test_run_resource_specification",
"reproman/interface/tests/test_run.py::test_run_and_fetch",
"reproman/interface/tests/test_run.py::test_run_and_follow",
"reproman/interface/tests/test_run.py::test_run_and_follow_action[stop]",
"reproman/interface/tests/test_run.py::test_run_and_follow_action[stop-if-success]",
"reproman/interface/tests/test_run.py::test_run_and_follow_action[delete]",
"reproman/interface/tests/test_run.py::test_run_and_follow_action[delete-if-success]",
"reproman/interface/tests/test_run.py::test_jobs_auto_fetch_with_query",
"reproman/interface/tests/test_run.py::test_jobs_query_unknown",
"reproman/interface/tests/test_run.py::test_jobs_delete",
"reproman/interface/tests/test_run.py::test_jobs_show",
"reproman/interface/tests/test_run.py::test_jobs_unknown_action",
"reproman/interface/tests/test_run.py::test_jobs_ambig_id_match",
"reproman/interface/tests/test_run.py::test_jobs_deleted_resource",
"reproman/interface/tests/test_run.py::test_jobs_deleted_local_directory",
"reproman/interface/tests/test_run.py::test_jobs_orc_error"
] | [] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2020-05-26T02:27:44Z" | mit |
|
ReproNim__reproman-539 | diff --git a/reproman/support/jobs/orchestrators.py b/reproman/support/jobs/orchestrators.py
index 8191a70..2ec5a8a 100644
--- a/reproman/support/jobs/orchestrators.py
+++ b/reproman/support/jobs/orchestrators.py
@@ -890,19 +890,18 @@ class FetchPlainMixin(object):
# treat it as the file.
op.join(self.local_directory, ""))
- def get_failed_meta(mdir, failed):
- for idx in failed:
- for f in ["status", "stdout", "stderr"]:
- self.session.get(
- op.join(self.meta_directory,
- "{}.{:d}".format(f, idx)),
- op.join(self.local_directory,
- op.relpath(self.meta_directory,
- self.working_directory),
- ""))
+ for idx in range(len(self.job_spec["_command_array"])):
+ for f in ["status", "stdout", "stderr"]:
+ self.session.get(
+ op.join(self.meta_directory,
+ "{}.{:d}".format(f, idx)),
+ op.join(self.local_directory,
+ op.relpath(self.meta_directory,
+ self.working_directory),
+ ""))
failed = self.get_failed_subjobs()
- self.log_failed(failed, func=get_failed_meta)
+ self.log_failed(failed)
lgr.info("Outputs fetched. Finished with remote resource '%s'",
self.resource.name)
| ReproNim/reproman | 98bcaf28682181ad36f5a7a9f8de9f22ad242300 | diff --git a/reproman/support/jobs/tests/test_orchestrators.py b/reproman/support/jobs/tests/test_orchestrators.py
index 290422b..925db6d 100644
--- a/reproman/support/jobs/tests/test_orchestrators.py
+++ b/reproman/support/jobs/tests/test_orchestrators.py
@@ -104,6 +104,11 @@ def check_orc_plain(tmpdir):
orc.fetch()
assert open("out").read() == "content\nmore\n"
+
+ metadir_local = op.relpath(orc.meta_directory,
+ orc.working_directory)
+ for fname in "status", "stderr", "stdout":
+ assert op.exists(op.join(metadir_local, fname + ".0"))
return fn
| plain orchestrator: make sure that it at least fetches logs (stdout/err) even if not --output's were specified? | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"reproman/support/jobs/tests/test_orchestrators.py::test_orc_plain_shell"
] | [
"reproman/support/jobs/tests/test_orchestrators.py::test_orc_root_directory_error[no",
"reproman/support/jobs/tests/test_orchestrators.py::test_orc_root_directory_error[relative]",
"reproman/support/jobs/tests/test_orchestrators.py::test_orc_resurrection_invalid_job_spec",
"reproman/support/jobs/tests/test_orchestrators.py::test_orc_log_failed[1]",
"reproman/support/jobs/tests/test_orchestrators.py::test_orc_log_failed[2]",
"reproman/support/jobs/tests/test_orchestrators.py::test_orc_log_failed[10]"
] | {
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false
} | "2020-07-29T19:55:04Z" | mit |
|
ReproNim__reproman-544 | diff --git a/reproman/resource/session.py b/reproman/resource/session.py
index 776701c..ba80322 100644
--- a/reproman/resource/session.py
+++ b/reproman/resource/session.py
@@ -508,6 +508,50 @@ class Session(object):
raise NotImplementedError
+ def transfer_recursive(self, src_path, dest_path, isdir_fct, listdir_fct, mkdir_fct, cp_fct):
+ """Recursively transfer files and directories.
+
+ Traversing the source tree contains a lot of the same logic whether
+ we're putting or getting, so we abstract that out here. The cost is
+ that we need to pass the functions needed for the operation:
+
+ isdir_fct(src_path)
+
+ listdir_fct(src_path)
+
+ mkdir_fct(dest_path)
+
+ cp_fct(src_path, dest_path)
+
+ We unwrap the recursion so we can calculate the relative path names
+ from the base source path.
+ """
+
+ # a simple copy now if the source is a file...
+ if not isdir_fct(src_path):
+ cp_fct(src_path, dest_path)
+ return
+ # ...otherwise we src_path for relative paths
+
+ stack = [src_path]
+ while stack:
+ path = stack.pop()
+ src_relpath = os.path.relpath(path, src_path)
+ dest_fullpath = os.path.join(dest_path, src_relpath)
+ if isdir_fct(path):
+ # For src_path, relpath() gives '.', so dest_fullpath ends
+ # with "/.". mkdir doesn't like this, so we handle src_path
+ # as a special case.
+ if path == src_path:
+ mkdir_fct(dest_path)
+ else:
+ mkdir_fct(dest_fullpath)
+ stack.extend(os.path.join(path, p) for p in listdir_fct(path))
+ else:
+ cp_fct(path, dest_fullpath)
+ return
+
+
@attr.s
class POSIXSession(Session):
"""A Session which relies on commands present in any POSIX-compliant env
diff --git a/reproman/resource/shell.py b/reproman/resource/shell.py
index 316ed8c..4e9558e 100644
--- a/reproman/resource/shell.py
+++ b/reproman/resource/shell.py
@@ -84,7 +84,10 @@ class ShellSession(POSIXSession):
@borrowdoc(Session)
def get(self, src_path, dest_path=None, uid=-1, gid=-1):
dest_path = self._prepare_dest_path(src_path, dest_path)
- shutil.copy(src_path, dest_path)
+ if os.path.isdir(src_path):
+ shutil.copytree(src_path, dest_path)
+ else:
+ shutil.copy(src_path, dest_path)
if uid > -1 or gid > -1:
self.chown(dest_path, uid, gid, recursive=True)
@@ -157,4 +160,4 @@ class Shell(Resource):
raise NotImplementedError
if shared:
raise NotImplementedError
- return ShellSession()
\ No newline at end of file
+ return ShellSession()
diff --git a/reproman/resource/singularity.py b/reproman/resource/singularity.py
index bd87c42..537afec 100644
--- a/reproman/resource/singularity.py
+++ b/reproman/resource/singularity.py
@@ -186,8 +186,7 @@ class SingularitySession(POSIXSession):
return (stdout, stderr)
- @borrowdoc(Session)
- def put(self, src_path, dest_path, uid=-1, gid=-1):
+ def _put_file(self, src_path, dest_path):
dest_path = self._prepare_dest_path(src_path, dest_path,
local=False, absolute_only=True)
cmd = 'cat {} | singularity exec instance://{} tee {} > /dev/null'
@@ -195,19 +194,50 @@ class SingularitySession(POSIXSession):
self.name,
shlex_quote(dest_path)))
+ @borrowdoc(Session)
+ def put(self, src_path, dest_path, uid=-1, gid=-1):
+ self.transfer_recursive(
+ src_path,
+ dest_path,
+ os.path.isdir,
+ os.listdir,
+ self.mkdir,
+ self._put_file
+ )
+
if uid > -1 or gid > -1:
- self.chown(dest_path, uid, gid)
+ self.chown(dest_path, uid, gid, recursive=True)
- @borrowdoc(Session)
- def get(self, src_path, dest_path=None, uid=-1, gid=-1):
+ def _get_file(self, src_path, dest_path):
dest_path = self._prepare_dest_path(src_path, dest_path)
cmd = 'singularity exec instance://{} cat {} > {}'
self._runner.run(cmd.format(self.name,
shlex_quote(src_path),
shlex_quote(dest_path)))
+ @borrowdoc(Session)
+ def get(self, src_path, dest_path=None, uid=-1, gid=-1):
+ self.transfer_recursive(
+ src_path,
+ dest_path,
+ self.isdir,
+ self.listdir,
+ os.mkdir,
+ self._get_file
+ )
+
if uid > -1 or gid > -1:
- self.chown(dest_path, uid, gid, remote=False)
+ self.chown(dest_path, uid, gid, remote=False, recursive=True)
+
+ def listdir(self, path):
+ cmd = ['singularity',
+ 'exec',
+ 'instance://{}'.format(self.name),
+ 'ls',
+ '-1',
+ path]
+ (stdout, stderr) = self._runner.run(cmd)
+ return [ f for f in stdout.split('\n') if f not in ('', '.', '..') ]
@attr.s
diff --git a/reproman/resource/ssh.py b/reproman/resource/ssh.py
index 4153d8d..ebd1668 100644
--- a/reproman/resource/ssh.py
+++ b/reproman/resource/ssh.py
@@ -8,6 +8,8 @@
"""Resource sub-class to provide management of a SSH connection."""
import attr
+import os
+import stat
import getpass
import uuid
from ..log import LoggerHelper
@@ -218,18 +220,34 @@ class SSHSession(POSIXSession):
@borrowdoc(Session)
def put(self, src_path, dest_path, uid=-1, gid=-1):
dest_path = self._prepare_dest_path(src_path, dest_path, local=False)
- self.connection.put(src_path, dest_path)
+ sftp = self.connection.sftp()
+ self.transfer_recursive(
+ src_path,
+ dest_path,
+ os.path.isdir,
+ os.listdir,
+ sftp.mkdir,
+ self.connection.put
+ )
if uid > -1 or gid > -1:
- self.chown(dest_path, uid, gid)
+ self.chown(dest_path, uid, gid, recursive=True)
@borrowdoc(Session)
def get(self, src_path, dest_path=None, uid=-1, gid=-1):
dest_path = self._prepare_dest_path(src_path, dest_path)
- self.connection.get(src_path, dest_path)
+ sftp = self.connection.sftp()
+ self.transfer_recursive(
+ src_path,
+ dest_path,
+ lambda f: stat.S_ISDIR(sftp.stat(f).st_mode),
+ sftp.listdir,
+ os.mkdir,
+ self.connection.get
+ )
if uid > -1 or gid > -1:
- self.chown(dest_path, uid, gid, remote=False)
+ self.chown(dest_path, uid, gid, remote=False, recursive=True)
@attr.s
| ReproNim/reproman | b82a412ecccce33c885247dbd9464972b0e87c3f | diff --git a/reproman/interface/tests/test_run.py b/reproman/interface/tests/test_run.py
index c12531a..efacca7 100644
--- a/reproman/interface/tests/test_run.py
+++ b/reproman/interface/tests/test_run.py
@@ -493,3 +493,28 @@ def test_jobs_orc_error(context):
jobs(queries=[], status=True)
assert "myshell" not in output.out
assert "resurrection failed" in log.out
+
+
+def test_recursive_transfer(context):
+ run = context["run_fn"]
+ path = context["directory"]
+ jobs = context["jobs_fn"]
+
+ # Our script takes an inventory of the execute directory so we can be
+ # sure that all of the files have transferred. It then creates a tree
+ # that we verify is returned.
+
+ create_tree(path, {"script": "find . > out_file ; mkdir out_dir ; touch out_dir/subfile",
+ "in_dir": {"subfile": ""}})
+
+ with swallow_outputs() as output:
+ run(command=["sh", "-e", "script"],
+ inputs=["script", "in_dir"],
+ outputs=["out_file", "out_dir"],
+ resref="myshell")
+ try_fetch(lambda: jobs(queries=[], action="fetch", all_=True))
+ assert op.exists(op.join(path, "out_file"))
+ with open(op.join(path, "out_file")) as fo:
+ lines = [ line.strip() for line in fo ]
+ assert "./in_dir/subfile" in lines
+ assert op.exists(op.join(path, "out_dir", "subfile"))
diff --git a/reproman/resource/tests/test_session.py b/reproman/resource/tests/test_session.py
index 8dd551e..9ae51df 100644
--- a/reproman/resource/tests/test_session.py
+++ b/reproman/resource/tests/test_session.py
@@ -18,6 +18,7 @@ import uuid
from ..session import get_updated_env, Session
from ...support.exceptions import CommandError
from ...utils import chpwd, swallow_logs
+from ...tests.utils import create_tree
from ...tests.skip import mark
from ...tests.fixtures import get_docker_fixture
from ...tests.fixtures import get_singularity_fixture
@@ -260,11 +261,13 @@ def check_methods(resource_test_dir):
assert not result
# Create a temporary test file
- temp_file = tempfile.NamedTemporaryFile(dir=resource_test_dir)
- with temp_file as f:
- f.write('ReproMan test content\nline 2\nline 3'.encode('utf8'))
- f.flush()
- local_path = temp_file.name
+ with tempfile.TemporaryDirectory(dir=resource_test_dir) as tdir:
+ create_tree(tdir,
+ {'f0': 'ReproMan test content\nline 2\nline 3',
+ 'f1': 'f1',
+ 'd0': {'f2': 'f2',
+ 'd2': {'f3': 'f3'}}})
+ local_path = os.path.join(tdir, 'f0')
remote_path = '{}/reproman upload/{}'.format(resource_test_dir,
uuid.uuid4().hex)
@@ -276,6 +279,13 @@ def check_methods(resource_test_dir):
assert result
# TODO: Check uid and gid of remote file
+ # Check recursive put().
+ remote_path_rec = '{}/recursive-put/{}'.format(
+ resource_test_dir, uuid.uuid4().hex)
+ session.put(tdir, remote_path_rec)
+ assert session.exists(remote_path_rec + "/d0/f2")
+ assert session.exists(remote_path_rec + "/d0/d2/f3")
+
# We can use a relative name for the target
basename_put_dir = os.path.join(resource_test_dir, "basename-put")
if not os.path.exists(basename_put_dir):
@@ -330,6 +340,14 @@ def check_methods(resource_test_dir):
result = session.isdir(test_dir)
assert result
+ # Check listdir() method
+ if hasattr(session, 'listdir'):
+ subdir = uuid.uuid4().hex
+ subfile = uuid.uuid4().hex
+ session.mkdir(os.path.join(test_dir, subdir))
+ session.put('/etc/hosts', os.path.join(test_dir, subfile))
+ assert set(session.listdir(test_dir)) == set((subdir, subfile))
+
# Check making parent dirs without setting flag
test_dir = '{}/tmp/i fail/{}'.format(resource_test_dir, uuid.uuid4().hex)
with pytest.raises(CommandError):
| ENH: recursive `get` for sessions (shell, ssh, etc) should support recursive mode of operation
It is necessary for any place where `get` is supposed to obtain a full hierarchy of directories like e.g. getting outputs of the job back to the local system.
I will send a follow up initial PR for the plain orchestrator to fetch everything not just failed subjobs logs | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"reproman/interface/tests/test_run.py::test_recursive_transfer"
] | [
"reproman/interface/tests/test_run.py::test_run_no_command[None]",
"reproman/interface/tests/test_run.py::test_run_no_command[[]]",
"reproman/interface/tests/test_run.py::test_run_no_resource",
"reproman/interface/tests/test_run.py::test_run_list[-expected0]",
"reproman/interface/tests/test_run.py::test_run_list[submitters-expected1]",
"reproman/interface/tests/test_run.py::test_run_list[orchestrators-expected2]",
"reproman/interface/tests/test_run.py::test_run_list[parameters-expected3]",
"reproman/interface/tests/test_run.py::test_combine_specs[empty]",
"reproman/interface/tests/test_run.py::test_combine_specs[exclusive]",
"reproman/interface/tests/test_run.py::test_combine_specs[simple-update]",
"reproman/interface/tests/test_run.py::test_combine_specs[mapping-to-atom]",
"reproman/interface/tests/test_run.py::test_combine_specs[atom-to-mapping]",
"reproman/interface/tests/test_run.py::test_combine_batch_params[empty]",
"reproman/interface/tests/test_run.py::test_combine_batch_params[one]",
"reproman/interface/tests/test_run.py::test_combine_batch_params[two,",
"reproman/interface/tests/test_run.py::test_combine_batch_params[two",
"reproman/interface/tests/test_run.py::test_combine_batch_params[=",
"reproman/interface/tests/test_run.py::test_combine_batch_params[spaces]",
"reproman/interface/tests/test_run.py::test_combine_batch_params_glob",
"reproman/interface/tests/test_run.py::test_combine_batch_params_repeat_key",
"reproman/interface/tests/test_run.py::test_combine_batch_params_no_equal",
"reproman/interface/tests/test_run.py::test_run_batch_spec_and_params",
"reproman/interface/tests/test_run.py::test_resolve_batch_params_eq[empty]",
"reproman/interface/tests/test_run.py::test_resolve_batch_params_eq[one]",
"reproman/interface/tests/test_run.py::test_resolve_batch_params_eq[two,",
"reproman/interface/tests/test_run.py::test_run_resource_specification",
"reproman/interface/tests/test_run.py::test_run_and_fetch",
"reproman/interface/tests/test_run.py::test_run_and_follow",
"reproman/interface/tests/test_run.py::test_run_and_follow_action[stop]",
"reproman/interface/tests/test_run.py::test_run_and_follow_action[stop-if-success]",
"reproman/interface/tests/test_run.py::test_run_and_follow_action[delete]",
"reproman/interface/tests/test_run.py::test_run_and_follow_action[delete-if-success]",
"reproman/interface/tests/test_run.py::test_jobs_auto_fetch_with_query",
"reproman/interface/tests/test_run.py::test_jobs_query_unknown",
"reproman/interface/tests/test_run.py::test_jobs_delete",
"reproman/interface/tests/test_run.py::test_jobs_show",
"reproman/interface/tests/test_run.py::test_jobs_unknown_action",
"reproman/interface/tests/test_run.py::test_jobs_ambig_id_match",
"reproman/interface/tests/test_run.py::test_jobs_deleted_resource",
"reproman/interface/tests/test_run.py::test_jobs_deleted_local_directory",
"reproman/interface/tests/test_run.py::test_jobs_orc_error",
"reproman/resource/tests/test_session.py::test_get_updated_env",
"reproman/resource/tests/test_session.py::test_get_local_session",
"reproman/resource/tests/test_session.py::test_session_class"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2020-08-19T20:26:32Z" | mit |
|
ResearchObject__ro-crate-py-100 | diff --git a/rocrate/model/metadata.py b/rocrate/model/metadata.py
index 711c0f1..7a4d85c 100644
--- a/rocrate/model/metadata.py
+++ b/rocrate/model/metadata.py
@@ -31,8 +31,15 @@ class Metadata(File):
BASENAME = "ro-crate-metadata.json"
PROFILE = "https://w3id.org/ro/crate/1.1"
- def __init__(self, crate):
- super().__init__(crate, None, self.BASENAME, False, None)
+ def __init__(self, crate, properties=None):
+ super().__init__(
+ crate,
+ source=None,
+ dest_path=self.BASENAME,
+ fetch_remote=False,
+ validate_url=False,
+ properties=properties
+ )
# https://www.researchobject.org/ro-crate/1.1/appendix/jsonld.html#extending-ro-crate
self.extra_terms = {}
@@ -88,3 +95,12 @@ TESTING_EXTRA_TERMS = {
"definition": "https://w3id.org/ro/terms/test#definition",
"engineVersion": "https://w3id.org/ro/terms/test#engineVersion"
}
+
+
+def metadata_class(descriptor_id):
+ if descriptor_id == Metadata.BASENAME:
+ return Metadata
+ elif descriptor_id == LegacyMetadata.BASENAME:
+ return LegacyMetadata
+ else:
+ return ValueError("Invalid metadata descriptor ID: {descriptor_id!r}")
diff --git a/rocrate/rocrate.py b/rocrate/rocrate.py
index af7a1cb..ebb8614 100644
--- a/rocrate/rocrate.py
+++ b/rocrate/rocrate.py
@@ -37,7 +37,7 @@ from .model.data_entity import DataEntity
from .model.file_or_dir import FileOrDir
from .model.file import File
from .model.dataset import Dataset
-from .model.metadata import Metadata, LegacyMetadata, TESTING_EXTRA_TERMS
+from .model.metadata import Metadata, LegacyMetadata, TESTING_EXTRA_TERMS, metadata_class
from .model.preview import Preview
from .model.testdefinition import TestDefinition
from .model.computationalworkflow import ComputationalWorkflow, galaxy_to_abstract_cwl
@@ -47,7 +47,7 @@ from .model.testservice import TestService, get_service
from .model.softwareapplication import SoftwareApplication, get_app, PLANEMO_DEFAULT_VERSION
from .model.testsuite import TestSuite
-from .utils import is_url, subclasses
+from .utils import is_url, subclasses, get_norm_value
def read_metadata(metadata_path):
@@ -67,6 +67,18 @@ def read_metadata(metadata_path):
return context, {_["@id"]: _ for _ in graph}
+def pick_type(json_entity, type_map, fallback=None):
+ try:
+ t = json_entity["@type"]
+ except KeyError:
+ raise ValueError(f'entity {json_entity["@id"]!r} has no @type')
+ types = {_.strip() for _ in set(t if isinstance(t, list) else [t])}
+ for name, c in type_map.items():
+ if name in types:
+ return c
+ return fallback
+
+
class ROCrate():
def __init__(self, source=None, gen_preview=False, init=False):
@@ -121,13 +133,10 @@ class ROCrate():
zf.extractall(zip_path)
source = Path(zip_path)
metadata_path = source / Metadata.BASENAME
- MetadataClass = Metadata
if not metadata_path.is_file():
metadata_path = source / LegacyMetadata.BASENAME
- MetadataClass = LegacyMetadata
if not metadata_path.is_file():
raise ValueError(f"Not a valid RO-Crate: missing {Metadata.BASENAME}")
- self.add(MetadataClass(self))
_, entities = read_metadata(metadata_path)
self.__read_data_entities(entities, source, gen_preview)
self.__read_contextual_entities(entities)
@@ -144,12 +153,11 @@ class ROCrate():
# First let's try conformsTo algorithm in
# <https://www.researchobject.org/ro-crate/1.1/root-data-entity.html#finding-the-root-data-entity>
for entity in entities.values():
- conformsTo = entity.get("conformsTo")
- if conformsTo and "@id" in conformsTo:
- conformsTo = conformsTo["@id"]
- if conformsTo and conformsTo.startswith("https://w3id.org/ro/crate/"):
- if "about" in entity:
- return (entity["@id"], entity["about"]["@id"])
+ about = get_norm_value(entity, "about")
+ if about:
+ for id_ in get_norm_value(entity, "conformsTo"):
+ if id_.startswith("https://w3id.org/ro/crate/"):
+ return(entity["@id"], about[0])
# ..fall back to a generous look up by filename,
for candidate in (
Metadata.BASENAME, LegacyMetadata.BASENAME,
@@ -175,7 +183,10 @@ class ROCrate():
def __read_data_entities(self, entities, source, gen_preview):
metadata_id, root_id = self.find_root_entity_id(entities)
- entities.pop(metadata_id) # added previously
+ MetadataClass = metadata_class(metadata_id)
+ metadata_properties = entities.pop(metadata_id)
+ self.add(MetadataClass(self, properties=metadata_properties))
+
root_entity = entities.pop(root_id)
assert root_id == root_entity.pop('@id')
parts = root_entity.pop('hasPart', [])
@@ -188,17 +199,7 @@ class ROCrate():
id_ = data_entity_ref['@id']
entity = entities.pop(id_)
assert id_ == entity.pop('@id')
- try:
- t = entity["@type"]
- except KeyError:
- raise ValueError(f'entity "{id_}" has no @type')
- types = {_.strip() for _ in set(t if isinstance(t, list) else [t])}
- # pick the most specific type (order guaranteed by subclasses)
- cls = DataEntity
- for name, c in type_map.items():
- if name in types:
- cls = c
- break
+ cls = pick_type(entity, type_map, fallback=DataEntity)
if cls is DataEntity:
instance = DataEntity(self, identifier=id_, properties=entity)
else:
@@ -212,10 +213,7 @@ class ROCrate():
type_map = {_.__name__: _ for _ in subclasses(ContextEntity)}
for identifier, entity in entities.items():
assert identifier == entity.pop('@id')
- # https://github.com/ResearchObject/ro-crate/issues/83
- if isinstance(entity['@type'], list):
- raise RuntimeError(f"multiple types for '{identifier}'")
- cls = type_map.get(entity['@type'], ContextEntity)
+ cls = pick_type(entity, type_map, fallback=ContextEntity)
self.add(cls(self, identifier, entity))
@property
diff --git a/rocrate/utils.py b/rocrate/utils.py
index 9cd22c5..40a2b14 100644
--- a/rocrate/utils.py
+++ b/rocrate/utils.py
@@ -65,3 +65,16 @@ def subclasses(cls):
for c in subclasses(d):
yield c
yield d
+
+
+def get_norm_value(json_entity, prop):
+ """\
+ Get a normalized value for a property (always as a list of strings).
+ """
+ value = json_entity.get(prop, [])
+ if not isinstance(value, list):
+ value = [value]
+ try:
+ return [_ if isinstance(_, str) else _["@id"] for _ in value]
+ except (TypeError, KeyError):
+ raise ValueError(f"Malformed value for {prop!r}: {json_entity.get(prop)!r}")
| ResearchObject/ro-crate-py | 8eab329b27faad0836bcff7f2c7a40c679340cc7 | diff --git a/test/test_read.py b/test/test_read.py
index ac173f1..b2fffe1 100644
--- a/test/test_read.py
+++ b/test/test_read.py
@@ -368,3 +368,65 @@ def test_generic_data_entity(tmpdir):
crate = ROCrate(out_crate_dir)
check_rc()
+
+
+def test_root_conformsto(tmpdir):
+ # actually not a valid workflow ro-crate, but here it does not matter
+ metadata = {
+ "@context": "https://w3id.org/ro/crate/1.1/context",
+ "@graph": [
+ {
+ "@id": "ro-crate-metadata.json",
+ "@type": "CreativeWork",
+ "about": {"@id": "./"},
+ "conformsTo": [
+ {"@id": "https://w3id.org/ro/crate/1.1"},
+ {"@id": "https://about.workflowhub.eu/Workflow-RO-Crate/"}
+ ]
+ },
+ {
+ "@id": "./",
+ "@type": "Dataset",
+ },
+ ]
+ }
+ crate_dir = tmpdir / "test_root_conformsto_crate"
+ crate_dir.mkdir()
+ with open(crate_dir / "ro-crate-metadata.json", "wt") as f:
+ json.dump(metadata, f, indent=4)
+ crate = ROCrate(crate_dir)
+ assert crate.metadata["conformsTo"] == [
+ "https://w3id.org/ro/crate/1.1",
+ "https://about.workflowhub.eu/Workflow-RO-Crate/"
+ ]
+
+
+def test_multi_type_context_entity(tmpdir):
+ id_, type_ = "#xyz", ["Project", "Organization"]
+ metadata = {
+ "@context": "https://w3id.org/ro/crate/1.1/context",
+ "@graph": [
+ {
+ "@id": "ro-crate-metadata.json",
+ "@type": "CreativeWork",
+ "about": {"@id": "./"},
+ "conformsTo": {"@id": "https://w3id.org/ro/crate/1.1"}
+ },
+ {
+ "@id": "./",
+ "@type": "Dataset",
+ },
+ {
+ "@id": id_,
+ "@type": type_,
+ }
+ ]
+ }
+ crate_dir = tmpdir / "test_multi_type_context_entity_crate"
+ crate_dir.mkdir()
+ with open(crate_dir / "ro-crate-metadata.json", "wt") as f:
+ json.dump(metadata, f, indent=4)
+ crate = ROCrate(crate_dir)
+ entity = crate.dereference(id_)
+ assert entity in crate.contextual_entities
+ assert set(entity.type) == set(type_)
diff --git a/test/test_utils.py b/test/test_utils.py
index e230d0f..ba220b9 100644
--- a/test/test_utils.py
+++ b/test/test_utils.py
@@ -15,7 +15,9 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-from rocrate.utils import subclasses
+import pytest
+
+from rocrate.utils import subclasses, get_norm_value
class Pet:
@@ -38,3 +40,15 @@ def test_subclasses():
pet_subclasses = list(subclasses(Pet))
assert set(pet_subclasses) == {Cat, Dog, Beagle}
assert pet_subclasses.index(Beagle) < pet_subclasses.index(Dog)
+
+
+def test_get_norm_value():
+ for value in {"@id": "foo"}, "foo", ["foo"], [{"@id": "foo"}]:
+ entity = {"@id": "#xyz", "name": value}
+ assert get_norm_value(entity, "name") == ["foo"]
+ for value in [{"@id": "foo"}, "bar"], ["foo", {"@id": "bar"}]:
+ entity = {"@id": "#xyz", "name": value}
+ assert get_norm_value(entity, "name") == ["foo", "bar"]
+ assert get_norm_value({"@id": "#xyz"}, "name") == []
+ with pytest.raises(ValueError):
+ get_norm_value({"@id": "#xyz", "name": [["foo"]]}, "name")
| Can't read recent WorkflowHub crates
Reported by @lrodrin and @jmfernandez at yesterday's community meeting. One such example is https://workflowhub.eu/workflows/244.
```pycon
>>> from rocrate.rocrate import ROCrate
>>> crate = ROCrate("/tmp/workflow-244-3")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/simleo/git/ro-crate-py/rocrate/rocrate.py", line 90, in __init__
source = self.__read(source, gen_preview=gen_preview)
File "/home/simleo/git/ro-crate-py/rocrate/rocrate.py", line 132, in __read
self.__read_data_entities(entities, source, gen_preview)
File "/home/simleo/git/ro-crate-py/rocrate/rocrate.py", line 177, in __read_data_entities
metadata_id, root_id = self.find_root_entity_id(entities)
File "/home/simleo/git/ro-crate-py/rocrate/rocrate.py", line 150, in find_root_entity_id
if conformsTo and conformsTo.startswith("https://w3id.org/ro/crate/"):
AttributeError: 'list' object has no attribute 'startswith'
``` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/test_read.py::test_crate_dir_loading[False-False]",
"test/test_read.py::test_crate_dir_loading[True-False]",
"test/test_read.py::test_crate_dir_loading[True-True]",
"test/test_read.py::test_legacy_crate",
"test/test_read.py::test_bad_crate",
"test/test_read.py::test_init[False]",
"test/test_read.py::test_init[True]",
"test/test_read.py::test_init_preview[False-False]",
"test/test_read.py::test_init_preview[False-True]",
"test/test_read.py::test_init_preview[True-False]",
"test/test_read.py::test_init_preview[True-True]",
"test/test_read.py::test_no_parts",
"test/test_read.py::test_extra_data[False]",
"test/test_read.py::test_extra_data[True]",
"test/test_read.py::test_missing_dir",
"test/test_read.py::test_missing_file",
"test/test_read.py::test_generic_data_entity",
"test/test_read.py::test_root_conformsto",
"test/test_read.py::test_multi_type_context_entity",
"test/test_utils.py::test_subclasses",
"test/test_utils.py::test_get_norm_value"
] | [] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2021-11-26T18:42:21Z" | apache-2.0 |
|
ResearchObject__ro-crate-py-102 | diff --git a/rocrate/model/entity.py b/rocrate/model/entity.py
index 826b564..77d5671 100644
--- a/rocrate/model/entity.py
+++ b/rocrate/model/entity.py
@@ -75,7 +75,7 @@ class Entity(MutableMapping):
def __getitem__(self, key):
v = self._jsonld[key]
- if isinstance(v, str) or key.startswith("@"):
+ if v is None or isinstance(v, str) or key.startswith("@"):
return v
values = v if isinstance(v, list) else [v]
deref_values = [self.crate.dereference(_["@id"], _["@id"]) for _ in values]
| ResearchObject/ro-crate-py | b8668904f18b6d4060d0b29406e2f04c95b6d2f9 | diff --git a/test/test_model.py b/test/test_model.py
index 57fad30..e71bda8 100644
--- a/test/test_model.py
+++ b/test/test_model.py
@@ -295,6 +295,7 @@ def test_entity_as_mapping(tmpdir, helpers):
"author": {"@id": orcid}},
{"@id": orcid,
"@type": "Person",
+ "name": None,
"givenName": "Josiah",
"familyName": "Carberry"}
]
@@ -305,18 +306,24 @@ def test_entity_as_mapping(tmpdir, helpers):
json.dump(metadata, f, indent=4)
crate = ROCrate(crate_dir)
person = crate.dereference(orcid)
- assert len(person) == 4
- assert len(list(person)) == 4
- assert set(person) == set(person.keys()) == {"@id", "@type", "givenName", "familyName"}
- assert set(person.values()) == {orcid, "Person", "Josiah", "Carberry"}
+ exp_len = len(metadata["@graph"][2])
+ assert len(person) == exp_len
+ assert len(list(person)) == exp_len
+ assert set(person) == set(person.keys()) == {"@id", "@type", "name", "givenName", "familyName"}
+ assert set(person.values()) == {orcid, "Person", None, "Josiah", "Carberry"}
assert set(person.items()) == set(zip(person.keys(), person.values()))
+ assert person.id == orcid
+ assert person.type == "Person"
+ assert person["name"] is None
+ assert person["givenName"] == "Josiah"
+ assert person["familyName"] == "Carberry"
assert person.setdefault("givenName", "foo") == "Josiah"
- assert len(person) == 4
+ assert len(person) == exp_len
assert person.setdefault("award", "Oscar") == "Oscar"
- assert len(person) == 5
+ assert len(person) == exp_len + 1
assert "award" in person
assert person.pop("award") == "Oscar"
- assert len(person) == 4
+ assert len(person) == exp_len
assert "award" not in person
for key in "@id", "@type":
with pytest.raises(KeyError):
@@ -326,8 +333,10 @@ def test_entity_as_mapping(tmpdir, helpers):
with pytest.raises(KeyError):
person.pop(key)
twin = Person(crate, orcid, properties={
+ "name": None,
"givenName": "Josiah",
"familyName": "Carberry"
})
assert twin == person
assert Person(crate, orcid) != person
+ assert crate.root_dataset["author"] is person
| Entity getitem breaks for null JSON values
Example:
```javascript
{
"@id": "sort-and-change-case.ga",
"@type": [
"File",
"SoftwareSourceCode",
"ComputationalWorkflow"
],
"programmingLanguage": {
"@id": "#galaxy"
},
"name": null
}
```
```pycon
>>> crate.mainEntity["name"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/simleo/git/ro-crate-py/rocrate/model/entity.py", line 81, in __getitem__
deref_values = [self.crate.dereference(_["@id"], _["@id"]) for _ in values]
File "/home/simleo/git/ro-crate-py/rocrate/model/entity.py", line 81, in <listcomp>
deref_values = [self.crate.dereference(_["@id"], _["@id"]) for _ in values]
TypeError: 'NoneType' object is not subscriptable
``` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/test_model.py::test_entity_as_mapping"
] | [
"test/test_model.py::test_dereferencing",
"test/test_model.py::test_dereferencing_equivalent_id[.foo]",
"test/test_model.py::test_dereferencing_equivalent_id[foo.]",
"test/test_model.py::test_dereferencing_equivalent_id[.foo/]",
"test/test_model.py::test_dereferencing_equivalent_id[foo./]",
"test/test_model.py::test_data_entities",
"test/test_model.py::test_remote_data_entities",
"test/test_model.py::test_bad_data_entities",
"test/test_model.py::test_contextual_entities",
"test/test_model.py::test_properties",
"test/test_model.py::test_uuid",
"test/test_model.py::test_update",
"test/test_model.py::test_delete",
"test/test_model.py::test_delete_refs",
"test/test_model.py::test_delete_by_id",
"test/test_model.py::test_self_delete"
] | {
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
} | "2021-11-27T10:16:55Z" | apache-2.0 |
|
ResearchObject__ro-crate-py-109 | diff --git a/rocrate/cli.py b/rocrate/cli.py
index 250a448..7d8dad7 100644
--- a/rocrate/cli.py
+++ b/rocrate/cli.py
@@ -120,7 +120,7 @@ def definition(state, suite, path, engine, engine_version):
@click.argument('dst', type=click.Path(writable=True))
@click.pass_obj
def write_zip(state, dst):
- crate = ROCrate(state.crate_dir, init=True, gen_preview=False)
+ crate = ROCrate(state.crate_dir, init=False, gen_preview=False)
crate.write_zip(dst)
| ResearchObject/ro-crate-py | 5f8f0e83c10018bdb161c6affc3f63eadc53bb08 | diff --git a/test/test_cli.py b/test/test_cli.py
index 31b701d..bcfe14f 100644
--- a/test/test_cli.py
+++ b/test/test_cli.py
@@ -21,6 +21,7 @@ from click.testing import CliRunner
from rocrate.cli import cli
from rocrate.model.metadata import TESTING_EXTRA_TERMS
+from rocrate.rocrate import ROCrate
@pytest.mark.parametrize("gen_preview,cwd", [(False, False), (False, True), (True, False), (True, True)])
@@ -137,6 +138,9 @@ def test_cli_write_zip(test_data_dir, monkeypatch, cwd):
crate_dir = test_data_dir / "ro-crate-galaxy-sortchangecase"
runner = CliRunner()
assert runner.invoke(cli, ["-c", str(crate_dir), "init"]).exit_code == 0
+ wf_path = crate_dir / "sort-and-change-case.ga"
+ args = ["-c", str(crate_dir), "add", "workflow", str(wf_path)]
+ assert runner.invoke(cli, args).exit_code == 0
output_zip_path = test_data_dir / "test-zip-archive.zip"
args = []
@@ -150,3 +154,6 @@ def test_cli_write_zip(test_data_dir, monkeypatch, cwd):
result = runner.invoke(cli, args)
assert result.exit_code == 0
assert output_zip_path.is_file()
+
+ crate = ROCrate(output_zip_path)
+ assert crate.mainEntity is not None
| write-zip CLI command reinitializes the crate
The `write-zip` CLI command reinitializes the crate, so any changes like adding a workflow or test suite are lost. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/test_cli.py::test_cli_write_zip[False]",
"test/test_cli.py::test_cli_write_zip[True]"
] | [
"test/test_cli.py::test_cli_init[False-False]",
"test/test_cli.py::test_cli_init[False-True]",
"test/test_cli.py::test_cli_init[True-False]",
"test/test_cli.py::test_cli_init[True-True]",
"test/test_cli.py::test_cli_add_workflow[False]",
"test/test_cli.py::test_cli_add_workflow[True]",
"test/test_cli.py::test_cli_add_test_metadata[False]",
"test/test_cli.py::test_cli_add_test_metadata[True]"
] | {
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false
} | "2022-02-04T16:28:44Z" | apache-2.0 |
|
ResearchObject__ro-crate-py-111 | diff --git a/rocrate/cli.py b/rocrate/cli.py
index 7d8dad7..a74ec90 100644
--- a/rocrate/cli.py
+++ b/rocrate/cli.py
@@ -23,6 +23,7 @@ from .rocrate import ROCrate
from .model.computerlanguage import LANG_MAP
from .model.testservice import SERVICE_MAP
from .model.softwareapplication import APP_MAP
+from .utils import is_url
LANG_CHOICES = list(LANG_MAP)
@@ -30,10 +31,31 @@ SERVICE_CHOICES = list(SERVICE_MAP)
ENGINE_CHOICES = list(APP_MAP)
+def add_hash(id_):
+ if id_ is None or id_.startswith("#") or is_url(id_):
+ return id_
+ return "#" + id_
+
+
class State:
pass
+class CSVParamType(click.ParamType):
+ name = "csv"
+
+ def convert(self, value, param, ctx):
+ if isinstance(value, (list, tuple, set, frozenset)):
+ return value
+ try:
+ return value.split(",") if value else []
+ except AttributeError:
+ self.fail(f"{value!r} is not splittable", param, ctx)
+
+
+CSV = CSVParamType()
+
+
@click.group()
@click.option('-c', '--crate-dir', type=click.Path())
@click.pass_context
@@ -44,9 +66,10 @@ def cli(ctx, crate_dir):
@cli.command()
@click.option('--gen-preview', is_flag=True)
[email protected]('-e', '--exclude', type=CSV)
@click.pass_obj
-def init(state, gen_preview):
- crate = ROCrate(state.crate_dir, init=True, gen_preview=gen_preview)
+def init(state, gen_preview, exclude):
+ crate = ROCrate(state.crate_dir, init=True, gen_preview=gen_preview, exclude=exclude)
crate.metadata.write(state.crate_dir)
if crate.preview:
crate.preview.write(state.crate_dir)
@@ -80,7 +103,7 @@ def workflow(state, path, language):
@click.option('-m', '--main-entity')
@click.pass_obj
def suite(state, identifier, name, main_entity):
- suite_ = state.crate.add_test_suite(identifier=identifier, name=name, main_entity=main_entity)
+ suite_ = state.crate.add_test_suite(identifier=add_hash(identifier), name=name, main_entity=main_entity)
state.crate.metadata.write(state.crate_dir)
print(suite_.id)
@@ -94,7 +117,10 @@ def suite(state, identifier, name, main_entity):
@click.option('-n', '--name')
@click.pass_obj
def instance(state, suite, url, resource, service, identifier, name):
- instance_ = state.crate.add_test_instance(suite, url, resource=resource, service=service, identifier=identifier, name=name)
+ instance_ = state.crate.add_test_instance(
+ add_hash(suite), url, resource=resource, service=service,
+ identifier=add_hash(identifier), name=name
+ )
state.crate.metadata.write(state.crate_dir)
print(instance_.id)
diff --git a/rocrate/rocrate.py b/rocrate/rocrate.py
index 8d5befc..95f55d4 100644
--- a/rocrate/rocrate.py
+++ b/rocrate/rocrate.py
@@ -19,7 +19,6 @@
import errno
import json
-import os
import uuid
import zipfile
import atexit
@@ -47,7 +46,7 @@ from .model.testservice import TestService, get_service
from .model.softwareapplication import SoftwareApplication, get_app, PLANEMO_DEFAULT_VERSION
from .model.testsuite import TestSuite
-from .utils import is_url, subclasses, get_norm_value
+from .utils import is_url, subclasses, get_norm_value, walk
def read_metadata(metadata_path):
@@ -81,7 +80,8 @@ def pick_type(json_entity, type_map, fallback=None):
class ROCrate():
- def __init__(self, source=None, gen_preview=False, init=False):
+ def __init__(self, source=None, gen_preview=False, init=False, exclude=None):
+ self.exclude = exclude
self.__entity_map = {}
self.default_entities = []
self.data_entities = []
@@ -108,7 +108,7 @@ class ROCrate():
if not top_dir.is_dir():
raise NotADirectoryError(errno.ENOTDIR, f"'{top_dir}': not a directory")
self.add(RootDataset(self), Metadata(self))
- for root, dirs, files in os.walk(top_dir):
+ for root, dirs, files in walk(top_dir, exclude=self.exclude):
root = Path(root)
for name in dirs:
source = root / name
@@ -453,7 +453,7 @@ class ROCrate():
# fetch all files defined in the crate
def _copy_unlisted(self, top, base_path):
- for root, dirs, files in os.walk(top):
+ for root, dirs, files in walk(top, exclude=self.exclude):
root = Path(root)
for name in dirs:
source = root / name
diff --git a/rocrate/utils.py b/rocrate/utils.py
index 2843f59..76507df 100644
--- a/rocrate/utils.py
+++ b/rocrate/utils.py
@@ -18,6 +18,7 @@
# limitations under the License.
import collections
+import os
from datetime import datetime, timezone
from urllib.parse import urlsplit
@@ -78,3 +79,12 @@ def get_norm_value(json_entity, prop):
return [_ if isinstance(_, str) else _["@id"] for _ in value]
except (TypeError, KeyError):
raise ValueError(f"Malformed value for {prop!r}: {json_entity.get(prop)!r}")
+
+
+def walk(top, topdown=True, onerror=None, followlinks=False, exclude=None):
+ exclude = frozenset(exclude or [])
+ for root, dirs, files in os.walk(top):
+ if exclude:
+ dirs[:] = [_ for _ in dirs if _ not in exclude]
+ files[:] = [_ for _ in files if _ not in exclude]
+ yield root, dirs, files
| ResearchObject/ro-crate-py | 043f7054c28d96128898435144049d1240ea6ea4 | diff --git a/test/test_cli.py b/test/test_cli.py
index bcfe14f..adcda3b 100644
--- a/test/test_cli.py
+++ b/test/test_cli.py
@@ -20,6 +20,7 @@ import pytest
from click.testing import CliRunner
from rocrate.cli import cli
+from rocrate.model.file import File
from rocrate.model.metadata import TESTING_EXTRA_TERMS
from rocrate.rocrate import ROCrate
@@ -53,6 +54,22 @@ def test_cli_init(test_data_dir, helpers, monkeypatch, cwd, gen_preview):
assert json_entities["sort-and-change-case.ga"]["@type"] == "File"
+def test_cli_init_exclude(test_data_dir, helpers):
+ crate_dir = test_data_dir / "ro-crate-galaxy-sortchangecase"
+ (crate_dir / helpers.METADATA_FILE_NAME).unlink()
+ exclude = "test,README.md"
+ runner = CliRunner()
+ args = ["-c", str(crate_dir), "init", "-e", exclude]
+ assert runner.invoke(cli, args).exit_code == 0
+ crate = ROCrate(crate_dir)
+ for p in "LICENSE", "sort-and-change-case.ga":
+ assert isinstance(crate.dereference(p), File)
+ for p in exclude.split(",") + ["test/"]:
+ assert not crate.dereference(p)
+ for e in crate.data_entities:
+ assert not(e.id.startswith("test"))
+
+
@pytest.mark.parametrize("cwd", [False, True])
def test_cli_add_workflow(test_data_dir, helpers, monkeypatch, cwd):
# init
@@ -94,7 +111,7 @@ def test_cli_add_test_metadata(test_data_dir, helpers, monkeypatch, cwd):
assert json_entities[def_id]["@type"] == "File"
# add workflow
wf_path = crate_dir / "sort-and-change-case.ga"
- runner.invoke(cli, ["-c", str(crate_dir), "add", "workflow", "-l", "galaxy", str(wf_path)]).exit_code == 0
+ assert runner.invoke(cli, ["-c", str(crate_dir), "add", "workflow", "-l", "galaxy", str(wf_path)]).exit_code == 0
# add test suite
result = runner.invoke(cli, ["-c", str(crate_dir), "add", "test-suite"])
assert result.exit_code == 0
@@ -133,6 +150,32 @@ def test_cli_add_test_metadata(test_data_dir, helpers, monkeypatch, cwd):
assert set(TESTING_EXTRA_TERMS.items()).issubset(extra_terms.items())
[email protected]("hash_", [False, True])
+def test_cli_add_test_metadata_explicit_ids(test_data_dir, helpers, monkeypatch, hash_):
+ crate_dir = test_data_dir / "ro-crate-galaxy-sortchangecase"
+ runner = CliRunner()
+ assert runner.invoke(cli, ["-c", str(crate_dir), "init"]).exit_code == 0
+ wf_path = crate_dir / "sort-and-change-case.ga"
+ assert runner.invoke(cli, ["-c", str(crate_dir), "add", "workflow", "-l", "galaxy", str(wf_path)]).exit_code == 0
+ suite_id = "#foo"
+ cli_suite_id = suite_id if hash_ else suite_id[1:]
+ result = runner.invoke(cli, ["-c", str(crate_dir), "add", "test-suite", "-i", cli_suite_id])
+ assert result.exit_code == 0
+ assert result.output.strip() == suite_id
+ json_entities = helpers.read_json_entities(crate_dir)
+ assert suite_id in json_entities
+ instance_id = "#bar"
+ cli_instance_id = instance_id if hash_ else instance_id[1:]
+ result = runner.invoke(
+ cli, ["-c", str(crate_dir), "add", "test-instance", cli_suite_id,
+ "http://example.com", "-r", "jobs", "-i", cli_instance_id]
+ )
+ assert result.exit_code == 0
+ assert result.output.strip() == instance_id
+ json_entities = helpers.read_json_entities(crate_dir)
+ assert instance_id in json_entities
+
+
@pytest.mark.parametrize("cwd", [False, True])
def test_cli_write_zip(test_data_dir, monkeypatch, cwd):
crate_dir = test_data_dir / "ro-crate-galaxy-sortchangecase"
diff --git a/test/test_read.py b/test/test_read.py
index ba948c8..323fb92 100644
--- a/test/test_read.py
+++ b/test/test_read.py
@@ -224,6 +224,29 @@ def test_init(test_data_dir, tmpdir, helpers, override):
assert f1.read() == f2.read()
+def test_exclude(test_data_dir, tmpdir, helpers):
+ def check(out=False):
+ for p in "LICENSE", "sort-and-change-case.ga":
+ assert isinstance(crate.dereference(p), File)
+ for p in exclude + ["test/"]:
+ assert not crate.dereference(p)
+ if out:
+ assert not(crate.source / p).exists()
+ for e in crate.data_entities:
+ assert not(e.id.startswith("test"))
+ if out:
+ assert not(crate.source / "test").exists()
+ crate_dir = test_data_dir / "ro-crate-galaxy-sortchangecase"
+ (crate_dir / helpers.METADATA_FILE_NAME).unlink()
+ exclude = ["test", "README.md"]
+ crate = ROCrate(crate_dir, init=True, exclude=exclude)
+ check()
+ out_path = tmpdir / 'ro_crate_out'
+ crate.write(out_path)
+ crate = ROCrate(out_path)
+ check(out=True)
+
+
@pytest.mark.parametrize("gen_preview,preview_exists", [(False, False), (False, True), (True, False), (True, True)])
def test_init_preview(test_data_dir, tmpdir, helpers, gen_preview, preview_exists):
crate_dir = test_data_dir / "ro-crate-galaxy-sortchangecase"
| Exclude option for crate init
It would be nice to support an `exclude` option to avoid considering certain sub-paths when initializing an RO-Crate from a directory tree, i.e., `ROCrate(source, init=True)`. For instance, from the command line, you might want to run:
```
rocrate init --exclude .git
```
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/test_cli.py::test_cli_init_exclude",
"test/test_cli.py::test_cli_add_test_metadata_explicit_ids[False]",
"test/test_read.py::test_exclude"
] | [
"test/test_cli.py::test_cli_init[False-False]",
"test/test_cli.py::test_cli_init[False-True]",
"test/test_cli.py::test_cli_init[True-False]",
"test/test_cli.py::test_cli_init[True-True]",
"test/test_cli.py::test_cli_add_workflow[False]",
"test/test_cli.py::test_cli_add_workflow[True]",
"test/test_cli.py::test_cli_add_test_metadata[False]",
"test/test_cli.py::test_cli_add_test_metadata[True]",
"test/test_cli.py::test_cli_add_test_metadata_explicit_ids[True]",
"test/test_cli.py::test_cli_write_zip[False]",
"test/test_cli.py::test_cli_write_zip[True]",
"test/test_read.py::test_crate_dir_loading[False-False]",
"test/test_read.py::test_crate_dir_loading[True-False]",
"test/test_read.py::test_crate_dir_loading[True-True]",
"test/test_read.py::test_legacy_crate",
"test/test_read.py::test_bad_crate",
"test/test_read.py::test_init[False]",
"test/test_read.py::test_init[True]",
"test/test_read.py::test_init_preview[False-False]",
"test/test_read.py::test_init_preview[False-True]",
"test/test_read.py::test_init_preview[True-False]",
"test/test_read.py::test_init_preview[True-True]",
"test/test_read.py::test_no_parts",
"test/test_read.py::test_extra_data[False]",
"test/test_read.py::test_extra_data[True]",
"test/test_read.py::test_missing_dir",
"test/test_read.py::test_missing_file",
"test/test_read.py::test_generic_data_entity",
"test/test_read.py::test_root_conformsto",
"test/test_read.py::test_multi_type_context_entity"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2022-03-09T13:48:46Z" | apache-2.0 |
|
ResearchObject__ro-crate-py-116 | diff --git a/rocrate/cli.py b/rocrate/cli.py
index a74ec90..38a20d0 100644
--- a/rocrate/cli.py
+++ b/rocrate/cli.py
@@ -54,58 +54,57 @@ class CSVParamType(click.ParamType):
CSV = CSVParamType()
+OPTION_CRATE_PATH = click.option('-c', '--crate-dir', type=click.Path(), default=os.getcwd)
@click.group()
[email protected]('-c', '--crate-dir', type=click.Path())
[email protected]_context
-def cli(ctx, crate_dir):
- ctx.obj = state = State()
- state.crate_dir = os.getcwd() if not crate_dir else os.path.abspath(crate_dir)
+def cli():
+ pass
@cli.command()
@click.option('--gen-preview', is_flag=True)
@click.option('-e', '--exclude', type=CSV)
[email protected]_obj
-def init(state, gen_preview, exclude):
- crate = ROCrate(state.crate_dir, init=True, gen_preview=gen_preview, exclude=exclude)
- crate.metadata.write(state.crate_dir)
+@OPTION_CRATE_PATH
+def init(crate_dir, gen_preview, exclude):
+ crate = ROCrate(crate_dir, init=True, gen_preview=gen_preview, exclude=exclude)
+ crate.metadata.write(crate_dir)
if crate.preview:
- crate.preview.write(state.crate_dir)
+ crate.preview.write(crate_dir)
@cli.group()
[email protected]_obj
-def add(state):
- state.crate = ROCrate(state.crate_dir, init=False, gen_preview=False)
+def add():
+ pass
@add.command()
@click.argument('path', type=click.Path(exists=True))
@click.option('-l', '--language', type=click.Choice(LANG_CHOICES), default="cwl")
[email protected]_obj
-def workflow(state, path, language):
+@OPTION_CRATE_PATH
+def workflow(crate_dir, path, language):
+ crate = ROCrate(crate_dir, init=False, gen_preview=False)
source = Path(path).resolve(strict=True)
try:
- dest_path = source.relative_to(state.crate_dir)
+ dest_path = source.relative_to(crate_dir)
except ValueError:
# For now, only support marking an existing file as a workflow
- raise ValueError(f"{source} is not in the crate dir {state.crate_dir}")
+ raise ValueError(f"{source} is not in the crate dir {crate_dir}")
# TODO: add command options for main and gen_cwl
- state.crate.add_workflow(source, dest_path, main=True, lang=language, gen_cwl=False)
- state.crate.metadata.write(state.crate_dir)
+ crate.add_workflow(source, dest_path, main=True, lang=language, gen_cwl=False)
+ crate.metadata.write(crate_dir)
@add.command(name="test-suite")
@click.option('-i', '--identifier')
@click.option('-n', '--name')
@click.option('-m', '--main-entity')
[email protected]_obj
-def suite(state, identifier, name, main_entity):
- suite_ = state.crate.add_test_suite(identifier=add_hash(identifier), name=name, main_entity=main_entity)
- state.crate.metadata.write(state.crate_dir)
- print(suite_.id)
+@OPTION_CRATE_PATH
+def suite(crate_dir, identifier, name, main_entity):
+ crate = ROCrate(crate_dir, init=False, gen_preview=False)
+ suite = crate.add_test_suite(identifier=add_hash(identifier), name=name, main_entity=main_entity)
+ crate.metadata.write(crate_dir)
+ print(suite.id)
@add.command(name="test-instance")
@@ -115,13 +114,14 @@ def suite(state, identifier, name, main_entity):
@click.option('-s', '--service', type=click.Choice(SERVICE_CHOICES), default="jenkins")
@click.option('-i', '--identifier')
@click.option('-n', '--name')
[email protected]_obj
-def instance(state, suite, url, resource, service, identifier, name):
- instance_ = state.crate.add_test_instance(
+@OPTION_CRATE_PATH
+def instance(crate_dir, suite, url, resource, service, identifier, name):
+ crate = ROCrate(crate_dir, init=False, gen_preview=False)
+ instance_ = crate.add_test_instance(
add_hash(suite), url, resource=resource, service=service,
identifier=add_hash(identifier), name=name
)
- state.crate.metadata.write(state.crate_dir)
+ crate.metadata.write(crate_dir)
print(instance_.id)
@@ -130,23 +130,24 @@ def instance(state, suite, url, resource, service, identifier, name):
@click.argument('path', type=click.Path(exists=True))
@click.option('-e', '--engine', type=click.Choice(ENGINE_CHOICES), default="planemo")
@click.option('-v', '--engine-version')
[email protected]_obj
-def definition(state, suite, path, engine, engine_version):
+@OPTION_CRATE_PATH
+def definition(crate_dir, suite, path, engine, engine_version):
+ crate = ROCrate(crate_dir, init=False, gen_preview=False)
source = Path(path).resolve(strict=True)
try:
- dest_path = source.relative_to(state.crate_dir)
+ dest_path = source.relative_to(crate_dir)
except ValueError:
# For now, only support marking an existing file as a test definition
- raise ValueError(f"{source} is not in the crate dir {state.crate_dir}")
- state.crate.add_test_definition(suite, source=source, dest_path=dest_path, engine=engine, engine_version=engine_version)
- state.crate.metadata.write(state.crate_dir)
+ raise ValueError(f"{source} is not in the crate dir {crate_dir}")
+ crate.add_test_definition(suite, source=source, dest_path=dest_path, engine=engine, engine_version=engine_version)
+ crate.metadata.write(crate_dir)
@cli.command()
@click.argument('dst', type=click.Path(writable=True))
[email protected]_obj
-def write_zip(state, dst):
- crate = ROCrate(state.crate_dir, init=False, gen_preview=False)
+@OPTION_CRATE_PATH
+def write_zip(crate_dir, dst):
+ crate = ROCrate(crate_dir, init=False, gen_preview=False)
crate.write_zip(dst)
| ResearchObject/ro-crate-py | aac1df6f5e5b4400696e485e709fe580d35b4e9e | diff --git a/test/test_cli.py b/test/test_cli.py
index adcda3b..0d9af09 100644
--- a/test/test_cli.py
+++ b/test/test_cli.py
@@ -14,10 +14,11 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
-
import json
-import pytest
+
+import click
from click.testing import CliRunner
+import pytest
from rocrate.cli import cli
from rocrate.model.file import File
@@ -25,6 +26,66 @@ from rocrate.model.metadata import TESTING_EXTRA_TERMS
from rocrate.rocrate import ROCrate
+def get_command_paths(command):
+ """\
+ Return a list of full command paths for all leaf commands that are part of
+ the given root command.
+
+ For example, for a root command that has two subcommands ``command_a`` and
+ ``command_b`` where ``command_b`` in turn has two subcommands, the
+ returned list will have the form::
+
+ [
+ ['command_a'],
+ ['command_b', 'subcommand_a'],
+ ['command_b', 'subcommand_b'],
+ ]
+
+ :param command: The root command.
+ :return: A list of lists, where each element is the full command path to a
+ leaf command.
+ """
+
+ def resolve_commands(command, command_path, commands):
+ if isinstance(command, click.MultiCommand):
+ for subcommand in command.commands.values():
+ command_subpath = command_path + [subcommand.name]
+ resolve_commands(subcommand, command_subpath, commands)
+ else:
+ commands.append(command_path)
+
+ commands = []
+ resolve_commands(command, [], commands)
+
+ return commands
+
+
[email protected]('command_path', get_command_paths(cli))
+def test_cli_help(command_path):
+ """\
+ Test that invoking any CLI command with ``--help`` prints the help string
+ and exits normally.
+
+ This is a regression test for:
+ https://github.com/ResearchObject/ro-crate-py/issues/97
+
+ Note that we cannot simply invoke the actual leaf :class:`click.Command`
+ that we are testing, because the test runner follows a different path then
+ when actually invoking the command from the command line. This means that
+ any code that is in the groups that the command is part of, won't be
+ executed. This in turn means that a command could actually be broken when
+ invoked from the command line but would not be detected by the test. The
+ workaround is to invoke the full command path. For example when testing
+ ``add workflow --help``, we cannot simply invoke ``workflow`` with
+ ``['--help']`` as argument but we need to invoke the base command with
+ ``['add', 'workflow', '--help']``.
+ """
+ runner = CliRunner()
+ result = runner.invoke(cli, command_path + ['--help'])
+ assert result.exit_code == 0, result.output
+ assert 'Usage:' in result.output
+
+
@pytest.mark.parametrize("gen_preview,cwd", [(False, False), (False, True), (True, False), (True, True)])
def test_cli_init(test_data_dir, helpers, monkeypatch, cwd, gen_preview):
crate_dir = test_data_dir / "ro-crate-galaxy-sortchangecase"
@@ -33,12 +94,11 @@ def test_cli_init(test_data_dir, helpers, monkeypatch, cwd, gen_preview):
metadata_path.unlink()
runner = CliRunner()
- args = []
+ args = ["init"]
if cwd:
monkeypatch.chdir(str(crate_dir))
else:
args.extend(["-c", str(crate_dir)])
- args.append("init")
if gen_preview:
args.append("--gen-preview")
result = runner.invoke(cli, args)
@@ -59,8 +119,9 @@ def test_cli_init_exclude(test_data_dir, helpers):
(crate_dir / helpers.METADATA_FILE_NAME).unlink()
exclude = "test,README.md"
runner = CliRunner()
- args = ["-c", str(crate_dir), "init", "-e", exclude]
- assert runner.invoke(cli, args).exit_code == 0
+ args = ["init", "-c", str(crate_dir), "-e", exclude]
+ result = runner.invoke(cli, args)
+ assert result.exit_code == 0
crate = ROCrate(crate_dir)
for p in "LICENSE", "sort-and-change-case.ga":
assert isinstance(crate.dereference(p), File)
@@ -75,20 +136,20 @@ def test_cli_add_workflow(test_data_dir, helpers, monkeypatch, cwd):
# init
crate_dir = test_data_dir / "ro-crate-galaxy-sortchangecase"
runner = CliRunner()
- assert runner.invoke(cli, ["-c", str(crate_dir), "init"]).exit_code == 0
+ assert runner.invoke(cli, ["init", "-c", str(crate_dir)]).exit_code == 0
json_entities = helpers.read_json_entities(crate_dir)
assert "sort-and-change-case.ga" in json_entities
assert json_entities["sort-and-change-case.ga"]["@type"] == "File"
# add
wf_path = crate_dir / "sort-and-change-case.ga"
- args = []
+ args = ["add", "workflow"]
if cwd:
monkeypatch.chdir(str(crate_dir))
wf_path = wf_path.relative_to(crate_dir)
else:
args.extend(["-c", str(crate_dir)])
for lang in "cwl", "galaxy":
- extra_args = ["add", "workflow", "-l", lang, str(wf_path)]
+ extra_args = ["-l", lang, str(wf_path)]
result = runner.invoke(cli, args + extra_args)
assert result.exit_code == 0
json_entities = helpers.read_json_entities(crate_dir)
@@ -104,35 +165,35 @@ def test_cli_add_test_metadata(test_data_dir, helpers, monkeypatch, cwd):
# init
crate_dir = test_data_dir / "ro-crate-galaxy-sortchangecase"
runner = CliRunner()
- assert runner.invoke(cli, ["-c", str(crate_dir), "init"]).exit_code == 0
+ assert runner.invoke(cli, ["init", "-c", str(crate_dir)]).exit_code == 0
json_entities = helpers.read_json_entities(crate_dir)
def_id = "test/test1/sort-and-change-case-test.yml"
assert def_id in json_entities
assert json_entities[def_id]["@type"] == "File"
# add workflow
wf_path = crate_dir / "sort-and-change-case.ga"
- assert runner.invoke(cli, ["-c", str(crate_dir), "add", "workflow", "-l", "galaxy", str(wf_path)]).exit_code == 0
+ assert runner.invoke(cli, ["add", "workflow", "-c", str(crate_dir), "-l", "galaxy", str(wf_path)]).exit_code == 0
# add test suite
- result = runner.invoke(cli, ["-c", str(crate_dir), "add", "test-suite"])
+ result = runner.invoke(cli, ["add", "test-suite", "-c", str(crate_dir)])
assert result.exit_code == 0
suite_id = result.output.strip()
json_entities = helpers.read_json_entities(crate_dir)
assert suite_id in json_entities
# add test instance
- result = runner.invoke(cli, ["-c", str(crate_dir), "add", "test-instance", suite_id, "http://example.com", "-r", "jobs"])
+ result = runner.invoke(cli, ["add", "test-instance", "-c", str(crate_dir), suite_id, "http://example.com", "-r", "jobs"])
assert result.exit_code == 0
instance_id = result.output.strip()
json_entities = helpers.read_json_entities(crate_dir)
assert instance_id in json_entities
# add test definition
def_path = crate_dir / def_id
- args = []
+ args = ["add", "test-definition"]
if cwd:
monkeypatch.chdir(str(crate_dir))
def_path = def_path.relative_to(crate_dir)
else:
args.extend(["-c", str(crate_dir)])
- extra_args = ["add", "test-definition", "-e", "planemo", "-v", ">=0.70", suite_id, str(def_path)]
+ extra_args = ["-e", "planemo", "-v", ">=0.70", suite_id, str(def_path)]
result = runner.invoke(cli, args + extra_args)
assert result.exit_code == 0
json_entities = helpers.read_json_entities(crate_dir)
@@ -154,22 +215,22 @@ def test_cli_add_test_metadata(test_data_dir, helpers, monkeypatch, cwd):
def test_cli_add_test_metadata_explicit_ids(test_data_dir, helpers, monkeypatch, hash_):
crate_dir = test_data_dir / "ro-crate-galaxy-sortchangecase"
runner = CliRunner()
- assert runner.invoke(cli, ["-c", str(crate_dir), "init"]).exit_code == 0
+ assert runner.invoke(cli, ["init", "-c", str(crate_dir)]).exit_code == 0
wf_path = crate_dir / "sort-and-change-case.ga"
- assert runner.invoke(cli, ["-c", str(crate_dir), "add", "workflow", "-l", "galaxy", str(wf_path)]).exit_code == 0
+ assert runner.invoke(cli, ["add", "workflow", "-c", str(crate_dir), "-l", "galaxy", str(wf_path)]).exit_code == 0
suite_id = "#foo"
cli_suite_id = suite_id if hash_ else suite_id[1:]
- result = runner.invoke(cli, ["-c", str(crate_dir), "add", "test-suite", "-i", cli_suite_id])
+ result = runner.invoke(cli, ["add", "test-suite", "-c", str(crate_dir), "-i", cli_suite_id])
assert result.exit_code == 0
assert result.output.strip() == suite_id
json_entities = helpers.read_json_entities(crate_dir)
assert suite_id in json_entities
instance_id = "#bar"
cli_instance_id = instance_id if hash_ else instance_id[1:]
- result = runner.invoke(
- cli, ["-c", str(crate_dir), "add", "test-instance", cli_suite_id,
- "http://example.com", "-r", "jobs", "-i", cli_instance_id]
- )
+ args = [
+ "add", "test-instance", cli_suite_id, "http://example.com", "-c", str(crate_dir), "-r", "jobs", "-i", cli_instance_id
+ ]
+ result = runner.invoke(cli, args)
assert result.exit_code == 0
assert result.output.strip() == instance_id
json_entities = helpers.read_json_entities(crate_dir)
@@ -180,18 +241,17 @@ def test_cli_add_test_metadata_explicit_ids(test_data_dir, helpers, monkeypatch,
def test_cli_write_zip(test_data_dir, monkeypatch, cwd):
crate_dir = test_data_dir / "ro-crate-galaxy-sortchangecase"
runner = CliRunner()
- assert runner.invoke(cli, ["-c", str(crate_dir), "init"]).exit_code == 0
+ assert runner.invoke(cli, ["init", "-c", str(crate_dir)]).exit_code == 0
wf_path = crate_dir / "sort-and-change-case.ga"
- args = ["-c", str(crate_dir), "add", "workflow", str(wf_path)]
+ args = ["add", "workflow", str(wf_path), "-c", str(crate_dir)]
assert runner.invoke(cli, args).exit_code == 0
output_zip_path = test_data_dir / "test-zip-archive.zip"
- args = []
+ args = ["write-zip"]
if cwd:
monkeypatch.chdir(str(crate_dir))
else:
args.extend(["-c", str(crate_dir)])
- args.append("write-zip")
args.append(str(output_zip_path))
result = runner.invoke(cli, args)
| CLI can generate an error when command help is requested
In a non-ro-crate dir:
```console
$ rocrate add workflow --help
Traceback (most recent call last):
File "/home/simleo/git/ro-crate-py/venv/bin/rocrate", line 11, in <module>
load_entry_point('rocrate==0.5.0', 'console_scripts', 'rocrate')()
File "/home/simleo/git/ro-crate-py/venv/lib/python3.6/site-packages/click/core.py", line 1128, in __call__
return self.main(*args, **kwargs)
File "/home/simleo/git/ro-crate-py/venv/lib/python3.6/site-packages/click/core.py", line 1053, in main
rv = self.invoke(ctx)
File "/home/simleo/git/ro-crate-py/venv/lib/python3.6/site-packages/click/core.py", line 1659, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/home/simleo/git/ro-crate-py/venv/lib/python3.6/site-packages/click/core.py", line 1656, in invoke
super().invoke(ctx)
File "/home/simleo/git/ro-crate-py/venv/lib/python3.6/site-packages/click/core.py", line 1395, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/home/simleo/git/ro-crate-py/venv/lib/python3.6/site-packages/click/core.py", line 754, in invoke
return __callback(*args, **kwargs)
File "/home/simleo/git/ro-crate-py/venv/lib/python3.6/site-packages/click/decorators.py", line 38, in new_func
return f(get_current_context().obj, *args, **kwargs)
File "/home/simleo/git/ro-crate-py/venv/lib/python3.6/site-packages/rocrate/cli.py", line 58, in add
state.crate = ROCrate(state.crate_dir, init=False, gen_preview=False)
File "/home/simleo/git/ro-crate-py/venv/lib/python3.6/site-packages/rocrate/rocrate.py", line 90, in __init__
source = self.__read(source, gen_preview=gen_preview)
File "/home/simleo/git/ro-crate-py/venv/lib/python3.6/site-packages/rocrate/rocrate.py", line 129, in __read
raise ValueError(f"Not a valid RO-Crate: missing {Metadata.BASENAME}")
ValueError: Not a valid RO-Crate: missing ro-crate-metadata.json
```
This should not happen, since the user is not actually trying to do anything ro-crate specific. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/test_cli.py::test_cli_help[command_path1]",
"test/test_cli.py::test_cli_help[command_path2]",
"test/test_cli.py::test_cli_help[command_path3]",
"test/test_cli.py::test_cli_help[command_path4]",
"test/test_cli.py::test_cli_init[False-False]",
"test/test_cli.py::test_cli_init[True-False]",
"test/test_cli.py::test_cli_init_exclude",
"test/test_cli.py::test_cli_add_workflow[False]",
"test/test_cli.py::test_cli_add_workflow[True]",
"test/test_cli.py::test_cli_add_test_metadata[False]",
"test/test_cli.py::test_cli_add_test_metadata[True]",
"test/test_cli.py::test_cli_add_test_metadata_explicit_ids[False]",
"test/test_cli.py::test_cli_add_test_metadata_explicit_ids[True]",
"test/test_cli.py::test_cli_write_zip[False]",
"test/test_cli.py::test_cli_write_zip[True]"
] | [
"test/test_cli.py::test_cli_help[command_path0]",
"test/test_cli.py::test_cli_help[command_path5]",
"test/test_cli.py::test_cli_init[False-True]",
"test/test_cli.py::test_cli_init[True-True]"
] | {
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
} | "2022-03-24T13:53:53Z" | apache-2.0 |
|
ResearchObject__ro-crate-py-126 | diff --git a/rocrate/rocrate.py b/rocrate/rocrate.py
index 8ed15de..c0fa0b8 100644
--- a/rocrate/rocrate.py
+++ b/rocrate/rocrate.py
@@ -151,8 +151,8 @@ class ROCrate():
root = entities[metadata["about"]["@id"]]
except (KeyError, TypeError):
raise ValueError("metadata descriptor does not reference the root entity")
- if root["@type"] != "Dataset":
- raise ValueError('root entity must be of type "Dataset"')
+ if ("Dataset" not in root["@type"] if isinstance(root["@type"], list) else root["@type"] != "Dataset"):
+ raise ValueError('root entity must have "Dataset" among its types')
return metadata["@id"], root["@id"]
def find_root_entity_id(self, entities):
| ResearchObject/ro-crate-py | 9c010654dce2b8cd9ca4e99dd73885439885e4fc | diff --git a/test/test_read.py b/test/test_read.py
index e3f2820..6497a76 100644
--- a/test/test_read.py
+++ b/test/test_read.py
@@ -530,7 +530,7 @@ def test_find_root_bad_entities():
# root type is not Dataset
entities = deepcopy(orig_entities)
entities["./"]["@type"] = "Thing"
- with pytest.raises(ValueError, match="must be of type"):
+ with pytest.raises(ValueError, match="must have"):
crate.find_root_entity_id(entities)
@@ -599,3 +599,30 @@ def test_find_root_multiple_entries():
mod_entities = deepcopy(orig_entities)
mod_entities["http://example.com/"]["@type"] = "Thing"
check_finds_org(mod_entities)
+
+
+def test_find_root_multiple_types():
+ entities = {_["@id"]: _ for _ in [
+ {
+ "@id": "ro-crate-metadata.json",
+ "@type": "CreativeWork",
+ "about": {"@id": "./"},
+ "conformsTo": {"@id": "https://w3id.org/ro/crate/1.1"},
+ },
+ {
+ "@id": "./",
+ "@type": ["Dataset", "RepositoryCollection"],
+ },
+ ]}
+ crate = ROCrate()
+ m_id, r_id = crate.find_root_entity_id(entities)
+ assert m_id == "ro-crate-metadata.json"
+ assert r_id == "./"
+ # "Dataset" not included
+ del entities["./"]["@type"][0]
+ with pytest.raises(ValueError):
+ crate.find_root_entity_id(entities)
+ # Check we're not trying to be too clever
+ entities["./"]["@type"] = "NotADataset"
+ with pytest.raises(ValueError):
+ crate.find_root_entity_id(entities)
| Allow root dataset to have more than one type
Fails if root dataset has an array as a value for @type
eg. @type = ['Dataset', 'RepositoryCollection']
Note: @ptsefton says: Can we always code defensively, please.
https://github.com/ResearchObject/ro-crate-py/blob/9c010654dce2b8cd9ca4e99dd73885439885e4fc/rocrate/rocrate.py#L154 | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/test_read.py::test_find_root_bad_entities",
"test/test_read.py::test_find_root_multiple_types"
] | [
"test/test_read.py::test_crate_dir_loading[False-False]",
"test/test_read.py::test_crate_dir_loading[True-False]",
"test/test_read.py::test_crate_dir_loading[True-True]",
"test/test_read.py::test_legacy_crate",
"test/test_read.py::test_bad_crate",
"test/test_read.py::test_init[False]",
"test/test_read.py::test_init[True]",
"test/test_read.py::test_exclude",
"test/test_read.py::test_init_preview[False-False]",
"test/test_read.py::test_init_preview[False-True]",
"test/test_read.py::test_init_preview[True-False]",
"test/test_read.py::test_init_preview[True-True]",
"test/test_read.py::test_no_parts",
"test/test_read.py::test_extra_data[False]",
"test/test_read.py::test_extra_data[True]",
"test/test_read.py::test_missing_dir",
"test/test_read.py::test_missing_file",
"test/test_read.py::test_generic_data_entity",
"test/test_read.py::test_root_conformsto",
"test/test_read.py::test_multi_type_context_entity",
"test/test_read.py::test_find_root[-ro-crate-metadata.json]",
"test/test_read.py::test_find_root[-ro-crate-metadata.jsonld]",
"test/test_read.py::test_find_root[https://example.org/crate/-ro-crate-metadata.json]",
"test/test_read.py::test_find_root[https://example.org/crate/-ro-crate-metadata.jsonld]",
"test/test_read.py::test_find_root[-bad-name.json]",
"test/test_read.py::test_find_root_multiple_entries"
] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
} | "2022-05-18T12:56:59Z" | apache-2.0 |
|
ResearchObject__ro-crate-py-136 | diff --git a/rocrate/model/dataset.py b/rocrate/model/dataset.py
index f883a02..b378ea3 100644
--- a/rocrate/model/dataset.py
+++ b/rocrate/model/dataset.py
@@ -18,6 +18,8 @@
# See the License for the specific language governing permissions and
# limitations under the License.
+import errno
+import os
import shutil
from pathlib import Path
from urllib.request import urlopen
@@ -48,9 +50,16 @@ class Dataset(FileOrDir):
if self.fetch_remote:
self.__get_parts(out_path)
else:
- out_path.mkdir(parents=True, exist_ok=True)
- if not self.crate.source and self.source and Path(self.source).exists():
- self.crate._copy_unlisted(self.source, out_path)
+ if self.source is None:
+ out_path.mkdir(parents=True, exist_ok=True)
+ else:
+ if not Path(self.source).exists():
+ raise FileNotFoundError(
+ errno.ENOENT, os.strerror(errno.ENOENT), str(self.source)
+ )
+ out_path.mkdir(parents=True, exist_ok=True)
+ if not self.crate.source:
+ self.crate._copy_unlisted(self.source, out_path)
def __get_parts(self, out_path):
out_path.mkdir(parents=True, exist_ok=True)
diff --git a/rocrate/model/file.py b/rocrate/model/file.py
index 263677d..6ea48db 100644
--- a/rocrate/model/file.py
+++ b/rocrate/model/file.py
@@ -18,10 +18,10 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-import os
from pathlib import Path
import shutil
import urllib.request
+import warnings
from http.client import HTTPResponse
from io import BytesIO, StringIO
@@ -59,7 +59,10 @@ class File(FileOrDir):
if self.fetch_remote:
out_file_path.parent.mkdir(parents=True, exist_ok=True)
urllib.request.urlretrieve(response.url, out_file_path)
- elif os.path.isfile(self.source):
+ elif self.source is None:
+ # Allows to record a File entity whose @id does not exist, see #73
+ warnings.warn(f"No source for {self.id}")
+ else:
out_file_path.parent.mkdir(parents=True, exist_ok=True)
if not out_file_path.exists() or not out_file_path.samefile(self.source):
shutil.copy(self.source, out_file_path)
| ResearchObject/ro-crate-py | 7380019e81cf3ab4fcffe9292737fff580674142 | diff --git a/test/test_read.py b/test/test_read.py
index edb1d9f..df50801 100644
--- a/test/test_read.py
+++ b/test/test_read.py
@@ -320,10 +320,27 @@ def test_missing_dir(test_data_dir, tmpdir):
assert examples_dataset.id == f'{name}/'
out_path = tmpdir / 'crate_read_out'
+ with pytest.raises(OSError):
+ crate.write(out_path)
+
+ # Two options to get a writable crate
+
+ # 1. Set the source to None (will create an empty dir)
+ examples_dataset.source = None
+ crate.write(out_path)
+ assert (out_path / name).is_dir()
+
+ shutil.rmtree(out_path)
+
+ # 2. Provide an existing source
+ source = tmpdir / "source"
+ source.mkdir()
+ examples_dataset.source = source
crate.write(out_path)
- assert not (out_path / 'README.txt').exists()
+ assert (out_path / name).is_dir()
[email protected]("ignore")
def test_missing_file(test_data_dir, tmpdir):
crate_dir = test_data_dir / 'read_crate'
name = 'test_file_galaxy.txt'
@@ -335,9 +352,26 @@ def test_missing_file(test_data_dir, tmpdir):
assert test_file.id == name
out_path = tmpdir / 'crate_read_out'
+ with pytest.raises(OSError):
+ crate.write(out_path)
+
+ # Two options to get a writable crate
+
+ # 1. Set the source to None (file will still be missing in the copy)
+ test_file.source = None
crate.write(out_path)
assert not (out_path / name).exists()
+ shutil.rmtree(out_path)
+
+ # 2. Provide an existing source
+ source = tmpdir / "source.txt"
+ text = "foo\nbar\n"
+ source.write_text(text)
+ test_file.source = source
+ crate.write(out_path)
+ assert (out_path / name).read_text() == text
+
def test_generic_data_entity(tmpdir):
rc_id = "#collection"
diff --git a/test/test_write.py b/test/test_write.py
index b806ae5..15a5244 100644
--- a/test/test_write.py
+++ b/test/test_write.py
@@ -301,23 +301,36 @@ def test_remote_uri_exceptions(tmpdir):
# no error on Windows, or on Linux as root, so we don't use pytest.raises
[email protected]("fetch_remote,validate_url", [(False, False), (False, True), (True, False), (True, True)])
-def test_missing_source(test_data_dir, tmpdir, fetch_remote, validate_url):
[email protected]("ignore")
[email protected]("what", ["file", "dataset"])
+def test_missing_source(test_data_dir, tmpdir, what):
path = test_data_dir / uuid.uuid4().hex
- args = {"fetch_remote": fetch_remote, "validate_url": validate_url}
crate = ROCrate()
- file_ = crate.add_file(path, **args)
- assert file_ is crate.dereference(path.name)
- out_path = tmpdir / 'ro_crate_out_1'
- crate.write(out_path)
- assert not (out_path / path.name).exists()
+ entity = getattr(crate, f"add_{what}")(path)
+ assert entity is crate.dereference(path.name)
+ crate_dir = tmpdir / 'ro_crate_out_1'
+ with pytest.raises(OSError):
+ crate.write(crate_dir)
crate = ROCrate()
- file_ = crate.add_file(path, path.name, **args)
- assert file_ is crate.dereference(path.name)
- out_path = tmpdir / 'ro_crate_out_2'
- assert not (out_path / path.name).exists()
+ entity = getattr(crate, f"add_{what}")(path, path.name)
+ assert entity is crate.dereference(path.name)
+ crate_dir = tmpdir / 'ro_crate_out_2'
+ with pytest.raises(OSError):
+ crate.write(crate_dir)
+
+ crate = ROCrate()
+ entity = getattr(crate, f"add_{what}")(None, path.name)
+ assert entity is crate.dereference(path.name)
+ crate_dir = tmpdir / 'ro_crate_out_3'
+ crate.write(crate_dir)
+ out_path = crate_dir / path.name
+ if what == "file":
+ assert not out_path.exists()
+ else:
+ assert out_path.is_dir()
+ assert not any(out_path.iterdir())
@pytest.mark.parametrize("fetch_remote,validate_url", [(False, False), (False, True), (True, False), (True, True)])
@@ -336,12 +349,15 @@ def test_no_source_no_dest(test_data_dir, fetch_remote, validate_url):
def test_dataset(test_data_dir, tmpdir):
crate = ROCrate()
- path = test_data_dir / "a" / "b"
- d1 = crate.add_dataset(path)
+ path_a_b = test_data_dir / "a" / "b"
+ path_c = test_data_dir / "c"
+ for p in path_a_b, path_c:
+ p.mkdir(parents=True)
+ d1 = crate.add_dataset(path_a_b)
assert crate.dereference("b") is d1
- d2 = crate.add_dataset(path, "a/b")
+ d2 = crate.add_dataset(path_a_b, "a/b")
assert crate.dereference("a/b") is d2
- d_from_str = crate.add_dataset(str(test_data_dir / "c"))
+ d_from_str = crate.add_dataset(str(path_c))
assert crate.dereference("c") is d_from_str
out_path = tmpdir / 'ro_crate_out'
| Fix behavior wrt "missing" data entities
After the merge of #75, we allow data entities whose `@id` does not map to an existing file or directory, even if local. While this adds flexibility for use cases like #73, such crates are not supported by other libraries. Specifically, I got reports of crates generated with ro-crate-py that lead to errors when submission to WorkflowHub is attempted. The main issue is that it's too easy to add a "missing" data entity:
```python
crate.add_file("/this/does/not/exist") # Adds a File entity with @id = "exist"
```
This means it can be done involuntarily, by simply mistyping the path. It should be harder to do so (advanced usage), and we should issue a warning when it's done. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/test_read.py::test_missing_dir",
"test/test_read.py::test_missing_file",
"test/test_write.py::test_missing_source[file]",
"test/test_write.py::test_missing_source[dataset]"
] | [
"test/test_read.py::test_crate_dir_loading[False-False]",
"test/test_read.py::test_crate_dir_loading[True-False]",
"test/test_read.py::test_crate_dir_loading[True-True]",
"test/test_read.py::test_legacy_crate",
"test/test_read.py::test_bad_crate",
"test/test_read.py::test_init[False]",
"test/test_read.py::test_init[True]",
"test/test_read.py::test_exclude",
"test/test_read.py::test_init_preview[False-False]",
"test/test_read.py::test_init_preview[False-True]",
"test/test_read.py::test_init_preview[True-False]",
"test/test_read.py::test_init_preview[True-True]",
"test/test_read.py::test_no_parts",
"test/test_read.py::test_extra_data[False]",
"test/test_read.py::test_extra_data[True]",
"test/test_read.py::test_generic_data_entity",
"test/test_read.py::test_root_conformsto",
"test/test_read.py::test_multi_type_context_entity",
"test/test_write.py::test_file_writing[False-False]",
"test/test_write.py::test_file_writing[False-True]",
"test/test_write.py::test_file_writing[True-False]",
"test/test_write.py::test_file_writing[True-True]",
"test/test_write.py::test_in_mem_stream[BytesIO]",
"test/test_write.py::test_in_mem_stream[StringIO]",
"test/test_write.py::test_remote_uri[False-False-False]",
"test/test_write.py::test_remote_uri[False-False-True]",
"test/test_write.py::test_remote_uri[False-True-False]",
"test/test_write.py::test_remote_uri[False-True-True]",
"test/test_write.py::test_remote_uri[True-False-False]",
"test/test_write.py::test_remote_uri[True-False-True]",
"test/test_write.py::test_remote_uri[True-True-False]",
"test/test_write.py::test_remote_uri[True-True-True]",
"test/test_write.py::test_file_uri",
"test/test_write.py::test_looks_like_file_uri",
"test/test_write.py::test_ftp_uri[False]",
"test/test_write.py::test_remote_dir[False-False]",
"test/test_write.py::test_remote_dir[False-True]",
"test/test_write.py::test_remote_dir[True-False]",
"test/test_write.py::test_remote_dir[True-True]",
"test/test_write.py::test_remote_uri_exceptions",
"test/test_write.py::test_stringio_no_dest[False-False]",
"test/test_write.py::test_stringio_no_dest[False-True]",
"test/test_write.py::test_stringio_no_dest[True-False]",
"test/test_write.py::test_stringio_no_dest[True-True]",
"test/test_write.py::test_no_source_no_dest[False-False]",
"test/test_write.py::test_no_source_no_dest[False-True]",
"test/test_write.py::test_no_source_no_dest[True-False]",
"test/test_write.py::test_no_source_no_dest[True-True]",
"test/test_write.py::test_dataset",
"test/test_write.py::test_no_parts",
"test/test_write.py::test_no_zip_in_zip"
] | {
"failed_lite_validators": [
"has_issue_reference",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2022-09-19T10:43:23Z" | apache-2.0 |
|
ResearchObject__ro-crate-py-152 | diff --git a/rocrate/model/softwareapplication.py b/rocrate/model/softwareapplication.py
index c7bc8a5..29d8b2b 100644
--- a/rocrate/model/softwareapplication.py
+++ b/rocrate/model/softwareapplication.py
@@ -54,7 +54,6 @@ class SoftwareApplication(ContextEntity, CreativeWork):
PLANEMO_ID = "https://w3id.org/ro/terms/test#PlanemoEngine"
-PLANEMO_DEFAULT_VERSION = "0.74"
def planemo(crate):
diff --git a/rocrate/rocrate.py b/rocrate/rocrate.py
index 76f9105..02c57f8 100644
--- a/rocrate/rocrate.py
+++ b/rocrate/rocrate.py
@@ -42,7 +42,7 @@ from .model.computationalworkflow import ComputationalWorkflow, WorkflowDescript
from .model.computerlanguage import ComputerLanguage, get_lang
from .model.testinstance import TestInstance
from .model.testservice import TestService, get_service
-from .model.softwareapplication import SoftwareApplication, get_app, PLANEMO_DEFAULT_VERSION
+from .model.softwareapplication import SoftwareApplication, get_app
from .model.testsuite import TestSuite
from .utils import is_url, subclasses, get_norm_value, walk
@@ -509,9 +509,6 @@ class ROCrate():
self, suite, source=None, dest_path=None, fetch_remote=False, validate_url=False, properties=None,
engine="planemo", engine_version=None
):
- if engine_version is None:
- # FIXME: this should be engine-specific
- engine_version = PLANEMO_DEFAULT_VERSION
suite = self.__validate_suite(suite)
definition = self.add(
TestDefinition(self, source=source, dest_path=dest_path, fetch_remote=fetch_remote,
@@ -523,7 +520,8 @@ class ROCrate():
engine = get_app(self, engine)
self.add(engine)
definition.engine = engine
- definition.engineVersion = engine_version
+ if engine_version is not None:
+ definition.engineVersion = engine_version
suite.definition = definition
self.metadata.extra_terms.update(TESTING_EXTRA_TERMS)
return definition
| ResearchObject/ro-crate-py | f5281c1c583b1b66bcd8e05e0953635519ba5b2f | diff --git a/test/test_test_metadata.py b/test/test_test_metadata.py
index 219baa4..6ba584d 100644
--- a/test/test_test_metadata.py
+++ b/test/test_test_metadata.py
@@ -243,6 +243,8 @@ def test_add_test_definition(test_data_dir, engine, engine_version):
assert crate.dereference(PLANEMO) is d.engine
if engine_version:
assert d.engineVersion == engine_version
+ else:
+ assert "engineVersion" not in d
def test_test_suites_prop(test_data_dir):
| Remove software version defaults
E.g., [`PLANEMO_DEFAULT_VERSION = "0.74"`](https://github.com/ResearchObject/ro-crate-py/blob/81d74b3c40241235229500d30b4747a392c65a0b/rocrate/model/softwareapplication.py#L57). No info is better than arbitrary (thus likely wrong) info. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/test_test_metadata.py::test_add_test_definition[None-None]",
"test/test_test_metadata.py::test_add_test_definition[planemo-None]"
] | [
"test/test_test_metadata.py::test_read",
"test/test_test_metadata.py::test_create",
"test/test_test_metadata.py::test_add_test_suite",
"test/test_test_metadata.py::test_add_test_instance",
"test/test_test_metadata.py::test_add_test_definition[planemo->=0.70]",
"test/test_test_metadata.py::test_test_suites_prop"
] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2023-05-30T09:55:09Z" | apache-2.0 |
|
ResearchObject__ro-crate-py-155 | diff --git a/rocrate/metadata.py b/rocrate/metadata.py
index 98e4583..e37c111 100644
--- a/rocrate/metadata.py
+++ b/rocrate/metadata.py
@@ -19,7 +19,7 @@
import json
import warnings
-from .model.metadata import Metadata, LegacyMetadata
+from .model import Metadata, LegacyMetadata
def read_metadata(metadata_path):
diff --git a/rocrate/model/__init__.py b/rocrate/model/__init__.py
index 2e3ad6b..ec4376d 100644
--- a/rocrate/model/__init__.py
+++ b/rocrate/model/__init__.py
@@ -24,3 +24,46 @@ in rocrate_ represented as different Python classes.
.. _rocrate: https://w3id.org/ro/crate/
"""
+
+from .computationalworkflow import ComputationalWorkflow, WorkflowDescription, Workflow
+from .computerlanguage import ComputerLanguage
+from .contextentity import ContextEntity
+from .creativework import CreativeWork
+from .data_entity import DataEntity
+from .dataset import Dataset
+from .entity import Entity
+from .file import File
+from .file_or_dir import FileOrDir
+from .metadata import Metadata, LegacyMetadata
+from .person import Person
+from .root_dataset import RootDataset
+from .softwareapplication import SoftwareApplication
+from .testdefinition import TestDefinition
+from .testinstance import TestInstance
+from .preview import Preview
+from .testservice import TestService
+from .testsuite import TestSuite
+
+__all__ = [
+ "ComputationalWorkflow",
+ "ComputerLanguage",
+ "ContextEntity",
+ "CreativeWork",
+ "DataEntity",
+ "Dataset",
+ "Entity",
+ "File",
+ "FileOrDir",
+ "LegacyMetadata",
+ "Metadata",
+ "Person",
+ "Preview",
+ "RootDataset",
+ "SoftwareApplication",
+ "TestDefinition",
+ "TestInstance",
+ "TestService",
+ "TestSuite",
+ "Workflow",
+ "WorkflowDescription",
+]
diff --git a/rocrate/rocrate.py b/rocrate/rocrate.py
index 02c57f8..98ec74b 100644
--- a/rocrate/rocrate.py
+++ b/rocrate/rocrate.py
@@ -28,22 +28,31 @@ from collections import OrderedDict
from pathlib import Path
from urllib.parse import urljoin
-from .model.contextentity import ContextEntity
-from .model.entity import Entity
-from .model.root_dataset import RootDataset
-from .model.data_entity import DataEntity
-from .model.file_or_dir import FileOrDir
-from .model.file import File
-from .model.dataset import Dataset
-from .model.metadata import WORKFLOW_PROFILE, Metadata, LegacyMetadata, TESTING_EXTRA_TERMS, metadata_class
-from .model.preview import Preview
-from .model.testdefinition import TestDefinition
-from .model.computationalworkflow import ComputationalWorkflow, WorkflowDescription, galaxy_to_abstract_cwl
-from .model.computerlanguage import ComputerLanguage, get_lang
-from .model.testinstance import TestInstance
-from .model.testservice import TestService, get_service
-from .model.softwareapplication import SoftwareApplication, get_app
-from .model.testsuite import TestSuite
+from .model import (
+ ComputationalWorkflow,
+ ComputerLanguage,
+ ContextEntity,
+ DataEntity,
+ Dataset,
+ Entity,
+ File,
+ FileOrDir,
+ LegacyMetadata,
+ Metadata,
+ Preview,
+ RootDataset,
+ SoftwareApplication,
+ TestDefinition,
+ TestInstance,
+ TestService,
+ TestSuite,
+ WorkflowDescription,
+)
+from .model.metadata import WORKFLOW_PROFILE, TESTING_EXTRA_TERMS, metadata_class
+from .model.computationalworkflow import galaxy_to_abstract_cwl
+from .model.computerlanguage import get_lang
+from .model.testservice import get_service
+from .model.softwareapplication import get_app
from .utils import is_url, subclasses, get_norm_value, walk
from .metadata import read_metadata, find_root_entity_id
| ResearchObject/ro-crate-py | a2cea76db4959471395afd5d766018bc05727d09 | diff --git a/test/test_cli.py b/test/test_cli.py
index 4781fcd..de2aa23 100644
--- a/test/test_cli.py
+++ b/test/test_cli.py
@@ -22,7 +22,7 @@ from click.testing import CliRunner
import pytest
from rocrate.cli import cli
-from rocrate.model.file import File
+from rocrate.model import File
from rocrate.model.metadata import TESTING_EXTRA_TERMS
from rocrate.rocrate import ROCrate
diff --git a/test/test_model.py b/test/test_model.py
index 184b1ef..c9ec981 100644
--- a/test/test_model.py
+++ b/test/test_model.py
@@ -26,13 +26,15 @@ from pathlib import Path
import pytest
from rocrate.rocrate import ROCrate
-from rocrate.model.data_entity import DataEntity
-from rocrate.model.file import File
-from rocrate.model.dataset import Dataset
-from rocrate.model.computationalworkflow import ComputationalWorkflow
-from rocrate.model.person import Person
-from rocrate.model.preview import Preview
-from rocrate.model.contextentity import ContextEntity
+from rocrate.model import (
+ DataEntity,
+ File,
+ Dataset,
+ ComputationalWorkflow,
+ Person,
+ Preview,
+ ContextEntity
+)
RAW_REPO_URL = "https://raw.githubusercontent.com/ResearchObject/ro-crate-py"
diff --git a/test/test_read.py b/test/test_read.py
index 57adc45..c7843f7 100644
--- a/test/test_read.py
+++ b/test/test_read.py
@@ -24,9 +24,7 @@ import zipfile
from pathlib import Path
from rocrate.rocrate import ROCrate
-from rocrate.model.data_entity import DataEntity
-from rocrate.model.file import File
-from rocrate.model.dataset import Dataset
+from rocrate.model import DataEntity, File, Dataset
_URL = ('https://raw.githubusercontent.com/ResearchObject/ro-crate-py/master/'
'test/test-data/sample_file.txt')
diff --git a/test/test_test_metadata.py b/test/test_test_metadata.py
index 6ba584d..f698490 100644
--- a/test/test_test_metadata.py
+++ b/test/test_test_metadata.py
@@ -19,12 +19,14 @@
import pytest
from rocrate.rocrate import ROCrate
-from rocrate.model.testservice import TestService
-from rocrate.model.testinstance import TestInstance
-from rocrate.model.testdefinition import TestDefinition
-from rocrate.model.testsuite import TestSuite
-from rocrate.model.softwareapplication import SoftwareApplication
-from rocrate.model.computationalworkflow import ComputationalWorkflow
+from rocrate.model import (
+ TestService,
+ TestInstance,
+ TestDefinition,
+ TestSuite,
+ SoftwareApplication,
+ ComputationalWorkflow,
+)
# Tell pytest these are not test classes (so it doesn't try to collect them)
TestService.__test__ = False
diff --git a/test/test_write.py b/test/test_write.py
index b2f264e..10f0ec3 100644
--- a/test/test_write.py
+++ b/test/test_write.py
@@ -24,8 +24,7 @@ import zipfile
from itertools import product
from urllib.error import URLError
-from rocrate.model.dataset import Dataset
-from rocrate.model.person import Person
+from rocrate.model import Dataset, Person
from rocrate.rocrate import ROCrate
| Export entities/models in `rocrate.model.__init__`
Hi,
Would it be possible to simplify the imports of ro-crate-py, import/exporting entities like `Person`, `ContextEntity`, `Metadata`, etc, from the `__init__.py` file?
So that instead of having to write
```
from rocrate.model.person import Person
from rocrate.model.contextentity import ContextEntity
from rocrate.model.metadata import Metadata
```
one can do just
```
from rocrate.model import Person, ContextEntity, Metadata
```
Cheers,
Bruno | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/test_cli.py::test_cli_help[command_path0]",
"test/test_cli.py::test_cli_help[command_path1]",
"test/test_cli.py::test_cli_help[command_path2]",
"test/test_cli.py::test_cli_help[command_path3]",
"test/test_cli.py::test_cli_help[command_path4]",
"test/test_cli.py::test_cli_help[command_path5]",
"test/test_cli.py::test_cli_init[False-False]",
"test/test_cli.py::test_cli_init[False-True]",
"test/test_cli.py::test_cli_init[True-False]",
"test/test_cli.py::test_cli_init[True-True]",
"test/test_cli.py::test_cli_init_exclude",
"test/test_cli.py::test_cli_add_workflow[False]",
"test/test_cli.py::test_cli_add_workflow[True]",
"test/test_cli.py::test_cli_add_test_metadata[False]",
"test/test_cli.py::test_cli_add_test_metadata[True]",
"test/test_cli.py::test_cli_add_test_metadata_explicit_ids[False]",
"test/test_cli.py::test_cli_add_test_metadata_explicit_ids[True]",
"test/test_cli.py::test_cli_write_zip[False]",
"test/test_cli.py::test_cli_write_zip[True]",
"test/test_model.py::test_dereferencing",
"test/test_model.py::test_dereferencing_equivalent_id[.foo]",
"test/test_model.py::test_dereferencing_equivalent_id[foo.]",
"test/test_model.py::test_dereferencing_equivalent_id[.foo/]",
"test/test_model.py::test_dereferencing_equivalent_id[foo./]",
"test/test_model.py::test_data_entities",
"test/test_model.py::test_data_entities_perf",
"test/test_model.py::test_remote_data_entities",
"test/test_model.py::test_bad_data_entities",
"test/test_model.py::test_contextual_entities",
"test/test_model.py::test_contextual_entities_hash",
"test/test_model.py::test_properties",
"test/test_model.py::test_uuid",
"test/test_model.py::test_update",
"test/test_model.py::test_delete",
"test/test_model.py::test_delete_refs",
"test/test_model.py::test_delete_by_id",
"test/test_model.py::test_self_delete",
"test/test_model.py::test_entity_as_mapping",
"test/test_model.py::test_wf_types",
"test/test_model.py::test_append_to[False]",
"test/test_model.py::test_append_to[True]",
"test/test_read.py::test_crate_dir_loading[False-False]",
"test/test_read.py::test_crate_dir_loading[True-False]",
"test/test_read.py::test_crate_dir_loading[True-True]",
"test/test_read.py::test_legacy_crate",
"test/test_read.py::test_bad_crate",
"test/test_read.py::test_init[False]",
"test/test_read.py::test_init[True]",
"test/test_read.py::test_exclude",
"test/test_read.py::test_init_preview[False-False]",
"test/test_read.py::test_init_preview[False-True]",
"test/test_read.py::test_init_preview[True-False]",
"test/test_read.py::test_init_preview[True-True]",
"test/test_read.py::test_no_parts",
"test/test_read.py::test_extra_data[False]",
"test/test_read.py::test_extra_data[True]",
"test/test_read.py::test_missing_dir",
"test/test_read.py::test_missing_file",
"test/test_read.py::test_generic_data_entity",
"test/test_read.py::test_root_conformsto",
"test/test_read.py::test_multi_type_context_entity",
"test/test_test_metadata.py::test_read",
"test/test_test_metadata.py::test_create",
"test/test_test_metadata.py::test_add_test_suite",
"test/test_test_metadata.py::test_add_test_instance",
"test/test_test_metadata.py::test_add_test_definition[None-None]",
"test/test_test_metadata.py::test_add_test_definition[planemo-None]",
"test/test_test_metadata.py::test_add_test_definition[planemo->=0.70]",
"test/test_test_metadata.py::test_test_suites_prop",
"test/test_write.py::test_file_writing[False-False]",
"test/test_write.py::test_file_writing[False-True]",
"test/test_write.py::test_file_writing[True-False]",
"test/test_write.py::test_file_writing[True-True]",
"test/test_write.py::test_in_mem_stream[BytesIO]",
"test/test_write.py::test_in_mem_stream[StringIO]",
"test/test_write.py::test_remote_uri[False-False-False]",
"test/test_write.py::test_remote_uri[False-False-True]",
"test/test_write.py::test_remote_uri[False-True-False]",
"test/test_write.py::test_remote_uri[False-True-True]",
"test/test_write.py::test_remote_uri[True-False-False]",
"test/test_write.py::test_remote_uri[True-False-True]",
"test/test_write.py::test_remote_uri[True-True-False]",
"test/test_write.py::test_remote_uri[True-True-True]",
"test/test_write.py::test_file_uri",
"test/test_write.py::test_looks_like_file_uri",
"test/test_write.py::test_ftp_uri[False]",
"test/test_write.py::test_remote_dir[False-False]",
"test/test_write.py::test_remote_dir[False-True]",
"test/test_write.py::test_remote_dir[True-False]",
"test/test_write.py::test_remote_dir[True-True]",
"test/test_write.py::test_remote_uri_exceptions",
"test/test_write.py::test_missing_source[file]",
"test/test_write.py::test_missing_source[dataset]",
"test/test_write.py::test_stringio_no_dest[False-False]",
"test/test_write.py::test_stringio_no_dest[False-True]",
"test/test_write.py::test_stringio_no_dest[True-False]",
"test/test_write.py::test_stringio_no_dest[True-True]",
"test/test_write.py::test_no_source_no_dest[False-False]",
"test/test_write.py::test_no_source_no_dest[False-True]",
"test/test_write.py::test_no_source_no_dest[True-False]",
"test/test_write.py::test_no_source_no_dest[True-True]",
"test/test_write.py::test_dataset",
"test/test_write.py::test_no_parts",
"test/test_write.py::test_no_zip_in_zip",
"test/test_write.py::test_add_tree"
] | [] | {
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2023-07-28T15:51:29Z" | apache-2.0 |
|
ResearchObject__ro-crate-py-161 | diff --git a/rocrate/rocrate.py b/rocrate/rocrate.py
index d6b12a6..57bcd39 100644
--- a/rocrate/rocrate.py
+++ b/rocrate/rocrate.py
@@ -147,10 +147,16 @@ class ROCrate():
preview_entity = entities.pop(Preview.BASENAME, None)
if preview_entity and not gen_preview:
self.add(Preview(self, source / Preview.BASENAME, properties=preview_entity))
+ self.__add_parts(parts, entities, source)
+
+ def __add_parts(self, parts, entities, source):
type_map = OrderedDict((_.__name__, _) for _ in subclasses(FileOrDir))
for data_entity_ref in parts:
id_ = data_entity_ref['@id']
- entity = entities.pop(id_)
+ try:
+ entity = entities.pop(id_)
+ except KeyError:
+ continue
assert id_ == entity.pop('@id')
cls = pick_type(entity, type_map, fallback=DataEntity)
if cls is DataEntity:
@@ -161,6 +167,7 @@ class ROCrate():
else:
instance = cls(self, source / id_, id_, properties=entity)
self.add(instance)
+ self.__add_parts(entity.get("hasPart", []), entities, source)
def __read_contextual_entities(self, entities):
type_map = {_.__name__: _ for _ in subclasses(ContextEntity)}
| ResearchObject/ro-crate-py | dc3f75b0d0390dedbf9a830b6325b76dba468f1f | diff --git a/test/test_read.py b/test/test_read.py
index c7843f7..9aa3e96 100644
--- a/test/test_read.py
+++ b/test/test_read.py
@@ -484,3 +484,53 @@ def test_multi_type_context_entity(tmpdir):
entity = crate.dereference(id_)
assert entity in crate.contextual_entities
assert set(entity.type) == set(type_)
+
+
+def test_indirect_data_entity(tmpdir):
+ metadata = {
+ "@context": "https://w3id.org/ro/crate/1.1/context",
+ "@graph": [
+ {
+ "@id": "ro-crate-metadata.json",
+ "@type": "CreativeWork",
+ "about": {"@id": "./"},
+ "conformsTo": {"@id": "https://w3id.org/ro/crate/1.1"}
+ },
+ {
+ "@id": "./",
+ "@type": "Dataset",
+ "hasPart": [{"@id": "d1"}]
+ },
+ {
+ "@id": "d1",
+ "@type": "Dataset",
+ "hasPart": [{"@id": "d1/d2"}]
+ },
+ {
+ "@id": "d1/d2",
+ "@type": "Dataset",
+ "hasPart": [{"@id": "d1/d2/f1"}]
+ },
+ {
+ "@id": "d1/d2/f1",
+ "@type": "File"
+ }
+ ]
+ }
+ crate_dir = tmpdir / "test_indirect_data_entity"
+ crate_dir.mkdir()
+ with open(crate_dir / "ro-crate-metadata.json", "wt") as f:
+ json.dump(metadata, f, indent=4)
+ d1 = crate_dir / "d1"
+ d1.mkdir()
+ d2 = d1 / "d2"
+ d2.mkdir()
+ f1 = d2 / "f1"
+ f1.touch()
+ crate = ROCrate(crate_dir)
+ d1_e = crate.dereference("d1")
+ assert d1_e
+ assert d1_e in crate.data_entities
+ d2_e = crate.dereference("d1/d2")
+ assert d2_e
+ assert d2_e in crate.data_entities
| Support indirect data entity linking from root
Currently we detect data entities only if they are *directly* linked to from the root data entity:
```json
{
"@id": "./",
"@type": "Dataset",
"hasPart": [
{"@id": "spam"},
{"@id": "spam/foo.txt"}
]
},
{
"@id": "spam",
"@type": "Dataset",
"hasPart": [
{"@id": "spam/foo.txt"}
]
},
{
"@id": "spam/foo.txt",
"@type": "File"
}
```
We should also support indirect linking as specified [in the specs](https://www.researchobject.org/ro-crate/1.1/data-entities.html#referencing-files-and-folders-from-the-root-data-entity). In the above example, for instance, we should treat `spam/foo.txt` as a data entity even if it wasn't listed in the root data entity's `hasPart`. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/test_read.py::test_indirect_data_entity"
] | [
"test/test_read.py::test_crate_dir_loading[False-False]",
"test/test_read.py::test_crate_dir_loading[True-False]",
"test/test_read.py::test_crate_dir_loading[True-True]",
"test/test_read.py::test_legacy_crate",
"test/test_read.py::test_bad_crate",
"test/test_read.py::test_init[False]",
"test/test_read.py::test_init[True]",
"test/test_read.py::test_exclude",
"test/test_read.py::test_init_preview[False-False]",
"test/test_read.py::test_init_preview[False-True]",
"test/test_read.py::test_init_preview[True-False]",
"test/test_read.py::test_init_preview[True-True]",
"test/test_read.py::test_no_parts",
"test/test_read.py::test_extra_data[False]",
"test/test_read.py::test_extra_data[True]",
"test/test_read.py::test_missing_dir",
"test/test_read.py::test_missing_file",
"test/test_read.py::test_generic_data_entity",
"test/test_read.py::test_root_conformsto",
"test/test_read.py::test_multi_type_context_entity"
] | {
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
} | "2023-09-22T08:39:16Z" | apache-2.0 |
|
ResearchObject__ro-crate-py-163 | diff --git a/rocrate/rocrate.py b/rocrate/rocrate.py
index 57bcd39..5d5a98d 100644
--- a/rocrate/rocrate.py
+++ b/rocrate/rocrate.py
@@ -142,7 +142,7 @@ class ROCrate():
root_entity = entities.pop(root_id)
assert root_id == root_entity.pop('@id')
- parts = root_entity.pop('hasPart', [])
+ parts = as_list(root_entity.pop('hasPart', []))
self.add(RootDataset(self, root_id, properties=root_entity))
preview_entity = entities.pop(Preview.BASENAME, None)
if preview_entity and not gen_preview:
@@ -167,7 +167,7 @@ class ROCrate():
else:
instance = cls(self, source / id_, id_, properties=entity)
self.add(instance)
- self.__add_parts(entity.get("hasPart", []), entities, source)
+ self.__add_parts(as_list(entity.get("hasPart", [])), entities, source)
def __read_contextual_entities(self, entities):
type_map = {_.__name__: _ for _ in subclasses(ContextEntity)}
| ResearchObject/ro-crate-py | b3e24baaff92636dc58d910f6f1103d4f86a4c31 | diff --git a/test/test_read.py b/test/test_read.py
index 9aa3e96..43bf328 100644
--- a/test/test_read.py
+++ b/test/test_read.py
@@ -499,17 +499,17 @@ def test_indirect_data_entity(tmpdir):
{
"@id": "./",
"@type": "Dataset",
- "hasPart": [{"@id": "d1"}]
+ "hasPart": {"@id": "d1"}
},
{
"@id": "d1",
"@type": "Dataset",
- "hasPart": [{"@id": "d1/d2"}]
+ "hasPart": {"@id": "d1/d2"}
},
{
"@id": "d1/d2",
"@type": "Dataset",
- "hasPart": [{"@id": "d1/d2/f1"}]
+ "hasPart": {"@id": "d1/d2/f1"}
},
{
"@id": "d1/d2/f1",
| hasPart property on root dataset is assumed to be an array
Loading this dataset causes an error as the hasPart value is not an array but the code assumes it will be :
```json
{
"@id": "./",
"@type": "Dataset",
"hasPart": {"@id": "spam/foo.txt"}
},
{
"@id": "spam/foo.txt",
"@type": "File"
}
```
This line is the culprit: https://github.com/ResearchObject/ro-crate-py/blob/dc3f75b0d0390dedbf9a830b6325b76dba468f1f/rocrate/rocrate.py#L145C1-L146C1
parts = root_entity.pop('hasPart', [])
I added this to my copy make it work but not sure if you have a general purpose way of doing this in this library:
if not isinstance(parts, list):
parts = [parts]
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/test_read.py::test_indirect_data_entity"
] | [
"test/test_read.py::test_crate_dir_loading[False-False]",
"test/test_read.py::test_crate_dir_loading[True-False]",
"test/test_read.py::test_crate_dir_loading[True-True]",
"test/test_read.py::test_legacy_crate",
"test/test_read.py::test_bad_crate",
"test/test_read.py::test_init[False]",
"test/test_read.py::test_init[True]",
"test/test_read.py::test_exclude",
"test/test_read.py::test_init_preview[False-False]",
"test/test_read.py::test_init_preview[False-True]",
"test/test_read.py::test_init_preview[True-False]",
"test/test_read.py::test_init_preview[True-True]",
"test/test_read.py::test_no_parts",
"test/test_read.py::test_extra_data[False]",
"test/test_read.py::test_extra_data[True]",
"test/test_read.py::test_missing_dir",
"test/test_read.py::test_missing_file",
"test/test_read.py::test_generic_data_entity",
"test/test_read.py::test_root_conformsto",
"test/test_read.py::test_multi_type_context_entity"
] | {
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
} | "2023-09-22T12:33:15Z" | apache-2.0 |
|
ResearchObject__ro-crate-py-166 | diff --git a/rocrate/rocrate.py b/rocrate/rocrate.py
index 5d5a98d..d3041a1 100644
--- a/rocrate/rocrate.py
+++ b/rocrate/rocrate.py
@@ -75,9 +75,6 @@ class ROCrate():
def __init__(self, source=None, gen_preview=False, init=False, exclude=None):
self.exclude = exclude
self.__entity_map = {}
- self.default_entities = []
- self.data_entities = []
- self.contextual_entities = []
# TODO: add this as @base in the context? At least when loading
# from zip
self.uuid = uuid.uuid4()
@@ -136,14 +133,14 @@ class ROCrate():
def __read_data_entities(self, entities, source, gen_preview):
metadata_id, root_id = find_root_entity_id(entities)
- MetadataClass = metadata_class(metadata_id)
- metadata_properties = entities.pop(metadata_id)
- self.add(MetadataClass(self, metadata_id, properties=metadata_properties))
-
root_entity = entities.pop(root_id)
assert root_id == root_entity.pop('@id')
parts = as_list(root_entity.pop('hasPart', []))
self.add(RootDataset(self, root_id, properties=root_entity))
+ MetadataClass = metadata_class(metadata_id)
+ metadata_properties = entities.pop(metadata_id)
+ self.add(MetadataClass(self, metadata_id, properties=metadata_properties))
+
preview_entity = entities.pop(Preview.BASENAME, None)
if preview_entity and not gen_preview:
self.add(Preview(self, source / Preview.BASENAME, properties=preview_entity))
@@ -176,6 +173,23 @@ class ROCrate():
cls = pick_type(entity, type_map, fallback=ContextEntity)
self.add(cls(self, identifier, entity))
+ @property
+ def default_entities(self):
+ return [e for e in self.__entity_map.values()
+ if isinstance(e, (RootDataset, Metadata, LegacyMetadata, Preview))]
+
+ @property
+ def data_entities(self):
+ return [e for e in self.__entity_map.values()
+ if not isinstance(e, (RootDataset, Metadata, LegacyMetadata, Preview))
+ and hasattr(e, "write")]
+
+ @property
+ def contextual_entities(self):
+ return [e for e in self.__entity_map.values()
+ if not isinstance(e, (RootDataset, Metadata, LegacyMetadata, Preview))
+ and not hasattr(e, "write")]
+
@property
def name(self):
return self.root_dataset.get('name')
@@ -379,18 +393,13 @@ class ROCrate():
key = e.canonical_id()
if isinstance(e, RootDataset):
self.root_dataset = e
- if isinstance(e, (Metadata, LegacyMetadata)):
+ elif isinstance(e, (Metadata, LegacyMetadata)):
self.metadata = e
- if isinstance(e, Preview):
+ elif isinstance(e, Preview):
self.preview = e
- if isinstance(e, (RootDataset, Metadata, LegacyMetadata, Preview)):
- self.default_entities.append(e)
elif hasattr(e, "write"):
- self.data_entities.append(e)
if key not in self.__entity_map:
self.root_dataset.append_to("hasPart", e)
- else:
- self.contextual_entities.append(e)
self.__entity_map[key] = e
return entities[0] if len(entities) == 1 else entities
@@ -412,21 +421,11 @@ class ROCrate():
if e is self.metadata:
raise ValueError("cannot delete the metadata entity")
if e is self.preview:
- self.default_entities.remove(e)
self.preview = None
elif hasattr(e, "write"):
- try:
- self.data_entities.remove(e)
- except ValueError:
- pass
self.root_dataset["hasPart"] = [_ for _ in self.root_dataset.get("hasPart", []) if _ != e]
if not self.root_dataset["hasPart"]:
del self.root_dataset._jsonld["hasPart"]
- else:
- try:
- self.contextual_entities.remove(e)
- except ValueError:
- pass
self.__entity_map.pop(e.canonical_id(), None)
def _copy_unlisted(self, top, base_path):
| ResearchObject/ro-crate-py | 0d3c63946d2a0ab5aeaa5f3bc228db76455c80f8 | diff --git a/test/test_model.py b/test/test_model.py
index 0324d90..e7b5343 100644
--- a/test/test_model.py
+++ b/test/test_model.py
@@ -475,3 +475,33 @@ def test_context(helpers):
crate.metadata.extra_terms[k] = v
jsonld = crate.metadata.generate()
assert jsonld["@context"] == [base_context, wfrun_ctx, {k: v}]
+
+
+def test_add_no_duplicates(test_data_dir, tmpdir):
+ source = test_data_dir / "sample_file.txt"
+ crate = ROCrate()
+ f1 = crate.add_file(source, properties={"name": "sample file"})
+ ret = crate.get(source.name)
+ assert ret is f1
+ assert ret["name"] == "sample file"
+ assert ret in crate.get_entities()
+ assert crate.data_entities == [f1]
+ f2 = crate.add_file(source, properties={"name": "foobar"})
+ ret = crate.get(source.name)
+ assert ret is f2
+ assert ret["name"] == "foobar"
+ assert ret in crate.get_entities()
+ assert f1 not in crate.get_entities()
+ assert crate.data_entities == [f2]
+ joe = crate.add(Person(crate, "#joe", properties={"name": "Joe"}))
+ ret = crate.get("#joe")
+ assert ret is joe
+ assert ret in crate.get_entities()
+ assert ret["name"] == "Joe"
+ assert crate.contextual_entities == [joe]
+ jim = crate.add(Person(crate, "#joe", properties={"name": "Jim"}))
+ ret = crate.get("#joe")
+ assert ret is jim
+ assert ret["name"] == "Jim"
+ assert ret in crate.get_entities()
+ assert crate.contextual_entities == [jim]
| Raise an error, warning, or ignore duplicate ID's?
Hi, I just noticed I had a duplicate ID in my crate, is that valid for RO-Crate?
I thought about checking something like `if File(data).id in crate.data_entities`, but I think what identifies uniquely data in the crate are `ID` + JSON-LD data. As I have the date that the entity was created in the JSON-LD data, whenever I create two entities they are never identical. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/test_model.py::test_add_no_duplicates"
] | [
"test/test_model.py::test_dereferencing",
"test/test_model.py::test_dereferencing_equivalent_id[.foo]",
"test/test_model.py::test_dereferencing_equivalent_id[foo.]",
"test/test_model.py::test_dereferencing_equivalent_id[.foo/]",
"test/test_model.py::test_dereferencing_equivalent_id[foo./]",
"test/test_model.py::test_data_entities",
"test/test_model.py::test_data_entities_perf",
"test/test_model.py::test_remote_data_entities",
"test/test_model.py::test_bad_data_entities",
"test/test_model.py::test_contextual_entities",
"test/test_model.py::test_contextual_entities_hash",
"test/test_model.py::test_properties",
"test/test_model.py::test_uuid",
"test/test_model.py::test_update",
"test/test_model.py::test_delete",
"test/test_model.py::test_delete_refs",
"test/test_model.py::test_delete_by_id",
"test/test_model.py::test_self_delete",
"test/test_model.py::test_entity_as_mapping",
"test/test_model.py::test_wf_types",
"test/test_model.py::test_append_to[False]",
"test/test_model.py::test_append_to[True]",
"test/test_model.py::test_get_by_type",
"test/test_model.py::test_context"
] | {
"failed_lite_validators": [
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2023-10-13T12:27:58Z" | apache-2.0 |
|
ResearchObject__ro-crate-py-168 | diff --git a/rocrate/utils.py b/rocrate/utils.py
index 18aa6f2..434fb41 100644
--- a/rocrate/utils.py
+++ b/rocrate/utils.py
@@ -33,7 +33,7 @@ def is_url(string):
parts = urlsplit(string)
if os.name == "nt" and len(parts.scheme) == 1:
return False
- return all((parts.scheme, parts.path))
+ return bool(parts.scheme)
def iso_now():
| ResearchObject/ro-crate-py | 91376829c2fcf1ecc2376255c1faa055e5f769fe | diff --git a/test/test_utils.py b/test/test_utils.py
index 7b0607b..20a8504 100644
--- a/test/test_utils.py
+++ b/test/test_utils.py
@@ -18,7 +18,7 @@
import pytest
-from rocrate.utils import subclasses, get_norm_value
+from rocrate.utils import subclasses, get_norm_value, is_url
class Pet:
@@ -53,3 +53,12 @@ def test_get_norm_value():
assert get_norm_value({"@id": "#xyz"}, "name") == []
with pytest.raises(ValueError):
get_norm_value({"@id": "#xyz", "name": [["foo"]]}, "name")
+
+
+def test_is_url():
+ assert is_url("http://example.com/index.html")
+ assert is_url("http://example.com/")
+ assert is_url("http://example.com")
+ assert not is_url("/etc/")
+ assert not is_url("/etc")
+ assert not is_url("/")
| BUG: If Root Data Entity has an arcp:// ID the arcp:// part gets stripped off it
Here's some code to reproduce the error:
```python
from rocrate.rocrate import ROCrate
import json
import os
test_crate = {
"@context": [
"https://w3id.org/ro/crate/1.1/context",
{
"@vocab": "http://schema.org/"
}
],
"@graph": [
{
"@id": "ro-crate-metadata.json",
"@type": "CreativeWork",
"conformsTo": [
{
"@id": "https://w3id.org/ro/crate/1.2"
}
],
"about": {
"@id": "arcp://name,corpus-of-oz-early-english"
}
},
{"@id": "arcp://name,corpus-of-oz-early-english", "@type": "Dataset"}
]}
os.makedirs("test_crate", exist_ok=True)
f = open("test_crate/ro-crate-metadata.json","w")
f.write(json.dumps(test_crate, indent=2))
f.close()
crate = ROCrate("test_crate")
print("ID of root dataset", crate.root_dataset.id) # name,corpus-of-oz-early-english
print("ID of original", test_crate["@graph"][1]["@id"]) # arcp://name,corpus-of-oz-early-english
print("same?", crate.root_dataset.id == test_crate["@graph"][1]["@id"])
``` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/test_utils.py::test_is_url"
] | [
"test/test_utils.py::test_subclasses",
"test/test_utils.py::test_get_norm_value"
] | {
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
} | "2023-12-21T10:09:25Z" | apache-2.0 |
|
ResearchObject__ro-crate-py-169 | diff --git a/rocrate/model/entity.py b/rocrate/model/entity.py
index 41bf09b..fa26218 100644
--- a/rocrate/model/entity.py
+++ b/rocrate/model/entity.py
@@ -30,9 +30,9 @@ class Entity(MutableMapping):
def __init__(self, crate, identifier=None, properties=None):
self.crate = crate
if identifier:
- self.id = self.format_id(identifier)
+ self.__id = self.format_id(identifier)
else:
- self.id = f"#{uuid.uuid4()}"
+ self.__id = f"#{uuid.uuid4()}"
if properties:
empty = self._empty()
empty.update(properties)
@@ -40,6 +40,10 @@ class Entity(MutableMapping):
else:
self._jsonld = self._empty()
+ @property
+ def id(self):
+ return self.__id
+
# Format the given ID with rules appropriate for this type.
# For example, Dataset (directory) data entities SHOULD end with /
def format_id(self, identifier):
| ResearchObject/ro-crate-py | fd5b75e2212698766f8ee10f4f448ed07dd99a47 | diff --git a/test/test_model.py b/test/test_model.py
index e7b5343..9f00a48 100644
--- a/test/test_model.py
+++ b/test/test_model.py
@@ -505,3 +505,10 @@ def test_add_no_duplicates(test_data_dir, tmpdir):
assert ret["name"] == "Jim"
assert ret in crate.get_entities()
assert crate.contextual_entities == [jim]
+
+
+def test_immutable_id():
+ crate = ROCrate()
+ p = crate.add(Person(crate, "#foo"))
+ with pytest.raises(AttributeError):
+ p.id = "#bar"
| Entity id should not be modifiable
It's used to index the entity in the crate's `__entity_map`, so changing it leads to inconsistencies:
```pycon
>>> from rocrate.rocrate import ROCrate
>>> crate = ROCrate()
>>> d = crate.add_dataset("FOO")
>>> crate._ROCrate__entity_map
{..., 'arcp://uuid,2f145cc1-20be-4cd7-ac86-d6d4a08cdcf9/FOO': <FOO/ Dataset>}
>>> d.id = "foo"
>>> crate._ROCrate__entity_map
{..., 'arcp://uuid,2f145cc1-20be-4cd7-ac86-d6d4a08cdcf9/FOO': <foo Dataset>}
>>> crate.dereference("foo")
>>> crate.dereference("FOO")
<foo Dataset>
``` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/test_model.py::test_immutable_id"
] | [
"test/test_model.py::test_dereferencing",
"test/test_model.py::test_dereferencing_equivalent_id[.foo]",
"test/test_model.py::test_dereferencing_equivalent_id[foo.]",
"test/test_model.py::test_dereferencing_equivalent_id[.foo/]",
"test/test_model.py::test_dereferencing_equivalent_id[foo./]",
"test/test_model.py::test_data_entities",
"test/test_model.py::test_data_entities_perf",
"test/test_model.py::test_remote_data_entities",
"test/test_model.py::test_bad_data_entities",
"test/test_model.py::test_contextual_entities",
"test/test_model.py::test_contextual_entities_hash",
"test/test_model.py::test_properties",
"test/test_model.py::test_uuid",
"test/test_model.py::test_update",
"test/test_model.py::test_delete",
"test/test_model.py::test_delete_refs",
"test/test_model.py::test_delete_by_id",
"test/test_model.py::test_self_delete",
"test/test_model.py::test_entity_as_mapping",
"test/test_model.py::test_wf_types",
"test/test_model.py::test_append_to[False]",
"test/test_model.py::test_append_to[True]",
"test/test_model.py::test_get_by_type",
"test/test_model.py::test_context",
"test/test_model.py::test_add_no_duplicates"
] | {
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
} | "2023-12-21T13:46:43Z" | apache-2.0 |
|
ResearchObject__ro-crate-py-170 | diff --git a/rocrate/model/file.py b/rocrate/model/file.py
index 9251aeb..a5d1c43 100644
--- a/rocrate/model/file.py
+++ b/rocrate/model/file.py
@@ -59,6 +59,7 @@ class File(FileOrDir):
if self.fetch_remote:
out_file_path.parent.mkdir(parents=True, exist_ok=True)
urllib.request.urlretrieve(response.url, out_file_path)
+ self._jsonld['contentUrl'] = str(self.source)
elif self.source is None:
# Allows to record a File entity whose @id does not exist, see #73
warnings.warn(f"No source for {self.id}")
| ResearchObject/ro-crate-py | 7364e13bf2546f3728e68d6a8c88a6fc66039e58 | diff --git a/test/test_write.py b/test/test_write.py
index 10f0ec3..6fb57b6 100644
--- a/test/test_write.py
+++ b/test/test_write.py
@@ -150,6 +150,7 @@ def test_remote_uri(tmpdir, helpers, fetch_remote, validate_url, to_zip):
if fetch_remote:
out_file = out_crate.dereference(file_.id)
assert (out_path / relpath).is_file()
+ assert out_file["contentUrl"] == url
else:
out_file = out_crate.dereference(url)
assert not (out_path / relpath).exists()
| Add contentUrl property to files when it's known
E.g., when a remote file is added with `fetch_remote=True`. See https://github.com/ResearchObject/ro-crate/pull/189#issuecomment-1227697348. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/test_write.py::test_remote_uri[True-False-False]",
"test/test_write.py::test_remote_uri[True-False-True]",
"test/test_write.py::test_remote_uri[True-True-False]",
"test/test_write.py::test_remote_uri[True-True-True]"
] | [
"test/test_write.py::test_file_writing[False-False]",
"test/test_write.py::test_file_writing[False-True]",
"test/test_write.py::test_file_writing[True-False]",
"test/test_write.py::test_file_writing[True-True]",
"test/test_write.py::test_in_mem_stream[BytesIO]",
"test/test_write.py::test_in_mem_stream[StringIO]",
"test/test_write.py::test_remote_uri[False-False-False]",
"test/test_write.py::test_remote_uri[False-False-True]",
"test/test_write.py::test_remote_uri[False-True-False]",
"test/test_write.py::test_remote_uri[False-True-True]",
"test/test_write.py::test_file_uri",
"test/test_write.py::test_looks_like_file_uri",
"test/test_write.py::test_ftp_uri[False]",
"test/test_write.py::test_remote_dir[False-False]",
"test/test_write.py::test_remote_dir[False-True]",
"test/test_write.py::test_remote_dir[True-False]",
"test/test_write.py::test_remote_dir[True-True]",
"test/test_write.py::test_remote_uri_exceptions",
"test/test_write.py::test_missing_source[file]",
"test/test_write.py::test_missing_source[dataset]",
"test/test_write.py::test_stringio_no_dest[False-False]",
"test/test_write.py::test_stringio_no_dest[False-True]",
"test/test_write.py::test_stringio_no_dest[True-False]",
"test/test_write.py::test_stringio_no_dest[True-True]",
"test/test_write.py::test_no_source_no_dest[False-False]",
"test/test_write.py::test_no_source_no_dest[False-True]",
"test/test_write.py::test_no_source_no_dest[True-False]",
"test/test_write.py::test_no_source_no_dest[True-True]",
"test/test_write.py::test_dataset",
"test/test_write.py::test_no_parts",
"test/test_write.py::test_no_zip_in_zip",
"test/test_write.py::test_add_tree"
] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
} | "2023-12-22T12:00:32Z" | apache-2.0 |
|
ResearchObject__ro-crate-py-171 | diff --git a/rocrate/cli.py b/rocrate/cli.py
index 9e63e54..8ff4e88 100644
--- a/rocrate/cli.py
+++ b/rocrate/cli.py
@@ -69,6 +69,36 @@ def add():
pass
[email protected]()
[email protected]('path', type=click.Path(exists=True, dir_okay=False))
+@OPTION_CRATE_PATH
+def file(crate_dir, path):
+ crate = ROCrate(crate_dir, init=False, gen_preview=False)
+ source = Path(path).resolve(strict=True)
+ try:
+ dest_path = source.relative_to(crate_dir)
+ except ValueError:
+ # For now, only support adding an existing file to the metadata
+ raise ValueError(f"{source} is not in the crate dir {crate_dir}")
+ crate.add_file(source, dest_path)
+ crate.metadata.write(crate_dir)
+
+
[email protected]()
[email protected]('path', type=click.Path(exists=True, file_okay=False))
+@OPTION_CRATE_PATH
+def dataset(crate_dir, path):
+ crate = ROCrate(crate_dir, init=False, gen_preview=False)
+ source = Path(path).resolve(strict=True)
+ try:
+ dest_path = source.relative_to(crate_dir)
+ except ValueError:
+ # For now, only support adding an existing directory to the metadata
+ raise ValueError(f"{source} is not in the crate dir {crate_dir}")
+ crate.add_dataset(source, dest_path)
+ crate.metadata.write(crate_dir)
+
+
@add.command()
@click.argument('path', type=click.Path(exists=True))
@click.option('-l', '--language', type=click.Choice(LANG_CHOICES), default="cwl")
| ResearchObject/ro-crate-py | 42aeed481d1c14dab3eaef00c90db7a9a30caf9e | diff --git a/test/test_cli.py b/test/test_cli.py
index 12e97ba..b6b8b69 100644
--- a/test/test_cli.py
+++ b/test/test_cli.py
@@ -20,6 +20,7 @@ import json
import click
from click.testing import CliRunner
import pytest
+import shutil
from rocrate.cli import cli
from rocrate.model import File
@@ -132,6 +133,58 @@ def test_cli_init_exclude(test_data_dir, helpers):
assert not e.id.startswith("test")
[email protected]("cwd", [False, True])
+def test_cli_add_file(tmpdir, test_data_dir, helpers, monkeypatch, cwd):
+ # init
+ crate_dir = tmpdir / "crate"
+ crate_dir.mkdir()
+ runner = CliRunner()
+ assert runner.invoke(cli, ["init", "-c", str(crate_dir)]).exit_code == 0
+ json_entities = helpers.read_json_entities(crate_dir)
+ assert set(json_entities) == {"./", "ro-crate-metadata.json"}
+ # add
+ shutil.copy(test_data_dir / "sample_file.txt", crate_dir)
+ file_path = crate_dir / "sample_file.txt"
+ args = ["add", "file"]
+ if cwd:
+ monkeypatch.chdir(str(crate_dir))
+ file_path = file_path.relative_to(crate_dir)
+ else:
+ args.extend(["-c", str(crate_dir)])
+ args.append(str(file_path))
+ result = runner.invoke(cli, args)
+ assert result.exit_code == 0
+ json_entities = helpers.read_json_entities(crate_dir)
+ assert "sample_file.txt" in json_entities
+ assert json_entities["sample_file.txt"]["@type"] == "File"
+
+
[email protected]("cwd", [False, True])
+def test_cli_add_dataset(tmpdir, test_data_dir, helpers, monkeypatch, cwd):
+ # init
+ crate_dir = tmpdir / "crate"
+ crate_dir.mkdir()
+ runner = CliRunner()
+ assert runner.invoke(cli, ["init", "-c", str(crate_dir)]).exit_code == 0
+ json_entities = helpers.read_json_entities(crate_dir)
+ assert set(json_entities) == {"./", "ro-crate-metadata.json"}
+ # add
+ dataset_path = crate_dir / "test_add_dir"
+ shutil.copytree(test_data_dir / "test_add_dir", dataset_path)
+ args = ["add", "dataset"]
+ if cwd:
+ monkeypatch.chdir(str(crate_dir))
+ dataset_path = dataset_path.relative_to(crate_dir)
+ else:
+ args.extend(["-c", str(crate_dir)])
+ args.append(str(dataset_path))
+ result = runner.invoke(cli, args)
+ assert result.exit_code == 0
+ json_entities = helpers.read_json_entities(crate_dir)
+ assert "test_add_dir/" in json_entities
+ assert json_entities["test_add_dir/"]["@type"] == "Dataset"
+
+
@pytest.mark.parametrize("cwd", [False, True])
def test_cli_add_workflow(test_data_dir, helpers, monkeypatch, cwd):
# init
| CLI subcommands to add files and directories
Add subcommands to allow this:
```bash
mkdir crate
cd crate
rocrate init # generates minimal metadata file and nothing else
cp /some/other/path/file1 .
cp -rf /some/path/dir1 .
rocrate add file file1
rocrate add dataset dir1
```
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/test_cli.py::test_cli_help[command_path6]",
"test/test_cli.py::test_cli_help[command_path7]",
"test/test_cli.py::test_cli_add_file[False]",
"test/test_cli.py::test_cli_add_file[True]",
"test/test_cli.py::test_cli_add_dataset[False]",
"test/test_cli.py::test_cli_add_dataset[True]"
] | [
"test/test_cli.py::test_cli_help[command_path0]",
"test/test_cli.py::test_cli_help[command_path1]",
"test/test_cli.py::test_cli_help[command_path2]",
"test/test_cli.py::test_cli_help[command_path3]",
"test/test_cli.py::test_cli_help[command_path4]",
"test/test_cli.py::test_cli_help[command_path5]",
"test/test_cli.py::test_cli_init[False-False]",
"test/test_cli.py::test_cli_init[False-True]",
"test/test_cli.py::test_cli_init[True-False]",
"test/test_cli.py::test_cli_init[True-True]",
"test/test_cli.py::test_cli_init_exclude",
"test/test_cli.py::test_cli_add_workflow[False]",
"test/test_cli.py::test_cli_add_workflow[True]",
"test/test_cli.py::test_cli_add_test_metadata[False]",
"test/test_cli.py::test_cli_add_test_metadata[True]",
"test/test_cli.py::test_cli_add_test_metadata_explicit_ids[False]",
"test/test_cli.py::test_cli_add_test_metadata_explicit_ids[True]",
"test/test_cli.py::test_cli_write_zip[False]",
"test/test_cli.py::test_cli_write_zip[True]"
] | {
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
} | "2024-01-09T09:30:42Z" | apache-2.0 |
|
ResearchObject__ro-crate-py-172 | diff --git a/README.md b/README.md
index dbbe578..76aa7e2 100644
--- a/README.md
+++ b/README.md
@@ -310,7 +310,7 @@ The command acts on the current directory, unless the `-c` option is specified.
### Adding items to the crate
-The `rocrate add` command allows to add workflows and other entity types (currently [testing-related metadata](https://crs4.github.io/life_monitor/workflow_testing_ro_crate)) to an RO-Crate:
+The `rocrate add` command allows to add file, datasets (directories), workflows and other entity types (currently [testing-related metadata](https://crs4.github.io/life_monitor/workflow_testing_ro_crate)) to an RO-Crate:
```console
$ rocrate add --help
@@ -320,6 +320,8 @@ Options:
--help Show this message and exit.
Commands:
+ dataset
+ file
test-definition
test-instance
test-suite
@@ -372,6 +374,29 @@ rocrate add test-instance test1 http://example.com -r jobs -i test1_1
rocrate add test-definition test1 test/test1/sort-and-change-case-test.yml -e planemo -v '>=0.70'
```
+To add files or directories after crate initialization:
+
+```bash
+cp ../sample_file.txt .
+rocrate add file sample_file.txt -P name=sample -P description="Sample file"
+cp -r ../test_add_dir .
+rocrate add dataset test_add_dir
+```
+
+The above example also shows how to set arbitrary properties for the entity with `-P`. This is supported by most `rocrate add` subcommands.
+
+```console
+$ rocrate add workflow --help
+Usage: rocrate add workflow [OPTIONS] PATH
+
+Options:
+ -l, --language [cwl|galaxy|knime|nextflow|snakemake|compss|autosubmit]
+ -c, --crate-dir PATH
+ -P, --property KEY=VALUE
+ --help Show this message and exit.
+```
+
+
## License
* Copyright 2019-2024 The University of Manchester, UK
diff --git a/rocrate/cli.py b/rocrate/cli.py
index 8ff4e88..b4ff19e 100644
--- a/rocrate/cli.py
+++ b/rocrate/cli.py
@@ -44,8 +44,20 @@ class CSVParamType(click.ParamType):
self.fail(f"{value!r} is not splittable", param, ctx)
+class KeyValueParamType(click.ParamType):
+ name = "key_value"
+
+ def convert(self, value, param, ctx):
+ try:
+ return tuple(value.split("=", 1)) if value else ()
+ except AttributeError:
+ self.fail(f"{value!r} is not splittable", param, ctx)
+
+
CSV = CSVParamType()
+KeyValue = KeyValueParamType()
OPTION_CRATE_PATH = click.option('-c', '--crate-dir', type=click.Path(), default=os.getcwd)
+OPTION_PROPS = click.option('-P', '--property', type=KeyValue, multiple=True, metavar="KEY=VALUE")
@click.group()
@@ -72,7 +84,8 @@ def add():
@add.command()
@click.argument('path', type=click.Path(exists=True, dir_okay=False))
@OPTION_CRATE_PATH
-def file(crate_dir, path):
+@OPTION_PROPS
+def file(crate_dir, path, property):
crate = ROCrate(crate_dir, init=False, gen_preview=False)
source = Path(path).resolve(strict=True)
try:
@@ -80,14 +93,15 @@ def file(crate_dir, path):
except ValueError:
# For now, only support adding an existing file to the metadata
raise ValueError(f"{source} is not in the crate dir {crate_dir}")
- crate.add_file(source, dest_path)
+ crate.add_file(source, dest_path, properties=dict(property))
crate.metadata.write(crate_dir)
@add.command()
@click.argument('path', type=click.Path(exists=True, file_okay=False))
@OPTION_CRATE_PATH
-def dataset(crate_dir, path):
+@OPTION_PROPS
+def dataset(crate_dir, path, property):
crate = ROCrate(crate_dir, init=False, gen_preview=False)
source = Path(path).resolve(strict=True)
try:
@@ -95,7 +109,7 @@ def dataset(crate_dir, path):
except ValueError:
# For now, only support adding an existing directory to the metadata
raise ValueError(f"{source} is not in the crate dir {crate_dir}")
- crate.add_dataset(source, dest_path)
+ crate.add_dataset(source, dest_path, properties=dict(property))
crate.metadata.write(crate_dir)
@@ -103,7 +117,8 @@ def dataset(crate_dir, path):
@click.argument('path', type=click.Path(exists=True))
@click.option('-l', '--language', type=click.Choice(LANG_CHOICES), default="cwl")
@OPTION_CRATE_PATH
-def workflow(crate_dir, path, language):
+@OPTION_PROPS
+def workflow(crate_dir, path, language, property):
crate = ROCrate(crate_dir, init=False, gen_preview=False)
source = Path(path).resolve(strict=True)
try:
@@ -112,7 +127,7 @@ def workflow(crate_dir, path, language):
# For now, only support marking an existing file as a workflow
raise ValueError(f"{source} is not in the crate dir {crate_dir}")
# TODO: add command options for main and gen_cwl
- crate.add_workflow(source, dest_path, main=True, lang=language, gen_cwl=False)
+ crate.add_workflow(source, dest_path, main=True, lang=language, gen_cwl=False, properties=dict(property))
crate.metadata.write(crate_dir)
@@ -121,9 +136,13 @@ def workflow(crate_dir, path, language):
@click.option('-n', '--name')
@click.option('-m', '--main-entity')
@OPTION_CRATE_PATH
-def suite(crate_dir, identifier, name, main_entity):
+@OPTION_PROPS
+def suite(crate_dir, identifier, name, main_entity, property):
crate = ROCrate(crate_dir, init=False, gen_preview=False)
- suite = crate.add_test_suite(identifier=add_hash(identifier), name=name, main_entity=main_entity)
+ suite = crate.add_test_suite(
+ identifier=add_hash(identifier), name=name, main_entity=main_entity,
+ properties=dict(property)
+ )
crate.metadata.write(crate_dir)
print(suite.id)
@@ -136,11 +155,12 @@ def suite(crate_dir, identifier, name, main_entity):
@click.option('-i', '--identifier')
@click.option('-n', '--name')
@OPTION_CRATE_PATH
-def instance(crate_dir, suite, url, resource, service, identifier, name):
+@OPTION_PROPS
+def instance(crate_dir, suite, url, resource, service, identifier, name, property):
crate = ROCrate(crate_dir, init=False, gen_preview=False)
instance_ = crate.add_test_instance(
add_hash(suite), url, resource=resource, service=service,
- identifier=add_hash(identifier), name=name
+ identifier=add_hash(identifier), name=name, properties=dict(property)
)
crate.metadata.write(crate_dir)
print(instance_.id)
@@ -152,7 +172,8 @@ def instance(crate_dir, suite, url, resource, service, identifier, name):
@click.option('-e', '--engine', type=click.Choice(ENGINE_CHOICES), default="planemo")
@click.option('-v', '--engine-version')
@OPTION_CRATE_PATH
-def definition(crate_dir, suite, path, engine, engine_version):
+@OPTION_PROPS
+def definition(crate_dir, suite, path, engine, engine_version, property):
crate = ROCrate(crate_dir, init=False, gen_preview=False)
source = Path(path).resolve(strict=True)
try:
@@ -162,7 +183,7 @@ def definition(crate_dir, suite, path, engine, engine_version):
raise ValueError(f"{source} is not in the crate dir {crate_dir}")
crate.add_test_definition(
add_hash(suite), source=source, dest_path=dest_path, engine=engine,
- engine_version=engine_version
+ engine_version=engine_version, properties=dict(property)
)
crate.metadata.write(crate_dir)
diff --git a/rocrate/rocrate.py b/rocrate/rocrate.py
index 0bf2166..daed143 100644
--- a/rocrate/rocrate.py
+++ b/rocrate/rocrate.py
@@ -497,23 +497,24 @@ class ROCrate():
workflow.subjectOf = cwl_workflow
return workflow
- def add_test_suite(self, identifier=None, name=None, main_entity=None):
+ def add_test_suite(self, identifier=None, name=None, main_entity=None, properties=None):
test_ref_prop = "mentions"
if not main_entity:
main_entity = self.mainEntity
if not main_entity:
test_ref_prop = "about"
- suite = self.add(TestSuite(self, identifier))
- suite.name = name or suite.id.lstrip("#")
+ suite = self.add(TestSuite(self, identifier, properties=properties))
+ if not properties or "name" not in properties:
+ suite.name = name or suite.id.lstrip("#")
if main_entity:
suite["mainEntity"] = main_entity
self.root_dataset.append_to(test_ref_prop, suite)
self.metadata.extra_terms.update(TESTING_EXTRA_TERMS)
return suite
- def add_test_instance(self, suite, url, resource="", service="jenkins", identifier=None, name=None):
+ def add_test_instance(self, suite, url, resource="", service="jenkins", identifier=None, name=None, properties=None):
suite = self.__validate_suite(suite)
- instance = self.add(TestInstance(self, identifier))
+ instance = self.add(TestInstance(self, identifier, properties=properties))
instance.url = url
instance.resource = resource
if isinstance(service, TestService):
@@ -522,7 +523,8 @@ class ROCrate():
service = get_service(self, service)
self.add(service)
instance.service = service
- instance.name = name or instance.id.lstrip("#")
+ if not properties or "name" not in properties:
+ instance.name = name or instance.id.lstrip("#")
suite.append_to("instance", instance)
self.metadata.extra_terms.update(TESTING_EXTRA_TERMS)
return instance
| ResearchObject/ro-crate-py | 2ea7fae01bca70c5601bcd860582824fb640d4ac | diff --git a/test/test_cli.py b/test/test_cli.py
index b6b8b69..28d918e 100644
--- a/test/test_cli.py
+++ b/test/test_cli.py
@@ -145,18 +145,19 @@ def test_cli_add_file(tmpdir, test_data_dir, helpers, monkeypatch, cwd):
# add
shutil.copy(test_data_dir / "sample_file.txt", crate_dir)
file_path = crate_dir / "sample_file.txt"
- args = ["add", "file"]
+ args = ["add", "file", str(file_path), "-P", "name=foo", "-P", "description=foo bar"]
if cwd:
monkeypatch.chdir(str(crate_dir))
file_path = file_path.relative_to(crate_dir)
else:
args.extend(["-c", str(crate_dir)])
- args.append(str(file_path))
result = runner.invoke(cli, args)
assert result.exit_code == 0
json_entities = helpers.read_json_entities(crate_dir)
assert "sample_file.txt" in json_entities
assert json_entities["sample_file.txt"]["@type"] == "File"
+ assert json_entities["sample_file.txt"]["name"] == "foo"
+ assert json_entities["sample_file.txt"]["description"] == "foo bar"
@pytest.mark.parametrize("cwd", [False, True])
@@ -171,18 +172,19 @@ def test_cli_add_dataset(tmpdir, test_data_dir, helpers, monkeypatch, cwd):
# add
dataset_path = crate_dir / "test_add_dir"
shutil.copytree(test_data_dir / "test_add_dir", dataset_path)
- args = ["add", "dataset"]
+ args = ["add", "dataset", str(dataset_path), "-P", "name=foo", "-P", "description=foo bar"]
if cwd:
monkeypatch.chdir(str(crate_dir))
dataset_path = dataset_path.relative_to(crate_dir)
else:
args.extend(["-c", str(crate_dir)])
- args.append(str(dataset_path))
result = runner.invoke(cli, args)
assert result.exit_code == 0
json_entities = helpers.read_json_entities(crate_dir)
assert "test_add_dir/" in json_entities
assert json_entities["test_add_dir/"]["@type"] == "Dataset"
+ assert json_entities["test_add_dir/"]["name"] == "foo"
+ assert json_entities["test_add_dir/"]["description"] == "foo bar"
@pytest.mark.parametrize("cwd", [False, True])
@@ -196,7 +198,7 @@ def test_cli_add_workflow(test_data_dir, helpers, monkeypatch, cwd):
assert json_entities["sort-and-change-case.ga"]["@type"] == "File"
# add
wf_path = crate_dir / "sort-and-change-case.ga"
- args = ["add", "workflow"]
+ args = ["add", "workflow", "-P", "name=foo", "-P", "description=foo bar"]
if cwd:
monkeypatch.chdir(str(crate_dir))
wf_path = wf_path.relative_to(crate_dir)
@@ -212,6 +214,8 @@ def test_cli_add_workflow(test_data_dir, helpers, monkeypatch, cwd):
lang_id = f"https://w3id.org/workflowhub/workflow-ro-crate#{lang}"
assert lang_id in json_entities
assert json_entities["sort-and-change-case.ga"]["programmingLanguage"]["@id"] == lang_id
+ assert json_entities["sort-and-change-case.ga"]["name"] == "foo"
+ assert json_entities["sort-and-change-case.ga"]["description"] == "foo bar"
@pytest.mark.parametrize("cwd", [False, True])
@@ -228,20 +232,27 @@ def test_cli_add_test_metadata(test_data_dir, helpers, monkeypatch, cwd):
wf_path = crate_dir / "sort-and-change-case.ga"
assert runner.invoke(cli, ["add", "workflow", "-c", str(crate_dir), "-l", "galaxy", str(wf_path)]).exit_code == 0
# add test suite
- result = runner.invoke(cli, ["add", "test-suite", "-c", str(crate_dir)])
+ result = runner.invoke(cli, ["add", "test-suite", "-c", str(crate_dir),
+ "-P", "name=foo", "-P", "description=foo bar"])
assert result.exit_code == 0
suite_id = result.output.strip()
json_entities = helpers.read_json_entities(crate_dir)
assert suite_id in json_entities
+ assert json_entities[suite_id]["name"] == "foo"
+ assert json_entities[suite_id]["description"] == "foo bar"
# add test instance
- result = runner.invoke(cli, ["add", "test-instance", "-c", str(crate_dir), suite_id, "http://example.com", "-r", "jobs"])
+ result = runner.invoke(cli, ["add", "test-instance", "-c", str(crate_dir),
+ suite_id, "http://example.com", "-r", "jobs",
+ "-P", "name=foo", "-P", "description=foo bar"])
assert result.exit_code == 0
instance_id = result.output.strip()
json_entities = helpers.read_json_entities(crate_dir)
assert instance_id in json_entities
+ assert json_entities[instance_id]["name"] == "foo"
+ assert json_entities[instance_id]["description"] == "foo bar"
# add test definition
def_path = crate_dir / def_id
- args = ["add", "test-definition"]
+ args = ["add", "test-definition", "-P", "name=foo", "-P", "description=foo bar"]
if cwd:
monkeypatch.chdir(str(crate_dir))
def_path = def_path.relative_to(crate_dir)
@@ -253,6 +264,8 @@ def test_cli_add_test_metadata(test_data_dir, helpers, monkeypatch, cwd):
json_entities = helpers.read_json_entities(crate_dir)
assert def_id in json_entities
assert set(json_entities[def_id]["@type"]) == {"File", "TestDefinition"}
+ assert json_entities[def_id]["name"] == "foo"
+ assert json_entities[def_id]["description"] == "foo bar"
# check extra terms
metadata_path = crate_dir / helpers.METADATA_FILE_NAME
with open(metadata_path, "rt") as f:
| CLI: add a way to set properties
E.g., with a repeatable arg:
```
rocrate add workflow foo.cwl -P name=Foo -P description='Lorem Ipsum'
``` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/test_cli.py::test_cli_add_file[False]",
"test/test_cli.py::test_cli_add_file[True]",
"test/test_cli.py::test_cli_add_dataset[False]",
"test/test_cli.py::test_cli_add_dataset[True]",
"test/test_cli.py::test_cli_add_workflow[False]",
"test/test_cli.py::test_cli_add_workflow[True]",
"test/test_cli.py::test_cli_add_test_metadata[False]",
"test/test_cli.py::test_cli_add_test_metadata[True]"
] | [
"test/test_cli.py::test_cli_help[command_path0]",
"test/test_cli.py::test_cli_help[command_path1]",
"test/test_cli.py::test_cli_help[command_path2]",
"test/test_cli.py::test_cli_help[command_path3]",
"test/test_cli.py::test_cli_help[command_path4]",
"test/test_cli.py::test_cli_help[command_path5]",
"test/test_cli.py::test_cli_help[command_path6]",
"test/test_cli.py::test_cli_help[command_path7]",
"test/test_cli.py::test_cli_init[False-False]",
"test/test_cli.py::test_cli_init[False-True]",
"test/test_cli.py::test_cli_init[True-False]",
"test/test_cli.py::test_cli_init[True-True]",
"test/test_cli.py::test_cli_init_exclude",
"test/test_cli.py::test_cli_add_test_metadata_explicit_ids[False]",
"test/test_cli.py::test_cli_add_test_metadata_explicit_ids[True]",
"test/test_cli.py::test_cli_write_zip[False]",
"test/test_cli.py::test_cli_write_zip[True]"
] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2024-01-10T12:29:08Z" | apache-2.0 |
|
ResearchObject__ro-crate-py-52 | diff --git a/rocrate/model/dataset.py b/rocrate/model/dataset.py
index 4a47c41..2944dff 100644
--- a/rocrate/model/dataset.py
+++ b/rocrate/model/dataset.py
@@ -79,4 +79,5 @@ class Dataset(DataEntity):
# iterate over the entries
for file_src, rel_path in self.directory_entries():
dest_path = os.path.join(out_path, rel_path)
- zip_out.write(file_src, dest_path)
+ if dest_path not in zip_out.namelist():
+ zip_out.write(file_src, dest_path)
diff --git a/rocrate/model/file.py b/rocrate/model/file.py
index 9f2e5a6..4b5cc50 100644
--- a/rocrate/model/file.py
+++ b/rocrate/model/file.py
@@ -124,4 +124,5 @@ class File(DataEntity):
shutil.copyfileobj(response, out_file)
def write_zip(self, zip_out):
- zip_out.write(self.source, self.id)
+ if self.id not in zip_out.namelist():
+ zip_out.write(self.source, self.id)
diff --git a/rocrate/rocrate.py b/rocrate/rocrate.py
index 0e652c7..74e0ab6 100644
--- a/rocrate/rocrate.py
+++ b/rocrate/rocrate.py
@@ -87,6 +87,8 @@ class ROCrate():
entities = self.entities_from_metadata(metadata_path)
self.build_crate(entities, source_path, load_preview)
# TODO: load root dataset properties
+ # in the zip case, self.source_path is the extracted dir
+ self.source_path = source_path
def __init_from_tree(self, top_dir, load_preview=False):
top_dir = Path(top_dir)
@@ -427,10 +429,26 @@ class ROCrate():
# write crate to local dir
def write_crate(self, base_path):
- Path(base_path).mkdir(parents=True, exist_ok=True)
+ base_path = Path(base_path)
+ base_path.mkdir(parents=True, exist_ok=True)
+ # copy unlisted files and directories
+ if self.source_path:
+ top = self.source_path
+ for root, dirs, files in os.walk(top):
+ root = Path(root)
+ for name in dirs:
+ source = root / name
+ dest = base_path / source.relative_to(top)
+ dest.mkdir(parents=True, exist_ok=True)
+ for name in files:
+ source = root / name
+ rel = source.relative_to(top)
+ if not self.dereference(str(rel)):
+ dest = base_path / rel
+ shutil.copyfile(source, dest)
# write data entities
for writable_entity in self.data_entities + self.default_entities:
- writable_entity.write(base_path)
+ writable_entity.write(str(base_path))
def write_zip(self, out_zip):
if str(out_zip).endswith('.zip'):
@@ -441,6 +459,16 @@ class ROCrate():
out_file_path, 'w', compression=zipfile.ZIP_DEFLATED,
allowZip64=True
)
+ # copy unlisted files and directories
+ if self.source_path:
+ top = self.source_path
+ for root, dirs, files in os.walk(top):
+ root = Path(root)
+ for name in files:
+ source = root / name
+ dest = source.relative_to(top)
+ if not self.dereference(str(dest)):
+ zf.write(str(source), str(dest))
for writable_entity in self.data_entities + self.default_entities:
writable_entity.write_zip(zf)
zf.close()
| ResearchObject/ro-crate-py | 21736196aece64f9dc43aa39e456acb889d83fcc | diff --git a/test/test-data/read_extra/listed.txt b/test/test-data/read_extra/listed.txt
new file mode 100644
index 0000000..f6174c1
--- /dev/null
+++ b/test/test-data/read_extra/listed.txt
@@ -0,0 +1,1 @@
+LISTED
diff --git a/test/test-data/read_extra/listed/listed.txt b/test/test-data/read_extra/listed/listed.txt
new file mode 100644
index 0000000..f6174c1
--- /dev/null
+++ b/test/test-data/read_extra/listed/listed.txt
@@ -0,0 +1,1 @@
+LISTED
diff --git a/test/test-data/read_extra/listed/not_listed.txt b/test/test-data/read_extra/listed/not_listed.txt
new file mode 100644
index 0000000..821cc78
--- /dev/null
+++ b/test/test-data/read_extra/listed/not_listed.txt
@@ -0,0 +1,1 @@
+NOT_LISTED
diff --git a/test/test-data/read_extra/not_listed.txt b/test/test-data/read_extra/not_listed.txt
new file mode 100644
index 0000000..821cc78
--- /dev/null
+++ b/test/test-data/read_extra/not_listed.txt
@@ -0,0 +1,1 @@
+NOT_LISTED
diff --git a/test/test-data/read_extra/not_listed/not_listed.txt b/test/test-data/read_extra/not_listed/not_listed.txt
new file mode 100644
index 0000000..821cc78
--- /dev/null
+++ b/test/test-data/read_extra/not_listed/not_listed.txt
@@ -0,0 +1,1 @@
+NOT_LISTED
diff --git a/test/test-data/read_extra/ro-crate-metadata.json b/test/test-data/read_extra/ro-crate-metadata.json
new file mode 100644
index 0000000..90e2682
--- /dev/null
+++ b/test/test-data/read_extra/ro-crate-metadata.json
@@ -0,0 +1,43 @@
+{
+ "@context": "https://w3id.org/ro/crate/1.1/context",
+ "@graph": [
+ {
+ "@id": "./",
+ "@type": "Dataset",
+ "datePublished": "2021-02-26T09:46:41.236862",
+ "hasPart": [
+ {
+ "@id": "listed/"
+ },
+ {
+ "@id": "listed.txt"
+ },
+ {
+ "@id": "listed/listed.txt"
+ }
+ ]
+ },
+ {
+ "@id": "ro-crate-metadata.json",
+ "@type": "CreativeWork",
+ "about": {
+ "@id": "./"
+ },
+ "conformsTo": {
+ "@id": "https://w3id.org/ro/crate/1.1"
+ }
+ },
+ {
+ "@id": "listed/",
+ "@type": "Dataset"
+ },
+ {
+ "@id": "listed.txt",
+ "@type": "File"
+ },
+ {
+ "@id": "listed/listed.txt",
+ "@type": "File"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/test/test_read.py b/test/test_read.py
index 4db2864..eea335a 100644
--- a/test/test_read.py
+++ b/test/test_read.py
@@ -18,6 +18,7 @@
import pytest
import shutil
import uuid
+import zipfile
from pathlib import Path
from rocrate.rocrate import ROCrate
@@ -120,7 +121,10 @@ def test_crate_dir_loading(test_data_dir, tmpdir, helpers, load_preview, from_zi
metadata_path = out_path / helpers.METADATA_FILE_NAME
assert metadata_path.exists()
legacy_metadata_path = out_path / helpers.LEGACY_METADATA_FILE_NAME
- assert not legacy_metadata_path.exists()
+ # legacy metadata file should just be copied over as a regular file
+ assert legacy_metadata_path.exists()
+ with open(crate_dir / helpers.LEGACY_METADATA_FILE_NAME) as f1, open(legacy_metadata_path) as f2:
+ assert f1.read() == f2.read()
preview_path = out_path / helpers.PREVIEW_FILE_NAME
assert preview_path.exists()
if load_preview:
@@ -241,3 +245,28 @@ def test_no_parts(tmpdir):
crate = ROCrate(out_path)
assert not crate.root_dataset["hasPart"]
+
+
[email protected]("to_zip", [False, True])
+def test_extra_data(test_data_dir, tmpdir, to_zip):
+ crate_dir = test_data_dir / 'read_extra'
+ crate = ROCrate(crate_dir)
+ out_path = tmpdir / 'read_extra_out'
+ if to_zip:
+ zip_path = tmpdir / 'ro_crate_out.crate.zip'
+ crate.write_zip(zip_path)
+ with zipfile.ZipFile(zip_path, "r") as zf:
+ zf.extractall(out_path)
+ else:
+ out_path.mkdir()
+ crate.write_crate(out_path)
+ for rel in {
+ "listed.txt",
+ "listed/listed.txt",
+ "listed/not_listed.txt",
+ "not_listed.txt",
+ "not_listed/not_listed.txt",
+ }:
+ assert (out_path / rel).is_file()
+ with open(crate_dir / rel) as f1, open(out_path / rel) as f2:
+ assert f1.read() == f2.read()
| Track files/dirs not listed in the metadata file
From the spec:
> Payload files may appear directly in the RO-Crate Root alongside the RO-Crate Metadata File, and/or appear in sub-directories of the RO-Crate Root. Each file and directory MAY be represented as Data Entities in the RO-Crate Metadata File.
> It is important to note that the RO-Crate Metadata File is not an exhaustive manifest or inventory, that is, it does not necessarily list or describe all files in the package.
Currently, when reading an ro-crate, files or directories not listed in the metadata file are ignored. Thus, when the crate is written out to some other location, those files / directories are not kept. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/test_read.py::test_crate_dir_loading[False-False]",
"test/test_read.py::test_crate_dir_loading[True-False]",
"test/test_read.py::test_crate_dir_loading[True-True]",
"test/test_read.py::test_extra_data[False]",
"test/test_read.py::test_extra_data[True]"
] | [
"test/test_read.py::test_legacy_crate",
"test/test_read.py::test_bad_crate",
"test/test_read.py::test_init[False]",
"test/test_read.py::test_init[True]",
"test/test_read.py::test_init_preview[False-False]",
"test/test_read.py::test_init_preview[False-True]",
"test/test_read.py::test_init_preview[True-False]",
"test/test_read.py::test_init_preview[True-True]",
"test/test_read.py::test_no_parts"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2021-02-26T11:59:15Z" | apache-2.0 |
|
ResearchObject__ro-crate-py-69 | diff --git a/rocrate/rocrate.py b/rocrate/rocrate.py
index 5c3969d..a968f10 100644
--- a/rocrate/rocrate.py
+++ b/rocrate/rocrate.py
@@ -510,6 +510,8 @@ class ROCrate():
root = Path(root)
for name in files:
source = root / name
+ if source.samefile(out_file_path):
+ continue
dest = source.relative_to(top)
if not self.dereference(str(dest)):
zf.write(str(source), str(dest))
| ResearchObject/ro-crate-py | 41f7646303bb27a148d5f964f24cd70a1db6fbc2 | diff --git a/test/test_write.py b/test/test_write.py
index 63fdc85..c83797c 100644
--- a/test/test_write.py
+++ b/test/test_write.py
@@ -215,3 +215,17 @@ def test_no_parts(tmpdir, helpers):
json_entities = helpers.read_json_entities(out_path)
helpers.check_crate(json_entities)
assert "hasPart" not in json_entities["./"]
+
+
+def test_no_zip_in_zip(test_data_dir, tmpdir):
+ crate_dir = test_data_dir / 'ro-crate-galaxy-sortchangecase'
+ crate = ROCrate(crate_dir)
+
+ zip_name = 'ro_crate_out.crate.zip'
+ zip_path = crate_dir / zip_name # within the crate dir
+ crate.write_zip(zip_path)
+ out_path = tmpdir / 'ro_crate_out'
+ with zipfile.ZipFile(zip_path, "r") as zf:
+ zf.extractall(out_path)
+
+ assert not (out_path / zip_name).exists()
| write_zip should not include the new archive in itself
If one calls `write_zip` with an output path that is within the RO-crate directory, the new zip file ends up inside itself. As `write_zip` walks the directory tree it'll find the partially written zip file and copy it into the archive. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/test_write.py::test_no_zip_in_zip"
] | [
"test/test_write.py::test_file_writing[False-False]",
"test/test_write.py::test_file_writing[False-True]",
"test/test_write.py::test_file_writing[True-False]",
"test/test_write.py::test_file_writing[True-True]",
"test/test_write.py::test_file_stringio",
"test/test_write.py::test_remote_uri[False]",
"test/test_write.py::test_remote_uri[True]",
"test/test_write.py::test_remote_uri_exceptions",
"test/test_write.py::test_missing_source[False-False]",
"test/test_write.py::test_missing_source[False-True]",
"test/test_write.py::test_missing_source[True-False]",
"test/test_write.py::test_missing_source[True-True]",
"test/test_write.py::test_stringio_no_dest[False-False]",
"test/test_write.py::test_stringio_no_dest[False-True]",
"test/test_write.py::test_stringio_no_dest[True-False]",
"test/test_write.py::test_stringio_no_dest[True-True]",
"test/test_write.py::test_no_source_no_dest[False-False]",
"test/test_write.py::test_no_source_no_dest[False-True]",
"test/test_write.py::test_no_source_no_dest[True-False]",
"test/test_write.py::test_no_source_no_dest[True-True]",
"test/test_write.py::test_dataset",
"test/test_write.py::test_no_parts"
] | {
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
} | "2021-06-16T15:46:37Z" | apache-2.0 |
|
ResearchObject__ro-crate-py-75 | diff --git a/rocrate/cli.py b/rocrate/cli.py
index 7512383..0f02132 100644
--- a/rocrate/cli.py
+++ b/rocrate/cli.py
@@ -39,25 +39,23 @@ class State:
@click.pass_context
def cli(ctx, crate_dir):
ctx.obj = state = State()
- state.crate_dir = crate_dir
+ state.crate_dir = os.getcwd() if not crate_dir else os.path.abspath(crate_dir)
@cli.command()
@click.option('--gen-preview', is_flag=True)
@click.pass_obj
def init(state, gen_preview):
- crate_dir = state.crate_dir or os.getcwd()
- crate = ROCrate(crate_dir, init=True, gen_preview=gen_preview)
- crate.metadata.write(crate_dir)
+ crate = ROCrate(state.crate_dir, init=True, gen_preview=gen_preview)
+ crate.metadata.write(state.crate_dir)
if crate.preview:
- crate.preview.write(crate_dir)
+ crate.preview.write(state.crate_dir)
@cli.group()
@click.pass_obj
def add(state):
- crate_dir = state.crate_dir or os.getcwd()
- state.crate = ROCrate(crate_dir, init=False, gen_preview=False)
+ state.crate = ROCrate(state.crate_dir, init=False, gen_preview=False)
@add.command()
@@ -65,16 +63,15 @@ def add(state):
@click.option('-l', '--language', type=click.Choice(LANG_CHOICES), default="cwl")
@click.pass_obj
def workflow(state, path, language):
- crate_dir = state.crate_dir or os.getcwd()
source = Path(path).resolve(strict=True)
try:
- dest_path = source.relative_to(crate_dir)
+ dest_path = source.relative_to(state.crate_dir)
except ValueError:
# For now, only support marking an existing file as a workflow
- raise ValueError(f"{source} is not in the crate dir")
+ raise ValueError(f"{source} is not in the crate dir {state.crate_dir}")
# TODO: add command options for main and gen_cwl
state.crate.add_workflow(source, dest_path, main=True, lang=language, gen_cwl=False)
- state.crate.metadata.write(crate_dir)
+ state.crate.metadata.write(state.crate_dir)
@add.command(name="test-suite")
@@ -83,9 +80,8 @@ def workflow(state, path, language):
@click.option('-m', '--main-entity')
@click.pass_obj
def suite(state, identifier, name, main_entity):
- crate_dir = state.crate_dir or os.getcwd()
suite_ = state.crate.add_test_suite(identifier=identifier, name=name, main_entity=main_entity)
- state.crate.metadata.write(crate_dir)
+ state.crate.metadata.write(state.crate_dir)
print(suite_.id)
@@ -98,9 +94,8 @@ def suite(state, identifier, name, main_entity):
@click.option('-n', '--name')
@click.pass_obj
def instance(state, suite, url, resource, service, identifier, name):
- crate_dir = state.crate_dir or os.getcwd()
instance_ = state.crate.add_test_instance(suite, url, resource=resource, service=service, identifier=identifier, name=name)
- state.crate.metadata.write(crate_dir)
+ state.crate.metadata.write(state.crate_dir)
print(instance_.id)
@@ -111,23 +106,21 @@ def instance(state, suite, url, resource, service, identifier, name):
@click.option('-v', '--engine-version')
@click.pass_obj
def definition(state, suite, path, engine, engine_version):
- crate_dir = state.crate_dir or os.getcwd()
source = Path(path).resolve(strict=True)
try:
- dest_path = source.relative_to(crate_dir)
+ dest_path = source.relative_to(state.crate_dir)
except ValueError:
# For now, only support marking an existing file as a test definition
- raise ValueError(f"{source} is not in the crate dir")
+ raise ValueError(f"{source} is not in the crate dir {state.crate_dir}")
state.crate.add_test_definition(suite, source=source, dest_path=dest_path, engine=engine, engine_version=engine_version)
- state.crate.metadata.write(crate_dir)
+ state.crate.metadata.write(state.crate_dir)
@cli.command()
@click.argument('dst', type=click.Path(writable=True))
@click.pass_obj
def write_zip(state, dst):
- crate_dir = state.crate_dir or os.getcwd()
- crate = ROCrate(crate_dir, init=True, gen_preview=False)
+ crate = ROCrate(state.crate_dir, init=True, gen_preview=False)
crate.write_zip(dst)
diff --git a/rocrate/model/file.py b/rocrate/model/file.py
index 4b5cc50..8005fcf 100644
--- a/rocrate/model/file.py
+++ b/rocrate/model/file.py
@@ -20,10 +20,9 @@
import os
from pathlib import Path
import shutil
-import urllib
+import urllib.request
from io import IOBase
-from shutil import copy
from urllib.error import HTTPError
from .data_entity import DataEntity
@@ -38,20 +37,14 @@ class File(DataEntity):
properties = {}
self.fetch_remote = fetch_remote
self.source = source
- is_local = is_remote = False
- if isinstance(source, (str, Path)):
- is_local = os.path.isfile(str(source))
- is_remote = is_url(str(source))
- if not is_local and not is_remote:
- raise ValueError(f"'{source}' is not a path to a local file or a valid remote URI")
- elif dest_path is None:
+ if not isinstance(source, (str, Path)) and dest_path is None:
raise ValueError("dest_path must be provided if source is not a path or URI")
if dest_path:
# the entity is refrencing a path relative to the ro-crate root
identifier = Path(dest_path).as_posix() # relative path?
else:
# if there is no dest_path there must be a URI/local path as source
- if is_local:
+ if not is_url(str(source)):
# local source -> becomes local reference = reference relative
# to ro-crate root
identifier = os.path.basename(source)
@@ -105,23 +98,16 @@ class File(DataEntity):
out_file_path.parent.mkdir(parents=True, exist_ok=True)
with open(out_file_path, 'w') as out_file:
out_file.write(self.source.getvalue())
- else:
- if os.path.isfile(self.source):
- out_file_path.parent.mkdir(parents=True, exist_ok=True)
- copy(self.source, out_file_path)
- else:
- if self.fetch_remote:
- # Legacy version
- # urllib.request.urlretrieve(self.source, out_file_path)
- # can check that the encodingFormat and contentSize matches
- # the request data? i.e.:
- # response.getheader('Content-Length') == \
- # self._jsonld['contentSize']
- # this would help check if the dataset to be retrieved is
- # in fact what was registered in the first place.
- out_file_path.parent.mkdir(parents=True, exist_ok=True)
- with urllib.request.urlopen(self.source) as response, open(out_file_path, 'wb') as out_file:
- shutil.copyfileobj(response, out_file)
+ elif is_url(str(self.source)) and self.fetch_remote:
+ # Should we check that the resource hasn't changed? E.g., compare
+ # response.getheader('Content-Length') to self._jsonld['contentSize'] or
+ # response.getheader('Content-Type') to self._jsonld['encodingFormat']
+ out_file_path.parent.mkdir(parents=True, exist_ok=True)
+ with urllib.request.urlopen(self.source) as response, open(out_file_path, 'wb') as out_file:
+ shutil.copyfileobj(response, out_file)
+ elif os.path.isfile(self.source):
+ out_file_path.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copy(self.source, out_file_path)
def write_zip(self, zip_out):
if self.id not in zip_out.namelist():
diff --git a/rocrate/rocrate.py b/rocrate/rocrate.py
index a968f10..029b8e3 100644
--- a/rocrate/rocrate.py
+++ b/rocrate/rocrate.py
@@ -21,7 +21,6 @@ import importlib
import json
import os
import uuid
-import requests
import zipfile
import atexit
import shutil
@@ -206,25 +205,21 @@ class ROCrate():
if 'File' in entity_types:
# temporary workaround, should be handled in the general case
cls = TestDefinition if "TestDefinition" in entity_types else File
- file_path = os.path.join(source, entity['@id'])
- identifier = entity.pop('@id', None)
- if os.path.exists(file_path):
- # referencing a file path relative to crate-root
- instance = cls(self, file_path, identifier, properties=entity)
+ identifier = entity['@id']
+ props = {k: v for k, v in entity.items() if k != '@id'}
+ if is_url(identifier):
+ instance = cls(self, source=identifier, properties=props)
else:
- # check if it is a valid absolute URI
- try:
- requests.get(identifier)
- instance = cls(self, identifier, properties=entity)
- except requests.ConnectionError:
- print("Source is not a valid URI")
+ instance = cls(
+ self,
+ source=os.path.join(source, identifier),
+ dest_path=identifier,
+ properties=props
+ )
if 'Dataset' in entity_types:
dir_path = os.path.join(source, entity['@id'])
- if os.path.exists(dir_path):
- props = {k: v for k, v in entity.items() if k != '@id'}
- instance = Dataset(self, dir_path, entity['@id'], props)
- else:
- raise Exception('Directory not found')
+ props = {k: v for k, v in entity.items() if k != '@id'}
+ instance = Dataset(self, dir_path, entity['@id'], props)
self.add(instance)
added_entities.append(data_entity_id)
| ResearchObject/ro-crate-py | 44e730c9bee4ffd312e8f81772deee47a509ba0a | diff --git a/test/test_read.py b/test/test_read.py
index a3e334b..e170040 100644
--- a/test/test_read.py
+++ b/test/test_read.py
@@ -269,3 +269,32 @@ def test_extra_data(test_data_dir, tmpdir, to_zip):
assert (out_path / rel).is_file()
with open(crate_dir / rel) as f1, open(out_path / rel) as f2:
assert f1.read() == f2.read()
+
+
+def test_missing_dir(test_data_dir, tmpdir):
+ crate_dir = test_data_dir / 'read_crate'
+ name = 'examples'
+ shutil.rmtree(crate_dir / name)
+ crate = ROCrate(crate_dir)
+
+ examples_dataset = crate.dereference(name)
+ assert examples_dataset.id == f'{name}/'
+
+ out_path = tmpdir / 'crate_read_out'
+ crate.write_crate(out_path)
+ assert not (out_path / 'README.txt').exists()
+
+
+def test_missing_file(test_data_dir, tmpdir):
+ crate_dir = test_data_dir / 'read_crate'
+ name = 'test_file_galaxy.txt'
+ test_path = crate_dir / name
+ test_path.unlink()
+ crate = ROCrate(crate_dir)
+
+ test_file = crate.dereference(name)
+ assert test_file.id == name
+
+ out_path = tmpdir / 'crate_read_out'
+ crate.write_crate(out_path)
+ assert not (out_path / name).exists()
diff --git a/test/test_write.py b/test/test_write.py
index c83797c..102d793 100644
--- a/test/test_write.py
+++ b/test/test_write.py
@@ -165,14 +165,22 @@ def test_remote_uri_exceptions(tmpdir):
@pytest.mark.parametrize("fetch_remote,validate_url", [(False, False), (False, True), (True, False), (True, True)])
-def test_missing_source(test_data_dir, fetch_remote, validate_url):
- crate = ROCrate()
+def test_missing_source(test_data_dir, tmpdir, fetch_remote, validate_url):
path = test_data_dir / uuid.uuid4().hex
- with pytest.raises(ValueError):
- crate.add_file(str(path), fetch_remote=fetch_remote, validate_url=validate_url)
+ args = {"fetch_remote": fetch_remote, "validate_url": validate_url}
- with pytest.raises(ValueError):
- crate.add_file(str(path), path.name, fetch_remote=fetch_remote, validate_url=validate_url)
+ crate = ROCrate()
+ file_ = crate.add_file(str(path), **args)
+ assert file_ is crate.dereference(path.name)
+ out_path = tmpdir / 'ro_crate_out_1'
+ crate.write_crate(out_path)
+ assert not (out_path / path.name).exists()
+
+ crate = ROCrate()
+ file_ = crate.add_file(str(path), path.name, **args)
+ assert file_ is crate.dereference(path.name)
+ out_path = tmpdir / 'ro_crate_out_2'
+ assert not (out_path / path.name).exists()
@pytest.mark.parametrize("fetch_remote,validate_url", [(False, False), (False, True), (True, False), (True, True)])
| Bug? Fails to load a crate file without its data entities (directories)
I think this is a bug.
On loading a directory with ONLY the sample file from here: https://raw.githubusercontent.com/ResearchObject/example-ro-sample-image-crate/main/sample-crate/ro-crate-metadata.jsonld
```
from rocrate.rocrate import ROCrate
crate = ROCrate("sample")
```
It dies like this:
```
Traceback (most recent call last):
File "/Users/pt/working/ro-crate-py/test.py", line 3, in <module>
crate = ROCrate("sample")
File "/Users/pt/rocrate/lib/python3.9/site-packages/rocrate/rocrate.py", line 92, in __init__
self.build_crate(entities, source_path, gen_preview)
File "/Users/pt/rocrate/lib/python3.9/site-packages/rocrate/rocrate.py", line 226, in build_crate
raise Exception('Directory not found')
Exception: Directory not found
```
Expected behaviour:
I would expect to be able to load an incomplete crate if I am:
- Writing an HTML renderer
- Writing a validator and I want to report all the errors (rather than dying on the first one
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/test_read.py::test_missing_dir",
"test/test_read.py::test_missing_file",
"test/test_write.py::test_missing_source[False-False]",
"test/test_write.py::test_missing_source[False-True]",
"test/test_write.py::test_missing_source[True-False]",
"test/test_write.py::test_missing_source[True-True]"
] | [
"test/test_read.py::test_crate_dir_loading[False-False]",
"test/test_read.py::test_crate_dir_loading[True-False]",
"test/test_read.py::test_crate_dir_loading[True-True]",
"test/test_read.py::test_legacy_crate",
"test/test_read.py::test_bad_crate",
"test/test_read.py::test_init[False]",
"test/test_read.py::test_init[True]",
"test/test_read.py::test_init_preview[False-False]",
"test/test_read.py::test_init_preview[False-True]",
"test/test_read.py::test_init_preview[True-False]",
"test/test_read.py::test_init_preview[True-True]",
"test/test_read.py::test_no_parts",
"test/test_read.py::test_extra_data[False]",
"test/test_read.py::test_extra_data[True]",
"test/test_write.py::test_file_writing[False-False]",
"test/test_write.py::test_file_writing[False-True]",
"test/test_write.py::test_file_writing[True-False]",
"test/test_write.py::test_file_writing[True-True]",
"test/test_write.py::test_file_stringio",
"test/test_write.py::test_remote_uri[False]",
"test/test_write.py::test_remote_uri[True]",
"test/test_write.py::test_remote_uri_exceptions",
"test/test_write.py::test_stringio_no_dest[False-False]",
"test/test_write.py::test_stringio_no_dest[False-True]",
"test/test_write.py::test_stringio_no_dest[True-False]",
"test/test_write.py::test_stringio_no_dest[True-True]",
"test/test_write.py::test_no_source_no_dest[False-False]",
"test/test_write.py::test_no_source_no_dest[False-True]",
"test/test_write.py::test_no_source_no_dest[True-False]",
"test/test_write.py::test_no_source_no_dest[True-True]",
"test/test_write.py::test_dataset",
"test/test_write.py::test_no_parts",
"test/test_write.py::test_no_zip_in_zip"
] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2021-10-01T15:42:40Z" | apache-2.0 |
|
ResearchObject__ro-crate-py-76 | diff --git a/rocrate/model/data_entity.py b/rocrate/model/data_entity.py
index d04d364..e9acbe5 100644
--- a/rocrate/model/data_entity.py
+++ b/rocrate/model/data_entity.py
@@ -24,13 +24,14 @@ from .entity import Entity
class DataEntity(Entity):
- def __init__(self, crate, identifier, properties=None):
- if not identifier or str(identifier).startswith("#"):
- raise ValueError("Identifier for data entity must be a relative path or absolute URI: %s" % identifier)
- super(DataEntity, self).__init__(crate, identifier, properties)
-
def filepath(self, base_path=None):
if base_path:
return os.path.join(base_path, self.id)
else:
return self.id
+
+ def write(self, base_path):
+ pass
+
+ def write_zip(self, zip_out):
+ pass
diff --git a/rocrate/rocrate.py b/rocrate/rocrate.py
index 029b8e3..b213172 100644
--- a/rocrate/rocrate.py
+++ b/rocrate/rocrate.py
@@ -32,6 +32,7 @@ from urllib.parse import urljoin
from .model import contextentity
from .model.entity import Entity
from .model.root_dataset import RootDataset
+from .model.data_entity import DataEntity
from .model.file import File
from .model.dataset import Dataset
from .model.metadata import Metadata, LegacyMetadata, TESTING_EXTRA_TERMS
@@ -186,42 +187,39 @@ class ROCrate():
added_entities = []
# iterate over data entities
for data_entity_ref in root_entity_parts:
- data_entity_id = data_entity_ref['@id']
- # print(data_entity_id)
- entity = entities[data_entity_id]
- # basic checks should be moved to a separate function
- if '@type' not in entity.keys():
- raise Exception("Entity with @id:" + data_entity_id +
- " has no type defined")
-
- # Data entities can have an array as @type. So far we just parse
- # them as File class if File is in the list. For further
- # extensions (e.g if a Workflow class is created) we can add extra
- # cases or create a mapping table for specific combinations. See
+ id_ = data_entity_ref['@id']
+ entity = entities[id_]
+ try:
+ t = entity["@type"]
+ except KeyError:
+ raise ValueError(f'entity "{id_}" has no @type')
+ types = {_.strip() for _ in set(t if isinstance(t, list) else [t])}
+ # Deciding what to instantiate is not trivial, see
# https://github.com/ResearchObject/ro-crate/issues/83
- entity_types = (entity['@type']
- if isinstance(entity['@type'], list)
- else [entity['@type']])
- if 'File' in entity_types:
+ if {'File', 'Dataset'} <= types:
+ raise ValueError("entity can't have both File and Dataset types")
+ if 'File' in types:
# temporary workaround, should be handled in the general case
- cls = TestDefinition if "TestDefinition" in entity_types else File
- identifier = entity['@id']
+ cls = TestDefinition if "TestDefinition" in types else File
props = {k: v for k, v in entity.items() if k != '@id'}
- if is_url(identifier):
- instance = cls(self, source=identifier, properties=props)
+ if is_url(id_):
+ instance = cls(self, source=id_, properties=props)
else:
instance = cls(
self,
- source=os.path.join(source, identifier),
- dest_path=identifier,
+ source=os.path.join(source, id_),
+ dest_path=id_,
properties=props
)
- if 'Dataset' in entity_types:
- dir_path = os.path.join(source, entity['@id'])
+ elif 'Dataset' in types:
+ dir_path = os.path.join(source, id_)
props = {k: v for k, v in entity.items() if k != '@id'}
- instance = Dataset(self, dir_path, entity['@id'], props)
+ instance = Dataset(self, dir_path, id_, props)
+ else:
+ props = {k: v for k, v in entity.items() if k != '@id'}
+ instance = DataEntity(self, identifier=id_, properties=props)
self.add(instance)
- added_entities.append(data_entity_id)
+ added_entities.append(id_)
# the rest of the entities must be contextual entities
prebuilt_entities = [
| ResearchObject/ro-crate-py | 7421fadf3836bb275a770999450059ef0219867e | diff --git a/test/test_model.py b/test/test_model.py
index aaf5169..e9d211c 100644
--- a/test/test_model.py
+++ b/test/test_model.py
@@ -20,7 +20,9 @@ import uuid
import pytest
from rocrate.rocrate import ROCrate
+from rocrate.model.data_entity import DataEntity
from rocrate.model.file import File
+from rocrate.model.dataset import Dataset
from rocrate.model.computationalworkflow import ComputationalWorkflow
from rocrate.model.person import Person
from rocrate.model.preview import Preview
@@ -70,6 +72,16 @@ def test_dereferencing_equivalent_id(test_data_dir, name):
assert deref_entity is entity
+def test_data_entities(test_data_dir):
+ crate = ROCrate()
+ file_ = crate.add(File(crate, test_data_dir / 'sample_file.txt'))
+ dataset = crate.add(Dataset(crate, test_data_dir / 'test_add_dir'))
+ data_entity = crate.add(DataEntity(crate, '#mysterious'))
+ assert set(crate.data_entities) == {file_, dataset, data_entity}
+ part_ids = set(_["@id"] for _ in crate.root_dataset._jsonld["hasPart"])
+ assert set(_.id for _ in (file_, dataset, data_entity)) <= part_ids
+
+
def test_contextual_entities():
crate = ROCrate()
new_person = crate.add(Person(crate, '#joe', {'name': 'Joe Pesci'}))
diff --git a/test/test_read.py b/test/test_read.py
index e170040..67f19b1 100644
--- a/test/test_read.py
+++ b/test/test_read.py
@@ -15,6 +15,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
+import json
import pytest
import shutil
import uuid
@@ -22,6 +23,7 @@ import zipfile
from pathlib import Path
from rocrate.rocrate import ROCrate
+from rocrate.model.data_entity import DataEntity
from rocrate.model.file import File
from rocrate.model.dataset import Dataset
@@ -298,3 +300,58 @@ def test_missing_file(test_data_dir, tmpdir):
out_path = tmpdir / 'crate_read_out'
crate.write_crate(out_path)
assert not (out_path / name).exists()
+
+
+def test_generic_data_entity(tmpdir):
+ rc_id = "#collection"
+ metadata = {
+ "@context": [
+ "https://w3id.org/ro/crate/1.1/context",
+ {"@vocab": "http://schema.org/"},
+ {"@base": None}
+ ],
+ "@graph": [
+ {
+ "@id": "ro-crate-metadata.json",
+ "@type": "CreativeWork",
+ "about": {
+ "@id": "./"
+ },
+ "identifier": "ro-crate-metadata.json"
+ },
+ {
+ "@id": "./",
+ "@type": "Dataset",
+ "hasPart": [{"@id": rc_id}],
+ "name": "Test RepositoryCollection"
+ },
+ {
+ "@id": rc_id,
+ "@type": "RepositoryCollection",
+ "name": "Test collection"
+ }
+ ]
+ }
+ crate_dir = tmpdir / "test_repository_collection"
+ crate_dir.mkdir()
+ with open(crate_dir / "ro-crate-metadata.json", "wt") as f:
+ json.dump(metadata, f, indent=4)
+ crate = ROCrate(crate_dir)
+
+ def check_rc():
+ rc = crate.dereference(rc_id)
+ assert rc is not None
+ assert isinstance(rc, DataEntity)
+ assert rc.id == rc_id
+ assert rc.type == "RepositoryCollection"
+ assert rc._jsonld["name"] == "Test collection"
+ assert crate.data_entities == [rc]
+ assert not crate.contextual_entities
+
+ check_rc()
+
+ out_crate_dir = tmpdir / "output_crate"
+ crate.write_crate(out_crate_dir)
+ crate = ROCrate(out_crate_dir)
+
+ check_rc()
| Bug: Won't load a crate with hasPart reference to a RepositoryCollection.
Loading the below test data gives an error:
```
File "/Users/pt/working/ro-crate-py/test.py", line 3, in <module>
crate = ROCrate("haspart")
File "/Users/pt/rocrate/lib/python3.9/site-packages/rocrate/rocrate.py", line 92, in __init__
self.build_crate(entities, source_path, gen_preview)
File "/Users/pt/rocrate/lib/python3.9/site-packages/rocrate/rocrate.py", line 227, in build_crate
self.add(instance)
UnboundLocalError: local variable 'instance' referenced before assignment
```
I would expect to be able to load anything with a flat JSON-LD structure even if it's not schema.org compliant.
Here's the offending ro-crate-metadata.json
```json
{
"@context": [
"https://w3id.org/ro/crate/1.1/context",
{
"@vocab": "http://schema.org/"
},
{
"@base": null
}
],
"@graph": [
{
"@id": "#collection",
"@type": "RepositoryCollection ",
"name": "Test collection"
},
{
"@id": "./",
"@type": "Dataset",
"hasFile": [],
"hasPart": [{"@id": "#collection"}],
"name": "testing hasPart"
},
{
"@id": "ro-crate-metadata.json",
"@type": "CreativeWork",
"about": {
"@id": "./"
},
"identifier": "ro-crate-metadata.json"
}
]
}
``` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/test_model.py::test_data_entities",
"test/test_read.py::test_generic_data_entity"
] | [
"test/test_model.py::test_dereferencing",
"test/test_model.py::test_dereferencing_equivalent_id[.foo]",
"test/test_model.py::test_dereferencing_equivalent_id[foo.]",
"test/test_model.py::test_dereferencing_equivalent_id[.foo/]",
"test/test_model.py::test_dereferencing_equivalent_id[foo./]",
"test/test_model.py::test_contextual_entities",
"test/test_model.py::test_properties",
"test/test_model.py::test_uuid",
"test/test_model.py::test_update",
"test/test_model.py::test_delete",
"test/test_model.py::test_delete_refs",
"test/test_model.py::test_delete_by_id",
"test/test_model.py::test_self_delete",
"test/test_read.py::test_crate_dir_loading[False-False]",
"test/test_read.py::test_crate_dir_loading[True-False]",
"test/test_read.py::test_crate_dir_loading[True-True]",
"test/test_read.py::test_legacy_crate",
"test/test_read.py::test_bad_crate",
"test/test_read.py::test_init[False]",
"test/test_read.py::test_init[True]",
"test/test_read.py::test_init_preview[False-False]",
"test/test_read.py::test_init_preview[False-True]",
"test/test_read.py::test_init_preview[True-False]",
"test/test_read.py::test_init_preview[True-True]",
"test/test_read.py::test_no_parts",
"test/test_read.py::test_extra_data[False]",
"test/test_read.py::test_extra_data[True]",
"test/test_read.py::test_missing_dir",
"test/test_read.py::test_missing_file"
] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2021-10-04T10:43:34Z" | apache-2.0 |
|
ResearchObject__ro-crate-py-95 | diff --git a/rocrate/model/preview.py b/rocrate/model/preview.py
index 553eacc..03013b9 100644
--- a/rocrate/model/preview.py
+++ b/rocrate/model/preview.py
@@ -32,8 +32,8 @@ class Preview(File):
"""
BASENAME = "ro-crate-preview.html"
- def __init__(self, crate, source=None):
- super().__init__(crate, source, self.BASENAME, None)
+ def __init__(self, crate, source=None, properties=None):
+ super().__init__(crate, source, self.BASENAME, properties=properties)
def _empty(self):
# default properties of the metadata entry
diff --git a/rocrate/rocrate.py b/rocrate/rocrate.py
index 8e3564e..af7a1cb 100644
--- a/rocrate/rocrate.py
+++ b/rocrate/rocrate.py
@@ -180,8 +180,9 @@ class ROCrate():
assert root_id == root_entity.pop('@id')
parts = root_entity.pop('hasPart', [])
self.add(RootDataset(self, properties=root_entity))
- if not gen_preview and Preview.BASENAME in entities:
- self.add(Preview(self, source / Preview.BASENAME))
+ preview_entity = entities.pop(Preview.BASENAME, None)
+ if preview_entity and not gen_preview:
+ self.add(Preview(self, source / Preview.BASENAME, properties=preview_entity))
type_map = OrderedDict((_.__name__, _) for _ in subclasses(FileOrDir))
for data_entity_ref in parts:
id_ = data_entity_ref['@id']
| ResearchObject/ro-crate-py | 7a5d25f3f4f8f4ca68f42cc582cf61378589bbe2 | diff --git a/test/test_read.py b/test/test_read.py
index 8db4036..ac173f1 100644
--- a/test/test_read.py
+++ b/test/test_read.py
@@ -33,7 +33,6 @@ _URL = ('https://raw.githubusercontent.com/ResearchObject/ro-crate-py/master/'
@pytest.mark.parametrize("gen_preview,from_zip", [(False, False), (True, False), (True, True)])
def test_crate_dir_loading(test_data_dir, tmpdir, helpers, gen_preview, from_zip):
- # load crate
crate_dir = test_data_dir / 'read_crate'
if from_zip:
zip_source = shutil.make_archive(tmpdir / "read_crate.crate", "zip", crate_dir)
@@ -41,7 +40,21 @@ def test_crate_dir_loading(test_data_dir, tmpdir, helpers, gen_preview, from_zip
else:
crate = ROCrate(crate_dir, gen_preview=gen_preview)
- # check loaded entities and properties
+ assert set(_["@id"] for _ in crate.default_entities) == {
+ "./",
+ "ro-crate-metadata.json",
+ "ro-crate-preview.html"
+ }
+ assert set(_["@id"] for _ in crate.data_entities) == {
+ "test_galaxy_wf.ga",
+ "abstract_wf.cwl",
+ "test_file_galaxy.txt",
+ "https://raw.githubusercontent.com/ResearchObject/ro-crate-py/master/test/test-data/sample_file.txt",
+ "examples/",
+ "test/",
+ }
+ assert set(_["@id"] for _ in crate.contextual_entities) == {"#joe"}
+
root = crate.dereference('./')
assert crate.root_dataset is root
root_prop = root.properties()
| Duplicate preview entry in output crate
```python
import shutil
from rocrate.rocrate import ROCrate
shutil.rmtree("/tmp/out_crate", ignore_errors=True)
crate = ROCrate("test/test-data/read_crate")
crate.write("/tmp/out_crate")
```
The output crate has:
```javascript
{
"@id": "ro-crate-preview.html",
"@type": "CreativeWork",
"about": {
"@id": "./"
}
},
```
but also:
```javascript
{
"@id": "#ro-crate-preview.html",
"@type": "CreativeWork",
"about": {
"@id": "./"
}
},
``` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/test_read.py::test_crate_dir_loading[False-False]",
"test/test_read.py::test_crate_dir_loading[True-False]",
"test/test_read.py::test_crate_dir_loading[True-True]"
] | [
"test/test_read.py::test_legacy_crate",
"test/test_read.py::test_bad_crate",
"test/test_read.py::test_init[False]",
"test/test_read.py::test_init[True]",
"test/test_read.py::test_init_preview[False-False]",
"test/test_read.py::test_init_preview[False-True]",
"test/test_read.py::test_init_preview[True-False]",
"test/test_read.py::test_init_preview[True-True]",
"test/test_read.py::test_no_parts",
"test/test_read.py::test_extra_data[False]",
"test/test_read.py::test_extra_data[True]",
"test/test_read.py::test_missing_dir",
"test/test_read.py::test_missing_file",
"test/test_read.py::test_generic_data_entity"
] | {
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2021-11-19T13:55:00Z" | apache-2.0 |
|
ResearchObject__runcrate-69 | diff --git a/src/runcrate/convert.py b/src/runcrate/convert.py
index 0d76432..ff48935 100644
--- a/src/runcrate/convert.py
+++ b/src/runcrate/convert.py
@@ -566,6 +566,8 @@ class ProvCrateBuilder:
))
if len(action_p["exampleOfWork"]) == 1:
action_p["exampleOfWork"] = action_p["exampleOfWork"][0]
+ if ptype == "generation":
+ action_p["dateCreated"] = rel.time.isoformat()
action_params.append(action_p)
return action_params
@@ -606,6 +608,7 @@ class ProvCrateBuilder:
source = self.manifest[hash_]
action_p = crate.add_file(source, dest, properties={
"sha1": hash_,
+ "contentSize": str(Path(source).stat().st_size)
})
self._set_alternate_name(prov_param, action_p, parent=parent)
try:
@@ -739,9 +742,9 @@ class ProvCrateBuilder:
if "ComputationalWorkflow" in as_list(tool.type):
self.patch_workflow_input_collection(crate, wf=tool)
- def _map_input_data(self, data):
+ def _map_input_data(self, crate, data):
if isinstance(data, list):
- return [self._map_input_data(_) for _ in data]
+ return [self._map_input_data(crate, _) for _ in data]
if isinstance(data, dict):
rval = {}
for k, v in data.items():
@@ -753,8 +756,13 @@ class ProvCrateBuilder:
source_k = str(source)
dest = self.file_map.get(source_k)
rval[k] = str(dest) if dest else v
+ fmt = data.get("format")
+ if fmt:
+ entity = crate.get(str(dest))
+ if entity:
+ entity["encodingFormat"] = fmt
else:
- rval[k] = self._map_input_data(v)
+ rval[k] = self._map_input_data(crate, v)
return rval
return data
@@ -763,7 +771,7 @@ class ProvCrateBuilder:
if path.is_file():
with open(path) as f:
data = json.load(f)
- data = self._map_input_data(data)
+ data = self._map_input_data(crate, data)
source = StringIO(json.dumps(data, indent=4))
crate.add_file(source, path.name, properties={
"name": "input object document",
| ResearchObject/runcrate | c27ed1181e0781a22481f1efd7a79879cb33505c | diff --git a/tests/test_cwlprov_crate_builder.py b/tests/test_cwlprov_crate_builder.py
index 416351f..0f6404d 100644
--- a/tests/test_cwlprov_crate_builder.py
+++ b/tests/test_cwlprov_crate_builder.py
@@ -95,10 +95,14 @@ def test_revsort(data_dir, tmpdir):
assert "File" in entity.type
assert entity["alternateName"] == "whale.txt"
assert entity["sha1"] == entity.id.rsplit("/")[-1]
+ assert entity["contentSize"] == "1111"
+ assert "encodingFormat" in entity
wf_input_file = entity
wf_output_file = wf_results[0]
assert wf_output_file["alternateName"] == "output.txt"
assert wf_output_file["sha1"] == wf_output_file.id.rsplit("/")[-1]
+ assert wf_output_file["dateCreated"] == "2018-10-25T15:46:38.058365"
+ assert wf_output_file["contentSize"] == "1111"
assert "File" in wf_output_file.type
steps = workflow["step"]
assert len(steps) == 2
@@ -118,6 +122,8 @@ def test_revsort(data_dir, tmpdir):
assert rev_input_file is wf_input_file
rev_output_file = results[0]
assert "File" in rev_output_file.type
+ assert rev_output_file["dateCreated"] == "2018-10-25T15:46:36.963254"
+ assert rev_output_file["contentSize"] == "1111"
assert step["position"] == "0"
assert set(_connected(step)) == set([
("packed.cwl#main/input", "packed.cwl#revtool.cwl/input"),
@@ -357,6 +363,7 @@ def test_dir_io(data_dir, tmpdir):
assert "Dataset" in entity.type
wf_input_dir = entity
wf_output_dir = wf_results[0]
+ assert wf_output_dir["dateCreated"] == "2023-02-17T16:20:30.288242"
assert wf_input_dir.type == wf_output_dir.type == "Dataset"
assert wf_input_dir["alternateName"] == "grepucase_in"
assert len(wf_input_dir["hasPart"]) == 2
@@ -395,6 +402,7 @@ def test_dir_io(data_dir, tmpdir):
assert greptool_input_dir is wf_input_dir
greptool_output_dir = greptool_results[0]
assert "Dataset" in greptool_output_dir.type
+ assert greptool_output_dir["dateCreated"] == "2023-02-17T16:20:30.262141"
ucasetool_action = action_map["packed.cwl#ucasetool.cwl"]
ucasetool_objects = ucasetool_action["object"]
ucasetool_results = ucasetool_action["result"]
| CWLProv conversion: include creation datetime, size, checksum, format
See https://github.com/RenskeW/runcrate-analysis/issues/2
Mappings:
* creation datetime: [dateCreated](https://schema.org/dateCreated) (there's a `prov:time` field in `wasGeneratedBy` entries)
* size: [contentSize](https://schema.org/contentSize)
* checksum: see https://github.com/ResearchObject/ro-terms/pull/15
* format: [encodingFormat](https://schema.org/encodingFormat) (on the `File` entity -- we already add it to the `FormalParameter`) | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_cwlprov_crate_builder.py::test_revsort",
"tests/test_cwlprov_crate_builder.py::test_dir_io"
] | [
"tests/test_cwlprov_crate_builder.py::test_no_input",
"tests/test_cwlprov_crate_builder.py::test_param_types",
"tests/test_cwlprov_crate_builder.py::test_no_output",
"tests/test_cwlprov_crate_builder.py::test_scatter_pvs",
"tests/test_cwlprov_crate_builder.py::test_subworkflows",
"tests/test_cwlprov_crate_builder.py::test_passthrough",
"tests/test_cwlprov_crate_builder.py::test_unset_param",
"tests/test_cwlprov_crate_builder.py::test_secondary_files",
"tests/test_cwlprov_crate_builder.py::test_exampleofwork_duplicates",
"tests/test_cwlprov_crate_builder.py::test_dir_array",
"tests/test_cwlprov_crate_builder.py::test_multisource",
"tests/test_cwlprov_crate_builder.py::test_step_in_nosource",
"tests/test_cwlprov_crate_builder.py::test_multioutputsource",
"tests/test_cwlprov_crate_builder.py::test_conditional_wf",
"tests/test_cwlprov_crate_builder.py::test_revsort_inline[1.0]",
"tests/test_cwlprov_crate_builder.py::test_revsort_inline[1.2]"
] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2023-11-08T15:34:54Z" | apache-2.0 |
|
ReviewNB__treon-25 | diff --git a/treon/treon.py b/treon/treon.py
index 60c75f0..f34f9fe 100644
--- a/treon/treon.py
+++ b/treon/treon.py
@@ -2,7 +2,7 @@
"""
Usage:
treon
- treon [PATH] [--threads=<number>] [-v] [--exclude=<string>]...
+ treon [PATH]... [--threads=<number>] [-v] [--exclude=<string>]...
Arguments:
PATH File or directory path to find notebooks to test. Searches recursively for directory paths. [default: current working directory]
@@ -120,24 +120,29 @@ def filter_results(results, args):
def get_notebooks_to_test(args):
- path = args['PATH'] or os.getcwd()
+ paths = args['PATH'] or [os.getcwd()]
result = []
- if os.path.isdir(path):
- LOG.info('Recursively scanning %s for notebooks...', path)
- path = os.path.join(path, '') # adds trailing slash (/) if it's missing
- glob_path = path + '**/*.ipynb'
- result = glob.glob(glob_path, recursive=True)
- elif os.path.isfile(path):
- if path.lower().endswith('.ipynb'):
- LOG.debug('Testing notebook %s', path)
- result = [path]
+ for path in paths:
+ current_result = []
+
+ if os.path.isdir(path):
+ LOG.info('Recursively scanning %s for notebooks...', path)
+ path = os.path.join(path, '') # adds trailing slash (/) if it's missing
+ glob_path = path + '**/*.ipynb'
+ current_result = glob.glob(glob_path, recursive=True)
+ elif os.path.isfile(path):
+ if path.lower().endswith('.ipynb'):
+ LOG.debug('Testing notebook %s', path)
+ current_result = [path]
+ else:
+ sys.exit('{path} is not a Notebook'.format(path=path))
else:
- sys.exit('{path} is not a Notebook'.format(path=path))
- else:
- sys.exit('{path} is not a valid path'.format(path=path))
+ sys.exit('{path} is not a valid path'.format(path=path))
- if not result:
- sys.exit('No notebooks to test in {path}'.format(path=path))
+ if not current_result:
+ sys.exit('No notebooks to test in {path}'.format(path=path))
+
+ result.extend(current_result)
return filter_results(result, args)
| ReviewNB/treon | c90f964ae714cb7ac78aede2f86753e3d21104ec | diff --git a/tests/test_treon.py b/tests/test_treon.py
index a07dd7a..39d1fd6 100644
--- a/tests/test_treon.py
+++ b/tests/test_treon.py
@@ -68,3 +68,17 @@ def test_filter_results_exclude_is_not_dir(mock_isdir):
filtered = treon.filter_results(results=results, args=args)
expected = []
assert filtered == expected
+
+
+def test_get_notebooks_to_test_with_multiple_paths():
+ notebook_files = [
+ os.path.join(os.path.dirname(__file__), "resources/basic.ipynb"),
+ os.path.join(os.path.dirname(__file__), "resources/unittest_failed.ipynb"),
+ ]
+ args = {
+ "PATH": list(notebook_files),
+ "--exclude": [],
+ }
+ notebooks = treon.get_notebooks_to_test(args=args)
+ expected = notebook_files
+ assert notebooks == expected
| Allow multiple PATHs to be provided
According to `treon --help`, treon is meant to be invoked as
```
treon [PATH] [--threads=<number>] [-v] [--exclude=<string>]...
```
However, it is currently not possible to pass multiple PATHs, unlike many command-line tools (e.g., `cat`). If multiple PATHs are provided, the help text is displayed and nothing else happens.
It is possible to _exclude_ multiple paths (#1), but currently, the only way to include multiple paths (e.g., to test multiple notebooks by individual filename or to test multiple directories) is to invoke treon multiple times sequentially, once for each. But this means that the full benefits of multithreading are not available. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_treon.py::test_get_notebooks_to_test_with_multiple_paths"
] | [
"tests/test_treon.py::test_filter_results_file",
"tests/test_treon.py::test_filter_results_folder",
"tests/test_treon.py::test_filter_results_empty",
"tests/test_treon.py::test_filter_results_homedir",
"tests/test_treon.py::test_filter_results_exclude_is_dir",
"tests/test_treon.py::test_filter_results_exclude_is_not_dir"
] | {
"failed_lite_validators": [
"has_issue_reference"
],
"has_test_patch": true,
"is_lite": false
} | "2022-07-29T02:11:44Z" | mit |
|
RhodiumGroup__rhg_compute_tools-15 | diff --git a/.travis.yml b/.travis.yml
index a67a703..f07100e 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -46,6 +46,12 @@ language: python
python:
- 3.6
script:
-- if [[ "$TEST_ENV" == "conda" ]]; then pytest && sphinx-apidoc -o docs rhg_compute_tools
- && sphinx-build -W -b html -d docs/_build/doctrees docs/. docs/_build/html; else
- tox; fi;
+- if [[ "$TEST_ENV" == "conda" ]];
+ then
+ pytest &&
+ rm docs/rhg_compute_tools*.rst &&
+ sphinx-apidoc -o docs rhg_compute_tools &&
+ sphinx-build -W -b html -d docs/_build/doctrees docs/. docs/_build/html;
+ else
+ tox;
+ fi;
diff --git a/docs/.gitignore b/docs/.gitignore
index a11931c..e69de29 100644
--- a/docs/.gitignore
+++ b/docs/.gitignore
@@ -1,2 +0,0 @@
-/rhg_compute_tools.rst
-/rhg_compute_tools.*.rst
diff --git a/docs/conf.py b/docs/conf.py
index c70b86d..47013ef 100755
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -46,6 +46,7 @@ extensions = [
'sphinx.ext.viewcode',
'sphinx.ext.extlinks',
'sphinx.ext.napoleon',
+ 'sphinx.ext.doctest',
'sphinx.ext.intersphinx']
extlinks = {
diff --git a/docs/rhg_compute_tools.rst b/docs/rhg_compute_tools.rst
index d01b7ea..a3efd4e 100644
--- a/docs/rhg_compute_tools.rst
+++ b/docs/rhg_compute_tools.rst
@@ -1,6 +1,9 @@
-API
+rhg\_compute\_tools package
===========================
+Submodules
+----------
+
rhg\_compute\_tools.gcs module
------------------------------
@@ -17,6 +20,14 @@ rhg\_compute\_tools.kubernetes module
:undoc-members:
:show-inheritance:
+rhg\_compute\_tools.utils module
+--------------------------------
+
+.. automodule:: rhg_compute_tools.utils
+ :members:
+ :undoc-members:
+ :show-inheritance:
+
Module contents
---------------
diff --git a/rhg_compute_tools/utils.py b/rhg_compute_tools/utils.py
new file mode 100644
index 0000000..eb66010
--- /dev/null
+++ b/rhg_compute_tools/utils.py
@@ -0,0 +1,151 @@
+import functools
+import itertools
+
+
+def expand(func):
+ '''
+ Decorator to expand an (args, kwargs) tuple in function calls
+
+ Intended for use with the :py:func:`collapse` function
+
+ Parameters
+ ----------
+ func : function
+ Function to have arguments expanded. Func can have any
+ number of positional and keyword arguments.
+
+ Returns
+ -------
+ wrapped : function
+ Wrapped version of ``func`` which accepts a single
+ ``(args, kwargs)`` tuple.
+
+ Examples
+ --------
+
+ .. code-block:: python
+
+ >>> @expand
+ ... def my_func(a, b, exp=1):
+ ... return (a * b)**exp
+ ...
+
+ >>> my_func(((2, 3), {}))
+ 6
+
+ >>> my_func(((2, 3, 2), {}))
+ 36
+
+ >>> my_func((tuple([]), {'b': 4, 'exp': 2, 'a': 1}))
+ 16
+
+ This function can be used in combination with the ``collapse`` helper
+ function, which allows more natural parameter calls
+
+ .. code-block:: python
+
+ >>> my_func(collapse(2, 3, exp=2))
+ 36
+
+ These can then be paired to enable many parameterized function calls:
+
+ .. code-block:: python
+
+ >>> func_calls = [collapse(a, a+1, exp=a) for a in range(5)]
+
+ >>> list(map(my_func, func_calls))
+ [1, 2, 36, 1728, 160000]
+
+ '''
+
+ @functools.wraps(func)
+ def inner(ak):
+ return func(*ak[0], **ak[1])
+ return inner
+
+
+def collapse(*args, **kwargs):
+ '''
+ Collapse positional and keyword arguments into an (args, kwargs) tuple
+
+ Intended for use with the :py:func:`expand` decorator
+
+ Parameters
+ ----------
+ *args
+ Variable length argument list.
+ **kwargs
+ Arbitrary keyword arguments.
+
+ Returns
+ -------
+ args : tuple
+ Positional arguments tuple
+ kwargs : dict
+ Keyword argument dictionary
+ '''
+ return (args, kwargs)
+
+
+def collapse_product(*args, **kwargs):
+ '''
+
+ Parameters
+ ----------
+
+ *args
+ Variable length list of iterables
+ **kwargs
+ Keyword arguments, whose values must be iterables
+
+ Returns
+ -------
+ iterator
+ Generator with collapsed arguments
+
+ See Also
+ --------
+
+ Function :py:func:`collapse`
+
+ Examples
+ --------
+
+ .. code-block:: python
+
+ >>> @expand
+ ... def my_func(a, b, exp=1):
+ ... return (a * b)**exp
+ ...
+
+ >>> product_args = list(collapse_product(
+ ... [0, 1, 2],
+ ... [0.5, 2],
+ ... exp=[0, 1]))
+
+ >>> product_args # doctest: +NORMALIZE_WHITESPACE
+ [((0, 0.5), {'exp': 0}),
+ ((0, 0.5), {'exp': 1}),
+ ((0, 2), {'exp': 0}),
+ ((0, 2), {'exp': 1}),
+ ((1, 0.5), {'exp': 0}),
+ ((1, 0.5), {'exp': 1}),
+ ((1, 2), {'exp': 0}),
+ ((1, 2), {'exp': 1}),
+ ((2, 0.5), {'exp': 0}),
+ ((2, 0.5), {'exp': 1}),
+ ((2, 2), {'exp': 0}),
+ ((2, 2), {'exp': 1})]
+
+ >>> list(map(my_func, product_args))
+ [1.0, 0.0, 1, 0, 1.0, 0.5, 1, 2, 1.0, 1.0, 1, 4]
+ '''
+ num_args = len(args)
+ kwarg_keys = list(kwargs.keys())
+ kwarg_vals = [kwargs[k] for k in kwarg_keys]
+
+ format_iterations = lambda x: (
+ tuple(x[:num_args]),
+ dict(zip(kwarg_keys, x[num_args:])))
+
+ return map(format_iterations, itertools.product(*args, *kwarg_vals))
| RhodiumGroup/rhg_compute_tools | bf940b75af8efcaa42eeb88ae610024c64e5c0dc | diff --git a/tests/test_rhg_compute_tools.py b/tests/test_rhg_compute_tools.py
index daaaa95..2b98710 100644
--- a/tests/test_rhg_compute_tools.py
+++ b/tests/test_rhg_compute_tools.py
@@ -6,7 +6,7 @@
import pytest
import inspect
-from rhg_compute_tools import gcs, kubernetes
+from rhg_compute_tools import gcs, kubernetes, utils
@pytest.fixture
@@ -28,7 +28,7 @@ def test_content(response):
def test_docstrings():
- for mod in [gcs, kubernetes]:
+ for mod in [gcs, kubernetes, utils]:
for cname, component in mod.__dict__.items():
if cname.startswith('_'):
continue
| Add client.map helper functions
## Goals
Provide functions for more semantic use of client.map and other dask workflows
* [x] expand/collapse for multi-arg function handling
* [x] provide [jrnr](https://github.com/ClimateImpactLab/jrnr)-like parameter iteration tools
## Prototype
```python
import functools, itertools
def expand(func):
'''
Decorator to expand an (args, kwargs) tuple in function calls
Intended for use with the :py:func:`collapse` function
Parameters
----------
func : function
Function to have arguments expanded. Func can have any
number of positional and keyword arguments.
Returns
-------
wrapped : function
Wrapped version of ``func`` which accepts a single
``(args, kwargs)`` tuple.
Examples
--------
.. code-block:: python
In [1]: @expand
...: def my_func(a, b, exp=1):
...: return (a * b)**exp
...:
In [2]: my_func((2, 3))
6
In [3]: my_func((2, 3, 2))
36
In [4]: my_func(tuple([]), {'b': 4, 'c': 2, 'a': 1})
16
This function can be used in combination with the ``collapse`` helper function,
which allows more natural parameter calls
.. code-block:: python
In [5]: my_func(collapse(2, 3, exp=2))
36
These can then be paired to enable many parameterized function calls:
.. code-block:: python
In [6]: func_calls = [collapse(a, a+1, exp=a) for a in range(5)]
In [7]: map(my_func, func_calls)
[1, 2, 36, 1728, 160000]
'''
@functools.wraps(func)
def inner(ak):
return func(*ak[0], **ak[1])
return inner
def collapse(*args, **kwargs):
'''
Collapse positional and keyword arguments into an (args, kwargs) tuple
Intended for use with the :py:func:`expand` decorator
Parameters
----------
*args
Variable length argument list.
**kwargs
Arbitrary keyword arguments.
Returns
-------
args : tuple
Positional arguments tuple
kwargs : dict
Keyword argument dictionary
'''
return (args, kwargs)
def collapse_product(*args, **kwargs):
'''
Parameters
----------
*args
Variable length list of iterables
**kwargs
Keyword arguments, whose values must be iterables
Returns
-------
iterator
Generator with collapsed arguments
See Also
--------
Function :py:func:`collapse`
Examples
--------
.. code-block:: python
In [1]: @expand
...: def my_func(a, b, exp=1):
...: return (a * b)**exp
...:
In [3]: product_args = collapse_product(
...: [0, 1, 2],
...: [0.5, 2],
...: exp=[0, 1])
In [4]: list(product_args) # doctest: NORMALIZE_WHITESPACE
[
((0, 0.5), {'exp': 0}),
((0, 0.5), {'exp': 1}),
((0, 2), {'exp': 0}),
((0, 2), {'exp': 1}),
((1, 0.5), {'exp': 0}),
((1, 0.5), {'exp': 1}),
((1, 2), {'exp': 0}),
((1, 2), {'exp': 1}),
((2, 0.5), {'exp': 0}),
((2, 0.5), {'exp': 1}),
((2, 2), {'exp': 0}),
((2, 2), {'exp': 1})]
In [5]: list(map(my_func, product_args))
[1.0, 0.0, 1, 0, 1.0, 0.5, 1, 2, 1.0, 1.0, 1, 4]
'''
num_args = len(args)
kwarg_keys = list(kwargs.keys())
kwarg_vals = [kwargs[k] for k in kwarg_keys]
format_iterations = lambda x: (tuple(x[:num_args]), dict(zip(kwarg_keys, x[num_args:])))
return map(format_iterations, itertools.product(*args, *kwarg_vals))
``` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_rhg_compute_tools.py::test_content",
"tests/test_rhg_compute_tools.py::test_docstrings"
] | [] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_added_files",
"has_removed_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2018-10-07T20:48:51Z" | mit |
|
RhodiumGroup__rhg_compute_tools-48 | diff --git a/HISTORY.rst b/HISTORY.rst
index c3f2eb7..053b986 100644
--- a/HISTORY.rst
+++ b/HISTORY.rst
@@ -4,6 +4,32 @@ History
.. current developments
+v0.2.0
+------
+
+* Add CLI tools (:issue:`37`). See ``rctools gcs repdirstruc --help`` to start
+* Add new function ``rhg_compute_tools.gcs.replicate_directory_structure_on_gcs`` to copy directory trees into GCS
+* Fixes to docstrings and metadata (:issue:`43`) (:issue:`45`)
+
+
+v0.1.8
+------
+
+* Deployment fixes
+
+v0.1.7
+------
+
+* Design tools: use RHG & CIL colors & styles
+* Plotting helpers: generate cmaps with consistent colors & norms, and apply a colorbar to geopandas plots with nonlinear norms
+* Autoscaling fix for kubecluster: switch to dask_kubernetes.KubeCluster to allow use of recent bug fixes
+
+
+v0.1.6
+------
+
+* Add ``rhg_compute_tools.gcs.cp_gcs`` and ``rhg_compute_tools.gcs.sync_gcs`` utilities
+
v0.1.5
------
diff --git a/requirements.txt b/requirements.txt
index d19ea9f..9e968c3 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -2,3 +2,4 @@ google-cloud-storage==1.16.1
dask-kubernetes==0.8.0
matplotlib==3.0.3
numpy>=1.14
+click
diff --git a/requirements_dev.txt b/requirements_dev.txt
index 903cbb1..0bf806b 100644
--- a/requirements_dev.txt
+++ b/requirements_dev.txt
@@ -8,4 +8,5 @@ Sphinx==1.7.4
pyyaml>=4.2b1
pytest-cov==2.5.1
pytest-runner==4.2
+pytest-mock
twine==1.13.0
diff --git a/rhg_compute_tools/cli.py b/rhg_compute_tools/cli.py
new file mode 100644
index 0000000..9aacdee
--- /dev/null
+++ b/rhg_compute_tools/cli.py
@@ -0,0 +1,36 @@
+import click
+from rhg_compute_tools.gcs import replicate_directory_structure_on_gcs
+
+
[email protected](
+ context_settings={'help_option_names': ['-h', '--help']}
+)
+def rctools_cli():
+ """Rhodium Compute Tools"""
+ pass
+
+
+@rctools_cli.group()
+def gcs():
+ """Tools for interacting with Google Cloud Storage
+ """
+ pass
+
+
[email protected]()
[email protected]('src', type=click.Path(exists=True))
[email protected]('dst', type=click.Path())
[email protected]('-c', '--credentials', type=click.Path(exists=True),
+ envvar='GOOGLE_APPLICATION_CREDENTIALS',
+ help='Optional path to GCS credentials file.')
+def repdirstruc(src, dst, credentials):
+ """Replicate directory structure onto GCS bucket.
+
+ SRC is path to a local directory. Directories within will be replicated.
+ DST is gs://[bucket] and optional path to replicate SRC into.
+
+ If --credentials or -c is not explicitly given, checks the
+ GOOGLE_APPLICATIONS_CREDENTIALS environment variable for path to a GCS
+ credentials file.
+ """
+ replicate_directory_structure_on_gcs(src, dst, credentials)
diff --git a/rhg_compute_tools/gcs.py b/rhg_compute_tools/gcs.py
index 93c1ac6..cfe89b8 100644
--- a/rhg_compute_tools/gcs.py
+++ b/rhg_compute_tools/gcs.py
@@ -47,13 +47,12 @@ def _get_path_types(src, dest):
return src_gs, dest_gs, dest_gcs
-def replicate_directory_structure_on_gcs(src, dst, storage_client):
- '''
+def replicate_directory_structure_on_gcs(src, dst, client_or_creds):
+ """
Replicate a local directory structure on google cloud storage
-
+
Parameters
----------
-
src : str
Path to the root directory on the source machine. The directory
structure within this directory will be reproduced within `dst`,
@@ -61,9 +60,15 @@ def replicate_directory_structure_on_gcs(src, dst, storage_client):
dst : str
A url for the root directory of the destination, starting with
`gs://[bucket_name]/`, e.g. `gs://my_bucket/path/to/my/data`
- storage_client : object
- An authenticated :py:class:`google.cloud.storage.client.Client` object
- '''
+ client_or_creds : google.cloud.storage.client.Client or str
+ An authenticated :py:class:`google.cloud.storage.client.Client` object,
+ or a str path to storage credentials authentication file.
+ """
+ if isinstance(client_or_creds, str):
+ credentials = service_account.Credentials.from_service_account_file(
+ client_or_creds
+ )
+ client_or_creds = storage.Client(credentials=credentials)
if dst.startswith('gs://'):
dst = dst[5:]
@@ -71,11 +76,11 @@ def replicate_directory_structure_on_gcs(src, dst, storage_client):
dst = dst[6:]
else:
raise ValueError('dst must begin with `gs://` or `gcs://`')
-
+
bucket_name = dst.split('/')[0]
blob_path = '/'.join(dst.split('/')[1:])
-
- bucket = storage_client.get_bucket(bucket_name)
+
+ bucket = client_or_creds.get_bucket(bucket_name)
for d, dirnames, files in os.walk(src):
dest_path = os.path.join(blob_path, os.path.relpath(d, src))
diff --git a/setup.py b/setup.py
index 1cdca31..2c039e2 100644
--- a/setup.py
+++ b/setup.py
@@ -60,4 +60,9 @@ setup(
test_suite='tests',
tests_require=test_requirements,
setup_requires=setup_requirements,
+ entry_points={
+ 'console_scripts': [
+ 'rctools = rhg_compute_tools.cli:rctools_cli',
+ ]
+ },
)
| RhodiumGroup/rhg_compute_tools | 502b8bd0d54417db4e71ce82a363a470314f50e2 | diff --git a/tests/test_cli.py b/tests/test_cli.py
new file mode 100644
index 0000000..786f38b
--- /dev/null
+++ b/tests/test_cli.py
@@ -0,0 +1,79 @@
+"""
+White-box testing to ensure that CLI passes variables correctly
+"""
+
+
+import pytest
+import click
+from click.testing import CliRunner
+import rhg_compute_tools.cli
+
+
[email protected]
+def replicate_directory_structure_on_gcs_stub(mocker):
+ mocker.patch.object(rhg_compute_tools.cli,
+ 'replicate_directory_structure_on_gcs',
+ new=lambda *args: click.echo(';'.join(args)))
+
+
[email protected]
+def tempfl_path(tmpdir):
+ """Creates a temporary file, returning its path"""
+ file = tmpdir.join('file.json')
+ file.write('foobar')
+ return str(file)
+
+
[email protected]('credflag', ['-c', '--credentials', None])
+def test_repdirstruc(credflag, replicate_directory_structure_on_gcs_stub,
+ tmpdir, tempfl_path, monkeypatch):
+ """Test rctools gcs repdirstruc for main input options
+ """
+ # Setup CLI args
+ cred_path = str(tempfl_path)
+ credargs = [credflag, cred_path]
+ src_path = str(tmpdir)
+ dst_path = 'gcs://foo/bar'
+
+ if credflag is None:
+ monkeypatch.setenv('GOOGLE_APPLICATION_CREDENTIALS', cred_path)
+ credargs = []
+
+ # Run CLI
+ runner = CliRunner()
+ result = runner.invoke(
+ rhg_compute_tools.cli.rctools_cli,
+ ['gcs', 'repdirstruc'] + credargs + [src_path, dst_path],
+ )
+
+ expected_output = ';'.join([src_path, dst_path, cred_path]) + '\n'
+ assert result.output == expected_output
+
+
[email protected]('credflag', ['-c', '--credentials', None])
+def test_repdirstruc_nocredfile(credflag, replicate_directory_structure_on_gcs_stub,
+ tmpdir, monkeypatch):
+ """Test rctools gcs repdirstruc for graceful fail when cred file missing
+ """
+ # Setup CLI args
+ cred_path = '_foobar.json'
+ credargs = [credflag, cred_path]
+ src_path = str(tmpdir)
+ dst_path = 'gcs://foo/bar'
+
+ if credflag is None:
+ monkeypatch.setenv('GOOGLE_APPLICATION_CREDENTIALS', cred_path)
+ credargs = []
+
+ # Run CLI
+ runner = CliRunner()
+ result = runner.invoke(
+ rhg_compute_tools.cli.rctools_cli,
+ ['gcs', 'repdirstruc'] + credargs + [src_path, dst_path],
+ )
+
+ expected_output = 'Usage: rctools-cli gcs repdirstruc [OPTIONS] SRC DST\nTry' \
+ ' "rctools-cli gcs repdirstruc -h" for help.\n\nError: ' \
+ 'Invalid value for "-c" / "--credentials": Path ' \
+ '"_foobar.json" does not exist.\n'
+ assert result.output == expected_output
| Add command line gcs tools
would be great to do something along the lines of
```bash
rhg-compute-tools gcs rsync src dst
```
Which suggests we probably need a broader command line strategy for handling different submodules | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_cli.py::test_repdirstruc[-c]",
"tests/test_cli.py::test_repdirstruc[--credentials]",
"tests/test_cli.py::test_repdirstruc[None]"
] | [] | {
"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-09-16T18:49:34Z" | mit |
|
RightBrain-Networks__auto-semver-51 | diff --git a/Jenkinsfile b/Jenkinsfile
index cbbd435..10aee15 100644
--- a/Jenkinsfile
+++ b/Jenkinsfile
@@ -1,4 +1,4 @@
-library('pipeline-library')
+library('pipeline-library@bugfix/durable-task-workaround')
pipeline {
options { timestamps() }
@@ -18,7 +18,7 @@ pipeline {
stage('Self Version') {
steps {
withCredentials([usernamePassword(credentialsId: env.DOCKER_CREDENTIALS, usernameVariable: 'DOCKER_USERNAME', passwordVariable: 'DOCKER_PASSWORD')]) {
- sh("docker login -u ${DOCKER_USERNAME} -p ${DOCKER_PASSWORD}")
+ sh("docker login -u $DOCKER_USERNAME -p $DOCKER_PASSWORD")
}
runAutoSemver("rightbrainnetworks/auto-semver:${SELF_SEMVER_TAG}")
}
@@ -59,6 +59,7 @@ pipeline {
agent {
docker {
image "rightbrainnetworks/auto-semver:${env.VERSION}"
+ args "--privileged"
}
}
steps
@@ -85,7 +86,7 @@ pipeline {
// Authenticate & push to DockerHub
withCredentials([usernamePassword(credentialsId: env.DOCKER_CREDENTIALS, usernameVariable: 'DOCKER_USERNAME', passwordVariable: 'DOCKER_PASSWORD')]) {
sh("""
- docker login -u ${DOCKER_USERNAME} -p ${DOCKER_PASSWORD}
+ docker login -u $DOCKER_USERNAME -p $DOCKER_PASSWORD
docker push rightbrainnetworks/auto-semver:${env.VERSION}
""")
}
diff --git a/semver/__init__.py b/semver/__init__.py
index da6a610..e0075ee 100644
--- a/semver/__init__.py
+++ b/semver/__init__.py
@@ -1,6 +1,8 @@
import argparse
import re
import subprocess
+import sys
+import traceback
from enum import IntEnum
from semver.utils import get_tag_version
from semver.logger import logging, logger, console_logger
@@ -59,7 +61,7 @@ class SemVer(object):
message = str(p.stdout.read())
branch = b.stdout.read().decode('utf-8').rstrip()
logger.info('Main branch is ' + branch)
- matches = GET_COMMIT_MESSAGE.search(message)
+ matches = GET_COMMIT_MESSAGE.search(message.replace('\\n','\n').replace('\\',''))
if matches:
if str(matches.group(4)) == branch:
self.merged_branch = matches.group(2)
@@ -111,7 +113,7 @@ class SemVer(object):
config_file = file.read()
# version repo
- logger.debug("Running bumpversion of type: " + self.version_type)
+ logger.debug("Running bumpversion of type: " + str(self.version_type.name))
bump_version(get_tag_version(), self.version_type)
return self
@@ -146,20 +148,22 @@ class SemVer(object):
return self
def main():
- try:
- parser = argparse.ArgumentParser(description='Bump Semantic Version.')
- parser.add_argument('-n','--no-push', help='Do not try to push', action='store_false', dest='push')
- parser.add_argument('-g','--global-user', help='Set git user at a global level, helps in jenkins', action='store_true', dest='global_user')
- parser.add_argument('-D', '--debug', help='Sets logging level to DEBUG', action='store_true', dest='debug', default=False)
- args = parser.parse_args()
-
+ parser = argparse.ArgumentParser(description='Bump Semantic Version.')
+ parser.add_argument('-n','--no-push', help='Do not try to push', action='store_false', dest='push')
+ parser.add_argument('-g','--global-user', help='Set git user at a global level, helps in jenkins', action='store_true', dest='global_user')
+ parser.add_argument('-D', '--debug', help='Sets logging level to DEBUG', action='store_true', dest='debug', default=False)
+ args = parser.parse_args()
- if args.debug:
- console_logger.setLevel(logging.DEBUG)
+ if args.debug:
+ console_logger.setLevel(logging.DEBUG)
+ try:
SemVer(global_user=args.global_user).run(push=args.push)
except Exception as e:
logger.error(e)
+ if args.debug:
+ tb = sys.exc_info()[2]
+ traceback.print_tb(tb)
if e == NO_MERGE_FOUND:
exit(1)
elif e == NOT_MAIN_BRANCH:
| RightBrain-Networks/auto-semver | eaebfcc3297fd1adb355069691cbf5e95eb31731 | diff --git a/semver/tests.py b/semver/tests.py
index 6383cd0..63025fa 100644
--- a/semver/tests.py
+++ b/semver/tests.py
@@ -158,6 +158,13 @@ class TestGetCommitMessageRegex(unittest.TestCase):
def test_non_merge_message(self):
matches = GET_COMMIT_MESSAGE.search("Example unrelated commit message that should get 0 matches")
self.assertEqual(matches, None)
+ def test_gitlab_merge_with_double_quotes(self):
+ matches = GET_COMMIT_MESSAGE.search("Merge branch 'branch' into 'master'\n\n\"Message in quotes!\"")
+ if matches:
+ self.assertEqual(matches.group(4), "master")
+ self.assertEqual(matches.group(2), "branch")
+ else:
+ self.assertTrue(False)
class TestVersionBumping(unittest.TestCase):
def test_patch_bump(self):
| Semver fails with double quotes in a commit
**Version of Auto-Semver:**
0.6.2
**Environment:**
docker
**Issue description:**
Having a double quote anywhere in the commit message will cause versioning to fail. For example:
this will work:
```
[klucas@klucas-wks ui-build-config] (master)$ git log -1
commit 081c914e0d5446aa6eaf8254a9ddb5cc127875fc (HEAD -> master, origin/master, origin/HEAD)
Merge: 9de95d8 7a67747
Author: Kevin Lucas <[email protected]>
Date: Fri Oct 23 14:14:59 2020 +0000
Merge branch 'bugfix/PSC-251-remove-polyfill' into 'master'
Arbitrary change
See merge request features/ui-build-config!15
```
But this will fail:
```
[klucas@klucas-wks ui-build-config] (master)$ git log -1
commit 49860371514800ddf853b887ef73c8d584fb4800 (HEAD -> master, origin/master, origin/HEAD)
Merge: 8dba406 431a34b
Author: Kevin Lucas <[email protected]>
Date: Fri Oct 23 16:04:55 2020 +0000
Merge branch 'bugfix/PSC-251-remove-polyfill' into 'master'
Arbitrary "change"
See merge request features/ui-build-config!17
```
**Steps to reproduce:**
Create a commit on another branch that has a double quote in the commit message. Merge the branch with the master branch in such a way that commit messages from the merged branch are included in the merge commit (fast-forward summery merges on GitLab) and try to version:
```
(app-root) semver -n --debug
2020-10-23 16:05:25,179 - INFO - Main branch is master
2020-10-23 16:05:25,180 - ERROR - No merge found
``` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"semver/tests.py::TestSemverObject::test_run_no_merge"
] | [
"semver/tests.py::TestGetTagVersion::test_default_get_version_tag",
"semver/tests.py::TestGetCommitMessageRegex::test_branch_in_message",
"semver/tests.py::TestGetCommitMessageRegex::test_github_message",
"semver/tests.py::TestGetCommitMessageRegex::test_gitlab_merge_with_double_quotes",
"semver/tests.py::TestGetCommitMessageRegex::test_gitlab_message",
"semver/tests.py::TestGetCommitMessageRegex::test_non_merge_message",
"semver/tests.py::TestVersionBumping::test_major_bump",
"semver/tests.py::TestVersionBumping::test_minor_bump",
"semver/tests.py::TestVersionBumping::test_patch_bump"
] | {
"failed_lite_validators": [
"has_git_commit_hash",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2020-11-23T14:43:39Z" | apache-2.0 |
|
RobinL__fuzzymatcher-50 | diff --git a/fuzzymatcher/data_getter_sqlite.py b/fuzzymatcher/data_getter_sqlite.py
index c54eec8..e97808e 100644
--- a/fuzzymatcher/data_getter_sqlite.py
+++ b/fuzzymatcher/data_getter_sqlite.py
@@ -177,10 +177,21 @@ class DataGetter:
"""
# This fails if the special tokens 'and' or 'or' are in fts string! See issue 35!
- tokens_to_remove = ["AND", "OR"]
- tokens = [t for t in tokens if t not in tokens_to_remove]
+ tokens_to_escape = ["AND", "OR", "NEAR"]
+
+ def escape_token(t):
+ # return t
+ if t in tokens_to_escape:
+ return '"' + t + '"'
+ else:
+ return t
+
+
+ tokens = [escape_token(t) for t in tokens]
+
fts_string = " ".join(tokens)
+
if misspelling:
table_name = "_concat_all_alternatives"
else:
@@ -188,6 +199,7 @@ class DataGetter:
sql = get_records_sql.format(table_name, fts_string, self.return_records_limit)
+
cur = self.con.cursor()
cur.execute(sql)
results = cur.fetchall()
| RobinL/fuzzymatcher | 5f0b19d50d5dcbcd930f9634d2bf429007b5efcc | diff --git a/tests/data/left_token_escape.csv b/tests/data/left_token_escape.csv
new file mode 100644
index 0000000..6da12f6
--- /dev/null
+++ b/tests/data/left_token_escape.csv
@@ -0,0 +1,5 @@
+id,fname,mname,lname,dob,another_field
+1,or,or and,and,20/05/1980,other data
+2,or,or,or smith or,15/06/1990,more data
+3,near,and,near,20/05/1960,another thing
+
diff --git a/tests/data/right_token_escape.csv b/tests/data/right_token_escape.csv
new file mode 100644
index 0000000..1b3232b
--- /dev/null
+++ b/tests/data/right_token_escape.csv
@@ -0,0 +1,4 @@
+id,name,middlename,surname,date,other
+1,or,or,or smith or,15/06/1990,more data
+2,near,and,near,20/05/1960,another thing
+3,or,or and,and,20/05/1980,other data
\ No newline at end of file
diff --git a/tests/test_misc.py b/tests/test_misc.py
index cbb1668..2377c62 100644
--- a/tests/test_misc.py
+++ b/tests/test_misc.py
@@ -17,4 +17,31 @@ class TestNulls(unittest.TestCase):
on = ["first_name", "surname", "dob", "city"]
- flj = link_table(df_left, df_right, on, on)
\ No newline at end of file
+ flj = link_table(df_left, df_right, on, on)
+
+
+class TestNulls(unittest.TestCase):
+ """
+ Test what happens when the user provides input data with
+ fts4 match expression keyworks like AND, OR, NEAR
+ """
+
+ def test_nulls_no_errors(self):
+ """
+
+ """
+
+
+ df_left = pd.read_csv("tests/data/left_token_escape.csv")
+ df_right = pd.read_csv("tests/data/right_token_escape.csv")
+
+ # Columns to match on from df_left
+ left_on = ["fname", "mname", "lname"]
+
+ # Columns to match on from df_right
+ right_on = ["name", "middlename", "surname"]
+
+ on = ["first_name", "surname", ]
+
+ flj = link_table(df_left, df_right, left_on, right_on,
+ left_id_col="id", right_id_col="id")
| OperationalError: malformed MATCH expression
Using `fuzzy_left_join`, I came across the above error while matching addresses.
It seems to relate to the following string: `'16 Orchard Court, Near Stepaside Park, Stepaside, Dublin, ireland'`
(note: I swapped out the street name for another for privacy reasons, but string length and structure is the same)
Code which I ran:
```python
import fuzzymatcher
import pandas as pd
df_left = contacts_unique_addresses
df_right = register
left_on = ["match_string"]
right_on = ["match_string"]
matched = fuzzymatcher.fuzzy_left_join(df_left, df_right, left_on, right_on)
```
And the error. Is it possible that my string is too long?
```python
OperationalError Traceback (most recent call last)
<ipython-input-78-6bd0c667558c> in <module>
7 right_on = ["match_string"]
8
----> 9 matched = fuzzymatcher.fuzzy_left_join(df_left, df_right, left_on, right_on)
~\Anaconda3\lib\site-packages\fuzzymatcher\__init__.py in fuzzy_left_join(df_left, df_right, left_on, right_on, left_id_col, right_id_col)
39 m = Matcher(dp, dg, s)
40 m.add_data(df_left, df_right, left_on, right_on, left_id_col, right_id_col)
---> 41 m.match_all()
42
43 return m.get_left_join_table()
~\Anaconda3\lib\site-packages\fuzzymatcher\matcher.py in match_all(self)
90
91 # Get a table that contains only the matches, scores and ids
---> 92 self.link_table = self._match_processed_data()
93
94 def get_formatted_link_table(self):
~\Anaconda3\lib\site-packages\fuzzymatcher\matcher.py in _match_processed_data(self)
134 log.debug(str_template.format(counter, (counter/total)*100, diff.minutes, diff.seconds))
135
--> 136 this_record.find_and_score_potential_matches()
137 link_table_list.extend(this_record.get_link_table_rows())
138
~\Anaconda3\lib\site-packages\fuzzymatcher\record.py in find_and_score_potential_matches(self)
74 def find_and_score_potential_matches(self):
75 # Each left_record has a list of left_record ids
---> 76 self.matcher.data_getter.get_potential_match_ids_from_record(self)
77
78 def get_link_table_rows(self):
~\Anaconda3\lib\site-packages\fuzzymatcher\data_getter_sqlite.py in get_potential_match_ids_from_record(self, rec_left)
91
92 for token_list in token_lists:
---> 93 self._search_specific_to_general_single(token_list, rec_left)
94 if not self._found_enough_matches(rec_left):
95 self._search_specific_to_general_band(token_list, rec_left)
~\Anaconda3\lib\site-packages\fuzzymatcher\data_getter_sqlite.py in _search_specific_to_general_single(self, token_list, rec_left)
115 for i in range(len(token_list)):
116 sub_tokens = token_list[i:]
--> 117 new_matches = self._tokens_to_matches(tuple(sub_tokens))
118
119 self._add_matches_to_potential_matches(new_matches, rec_left)
~\Anaconda3\lib\site-packages\fuzzymatcher\data_getter_sqlite.py in _tokens_to_matches(self, tokens, misspelling)
190
191 cur = self.con.cursor()
--> 192 cur.execute(sql)
193 results = cur.fetchall()
194
OperationalError: malformed MATCH expression: [NEAR IRELAND STEPASIDE STEPASIDE ORCHARD 16 COURT PARK DUBLIN]
``` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_misc.py::TestNulls::test_nulls_no_errors"
] | [] | {
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
} | "2019-10-14T10:06:02Z" | mit |
|
RockefellerArchiveCenter__DACSspace-39 | diff --git a/dacsspace/reporter.py b/dacsspace/reporter.py
index 731b7a8..514a247 100644
--- a/dacsspace/reporter.py
+++ b/dacsspace/reporter.py
@@ -1,10 +1,13 @@
+import csv
+
class CSVReporter:
"""Creates CSV reports."""
- def __init__(self):
- # TODO: set filepath for CSV
- pass
+ def __init__(self, filename, filemode="w"):
+ """Sets the filename and filemode."""
+ self.filename = filename
+ self.filemode = filemode
def write_report(self, results, invalid_only=True):
"""Writes results to a CSV file.
@@ -13,4 +16,15 @@ class CSVReporter:
results (list): A list of dictionaries containing information about validation results.
invalid_only (boolean): Only report on invalid results.
"""
- pass
+
+ if self.filemode.startswith("r"):
+ raise ValueError("Filemode must allow write options.")
+ with open(self.filename, self.filemode) as f:
+ fieldnames = [
+ "valid",
+ "explanation"]
+ writer = csv.DictWriter(
+ f, fieldnames=fieldnames)
+ writer.writeheader()
+ filtered_results = [row for row in results if not row["valid"]] if invalid_only else results
+ writer.writerows(filtered_results)
diff --git a/dacsspace/validator.py b/dacsspace/validator.py
index bde8b8c..9f0fa71 100644
--- a/dacsspace/validator.py
+++ b/dacsspace/validator.py
@@ -1,25 +1,13 @@
-
+import json
from jsonschema import ValidationError, validate
class Validator:
"""Validates data from ArchivesSpace."""
- def get_schema(self):
- schema = {
- "type": "object",
- "title": "DACSspace schema",
- "required": [
- "title",
- "id_0"
- ],
- "properties": {
- "title": {
- "type": "string"
- }
- }
- }
- return schema
+ def __init__(self):
+ with open("single_level_required.json", "r") as json_file:
+ self.schema = json.load(json_file)
def validate_data(self, data):
"""Validates data.
@@ -32,9 +20,8 @@ class Validator:
indication of the validation result and, if necessary, an explanation
of any validation errors. { "valid": False, "explanation": "You are missing the following fields..." }
"""
- schema = self.get_schema()
try:
- validate(data, schema)
+ validate(data, self.schema)
return {"valid": True}
except ValidationError as error:
return {"valid": False, "explanation": error.message}
diff --git a/fixtures/invalid_resource.json b/fixtures/multiple_invalid.json
similarity index 100%
rename from fixtures/invalid_resource.json
rename to fixtures/multiple_invalid.json
diff --git a/fixtures/no_metadata_rights.json b/fixtures/no_metadata_rights.json
new file mode 100644
index 0000000..18ec544
--- /dev/null
+++ b/fixtures/no_metadata_rights.json
@@ -0,0 +1,160 @@
+{
+ "lock_version": 17,
+ "title": "Henry Luce Foundation records, Clare Boothe Luce Program",
+ "publish": true,
+ "restrictions": false,
+ "ead_id": "FA1725.xml",
+ "finding_aid_title": "A Guide to the Henry Luce Foundation records, Clare Boothe Luce Program",
+ "finding_aid_filing_title": "Henry Luce Foundation records, Clare Boothe Luce Program",
+ "created_by": "aberish",
+ "last_modified_by": "battalb",
+ "create_time": "2020-02-14T16:21:48Z",
+ "system_mtime": "2021-12-22T15:31:27Z",
+ "user_mtime": "2021-11-05T15:52:48Z",
+ "suppressed": false,
+ "is_slug_auto": false,
+ "id_0": "FA1725",
+ "level": "recordgrp",
+ "resource_type": "records",
+ "finding_aid_description_rules": "Describing Archives: A Content Standard",
+ "finding_aid_language": "eng",
+ "finding_aid_script": "Latn",
+ "jsonmodel_type": "resource",
+ "external_ids": [],
+ "subjects": [
+ {
+ "ref": "/subjects/1725"
+ },
+ {
+ "ref": "/subjects/20081"
+ }
+ ],
+ "linked_events": [],
+ "extents": [
+ {
+ "lock_version": 0,
+ "number": "11.44",
+ "container_summary": "16 letter-sized document boxes",
+ "created_by": "battalb",
+ "last_modified_by": "battalb",
+ "create_time": "2021-11-05T15:53:05Z",
+ "system_mtime": "2021-11-05T15:53:05Z",
+ "user_mtime": "2021-11-05T15:53:05Z",
+ "portion": "whole",
+ "extent_type": "Cubic Feet",
+ "jsonmodel_type": "extent"
+ }
+ ],
+ "lang_materials": [
+ {
+ "lock_version": 0,
+ "created_by": "battalb",
+ "last_modified_by": "battalb",
+ "create_time": "2021-11-05T15:53:05Z",
+ "system_mtime": "2021-11-05T15:53:05Z",
+ "user_mtime": "2021-11-05T15:53:05Z",
+ "jsonmodel_type": "lang_material",
+ "notes": [],
+ "language_and_script": {
+ "lock_version": 0,
+ "created_by": "battalb",
+ "last_modified_by": "battalb",
+ "create_time": "2021-11-05T15:53:05Z",
+ "system_mtime": "2021-11-05T15:53:05Z",
+ "user_mtime": "2021-11-05T15:53:05Z",
+ "language": "eng",
+ "jsonmodel_type": "language_and_script"
+ }
+ }
+ ],
+ "dates": [
+ {
+ "lock_version": 0,
+ "expression": "1986-2014",
+ "begin": "1986",
+ "end": "2014",
+ "created_by": "battalb",
+ "last_modified_by": "battalb",
+ "create_time": "2021-11-05T15:53:05Z",
+ "system_mtime": "2021-11-05T15:53:05Z",
+ "user_mtime": "2021-11-05T15:53:05Z",
+ "date_type": "inclusive",
+ "label": "creation",
+ "jsonmodel_type": "date"
+ }
+ ],
+ "external_documents": [],
+ "rights_statements": [],
+ "linked_agents": [
+ {
+ "role": "creator",
+ "relator": "aut",
+ "terms": [],
+ "ref": "/agents/corporate_entities/4246"
+ }
+ ],
+ "revision_statements": [],
+ "instances": [],
+ "deaccessions": [],
+ "related_accessions": [
+ {
+ "ref": "/repositories/2/accessions/3971"
+ }
+ ],
+ "classifications": [],
+ "notes": [
+ {
+ "jsonmodel_type": "note_multipart",
+ "persistent_id": "bf2011f3353f37f389577d36cd942721",
+ "type": "accessrestrict",
+ "rights_restriction": {
+ "local_access_restriction_type": []
+ },
+ "subnotes": [
+ {
+ "jsonmodel_type": "note_text",
+ "content": "Open for research with select materials restricted as noted. Brittle or damaged items are available at the discretion of RAC.",
+ "publish": true
+ }
+ ],
+ "publish": true
+ },
+ {
+ "jsonmodel_type": "note_multipart",
+ "persistent_id": "b4ad37dbd0891b871c8fe5d3e969f487",
+ "type": "userestrict",
+ "rights_restriction": {
+ "local_access_restriction_type": []
+ },
+ "subnotes": [
+ {
+ "jsonmodel_type": "note_text",
+ "content": "RAC holds legal title. The Henry Luce Foundation retains all applicable intellectual property rights in so far as it holds them.",
+ "publish": true
+ }
+ ],
+ "publish": true
+ },
+ {
+ "jsonmodel_type": "note_multipart",
+ "persistent_id": "a0fb232b40ebc33ff21f51fc5fa71017",
+ "type": "scopecontent",
+ "subnotes": [
+ {
+ "jsonmodel_type": "note_text",
+ "content": "The Henry Luce Foundation was established by Henry R. Luce in 1936. As a New York-based nonprofit organization, the Luce Foundation awards grants in American Art, Asian studies, Higher Education, Theology, and supports the Clare Boothe Luce Program for women in science, mathematics, and engineering.",
+ "publish": true
+ }
+ ],
+ "publish": true
+ }
+ ],
+ "metadata_rights_declarations": [],
+ "uri": "/repositories/2/resources/13192",
+ "repository": {
+ "ref": "/repositories/2"
+ },
+ "tree": {
+ "ref": "/repositories/2/resources/13192/tree"
+ }
+}
diff --git a/fixtures/valid_resource.json b/fixtures/valid_resource.json
index 18ec544..62c4457 100644
--- a/fixtures/valid_resource.json
+++ b/fixtures/valid_resource.json
@@ -149,7 +149,7 @@
"publish": true
}
],
- "metadata_rights_declarations": [],
+ "metadata_rights_declarations": ["ADD SOMETHING LATER"],
"uri": "/repositories/2/resources/13192",
"repository": {
"ref": "/repositories/2"
diff --git a/single_level_required.json b/single_level_required.json
new file mode 100644
index 0000000..848a030
--- /dev/null
+++ b/single_level_required.json
@@ -0,0 +1,47 @@
+{
+ "$schema": "http://json-schema.org/draft-07/schema#",
+ "$id": "single_level_required.json",
+ "type": "object",
+ "title": "DACSspace Single Level Required Schema",
+ "required": [
+ "id_0",
+ "title",
+ "dates",
+ "extents",
+ "linked_agents",
+ "lang_materials",
+ "metadata_rights_declarations"
+ ],
+ "properties": {
+ "id_0": {
+ "type": "string"
+ },
+ "title": {
+ "type": "string"
+ },
+ "dates": {
+ "type": "array",
+ "minItems": 1
+ },
+ "extents": {
+ "type": "array",
+ "minItems": 1
+ },
+ "linked_agents": {
+ "type": "array",
+ "minItems": 1
+ },
+ "notes": {
+ "type": "array",
+ "minItems": 1
+ },
+ "lang_materials": {
+ "type": "array",
+ "minItems": 1
+ },
+ "metadata_rights_declarations": {
+ "type": "array",
+ "minItems": 1
+ }
+ }
+}
\ No newline at end of file
diff --git a/tox.ini b/tox.ini
index c3ec76b..32e8736 100644
--- a/tox.ini
+++ b/tox.ini
@@ -1,5 +1,5 @@
[tox]
-envlist = py39
+envlist = py310
skipsdist = True
[testenv]
| RockefellerArchiveCenter/DACSspace | c6a6042607540fd0522a9b0e1aaf2b43fe389e6d | diff --git a/tests/__init__.py b/tests/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/tests/test_reporter.py b/tests/test_reporter.py
index f2d4612..92b27c9 100644
--- a/tests/test_reporter.py
+++ b/tests/test_reporter.py
@@ -1,7 +1,44 @@
-# from unittest.mock import patch
-#
-# from dacsspace.reporter import CSVReporter
+import os
+from unittest import TestCase
+from unittest.mock import patch
+from dacsspace.reporter import CSVReporter
-def test_reporter():
- pass
+
+class CSVReporterTest(TestCase):
+
+ def setUp(self):
+ """Sets filename and data attributes for test file.
+
+ Checks if test file exists, then deletes it.
+ """
+ self.filename = "DACSSpace_results"
+ self.results = [{"valid": True, "explanation": None}, {"valid": False, "explanation": "No title"}]
+ if os.path.isfile(self.filename):
+ os.remove(self.filename)
+
+ def test_CSV(self):
+ """Asserts that the results are correctly written to the file.
+
+ Raises an error if the file has an incorrect filemode and asserts that the filemode must allow write options.
+ """
+ CSVReporter(self.filename).write_report(self.results)
+ self.assertTrue(self.filename)
+ with self.assertRaises(ValueError) as err:
+ CSVReporter(self.filename, "r").write_report(self.results)
+ self.assertEqual(str(err.exception), "Filemode must allow write options.")
+
+ @patch("csv.DictWriter.writerows")
+ def test_invalid(self, mock_writerows):
+ """Mocks writing only invalid results and valid results to file."""
+ CSVReporter(self.filename).write_report(self.results)
+ mock_writerows.assert_called_with([{"valid": False, "explanation": "No title"}])
+ CSVReporter(self.filename).write_report(self.results, invalid_only=False)
+ mock_writerows.assert_called_with(self.results)
+
+ def tearDown(self):
+ """Tears down test file.
+
+ Checks if test file exists, then deletes it."""
+ if os.path.isfile(self.filename):
+ os.remove(self.filename)
diff --git a/tests/test_validator.py b/tests/test_validator.py
index 3796a93..ca424a5 100644
--- a/tests/test_validator.py
+++ b/tests/test_validator.py
@@ -10,14 +10,15 @@ from dacsspace.validator import Validator
class TestValidator(unittest.TestCase):
def test_validator(self):
valid_json = "fixtures/valid_resource.json"
- multiple_invalid = "fixtures/invalid_resource.json"
+ invalid_fixtures = ["fixtures/multiple_invalid.json", "fixtures/no_metadata_rights.json"]
with open(valid_json, 'r') as v:
valid_json = json.load(v)
result = Validator().validate_data(valid_json)
self.assertTrue(isinstance(result, dict))
self.assertEqual(result["valid"], True)
- with open(multiple_invalid, 'r') as i:
- multiple_invalid = json.load(i)
- result = Validator().validate_data(multiple_invalid)
- self.assertTrue(isinstance(result, dict))
- self.assertEqual(result["valid"], False)
+ for f in invalid_fixtures:
+ with open(f, 'r') as i:
+ invalid_json = json.load(i)
+ result = Validator().validate_data(invalid_json)
+ self.assertTrue(isinstance(result, dict))
+ self.assertEqual(result["valid"], False)
| Create reporting class
As part of #21, create a class which handles reporting logic. Currently this is written to a CSV but we could also print it to stdout, or possibly other formats. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_reporter.py::CSVReporterTest::test_CSV",
"tests/test_reporter.py::CSVReporterTest::test_invalid",
"tests/test_validator.py::TestValidator::test_validator"
] | [] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_issue_reference",
"has_added_files",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
} | "2022-03-15T19:36:33Z" | mit |
|
RockefellerArchiveCenter__DACSspace-51 | diff --git a/dacsspace/dacsspace.py b/dacsspace/dacsspace.py
index fcecea7..b953a5b 100644
--- a/dacsspace/dacsspace.py
+++ b/dacsspace/dacsspace.py
@@ -6,9 +6,10 @@ from .validator import Validator
class DACSspace:
"""Base DACSspace class. Fetches data from AS, validates and reports results."""
- def run(self, published_only, invalid_only):
+ def run(self, published_only, invalid_only,
+ schema_identifier='single_level_required.json', schema_filepath=None):
client = ArchivesSpaceClient()
- validator = Validator()
+ validator = Validator(schema_identifier, schema_filepath)
reporter = CSVReporter()
data = client.get_resources(published_only)
results = []
@@ -21,3 +22,6 @@ class DACSspace:
# These variables should eventually be passed as arguments in the command line
# published_only = False
# invalid_only = True
+# schema_identifier - should default to single_level_required.json
+# schema_filepath - should default to None, only one of schema_identifier
+# or schema_filepath allowed
diff --git a/dacsspace/validator.py b/dacsspace/validator.py
index 82cc9b3..3f4d8cb 100644
--- a/dacsspace/validator.py
+++ b/dacsspace/validator.py
@@ -1,14 +1,25 @@
import json
-from jsonschema import Draft7Validator
+from jsonschema import Draft202012Validator
class Validator:
"""Validates data from ArchivesSpace."""
- def __init__(self):
- with open("single_level_required.json", "r") as json_file:
+ def __init__(self, schema_identifier, schema_filepath):
+ """Loads and validates the schema from an identifier or filepath.
+
+ Args:
+ schema_identifier (str): a pointer to a schema that is part of
+ DACSspace, located in the `schemas` directory.
+ schema_filepath (str): a filepath pointing to an external schema.
+ """
+ self.validator = Draft202012Validator
+ if not schema_filepath:
+ schema_filepath = f"schemas/{schema_identifier.removesuffix('.json')}.json"
+ with open(schema_filepath, "r") as json_file:
self.schema = json.load(json_file)
+ self.validator.check_schema(self.schema)
def validate_data(self, data):
"""Validates data.
@@ -21,8 +32,7 @@ class Validator:
indication of the validation result and, if necessary, an explanation
of any validation errors. { "valid": False, "explanation": "You are missing the following fields..." }
"""
- schema = self.schema
- validator = Draft7Validator(schema)
+ validator = self.validator(self.schema)
errors_found = [error.message for error in validator.iter_errors(data)]
if len(errors_found):
return {"valid": False, "explanation": "\n".join(errors_found)}
| RockefellerArchiveCenter/DACSspace | 35d9e7686b660844a831391c4ac3d2fd3ce0be86 | diff --git a/single_level_required.json b/schemas/single_level_required.json
similarity index 100%
rename from single_level_required.json
rename to schemas/single_level_required.json
diff --git a/tests/test_validator.py b/tests/test_validator.py
index 5b6176b..cc75b39 100644
--- a/tests/test_validator.py
+++ b/tests/test_validator.py
@@ -1,13 +1,40 @@
-# from unittest.mock import patch
-
-
import json
+import os
import unittest
+from jsonschema.exceptions import SchemaError
+
from dacsspace.validator import Validator
class TestValidator(unittest.TestCase):
+ def test_schema(self):
+ """Asserts schema identifiers and filenames are handled correctly."""
+
+ test_schema_filepath = "test_schema.json"
+
+ # handling for schema identifier
+ validator = Validator('single_level_required', None)
+ self.assertEqual(validator.schema["$id"], 'single_level_required.json')
+
+ validator = Validator('single_level_required.json', None)
+ self.assertEqual(validator.schema["$id"], 'single_level_required.json')
+
+ # passing external filename
+ with open(test_schema_filepath, "w") as sf:
+ json.dump({"$id": "test_schema.json"}, sf)
+ validator = Validator(None, test_schema_filepath)
+ self.assertEqual(validator.schema["$id"], test_schema_filepath)
+
+ # invalid external schema
+ with open(test_schema_filepath, "w") as sf:
+ json.dump({"type": 12}, sf)
+ with self.assertRaises(SchemaError):
+ validator = Validator(None, test_schema_filepath)
+
+ # cleanup
+ os.remove(test_schema_filepath)
+
def test_validator(self):
valid_json = "fixtures/valid_resource.json"
invalid_fixtures = [
@@ -15,12 +42,16 @@ class TestValidator(unittest.TestCase):
"fixtures/no_metadata_rights.json"]
with open(valid_json, 'r') as v:
valid_json = json.load(v)
- result = Validator().validate_data(valid_json)
+ result = Validator(
+ 'single_level_required',
+ None).validate_data(valid_json)
self.assertTrue(isinstance(result, dict))
self.assertEqual(result["valid"], True)
for f in invalid_fixtures:
with open(f, 'r') as i:
invalid_json = json.load(i)
- result = Validator().validate_data(invalid_json)
+ result = Validator(
+ 'single_level_required',
+ None).validate_data(invalid_json)
self.assertTrue(isinstance(result, dict))
self.assertEqual(result["valid"], False)
| Allow users to specify a schema to validate against
**Is your feature request related to a problem? Please describe.**
DACSspace will ship with a schema for single-level minimum requirement and (maybe) a custom RAC schema. Users may also want to supply their own schema to validate against.
**Describe the solution you'd like**
Allow users to specify which schema they want to validate against. Ideally we should allow both:
- A pointer to an existing schema that is part of DACSspace (presuming there is more than one), somewhat like we do in `rac_schemas`: https://github.com/RockefellerArchiveCenter/rac_schemas/blob/base/rac_schemas/__init__.py#L49
- A schema as a file object or a filepath, which would allow users to create their own arbitrary schema. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_validator.py::TestValidator::test_schema",
"tests/test_validator.py::TestValidator::test_validator"
] | [] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
} | "2022-03-29T18:54:24Z" | mit |
|
RockefellerArchiveCenter__DACSspace-52 | diff --git a/dacsspace/dacsspace.py b/dacsspace/dacsspace.py
index b953a5b..35118e7 100644
--- a/dacsspace/dacsspace.py
+++ b/dacsspace/dacsspace.py
@@ -1,3 +1,5 @@
+import re
+
from .client import ArchivesSpaceClient
from .reporter import CSVReporter
from .validator import Validator
@@ -6,6 +8,14 @@ from .validator import Validator
class DACSspace:
"""Base DACSspace class. Fetches data from AS, validates and reports results."""
+ def __init__(self, csv_filepath):
+ """Checks csv filepath to make sure it has the proper extension and characters."""
+ if not csv_filepath.endswith(".csv"):
+ raise ValueError("File must have .csv extension")
+ if re.search(r'[*?:"<>|]', csv_filepath):
+ raise ValueError(
+ 'File name cannot contain the following characters: * ? : " < > | ')
+
def run(self, published_only, invalid_only,
schema_identifier='single_level_required.json', schema_filepath=None):
client = ArchivesSpaceClient()
| RockefellerArchiveCenter/DACSspace | 1fc1a52c2404e97be7ff26fc38660f5ffcb806e2 | diff --git a/tests/test_dacsspace.py b/tests/test_dacsspace.py
new file mode 100644
index 0000000..87de2f0
--- /dev/null
+++ b/tests/test_dacsspace.py
@@ -0,0 +1,22 @@
+from unittest import TestCase
+
+from dacsspace import DACSspace
+
+
+class TestDACSspace(TestCase):
+
+ def test_csv_filepath(self):
+ """Asserts that CSV filepath is handled as expected.
+
+ Filepaths are checked to ensure they end with the appropriate file
+ extension (.csv) and don't contain any illegal characters.
+ """
+ DACSspace("csv_filepath.csv")
+ with self.assertRaises(ValueError) as err:
+ DACSspace("my*file.csv")
+ self.assertEqual(str(err.exception),
+ 'File name cannot contain the following characters: * ? : " < > | ')
+ with self.assertRaises(ValueError) as err:
+ DACSspace("myfile")
+ self.assertEqual(str(err.exception),
+ "File must have .csv extension")
| Address filename conventions/extension
@daremiyo discovered that troublesome filenames (filenames with spaces and no extensions provided) will pass tests. We might want to consider building out a solution to this:
- Enhance the TestReporter class to include testing for specific filenames/characters/extensions
- Have the code fudge a troublesome filename into a better filename (remove spaces, add extension)
- Remove the option to include a filename. Instead, always use the same filename and always save the file in the same location with a standard filename or a filename based on the timestamp.
For additional information, see @daremiyo comment on PR #39
> One thing to note for us to consider is how we should handle filename conventions for the file to which the results are being written. Do we want to specify a file extension like .csv; specify what characters shouldnβt be included like spaces, etc. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_dacsspace.py::TestDACSspace::test_csv_filepath"
] | [] | {
"failed_lite_validators": [
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
} | "2022-03-30T23:39:38Z" | mit |
|
RockefellerArchiveCenter__DACSspace-77 | diff --git a/README.md b/README.md
index 3649ae3..104e9ea 100644
--- a/README.md
+++ b/README.md
@@ -1,8 +1,10 @@
# DACSspace
-A simple Python script to evaluate your ArchivesSpace instance for DACS [single-level minimum](http://www2.archivists.org/standards/DACS/part_I/chapter_1) required elements.
+A Python package to evaluate your ArchivesSpace instance for DACS [single-level required](https://saa-ts-dacs.github.io/dacs/06_part_I/02_chapter_01.html#single-level-required) elements.
-DACSspace utilizes the ArchivesSpace API to check resources for DACS compliance and produces a csv containing a list of evaluated resources. If a DACS field is present its content will be written to the csv, if a field is missing the csv will read "FALSE" for that item.
+DACSspace utilizes the ArchivesSpace API and a default JSON schema to validate resources. The output is a CSV containing a list of invalid URIs with the following fields: validation status, error count, and explanation.
+
+DACSspace also allows users to specify a schema to validate against other than the default DACS single-level required schema, see [Usage](https://github.com/RockefellerArchiveCenter/DACSspace#usage) section for more information.
## Requirements
@@ -10,13 +12,6 @@ DACSspace utilizes the ArchivesSpace API to check resources for DACS compliance
* [ArchivesSnake](https://github.com/archivesspace-labs/ArchivesSnake) (Python library) (0.9.1 or higher)
* Requests module
* JSONschema
-* [tox](https://tox.readthedocs.io/) (for running tests)
-* [pre-commit](https://pre-commit.com/) (for running linters before committing)
- * After locally installing pre-commit, install the git-hook scripts in the DACSSpace directory:
-
- ```
- pre-commit install
- ```
## Installation
@@ -24,9 +19,7 @@ Download and install [Python](https://www.python.org/downloads/)
* If you are using Windows, add Python to your [PATH variable](https://docs.python.org/2/using/windows.html)
-Download or [clone](https://docs.github.com/en/repositories/creating-and-managing-repositories/cloning-a-repository) this repository
-
-Install requirements from within the main DACSspace directory: ```pip install -r requirements.txt```
+Install DACSspace and its requirements: ```pip install dacsspace```
## Setup
@@ -44,39 +37,104 @@ pass a different filepath via the `as_config` command-line argument.
## Usage
-Using the command line navigate to the directory containing the DACSspace repository and run `single-level.py` to execute the script.
+DACSspace can be used as a command line utility to evaluate your ArchivesSpace repository for DACS compliance, and it can also be used as part of another Python program.
+
+Required arguments:
+- `csv_filepath`
+
+Use this argument to set the filepath to the CSV file where the output of DACSspace will print. Your CSV filepath must have a .csv extension and cannot contain the following characters: * ? : " < > | '
+
+Optional arguments:
+- `--published_only`
+- `--invalid_only`
+- `--schema_identifier`
+- `--schema_filepath`
+
+For use cases on how these optional arguments can be employed, look under the next section, Running DACSspace from the command line.
+
+### Running DACSspace from the command line
+
+In the command line, run `dacsspace`. You also need to pass in the `csv_filepath` argument with the name of your CSV filepath in order to run the script (see [above]((https://github.com/RockefellerArchiveCenter/DACSspace#usage))).
+
+You can use the different DACSspace optional arguments to decide what data DACSspace will fetch, what data it will report out on, and what schema it will validate the data against.
+
+#### What data to fetch
+
+If you plan to only evaluate DACS compliance on resources in your ArchivesSpace repository that are published, pass in the argument `--published_only` into the command line. This tells the DACSspace client class to only fetch data from published resources.
+
+#### What data to report on
+
+If you want to limit your CSV file to contain information on resources that do not meet DACS compliance, pass in the argument `--invalid_only` into the command line. This tells the DACSspace reporter class to only write information on invalid results of the validation to your CSV file.
+
+The output to your CSV will include the following field names:
+- uri: The ArchivesSpace object's unique identifier (ex. /repositories/2/resources/1234)
+- valid: A boolean indication of the validation result (True or False)
+- error_count: An integer representation of the number of validation errors (ex. 1)
+- explanation: An explanation of any validation errors (You are missing the following fields ...)
-DACSspace will prompt you to answer two questions allowing you to limit which resources you'd like the script to evaluate:
+If you are using Microsoft Excel to view the CSV file, consult the following links to avoid encoding issues: [Excel 2007](https://www.itg.ias.edu/content/how-import-csv-file-uses-utf-8-character-encoding-0), [Excel 2013](https://www.ias.edu/itg/how-import-csv-file-uses-utf-8-character-encoding).
-```
-Welcome to DACSspace!
-I'll ask you a series of questions to refine how to script works.
-If you want to use the default value for a question press the ENTER key.
+#### What schema to validate your data against
-Do you want DACSspace to include unpublished resources? y/n (default is n):
-Do you want to further limit the script by a specific resource id? If so, enter a string that must be present in the resource id (enter to skip):
-```
+The default JSON schema that DACSspace will run the data it fetches from your ArchivesSpace repository against is the single_level_required JSON schema. If you want to validate your data against a different schema, you have two options:
-Pressing the ENTER key for both questions will use the default version of the script which will get ALL resources.
+1. To run DACSspace against a schema other than single_level_required within the `schemas` directory in dacsspace, use the command line argument `--schema_identifier` and specify the identifier for that schema. The identifier must be entered in as a string.
+2. To run DACSspace against a schema that is external to dacsspace, use the command line argument `schema_filepath` and specify the filepath to this external schema. The filepath must be entered in as a string.
-The script will create a list of evaluated resources in a csv file (default is `dacs_singlelevel_report.csv`).
+### Using DACSspace in another Python program
-A sample csv file will look like this:
+Different components of the DACSspace package can be incorporated into other Python programs.
-| title | publish | resource | extent | date| language | repository | creator | scope | restrictions
-|---|---|---|---|---|---|---|---|---|---|
-| #resource title | TRUE | #resourceId | 20.8 | inclusive| eng | #NameofRepository | FALSE | #scopenote| #accessrestriction
-| #resource title | TRUE | #resourceId | 50.6 | single | FALSE | #NameofRepository | #creator | FALSE| FALSE
+For example, say you had a set of data that has already been exported from ArchivesSpace into another sort of container. You do not need to run the entire DACSspace package, but you do want to validate your data set against a JSON schema. To do this, add this code to your script:
-If you are using Microsoft Excel to view the csv file, consult the following links to avoid encoding issues: [Excel 2007](https://www.itg.ias.edu/content/how-import-csv-file-uses-utf-8-character-encoding-0), [Excel 2013](https://www.itg.ias.edu/node/985).
+`from dacsspace.validator import Validator
+
+exported_data = [{"title": "Archival object" ... }, { ...}]
+validator = Validator("single_level_required.json", None)
+results = [validator.validate_data(obj) for obj in exported_data]
+print(results)`
## Contributing
-Pull requests accepted!
+Found a bug? [File an issue.](https://github.com/RockefellerArchiveCenter/DACSspace/issues/new/choose)
+
+Pull requests accepted! To contribute:
+
+1. File an issue in the repository or work on an issue already documented
+2. Fork the repository and create a new branch for your work
+3. After you have completed your work, push your branch back to the repository and open a pull request
+
+### Contribution standards
+
+#### Style
+
+DACSspace uses the Python PEP8 community style guidelines. To conform to these guidelines, the following linters are part of the pre-commit:
+
+* autopep8 formats the code automatically
+* flake8 checks for style problems as well as errors and complexity
+* isort sorts imports alphabetically, and automatically separated into sections and by type
+
+After locally installing pre-commit, install the git-hook scripts in the DACSSpace directory:
+
+ ```
+ pre-commit install
+ ```
+
+#### Documentation
+
+Docstrings should explain what a module, class, or function does by explaining its syntax and the semantics of its components. They focus on specific elements of the code, and less on how the code works. The point of docstrings is to provide information about the code you have written; what it does, any exceptions it raises, what it returns, relevant details about the parameters, and any assumptions which might not be obvious. Docstrings should describe a small segment of code and not the way the code is implemented in a larger environment.
+
+DACSspace adheres to [Googleβs docstring style guide](https://google.github.io/styleguide/pyguide.html#381-docstrings). There are two types of docstrings: one-liners and multi-line docstrings. A one-line docstring may be perfectly appropriate for obvious cases where the code is immediately self-explanatory. Use multiline docstrings for all other cases.
+
+#### Tests
+
+New code should have unit tests. Tests are written in unittest style and run using [tox](https://tox.readthedocs.io/).
## Authors
-Hillel Arnold and Amy Berish
+Initial version: Hillel Arnold and Amy Berish.
+
+Version 2.0: Hillel Arnold, Amy Berish, Bonnie Gordon, Katie Martin, and Darren Young.
## License
diff --git a/dacsspace/client.py b/dacsspace/client.py
index b83eae7..fc19600 100644
--- a/dacsspace/client.py
+++ b/dacsspace/client.py
@@ -1,5 +1,3 @@
-from configparser import ConfigParser
-
from asnake.aspace import ASpace
@@ -10,14 +8,12 @@ class ASnakeConfigError(Exception):
class ArchivesSpaceClient:
"""Handles communication with ArchivesSpace."""
- def __init__(self, as_config):
- config = ConfigParser()
- config.read(as_config)
- self.aspace = ASpace(baseurl=config.get('ArchivesSpace', 'baseurl'),
- username=config.get('ArchivesSpace', 'user'),
- password=config.get('ArchivesSpace', 'password'))
- self.repo = self.aspace.repositories(
- config.get('ArchivesSpace', 'repository'))
+ def __init__(self, baseurl, username, password, repo_id):
+ self.aspace = ASpace(
+ baseurl=baseurl,
+ username=username,
+ password=password)
+ self.repo = self.aspace.repositories(repo_id)
if isinstance(self.repo, dict):
raise ASnakeConfigError(
"Error getting repository: {}".format(
diff --git a/dacsspace/dacsspace.py b/dacsspace/dacsspace.py
index 0488dc1..75a3d81 100644
--- a/dacsspace/dacsspace.py
+++ b/dacsspace/dacsspace.py
@@ -1,4 +1,5 @@
import re
+from configparser import ConfigParser
from os.path import isfile
from .client import ArchivesSpaceClient
@@ -10,21 +11,33 @@ class DACSspace:
"""Base DACSspace class. Fetches data from AS, validates and reports results."""
def __init__(self, as_config, csv_filepath):
- """Checks csv filepath to make sure it has the proper extension and characters."""
+ """Checks CSV and AS config filepaths.
+
+ Args:
+ as_config (str): filepath to ArchivesSpace configuration file.
+ csv_filepath (str): filepath at which to save results file.
+ """
if not csv_filepath.endswith(".csv"):
raise ValueError("File must have .csv extension")
if re.search(r'[*?:"<>|]', csv_filepath):
raise ValueError(
'File name cannot contain the following characters: * ? : " < > | ')
self.csv_filepath = csv_filepath
+
if not isfile(as_config):
raise IOError(
"Could not find an ArchivesSpace configuration file at {}".format(as_config))
- self.as_config = as_config
+ config = ConfigParser()
+ config.read(as_config)
+ self.as_config = (
+ config.get('ArchivesSpace', 'baseurl'),
+ config.get('ArchivesSpace', 'user'),
+ config.get('ArchivesSpace', 'password'),
+ config.get('ArchivesSpace', 'repository'))
def run(self, published_only, invalid_only,
schema_identifier, schema_filepath):
- client = ArchivesSpaceClient(self.as_config)
+ client = ArchivesSpaceClient(*self.as_config)
validator = Validator(schema_identifier, schema_filepath)
reporter = CSVReporter(self.csv_filepath)
data = client.get_resources(published_only)
diff --git a/setup-old.py b/setup-old.py
deleted file mode 100644
index 9d23c53..0000000
--- a/setup-old.py
+++ /dev/null
@@ -1,73 +0,0 @@
-#!/usr/bin/env python
-
-import os
-import sys
-
-current_dir = os.path.dirname(__file__)
-
-file_path = os.path.join(current_dir, "local_settings.cfg")
-
-
-def check_response(response, yes):
- if response != yes:
- print("Exiting!")
- sys.exit()
-
-
-def start_section(section_name):
- cfg_file.write("\n[{}]\n".format(section_name))
-
-
-def write_value(name, default, value=None):
- if value:
- line = ("{}: {}\n".format(name, value))
- else:
- line = ("{}: {}\n".format(name, default))
- cfg_file.write(line)
-
-
-def main():
- global cfg_file
- print("This script will create a configuration file with settings to connect and download JSON files from ArchivesSpace.\nYou\'ll need to know a few things in order to do this:\n\n1. The base URL of the backend of your ArchivesSpace installation, including the port number.\n2. The ID for the ArchivesSpace repository from which you want to export JSON files.\n3. A user name and password for a user with read writes to the ArchivesSpace repository.\n")
- response = input("Do you want to continue? (y/n): ")
- check_response(response, "y")
-
- if os.path.isfile(file_path):
- print("\nIt looks like a configuration file already exists. This script will replace that file.\n")
- response = input("Do you want to continue? (y/n): ")
- check_response(response, "y")
-
- cfg_file = open(file_path, 'w+')
- print("\nOK, let's create this file! I\'ll ask you to enter a bunch of values. If you want to use the default value you can just hit the Enter key.\n")
- start_section("ArchivesSpace")
- print("We\'ll start with some values for your ArchivesSpace instance.")
- baseURL = input(
- "Enter the base URL of your ArchivesSpace installation (default is 'http://localhost:8089'): ")
- write_value("baseURL", "http://localhost:8089", baseURL)
- repoId = input(
- "Enter the repository ID for your ArchivesSpace installation (default is '2'): ")
- write_value("repository", "2", repoId)
- username = input(
- "Enter the username for your ArchivesSpace installation (default is 'admin'): ")
- write_value("user", "admin", username)
- password = input(
- "Enter the password associated with this username (default is 'admin'): ")
- write_value("password", "admin", password)
-
- start_section("Destinations")
- print("\nNow you need to tell me where you want to save the spreadsheet that will be created. Unless you know what you\'re doing, you should probably leave the defaults in place.\n")
- directory = input(
- "Enter the directory in which you want to save the spreadsheet (default is the current directory): ")
- write_value("directory", "", directory)
- filename = input(
- "Now tell me the filename of the CSV spreadsheet you want to create (default is 'dacs_singlelevel_report.csv'): ")
- write_value("filename", "dacs_singlelevel_report.csv", filename)
-
- cfg_file.close()
-
- print("You\'re all set! I created a configuration file at {}. You can edit that file at any time, or run this script again if you want to replace those configurations.".format(file_path))
-
- sys.exit()
-
-
-main()
| RockefellerArchiveCenter/DACSspace | 2ac435473ed330a64842e27109756741727becd6 | diff --git a/tests/test_client.py b/tests/test_client.py
index 59059bb..e7e65c7 100644
--- a/tests/test_client.py
+++ b/tests/test_client.py
@@ -1,6 +1,3 @@
-import configparser
-import os
-import shutil
import unittest
from unittest.mock import Mock, patch
@@ -8,56 +5,15 @@ from asnake.client.web_client import ASnakeAuthError
from dacsspace.client import ArchivesSpaceClient, ASnakeConfigError
-CONFIG_FILEPATH = "as_config.cfg"
-
class ArchivesSpaceClientTests(unittest.TestCase):
def setUp(self):
"""Move existing config file and replace with sample config."""
- if os.path.isfile(CONFIG_FILEPATH):
- shutil.move(CONFIG_FILEPATH, "as_config.old")
- shutil.copy("as_config.example", CONFIG_FILEPATH)
-
- @patch("requests.Session.get")
- @patch("requests.Session.post")
- def test_config_file(self, mock_post, mock_get):
- """Asserts that configuration files are correctly handled:
- - Configuration files without all the necessary values cause an exception to be raised.
- - Valid configuration file allows for successful instantiation of ArchivesSpaceClient class.
- """
- # mock returns from ASpace
- mock_post.return_value.status_code = 200
- mock_post.return_value.text = "{\"session\": \"12355\"}"
- mock_get.return_value.status_code = 200
- mock_get.return_value.text = "v3.0.2"
-
- # Valid config file
- ArchivesSpaceClient(CONFIG_FILEPATH)
-
- # remove baseurl from ArchivesSpace section
- config = configparser.ConfigParser()
- config.read(CONFIG_FILEPATH)
- config.remove_option('ArchivesSpace', 'baseurl')
- with open(CONFIG_FILEPATH, "w") as cf:
- config.write(cf)
-
- # Configuration file missing necessary options
- with self.assertRaises(configparser.NoOptionError) as err:
- ArchivesSpaceClient(CONFIG_FILEPATH)
- self.assertEqual(str(err.exception),
- "No option 'baseurl' in section: 'ArchivesSpace'")
-
- # remove ArchivesSpace section
- config = configparser.ConfigParser()
- config.read(CONFIG_FILEPATH)
- config.remove_section('ArchivesSpace')
- with open(CONFIG_FILEPATH, "w") as cf:
- config.write(cf)
-
- # Configuration file missing necessary section
- with self.assertRaises(configparser.NoSectionError) as err:
- ArchivesSpaceClient(CONFIG_FILEPATH)
- self.assertEqual(str(err.exception), "No section: 'ArchivesSpace'")
+ self.as_config = (
+ "https://sandbox.archivesspace.org/api/",
+ "admin",
+ "admin",
+ 101)
@patch("requests.Session.get")
@patch("requests.Session.post")
@@ -71,14 +27,14 @@ class ArchivesSpaceClientTests(unittest.TestCase):
# Incorrect authentication credentials
mock_post.return_value.status_code = 403
with self.assertRaises(ASnakeAuthError) as err:
- ArchivesSpaceClient(CONFIG_FILEPATH)
+ ArchivesSpaceClient(*self.as_config)
self.assertEqual(str(err.exception),
"Failed to authorize ASnake with status: 403")
# Incorrect base URL
mock_post.return_value.status_code = 404
with self.assertRaises(ASnakeAuthError) as err:
- ArchivesSpaceClient(CONFIG_FILEPATH)
+ ArchivesSpaceClient(*self.as_config)
self.assertEqual(str(err.exception),
"Failed to authorize ASnake with status: 404")
@@ -90,7 +46,7 @@ class ArchivesSpaceClientTests(unittest.TestCase):
mock_get.return_value.json.return_value = {
'error': 'Repository not found'}
with self.assertRaises(ASnakeConfigError) as err:
- ArchivesSpaceClient(CONFIG_FILEPATH)
+ ArchivesSpaceClient(*self.as_config)
self.assertEqual(str(err.exception),
"Error getting repository: Repository not found")
@@ -101,7 +57,7 @@ class ArchivesSpaceClientTests(unittest.TestCase):
"""Asserts that the `published_only` flag is handled correctly."""
mock_get.return_value.text = "v3.0.2" # Allows ArchivesSpaceClient to instantiate
# Instantiates ArchivesSpaceClient for testing
- client = ArchivesSpaceClient(CONFIG_FILEPATH)
+ client = ArchivesSpaceClient(*self.as_config)
# Test search for only published resources
list(client.get_resources(True))
@@ -121,7 +77,7 @@ class ArchivesSpaceClientTests(unittest.TestCase):
def test_data(self, mock_authorize, mock_get, mock_search):
"""Asserts that individual resources are returned"""
mock_get.return_value.text = "v3.0.2"
- client = ArchivesSpaceClient(CONFIG_FILEPATH)
+ client = ArchivesSpaceClient(*self.as_config)
# create a mocked object which acts like an
# `asnake.jsonmodel.JSONModel` object
@@ -133,8 +89,3 @@ class ArchivesSpaceClientTests(unittest.TestCase):
result = list(client.get_resources(True))
self.assertEqual(len(result), 1)
self.assertEqual(result[0], expected_return)
-
- def tearDown(self):
- """Replace sample config with existing config."""
- if os.path.isfile("as_config.old"):
- shutil.move("as_config.old", CONFIG_FILEPATH)
diff --git a/tests/test_dacsspace.py b/tests/test_dacsspace.py
index f20fef4..82c1d4c 100644
--- a/tests/test_dacsspace.py
+++ b/tests/test_dacsspace.py
@@ -1,3 +1,4 @@
+import configparser
import os
import shutil
from unittest import TestCase
@@ -32,7 +33,39 @@ class TestDACSspace(TestCase):
"File must have .csv extension")
def test_as_config(self):
- """Asserts missing files raise an exception."""
+ """Asserts that ArchivesSpace configuration file is correctly handled:
+ - Configuration files without all the necessary values cause an exception to be raised.
+ - Valid configuration file allows for successful instantiation of DACSspace class.
+ - Missing configuration file raises exception.
+ """
+ DACSspace(CONFIG_FILEPATH, "csv_filepath.csv")
+
+ # remove baseurl from ArchivesSpace section
+ config = configparser.ConfigParser()
+ config.read(CONFIG_FILEPATH)
+ config.remove_option('ArchivesSpace', 'baseurl')
+ with open(CONFIG_FILEPATH, "w") as cf:
+ config.write(cf)
+
+ # Configuration file missing necessary options
+ with self.assertRaises(configparser.NoOptionError) as err:
+ DACSspace(CONFIG_FILEPATH, "csv_filepath.csv")
+ self.assertEqual(str(err.exception),
+ "No option 'baseurl' in section: 'ArchivesSpace'")
+
+ # remove ArchivesSpace section
+ config = configparser.ConfigParser()
+ config.read(CONFIG_FILEPATH)
+ config.remove_section('ArchivesSpace')
+ with open(CONFIG_FILEPATH, "w") as cf:
+ config.write(cf)
+
+ # Configuration file missing necessary section
+ with self.assertRaises(configparser.NoSectionError) as err:
+ DACSspace(CONFIG_FILEPATH, "csv_filepath.csv")
+ self.assertEqual(str(err.exception), "No section: 'ArchivesSpace'")
+
+ # missing configuration file
os.remove(CONFIG_FILEPATH)
with self.assertRaises(IOError) as err:
DACSspace(CONFIG_FILEPATH, "csv_filepath.csv")
| Update "Usage" section in README
Explain what a person would need to do to run DACSspace and what the output looks like. This should include adding information about using different schemas. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_client.py::ArchivesSpaceClientTests::test_connection",
"tests/test_client.py::ArchivesSpaceClientTests::test_data",
"tests/test_client.py::ArchivesSpaceClientTests::test_published_only",
"tests/test_dacsspace.py::TestDACSspace::test_as_config"
] | [
"tests/test_dacsspace.py::TestDACSspace::test_args",
"tests/test_dacsspace.py::TestDACSspace::test_csv_filepath"
] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_removed_files",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
} | "2022-05-05T17:59:12Z" | mit |
|
RockefellerArchiveCenter__DACSspace-78 | diff --git a/README.md b/README.md
index 3649ae3..3278c9a 100644
--- a/README.md
+++ b/README.md
@@ -76,7 +76,9 @@ Pull requests accepted!
## Authors
-Hillel Arnold and Amy Berish
+Initial version: Hillel Arnold and Amy Berish.
+
+Version 2.0: Hillel Arnold, Amy Berish, Bonnie Gordon, Katie Martin, and Darren Young.
## License
diff --git a/dacsspace/client.py b/dacsspace/client.py
index b83eae7..fc19600 100644
--- a/dacsspace/client.py
+++ b/dacsspace/client.py
@@ -1,5 +1,3 @@
-from configparser import ConfigParser
-
from asnake.aspace import ASpace
@@ -10,14 +8,12 @@ class ASnakeConfigError(Exception):
class ArchivesSpaceClient:
"""Handles communication with ArchivesSpace."""
- def __init__(self, as_config):
- config = ConfigParser()
- config.read(as_config)
- self.aspace = ASpace(baseurl=config.get('ArchivesSpace', 'baseurl'),
- username=config.get('ArchivesSpace', 'user'),
- password=config.get('ArchivesSpace', 'password'))
- self.repo = self.aspace.repositories(
- config.get('ArchivesSpace', 'repository'))
+ def __init__(self, baseurl, username, password, repo_id):
+ self.aspace = ASpace(
+ baseurl=baseurl,
+ username=username,
+ password=password)
+ self.repo = self.aspace.repositories(repo_id)
if isinstance(self.repo, dict):
raise ASnakeConfigError(
"Error getting repository: {}".format(
diff --git a/dacsspace/dacsspace.py b/dacsspace/dacsspace.py
index 0488dc1..75a3d81 100644
--- a/dacsspace/dacsspace.py
+++ b/dacsspace/dacsspace.py
@@ -1,4 +1,5 @@
import re
+from configparser import ConfigParser
from os.path import isfile
from .client import ArchivesSpaceClient
@@ -10,21 +11,33 @@ class DACSspace:
"""Base DACSspace class. Fetches data from AS, validates and reports results."""
def __init__(self, as_config, csv_filepath):
- """Checks csv filepath to make sure it has the proper extension and characters."""
+ """Checks CSV and AS config filepaths.
+
+ Args:
+ as_config (str): filepath to ArchivesSpace configuration file.
+ csv_filepath (str): filepath at which to save results file.
+ """
if not csv_filepath.endswith(".csv"):
raise ValueError("File must have .csv extension")
if re.search(r'[*?:"<>|]', csv_filepath):
raise ValueError(
'File name cannot contain the following characters: * ? : " < > | ')
self.csv_filepath = csv_filepath
+
if not isfile(as_config):
raise IOError(
"Could not find an ArchivesSpace configuration file at {}".format(as_config))
- self.as_config = as_config
+ config = ConfigParser()
+ config.read(as_config)
+ self.as_config = (
+ config.get('ArchivesSpace', 'baseurl'),
+ config.get('ArchivesSpace', 'user'),
+ config.get('ArchivesSpace', 'password'),
+ config.get('ArchivesSpace', 'repository'))
def run(self, published_only, invalid_only,
schema_identifier, schema_filepath):
- client = ArchivesSpaceClient(self.as_config)
+ client = ArchivesSpaceClient(*self.as_config)
validator = Validator(schema_identifier, schema_filepath)
reporter = CSVReporter(self.csv_filepath)
data = client.get_resources(published_only)
diff --git a/setup-old.py b/setup-old.py
deleted file mode 100644
index 9d23c53..0000000
--- a/setup-old.py
+++ /dev/null
@@ -1,73 +0,0 @@
-#!/usr/bin/env python
-
-import os
-import sys
-
-current_dir = os.path.dirname(__file__)
-
-file_path = os.path.join(current_dir, "local_settings.cfg")
-
-
-def check_response(response, yes):
- if response != yes:
- print("Exiting!")
- sys.exit()
-
-
-def start_section(section_name):
- cfg_file.write("\n[{}]\n".format(section_name))
-
-
-def write_value(name, default, value=None):
- if value:
- line = ("{}: {}\n".format(name, value))
- else:
- line = ("{}: {}\n".format(name, default))
- cfg_file.write(line)
-
-
-def main():
- global cfg_file
- print("This script will create a configuration file with settings to connect and download JSON files from ArchivesSpace.\nYou\'ll need to know a few things in order to do this:\n\n1. The base URL of the backend of your ArchivesSpace installation, including the port number.\n2. The ID for the ArchivesSpace repository from which you want to export JSON files.\n3. A user name and password for a user with read writes to the ArchivesSpace repository.\n")
- response = input("Do you want to continue? (y/n): ")
- check_response(response, "y")
-
- if os.path.isfile(file_path):
- print("\nIt looks like a configuration file already exists. This script will replace that file.\n")
- response = input("Do you want to continue? (y/n): ")
- check_response(response, "y")
-
- cfg_file = open(file_path, 'w+')
- print("\nOK, let's create this file! I\'ll ask you to enter a bunch of values. If you want to use the default value you can just hit the Enter key.\n")
- start_section("ArchivesSpace")
- print("We\'ll start with some values for your ArchivesSpace instance.")
- baseURL = input(
- "Enter the base URL of your ArchivesSpace installation (default is 'http://localhost:8089'): ")
- write_value("baseURL", "http://localhost:8089", baseURL)
- repoId = input(
- "Enter the repository ID for your ArchivesSpace installation (default is '2'): ")
- write_value("repository", "2", repoId)
- username = input(
- "Enter the username for your ArchivesSpace installation (default is 'admin'): ")
- write_value("user", "admin", username)
- password = input(
- "Enter the password associated with this username (default is 'admin'): ")
- write_value("password", "admin", password)
-
- start_section("Destinations")
- print("\nNow you need to tell me where you want to save the spreadsheet that will be created. Unless you know what you\'re doing, you should probably leave the defaults in place.\n")
- directory = input(
- "Enter the directory in which you want to save the spreadsheet (default is the current directory): ")
- write_value("directory", "", directory)
- filename = input(
- "Now tell me the filename of the CSV spreadsheet you want to create (default is 'dacs_singlelevel_report.csv'): ")
- write_value("filename", "dacs_singlelevel_report.csv", filename)
-
- cfg_file.close()
-
- print("You\'re all set! I created a configuration file at {}. You can edit that file at any time, or run this script again if you want to replace those configurations.".format(file_path))
-
- sys.exit()
-
-
-main()
| RockefellerArchiveCenter/DACSspace | 2ac435473ed330a64842e27109756741727becd6 | diff --git a/tests/test_client.py b/tests/test_client.py
index 59059bb..e7e65c7 100644
--- a/tests/test_client.py
+++ b/tests/test_client.py
@@ -1,6 +1,3 @@
-import configparser
-import os
-import shutil
import unittest
from unittest.mock import Mock, patch
@@ -8,56 +5,15 @@ from asnake.client.web_client import ASnakeAuthError
from dacsspace.client import ArchivesSpaceClient, ASnakeConfigError
-CONFIG_FILEPATH = "as_config.cfg"
-
class ArchivesSpaceClientTests(unittest.TestCase):
def setUp(self):
"""Move existing config file and replace with sample config."""
- if os.path.isfile(CONFIG_FILEPATH):
- shutil.move(CONFIG_FILEPATH, "as_config.old")
- shutil.copy("as_config.example", CONFIG_FILEPATH)
-
- @patch("requests.Session.get")
- @patch("requests.Session.post")
- def test_config_file(self, mock_post, mock_get):
- """Asserts that configuration files are correctly handled:
- - Configuration files without all the necessary values cause an exception to be raised.
- - Valid configuration file allows for successful instantiation of ArchivesSpaceClient class.
- """
- # mock returns from ASpace
- mock_post.return_value.status_code = 200
- mock_post.return_value.text = "{\"session\": \"12355\"}"
- mock_get.return_value.status_code = 200
- mock_get.return_value.text = "v3.0.2"
-
- # Valid config file
- ArchivesSpaceClient(CONFIG_FILEPATH)
-
- # remove baseurl from ArchivesSpace section
- config = configparser.ConfigParser()
- config.read(CONFIG_FILEPATH)
- config.remove_option('ArchivesSpace', 'baseurl')
- with open(CONFIG_FILEPATH, "w") as cf:
- config.write(cf)
-
- # Configuration file missing necessary options
- with self.assertRaises(configparser.NoOptionError) as err:
- ArchivesSpaceClient(CONFIG_FILEPATH)
- self.assertEqual(str(err.exception),
- "No option 'baseurl' in section: 'ArchivesSpace'")
-
- # remove ArchivesSpace section
- config = configparser.ConfigParser()
- config.read(CONFIG_FILEPATH)
- config.remove_section('ArchivesSpace')
- with open(CONFIG_FILEPATH, "w") as cf:
- config.write(cf)
-
- # Configuration file missing necessary section
- with self.assertRaises(configparser.NoSectionError) as err:
- ArchivesSpaceClient(CONFIG_FILEPATH)
- self.assertEqual(str(err.exception), "No section: 'ArchivesSpace'")
+ self.as_config = (
+ "https://sandbox.archivesspace.org/api/",
+ "admin",
+ "admin",
+ 101)
@patch("requests.Session.get")
@patch("requests.Session.post")
@@ -71,14 +27,14 @@ class ArchivesSpaceClientTests(unittest.TestCase):
# Incorrect authentication credentials
mock_post.return_value.status_code = 403
with self.assertRaises(ASnakeAuthError) as err:
- ArchivesSpaceClient(CONFIG_FILEPATH)
+ ArchivesSpaceClient(*self.as_config)
self.assertEqual(str(err.exception),
"Failed to authorize ASnake with status: 403")
# Incorrect base URL
mock_post.return_value.status_code = 404
with self.assertRaises(ASnakeAuthError) as err:
- ArchivesSpaceClient(CONFIG_FILEPATH)
+ ArchivesSpaceClient(*self.as_config)
self.assertEqual(str(err.exception),
"Failed to authorize ASnake with status: 404")
@@ -90,7 +46,7 @@ class ArchivesSpaceClientTests(unittest.TestCase):
mock_get.return_value.json.return_value = {
'error': 'Repository not found'}
with self.assertRaises(ASnakeConfigError) as err:
- ArchivesSpaceClient(CONFIG_FILEPATH)
+ ArchivesSpaceClient(*self.as_config)
self.assertEqual(str(err.exception),
"Error getting repository: Repository not found")
@@ -101,7 +57,7 @@ class ArchivesSpaceClientTests(unittest.TestCase):
"""Asserts that the `published_only` flag is handled correctly."""
mock_get.return_value.text = "v3.0.2" # Allows ArchivesSpaceClient to instantiate
# Instantiates ArchivesSpaceClient for testing
- client = ArchivesSpaceClient(CONFIG_FILEPATH)
+ client = ArchivesSpaceClient(*self.as_config)
# Test search for only published resources
list(client.get_resources(True))
@@ -121,7 +77,7 @@ class ArchivesSpaceClientTests(unittest.TestCase):
def test_data(self, mock_authorize, mock_get, mock_search):
"""Asserts that individual resources are returned"""
mock_get.return_value.text = "v3.0.2"
- client = ArchivesSpaceClient(CONFIG_FILEPATH)
+ client = ArchivesSpaceClient(*self.as_config)
# create a mocked object which acts like an
# `asnake.jsonmodel.JSONModel` object
@@ -133,8 +89,3 @@ class ArchivesSpaceClientTests(unittest.TestCase):
result = list(client.get_resources(True))
self.assertEqual(len(result), 1)
self.assertEqual(result[0], expected_return)
-
- def tearDown(self):
- """Replace sample config with existing config."""
- if os.path.isfile("as_config.old"):
- shutil.move("as_config.old", CONFIG_FILEPATH)
diff --git a/tests/test_dacsspace.py b/tests/test_dacsspace.py
index f20fef4..82c1d4c 100644
--- a/tests/test_dacsspace.py
+++ b/tests/test_dacsspace.py
@@ -1,3 +1,4 @@
+import configparser
import os
import shutil
from unittest import TestCase
@@ -32,7 +33,39 @@ class TestDACSspace(TestCase):
"File must have .csv extension")
def test_as_config(self):
- """Asserts missing files raise an exception."""
+ """Asserts that ArchivesSpace configuration file is correctly handled:
+ - Configuration files without all the necessary values cause an exception to be raised.
+ - Valid configuration file allows for successful instantiation of DACSspace class.
+ - Missing configuration file raises exception.
+ """
+ DACSspace(CONFIG_FILEPATH, "csv_filepath.csv")
+
+ # remove baseurl from ArchivesSpace section
+ config = configparser.ConfigParser()
+ config.read(CONFIG_FILEPATH)
+ config.remove_option('ArchivesSpace', 'baseurl')
+ with open(CONFIG_FILEPATH, "w") as cf:
+ config.write(cf)
+
+ # Configuration file missing necessary options
+ with self.assertRaises(configparser.NoOptionError) as err:
+ DACSspace(CONFIG_FILEPATH, "csv_filepath.csv")
+ self.assertEqual(str(err.exception),
+ "No option 'baseurl' in section: 'ArchivesSpace'")
+
+ # remove ArchivesSpace section
+ config = configparser.ConfigParser()
+ config.read(CONFIG_FILEPATH)
+ config.remove_section('ArchivesSpace')
+ with open(CONFIG_FILEPATH, "w") as cf:
+ config.write(cf)
+
+ # Configuration file missing necessary section
+ with self.assertRaises(configparser.NoSectionError) as err:
+ DACSspace(CONFIG_FILEPATH, "csv_filepath.csv")
+ self.assertEqual(str(err.exception), "No section: 'ArchivesSpace'")
+
+ # missing configuration file
os.remove(CONFIG_FILEPATH)
with self.assertRaises(IOError) as err:
DACSspace(CONFIG_FILEPATH, "csv_filepath.csv")
| Update "Authors" section in README
Add everyone who worked on this version! π₯³ | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_client.py::ArchivesSpaceClientTests::test_connection",
"tests/test_client.py::ArchivesSpaceClientTests::test_data",
"tests/test_client.py::ArchivesSpaceClientTests::test_published_only",
"tests/test_dacsspace.py::TestDACSspace::test_as_config"
] | [
"tests/test_dacsspace.py::TestDACSspace::test_args",
"tests/test_dacsspace.py::TestDACSspace::test_csv_filepath"
] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_removed_files",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
} | "2022-05-05T19:15:13Z" | mit |
|
RockefellerArchiveCenter__DACSspace-79 | diff --git a/README.md b/README.md
index 3649ae3..40e2103 100644
--- a/README.md
+++ b/README.md
@@ -1,8 +1,10 @@
# DACSspace
-A simple Python script to evaluate your ArchivesSpace instance for DACS [single-level minimum](http://www2.archivists.org/standards/DACS/part_I/chapter_1) required elements.
+A Python package to evaluate your ArchivesSpace instance for DACS [single-level required](https://saa-ts-dacs.github.io/dacs/06_part_I/02_chapter_01.html#single-level-required) elements.
-DACSspace utilizes the ArchivesSpace API to check resources for DACS compliance and produces a csv containing a list of evaluated resources. If a DACS field is present its content will be written to the csv, if a field is missing the csv will read "FALSE" for that item.
+DACSspace utilizes the ArchivesSpace API and a default JSON schema to validate resources. The output is a CSV containing a list of invalid URIs with the following fields: validation status, error count, and explanation.
+
+DACSspace also allows users to specify a schema to validate against other than the default DACS single-level required schema, see [Usage](https://github.com/RockefellerArchiveCenter/DACSspace#usage) section for more information.
## Requirements
@@ -24,9 +26,7 @@ Download and install [Python](https://www.python.org/downloads/)
* If you are using Windows, add Python to your [PATH variable](https://docs.python.org/2/using/windows.html)
-Download or [clone](https://docs.github.com/en/repositories/creating-and-managing-repositories/cloning-a-repository) this repository
-
-Install requirements from within the main DACSspace directory: ```pip install -r requirements.txt```
+Install DACSspace and its requirements: ```pip install dacsspace```
## Setup
@@ -76,7 +76,9 @@ Pull requests accepted!
## Authors
-Hillel Arnold and Amy Berish
+Initial version: Hillel Arnold and Amy Berish.
+
+Version 2.0: Hillel Arnold, Amy Berish, Bonnie Gordon, Katie Martin, and Darren Young.
## License
diff --git a/dacsspace/client.py b/dacsspace/client.py
index b83eae7..fc19600 100644
--- a/dacsspace/client.py
+++ b/dacsspace/client.py
@@ -1,5 +1,3 @@
-from configparser import ConfigParser
-
from asnake.aspace import ASpace
@@ -10,14 +8,12 @@ class ASnakeConfigError(Exception):
class ArchivesSpaceClient:
"""Handles communication with ArchivesSpace."""
- def __init__(self, as_config):
- config = ConfigParser()
- config.read(as_config)
- self.aspace = ASpace(baseurl=config.get('ArchivesSpace', 'baseurl'),
- username=config.get('ArchivesSpace', 'user'),
- password=config.get('ArchivesSpace', 'password'))
- self.repo = self.aspace.repositories(
- config.get('ArchivesSpace', 'repository'))
+ def __init__(self, baseurl, username, password, repo_id):
+ self.aspace = ASpace(
+ baseurl=baseurl,
+ username=username,
+ password=password)
+ self.repo = self.aspace.repositories(repo_id)
if isinstance(self.repo, dict):
raise ASnakeConfigError(
"Error getting repository: {}".format(
diff --git a/dacsspace/dacsspace.py b/dacsspace/dacsspace.py
index 0488dc1..75a3d81 100644
--- a/dacsspace/dacsspace.py
+++ b/dacsspace/dacsspace.py
@@ -1,4 +1,5 @@
import re
+from configparser import ConfigParser
from os.path import isfile
from .client import ArchivesSpaceClient
@@ -10,21 +11,33 @@ class DACSspace:
"""Base DACSspace class. Fetches data from AS, validates and reports results."""
def __init__(self, as_config, csv_filepath):
- """Checks csv filepath to make sure it has the proper extension and characters."""
+ """Checks CSV and AS config filepaths.
+
+ Args:
+ as_config (str): filepath to ArchivesSpace configuration file.
+ csv_filepath (str): filepath at which to save results file.
+ """
if not csv_filepath.endswith(".csv"):
raise ValueError("File must have .csv extension")
if re.search(r'[*?:"<>|]', csv_filepath):
raise ValueError(
'File name cannot contain the following characters: * ? : " < > | ')
self.csv_filepath = csv_filepath
+
if not isfile(as_config):
raise IOError(
"Could not find an ArchivesSpace configuration file at {}".format(as_config))
- self.as_config = as_config
+ config = ConfigParser()
+ config.read(as_config)
+ self.as_config = (
+ config.get('ArchivesSpace', 'baseurl'),
+ config.get('ArchivesSpace', 'user'),
+ config.get('ArchivesSpace', 'password'),
+ config.get('ArchivesSpace', 'repository'))
def run(self, published_only, invalid_only,
schema_identifier, schema_filepath):
- client = ArchivesSpaceClient(self.as_config)
+ client = ArchivesSpaceClient(*self.as_config)
validator = Validator(schema_identifier, schema_filepath)
reporter = CSVReporter(self.csv_filepath)
data = client.get_resources(published_only)
diff --git a/setup-old.py b/setup-old.py
deleted file mode 100644
index 9d23c53..0000000
--- a/setup-old.py
+++ /dev/null
@@ -1,73 +0,0 @@
-#!/usr/bin/env python
-
-import os
-import sys
-
-current_dir = os.path.dirname(__file__)
-
-file_path = os.path.join(current_dir, "local_settings.cfg")
-
-
-def check_response(response, yes):
- if response != yes:
- print("Exiting!")
- sys.exit()
-
-
-def start_section(section_name):
- cfg_file.write("\n[{}]\n".format(section_name))
-
-
-def write_value(name, default, value=None):
- if value:
- line = ("{}: {}\n".format(name, value))
- else:
- line = ("{}: {}\n".format(name, default))
- cfg_file.write(line)
-
-
-def main():
- global cfg_file
- print("This script will create a configuration file with settings to connect and download JSON files from ArchivesSpace.\nYou\'ll need to know a few things in order to do this:\n\n1. The base URL of the backend of your ArchivesSpace installation, including the port number.\n2. The ID for the ArchivesSpace repository from which you want to export JSON files.\n3. A user name and password for a user with read writes to the ArchivesSpace repository.\n")
- response = input("Do you want to continue? (y/n): ")
- check_response(response, "y")
-
- if os.path.isfile(file_path):
- print("\nIt looks like a configuration file already exists. This script will replace that file.\n")
- response = input("Do you want to continue? (y/n): ")
- check_response(response, "y")
-
- cfg_file = open(file_path, 'w+')
- print("\nOK, let's create this file! I\'ll ask you to enter a bunch of values. If you want to use the default value you can just hit the Enter key.\n")
- start_section("ArchivesSpace")
- print("We\'ll start with some values for your ArchivesSpace instance.")
- baseURL = input(
- "Enter the base URL of your ArchivesSpace installation (default is 'http://localhost:8089'): ")
- write_value("baseURL", "http://localhost:8089", baseURL)
- repoId = input(
- "Enter the repository ID for your ArchivesSpace installation (default is '2'): ")
- write_value("repository", "2", repoId)
- username = input(
- "Enter the username for your ArchivesSpace installation (default is 'admin'): ")
- write_value("user", "admin", username)
- password = input(
- "Enter the password associated with this username (default is 'admin'): ")
- write_value("password", "admin", password)
-
- start_section("Destinations")
- print("\nNow you need to tell me where you want to save the spreadsheet that will be created. Unless you know what you\'re doing, you should probably leave the defaults in place.\n")
- directory = input(
- "Enter the directory in which you want to save the spreadsheet (default is the current directory): ")
- write_value("directory", "", directory)
- filename = input(
- "Now tell me the filename of the CSV spreadsheet you want to create (default is 'dacs_singlelevel_report.csv'): ")
- write_value("filename", "dacs_singlelevel_report.csv", filename)
-
- cfg_file.close()
-
- print("You\'re all set! I created a configuration file at {}. You can edit that file at any time, or run this script again if you want to replace those configurations.".format(file_path))
-
- sys.exit()
-
-
-main()
| RockefellerArchiveCenter/DACSspace | 2ac435473ed330a64842e27109756741727becd6 | diff --git a/tests/test_client.py b/tests/test_client.py
index 59059bb..e7e65c7 100644
--- a/tests/test_client.py
+++ b/tests/test_client.py
@@ -1,6 +1,3 @@
-import configparser
-import os
-import shutil
import unittest
from unittest.mock import Mock, patch
@@ -8,56 +5,15 @@ from asnake.client.web_client import ASnakeAuthError
from dacsspace.client import ArchivesSpaceClient, ASnakeConfigError
-CONFIG_FILEPATH = "as_config.cfg"
-
class ArchivesSpaceClientTests(unittest.TestCase):
def setUp(self):
"""Move existing config file and replace with sample config."""
- if os.path.isfile(CONFIG_FILEPATH):
- shutil.move(CONFIG_FILEPATH, "as_config.old")
- shutil.copy("as_config.example", CONFIG_FILEPATH)
-
- @patch("requests.Session.get")
- @patch("requests.Session.post")
- def test_config_file(self, mock_post, mock_get):
- """Asserts that configuration files are correctly handled:
- - Configuration files without all the necessary values cause an exception to be raised.
- - Valid configuration file allows for successful instantiation of ArchivesSpaceClient class.
- """
- # mock returns from ASpace
- mock_post.return_value.status_code = 200
- mock_post.return_value.text = "{\"session\": \"12355\"}"
- mock_get.return_value.status_code = 200
- mock_get.return_value.text = "v3.0.2"
-
- # Valid config file
- ArchivesSpaceClient(CONFIG_FILEPATH)
-
- # remove baseurl from ArchivesSpace section
- config = configparser.ConfigParser()
- config.read(CONFIG_FILEPATH)
- config.remove_option('ArchivesSpace', 'baseurl')
- with open(CONFIG_FILEPATH, "w") as cf:
- config.write(cf)
-
- # Configuration file missing necessary options
- with self.assertRaises(configparser.NoOptionError) as err:
- ArchivesSpaceClient(CONFIG_FILEPATH)
- self.assertEqual(str(err.exception),
- "No option 'baseurl' in section: 'ArchivesSpace'")
-
- # remove ArchivesSpace section
- config = configparser.ConfigParser()
- config.read(CONFIG_FILEPATH)
- config.remove_section('ArchivesSpace')
- with open(CONFIG_FILEPATH, "w") as cf:
- config.write(cf)
-
- # Configuration file missing necessary section
- with self.assertRaises(configparser.NoSectionError) as err:
- ArchivesSpaceClient(CONFIG_FILEPATH)
- self.assertEqual(str(err.exception), "No section: 'ArchivesSpace'")
+ self.as_config = (
+ "https://sandbox.archivesspace.org/api/",
+ "admin",
+ "admin",
+ 101)
@patch("requests.Session.get")
@patch("requests.Session.post")
@@ -71,14 +27,14 @@ class ArchivesSpaceClientTests(unittest.TestCase):
# Incorrect authentication credentials
mock_post.return_value.status_code = 403
with self.assertRaises(ASnakeAuthError) as err:
- ArchivesSpaceClient(CONFIG_FILEPATH)
+ ArchivesSpaceClient(*self.as_config)
self.assertEqual(str(err.exception),
"Failed to authorize ASnake with status: 403")
# Incorrect base URL
mock_post.return_value.status_code = 404
with self.assertRaises(ASnakeAuthError) as err:
- ArchivesSpaceClient(CONFIG_FILEPATH)
+ ArchivesSpaceClient(*self.as_config)
self.assertEqual(str(err.exception),
"Failed to authorize ASnake with status: 404")
@@ -90,7 +46,7 @@ class ArchivesSpaceClientTests(unittest.TestCase):
mock_get.return_value.json.return_value = {
'error': 'Repository not found'}
with self.assertRaises(ASnakeConfigError) as err:
- ArchivesSpaceClient(CONFIG_FILEPATH)
+ ArchivesSpaceClient(*self.as_config)
self.assertEqual(str(err.exception),
"Error getting repository: Repository not found")
@@ -101,7 +57,7 @@ class ArchivesSpaceClientTests(unittest.TestCase):
"""Asserts that the `published_only` flag is handled correctly."""
mock_get.return_value.text = "v3.0.2" # Allows ArchivesSpaceClient to instantiate
# Instantiates ArchivesSpaceClient for testing
- client = ArchivesSpaceClient(CONFIG_FILEPATH)
+ client = ArchivesSpaceClient(*self.as_config)
# Test search for only published resources
list(client.get_resources(True))
@@ -121,7 +77,7 @@ class ArchivesSpaceClientTests(unittest.TestCase):
def test_data(self, mock_authorize, mock_get, mock_search):
"""Asserts that individual resources are returned"""
mock_get.return_value.text = "v3.0.2"
- client = ArchivesSpaceClient(CONFIG_FILEPATH)
+ client = ArchivesSpaceClient(*self.as_config)
# create a mocked object which acts like an
# `asnake.jsonmodel.JSONModel` object
@@ -133,8 +89,3 @@ class ArchivesSpaceClientTests(unittest.TestCase):
result = list(client.get_resources(True))
self.assertEqual(len(result), 1)
self.assertEqual(result[0], expected_return)
-
- def tearDown(self):
- """Replace sample config with existing config."""
- if os.path.isfile("as_config.old"):
- shutil.move("as_config.old", CONFIG_FILEPATH)
diff --git a/tests/test_dacsspace.py b/tests/test_dacsspace.py
index f20fef4..82c1d4c 100644
--- a/tests/test_dacsspace.py
+++ b/tests/test_dacsspace.py
@@ -1,3 +1,4 @@
+import configparser
import os
import shutil
from unittest import TestCase
@@ -32,7 +33,39 @@ class TestDACSspace(TestCase):
"File must have .csv extension")
def test_as_config(self):
- """Asserts missing files raise an exception."""
+ """Asserts that ArchivesSpace configuration file is correctly handled:
+ - Configuration files without all the necessary values cause an exception to be raised.
+ - Valid configuration file allows for successful instantiation of DACSspace class.
+ - Missing configuration file raises exception.
+ """
+ DACSspace(CONFIG_FILEPATH, "csv_filepath.csv")
+
+ # remove baseurl from ArchivesSpace section
+ config = configparser.ConfigParser()
+ config.read(CONFIG_FILEPATH)
+ config.remove_option('ArchivesSpace', 'baseurl')
+ with open(CONFIG_FILEPATH, "w") as cf:
+ config.write(cf)
+
+ # Configuration file missing necessary options
+ with self.assertRaises(configparser.NoOptionError) as err:
+ DACSspace(CONFIG_FILEPATH, "csv_filepath.csv")
+ self.assertEqual(str(err.exception),
+ "No option 'baseurl' in section: 'ArchivesSpace'")
+
+ # remove ArchivesSpace section
+ config = configparser.ConfigParser()
+ config.read(CONFIG_FILEPATH)
+ config.remove_section('ArchivesSpace')
+ with open(CONFIG_FILEPATH, "w") as cf:
+ config.write(cf)
+
+ # Configuration file missing necessary section
+ with self.assertRaises(configparser.NoSectionError) as err:
+ DACSspace(CONFIG_FILEPATH, "csv_filepath.csv")
+ self.assertEqual(str(err.exception), "No section: 'ArchivesSpace'")
+
+ # missing configuration file
os.remove(CONFIG_FILEPATH)
with self.assertRaises(IOError) as err:
DACSspace(CONFIG_FILEPATH, "csv_filepath.csv")
| Update README to reflect installing DACSspace as a package
Update the [installation](https://github.com/RockefellerArchiveCenter/DACSspace#installation) section of the README to reflect the changes made in PR #61 as part of issue #60. We can now install daccspace as a package which means we no longer need to install the requirements ourselves.
Instead of `pip install -r requirements.txt` we can use `pip install dacsspace`
From PR #61:
> Adds a [entrypoint](https://python-packaging.readthedocs.io/en/latest/command-line-scripts.html) script which allows DACSspace to be called via the command line. To try this out, from the root of the repository do:
```
pip install .
dacsspace test.csv
``` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_client.py::ArchivesSpaceClientTests::test_connection",
"tests/test_client.py::ArchivesSpaceClientTests::test_data",
"tests/test_client.py::ArchivesSpaceClientTests::test_published_only",
"tests/test_dacsspace.py::TestDACSspace::test_as_config"
] | [
"tests/test_dacsspace.py::TestDACSspace::test_args",
"tests/test_dacsspace.py::TestDACSspace::test_csv_filepath"
] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_issue_reference",
"has_removed_files",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
} | "2022-05-05T19:44:54Z" | mit |
|
RockefellerArchiveCenter__DACSspace-81 | diff --git a/dacsspace/command_line.py b/dacsspace/command_line.py
index d96267a..78bf994 100644
--- a/dacsspace/command_line.py
+++ b/dacsspace/command_line.py
@@ -14,7 +14,7 @@ def main():
parser.add_argument(
'--as_config',
help='Filepath for ArchivesSpace configuration file',
- typ=str,
+ type=str,
default='as_config.cfg')
parser.add_argument(
'--published_only',
diff --git a/requirements.in b/requirements.in
index 94960cd..2db699d 100644
--- a/requirements.in
+++ b/requirements.in
@@ -1,3 +1,3 @@
ArchivesSnake==0.9.1
requests==2.27.1
-jsonschema==4.4.0
+jsonschema==4.6.0
diff --git a/requirements.txt b/requirements.txt
index 72a4b9e..50936a2 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -20,7 +20,7 @@ idna==3.3
# via requests
jarowinkler==1.0.2
# via rapidfuzz
-jsonschema==4.4.0
+jsonschema==4.6.0
# via -r requirements.in
more-itertools==8.12.0
# via archivessnake
diff --git a/setup.py b/setup.py
index 8de4b02..4116e84 100644
--- a/setup.py
+++ b/setup.py
@@ -11,7 +11,7 @@ setup(
long_description_content_type="text/markdown",
author="Rockefeller Archive Center",
author_email="[email protected]",
- version="0.1.0",
+ version="0.1.1",
license='MIT',
packages=find_packages(),
entry_points={
diff --git a/tox.ini b/tox.ini
index e3d0701..f16c325 100644
--- a/tox.ini
+++ b/tox.ini
@@ -1,13 +1,11 @@
[tox]
envlist = py310, linting
-skipsdist = True
[testenv]
deps =
-rrequirements.txt
pytest
coverage
-skip_install = True
commands =
coverage run -m pytest -s
coverage report -m --omit=tests/*
| RockefellerArchiveCenter/DACSspace | 5edc66932c21b5d718e0ffa90d7347e11de04784 | diff --git a/tests/test_commandline.py b/tests/test_commandline.py
new file mode 100644
index 0000000..4c56358
--- /dev/null
+++ b/tests/test_commandline.py
@@ -0,0 +1,10 @@
+import os
+from unittest import TestCase
+
+
+class CommandLineTest(TestCase):
+
+ def test_command_line(self):
+ """Ensures command line interface does not contain typos."""
+ exit_status = os.system('dacsspace --help')
+ assert exit_status == 0
| TypeError when running dacsspace
**Describe the bug**
When running dacsspace I get this error:
`TypeError: _StoreAction.__init__() got an unexpected keyword argument 'typ'`
**To Reproduce**
Steps to reproduce the behavior:
1. `dacsspace test.csv`
4. See error `TypeError: _StoreAction.__init__() got an unexpected keyword argument 'typ'`
**Expected behavior**
The script to run :)
**Additional context**
Found this [article](https://stackoverflow.com/questions/33574270/typeerror-init-got-an-unexpected-keyword-argument-type-in-argparse), seems like it's argparse messing things up?
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_commandline.py::CommandLineTest::test_command_line"
] | [] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2022-06-03T20:58:54Z" | mit |
|
Roguelazer__muttdown-14 | diff --git a/muttdown/config.py b/muttdown/config.py
index 236d16f..a09e9c7 100644
--- a/muttdown/config.py
+++ b/muttdown/config.py
@@ -80,6 +80,7 @@ class Config(object):
if self._config['smtp_password'] and self._config['smtp_password_command']:
raise ConfigError('Cannot set smtp_password *and* smtp_password_command')
if self._config['css_file']:
+ self._css = None
self._config['css_file'] = os.path.expanduser(self._config['css_file'])
if not os.path.exists(self._config['css_file']):
raise ConfigError('CSS file %s does not exist' % self._config['css_file'])
@@ -101,6 +102,6 @@ class Config(object):
@property
def smtp_password(self):
if self._config['smtp_password_command']:
- return check_output(self._config['smtp_password_command'], shell=True).rstrip('\n')
+ return check_output(self._config['smtp_password_command'], shell=True, universal_newlines=True).rstrip('\n')
else:
return self._config['smtp_password']
| Roguelazer/muttdown | 61809de9a445bda848d4933822070e0dd705c192 | diff --git a/tests/test_basic.py b/tests/test_basic.py
index 7f69017..1eb2df9 100644
--- a/tests/test_basic.py
+++ b/tests/test_basic.py
@@ -1,6 +1,8 @@
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.message import Message
+import tempfile
+import shutil
import pytest
@@ -15,11 +17,21 @@ def basic_config():
@pytest.fixture
-def config_with_css(tmpdir):
- with open('%s/test.css' % tmpdir, 'w') as f:
+def tempdir():
+ # workaround because pytest's bultin tmpdir fixture is broken on python 3.3
+ dirname = tempfile.mkdtemp()
+ try:
+ yield dirname
+ finally:
+ shutil.rmtree(dirname)
+
+
[email protected]
+def config_with_css(tempdir):
+ with open('%s/test.css' % tempdir, 'w') as f:
f.write('html, body, p { font-family: serif; }\n')
c = Config()
- c.merge_config({'css_file': '%s/test.css' % tmpdir})
+ c.merge_config({'css_file': '%s/test.css' % tempdir})
return c
diff --git a/tests/test_config.py b/tests/test_config.py
new file mode 100644
index 0000000..f5a040b
--- /dev/null
+++ b/tests/test_config.py
@@ -0,0 +1,27 @@
+import tempfile
+
+from muttdown.config import Config
+
+
+def test_smtp_password_literal():
+ c = Config()
+ c.merge_config({'smtp_password': 'foo'})
+ assert c.smtp_password == 'foo'
+
+
+def test_smtp_password_command():
+ c = Config()
+ c.merge_config({'smtp_password_command': 'sh -c "echo foo"'})
+ assert c.smtp_password == 'foo'
+
+
+def test_css():
+ c = Config()
+ c.merge_config({'css_file': None})
+ assert c.css == ''
+
+ with tempfile.NamedTemporaryFile(delete=True) as css_file:
+ css_file.write(b'html { background-color: black; }\n')
+ css_file.flush()
+ c.merge_config({'css_file': css_file.name})
+ assert c.css == 'html { background-color: black; }\n'
| Error when trying to run gpg command as smtp_password_command
Hello, I've just switched machines and have been setting things up as I usually have them. I seem to be having an issue with the `smtp_password_command` parameter. My yaml file looks like this:
```yaml
smtp_host: smtp.gmail.com
smtp_port: 465
smtp_ssl: true
smtp_username: [email protected]
smtp_password_command: gpg -d --no-tty /home/jacklenox/.passwd/gmail.gpg
```
But when I try to send an email, I get the following error.
```
Traceback (most recent call last):
File "/home/jacklenox/.local/bin/muttdown", line 11, in <module>
sys.exit(main())
File "/home/jacklenox/.local/lib/python3.6/site-packages/muttdown/main.py",
line 169, in main
conn = smtp_connection(c)
File "/home/jacklenox/.local/lib/python3.6/site-packages/muttdown/main.py",
line 120, in smtp_connection
conn.login(c.smtp_username, c.smtp_password)
File "/home/jacklenox/.local/lib/python3.6/site-packages/muttdown/config.py",
line 104, in smtp_password
return check_output(self._config['smtp_password_command'],
shell=True).rstrip('\n')
TypeError: a bytes-like object is required, not 'str'
```
If I replace `smtp_password_command` with the decrypted `smtp_password`, everything works fine. And if I try to run the GPG command on its own, equally everything works.
Any thoughts? | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_config.py::test_smtp_password_command",
"tests/test_config.py::test_css"
] | [
"tests/test_basic.py::test_unmodified_no_match",
"tests/test_basic.py::test_simple_message",
"tests/test_basic.py::test_with_css",
"tests/test_config.py::test_smtp_password_literal"
] | {
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
} | "2018-10-22T16:11:11Z" | isc |
|
Roguelazer__muttdown-21 | diff --git a/muttdown/main.py b/muttdown/main.py
index d9c551f..0816c28 100644
--- a/muttdown/main.py
+++ b/muttdown/main.py
@@ -59,7 +59,7 @@ def _move_headers(source, dest):
del source[k]
-def convert_tree(message, config, indent=0):
+def convert_tree(message, config, indent=0, wrap_alternative=True):
"""Recursively convert a potentially-multipart tree.
Returns a tuple of (the converted tree, whether any markdown was found)
@@ -73,19 +73,32 @@ def convert_tree(message, config, indent=0):
if disposition == 'inline' and ct in ('text/plain', 'text/markdown'):
converted = convert_one(message, config)
if converted is not None:
- new_tree = MIMEMultipart('alternative')
- _move_headers(message, new_tree)
- new_tree.attach(message)
- new_tree.attach(converted)
- return new_tree, True
+ if wrap_alternative:
+ new_tree = MIMEMultipart('alternative')
+ _move_headers(message, new_tree)
+ new_tree.attach(message)
+ new_tree.attach(converted)
+ return new_tree, True
+ else:
+ return converted, True
return message, False
else:
if ct == 'multipart/signed':
# if this is a multipart/signed message, then let's just
# recurse into the non-signature part
+ new_root = MIMEMultipart('alternative')
+ if message.preamble:
+ new_root.preamble = message.preamble
+ _move_headers(message, new_root)
+ converted = None
for part in message.get_payload():
if part.get_content_type() != 'application/pgp-signature':
- return convert_tree(part, config, indent=indent + 1)
+ converted, did_conversion = convert_tree(part, config, indent=indent + 1,
+ wrap_alternative=False)
+ if did_conversion:
+ new_root.attach(converted)
+ new_root.attach(message)
+ return new_root, did_conversion
else:
did_conversion = False
new_root = MIMEMultipart(cs, message.get_charset())
| Roguelazer/muttdown | a8d8b954fa0dcc51a215df36041c2d330d7f1c19 | diff --git a/requirements-tests.txt b/requirements-tests.txt
index 2dab085..e2da4c8 100644
--- a/requirements-tests.txt
+++ b/requirements-tests.txt
@@ -1,2 +1,2 @@
-pytest>=3.0,<4.0
-pytest-cov>=2.0,<3.0
+pytest==3.10.*
+pytest-cov==2.6.*
diff --git a/tests/test_basic.py b/tests/test_basic.py
index 1eb2df9..e86bf31 100644
--- a/tests/test_basic.py
+++ b/tests/test_basic.py
@@ -1,5 +1,6 @@
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
+from email.mime.application import MIMEApplication
from email.message import Message
import tempfile
import shutil
@@ -100,3 +101,37 @@ def test_with_css(config_with_css):
assert text_part.get_payload(decode=True) == b'!m\n\nThis is a message'
html_part = converted.get_payload()[1]
assert html_part.get_payload(decode=True) == b'<p style="font-family: serif">This is a message</p>'
+
+
+def test_headers_when_multipart_signed(basic_config):
+ msg = MIMEMultipart('signed')
+ msg['Subject'] = 'Test Message'
+ msg['From'] = '[email protected]'
+ msg['To'] = '[email protected]'
+ msg['Bcc'] = 'bananas'
+ msg.preamble = 'Outer preamble'
+
+ msg.attach(MIMEText("!m This is the main message body"))
+ msg.attach(MIMEApplication('signature here', 'pgp-signature', name='signature.asc'))
+
+ converted, _ = convert_tree(msg, basic_config)
+
+ assert converted['Subject'] == 'Test Message'
+ assert converted['From'] == '[email protected]'
+ assert converted['To'] == '[email protected]'
+
+ assert isinstance(converted, MIMEMultipart)
+ assert converted.preamble == 'Outer preamble'
+ assert len(converted.get_payload()) == 2
+ assert converted.get_content_type() == 'multipart/alternative'
+ html_part = converted.get_payload()[0]
+ original_signed_part = converted.get_payload()[1]
+ assert isinstance(html_part, MIMEText)
+ assert html_part.get_content_type() == 'text/html'
+ assert isinstance(original_signed_part, MIMEMultipart)
+ assert original_signed_part.get_content_type() == 'multipart/signed'
+ assert original_signed_part['Subject'] is None
+ text_part = original_signed_part.get_payload()[0]
+ signature_part = original_signed_part.get_payload()[1]
+ assert text_part.get_content_type() == 'text/plain'
+ assert signature_part.get_content_type() == 'application/pgp-signature'
| Most header information seems to be going missing somewhere
Hello, I don't send a huge amount of email from Mutt so I'm not sure how long this has been going on, but I've recently realised that when I send emails, almost all the header information appears to get discarded. At the receiving end I can't see the "Subject", or the full "From" name (just the raw email address is shown there). Emails sent via Muttdown also don't appear to be including my PGP electronic signature. Interestingly, the email in my "Sent items" looks exactly as it should and includes the PGP signature.
If I take Muttdown out of the picture, everything seems to be working fine.
I'm running Neomutt 20180716. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_basic.py::test_headers_when_multipart_signed"
] | [
"tests/test_basic.py::test_unmodified_no_match",
"tests/test_basic.py::test_simple_message",
"tests/test_basic.py::test_with_css"
] | {
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
} | "2019-02-09T02:35:32Z" | isc |
|
SALib__SALib-457 | diff --git a/examples/Problem/multi_output.py b/examples/Problem/multi_output.py
index a308bff..717aec0 100644
--- a/examples/Problem/multi_output.py
+++ b/examples/Problem/multi_output.py
@@ -18,7 +18,7 @@ sp = ProblemSpec({
'outputs': ['max_P', 'Utility', 'Inertia', 'Reliability']
})
-(sp.sample_saltelli(1000)
+(sp.sample_saltelli(1024)
.evaluate(lake_problem.evaluate)
.analyze_sobol())
diff --git a/examples/Problem/problem_spec.py b/examples/Problem/problem_spec.py
index 3c7a49a..e250a7c 100644
--- a/examples/Problem/problem_spec.py
+++ b/examples/Problem/problem_spec.py
@@ -1,15 +1,15 @@
"""Example showing how to use the ProblemSpec approach.
-Showcases method chaining, and parallel model runs using
-all available processors.
+Showcases method chaining, and parallel model runs using 2 processors.
The following caveats apply:
-1. Functions passed into `sample`, `analyze`, `evaluate` and `evaluate_*` must
+1. Functions passed into `sample`, `analyze` and `evaluate` must
accept a numpy array of `X` values as the first parameter, and return a
numpy array of results.
-2. Parallel evaluation is only beneficial for long-running models
-3. Currently, model results must fit in memory - no on-disk caching is provided.
+2. Parallel evaluation/analysis is only beneficial for long-running models
+ or large datasets
+3. Currently, results must fit in memory - no on-disk caching is provided.
"""
from SALib.analyze import sobol
@@ -33,29 +33,40 @@ if __name__ == '__main__':
# Single core example
start = time.perf_counter()
- (sp.sample_saltelli(25000)
+ (sp.sample_saltelli(2**15)
.evaluate(Ishigami.evaluate)
.analyze_sobol(calc_second_order=True, conf_level=0.95))
print("Time taken with 1 core:", time.perf_counter() - start, '\n')
+ # Same above example, but passing in specific functions
+ # (sp.sample(saltelli.sample, 25000, calc_second_order=True)
+ # .evaluate(Ishigami.evaluate)
+ # .analyze(sobol.analyze, calc_second_order=True, conf_level=0.95))
+
# Samples, model results and analyses can be extracted:
# print(sp.samples)
# print(sp.results)
# print(sp.analysis)
# print(sp.to_df())
- # Same above, but passing in specific functions
- # (sp.sample(saltelli.sample, 25000, calc_second_order=True)
- # .evaluate(Ishigami.evaluate)
- # .analyze(sobol.analyze, calc_second_order=True, conf_level=0.95))
+ # Can set pre-existing samples/results as needed
+ # sp.samples = some_numpy_array
+ # sp.set_samples(some_numpy_array)
+ #
+ # Using method chaining...
+ # (sp.set_samples(some_numpy_array)
+ # .set_results(some_result_array)
+ # .analyze_sobol(calc_second_order=True, conf_level=0.95))
# Parallel example
start = time.perf_counter()
- (sp.sample(saltelli.sample, 25000)
+ (sp.sample(saltelli.sample, 2**15)
# can specify number of processors to use with `nprocs`
- .evaluate_parallel(Ishigami.evaluate, nprocs=2)
- .analyze(sobol.analyze, calc_second_order=True, conf_level=0.95))
- print("Time taken with all available cores:", time.perf_counter() - start, '\n')
+ # this will be capped to the number of detected processors
+ # or, in the case of analysis, the number of outputs.
+ .evaluate(Ishigami.evaluate, nprocs=2)
+ .analyze_sobol(calc_second_order=True, conf_level=0.95, nprocs=2))
+ print("Time taken with 2 cores:", time.perf_counter() - start, '\n')
print(sp)
@@ -66,7 +77,7 @@ if __name__ == '__main__':
'localhost:55776')
start = time.perf_counter()
- (sp.sample(saltelli.sample, 25000)
+ (sp.sample(saltelli.sample, 2**15)
.evaluate_distributed(Ishigami.evaluate, nprocs=2, servers=servers, verbose=True)
.analyze(sobol.analyze, calc_second_order=True, conf_level=0.95))
print("Time taken with distributed cores:", time.perf_counter() - start, '\n')
diff --git a/src/SALib/analyze/sobol.py b/src/SALib/analyze/sobol.py
index 002ab6b..289e407 100644
--- a/src/SALib/analyze/sobol.py
+++ b/src/SALib/analyze/sobol.py
@@ -65,7 +65,11 @@ def analyze(problem, Y, calc_second_order=True, num_resamples=100,
"""
if seed:
- np.random.seed(seed)
+ # Set seed to ensure CIs are the same
+ rng = np.random.default_rng(seed).integers
+ else:
+ rng = np.random.randint
+
# determining if groups are defined and adjusting the number
# of rows in the cross-sampled matrix accordingly
groups = _check_groups(problem)
@@ -90,7 +94,7 @@ def analyze(problem, Y, calc_second_order=True, num_resamples=100,
Y = (Y - Y.mean()) / Y.std()
A, B, AB, BA = separate_output_values(Y, D, N, calc_second_order)
- r = np.random.randint(N, size=(N, num_resamples))
+ r = rng(N, size=(N, num_resamples))
Z = norm.ppf(0.5 + conf_level / 2)
if not parallel:
diff --git a/src/SALib/util/problem.py b/src/SALib/util/problem.py
index 6a2dd78..177e941 100644
--- a/src/SALib/util/problem.py
+++ b/src/SALib/util/problem.py
@@ -5,6 +5,7 @@ from types import MethodType
from multiprocess import Pool, cpu_count
from pathos.pp import ParallelPythonPool as pp_Pool
from functools import partial, wraps
+import itertools as it
import numpy as np
@@ -61,7 +62,7 @@ class ProblemSpec(dict):
@property
def results(self):
return self._results
-
+
@results.setter
def results(self, vals):
val_shape = vals.shape
@@ -85,7 +86,7 @@ class ProblemSpec(dict):
raise ValueError(msg)
self._results = vals
-
+
@property
def analysis(self):
return self._analysis
@@ -99,10 +100,10 @@ class ProblemSpec(dict):
Sampling method to use. The given function must accept the SALib
problem specification as the first parameter and return a numpy
array.
-
+
*args : list,
Additional arguments to be passed to `func`
-
+
**kwargs : dict,
Additional keyword arguments passed to `func`
@@ -118,17 +119,19 @@ class ProblemSpec(dict):
return self
- def set_samples(self, samples):
+ def set_samples(self, samples: np.ndarray):
"""Set previous samples used."""
self.samples = samples
return self
- def set_results(self, results):
+ def set_results(self, results: np.ndarray):
"""Set previously available model results."""
+ if self.samples is not None:
+ assert self.samples.shape[0] == results.shape[0], \
+ "Provided result array does not match existing number of existing samples!"
+
self.results = results
- # if self.samples is not None:
- # warnings.warn('Existing samples found - make sure these results are for those samples!')
return self
@@ -142,10 +145,13 @@ class ProblemSpec(dict):
The provided function is required to accept a numpy array of
inputs as its first parameter and must return a numpy array of
results.
-
+
*args : list,
Additional arguments to be passed to `func`
-
+
+ nprocs : int,
+ If specified, attempts to parallelize model evaluations
+
**kwargs : dict,
Additional keyword arguments passed to `func`
@@ -153,10 +159,14 @@ class ProblemSpec(dict):
----------
self : ProblemSpec object
"""
+ if 'nprocs' in kwargs:
+ nprocs = kwargs.pop('nprocs')
+ return self.evaluate_parallel(func, *args, nprocs=nprocs, **kwargs)
+
self._results = func(self._samples, *args, **kwargs)
return self
-
+
def evaluate_parallel(self, func, *args, nprocs=None, **kwargs):
"""Evaluate model locally in parallel.
@@ -166,15 +176,16 @@ class ProblemSpec(dict):
----------
func : function,
Model, or function that wraps a model, to be run in parallel.
- The provided function needs to accept a numpy array of inputs as
+ The provided function needs to accept a numpy array of inputs as
its first parameter and must return a numpy array of results.
-
+
nprocs : int,
- Number of processors to use. Uses all available if not specified.
-
+ Number of processors to use.
+ Capped to the number of available processors.
+
*args : list,
Additional arguments to be passed to `func`
-
+
**kwargs : dict,
Additional keyword arguments passed to `func`
@@ -186,9 +197,14 @@ class ProblemSpec(dict):
if self._samples is None:
raise RuntimeError("Sampling not yet conducted")
-
+
+ max_procs = cpu_count()
if nprocs is None:
- nprocs = cpu_count()
+ nprocs = max_procs
+ else:
+ if nprocs > max_procs:
+ warnings.warn(f"{nprocs} processors requested but only {max_procs} found.")
+ nprocs = min(max_procs, nprocs)
# Create wrapped partial function to allow passing of additional args
tmp_f = self._wrap_func(func, *args, **kwargs)
@@ -211,7 +227,7 @@ class ProblemSpec(dict):
"""Distribute model evaluation across a cluster.
Usage Conditions:
- * The provided function needs to accept a numpy array of inputs as
+ * The provided function needs to accept a numpy array of inputs as
its first parameter
* The provided function must return a numpy array of results
@@ -219,19 +235,19 @@ class ProblemSpec(dict):
----------
func : function,
Model, or function that wraps a model, to be run in parallel
-
+
nprocs : int,
Number of processors to use for each node. Defaults to 1.
-
+
servers : list[str] or None,
IP addresses or alias for each server/node to use.
verbose : bool,
Display job execution statistics. Defaults to False.
-
+
*args : list,
Additional arguments to be passed to `func`
-
+
**kwargs : dict,
Additional keyword arguments passed to `func`
@@ -266,17 +282,19 @@ class ProblemSpec(dict):
def analyze(self, func, *args, **kwargs):
"""Analyze sampled results using given function.
-
Parameters
----------
func : function,
- Analysis method to use. The provided function must accept the
- problem specification as the first parameter, X values if needed,
+ Analysis method to use. The provided function must accept the
+ problem specification as the first parameter, X values if needed,
Y values, and return a numpy array.
-
+
*args : list,
Additional arguments to be passed to `func`
-
+
+ nprocs : int,
+ If specified, attempts to parallelize model evaluations
+
**kwargs : dict,
Additional keyword arguments passed to `func`
@@ -284,12 +302,18 @@ class ProblemSpec(dict):
----------
self : ProblemSpec object
"""
+ if 'nprocs' in kwargs:
+ # Call parallel method instead
+ return self.analyze_parallel(func, *args, **kwargs)
+
if self._results is None:
raise RuntimeError("Model not yet evaluated")
if 'X' in func.__code__.co_varnames:
# enforce passing of X if expected
func = partial(func, *args, X=self._samples, **kwargs)
+ else:
+ func = partial(func, *args, **kwargs)
out_cols = self.get('outputs', None)
if out_cols is None:
@@ -302,9 +326,87 @@ class ProblemSpec(dict):
if len(self['outputs']) > 1:
self._analysis = {}
for i, out in enumerate(self['outputs']):
- self._analysis[out] = func(self, *args, Y=self._results[:, i], **kwargs)
+ self._analysis[out] = func(self, Y=self._results[:, i])
else:
- self._analysis = func(self, *args, Y=self._results, **kwargs)
+ self._analysis = func(self, Y=self._results)
+
+ return self
+
+ def analyze_parallel(self, func, *args, nprocs=None, **kwargs):
+ """Analyze sampled results using the given function in parallel.
+
+ Parameters
+ ----------
+ func : function,
+ Analysis method to use. The provided function must accept the
+ problem specification as the first parameter, X values if needed,
+ Y values, and return a numpy array.
+
+ *args : list,
+ Additional arguments to be passed to `func`
+
+ nprocs : int,
+ Number of processors to use.
+ Capped to the number of outputs or available processors.
+
+ **kwargs : dict,
+ Additional keyword arguments passed to `func`
+
+ Returns
+ ----------
+ self : ProblemSpec object
+ """
+ warnings.warn("This is an experimental feature and may not work.")
+
+ if self._results is None:
+ raise RuntimeError("Model not yet evaluated")
+
+ if 'X' in func.__code__.co_varnames:
+ # enforce passing of X if expected
+ func = partial(func, *args, X=self._samples, **kwargs)
+ else:
+ func = partial(func, *args, **kwargs)
+
+ out_cols = self.get('outputs', None)
+ if out_cols is None:
+ if len(self._results.shape) == 1:
+ self['outputs'] = ['Y']
+ else:
+ num_cols = self._results.shape[1]
+ self['outputs'] = [f'Y{i}' for i in range(1, num_cols+1)]
+
+ # Cap number of processors used
+ Yn = len(self['outputs'])
+ if Yn == 1:
+ # Only single output, cannot parallelize
+ warnings.warn(f"Analysis was not parallelized: {nprocs} processors requested for 1 output.")
+
+ res = func(self, Y=self._results)
+ else:
+ max_procs = cpu_count()
+ if nprocs is None:
+ nprocs = max_procs
+ else:
+ nprocs = min(Yn, nprocs, max_procs)
+
+ if ptqdm_available:
+ # Display progress bar if available
+ res = p_imap(lambda y: func(self, Y=y),
+ [self._results[:, i] for i in range(Yn)],
+ num_cpus=nprocs)
+ else:
+ with Pool(nprocs) as pool:
+ res = list(pool.imap(lambda y: func(self, Y=y),
+ [self._results[:, i] for i in range(Yn)]))
+
+ # Assign by output name if more than 1 output, otherwise
+ # attach directly
+ if Yn > 1:
+ self._analysis = {}
+ for out, Si in zip(self['outputs'], list(res)):
+ self._analysis[out] = Si
+ else:
+ self._analysis = res
return self
@@ -316,9 +418,9 @@ class ProblemSpec(dict):
elif isinstance(an_res, dict):
# case where analysis result is a dict of ResultDicts
return [an.to_df() for an in list(an_res.values())]
-
+
raise RuntimeError("Analysis not yet conducted")
-
+
def plot(self):
"""Plot results.
@@ -346,7 +448,7 @@ class ProblemSpec(dict):
p_width = max(num_cols*3, 5)
p_height = max(num_rows*3, 6)
- _, axes = plt.subplots(num_rows, num_cols, sharey=True,
+ _, axes = plt.subplots(num_rows, num_cols, sharey=True,
figsize=(p_width, p_height))
for res, ax in zip(self._analysis, axes):
self._analysis[res].plot(ax=ax)
@@ -366,9 +468,9 @@ class ProblemSpec(dict):
tmp_f = func
if (len(args) > 0) or (len(kwargs) > 0):
tmp_f = partial(func, *args, **kwargs)
-
+
return tmp_f
-
+
def _setup_result_array(self):
if len(self['outputs']) > 1:
res_shape = (len(self._samples), len(self['outputs']))
@@ -388,24 +490,25 @@ class ProblemSpec(dict):
r_len = len(r)
final_res[i:i+r_len] = r
i += r_len
-
+
return final_res
def _method_creator(self, func, method):
+ """Generate convenience methods for specified `method`."""
@wraps(func)
def modfunc(self, *args, **kwargs):
return getattr(self, method)(func, *args, **kwargs)
-
+
return modfunc
def _add_samplers(self):
"""Dynamically add available SALib samplers as ProblemSpec methods."""
for sampler in avail_approaches(samplers):
func = getattr(importlib.import_module('SALib.sample.{}'.format(sampler)), 'sample')
- method_name = "sample_{}".format(sampler.replace('_sampler', ''))
+ method_name = "sample_{}".format(sampler.replace('_sampler', ''))
self.__setattr__(method_name, MethodType(self._method_creator(func, 'sample'), self))
-
+
def _add_analyzers(self):
"""Dynamically add available SALib analyzers as ProblemSpec methods."""
for analyzer in avail_approaches(analyzers):
@@ -414,13 +517,25 @@ class ProblemSpec(dict):
self.__setattr__(method_name, MethodType(self._method_creator(func, 'analyze'), self))
- def __repr__(self):
+ def __str__(self):
if self._samples is not None:
- print('Samples:', self._samples.shape, "\n")
+ arr_shape = self._samples.shape
+ if len(arr_shape) == 1:
+ arr_shape = (arr_shape[0], 1)
+ nr, nx = arr_shape
+ print('Samples:')
+ print(f'\t{nx} parameters:', self['names'])
+ print(f'\t{nr} evaluations', '\n')
if self._results is not None:
- print('Outputs:', self._results.shape, "\n")
+ arr_shape = self._results.shape
+ if len(arr_shape) == 1:
+ arr_shape = (arr_shape[0], 1)
+ nr, ny = arr_shape
+ print('Outputs:')
+ print(f"\t{ny} outputs:", self['outputs'])
+ print(f'\t{nr} evaluations', '\n')
if self._analysis is not None:
- print('Analysis:\n')
+ print('Analysis:')
an_res = self._analysis
allowed_types = (list, tuple)
@@ -448,7 +563,7 @@ def _check_spec_attributes(spec: ProblemSpec):
assert 'bounds' in spec, "Bounds not defined"
assert len(spec['bounds']) == len(spec['names']), \
f"""Number of bounds do not match number of names
- Number of names:
+ Number of names:
{len(spec['names'])} | {spec['names']}
----------------
Number of bounds: {len(spec['bounds'])}
| SALib/SALib | 4012c1313ee360d0cc3be0fba084f4f86048e2ea | diff --git a/src/SALib/test_functions/lake_problem.py b/src/SALib/test_functions/lake_problem.py
index 88cf0e2..a0792d9 100644
--- a/src/SALib/test_functions/lake_problem.py
+++ b/src/SALib/test_functions/lake_problem.py
@@ -55,7 +55,7 @@ def lake_problem(X: FLOAT_OR_ARRAY, a: FLOAT_OR_ARRAY = 0.1, q: FLOAT_OR_ARRAY =
return X_t1
-def evaluate_lake(values: np.ndarray) -> np.ndarray:
+def evaluate_lake(values: np.ndarray, seed=101) -> np.ndarray:
"""Evaluate the Lake Problem with an array of parameter values.
.. [1] Hadka, D., Herman, J., Reed, P., Keller, K., (2015).
@@ -86,15 +86,17 @@ def evaluate_lake(values: np.ndarray) -> np.ndarray:
-------
np.ndarray, of Phosphorus pollution over time `t`
"""
+ rng = np.random.default_rng(seed)
+
nvars = values.shape[0]
a, q, b, mean, stdev = values.T
sq_mean = mean**2
sq_std = stdev**2
- eps = np.random.lognormal(log(sq_mean / sqrt(sq_std + sq_mean)),
- sqrt(log(1.0 + sq_std / sq_mean)),
- size=nvars)
+ eps = rng.lognormal(log(sq_mean / sqrt(sq_std + sq_mean)),
+ sqrt(log(1.0 + sq_std / sq_mean)),
+ size=nvars)
Y = np.zeros((nvars, nvars))
for t in range(nvars):
@@ -104,7 +106,7 @@ def evaluate_lake(values: np.ndarray) -> np.ndarray:
return Y
-def evaluate(values: np.ndarray, nvars: int = 100):
+def evaluate(values: np.ndarray, nvars: int = 100, seed=101):
"""Evaluate the Lake Problem with an array of parameter values.
Parameters
@@ -126,7 +128,7 @@ def evaluate(values: np.ndarray, nvars: int = 100):
nsamples = len(a)
Y = np.empty((nsamples, 4))
for i in range(nsamples):
- tmp = evaluate_lake(values[i, :5])
+ tmp = evaluate_lake(values[i, :5], seed=seed)
a_i = a[i]
q_i = q[i]
diff --git a/tests/test_cli_analyze.py b/tests/test_cli_analyze.py
index 411a3fc..1c4f01b 100644
--- a/tests/test_cli_analyze.py
+++ b/tests/test_cli_analyze.py
@@ -243,7 +243,7 @@ def test_sobol():
result = subprocess.check_output(analyze_cmd, universal_newlines=True)
result = re.sub(r'[\n\t\s]*', '', result)
- expected_output = 'STST_confx10.5579470.084460x20.4421890.044082x30.2414020.028068S1S1_confx10.3105760.060494x20.4436530.054648x3-0.0129620.054765S2S2_conf(x1,x2)-0.0143970.084384(x1,x3)0.2462310.103131(x2,x3)0.0005390.064658'
+ expected_output = "STST_confx10.5579470.085851x20.4421890.041396x30.2414020.028607S1S1_confx10.3105760.059615x20.4436530.053436x3-0.0129620.053891S2S2_conf(x1,x2)-0.0143970.083679(x1,x3)0.2462310.103117(x2,x3)0.0005390.064169"
assert len(result) > 0 and result == expected_output, \
"Results did not match expected values:\n\n Expected: \n{} \n\n Got: \n{}".format(
expected_output, result)
diff --git a/tests/test_problem_spec.py b/tests/test_problem_spec.py
index c826646..fc8226b 100644
--- a/tests/test_problem_spec.py
+++ b/tests/test_problem_spec.py
@@ -1,4 +1,5 @@
import pytest
+import copy
import numpy as np
@@ -83,6 +84,56 @@ def test_sp_setters():
.analyze_sobol(calc_second_order=True, conf_level=0.95))
-if __name__ == '__main__':
- test_sp_setters()
+def test_parallel_single_output():
+ # Create the SALib Problem specification
+ sp = ProblemSpec({
+ 'names': ['x1', 'x2', 'x3'],
+ 'groups': None,
+ 'bounds': [[-np.pi, np.pi]]*3,
+ 'outputs': ['Y']
+ })
+
+ # Single core example
+ (sp.sample_saltelli(2**8)
+ .evaluate(Ishigami.evaluate)
+ .analyze_sobol(calc_second_order=True, conf_level=0.95, seed=101))
+
+ # Parallel example
+ psp = copy.deepcopy(sp)
+ (psp.sample_saltelli(2**8)
+ .evaluate_parallel(Ishigami.evaluate, nprocs=2)
+ .analyze_sobol(calc_second_order=True, conf_level=0.95, nprocs=2, seed=101))
+
+ assert np.testing.assert_equal(sp.results, psp.results) is None, "Model results not equal!"
+ assert np.testing.assert_equal(sp.analysis, psp.analysis) is None, "Analysis results not equal!"
+
+
+def test_parallel_multi_output():
+ from SALib.test_functions import lake_problem
+
+ # Create the SALib Problem specification
+ sp = ProblemSpec({
+ 'names': ['a', 'q', 'b', 'mean', 'stdev', 'delta', 'alpha'],
+ 'bounds': [[0.0, 0.1],
+ [2.0, 4.5],
+ [0.1, 0.45],
+ [0.01, 0.05],
+ [0.001, 0.005],
+ [0.93, 0.99],
+ [0.2, 0.5]],
+ 'outputs': ['max_P', 'Utility', 'Inertia', 'Reliability']
+ })
+
+ # Single core example
+ (sp.sample_saltelli(2**8)
+ .evaluate(lake_problem.evaluate)
+ .analyze_sobol(calc_second_order=True, conf_level=0.95, seed=101))
+
+ # Parallel example
+ psp = copy.deepcopy(sp)
+ (psp.sample_saltelli(2**8)
+ .evaluate_parallel(lake_problem.evaluate, nprocs=2)
+ .analyze_sobol(calc_second_order=True, conf_level=0.95, nprocs=2, seed=101))
+ assert np.testing.assert_equal(sp.results, psp.results) is None, "Model results not equal!"
+ assert np.testing.assert_equal(sp.analysis, psp.analysis) is None, "Analysis results not equal!"
| Add parallel analysis
Users are currently expected to apply the desired analysis method to every column in the result array.
```python
# example taken from readme
sobol_indices = [sobol.analyze(problem, Y) for Y in y.T]
```
The hybrid OO/functional approach introduced in v1.4 handles this [automatically](https://github.com/SALib/SALib/blob/4012c1313ee360d0cc3be0fba084f4f86048e2ea/src/SALib/util/problem.py#L302) but does so sequentially as in the above example.
The approach could be extended to allow parallel analyses. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_cli_analyze.py::test_sobol",
"tests/test_problem_spec.py::test_parallel_multi_output"
] | [
"tests/test_cli_analyze.py::test_delta",
"tests/test_cli_analyze.py::test_dgsm",
"tests/test_cli_analyze.py::test_fast",
"tests/test_cli_analyze.py::test_ff",
"tests/test_cli_analyze.py::test_rbd_fast",
"tests/test_problem_spec.py::test_sp_bounds",
"tests/test_problem_spec.py::test_sp",
"tests/test_problem_spec.py::test_sp_setters"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2021-08-07T05:55:41Z" | mit |
|
SAP__cf-python-logging-support-14 | diff --git a/.gitignore b/.gitignore
index e6ff992..4a314cd 100644
--- a/.gitignore
+++ b/.gitignore
@@ -12,6 +12,7 @@ __pycache__/
# Distribution / packaging
.Python
+.env
env/
env3/
venv/
@@ -25,6 +26,7 @@ lib/
dist/
lib64/
parts/
+.pytest_cache/
sdist/
var/
*.egg-info/
diff --git a/sap/cf_logging/formatters/json_formatter.py b/sap/cf_logging/formatters/json_formatter.py
index 9df5474..1e941d0 100644
--- a/sap/cf_logging/formatters/json_formatter.py
+++ b/sap/cf_logging/formatters/json_formatter.py
@@ -2,22 +2,26 @@
import json
import logging
import sys
+from sap.cf_logging.record.simple_log_record import SimpleLogRecord
+
+def _default_serializer(obj):
+ return str(obj)
if sys.version_info[0] == 3:
def _encode(obj):
- return json.dumps(obj)
+ return json.dumps(obj, default=_default_serializer)
else:
def _encode(obj):
- return unicode(json.dumps(obj)) # pylint: disable=undefined-variable
+ return unicode(json.dumps(obj, default=_default_serializer)) # pylint: disable=undefined-variable
class JsonFormatter(logging.Formatter):
"""
- Formatter for non-web application log
+ Format application log in JSON format
"""
def format(self, record):
- """ Format the log record into a JSON object """
- if hasattr(record, 'format'):
+ """ Format the known log records in JSON format """
+ if isinstance(record, SimpleLogRecord):
return _encode(record.format())
- return _encode(record.__dict__)
+ return super(JsonFormatter, self).format(record)
| SAP/cf-python-logging-support | 396ba738098024745205cbff22b2646a5337d1d1 | diff --git a/tests/unit/formatters/test_json_formatter.py b/tests/unit/formatters/test_json_formatter.py
new file mode 100644
index 0000000..70ffe60
--- /dev/null
+++ b/tests/unit/formatters/test_json_formatter.py
@@ -0,0 +1,24 @@
+""" Tests json log formatting """
+import json
+import logging
+from sap.cf_logging.record.simple_log_record import SimpleLogRecord
+from sap.cf_logging.formatters.json_formatter import JsonFormatter
+
+lvl, fn, lno, func, exc_info = logging.INFO, "(unknown file)", 0, "(unknown function)", None
+formatter = JsonFormatter()
+
+
+def test_unknown_records_format():
+ """ test unknown log records will be delegated to logging.Formatter """
+ log_record = logging.LogRecord('name', lvl, fn, lno, 'msg', [], exc_info)
+ assert formatter.format(log_record) == 'msg'
+
+
+def test_non_json_serializable():
+ """ test json formatter handles non JSON serializable object """
+ class MyClass(object): pass
+ extra = { 'cls': MyClass() }
+ log_record = SimpleLogRecord(extra, None, 'name', lvl, fn, lno, 'msg', [], exc_info)
+ record_object = json.loads(formatter.format(log_record))
+ assert record_object.get('cls') is not None
+ assert 'MyClass' in record_object.get('cls')
| Problem with object logging
Hello,
we run into trouble using this package in combination with the pika package (http://pika.readthedocs.io/en/0.10.0/). After initialization of the logger using cf_logging.init() the pika packages produces exceptions while trying to perform the following log operation:
LOGGER.info('Closing channel (%s): %r on %s',
reply_code, reply_text, self)
Here 'reply_code' is an int, 'reply_text' a string and 'self' is the channel object which has a working __repr__ method.
Best
Jan | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/unit/formatters/test_json_formatter.py::test_unknown_records_format",
"tests/unit/formatters/test_json_formatter.py::test_non_json_serializable"
] | [] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2018-04-12T14:25:16Z" | apache-2.0 |
|
SAP__python-pyodata-149 | diff --git a/pyodata/v2/model.py b/pyodata/v2/model.py
index 5412ca9..67cc1ad 100644
--- a/pyodata/v2/model.py
+++ b/pyodata/v2/model.py
@@ -21,6 +21,8 @@ from lxml import etree
from pyodata.exceptions import PyODataException, PyODataModelError, PyODataParserError
LOGGER_NAME = 'pyodata.model'
+FIX_SCREWED_UP_MINIMAL_DATETIME_VALUE = False
+FIX_SCREWED_UP_MAXIMUM_DATETIME_VALUE = False
IdentifierInfo = collections.namedtuple('IdentifierInfo', 'namespace name')
TypeInfo = collections.namedtuple('TypeInfo', 'namespace name is_collection')
@@ -414,8 +416,19 @@ class EdmDateTimeTypTraits(EdmPrefixedTypTraits):
try:
# https://stackoverflow.com/questions/36179914/timestamp-out-of-range-for-platform-localtime-gmtime-function
value = datetime.datetime(1970, 1, 1, tzinfo=current_timezone()) + datetime.timedelta(milliseconds=int(value))
- except ValueError:
- raise PyODataModelError(f'Cannot decode datetime from value {value}.')
+ except (ValueError, OverflowError):
+ if FIX_SCREWED_UP_MINIMAL_DATETIME_VALUE and int(value) < -62135596800000:
+ # Some service providers return false minimal date values.
+ # -62135596800000 is the lowest value PyOData could read.
+ # This workaroud fixes this issue and returns 0001-01-01 00:00:00+00:00 in such a case.
+ value = datetime.datetime(year=1, day=1, month=1, tzinfo=current_timezone())
+ elif FIX_SCREWED_UP_MAXIMUM_DATETIME_VALUE and int(value) > 253402300799999:
+ value = datetime.datetime(year=9999, day=31, month=12, tzinfo=current_timezone())
+ else:
+ raise PyODataModelError(f'Cannot decode datetime from value {value}. '
+ f'Possible value range: -62135596800000 to 253402300799999. '
+ f'You may fix this by setting `FIX_SCREWED_UP_MINIMAL_DATETIME_VALUE` '
+ f' or `FIX_SCREWED_UP_MAXIMUM_DATETIME_VALUE` as a workaround.')
return value
| SAP/python-pyodata | 9a3694d553c64e781923e11f6fbc28af67b01bc3 | diff --git a/tests/test_model_v2.py b/tests/test_model_v2.py
index ca72430..8f7ecef 100644
--- a/tests/test_model_v2.py
+++ b/tests/test_model_v2.py
@@ -9,6 +9,7 @@ from pyodata.v2.model import Schema, Typ, StructTypeProperty, Types, EntityType,
PolicyIgnore, Config, PolicyFatal, NullType, NullAssociation, current_timezone, StructType
from pyodata.exceptions import PyODataException, PyODataModelError, PyODataParserError
from tests.conftest import assert_logging_policy
+import pyodata.v2.model
def test_edmx(schema):
@@ -537,10 +538,20 @@ def test_traits_datetime():
assert testdate.microsecond == 0
assert testdate.tzinfo == current_timezone()
+ # parsing below lowest value with workaround
+ pyodata.v2.model.FIX_SCREWED_UP_MINIMAL_DATETIME_VALUE = True
+ testdate = typ.traits.from_json("/Date(-62135596800001)/")
+ assert testdate.year == 1
+ assert testdate.month == 1
+ assert testdate.day == 1
+ assert testdate.tzinfo == current_timezone()
+
# parsing the lowest value
- with pytest.raises(OverflowError):
+ pyodata.v2.model.FIX_SCREWED_UP_MINIMAL_DATETIME_VALUE = False
+ with pytest.raises(PyODataModelError) as e_info:
typ.traits.from_json("/Date(-62135596800001)/")
-
+ assert str(e_info.value).startswith('Cannot decode datetime from value -62135596800001.')
+
testdate = typ.traits.from_json("/Date(-62135596800000)/")
assert testdate.year == 1
assert testdate.month == 1
@@ -551,9 +562,19 @@ def test_traits_datetime():
assert testdate.microsecond == 0
assert testdate.tzinfo == current_timezone()
+ # parsing above highest value with workaround
+ pyodata.v2.model.FIX_SCREWED_UP_MAXIMUM_DATETIME_VALUE = True
+ testdate = typ.traits.from_json("/Date(253402300800000)/")
+ assert testdate.year == 9999
+ assert testdate.month == 12
+ assert testdate.day == 31
+ assert testdate.tzinfo == current_timezone()
+
# parsing the highest value
- with pytest.raises(OverflowError):
+ pyodata.v2.model.FIX_SCREWED_UP_MAXIMUM_DATETIME_VALUE = False
+ with pytest.raises(PyODataModelError) as e_info:
typ.traits.from_json("/Date(253402300800000)/")
+ assert str(e_info.value).startswith('Cannot decode datetime from value 253402300800000.')
testdate = typ.traits.from_json("/Date(253402300799999)/")
assert testdate.year == 9999
| Date out of range error
According to #80 we facing the same error. We're just consumer using the api to receive data for our DWH. Currently one of our job fails because of this error.
Is it possible to implement a fix for this problem on pyodata side?
Json:
```
{
"d": {
"results": {
"__metadata": {
"uri": "https://service.url/sap/c4c/odata/v1/c4codataapi/CorporateAccountIdentificationCollection('12345678910111213ABCDEFGHIJKLMNO')",
"type": "c4codata.CorporateAccountIdentification",
"etag": "W/"datetimeoffset'2021-02-01T19%3A41%3A17.9430080Z'""
},
"ObjectID": "12345678910111213ABCDEFGHIJKLMNO",
"ParentObjectID": "166345678910111213ABCDEFGHIJKLMNO",
"ETag": "/Date(1612208477943)/",
"AccountID": "12345",
"IDTypeCode": "ABCDE",
"IDTypeCodeText": "<ABCD12>",
"IDNumber": "1234-123",
"ResponsibleInstitution": "",
"EntryDate": null,
"ValidFrom": "/Date(-62135769600000)/",
"ValidTo": "/Date(253402214400000)/",
"CountryCode": "",
"CountryCodeText": "",
"StateCode": "",
"StateCodeText": "",
"ZZWECK_KUT": "",
"ZZWECK_KUTText": "",
"CorporateAccount": {
"__deferred": {
"uri": "https://service.url/sap/c4c/odata/v1/c4codataapi/CorporateAccountIdentificationCollection('12345678910111213ABCDEFGHIJKLMNO')/CorporateAccount"
}
}
}
}
}
```
Thanks & BR
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_model_v2.py::test_traits_datetime"
] | [
"tests/test_model_v2.py::test_edmx",
"tests/test_model_v2.py::test_schema_entity_type_nullable",
"tests/test_model_v2.py::test_schema_entity_sets",
"tests/test_model_v2.py::test_edmx_associations",
"tests/test_model_v2.py::test_edmx_navigation_properties",
"tests/test_model_v2.py::test_edmx_function_imports",
"tests/test_model_v2.py::test_edmx_complex_types",
"tests/test_model_v2.py::test_edmx_complex_type_prop_vh",
"tests/test_model_v2.py::test_traits",
"tests/test_model_v2.py::test_traits_collections",
"tests/test_model_v2.py::test_type_parsing",
"tests/test_model_v2.py::test_types",
"tests/test_model_v2.py::test_complex_serializer",
"tests/test_model_v2.py::test_annot_v_l_missing_e_s",
"tests/test_model_v2.py::test_annot_v_l_missing_e_t",
"tests/test_model_v2.py::test_annot_v_l_trgt_inv_prop",
"tests/test_model_v2.py::test_namespace_with_periods",
"tests/test_model_v2.py::test_edmx_entity_sets",
"tests/test_model_v2.py::test_config_set_default_error_policy",
"tests/test_model_v2.py::test_null_type",
"tests/test_model_v2.py::test_faulty_association",
"tests/test_model_v2.py::test_faulty_association_set",
"tests/test_model_v2.py::test_missing_association_for_navigation_property",
"tests/test_model_v2.py::test_edmx_association_end_by_role",
"tests/test_model_v2.py::test_edmx_association_set_end_by_role",
"tests/test_model_v2.py::test_edmx_association_set_end_by_entity_set",
"tests/test_model_v2.py::test_missing_data_service",
"tests/test_model_v2.py::test_missing_schema",
"tests/test_model_v2.py::test_namespace_whitelist",
"tests/test_model_v2.py::test_unsupported_edmx_n",
"tests/test_model_v2.py::test_unsupported_schema_n",
"tests/test_model_v2.py::test_whitelisted_edm_namespace",
"tests/test_model_v2.py::test_whitelisted_edm_namespace_2006_04",
"tests/test_model_v2.py::test_whitelisted_edm_namespace_2007_05",
"tests/test_model_v2.py::test_enum_parsing",
"tests/test_model_v2.py::test_unsupported_enum_underlying_type",
"tests/test_model_v2.py::test_enum_value_out_of_range",
"tests/test_model_v2.py::test_missing_property_referenced_in_annotation",
"tests/test_model_v2.py::test_struct_type_has_property_initial_instance",
"tests/test_model_v2.py::test_struct_type_has_property_no",
"tests/test_model_v2.py::test_struct_type_has_property_yes"
] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_issue_reference"
],
"has_test_patch": true,
"is_lite": false
} | "2021-03-19T13:12:21Z" | apache-2.0 |
|
SAP__python-pyodata-232 | diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0f876b9..7175a5d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,8 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
## [Unreleased]
+- model: fix edge case for Edm.DateTimeOffset.from_json() without offset - Petr Hanak
+
## [1.10.0]
### Added
diff --git a/pyodata/v2/model.py b/pyodata/v2/model.py
index 065f93e..4f15c84 100644
--- a/pyodata/v2/model.py
+++ b/pyodata/v2/model.py
@@ -529,6 +529,12 @@ class EdmDateTimeOffsetTypTraits(EdmPrefixedTypTraits):
return f'/Date({ticks}{offset_in_minutes:+05})/'
def from_json(self, value):
+ # special edge case:
+ # datetimeoffset'yyyy-mm-ddThh:mm[:ss]' = defaults to UTC, when offset value is not provided in responde data by service but the metadata is EdmDateTimeOffset
+ # intentionally just for from_json, generation of to_json should always provide timezone info
+ if re.match(r"^/Date\((?P<milliseconds_since_epoch>-?\d+)\)/$", value):
+ value = value.replace(')', '+0000)')
+
matches = re.match(r"^/Date\((?P<milliseconds_since_epoch>-?\d+)(?P<offset_in_minutes>[+-]\d+)\)/$", value)
try:
milliseconds_since_epoch = matches.group('milliseconds_since_epoch')
| SAP/python-pyodata | 5d1490871f4b824a82dd6eaa148444a99ea4f47d | diff --git a/tests/test_model_v2.py b/tests/test_model_v2.py
index 5bdef48..258dde7 100644
--- a/tests/test_model_v2.py
+++ b/tests/test_model_v2.py
@@ -690,6 +690,9 @@ def test_traits_datetimeoffset(type_date_time_offset):
def test_traits_datetimeoffset_to_literal(type_date_time_offset):
"""Test Edm.DateTimeOffset trait: Python -> literal"""
+ testdate = datetime(1, 1, 1, 0, 0, 0, 0, tzinfo=timezone.utc)
+ assert type_date_time_offset.traits.to_literal(testdate) == "datetimeoffset'0001-01-01T00:00:00+00:00'"
+
testdate = datetime(2005, 1, 28, 18, 30, 44, 123456, tzinfo=timezone(timedelta(hours=3, minutes=40)))
assert type_date_time_offset.traits.to_literal(testdate) == "datetimeoffset'2005-01-28T18:30:44.123456+03:40'"
@@ -746,7 +749,7 @@ def test_traits_datetimeoffset_from_invalid_literal(type_date_time_offset):
assert str(e_info.value).startswith('Cannot decode datetimeoffset from value xyz')
-def test_traits_datetimeoffset_from_odata(type_date_time_offset):
+def test_traits_datetimeoffset_from_json(type_date_time_offset):
"""Test Edm.DateTimeOffset trait: OData -> Python"""
# parsing full representation
@@ -768,6 +771,14 @@ def test_traits_datetimeoffset_from_odata(type_date_time_offset):
assert testdate.microsecond == 0
assert testdate.tzinfo == timezone(-timedelta(minutes=5))
+ # parsing special edge case with no offset provided, defaults to UTC
+ testdate = type_date_time_offset.traits.from_json("/Date(217567986000)/")
+ assert testdate.year == 1976
+ assert testdate.minute == 33
+ assert testdate.second == 6
+ assert testdate.microsecond == 0
+ assert testdate.tzinfo == timezone.utc
+
# parsing below lowest value with workaround
pyodata.v2.model.FIX_SCREWED_UP_MINIMAL_DATETIME_VALUE = True
testdate = type_date_time_offset.traits.from_json("/Date(-62135596800001+0001)/")
| Malformed value for primitive Edm.DateTimeOffset type
We are using pyodata v1.7.1 the whole time and I'm tried to update to the latest v1.10.0 version. But now I get this error when querying data from the odata service:
```
Traceback (most recent call last):
File "/workspace/tmp/venv/odatavenv/lib/python3.10/site-packages/pyodata/v2/model.py", line 534, in from_json
milliseconds_since_epoch = matches.group('milliseconds_since_epoch')
AttributeError: 'NoneType' object has no attribute 'group'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/workspace/tmp/venv/odatavenv/lib/python3.10/site-packages/prefect/engine.py", line 1192, in orchestrate_task_run
result = await run_sync(task.fn, *args, **kwargs)
File "/workspace/tmp/venv/odatavenv/lib/python3.10/site-packages/prefect/utilities/asyncutils.py", line 57, in run_sync_in_worker_thread
return await anyio.to_thread.run_sync(call, cancellable=True)
File "/workspace/tmp/venv/odatavenv/lib/python3.10/site-packages/anyio/to_thread.py", line 31, in run_sync
return await get_asynclib().run_sync_in_worker_thread(
File "/workspace/tmp/venv/odatavenv/lib/python3.10/site-packages/anyio/_backends/_asyncio.py", line 937, in run_sync_in_worker_thread
return await future
File "/workspace/tmp/venv/odatavenv/lib/python3.10/site-packages/anyio/_backends/_asyncio.py", line 867, in run
result = context.run(func, *args)
File "/workspace/odatavenv/flow_utilities/prefect/tasks/odata.py", line 60, in fetch_odata
for cnt, batch in enumerate(batches, start=1):
File "/workspace/odatavenv/flow_utilities/api/odata.py", line 114, in query_all
yield list(self.query(skip, top))
File "/workspace/odatavenv/flow_utilities/api/odata.py", line 98, in query
response = self._entity_service().skip(skip).top(top).execute()
File "/workspace/tmp/venv/odatavenv/lib/python3.10/site-packages/pyodata/v2/service.py", line 349, in execute
return self._call_handler(response)
File "/workspace/tmp/venv/odatavenv/lib/python3.10/site-packages/pyodata/v2/service.py", line 362, in _call_handler
return self._handler(response)
File "/workspace/tmp/venv/odatavenv/lib/python3.10/site-packages/pyodata/v2/service.py", line 1509, in get_entities_handler
entity = EntityProxy(self._service, self._entity_set, self._entity_set.entity_type, props)
File "/workspace/tmp/venv/odatavenv/lib/python3.10/site-packages/pyodata/v2/service.py", line 814, in __init__
self._cache[type_proprty.name] = type_proprty.from_json(proprties[type_proprty.name])
File "/workspace/tmp/venv/odatavenv/lib/python3.10/site-packages/pyodata/v2/model.py", line 872, in from_json
return self.typ.traits.from_json(value)
File "/workspace/tmp/venv/odatavenv/lib/python3.10/site-packages/pyodata/v2/model.py", line 537, in from_json
raise PyODataModelError(
pyodata.exceptions.PyODataModelError: Malformed value /Date(1599659339088)/ for primitive Edm.DateTimeOffset type. Expected format is /Date(<ticks>Β±<offset>)/
```
Maybe this is related to our instance because they are uncompatible dates (see https://github.com/SAP/python-pyodata/issues/143). | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_model_v2.py::test_traits_datetimeoffset_from_json"
] | [
"tests/test_model_v2.py::test_edmx",
"tests/test_model_v2.py::test_schema_entity_type_nullable",
"tests/test_model_v2.py::test_schema_entity_type_fixed_length[Name-False-Name",
"tests/test_model_v2.py::test_schema_entity_type_fixed_length[ID-True-Customer",
"tests/test_model_v2.py::test_schema_entity_type_fixed_length[City-False-City",
"tests/test_model_v2.py::test_schema_entity_sets",
"tests/test_model_v2.py::test_edmx_associations",
"tests/test_model_v2.py::test_edmx_navigation_properties",
"tests/test_model_v2.py::test_edmx_function_imports",
"tests/test_model_v2.py::test_edmx_complex_types",
"tests/test_model_v2.py::test_edmx_complex_type_prop_vh",
"tests/test_model_v2.py::test_traits",
"tests/test_model_v2.py::test_parse_datetime_literal[2001-02-03T04:05:06.000007-expected0]",
"tests/test_model_v2.py::test_parse_datetime_literal[2001-02-03T04:05:06-expected1]",
"tests/test_model_v2.py::test_parse_datetime_literal[2001-02-03T04:05-expected2]",
"tests/test_model_v2.py::test_parse_datetime_literal_faulty[2001-02-03T04:05:61]",
"tests/test_model_v2.py::test_parse_datetime_literal_faulty[2001-02-03T04:61]",
"tests/test_model_v2.py::test_parse_datetime_literal_faulty[2001-02-03T24:05]",
"tests/test_model_v2.py::test_parse_datetime_literal_faulty[2001-02-32T04:05]",
"tests/test_model_v2.py::test_parse_datetime_literal_faulty[2001-13-03T04:05]",
"tests/test_model_v2.py::test_parse_datetime_literal_faulty[2001-00-03T04:05]",
"tests/test_model_v2.py::test_parse_datetime_literal_faulty[01-02-03T04:05]",
"tests/test_model_v2.py::test_parse_datetime_literal_faulty[2001-02-03T04:05.AAA]",
"tests/test_model_v2.py::test_parse_datetime_literal_faulty[]",
"tests/test_model_v2.py::test_traits_datetime",
"tests/test_model_v2.py::test_traits_datetime_with_offset_from_json",
"tests/test_model_v2.py::test_traits_datetime_with_offset_to_json[python_datetime0-/Date(217567986123)/-With",
"tests/test_model_v2.py::test_traits_datetime_with_offset_to_json[python_datetime1-/Date(217567986000)/-No",
"tests/test_model_v2.py::test_traits_datetimeoffset",
"tests/test_model_v2.py::test_traits_datetimeoffset_to_literal",
"tests/test_model_v2.py::test_traits_invalid_datetimeoffset_to_literal",
"tests/test_model_v2.py::test_traits_datetimeoffset_to_json[python_datetime0-/Date(217567986123+0000)/-UTC]",
"tests/test_model_v2.py::test_traits_datetimeoffset_to_json[python_datetime1-/Date(217567986000+0840)/-+14",
"tests/test_model_v2.py::test_traits_datetimeoffset_to_json[python_datetime2-/Date(217567986000-0720)/--12",
"tests/test_model_v2.py::test_traits_datetimeoffset_from_literal[datetimeoffset'1976-11-23T03:33:06.654321+12:11'-expected0-Full",
"tests/test_model_v2.py::test_traits_datetimeoffset_from_literal[datetimeoffset'1976-11-23T03:33:06+12:11'-expected1-No",
"tests/test_model_v2.py::test_traits_datetimeoffset_from_literal[datetimeoffset'1976-11-23T03:33:06-01:00'-expected2-Negative",
"tests/test_model_v2.py::test_traits_datetimeoffset_from_literal[datetimeoffset'1976-11-23t03:33:06-01:00'-expected3-lowercase",
"tests/test_model_v2.py::test_traits_datetimeoffset_from_literal[datetimeoffset'1976-11-23T03:33:06+00:00'-expected4-+00:00",
"tests/test_model_v2.py::test_traits_datetimeoffset_from_literal[datetimeoffset'1976-11-23T03:33:06-00:00'-expected5--00:00",
"tests/test_model_v2.py::test_traits_datetimeoffset_from_literal[datetimeoffset'1976-11-23t03:33:06Z'-expected6-Z",
"tests/test_model_v2.py::test_traits_datetimeoffset_from_literal[datetimeoffset'1976-11-23t03:33:06+12:00'-expected7-On",
"tests/test_model_v2.py::test_traits_datetimeoffset_from_literal[datetimeoffset'1976-11-23t03:33:06-12:00'-expected8-Minimum",
"tests/test_model_v2.py::test_traits_datetimeoffset_from_literal[datetimeoffset'1976-11-23t03:33:06+14:00'-expected9-Maximum",
"tests/test_model_v2.py::test_traits_datetimeoffset_from_invalid_literal",
"tests/test_model_v2.py::test_traits_collections",
"tests/test_model_v2.py::test_type_parsing",
"tests/test_model_v2.py::test_types",
"tests/test_model_v2.py::test_complex_serializer",
"tests/test_model_v2.py::test_annot_v_l_missing_e_s",
"tests/test_model_v2.py::test_annot_v_l_missing_e_t",
"tests/test_model_v2.py::test_annot_v_l_trgt_inv_prop",
"tests/test_model_v2.py::test_namespace_with_periods",
"tests/test_model_v2.py::test_edmx_entity_sets",
"tests/test_model_v2.py::test_config_set_default_error_policy",
"tests/test_model_v2.py::test_null_type",
"tests/test_model_v2.py::test_faulty_association",
"tests/test_model_v2.py::test_faulty_association_set",
"tests/test_model_v2.py::test_missing_association_for_navigation_property",
"tests/test_model_v2.py::test_edmx_association_end_by_role",
"tests/test_model_v2.py::test_edmx_association_set_end_by_role",
"tests/test_model_v2.py::test_edmx_association_set_end_by_entity_set",
"tests/test_model_v2.py::test_missing_data_service",
"tests/test_model_v2.py::test_missing_schema",
"tests/test_model_v2.py::test_namespace_whitelist",
"tests/test_model_v2.py::test_unsupported_edmx_n",
"tests/test_model_v2.py::test_unsupported_schema_n",
"tests/test_model_v2.py::test_whitelisted_edm_namespace",
"tests/test_model_v2.py::test_whitelisted_edm_namespace_2006_04",
"tests/test_model_v2.py::test_whitelisted_edm_namespace_2007_05",
"tests/test_model_v2.py::test_enum_parsing",
"tests/test_model_v2.py::test_unsupported_enum_underlying_type",
"tests/test_model_v2.py::test_enum_value_out_of_range",
"tests/test_model_v2.py::test_missing_property_referenced_in_annotation",
"tests/test_model_v2.py::test_struct_type_has_property_initial_instance",
"tests/test_model_v2.py::test_struct_type_has_property_no",
"tests/test_model_v2.py::test_struct_type_has_property_yes",
"tests/test_model_v2.py::test_invalid_xml"
] | {
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2022-09-23T14:08:18Z" | apache-2.0 |
|
SNEWS2__snewpy-105 | diff --git a/python/snewpy/flavor_transformation.py b/python/snewpy/flavor_transformation.py
index bab1190..d30959c 100644
--- a/python/snewpy/flavor_transformation.py
+++ b/python/snewpy/flavor_transformation.py
@@ -1144,23 +1144,14 @@ class NeutrinoDecay(FlavorTransformation):
prob : float or ndarray
Transition probability.
"""
- pe_array = []
-
# NMO case.
if self.mass_order == MassHierarchy.NORMAL:
- for energy in E:
- pe_array.append(
- self.De1*(1-np.exp(-self.gamma(energy)*self.d)) +
- self.De3*np.exp(-self.gamma(energy)*self.d))
- pe_array = np.array(pe_array)
+ pe_array = self.De1*(1-np.exp(-self.gamma(E)*self.d)) + \
+ self.De3*np.exp(-self.gamma(E)*self.d)
# IMO case.
else:
- for energy in E:
- pe_array.append(
- self.De2*np.exp(-self.gamma(energy)*self.d) +
- self.De3*(1-np.exp(-self.gamma(energy)*self.d)))
- pe_array = np.array(pe_array)
-
+ pe_array = self.De2*np.exp(-self.gamma(E)*self.d) + \
+ self.De3*(1-np.exp(-self.gamma(E)*self.d))
return pe_array
def prob_ex(self, t, E):
@@ -1251,23 +1242,14 @@ class NeutrinoDecay(FlavorTransformation):
prob : float or ndarray
Transition probability.
"""
- pxbar_array = []
-
# NMO case.
if self.mass_order == MassHierarchy.NORMAL:
- for energy in E:
- pxbar_array.append(
- self.De1*(1-np.exp(-self.gamma(energy)*self.d)) +
- self.De2 + self.De3*np.exp(-self.gamma(energy)*self.d))
- pxbar_array = np.array(pxbar_array)
+ pxbar_array = self.De1*(1-np.exp(-self.gamma(E)*self.d)) + \
+ self.De2 + self.De3*np.exp(-self.gamma(E)*self.d)
# IMO case.
else:
- for energy in E:
- pxbar_array.append(
- self.De1 + self.De2*np.exp(-self.gamma(energy)*self.d) +
- self.De3*(1-np.exp(-self.gamma(energy)*self.d)))
- pxbar_array = np.array(pxbar_array)
-
+ pxbar_array = self.De1 + self.De2*np.exp(-self.gamma(E)*self.d) + \
+ self.De3*(1-np.exp(-self.gamma(E)*self.d))
return pxbar_array
def prob_xxbar(self, t, E):
diff --git a/python/snewpy/models.py b/python/snewpy/models.py
index e807386..4778d0a 100644
--- a/python/snewpy/models.py
+++ b/python/snewpy/models.py
@@ -1018,7 +1018,7 @@ class Warren_2020(SupernovaModel):
# Set model metadata.
self.filename = os.path.basename(filename)
self.EOS = eos
- self.progenitor_mass = float(filename.split('_')[-1].strip('m%.h5')) * u.Msun
+ self.progenitor_mass = float(filename.split('_')[-1][1:-3]) * u.Msun
self.turbmixing_param = float(filename.split('_')[-2].strip('a%'))
# Get grid of model times.
@@ -1251,7 +1251,12 @@ class Fornax_2019(SupernovaModel):
# Set up model metadata.
self.filename = filename
- self.progenitor_mass = float(filename.split('_')[-1][:-4]) * u.Msun
+ mass_str = filename.split('_')[-1]
+ if 'M' in mass_str:
+ self.progenitor_mass = float(mass_str[:-4]) * u.Msun
+ else:
+ mass_str = filename.split('_')[-2]
+ self.progenitor_mass = float(mass_str[:-1]) * u.Msun
self.fluxunit = 1e50 * u.erg/(u.s*u.MeV)
self.time = None
@@ -1637,7 +1642,7 @@ class Fornax_2021(SupernovaModel):
Absolute or relative path to FITS file with model data.
"""
# Set up model metadata.
- self.progenitor_mass = float(filename.split('_')[-3][:-1]) * u.Msun
+ self.progenitor_mass = float(filename.split('/')[-1].split('_')[2][:-1]) * u.Msun
# Conversion of flavor to key name in the model HDF5 file.
self._flavorkeys = { Flavor.NU_E : 'nu0',
| SNEWS2/snewpy | ab058b712a0995fe71f00ce6c49c294ec5f81062 | diff --git a/python/snewpy/test/test_models.py b/python/snewpy/test/test_models.py
index 4dc7990..bca7655 100644
--- a/python/snewpy/test/test_models.py
+++ b/python/snewpy/test/test_models.py
@@ -5,7 +5,10 @@ import unittest
from snewpy.neutrino import Flavor
from snewpy.flavor_transformation import NoTransformation
-from snewpy.models import Nakazato_2013
+from snewpy.models import Nakazato_2013, Tamborra_2014, OConnor_2015, \
+ Sukhbold_2015, Bollig_2016, Walk_2018, \
+ Walk_2019, Fornax_2019, Warren_2020, \
+ Kuroda_2020, Fornax_2021, Zha_2021
from astropy import units as u
@@ -13,23 +16,286 @@ import numpy as np
class TestModels(unittest.TestCase):
- def test_Nakazato_vanilla(self):
+ def test_Nakazato_2013(self):
"""
- Instantiate a 'Nakazato 2013' model
+ Instantiate a set of 'Nakazato 2013' models
"""
- xform = NoTransformation()
- mfile = 'models/Nakazato_2013/nakazato-shen-z0.004-t_rev100ms-s13.0.fits'
- model = Nakazato_2013(mfile)
+ for z in [0.004, 0.02]:
+ for trev in [100, 200, 300]:
+ for mass in [13., 20., 50.]:
+ mfile = 'models/Nakazato_2013/nakazato-shen-z{}-t_rev{}ms-s{:.1f}.fits'.format(z, trev, mass)
+ model = Nakazato_2013(mfile)
- self.assertEqual(model.EOS, 'SHEN')
- self.assertEqual(model.progenitor_mass, 13.*u.Msun)
- self.assertEqual(model.revival_time, 100.*u.ms)
+ self.assertEqual(model.EOS, 'SHEN')
+ self.assertEqual(model.progenitor_mass, mass*u.Msun)
+ self.assertEqual(model.revival_time, trev*u.ms)
+ self.assertEqual(model.metallicity, z)
- self.assertEqual(model.time[0], -50*u.ms)
+ # Check that times are in proper units.
+ t = model.get_time()
+ self.assertTrue(t.unit, u.s)
+ self.assertEqual(model.time[0], -50*u.ms)
-# tunit = model.time.unit
-# Eunit = model.meanE[Flavor.NU_E].unit
-#
-# t = -50*u.ms
-# self.assertTrue(np.interp(t.to(tunit), model.time, model.meanE[Flavor.NU_E])*Eunit == 6.79147181061522*u.MeV)
+ # Check that we can compute flux dictionaries.
+ f = model.get_initial_spectra(0*u.s, 10*u.MeV)
+ self.assertEqual(type(f), dict)
+ self.assertEqual(len(f), len(Flavor))
+ self.assertEqual(f[Flavor.NU_E].unit, 1/(u.erg * u.s))
+
+ def test_Tamborra_2014(self):
+ """
+ Instantiate a set of 'Tamborra 2014' models
+ """
+ for mass in [20., 27.]:
+ mfile = 'models/Tamborra_2014/s{:.1f}c_3D_dir1'.format(mass)
+ model = Tamborra_2014(mfile, eos='LS220')
+
+ self.assertEqual(model.EOS, 'LS220')
+ self.assertEqual(model.progenitor_mass, mass*u.Msun)
+
+ # Check that times are in proper units.
+ t = model.get_time()
+ self.assertTrue(t.unit, u.s)
+
+ # Check that we can compute flux dictionaries.
+ f = model.get_initial_spectra(0*u.s, 10*u.MeV)
+ self.assertEqual(type(f), dict)
+ self.assertEqual(len(f), len(Flavor))
+ self.assertEqual(f[Flavor.NU_E].unit, 1/(u.erg * u.s))
+
+ def test_OConnor_2015(self):
+ """
+ Instantiate a set of "O'Connor 2015" models
+ """
+ mfile = 'models/OConnor_2015/M1_neutrinos.dat'
+ model = OConnor_2015(mfile, eos='LS220')
+
+ self.assertEqual(model.EOS, 'LS220')
+ self.assertEqual(model.progenitor_mass, 40*u.Msun)
+
+ # Check that times are in proper units.
+ t = model.get_time()
+ self.assertTrue(t.unit, u.s)
+
+ # Check that we can compute flux dictionaries.
+ f = model.get_initial_spectra(0*u.s, 10*u.MeV)
+ self.assertEqual(type(f), dict)
+ self.assertEqual(len(f), len(Flavor))
+ self.assertEqual(f[Flavor.NU_E].unit, 1/(u.erg * u.s))
+
+ def test_Sukhbold_2015(self):
+ """
+ Instantiate a set of 'Sukhbold 2015' models
+ """
+ for mass in ['z9.6', 's27.0']:
+ for eos in ['LS220', 'SFHo']:
+ mfile = 'models/Sukhbold_2015/sukhbold-{}-{}.fits'.format(eos, mass)
+ massval = float(mass[1:]) * u.Msun
+ model = Sukhbold_2015(mfile)
+
+ self.assertEqual(model.EOS, eos)
+ self.assertEqual(model.progenitor_mass, massval)
+
+ # Check that times are in proper units.
+ t = model.get_time()
+ self.assertTrue(t.unit, u.s)
+
+ # Check that we can compute flux dictionaries.
+ f = model.get_initial_spectra(0*u.s, 10*u.MeV)
+ self.assertEqual(type(f), dict)
+ self.assertEqual(len(f), len(Flavor))
+ self.assertEqual(f[Flavor.NU_E].unit, 1/(u.erg * u.s))
+
+ def test_Bollig_2016(self):
+ """
+ Instantiate a set of 'Bollig 2016' models
+ """
+ for mass in [11.2, 27.]:
+ mfile = 'models/Bollig_2016/s{:.1f}c'.format(mass)
+ model = Bollig_2016(mfile, eos='LS220')
+
+ self.assertEqual(model.EOS, 'LS220')
+ self.assertEqual(model.progenitor_mass, mass*u.Msun)
+
+ # Check that times are in proper units.
+ t = model.get_time()
+ self.assertTrue(t.unit, u.s)
+
+ # Check that we can compute flux dictionaries.
+ f = model.get_initial_spectra(0*u.s, 10*u.MeV)
+ self.assertEqual(type(f), dict)
+ self.assertEqual(len(f), len(Flavor))
+ self.assertEqual(f[Flavor.NU_E].unit, 1/(u.erg * u.s))
+
+ def test_Walk_2018(self):
+ """
+ Instantiate a set of 'Walk 2018' models
+ """
+ mass = 15.
+ mfile = 'models/Walk_2018/s{:.1f}c_3D_nonrot_dir1'.format(mass)
+ model = Walk_2018(mfile, eos='LS220')
+
+ self.assertEqual(model.EOS, 'LS220')
+ self.assertEqual(model.progenitor_mass, mass*u.Msun)
+
+ # Check that times are in proper units.
+ t = model.get_time()
+ self.assertTrue(t.unit, u.s)
+
+ # Check that we can compute flux dictionaries.
+ f = model.get_initial_spectra(0*u.s, 10*u.MeV)
+ self.assertEqual(type(f), dict)
+ self.assertEqual(len(f), len(Flavor))
+ self.assertEqual(f[Flavor.NU_E].unit, 1/(u.erg * u.s))
+
+ def test_Walk_2019(self):
+ """
+ Instantiate a set of 'Walk 2019' models
+ """
+ mass = 40.
+ mfile = 'models/Walk_2019/s{:.1f}c_3DBH_dir1'.format(mass)
+ model = Walk_2019(mfile, eos='LS220')
+
+ self.assertEqual(model.EOS, 'LS220')
+ self.assertEqual(model.progenitor_mass, mass*u.Msun)
+
+ # Check that times are in proper units.
+ t = model.get_time()
+ self.assertTrue(t.unit, u.s)
+
+ # Check that we can compute flux dictionaries.
+ f = model.get_initial_spectra(0*u.s, 10*u.MeV)
+ self.assertEqual(type(f), dict)
+ self.assertEqual(len(f), len(Flavor))
+ self.assertEqual(f[Flavor.NU_E].unit, 1/(u.erg * u.s))
+
+ def test_Fornax_2019(self):
+ """
+ Instantiate a set of 'Fornax 2019' models
+ """
+ for mass in [9, 10, 12, 13, 14, 15, 19, 25, 60]:
+ mfile = 'models/Fornax_2019/lum_spec_{}M.h5'.format(mass)
+ model = Fornax_2019(mfile)
+
+ self.assertEqual(model.progenitor_mass, mass*u.Msun)
+
+ # Check that times are in proper units.
+ t = model.get_time()
+ self.assertTrue(t.unit, u.s)
+
+ # Check that we can compute flux dictionaries.
+ f = model.get_initial_spectra(0*u.s, 10*u.MeV, theta=23*u.degree, phi=22*u.degree)
+ self.assertEqual(type(f), dict)
+ self.assertEqual(len(f), len(Flavor))
+ self.assertEqual(f[Flavor.NU_E].unit, u.erg/(u.MeV * u.s))
+
+ def test_Warren_2020(self):
+ """
+ Instantiate a set of 'Warren 2020' models
+ """
+ masses = [
+ '10.0', '10.25', '10.5', '10.75', '100', '11.0', '11.25', '11.5', '11.75',
+ '12.0', '12.25', '12.5', '12.75', '120', '13.0', '13.1', '13.2', '13.3',
+ '13.4', '13.5', '13.6', '13.7', '13.8', '13.9', '14.0', '14.1', '14.2',
+ '14.3', '14.4', '14.5', '14.6', '14.7', '14.8', '14.9', '15.0', '15.1',
+ '15.2', '15.3', '15.4', '15.5', '15.6', '15.7', '15.8', '15.9', '16.0',
+ '16.1', '16.2', '16.3', '16.4', '16.5', '16.6', '16.7', '16.8', '16.9',
+ '17.0', '17.1', '17.2', '17.3', '17.4', '17.5', '17.6', '17.7', '17.8',
+ '17.9', '18.0', '18.1', '18.2', '18.3', '18.4', '18.5', '18.6', '18.7',
+ '18.8', '18.9', '19.0', '19.1', '19.2', '19.3', '19.4', '19.5', '19.6',
+ '19.7', '19.8', '19.9', '20.0', '20.1', '20.2', '20.3', '20.4', '20.5',
+ '20.6', '20.7', '20.8', '20.9', '21.0', '21.1', '21.2', '21.3', '21.4',
+ '21.5', '21.6', '21.7', '21.8', '21.9', '22.0', '22.1', '22.2', '22.3',
+ '22.4', '22.5', '22.6', '22.7', '22.8', '22.9', '23.0', '23.1', '23.2',
+ '23.3', '23.4', '23.5', '23.6', '23.7', '23.8', '23.9', '24.0', '24.1',
+ '24.2', '24.3', '24.4', '24.5', '24.6', '24.7', '24.8', '24.9', '25.0',
+ '25.1', '25.2', '25.3', '25.4', '25.5', '25.6', '25.7', '25.8', '25.9',
+ '26.0', '26.1', '26.2', '26.3', '26.4', '26.5', '26.6', '26.7', '26.8',
+ '26.9', '27.0', '27.1', '27.2', '27.3', '27.4', '27.5', '27.6', '27.7',
+ '27.8', '27.9', '28.0', '28.1', '28.2', '28.3', '28.4', '28.5', '28.6',
+ '28.7', '28.8', '28.9', '29.0', '29.1', '29.2', '29.3', '29.4', '29.5',
+ '29.6', '29.7', '29.8', '29.9', '30.0', '31', '32', '33', '35', '40', '45',
+ '50', '55', '60', '70', '80', '9.0', '9.25', '9.5', '9.75']
+
+ for mixing in [1.23, 1.25, 1.27]:
+ for mass in masses:
+ mfile = 'models/Warren_2020/stir_a{}/stir_multimessenger_a{}_m{}.h5'.format(mixing, mixing, mass)
+
+ model = Warren_2020(mfile)
+
+ self.assertEqual(model.progenitor_mass, float(mass)*u.Msun)
+ self.assertEqual(model.turbmixing_param, mixing)
+ self.assertEqual(model.EOS, 'LS220')
+
+ # Check that times are in proper units.
+ t = model.get_time()
+ self.assertTrue(t.unit, u.s)
+
+ # Check that we can compute flux dictionaries.
+ f = model.get_initial_spectra(0*u.s, 10*u.MeV)
+ self.assertEqual(type(f), dict)
+ self.assertEqual(len(f), len(Flavor))
+ self.assertEqual(f[Flavor.NU_E].unit, 1./(u.erg * u.s))
+
+ def test_Kuroda_2020(self):
+ """
+ Instantiate a set of 'Kuroda 2020' models
+ """
+ for field in ['R00B00', 'R10B12', 'R10B13']:
+ mfile = 'models/Kuroda_2020/Lnu{}.dat'.format(field)
+ model = Kuroda_2020(mfile)
+
+ self.assertEqual(model.EOS, 'LS220')
+ self.assertEqual(model.progenitor_mass, 20*u.Msun)
+
+ # Check that times are in proper units.
+ t = model.get_time()
+ self.assertTrue(t.unit, u.s)
+
+ # Check that we can compute flux dictionaries.
+ f = model.get_initial_spectra(0*u.s, 10*u.MeV)
+ self.assertEqual(type(f), dict)
+ self.assertEqual(len(f), len(Flavor))
+ self.assertEqual(f[Flavor.NU_E].unit, 1/(u.erg * u.s))
+
+ def test_Fornax_2021(self):
+ """
+ Instantiate a set of 'Fornax 2021' models
+ """
+ for mass in ['12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '25', '26', '26.99']:
+ mfile = 'models/Fornax_2021/lum_spec_{}M_r10000_dat.h5'.format(mass)
+ model = Fornax_2021(mfile)
+
+ self.assertEqual(model.progenitor_mass, float(mass)*u.Msun)
+
+ # Check that times are in proper units.
+ t = model.get_time()
+ self.assertTrue(t.unit, u.s)
+
+ # Check that we can compute flux dictionaries.
+ f = model.get_initial_spectra(0*u.s, 10*u.MeV)
+ self.assertEqual(type(f), dict)
+ self.assertEqual(len(f), len(Flavor))
+ self.assertEqual(f[Flavor.NU_E].unit, u.erg/(u.MeV * u.s))
+
+ def test_Zha_2021(self):
+ """
+ Instantiate a set of 'Zha 2021' models
+ """
+ for mass in ['16', '17', '18', '19', '19.89', '20', '21', '22.39', '23', '24', '25', '26', '30', '33']:
+ mfile = 'models/Zha_2021/s{}.dat'.format(mass)
+ model = Zha_2021(mfile)
+
+ self.assertEqual(model.progenitor_mass, float(mass)*u.Msun)
+ self.assertEqual(model.EOS, 'STOS_B145')
+
+ # Check that times are in proper units.
+ t = model.get_time()
+ self.assertTrue(t.unit, u.s)
+
+ # Check that we can compute flux dictionaries.
+ f = model.get_initial_spectra(0*u.s, 10*u.MeV)
+ self.assertEqual(type(f), dict)
+ self.assertEqual(len(f), len(Flavor))
+ self.assertEqual(f[Flavor.NU_E].unit, 1./(u.erg * u.s))
| Vectorize NeutrinoDecay calculation in flavor transformation module
The NeutrinoDecay transformation is extremely slow; the loop over energy spectra can be vectorized. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"python/snewpy/test/test_models.py::TestModels::test_Warren_2020"
] | [
"python/snewpy/test/test_models.py::TestModels::test_Bollig_2016",
"python/snewpy/test/test_models.py::TestModels::test_Fornax_2019",
"python/snewpy/test/test_models.py::TestModels::test_Fornax_2021",
"python/snewpy/test/test_models.py::TestModels::test_Kuroda_2020",
"python/snewpy/test/test_models.py::TestModels::test_Nakazato_2013",
"python/snewpy/test/test_models.py::TestModels::test_OConnor_2015",
"python/snewpy/test/test_models.py::TestModels::test_Sukhbold_2015",
"python/snewpy/test/test_models.py::TestModels::test_Tamborra_2014",
"python/snewpy/test/test_models.py::TestModels::test_Walk_2018",
"python/snewpy/test/test_models.py::TestModels::test_Walk_2019",
"python/snewpy/test/test_models.py::TestModels::test_Zha_2021"
] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2021-09-13T19:53:23Z" | bsd-3-clause |
|
Sage-Bionetworks__Genie-438 | diff --git a/genie_registry/maf.py b/genie_registry/maf.py
index f4dae91..714233a 100644
--- a/genie_registry/maf.py
+++ b/genie_registry/maf.py
@@ -25,8 +25,8 @@ def _check_tsa1_tsa2(df):
error = (
"maf: Contains both "
"TUMOR_SEQ_ALLELE1 and TUMOR_SEQ_ALLELE2 columns. "
- "The values in TUMOR_SEQ_ALLELE1 must be the same as "
- "all the values in REFERENCE_ALELLE OR TUMOR_SEQ_ALLELE2."
+ "All values in TUMOR_SEQ_ALLELE1 must match all values in "
+ "REFERENCE_ALLELE or all values in TUMOR_SEQ_ALLELE2.\n"
)
return error
| Sage-Bionetworks/Genie | ef4b90520b2b7664e8ab19e001a2cc9c9724437c | diff --git a/tests/test_maf.py b/tests/test_maf.py
index edc9105..75bcecd 100644
--- a/tests/test_maf.py
+++ b/tests/test_maf.py
@@ -211,8 +211,8 @@ def test_invalid__check_tsa1_tsa2():
assert error == (
"maf: Contains both "
"TUMOR_SEQ_ALLELE1 and TUMOR_SEQ_ALLELE2 columns. "
- "The values in TUMOR_SEQ_ALLELE1 must be the same as "
- "all the values in REFERENCE_ALELLE OR TUMOR_SEQ_ALLELE2."
+ "All values in TUMOR_SEQ_ALLELE1 must match all values in "
+ "REFERENCE_ALLELE or all values in TUMOR_SEQ_ALLELE2.\n"
)
| Modify error message for maf.py check
for _check_tsa1_tsa2 in maf.py, modify error message.
https://github.com/Sage-Bionetworks/Genie/blob/develop/genie_registry/maf.py#L25
Instead of
> The values in TUMOR_SEQ_ALLELE1 must be the same as all the values in REFERENCE_ALLELE OR TUMOR_SEQ_ALLELE2
maybe
> All values in TUMOR_SEQ_ALLELE1 must match all values in REFERENCE_ALLELE or all values in TUMOR_SEQ_ALLELE2 | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_maf.py::test_invalid__check_tsa1_tsa2"
] | [
"tests/test_maf.py::test_invalidname_validateFilename",
"tests/test_maf.py::test_valid_validateFilename",
"tests/test_maf.py::test_perfect_validation",
"tests/test_maf.py::test_firstcolumn_validation",
"tests/test_maf.py::test_missingcols_validation",
"tests/test_maf.py::test_errors_validation",
"tests/test_maf.py::test_invalid_validation",
"tests/test_maf.py::test_noerror__check_allele_col[temp]",
"tests/test_maf.py::test_noerror__check_allele_col[REFERENCE_ALLELE]",
"tests/test_maf.py::test_warning__check_allele_col",
"tests/test_maf.py::test_error__check_allele_col",
"tests/test_maf.py::test_valid__check_tsa1_tsa2[df0]",
"tests/test_maf.py::test_valid__check_tsa1_tsa2[df1]"
] | {
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
} | "2022-02-14T10:47:35Z" | mit |
|
Sage-Bionetworks__Genie-450 | diff --git a/genie_registry/clinical.py b/genie_registry/clinical.py
index 90fca60..7739b2e 100644
--- a/genie_registry/clinical.py
+++ b/genie_registry/clinical.py
@@ -95,10 +95,10 @@ def _check_int_dead_consistency(clinicaldf: DataFrame) -> str:
# Check that all string values are equal each other
is_equal = all(clinicaldf.loc[is_str, "DEAD"] == clinicaldf.loc[is_str, "INT_DOD"])
# If dead, int column can't be Not Applicable
- # If alive, int column can't have values
+ # If alive, int column must be Not Applicable
if (
any(clinicaldf.loc[is_dead, "INT_DOD"] == "Not Applicable")
- or not all(clinicaldf.loc[is_alive, "INT_DOD"].isin(allowed_str))
+ or not all(clinicaldf.loc[is_alive, "INT_DOD"] == "Not Applicable")
or not is_equal
):
return (
| Sage-Bionetworks/Genie | 044479d77e7a12626cb6dc366edfc181908c62f7 | diff --git a/tests/test_clinical.py b/tests/test_clinical.py
index 8668f71..18937f2 100644
--- a/tests/test_clinical.py
+++ b/tests/test_clinical.py
@@ -804,8 +804,8 @@ def test__check_int_year_consistency_inconsistent(inconsistent_df,
"DEAD": [True, False]}
),
pd.DataFrame(
- {"INT_DOD": [1111, "Not Released"],
- "DEAD": [True, False]}
+ {"INT_DOD": ["Not Applicable", "Not Applicable"],
+ "DEAD": [False, False]}
)
]
)
@@ -824,6 +824,10 @@ def test__check_int_dead_consistency_valid(valid_df):
{"INT_DOD": ["Not Applicable", "Not Applicable"],
"DEAD": [True, False]}
),
+ pd.DataFrame(
+ {"INT_DOD": [1111, "Not Released"],
+ "DEAD": [True, False]}
+ ),
pd.DataFrame(
{"INT_DOD": [1111, 11111],
"DEAD": [True, False]}
| Modify check for DEAD variable in clinical file
if DEAD is False, then YEAR_DEATH and INT_DOD must be βNot Applicableβ
https://www.synapse.org/#!Synapse:syn3380222/wiki/412290 | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_clinical.py::test__check_int_dead_consistency_inconsistent[inconsistent_df1]"
] | [
"tests/test_clinical.py::test_filetype",
"tests/test_clinical.py::test_incorrect_validatefilename[filename_fileformat_map0]",
"tests/test_clinical.py::test_incorrect_validatefilename[filename_fileformat_map1]",
"tests/test_clinical.py::test_correct_validatefilename",
"tests/test_clinical.py::test_patient_fillvs__process",
"tests/test_clinical.py::test_patient_lesscoltemplate__process",
"tests/test_clinical.py::test_patient_vs__process",
"tests/test_clinical.py::test_sample__process",
"tests/test_clinical.py::test_perfect__validate",
"tests/test_clinical.py::test_nonull__validate",
"tests/test_clinical.py::test_missingcols__validate",
"tests/test_clinical.py::test_errors__validate",
"tests/test_clinical.py::test_duplicated__validate",
"tests/test_clinical.py::test_get_oncotree_code_mappings",
"tests/test_clinical.py::test__check_year_no_errors",
"tests/test_clinical.py::test__check_year_too_big_year",
"tests/test_clinical.py::test__check_year_invalid",
"tests/test_clinical.py::test_remap_clinical_values_sampletype",
"tests/test_clinical.py::test_remap_clinical_values[SEX]",
"tests/test_clinical.py::test_remap_clinical_values[PRIMARY_RACE]",
"tests/test_clinical.py::test_remap_clinical_values[SECONDARY_RACE]",
"tests/test_clinical.py::test_remap_clinical_values[TERTIARY_RACE]",
"tests/test_clinical.py::test_remap_clinical_values[ETHNICITY]",
"tests/test_clinical.py::test__check_int_year_consistency_valid",
"tests/test_clinical.py::test__check_int_year_consistency_inconsistent[inconsistent_df0-Patient:",
"tests/test_clinical.py::test__check_int_year_consistency_inconsistent[inconsistent_df1-Patient:",
"tests/test_clinical.py::test__check_int_year_consistency_inconsistent[inconsistent_df2-Patient:",
"tests/test_clinical.py::test__check_int_year_consistency_inconsistent[inconsistent_df3-Patient:",
"tests/test_clinical.py::test__check_int_year_consistency_inconsistent[inconsistent_df4-Patient:",
"tests/test_clinical.py::test__check_int_year_consistency_inconsistent[inconsistent_df5-Patient:",
"tests/test_clinical.py::test__check_int_dead_consistency_valid[valid_df0]",
"tests/test_clinical.py::test__check_int_dead_consistency_valid[valid_df1]",
"tests/test_clinical.py::test__check_int_dead_consistency_inconsistent[inconsistent_df0]",
"tests/test_clinical.py::test__check_int_dead_consistency_inconsistent[inconsistent_df2]",
"tests/test_clinical.py::test__check_int_dead_consistency_inconsistent[inconsistent_df3]"
] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
} | "2022-03-04T00:26:19Z" | mit |
|
Sage-Bionetworks__Genie-464 | diff --git a/genie_registry/clinical.py b/genie_registry/clinical.py
index cbf1a42..cac16e4 100644
--- a/genie_registry/clinical.py
+++ b/genie_registry/clinical.py
@@ -140,8 +140,14 @@ def _check_int_year_consistency(
for str_val in string_vals:
# n string values per row
n_str = (clinicaldf[cols] == str_val).sum(axis=1)
- if n_str.between(0, len(cols), inclusive="neither").any():
- is_text_inconsistent = True
+ # year can be known with unknown interval value
+ # otherwise must be all numeric or the same text value
+ if str_val == "Unknown":
+ if ((n_str == 1) & (clinicaldf[interval_col] != "Unknown")).any():
+ is_text_inconsistent = True
+ else:
+ if n_str.between(0, len(cols), inclusive="neither").any():
+ is_text_inconsistent = True
is_redaction_inconsistent = False
# Check that the redacted values are consistent
| Sage-Bionetworks/Genie | bdeacb848e48ddadc1652b6572d6a5deb5f37869 | diff --git a/tests/test_clinical.py b/tests/test_clinical.py
index e0d29e0..70e8f1b 100644
--- a/tests/test_clinical.py
+++ b/tests/test_clinical.py
@@ -727,13 +727,13 @@ def test_remap_clinical_values(col):
def test__check_int_year_consistency_valid():
"""Test valid vital status consistency"""
testdf = pd.DataFrame(
- {"INT_2": [1, 2, "Unknown"],
- "YEAR_1": [1, 4, "Unknown"],
- "FOO_3": [1, 3, "Unknown"]}
+ {"INT_2": [1, 2, "Unknown", "Unknown"],
+ "YEAR_1": [1, 4, "Unknown", 1],
+ "FOO_3": [1, 3, "Unknown", 1]}
)
error = genie_registry.clinical._check_int_year_consistency(
clinicaldf=testdf,
- cols=['INT_2', "YEAR_1"],
+ cols=["INT_2", "YEAR_1"],
string_vals=["Unknown"]
)
assert error == ""
@@ -759,7 +759,7 @@ def test__check_int_year_consistency_valid():
(
pd.DataFrame(
{"INT_2": [1, "Unknown", "Unknown"],
- "YEAR_1": [1, 4, "Unknown"]}
+ "YEAR_1": [1, "Not Applicable", "Unknown"]}
),
"Patient: you have inconsistent text values in INT_2, YEAR_1.\n"
),
@@ -780,10 +780,17 @@ def test__check_int_year_consistency_valid():
(
pd.DataFrame(
{"INT_2": ["<6570", "Unknown", "Unknown"],
- "YEAR_1": [1, 3, "Unknown"]}
+ "YEAR_1": [1, "Not Applicable", "Unknown"]}
),
"Patient: you have inconsistent redaction and text values in "
"INT_2, YEAR_1.\n"
+ ),
+ (
+ pd.DataFrame(
+ {"INT_2": ["12345", "Unknown", "Unknown"],
+ "YEAR_1": ["Unknown", "Unknown", "Unknown"]}
+ ),
+ "Patient: you have inconsistent text values in INT_2, YEAR_1.\n"
)
]
)
| Modify vital status inconsistency check
One site reports that they are able to supply the YEAR but not INT of the vital status values.
Therefore, should allow for a numeric year and `Unknown` INT pattern for both death and contact variable pairs. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_clinical.py::test__check_int_year_consistency_valid"
] | [
"tests/test_clinical.py::test_filetype",
"tests/test_clinical.py::test_incorrect_validatefilename[filename_fileformat_map0]",
"tests/test_clinical.py::test_incorrect_validatefilename[filename_fileformat_map1]",
"tests/test_clinical.py::test_correct_validatefilename",
"tests/test_clinical.py::test_patient_fillvs__process",
"tests/test_clinical.py::test_patient_lesscoltemplate__process",
"tests/test_clinical.py::test_patient_vs__process",
"tests/test_clinical.py::test_sample__process",
"tests/test_clinical.py::test_perfect__validate",
"tests/test_clinical.py::test_nonull__validate",
"tests/test_clinical.py::test_missingcols__validate",
"tests/test_clinical.py::test_errors__validate",
"tests/test_clinical.py::test_duplicated__validate",
"tests/test_clinical.py::test_get_oncotree_code_mappings",
"tests/test_clinical.py::test__check_year_no_errors",
"tests/test_clinical.py::test__check_year_too_big_year",
"tests/test_clinical.py::test__check_year_invalid",
"tests/test_clinical.py::test_remap_clinical_values_sampletype",
"tests/test_clinical.py::test_remap_clinical_values[SEX]",
"tests/test_clinical.py::test_remap_clinical_values[PRIMARY_RACE]",
"tests/test_clinical.py::test_remap_clinical_values[SECONDARY_RACE]",
"tests/test_clinical.py::test_remap_clinical_values[TERTIARY_RACE]",
"tests/test_clinical.py::test_remap_clinical_values[ETHNICITY]",
"tests/test_clinical.py::test__check_int_year_consistency_inconsistent[inconsistent_df0-Patient:",
"tests/test_clinical.py::test__check_int_year_consistency_inconsistent[inconsistent_df1-Patient:",
"tests/test_clinical.py::test__check_int_year_consistency_inconsistent[inconsistent_df2-Patient:",
"tests/test_clinical.py::test__check_int_year_consistency_inconsistent[inconsistent_df3-Patient:",
"tests/test_clinical.py::test__check_int_year_consistency_inconsistent[inconsistent_df4-Patient:",
"tests/test_clinical.py::test__check_int_year_consistency_inconsistent[inconsistent_df5-Patient:",
"tests/test_clinical.py::test__check_int_year_consistency_inconsistent[inconsistent_df6-Patient:",
"tests/test_clinical.py::test__check_int_dead_consistency_valid[valid_df0]",
"tests/test_clinical.py::test__check_int_dead_consistency_valid[valid_df1]",
"tests/test_clinical.py::test__check_int_dead_consistency_inconsistent[inconsistent_df0]",
"tests/test_clinical.py::test__check_int_dead_consistency_inconsistent[inconsistent_df1]",
"tests/test_clinical.py::test__check_int_dead_consistency_inconsistent[inconsistent_df2]",
"tests/test_clinical.py::test__check_int_dead_consistency_inconsistent[inconsistent_df3]"
] | {
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
} | "2022-04-12T18:59:37Z" | mit |
|
Sage-Bionetworks__challengeutils-247 | diff --git a/challengeutils/submission.py b/challengeutils/submission.py
index 6a625d0..3c3c74e 100644
--- a/challengeutils/submission.py
+++ b/challengeutils/submission.py
@@ -103,18 +103,14 @@ def validate_project(syn, submission, challenge, public=False, admin=None):
"""
writeup = syn.getSubmission(submission)
errors = []
-
type_error = _validate_ent_type(writeup)
if type_error:
errors.append(type_error)
-
contents_error = _validate_project_id(writeup, challenge)
if contents_error:
errors.append(contents_error)
-
permissions_error = _check_project_permissions(syn, writeup, public, admin)
errors.extend(permissions_error)
-
status = "INVALID" if errors else "VALIDATED"
return {"submission_errors": "\n".join(errors), "submission_status": status}
@@ -142,7 +138,6 @@ def archive_project(syn, submission, admin):
# TODO: move to utils module
def _validate_ent_type(submission):
"""Check entity type of submission."""
-
try:
if not isinstance(submission.entity, entity.Project):
ent_type = re.search(r"entity\.(.*?)'", str(type(submission.entity))).group(
@@ -157,7 +152,6 @@ def _validate_ent_type(submission):
def _validate_project_id(proj, challenge):
"""Check that submission is not the Challenge site."""
-
return (
"Submission should not be the Challenge site."
if proj.entityId == challenge
@@ -167,56 +161,48 @@ def _validate_project_id(proj, challenge):
def _validate_public_permissions(syn, proj):
"""Ensure project is shared with the public."""
-
error = "Your project is not publicly available."
-
try:
# Remove error message if the project is accessible by the public.
- syn_users_perms = syn.getPermissions(proj.entityId, AUTHENTICATED_USERS)
public_perms = syn.getPermissions(proj.entityId)
- if (
- "READ" in syn_users_perms and "DOWNLOAD" in syn_users_perms
- ) and "READ" in public_perms:
+ if "READ" in public_perms:
error = ""
-
except SynapseHTTPError as e:
# Raise exception message if error is not a permissions error.
if e.response.status_code != 403:
raise e
-
return error
def _validate_admin_permissions(syn, proj, admin):
"""Ensure project is shared with the given admin."""
-
error = (
"Project is private; please update its sharing settings."
f" Writeup should be shared with {admin}."
)
try:
- # Remove error message if admin has read and download permissions.
+ # Remove error message if admin has read and download permissions
+ # OR if the project is publicly availably.
admin_perms = syn.getPermissions(proj.entityId, admin)
- if "READ" in admin_perms and "DOWNLOAD" in admin_perms:
+ public_perms = syn.getPermissions(proj.entityId)
+ if "READ" in public_perms or (
+ "READ" in admin_perms and "DOWNLOAD" in admin_perms
+ ):
error = ""
-
except SynapseHTTPError as e:
# Raise exception message if error is not a permissions error.
if e.response.status_code != 403:
raise e
-
return error
def _check_project_permissions(syn, submission, public, admin):
"""Check the submission sharing settings."""
-
errors = []
if public:
public_error = _validate_public_permissions(syn, submission)
if public_error:
errors.append(public_error)
-
if not public and admin is not None:
admin_error = _validate_admin_permissions(syn, submission, admin)
if admin_error:
| Sage-Bionetworks/challengeutils | 51915b06f431df229ad41ade949291f60950bf85 | diff --git a/tests/test_submission.py b/tests/test_submission.py
index 7680620..c30051b 100644
--- a/tests/test_submission.py
+++ b/tests/test_submission.py
@@ -69,7 +69,7 @@ def test__validate_admin_permissions_admin_permissions_req():
admin = "me"
with patch.object(SYN, "getPermissions") as patch_perms:
errors = submission._validate_admin_permissions(SYN, PROJ, admin=admin)
- patch_perms.assert_called_once()
+ assert patch_perms.call_count == 2
message = (
"Project is private; please update its sharing settings."
@@ -86,7 +86,7 @@ def test__validate_public_permissions_public_permissions_req():
"""
with patch.object(SYN, "getPermissions") as patch_perms:
errors = submission._validate_public_permissions(SYN, PROJ)
- assert patch_perms.call_count == 2
+ patch_perms.assert_called_once()
assert errors == "Your project is not publicly available."
| `--admin` check for `validate-project` does not work as expected
**Describe the bug**
The project associated with submission ID 9731653 is a publicly accessible Synapse project, but comes back as INVALID when `--admin <some user/team>` is flagged. e.g.
```
$ challengeutils validate-project 9731653 syn28590455 --admin "RARE-X Organizers"
INFO:challengeutils.__main__:{'submission_errors': 'Project is private; please update its sharing settings. Writeup should be shared with RARE-X Organizers.', 'submission_status': 'INVALID'}
```
**Expected behavior**
Because the project is publicly accessible, the submission should come back as VALID, since the admin team could technically view the project.
**Priority**
High - needed for the RARE-X challenge which will open soon. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_submission.py::test__validate_admin_permissions_admin_permissions_req",
"tests/test_submission.py::test__validate_public_permissions_public_permissions_req"
] | [
"tests/test_submission.py::test__validate_ent_type_submission_type_project[project0-]",
"tests/test_submission.py::test__validate_ent_type_submission_type_project[project1-Submission",
"tests/test_submission.py::test__validate_ent_type_submission_type_project[project2-Unknown",
"tests/test_submission.py::test__validate_project_id_nonchallenge_submission[syn000-]",
"tests/test_submission.py::test__validate_project_id_nonchallenge_submission[syn123-Submission",
"tests/test_submission.py::test__check_project_permissions_errorcode[True-None-Your",
"tests/test_submission.py::test__check_project_permissions_errorcode[True-me-Your",
"tests/test_submission.py::test__check_project_permissions_errorcode[False-me-Project",
"tests/test_submission.py::test_validate_project_command_success[syn000-VALIDATED]",
"tests/test_submission.py::test_validate_project_command_success[syn123-INVALID]",
"tests/test_submission.py::test_validate_docker_submission_valid",
"tests/test_submission.py::test_validate_docker_submission_nousername",
"tests/test_submission.py::test_validate_docker_submission_notdocker",
"tests/test_submission.py::test_nosub_get_submitterid_from_submission_id",
"tests/test_submission.py::test_get_submitterid_from_submission_id",
"tests/test_submission.py::test_get_submitters_lead_submission",
"tests/test_submission.py::test_none_get_submitters_lead_submission",
"tests/test_submission.py::test_download_current_lead_sub",
"tests/test_submission.py::test_invalid_download_current_lead_sub",
"tests/test_submission.py::TestStopDockerSubmission::test_noneintquota",
"tests/test_submission.py::TestStopDockerSubmission::test_greaterthan0quota[0]",
"tests/test_submission.py::TestStopDockerSubmission::test_greaterthan0quota[-1]",
"tests/test_submission.py::TestStopDockerSubmission::test_queryfail",
"tests/test_submission.py::TestStopDockerSubmission::test_noquota",
"tests/test_submission.py::TestStopDockerSubmission::test_notstartedsubmission",
"tests/test_submission.py::TestStopDockerSubmission::test_underquota",
"tests/test_submission.py::TestStopDockerSubmission::test_overquota"
] | {
"failed_lite_validators": [
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2023-07-04T07:47:41Z" | apache-2.0 |
|
SalihTasdelen__paco-13 | diff --git a/examples/recursive_array.py b/examples/recursive_array.py
index 55b56df..46d5e5a 100644
--- a/examples/recursive_array.py
+++ b/examples/recursive_array.py
@@ -1,4 +1,5 @@
-from paco.combinators import (Char, Lazy)
+from paco.combinators import Lazy
+from paco.atomic import Char
from paco.miscellaneous import (letters, numbers, optSpace)
lbra = Char('[').then(optSpace)
@@ -12,7 +13,10 @@ array.p = optSpace >> lbra >> element.sepby(comm) << rbra << optSpace
def main():
test_str = ' [ [1, 3, 5], [hi, howdy, bye], 42, [[1,2], [4,5]]] '
print('Running on: ' + test_str)
- print(array(test_str))
+ _, ar = array(test_str)
+ print('(ar[0][2] == {}) ->'.format(ar[0][2]), ar[0][2] == '5')
+ print('(ar[1][1] == {}) ->'.format(ar[1][1]), ar[1][1] == 'howdy')
+ print('(ar[3][1][0] == {}) ->'.format(ar[3][1][0]), ar[3][1][0] == '4')
if __name__ == '__main__':
exit(main())
\ No newline at end of file
diff --git a/src/paco/__init__.py b/src/paco/__init__.py
index 0a0fd75..b2db0a3 100644
--- a/src/paco/__init__.py
+++ b/src/paco/__init__.py
@@ -1,1 +1,1 @@
-from . import combinators, miscellaneous, lexer
+from . import combinators, atomic, miscellaneous, lexer
diff --git a/src/paco/atomic.py b/src/paco/atomic.py
new file mode 100644
index 0000000..2468c3d
--- /dev/null
+++ b/src/paco/atomic.py
@@ -0,0 +1,67 @@
+
+import re
+from .combinators import Parser, ParseError
+
+class Char(Parser):
+ def __init__(self, char : str) -> None:
+ super().__init__()
+ self.name = 'char(\'{}\')'.format(char)
+ self.char = char
+
+ def run(self, pos : int, tar : str):
+ if (len(tar) > pos) and (tar[pos] == self.char):
+ return (pos + 1, self.char)
+
+ got = tar[pos] if len(tar) > pos else "EOF"
+ msg = f"Excpected '{self.char}' but got '{got}'"
+ raise ParseError(pos, pos + 1, msg, self)
+
+class Literal(Parser):
+
+ def __init__(self, literal : str) -> None:
+ super().__init__()
+ self.name = 'lit(\'{}\')'.format(literal)
+ self.literal = literal
+ self.length = len(literal)
+
+ def run(self, pos : int, tar : str):
+ if tar.startswith(self.literal,pos):
+ return (pos + self.length, self.literal)
+ if len(tar) > (pos + self.length-1):
+ msg = f"Tried to match '{self.literal}' but got '{tar[pos:pos+self.length]}'"
+ raise ParseError(pos, pos + self.length, msg, self)
+ msg = f"Tried to match '{self.literal}' but got EOF"
+ raise ParseError(pos, pos + self.length, msg, self)
+
+class Regex(Parser):
+
+ def __init__(self, rule : str) -> None:
+ super().__init__()
+ self.name = 'reg(r\'{}\')'.format(rule)
+ self.rule = re.compile(rule)
+
+ def run(self, pos : int, tar : str):
+ m = self.rule.match(tar, pos)
+ if m is None:
+ msg = f"Couldn't match the rule: {self.rule}"
+ raise ParseError(pos, pos, msg, self)
+ return (m.end(), m.group())
+
+class Tok(Parser):
+
+ def __init__(self, tag : str, data = None):
+ self.tag, self.data = tag, data
+ if data:
+ self.condition = lambda t : (t.type == tag) and (t.data == data)
+ else:
+ self.condition = lambda t : (t.type == tag)
+
+ def run(self, pos : int, tar : list):
+ if len(tar) > pos:
+ tok = tar[pos]
+ if self.condition(tok):
+ return (pos + 1, tok)
+ msg = 'Expected Token {} but got {}'.format((self.tag,self.data),tok)
+ raise ParseError(tok.start, tok.end, msg, self)
+ else:
+ raise ParseError(pos, pos, 'Got EOF', self)
diff --git a/src/paco/combinators.py b/src/paco/combinators.py
index 6ff2b26..7f2f721 100644
--- a/src/paco/combinators.py
+++ b/src/paco/combinators.py
@@ -1,4 +1,3 @@
-import re
from typing import Iterable
class Parser(object):
@@ -65,67 +64,6 @@ class ParseError(Exception):
def __str__(self):
return self.msg
-class Char(Parser):
- def __init__(self, char : str) -> None:
- super().__init__()
- self.name = 'char(\'{}\')'.format(char)
- self.char = char
-
- def run(self, pos : int, tar : str):
- if (len(tar) > pos) and (tar[pos] == self.char):
- return (pos + 1, self.char)
-
- got = tar[pos] if len(tar) > pos else "EOF"
- msg = f"Excpected '{self.char}' but got '{got}'"
- raise ParseError(pos, pos + 1, msg, self)
-
-class Literal(Parser):
-
- def __init__(self, literal : str) -> None:
- super().__init__()
- self.name = 'lit(\'{}\')'.format(literal)
- self.literal = literal
- self.length = len(literal)
-
- def run(self, pos : int, tar : str):
- if tar.startswith(self.literal,pos):
- return (pos + self.length, self.literal)
- if len(tar) > (pos + self.length-1):
- msg = f"Tried to match '{self.literal}' but got '{tar[pos:pos+self.length]}'"
- raise ParseError(pos, pos + self.length, msg, self)
- msg = f"Tried to match '{self.literal}' but got EOF"
- raise ParseError(pos, pos + self.length, msg, self)
-
-class Regex(Parser):
-
- def __init__(self, rule : str) -> None:
- super().__init__()
- self.name = 'reg(r\'{}\')'.format(rule)
- self.rule = re.compile(rule)
-
- def run(self, pos : int, tar : str):
- m = self.rule.match(tar, pos)
- if m is None:
- msg = f"Couldn't match the rule: {self.rule}"
- raise ParseError(pos, pos, msg, self)
- return (m.end(), m.group())
-
-class Tok(Parser):
-
- def __init__(self, tag : str, data = None):
- self.tag, self.data = tag, data
- if data:
- self.condition = lambda t : (t.type == tag) and (t.data == data)
- else:
- self.condition = lambda t : (t.type == tag)
-
- def run(self, pos : int, tar : list):
- tok = tar[pos]
- if self.condition(tok):
- return (pos + 1, tok)
- msg = 'Expected Token was {} but got {}'.format((self.tag,self.data),tok)
- raise ParseError(tok.start, tok.end, msg, self)
-
class Sequence(Parser):
def __init__(self, *parsers) -> None:
diff --git a/src/paco/miscellaneous.py b/src/paco/miscellaneous.py
index 3938293..c87c881 100644
--- a/src/paco/miscellaneous.py
+++ b/src/paco/miscellaneous.py
@@ -1,4 +1,4 @@
-from .combinators import (Regex)
+from .atomic import (Regex)
letters = Regex("[a-zA-Z]+")
letter = Regex("[a-zA-Z]")
| SalihTasdelen/paco | bd5ba329f7631e58ad911d2c2c0cf25d503b91fb | diff --git a/tests/test_char_parser.py b/tests/test_char_parser.py
index e8737e1..861b054 100644
--- a/tests/test_char_parser.py
+++ b/tests/test_char_parser.py
@@ -1,5 +1,5 @@
import unittest
-from paco.combinators import Char
+from paco.atomic import Char
class TestCharParser(unittest.TestCase):
diff --git a/tests/test_choice_parser.py b/tests/test_choice_parser.py
index 1f4ff34..652ac7c 100644
--- a/tests/test_choice_parser.py
+++ b/tests/test_choice_parser.py
@@ -1,5 +1,6 @@
import unittest
-from paco.combinators import (Char, Literal, Regex, Choice)
+from paco.combinators import Choice
+from paco.atomic import (Char, Literal, Regex)
class TestChoiceParser(unittest.TestCase):
diff --git a/tests/test_keepleft_parser.py b/tests/test_keepleft_parser.py
index 4a27682..4c89b22 100644
--- a/tests/test_keepleft_parser.py
+++ b/tests/test_keepleft_parser.py
@@ -1,5 +1,6 @@
import unittest
-from paco.combinators import (Char, Literal, Regex, KeepLeft)
+from paco.combinators import KeepLeft
+from paco.atomic import (Char, Literal, Regex)
class TestKeepLeftParser(unittest.TestCase):
diff --git a/tests/test_keepright_parser.py b/tests/test_keepright_parser.py
index d90fbfe..3ff8807 100644
--- a/tests/test_keepright_parser.py
+++ b/tests/test_keepright_parser.py
@@ -1,5 +1,6 @@
import unittest
-from paco.combinators import (Char, Literal, Regex, KeepRight)
+from paco.combinators import KeepRight
+from paco.atomic import (Char, Literal, Regex)
class TestKeepRightParser(unittest.TestCase):
diff --git a/tests/test_lazy_parser.py b/tests/test_lazy_parser.py
index 4d902be..2207861 100644
--- a/tests/test_lazy_parser.py
+++ b/tests/test_lazy_parser.py
@@ -1,5 +1,6 @@
import unittest
-from paco.combinators import (Char, Lazy)
+from paco.combinators import Lazy
+from paco.atomic import Char
class TestLazyParser(unittest.TestCase):
diff --git a/tests/test_literal_parser.py b/tests/test_literal_parser.py
index 199e5b6..24e8cdc 100644
--- a/tests/test_literal_parser.py
+++ b/tests/test_literal_parser.py
@@ -1,5 +1,5 @@
import unittest
-from paco.combinators import Literal
+from paco.atomic import Literal
class TestLiteralParser(unittest.TestCase):
diff --git a/tests/test_many_parser.py b/tests/test_many_parser.py
index 1e6abba..75a0d12 100644
--- a/tests/test_many_parser.py
+++ b/tests/test_many_parser.py
@@ -1,5 +1,6 @@
import unittest
-from paco.combinators import (Char, Regex, Many)
+from paco.combinators import Many
+from paco.atomic import (Char, Regex)
class TestManyParser(unittest.TestCase):
diff --git a/tests/test_regex_parser.py b/tests/test_regex_parser.py
index 109fd50..57740f2 100644
--- a/tests/test_regex_parser.py
+++ b/tests/test_regex_parser.py
@@ -1,5 +1,5 @@
import unittest
-from paco.combinators import Regex
+from paco.atomic import Regex
class TestRegexParser(unittest.TestCase):
diff --git a/tests/test_sepby_parser.py b/tests/test_sepby_parser.py
index cfeb181..8e420ca 100644
--- a/tests/test_sepby_parser.py
+++ b/tests/test_sepby_parser.py
@@ -1,5 +1,6 @@
import unittest
-from paco.combinators import (Char, Regex, SepBy)
+from paco.combinators import SepBy
+from paco.atomic import (Char, Regex)
class TestSepByParser(unittest.TestCase):
diff --git a/tests/test_sequence_parser.py b/tests/test_sequence_parser.py
index 0dc25b6..70176ba 100644
--- a/tests/test_sequence_parser.py
+++ b/tests/test_sequence_parser.py
@@ -1,5 +1,6 @@
import unittest
-from paco.combinators import (Char, Literal, Regex, Sequence)
+from paco.combinators import Sequence
+from paco.atomic import (Char, Literal, Regex)
class TestSequenceParser(unittest.TestCase):
| Seperating Atomic Parsers from combinators.py
The Atomic Parsers = [Char, Literal, Regex, Tok]
These parsers are usually the starting points for grammars so they are not actually combinators but pieces for combinators, like Choice, Sequence and Many to use. This issue proposes a goal to move Atomic parsers to atomic.py and change imports accoringly. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_char_parser.py::TestCharParser::test_empty",
"tests/test_char_parser.py::TestCharParser::test_error",
"tests/test_char_parser.py::TestCharParser::test_name",
"tests/test_char_parser.py::TestCharParser::test_return",
"tests/test_choice_parser.py::TestChoiceParser::test_empty",
"tests/test_choice_parser.py::TestChoiceParser::test_error",
"tests/test_choice_parser.py::TestChoiceParser::test_return",
"tests/test_choice_parser.py::TestChoiceParser::test_rshift",
"tests/test_keepleft_parser.py::TestKeepLeftParser::test_empty",
"tests/test_keepleft_parser.py::TestKeepLeftParser::test_error",
"tests/test_keepleft_parser.py::TestKeepLeftParser::test_lshift",
"tests/test_keepleft_parser.py::TestKeepLeftParser::test_return",
"tests/test_keepright_parser.py::TestKeepRightParser::test_empty",
"tests/test_keepright_parser.py::TestKeepRightParser::test_error",
"tests/test_keepright_parser.py::TestKeepRightParser::test_return",
"tests/test_keepright_parser.py::TestKeepRightParser::test_rshift",
"tests/test_lazy_parser.py::TestLazyParser::test_empty",
"tests/test_lazy_parser.py::TestLazyParser::test_error",
"tests/test_lazy_parser.py::TestLazyParser::test_return",
"tests/test_literal_parser.py::TestLiteralParser::test_empty",
"tests/test_literal_parser.py::TestLiteralParser::test_error",
"tests/test_literal_parser.py::TestLiteralParser::test_name",
"tests/test_literal_parser.py::TestLiteralParser::test_return",
"tests/test_many_parser.py::TestManyParser::test_empty",
"tests/test_many_parser.py::TestManyParser::test_error",
"tests/test_many_parser.py::TestManyParser::test_return",
"tests/test_regex_parser.py::TestRegexParser::test_empty_rule",
"tests/test_regex_parser.py::TestRegexParser::test_empty_target",
"tests/test_regex_parser.py::TestRegexParser::test_error",
"tests/test_regex_parser.py::TestRegexParser::test_name",
"tests/test_regex_parser.py::TestRegexParser::test_return",
"tests/test_sepby_parser.py::TestSepByParser::test_empty",
"tests/test_sepby_parser.py::TestSepByParser::test_error",
"tests/test_sepby_parser.py::TestSepByParser::test_return",
"tests/test_sequence_parser.py::TestSequenceParser::test_add",
"tests/test_sequence_parser.py::TestSequenceParser::test_empty",
"tests/test_sequence_parser.py::TestSequenceParser::test_error",
"tests/test_sequence_parser.py::TestSequenceParser::test_return"
] | [] | {
"failed_lite_validators": [
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2021-09-19T14:47:59Z" | mit |
|
SathyaBhat__spotify-dl-311 | diff --git a/README.md b/README.md
index 1384fe5..b1752c0 100644
--- a/README.md
+++ b/README.md
@@ -30,6 +30,10 @@ If you want to make use of parallel download, pass `-mc <number>`, where `<numbe
spotify_dl -mc 4 -l spotify_playlist_link_1 spotify_playlist_link_2
+Spotify-dl can make use of SponsorBlock and skip non-music sections when downloading from YouTube. This is disabled by default and can be enabled using:
+
+ spotify_dl -l spotify_playlist_link_1 -s y
+
For running in verbose mode, append `-V`
spotify_dl -V -l spotify_playlist_link -o download_directory
diff --git a/requirements.txt b/requirements.txt
index 186024e..2313956 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -1,5 +1,6 @@
sentry_sdk~=1.5
yt-dlp>=2022.01.21
-spotipy~=2.19
+spotipy~=2.21
mutagen~=1.45
rich~=12.0
+urllib3~=1.26
\ No newline at end of file
diff --git a/spotify_dl/spotify_dl.py b/spotify_dl/spotify_dl.py
index 94b0519..d1d6627 100755
--- a/spotify_dl/spotify_dl.py
+++ b/spotify_dl/spotify_dl.py
@@ -72,10 +72,10 @@ def spotify_dl():
)
parser.add_argument(
"-s",
- "--skip_non_music_sections",
- default=False,
- action="store_true",
- help="Whether to skip non-music sections using SponsorBlock API.",
+ "--use_sponsorblock",
+ default="no",
+ action="store",
+ help="Whether to skip non-music sections using SponsorBlock API. Pass y or yes to skip using SponsorBlock",
)
parser.add_argument(
"-w",
@@ -148,7 +148,9 @@ def spotify_dl():
)
)
log.debug("Arguments: %s ", args)
-
+ console.print(
+ f"Sponsorblock enabled?: [bold green]{args.use_sponsorblock}[/bold green]"
+ )
valid_urls = validate_spotify_urls(args.url)
if not valid_urls:
sys.exit(1)
@@ -180,7 +182,7 @@ def spotify_dl():
skip_mp3=args.skip_mp3,
keep_playlist_order=args.keep_playlist_order,
no_overwrites=args.no_overwrites,
- skip_non_music_sections=args.skip_non_music_sections,
+ use_sponsorblock=args.use_sponsorblock,
file_name_f=file_name_f,
multi_core=args.multi_core,
)
diff --git a/spotify_dl/youtube.py b/spotify_dl/youtube.py
index 9538d1d..fc0e1ea 100644
--- a/spotify_dl/youtube.py
+++ b/spotify_dl/youtube.py
@@ -123,6 +123,7 @@ def find_and_download_songs(kwargs):
the youtube_search lib is used to search for songs and get best url
:param kwargs: dictionary of key value arguments to be used in download
"""
+ sponsorblock_postprocessor = []
reference_file = kwargs["reference_file"]
with open(reference_file, "r", encoding="utf-8") as file:
for line in file:
@@ -140,27 +141,28 @@ def find_and_download_songs(kwargs):
file_name = kwargs["file_name_f"](
name=name, artist=artist, track_num=kwargs["track_db"][i].get("num")
)
- sponsorblock_remove_list = (
- ["music_offtopic"] if kwargs["skip_non_music_sections"] else []
- )
- file_path = path.join(kwargs["track_db"][i]["save_path"], file_name)
- outtmpl = f"{file_path}.%(ext)s"
- ydl_opts = {
- "default_search": "ytsearch",
- "format": "bestaudio/best",
- "outtmpl": outtmpl,
- "postprocessors": [
+ if kwargs["use_sponsorblock"][0].lower() == "y":
+
+ sponsorblock_postprocessor = [
{
"key": "SponsorBlock",
- "categories": sponsorblock_remove_list,
+ "categories": ["skip_non_music_sections"],
},
{
"key": "ModifyChapters",
"remove_sponsor_segments": ["music_offtopic"],
"force_keyframes": True,
},
- ],
+ ]
+
+ file_path = path.join(kwargs["track_db"][i]["save_path"], file_name)
+ outtmpl = f"{file_path}.%(ext)s"
+ ydl_opts = {
+ "default_search": "ytsearch",
+ "format": "bestaudio/best",
+ "outtmpl": outtmpl,
+ "postprocessors": sponsorblock_postprocessor,
"noplaylist": True,
"no_color": False,
"postprocessor_args": [
| SathyaBhat/spotify-dl | 403547b8f73cfafba6f39d421aae419b29259d1d | diff --git a/tests/test_youtube.py b/tests/test_youtube.py
index 0fccbf4..c941ac1 100644
--- a/tests/test_youtube.py
+++ b/tests/test_youtube.py
@@ -41,7 +41,7 @@ def test_download_one_false_skip():
skip_mp3=False,
keep_playlist_order=False,
no_overwrites=False,
- skip_non_music_sections=False,
+ use_sponsorblock="no",
file_name_f=yt.default_filename,
multi_core=0,
)
@@ -49,7 +49,9 @@ def test_download_one_false_skip():
"Hotel California - Live On MTV, 1994/Eagles - Hotel California - Live On MTV, 1994.mp3",
ID3=EasyID3,
)
- tags = ID3("Hotel California - Live On MTV, 1994/Eagles - Hotel California - Live On MTV, 1994.mp3")
+ tags = ID3(
+ "Hotel California - Live On MTV, 1994/Eagles - Hotel California - Live On MTV, 1994.mp3"
+ )
assert music["artist"][0] == "Eagles"
assert music["album"][0] == "Hell Freezes Over (Remaster 2018)"
assert music["genre"][0] == "album rock"
@@ -92,7 +94,7 @@ def test_download_one_true_skip():
skip_mp3=True,
keep_playlist_order=False,
no_overwrites=False,
- skip_non_music_sections=False,
+ use_sponsorblock="yes",
file_name_f=yt.default_filename,
multi_core=0,
)
@@ -128,7 +130,7 @@ def test_download_cover_none():
skip_mp3=False,
keep_playlist_order=False,
no_overwrites=False,
- skip_non_music_sections=False,
+ use_sponsorblock="no",
file_name_f=yt.default_filename,
multi_core=0,
)
| Error SponsorBlock
The system downloads but does not convert to mp3 due to the error below, is there a way to skip this check?
Because it does not convert and is in webm format
[SponsorBlock] Fetching SponsorBlock segments
WARNING: Unable to communicate with SponsorBlock API: The read operation timed out. Retrying (1/3)...
WARNING: Unable to communicate with SponsorBlock API: The read operation timed out. Retrying (2/3)...
WARNING: Unable to communicate with SponsorBlock API: The read operation timed out. Retrying (3/3)...
ERROR: Postprocessing: Unable to communicate with SponsorBlock API: The read operation timed out
Failed to download Freak On a Leash, make sure yt_dlp is up to date
Failed to download: Freak On a Leash/Korn - Freak On a Leash.mp3, please ensure YouTubeDL is up-to-date.
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_youtube.py::test_download_one_true_skip"
] | [] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2022-10-30T00:59:17Z" | mit |
|
SathyaBhat__spotify-dl-368 | diff --git a/spotify_dl/spotify.py b/spotify_dl/spotify.py
index f777a59..448d5e4 100644
--- a/spotify_dl/spotify.py
+++ b/spotify_dl/spotify.py
@@ -42,8 +42,14 @@ def fetch_tracks(sp, item_type, item_id):
continue
track_album_info = track_info.get("album")
track_num = track_info.get("track_number")
- spotify_id = track_info.get("id")
track_name = track_info.get("name")
+ spotify_id = track_info.get("id")
+ try:
+ track_audio_data = sp.audio_analysis(spotify_id)
+ tempo = track_audio_data.get("track").get("tempo")
+ except:
+ log.error("Couldn't fetch audio analysis for %s", track_name)
+ tempo = None
track_artist = ", ".join(
[artist["name"] for artist in track_info.get("artists")]
)
@@ -86,6 +92,7 @@ def fetch_tracks(sp, item_type, item_id):
"genre": genre,
"spotify_id": spotify_id,
"track_url": None,
+ "tempo": tempo,
}
)
offset += 1
@@ -141,6 +148,12 @@ def fetch_tracks(sp, item_type, item_id):
)
track_num = item["track_number"]
spotify_id = item.get("id")
+ try:
+ track_audio_data = sp.audio_analysis(spotify_id)
+ tempo = track_audio_data.get("track").get("tempo")
+ except:
+ log.error("Couldn't fetch audio analysis for %s", track_name)
+ tempo = None
songs_list.append(
{
"name": track_name,
@@ -154,6 +167,7 @@ def fetch_tracks(sp, item_type, item_id):
"cover": cover,
"genre": genre,
"spotify_id": spotify_id,
+ "tempo": tempo,
}
)
offset += 1
@@ -182,6 +196,12 @@ def fetch_tracks(sp, item_type, item_id):
album_total = album_info.get("total_tracks")
track_num = items["track_number"]
spotify_id = items["id"]
+ try:
+ track_audio_data = sp.audio_analysis(spotify_id)
+ tempo = track_audio_data.get("track").get("tempo")
+ except:
+ log.error("Couldn't fetch audio analysis for %s", track_name)
+ tempo = None
if len(items["album"]["images"]) > 0:
cover = items["album"]["images"][0]["url"]
else:
@@ -203,6 +223,7 @@ def fetch_tracks(sp, item_type, item_id):
"genre": genre,
"track_url": None,
"spotify_id": spotify_id,
+ "tempo": tempo,
}
)
diff --git a/spotify_dl/youtube.py b/spotify_dl/youtube.py
index e0f47f5..f3b6846 100644
--- a/spotify_dl/youtube.py
+++ b/spotify_dl/youtube.py
@@ -64,13 +64,13 @@ def write_tracks(tracks_file, song_dict):
i = 0
writer = csv.writer(file_out, delimiter=";")
for url_dict in song_dict["urls"]:
- # for track in url_dict['songs']:
for track in url_dict["songs"]:
track_url = track["track_url"] # here
track_name = track["name"]
track_artist = track["artist"]
track_num = track["num"]
track_album = track["album"]
+ track_tempo = track["tempo"]
track["save_path"] = url_dict["save_path"]
track_db.append(track)
track_index = i
@@ -81,6 +81,7 @@ def write_tracks(tracks_file, song_dict):
track_url,
str(track_num),
track_album,
+ str(track_tempo),
str(track_index),
]
try:
@@ -119,6 +120,8 @@ def set_tags(temp, filename, kwargs):
)
song_file["genre"] = song.get("genre")
+ if song.get("tempo") is not None:
+ song_file["bpm"] = str(song.get("tempo"))
song_file.save()
song_file = MP3(filename, ID3=ID3)
cover = song.get("cover")
| SathyaBhat/spotify-dl | b56afb2b459b93245dede75b7c27fd46753707ff | diff --git a/tests/test_spotify_fetch_tracks.py b/tests/test_spotify_fetch_tracks.py
index 89b2ed6..7addca4 100644
--- a/tests/test_spotify_fetch_tracks.py
+++ b/tests/test_spotify_fetch_tracks.py
@@ -32,6 +32,7 @@ def test_spotify_playlist_fetch_one():
"track_url": None,
"playlist_num": 1,
"spotify_id": "2GpBrAoCwt48fxjgjlzMd4",
+ 'tempo': 74.656,
} == songs[0]
@@ -53,6 +54,7 @@ def test_spotify_playlist_fetch_more():
"year": "2012",
"playlist_num": 1,
"spotify_id": "4rzfv0JLZfVhOhbSQ8o5jZ",
+ 'tempo': 135.016,
},
{
"album": "Wellness & Dreaming Source",
@@ -66,6 +68,7 @@ def test_spotify_playlist_fetch_more():
"playlist_num": 2,
"track_url": None,
"spotify_id": "5o3jMYOSbaVz3tkgwhELSV",
+ 'tempo': 137.805,
},
{
"album": "This Is Happening",
@@ -79,6 +82,7 @@ def test_spotify_playlist_fetch_more():
"year": "2010",
"playlist_num": 3,
"spotify_id": "4Cy0NHJ8Gh0xMdwyM9RkQm",
+ 'tempo': 134.99,
},
{
"album": "Glenn Horiuchi Trio / Gelenn Horiuchi Quartet: Mercy / Jump Start "
@@ -94,6 +98,7 @@ def test_spotify_playlist_fetch_more():
"track_url": None,
"playlist_num": 4,
"spotify_id": "6hvFrZNocdt2FcKGCSY5NI",
+ 'tempo': 114.767,
},
{
"album": "All The Best (Spanish Version)",
@@ -107,6 +112,7 @@ def test_spotify_playlist_fetch_more():
"year": "2007",
"playlist_num": 5,
"spotify_id": "2E2znCPaS8anQe21GLxcvJ",
+ 'tempo': 122.318,
},
] == songs
@@ -128,6 +134,7 @@ def test_spotify_track_fetch_one():
"track_url": None,
"playlist_num": 1,
"spotify_id": "2GpBrAoCwt48fxjgjlzMd4",
+ 'tempo': 74.656,
} == songs[0]
@@ -148,6 +155,7 @@ def test_spotify_album_fetch_one():
"year": "2012",
"playlist_num": 1,
"spotify_id": "5EoKQDGE2zxrTfRFZF52u5",
+ 'tempo': 120.009,
} == songs[0]
@@ -169,6 +177,7 @@ def test_spotify_album_fetch_more():
"year": "1974",
"playlist_num": 1,
"spotify_id": "69Yw7H4bRIwfIxL0ZCZy8y",
+ 'tempo': 120.955,
},
{
"album": "Queen II (Deluxe Remastered Version)",
@@ -182,6 +191,7 @@ def test_spotify_album_fetch_more():
"year": "1974",
"playlist_num": 2,
"spotify_id": "5GGSjXZeTgX9sKYBtl8K6U",
+ 'tempo': 147.384,
},
{
"album": "Queen II (Deluxe Remastered Version)",
@@ -195,6 +205,7 @@ def test_spotify_album_fetch_more():
"year": "1974",
"playlist_num": 3,
"spotify_id": "0Ssh20fuVhmasLRJ97MLnp",
+ 'tempo': 152.769,
},
{
"album": "Queen II (Deluxe Remastered Version)",
@@ -208,6 +219,7 @@ def test_spotify_album_fetch_more():
"year": "1974",
"playlist_num": 4,
"spotify_id": "2LasW39KJDE4VH9hTVNpE2",
+ 'tempo': 115.471,
},
{
"album": "Queen II (Deluxe Remastered Version)",
@@ -221,6 +233,7 @@ def test_spotify_album_fetch_more():
"year": "1974",
"playlist_num": 5,
"spotify_id": "6jXrIu3hWbmJziw34IHIwM",
+ 'tempo': 145.124,
},
{
"album": "Queen II (Deluxe Remastered Version)",
@@ -234,6 +247,7 @@ def test_spotify_album_fetch_more():
"track_url": None,
"playlist_num": 6,
"spotify_id": "5dHmGuUeRgp5f93G69tox5",
+ 'tempo': 108.544,
},
{
"album": "Queen II (Deluxe Remastered Version)",
@@ -247,6 +261,7 @@ def test_spotify_album_fetch_more():
"year": "1974",
"playlist_num": 7,
"spotify_id": "2KPj0oB7cUuHQ3FuardOII",
+ 'tempo': 159.156,
},
{
"album": "Queen II (Deluxe Remastered Version)",
@@ -260,6 +275,7 @@ def test_spotify_album_fetch_more():
"year": "1974",
"playlist_num": 8,
"spotify_id": "34CcBjL9WqEAtnl2i6Hbxa",
+ 'tempo': 118.48,
},
{
"album": "Queen II (Deluxe Remastered Version)",
@@ -273,6 +289,7 @@ def test_spotify_album_fetch_more():
"year": "1974",
"playlist_num": 9,
"spotify_id": "1x9ak6LGIazLhfuaSIEkhG",
+ 'tempo': 112.623,
},
{
"album": "Queen II (Deluxe Remastered Version)",
@@ -286,6 +303,7 @@ def test_spotify_album_fetch_more():
"year": "1974",
"playlist_num": 10,
"spotify_id": "4CITL18Tos0PscW1amCK4j",
+ 'tempo': 145.497,
},
{
"album": "Queen II (Deluxe Remastered Version)",
@@ -299,6 +317,7 @@ def test_spotify_album_fetch_more():
"year": "1974",
"playlist_num": 11,
"spotify_id": "1e9Tt3nKBwRbuaU79kN3dn",
+ 'tempo': 126.343,
},
{
"album": "Queen II (Deluxe Remastered Version)",
@@ -312,6 +331,7 @@ def test_spotify_album_fetch_more():
"year": "1974",
"playlist_num": 12,
"spotify_id": "0uHqoDT7J2TYBsJx6m4Tvi",
+ 'tempo': 172.274,
},
{
"album": "Queen II (Deluxe Remastered Version)",
@@ -325,6 +345,8 @@ def test_spotify_album_fetch_more():
"year": "1974",
"playlist_num": 13,
"spotify_id": "3MIueGYoNiyBNfi5ukDgAK",
+ 'tempo': 146.712,
+
},
{
"album": "Queen II (Deluxe Remastered Version)",
@@ -338,6 +360,7 @@ def test_spotify_album_fetch_more():
"year": "1974",
"playlist_num": 14,
"spotify_id": "34WAOFWdJ83a3YYrDAZTjm",
+ 'tempo': 128.873,
},
{
"album": "Queen II (Deluxe Remastered Version)",
@@ -351,6 +374,7 @@ def test_spotify_album_fetch_more():
"year": "1974",
"playlist_num": 15,
"spotify_id": "2AFIPUlApcUwGEgOSDwoBz",
+ 'tempo': 122.986,
},
{
"album": "Queen II (Deluxe Remastered Version)",
@@ -364,6 +388,7 @@ def test_spotify_album_fetch_more():
"year": "1974",
"playlist_num": 16,
"spotify_id": "4G4Sf18XkFvNTV5vAxiQyd",
+ 'tempo': 169.166,
},
] == songs
assert (len(songs)) == 16
@@ -387,5 +412,6 @@ def test_spotify_playlist_fetch_local_file():
"year": "",
"playlist_num": 1,
"spotify_id": None,
+ "tempo": None,
}
- ] == songs
+ ] == songs
\ No newline at end of file
diff --git a/tests/test_youtube.py b/tests/test_youtube.py
index d3c29d6..38f0f38 100644
--- a/tests/test_youtube.py
+++ b/tests/test_youtube.py
@@ -28,6 +28,7 @@ def test_download_one_false_skip():
"cover": "https://i.scdn.co/image/ab67616d0000b27396d28597a5ae44ab66552183",
"genre": "album rock",
"spotify_id": "2GpBrAoCwt48fxjgjlzMd4",
+ 'tempo': 74.656,
}
],
}
@@ -83,6 +84,7 @@ def test_download_one_true_skip():
"cover": "https://i.scdn.co/image/ab67616d0000b27396d28597a5ae44ab66552183",
"genre": "album rock",
"spotify_id": "2GpBrAoCwt48fxjgjlzMd4",
+ 'tempo': 74.656,
}
],
}
@@ -120,6 +122,7 @@ def test_download_cover_none():
"cover": None,
"genre": "classic rock",
"spotify_id": "12LhScrlYazmU4vsqpRQNI",
+ 'tempo': 159.15,
}
],
}
| Add BPM to metadata of MP3 songs.
Since adding BPM to the metadata of the MP3 is an option provided with the Spotify API and mutagen supports it as well. This feature could help with many who are in the field of DJ Mixing.
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_spotify_fetch_tracks.py::test_spotify_playlist_fetch_one",
"tests/test_spotify_fetch_tracks.py::test_spotify_playlist_fetch_more",
"tests/test_spotify_fetch_tracks.py::test_spotify_track_fetch_one",
"tests/test_spotify_fetch_tracks.py::test_spotify_album_fetch_one",
"tests/test_spotify_fetch_tracks.py::test_spotify_album_fetch_more",
"tests/test_spotify_fetch_tracks.py::test_spotify_playlist_fetch_local_file"
] | [
"tests/test_youtube.py::test_download_one_true_skip"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2023-12-30T12:03:54Z" | mit |
|
Sceptre__sceptre-1246 | diff --git a/sceptre/cli/drift.py b/sceptre/cli/drift.py
index 9aab47d..282d9b8 100644
--- a/sceptre/cli/drift.py
+++ b/sceptre/cli/drift.py
@@ -68,9 +68,12 @@ def drift_detect(ctx: Context, path: str):
@drift_group.command(name="show", short_help="Shows stack drift on running stacks.")
@click.argument("path")
[email protected](
+ "-D", "--drifted", is_flag=True, default=False, help="Filter out in sync resources."
+)
@click.pass_context
@catch_exceptions
-def drift_show(ctx, path):
+def drift_show(ctx, path, drifted):
"""
Show stack drift on deployed stacks.
@@ -92,7 +95,7 @@ def drift_show(ctx, path):
)
plan = SceptrePlan(context)
- responses = plan.drift_show()
+ responses = plan.drift_show(drifted)
output_format = "json" if context.output_format == "json" else "yaml"
@@ -100,7 +103,6 @@ def drift_show(ctx, path):
for stack, (status, response) in responses.items():
if status in BAD_STATUSES:
exit_status += 1
- response.pop("ResponseMetadata", None)
write({stack.external_name: deserialize_json_properties(response)}, output_format)
exit(exit_status)
diff --git a/sceptre/plan/actions.py b/sceptre/plan/actions.py
index 8711f0f..992a6e9 100644
--- a/sceptre/plan/actions.py
+++ b/sceptre/plan/actions.py
@@ -1039,10 +1039,11 @@ class StackActions(object):
return response
@add_stack_hooks
- def drift_show(self) -> Tuple[str, dict]:
+ def drift_show(self, drifted: bool = False) -> Tuple[str, dict]:
"""
Detect drift status on stacks.
+ :param drifted: Filter out IN_SYNC resources.
:returns: The detection status and resource drifts.
"""
response = self.drift_detect()
@@ -1055,6 +1056,7 @@ class StackActions(object):
else:
raise Exception("Not expected to be reachable")
+ response = self._filter_drifts(response, drifted)
return (detection_status, response)
def _wait_for_drift_status(self, detection_id: str) -> dict:
@@ -1144,6 +1146,24 @@ class StackActions(object):
}
)
+ def _filter_drifts(self, response: dict, drifted: bool) -> dict:
+ """
+ The filtered response after filtering out StackResourceDriftStatus.
+ :param drifted: Filter out IN_SYNC resources from CLI --drifted.
+ """
+ if "StackResourceDrifts" not in response:
+ return response
+
+ result = {"StackResourceDrifts": []}
+ include_all_drift_statuses = not drifted
+
+ for drift in response["StackResourceDrifts"]:
+ is_drifted = drift["StackResourceDriftStatus"] != "IN_SYNC"
+ if include_all_drift_statuses or is_drifted:
+ result["StackResourceDrifts"].append(drift)
+
+ return result
+
@add_stack_hooks
def dump_config(self, config_reader: ConfigReader):
"""
| Sceptre/sceptre | 45629a5530b16e7f439bd3ba2f6e68cddf551506 | diff --git a/tests/test_actions.py b/tests/test_actions.py
index 672fe4a..62d76fd 100644
--- a/tests/test_actions.py
+++ b/tests/test_actions.py
@@ -1347,14 +1347,66 @@ class TestStackActions(object):
mock_describe_stack_resource_drifts.return_value = expected_drifts
expected_response = (detection_status, expected_drifts)
- response = self.actions.drift_show()
+ response = self.actions.drift_show(drifted=False)
+
+ assert response == expected_response
+
+ @patch("sceptre.plan.actions.StackActions._describe_stack_resource_drifts")
+ @patch("sceptre.plan.actions.StackActions._describe_stack_drift_detection_status")
+ @patch("sceptre.plan.actions.StackActions._detect_stack_drift")
+ @patch("time.sleep")
+ def test_drift_show_drift_only(
+ self,
+ mock_sleep,
+ mock_detect_stack_drift,
+ mock_describe_stack_drift_detection_status,
+ mock_describe_stack_resource_drifts
+ ):
+ mock_sleep.return_value = None
+
+ mock_detect_stack_drift.return_value = {
+ "StackDriftDetectionId": "3fb76910-f660-11eb-80ac-0246f7a6da62"
+ }
+ mock_describe_stack_drift_detection_status.return_value = {
+ "StackId": "fake-stack-id",
+ "StackDriftDetectionId": "3fb76910-f660-11eb-80ac-0246f7a6da62",
+ "StackDriftStatus": "DRIFTED",
+ "DetectionStatus": "DETECTION_COMPLETE",
+ "DriftedStackResourceCount": 0
+ }
+
+ input_drifts = {
+ "StackResourceDrifts": [
+ {
+ "LogicalResourceId": "ServerLoadBalancer",
+ "PhysicalResourceId": "bi-tablea-ServerLo-1E133TWLWYLON",
+ "ResourceType": "AWS::ElasticLoadBalancing::LoadBalancer",
+ "StackId": "fake-stack-id",
+ "StackResourceDriftStatus": "IN_SYNC",
+ },
+ {
+ "LogicalResourceId": "TableauServer",
+ "PhysicalResourceId": "i-08c16bc1c5e2cd185",
+ "ResourceType": "AWS::EC2::Instance",
+ "StackId": "fake-stack-id",
+ "StackResourceDriftStatus": "DELETED",
+ }
+ ]
+ }
+ mock_describe_stack_resource_drifts.return_value = input_drifts
+
+ expected_response = ("DETECTION_COMPLETE", {
+ "StackResourceDrifts": [input_drifts["StackResourceDrifts"][1]]
+ })
+
+ response = self.actions.drift_show(drifted=True)
assert response == expected_response
@patch("sceptre.plan.actions.StackActions._get_status")
def test_drift_show_with_stack_that_does_not_exist(self, mock_get_status):
mock_get_status.side_effect = StackDoesNotExistError()
- response = self.actions.drift_show()
+ response = self.actions.drift_show(drifted=False)
assert response == (
'STACK_DOES_NOT_EXIST', {
'StackResourceDriftStatus': 'STACK_DOES_NOT_EXIST'
@@ -1408,6 +1460,6 @@ class TestStackActions(object):
mock_describe_stack_resource_drifts.return_value = expected_drifts
expected_response = ("TIMED_OUT", {"StackResourceDriftStatus": "TIMED_OUT"})
- response = self.actions.drift_show()
+ response = self.actions.drift_show(drifted=False)
assert response == expected_response
| It'd be great if `drift show` had an option to filter out IN_SYNC resources.
Right now, when `drift show` is run, it shows the drift status of all the resources in all stacks. However, this is a bit overload if you're really just trying to find drifted resources. It would be a great addition if we added a `--filter` flag that would only show resources that are not IN_SYNC. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_actions.py::TestStackActions::test_drift_show[DETECTION_COMPLETE]",
"tests/test_actions.py::TestStackActions::test_drift_show[DETECTION_FAILED]",
"tests/test_actions.py::TestStackActions::test_drift_show_drift_only",
"tests/test_actions.py::TestStackActions::test_drift_show_with_stack_that_does_not_exist",
"tests/test_actions.py::TestStackActions::test_drift_show_times_out"
] | [
"tests/test_actions.py::TestStackActions::test_template_loads_template",
"tests/test_actions.py::TestStackActions::test_template_returns_template_if_it_exists",
"tests/test_actions.py::TestStackActions::test_external_name_with_custom_stack_name",
"tests/test_actions.py::TestStackActions::test_create_sends_correct_request",
"tests/test_actions.py::TestStackActions::test_create_sends_correct_request_no_notifications",
"tests/test_actions.py::TestStackActions::test_create_sends_correct_request_with_no_failure_no_timeout",
"tests/test_actions.py::TestStackActions::test_create_stack_already_exists",
"tests/test_actions.py::TestStackActions::test_update_sends_correct_request",
"tests/test_actions.py::TestStackActions::test_update_cancels_after_timeout",
"tests/test_actions.py::TestStackActions::test_update_sends_correct_request_no_notification",
"tests/test_actions.py::TestStackActions::test_update_with_complete_stack_with_no_updates_to_perform",
"tests/test_actions.py::TestStackActions::test_cancel_update_sends_correct_request",
"tests/test_actions.py::TestStackActions::test_launch_with_stack_that_does_not_exist",
"tests/test_actions.py::TestStackActions::test_launch_with_stack_that_failed_to_create",
"tests/test_actions.py::TestStackActions::test_launch_with_complete_stack_with_updates_to_perform",
"tests/test_actions.py::TestStackActions::test_launch_with_complete_stack_with_no_updates_to_perform",
"tests/test_actions.py::TestStackActions::test_launch_with_complete_stack_with_unknown_client_error",
"tests/test_actions.py::TestStackActions::test_launch_with_in_progress_stack",
"tests/test_actions.py::TestStackActions::test_launch_with_failed_stack",
"tests/test_actions.py::TestStackActions::test_launch_with_unknown_stack_status",
"tests/test_actions.py::TestStackActions::test_delete_with_created_stack",
"tests/test_actions.py::TestStackActions::test_delete_when_wait_for_completion_raises_stack_does_not_exist_error",
"tests/test_actions.py::TestStackActions::test_delete_when_wait_for_completion_raises_non_existent_client_error",
"tests/test_actions.py::TestStackActions::test_delete_when_wait_for_completion_raises_unexpected_client_error",
"tests/test_actions.py::TestStackActions::test_delete_with_non_existent_stack",
"tests/test_actions.py::TestStackActions::test_describe_stack_sends_correct_request",
"tests/test_actions.py::TestStackActions::test_describe_events_sends_correct_request",
"tests/test_actions.py::TestStackActions::test_describe_resources_sends_correct_request",
"tests/test_actions.py::TestStackActions::test_describe_outputs_sends_correct_request",
"tests/test_actions.py::TestStackActions::test_describe_outputs_handles_stack_with_no_outputs",
"tests/test_actions.py::TestStackActions::test_continue_update_rollback_sends_correct_request",
"tests/test_actions.py::TestStackActions::test_set_stack_policy_sends_correct_request",
"tests/test_actions.py::TestStackActions::test_get_stack_policy_sends_correct_request",
"tests/test_actions.py::TestStackActions::test_create_change_set_sends_correct_request",
"tests/test_actions.py::TestStackActions::test_create_change_set_sends_correct_request_no_notifications",
"tests/test_actions.py::TestStackActions::test_delete_change_set_sends_correct_request",
"tests/test_actions.py::TestStackActions::test_describe_change_set_sends_correct_request",
"tests/test_actions.py::TestStackActions::test_execute_change_set_sends_correct_request",
"tests/test_actions.py::TestStackActions::test_execute_change_set__change_set_is_failed_for_no_changes__returns_0",
"tests/test_actions.py::TestStackActions::test_execute_change_set__change_set_is_failed_for_no_updates__returns_0",
"tests/test_actions.py::TestStackActions::test_list_change_sets_sends_correct_request",
"tests/test_actions.py::TestStackActions::test_list_change_sets",
"tests/test_actions.py::TestStackActions::test_list_change_sets_url_mode",
"tests/test_actions.py::TestStackActions::test_list_change_sets_empty[True]",
"tests/test_actions.py::TestStackActions::test_list_change_sets_empty[False]",
"tests/test_actions.py::TestStackActions::test_lock_calls_set_stack_policy_with_policy",
"tests/test_actions.py::TestStackActions::test_unlock_calls_set_stack_policy_with_policy",
"tests/test_actions.py::TestStackActions::test_format_parameters_with_sting_values",
"tests/test_actions.py::TestStackActions::test_format_parameters_with_none_values",
"tests/test_actions.py::TestStackActions::test_format_parameters_with_none_and_string_values",
"tests/test_actions.py::TestStackActions::test_format_parameters_with_list_values",
"tests/test_actions.py::TestStackActions::test_format_parameters_with_none_and_list_values",
"tests/test_actions.py::TestStackActions::test_format_parameters_with_list_and_string_values",
"tests/test_actions.py::TestStackActions::test_format_parameters_with_none_list_and_string_values",
"tests/test_actions.py::TestStackActions::test_get_status_with_created_stack",
"tests/test_actions.py::TestStackActions::test_get_status_with_non_existent_stack",
"tests/test_actions.py::TestStackActions::test_get_status_with_unknown_clinet_error",
"tests/test_actions.py::TestStackActions::test_get_role_arn_without_role",
"tests/test_actions.py::TestStackActions::test_get_role_arn_with_role",
"tests/test_actions.py::TestStackActions::test_protect_execution_without_protection",
"tests/test_actions.py::TestStackActions::test_protect_execution_without_explicit_protection",
"tests/test_actions.py::TestStackActions::test_protect_execution_with_protection",
"tests/test_actions.py::TestStackActions::test_wait_for_completion_calls_log_new_events",
"tests/test_actions.py::TestStackActions::test_get_simplified_status_with_known_stack_statuses[ROLLBACK_COMPLETE-failed]",
"tests/test_actions.py::TestStackActions::test_get_simplified_status_with_known_stack_statuses[STACK_COMPLETE-complete]",
"tests/test_actions.py::TestStackActions::test_get_simplified_status_with_known_stack_statuses[STACK_IN_PROGRESS-in",
"tests/test_actions.py::TestStackActions::test_get_simplified_status_with_known_stack_statuses[STACK_FAILED-failed]",
"tests/test_actions.py::TestStackActions::test_get_simplified_status_with_stack_in_unknown_state",
"tests/test_actions.py::TestStackActions::test_log_new_events_calls_describe_events",
"tests/test_actions.py::TestStackActions::test_log_new_events_prints_correct_event",
"tests/test_actions.py::TestStackActions::test_wait_for_cs_completion_calls_get_cs_status",
"tests/test_actions.py::TestStackActions::test_get_cs_status_handles_all_statuses",
"tests/test_actions.py::TestStackActions::test_get_cs_status_raises_unexpected_exceptions",
"tests/test_actions.py::TestStackActions::test_fetch_remote_template__cloudformation_returns_validation_error__returns_none",
"tests/test_actions.py::TestStackActions::test_fetch_remote_template__calls_cloudformation_get_template",
"tests/test_actions.py::TestStackActions::test_fetch_remote_template__dict_template__returns_json",
"tests/test_actions.py::TestStackActions::test_fetch_remote_template__cloudformation_returns_string_template__returns_that_string",
"tests/test_actions.py::TestStackActions::test_fetch_remote_template_summary__calls_cloudformation_get_template_summary",
"tests/test_actions.py::TestStackActions::test_fetch_remote_template_summary__returns_response_from_cloudformation",
"tests/test_actions.py::TestStackActions::test_fetch_local_template_summary__calls_cloudformation_get_template_summary",
"tests/test_actions.py::TestStackActions::test_fetch_local_template_summary__returns_response_from_cloudformation",
"tests/test_actions.py::TestStackActions::test_fetch_local_template_summary__cloudformation_returns_validation_error_invalid_stack__raises_it",
"tests/test_actions.py::TestStackActions::test_fetch_remote_template_summary__cloudformation_returns_validation_error_for_no_stack__returns_none",
"tests/test_actions.py::TestStackActions::test_diff__invokes_diff_method_on_injected_differ_with_self",
"tests/test_actions.py::TestStackActions::test_diff__returns_result_of_injected_differs_diff_method",
"tests/test_actions.py::TestStackActions::test_drift_detect"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2022-07-18T20:08:58Z" | apache-2.0 |
|
Sceptre__sceptre-1248 | diff --git a/sceptre/cli/drift.py b/sceptre/cli/drift.py
index 9aab47d..282d9b8 100644
--- a/sceptre/cli/drift.py
+++ b/sceptre/cli/drift.py
@@ -68,9 +68,12 @@ def drift_detect(ctx: Context, path: str):
@drift_group.command(name="show", short_help="Shows stack drift on running stacks.")
@click.argument("path")
[email protected](
+ "-D", "--drifted", is_flag=True, default=False, help="Filter out in sync resources."
+)
@click.pass_context
@catch_exceptions
-def drift_show(ctx, path):
+def drift_show(ctx, path, drifted):
"""
Show stack drift on deployed stacks.
@@ -92,7 +95,7 @@ def drift_show(ctx, path):
)
plan = SceptrePlan(context)
- responses = plan.drift_show()
+ responses = plan.drift_show(drifted)
output_format = "json" if context.output_format == "json" else "yaml"
@@ -100,7 +103,6 @@ def drift_show(ctx, path):
for stack, (status, response) in responses.items():
if status in BAD_STATUSES:
exit_status += 1
- response.pop("ResponseMetadata", None)
write({stack.external_name: deserialize_json_properties(response)}, output_format)
exit(exit_status)
diff --git a/sceptre/cli/helpers.py b/sceptre/cli/helpers.py
index 5d680d9..5f48da8 100644
--- a/sceptre/cli/helpers.py
+++ b/sceptre/cli/helpers.py
@@ -216,7 +216,7 @@ def setup_vars(var_file, var, merge_vars, debug, no_colour):
if var_file:
for fh in var_file:
- parsed = yaml.safe_load(fh.read())
+ parsed = yaml.safe_load(fh.read()) or {}
if merge_vars:
return_value = _deep_merge(parsed, return_value)
diff --git a/sceptre/plan/actions.py b/sceptre/plan/actions.py
index 8711f0f..992a6e9 100644
--- a/sceptre/plan/actions.py
+++ b/sceptre/plan/actions.py
@@ -1039,10 +1039,11 @@ class StackActions(object):
return response
@add_stack_hooks
- def drift_show(self) -> Tuple[str, dict]:
+ def drift_show(self, drifted: bool = False) -> Tuple[str, dict]:
"""
Detect drift status on stacks.
+ :param drifted: Filter out IN_SYNC resources.
:returns: The detection status and resource drifts.
"""
response = self.drift_detect()
@@ -1055,6 +1056,7 @@ class StackActions(object):
else:
raise Exception("Not expected to be reachable")
+ response = self._filter_drifts(response, drifted)
return (detection_status, response)
def _wait_for_drift_status(self, detection_id: str) -> dict:
@@ -1144,6 +1146,24 @@ class StackActions(object):
}
)
+ def _filter_drifts(self, response: dict, drifted: bool) -> dict:
+ """
+ The filtered response after filtering out StackResourceDriftStatus.
+ :param drifted: Filter out IN_SYNC resources from CLI --drifted.
+ """
+ if "StackResourceDrifts" not in response:
+ return response
+
+ result = {"StackResourceDrifts": []}
+ include_all_drift_statuses = not drifted
+
+ for drift in response["StackResourceDrifts"]:
+ is_drifted = drift["StackResourceDriftStatus"] != "IN_SYNC"
+ if include_all_drift_statuses or is_drifted:
+ result["StackResourceDrifts"].append(drift)
+
+ return result
+
@add_stack_hooks
def dump_config(self, config_reader: ConfigReader):
"""
| Sceptre/sceptre | 45629a5530b16e7f439bd3ba2f6e68cddf551506 | diff --git a/tests/test_actions.py b/tests/test_actions.py
index 672fe4a..62d76fd 100644
--- a/tests/test_actions.py
+++ b/tests/test_actions.py
@@ -1347,14 +1347,66 @@ class TestStackActions(object):
mock_describe_stack_resource_drifts.return_value = expected_drifts
expected_response = (detection_status, expected_drifts)
- response = self.actions.drift_show()
+ response = self.actions.drift_show(drifted=False)
+
+ assert response == expected_response
+
+ @patch("sceptre.plan.actions.StackActions._describe_stack_resource_drifts")
+ @patch("sceptre.plan.actions.StackActions._describe_stack_drift_detection_status")
+ @patch("sceptre.plan.actions.StackActions._detect_stack_drift")
+ @patch("time.sleep")
+ def test_drift_show_drift_only(
+ self,
+ mock_sleep,
+ mock_detect_stack_drift,
+ mock_describe_stack_drift_detection_status,
+ mock_describe_stack_resource_drifts
+ ):
+ mock_sleep.return_value = None
+
+ mock_detect_stack_drift.return_value = {
+ "StackDriftDetectionId": "3fb76910-f660-11eb-80ac-0246f7a6da62"
+ }
+ mock_describe_stack_drift_detection_status.return_value = {
+ "StackId": "fake-stack-id",
+ "StackDriftDetectionId": "3fb76910-f660-11eb-80ac-0246f7a6da62",
+ "StackDriftStatus": "DRIFTED",
+ "DetectionStatus": "DETECTION_COMPLETE",
+ "DriftedStackResourceCount": 0
+ }
+
+ input_drifts = {
+ "StackResourceDrifts": [
+ {
+ "LogicalResourceId": "ServerLoadBalancer",
+ "PhysicalResourceId": "bi-tablea-ServerLo-1E133TWLWYLON",
+ "ResourceType": "AWS::ElasticLoadBalancing::LoadBalancer",
+ "StackId": "fake-stack-id",
+ "StackResourceDriftStatus": "IN_SYNC",
+ },
+ {
+ "LogicalResourceId": "TableauServer",
+ "PhysicalResourceId": "i-08c16bc1c5e2cd185",
+ "ResourceType": "AWS::EC2::Instance",
+ "StackId": "fake-stack-id",
+ "StackResourceDriftStatus": "DELETED",
+ }
+ ]
+ }
+ mock_describe_stack_resource_drifts.return_value = input_drifts
+
+ expected_response = ("DETECTION_COMPLETE", {
+ "StackResourceDrifts": [input_drifts["StackResourceDrifts"][1]]
+ })
+
+ response = self.actions.drift_show(drifted=True)
assert response == expected_response
@patch("sceptre.plan.actions.StackActions._get_status")
def test_drift_show_with_stack_that_does_not_exist(self, mock_get_status):
mock_get_status.side_effect = StackDoesNotExistError()
- response = self.actions.drift_show()
+ response = self.actions.drift_show(drifted=False)
assert response == (
'STACK_DOES_NOT_EXIST', {
'StackResourceDriftStatus': 'STACK_DOES_NOT_EXIST'
@@ -1408,6 +1460,6 @@ class TestStackActions(object):
mock_describe_stack_resource_drifts.return_value = expected_drifts
expected_response = ("TIMED_OUT", {"StackResourceDriftStatus": "TIMED_OUT"})
- response = self.actions.drift_show()
+ response = self.actions.drift_show(drifted=False)
assert response == expected_response
| An empty var file causes Sceptre to blow up
### Subject of the issue
If an empty var file is passed to Sceptre, Sceptre raises an exception
### Your environment
* version of sceptre (sceptre --version) 3.0.0
* version of python (python --version) 3.8.10
* which OS/distro Ubuntu
### Steps to reproduce
```
> common-env.yaml
sceptre --var-file=common-env.yaml config/stack.yaml
```
### Expected behaviour
It should validate stack.yaml.
### Actual behaviour
```
Traceback (most recent call last):
File "/usr/local/bin/sceptre", line 8, in <module>
sys.exit(cli())
File "/usr/local/lib/python3.8/site-packages/click/core.py", line 829, in __call__
return self.main(*args, **kwargs)
File "/usr/local/lib/python3.8/site-packages/click/core.py", line 782, in main
rv = self.invoke(ctx)
File "/usr/local/lib/python3.8/site-packages/click/core.py", line 1256, in invoke
Command.invoke(self, ctx)
File "/usr/local/lib/python3.8/site-packages/click/core.py", line 1066, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/usr/local/lib/python3.8/site-packages/click/core.py", line 610, in invoke
return callback(*args, **kwargs)
File "/usr/local/lib/python3.8/site-packages/click/decorators.py", line 21, in new_func
return f(get_current_context(), *args, **kwargs)
File "/usr/local/lib/python3.8/site-packages/sceptre/cli/helpers.py", line 42, in decorated
return func(*args, **kwargs)
File "/usr/local/lib/python3.8/site-packages/sceptre/cli/__init__.py", line 69, in cli
"user_variables": setup_vars(var_file, var, merge_vars, debug, no_colour),
File "/usr/local/lib/python3.8/site-packages/sceptre/cli/helpers.py", line 224, in setup_vars
return_value.update(parsed)
TypeError: 'NoneType' object is not iterable
```
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_actions.py::TestStackActions::test_drift_show[DETECTION_COMPLETE]",
"tests/test_actions.py::TestStackActions::test_drift_show[DETECTION_FAILED]",
"tests/test_actions.py::TestStackActions::test_drift_show_drift_only",
"tests/test_actions.py::TestStackActions::test_drift_show_with_stack_that_does_not_exist",
"tests/test_actions.py::TestStackActions::test_drift_show_times_out"
] | [
"tests/test_actions.py::TestStackActions::test_template_loads_template",
"tests/test_actions.py::TestStackActions::test_template_returns_template_if_it_exists",
"tests/test_actions.py::TestStackActions::test_external_name_with_custom_stack_name",
"tests/test_actions.py::TestStackActions::test_create_sends_correct_request",
"tests/test_actions.py::TestStackActions::test_create_sends_correct_request_no_notifications",
"tests/test_actions.py::TestStackActions::test_create_sends_correct_request_with_no_failure_no_timeout",
"tests/test_actions.py::TestStackActions::test_create_stack_already_exists",
"tests/test_actions.py::TestStackActions::test_update_sends_correct_request",
"tests/test_actions.py::TestStackActions::test_update_cancels_after_timeout",
"tests/test_actions.py::TestStackActions::test_update_sends_correct_request_no_notification",
"tests/test_actions.py::TestStackActions::test_update_with_complete_stack_with_no_updates_to_perform",
"tests/test_actions.py::TestStackActions::test_cancel_update_sends_correct_request",
"tests/test_actions.py::TestStackActions::test_launch_with_stack_that_does_not_exist",
"tests/test_actions.py::TestStackActions::test_launch_with_stack_that_failed_to_create",
"tests/test_actions.py::TestStackActions::test_launch_with_complete_stack_with_updates_to_perform",
"tests/test_actions.py::TestStackActions::test_launch_with_complete_stack_with_no_updates_to_perform",
"tests/test_actions.py::TestStackActions::test_launch_with_complete_stack_with_unknown_client_error",
"tests/test_actions.py::TestStackActions::test_launch_with_in_progress_stack",
"tests/test_actions.py::TestStackActions::test_launch_with_failed_stack",
"tests/test_actions.py::TestStackActions::test_launch_with_unknown_stack_status",
"tests/test_actions.py::TestStackActions::test_delete_with_created_stack",
"tests/test_actions.py::TestStackActions::test_delete_when_wait_for_completion_raises_stack_does_not_exist_error",
"tests/test_actions.py::TestStackActions::test_delete_when_wait_for_completion_raises_non_existent_client_error",
"tests/test_actions.py::TestStackActions::test_delete_when_wait_for_completion_raises_unexpected_client_error",
"tests/test_actions.py::TestStackActions::test_delete_with_non_existent_stack",
"tests/test_actions.py::TestStackActions::test_describe_stack_sends_correct_request",
"tests/test_actions.py::TestStackActions::test_describe_events_sends_correct_request",
"tests/test_actions.py::TestStackActions::test_describe_resources_sends_correct_request",
"tests/test_actions.py::TestStackActions::test_describe_outputs_sends_correct_request",
"tests/test_actions.py::TestStackActions::test_describe_outputs_handles_stack_with_no_outputs",
"tests/test_actions.py::TestStackActions::test_continue_update_rollback_sends_correct_request",
"tests/test_actions.py::TestStackActions::test_set_stack_policy_sends_correct_request",
"tests/test_actions.py::TestStackActions::test_get_stack_policy_sends_correct_request",
"tests/test_actions.py::TestStackActions::test_create_change_set_sends_correct_request",
"tests/test_actions.py::TestStackActions::test_create_change_set_sends_correct_request_no_notifications",
"tests/test_actions.py::TestStackActions::test_delete_change_set_sends_correct_request",
"tests/test_actions.py::TestStackActions::test_describe_change_set_sends_correct_request",
"tests/test_actions.py::TestStackActions::test_execute_change_set_sends_correct_request",
"tests/test_actions.py::TestStackActions::test_execute_change_set__change_set_is_failed_for_no_changes__returns_0",
"tests/test_actions.py::TestStackActions::test_execute_change_set__change_set_is_failed_for_no_updates__returns_0",
"tests/test_actions.py::TestStackActions::test_list_change_sets_sends_correct_request",
"tests/test_actions.py::TestStackActions::test_list_change_sets",
"tests/test_actions.py::TestStackActions::test_list_change_sets_url_mode",
"tests/test_actions.py::TestStackActions::test_list_change_sets_empty[True]",
"tests/test_actions.py::TestStackActions::test_list_change_sets_empty[False]",
"tests/test_actions.py::TestStackActions::test_lock_calls_set_stack_policy_with_policy",
"tests/test_actions.py::TestStackActions::test_unlock_calls_set_stack_policy_with_policy",
"tests/test_actions.py::TestStackActions::test_format_parameters_with_sting_values",
"tests/test_actions.py::TestStackActions::test_format_parameters_with_none_values",
"tests/test_actions.py::TestStackActions::test_format_parameters_with_none_and_string_values",
"tests/test_actions.py::TestStackActions::test_format_parameters_with_list_values",
"tests/test_actions.py::TestStackActions::test_format_parameters_with_none_and_list_values",
"tests/test_actions.py::TestStackActions::test_format_parameters_with_list_and_string_values",
"tests/test_actions.py::TestStackActions::test_format_parameters_with_none_list_and_string_values",
"tests/test_actions.py::TestStackActions::test_get_status_with_created_stack",
"tests/test_actions.py::TestStackActions::test_get_status_with_non_existent_stack",
"tests/test_actions.py::TestStackActions::test_get_status_with_unknown_clinet_error",
"tests/test_actions.py::TestStackActions::test_get_role_arn_without_role",
"tests/test_actions.py::TestStackActions::test_get_role_arn_with_role",
"tests/test_actions.py::TestStackActions::test_protect_execution_without_protection",
"tests/test_actions.py::TestStackActions::test_protect_execution_without_explicit_protection",
"tests/test_actions.py::TestStackActions::test_protect_execution_with_protection",
"tests/test_actions.py::TestStackActions::test_wait_for_completion_calls_log_new_events",
"tests/test_actions.py::TestStackActions::test_get_simplified_status_with_known_stack_statuses[ROLLBACK_COMPLETE-failed]",
"tests/test_actions.py::TestStackActions::test_get_simplified_status_with_known_stack_statuses[STACK_COMPLETE-complete]",
"tests/test_actions.py::TestStackActions::test_get_simplified_status_with_known_stack_statuses[STACK_IN_PROGRESS-in",
"tests/test_actions.py::TestStackActions::test_get_simplified_status_with_known_stack_statuses[STACK_FAILED-failed]",
"tests/test_actions.py::TestStackActions::test_get_simplified_status_with_stack_in_unknown_state",
"tests/test_actions.py::TestStackActions::test_log_new_events_calls_describe_events",
"tests/test_actions.py::TestStackActions::test_log_new_events_prints_correct_event",
"tests/test_actions.py::TestStackActions::test_wait_for_cs_completion_calls_get_cs_status",
"tests/test_actions.py::TestStackActions::test_get_cs_status_handles_all_statuses",
"tests/test_actions.py::TestStackActions::test_get_cs_status_raises_unexpected_exceptions",
"tests/test_actions.py::TestStackActions::test_fetch_remote_template__cloudformation_returns_validation_error__returns_none",
"tests/test_actions.py::TestStackActions::test_fetch_remote_template__calls_cloudformation_get_template",
"tests/test_actions.py::TestStackActions::test_fetch_remote_template__dict_template__returns_json",
"tests/test_actions.py::TestStackActions::test_fetch_remote_template__cloudformation_returns_string_template__returns_that_string",
"tests/test_actions.py::TestStackActions::test_fetch_remote_template_summary__calls_cloudformation_get_template_summary",
"tests/test_actions.py::TestStackActions::test_fetch_remote_template_summary__returns_response_from_cloudformation",
"tests/test_actions.py::TestStackActions::test_fetch_local_template_summary__calls_cloudformation_get_template_summary",
"tests/test_actions.py::TestStackActions::test_fetch_local_template_summary__returns_response_from_cloudformation",
"tests/test_actions.py::TestStackActions::test_fetch_local_template_summary__cloudformation_returns_validation_error_invalid_stack__raises_it",
"tests/test_actions.py::TestStackActions::test_fetch_remote_template_summary__cloudformation_returns_validation_error_for_no_stack__returns_none",
"tests/test_actions.py::TestStackActions::test_diff__invokes_diff_method_on_injected_differ_with_self",
"tests/test_actions.py::TestStackActions::test_diff__returns_result_of_injected_differs_diff_method",
"tests/test_actions.py::TestStackActions::test_drift_detect"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2022-07-21T16:59:45Z" | apache-2.0 |
|
Sceptre__sceptre-1249 | diff --git a/sceptre/resolvers/__init__.py b/sceptre/resolvers/__init__.py
index 5dde952..1515d61 100644
--- a/sceptre/resolvers/__init__.py
+++ b/sceptre/resolvers/__init__.py
@@ -238,8 +238,19 @@ class ResolvableContainerProperty(ResolvableProperty):
resolve, container, Resolver
)
# Remove keys and indexes from their containers that had resolvers resolve to None.
+ list_items_to_delete = []
for attr, key in keys_to_delete:
- del attr[key]
+ if isinstance(attr, list):
+ # If it's a list, we want to gather up the items to remove from the list.
+ # We don't want to modify the list length yet.
+ # Since removals will change all the other list indexes,
+ # we don't wan't to modify lists yet.
+ list_items_to_delete.append((attr, attr[key]))
+ else:
+ del attr[key]
+
+ for containing_list, item in list_items_to_delete:
+ containing_list.remove(item)
return container
| Sceptre/sceptre | 880fba9bd11e5167adfee0167608aede2439228a | diff --git a/tests/test_resolvers/test_resolver.py b/tests/test_resolvers/test_resolver.py
index e7fc553..48c2507 100644
--- a/tests/test_resolvers/test_resolver.py
+++ b/tests/test_resolvers/test_resolver.py
@@ -341,6 +341,42 @@ class TestResolvableContainerPropertyDescriptor:
'resolver': 'stack1'
}
+ def test_get__resolver_resolves_to_none__value_is_dict__deletes_those_items_from_dict(self):
+ class MyResolver(Resolver):
+ def resolve(self):
+ return None
+
+ resolver = MyResolver()
+ self.mock_object.resolvable_container_property = {
+ 'a': 4,
+ 'b': resolver,
+ 'c': 3,
+ 'd': resolver,
+ 'e': resolver,
+ 'f': 5,
+ }
+ expected = {'a': 4, 'c': 3, 'f': 5}
+ assert self.mock_object.resolvable_container_property == expected
+
+ def test_get__resolver_resolves_to_none__value_is_dict__deletes_those_items_from_complex_structure(self):
+ class MyResolver(Resolver):
+ def resolve(self):
+ return None
+
+ resolver = MyResolver()
+ self.mock_object.resolvable_container_property = {
+ 'a': 4,
+ 'b': [
+ resolver,
+ ],
+ 'c': [{
+ 'v': resolver
+ }],
+ 'd': 3
+ }
+ expected = {'a': 4, 'b': [], 'c': [{}], 'd': 3}
+ assert self.mock_object.resolvable_container_property == expected
+
def test_get__resolver_resolves_to_none__value_is_list__deletes_that_item_from_list(self):
class MyResolver(Resolver):
def resolve(self):
@@ -368,6 +404,39 @@ class TestResolvableContainerPropertyDescriptor:
expected = {'some key': 'some value'}
assert self.mock_object.resolvable_container_property == expected
+ def test_get__resolvers_resolves_to_none__value_is_list__deletes_those_items_from_list(self):
+ class MyResolver(Resolver):
+ def resolve(self):
+ return None
+
+ resolver = MyResolver()
+
+ self.mock_object.resolvable_container_property = [
+ 1,
+ resolver,
+ 3,
+ resolver,
+ resolver,
+ 6
+ ]
+ expected = [1, 3, 6]
+ assert self.mock_object.resolvable_container_property == expected
+
+ def test_get__resolvers_resolves_to_none__value_is_list__deletes_all_items_from_list(self):
+ class MyResolver(Resolver):
+ def resolve(self):
+ return None
+
+ resolver = MyResolver()
+
+ self.mock_object.resolvable_container_property = [
+ resolver,
+ resolver,
+ resolver
+ ]
+ expected = []
+ assert self.mock_object.resolvable_container_property == expected
+
def test_get__value_in_list_is_none__returns_list_with_none(self):
self.mock_object.resolvable_container_property = [
1,
| Sceptre fails when multiple resolvers return None
### Sceptre fails when multiple resolvers return None
When multiple resolvers in a stack config return None sceptre fails.
### Your environment
* version of sceptre (3.1.0)
* version of python (3.8.10)
* which OS/distro -- windows 10, linux
### Steps to reproduce
```
sceptre_user_data:
some_structure:
abc0: !resolver1
abc1: !resolver2
abc3: !resolver3
```
### Expected behaviour
Variables in the stack should get None (the actual values that the resolvers returned)
### Actual behaviour
sceptre fails with
```
Traceback (most recent call last):
File "scripts/render-templates.py", line 73, in main
for stack, template_body in plan.generate().items():
File "C:\Users\ykhalyavin\venv\cfn\lib\site-packages\sceptre\plan\plan.py", line 351, in generate
return self._execute(*args)
File "C:\Users\ykhalyavin\venv\cfn\lib\site-packages\sceptre\plan\plan.py", line 43, in _execute
return executor.execute(*args)
File "C:\Users\ykhalyavin\venv\cfn\lib\site-packages\sceptre\plan\executor.py", line 55, in execute
stack, status = future.result()
File "C:\Users\ykhalyavin\AppData\Local\Programs\Python\Python38\lib\concurrent\futures\_base.py", line 432, in result
return self.__get_result()
File "C:\Users\ykhalyavin\AppData\Local\Programs\Python\Python38\lib\concurrent\futures\_base.py", line 388, in __get_result
raise self._exception
File "C:\Users\ykhalyavin\AppData\Local\Programs\Python\Python38\lib\concurrent\futures\thread.py", line 57, in run
result = self.fn(*self.args, **self.kwargs)
File "C:\Users\ykhalyavin\venv\cfn\lib\site-packages\sceptre\plan\executor.py", line 62, in _execute
result = getattr(actions, self.command)(*args)
File "C:\Users\ykhalyavin\venv\cfn\lib\site-packages\sceptre\hooks\__init__.py", line 104, in decorated
response = func(self, *args, **kwargs)
File "C:\Users\ykhalyavin\venv\cfn\lib\site-packages\sceptre\plan\actions.py", line 634, in generate
return self.stack.template.body
File "C:\Users\ykhalyavin\venv\cfn\lib\site-packages\sceptre\stack.py", line 352, in template
sceptre_user_data=self.sceptre_user_data,
File "C:\Users\ykhalyavin\venv\cfn\lib\site-packages\sceptre\resolvers\__init__.py", line 191, in __get__
container = super().__get__(stack, stack_class)
File "C:\Users\ykhalyavin\venv\cfn\lib\site-packages\sceptre\resolvers\__init__.py", line 93, in __get__
return self.get_resolved_value(stack, stack_class)
File "C:\Users\ykhalyavin\venv\cfn\lib\site-packages\sceptre\resolvers\__init__.py", line 245, in get_resolved_value
del attr[key]
IndexError: list assignment index out of rangeTraceback (most recent call last):
```
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_resolvers/test_resolver.py::TestResolvableContainerPropertyDescriptor::test_get__resolvers_resolves_to_none__value_is_list__deletes_those_items_from_list",
"tests/test_resolvers/test_resolver.py::TestResolvableContainerPropertyDescriptor::test_get__resolvers_resolves_to_none__value_is_list__deletes_all_items_from_list"
] | [
"tests/test_resolvers/test_resolver.py::TestResolver::test_init",
"tests/test_resolvers/test_resolver.py::TestResolvableContainerPropertyDescriptor::test_setting_resolvable_property_with_none",
"tests/test_resolvers/test_resolver.py::TestResolvableContainerPropertyDescriptor::test_setting_resolvable_property_with_nested_lists",
"tests/test_resolvers/test_resolver.py::TestResolvableContainerPropertyDescriptor::test_getting_resolvable_property_with_none",
"tests/test_resolvers/test_resolver.py::TestResolvableContainerPropertyDescriptor::test_getting_resolvable_property_with_nested_lists",
"tests/test_resolvers/test_resolver.py::TestResolvableContainerPropertyDescriptor::test_getting_resolvable_property_with_nested_dictionaries_and_lists",
"tests/test_resolvers/test_resolver.py::TestResolvableContainerPropertyDescriptor::test_getting_resolvable_property_with_nested_dictionaries",
"tests/test_resolvers/test_resolver.py::TestResolvableContainerPropertyDescriptor::test_get__resolver_references_same_property_for_other_value__resolves_it",
"tests/test_resolvers/test_resolver.py::TestResolvableContainerPropertyDescriptor::test_get__resolver_references_itself__raises_recursive_resolve",
"tests/test_resolvers/test_resolver.py::TestResolvableContainerPropertyDescriptor::test_get__resolvable_container_property_references_same_property_of_other_stack__resolves",
"tests/test_resolvers/test_resolver.py::TestResolvableContainerPropertyDescriptor::test_get__resolver_resolves_to_none__value_is_dict__deletes_those_items_from_dict",
"tests/test_resolvers/test_resolver.py::TestResolvableContainerPropertyDescriptor::test_get__resolver_resolves_to_none__value_is_dict__deletes_those_items_from_complex_structure",
"tests/test_resolvers/test_resolver.py::TestResolvableContainerPropertyDescriptor::test_get__resolver_resolves_to_none__value_is_list__deletes_that_item_from_list",
"tests/test_resolvers/test_resolver.py::TestResolvableContainerPropertyDescriptor::test_get__resolver_resolves_to_none__value_is_dict__deletes_that_key_from_dict",
"tests/test_resolvers/test_resolver.py::TestResolvableContainerPropertyDescriptor::test_get__value_in_list_is_none__returns_list_with_none",
"tests/test_resolvers/test_resolver.py::TestResolvableContainerPropertyDescriptor::test_get__value_in_dict_is_none__returns_dict_with_none",
"tests/test_resolvers/test_resolver.py::TestResolvableContainerPropertyDescriptor::test_get__resolver_raises_error__placeholders_allowed__returns_placeholder",
"tests/test_resolvers/test_resolver.py::TestResolvableContainerPropertyDescriptor::test_get__resolver_raises_error__placeholders_not_allowed__raises_error",
"tests/test_resolvers/test_resolver.py::TestResolvableContainerPropertyDescriptor::test_get__resolver_raises_recursive_resolve__placeholders_allowed__raises_error",
"tests/test_resolvers/test_resolver.py::TestResolvableContainerPropertyDescriptor::test_get__resolver_raises_error__placeholders_allowed__alternate_placeholder_type__uses_alternate",
"tests/test_resolvers/test_resolver.py::TestResolvableValueProperty::test_set__non_resolver__sets_private_variable_as_value[string]",
"tests/test_resolvers/test_resolver.py::TestResolvableValueProperty::test_set__non_resolver__sets_private_variable_as_value[True]",
"tests/test_resolvers/test_resolver.py::TestResolvableValueProperty::test_set__non_resolver__sets_private_variable_as_value[123]",
"tests/test_resolvers/test_resolver.py::TestResolvableValueProperty::test_set__non_resolver__sets_private_variable_as_value[1.23]",
"tests/test_resolvers/test_resolver.py::TestResolvableValueProperty::test_set__non_resolver__sets_private_variable_as_value[None]",
"tests/test_resolvers/test_resolver.py::TestResolvableValueProperty::test_set__resolver__sets_private_variable_with_clone_of_resolver_with_instance",
"tests/test_resolvers/test_resolver.py::TestResolvableValueProperty::test_set__resolver__sets_up_cloned_resolver",
"tests/test_resolvers/test_resolver.py::TestResolvableValueProperty::test_get__non_resolver__returns_value[string]",
"tests/test_resolvers/test_resolver.py::TestResolvableValueProperty::test_get__non_resolver__returns_value[True]",
"tests/test_resolvers/test_resolver.py::TestResolvableValueProperty::test_get__non_resolver__returns_value[123]",
"tests/test_resolvers/test_resolver.py::TestResolvableValueProperty::test_get__non_resolver__returns_value[1.23]",
"tests/test_resolvers/test_resolver.py::TestResolvableValueProperty::test_get__non_resolver__returns_value[None]",
"tests/test_resolvers/test_resolver.py::TestResolvableValueProperty::test_get__resolver__returns_resolved_value",
"tests/test_resolvers/test_resolver.py::TestResolvableValueProperty::test_get__resolver__updates_set_value_with_resolved_value",
"tests/test_resolvers/test_resolver.py::TestResolvableValueProperty::test_get__resolver__resolver_attempts_to_access_resolver__raises_recursive_resolve",
"tests/test_resolvers/test_resolver.py::TestResolvableValueProperty::test_get__resolvable_value_property_references_same_property_of_other_stack__resolves",
"tests/test_resolvers/test_resolver.py::TestResolvableValueProperty::test_get__resolver_raises_error__placeholders_allowed__returns_placeholder",
"tests/test_resolvers/test_resolver.py::TestResolvableValueProperty::test_get__resolver_raises_error__placeholders_not_allowed__raises_error",
"tests/test_resolvers/test_resolver.py::TestResolvableValueProperty::test_get__resolver_raises_recursive_resolve__placeholders_allowed__raises_error",
"tests/test_resolvers/test_resolver.py::TestResolvableValueProperty::test_get__resolver_raises_error__placeholders_allowed__alternate_placeholder_type__uses_alternate_type"
] | {
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
} | "2022-07-22T15:10:39Z" | apache-2.0 |
|
Sceptre__sceptre-1260 | diff --git a/sceptre/cli/diff.py b/sceptre/cli/diff.py
index a7f2697..4a723c8 100644
--- a/sceptre/cli/diff.py
+++ b/sceptre/cli/diff.py
@@ -8,7 +8,7 @@ from click import Context
from sceptre.cli.helpers import catch_exceptions
from sceptre.context import SceptreContext
-from sceptre.diffing.diff_writer import DeepDiffWriter, DiffLibWriter, DiffWriter
+from sceptre.diffing.diff_writer import DeepDiffWriter, DiffLibWriter, ColouredDiffLibWriter, DiffWriter
from sceptre.diffing.stack_differ import DeepDiffStackDiffer, DifflibStackDiffer, StackDiff
from sceptre.helpers import null_context
from sceptre.plan.plan import SceptrePlan
@@ -95,14 +95,16 @@ def diff_command(
Particularly in cases where the replaced value doesn't work in the template as the template logic
requires and causes an error, there is nothing further Sceptre can do and diffing will fail.
"""
+ no_colour = ctx.obj.get("no_colour")
+
context = SceptreContext(
command_path=path,
project_path=ctx.obj.get("project_path"),
user_variables=ctx.obj.get("user_variables"),
options=ctx.obj.get("options"),
ignore_dependencies=ctx.obj.get("ignore_dependencies"),
- output_format=ctx.obj.get('output_format'),
- no_colour=ctx.obj.get('no_colour')
+ output_format=ctx.obj.get("output_format"),
+ no_colour=no_colour
)
output_format = context.output_format
plan = SceptrePlan(context)
@@ -112,9 +114,9 @@ def diff_command(
if differ == "deepdiff":
stack_differ = DeepDiffStackDiffer(show_no_echo)
writer_class = DeepDiffWriter
- elif differ == 'difflib':
+ elif differ == "difflib":
stack_differ = DifflibStackDiffer(show_no_echo)
- writer_class = DiffLibWriter
+ writer_class = DiffLibWriter if no_colour else ColouredDiffLibWriter
else:
raise ValueError(f"Unexpected differ type: {differ}")
diff --git a/sceptre/diffing/diff_writer.py b/sceptre/diffing/diff_writer.py
index d4c79d3..8d2d672 100644
--- a/sceptre/diffing/diff_writer.py
+++ b/sceptre/diffing/diff_writer.py
@@ -3,6 +3,7 @@ import json
import re
from abc import abstractmethod
from typing import TextIO, Generic, List
+from colorama import Fore
import cfn_flip
import yaml
@@ -207,3 +208,22 @@ class DiffLibWriter(DiffWriter[List[str]]):
# Difflib doesn't care about the output format since it only outputs strings. We would have
# accounted for the output format in the differ itself rather than here.
return '\n'.join(diff)
+
+
+class ColouredDiffLibWriter(DiffLibWriter):
+ """A DiffWriter for StackDiffs where the DiffType is a a list of strings with coloured diffs."""
+
+ def _colour_diff(self, diff: List[str]):
+ for line in diff:
+ if line.startswith('+'):
+ yield Fore.GREEN + line + Fore.RESET
+ elif line.startswith('-'):
+ yield Fore.RED + line + Fore.RESET
+ elif line.startswith('^'):
+ yield Fore.BLUE + line + Fore.RESET
+ else:
+ yield line
+
+ def dump_diff(self, diff: List[str]) -> str:
+ coloured_diff = self._colour_diff(diff)
+ return super().dump_diff(coloured_diff)
| Sceptre/sceptre | b67fe16600d2c62481e59c03418418445e1d7e28 | diff --git a/tests/test_diffing/test_diff_writer.py b/tests/test_diffing/test_diff_writer.py
index 41c4679..769a2f5 100644
--- a/tests/test_diffing/test_diff_writer.py
+++ b/tests/test_diffing/test_diff_writer.py
@@ -9,8 +9,10 @@ import pytest
import yaml
from deepdiff import DeepDiff
-from sceptre.diffing.diff_writer import DiffWriter, DeepDiffWriter, deepdiff_json_defaults, DiffLibWriter
+from sceptre.diffing.diff_writer import DiffWriter, DeepDiffWriter, deepdiff_json_defaults, \
+ DiffLibWriter, ColouredDiffLibWriter
from sceptre.diffing.stack_differ import StackDiff, DiffType, StackConfiguration
+from colorama import Fore
class ImplementedDiffWriter(DiffWriter):
@@ -368,3 +370,74 @@ class TestDiffLibWriter:
result = self.writer.dump_diff(self.diff.config_diff)
expected = '\n'.join(self.diff.config_diff)
assert result == expected
+
+
+class TestColouredDiffLibWriter:
+ def setup_method(self, method):
+ self.stack_name = 'stack'
+
+ self.is_deployed = True
+ self.output_format = 'yaml'
+
+ self.output_stream = StringIO()
+
+ self.config1 = StackConfiguration(
+ stack_name=self.stack_name,
+ parameters={},
+ stack_tags={},
+ notifications=[],
+ role_arn=None
+ )
+
+ self.template1 = "foo"
+
+ @property
+ def template_diff(self):
+ return [
+ '--- file1.txt 2018-01-11 10:39:38.237464052 +0000\n',
+ '+++ file2.txt 2018-01-11 10:40:00.323423021 +0000\n',
+ '@@ -1,4 +1,4 @@\n',
+ ' cat\n',
+ '-mv\n',
+ '-comm\n',
+ ' cp\n',
+ '+diff\n',
+ '+comm\n'
+ ]
+
+ @property
+ def config_diff(self):
+ return []
+
+ @property
+ def diff(self):
+ return StackDiff(
+ self.stack_name,
+ self.template_diff,
+ self.config_diff,
+ self.is_deployed,
+ self.config1,
+ self.template1
+ )
+
+ @property
+ def writer(self):
+ return ColouredDiffLibWriter(
+ self.diff,
+ self.output_stream,
+ self.output_format
+ )
+
+ def test_lines_are_coloured(self):
+ coloured = (
+ f'{Fore.RED}--- file1.txt 2018-01-11 10:39:38.237464052 +0000\n{Fore.RESET}\n'
+ f"{Fore.GREEN}+++ file2.txt 2018-01-11 10:40:00.323423021 +0000\n{Fore.RESET}\n"
+ '@@ -1,4 +1,4 @@\n\n'
+ " cat\n\n"
+ f'{Fore.RED}-mv\n{Fore.RESET}\n'
+ f"{Fore.RED}-comm\n{Fore.RESET}\n"
+ ' cp\n\n'
+ f"{Fore.GREEN}+diff\n{Fore.RESET}\n"
+ f'{Fore.GREEN}+comm\n{Fore.RESET}'
+ )
+ assert self.writer.dump_diff(self.template_diff) == coloured
| Add coloured diffs
### Subject of the issue
Sceptre's diff output is a useful tool but many us are probably feeding its output into `colordiff` in order to make its diffs more readable. A feature that colours that diffs and can be disabled via `--no-color` is needed.
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_diffing/test_diff_writer.py::TestDiffWriter::test_write__no_difference__writes_no_difference",
"tests/test_diffing/test_diff_writer.py::TestDiffWriter::test_write__new_stack__writes_new_stack_config_and_template[output",
"tests/test_diffing/test_diff_writer.py::TestDiffWriter::test_write__only_config_is_different__writes_config_difference",
"tests/test_diffing/test_diff_writer.py::TestDiffWriter::test_write__only_template_is_different__writes_template_difference",
"tests/test_diffing/test_diff_writer.py::TestDiffWriter::test_write__config_and_template_are_different__writes_both_differences",
"tests/test_diffing/test_diff_writer.py::TestDeepDiffWriter::test_has_config_difference__config_difference_is_present__returns_true",
"tests/test_diffing/test_diff_writer.py::TestDeepDiffWriter::test_has_config_difference__config_difference_is_absent__returns_false",
"tests/test_diffing/test_diff_writer.py::TestDeepDiffWriter::test_has_template_difference__template_difference_is_present__returns_true",
"tests/test_diffing/test_diff_writer.py::TestDeepDiffWriter::test_has_template_difference__template_difference_is_absent__returns_false",
"tests/test_diffing/test_diff_writer.py::TestDeepDiffWriter::test_dump_diff__output_format_is_json__outputs_to_json",
"tests/test_diffing/test_diff_writer.py::TestDeepDiffWriter::test_dump_diff__output_format_is_yaml__outputs_to_yaml",
"tests/test_diffing/test_diff_writer.py::TestDeepDiffWriter::test_dump_diff__output_format_is_text__outputs_to_yaml",
"tests/test_diffing/test_diff_writer.py::TestDeepDiffWriter::test_dump_diff__output_format_is_yaml__diff_has_multiline_strings__strips_out_extra_spaces",
"tests/test_diffing/test_diff_writer.py::TestDiffLibWriter::test_has_config_difference__config_difference_is_present__returns_true",
"tests/test_diffing/test_diff_writer.py::TestDiffLibWriter::test_has_config_difference__config_difference_is_absent__returns_false",
"tests/test_diffing/test_diff_writer.py::TestDiffLibWriter::test_has_template_difference__template_difference_is_present__returns_true",
"tests/test_diffing/test_diff_writer.py::TestDiffLibWriter::test_has_template_difference__template_difference_is_absent__returns_false",
"tests/test_diffing/test_diff_writer.py::TestDiffLibWriter::test_dump_diff__returns_joined_list",
"tests/test_diffing/test_diff_writer.py::TestColouredDiffLibWriter::test_lines_are_coloured"
] | [] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2022-11-09T11:20:58Z" | apache-2.0 |
|
Sceptre__sceptre-1275 | diff --git a/sceptre/helpers.py b/sceptre/helpers.py
index d0bcc25..0ca370e 100644
--- a/sceptre/helpers.py
+++ b/sceptre/helpers.py
@@ -1,6 +1,10 @@
# -*- coding: utf-8 -*-
from contextlib import contextmanager
+from datetime import datetime
from os import sep
+from typing import Optional
+
+import dateutil.parser
from sceptre.exceptions import PathConversionError
@@ -117,3 +121,20 @@ def null_context():
available in py3.6, so providing it here instead.
"""
yield
+
+
+def extract_datetime_from_aws_response_headers(boto_response: dict) -> Optional[datetime]:
+ """Returns a datetime.datetime extracted from the response metadata in a
+ boto response or None if it's unable to find or parse one.
+ :param boto_response: A dictionary returned from a boto client call
+ :returns a datetime.datetime or None
+ """
+ if boto_response is None:
+ return None
+ try:
+ return dateutil.parser.parse(boto_response["ResponseMetadata"]["HTTPHeaders"]["date"])
+ except (KeyError, dateutil.parser.ParserError):
+ # We expect a KeyError if the date isn't present in the response. We
+ # expect a ParserError if it's not well-formed. Any other error we want
+ # to pass along.
+ return None
diff --git a/sceptre/plan/actions.py b/sceptre/plan/actions.py
index 1576e1d..147de60 100644
--- a/sceptre/plan/actions.py
+++ b/sceptre/plan/actions.py
@@ -14,21 +14,19 @@ import typing
import urllib
from datetime import datetime, timedelta
from os import path
-from typing import Union, Optional, Tuple, Dict
+from typing import Dict, Optional, Tuple, Union
import botocore
from dateutil.tz import tzutc
from sceptre.config.reader import ConfigReader
from sceptre.connection_manager import ConnectionManager
-from sceptre.exceptions import (
- CannotUpdateFailedStackError,
- ProtectedStackError,
- StackDoesNotExistError,
- UnknownStackChangeSetStatusError,
- UnknownStackStatusError
-)
-from sceptre.helpers import normalise_path
+from sceptre.exceptions import (CannotUpdateFailedStackError,
+ ProtectedStackError, StackDoesNotExistError,
+ UnknownStackChangeSetStatusError,
+ UnknownStackStatusError)
+from sceptre.helpers import (extract_datetime_from_aws_response_headers,
+ normalise_path)
from sceptre.hooks import add_stack_hooks
from sceptre.stack import Stack
from sceptre.stack_status import StackChangeSetStatus, StackStatus
@@ -95,7 +93,7 @@ class StackActions(object):
"%s - Create stack response: %s", self.stack.name, response
)
- status = self._wait_for_completion()
+ status = self._wait_for_completion(boto_response=response)
except botocore.exceptions.ClientError as exp:
if exp.response["Error"]["Code"] == "AlreadyExistsException":
self.logger.info(
@@ -141,7 +139,7 @@ class StackActions(object):
command="update_stack",
kwargs=update_stack_kwargs
)
- status = self._wait_for_completion(self.stack.stack_timeout)
+ status = self._wait_for_completion(self.stack.stack_timeout, boto_response=response)
self.logger.debug(
"%s - Update Stack response: %s", self.stack.name, response
)
@@ -180,7 +178,7 @@ class StackActions(object):
self.logger.debug(
"%s - Cancel update Stack response: %s", self.stack.name, response
)
- return self._wait_for_completion()
+ return self._wait_for_completion(boto_response=response)
@add_stack_hooks
def launch(self) -> StackStatus:
@@ -251,14 +249,14 @@ class StackActions(object):
delete_stack_kwargs = {"StackName": self.stack.external_name}
delete_stack_kwargs.update(self._get_role_arn())
- self.connection_manager.call(
+ response = self.connection_manager.call(
service="cloudformation",
command="delete_stack",
kwargs=delete_stack_kwargs
)
try:
- status = self._wait_for_completion()
+ status = self._wait_for_completion(boto_response=response)
except StackDoesNotExistError:
status = StackStatus.COMPLETE
except botocore.exceptions.ClientError as error:
@@ -549,7 +547,7 @@ class StackActions(object):
self.logger.debug(
"%s - Executing Change Set '%s'", self.stack.name, change_set_name
)
- self.connection_manager.call(
+ response = self.connection_manager.call(
service="cloudformation",
command="execute_change_set",
kwargs={
@@ -557,8 +555,7 @@ class StackActions(object):
"StackName": self.stack.external_name
}
)
-
- status = self._wait_for_completion()
+ status = self._wait_for_completion(boto_response=response)
return status
def change_set_creation_failed_due_to_no_changes(self, reason: str) -> bool:
@@ -767,15 +764,15 @@ class StackActions(object):
"currently enabled".format(self.stack.name)
)
- def _wait_for_completion(self, timeout=0):
+ def _wait_for_completion(self, timeout=0, boto_response: Optional[dict] = None) -> StackStatus:
"""
Waits for a Stack operation to finish. Prints CloudFormation events
while it waits.
:param timeout: Timeout before returning, in minutes.
+ :param boto_response: Response from the boto call which initiated the stack change.
:returns: The final Stack status.
- :rtype: sceptre.stack_status.StackStatus
"""
timeout = 60 * timeout
@@ -784,13 +781,14 @@ class StackActions(object):
status = StackStatus.IN_PROGRESS
- self.most_recent_event_datetime = (
- datetime.now(tzutc()) - timedelta(seconds=3)
- )
+ most_recent_event_datetime = extract_datetime_from_aws_response_headers(
+ boto_response
+ ) or (datetime.now(tzutc()) - timedelta(seconds=3))
+
elapsed = 0
while status == StackStatus.IN_PROGRESS and not timed_out(elapsed):
status = self._get_simplified_status(self._get_status())
- self._log_new_events()
+ most_recent_event_datetime = self._log_new_events(most_recent_event_datetime)
time.sleep(4)
elapsed += 4
@@ -843,15 +841,18 @@ class StackActions(object):
"{0} is unknown".format(status)
)
- def _log_new_events(self):
+ def _log_new_events(self, after_datetime: datetime) -> datetime:
"""
Log the latest Stack events while the Stack is being built.
+
+ :param after_datetime: Only events after this datetime will be logged.
+ :returns: The datetime of the last logged event or after_datetime if no events were logged.
"""
events = self.describe_events()["StackEvents"]
events.reverse()
new_events = [
event for event in events
- if event["Timestamp"] > self.most_recent_event_datetime
+ if event["Timestamp"] > after_datetime
]
for event in new_events:
self.logger.info(" ".join([
@@ -861,7 +862,8 @@ class StackActions(object):
event["ResourceStatus"],
event.get("ResourceStatusReason", "")
]))
- self.most_recent_event_datetime = event["Timestamp"]
+ after_datetime = event["Timestamp"]
+ return after_datetime
def wait_for_cs_completion(self, change_set_name):
"""
| Sceptre/sceptre | b73af2f341ff3b7b9ca4192858b69732fb26f195 | diff --git a/tests/test_actions.py b/tests/test_actions.py
index 3b3b5d1..611a902 100644
--- a/tests/test_actions.py
+++ b/tests/test_actions.py
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
import datetime
import json
-from unittest.mock import patch, sentinel, Mock, call
+from unittest.mock import patch, sentinel, Mock, call, ANY
import pytest
from botocore.exceptions import ClientError
@@ -127,7 +127,7 @@ class TestStackActions(object):
"TimeoutInMinutes": sentinel.timeout
}
)
- mock_wait_for_completion.assert_called_once_with()
+ mock_wait_for_completion.assert_called_once_with(boto_response=ANY)
@patch("sceptre.plan.actions.StackActions._wait_for_completion")
def test_create_sends_correct_request_no_notifications(
@@ -162,7 +162,7 @@ class TestStackActions(object):
"TimeoutInMinutes": sentinel.stack_timeout
}
)
- mock_wait_for_completion.assert_called_once_with()
+ mock_wait_for_completion.assert_called_once_with(boto_response=ANY)
@patch("sceptre.plan.actions.StackActions._wait_for_completion")
def test_create_sends_correct_request_with_no_failure_no_timeout(
@@ -194,7 +194,8 @@ class TestStackActions(object):
]
}
)
- mock_wait_for_completion.assert_called_once_with()
+
+ mock_wait_for_completion.assert_called_once_with(boto_response=ANY)
@patch("sceptre.plan.actions.StackActions._wait_for_completion")
def test_create_stack_already_exists(
@@ -245,7 +246,8 @@ class TestStackActions(object):
}
)
mock_wait_for_completion.assert_called_once_with(
- sentinel.stack_timeout
+ sentinel.stack_timeout,
+ boto_response=ANY
)
@patch("sceptre.plan.actions.StackActions._wait_for_completion")
@@ -284,7 +286,7 @@ class TestStackActions(object):
]
self.actions.connection_manager.call.assert_has_calls(calls)
mock_wait_for_completion.assert_has_calls(
- [call(sentinel.stack_timeout), call()]
+ [call(sentinel.stack_timeout, boto_response=ANY), call(boto_response=ANY)]
)
@patch("sceptre.plan.actions.StackActions._wait_for_completion")
@@ -319,7 +321,8 @@ class TestStackActions(object):
}
)
mock_wait_for_completion.assert_called_once_with(
- sentinel.stack_timeout
+ sentinel.stack_timeout,
+ boto_response=ANY
)
@patch("sceptre.plan.actions.StackActions._wait_for_completion")
@@ -352,7 +355,7 @@ class TestStackActions(object):
command="cancel_update_stack",
kwargs={"StackName": sentinel.external_name}
)
- mock_wait_for_completion.assert_called_once_with()
+ mock_wait_for_completion.assert_called_once_with(boto_response=ANY)
@patch("sceptre.plan.actions.StackActions.create")
@patch("sceptre.plan.actions.StackActions._get_status")
@@ -707,7 +710,7 @@ class TestStackActions(object):
"StackName": sentinel.external_name
}
)
- mock_wait_for_completion.assert_called_once_with()
+ mock_wait_for_completion.assert_called_once_with(boto_response=ANY)
def test_execute_change_set__change_set_is_failed_for_no_changes__returns_0(self):
def fake_describe(service, command, kwargs):
@@ -994,7 +997,8 @@ class TestStackActions(object):
mock_get_simplified_status.return_value = StackStatus.COMPLETE
self.actions._wait_for_completion()
- mock_log_new_events.assert_called_once_with()
+ mock_log_new_events.assert_called_once()
+ assert type(mock_log_new_events.mock_calls[0].args[0]) is datetime.datetime
@pytest.mark.parametrize("test_input,expected", [
("ROLLBACK_COMPLETE", StackStatus.FAILED),
@@ -1017,7 +1021,7 @@ class TestStackActions(object):
mock_describe_events.return_value = {
"StackEvents": []
}
- self.actions._log_new_events()
+ self.actions._log_new_events(datetime.datetime.utcnow())
self.actions.describe_events.assert_called_once_with()
@patch("sceptre.plan.actions.StackActions.describe_events")
@@ -1044,10 +1048,7 @@ class TestStackActions(object):
}
]
}
- self.actions.most_recent_event_datetime = (
- datetime.datetime(2016, 3, 15, 14, 0, 0, 0, tzinfo=tzutc())
- )
- self.actions._log_new_events()
+ self.actions._log_new_events(datetime.datetime(2016, 3, 15, 14, 0, 0, 0, tzinfo=tzutc()))
@patch("sceptre.plan.actions.StackActions._get_cs_status")
def test_wait_for_cs_completion_calls_get_cs_status(
diff --git a/tests/test_helpers.py b/tests/test_helpers.py
index fafdaec..5b8c2c6 100644
--- a/tests/test_helpers.py
+++ b/tests/test_helpers.py
@@ -3,11 +3,13 @@
import pytest
from os.path import join, sep
+from datetime import datetime, timezone, timedelta
from sceptre.exceptions import PathConversionError
from sceptre.helpers import get_external_stack_name
from sceptre.helpers import normalise_path
from sceptre.helpers import sceptreise_path
+from sceptre.helpers import extract_datetime_from_aws_response_headers
class TestHelpers(object):
@@ -67,3 +69,34 @@ class TestHelpers(object):
sceptreise_path(
'this\\path\\is\\invalid\\'
)
+
+ def test_get_response_datetime__response_is_valid__returns_datetime(self):
+ resp = {
+ "ResponseMetadata": {
+ "HTTPHeaders": {"date": "Wed, 16 Oct 2019 07:28:00 GMT"}
+ }
+ }
+ assert extract_datetime_from_aws_response_headers(resp) == datetime(2019, 10, 16, 7, 28, tzinfo=timezone.utc)
+
+ def test_get_response_datetime__response_has_offset__returns_datetime(self):
+ resp = {
+ "ResponseMetadata": {
+ "HTTPHeaders": {"date": "Wed, 16 Oct 2019 07:28:00 +0400"}
+ }
+ }
+ offset = timezone(timedelta(hours=4))
+ assert extract_datetime_from_aws_response_headers(resp) == datetime(2019, 10, 16, 7, 28, tzinfo=offset)
+
+ def test_get_response_datetime__date_string_is_invalid__returns_none(self):
+ resp = {
+ "ResponseMetadata": {
+ "HTTPHeaders": {"date": "garbage"}
+ }
+ }
+ assert extract_datetime_from_aws_response_headers(resp) is None
+
+ def test_get_response_datetime__response_is_empty__returns_none(self):
+ assert extract_datetime_from_aws_response_headers({}) is None
+
+ def test_get_response_datetime__response_is_none__returns_none(self):
+ assert extract_datetime_from_aws_response_headers(None) is None
| Events missing from launch output
### Events missing from launch output
At some point after updating to Sceptre 3 events which appear in the web console are not included in the command output. It seems like if the stack update lasts long enough events will start to appear as they used to. If the stack launch is short then the command simply exits without feedback. This includes launch failures and roll-backs.
### Your environment
* Sceptre, version 3.2.0
* Python 3.9.9
* Official Python 3.9.9 Docker image
### Steps to reproduce
```$ sceptre launch -y <stack>```
This has been consistent across several accounts and versions of Sceptre. I've not yet identified which version the problem appears in.
### Expected behaviour
After the `Updating Stack` message we expect to see a number of resource state-change events and end with the final state of the stack.
### Actual behaviour
The process completes successfully, but events which appear in the web console are not output at the terminal:
```
$ sceptre launch -y prod/alb-internal.yaml
[2022-12-11 15:37:23] - prod/alb-internal - Launching Stack
[2022-12-11 15:37:24] - prod/alb-internal - Stack is in the UPDATE_COMPLETE state
[2022-12-11 15:37:24] - prod/alb-internal - Updating Stack
$
``` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_actions.py::TestStackActions::test_template_loads_template",
"tests/test_actions.py::TestStackActions::test_template_returns_template_if_it_exists",
"tests/test_actions.py::TestStackActions::test_external_name_with_custom_stack_name",
"tests/test_actions.py::TestStackActions::test_create_sends_correct_request",
"tests/test_actions.py::TestStackActions::test_create_sends_correct_request_no_notifications",
"tests/test_actions.py::TestStackActions::test_create_sends_correct_request_with_no_failure_no_timeout",
"tests/test_actions.py::TestStackActions::test_create_stack_already_exists",
"tests/test_actions.py::TestStackActions::test_update_sends_correct_request",
"tests/test_actions.py::TestStackActions::test_update_cancels_after_timeout",
"tests/test_actions.py::TestStackActions::test_update_sends_correct_request_no_notification",
"tests/test_actions.py::TestStackActions::test_update_with_complete_stack_with_no_updates_to_perform",
"tests/test_actions.py::TestStackActions::test_cancel_update_sends_correct_request",
"tests/test_actions.py::TestStackActions::test_launch_with_stack_that_does_not_exist",
"tests/test_actions.py::TestStackActions::test_launch_with_stack_that_failed_to_create",
"tests/test_actions.py::TestStackActions::test_launch_with_complete_stack_with_updates_to_perform",
"tests/test_actions.py::TestStackActions::test_launch_with_complete_stack_with_no_updates_to_perform",
"tests/test_actions.py::TestStackActions::test_launch_with_complete_stack_with_unknown_client_error",
"tests/test_actions.py::TestStackActions::test_launch_with_in_progress_stack",
"tests/test_actions.py::TestStackActions::test_launch_with_failed_stack",
"tests/test_actions.py::TestStackActions::test_launch_with_unknown_stack_status",
"tests/test_actions.py::TestStackActions::test_delete_with_created_stack",
"tests/test_actions.py::TestStackActions::test_delete_when_wait_for_completion_raises_stack_does_not_exist_error",
"tests/test_actions.py::TestStackActions::test_delete_when_wait_for_completion_raises_non_existent_client_error",
"tests/test_actions.py::TestStackActions::test_delete_when_wait_for_completion_raises_unexpected_client_error",
"tests/test_actions.py::TestStackActions::test_delete_with_non_existent_stack",
"tests/test_actions.py::TestStackActions::test_describe_stack_sends_correct_request",
"tests/test_actions.py::TestStackActions::test_describe_events_sends_correct_request",
"tests/test_actions.py::TestStackActions::test_describe_resources_sends_correct_request",
"tests/test_actions.py::TestStackActions::test_describe_outputs_sends_correct_request",
"tests/test_actions.py::TestStackActions::test_describe_outputs_handles_stack_with_no_outputs",
"tests/test_actions.py::TestStackActions::test_continue_update_rollback_sends_correct_request",
"tests/test_actions.py::TestStackActions::test_set_stack_policy_sends_correct_request",
"tests/test_actions.py::TestStackActions::test_get_stack_policy_sends_correct_request",
"tests/test_actions.py::TestStackActions::test_create_change_set_sends_correct_request",
"tests/test_actions.py::TestStackActions::test_create_change_set_sends_correct_request_no_notifications",
"tests/test_actions.py::TestStackActions::test_delete_change_set_sends_correct_request",
"tests/test_actions.py::TestStackActions::test_describe_change_set_sends_correct_request",
"tests/test_actions.py::TestStackActions::test_execute_change_set_sends_correct_request",
"tests/test_actions.py::TestStackActions::test_execute_change_set__change_set_is_failed_for_no_changes__returns_0",
"tests/test_actions.py::TestStackActions::test_execute_change_set__change_set_is_failed_for_no_updates__returns_0",
"tests/test_actions.py::TestStackActions::test_list_change_sets_sends_correct_request",
"tests/test_actions.py::TestStackActions::test_list_change_sets",
"tests/test_actions.py::TestStackActions::test_list_change_sets_url_mode",
"tests/test_actions.py::TestStackActions::test_list_change_sets_empty[True]",
"tests/test_actions.py::TestStackActions::test_list_change_sets_empty[False]",
"tests/test_actions.py::TestStackActions::test_lock_calls_set_stack_policy_with_policy",
"tests/test_actions.py::TestStackActions::test_unlock_calls_set_stack_policy_with_policy",
"tests/test_actions.py::TestStackActions::test_format_parameters_with_sting_values",
"tests/test_actions.py::TestStackActions::test_format_parameters_with_none_values",
"tests/test_actions.py::TestStackActions::test_format_parameters_with_none_and_string_values",
"tests/test_actions.py::TestStackActions::test_format_parameters_with_list_values",
"tests/test_actions.py::TestStackActions::test_format_parameters_with_none_and_list_values",
"tests/test_actions.py::TestStackActions::test_format_parameters_with_list_and_string_values",
"tests/test_actions.py::TestStackActions::test_format_parameters_with_none_list_and_string_values",
"tests/test_actions.py::TestStackActions::test_get_status_with_created_stack",
"tests/test_actions.py::TestStackActions::test_get_status_with_non_existent_stack",
"tests/test_actions.py::TestStackActions::test_get_status_with_unknown_clinet_error",
"tests/test_actions.py::TestStackActions::test_get_role_arn_without_role",
"tests/test_actions.py::TestStackActions::test_get_role_arn_with_role",
"tests/test_actions.py::TestStackActions::test_protect_execution_without_protection",
"tests/test_actions.py::TestStackActions::test_protect_execution_without_explicit_protection",
"tests/test_actions.py::TestStackActions::test_protect_execution_with_protection",
"tests/test_actions.py::TestStackActions::test_wait_for_completion_calls_log_new_events",
"tests/test_actions.py::TestStackActions::test_get_simplified_status_with_known_stack_statuses[ROLLBACK_COMPLETE-failed]",
"tests/test_actions.py::TestStackActions::test_get_simplified_status_with_known_stack_statuses[STACK_COMPLETE-complete]",
"tests/test_actions.py::TestStackActions::test_get_simplified_status_with_known_stack_statuses[STACK_IN_PROGRESS-in",
"tests/test_actions.py::TestStackActions::test_get_simplified_status_with_known_stack_statuses[STACK_FAILED-failed]",
"tests/test_actions.py::TestStackActions::test_get_simplified_status_with_stack_in_unknown_state",
"tests/test_actions.py::TestStackActions::test_log_new_events_calls_describe_events",
"tests/test_actions.py::TestStackActions::test_log_new_events_prints_correct_event",
"tests/test_actions.py::TestStackActions::test_wait_for_cs_completion_calls_get_cs_status",
"tests/test_actions.py::TestStackActions::test_get_cs_status_handles_all_statuses",
"tests/test_actions.py::TestStackActions::test_get_cs_status_raises_unexpected_exceptions",
"tests/test_actions.py::TestStackActions::test_fetch_remote_template__cloudformation_returns_validation_error__returns_none",
"tests/test_actions.py::TestStackActions::test_fetch_remote_template__calls_cloudformation_get_template",
"tests/test_actions.py::TestStackActions::test_fetch_remote_template__dict_template__returns_json",
"tests/test_actions.py::TestStackActions::test_fetch_remote_template__cloudformation_returns_string_template__returns_that_string",
"tests/test_actions.py::TestStackActions::test_fetch_remote_template_summary__calls_cloudformation_get_template_summary",
"tests/test_actions.py::TestStackActions::test_fetch_remote_template_summary__returns_response_from_cloudformation",
"tests/test_actions.py::TestStackActions::test_fetch_local_template_summary__calls_cloudformation_get_template_summary",
"tests/test_actions.py::TestStackActions::test_fetch_local_template_summary__returns_response_from_cloudformation",
"tests/test_actions.py::TestStackActions::test_fetch_local_template_summary__cloudformation_returns_validation_error_invalid_stack__raises_it",
"tests/test_actions.py::TestStackActions::test_fetch_remote_template_summary__cloudformation_returns_validation_error_for_no_stack__returns_none",
"tests/test_actions.py::TestStackActions::test_diff__invokes_diff_method_on_injected_differ_with_self",
"tests/test_actions.py::TestStackActions::test_diff__returns_result_of_injected_differs_diff_method",
"tests/test_actions.py::TestStackActions::test_drift_detect",
"tests/test_actions.py::TestStackActions::test_drift_show[DETECTION_COMPLETE]",
"tests/test_actions.py::TestStackActions::test_drift_show[DETECTION_FAILED]",
"tests/test_actions.py::TestStackActions::test_drift_show_drift_only",
"tests/test_actions.py::TestStackActions::test_drift_show_with_stack_that_does_not_exist",
"tests/test_actions.py::TestStackActions::test_drift_show_times_out",
"tests/test_helpers.py::TestHelpers::test_get_external_stack_name",
"tests/test_helpers.py::TestHelpers::test_normalise_path_with_valid_path",
"tests/test_helpers.py::TestHelpers::test_normalise_path_with_backslashes_in_path",
"tests/test_helpers.py::TestHelpers::test_normalise_path_with_double_backslashes_in_path",
"tests/test_helpers.py::TestHelpers::test_normalise_path_with_leading_slash",
"tests/test_helpers.py::TestHelpers::test_normalise_path_with_leading_backslash",
"tests/test_helpers.py::TestHelpers::test_normalise_path_with_trailing_slash",
"tests/test_helpers.py::TestHelpers::test_normalise_path_with_trailing_backslash",
"tests/test_helpers.py::TestHelpers::test_sceptreise_path_with_valid_path",
"tests/test_helpers.py::TestHelpers::test_sceptreise_path_with_windows_path",
"tests/test_helpers.py::TestHelpers::test_sceptreise_path_with_trailing_slash",
"tests/test_helpers.py::TestHelpers::test_sceptreise_path_with_trailing_backslash",
"tests/test_helpers.py::TestHelpers::test_get_response_datetime__response_is_valid__returns_datetime",
"tests/test_helpers.py::TestHelpers::test_get_response_datetime__response_has_offset__returns_datetime",
"tests/test_helpers.py::TestHelpers::test_get_response_datetime__date_string_is_invalid__returns_none",
"tests/test_helpers.py::TestHelpers::test_get_response_datetime__response_is_empty__returns_none",
"tests/test_helpers.py::TestHelpers::test_get_response_datetime__response_is_none__returns_none"
] | [] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2022-12-11T20:36:30Z" | apache-2.0 |
|
Sceptre__sceptre-1277 | diff --git a/sceptre/template_handlers/http.py b/sceptre/template_handlers/http.py
index 31ac126..983e228 100644
--- a/sceptre/template_handlers/http.py
+++ b/sceptre/template_handlers/http.py
@@ -1,15 +1,15 @@
# -*- coding: utf-8 -*-
import pathlib
-import requests
import tempfile
-import sceptre.template_handlers.helper as helper
+from urllib.parse import urlparse
+import requests
from requests.adapters import HTTPAdapter
-from requests.exceptions import InvalidURL, ConnectTimeout
from requests.packages.urllib3.util.retry import Retry
+
+import sceptre.template_handlers.helper as helper
from sceptre.exceptions import UnsupportedTemplateFileTypeError
from sceptre.template_handlers import TemplateHandler
-from urllib.parse import urlparse
HANDLER_OPTION_KEY = "http_template_handler"
HANDLER_RETRIES_OPTION_PARAM = "retries"
@@ -77,23 +77,22 @@ class Http(TemplateHandler):
return template
- def _get_template(self, url, retries, timeout):
+ def _get_template(self, url: str, retries: int, timeout: int) -> str:
"""
Get template from the web
:param url: The url to the template
- :type: str
:param retries: The number of retry attempts.
- :rtype: int
:param timeout: The timeout for the session in seconds.
- :rtype: int
+ :raises: :class:`requests.exceptions.HTTPError`: When a download error occurs
"""
self.logger.debug("Downloading file from: %s", url)
session = self._get_retry_session(retries=retries)
- try:
- response = session.get(url, timeout=timeout)
- return response.content
- except (InvalidURL, ConnectTimeout) as e:
- raise e
+ response = session.get(url, timeout=timeout)
+
+ # If the response was unsuccessful, raise an error.
+ response.raise_for_status()
+
+ return response.content
def _get_retry_session(self,
retries,
| Sceptre/sceptre | ebe7c25295b5dcf5da8aef3bcc050623f5641d7b | diff --git a/tests/test_template_handlers/test_http.py b/tests/test_template_handlers/test_http.py
index 5db89ec..8947ec6 100644
--- a/tests/test_template_handlers/test_http.py
+++ b/tests/test_template_handlers/test_http.py
@@ -1,11 +1,12 @@
# -*- coding: utf-8 -*-
import json
+from unittest.mock import patch
import pytest
+from requests.exceptions import HTTPError
from sceptre.exceptions import UnsupportedTemplateFileTypeError
from sceptre.template_handlers.http import Http
-from unittest.mock import patch
class TestHttp(object):
@@ -20,6 +21,16 @@ class TestHttp(object):
result = template_handler.handle()
assert result == b"Stuff is working"
+ def test_get_template__request_error__raises_error(self, requests_mock):
+ url = "https://raw.githubusercontent.com/acme/bucket.yaml"
+ requests_mock.get(url, content=b"Error message", status_code=404)
+ template_handler = Http(
+ name="vpc",
+ arguments={"url": url},
+ )
+ with pytest.raises(HTTPError):
+ template_handler.handle()
+
def test_handler_unsupported_type(self):
handler = Http("http_handler", {'url': 'https://raw.githubusercontent.com/acme/bucket.unsupported'})
with pytest.raises(UnsupportedTemplateFileTypeError):
| Better error handling with invalid templates
### Subject of the issue
The template handler does not provide a helpful message when sceptre cannot resolve a template from an http source. It would be nice to improve the error handling for that.
### Your environment
* version of sceptre: 3.1
* version of python: 3.9
* which OS/distro: MAC OSX
### Steps to reproduce
1. Create a sceptre config and reference a non-existing template using the http template handler
contents of `dev/my-template.yaml`:
```
template:
type: http
url: https://my-bucket.s3.amazonaws.com/templates/my-template.yaml
stack_name: my-stack
```
2. run `sceptre launch dev`
get the following message..
```
"An error occurred (ValidationError) when calling the UpdateStack operation: Template format error: unsupported structure."
```
3. run `sceptre launch dev/mytemplate.yaml` will output the following message..
```
---
<?xml version="1.0" encoding="UTF-8"?>
<Error><Code>NoSuchKey</Code><Message>The specified key does not exist.</Message><Key>templates/my-template.yaml</Key><RequestId>YSEQKP3YV3RZ9FEJ</RequestId><HostId>Tc/l2Ne92PC1WZ3zoa4HhydMjuk3PRh+puZ0CAaC8YvnthVPYpBJiLBFQpbIFfSG+7+3b7LA5N4=</HostId></Error>
```
### Expected behaviour
More helpful message would be nice.
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_template_handlers/test_http.py::TestHttp::test_get_template__request_error__raises_error"
] | [
"tests/test_template_handlers/test_http.py::TestHttp::test_handler_python_template",
"tests/test_template_handlers/test_http.py::TestHttp::test_handler_jinja_template",
"tests/test_template_handlers/test_http.py::TestHttp::test_handler_unsupported_type",
"tests/test_template_handlers/test_http.py::TestHttp::test_handler_raw_template[https://raw.githubusercontent.com/acme/bucket.json]",
"tests/test_template_handlers/test_http.py::TestHttp::test_handler_override_handler_options",
"tests/test_template_handlers/test_http.py::TestHttp::test_handler_raw_template[https://raw.githubusercontent.com/acme/bucket.yaml]",
"tests/test_template_handlers/test_http.py::TestHttp::test_handler_raw_template[https://raw.githubusercontent.com/acme/bucket.template]",
"tests/test_template_handlers/test_http.py::TestHttp::test_get_template"
] | {
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
} | "2022-12-14T19:41:07Z" | apache-2.0 |
|
Sceptre__sceptre-1296 | diff --git a/sceptre/context.py b/sceptre/context.py
index c958c97..73b86f9 100644
--- a/sceptre/context.py
+++ b/sceptre/context.py
@@ -60,7 +60,7 @@ class SceptreContext(object):
):
# project_path: absolute path to the base sceptre project folder
# e.g. absolute_path/to/sceptre_directory
- self.project_path = normalise_path(project_path)
+ self.project_path = path.abspath(normalise_path(project_path))
# config_path: holds the project stack_groups
# e.g {project_path}/config
| Sceptre/sceptre | 855a030c7cff5ffb7dc447c14ab0ae9d9befa267 | diff --git a/tests/test_context.py b/tests/test_context.py
index bb9694a..45cffbc 100644
--- a/tests/test_context.py
+++ b/tests/test_context.py
@@ -1,4 +1,4 @@
-from os import path
+from os import getcwd, path
from unittest.mock import sentinel
from sceptre.context import SceptreContext
@@ -9,7 +9,7 @@ class TestSceptreContext(object):
self.config_path = "config"
self.config_file = "config.yaml"
- def test_context_with_path(self):
+ def test_context_with_path_in_cwd(self):
self.context = SceptreContext(
project_path="project_path/to/sceptre",
command_path="command-path",
@@ -21,9 +21,39 @@ class TestSceptreContext(object):
ignore_dependencies=sentinel.ignore_dependencies,
)
- sentinel.project_path = "project_path/to/sceptre"
+ sentinel.project_path = f"{getcwd()}/project_path/to/sceptre"
assert self.context.project_path.replace(path.sep, "/") == sentinel.project_path
+ def test_context_with_relative_path(self):
+ self.context = SceptreContext(
+ project_path="./project_path/to/sceptre",
+ command_path="command-path",
+ command_params=sentinel.command_params,
+ user_variables=sentinel.user_variables,
+ options=sentinel.options,
+ output_format=sentinel.output_format,
+ no_colour=sentinel.no_colour,
+ ignore_dependencies=sentinel.ignore_dependencies,
+ )
+
+ expected = f"{getcwd()}/project_path/to/sceptre"
+ assert self.context.project_path.replace(path.sep, "/") == expected
+
+ def test_context_with_absolute_path(self):
+ self.context = SceptreContext(
+ project_path=f"{getcwd()}/project_path/to/sceptre",
+ command_path="command-path",
+ command_params=sentinel.command_params,
+ user_variables=sentinel.user_variables,
+ options=sentinel.options,
+ output_format=sentinel.output_format,
+ no_colour=sentinel.no_colour,
+ ignore_dependencies=sentinel.ignore_dependencies,
+ )
+
+ expected = f"{getcwd()}/project_path/to/sceptre"
+ assert self.context.project_path.replace(path.sep, "/") == expected
+
def test_full_config_path_returns_correct_path(self):
context = SceptreContext(
project_path="project_path",
@@ -36,7 +66,7 @@ class TestSceptreContext(object):
ignore_dependencies=sentinel.ignore_dependencies,
)
- full_config_path = path.join("project_path", self.config_path)
+ full_config_path = path.join(f"{getcwd()}/project_path", self.config_path)
assert context.full_config_path() == full_config_path
def test_full_command_path_returns_correct_path(self):
@@ -50,7 +80,9 @@ class TestSceptreContext(object):
no_colour=sentinel.no_colour,
ignore_dependencies=sentinel.ignore_dependencies,
)
- full_command_path = path.join("project_path", self.config_path, "command")
+ full_command_path = path.join(
+ f"{getcwd()}/project_path", self.config_path, "command"
+ )
assert context.full_command_path() == full_command_path
@@ -65,7 +97,7 @@ class TestSceptreContext(object):
no_colour=sentinel.no_colour,
ignore_dependencies=sentinel.ignore_dependencies,
)
- full_templates_path = path.join("project_path", self.templates_path)
+ full_templates_path = path.join(f"{getcwd()}/project_path", self.templates_path)
assert context.full_templates_path() == full_templates_path
def test_clone__returns_full_clone_of_context(self):
| Intermittent AttributeError when resolving dependencies using the sceptre.plan.plan module.
### Subject of the issue
Hello,
I've got an intermittent AttributeError when resolving dependencies using the sceptre.plan.plan module. It only occurs when using a particular hierarchy of dependencies. The error does not occur when using equivalent Sceptre CLI commands. I'm not sure if there's something I'm overlooking in my usage of the API. My config appears to be consistent with the CLI. I didn't spot anything similar when looking through existing issues regarding dependencies.
Cheers,
Pat
The dependency hierarchy:
- Stack 1 depends on Stack 2 and Stack 3.
- Stack 2 depends on Stack 3.
Workarounds:
- Removing either Stack 1s dependency on Stack 2, or Stack 2s dependency on Stack 3 stops the issue occurring.
- Adding `ignore_dependencies` to the SceptreContext will prevent the error. This seems to be practical for what I need to do.
The trace:
```
Traceback (most recent call last):
File "/home/pjls/repos/sceptre-bug/sceptre-describe.py", line 10, in <module>
change_sets = plan.describe()
File "/home/pjls/.local/lib/python3.9/site-packages/sceptre/plan/plan.py", line 208, in describe
self.resolve(command=self.describe.__name__)
File "/home/pjls/.local/lib/python3.9/site-packages/sceptre/plan/plan.py", line 114, in resolve
self.launch_order = self._generate_launch_order(reverse)
File "/home/pjls/.local/lib/python3.9/site-packages/sceptre/plan/plan.py", line 62, in _generate_launch_order
graph = self.graph.filtered(self.command_stacks, reverse)
File "/home/pjls/.local/lib/python3.9/site-packages/sceptre/config/graph.py", line 47, in filtered
relevant |= nx.algorithms.dag.ancestors(graph, stack)
File "/home/pjls/.local/lib/python3.9/site-packages/sceptre/stack.py", line 251, in __eq__
self.dependencies == stack.dependencies and
File "/home/pjls/.local/lib/python3.9/site-packages/sceptre/stack.py", line 242, in __eq__
self.name == stack.name and
AttributeError: 'str' object has no attribute 'name'
```
### Your environment
* version of sceptre (sceptre --version): 3.2.0
* version of python (python --version): 3.9.2
* which OS/distro: Debian Bullseye
### Steps to reproduce
Using the sample repository here: https://github.com/pjsmith404/sceptre-bug
1. Create the stacks using `sceptre launch .`
2. Create a change set using `sceptre create experimental test-change-set`
3. Describe the change set using `sceptre describe change-set experimental test-change-set
4. Describe the change set using `python sceptre-describe.py`. Sometimes it will work, most times it will throw the AttributeError
### Expected behaviour
I would expect dependency resolution via the CLI or the API to return the same result.
### Actual behaviour
Dependency resolution via the API causes intermittent AttributeErrors
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_context.py::TestSceptreContext::test_context_with_path_in_cwd",
"tests/test_context.py::TestSceptreContext::test_context_with_relative_path",
"tests/test_context.py::TestSceptreContext::test_full_config_path_returns_correct_path",
"tests/test_context.py::TestSceptreContext::test_full_command_path_returns_correct_path",
"tests/test_context.py::TestSceptreContext::test_full_templates_path_returns_correct_path"
] | [
"tests/test_context.py::TestSceptreContext::test_context_with_absolute_path",
"tests/test_context.py::TestSceptreContext::test_clone__returns_full_clone_of_context"
] | {
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
} | "2023-02-02T03:37:28Z" | apache-2.0 |
|
Sceptre__sceptre-1333 | diff --git a/sceptre/config/reader.py b/sceptre/config/reader.py
index f618d87..4b371a6 100644
--- a/sceptre/config/reader.py
+++ b/sceptre/config/reader.py
@@ -102,14 +102,6 @@ STACK_CONFIG_ATTRIBUTES = ConfigAttributes(
},
)
-INTERNAL_CONFIG_ATTRIBUTES = ConfigAttributes(
- {
- "project_path",
- "stack_group_path",
- },
- {},
-)
-
REQUIRED_KEYS = STACK_GROUP_CONFIG_ATTRIBUTES.required.union(
STACK_CONFIG_ATTRIBUTES.required
)
@@ -251,7 +243,7 @@ class ConfigReader(object):
if directory in stack_group_configs:
stack_group_config = stack_group_configs[directory]
else:
- stack_group_config = stack_group_configs[directory] = self.read(
+ stack_group_config = stack_group_configs[directory] = self._read(
path.join(directory, self.context.config_file)
)
@@ -323,7 +315,7 @@ class ConfigReader(object):
stacks.add(stack)
return stacks
- def read(self, rel_path, base_config=None):
+ def _read(self, rel_path, base_config=None):
"""
Reads in configuration from one or more YAML files
within the Sceptre project folder.
@@ -559,7 +551,7 @@ class ConfigReader(object):
self.templating_vars["stack_group_config"] = stack_group_config
parsed_stack_group_config = self._parsed_stack_group_config(stack_group_config)
- config = self.read(rel_path, stack_group_config)
+ config = self._read(rel_path, stack_group_config)
stack_name = path.splitext(rel_path)[0]
# Check for missing mandatory attributes
@@ -609,6 +601,7 @@ class ConfigReader(object):
ignore=config.get("ignore", False),
obsolete=config.get("obsolete", False),
stack_group_config=parsed_stack_group_config,
+ config=config,
)
del self.templating_vars["stack_group_config"]
diff --git a/sceptre/plan/actions.py b/sceptre/plan/actions.py
index bbcacdf..b453b6d 100644
--- a/sceptre/plan/actions.py
+++ b/sceptre/plan/actions.py
@@ -19,7 +19,6 @@ from typing import Dict, Optional, Tuple, Union
import botocore
from dateutil.tz import tzutc
-from sceptre.config.reader import ConfigReader
from sceptre.connection_manager import ConnectionManager
from sceptre.exceptions import (
CannotUpdateFailedStackError,
@@ -28,7 +27,7 @@ from sceptre.exceptions import (
UnknownStackChangeSetStatusError,
UnknownStackStatusError,
)
-from sceptre.helpers import extract_datetime_from_aws_response_headers, normalise_path
+from sceptre.helpers import extract_datetime_from_aws_response_headers
from sceptre.hooks import add_stack_hooks
from sceptre.stack import Stack
from sceptre.stack_status import StackChangeSetStatus, StackStatus
@@ -1146,9 +1145,8 @@ class StackActions:
return result
@add_stack_hooks
- def dump_config(self, config_reader: ConfigReader):
+ def dump_config(self):
"""
Dump the config for a stack.
"""
- stack_path = normalise_path(self.stack.name + ".yaml")
- return config_reader.read(stack_path)
+ return self.stack.config
diff --git a/sceptre/plan/plan.py b/sceptre/plan/plan.py
index 7b40dff..6164488 100644
--- a/sceptre/plan/plan.py
+++ b/sceptre/plan/plan.py
@@ -439,4 +439,4 @@ class SceptrePlan(object):
Dump the config for a stack.
"""
self.resolve(command=self.dump_config.__name__)
- return self._execute(self.config_reader, *args)
+ return self._execute(*args)
diff --git a/sceptre/stack.py b/sceptre/stack.py
index b953dcb..b1d7a29 100644
--- a/sceptre/stack.py
+++ b/sceptre/stack.py
@@ -123,6 +123,8 @@ class Stack:
If not supplied, Sceptre uses default value (3600 seconds)
:param stack_group_config: The StackGroup config for the Stack
+
+ :param config: The complete config for the stack. Used by dump config.
"""
parameters = ResolvableContainerProperty("parameters")
@@ -193,7 +195,8 @@ class Stack:
iam_role_session_duration: Optional[int] = None,
ignore=False,
obsolete=False,
- stack_group_config: dict = {},
+ stack_group_config: dict = None,
+ config: dict = None,
):
self.logger = logging.getLogger(__name__)
@@ -211,6 +214,7 @@ class Stack:
"disable_rollback", disable_rollback
)
self.stack_group_config = stack_group_config or {}
+ self.config = config or {}
self.stack_timeout = stack_timeout
self.profile = profile
self.template_key_prefix = template_key_prefix
| Sceptre/sceptre | cb118579367adf28f887fa604c47f2d4be1abed0 | diff --git a/tests/test_config_reader.py b/tests/test_config_reader.py
index 1918d5f..65a36ec 100644
--- a/tests/test_config_reader.py
+++ b/tests/test_config_reader.py
@@ -2,7 +2,7 @@
import errno
import os
-from unittest.mock import patch, sentinel, MagicMock
+from unittest.mock import patch, sentinel, MagicMock, ANY
import pytest
import yaml
@@ -87,7 +87,7 @@ class TestConfigReader(object):
self.write_config(abs_path, config)
self.context.project_path = project_path
- config = ConfigReader(self.context).read(target)
+ config = ConfigReader(self.context)._read(target)
assert config == {
"project_path": project_path,
@@ -127,7 +127,7 @@ class TestConfigReader(object):
self.context.project_path = project_path
reader = ConfigReader(self.context)
- config_a = reader.read("A/config.yaml")
+ config_a = reader._read("A/config.yaml")
assert config_a == {
"project_path": project_path,
@@ -136,7 +136,7 @@ class TestConfigReader(object):
"shared": "A",
}
- config_b = reader.read("A/B/config.yaml")
+ config_b = reader._read("A/B/config.yaml")
assert config_b == {
"project_path": project_path,
@@ -147,7 +147,7 @@ class TestConfigReader(object):
"parent": "A",
}
- config_c = reader.read("A/B/C/config.yaml")
+ config_c = reader._read("A/B/C/config.yaml")
assert config_c == {
"project_path": project_path,
@@ -173,7 +173,7 @@ class TestConfigReader(object):
base_config = {"base_config": "base_config"}
self.context.project_path = project_path
- config = ConfigReader(self.context).read("A/stack.yaml", base_config)
+ config = ConfigReader(self.context)._read("A/stack.yaml", base_config)
assert config == {
"project_path": project_path,
@@ -186,11 +186,11 @@ class TestConfigReader(object):
project_path, config_dir = self.create_project()
self.context.project_path = project_path
with pytest.raises(ConfigFileNotFoundError):
- ConfigReader(self.context).read("stack.yaml")
+ ConfigReader(self.context)._read("stack.yaml")
def test_read_with_empty_config_file(self):
config_reader = ConfigReader(self.context)
- config = config_reader.read("account/stack-group/region/subnets.yaml")
+ config = config_reader._read("account/stack-group/region/subnets.yaml")
assert config == {
"project_path": self.test_project_path,
"stack_group_path": "account/stack-group/region",
@@ -207,7 +207,7 @@ class TestConfigReader(object):
"template_bucket_name": "stack_group_template_bucket_name",
}
os.environ["TEST_ENV_VAR"] = "environment_variable_value"
- config = config_reader.read("account/stack-group/region/security_groups.yaml")
+ config = config_reader._read("account/stack-group/region/security_groups.yaml")
assert config == {
"project_path": self.context.project_path,
@@ -314,6 +314,7 @@ class TestConfigReader(object):
"project_path": self.context.project_path,
"custom_key": "custom_value",
},
+ config=ANY,
)
assert stacks == ({sentinel.stack}, {sentinel.stack})
| The dump config command is not loading the j2_environment
### Subject of the issue
Given a stack with custom `j2_environment`, this is not loaded or available during the `dump config` command.
### Your environment
* version of sceptre - latest
* version of python - 3.10
* which OS/distro - Debian
### Steps to reproduce
Create a stack that has a custom Jinja filter called in its config. Try dump config. A message like this will be seen:
```
"No filter named '<some_filter>'."
```
Try `sceptre generate`; that should work fine.
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_config_reader.py::TestConfigReader::test_read_reads_config_file[filepaths1-A/B/1.yaml]",
"tests/test_config_reader.py::TestConfigReader::test_read_with_empty_config_file",
"tests/test_config_reader.py::TestConfigReader::test_read_with_nonexistant_filepath",
"tests/test_config_reader.py::TestConfigReader::test_read_reads_config_file_with_base_config",
"tests/test_config_reader.py::TestConfigReader::test_read_reads_config_file[filepaths2-A/B/C/1.yaml]",
"tests/test_config_reader.py::TestConfigReader::test_read_reads_config_file[filepaths0-A/1.yaml]",
"tests/test_config_reader.py::TestConfigReader::test_read_with_templated_config_file",
"tests/test_config_reader.py::TestConfigReader::test_construct_stacks_constructs_stack",
"tests/test_config_reader.py::TestConfigReader::test_read_nested_configs"
] | [
"tests/test_config_reader.py::TestConfigReader::test_missing_attr[filepaths0-project_code]",
"tests/test_config_reader.py::TestConfigReader::test_collect_s3_details[name-config1-expected1]",
"tests/test_config_reader.py::TestConfigReader::test_missing_dependency[filepaths0-A/2.yaml]",
"tests/test_config_reader.py::TestConfigReader::test_missing_dependency[filepaths1-1.yaml]",
"tests/test_config_reader.py::TestConfigReader::test_inherited_dependency_already_resolved[filepaths0-B/1.yaml-A/config.yaml]",
"tests/test_config_reader.py::TestConfigReader::test_construct_stacks_with_valid_config[-filepaths0-expected_stacks0-expected_command_stacks0-False]",
"tests/test_config_reader.py::TestConfigReader::test_construct_stacks_with_valid_config[Ab-filepaths8-expected_stacks8-expected_command_stacks8-False]",
"tests/test_config_reader.py::TestConfigReader::test_existing_dependency[filepaths0-A/1.yaml]",
"tests/test_config_reader.py::TestConfigReader::test_construct_stacks_with_disable_rollback_command_param",
"tests/test_config_reader.py::TestConfigReader::test_collect_s3_details[name-config2-expected2]",
"tests/test_config_reader.py::TestConfigReader::test_resolve_node_tag",
"tests/test_config_reader.py::TestConfigReader::test_missing_attr[filepaths1-region]",
"tests/test_config_reader.py::TestConfigReader::test_construct_stacks_with_valid_config[Abd-filepaths5-expected_stacks5-expected_command_stacks5-False]",
"tests/test_config_reader.py::TestConfigReader::test_construct_stacks_with_valid_config[-filepaths1-expected_stacks1-expected_command_stacks1-False]",
"tests/test_config_reader.py::TestConfigReader::test_construct_stacks_with_valid_config[Abd/Abc-filepaths9-expected_stacks9-expected_command_stacks9-True]",
"tests/test_config_reader.py::TestConfigReader::test_collect_s3_details[name-config3-None]",
"tests/test_config_reader.py::TestConfigReader::test_config_reader_with_invalid_path",
"tests/test_config_reader.py::TestConfigReader::test_construct_stacks_with_valid_config[-filepaths3-expected_stacks3-expected_command_stacks3-False]",
"tests/test_config_reader.py::TestConfigReader::test_construct_stacks_with_valid_config[Abd/Abc-filepaths7-expected_stacks7-expected_command_stacks7-False]",
"tests/test_config_reader.py::TestConfigReader::test_collect_s3_details[name-config0-expected0]",
"tests/test_config_reader.py::TestConfigReader::test_construct_stacks_with_valid_config[-filepaths4-expected_stacks4-expected_command_stacks4-False]",
"tests/test_config_reader.py::TestConfigReader::test_construct_stacks_with_valid_config[-filepaths2-expected_stacks2-expected_command_stacks2-False]",
"tests/test_config_reader.py::TestConfigReader::test_inherited_dependency_already_resolved[filepaths1-A/1.yaml-A/config.yaml]",
"tests/test_config_reader.py::TestConfigReader::test_construct_stacks_with_disable_rollback_in_stack_config",
"tests/test_config_reader.py::TestConfigReader::test_aborts_on_incompatible_version_requirement",
"tests/test_config_reader.py::TestConfigReader::test_construct_stacks_with_valid_config[Abd-filepaths6-expected_stacks6-expected_command_stacks6-False]",
"tests/test_config_reader.py::TestConfigReader::test_existing_dependency[filepaths1-B/1.yaml]",
"tests/test_config_reader.py::TestConfigReader::test_config_reader_correctly_initialised"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2023-04-21T09:31:04Z" | apache-2.0 |
|
Sceptre__sceptre-1346 | diff --git a/docs/_source/docs/hooks.rst b/docs/_source/docs/hooks.rst
index 9adb2fb..a1eeef6 100644
--- a/docs/_source/docs/hooks.rst
+++ b/docs/_source/docs/hooks.rst
@@ -1,30 +1,31 @@
Hooks
=====
-Hooks allows the ability for custom commands to be run when Sceptre actions
-occur.
+Hooks allows the ability for actions to be run when Sceptre actions occur.
A hook is executed at a particular hook point when Sceptre is run.
-If required, users can create their own ``hooks``, as described in the section
-`Custom Hooks`_.
+If required, users can create their own ``hooks``, as described in the section `Custom Hooks`_.
Hook points
-----------
-``before_generate`` or ``after_generate`` - run hook before or after generating stack template.
-
-``before_create`` or ``after_create`` - run hook before or after Stack creation.
-
-``before_update`` or ``after_update`` - run hook before or after Stack update.
-
-``before_delete`` or ``after_delete`` - run hook before or after Stack deletion.
-
-``before_launch`` or ``after_launch`` - run hook before or after Stack launch.
-
-``before_validate`` or ``after_validate`` - run hook before or after Stack validation.
-
-``before_create_change_set`` or ``after_create_change_set`` - run hook before or after create change set.
+- ``before_create``/``after_create`` - Runs before/after Stack creation.
+- ``before_update``/``after_update`` - Runs before/after Stack update.
+- ``before_delete``/``after_delete`` - Runs before/after Stack deletion.
+- ``before_launch``/``after_launch`` - Runs before/after Stack launch.
+- ``before_create_change_set``/``after_create_change_set`` - Runs before/after create change set.
+- ``before_validate``/``after_validate`` - Runs before/after Stack validation.
+- ``before_diff``/``after_diff`` - Runs before/after diffing the deployed stack with the local
+ configuration.
+- ``before_drift_detect``/``after_drift_detect`` - Runs before/after detecting drift on the stack.
+- ``before_drift_show``/``after_drift_show`` - Runs before/after showing detected drift on the stack.
+- ``before_dump_config``/``after_dump_config`` - Runs before/after dumpint the Stack Config.
+- ``before_dump_template``/``after_dump_template`` - Runs before/after rendering the stack template.
+ This hook point is aliased to ``before/generate``/``after_generate``. This hook point will also
+ be triggered when diffing, since the template needs to be generated to diff the template.
+- ``before_generate``/``after_generate`` - Runs before/after rendering the stack template. This hook
+ point is aliased to ``before_dump_template``/``after_dump_template``.
Syntax:
diff --git a/sceptre/cli/template.py b/sceptre/cli/template.py
index cf81c1b..28ad66c 100644
--- a/sceptre/cli/template.py
+++ b/sceptre/cli/template.py
@@ -2,9 +2,7 @@ import logging
import webbrowser
import click
-from deprecation import deprecated
-
-from sceptre import __version__
+from sceptre.cli.dump import dump_template
from sceptre.cli.helpers import catch_exceptions, write
from sceptre.context import SceptreContext
from sceptre.helpers import null_context
@@ -67,35 +65,19 @@ def validate_command(ctx, no_placeholders, path):
@click.argument("path")
@click.pass_context
@catch_exceptions
-@deprecated("4.2.0", "5.0.0", __version__, "Use dump template instead.")
-def generate_command(ctx, no_placeholders, path):
+def generate_command(ctx: click.Context, no_placeholders: bool, path: str):
"""
Prints the template used for stack in PATH.
- \f
+ This command is aliased to the dump template command for legacy support reasons. It's the same
+ as running `sceptre dump template`.
+
+ \f
+ :param no_placeholders: If True, will disable placeholders for unresolvable resolvers. By
+ default, placeholders will be active.
:param path: Path to execute the command on.
- :type path: str
"""
- context = SceptreContext(
- command_path=path,
- command_params=ctx.params,
- project_path=ctx.obj.get("project_path"),
- user_variables=ctx.obj.get("user_variables"),
- options=ctx.obj.get("options"),
- output_format=ctx.obj.get("output_format"),
- ignore_dependencies=ctx.obj.get("ignore_dependencies"),
- )
-
- plan = SceptrePlan(context)
-
- execution_context = (
- null_context() if no_placeholders else use_resolver_placeholders_on_error()
- )
- with execution_context:
- responses = plan.generate()
-
- output = [template for template in responses.values()]
- write(output, context.output_format)
+ ctx.forward(dump_template)
@click.command(name="estimate-cost", short_help="Estimates the cost of the template.")
diff --git a/sceptre/diffing/stack_differ.py b/sceptre/diffing/stack_differ.py
index 6712aa6..87ad33e 100644
--- a/sceptre/diffing/stack_differ.py
+++ b/sceptre/diffing/stack_differ.py
@@ -313,7 +313,7 @@ class StackDiffer(Generic[DiffType]):
generated_config.parameters[key] = self.NO_ECHO_REPLACEMENT
def _generate_template(self, stack_actions: StackActions) -> str:
- return stack_actions.generate()
+ return stack_actions.dump_template()
def _get_deployed_template(
self, stack_actions: StackActions, is_deployed: bool
diff --git a/sceptre/hooks/__init__.py b/sceptre/hooks/__init__.py
index 56b4df6..1a454fc 100644
--- a/sceptre/hooks/__init__.py
+++ b/sceptre/hooks/__init__.py
@@ -1,7 +1,7 @@
import abc
import logging
from functools import wraps
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, List
from sceptre.helpers import _call_func_on_values
from sceptre.resolvers import CustomYamlTagBase
@@ -98,3 +98,33 @@ def add_stack_hooks(func):
return response
return decorated
+
+
+def add_stack_hooks_with_aliases(function_aliases: List[str]):
+ """
+ Returns a decorator to trigger the before and after hooks, relative to the decorated function's
+ name AS WELL AS the passed function alias names.
+ :param function_aliases: The list of OTHER functions to trigger hooks around.
+ :return: The hook-triggering decorator.
+ """
+
+ def decorator(func):
+ all_hook_names = [func.__name__] + function_aliases
+
+ @wraps(func)
+ def decorated(self, *args, **kwargs):
+ for hook in all_hook_names:
+ before_hook_name = f"before_{hook}"
+ execute_hooks(self.stack.hooks.get(before_hook_name))
+
+ response = func(self, *args, **kwargs)
+
+ for hook in all_hook_names:
+ after_hook_name = f"after_{hook}"
+ execute_hooks(self.stack.hooks.get(after_hook_name))
+
+ return response
+
+ return decorated
+
+ return decorator
diff --git a/sceptre/plan/actions.py b/sceptre/plan/actions.py
index ac9c60e..7495790 100644
--- a/sceptre/plan/actions.py
+++ b/sceptre/plan/actions.py
@@ -17,9 +17,7 @@ import botocore
from datetime import datetime, timedelta
from dateutil.tz import tzutc
from os import path
-from deprecation import deprecated
-from sceptre import __version__
from sceptre.connection_manager import ConnectionManager
from sceptre.exceptions import (
@@ -30,7 +28,7 @@ from sceptre.exceptions import (
UnknownStackStatusError,
)
from sceptre.helpers import extract_datetime_from_aws_response_headers
-from sceptre.hooks import add_stack_hooks
+from sceptre.hooks import add_stack_hooks, add_stack_hooks_with_aliases
from sceptre.stack import Stack
from sceptre.stack_status import StackChangeSetStatus, StackStatus
@@ -627,10 +625,10 @@ class StackActions:
return new_summaries
- @deprecated("4.2.0", "5.0.0", __version__, "Use dump template instead.")
def generate(self):
"""
- Returns the Template for the Stack
+ Returns the Template for the Stack. An alias for
+ dump_template for historical reasons.
"""
return self.dump_template()
@@ -1155,9 +1153,10 @@ class StackActions:
"""
return self.stack.config
- @add_stack_hooks
+ @add_stack_hooks_with_aliases([generate.__name__])
def dump_template(self):
"""
- Returns the Template for the Stack
+ Dump the template for the Stack. An alias for generate
+ for historical reasons.
"""
return self.stack.template.body
diff --git a/sceptre/plan/plan.py b/sceptre/plan/plan.py
index 46008af..27e551a 100644
--- a/sceptre/plan/plan.py
+++ b/sceptre/plan/plan.py
@@ -11,7 +11,6 @@ import itertools
from os import path, walk
from typing import Dict, List, Set, Callable, Iterable, Optional
-from deprecation import deprecated
from sceptre.config.graph import StackGraph
from sceptre.config.reader import ConfigReader
@@ -21,7 +20,6 @@ from sceptre.exceptions import ConfigFileNotFoundError
from sceptre.helpers import sceptreise_path
from sceptre.plan.executor import SceptrePlanExecutor
from sceptre.stack import Stack
-from sceptre import __version__
def require_resolved(func) -> Callable:
@@ -380,10 +378,10 @@ class SceptrePlan(object):
self.resolve(command=self.estimate_cost.__name__)
return self._execute(*args)
- @deprecated("4.2.0", "5.0.0", __version__, "Use dump template instead.")
def generate(self, *args):
"""
- Returns a generated Template for a given Stack
+ Returns a generated Template for a given Stack. An alias for
+ dump_template for historical reasons.
:returns: A dictionary of Stacks and their template body.
:rtype: dict
@@ -447,7 +445,8 @@ class SceptrePlan(object):
def dump_template(self, *args):
"""
- Returns a generated Template for a given Stack
+ Dump the template for a stack. An alias
+ for generate for historical reasons.
"""
self.resolve(command=self.dump_template.__name__)
return self._execute(*args)
| Sceptre/sceptre | db13f09407194f106df94e0be233e4baa61f74c1 | diff --git a/tests/test_diffing/test_stack_differ.py b/tests/test_diffing/test_stack_differ.py
index 4f852f7..b55bbb8 100644
--- a/tests/test_diffing/test_stack_differ.py
+++ b/tests/test_diffing/test_stack_differ.py
@@ -179,7 +179,7 @@ class TestStackDiffer:
self.command_capturer.compare_templates.assert_called_with(
self.actions.fetch_remote_template.return_value,
- self.actions.generate.return_value,
+ self.actions.dump_template.return_value,
)
def test_diff__template_diff_is_value_returned_by_implemented_differ(self):
@@ -216,7 +216,7 @@ class TestStackDiffer:
def test_diff__returns_generated_template(self):
diff = self.differ.diff(self.actions)
- assert diff.generated_template == self.actions.generate.return_value
+ assert diff.generated_template == self.actions.dump_template.return_value
def test_diff__deployed_stack_exists__returns_is_deployed_as_true(self):
diff = self.differ.diff(self.actions)
@@ -244,7 +244,7 @@ class TestStackDiffer:
self.differ.diff(self.actions)
self.command_capturer.compare_templates.assert_called_with(
- "{}", self.actions.generate.return_value
+ "{}", self.actions.dump_template.return_value
)
@pytest.mark.parametrize(
@@ -285,7 +285,7 @@ class TestStackDiffer:
self.stack_status = status
self.differ.diff(self.actions)
self.command_capturer.compare_templates.assert_called_with(
- "{}", self.actions.generate.return_value
+ "{}", self.actions.dump_template.return_value
)
def test_diff__deployed_stack_has_default_values__doesnt_pass_parameter__compares_identical_configs(
diff --git a/tests/test_hooks/test_hooks.py b/tests/test_hooks/test_hooks.py
index 47194b6..bf70bbf 100644
--- a/tests/test_hooks/test_hooks.py
+++ b/tests/test_hooks/test_hooks.py
@@ -2,7 +2,13 @@
from unittest import TestCase
from unittest.mock import MagicMock, Mock
-from sceptre.hooks import Hook, HookProperty, add_stack_hooks, execute_hooks
+from sceptre.hooks import (
+ Hook,
+ HookProperty,
+ add_stack_hooks,
+ execute_hooks,
+ add_stack_hooks_with_aliases,
+)
from sceptre.resolvers import Resolver
from sceptre.stack import Stack
import logging
@@ -39,6 +45,29 @@ class TestHooksFunctions(object):
assert mock_hook_before.run.call_count == 1
assert mock_hook_after.run.call_count == 1
+ def test_add_stack_hooks_with_aliases(self):
+ mock_before_something = MagicMock(Hook)
+ mock_after_something = MagicMock(Hook)
+ mock_object = MagicMock()
+
+ mock_object.stack.hooks = {
+ "before_something": [mock_before_something],
+ "after_something": [mock_after_something],
+ }
+
+ @add_stack_hooks_with_aliases(["something"])
+ def mock_function(self):
+ return 123
+
+ mock_object.mock_function = mock_function
+ mock_object.mock_function.__name__ = "mock_function"
+
+ result = mock_function(mock_object)
+
+ assert mock_before_something.run.call_count == 1
+ assert mock_after_something.run.call_count == 1
+ assert result == 123
+
def test_execute_hooks_with_not_a_list(self):
execute_hooks(None)
diff --git a/tests/test_plan.py b/tests/test_plan.py
index 11f0a4e..9e92ba9 100644
--- a/tests/test_plan.py
+++ b/tests/test_plan.py
@@ -1,8 +1,6 @@
import pytest
from unittest.mock import MagicMock, patch, sentinel
-from deprecation import fail_if_not_removed
-
from sceptre.context import SceptreContext
from sceptre.stack import Stack
from sceptre.config.reader import ConfigReader
@@ -63,9 +61,3 @@ class TestSceptrePlan(object):
plan = MagicMock(spec=SceptrePlan)
plan.context = self.mock_context
plan.invalid_command()
-
- @fail_if_not_removed
- def test_generate_removed(self):
- plan = MagicMock(spec=SceptrePlan)
- plan.context = self.mock_context
- plan.generate("test-attribute")
| before_generate hook broken by recent deprecation
### Subject of the issue
The `before_generate` hook has been broken by a recent deprecation.
### Your environment
* version of sceptre (sceptre --version)
* version of python (python --version)
* which OS/distro
### Steps to reproduce
Tell us how to reproduce this issue. Please provide sceptre projct files if possible,
you can use https://plnkr.co/edit/ANFHm61Ilt4mQVgF as a base.
### Expected behaviour
Tell us what should happen
### Actual behaviour
Tell us what happens instead
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_diffing/test_stack_differ.py::TestStackDiffer::test_diff__compares_deployed_template_to_generated_template",
"tests/test_diffing/test_stack_differ.py::TestStackDiffer::test_diff__template_diff_is_value_returned_by_implemented_differ",
"tests/test_diffing/test_stack_differ.py::TestStackDiffer::test_diff__compares_deployed_stack_config_to_generated_stack_config",
"tests/test_diffing/test_stack_differ.py::TestStackDiffer::test_diff__config_diff_is_value_returned_by_implemented_differ",
"tests/test_diffing/test_stack_differ.py::TestStackDiffer::test_diff__returned_diff_has_stack_name_of_external_name",
"tests/test_diffing/test_stack_differ.py::TestStackDiffer::test_diff__returns_generated_config",
"tests/test_diffing/test_stack_differ.py::TestStackDiffer::test_diff__returns_generated_template",
"tests/test_diffing/test_stack_differ.py::TestStackDiffer::test_diff__deployed_stack_exists__returns_is_deployed_as_true",
"tests/test_diffing/test_stack_differ.py::TestStackDiffer::test_diff__deployed_stack_does_not_exist__returns_is_deployed_as_false",
"tests/test_diffing/test_stack_differ.py::TestStackDiffer::test_diff__deployed_stack_does_not_exist__compares_none_to_generated_config",
"tests/test_diffing/test_stack_differ.py::TestStackDiffer::test_diff__deployed_stack_does_not_exist__compares_empty_dict_string_to_generated_template",
"tests/test_diffing/test_stack_differ.py::TestStackDiffer::test_diff__non_deployed_stack_status__compares_none_to_generated_config[CREATE_FAILED]",
"tests/test_diffing/test_stack_differ.py::TestStackDiffer::test_diff__non_deployed_stack_status__compares_none_to_generated_config[ROLLBACK_COMPLETE]",
"tests/test_diffing/test_stack_differ.py::TestStackDiffer::test_diff__non_deployed_stack_status__compares_none_to_generated_config[DELETE_COMPLETE]",
"tests/test_diffing/test_stack_differ.py::TestStackDiffer::test_diff__non_deployed_stack_status__compares_empty_dict_string_to_generated_template[CREATE_FAILED]",
"tests/test_diffing/test_stack_differ.py::TestStackDiffer::test_diff__non_deployed_stack_status__compares_empty_dict_string_to_generated_template[ROLLBACK_COMPLETE]",
"tests/test_diffing/test_stack_differ.py::TestStackDiffer::test_diff__non_deployed_stack_status__compares_empty_dict_string_to_generated_template[DELETE_COMPLETE]",
"tests/test_diffing/test_stack_differ.py::TestStackDiffer::test_diff__deployed_stack_has_default_values__doesnt_pass_parameter__compares_identical_configs",
"tests/test_diffing/test_stack_differ.py::TestStackDiffer::test_diff__deployed_stack_has_list_default_parameter__doesnt_pass_parameter__compares_identical_configs",
"tests/test_diffing/test_stack_differ.py::TestStackDiffer::test_diff__deployed_stack_has_default_values__passes_the_parameter__compares_identical_configs",
"tests/test_diffing/test_stack_differ.py::TestStackDiffer::test_diff__deployed_stack_has_default_values__passes_different_value__compares_different_configs",
"tests/test_diffing/test_stack_differ.py::TestStackDiffer::test_diff__generated_stack_has_none_for_parameter_value__its_treated_like_its_not_specified",
"tests/test_diffing/test_stack_differ.py::TestStackDiffer::test_diff__stack_exists_with_same_config_but_template_does_not__compares_identical_configs",
"tests/test_diffing/test_stack_differ.py::TestStackDiffer::test_diff__deployed_parameter_has_linebreak_but_otherwise_no_difference__compares_identical_configs",
"tests/test_diffing/test_stack_differ.py::TestStackDiffer::test_diff__parameter_has_identical_string_linebreak__compares_identical_configs",
"tests/test_diffing/test_stack_differ.py::TestStackDiffer::test_diff__parameter_has_identical_list_linebreaks__compares_identical_configs",
"tests/test_diffing/test_stack_differ.py::TestStackDiffer::test_diff__no_echo_default_parameter__generated_stack_doesnt_pass_parameter__compares_identical_configs",
"tests/test_diffing/test_stack_differ.py::TestStackDiffer::test_diff__generated_template_has_no_echo_parameter__masks_value",
"tests/test_diffing/test_stack_differ.py::TestStackDiffer::test_diff__generated_template_has_no_echo_parameter__show_no_echo__shows_value",
"tests/test_diffing/test_stack_differ.py::TestDeepDiffStackDiffer::test_compare_stack_configurations__returns_deepdiff_of_deployed_and_generated",
"tests/test_diffing/test_stack_differ.py::TestDeepDiffStackDiffer::test_compare_stack_configurations__returned_deepdiff_has_verbosity_of_2",
"tests/test_diffing/test_stack_differ.py::TestDeepDiffStackDiffer::test_compare_stack_configurations__deployed_is_none__returns_deepdiff_with_none_for_t1",
"tests/test_diffing/test_stack_differ.py::TestDeepDiffStackDiffer::test_compare_templates__templates_are_json__returns_deepdiff_of_dicts[templates",
"tests/test_diffing/test_stack_differ.py::TestDeepDiffStackDiffer::test_compare_templates__templates_are_yaml_with_intrinsic_functions__returns_deepdiff_of_dicts",
"tests/test_diffing/test_stack_differ.py::TestDeepDiffStackDiffer::test_compare_templates__deployed_is_empty_dict_string__returns_deepdiff_with_empty_dict_for_t1",
"tests/test_diffing/test_stack_differ.py::TestDifflibStackDiffer::test_compare_stack_configurations__returns_diff_of_deployed_and_generated_when_converted_to_dicts",
"tests/test_diffing/test_stack_differ.py::TestDifflibStackDiffer::test_compare_stack_configurations__deployed_is_none__returns_diff_with_none",
"tests/test_diffing/test_stack_differ.py::TestDifflibStackDiffer::test_compare_stack_configurations__deployed_is_none__all_configs_are_falsey__returns_diff_with_none",
"tests/test_diffing/test_stack_differ.py::TestDifflibStackDiffer::test_compare_templates__templates_are_json__returns_deepdiff_of_dicts[templates",
"tests/test_diffing/test_stack_differ.py::TestDifflibStackDiffer::test_compare_templates__deployed_is_empty_dict_string__returns_diff_with_empty_string",
"tests/test_diffing/test_stack_differ.py::TestDifflibStackDiffer::test_compare_templates__json_template__only_indentation_diff__returns_no_diff",
"tests/test_diffing/test_stack_differ.py::TestDifflibStackDiffer::test_compare_templates__yaml_template__only_indentation_diff__returns_no_diff",
"tests/test_diffing/test_stack_differ.py::TestDifflibStackDiffer::test_compare_templates__opposite_template_types_but_identical_template__returns_no_diff",
"tests/test_hooks/test_hooks.py::TestHooksFunctions::test_add_stack_hooks",
"tests/test_hooks/test_hooks.py::TestHooksFunctions::test_add_stack_hooks_with_aliases",
"tests/test_hooks/test_hooks.py::TestHooksFunctions::test_execute_hooks_with_not_a_list",
"tests/test_hooks/test_hooks.py::TestHooksFunctions::test_execute_hooks_with_empty_list",
"tests/test_hooks/test_hooks.py::TestHooksFunctions::test_execute_hooks_with_list_with_non_hook_objects",
"tests/test_hooks/test_hooks.py::TestHooksFunctions::test_execute_hooks_with_single_hook",
"tests/test_hooks/test_hooks.py::TestHooksFunctions::test_execute_hooks_with_multiple_hook",
"tests/test_hooks/test_hooks.py::TestHook::test_argument__supports_resolvers_in_arguments",
"tests/test_hooks/test_hooks.py::TestHook::test_logger__logs_have_stack_name_prefix",
"tests/test_hooks/test_hooks.py::TestHookPropertyDescriptor::test_setting_hook_property",
"tests/test_hooks/test_hooks.py::TestHookPropertyDescriptor::test_getting_hook_property",
"tests/test_plan.py::TestSceptrePlan::test_planner_executes_without_params",
"tests/test_plan.py::TestSceptrePlan::test_planner_executes_with_params",
"tests/test_plan.py::TestSceptrePlan::test_command_not_found_error_raised"
] | [] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2023-06-10T16:37:01Z" | apache-2.0 |
|
Sceptre__sceptre-1357 | diff --git a/docs/_source/docs/hooks.rst b/docs/_source/docs/hooks.rst
index a1eeef6..9a3bc82 100644
--- a/docs/_source/docs/hooks.rst
+++ b/docs/_source/docs/hooks.rst
@@ -44,23 +44,105 @@ Available Hooks
cmd
~~~
-Executes the argument string in the shell as a Python subprocess.
-
-For more information about how this works, see the `subprocess documentation`_
+Executes a command through the shell.
Syntax:
.. code-block:: yaml
+ # Default shell.
<hook_point>:
- !cmd <shell_command>
-Example:
+ # Another shell.
+ <hook_point>:
+ - !cmd
+ run: <shell_command>
+ shell: <shell_name_or_path>
+
+Pass the command string as the only argument to use the default shell.
+
+On POSIX the default shell is ``sh``. On Windows it's usually ``cmd.exe``, but ``%ComSpec%`` may
+override that.
+
+Write the command string as you would type it at the shell prompt. This includes quotes and
+backslashes to escape filenames with spaces in them. To minimize escaping, you can use YAML plain
+strings like the following examples.
+
+.. code-block:: yaml
+
+ hooks:
+ before_update:
+ - !cmd echo "Hello, world!"
+
+A successful command prints its standard output messages between status messages from Sceptre.
+
+.. code-block::
+
+ [2023-09-03 01:06:28] - test - Launching Stack
+ [2023-09-03 01:06:29] - test - Stack is in the CREATE_COMPLETE state
+ Hello, world!
+ [2023-09-03 01:06:31] - test - Updating Stack
+ [2023-09-03 01:06:31] - test - No updates to perform.
+
+Pass named arguments to use a different shell. Here the command string is called ``run`` and the
+shell executable is called ``shell``.
+
+Write the executable name as you would type it at an interactive prompt to start the shell. For
+example, if Bash is in the system path, you can write ``bash``; otherwise, you need to write the
+absolute path such as ``/bin/bash``.
+
+.. code-block:: yaml
+
+ hooks:
+ before_update:
+ - !cmd
+ run: echo "Hello, $0!"
+ shell: bash
+
+.. code-block:: text
+
+ [2023-09-04 00:29:42] - test - Launching Stack
+ [2023-09-04 00:29:43] - test - Stack is in the CREATE_COMPLETE state
+ Hello, bash!
+ [2023-09-04 00:29:43] - test - Updating Stack
+ [2023-09-04 00:29:43] - test - No updates to perform.
+
+You can use PowerShell in the same way.
+
+.. code-block:: yaml
+
+ hooks:
+ before_update:
+ - !cmd
+ run: Write-Output "Hello, Posh!"
+ shell: pwsh
+
+.. code-block:: text
+
+ [2023-09-04 00:44:32] - test - Launching Stack
+ [2023-09-04 00:44:33] - test - Stack is in the CREATE_COMPLETE state
+ Hello, Posh!
+ [2023-09-04 00:44:34] - test - Updating Stack
+ [2023-09-04 00:44:34] - test - No updates to perform.
+
+If the shell command fails, so does Sceptre. Its output sits between Sceptre's status
+messages and a Python traceback.
.. code-block:: yaml
- before_create:
- - !cmd "echo hello"
+ hooks:
+ before_update:
+ - !cmd missing_command
+
+.. code-block:: text
+
+ [2023-09-04 00:46:25] - test - Launching Stack
+ [2023-09-04 00:46:26] - test - Stack is in the CREATE_COMPLETE state
+ /bin/sh: 1: missing_command: not found
+ Traceback (most recent call last):
+ <snip>
+ subprocess.CalledProcessError: Command 'missing_command' returned non-zero exit status 127.
asg_scaling_processes
~~~~~~~~~~~~~~~~~~~~~
diff --git a/sceptre/cli/list.py b/sceptre/cli/list.py
index 6f11bd2..c9b7b0c 100644
--- a/sceptre/cli/list.py
+++ b/sceptre/cli/list.py
@@ -5,6 +5,8 @@ from sceptre.context import SceptreContext
from sceptre.cli.helpers import catch_exceptions, write
from sceptre.plan.plan import SceptrePlan
+from typing import List, Dict
+
logger = logging.getLogger(__name__)
@@ -46,12 +48,67 @@ def list_resources(ctx, path):
write(responses, context.output_format)
+# flake8: noqa: C901
+def write_outputs(export, responses, plan, context):
+ """
+ Helper function for list outputs.
+ """
+ # Legacy. This option was added in the initial commit of the project,
+ # although its intended use case is unclear. It may relate to a feature
+ # that had been removed prior to the initial commit.
+ if export == "envvar":
+ for response in responses:
+ for stack in response.values():
+ for output in stack:
+ write(
+ "export SCEPTRE_{0}='{1}'".format(
+ output.get("OutputKey"), output.get("OutputValue")
+ ),
+ "text",
+ )
+
+ # Format outputs as !stack_output references.
+ elif export == "stackoutput":
+ for response in responses:
+ for stack_name, stack in response.items():
+ for output in stack:
+ write(
+ "!stack_output {0}.yaml::{1} [{2}]".format(
+ stack_name,
+ output.get("OutputKey"),
+ output.get("OutputValue"),
+ ),
+ "text",
+ )
+
+ # Format outputs as !stack_output_external references.
+ elif export == "stackoutputexternal":
+ stack_names = {stack.name: stack.external_name for stack in plan.graph}
+ for response in responses:
+ for stack_name, stack in response.items():
+ for output in stack:
+ write(
+ "!stack_output_external {0}::{1} [{2}]".format(
+ stack_names[stack_name],
+ output.get("OutputKey"),
+ output.get("OutputValue"),
+ ),
+ "text",
+ )
+
+ # Legacy. The output here is somewhat confusing in that
+ # outputs are organised in keys that only have meaning inside
+ # Sceptre.
+ else:
+ write(responses, context.output_format)
+
+
@list_group.command(name="outputs")
@click.argument("path")
@click.option(
"-e",
"--export",
- type=click.Choice(["envvar"]),
+ type=click.Choice(["envvar", "stackoutput", "stackoutputexternal"]),
help="Specify the export formatting.",
)
@click.pass_context
@@ -60,7 +117,6 @@ def list_outputs(ctx, path, export):
"""
List outputs for stack.
\f
-
:param path: Path to execute the command on.
:type path: str
:param export: Specify the export formatting.
@@ -79,18 +135,7 @@ def list_outputs(ctx, path, export):
plan = SceptrePlan(context)
responses = [response for response in plan.describe_outputs().values() if response]
- if export == "envvar":
- for response in responses:
- for stack in response.values():
- for output in stack:
- write(
- "export SCEPTRE_{0}='{1}'".format(
- output.get("OutputKey"), output.get("OutputValue")
- ),
- "text",
- )
- else:
- write(responses, context.output_format)
+ write_outputs(export, responses, plan, context)
@list_group.command(name="change-sets")
diff --git a/sceptre/hooks/cmd.py b/sceptre/hooks/cmd.py
index 5ec3216..8292e87 100644
--- a/sceptre/hooks/cmd.py
+++ b/sceptre/hooks/cmd.py
@@ -13,16 +13,37 @@ class Cmd(Hook):
def run(self):
"""
- Runs the argument string in a subprocess.
+ Executes a command through the shell.
- :raises: sceptre.exceptions.InvalidTaskArgumentTypeException
- :raises: subprocess.CalledProcessError
+ See hooks documentation for details.
+
+ :raises: sceptre.exceptions.InvalidHookArgumentTypeError invalid input
+ :raises: CalledProcessError failed command
+ :raises: FileNotFoundError missing shell
+ :raises: PermissionError non-executable shell
"""
envs = self.stack.connection_manager.create_session_environment_variables()
- try:
- subprocess.check_call(self.argument, shell=True, env=envs)
- except TypeError:
+
+ if isinstance(self.argument, str) and self.argument != "":
+ command_to_run = self.argument
+ shell = None
+
+ elif (
+ isinstance(self.argument, dict)
+ and set(self.argument) == {"run", "shell"}
+ and isinstance(self.argument["run"], str)
+ and isinstance(self.argument["shell"], str)
+ and self.argument["run"] != ""
+ and self.argument["shell"] != ""
+ ):
+ command_to_run = self.argument["run"]
+ shell = self.argument["shell"]
+
+ else:
raise InvalidHookArgumentTypeError(
- 'The argument "{0}" is the wrong type - cmd hooks require '
- "arguments of type string.".format(self.argument)
+ "A cmd hook requires either a string argument or an object with "
+ "`run` and `shell` keys with string values. "
+ f"You gave `{self.argument!r}`."
)
+
+ subprocess.check_call(command_to_run, shell=True, env=envs, executable=shell)
| Sceptre/sceptre | 64ab818cb9be16276689932b7a15072c3fa6c86e | diff --git a/tests/test_cli/test_cli_commands.py b/tests/test_cli/test_cli_commands.py
index c3b4fd5..b5b8c88 100644
--- a/tests/test_cli/test_cli_commands.py
+++ b/tests/test_cli/test_cli_commands.py
@@ -636,8 +636,8 @@ class TestCli:
expected_output = "StackOutputKeyOutputValue\n\nStackNameKeyValue\n"
assert result.output.replace(" ", "") == expected_output
- def test_list_outputs_with_export(self):
- outputs = {"stack": [{"OutputKey": "Key", "OutputValue": "Value"}]}
+ def test_list_outputs_with_export__envvar(self):
+ outputs = {"mock-stack": [{"OutputKey": "Key", "OutputValue": "Value"}]}
self.mock_stack_actions.describe_outputs.return_value = outputs
result = self.runner.invoke(
cli, ["list", "outputs", "dev/vpc.yaml", "-e", "envvar"]
@@ -645,6 +645,26 @@ class TestCli:
assert result.exit_code == 0
assert result.output == "export SCEPTRE_Key='Value'\n"
+ def test_list_outputs_with_export__stackoutput(self):
+ outputs = {"mock-stack": [{"OutputKey": "Key", "OutputValue": "Value"}]}
+ self.mock_stack_actions.describe_outputs.return_value = outputs
+ result = self.runner.invoke(
+ cli, ["list", "outputs", "dev/vpc.yaml", "-e", "stackoutput"]
+ )
+ assert result.exit_code == 0
+ assert result.output == "!stack_output mock-stack.yaml::Key [Value]\n"
+
+ def test_list_outputs_with_export__stackoutputexternal(self):
+ outputs = {"mock-stack": [{"OutputKey": "Key", "OutputValue": "Value"}]}
+ self.mock_stack_actions.describe_outputs.return_value = outputs
+ result = self.runner.invoke(
+ cli, ["list", "outputs", "dev/vpc.yaml", "-e", "stackoutputexternal"]
+ )
+ assert result.exit_code == 0
+ assert (
+ result.output == "!stack_output_external mock-stack-external::Key [Value]\n"
+ )
+
@pytest.mark.parametrize(
"path,output_format,expected_output",
[
diff --git a/tests/test_hooks/test_cmd.py b/tests/test_hooks/test_cmd.py
index 3f15a7f..d65b313 100644
--- a/tests/test_hooks/test_cmd.py
+++ b/tests/test_hooks/test_cmd.py
@@ -1,37 +1,174 @@
# -*- coding: utf-8 -*-
-import subprocess
-from unittest.mock import patch, Mock
-
+from subprocess import CalledProcessError
+from unittest.mock import Mock
import pytest
from sceptre.exceptions import InvalidHookArgumentTypeError
from sceptre.hooks.cmd import Cmd
from sceptre.stack import Stack
+ERROR_MESSAGE = (
+ r"^A cmd hook requires either a string argument or an object with `run` and "
+ r"`shell` keys with string values\. You gave `{0}`\.$"
+)
+
+
[email protected]()
+def stack():
+ stack = Stack(
+ "stack1",
+ "project1",
+ "region1",
+ template_handler_config={"template": "path.yaml"},
+ )
+
+ # Otherwise the test works only when the environment variables already set a
+ # valid AWS session.
+ stack.connection_manager.create_session_environment_variables = Mock(
+ return_value={}
+ )
+
+ return stack
+
+
+def test_null_input_raises_exception(stack):
+ message = ERROR_MESSAGE.format(r"None")
+ with pytest.raises(InvalidHookArgumentTypeError, match=message):
+ Cmd(None, stack).run()
+
+
+def test_empty_string_raises_exception(stack):
+ message = ERROR_MESSAGE.format(r"''")
+ with pytest.raises(InvalidHookArgumentTypeError, match=message):
+ Cmd("", stack).run()
+
+
+def test_list_raises_exception(stack):
+ message = ERROR_MESSAGE.format(r"\['echo', 'hello'\]")
+ with pytest.raises(InvalidHookArgumentTypeError, match=message):
+ Cmd(["echo", "hello"], stack).run()
+
+
+def test_dict_without_shell_raises_exception(stack):
+ message = ERROR_MESSAGE.format(r"\{'run': 'echo hello'\}")
+ with pytest.raises(InvalidHookArgumentTypeError, match=message):
+ Cmd({"run": "echo hello"}, stack).run()
+
+
+def test_dict_without_run_raises_exception(stack):
+ message = ERROR_MESSAGE.format(r"\{'shell': '/bin/bash'\}")
+ with pytest.raises(InvalidHookArgumentTypeError, match=message):
+ Cmd({"shell": "/bin/bash"}, stack).run()
+
+
+def test_dict_with_list_run_raises_exception(stack):
+ message = ERROR_MESSAGE.format(
+ r"\{'run': \['echo', 'hello'\], 'shell': '/bin/bash'\}"
+ )
+ with pytest.raises(InvalidHookArgumentTypeError, match=message):
+ Cmd({"run": ["echo", "hello"], "shell": "/bin/bash"}, stack).run()
+
+
+def test_dict_with_empty_run_raises_exception(stack):
+ message = ERROR_MESSAGE.format(r"\{'run': '', 'shell': '/bin/bash'\}")
+ with pytest.raises(InvalidHookArgumentTypeError, match=message):
+ Cmd({"run": "", "shell": "/bin/bash"}, stack).run()
+
+
+def test_dict_with_null_run_raises_exception(stack):
+ message = ERROR_MESSAGE.format(r"\{'run': None, 'shell': '/bin/bash'\}")
+ with pytest.raises(InvalidHookArgumentTypeError, match=message):
+ Cmd({"run": None, "shell": "/bin/bash"}, stack).run()
+
+
+def test_dict_with_list_shell_raises_exception(stack):
+ message = ERROR_MESSAGE.format(r"\{'run': 'echo hello', 'shell': \['/bin/bash'\]\}")
+ with pytest.raises(InvalidHookArgumentTypeError, match=message):
+ Cmd({"run": "echo hello", "shell": ["/bin/bash"]}, stack).run()
+
+
+def test_dict_with_typo_shell_raises_exception(stack):
+ import platform
+
+ if platform.python_version().startswith("3.7."):
+ message = r"^\[Errno 2\] No such file or directory: '/bin/bsah': '/bin/bsah'$"
+ else:
+ message = r"^\[Errno 2\] No such file or directory: '/bin/bsah'$"
+ with pytest.raises(FileNotFoundError, match=message):
+ typo = "/bin/bsah"
+ Cmd({"run": "echo hello", "shell": typo}, stack).run()
+
+
+def test_dict_with_non_executable_shell_raises_exception(stack):
+ message = r"^\[Errno 13\] Permission denied: '/'$"
+ with pytest.raises(PermissionError, match=message):
+ Cmd({"run": "echo hello", "shell": "/"}, stack).run()
+
+
+def test_dict_with_empty_shell_raises_exception(stack):
+ message = ERROR_MESSAGE.format(r"\{'run': 'echo hello', 'shell': ''\}")
+ with pytest.raises(InvalidHookArgumentTypeError, match=message):
+ Cmd({"run": "echo hello", "shell": ""}, stack).run()
+
+
+def test_dict_with_null_shell_raises_exception(stack):
+ message = ERROR_MESSAGE.format(r"\{'run': 'echo hello', 'shell': None\}")
+ with pytest.raises(InvalidHookArgumentTypeError, match=message):
+ Cmd({"run": "echo hello", "shell": None}, stack).run()
+
+
+def test_input_exception_reprs_input(stack):
+ import datetime
+
+ exception_message = ERROR_MESSAGE.format(r"datetime.date\(2023, 8, 31\)")
+ with pytest.raises(InvalidHookArgumentTypeError, match=exception_message):
+ Cmd(datetime.date(2023, 8, 31), stack).run()
+
+
+def test_zero_exit_returns(stack):
+ Cmd("exit 0", stack).run()
+
+
+def test_nonzero_exit_raises_exception(stack):
+ message = r"Command 'exit 1' returned non-zero exit status 1\."
+ with pytest.raises(CalledProcessError, match=message):
+ Cmd("exit 1", stack).run()
+
+
+def test_hook_writes_to_stdout(stack, capfd):
+ Cmd("echo hello", stack).run()
+ cap = capfd.readouterr()
+ assert cap.out.strip() == "hello"
+ assert cap.err.strip() == ""
+
+
+def test_hook_writes_to_stderr(stack, capfd):
+ with pytest.raises(Exception):
+ Cmd("missing_command", stack).run()
+ cap = capfd.readouterr()
+ assert cap.out.strip() == ""
+ assert cap.err.strip() == "/bin/sh: 1: missing_command: not found"
+
+
+def test_default_shell_is_sh(stack, capfd):
+ Cmd("echo $0", stack).run()
+ cap = capfd.readouterr()
+ assert cap.out.strip() == "/bin/sh"
+ assert cap.err.strip() == ""
+
+
+def test_shell_parameter_sets_the_shell(stack, capfd):
+ Cmd({"run": "echo $0", "shell": "/bin/bash"}, stack).run()
+ cap = capfd.readouterr()
+ assert cap.out.strip() == "/bin/bash"
+ assert cap.err.strip() == ""
+
-class TestCmd(object):
- def setup_method(self, test_method):
- self.stack = Mock(Stack)
- self.stack.name = "my/stack.yaml"
- self.cmd = Cmd(stack=self.stack)
-
- def test_run_with_non_str_argument(self):
- self.cmd.argument = None
- with pytest.raises(InvalidHookArgumentTypeError):
- self.cmd.run()
-
- @patch("sceptre.hooks.cmd.subprocess.check_call")
- def test_run_with_str_argument(self, mock_call):
- self.cmd.argument = "echo hello"
- self.cmd.run()
- expected_envs = (
- self.stack.connection_manager.create_session_environment_variables.return_value
- )
- mock_call.assert_called_once_with("echo hello", shell=True, env=expected_envs)
-
- @patch("sceptre.hooks.cmd.subprocess.check_call")
- def test_run_with_erroring_command(self, mock_call):
- mock_call.side_effect = subprocess.CalledProcessError(1, "echo")
- self.cmd.argument = "echo hello"
- with pytest.raises(subprocess.CalledProcessError):
- self.cmd.run()
+def test_shell_has_session_environment_variables(stack, capfd):
+ stack.connection_manager.create_session_environment_variables = Mock(
+ return_value={"AWS_PROFILE": "sceptre_profile"}
+ )
+ Cmd("echo $AWS_PROFILE", stack).run()
+ cap = capfd.readouterr()
+ assert cap.out.strip() == "sceptre_profile"
+ assert cap.err.strip() == ""
| Stack outputs in stack groups hide the stack names
### An export format for stack outputs that shows stack name is needed
The main purpose of stack outputs is to consume them in other stacks. Example:
```yaml
VpcId: !stack_output network.yaml::VpcId
```
or in a var file:
```yaml
VpcId: '!stack_output_external my-network-stack::VpcId'
```
In the case of stack groups however, there is no easy way to know which stack exports which outputs without either reading the source, going to the AWS Console, or using AWS CLI commands. Furthermore, even knowing what the stack name of any stack is requires use of Sceptre's `list stacks` command as Sceptre's logic of setting the stack name has never been obvious.
The options we have are:
1. list outputs
```
% sceptre --output=yaml list outputs
---
- direct-connect:
- OutputKey: VPGWId
OutputValue: vgw-1fb1e1e1af11da11b
- vpc:
- ExportName: nonprod-DataSubnetCIDRa
OutputKey: DataSubnetCIDRa
OutputValue: 11.11.111.11/11
- ExportName: nonprod-PublicSubnetCIDRa
OutputKey: PublicSubnetCIDRa
OutputValue: 11.11.111.111/11
...
```
This command is flawed, in that it does not report true stack names, but names like `direct-connect` and `vpc` that only have meaning inside Sceptre itself.
2. list outputs --export=envvar
```
% sceptre --output=yaml list outputs --export=envvar
export SCEPTRE_VPGWId='vgw-1fb1e1e1af11da11b'
export SCEPTRE_DataSubnetCIDRa='11.11.111.11/11'
export SCEPTRE_PublicSubnetCIDRa='11.11.111.111/11'
export SCEPTRE_DataSubnetCIDRb='11.11.111.11/11'
export SCEPTRE_VPCId='vpc-111111ab111a11e11'
...
```
This command is also flawed, as it does not report the stack name at all.
Note that this same CLI behaviour of listing outputs originates in the initial commit of this project back in 2017. In that original version of the code we had:
```python
@cli.command(name="describe-stack-outputs")
@stack_options
@click.option("--export", type=click.Choice(["envvar"]))
@click.pass_context
@catch_exceptions
def describe_stack_outputs(ctx, environment, stack, export):
"""
Describes stack outputs.
Describes ENVIRONMENT/STACK's stack outputs.
"""
env = get_env(ctx.obj["sceptre_dir"], environment, ctx.obj["options"])
response = env.stacks[stack].describe_outputs()
if export == "envvar":
write("\n".join(
[
"export SCEPTRE_{0}={1}".format(
output["OutputKey"], output["OutputValue"]
)
for output in response
]
))
else:
write(response, ctx.obj["output_format"])
```
### Proposal export=stackoutput and export=stackoutputexternal
In addition to `--export=envvar` options like `--export=stackoutput` and `--export=stackoutputexternal` are needed. They might look like this:
```
% sceptre list outputs --export=stackoutput
!stack_output direct-connect.yaml::VPGWId --- vgw-1fb1e1e1af11da111
!stack_output vpc.yaml::DataSubnetCIDRa --- 11.11.111.11/11
!stack_output vpc.yaml::PublicSubnetCIDRa --- 11.11.111.111/11
!stack_output vpc.yaml::DataSubnetCIDRb --- 11.11.111.11/11
!stack_output vpc.yaml::VPCId --- vpc-111111ab111a11e11
...
```
and
```
% sceptre list outputs --export=stackoutputexternal
!stack_output_external nonprod-direct-connect::VPGWId --- vgw-1fb1e1e1af11da111
!stack_output_external nonprod-vpc::DataSubnetCIDRa --- 11.11.111.11/11
!stack_output_external nonprod-vpc::PublicSubnetCIDRa --- 11.11.111.111/11
!stack_output_external nonprod-vpc::DataSubnetCIDRb --- 11.11.111.11/11
!stack_output_external nonprod-vpc::VPCId --- vpc-111111ab111a11e11
...
``` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_cli/test_cli_commands.py::TestCli::test_list_outputs_with_export__stackoutput",
"tests/test_cli/test_cli_commands.py::TestCli::test_list_outputs_with_export__stackoutputexternal",
"tests/test_hooks/test_cmd.py::test_null_input_raises_exception",
"tests/test_hooks/test_cmd.py::test_empty_string_raises_exception",
"tests/test_hooks/test_cmd.py::test_list_raises_exception",
"tests/test_hooks/test_cmd.py::test_dict_without_shell_raises_exception",
"tests/test_hooks/test_cmd.py::test_dict_without_run_raises_exception",
"tests/test_hooks/test_cmd.py::test_dict_with_list_run_raises_exception",
"tests/test_hooks/test_cmd.py::test_dict_with_empty_run_raises_exception",
"tests/test_hooks/test_cmd.py::test_dict_with_null_run_raises_exception",
"tests/test_hooks/test_cmd.py::test_dict_with_list_shell_raises_exception",
"tests/test_hooks/test_cmd.py::test_dict_with_typo_shell_raises_exception",
"tests/test_hooks/test_cmd.py::test_dict_with_non_executable_shell_raises_exception",
"tests/test_hooks/test_cmd.py::test_dict_with_empty_shell_raises_exception",
"tests/test_hooks/test_cmd.py::test_dict_with_null_shell_raises_exception",
"tests/test_hooks/test_cmd.py::test_input_exception_reprs_input",
"tests/test_hooks/test_cmd.py::test_shell_parameter_sets_the_shell"
] | [
"tests/test_cli/test_cli_commands.py::TestCli::test_catch_exceptions",
"tests/test_cli/test_cli_commands.py::TestCli::test_catch_exceptions_debug_mode",
"tests/test_cli/test_cli_commands.py::TestCli::test_user_variables[command0-files0-output0]",
"tests/test_cli/test_cli_commands.py::TestCli::test_user_variables[command1-files1-output1]",
"tests/test_cli/test_cli_commands.py::TestCli::test_user_variables[command2-files2-output2]",
"tests/test_cli/test_cli_commands.py::TestCli::test_user_variables[command3-files3-output3]",
"tests/test_cli/test_cli_commands.py::TestCli::test_user_variables[command4-files4-output4]",
"tests/test_cli/test_cli_commands.py::TestCli::test_user_variables[command5-files5-output5]",
"tests/test_cli/test_cli_commands.py::TestCli::test_user_variables[command6-files6-output6]",
"tests/test_cli/test_cli_commands.py::TestCli::test_user_variables[command7-files7-output7]",
"tests/test_cli/test_cli_commands.py::TestCli::test_user_variables[command8-files8-output8]",
"tests/test_cli/test_cli_commands.py::TestCli::test_user_variables[command9-files9-output9]",
"tests/test_cli/test_cli_commands.py::TestCli::test_user_variables[command10-files10-output10]",
"tests/test_cli/test_cli_commands.py::TestCli::test_user_variables[command11-files11-output11]",
"tests/test_cli/test_cli_commands.py::TestCli::test_user_variables[command12-files12-output12]",
"tests/test_cli/test_cli_commands.py::TestCli::test_user_variables[command13-files13-output13]",
"tests/test_cli/test_cli_commands.py::TestCli::test_user_variables[command14-files14-output14]",
"tests/test_cli/test_cli_commands.py::TestCli::test_validate_template_with_valid_template",
"tests/test_cli/test_cli_commands.py::TestCli::test_validate_template_with_invalid_template",
"tests/test_cli/test_cli_commands.py::TestCli::test_estimate_template_cost_with_browser",
"tests/test_cli/test_cli_commands.py::TestCli::test_estimate_template_cost_with_no_browser",
"tests/test_cli/test_cli_commands.py::TestCli::test_lock_stack",
"tests/test_cli/test_cli_commands.py::TestCli::test_unlock_stack",
"tests/test_cli/test_cli_commands.py::TestCli::test_set_policy_with_file_flag",
"tests/test_cli/test_cli_commands.py::TestCli::test_describe_policy_with_existing_policy",
"tests/test_cli/test_cli_commands.py::TestCli::test_list_group_resources",
"tests/test_cli/test_cli_commands.py::TestCli::test_list_stack_resources",
"tests/test_cli/test_cli_commands.py::TestCli::test_stack_commands[create-True-True-0]",
"tests/test_cli/test_cli_commands.py::TestCli::test_stack_commands[create-False-True-1]",
"tests/test_cli/test_cli_commands.py::TestCli::test_stack_commands[create-True-False-0]",
"tests/test_cli/test_cli_commands.py::TestCli::test_stack_commands[create-False-False-1]",
"tests/test_cli/test_cli_commands.py::TestCli::test_stack_commands[delete-True-True-0]",
"tests/test_cli/test_cli_commands.py::TestCli::test_stack_commands[delete-False-True-1]",
"tests/test_cli/test_cli_commands.py::TestCli::test_stack_commands[delete-True-False-0]",
"tests/test_cli/test_cli_commands.py::TestCli::test_stack_commands[delete-False-False-1]",
"tests/test_cli/test_cli_commands.py::TestCli::test_stack_commands[update-True-True-0]",
"tests/test_cli/test_cli_commands.py::TestCli::test_stack_commands[update-False-True-1]",
"tests/test_cli/test_cli_commands.py::TestCli::test_stack_commands[update-True-False-0]",
"tests/test_cli/test_cli_commands.py::TestCli::test_stack_commands[update-False-False-1]",
"tests/test_cli/test_cli_commands.py::TestCli::test_stack_commands[launch-True-True-0]",
"tests/test_cli/test_cli_commands.py::TestCli::test_stack_commands[launch-False-True-1]",
"tests/test_cli/test_cli_commands.py::TestCli::test_stack_commands[launch-True-False-0]",
"tests/test_cli/test_cli_commands.py::TestCli::test_stack_commands[launch-False-False-1]",
"tests/test_cli/test_cli_commands.py::TestCli::test_ignore_dependencies_commands[create-True]",
"tests/test_cli/test_cli_commands.py::TestCli::test_ignore_dependencies_commands[create-False]",
"tests/test_cli/test_cli_commands.py::TestCli::test_ignore_dependencies_commands[delete-True]",
"tests/test_cli/test_cli_commands.py::TestCli::test_ignore_dependencies_commands[delete-False]",
"tests/test_cli/test_cli_commands.py::TestCli::test_change_set_commands[create-True]",
"tests/test_cli/test_cli_commands.py::TestCli::test_change_set_commands[create-False]",
"tests/test_cli/test_cli_commands.py::TestCli::test_change_set_commands[delete-True]",
"tests/test_cli/test_cli_commands.py::TestCli::test_change_set_commands[delete-False]",
"tests/test_cli/test_cli_commands.py::TestCli::test_change_set_commands[execute-True]",
"tests/test_cli/test_cli_commands.py::TestCli::test_change_set_commands[execute-False]",
"tests/test_cli/test_cli_commands.py::TestCli::test_describe_change_set[False]",
"tests/test_cli/test_cli_commands.py::TestCli::test_describe_change_set[True]",
"tests/test_cli/test_cli_commands.py::TestCli::test_list_change_sets_with_200",
"tests/test_cli/test_cli_commands.py::TestCli::test_list_change_sets_without_200",
"tests/test_cli/test_cli_commands.py::TestCli::test_list_outputs_json",
"tests/test_cli/test_cli_commands.py::TestCli::test_list_outputs_yaml",
"tests/test_cli/test_cli_commands.py::TestCli::test_list_outputs_text",
"tests/test_cli/test_cli_commands.py::TestCli::test_list_outputs_with_export__envvar",
"tests/test_cli/test_cli_commands.py::TestCli::test_list_stacks[dev/vpc.yaml-yaml----\\nmock-stack.yaml:",
"tests/test_cli/test_cli_commands.py::TestCli::test_list_stacks[dev/vpc.yaml-text----\\nmock-stack.yaml:",
"tests/test_cli/test_cli_commands.py::TestCli::test_list_stacks[dev/vpc.yaml-json-{\\n",
"tests/test_cli/test_cli_commands.py::TestCli::test_list_stacks[dev-yaml----\\nmock-stack.yaml:",
"tests/test_cli/test_cli_commands.py::TestCli::test_status_with_group",
"tests/test_cli/test_cli_commands.py::TestCli::test_status_with_stack",
"tests/test_cli/test_cli_commands.py::TestCli::test_new_project_non_existant",
"tests/test_cli/test_cli_commands.py::TestCli::test_new_project_already_exist",
"tests/test_cli/test_cli_commands.py::TestCli::test_new_project_another_exception",
"tests/test_cli/test_cli_commands.py::TestCli::test_create_new_stack_group_folder[A-config_structure0-y\\nA\\nA\\n-result0]",
"tests/test_cli/test_cli_commands.py::TestCli::test_create_new_stack_group_folder[A-config_structure1-y\\n\\n\\n-result1]",
"tests/test_cli/test_cli_commands.py::TestCli::test_create_new_stack_group_folder[A-config_structure2-y\\nA\\nA\\n-result2]",
"tests/test_cli/test_cli_commands.py::TestCli::test_create_new_stack_group_folder[A/A-config_structure3-y\\nA/A\\nA/A\\n-result3]",
"tests/test_cli/test_cli_commands.py::TestCli::test_create_new_stack_group_folder[A/A-config_structure4-y\\nA\\nA\\n-result4]",
"tests/test_cli/test_cli_commands.py::TestCli::test_new_stack_group_folder_with_existing_folder",
"tests/test_cli/test_cli_commands.py::TestCli::test_new_stack_group_folder_with_another_exception",
"tests/test_cli/test_cli_commands.py::TestCli::test_write_output_format_flags[describe-command0-yaml-True]",
"tests/test_cli/test_cli_commands.py::TestCli::test_write_output_format_flags[describe-command1-json-False]",
"tests/test_cli/test_cli_commands.py::TestCli::test_write_output_format_flags[describe-command2-yaml-True]",
"tests/test_cli/test_cli_commands.py::TestCli::test_write_output_format_flags[describe-command3-json-False]",
"tests/test_cli/test_cli_commands.py::TestCli::test_setup_logging_with_debug",
"tests/test_cli/test_cli_commands.py::TestCli::test_setup_logging_without_debug",
"tests/test_cli/test_cli_commands.py::TestCli::test_write_formats[json-True-{\\n",
"tests/test_cli/test_cli_commands.py::TestCli::test_write_formats[json-False-{\\n",
"tests/test_cli/test_cli_commands.py::TestCli::test_write_formats[yaml-True----\\nstack:",
"tests/test_cli/test_cli_commands.py::TestCli::test_write_formats[yaml-False----\\nstack:",
"tests/test_cli/test_cli_commands.py::TestCli::test_write_status_with_colour",
"tests/test_cli/test_cli_commands.py::TestCli::test_write_status_without_colour",
"tests/test_cli/test_cli_commands.py::TestCli::test_ColouredFormatter_format_with_string",
"tests/test_cli/test_cli_commands.py::TestCli::test_CustomJsonEncoder_with_non_json_serialisable_object",
"tests/test_cli/test_cli_commands.py::TestCli::test_diff_command__diff_type_is_deepdiff__passes_deepdiff_stack_differ_to_actions",
"tests/test_cli/test_cli_commands.py::TestCli::test_diff_command__diff_type_is_difflib__passes_difflib_stack_differ_to_actions",
"tests/test_cli/test_cli_commands.py::TestCli::test_diff_command__stack_diffs_have_differences__returns_0",
"tests/test_cli/test_cli_commands.py::TestCli::test_diff_command__no_differences__returns_0",
"tests/test_cli/test_cli_commands.py::TestCli::test_diff_command__bars_are_all_full_width_of_output[**********]",
"tests/test_cli/test_cli_commands.py::TestCli::test_diff_command__bars_are_all_full_width_of_output[----------]",
"tests/test_cli/test_cli_commands.py::TestCli::test_deserialize_json_properties[input0-expected_output0]",
"tests/test_cli/test_cli_commands.py::TestCli::test_deserialize_json_properties[input1-expected_output1]",
"tests/test_cli/test_cli_commands.py::TestCli::test_drift_detect",
"tests/test_cli/test_cli_commands.py::TestCli::test_drift_show",
"tests/test_hooks/test_cmd.py::test_zero_exit_returns",
"tests/test_hooks/test_cmd.py::test_nonzero_exit_raises_exception",
"tests/test_hooks/test_cmd.py::test_hook_writes_to_stdout",
"tests/test_hooks/test_cmd.py::test_hook_writes_to_stderr",
"tests/test_hooks/test_cmd.py::test_default_shell_is_sh",
"tests/test_hooks/test_cmd.py::test_shell_has_session_environment_variables"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
} | "2023-07-09T03:48:44Z" | apache-2.0 |
|
Sceptre__sceptre-1372 | diff --git a/docs/_source/docs/hooks.rst b/docs/_source/docs/hooks.rst
index a1eeef6..9a3bc82 100644
--- a/docs/_source/docs/hooks.rst
+++ b/docs/_source/docs/hooks.rst
@@ -44,23 +44,105 @@ Available Hooks
cmd
~~~
-Executes the argument string in the shell as a Python subprocess.
-
-For more information about how this works, see the `subprocess documentation`_
+Executes a command through the shell.
Syntax:
.. code-block:: yaml
+ # Default shell.
<hook_point>:
- !cmd <shell_command>
-Example:
+ # Another shell.
+ <hook_point>:
+ - !cmd
+ run: <shell_command>
+ shell: <shell_name_or_path>
+
+Pass the command string as the only argument to use the default shell.
+
+On POSIX the default shell is ``sh``. On Windows it's usually ``cmd.exe``, but ``%ComSpec%`` may
+override that.
+
+Write the command string as you would type it at the shell prompt. This includes quotes and
+backslashes to escape filenames with spaces in them. To minimize escaping, you can use YAML plain
+strings like the following examples.
+
+.. code-block:: yaml
+
+ hooks:
+ before_update:
+ - !cmd echo "Hello, world!"
+
+A successful command prints its standard output messages between status messages from Sceptre.
+
+.. code-block::
+
+ [2023-09-03 01:06:28] - test - Launching Stack
+ [2023-09-03 01:06:29] - test - Stack is in the CREATE_COMPLETE state
+ Hello, world!
+ [2023-09-03 01:06:31] - test - Updating Stack
+ [2023-09-03 01:06:31] - test - No updates to perform.
+
+Pass named arguments to use a different shell. Here the command string is called ``run`` and the
+shell executable is called ``shell``.
+
+Write the executable name as you would type it at an interactive prompt to start the shell. For
+example, if Bash is in the system path, you can write ``bash``; otherwise, you need to write the
+absolute path such as ``/bin/bash``.
+
+.. code-block:: yaml
+
+ hooks:
+ before_update:
+ - !cmd
+ run: echo "Hello, $0!"
+ shell: bash
+
+.. code-block:: text
+
+ [2023-09-04 00:29:42] - test - Launching Stack
+ [2023-09-04 00:29:43] - test - Stack is in the CREATE_COMPLETE state
+ Hello, bash!
+ [2023-09-04 00:29:43] - test - Updating Stack
+ [2023-09-04 00:29:43] - test - No updates to perform.
+
+You can use PowerShell in the same way.
+
+.. code-block:: yaml
+
+ hooks:
+ before_update:
+ - !cmd
+ run: Write-Output "Hello, Posh!"
+ shell: pwsh
+
+.. code-block:: text
+
+ [2023-09-04 00:44:32] - test - Launching Stack
+ [2023-09-04 00:44:33] - test - Stack is in the CREATE_COMPLETE state
+ Hello, Posh!
+ [2023-09-04 00:44:34] - test - Updating Stack
+ [2023-09-04 00:44:34] - test - No updates to perform.
+
+If the shell command fails, so does Sceptre. Its output sits between Sceptre's status
+messages and a Python traceback.
.. code-block:: yaml
- before_create:
- - !cmd "echo hello"
+ hooks:
+ before_update:
+ - !cmd missing_command
+
+.. code-block:: text
+
+ [2023-09-04 00:46:25] - test - Launching Stack
+ [2023-09-04 00:46:26] - test - Stack is in the CREATE_COMPLETE state
+ /bin/sh: 1: missing_command: not found
+ Traceback (most recent call last):
+ <snip>
+ subprocess.CalledProcessError: Command 'missing_command' returned non-zero exit status 127.
asg_scaling_processes
~~~~~~~~~~~~~~~~~~~~~
diff --git a/sceptre/hooks/cmd.py b/sceptre/hooks/cmd.py
index 5ec3216..8292e87 100644
--- a/sceptre/hooks/cmd.py
+++ b/sceptre/hooks/cmd.py
@@ -13,16 +13,37 @@ class Cmd(Hook):
def run(self):
"""
- Runs the argument string in a subprocess.
+ Executes a command through the shell.
- :raises: sceptre.exceptions.InvalidTaskArgumentTypeException
- :raises: subprocess.CalledProcessError
+ See hooks documentation for details.
+
+ :raises: sceptre.exceptions.InvalidHookArgumentTypeError invalid input
+ :raises: CalledProcessError failed command
+ :raises: FileNotFoundError missing shell
+ :raises: PermissionError non-executable shell
"""
envs = self.stack.connection_manager.create_session_environment_variables()
- try:
- subprocess.check_call(self.argument, shell=True, env=envs)
- except TypeError:
+
+ if isinstance(self.argument, str) and self.argument != "":
+ command_to_run = self.argument
+ shell = None
+
+ elif (
+ isinstance(self.argument, dict)
+ and set(self.argument) == {"run", "shell"}
+ and isinstance(self.argument["run"], str)
+ and isinstance(self.argument["shell"], str)
+ and self.argument["run"] != ""
+ and self.argument["shell"] != ""
+ ):
+ command_to_run = self.argument["run"]
+ shell = self.argument["shell"]
+
+ else:
raise InvalidHookArgumentTypeError(
- 'The argument "{0}" is the wrong type - cmd hooks require '
- "arguments of type string.".format(self.argument)
+ "A cmd hook requires either a string argument or an object with "
+ "`run` and `shell` keys with string values. "
+ f"You gave `{self.argument!r}`."
)
+
+ subprocess.check_call(command_to_run, shell=True, env=envs, executable=shell)
| Sceptre/sceptre | 64ab818cb9be16276689932b7a15072c3fa6c86e | diff --git a/tests/test_hooks/test_cmd.py b/tests/test_hooks/test_cmd.py
index 3f15a7f..d65b313 100644
--- a/tests/test_hooks/test_cmd.py
+++ b/tests/test_hooks/test_cmd.py
@@ -1,37 +1,174 @@
# -*- coding: utf-8 -*-
-import subprocess
-from unittest.mock import patch, Mock
-
+from subprocess import CalledProcessError
+from unittest.mock import Mock
import pytest
from sceptre.exceptions import InvalidHookArgumentTypeError
from sceptre.hooks.cmd import Cmd
from sceptre.stack import Stack
+ERROR_MESSAGE = (
+ r"^A cmd hook requires either a string argument or an object with `run` and "
+ r"`shell` keys with string values\. You gave `{0}`\.$"
+)
+
+
[email protected]()
+def stack():
+ stack = Stack(
+ "stack1",
+ "project1",
+ "region1",
+ template_handler_config={"template": "path.yaml"},
+ )
+
+ # Otherwise the test works only when the environment variables already set a
+ # valid AWS session.
+ stack.connection_manager.create_session_environment_variables = Mock(
+ return_value={}
+ )
+
+ return stack
+
+
+def test_null_input_raises_exception(stack):
+ message = ERROR_MESSAGE.format(r"None")
+ with pytest.raises(InvalidHookArgumentTypeError, match=message):
+ Cmd(None, stack).run()
+
+
+def test_empty_string_raises_exception(stack):
+ message = ERROR_MESSAGE.format(r"''")
+ with pytest.raises(InvalidHookArgumentTypeError, match=message):
+ Cmd("", stack).run()
+
+
+def test_list_raises_exception(stack):
+ message = ERROR_MESSAGE.format(r"\['echo', 'hello'\]")
+ with pytest.raises(InvalidHookArgumentTypeError, match=message):
+ Cmd(["echo", "hello"], stack).run()
+
+
+def test_dict_without_shell_raises_exception(stack):
+ message = ERROR_MESSAGE.format(r"\{'run': 'echo hello'\}")
+ with pytest.raises(InvalidHookArgumentTypeError, match=message):
+ Cmd({"run": "echo hello"}, stack).run()
+
+
+def test_dict_without_run_raises_exception(stack):
+ message = ERROR_MESSAGE.format(r"\{'shell': '/bin/bash'\}")
+ with pytest.raises(InvalidHookArgumentTypeError, match=message):
+ Cmd({"shell": "/bin/bash"}, stack).run()
+
+
+def test_dict_with_list_run_raises_exception(stack):
+ message = ERROR_MESSAGE.format(
+ r"\{'run': \['echo', 'hello'\], 'shell': '/bin/bash'\}"
+ )
+ with pytest.raises(InvalidHookArgumentTypeError, match=message):
+ Cmd({"run": ["echo", "hello"], "shell": "/bin/bash"}, stack).run()
+
+
+def test_dict_with_empty_run_raises_exception(stack):
+ message = ERROR_MESSAGE.format(r"\{'run': '', 'shell': '/bin/bash'\}")
+ with pytest.raises(InvalidHookArgumentTypeError, match=message):
+ Cmd({"run": "", "shell": "/bin/bash"}, stack).run()
+
+
+def test_dict_with_null_run_raises_exception(stack):
+ message = ERROR_MESSAGE.format(r"\{'run': None, 'shell': '/bin/bash'\}")
+ with pytest.raises(InvalidHookArgumentTypeError, match=message):
+ Cmd({"run": None, "shell": "/bin/bash"}, stack).run()
+
+
+def test_dict_with_list_shell_raises_exception(stack):
+ message = ERROR_MESSAGE.format(r"\{'run': 'echo hello', 'shell': \['/bin/bash'\]\}")
+ with pytest.raises(InvalidHookArgumentTypeError, match=message):
+ Cmd({"run": "echo hello", "shell": ["/bin/bash"]}, stack).run()
+
+
+def test_dict_with_typo_shell_raises_exception(stack):
+ import platform
+
+ if platform.python_version().startswith("3.7."):
+ message = r"^\[Errno 2\] No such file or directory: '/bin/bsah': '/bin/bsah'$"
+ else:
+ message = r"^\[Errno 2\] No such file or directory: '/bin/bsah'$"
+ with pytest.raises(FileNotFoundError, match=message):
+ typo = "/bin/bsah"
+ Cmd({"run": "echo hello", "shell": typo}, stack).run()
+
+
+def test_dict_with_non_executable_shell_raises_exception(stack):
+ message = r"^\[Errno 13\] Permission denied: '/'$"
+ with pytest.raises(PermissionError, match=message):
+ Cmd({"run": "echo hello", "shell": "/"}, stack).run()
+
+
+def test_dict_with_empty_shell_raises_exception(stack):
+ message = ERROR_MESSAGE.format(r"\{'run': 'echo hello', 'shell': ''\}")
+ with pytest.raises(InvalidHookArgumentTypeError, match=message):
+ Cmd({"run": "echo hello", "shell": ""}, stack).run()
+
+
+def test_dict_with_null_shell_raises_exception(stack):
+ message = ERROR_MESSAGE.format(r"\{'run': 'echo hello', 'shell': None\}")
+ with pytest.raises(InvalidHookArgumentTypeError, match=message):
+ Cmd({"run": "echo hello", "shell": None}, stack).run()
+
+
+def test_input_exception_reprs_input(stack):
+ import datetime
+
+ exception_message = ERROR_MESSAGE.format(r"datetime.date\(2023, 8, 31\)")
+ with pytest.raises(InvalidHookArgumentTypeError, match=exception_message):
+ Cmd(datetime.date(2023, 8, 31), stack).run()
+
+
+def test_zero_exit_returns(stack):
+ Cmd("exit 0", stack).run()
+
+
+def test_nonzero_exit_raises_exception(stack):
+ message = r"Command 'exit 1' returned non-zero exit status 1\."
+ with pytest.raises(CalledProcessError, match=message):
+ Cmd("exit 1", stack).run()
+
+
+def test_hook_writes_to_stdout(stack, capfd):
+ Cmd("echo hello", stack).run()
+ cap = capfd.readouterr()
+ assert cap.out.strip() == "hello"
+ assert cap.err.strip() == ""
+
+
+def test_hook_writes_to_stderr(stack, capfd):
+ with pytest.raises(Exception):
+ Cmd("missing_command", stack).run()
+ cap = capfd.readouterr()
+ assert cap.out.strip() == ""
+ assert cap.err.strip() == "/bin/sh: 1: missing_command: not found"
+
+
+def test_default_shell_is_sh(stack, capfd):
+ Cmd("echo $0", stack).run()
+ cap = capfd.readouterr()
+ assert cap.out.strip() == "/bin/sh"
+ assert cap.err.strip() == ""
+
+
+def test_shell_parameter_sets_the_shell(stack, capfd):
+ Cmd({"run": "echo $0", "shell": "/bin/bash"}, stack).run()
+ cap = capfd.readouterr()
+ assert cap.out.strip() == "/bin/bash"
+ assert cap.err.strip() == ""
+
-class TestCmd(object):
- def setup_method(self, test_method):
- self.stack = Mock(Stack)
- self.stack.name = "my/stack.yaml"
- self.cmd = Cmd(stack=self.stack)
-
- def test_run_with_non_str_argument(self):
- self.cmd.argument = None
- with pytest.raises(InvalidHookArgumentTypeError):
- self.cmd.run()
-
- @patch("sceptre.hooks.cmd.subprocess.check_call")
- def test_run_with_str_argument(self, mock_call):
- self.cmd.argument = "echo hello"
- self.cmd.run()
- expected_envs = (
- self.stack.connection_manager.create_session_environment_variables.return_value
- )
- mock_call.assert_called_once_with("echo hello", shell=True, env=expected_envs)
-
- @patch("sceptre.hooks.cmd.subprocess.check_call")
- def test_run_with_erroring_command(self, mock_call):
- mock_call.side_effect = subprocess.CalledProcessError(1, "echo")
- self.cmd.argument = "echo hello"
- with pytest.raises(subprocess.CalledProcessError):
- self.cmd.run()
+def test_shell_has_session_environment_variables(stack, capfd):
+ stack.connection_manager.create_session_environment_variables = Mock(
+ return_value={"AWS_PROFILE": "sceptre_profile"}
+ )
+ Cmd("echo $AWS_PROFILE", stack).run()
+ cap = capfd.readouterr()
+ assert cap.out.strip() == "sceptre_profile"
+ assert cap.err.strip() == ""
| !cmd hook runs in `sh`, which is not my default shell
### Subject of the issue
When I use a `!cmd` hook, it appears to be run by `sh` because I receive this error:
```shell
/bin/sh: 1: [[: not found
```
Is there a way to force the underlying `subprocess.run()` call to use Python? I know I can do this in Python by using arguments that look like `["bash", "-c", "your command goes here"]`, and, in fact, if I simply pass in `["your command goes here"]` in Python, it will run in bash because it is my default shell. Is `sceptre` really running my hook using `sh`? If so, how can I make it use `bash` instead?
### Your environment
* version of sceptre (sceptre --version)
**Sceptre, version 2.4.0**
* version of python (python --version)
**Python 3.8.10**
* which OS/distro
**Ubuntu 20.04.3 LTS on 4.4.0-19041-Microsoft #1237-Microsoft x86_64**
### Steps to reproduce
Tell us how to reproduce this issue. Please provide sceptre project files if possible,
you can use https://plnkr.co/edit/ANFHm61Ilt4mQVgF as a base.
Here is a hook that causes the behavior:
```yaml
hooks:
before_update:
- !cmd 'if [[ "{{ var.update_lambdas | default("false") }}" == "true" ]]; then lambdas/deploy-lambdas.sh -u "$(./get-stack-output.sh "{{ environment }}/{{ region }}/LambdaS3Bucket.yaml" LambdaBucketName)" HandleServiceAccountAppGitHubWebhook; fi;'
```
### Expected behaviour
The hook should run successfully using my default shell, which is `bash`.
### Actual behaviour
I see the error `/bin/sh: 1: [[: not found` instead.
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_hooks/test_cmd.py::test_null_input_raises_exception",
"tests/test_hooks/test_cmd.py::test_empty_string_raises_exception",
"tests/test_hooks/test_cmd.py::test_list_raises_exception",
"tests/test_hooks/test_cmd.py::test_dict_without_shell_raises_exception",
"tests/test_hooks/test_cmd.py::test_dict_without_run_raises_exception",
"tests/test_hooks/test_cmd.py::test_dict_with_list_run_raises_exception",
"tests/test_hooks/test_cmd.py::test_dict_with_empty_run_raises_exception",
"tests/test_hooks/test_cmd.py::test_dict_with_null_run_raises_exception",
"tests/test_hooks/test_cmd.py::test_dict_with_list_shell_raises_exception",
"tests/test_hooks/test_cmd.py::test_dict_with_typo_shell_raises_exception",
"tests/test_hooks/test_cmd.py::test_dict_with_non_executable_shell_raises_exception",
"tests/test_hooks/test_cmd.py::test_dict_with_empty_shell_raises_exception",
"tests/test_hooks/test_cmd.py::test_dict_with_null_shell_raises_exception",
"tests/test_hooks/test_cmd.py::test_input_exception_reprs_input",
"tests/test_hooks/test_cmd.py::test_shell_parameter_sets_the_shell"
] | [
"tests/test_hooks/test_cmd.py::test_zero_exit_returns",
"tests/test_hooks/test_cmd.py::test_nonzero_exit_raises_exception",
"tests/test_hooks/test_cmd.py::test_hook_writes_to_stdout",
"tests/test_hooks/test_cmd.py::test_hook_writes_to_stderr",
"tests/test_hooks/test_cmd.py::test_default_shell_is_sh",
"tests/test_hooks/test_cmd.py::test_shell_has_session_environment_variables"
] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_issue_reference",
"has_many_modified_files",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
} | "2023-08-27T18:30:07Z" | apache-2.0 |
|
Sceptre__sceptre-1391 | diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 9c25517..da8c1e4 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -47,7 +47,7 @@ repos:
language_version: python3.10
args: ['--check']
- repo: https://github.com/sirosen/check-jsonschema
- rev: 0.27.3
+ rev: 0.27.4
hooks:
- id: check-github-workflows
- id: check-github-actions
diff --git a/sceptre/resolvers/stack_output.py b/sceptre/resolvers/stack_output.py
index 6b22541..994636c 100644
--- a/sceptre/resolvers/stack_output.py
+++ b/sceptre/resolvers/stack_output.py
@@ -6,7 +6,12 @@ import shlex
from botocore.exceptions import ClientError
-from sceptre.exceptions import DependencyStackMissingOutputError, StackDoesNotExistError
+from sceptre.exceptions import (
+ DependencyStackMissingOutputError,
+ StackDoesNotExistError,
+ SceptreException,
+)
+
from sceptre.helpers import normalise_path, sceptreise_path
from sceptre.resolvers import Resolver
@@ -108,7 +113,13 @@ class StackOutput(StackOutputBase):
"""
Adds dependency to a Stack.
"""
- dep_stack_name, self.output_key = self.argument.split("::")
+ try:
+ dep_stack_name, self.output_key = self.argument.split("::")
+ except ValueError as err:
+ raise SceptreException(
+ "!stack_output arg should match STACK_NAME::OUTPUT_KEY"
+ ) from err
+
self.dependency_stack_name = sceptreise_path(normalise_path(dep_stack_name))
self.stack.dependencies.append(self.dependency_stack_name)
@@ -120,7 +131,6 @@ class StackOutput(StackOutputBase):
:rtype: str
"""
self.logger.debug("Resolving Stack output: {0}".format(self.argument))
-
friendly_stack_name = self.dependency_stack_name.replace(TEMPLATE_EXTENSION, "")
stack = next(
@@ -163,21 +173,43 @@ class StackOutputExternal(StackOutputBase):
"""
self.logger.debug("Resolving external Stack output: {0}".format(self.argument))
- profile = None
- region = None
- sceptre_role = None
arguments = shlex.split(self.argument)
+ if not arguments:
+ message = "!stack_output_external requires at least one argument"
+ raise SceptreException(message)
+
stack_argument = arguments[0]
+ stack_args = iter(stack_argument.split("::"))
+
+ try:
+ dependency_stack_name = next(stack_args)
+ output_key = next(stack_args)
+
+ except StopIteration as err:
+ message = "!stack_output_external arg should match STACK_NAME::OUTPUT_KEY"
+ raise SceptreException(message) from err
+
+ profile = region = sceptre_role = None
+
if len(arguments) > 1:
- extra_args = arguments[1].split("::", 2)
- profile, region, sceptre_role = extra_args + (3 - len(extra_args)) * [None]
+ extra_args = iter(arguments[1].split("::"))
+
+ profile = next(extra_args, None)
+ region = next(extra_args, None)
+ sceptre_role = next(extra_args, None)
+
+ try:
+ next(extra_args)
+ message = (
+ "!stack_output_external second arg should be "
+ "in the format 'PROFILE[::REGION[::SCEPTRE_ROLE]]'"
+ )
+ raise SceptreException(message)
+
+ except StopIteration:
+ pass
- dependency_stack_name, output_key = stack_argument.split("::")
return self._get_output_value(
- dependency_stack_name,
- output_key,
- profile or None,
- region or None,
- sceptre_role or None,
+ dependency_stack_name, output_key, profile, region, sceptre_role
)
| Sceptre/sceptre | 3f16beda2a51db8bf7b7de87fbaad2582387897f | diff --git a/tests/test_resolvers/test_stack_output.py b/tests/test_resolvers/test_stack_output.py
index ff20eff..0d671ac 100644
--- a/tests/test_resolvers/test_stack_output.py
+++ b/tests/test_resolvers/test_stack_output.py
@@ -5,6 +5,7 @@ from unittest.mock import MagicMock, patch, sentinel
from sceptre.exceptions import DependencyStackMissingOutputError
from sceptre.exceptions import StackDoesNotExistError
+from sceptre.exceptions import SceptreException
from botocore.exceptions import ClientError
@@ -58,7 +59,10 @@ class TestStackOutputResolver(object):
stack_output_resolver = StackOutput("not_a_valid_stack_output", stack)
- with pytest.raises(ValueError, match="not enough values to unpack"):
+ with pytest.raises(
+ SceptreException,
+ match="!stack_output arg should match STACK_NAME::OUTPUT_KEY",
+ ):
stack_output_resolver.setup()
@patch("sceptre.resolvers.stack_output.StackOutput._get_output_value")
@@ -191,7 +195,10 @@ class TestStackOutputExternalResolver(object):
"not_a_valid_stack_output", stack
)
- with pytest.raises(ValueError, match="not enough values to unpack"):
+ with pytest.raises(
+ SceptreException,
+ match="!stack_output_external arg should match STACK_NAME::OUTPUT_KEY",
+ ):
stack_output_external_resolver.resolve()
@patch("sceptre.resolvers.stack_output.StackOutputExternal._get_output_value")
| Not enough values to unpack given a badly formatted stack ref
### Subject of the issue
If a stack output is incorrectly formatted, and missing `::`, a confusing and unhandled exception is seen:
```
[2023-11-24 01:53:39] - REDACTED - Successfully initiated creation of Change Set 'sceptre-foundations-3551-834819d8978ad61146f7c9d9d30cae792d4fe192'
Traceback (most recent call last):
File "/usr/local/bin/sceptre", line 8, in <module>
sys.exit(cli())
File "/usr/local/lib/python3.10/site-packages/click/core.py", line 1130, in __call__
return self.main(*args, **kwargs)
File "/usr/local/lib/python3.10/site-packages/click/core.py", line 1055, in main
rv = self.invoke(ctx)
File "/usr/local/lib/python3.10/site-packages/click/core.py", line 1657, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/usr/local/lib/python3.10/site-packages/click/core.py", line 1404, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/usr/local/lib/python3.10/site-packages/click/core.py", line 760, in invoke
return __callback(*args, **kwargs)
File "/usr/local/lib/python3.10/site-packages/click/decorators.py", line 26, in new_func
return f(get_current_context(), *args, **kwargs)
File "/usr/local/lib/python3.10/site-packages/sceptre/cli/helpers.py", line 46, in decorated
return func(*args, **kwargs)
File "/usr/local/lib/python3.10/site-packages/sceptre/cli/create.py", line 49, in create_command
plan.create_change_set(change_set_name)
File "/usr/local/lib/python3.10/site-packages/sceptre/plan/plan.py", line 286, in create_change_set
return self._execute(*args)
File "/usr/local/lib/python3.10/site-packages/sceptre/plan/plan.py", line 30, in wrapped
return func(self, *args, **kwargs)
File "/usr/local/lib/python3.10/site-packages/sceptre/plan/plan.py", line 56, in _execute
return executor.execute(*args)
File "/usr/local/lib/python3.10/site-packages/sceptre/plan/executor.py", line 52, in execute
stack, status = future.result()
File "/usr/local/lib/python3.10/concurrent/futures/_base.py", line 451, in result
return self.__get_result()
File "/usr/local/lib/python3.10/concurrent/futures/_base.py", line 403, in __get_result
raise self._exception
File "/usr/local/lib/python3.10/concurrent/futures/thread.py", line 58, in run
result = self.fn(*self.args, **self.kwargs)
File "/usr/local/lib/python3.10/site-packages/sceptre/plan/executor.py", line 59, in _execute
result = getattr(actions, self.command)(*args)
File "/usr/local/lib/python3.10/site-packages/sceptre/hooks/__init__.py", line 95, in decorated
response = func(self, *args, **kwargs)
File "/usr/local/lib/python3.10/site-packages/sceptre/plan/actions.py", line 445, in create_change_set
"Parameters": self._format_parameters(self.stack.parameters),
File "/usr/local/lib/python3.10/site-packages/sceptre/resolvers/__init__.py", line 321, in __get__
container = super().__get__(stack, stack_class)
File "/usr/local/lib/python3.10/site-packages/sceptre/resolvers/__init__.py", line 230, in __get__
return self.get_resolved_value(stack, stack_class)
File "/usr/local/lib/python3.10/site-packages/sceptre/resolvers/__init__.py", line 371, in get_resolved_value
_call_func_on_values(resolve, container, Resolver)
File "/usr/local/lib/python3.10/site-packages/sceptre/helpers.py", line 91, in _call_func_on_values
func_on_instance(key)
File "/usr/local/lib/python3.10/site-packages/sceptre/helpers.py", line 85, in func_on_instance
func(attr, key, value)
File "/usr/local/lib/python3.10/site-packages/sceptre/resolvers/__init__.py", line 345, in resolve
result = self.resolve_resolver_value(value)
File "/usr/local/lib/python3.10/site-packages/sceptre/resolvers/__init__.py", line 2[84](https://github.com/REDACTED/actions/runs/6975938755/job/18983741778?pr=3551#step:9:86), in resolve_resolver_value
return resolver.resolve()
File "/usr/local/lib/python3.10/site-packages/sceptre/resolvers/stack_output.py", line 176, in resolve
dependency_stack_name, output_key = stack_argument.split("::")
ValueError: not enough values to unpack (expected 2, got 1)
```
### Your environment
* version of sceptre (sceptre --version) 4.3.0
* version of python (python --version) 3.10
* which OS/distro
### Steps to reproduce
Create a stack reference like
```
!stack_output_external myStackName
```
Noting that this is incomplete and missing the `::`.
### Expected behaviour
It should error out with a more helpful error message informing the expected format of the reference compared to the actual format.
### Actual behaviour
```
ValueError: not enough values to unpack (expected 2, got 1)
``` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_resolvers/test_stack_output.py::TestStackOutputResolver::test_resolver__badly_formatted",
"tests/test_resolvers/test_stack_output.py::TestStackOutputExternalResolver::test_resolve__badly_formatted"
] | [
"tests/test_resolvers/test_stack_output.py::TestStackOutputResolver::test_resolver",
"tests/test_resolvers/test_stack_output.py::TestStackOutputResolver::test_resolver_with_existing_dependencies",
"tests/test_resolvers/test_stack_output.py::TestStackOutputResolver::test_resolve_with_implicit_stack_reference",
"tests/test_resolvers/test_stack_output.py::TestStackOutputResolver::test_resolve_with_implicit_stack_reference_top_level",
"tests/test_resolvers/test_stack_output.py::TestStackOutputExternalResolver::test_resolve",
"tests/test_resolvers/test_stack_output.py::TestStackOutputExternalResolver::test_resolve_with_args",
"tests/test_resolvers/test_stack_output.py::TestStackOutputBaseResolver::test_get_output_value_with_valid_key",
"tests/test_resolvers/test_stack_output.py::TestStackOutputBaseResolver::test_get_output_value_with_invalid_key",
"tests/test_resolvers/test_stack_output.py::TestStackOutputBaseResolver::test_get_stack_outputs_with_valid_stack",
"tests/test_resolvers/test_stack_output.py::TestStackOutputBaseResolver::test_get_stack_outputs_with_valid_stack_without_outputs",
"tests/test_resolvers/test_stack_output.py::TestStackOutputBaseResolver::test_get_stack_outputs_with_unlaunched_stack",
"tests/test_resolvers/test_stack_output.py::TestStackOutputBaseResolver::test_get_stack_outputs_with_unkown_boto_error"
] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_git_commit_hash",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
} | "2023-11-27T15:13:17Z" | apache-2.0 |
|
Sceptre__sceptre-1442 | diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 25013c5..ace46ff 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -13,11 +13,11 @@ repos:
hooks:
- id: flake8
- repo: https://github.com/adrienverge/yamllint
- rev: v1.34.0
+ rev: v1.35.1
hooks:
- id: yamllint
- repo: https://github.com/awslabs/cfn-python-lint
- rev: v0.85.1
+ rev: v0.85.2
hooks:
- id: cfn-python-lint
args:
diff --git a/sceptre/stack.py b/sceptre/stack.py
index 8a63309..fa5639a 100644
--- a/sceptre/stack.py
+++ b/sceptre/stack.py
@@ -9,7 +9,7 @@ This module implements a Stack class, which stores a Stack's data.
import logging
-from typing import List, Any, Optional
+from typing import List, Dict, Union, Any, Optional
from deprecation import deprecated
from sceptre import __version__
@@ -26,6 +26,7 @@ from sceptre.resolvers import (
ResolvableValueProperty,
RecursiveResolve,
PlaceholderType,
+ Resolver,
)
from sceptre.template import Template
@@ -262,7 +263,7 @@ class Stack:
)
self.s3_details = s3_details
- self.parameters = parameters or {}
+ self.parameters = self._ensure_parameters(parameters or {})
self.sceptre_user_data = sceptre_user_data or {}
self.notifications = notifications or []
@@ -275,6 +276,30 @@ class Stack:
)
return value
+ def _ensure_parameters(
+ self, parameters: Dict[str, Any]
+ ) -> Dict[str, Union[str, List[Union[str, Resolver]], Resolver]]:
+ """Ensure CloudFormation parameters are of valid types"""
+
+ def is_valid(value: Any) -> bool:
+ return (
+ isinstance(value, str)
+ or (
+ isinstance(value, list)
+ and all(
+ isinstance(item, str) or isinstance(item, Resolver)
+ for item in value
+ )
+ )
+ or isinstance(value, Resolver)
+ )
+
+ if not all(is_valid(value) for value in parameters.values()):
+ raise InvalidConfigFileError(
+ f"{self.name}: Values for parameters must be strings, lists or resolvers, got {parameters}"
+ )
+ return parameters
+
def __repr__(self):
return (
"sceptre.stack.Stack("
| Sceptre/sceptre | 68db2e0bc0579e89ab64b408d328205eaa4dac1d | diff --git a/tests/test_stack.py b/tests/test_stack.py
index 7e843e4..6f67e08 100644
--- a/tests/test_stack.py
+++ b/tests/test_stack.py
@@ -40,6 +40,11 @@ def stack_factory(**kwargs):
return Stack(**call_kwargs)
+class FakeResolver(Resolver):
+ def resolve(self):
+ return "Fake"
+
+
class TestStack(object):
def setup_method(self, test_method):
self.stack = Stack(
@@ -183,6 +188,46 @@ class TestStack(object):
obsolete="true",
)
+ @pytest.mark.parametrize(
+ "parameters",
+ [
+ {"someNum": 1},
+ {"someBool": True},
+ {"aBadList": [1, 2, 3]},
+ {"aDict": {"foo": "bar"}},
+ ],
+ )
+ def test_init__invalid_parameters_raise_invalid_config_file_error(self, parameters):
+ with pytest.raises(InvalidConfigFileError):
+ Stack(
+ name="stack_name",
+ project_code="project_code",
+ template_handler_config={"type": "file"},
+ region="region",
+ parameters=parameters,
+ )
+
+ @pytest.mark.parametrize(
+ "parameters",
+ [
+ {"someNum": "1"},
+ {"someBool": "true"},
+ {"aList": ["aString", FakeResolver()]},
+ {"aResolver": FakeResolver()},
+ ],
+ )
+ def test_init__valid_parameters_do_not_raise_invalid_config_file_error(
+ self, parameters
+ ):
+ stack = Stack(
+ name="stack_name",
+ project_code="project_code",
+ template_handler_config={"type": "file"},
+ region="region",
+ parameters=parameters,
+ )
+ assert isinstance(stack, Stack)
+
def test_stack_repr(self):
assert (
self.stack.__repr__() == "sceptre.stack.Stack("
@@ -248,14 +293,10 @@ class TestStack(object):
def test_configuration_manager__sceptre_role_returns_value__returns_connection_manager_with_that_role(
self,
):
- class FakeResolver(Resolver):
- def resolve(self):
- return "role"
-
self.stack.sceptre_role = FakeResolver()
connection_manager = self.stack.connection_manager
- assert connection_manager.sceptre_role == "role"
+ assert connection_manager.sceptre_role == "Fake"
@fail_if_not_removed
def test_iam_role__is_removed_on_removal_version(self):
| Input parameters should be validated
### Subject of the issue
For historical reasons, Sceptre has never validated input parameters that are passed in to CloudFormation stack parameters. Blocks that contain bools, ints etc give rise to confusing failures. For example:
```yaml
parameters:
someBool: true
```
Would lead to an error appearing like:
```
"Parameter validation failed:\nInvalid type for parameter Parameters[0].ParameterValue, value: 1, type: <class 'bool'>, valid types: <class 'str'>"
```
In more complicated examples it is often quite unclear what `Parameter[0]` means.
A feature requested here to add a layer of input data validation at the time of Stack instantiation after discussion with @jfalkenstein in Slack.
### Your environment
* version of sceptre (sceptre --version) latest
* version of python (python --version) 3.10
* which OS/distro
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_stack.py::TestStack::test_init__invalid_parameters_raise_invalid_config_file_error[parameters0]",
"tests/test_stack.py::TestStack::test_init__invalid_parameters_raise_invalid_config_file_error[parameters1]",
"tests/test_stack.py::TestStack::test_init__invalid_parameters_raise_invalid_config_file_error[parameters2]",
"tests/test_stack.py::TestStack::test_init__invalid_parameters_raise_invalid_config_file_error[parameters3]"
] | [
"tests/test_stack.py::TestStack::test_initialize_stack_with_template_path",
"tests/test_stack.py::TestStack::test_initialize_stack_with_template_handler",
"tests/test_stack.py::TestStack::test_raises_exception_if_path_and_handler_configured",
"tests/test_stack.py::TestStack::test_init__non_boolean_ignore_value__raises_invalid_config_file_error",
"tests/test_stack.py::TestStack::test_init__non_boolean_obsolete_value__raises_invalid_config_file_error",
"tests/test_stack.py::TestStack::test_init__valid_parameters_do_not_raise_invalid_config_file_error[parameters0]",
"tests/test_stack.py::TestStack::test_init__valid_parameters_do_not_raise_invalid_config_file_error[parameters1]",
"tests/test_stack.py::TestStack::test_init__valid_parameters_do_not_raise_invalid_config_file_error[parameters2]",
"tests/test_stack.py::TestStack::test_init__valid_parameters_do_not_raise_invalid_config_file_error[parameters3]",
"tests/test_stack.py::TestStack::test_stack_repr",
"tests/test_stack.py::TestStack::test_configuration_manager__sceptre_role_raises_recursive_resolve__returns_connection_manager_with_no_role",
"tests/test_stack.py::TestStack::test_configuration_manager__sceptre_role_returns_value_second_access__returns_value_on_second_access",
"tests/test_stack.py::TestStack::test_configuration_manager__sceptre_role_returns_value__returns_connection_manager_with_that_role",
"tests/test_stack.py::TestStack::test_iam_role__is_removed_on_removal_version",
"tests/test_stack.py::TestStack::test_role_arn__is_removed_on_removal_version",
"tests/test_stack.py::TestStack::test_iam_role_session_duration__is_removed_on_removal_version",
"tests/test_stack.py::TestStack::test_init__iam_role_set_resolves_to_sceptre_role",
"tests/test_stack.py::TestStack::test_init__role_arn_set_resolves_to_cloudformation_service_role",
"tests/test_stack.py::TestStack::test_init__iam_role_session_duration_set_resolves_to_sceptre_role_session_duration",
"tests/test_stack.py::TestStackSceptreUserData::test_user_data_is_accessible",
"tests/test_stack.py::TestStackSceptreUserData::test_user_data_gets_resolved",
"tests/test_stack.py::TestStackSceptreUserData::test_recursive_user_data_gets_resolved"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2024-02-17T02:10:13Z" | apache-2.0 |
|
Sceptre__sceptre-1445 | diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index ace46ff..95677b3 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -17,7 +17,7 @@ repos:
hooks:
- id: yamllint
- repo: https://github.com/awslabs/cfn-python-lint
- rev: v0.85.2
+ rev: v0.86.0
hooks:
- id: cfn-python-lint
args:
@@ -36,11 +36,11 @@ repos:
^.pre-commit-config.yaml
)
- repo: https://github.com/psf/black
- rev: 24.2.0
+ rev: 24.3.0
hooks:
- id: black
- repo: https://github.com/python-poetry/poetry
- rev: '1.7.0'
+ rev: '1.8.0'
hooks:
- id: poetry-check
- id: poetry-lock
diff --git a/docs/_source/docs/stack_config.rst b/docs/_source/docs/stack_config.rst
index 52ff8db..d8e8807 100644
--- a/docs/_source/docs/stack_config.rst
+++ b/docs/_source/docs/stack_config.rst
@@ -15,13 +15,16 @@ particular Stack. The available keys are listed below.
- `template_path`_ or `template`_ *(required)*
- `dependencies`_ *(optional)*
+- `dependencies_inheritance`_ *(optional)*
- `hooks`_ *(optional)*
+- `hooks_inheritance`_ *(optional)*
- `ignore`_ *(optional)*
- `notifications`_ *(optional)*
- `obsolete`_ *(optional)*
- `on_failure`_ *(optional)*
- `disable_rollback`_ *(optional)*
- `parameters`_ *(optional)*
+- `parameters_inheritance`_ *(optional)*
- `protected`_ *(optional)*
- `role_arn`_ *(optional)*
- `cloudformation_service_role`_ *(optional)*
@@ -30,8 +33,10 @@ particular Stack. The available keys are listed below.
- `iam_role_session_duration`_ *(optional)*
- `sceptre_role_session_duration`_ *(optional)*
- `sceptre_user_data`_ *(optional)*
+- `sceptre_user_data_inheritance`_ *(optional)*
- `stack_name`_ *(optional)*
- `stack_tags`_ *(optional)*
+- `stack_tags_inheritance`_ *(optional)*
- `stack_timeout`_ *(optional)*
It is not possible to define both `template_path`_ and `template`_. If you do so,
@@ -80,7 +85,7 @@ dependencies
~~~~~~~~~~~~
* Resolvable: No
* Can be inherited from StackGroup: Yes
-* Inheritance strategy: Appended to parent's dependencies
+* Inheritance strategy: Appended to parent's dependencies. Configurable with ``dependencies_inheritance`` parameter.
A list of other Stacks in the environment that this Stack depends on. Note that
if a Stack fetches an output value from another Stack using the
@@ -97,15 +102,39 @@ and that Stack need not be added as an explicit dependency.
situation by either (a) setting those ``dependencies`` on individual Stack Configs rather than the
the StackGroup Config, or (b) moving those dependency stacks outside of the StackGroup.
+dependencies_inheritance
+~~~~~~~~~~~~~~~~~~~~~~~~
+* Resolvable: No
+* Can be inherited from StackGroup: Yes
+* Inheritance strategy: Overrides parent if set
+
+This configuration will override the default inheritance strategy of `dependencies`.
+
+The default value for this is ``merge``.
+
+Valid values for this config are: ``merge``, or ``override``.
+
hooks
~~~~~
* Resolvable: No (but you can use resolvers _in_ hook arguments!)
* Can be inherited from StackGroup: Yes
-* Inheritance strategy: Overrides parent if set
+* Inheritance strategy: Overrides parent if set. Configurable with ``hooks_inheritance`` parameter.
A list of arbitrary shell or Python commands or scripts to run. Find out more
in the :doc:`hooks` section.
+hooks_inheritance
+~~~~~~~~~~~~~~~~~~~~~~~~
+* Resolvable: No
+* Can be inherited from StackGroup: Yes
+* Inheritance strategy: Overrides parent if set
+
+This configuration will override the default inheritance strategy of `hooks`.
+
+The default value for this is ``override``.
+
+Valid values for this config are: ``merge``, or ``override``.
+
ignore
~~~~~~
* Resolvable: No
@@ -155,7 +184,7 @@ notifications
List of SNS topic ARNs to publish Stack related events to. A maximum of 5 ARNs
can be specified per Stack. This configuration will be used by the ``create``,
-``update``, and ``delete`` commands. More information about Stack notifications
+``update``, or ``delete`` commands. More information about Stack notifications
can found under the relevant section in the `AWS CloudFormation API
documentation`_.
@@ -231,7 +260,7 @@ parameters
~~~~~~~~~~
* Resolvable: Yes
* Can be inherited from StackGroup: Yes
-* Inheritance strategy: Overrides parent if set
+* Inheritance strategy: Overrides parent if set. Configurable with ``parameters_inheritance`` parameter.
.. warning::
@@ -241,7 +270,7 @@ parameters
environment variable resolver.
A dictionary of key-value pairs to be supplied to a template as parameters. The
-keys must match up with the name of the parameter, and the value must be of the
+keys must match up with the name of the parameter, or the value must be of the
type as defined in the template.
.. note::
@@ -292,6 +321,18 @@ Example:
- !stack_output security-groups.yaml::BaseSecurityGroupId
- !file_contents /file/with/security_group_id.txt
+parameters_inheritance
+~~~~~~~~~~~~~~~~~~~~~~~~
+* Resolvable: No
+* Can be inherited from StackGroup: Yes
+* Inheritance strategy: Overrides parent if set
+
+This configuration will override the default inheritance strategy of `parameters`.
+
+The default value for this is ``override``.
+
+Valid values for this config are: ``merge``, or ``override``.
+
protected
~~~~~~~~~
* Resolvable: No
@@ -391,12 +432,24 @@ sceptre_user_data
~~~~~~~~~~~~~~~~~
* Resolvable: Yes
* Can be inherited from StackGroup: Yes
-* Inheritance strategy: Overrides parent if set
+* Inheritance strategy: Overrides parent if set. Configurable with ``sceptre_user_data_inheritance`` parameter.
Represents data to be passed to the ``sceptre_handler(sceptre_user_data)``
function in Python templates or accessible under ``sceptre_user_data`` variable
key within Jinja2 templates.
+sceptre_user_data_inheritance
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+* Resolvable: No
+* Can be inherited from StackGroup: Yes
+* Inheritance strategy: Overrides parent if set
+
+This configuration will override the default inheritance strategy of `sceptre_user_data`.
+
+The default value for this is ``override``.
+
+Valid values for this config are: ``merge``, or ``override``.
+
stack_name
~~~~~~~~~~
* Resolvable: No
@@ -436,10 +489,22 @@ stack_tags
~~~~~~~~~~
* Resolvable: Yes
* Can be inherited from StackGroup: Yes
-* Inheritance strategy: Overrides parent if set
+* Inheritance strategy: Overrides parent if set. Configurable with ``stack_tags_inheritance`` parameter.
A dictionary of `CloudFormation Tags`_ to be applied to the Stack.
+stack_tags_inheritance
+~~~~~~~~~~~~~~~~~~~~~~~~
+* Resolvable: No
+* Can be inherited from StackGroup: Yes
+* Inheritance strategy: Overrides parent if set
+
+This configuration will override the default inheritance strategy of `stack_tags`.
+
+The default value for this is ``override``.
+
+Valid values for this config are: ``merge``, or ``override``.
+
stack_timeout
~~~~~~~~~~~~~
* Resolvable: No
diff --git a/docs/_source/docs/stack_group_config.rst b/docs/_source/docs/stack_group_config.rst
index 3da527e..2638dc2 100644
--- a/docs/_source/docs/stack_group_config.rst
+++ b/docs/_source/docs/stack_group_config.rst
@@ -175,7 +175,7 @@ configurations should be defined at a lower directory level.
YAML files that define configuration settings with conflicting keys, the child
configuration file will usually take precedence (see the specific config keys as documented
-for the inheritance strategy employed).
+for the inheritance strategy employed and `Inheritance Strategy Override`_).
In the above directory structure, ``config/config.yaml`` will be read in first,
followed by ``config/account-1/config.yaml``, followed by
@@ -185,6 +185,16 @@ For example, if you wanted the ``dev`` StackGroup to build to a different
region, this setting could be specified in the ``config/dev/config.yaml`` file,
and would only be applied to builds in the ``dev`` StackGroup.
+Inheritance Strategy Override
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+The inheritance strategy of some properties may be overridden by the stack group config.
+
+Strategy options:
+
+* ``merge``: Child config is merged with parent configs, with child taking precedence for conflicting dictionary keys.
+* ``override``: Overrides the parent config, if set.
+
.. _setting_dependencies_for_stack_groups:
Setting Dependencies for StackGroups
diff --git a/sceptre/config/graph.py b/sceptre/config/graph.py
index 34d6b79..1ad11da 100644
--- a/sceptre/config/graph.py
+++ b/sceptre/config/graph.py
@@ -90,14 +90,18 @@ class StackGraph(object):
:param stack: A Sceptre Stack
:param dependencies: a collection of dependency paths
"""
- self.logger.debug("Generate dependencies for stack {0}".format(stack))
+ self.logger.debug(f"Generate dependencies for stack {stack}")
for dependency in set(dependencies):
self.graph.add_edge(dependency, stack)
- if not nx.is_directed_acyclic_graph(self.graph):
+ try:
+ cycle = nx.find_cycle(self.graph, orientation="original")
+ cycle_str = ", ".join([f"{edge[0]} -> {edge[1]}" for edge in cycle])
raise CircularDependenciesError(
- f"Dependency cycle detected: {stack} {dependency}"
+ f"Dependency cycle detected: {cycle_str}"
)
- self.logger.debug(" Added dependency: {}".format(dependency))
+ except nx.NetworkXNoCycle:
+ pass # No cycle, continue
+ self.logger.debug(f" Added dependency: {dependency}")
if not dependencies:
self.graph.add_node(stack)
diff --git a/sceptre/config/reader.py b/sceptre/config/reader.py
index c1a1018..fc74217 100644
--- a/sceptre/config/reader.py
+++ b/sceptre/config/reader.py
@@ -39,16 +39,30 @@ from sceptre.config import strategies
ConfigAttributes = collections.namedtuple("Attributes", "required optional")
+
+CONFIG_MERGE_STRATEGY_OVERRIDES = {
+ "dependencies": strategies.LIST_STRATEGIES,
+ "hooks": strategies.LIST_STRATEGIES,
+ "notifications": strategies.LIST_STRATEGIES,
+ "parameters": strategies.DICT_STRATEGIES,
+ "sceptre_user_data": strategies.DICT_STRATEGIES,
+ "stack_tags": strategies.DICT_STRATEGIES,
+}
+
CONFIG_MERGE_STRATEGIES = {
"dependencies": strategies.list_join,
+ "dependencies_inheritance": strategies.child_or_parent,
"hooks": strategies.child_wins,
+ "hooks_inheritance": strategies.child_or_parent,
"iam_role": strategies.child_wins,
"sceptre_role": strategies.child_wins,
"iam_role_session_duration": strategies.child_wins,
"sceptre_role_session_duration": strategies.child_wins,
"notifications": strategies.child_wins,
+ "notifications_inheritance": strategies.child_or_parent,
"on_failure": strategies.child_wins,
"parameters": strategies.child_wins,
+ "parameters_inheritance": strategies.child_or_parent,
"profile": strategies.child_wins,
"project_code": strategies.child_wins,
"protect": strategies.child_wins,
@@ -57,8 +71,10 @@ CONFIG_MERGE_STRATEGIES = {
"role_arn": strategies.child_wins,
"cloudformation_service_role": strategies.child_wins,
"sceptre_user_data": strategies.child_wins,
+ "sceptre_user_data_inheritance": strategies.child_or_parent,
"stack_name": strategies.child_wins,
"stack_tags": strategies.child_wins,
+ "stack_tags_inheritance": strategies.child_or_parent,
"stack_timeout": strategies.child_wins,
"template_bucket_name": strategies.child_wins,
"template_key_value": strategies.child_wins,
@@ -68,6 +84,7 @@ CONFIG_MERGE_STRATEGIES = {
"obsolete": strategies.child_wins,
}
+
STACK_GROUP_CONFIG_ATTRIBUTES = ConfigAttributes(
{"project_code", "region"},
{
@@ -84,7 +101,9 @@ STACK_CONFIG_ATTRIBUTES = ConfigAttributes(
"template_path",
"template",
"dependencies",
+ "dependencies_inheritance",
"hooks",
+ "hooks_inheritance",
"iam_role",
"sceptre_role",
"iam_role_session_duration",
@@ -92,13 +111,16 @@ STACK_CONFIG_ATTRIBUTES = ConfigAttributes(
"notifications",
"on_failure",
"parameters",
+ "parameters_inheritance",
"profile",
"protect",
"role_arn",
"cloudformation_service_role",
"sceptre_user_data",
+ "sceptre_user_data_inheritance",
"stack_name",
"stack_tags",
+ "stack_tags_inheritance",
"stack_timeout",
},
)
@@ -352,11 +374,8 @@ class ConfigReader(object):
# Parse and read in the config files.
this_config = self._recursive_read(directory_path, filename, config)
-
- if "dependencies" in config or "dependencies" in this_config:
- this_config["dependencies"] = CONFIG_MERGE_STRATEGIES["dependencies"](
- this_config.get("dependencies"), config.get("dependencies")
- )
+ # Apply merge strategies with the config that includes base_config values.
+ this_config.update(self._get_merge_with_stratgies(config, this_config))
config.update(this_config)
self._check_version(config)
@@ -395,16 +414,39 @@ class ConfigReader(object):
# Read config file and overwrite inherited properties
child_config = self._render(directory_path, filename, config_group) or {}
+ child_config.update(self._get_merge_with_stratgies(config, child_config))
+ config.update(child_config)
+ return config
- for config_key, strategy in CONFIG_MERGE_STRATEGIES.items():
- value = strategy(config.get(config_key), child_config.get(config_key))
+ def _get_merge_with_stratgies(self, left: dict, right: dict) -> dict:
+ """
+ Returns a new dict with only the merge values of the two inputs, using the
+ merge strategies defined for each key.
+ """
+ merge = {}
+
+ # Then apply the merge strategies to each item
+ for config_key, default_strategy in CONFIG_MERGE_STRATEGIES.items():
+ strategy = default_strategy
+ override_key = f"{config_key}_inheritance"
+ if override_key in CONFIG_MERGE_STRATEGIES:
+ name = CONFIG_MERGE_STRATEGIES[override_key](
+ left.get(override_key), right.get(override_key)
+ )
+ if not name:
+ pass
+ elif name not in CONFIG_MERGE_STRATEGY_OVERRIDES[config_key]:
+ raise SceptreException(
+ f"{name} is not a valid inheritance strategy for {config_key}"
+ )
+ else:
+ strategy = CONFIG_MERGE_STRATEGY_OVERRIDES[config_key][name]
+ value = strategy(left.get(config_key), right.get(config_key))
if value:
- child_config[config_key] = value
+ merge[config_key] = value
- config.update(child_config)
-
- return config
+ return merge
def _render(self, directory_path, basename, stack_group_config):
"""
diff --git a/sceptre/config/strategies.py b/sceptre/config/strategies.py
index 29b37d9..b0dc989 100644
--- a/sceptre/config/strategies.py
+++ b/sceptre/config/strategies.py
@@ -71,3 +71,26 @@ def child_wins(a, b):
:returns: b
"""
return b
+
+
+def child_or_parent(a, b):
+ """
+ Returns the second arg if it is not empty, else the first.
+
+ :param a: An object.
+ :type a: object
+ :param b: An object.
+ :type b: object
+ :returns: b
+ """
+ return b or a
+
+
+LIST_STRATEGIES = {
+ "merge": list_join,
+ "override": child_wins,
+}
+DICT_STRATEGIES = {
+ "merge": dict_merge,
+ "override": child_wins,
+}
diff --git a/sceptre/stack.py b/sceptre/stack.py
index 8a63309..fa5639a 100644
--- a/sceptre/stack.py
+++ b/sceptre/stack.py
@@ -9,7 +9,7 @@ This module implements a Stack class, which stores a Stack's data.
import logging
-from typing import List, Any, Optional
+from typing import List, Dict, Union, Any, Optional
from deprecation import deprecated
from sceptre import __version__
@@ -26,6 +26,7 @@ from sceptre.resolvers import (
ResolvableValueProperty,
RecursiveResolve,
PlaceholderType,
+ Resolver,
)
from sceptre.template import Template
@@ -262,7 +263,7 @@ class Stack:
)
self.s3_details = s3_details
- self.parameters = parameters or {}
+ self.parameters = self._ensure_parameters(parameters or {})
self.sceptre_user_data = sceptre_user_data or {}
self.notifications = notifications or []
@@ -275,6 +276,30 @@ class Stack:
)
return value
+ def _ensure_parameters(
+ self, parameters: Dict[str, Any]
+ ) -> Dict[str, Union[str, List[Union[str, Resolver]], Resolver]]:
+ """Ensure CloudFormation parameters are of valid types"""
+
+ def is_valid(value: Any) -> bool:
+ return (
+ isinstance(value, str)
+ or (
+ isinstance(value, list)
+ and all(
+ isinstance(item, str) or isinstance(item, Resolver)
+ for item in value
+ )
+ )
+ or isinstance(value, Resolver)
+ )
+
+ if not all(is_valid(value) for value in parameters.values()):
+ raise InvalidConfigFileError(
+ f"{self.name}: Values for parameters must be strings, lists or resolvers, got {parameters}"
+ )
+ return parameters
+
def __repr__(self):
return (
"sceptre.stack.Stack("
| Sceptre/sceptre | 08f64759c4fa1e100aed52e17d5f3f54ba0f4e9b | diff --git a/tests/test_config_reader.py b/tests/test_config_reader.py
index c860952..1bd9f7e 100644
--- a/tests/test_config_reader.py
+++ b/tests/test_config_reader.py
@@ -2,6 +2,7 @@
import errno
import os
+import string
from unittest.mock import patch, sentinel, MagicMock, ANY
import pytest
@@ -13,6 +14,7 @@ from glob import glob
from sceptre.config.reader import ConfigReader
from sceptre.context import SceptreContext
+from sceptre.resolvers.stack_attr import StackAttr
from sceptre.exceptions import (
DependencyDoesNotExistError,
@@ -295,7 +297,7 @@ class TestConfigReader(object):
sceptre_user_data={},
hooks={},
s3_details=sentinel.s3_details,
- dependencies=["child/level", "top/level"],
+ dependencies=["top/level", "child/level"],
iam_role=None,
sceptre_role=None,
iam_role_session_duration=None,
@@ -667,3 +669,167 @@ class TestConfigReader(object):
with pytest.raises(ValueError, match="Error parsing .*"):
config_reader._render("configs", basename, stack_group_config)
assert len(glob("/tmp/rendered_*")) == 1
+
+ @pytest.mark.parametrize(
+ "config_key", ("parameters", "sceptre_user_data", "stack_tags")
+ )
+ @pytest.mark.parametrize(
+ "inheritance_at,values,expected_value",
+ [
+ (
+ 0,
+ [{"a": "a"}, {"b": "b"}, {"c": "c"}, {}],
+ {"a": "a", "b": "b", "c": "c"},
+ ),
+ (
+ 1,
+ [{"a": "a"}, {"b": "b"}, {"c": "c"}, {}],
+ {"a": "a", "b": "b", "c": "c"},
+ ),
+ (
+ 0,
+ [{"a": "a"}, {"b": "b"}, {"c": "c"}, {"d": "d"}],
+ {"a": "a", "b": "b", "c": "c", "d": "d"},
+ ),
+ (
+ 2,
+ [{"a": "a"}, {"b": "b"}, {"c": "c"}, {}],
+ {"b": "b", "c": "c"},
+ ),
+ (
+ 3,
+ [{"a": "a"}, {"b": "b"}, {"c": "c"}, {}],
+ {"c": "c"},
+ ),
+ (
+ 99,
+ [{"a": "a"}, {"b": "b"}, {"c": "c"}, {}],
+ {},
+ ),
+ (
+ 99,
+ [{"a": "a"}, {"b": "b"}, {"c": "c"}, {"d": "d"}],
+ {"d": "d"},
+ ),
+ (
+ 3,
+ [{"a": "a"}, {"b": "b"}, {"c": "c"}, {"c": "x", "d": "d"}],
+ {"c": "x", "d": "d"},
+ ),
+ ],
+ )
+ def test_inheritance_strategy_override_dict_merge(
+ self,
+ config_key,
+ inheritance_at,
+ values,
+ expected_value,
+ ):
+ project_path, config_dir = self.create_project()
+ filepaths = [
+ "/".join(string.ascii_uppercase[:i]) + "/config.yaml"
+ for i in range(1, len(values))
+ ]
+ filepaths.append(
+ "/".join(string.ascii_uppercase[: len(values) - 1]) + "/1.yaml"
+ )
+
+ for i, (stack_path, stack_values) in enumerate(zip(filepaths, values)):
+ params = {config_key: stack_values}
+ if i == inheritance_at:
+ params[f"{config_key}_inheritance"] = "merge"
+ config = {
+ "region": "region",
+ "project_code": "project_code",
+ "template": {
+ "path": stack_path,
+ },
+ **params,
+ }
+ abs_path = os.path.join(config_dir, stack_path)
+ self.write_config(abs_path, config)
+
+ self.context.project_path = project_path
+ config_reader = ConfigReader(self.context)
+ stack = list(config_reader.construct_stacks()[0])[-1]
+ stack_key = StackAttr.STACK_ATTR_MAP.get(config_key, config_key)
+ assert getattr(stack, stack_key) == expected_value
+
+ # "dependencies" is not included here as it has other tests and testing
+ # it requires configs to be created which makes setup harder.
+ @pytest.mark.parametrize("config_key", ("hooks", "notifications"))
+ @pytest.mark.parametrize(
+ "inheritance_at,values,expected_value",
+ [
+ (0, [["a"], ["b"], ["c"], []], ["a", "b", "c"]),
+ (1, [["a"], ["b"], ["c"], []], ["a", "b", "c"]),
+ (2, [["a"], ["b"], ["c"], []], ["b", "c"]),
+ (3, [["a"], ["b"], ["c"], ["d"]], ["c", "d"]),
+ (99, [["a"], ["b"], ["c"], ["d"]], ["d"]),
+ ],
+ )
+ def test_inheritance_strategy_override_list_join(
+ self,
+ config_key,
+ inheritance_at,
+ values,
+ expected_value,
+ ):
+ project_path, config_dir = self.create_project()
+ filepaths = [
+ "/".join(string.ascii_uppercase[:i]) + "/config.yaml"
+ for i in range(1, len(values))
+ ]
+ filepaths.append(
+ "/".join(string.ascii_uppercase[: len(values) - 1]) + "/1.yaml"
+ )
+
+ for i, (stack_path, stack_values) in enumerate(zip(filepaths, values)):
+ params = {config_key: stack_values}
+ if i == inheritance_at:
+ params[f"{config_key}_inheritance"] = "merge"
+ config = {
+ "region": "region",
+ "project_code": "project_code",
+ "template": {
+ "path": stack_path,
+ },
+ **params,
+ }
+ abs_path = os.path.join(config_dir, stack_path)
+ self.write_config(abs_path, config)
+
+ self.context.project_path = project_path
+ config_reader = ConfigReader(self.context)
+ stack = list(config_reader.construct_stacks()[0])[-1]
+ stack_key = StackAttr.STACK_ATTR_MAP.get(config_key, config_key)
+ assert getattr(stack, stack_key) == expected_value
+
+ @pytest.mark.parametrize(
+ "config_key,strategy",
+ (
+ ("hooks", "foo"),
+ ("hooks", "deepcopy"),
+ ("hooks", "child_or_parent"),
+ ("stack_tags", "foo"),
+ ),
+ )
+ def test_inheritance_strategy_override_errors_on_invalid_strategy(
+ self, config_key, strategy
+ ):
+ project_path, config_dir = self.create_project()
+ stack_path = "A/1.yaml"
+ config = {
+ "region": "region",
+ "project_code": "project_code",
+ "template": {
+ "path": stack_path,
+ },
+ f"{config_key}_inheritance": strategy,
+ }
+ abs_path = os.path.join(config_dir, stack_path)
+ self.write_config(abs_path, config)
+ self.context.project_path = project_path
+ config_reader = ConfigReader(self.context)
+ with pytest.raises(SceptreException):
+ config_reader.construct_stacks()
diff --git a/tests/test_stack.py b/tests/test_stack.py
index 7e843e4..6f67e08 100644
--- a/tests/test_stack.py
+++ b/tests/test_stack.py
@@ -40,6 +40,11 @@ def stack_factory(**kwargs):
return Stack(**call_kwargs)
+class FakeResolver(Resolver):
+ def resolve(self):
+ return "Fake"
+
+
class TestStack(object):
def setup_method(self, test_method):
self.stack = Stack(
@@ -183,6 +188,46 @@ class TestStack(object):
obsolete="true",
)
+ @pytest.mark.parametrize(
+ "parameters",
+ [
+ {"someNum": 1},
+ {"someBool": True},
+ {"aBadList": [1, 2, 3]},
+ {"aDict": {"foo": "bar"}},
+ ],
+ )
+ def test_init__invalid_parameters_raise_invalid_config_file_error(self, parameters):
+ with pytest.raises(InvalidConfigFileError):
+ Stack(
+ name="stack_name",
+ project_code="project_code",
+ template_handler_config={"type": "file"},
+ region="region",
+ parameters=parameters,
+ )
+
+ @pytest.mark.parametrize(
+ "parameters",
+ [
+ {"someNum": "1"},
+ {"someBool": "true"},
+ {"aList": ["aString", FakeResolver()]},
+ {"aResolver": FakeResolver()},
+ ],
+ )
+ def test_init__valid_parameters_do_not_raise_invalid_config_file_error(
+ self, parameters
+ ):
+ stack = Stack(
+ name="stack_name",
+ project_code="project_code",
+ template_handler_config={"type": "file"},
+ region="region",
+ parameters=parameters,
+ )
+ assert isinstance(stack, Stack)
+
def test_stack_repr(self):
assert (
self.stack.__repr__() == "sceptre.stack.Stack("
@@ -248,14 +293,10 @@ class TestStack(object):
def test_configuration_manager__sceptre_role_returns_value__returns_connection_manager_with_that_role(
self,
):
- class FakeResolver(Resolver):
- def resolve(self):
- return "role"
-
self.stack.sceptre_role = FakeResolver()
connection_manager = self.stack.connection_manager
- assert connection_manager.sceptre_role == "role"
+ assert connection_manager.sceptre_role == "Fake"
@fail_if_not_removed
def test_iam_role__is_removed_on_removal_version(self):
| feature request: append stack_tag inheritance
Currently stack_tags inheritance strategy is override which means that stack tags can be defined in a Sceptre StackGroup and then overridden in the a child StackGroup or Stack config. I would like to make a feature request to append stack_tags on a dependencies.
Example:
Assume Scepter project A, B and C with dependency C -> B
root StackConfig config/config.yaml
```
stack_tags:
- country: US
```
config/prod/A.yaml
```
stack_tags:
- city: anaheim # stack A tags are 'city:anaheim', 'country:US'
```
config/prod/C.yaml
```
dependencies:
- prod/B.yaml
stack_tags:
- county: collin # stack C tags are 'county:collin', 'country:US'
```
config/prod/B.yaml
```
stack_tags:
- city: boston # stack B tags are 'city:boston', 'county:collin', 'country:US'
```
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_config_reader.py::TestConfigReader::test_inheritance_strategy_override_errors_on_invalid_strategy[stack_tags-foo]",
"tests/test_config_reader.py::TestConfigReader::test_inheritance_strategy_override_dict_merge[2-values3-expected_value3-parameters]",
"tests/test_config_reader.py::TestConfigReader::test_construct_stacks_constructs_stack",
"tests/test_config_reader.py::TestConfigReader::test_inheritance_strategy_override_dict_merge[0-values0-expected_value0-parameters]",
"tests/test_config_reader.py::TestConfigReader::test_inheritance_strategy_override_dict_merge[3-values4-expected_value4-parameters]",
"tests/test_config_reader.py::TestConfigReader::test_inheritance_strategy_override_dict_merge[0-values2-expected_value2-stack_tags]",
"tests/test_config_reader.py::TestConfigReader::test_inheritance_strategy_override_dict_merge[1-values1-expected_value1-sceptre_user_data]",
"tests/test_config_reader.py::TestConfigReader::test_inheritance_strategy_override_list_join[1-values1-expected_value1-hooks]",
"tests/test_config_reader.py::TestConfigReader::test_inheritance_strategy_override_list_join[0-values0-expected_value0-hooks]",
"tests/test_config_reader.py::TestConfigReader::test_inheritance_strategy_override_dict_merge[2-values3-expected_value3-stack_tags]",
"tests/test_config_reader.py::TestConfigReader::test_inheritance_strategy_override_list_join[2-values2-expected_value2-hooks]",
"tests/test_config_reader.py::TestConfigReader::test_inheritance_strategy_override_list_join[1-values1-expected_value1-notifications]",
"tests/test_config_reader.py::TestConfigReader::test_inheritance_strategy_override_dict_merge[3-values4-expected_value4-sceptre_user_data]",
"tests/test_config_reader.py::TestConfigReader::test_inheritance_strategy_override_dict_merge[0-values2-expected_value2-sceptre_user_data]",
"tests/test_config_reader.py::TestConfigReader::test_inheritance_strategy_override_dict_merge[1-values1-expected_value1-stack_tags]",
"tests/test_config_reader.py::TestConfigReader::test_inheritance_strategy_override_list_join[2-values2-expected_value2-notifications]",
"tests/test_config_reader.py::TestConfigReader::test_inheritance_strategy_override_errors_on_invalid_strategy[hooks-child_or_parent]",
"tests/test_config_reader.py::TestConfigReader::test_inheritance_strategy_override_dict_merge[0-values0-expected_value0-stack_tags]",
"tests/test_config_reader.py::TestConfigReader::test_inheritance_strategy_override_dict_merge[0-values0-expected_value0-sceptre_user_data]",
"tests/test_config_reader.py::TestConfigReader::test_inheritance_strategy_override_list_join[0-values0-expected_value0-notifications]",
"tests/test_config_reader.py::TestConfigReader::test_inheritance_strategy_override_dict_merge[0-values2-expected_value2-parameters]",
"tests/test_config_reader.py::TestConfigReader::test_inheritance_strategy_override_errors_on_invalid_strategy[hooks-deepcopy]",
"tests/test_config_reader.py::TestConfigReader::test_inheritance_strategy_override_list_join[3-values3-expected_value3-hooks]",
"tests/test_config_reader.py::TestConfigReader::test_inheritance_strategy_override_list_join[3-values3-expected_value3-notifications]",
"tests/test_config_reader.py::TestConfigReader::test_inheritance_strategy_override_dict_merge[1-values1-expected_value1-parameters]",
"tests/test_config_reader.py::TestConfigReader::test_inheritance_strategy_override_dict_merge[3-values4-expected_value4-stack_tags]",
"tests/test_config_reader.py::TestConfigReader::test_inheritance_strategy_override_errors_on_invalid_strategy[hooks-foo]",
"tests/test_config_reader.py::TestConfigReader::test_inheritance_strategy_override_dict_merge[2-values3-expected_value3-sceptre_user_data]",
"tests/test_stack.py::TestStack::test_init__invalid_parameters_raise_invalid_config_file_error[parameters1]",
"tests/test_stack.py::TestStack::test_init__invalid_parameters_raise_invalid_config_file_error[parameters2]",
"tests/test_stack.py::TestStack::test_init__invalid_parameters_raise_invalid_config_file_error[parameters0]",
"tests/test_stack.py::TestStack::test_init__invalid_parameters_raise_invalid_config_file_error[parameters3]"
] | [
"tests/test_config_reader.py::TestConfigReader::test_read_reads_config_file_with_base_config",
"tests/test_config_reader.py::TestConfigReader::test_read_reads_config_file[filepaths1-A/B/1.yaml]",
"tests/test_config_reader.py::TestConfigReader::test_construct_stacks_with_valid_config[-filepaths3-expected_stacks3-expected_command_stacks3-False]",
"tests/test_config_reader.py::TestConfigReader::test_collect_s3_details[name-config2-expected2]",
"tests/test_config_reader.py::TestConfigReader::test_render__existing_config_file__returns_dict",
"tests/test_config_reader.py::TestConfigReader::test_construct_stacks_with_valid_config[-filepaths4-expected_stacks4-expected_command_stacks4-False]",
"tests/test_config_reader.py::TestConfigReader::test_render__invalid_jinja_template__raises_and_creates_debug_file",
"tests/test_config_reader.py::TestConfigReader::test_inheritance_strategy_override_dict_merge[99-values6-expected_value6-sceptre_user_data]",
"tests/test_config_reader.py::TestConfigReader::test_aborts_on_incompatible_version_requirement",
"tests/test_config_reader.py::TestConfigReader::test_read_with_empty_config_file",
"tests/test_config_reader.py::TestConfigReader::test_inherited_dependency_already_resolved[filepaths0-B/1.yaml-A/config.yaml]",
"tests/test_config_reader.py::TestConfigReader::test_construct_stacks_with_valid_config[Ab-filepaths8-expected_stacks8-expected_command_stacks8-False]",
"tests/test_config_reader.py::TestConfigReader::test_collect_s3_details[name-config0-expected0]",
"tests/test_config_reader.py::TestConfigReader::test_inheritance_strategy_override_dict_merge[3-values7-expected_value7-stack_tags]",
"tests/test_config_reader.py::TestConfigReader::test_read_with_nonexistant_filepath",
"tests/test_config_reader.py::TestConfigReader::test_construct_stacks_with_valid_config[-filepaths1-expected_stacks1-expected_command_stacks1-False]",
"tests/test_config_reader.py::TestConfigReader::test_read_nested_configs",
"tests/test_config_reader.py::TestConfigReader::test_construct_stacks_with_valid_config[-filepaths2-expected_stacks2-expected_command_stacks2-False]",
"tests/test_config_reader.py::TestConfigReader::test_inheritance_strategy_override_dict_merge[3-values7-expected_value7-parameters]",
"tests/test_config_reader.py::TestConfigReader::test_construct_stacks_with_disable_rollback_command_param",
"tests/test_config_reader.py::TestConfigReader::test_read_reads_config_file[filepaths2-A/B/C/1.yaml]",
"tests/test_config_reader.py::TestConfigReader::test_inheritance_strategy_override_list_join[99-values4-expected_value4-hooks]",
"tests/test_config_reader.py::TestConfigReader::test_collect_s3_details[name-config1-expected1]",
"tests/test_config_reader.py::TestConfigReader::test_config_reader_with_invalid_path",
"tests/test_config_reader.py::TestConfigReader::test_config_reader_correctly_initialised",
"tests/test_config_reader.py::TestConfigReader::test_inheritance_strategy_override_dict_merge[3-values7-expected_value7-sceptre_user_data]",
"tests/test_config_reader.py::TestConfigReader::test_missing_attr[filepaths1-region]",
"tests/test_config_reader.py::TestConfigReader::test_read_reads_config_file[filepaths0-A/1.yaml]",
"tests/test_config_reader.py::TestConfigReader::test_collect_s3_details[name-config3-None]",
"tests/test_config_reader.py::TestConfigReader::test_inheritance_strategy_override_dict_merge[99-values6-expected_value6-stack_tags]",
"tests/test_config_reader.py::TestConfigReader::test_inheritance_strategy_override_dict_merge[99-values6-expected_value6-parameters]",
"tests/test_config_reader.py::TestConfigReader::test_inheritance_strategy_override_dict_merge[99-values5-expected_value5-parameters]",
"tests/test_config_reader.py::TestConfigReader::test_construct_stacks_with_disable_rollback_in_stack_config",
"tests/test_config_reader.py::TestConfigReader::test_resolve_node_tag",
"tests/test_config_reader.py::TestConfigReader::test_inherited_dependency_already_resolved[filepaths1-A/1.yaml-A/config.yaml]",
"tests/test_config_reader.py::TestConfigReader::test_render_invalid_yaml__raises_and_creates_debug_file",
"tests/test_config_reader.py::TestConfigReader::test_missing_dependency[filepaths1-1.yaml]",
"tests/test_config_reader.py::TestConfigReader::test_missing_attr[filepaths0-project_code]",
"tests/test_config_reader.py::TestConfigReader::test_existing_dependency[filepaths1-B/1.yaml]",
"tests/test_config_reader.py::TestConfigReader::test_read_with_templated_config_file",
"tests/test_config_reader.py::TestConfigReader::test_inheritance_strategy_override_dict_merge[99-values5-expected_value5-sceptre_user_data]",
"tests/test_config_reader.py::TestConfigReader::test_existing_dependency[filepaths0-A/1.yaml]",
"tests/test_config_reader.py::TestConfigReader::test_construct_stacks_with_valid_config[Abd-filepaths6-expected_stacks6-expected_command_stacks6-False]",
"tests/test_config_reader.py::TestConfigReader::test_construct_stacks_with_valid_config[Abd/Abc-filepaths7-expected_stacks7-expected_command_stacks7-False]",
"tests/test_config_reader.py::TestConfigReader::test_inheritance_strategy_override_list_join[99-values4-expected_value4-notifications]",
"tests/test_config_reader.py::TestConfigReader::test_missing_dependency[filepaths0-A/2.yaml]",
"tests/test_config_reader.py::TestConfigReader::test_render__missing_config_file__returns_none",
"tests/test_config_reader.py::TestConfigReader::test_construct_stacks_with_valid_config[-filepaths0-expected_stacks0-expected_command_stacks0-False]",
"tests/test_config_reader.py::TestConfigReader::test_inheritance_strategy_override_dict_merge[99-values5-expected_value5-stack_tags]",
"tests/test_config_reader.py::TestConfigReader::test_construct_stacks_with_valid_config[Abd-filepaths5-expected_stacks5-expected_command_stacks5-False]",
"tests/test_config_reader.py::TestConfigReader::test_construct_stacks_with_valid_config[Abd/Abc-filepaths9-expected_stacks9-expected_command_stacks9-True]",
"tests/test_stack.py::TestStack::test_configuration_manager__sceptre_role_returns_value_second_access__returns_value_on_second_access",
"tests/test_stack.py::TestStack::test_init__valid_parameters_do_not_raise_invalid_config_file_error[parameters3]",
"tests/test_stack.py::TestStack::test_init__non_boolean_ignore_value__raises_invalid_config_file_error",
"tests/test_stack.py::TestStack::test_init__valid_parameters_do_not_raise_invalid_config_file_error[parameters1]",
"tests/test_stack.py::TestStack::test_configuration_manager__sceptre_role_returns_value__returns_connection_manager_with_that_role",
"tests/test_stack.py::TestStack::test_role_arn__is_removed_on_removal_version",
"tests/test_stack.py::TestStack::test_init__iam_role_session_duration_set_resolves_to_sceptre_role_session_duration",
"tests/test_stack.py::TestStack::test_stack_repr",
"tests/test_stack.py::TestStack::test_iam_role__is_removed_on_removal_version",
"tests/test_stack.py::TestStack::test_init__iam_role_set_resolves_to_sceptre_role",
"tests/test_stack.py::TestStack::test_init__valid_parameters_do_not_raise_invalid_config_file_error[parameters0]",
"tests/test_stack.py::TestStack::test_init__non_boolean_obsolete_value__raises_invalid_config_file_error",
"tests/test_stack.py::TestStack::test_init__role_arn_set_resolves_to_cloudformation_service_role",
"tests/test_stack.py::TestStack::test_raises_exception_if_path_and_handler_configured",
"tests/test_stack.py::TestStack::test_initialize_stack_with_template_path",
"tests/test_stack.py::TestStack::test_initialize_stack_with_template_handler",
"tests/test_stack.py::TestStack::test_configuration_manager__sceptre_role_raises_recursive_resolve__returns_connection_manager_with_no_role",
"tests/test_stack.py::TestStack::test_iam_role_session_duration__is_removed_on_removal_version",
"tests/test_stack.py::TestStack::test_init__valid_parameters_do_not_raise_invalid_config_file_error[parameters2]",
"tests/test_stack.py::TestStackSceptreUserData::test_user_data_gets_resolved",
"tests/test_stack.py::TestStackSceptreUserData::test_user_data_is_accessible",
"tests/test_stack.py::TestStackSceptreUserData::test_recursive_user_data_gets_resolved"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
} | "2024-02-25T02:53:08Z" | apache-2.0 |
|
Sceptre__sceptre-1447 | diff --git a/sceptre/config/graph.py b/sceptre/config/graph.py
index 34d6b79..1ad11da 100644
--- a/sceptre/config/graph.py
+++ b/sceptre/config/graph.py
@@ -90,14 +90,18 @@ class StackGraph(object):
:param stack: A Sceptre Stack
:param dependencies: a collection of dependency paths
"""
- self.logger.debug("Generate dependencies for stack {0}".format(stack))
+ self.logger.debug(f"Generate dependencies for stack {stack}")
for dependency in set(dependencies):
self.graph.add_edge(dependency, stack)
- if not nx.is_directed_acyclic_graph(self.graph):
+ try:
+ cycle = nx.find_cycle(self.graph, orientation="original")
+ cycle_str = ", ".join([f"{edge[0]} -> {edge[1]}" for edge in cycle])
raise CircularDependenciesError(
- f"Dependency cycle detected: {stack} {dependency}"
+ f"Dependency cycle detected: {cycle_str}"
)
- self.logger.debug(" Added dependency: {}".format(dependency))
+ except nx.NetworkXNoCycle:
+ pass # No cycle, continue
+ self.logger.debug(f" Added dependency: {dependency}")
if not dependencies:
self.graph.add_node(stack)
diff --git a/sceptre/stack.py b/sceptre/stack.py
index 8a63309..fa5639a 100644
--- a/sceptre/stack.py
+++ b/sceptre/stack.py
@@ -9,7 +9,7 @@ This module implements a Stack class, which stores a Stack's data.
import logging
-from typing import List, Any, Optional
+from typing import List, Dict, Union, Any, Optional
from deprecation import deprecated
from sceptre import __version__
@@ -26,6 +26,7 @@ from sceptre.resolvers import (
ResolvableValueProperty,
RecursiveResolve,
PlaceholderType,
+ Resolver,
)
from sceptre.template import Template
@@ -262,7 +263,7 @@ class Stack:
)
self.s3_details = s3_details
- self.parameters = parameters or {}
+ self.parameters = self._ensure_parameters(parameters or {})
self.sceptre_user_data = sceptre_user_data or {}
self.notifications = notifications or []
@@ -275,6 +276,30 @@ class Stack:
)
return value
+ def _ensure_parameters(
+ self, parameters: Dict[str, Any]
+ ) -> Dict[str, Union[str, List[Union[str, Resolver]], Resolver]]:
+ """Ensure CloudFormation parameters are of valid types"""
+
+ def is_valid(value: Any) -> bool:
+ return (
+ isinstance(value, str)
+ or (
+ isinstance(value, list)
+ and all(
+ isinstance(item, str) or isinstance(item, Resolver)
+ for item in value
+ )
+ )
+ or isinstance(value, Resolver)
+ )
+
+ if not all(is_valid(value) for value in parameters.values()):
+ raise InvalidConfigFileError(
+ f"{self.name}: Values for parameters must be strings, lists or resolvers, got {parameters}"
+ )
+ return parameters
+
def __repr__(self):
return (
"sceptre.stack.Stack("
| Sceptre/sceptre | 08f64759c4fa1e100aed52e17d5f3f54ba0f4e9b | diff --git a/tests/test_stack.py b/tests/test_stack.py
index 7e843e4..6f67e08 100644
--- a/tests/test_stack.py
+++ b/tests/test_stack.py
@@ -40,6 +40,11 @@ def stack_factory(**kwargs):
return Stack(**call_kwargs)
+class FakeResolver(Resolver):
+ def resolve(self):
+ return "Fake"
+
+
class TestStack(object):
def setup_method(self, test_method):
self.stack = Stack(
@@ -183,6 +188,46 @@ class TestStack(object):
obsolete="true",
)
+ @pytest.mark.parametrize(
+ "parameters",
+ [
+ {"someNum": 1},
+ {"someBool": True},
+ {"aBadList": [1, 2, 3]},
+ {"aDict": {"foo": "bar"}},
+ ],
+ )
+ def test_init__invalid_parameters_raise_invalid_config_file_error(self, parameters):
+ with pytest.raises(InvalidConfigFileError):
+ Stack(
+ name="stack_name",
+ project_code="project_code",
+ template_handler_config={"type": "file"},
+ region="region",
+ parameters=parameters,
+ )
+
+ @pytest.mark.parametrize(
+ "parameters",
+ [
+ {"someNum": "1"},
+ {"someBool": "true"},
+ {"aList": ["aString", FakeResolver()]},
+ {"aResolver": FakeResolver()},
+ ],
+ )
+ def test_init__valid_parameters_do_not_raise_invalid_config_file_error(
+ self, parameters
+ ):
+ stack = Stack(
+ name="stack_name",
+ project_code="project_code",
+ template_handler_config={"type": "file"},
+ region="region",
+ parameters=parameters,
+ )
+ assert isinstance(stack, Stack)
+
def test_stack_repr(self):
assert (
self.stack.__repr__() == "sceptre.stack.Stack("
@@ -248,14 +293,10 @@ class TestStack(object):
def test_configuration_manager__sceptre_role_returns_value__returns_connection_manager_with_that_role(
self,
):
- class FakeResolver(Resolver):
- def resolve(self):
- return "role"
-
self.stack.sceptre_role = FakeResolver()
connection_manager = self.stack.connection_manager
- assert connection_manager.sceptre_role == "role"
+ assert connection_manager.sceptre_role == "Fake"
@fail_if_not_removed
def test_iam_role__is_removed_on_removal_version(self):
| Cyclic dependencies should result in a clearer error message
### Subject of the issue
When a cyclical dependency is detected in the dependency graph, a slightly unclear error message appears like:
```
sceptre.exceptions.CircularDependenciesError: Dependency cycle detected: configmap-lambda eks-securitygroups
```
It would be better if Sceptre behaved more like Terraform here and displayed the edges from the graph to make it clearer as to the path of the circular dependency in the graph.
### Your environment
* version of sceptre (sceptre --version) latest
* version of python (python --version) 3.10
* which OS/distro Ubuntu
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_stack.py::TestStack::test_init__invalid_parameters_raise_invalid_config_file_error[parameters0]",
"tests/test_stack.py::TestStack::test_init__invalid_parameters_raise_invalid_config_file_error[parameters1]",
"tests/test_stack.py::TestStack::test_init__invalid_parameters_raise_invalid_config_file_error[parameters2]",
"tests/test_stack.py::TestStack::test_init__invalid_parameters_raise_invalid_config_file_error[parameters3]"
] | [
"tests/test_stack.py::TestStack::test_initialize_stack_with_template_path",
"tests/test_stack.py::TestStack::test_initialize_stack_with_template_handler",
"tests/test_stack.py::TestStack::test_raises_exception_if_path_and_handler_configured",
"tests/test_stack.py::TestStack::test_init__non_boolean_ignore_value__raises_invalid_config_file_error",
"tests/test_stack.py::TestStack::test_init__non_boolean_obsolete_value__raises_invalid_config_file_error",
"tests/test_stack.py::TestStack::test_init__valid_parameters_do_not_raise_invalid_config_file_error[parameters0]",
"tests/test_stack.py::TestStack::test_init__valid_parameters_do_not_raise_invalid_config_file_error[parameters1]",
"tests/test_stack.py::TestStack::test_init__valid_parameters_do_not_raise_invalid_config_file_error[parameters2]",
"tests/test_stack.py::TestStack::test_init__valid_parameters_do_not_raise_invalid_config_file_error[parameters3]",
"tests/test_stack.py::TestStack::test_stack_repr",
"tests/test_stack.py::TestStack::test_configuration_manager__sceptre_role_raises_recursive_resolve__returns_connection_manager_with_no_role",
"tests/test_stack.py::TestStack::test_configuration_manager__sceptre_role_returns_value_second_access__returns_value_on_second_access",
"tests/test_stack.py::TestStack::test_configuration_manager__sceptre_role_returns_value__returns_connection_manager_with_that_role",
"tests/test_stack.py::TestStack::test_iam_role__is_removed_on_removal_version",
"tests/test_stack.py::TestStack::test_role_arn__is_removed_on_removal_version",
"tests/test_stack.py::TestStack::test_iam_role_session_duration__is_removed_on_removal_version",
"tests/test_stack.py::TestStack::test_init__iam_role_set_resolves_to_sceptre_role",
"tests/test_stack.py::TestStack::test_init__role_arn_set_resolves_to_cloudformation_service_role",
"tests/test_stack.py::TestStack::test_init__iam_role_session_duration_set_resolves_to_sceptre_role_session_duration",
"tests/test_stack.py::TestStackSceptreUserData::test_user_data_is_accessible",
"tests/test_stack.py::TestStackSceptreUserData::test_user_data_gets_resolved",
"tests/test_stack.py::TestStackSceptreUserData::test_recursive_user_data_gets_resolved"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2024-02-25T06:13:22Z" | apache-2.0 |
|
SciCatProject__scitacean-57 | diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 4a3c6fd..4d67bf3 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -9,12 +9,6 @@ repos:
- id: detect-private-key
- id: trailing-whitespace
args: [--markdown-linebreak-ext=md]
-- repo: https://github.com/charliermarsh/ruff-pre-commit
- rev: 'v0.0.225'
- hooks:
- - id: ruff
- # Respect `exclude` and `extend-exclude` settings.
- args: ["--force-exclude", "--fix"]
- repo: https://github.com/psf/black
rev: 22.10.0
hooks:
@@ -26,6 +20,12 @@ repos:
types: ["jupyter"]
args: ["--drop-empty-cells",
"--extra-keys 'metadata.language_info.version cell.metadata.jp-MarkdownHeadingCollapsed cell.metadata.pycharm'"]
+- repo: https://github.com/charliermarsh/ruff-pre-commit
+ rev: 'v0.0.225'
+ hooks:
+ - id: ruff
+ # Respect `exclude` and `extend-exclude` settings.
+ args: ["--force-exclude", "--fix"]
- repo: https://github.com/codespell-project/codespell
rev: v2.2.2
hooks:
diff --git a/docs/release-notes.rst b/docs/release-notes.rst
index fd2bb0e..c1b4b4b 100644
--- a/docs/release-notes.rst
+++ b/docs/release-notes.rst
@@ -30,6 +30,29 @@ Release notes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+vYY.0M.MICRO (Unreleased)
+-------------------------
+
+Features
+~~~~~~~~
+
+* Files are no longer downloaded if an up-to-date version exists on local.
+
+Breaking changes
+~~~~~~~~~~~~~~~~
+
+Bugfixes
+~~~~~~~~
+
+Documentation
+~~~~~~~~~~~~~
+
+Deprecations
+~~~~~~~~~~~~
+
+Stability, Maintainability, and Testing
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
v23.01.1 (2023-01-20)
---------------------
diff --git a/pyproject.toml b/pyproject.toml
index fd13655..2711e49 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -56,6 +56,8 @@ addopts = """
"""
filterwarnings = [
"error",
+ # Many tests don't set a checksum, so File raises this warning.
+ "ignore:Cannot check if local file:UserWarning",
]
[tool.mypy]
diff --git a/src/scitacean/client.py b/src/scitacean/client.py
index 5e15f40..d172965 100644
--- a/src/scitacean/client.py
+++ b/src/scitacean/client.py
@@ -4,6 +4,7 @@
from __future__ import annotations
+import dataclasses
import datetime
import re
from contextlib import contextmanager
@@ -33,7 +34,7 @@ class Client:
a client instead of the constructor directly.
See the user guide for typical usage patterns.
- In particular `Downloading Datasets <../../user-guide/downloading.ipynb>`_
+ In particular, `Downloading Datasets <../../user-guide/downloading.ipynb>`_
and `Uploading Datasets <../../user-guide/uploading.ipynb>`_.
"""
@@ -280,7 +281,12 @@ class Client:
return self._file_transfer
def download_files(
- self, dataset: Dataset, *, target: Union[str, Path], select: FileSelector = True
+ self,
+ dataset: Dataset,
+ *,
+ target: Union[str, Path],
+ select: FileSelector = True,
+ checksum_algorithm: Optional[str] = None,
) -> Dataset:
r"""Download files of a dataset.
@@ -304,6 +310,10 @@ class Client:
- An **re.Pattern** as returned by :func:`re.compile`:
if this pattern matches ``f.remote_path`` using :func:`re.search`
- A **Callable[File]**: if this callable returns ``True`` for ``f``
+ checksum_algorithm:
+ Select an algorithm for computing file checksums.
+ This argument will be removed when the next SciCat version
+ has been released.
Returns
-------
@@ -348,19 +358,24 @@ class Client:
# TODO undo if later fails but only if no files were written
target.mkdir(parents=True, exist_ok=True)
files = _select_files(select, dataset)
- local_paths = [target / f.remote_path for f in files]
+ downloaded_files = [
+ f.downloaded(local_path=target / f.remote_path) for f in files
+ ]
+ downloaded_files = _remove_up_to_date_local_files(
+ downloaded_files, checksum_algorithm=checksum_algorithm
+ )
+ if not downloaded_files:
+ return dataset.replace()
+
with self._connect_for_file_download() as con:
con.download_files(
remote=[
p
- for f in files
+ for f in downloaded_files
if (p := f.remote_access_path(dataset.source_folder)) is not None
],
- local=local_paths,
+ local=[f.local_path for f in downloaded_files],
)
- downloaded_files = tuple(
- f.downloaded(local_path=l) for f, l in zip(files, local_paths)
- )
for f in downloaded_files:
f.validate_after_download()
return dataset.replace_files(*downloaded_files)
@@ -746,3 +761,18 @@ def _file_selector(select: FileSelector) -> Callable[[File], bool]:
def _select_files(select: FileSelector, dataset: Dataset) -> List[File]:
selector = _file_selector(select)
return [f for f in dataset.files if selector(f)]
+
+
+def _remove_up_to_date_local_files(
+ files: List[File], checksum_algorithm: Optional[str]
+) -> List[File]:
+ return [
+ file
+ for file in files
+ if not (
+ file.local_path.exists()
+ and dataclasses.replace(
+ file, checksum_algorithm=checksum_algorithm
+ ).local_is_up_to_date()
+ )
+ ]
diff --git a/src/scitacean/file.py b/src/scitacean/file.py
index 9820164..d923936 100644
--- a/src/scitacean/file.py
+++ b/src/scitacean/file.py
@@ -6,6 +6,7 @@ from __future__ import annotations
import dataclasses
import os
+import warnings
from datetime import datetime, timezone
from pathlib import Path
from typing import NoReturn, Optional, Union, cast
@@ -195,14 +196,14 @@ class File:
:
The checksum of the file.
"""
- if self.is_on_local:
- if self.checksum_algorithm is None:
- return None
- return self._checksum_cache.get( # type: ignore[union-attr]
- path=self.local_path, # type: ignore[arg-type]
- algorithm=self.checksum_algorithm,
- )
- return self._remote_checksum
+ if not self.is_on_local:
+ return self._remote_checksum
+ if self.checksum_algorithm is None:
+ return None
+ return self._checksum_cache.get( # type: ignore[union-attr]
+ path=self.local_path, # type: ignore[arg-type]
+ algorithm=self.checksum_algorithm,
+ )
def remote_access_path(
self, source_folder: Union[RemotePath, str]
@@ -220,6 +221,32 @@ class File:
"""True if the file is on local."""
return self.local_path is not None
+ def local_is_up_to_date(self) -> bool:
+ """Check if the file on local is up-to-date.
+
+ Returns
+ -------
+ :
+ True if the file exists on local and its checksum
+ matches the stored checksum for the remote file.
+ """
+ if not self.is_on_remote:
+ return True
+ if not self.is_on_local:
+ return False
+ if self.checksum_algorithm is None:
+ warnings.warn(
+ f"Cannot check if local file {self.local_path} is up to date because "
+ "the checksum algorithm is not set. "
+ "Assuming the file needs to be updated."
+ )
+ return False
+ local_checksum = self._checksum_cache.get( # type: ignore[union-attr]
+ path=self.local_path, # type: ignore[arg-type]
+ algorithm=self.checksum_algorithm,
+ )
+ return self._remote_checksum == local_checksum
+
def make_model(self, *, for_archive: bool = False) -> DataFile:
"""Build a pydantic model for this file.
| SciCatProject/scitacean | 660b6a58ded9d90c8f3389134c7a4920b4f8cf27 | diff --git a/tests/download_test.py b/tests/download_test.py
index 9279eb6..3a44e54 100644
--- a/tests/download_test.py
+++ b/tests/download_test.py
@@ -2,6 +2,7 @@
# Copyright (c) 2023 SciCat Project (https://github.com/SciCatProject/scitacean)
import hashlib
import re
+from contextlib import contextmanager
from pathlib import Path
from typing import Union
@@ -15,6 +16,12 @@ from scitacean.model import DataFile, OrigDatablock, RawDataset
from scitacean.testing.transfer import FakeFileTransfer
+def _checksum(data: bytes) -> str:
+ checksum = hashlib.new("md5")
+ checksum.update(data)
+ return checksum.hexdigest()
+
+
@pytest.fixture
def data_files():
contents = {
@@ -23,7 +30,8 @@ def data_files():
"thaum.dat": b"0 4 2 59 330 2314552",
}
files = [
- DataFile(path=name, size=len(content)) for name, content in contents.items()
+ DataFile(path=name, size=len(content), chk=_checksum(content))
+ for name, content in contents.items()
]
return files, contents
@@ -251,3 +259,56 @@ def test_download_files_detects_bad_size(fs, dataset_and_files, caplog):
client.download_files(dataset, target="./download", select="file.txt")
assert "does not match size reported in dataset" in caplog.text
assert "89412" in caplog.text
+
+
[email protected]("Checksum algorithm not yet supported by datablocks")
+def test_download_does_not_download_up_to_date_file(fs, dataset_and_files):
+ # Ensure the file exists locally
+ dataset, contents = dataset_and_files
+ client = Client.without_login(
+ url="/", file_transfer=FakeFileTransfer(fs=fs, files=contents)
+ )
+ client.download_files(dataset, target="./download", select=True)
+
+ # Downloading the same files again should not call the downloader.
+ class RaisingDownloader(FakeFileTransfer):
+ source_dir = "/"
+
+ @contextmanager
+ def connect_for_download(self):
+ raise RuntimeError("Download disabled")
+
+ client = Client.without_login(
+ url="/",
+ file_transfer=RaisingDownloader(fs=fs),
+ )
+ # Does not raise
+ client.download_files(dataset, target="./download", select=True)
+
+
+def test_download_does_not_download_up_to_date_file_manual_checksum(
+ fs, dataset_and_files
+):
+ # Ensure the file exists locally
+ dataset, contents = dataset_and_files
+ client = Client.without_login(
+ url="/", file_transfer=FakeFileTransfer(fs=fs, files=contents)
+ )
+ client.download_files(dataset, target="./download", select=True)
+
+ # Downloading the same files again should not call the downloader.
+ class RaisingDownloader(FakeFileTransfer):
+ source_dir = "/"
+
+ @contextmanager
+ def connect_for_download(self):
+ raise RuntimeError("Download disabled")
+
+ client = Client.without_login(
+ url="/",
+ file_transfer=RaisingDownloader(fs=fs),
+ )
+ # Does not raise
+ client.download_files(
+ dataset, target="./download", select=True, checksum_algorithm="md5"
+ )
diff --git a/tests/file_test.py b/tests/file_test.py
index ca745cc..bb89fba 100644
--- a/tests/file_test.py
+++ b/tests/file_test.py
@@ -286,3 +286,51 @@ def test_validate_after_download_detects_size_mismatch(fake_file, caplog):
with caplog.at_level("INFO", logger=logger_name()):
downloaded.validate_after_download()
assert "does not match size reported in dataset" in caplog.text
+
+
[email protected]("chk", ("sha256", None))
+def test_local_is_not_up_to_date_for_remote_file(chk):
+ file = File.from_scicat(DataFile(path="data.csv", size=65178, chk=chk))
+ assert not file.local_is_up_to_date()
+
+
+def test_local_is_up_to_date_for_local_file():
+ # Note that the file does not actually exist on disk but the test still works.
+ file = File.from_local(path="image.jpg")
+ assert file.local_is_up_to_date()
+
+
+def test_local_is_not_up_to_date_without_checksum_alg():
+ file = File.from_scicat(
+ DataFile(path="data.csv", size=65178, chk="sha256")
+ ).downloaded(local_path="data.csv")
+ with pytest.warns(UserWarning, match="checksum"):
+ assert not file.local_is_up_to_date()
+
+
+def test_local_is_up_to_date_matching_checksum(fake_file):
+ model = DataFile(
+ path=fake_file["path"].name,
+ size=fake_file["size"],
+ time=parse_date("2022-06-22T15:42:53.123Z"),
+ chk=fake_file["checksum"],
+ )
+ file = replace(
+ File.from_scicat(model).downloaded(local_path=fake_file["path"]),
+ checksum_algorithm="md5",
+ )
+ assert file.local_is_up_to_date()
+
+
+def test_local_is_not_up_to_date_differing_checksum(fake_file):
+ model = DataFile(
+ path=fake_file["path"].name,
+ size=fake_file["size"],
+ time=parse_date("2022-06-22T15:42:53.123Z"),
+ chk="a-different-checksum",
+ )
+ file = replace(
+ File.from_scicat(model).downloaded(local_path=fake_file["path"]),
+ checksum_algorithm="md5",
+ )
+ assert not file.local_is_up_to_date()
| File caching
I was think if we could implement a rudimentary file caching following this simple workflow:
- user indicate that a local copy of the file is needed by using the provide_locally function
```
dataset.files[x].provide_locally(
local_folder,
downloader=file_transfer_function,
checksum_algorithm=algorithm
)
```
- scitacean find the local path where the file should be saved
- scitacean check if a file by that name is already present
- if no file is present, it downloads the file
- if the file is present and we have the original checksum and the checksum algorithm:
- Scitacean computes the has of the local file
- if it matches the hash of the remote one, the local file is used
- if it does not match, it downloads the remote file overwriting the local one
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/file_test.py::test_local_is_up_to_date_for_local_file"
] | [] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
} | "2023-01-24T15:34:21Z" | bsd-3-clause |
|
SciTools__nc-time-axis-80 | diff --git a/README.md b/README.md
index d1fc951..132b072 100644
--- a/README.md
+++ b/README.md
@@ -58,18 +58,16 @@ Or `pip`:
import cftime
import matplotlib.pyplot as plt
-
- from nc_time_axis import CalendarDateTime
+ import nc_time_axis
calendar = "360_day"
dt = [
cftime.datetime(year=2017, month=2, day=day, calendar=calendar)
for day in range(1, 31)
]
- cdt = [CalendarDateTime(item, calendar) for item in dt]
- temperatures = [round(random.uniform(0, 12), 3) for _ in range(len(cdt))]
+ temperatures = [round(random.uniform(0, 12), 3) for _ in range(len(dt))]
- plt.plot(cdt, temperatures)
+ plt.plot(dt, temperatures)
plt.margins(0.1)
plt.ylim(0, 12)
plt.xlabel("Date")
diff --git a/nc_time_axis/__init__.py b/nc_time_axis/__init__.py
index a683cdc..2a3f79f 100644
--- a/nc_time_axis/__init__.py
+++ b/nc_time_axis/__init__.py
@@ -308,6 +308,10 @@ class NetCDFTimeConverter(mdates.DateConverter):
else:
calendar = sample_point.calendar
date_type = type(sample_point)
+ if calendar == "":
+ raise ValueError(
+ "A calendar must be defined to plot dates using a cftime axis."
+ )
return calendar, cls.standard_unit, date_type
@classmethod
@@ -373,6 +377,7 @@ if CalendarDateTime not in munits.registry:
munits.registry[CalendarDateTime] = NetCDFTimeConverter()
CFTIME_TYPES = [
+ cftime.datetime,
cftime.DatetimeNoLeap,
cftime.DatetimeAllLeap,
cftime.DatetimeProlepticGregorian,
diff --git a/requirements/py37.yml b/requirements/py37.yml
index 40e3a9d..321ba26 100644
--- a/requirements/py37.yml
+++ b/requirements/py37.yml
@@ -11,13 +11,13 @@ dependencies:
- setuptools-scm
# core dependencies
- - cftime
+ - cftime >=1.5
- matplotlib
- numpy
# test dependencies
- codecov
- - pytest>=6.0
+ - pytest >=6.0
- pytest-cov
# dev dependencies
diff --git a/requirements/py38.yml b/requirements/py38.yml
index 4f97610..1ff1b39 100644
--- a/requirements/py38.yml
+++ b/requirements/py38.yml
@@ -11,13 +11,13 @@ dependencies:
- setuptools-scm
# core dependencies
- - cftime
+ - cftime >=1.5
- matplotlib
- numpy
# test dependencies
- codecov
- - pytest>=6.0
+ - pytest >=6.0
- pytest-cov
# dev dependencies
diff --git a/requirements/py39.yml b/requirements/py39.yml
index e141ecb..d6519f1 100644
--- a/requirements/py39.yml
+++ b/requirements/py39.yml
@@ -11,13 +11,13 @@ dependencies:
- setuptools-scm
# core dependencies
- - cftime
+ - cftime >=1.5
- matplotlib
- numpy
# test dependencies
- codecov
- - pytest>=6.0
+ - pytest >=6.0
- pytest-cov
# dev dependencies
diff --git a/setup.cfg b/setup.cfg
index 8a0fe29..69c4fb7 100644
--- a/setup.cfg
+++ b/setup.cfg
@@ -34,7 +34,7 @@ version = attr: nc_time_axis.__version__
[options]
include_package_data = True
install_requires =
- cftime
+ cftime >=1.5
matplotlib
numpy
packages = find:
| SciTools/nc-time-axis | 59c567d307eb8ced44f2c95b393c93ba571e486c | diff --git a/nc_time_axis/tests/integration/test_plot.py b/nc_time_axis/tests/integration/test_plot.py
index 4b90584..4d9ef70 100644
--- a/nc_time_axis/tests/integration/test_plot.py
+++ b/nc_time_axis/tests/integration/test_plot.py
@@ -44,6 +44,23 @@ class Test(unittest.TestCase):
result_ydata = line1.get_ydata()
np.testing.assert_array_equal(result_ydata, datetimes)
+ def test_360_day_calendar_raw_universal_dates(self):
+ datetimes = [
+ cftime.datetime(1986, month, 30, calendar="360_day")
+ for month in range(1, 6)
+ ]
+ (line1,) = plt.plot(datetimes)
+ result_ydata = line1.get_ydata()
+ np.testing.assert_array_equal(result_ydata, datetimes)
+
+ def test_no_calendar_raw_universal_dates(self):
+ datetimes = [
+ cftime.datetime(1986, month, 30, calendar=None)
+ for month in range(1, 6)
+ ]
+ with self.assertRaisesRegex(ValueError, "defined"):
+ plt.plot(datetimes)
+
def test_fill_between(self):
calendar = "360_day"
dt = [
diff --git a/nc_time_axis/tests/unit/test_NetCDFTimeConverter.py b/nc_time_axis/tests/unit/test_NetCDFTimeConverter.py
index b564801..935ffab 100644
--- a/nc_time_axis/tests/unit/test_NetCDFTimeConverter.py
+++ b/nc_time_axis/tests/unit/test_NetCDFTimeConverter.py
@@ -78,6 +78,33 @@ class Test_default_units(unittest.TestCase):
result = NetCDFTimeConverter().default_units(val, None)
self.assertEqual(result, (calendar, unit, cftime.Datetime360Day))
+ def test_360_day_calendar_point_raw_universal_date(self):
+ calendar = "360_day"
+ unit = "days since 2000-01-01"
+ val = cftime.datetime(2014, 8, 12, calendar=calendar)
+ result = NetCDFTimeConverter().default_units(val, None)
+ self.assertEqual(result, (calendar, unit, cftime.datetime))
+
+ def test_360_day_calendar_list_raw_universal_date(self):
+ calendar = "360_day"
+ unit = "days since 2000-01-01"
+ val = [cftime.datetime(2014, 8, 12, calendar=calendar)]
+ result = NetCDFTimeConverter().default_units(val, None)
+ self.assertEqual(result, (calendar, unit, cftime.datetime))
+
+ def test_360_day_calendar_nd_raw_universal_date(self):
+ # Test the case where the input is an nd-array.
+ calendar = "360_day"
+ unit = "days since 2000-01-01"
+ val = np.array(
+ [
+ [cftime.datetime(2014, 8, 12, calendar=calendar)],
+ [cftime.datetime(2014, 8, 13, calendar=calendar)],
+ ]
+ )
+ result = NetCDFTimeConverter().default_units(val, None)
+ self.assertEqual(result, (calendar, unit, cftime.datetime))
+
def test_nonequal_calendars(self):
# Test that different supplied calendars causes an error.
calendar_1 = "360_day"
@@ -89,6 +116,12 @@ class Test_default_units(unittest.TestCase):
with self.assertRaisesRegex(ValueError, "not all equal"):
NetCDFTimeConverter().default_units(val, None)
+ def test_no_calendar_point_raw_universal_date(self):
+ calendar = None
+ val = cftime.datetime(2014, 8, 12, calendar=calendar)
+ with self.assertRaisesRegex(ValueError, "defined"):
+ NetCDFTimeConverter().default_units(val, None)
+
class Test_convert(unittest.TestCase):
def test_numpy_array(self):
@@ -141,6 +174,27 @@ class Test_convert(unittest.TestCase):
assert result == expected
assert len(result) == 1
+ def test_cftime_raw_universal_date(self):
+ val = cftime.datetime(2014, 8, 12, calendar="noleap")
+ result = NetCDFTimeConverter().convert(val, None, None)
+ expected = 5333.0
+ assert result == expected
+ assert np.isscalar(result)
+
+ def test_cftime_list_universal_date(self):
+ val = [cftime.datetime(2014, 8, 12, calendar="noleap")]
+ result = NetCDFTimeConverter().convert(val, None, None)
+ expected = 5333.0
+ assert result == expected
+ assert len(result) == 1
+
+ def test_cftime_tuple_univeral_date(self):
+ val = (cftime.datetime(2014, 8, 12, calendar="noleap"),)
+ result = NetCDFTimeConverter().convert(val, None, None)
+ expected = 5333.0
+ assert result == expected
+ assert len(result) == 1
+
def test_cftime_np_array_CalendarDateTime(self):
val = np.array(
[CalendarDateTime(cftime.datetime(2012, 6, 4), "360_day")],
@@ -154,6 +208,13 @@ class Test_convert(unittest.TestCase):
result = NetCDFTimeConverter().convert(val, None, None)
self.assertEqual(result, np.array([4473.0]))
+ def test_cftime_np_array_raw_universal_date(self):
+ val = np.array(
+ [cftime.datetime(2012, 6, 4, calendar="360_day")], dtype=object
+ )
+ result = NetCDFTimeConverter().convert(val, None, None)
+ self.assertEqual(result, np.array([4473.0]))
+
def test_non_cftime_datetime(self):
val = CalendarDateTime(4, "360_day")
msg = (
diff --git a/nc_time_axis/tests/unit/test_NetCDFTimeDateLocator.py b/nc_time_axis/tests/unit/test_NetCDFTimeDateLocator.py
index 11310a6..a1f060a 100644
--- a/nc_time_axis/tests/unit/test_NetCDFTimeDateLocator.py
+++ b/nc_time_axis/tests/unit/test_NetCDFTimeDateLocator.py
@@ -83,6 +83,23 @@ class Test_compute_resolution(unittest.TestCase):
)
+class Test_compute_resolution_universal_datetime(unittest.TestCase):
+ def check(self, max_n_ticks, num1, num2):
+ locator = NetCDFTimeDateLocator(
+ max_n_ticks=max_n_ticks,
+ calendar=self.calendar,
+ date_unit=self.date_unit,
+ )
+ date1 = cftime.num2date(num1, self.date_unit, calendar=self.calendar)
+ date2 = cftime.num2date(num2, self.date_unit, calendar=self.calendar)
+ return locator.compute_resolution(
+ num1,
+ num2,
+ cftime.datetime(*date1.timetuple(), calendar=self.calendar),
+ cftime.datetime(*date2.timetuple(), calendar=self.calendar),
+ )
+
+
class Test_tick_values(unittest.TestCase):
def setUp(self):
self.date_unit = "days since 2004-01-01 00:00"
| Why can't we just visualise a vanilla netcdftime.datetime
I think it is worth putting the rationale here for why we can't handle a calendar-less netcdftime datetime as I'm certain this will come up regularly.
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"nc_time_axis/tests/integration/test_plot.py::Test::test_no_calendar_raw_universal_dates",
"nc_time_axis/tests/unit/test_NetCDFTimeConverter.py::Test_default_units::test_no_calendar_point_raw_universal_date"
] | [
"nc_time_axis/tests/unit/test_NetCDFTimeConverter.py::Test_axisinfo::test_axis_default_limits",
"nc_time_axis/tests/unit/test_NetCDFTimeConverter.py::Test_default_units::test_360_day_calendar_list_CalendarDateTime",
"nc_time_axis/tests/unit/test_NetCDFTimeConverter.py::Test_default_units::test_360_day_calendar_list_raw_date",
"nc_time_axis/tests/unit/test_NetCDFTimeConverter.py::Test_default_units::test_360_day_calendar_list_raw_universal_date",
"nc_time_axis/tests/unit/test_NetCDFTimeConverter.py::Test_default_units::test_360_day_calendar_nd_CalendarDateTime",
"nc_time_axis/tests/unit/test_NetCDFTimeConverter.py::Test_default_units::test_360_day_calendar_nd_raw_date",
"nc_time_axis/tests/unit/test_NetCDFTimeConverter.py::Test_default_units::test_360_day_calendar_nd_raw_universal_date",
"nc_time_axis/tests/unit/test_NetCDFTimeConverter.py::Test_default_units::test_360_day_calendar_point_CalendarDateTime",
"nc_time_axis/tests/unit/test_NetCDFTimeConverter.py::Test_default_units::test_360_day_calendar_point_raw_date",
"nc_time_axis/tests/unit/test_NetCDFTimeConverter.py::Test_default_units::test_360_day_calendar_point_raw_universal_date",
"nc_time_axis/tests/unit/test_NetCDFTimeConverter.py::Test_default_units::test_nonequal_calendars",
"nc_time_axis/tests/unit/test_NetCDFTimeConverter.py::Test_convert::test_cftime_np_array_CalendarDateTime",
"nc_time_axis/tests/unit/test_NetCDFTimeConverter.py::Test_convert::test_cftime_np_array_raw_date",
"nc_time_axis/tests/unit/test_NetCDFTimeConverter.py::Test_convert::test_cftime_np_array_raw_universal_date",
"nc_time_axis/tests/unit/test_NetCDFTimeConverter.py::Test_convert::test_numpy_array",
"nc_time_axis/tests/unit/test_NetCDFTimeConverter.py::Test_convert::test_numpy_nd_array",
"nc_time_axis/tests/unit/test_NetCDFTimeDateLocator.py::Test_compute_resolution::test_10_years",
"nc_time_axis/tests/unit/test_NetCDFTimeDateLocator.py::Test_compute_resolution::test_30_days",
"nc_time_axis/tests/unit/test_NetCDFTimeDateLocator.py::Test_compute_resolution::test_365_days",
"nc_time_axis/tests/unit/test_NetCDFTimeDateLocator.py::Test_compute_resolution::test_one_day",
"nc_time_axis/tests/unit/test_NetCDFTimeDateLocator.py::Test_compute_resolution::test_one_hour",
"nc_time_axis/tests/unit/test_NetCDFTimeDateLocator.py::Test_compute_resolution::test_one_minute",
"nc_time_axis/tests/unit/test_NetCDFTimeDateLocator.py::Test_tick_values::test_daily",
"nc_time_axis/tests/unit/test_NetCDFTimeDateLocator.py::Test_tick_values::test_hourly",
"nc_time_axis/tests/unit/test_NetCDFTimeDateLocator.py::Test_tick_values::test_minutely",
"nc_time_axis/tests/unit/test_NetCDFTimeDateLocator.py::Test_tick_values::test_monthly",
"nc_time_axis/tests/unit/test_NetCDFTimeDateLocator.py::Test_tick_values::test_secondly",
"nc_time_axis/tests/unit/test_NetCDFTimeDateLocator.py::Test_tick_values::test_yearly",
"nc_time_axis/tests/unit/test_NetCDFTimeDateLocator.py::Test_tick_values_yr0::test_yearly_yr0_remove"
] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
} | "2021-08-14T10:54:47Z" | bsd-3-clause |
|
Scille__umongo-330 | diff --git a/umongo/frameworks/motor_asyncio.py b/umongo/frameworks/motor_asyncio.py
index 976ee5d..ccb61a5 100644
--- a/umongo/frameworks/motor_asyncio.py
+++ b/umongo/frameworks/motor_asyncio.py
@@ -338,12 +338,16 @@ async def _io_validate_data_proxy(schema, data_proxy, partial=None):
async def _reference_io_validate(field, value):
+ if value is None:
+ return
await value.fetch(no_data=True)
async def _list_io_validate(field, value):
+ if not value:
+ return
validators = field.inner.io_validate
- if not validators or not value:
+ if not validators:
return
tasks = [_run_validators(validators, field.inner, e) for e in value]
results = await asyncio.gather(*tasks, return_exceptions=True)
@@ -358,6 +362,8 @@ async def _list_io_validate(field, value):
async def _embedded_document_io_validate(field, value):
+ if not value:
+ return
await _io_validate_data_proxy(value.schema, value._data)
diff --git a/umongo/frameworks/pymongo.py b/umongo/frameworks/pymongo.py
index 591a58d..aace5fe 100644
--- a/umongo/frameworks/pymongo.py
+++ b/umongo/frameworks/pymongo.py
@@ -272,10 +272,14 @@ def _io_validate_data_proxy(schema, data_proxy, partial=None):
def _reference_io_validate(field, value):
+ if value is None:
+ return
value.fetch(no_data=True)
def _list_io_validate(field, value):
+ if not value:
+ return
errors = {}
validators = field.inner.io_validate
if not validators:
@@ -290,6 +294,8 @@ def _list_io_validate(field, value):
def _embedded_document_io_validate(field, value):
+ if not value:
+ return
_io_validate_data_proxy(value.schema, value._data)
diff --git a/umongo/frameworks/txmongo.py b/umongo/frameworks/txmongo.py
index 7a965aa..408d173 100644
--- a/umongo/frameworks/txmongo.py
+++ b/umongo/frameworks/txmongo.py
@@ -273,14 +273,20 @@ def _io_validate_data_proxy(schema, data_proxy, partial=None):
raise ma.ValidationError(errors)
+@inlineCallbacks
def _reference_io_validate(field, value):
- return value.fetch(no_data=True)
+ if value is None:
+ yield
+ else:
+ yield value.fetch(no_data=True)
@inlineCallbacks
def _list_io_validate(field, value):
+ if not value:
+ return
validators = field.inner.io_validate
- if not validators or not value:
+ if not validators:
return
errors = {}
defers = []
@@ -294,6 +300,8 @@ def _list_io_validate(field, value):
def _embedded_document_io_validate(field, value):
+ if not value:
+ return
return _io_validate_data_proxy(value.schema, value._data)
| Scille/umongo | 38099cd9cd484e83c88df20ed6bd6ff1e6316877 | diff --git a/tests/conftest.py b/tests/conftest.py
index 11942e6..342c9ab 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -21,7 +21,7 @@ def classroom_model(instance):
@instance.register
class Course(Document):
name = fields.StrField(required=True)
- teacher = fields.ReferenceField(Teacher, required=True)
+ teacher = fields.ReferenceField(Teacher, required=True, allow_none=True)
@instance.register
class Student(Document):
diff --git a/tests/frameworks/test_motor_asyncio.py b/tests/frameworks/test_motor_asyncio.py
index 1400ebc..9a06fda 100644
--- a/tests/frameworks/test_motor_asyncio.py
+++ b/tests/frameworks/test_motor_asyncio.py
@@ -342,6 +342,11 @@ class TestMotorAsyncIO(BaseDBTest):
with pytest.raises(ma.ValidationError) as exc:
await course.io_validate()
assert exc.value.messages == {'teacher': ['Reference not found for document Teacher.']}
+ # Test setting to None / deleting
+ course.teacher = None
+ await course.io_validate()
+ del course.teacher
+ await course.io_validate()
loop.run_until_complete(do_test())
@@ -474,12 +479,42 @@ class TestMotorAsyncIO(BaseDBTest):
@instance.register
class IOStudent(Student):
- io_field = fields.ListField(fields.IntField(io_validate=io_validate))
+ io_field = fields.ListField(
+ fields.IntField(io_validate=io_validate),
+ allow_none=True
+ )
student = IOStudent(name='Marty', io_field=values)
await student.io_validate()
assert set(called) == set(values)
+ student.io_field = None
+ await student.io_validate()
+ del student.io_field
+ await student.io_validate()
+
+ loop.run_until_complete(do_test())
+
+ def test_io_validate_embedded(self, loop, instance, classroom_model):
+ Student = classroom_model.Student
+
+ @instance.register
+ class EmbeddedDoc(EmbeddedDocument):
+ io_field = fields.IntField()
+
+ @instance.register
+ class IOStudent(Student):
+ embedded_io_field = fields.EmbeddedField(EmbeddedDoc, allow_none=True)
+
+ async def do_test():
+
+ student = IOStudent(name='Marty', embedded_io_field={'io_field': 12})
+ await student.io_validate()
+ student.embedded_io_field = None
+ await student.io_validate()
+ del student.embedded_io_field
+ await student.io_validate()
+
loop.run_until_complete(do_test())
def test_indexes(self, loop, instance):
diff --git a/tests/frameworks/test_pymongo.py b/tests/frameworks/test_pymongo.py
index 4af4436..100279d 100644
--- a/tests/frameworks/test_pymongo.py
+++ b/tests/frameworks/test_pymongo.py
@@ -245,6 +245,11 @@ class TestPymongo(BaseDBTest):
with pytest.raises(ma.ValidationError) as exc:
course.io_validate()
assert exc.value.messages == {'teacher': ['Reference not found for document Teacher.']}
+ # Test setting to None / deleting
+ course.teacher = None
+ course.io_validate()
+ del course.teacher
+ course.io_validate()
def test_io_validate(self, instance, classroom_model):
Student = classroom_model.Student
@@ -331,12 +336,35 @@ class TestPymongo(BaseDBTest):
@instance.register
class IOStudent(Student):
- io_field = fields.ListField(fields.IntField(io_validate=io_validate))
+ io_field = fields.ListField(fields.IntField(io_validate=io_validate), allow_none=True)
student = IOStudent(name='Marty', io_field=values)
student.io_validate()
assert called == values
+ student.io_field = None
+ student.io_validate()
+ del student.io_field
+ student.io_validate()
+
+ def test_io_validate_embedded(self, instance, classroom_model):
+ Student = classroom_model.Student
+
+ @instance.register
+ class EmbeddedDoc(EmbeddedDocument):
+ io_field = fields.IntField()
+
+ @instance.register
+ class IOStudent(Student):
+ embedded_io_field = fields.EmbeddedField(EmbeddedDoc, allow_none=True)
+
+ student = IOStudent(name='Marty', embedded_io_field={'io_field': 12})
+ student.io_validate()
+ student.embedded_io_field = None
+ student.io_validate()
+ del student.embedded_io_field
+ student.io_validate()
+
def test_indexes(self, instance):
@instance.register
diff --git a/tests/frameworks/test_txmongo.py b/tests/frameworks/test_txmongo.py
index 6e11723..a829d44 100644
--- a/tests/frameworks/test_txmongo.py
+++ b/tests/frameworks/test_txmongo.py
@@ -294,6 +294,11 @@ class TestTxMongo(BaseDBTest):
with pytest.raises(ma.ValidationError) as exc:
yield course.io_validate()
assert exc.value.messages == {'teacher': ['Reference not found for document Teacher.']}
+ # Test setting to None / deleting
+ course.teacher = None
+ yield course.io_validate()
+ del course.teacher
+ yield course.io_validate()
@pytest_inlineCallbacks
def test_io_validate(self, instance, classroom_model):
@@ -311,7 +316,7 @@ class TestTxMongo(BaseDBTest):
@instance.register
class IOStudent(Student):
- io_field = fields.StrField(io_validate=io_validate)
+ io_field = fields.StrField(io_validate=io_validate, allow_none=True)
student = IOStudent(name='Marty', io_field=io_field_value)
assert not io_validate_called
@@ -319,6 +324,11 @@ class TestTxMongo(BaseDBTest):
yield student.io_validate()
assert io_validate_called
+ student.io_field = None
+ yield student.io_validate()
+ del student.io_field
+ yield student.io_validate()
+
@pytest_inlineCallbacks
def test_io_validate_error(self, instance, classroom_model):
Student = classroom_model.Student
@@ -417,6 +427,25 @@ class TestTxMongo(BaseDBTest):
yield student.io_validate()
assert called == values
+ @pytest_inlineCallbacks
+ def test_io_validate_embedded(self, instance, classroom_model):
+ Student = classroom_model.Student
+
+ @instance.register
+ class EmbeddedDoc(EmbeddedDocument):
+ io_field = fields.IntField()
+
+ @instance.register
+ class IOStudent(Student):
+ embedded_io_field = fields.EmbeddedField(EmbeddedDoc, allow_none=True)
+
+ student = IOStudent(name='Marty', embedded_io_field={'io_field': 12})
+ yield student.io_validate()
+ student.embedded_io_field = None
+ yield student.io_validate()
+ del student.embedded_io_field
+ yield student.io_validate()
+
@pytest_inlineCallbacks
def test_indexes(self, instance):
| Trying to set a ReferenceField to None fails in _reference_io_validate
Using Python 3.8.6 and `motor_asyncio`, when trying to set a `ReferenceField` in a document to None, I get an `AttributeError` while committing.
The traceback looks something like this:
```
Traceback (most recent call last):
... various project-specific stuff ...
await obj.commit()
File "/opt/venv/lib/python3.7/site-packages/umongo/frameworks/motor_asyncio.py", line 161, in commit
await self.io_validate(validate_all=io_validate_all)
File "/opt/venv/lib/python3.7/site-packages/umongo/frameworks/motor_asyncio.py", line 253, in io_validate
self.schema, self._data, partial=self._data.get_modified_fields())
File "/opt/venv/lib/python3.7/site-packages/umongo/frameworks/motor_asyncio.py", line 335, in _io_validate_data_proxy
raise res
File "/usr/lib/python3.7/asyncio/tasks.py", line 223, in __step
result = coro.send(None)
File "/opt/venv/lib/python3.7/site-packages/umongo/frameworks/motor_asyncio.py", line 307, in _run_validators
raise res
File "/usr/lib/python3.7/asyncio/tasks.py", line 223, in __step
result = coro.send(None)
File "/opt/venv/lib/python3.7/site-packages/umongo/frameworks/motor_asyncio.py", line 341, in _reference_io_validate
await value.fetch(no_data=True)
AttributeError: 'NoneType' object has no attribute 'fetch'
```
This appears to be because the `_reference_io_validate` function doesn't check if the value it's validating is not None, unlike (for example) the one for list fields:
```python
async def _reference_io_validate(field, value):
await value.fetch(no_data=True)
```
(from [`motor_asyncio.py`](https://github.com/Scille/umongo/blob/master/umongo/frameworks/motor_asyncio.py#L340) line 340)
Currently I'm working around this by doing the update manually (with `Impl.collection.update_one({"_id": obj.pk}, {"$unset": {"field": None}})`) but it'd much nicer if this worked natively. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/frameworks/test_pymongo.py::TestPymongo::test_io_validate_list",
"tests/frameworks/test_pymongo.py::TestPymongo::test_io_validate_embedded"
] | [
"tests/frameworks/test_pymongo.py::TestPymongo::test_io_validate",
"tests/frameworks/test_pymongo.py::TestPymongo::test_io_validate_multi_validate"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2021-01-04T11:03:28Z" | mit |
|
SebastianCzoch__influx-line-protocol-11 | diff --git a/influx_line_protocol/metric.py b/influx_line_protocol/metric.py
index dd96e5f..e8b06eb 100644
--- a/influx_line_protocol/metric.py
+++ b/influx_line_protocol/metric.py
@@ -10,20 +10,37 @@ class Metric(object):
self.timestamp = timestamp
def add_tag(self, name, value):
- if ' ' in str(value):
- value = value.replace(' ', '\\ ')
- self.tags[name] = value
+ self.tags[str(name)] = str(value)
def add_value(self, name, value):
- self.values[name] = self.__parse_value(value)
+ self.values[str(name)] = value
def __str__(self):
- protocol = self.measurement
- tags = ["%s=%s" % (key.replace(' ', '\\ '), self.tags[key]) for key in self.tags]
+ # Escape measurement manually
+ escaped_measurement = self.measurement.replace(',', '\\,')
+ escaped_measurement = escaped_measurement.replace(' ', '\\ ')
+ protocol = escaped_measurement
+
+ # Create tag strings
+ tags = []
+ for key, value in self.tags.items():
+ escaped_name = self.__escape(key)
+ escaped_value = self.__escape(value)
+
+ tags.append("%s=%s" % (escaped_name, escaped_value))
+
+ # Concatenate tags to current line protocol
if len(tags) > 0:
protocol = "%s,%s" % (protocol, ",".join(tags))
- values = ["%s=%s" % (key, self.values[key]) for key in self.values]
+ # Create field strings
+ values = []
+ for key, value in self.values.items():
+ escaped_name = self.__escape(key)
+ escaped_value = self.__parse_value(value)
+ values.append("%s=%s" % (escaped_name, escaped_value))
+
+ # Concatenate fields to current line protocol
protocol = "%s %s" % (protocol, ",".join(values))
if self.timestamp is not None:
@@ -31,14 +48,27 @@ class Metric(object):
return protocol
+ def __escape(self, value, escape_quotes=False):
+ # Escape backslashes first since the other characters are escaped with
+ # backslashes
+ new_value = value.replace('\\', '\\\\')
+ new_value = new_value.replace(' ', '\\ ')
+ new_value = new_value.replace('=', '\\=')
+ new_value = new_value.replace(',', '\\,')
+
+ if escape_quotes:
+ new_value = new_value.replace('"', '\\"')
+
+ return new_value
+
def __parse_value(self, value):
- if type(value).__name__ == 'int':
+ if type(value) is int:
return "%di" % value
- if type(value).__name__ == 'float':
+ if type(value) is float:
return "%g" % value
- if type(value).__name__ == 'bool':
+ if type(value) is bool:
return value and "t" or "f"
- return "\"%s\"" % value
+ return "\"%s\"" % self.__escape(value, True)
| SebastianCzoch/influx-line-protocol | cfb52c5e223de5f4dd6a73ddee0b458ce773b61b | diff --git a/influx_line_protocol/test_metric.py b/influx_line_protocol/test_metric.py
index 73ae904..d4d323a 100644
--- a/influx_line_protocol/test_metric.py
+++ b/influx_line_protocol/test_metric.py
@@ -15,12 +15,58 @@ class TestMetric(unittest.TestCase):
self.assertEqual("test,tag1=string ", str(metric))
+ def test_metric_escape_measurement_spaces(self):
+ metric = Metric("test test")
+ metric.add_value("a", "b")
+
+ self.assertEqual("test\\ test a=\"b\"", str(metric))
+
+ def test_metric_escape_measurement_commas(self):
+ metric = Metric("test,test")
+ metric.add_value("a", "b")
+
+ self.assertEqual("test\\,test a=\"b\"", str(metric))
+
def test_metric_with_tag_string_space_without_values_and_timestamp(self):
metric = Metric("test")
metric.add_tag("tag name", "string with space")
self.assertEqual("test,tag\\ name=string\\ with\\ space ", str(metric))
+ def test_metric_escape_tag_and_field_commas(self):
+ metric = Metric("test")
+ metric.add_tag("a,b", "c,d")
+ metric.add_value("x,y", "z")
+
+ self.assertEqual("test,a\\,b=c\\,d x\\,y=\"z\"", str(metric))
+
+ def test_metric_escape_tag_and_field_equals(self):
+ metric = Metric("test")
+ metric.add_tag("a=b", "c=d")
+ metric.add_value("x=y", "z")
+
+ self.assertEqual("test,a\\=b=c\\=d x\\=y=\"z\"", str(metric))
+
+ def test_metric_escape_field_double_quotes(self):
+ metric = Metric("test")
+ metric.add_tag("a\"b", "c\"d")
+ metric.add_value("x\"y", "z\"")
+
+ self.assertEqual("test,a\"b=c\"d x\"y=\"z\\\"\"", str(metric))
+
+ def test_metric_escape_tag_and_field_backslash(self):
+ metric = Metric("test")
+ metric.add_tag("a\\b", "c\\d")
+ metric.add_value("x\\y", "z\\a")
+
+ self.assertEqual("test,a\\\\b=c\\\\d x\\\\y=\"z\\\\a\"", str(metric))
+
+ def test_metric_escape_field_double_quotes_and_backslash(self):
+ metric = Metric("test")
+ metric.add_value("x", "z\\\"")
+
+ self.assertEqual("test x=\"z\\\\\\\"\"", str(metric))
+
def test_metric_with_tag_value_and_timestamp(self):
metric = Metric("test")
metric.add_tag("tag", "string")
| needs to properly escape all characters
it only escapes spaces in tag keys. It also needs to escape = and ,
https://docs.influxdata.com/influxdb/v1.7/write_protocols/line_protocol_tutorial/#special-characters | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"influx_line_protocol/test_metric.py::TestMetric::test_metric_escape_field_double_quotes",
"influx_line_protocol/test_metric.py::TestMetric::test_metric_escape_field_double_quotes_and_backslash",
"influx_line_protocol/test_metric.py::TestMetric::test_metric_escape_measurement_commas",
"influx_line_protocol/test_metric.py::TestMetric::test_metric_escape_measurement_spaces",
"influx_line_protocol/test_metric.py::TestMetric::test_metric_escape_tag_and_field_backslash",
"influx_line_protocol/test_metric.py::TestMetric::test_metric_escape_tag_and_field_commas",
"influx_line_protocol/test_metric.py::TestMetric::test_metric_escape_tag_and_field_equals"
] | [
"influx_line_protocol/test_metric.py::TestMetric::test_metric_multiple_tags_without_values_and_timestamp",
"influx_line_protocol/test_metric.py::TestMetric::test_metric_multiple_values_tags_and_timestamp",
"influx_line_protocol/test_metric.py::TestMetric::test_metric_multiple_values_without_tags_and_timestamp",
"influx_line_protocol/test_metric.py::TestMetric::test_metric_with_tag_string_space_without_values_and_timestamp",
"influx_line_protocol/test_metric.py::TestMetric::test_metric_with_tag_value_and_timestamp",
"influx_line_protocol/test_metric.py::TestMetric::test_metric_without_tags_and_timestamp",
"influx_line_protocol/test_metric.py::TestMetric::test_metric_without_tags_values_and_timestamp",
"influx_line_protocol/test_metric.py::TestMetric::test_metric_without_values_and_timestamp"
] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
} | "2020-08-07T08:37:23Z" | mit |
|
Senth__minecraft-mod-manager-36 | diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7d15922..b16295c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## [1.0.4] - ???
+
+### Fixed
+
+- Reinstalling a mod after deleting it manually #33
+
## [1.0.3] - 2021-04-25
### Fixed
diff --git a/minecraft_mod_manager/gateways/sqlite.py b/minecraft_mod_manager/gateways/sqlite.py
index 7305020..04d8c82 100644
--- a/minecraft_mod_manager/gateways/sqlite.py
+++ b/minecraft_mod_manager/gateways/sqlite.py
@@ -2,12 +2,11 @@ import sqlite3
from os import path
from typing import Dict, List
-from ..gateways.sqlite_upgrader import SqliteUpgrader
-
from ..config import config
from ..core.entities.mod import Mod
from ..core.entities.sites import Sites
from ..core.errors.mod_already_exists import ModAlreadyExists
+from ..gateways.sqlite_upgrader import SqliteUpgrader
from ..utils.logger import LogColors, Logger
from .sqlite_upgrader import _Column
@@ -105,15 +104,18 @@ class Sqlite:
)
return mods
- def exists(self, id: str) -> bool:
- self._cursor.execute(f"SELECT 1 FROM mod WHERE {_Column.c_id}=?", [id])
+ def exists(self, id: str, filter_active: bool = True) -> bool:
+ extra_filter = ""
+ if filter_active:
+ extra_filter = f"AND {_Column.c_active}=1"
+ self._cursor.execute(f"SELECT 1 FROM mod WHERE {_Column.c_id}=? {extra_filter}", [id])
return bool(self._cursor.fetchone())
def update_mod(self, mod: Mod):
if config.pretend:
return
- if self.exists(mod.id):
+ if self.exists(mod.id, filter_active=False):
self._connection.execute(
"UPDATE mod SET "
+ f"{_Column.c_site}=?, "
| Senth/minecraft-mod-manager | bed8d27f3e6ca6570c6d21faf8959d92c753b7b8 | diff --git a/minecraft_mod_manager/gateways/sqlite_test.py b/minecraft_mod_manager/gateways/sqlite_test.py
index f8f3325..28ec7af 100644
--- a/minecraft_mod_manager/gateways/sqlite_test.py
+++ b/minecraft_mod_manager/gateways/sqlite_test.py
@@ -3,11 +3,11 @@ import sqlite3
from typing import Any, List, Tuple, Union
import pytest
-from ..core.entities.sites import Sites
-from ..core.errors.mod_already_exists import ModAlreadyExists
from ..config import config
from ..core.entities.mod import Mod
+from ..core.entities.sites import Sites
+from ..core.errors.mod_already_exists import ModAlreadyExists
from ..gateways.sqlite import Sqlite
db_file = f".{config.app_name}.db"
@@ -148,6 +148,30 @@ def test_exists_when_exists(mod: Mod, sqlite: Sqlite, db: sqlite3.Connection):
assert result
+def test_does_not_exist_when_set_as_inactive(mod: Mod, sqlite: Sqlite, db: sqlite3.Connection):
+ db.execute(
+ "INSERT INTO mod (id, site, site_id, site_slug, upload_time, active) VALUES (?, ?, ?, ?, ?, 0)",
+ [mod.id, mod.site.value, mod.site_id, mod.site_slug, mod.upload_time],
+ )
+ db.commit()
+
+ result = sqlite.exists(mod.id)
+
+ assert not result
+
+
+def test_exists_when_set_as_inactive_but_not_filtering(mod: Mod, sqlite: Sqlite, db: sqlite3.Connection):
+ db.execute(
+ "INSERT INTO mod (id, site, site_id, site_slug, upload_time, active) VALUES (?, ?, ?, ?, ?, 0)",
+ [mod.id, mod.site.value, mod.site_id, mod.site_slug, mod.upload_time],
+ )
+ db.commit()
+
+ result = sqlite.exists(mod.id, filter_active=False)
+
+ assert result
+
+
def test_exists_when_doesnt_exists(sqlite: Sqlite):
result = sqlite.exists("id")
| Mod is already installed - Can't reinstall mod after manually deleting it
When you install a mod via the mod manager and then delete it from the folder and try to install it again via the manager it says the mod is already installed.
I had thinked about an uninstall command line to delete the mod from the database as a possible solution. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"minecraft_mod_manager/gateways/sqlite_test.py::test_does_not_exist_when_set_as_inactive",
"minecraft_mod_manager/gateways/sqlite_test.py::test_exists_when_set_as_inactive_but_not_filtering"
] | [
"minecraft_mod_manager/gateways/sqlite_test.py::test_insert_mod",
"minecraft_mod_manager/gateways/sqlite_test.py::test_insert_mod_when_fields_set_to_none",
"minecraft_mod_manager/gateways/sqlite_test.py::test_insert_mod_raises_error_when_already_exists",
"minecraft_mod_manager/gateways/sqlite_test.py::test_skip_insert_mod_when_pretend",
"minecraft_mod_manager/gateways/sqlite_test.py::test_update_mod",
"minecraft_mod_manager/gateways/sqlite_test.py::test_skip_update_mod_when_pretend",
"minecraft_mod_manager/gateways/sqlite_test.py::test_insert_mod_when_calling_update_mod_but_does_not_exist",
"minecraft_mod_manager/gateways/sqlite_test.py::test_exists_when_exists",
"minecraft_mod_manager/gateways/sqlite_test.py::test_exists_when_doesnt_exists",
"minecraft_mod_manager/gateways/sqlite_test.py::test_sync_with_dir[test0]",
"minecraft_mod_manager/gateways/sqlite_test.py::test_sync_with_dir[test1]",
"minecraft_mod_manager/gateways/sqlite_test.py::test_sync_with_dir[test2]",
"minecraft_mod_manager/gateways/sqlite_test.py::test_sync_with_dir[test3]",
"minecraft_mod_manager/gateways/sqlite_test.py::test_sync_with_dir[test4]"
] | {
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2021-04-29T17:18:03Z" | mit |
|
SethMMorton__natsort-102 | diff --git a/docs/api.rst b/docs/api.rst
index 5e7a482..8052606 100644
--- a/docs/api.rst
+++ b/docs/api.rst
@@ -91,7 +91,14 @@ Help With Creating Function Keys
If you need to create a complicated *key* argument to (for example)
:func:`natsorted` that is actually multiple functions called one after the other,
the following function can help you easily perform this action. It is
-used internally to :mod:`natsort`, and has been exposed publically for
+used internally to :mod:`natsort`, and has been exposed publicly for
the convenience of the user.
.. autofunction:: chain_functions
+
+If you need to be able to search your input for numbers using the same definition
+as :mod:`natsort`, you can do so using the following function. Given your chosen
+algorithm (selected using the :class:`~natsort.ns` enum), the corresponding regular
+expression to locate numbers will be returned.
+
+.. autofunction:: numeric_regex_chooser
diff --git a/docs/examples.rst b/docs/examples.rst
index e44aa1c..04ca632 100644
--- a/docs/examples.rst
+++ b/docs/examples.rst
@@ -245,6 +245,56 @@ sort key so that:
>>> natsorted(b, key=attrgetter('bar'))
[Foo('num2'), Foo('num3'), Foo('num5')]
+.. _unit_sorting:
+
+Accounting for Units When Sorting
++++++++++++++++++++++++++++++++++
+
+:mod:`natsort` does not come with any pre-built mechanism to sort units,
+but you can write your own `key` to do this. Below, I will demonstrate sorting
+imperial lengths (e.g. feet an inches), but of course you can extend this to any
+set of units you need. This example is based on code from
+`this issue <https://github.com/SethMMorton/natsort/issues/100#issuecomment-530659310>`_,
+and uses the function :func:`natsort.numeric_regex_chooser` to build a regular
+expression that will parse numbers in the same manner as :mod:`natsort` itself.
+
+.. code-block:: pycon
+
+ >>> import re
+ >>> import natsort
+ >>>
+ >>> # Define how each unit will be transformed
+ >>> conversion_mapping = {
+ ... "in": 1,
+ ... "inch": 1,
+ ... "inches": 1,
+ ... "ft": 12,
+ ... "feet": 12,
+ ... "foot": 12,
+ ... }
+ >>>
+ >>> # This regular expression searches for numbers and units
+ >>> all_units = "|".join(conversion_mapping.keys())
+ >>> float_re = natsort.numeric_regex_chooser(natsort.FLOAT | natsort.SIGNED)
+ >>> unit_finder = re.compile(r"({})\s*({})".format(float_re, all_units), re.IGNORECASE)
+ >>>
+ >>> def unit_replacer(matchobj):
+ ... """
+ ... Given a regex match object, return a replacement string where units are modified
+ ... """
+ ... number = matchobj.group(1)
+ ... unit = matchobj.group(2)
+ ... new_number = float(number) * conversion_mapping[unit]
+ ... return "{} in".format(new_number)
+ ...
+ >>> # Demo time!
+ >>> data = ['1 ft', '5 in', '10 ft', '2 in']
+ >>> [unit_finder.sub(unit_replacer, x) for x in data]
+ ['12.0 in', '5.0 in', '120.0 in', '2.0 in']
+ >>>
+ >>> natsort.natsorted(data, key=lambda x: unit_finder.sub(unit_replacer, x))
+ ['2 in', '5 in', '1 ft', '10 ft']
+
Generating a Natsort Key
------------------------
diff --git a/natsort/__init__.py b/natsort/__init__.py
index da23650..561164b 100644
--- a/natsort/__init__.py
+++ b/natsort/__init__.py
@@ -15,6 +15,7 @@ from natsort.natsort import (
natsort_keygen,
natsorted,
ns,
+ numeric_regex_chooser,
order_by_index,
realsorted,
)
@@ -41,6 +42,7 @@ __all__ = [
"as_utf8",
"ns",
"chain_functions",
+ "numeric_regex_chooser",
]
# Add the ns keys to this namespace for convenience.
diff --git a/natsort/natsort.py b/natsort/natsort.py
index e597815..58641e4 100644
--- a/natsort/natsort.py
+++ b/natsort/natsort.py
@@ -601,6 +601,25 @@ def order_by_index(seq, index, iter=False):
return (seq[i] for i in index) if iter else [seq[i] for i in index]
+def numeric_regex_chooser(alg):
+ """
+ Select an appropriate regex for the type of number of interest.
+
+ Parameters
+ ----------
+ alg : ns enum
+ Used to indicate the regular expression to select.
+
+ Returns
+ -------
+ regex : str
+ Regular expression string that matches the desired number type.
+
+ """
+ # Remove the leading and trailing parens
+ return utils.regex_chooser(alg).pattern[1:-1]
+
+
if float(sys.version[:3]) < 3:
# pylint: disable=unused-variable
# noinspection PyUnresolvedReferences,PyPep8Naming
diff --git a/tox.ini b/tox.ini
index 9382ada..2919f69 100644
--- a/tox.ini
+++ b/tox.ini
@@ -24,11 +24,11 @@ extras =
commands =
# Only run How It Works doctest on Python 3.6.
py36: {envpython} -m doctest -o IGNORE_EXCEPTION_DETAIL docs/howitworks.rst
- # Other doctests are run for all pythons.
- pytest README.rst docs/intro.rst docs/examples.rst
+ # Other doctests are run for all pythons except 2.7.
+ !py27: pytest README.rst docs/intro.rst docs/examples.rst
pytest --doctest-modules {envsitepackagesdir}/natsort
# Full test suite. Allow the user to pass command-line objects.
- pytest --tb=short --cov {envsitepackagesdir}/natsort --cov-report term-missing {posargs:}
+ pytest --hypothesis-profile=slow-tests --tb=short --cov {envsitepackagesdir}/natsort --cov-report term-missing {posargs:}
# Check code quality.
[testenv:flake8]
| SethMMorton/natsort | 5e640c09c5b4a10b86e3419ca81c7fb81f27a9de | diff --git a/tests/conftest.py b/tests/conftest.py
index 8a7412b..d584789 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -4,9 +4,19 @@ Fixtures for pytest.
import locale
+import hypothesis
import pytest
+# This disables the "too slow" hypothesis heath check globally.
+# For some reason it thinks that the text/binary generation is too
+# slow then causes the tests to fail.
+hypothesis.settings.register_profile(
+ "slow-tests",
+ suppress_health_check=[hypothesis.HealthCheck.too_slow],
+)
+
+
def load_locale(x):
"""Convenience to load a locale, trying ISO8859-1 first."""
try:
diff --git a/tests/test_regex.py b/tests/test_regex.py
index d3fe617..a6da62d 100644
--- a/tests/test_regex.py
+++ b/tests/test_regex.py
@@ -3,6 +3,7 @@
from __future__ import unicode_literals
import pytest
+from natsort import ns, numeric_regex_chooser
from natsort.utils import NumericalRegularExpressions as NumRegex
@@ -98,3 +99,22 @@ labels = ["{}-{}".format(given, regex_names[regex]) for given, _, regex in regex
def test_regex_splits_correctly(x, expected, regex):
# noinspection PyUnresolvedReferences
assert regex.split(x) == expected
+
+
[email protected](
+ "given, expected",
+ [
+ (ns.INT, NumRegex.int_nosign()),
+ (ns.INT | ns.UNSIGNED, NumRegex.int_nosign()),
+ (ns.INT | ns.SIGNED, NumRegex.int_sign()),
+ (ns.INT | ns.NOEXP, NumRegex.int_nosign()),
+ (ns.FLOAT, NumRegex.float_nosign_exp()),
+ (ns.FLOAT | ns.UNSIGNED, NumRegex.float_nosign_exp()),
+ (ns.FLOAT | ns.SIGNED, NumRegex.float_sign_exp()),
+ (ns.FLOAT | ns.NOEXP, NumRegex.float_nosign_noexp()),
+ (ns.FLOAT | ns.SIGNED | ns.NOEXP, NumRegex.float_sign_noexp()),
+ (ns.FLOAT | ns.UNSIGNED | ns.NOEXP, NumRegex.float_nosign_noexp()),
+ ],
+)
+def test_regex_chooser(given, expected):
+ assert numeric_regex_chooser(given) == expected.pattern[1:-1] # remove parens
| Consider units of measurement
Hi Seth,
I just stumbled over natsort and think it's great! Would it be feasible to consider units of measurement to sort something like ['1 ft', '5 in', '10 ft', '2 in']? I would really appreciate it, if you could point me in the right direction.
Cheers,
Gunnar | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_regex.py::test_regex_splits_correctly[abc12.34.56-7def-float_nosign_exp]",
"tests/test_regex.py::test_regex_chooser[7-([-+]?(?:\\\\d+\\\\.?\\\\d*|\\\\.\\\\d+)|[\\xb2\\xb3\\xb9\\xbc\\xbd\\xbe\\u09f4\\u09f5\\u09f6\\u09f7\\u09f8\\u09f9\\u0b72\\u0b73\\u0b74\\u0b75\\u0b76\\u0b77\\u0bf0\\u0bf1\\u0bf2\\u0c78\\u0c79\\u0c7a\\u0c7b\\u0c7c\\u0c7d\\u0c7e\\u0d58\\u0d59\\u0d5a\\u0d5b\\u0d5c\\u0d5d\\u0d5e\\u0d70\\u0d71\\u0d72\\u0d73\\u0d74\\u0d75\\u0d76\\u0d77\\u0d78\\u0f2a\\u0f2b\\u0f2c\\u0f2d\\u0f2e\\u0f2f\\u0f30\\u0f31\\u0f32\\u0f33\\u1369\\u136a\\u136b\\u136c\\u136d\\u136e\\u136f\\u1370\\u1371\\u1372\\u1373\\u1374\\u1375\\u1376\\u1377\\u1378\\u1379\\u137a\\u137b\\u137c\\u16ee\\u16ef\\u16f0\\u17f0\\u17f1\\u17f2\\u17f3\\u17f4\\u17f5\\u17f6\\u17f7\\u17f8\\u17f9\\u19da\\u2070\\u2074\\u2075\\u2076\\u2077\\u2078\\u2079\\u2080\\u2081\\u2082\\u2083\\u2084\\u2085\\u2086\\u2087\\u2088\\u2089\\u2150\\u2151\\u2152\\u2153\\u2154\\u2155\\u2156\\u2157\\u2158\\u2159\\u215a\\u215b\\u215c\\u215d\\u215e\\u215f\\u2160\\u2161\\u2162\\u2163\\u2164\\u2165\\u2166\\u2167\\u2168\\u2169\\u216a\\u216b\\u216c\\u216d\\u216e\\u216f\\u2170\\u2171\\u2172\\u2173\\u2174\\u2175\\u2176\\u2177\\u2178\\u2179\\u217a\\u217b\\u217c\\u217d\\u217e\\u217f\\u2180\\u2181\\u2182\\u2185\\u2186\\u2187\\u2188\\u2189\\u2460\\u2461\\u2462\\u2463\\u2464\\u2465\\u2466\\u2467\\u2468\\u2469\\u246a\\u246b\\u246c\\u246d\\u246e\\u246f\\u2470\\u2471\\u2472\\u2473\\u2474\\u2475\\u2476\\u2477\\u2478\\u2479\\u247a\\u247b\\u247c\\u247d\\u247e\\u247f\\u2480\\u2481\\u2482\\u2483\\u2484\\u2485\\u2486\\u2487\\u2488\\u2489\\u248a\\u248b\\u248c\\u248d\\u248e\\u248f\\u2490\\u2491\\u2492\\u2493\\u2494\\u2495\\u2496\\u2497\\u2498\\u2499\\u249a\\u249b\\u24ea\\u24eb\\u24ec\\u24ed\\u24ee\\u24ef\\u24f0\\u24f1\\u24f2\\u24f3\\u24f4\\u24f5\\u24f6\\u24f7\\u24f8\\u24f9\\u24fa\\u24fb\\u24fc\\u24fd\\u24fe\\u24ff\\u2776\\u2777\\u2778\\u2779\\u277a\\u277b\\u277c\\u277d\\u277e\\u277f\\u2780\\u2781\\u2782\\u2783\\u2784\\u2785\\u2786\\u2787\\u2788\\u2789\\u278a\\u278b\\u278c\\u278d\\u278e\\u278f\\u2790\\u2791\\u2792\\u2793\\u2cfd\\u3007\\u3021\\u3022\\u3023\\u3024\\u3025\\u3026\\u3027\\u3028\\u3029\\u3038\\u3039\\u303a\\u3192\\u3193\\u3194\\u3195\\u3220\\u3221\\u3222\\u3223\\u3224\\u3225\\u3226\\u3227\\u3228\\u3229\\u3248\\u3249\\u324a\\u324b\\u324c\\u324d\\u324e\\u324f\\u3251\\u3252\\u3253\\u3254\\u3255\\u3256\\u3257\\u3258\\u3259\\u325a\\u325b\\u325c\\u325d\\u325e\\u325f\\u3280\\u3281\\u3282\\u3283\\u3284\\u3285\\u3286\\u3287\\u3288\\u3289\\u32b1\\u32b2\\u32b3\\u32b4\\u32b5\\u32b6\\u32b7\\u32b8\\u32b9\\u32ba\\u32bb\\u32bc\\u32bd\\u32be\\u32bf\\u3405\\u3483\\u382a\\u3b4d\\u4e00\\u4e03\\u4e07\\u4e09\\u4e5d\\u4e8c\\u4e94\\u4e96\\u4ebf\\u4ec0\\u4edf\\u4ee8\\u4f0d\\u4f70\\u5104\\u5146\\u5169\\u516b\\u516d\\u5341\\u5343\\u5344\\u5345\\u534c\\u53c1\\u53c2\\u53c3\\u53c4\\u56db\\u58f1\\u58f9\\u5e7a\\u5efe\\u5eff\\u5f0c\\u5f0d\\u5f0e\\u5f10\\u62fe\\u634c\\u67d2\\u6f06\\u7396\\u767e\\u8086\\u842c\\u8cae\\u8cb3\\u8d30\\u9621\\u9646\\u964c\\u9678\\u96f6\\ua6e6\\ua6e7\\ua6e8\\ua6e9\\ua6ea\\ua6eb\\ua6ec\\ua6ed\\ua6ee\\ua6ef\\ua830\\ua831\\ua832\\ua833\\ua834\\ua835\\uf96b\\uf973\\uf978\\uf9b2\\uf9d1\\uf9d3\\uf9fd\\U00010107\\U00010108\\U00010109\\U0001010a\\U0001010b\\U0001010c\\U0001010d\\U0001010e\\U0001010f\\U00010110\\U00010111\\U00010112\\U00010113\\U00010114\\U00010115\\U00010116\\U00010117\\U00010118\\U00010119\\U0001011a\\U0001011b\\U0001011c\\U0001011d\\U0001011e\\U0001011f\\U00010120\\U00010121\\U00010122\\U00010123\\U00010124\\U00010125\\U00010126\\U00010127\\U00010128\\U00010129\\U0001012a\\U0001012b\\U0001012c\\U0001012d\\U0001012e\\U0001012f\\U00010130\\U00010131\\U00010132\\U00010133\\U00010140\\U00010141\\U00010142\\U00010143\\U00010144\\U00010145\\U00010146\\U00010147\\U00010148\\U00010149\\U0001014a\\U0001014b\\U0001014c\\U0001014d\\U0001014e\\U0001014f\\U00010150\\U00010151\\U00010152\\U00010153\\U00010154\\U00010155\\U00010156\\U00010157\\U00010158\\U00010159\\U0001015a\\U0001015b\\U0001015c\\U0001015d\\U0001015e\\U0001015f\\U00010160\\U00010161\\U00010162\\U00010163\\U00010164\\U00010165\\U00010166\\U00010167\\U00010168\\U00010169\\U0001016a\\U0001016b\\U0001016c\\U0001016d\\U0001016e\\U0001016f\\U00010170\\U00010171\\U00010172\\U00010173\\U00010174\\U00010175\\U00010176\\U00010177\\U00010178\\U0001018a\\U0001018b\\U000102e1\\U000102e2\\U000102e3\\U000102e4\\U000102e5\\U000102e6\\U000102e7\\U000102e8\\U000102e9\\U000102ea\\U000102eb\\U000102ec\\U000102ed\\U000102ee\\U000102ef\\U000102f0\\U000102f1\\U000102f2\\U000102f3\\U000102f4\\U000102f5\\U000102f6\\U000102f7\\U000102f8\\U000102f9\\U000102fa\\U000102fb\\U00010320\\U00010321\\U00010322\\U00010323\\U00010341\\U0001034a\\U000103d1\\U000103d2\\U000103d3\\U000103d4\\U000103d5\\U00010858\\U00010859\\U0001085a\\U0001085b\\U0001085c\\U0001085d\\U0001085e\\U0001085f\\U00010879\\U0001087a\\U0001087b\\U0001087c\\U0001087d\\U0001087e\\U0001087f\\U000108a7\\U000108a8\\U000108a9\\U000108aa\\U000108ab\\U000108ac\\U000108ad\\U000108ae\\U000108af\\U000108fb\\U000108fc\\U000108fd\\U000108fe\\U000108ff\\U00010916\\U00010917\\U00010918\\U00010919\\U0001091a\\U0001091b\\U000109bc\\U000109bd\\U000109c0\\U000109c1\\U000109c2\\U000109c3\\U000109c4\\U000109c5\\U000109c6\\U000109c7\\U000109c8\\U000109c9\\U000109ca\\U000109cb\\U000109cc\\U000109cd\\U000109ce\\U000109cf\\U000109d2\\U000109d3\\U000109d4\\U000109d5\\U000109d6\\U000109d7\\U000109d8\\U000109d9\\U000109da\\U000109db\\U000109dc\\U000109dd\\U000109de\\U000109df\\U000109e0\\U000109e1\\U000109e2\\U000109e3\\U000109e4\\U000109e5\\U000109e6\\U000109e7\\U000109e8\\U000109e9\\U000109ea\\U000109eb\\U000109ec\\U000109ed\\U000109ee\\U000109ef\\U000109f0\\U000109f1\\U000109f2\\U000109f3\\U000109f4\\U000109f5\\U000109f6\\U000109f7\\U000109f8\\U000109f9\\U000109fa\\U000109fb\\U000109fc\\U000109fd\\U000109fe\\U000109ff\\U00010a40\\U00010a41\\U00010a42\\U00010a43\\U00010a44\\U00010a45\\U00010a46\\U00010a47\\U00010a48\\U00010a7d\\U00010a7e\\U00010a9d\\U00010a9e\\U00010a9f\\U00010aeb\\U00010aec\\U00010aed\\U00010aee\\U00010aef\\U00010b58\\U00010b59\\U00010b5a\\U00010b5b\\U00010b5c\\U00010b5d\\U00010b5e\\U00010b5f\\U00010b78\\U00010b79\\U00010b7a\\U00010b7b\\U00010b7c\\U00010b7d\\U00010b7e\\U00010b7f\\U00010ba9\\U00010baa\\U00010bab\\U00010bac\\U00010bad\\U00010bae\\U00010baf\\U00010cfa\\U00010cfb\\U00010cfc\\U00010cfd\\U00010cfe\\U00010cff\\U00010e60\\U00010e61\\U00010e62\\U00010e63\\U00010e64\\U00010e65\\U00010e66\\U00010e67\\U00010e68\\U00010e69\\U00010e6a\\U00010e6b\\U00010e6c\\U00010e6d\\U00010e6e\\U00010e6f\\U00010e70\\U00010e71\\U00010e72\\U00010e73\\U00010e74\\U00010e75\\U00010e76\\U00010e77\\U00010e78\\U00010e79\\U00010e7a\\U00010e7b\\U00010e7c\\U00010e7d\\U00010e7e\\U00010f1d\\U00010f1e\\U00010f1f\\U00010f20\\U00010f21\\U00010f22\\U00010f23\\U00010f24\\U00010f25\\U00010f26\\U00010f51\\U00010f52\\U00010f53\\U00010f54\\U00011052\\U00011053\\U00011054\\U00011055\\U00011056\\U00011057\\U00011058\\U00011059\\U0001105a\\U0001105b\\U0001105c\\U0001105d\\U0001105e\\U0001105f\\U00011060\\U00011061\\U00011062\\U00011063\\U00011064\\U00011065\\U000111e1\\U000111e2\\U000111e3\\U000111e4\\U000111e5\\U000111e6\\U000111e7\\U000111e8\\U000111e9\\U000111ea\\U000111eb\\U000111ec\\U000111ed\\U000111ee\\U000111ef\\U000111f0\\U000111f1\\U000111f2\\U000111f3\\U000111f4\\U0001173a\\U0001173b\\U000118ea\\U000118eb\\U000118ec\\U000118ed\\U000118ee\\U000118ef\\U000118f0\\U000118f1\\U000118f2\\U00011c5a\\U00011c5b\\U00011c5c\\U00011c5d\\U00011c5e\\U00011c5f\\U00011c60\\U00011c61\\U00011c62\\U00011c63\\U00011c64\\U00011c65\\U00011c66\\U00011c67\\U00011c68\\U00011c69\\U00011c6a\\U00011c6b\\U00011c6c\\U00012400\\U00012401\\U00012402\\U00012403\\U00012404\\U00012405\\U00012406\\U00012407\\U00012408\\U00012409\\U0001240a\\U0001240b\\U0001240c\\U0001240d\\U0001240e\\U0001240f\\U00012410\\U00012411\\U00012412\\U00012413\\U00012414\\U00012415\\U00012416\\U00012417\\U00012418\\U00012419\\U0001241a\\U0001241b\\U0001241c\\U0001241d\\U0001241e\\U0001241f\\U00012420\\U00012421\\U00012422\\U00012423\\U00012424\\U00012425\\U00012426\\U00012427\\U00012428\\U00012429\\U0001242a\\U0001242b\\U0001242c\\U0001242d\\U0001242e\\U0001242f\\U00012430\\U00012431\\U00012432\\U00012433\\U00012434\\U00012435\\U00012436\\U00012437\\U00012438\\U00012439\\U0001243a\\U0001243b\\U0001243c\\U0001243d\\U0001243e\\U0001243f\\U00012440\\U00012441\\U00012442\\U00012443\\U00012444\\U00012445\\U00012446\\U00012447\\U00012448\\U00012449\\U0001244a\\U0001244b\\U0001244c\\U0001244d\\U0001244e\\U0001244f\\U00012450\\U00012451\\U00012452\\U00012453\\U00012454\\U00012455\\U00012456\\U00012457\\U00012458\\U00012459\\U0001245a\\U0001245b\\U0001245c\\U0001245d\\U0001245e\\U0001245f\\U00012460\\U00012461\\U00012462\\U00012463\\U00012464\\U00012465\\U00012466\\U00012467\\U00012468\\U00012469\\U0001246a\\U0001246b\\U0001246c\\U0001246d\\U0001246e\\U00016b5b\\U00016b5c\\U00016b5d\\U00016b5e\\U00016b5f\\U00016b60\\U00016b61\\U00016e80\\U00016e81\\U00016e82\\U00016e83\\U00016e84\\U00016e85\\U00016e86\\U00016e87\\U00016e88\\U00016e89\\U00016e8a\\U00016e8b\\U00016e8c\\U00016e8d\\U00016e8e\\U00016e8f\\U00016e90\\U00016e91\\U00016e92\\U00016e93\\U00016e94\\U00016e95\\U00016e96\\U0001d2e0\\U0001d2e1\\U0001d2e2\\U0001d2e3\\U0001d2e4\\U0001d2e5\\U0001d2e6\\U0001d2e7\\U0001d2e8\\U0001d2e9\\U0001d2ea\\U0001d2eb\\U0001d2ec\\U0001d2ed\\U0001d2ee\\U0001d2ef\\U0001d2f0\\U0001d2f1\\U0001d2f2\\U0001d2f3\\U0001d360\\U0001d361\\U0001d362\\U0001d363\\U0001d364\\U0001d365\\U0001d366\\U0001d367\\U0001d368\\U0001d369\\U0001d36a\\U0001d36b\\U0001d36c\\U0001d36d\\U0001d36e\\U0001d36f\\U0001d370\\U0001d371\\U0001d372\\U0001d373\\U0001d374\\U0001d375\\U0001d376\\U0001d377\\U0001d378\\U0001e8c7\\U0001e8c8\\U0001e8c9\\U0001e8ca\\U0001e8cb\\U0001e8cc\\U0001e8cd\\U0001e8ce\\U0001e8cf\\U0001ec71\\U0001ec72\\U0001ec73\\U0001ec74\\U0001ec75\\U0001ec76\\U0001ec77\\U0001ec78\\U0001ec79\\U0001ec7a\\U0001ec7b\\U0001ec7c\\U0001ec7d\\U0001ec7e\\U0001ec7f\\U0001ec80\\U0001ec81\\U0001ec82\\U0001ec83\\U0001ec84\\U0001ec85\\U0001ec86\\U0001ec87\\U0001ec88\\U0001ec89\\U0001ec8a\\U0001ec8b\\U0001ec8c\\U0001ec8d\\U0001ec8e\\U0001ec8f\\U0001ec90\\U0001ec91\\U0001ec92\\U0001ec93\\U0001ec94\\U0001ec95\\U0001ec96\\U0001ec97\\U0001ec98\\U0001ec99\\U0001ec9a\\U0001ec9b\\U0001ec9c\\U0001ec9d\\U0001ec9e\\U0001ec9f\\U0001eca0\\U0001eca1\\U0001eca2\\U0001eca3\\U0001eca4\\U0001eca5\\U0001eca6\\U0001eca7\\U0001eca8\\U0001eca9\\U0001ecaa\\U0001ecab\\U0001ecad\\U0001ecae\\U0001ecaf\\U0001ecb1\\U0001ecb2\\U0001ecb3\\U0001ecb4\\U0001f100\\U0001f101\\U0001f102\\U0001f103\\U0001f104\\U0001f105\\U0001f106\\U0001f107\\U0001f108\\U0001f109\\U0001f10a\\U0001f10b\\U0001f10c\\U00020001\\U00020064\\U000200e2\\U00020121\\U0002092a\\U00020983\\U0002098c\\U0002099c\\U00020aea\\U00020afd\\U00020b19\\U00022390\\U00022998\\U00023b1b\\U0002626d\\U0002f890])]",
"tests/test_regex.py::test_regex_splits_correctly[a-123.45e+67b-float_nosign_noexp]",
"tests/test_regex.py::test_regex_splits_correctly[a-123.45e+67b-float_nosign_exp]",
"tests/test_regex.py::test_regex_splits_correctly[abc12.34.56-7def-int_nosign]",
"tests/test_regex.py::test_regex_splits_correctly[a-123.45e+67b-float_sign_exp]",
"tests/test_regex.py::test_regex_chooser[3-([-+]?(?:\\\\d+\\\\.?\\\\d*|\\\\.\\\\d+)(?:[eE][-+]?\\\\d+)?|[\\xb2\\xb3\\xb9\\xbc\\xbd\\xbe\\u09f4\\u09f5\\u09f6\\u09f7\\u09f8\\u09f9\\u0b72\\u0b73\\u0b74\\u0b75\\u0b76\\u0b77\\u0bf0\\u0bf1\\u0bf2\\u0c78\\u0c79\\u0c7a\\u0c7b\\u0c7c\\u0c7d\\u0c7e\\u0d58\\u0d59\\u0d5a\\u0d5b\\u0d5c\\u0d5d\\u0d5e\\u0d70\\u0d71\\u0d72\\u0d73\\u0d74\\u0d75\\u0d76\\u0d77\\u0d78\\u0f2a\\u0f2b\\u0f2c\\u0f2d\\u0f2e\\u0f2f\\u0f30\\u0f31\\u0f32\\u0f33\\u1369\\u136a\\u136b\\u136c\\u136d\\u136e\\u136f\\u1370\\u1371\\u1372\\u1373\\u1374\\u1375\\u1376\\u1377\\u1378\\u1379\\u137a\\u137b\\u137c\\u16ee\\u16ef\\u16f0\\u17f0\\u17f1\\u17f2\\u17f3\\u17f4\\u17f5\\u17f6\\u17f7\\u17f8\\u17f9\\u19da\\u2070\\u2074\\u2075\\u2076\\u2077\\u2078\\u2079\\u2080\\u2081\\u2082\\u2083\\u2084\\u2085\\u2086\\u2087\\u2088\\u2089\\u2150\\u2151\\u2152\\u2153\\u2154\\u2155\\u2156\\u2157\\u2158\\u2159\\u215a\\u215b\\u215c\\u215d\\u215e\\u215f\\u2160\\u2161\\u2162\\u2163\\u2164\\u2165\\u2166\\u2167\\u2168\\u2169\\u216a\\u216b\\u216c\\u216d\\u216e\\u216f\\u2170\\u2171\\u2172\\u2173\\u2174\\u2175\\u2176\\u2177\\u2178\\u2179\\u217a\\u217b\\u217c\\u217d\\u217e\\u217f\\u2180\\u2181\\u2182\\u2185\\u2186\\u2187\\u2188\\u2189\\u2460\\u2461\\u2462\\u2463\\u2464\\u2465\\u2466\\u2467\\u2468\\u2469\\u246a\\u246b\\u246c\\u246d\\u246e\\u246f\\u2470\\u2471\\u2472\\u2473\\u2474\\u2475\\u2476\\u2477\\u2478\\u2479\\u247a\\u247b\\u247c\\u247d\\u247e\\u247f\\u2480\\u2481\\u2482\\u2483\\u2484\\u2485\\u2486\\u2487\\u2488\\u2489\\u248a\\u248b\\u248c\\u248d\\u248e\\u248f\\u2490\\u2491\\u2492\\u2493\\u2494\\u2495\\u2496\\u2497\\u2498\\u2499\\u249a\\u249b\\u24ea\\u24eb\\u24ec\\u24ed\\u24ee\\u24ef\\u24f0\\u24f1\\u24f2\\u24f3\\u24f4\\u24f5\\u24f6\\u24f7\\u24f8\\u24f9\\u24fa\\u24fb\\u24fc\\u24fd\\u24fe\\u24ff\\u2776\\u2777\\u2778\\u2779\\u277a\\u277b\\u277c\\u277d\\u277e\\u277f\\u2780\\u2781\\u2782\\u2783\\u2784\\u2785\\u2786\\u2787\\u2788\\u2789\\u278a\\u278b\\u278c\\u278d\\u278e\\u278f\\u2790\\u2791\\u2792\\u2793\\u2cfd\\u3007\\u3021\\u3022\\u3023\\u3024\\u3025\\u3026\\u3027\\u3028\\u3029\\u3038\\u3039\\u303a\\u3192\\u3193\\u3194\\u3195\\u3220\\u3221\\u3222\\u3223\\u3224\\u3225\\u3226\\u3227\\u3228\\u3229\\u3248\\u3249\\u324a\\u324b\\u324c\\u324d\\u324e\\u324f\\u3251\\u3252\\u3253\\u3254\\u3255\\u3256\\u3257\\u3258\\u3259\\u325a\\u325b\\u325c\\u325d\\u325e\\u325f\\u3280\\u3281\\u3282\\u3283\\u3284\\u3285\\u3286\\u3287\\u3288\\u3289\\u32b1\\u32b2\\u32b3\\u32b4\\u32b5\\u32b6\\u32b7\\u32b8\\u32b9\\u32ba\\u32bb\\u32bc\\u32bd\\u32be\\u32bf\\u3405\\u3483\\u382a\\u3b4d\\u4e00\\u4e03\\u4e07\\u4e09\\u4e5d\\u4e8c\\u4e94\\u4e96\\u4ebf\\u4ec0\\u4edf\\u4ee8\\u4f0d\\u4f70\\u5104\\u5146\\u5169\\u516b\\u516d\\u5341\\u5343\\u5344\\u5345\\u534c\\u53c1\\u53c2\\u53c3\\u53c4\\u56db\\u58f1\\u58f9\\u5e7a\\u5efe\\u5eff\\u5f0c\\u5f0d\\u5f0e\\u5f10\\u62fe\\u634c\\u67d2\\u6f06\\u7396\\u767e\\u8086\\u842c\\u8cae\\u8cb3\\u8d30\\u9621\\u9646\\u964c\\u9678\\u96f6\\ua6e6\\ua6e7\\ua6e8\\ua6e9\\ua6ea\\ua6eb\\ua6ec\\ua6ed\\ua6ee\\ua6ef\\ua830\\ua831\\ua832\\ua833\\ua834\\ua835\\uf96b\\uf973\\uf978\\uf9b2\\uf9d1\\uf9d3\\uf9fd\\U00010107\\U00010108\\U00010109\\U0001010a\\U0001010b\\U0001010c\\U0001010d\\U0001010e\\U0001010f\\U00010110\\U00010111\\U00010112\\U00010113\\U00010114\\U00010115\\U00010116\\U00010117\\U00010118\\U00010119\\U0001011a\\U0001011b\\U0001011c\\U0001011d\\U0001011e\\U0001011f\\U00010120\\U00010121\\U00010122\\U00010123\\U00010124\\U00010125\\U00010126\\U00010127\\U00010128\\U00010129\\U0001012a\\U0001012b\\U0001012c\\U0001012d\\U0001012e\\U0001012f\\U00010130\\U00010131\\U00010132\\U00010133\\U00010140\\U00010141\\U00010142\\U00010143\\U00010144\\U00010145\\U00010146\\U00010147\\U00010148\\U00010149\\U0001014a\\U0001014b\\U0001014c\\U0001014d\\U0001014e\\U0001014f\\U00010150\\U00010151\\U00010152\\U00010153\\U00010154\\U00010155\\U00010156\\U00010157\\U00010158\\U00010159\\U0001015a\\U0001015b\\U0001015c\\U0001015d\\U0001015e\\U0001015f\\U00010160\\U00010161\\U00010162\\U00010163\\U00010164\\U00010165\\U00010166\\U00010167\\U00010168\\U00010169\\U0001016a\\U0001016b\\U0001016c\\U0001016d\\U0001016e\\U0001016f\\U00010170\\U00010171\\U00010172\\U00010173\\U00010174\\U00010175\\U00010176\\U00010177\\U00010178\\U0001018a\\U0001018b\\U000102e1\\U000102e2\\U000102e3\\U000102e4\\U000102e5\\U000102e6\\U000102e7\\U000102e8\\U000102e9\\U000102ea\\U000102eb\\U000102ec\\U000102ed\\U000102ee\\U000102ef\\U000102f0\\U000102f1\\U000102f2\\U000102f3\\U000102f4\\U000102f5\\U000102f6\\U000102f7\\U000102f8\\U000102f9\\U000102fa\\U000102fb\\U00010320\\U00010321\\U00010322\\U00010323\\U00010341\\U0001034a\\U000103d1\\U000103d2\\U000103d3\\U000103d4\\U000103d5\\U00010858\\U00010859\\U0001085a\\U0001085b\\U0001085c\\U0001085d\\U0001085e\\U0001085f\\U00010879\\U0001087a\\U0001087b\\U0001087c\\U0001087d\\U0001087e\\U0001087f\\U000108a7\\U000108a8\\U000108a9\\U000108aa\\U000108ab\\U000108ac\\U000108ad\\U000108ae\\U000108af\\U000108fb\\U000108fc\\U000108fd\\U000108fe\\U000108ff\\U00010916\\U00010917\\U00010918\\U00010919\\U0001091a\\U0001091b\\U000109bc\\U000109bd\\U000109c0\\U000109c1\\U000109c2\\U000109c3\\U000109c4\\U000109c5\\U000109c6\\U000109c7\\U000109c8\\U000109c9\\U000109ca\\U000109cb\\U000109cc\\U000109cd\\U000109ce\\U000109cf\\U000109d2\\U000109d3\\U000109d4\\U000109d5\\U000109d6\\U000109d7\\U000109d8\\U000109d9\\U000109da\\U000109db\\U000109dc\\U000109dd\\U000109de\\U000109df\\U000109e0\\U000109e1\\U000109e2\\U000109e3\\U000109e4\\U000109e5\\U000109e6\\U000109e7\\U000109e8\\U000109e9\\U000109ea\\U000109eb\\U000109ec\\U000109ed\\U000109ee\\U000109ef\\U000109f0\\U000109f1\\U000109f2\\U000109f3\\U000109f4\\U000109f5\\U000109f6\\U000109f7\\U000109f8\\U000109f9\\U000109fa\\U000109fb\\U000109fc\\U000109fd\\U000109fe\\U000109ff\\U00010a40\\U00010a41\\U00010a42\\U00010a43\\U00010a44\\U00010a45\\U00010a46\\U00010a47\\U00010a48\\U00010a7d\\U00010a7e\\U00010a9d\\U00010a9e\\U00010a9f\\U00010aeb\\U00010aec\\U00010aed\\U00010aee\\U00010aef\\U00010b58\\U00010b59\\U00010b5a\\U00010b5b\\U00010b5c\\U00010b5d\\U00010b5e\\U00010b5f\\U00010b78\\U00010b79\\U00010b7a\\U00010b7b\\U00010b7c\\U00010b7d\\U00010b7e\\U00010b7f\\U00010ba9\\U00010baa\\U00010bab\\U00010bac\\U00010bad\\U00010bae\\U00010baf\\U00010cfa\\U00010cfb\\U00010cfc\\U00010cfd\\U00010cfe\\U00010cff\\U00010e60\\U00010e61\\U00010e62\\U00010e63\\U00010e64\\U00010e65\\U00010e66\\U00010e67\\U00010e68\\U00010e69\\U00010e6a\\U00010e6b\\U00010e6c\\U00010e6d\\U00010e6e\\U00010e6f\\U00010e70\\U00010e71\\U00010e72\\U00010e73\\U00010e74\\U00010e75\\U00010e76\\U00010e77\\U00010e78\\U00010e79\\U00010e7a\\U00010e7b\\U00010e7c\\U00010e7d\\U00010e7e\\U00010f1d\\U00010f1e\\U00010f1f\\U00010f20\\U00010f21\\U00010f22\\U00010f23\\U00010f24\\U00010f25\\U00010f26\\U00010f51\\U00010f52\\U00010f53\\U00010f54\\U00011052\\U00011053\\U00011054\\U00011055\\U00011056\\U00011057\\U00011058\\U00011059\\U0001105a\\U0001105b\\U0001105c\\U0001105d\\U0001105e\\U0001105f\\U00011060\\U00011061\\U00011062\\U00011063\\U00011064\\U00011065\\U000111e1\\U000111e2\\U000111e3\\U000111e4\\U000111e5\\U000111e6\\U000111e7\\U000111e8\\U000111e9\\U000111ea\\U000111eb\\U000111ec\\U000111ed\\U000111ee\\U000111ef\\U000111f0\\U000111f1\\U000111f2\\U000111f3\\U000111f4\\U0001173a\\U0001173b\\U000118ea\\U000118eb\\U000118ec\\U000118ed\\U000118ee\\U000118ef\\U000118f0\\U000118f1\\U000118f2\\U00011c5a\\U00011c5b\\U00011c5c\\U00011c5d\\U00011c5e\\U00011c5f\\U00011c60\\U00011c61\\U00011c62\\U00011c63\\U00011c64\\U00011c65\\U00011c66\\U00011c67\\U00011c68\\U00011c69\\U00011c6a\\U00011c6b\\U00011c6c\\U00012400\\U00012401\\U00012402\\U00012403\\U00012404\\U00012405\\U00012406\\U00012407\\U00012408\\U00012409\\U0001240a\\U0001240b\\U0001240c\\U0001240d\\U0001240e\\U0001240f\\U00012410\\U00012411\\U00012412\\U00012413\\U00012414\\U00012415\\U00012416\\U00012417\\U00012418\\U00012419\\U0001241a\\U0001241b\\U0001241c\\U0001241d\\U0001241e\\U0001241f\\U00012420\\U00012421\\U00012422\\U00012423\\U00012424\\U00012425\\U00012426\\U00012427\\U00012428\\U00012429\\U0001242a\\U0001242b\\U0001242c\\U0001242d\\U0001242e\\U0001242f\\U00012430\\U00012431\\U00012432\\U00012433\\U00012434\\U00012435\\U00012436\\U00012437\\U00012438\\U00012439\\U0001243a\\U0001243b\\U0001243c\\U0001243d\\U0001243e\\U0001243f\\U00012440\\U00012441\\U00012442\\U00012443\\U00012444\\U00012445\\U00012446\\U00012447\\U00012448\\U00012449\\U0001244a\\U0001244b\\U0001244c\\U0001244d\\U0001244e\\U0001244f\\U00012450\\U00012451\\U00012452\\U00012453\\U00012454\\U00012455\\U00012456\\U00012457\\U00012458\\U00012459\\U0001245a\\U0001245b\\U0001245c\\U0001245d\\U0001245e\\U0001245f\\U00012460\\U00012461\\U00012462\\U00012463\\U00012464\\U00012465\\U00012466\\U00012467\\U00012468\\U00012469\\U0001246a\\U0001246b\\U0001246c\\U0001246d\\U0001246e\\U00016b5b\\U00016b5c\\U00016b5d\\U00016b5e\\U00016b5f\\U00016b60\\U00016b61\\U00016e80\\U00016e81\\U00016e82\\U00016e83\\U00016e84\\U00016e85\\U00016e86\\U00016e87\\U00016e88\\U00016e89\\U00016e8a\\U00016e8b\\U00016e8c\\U00016e8d\\U00016e8e\\U00016e8f\\U00016e90\\U00016e91\\U00016e92\\U00016e93\\U00016e94\\U00016e95\\U00016e96\\U0001d2e0\\U0001d2e1\\U0001d2e2\\U0001d2e3\\U0001d2e4\\U0001d2e5\\U0001d2e6\\U0001d2e7\\U0001d2e8\\U0001d2e9\\U0001d2ea\\U0001d2eb\\U0001d2ec\\U0001d2ed\\U0001d2ee\\U0001d2ef\\U0001d2f0\\U0001d2f1\\U0001d2f2\\U0001d2f3\\U0001d360\\U0001d361\\U0001d362\\U0001d363\\U0001d364\\U0001d365\\U0001d366\\U0001d367\\U0001d368\\U0001d369\\U0001d36a\\U0001d36b\\U0001d36c\\U0001d36d\\U0001d36e\\U0001d36f\\U0001d370\\U0001d371\\U0001d372\\U0001d373\\U0001d374\\U0001d375\\U0001d376\\U0001d377\\U0001d378\\U0001e8c7\\U0001e8c8\\U0001e8c9\\U0001e8ca\\U0001e8cb\\U0001e8cc\\U0001e8cd\\U0001e8ce\\U0001e8cf\\U0001ec71\\U0001ec72\\U0001ec73\\U0001ec74\\U0001ec75\\U0001ec76\\U0001ec77\\U0001ec78\\U0001ec79\\U0001ec7a\\U0001ec7b\\U0001ec7c\\U0001ec7d\\U0001ec7e\\U0001ec7f\\U0001ec80\\U0001ec81\\U0001ec82\\U0001ec83\\U0001ec84\\U0001ec85\\U0001ec86\\U0001ec87\\U0001ec88\\U0001ec89\\U0001ec8a\\U0001ec8b\\U0001ec8c\\U0001ec8d\\U0001ec8e\\U0001ec8f\\U0001ec90\\U0001ec91\\U0001ec92\\U0001ec93\\U0001ec94\\U0001ec95\\U0001ec96\\U0001ec97\\U0001ec98\\U0001ec99\\U0001ec9a\\U0001ec9b\\U0001ec9c\\U0001ec9d\\U0001ec9e\\U0001ec9f\\U0001eca0\\U0001eca1\\U0001eca2\\U0001eca3\\U0001eca4\\U0001eca5\\U0001eca6\\U0001eca7\\U0001eca8\\U0001eca9\\U0001ecaa\\U0001ecab\\U0001ecad\\U0001ecae\\U0001ecaf\\U0001ecb1\\U0001ecb2\\U0001ecb3\\U0001ecb4\\U0001f100\\U0001f101\\U0001f102\\U0001f103\\U0001f104\\U0001f105\\U0001f106\\U0001f107\\U0001f108\\U0001f109\\U0001f10a\\U0001f10b\\U0001f10c\\U00020001\\U00020064\\U000200e2\\U00020121\\U0002092a\\U00020983\\U0002098c\\U0002099c\\U00020aea\\U00020afd\\U00020b19\\U00022390\\U00022998\\U00023b1b\\U0002626d\\U0002f890])]",
"tests/test_regex.py::test_regex_splits_correctly[eleven\\u06f1\\u06f1eleven11eleven\\u09e7\\u09e7-float_sign_noexp]",
"tests/test_regex.py::test_regex_splits_correctly[eleven\\u06f1\\u06f1eleven11eleven\\u09e7\\u09e7-int_sign]",
"tests/test_regex.py::test_regex_splits_correctly[hello-float_sign_noexp]",
"tests/test_regex.py::test_regex_splits_correctly[-123.45e+67-float_sign_noexp]",
"tests/test_regex.py::test_regex_splits_correctly[abc12.34.56-7def-int_sign]",
"tests/test_regex.py::test_regex_splits_correctly[hello-int_nosign]",
"tests/test_regex.py::test_regex_splits_correctly[a-123.45e+67b-float_sign_noexp]",
"tests/test_regex.py::test_regex_splits_correctly[a1b2c3d4e5e6-int_sign]",
"tests/test_regex.py::test_regex_chooser[1-((?:\\\\d+\\\\.?\\\\d*|\\\\.\\\\d+)(?:[eE][-+]?\\\\d+)?|[\\xb2\\xb3\\xb9\\xbc\\xbd\\xbe\\u09f4\\u09f5\\u09f6\\u09f7\\u09f8\\u09f9\\u0b72\\u0b73\\u0b74\\u0b75\\u0b76\\u0b77\\u0bf0\\u0bf1\\u0bf2\\u0c78\\u0c79\\u0c7a\\u0c7b\\u0c7c\\u0c7d\\u0c7e\\u0d58\\u0d59\\u0d5a\\u0d5b\\u0d5c\\u0d5d\\u0d5e\\u0d70\\u0d71\\u0d72\\u0d73\\u0d74\\u0d75\\u0d76\\u0d77\\u0d78\\u0f2a\\u0f2b\\u0f2c\\u0f2d\\u0f2e\\u0f2f\\u0f30\\u0f31\\u0f32\\u0f33\\u1369\\u136a\\u136b\\u136c\\u136d\\u136e\\u136f\\u1370\\u1371\\u1372\\u1373\\u1374\\u1375\\u1376\\u1377\\u1378\\u1379\\u137a\\u137b\\u137c\\u16ee\\u16ef\\u16f0\\u17f0\\u17f1\\u17f2\\u17f3\\u17f4\\u17f5\\u17f6\\u17f7\\u17f8\\u17f9\\u19da\\u2070\\u2074\\u2075\\u2076\\u2077\\u2078\\u2079\\u2080\\u2081\\u2082\\u2083\\u2084\\u2085\\u2086\\u2087\\u2088\\u2089\\u2150\\u2151\\u2152\\u2153\\u2154\\u2155\\u2156\\u2157\\u2158\\u2159\\u215a\\u215b\\u215c\\u215d\\u215e\\u215f\\u2160\\u2161\\u2162\\u2163\\u2164\\u2165\\u2166\\u2167\\u2168\\u2169\\u216a\\u216b\\u216c\\u216d\\u216e\\u216f\\u2170\\u2171\\u2172\\u2173\\u2174\\u2175\\u2176\\u2177\\u2178\\u2179\\u217a\\u217b\\u217c\\u217d\\u217e\\u217f\\u2180\\u2181\\u2182\\u2185\\u2186\\u2187\\u2188\\u2189\\u2460\\u2461\\u2462\\u2463\\u2464\\u2465\\u2466\\u2467\\u2468\\u2469\\u246a\\u246b\\u246c\\u246d\\u246e\\u246f\\u2470\\u2471\\u2472\\u2473\\u2474\\u2475\\u2476\\u2477\\u2478\\u2479\\u247a\\u247b\\u247c\\u247d\\u247e\\u247f\\u2480\\u2481\\u2482\\u2483\\u2484\\u2485\\u2486\\u2487\\u2488\\u2489\\u248a\\u248b\\u248c\\u248d\\u248e\\u248f\\u2490\\u2491\\u2492\\u2493\\u2494\\u2495\\u2496\\u2497\\u2498\\u2499\\u249a\\u249b\\u24ea\\u24eb\\u24ec\\u24ed\\u24ee\\u24ef\\u24f0\\u24f1\\u24f2\\u24f3\\u24f4\\u24f5\\u24f6\\u24f7\\u24f8\\u24f9\\u24fa\\u24fb\\u24fc\\u24fd\\u24fe\\u24ff\\u2776\\u2777\\u2778\\u2779\\u277a\\u277b\\u277c\\u277d\\u277e\\u277f\\u2780\\u2781\\u2782\\u2783\\u2784\\u2785\\u2786\\u2787\\u2788\\u2789\\u278a\\u278b\\u278c\\u278d\\u278e\\u278f\\u2790\\u2791\\u2792\\u2793\\u2cfd\\u3007\\u3021\\u3022\\u3023\\u3024\\u3025\\u3026\\u3027\\u3028\\u3029\\u3038\\u3039\\u303a\\u3192\\u3193\\u3194\\u3195\\u3220\\u3221\\u3222\\u3223\\u3224\\u3225\\u3226\\u3227\\u3228\\u3229\\u3248\\u3249\\u324a\\u324b\\u324c\\u324d\\u324e\\u324f\\u3251\\u3252\\u3253\\u3254\\u3255\\u3256\\u3257\\u3258\\u3259\\u325a\\u325b\\u325c\\u325d\\u325e\\u325f\\u3280\\u3281\\u3282\\u3283\\u3284\\u3285\\u3286\\u3287\\u3288\\u3289\\u32b1\\u32b2\\u32b3\\u32b4\\u32b5\\u32b6\\u32b7\\u32b8\\u32b9\\u32ba\\u32bb\\u32bc\\u32bd\\u32be\\u32bf\\u3405\\u3483\\u382a\\u3b4d\\u4e00\\u4e03\\u4e07\\u4e09\\u4e5d\\u4e8c\\u4e94\\u4e96\\u4ebf\\u4ec0\\u4edf\\u4ee8\\u4f0d\\u4f70\\u5104\\u5146\\u5169\\u516b\\u516d\\u5341\\u5343\\u5344\\u5345\\u534c\\u53c1\\u53c2\\u53c3\\u53c4\\u56db\\u58f1\\u58f9\\u5e7a\\u5efe\\u5eff\\u5f0c\\u5f0d\\u5f0e\\u5f10\\u62fe\\u634c\\u67d2\\u6f06\\u7396\\u767e\\u8086\\u842c\\u8cae\\u8cb3\\u8d30\\u9621\\u9646\\u964c\\u9678\\u96f6\\ua6e6\\ua6e7\\ua6e8\\ua6e9\\ua6ea\\ua6eb\\ua6ec\\ua6ed\\ua6ee\\ua6ef\\ua830\\ua831\\ua832\\ua833\\ua834\\ua835\\uf96b\\uf973\\uf978\\uf9b2\\uf9d1\\uf9d3\\uf9fd\\U00010107\\U00010108\\U00010109\\U0001010a\\U0001010b\\U0001010c\\U0001010d\\U0001010e\\U0001010f\\U00010110\\U00010111\\U00010112\\U00010113\\U00010114\\U00010115\\U00010116\\U00010117\\U00010118\\U00010119\\U0001011a\\U0001011b\\U0001011c\\U0001011d\\U0001011e\\U0001011f\\U00010120\\U00010121\\U00010122\\U00010123\\U00010124\\U00010125\\U00010126\\U00010127\\U00010128\\U00010129\\U0001012a\\U0001012b\\U0001012c\\U0001012d\\U0001012e\\U0001012f\\U00010130\\U00010131\\U00010132\\U00010133\\U00010140\\U00010141\\U00010142\\U00010143\\U00010144\\U00010145\\U00010146\\U00010147\\U00010148\\U00010149\\U0001014a\\U0001014b\\U0001014c\\U0001014d\\U0001014e\\U0001014f\\U00010150\\U00010151\\U00010152\\U00010153\\U00010154\\U00010155\\U00010156\\U00010157\\U00010158\\U00010159\\U0001015a\\U0001015b\\U0001015c\\U0001015d\\U0001015e\\U0001015f\\U00010160\\U00010161\\U00010162\\U00010163\\U00010164\\U00010165\\U00010166\\U00010167\\U00010168\\U00010169\\U0001016a\\U0001016b\\U0001016c\\U0001016d\\U0001016e\\U0001016f\\U00010170\\U00010171\\U00010172\\U00010173\\U00010174\\U00010175\\U00010176\\U00010177\\U00010178\\U0001018a\\U0001018b\\U000102e1\\U000102e2\\U000102e3\\U000102e4\\U000102e5\\U000102e6\\U000102e7\\U000102e8\\U000102e9\\U000102ea\\U000102eb\\U000102ec\\U000102ed\\U000102ee\\U000102ef\\U000102f0\\U000102f1\\U000102f2\\U000102f3\\U000102f4\\U000102f5\\U000102f6\\U000102f7\\U000102f8\\U000102f9\\U000102fa\\U000102fb\\U00010320\\U00010321\\U00010322\\U00010323\\U00010341\\U0001034a\\U000103d1\\U000103d2\\U000103d3\\U000103d4\\U000103d5\\U00010858\\U00010859\\U0001085a\\U0001085b\\U0001085c\\U0001085d\\U0001085e\\U0001085f\\U00010879\\U0001087a\\U0001087b\\U0001087c\\U0001087d\\U0001087e\\U0001087f\\U000108a7\\U000108a8\\U000108a9\\U000108aa\\U000108ab\\U000108ac\\U000108ad\\U000108ae\\U000108af\\U000108fb\\U000108fc\\U000108fd\\U000108fe\\U000108ff\\U00010916\\U00010917\\U00010918\\U00010919\\U0001091a\\U0001091b\\U000109bc\\U000109bd\\U000109c0\\U000109c1\\U000109c2\\U000109c3\\U000109c4\\U000109c5\\U000109c6\\U000109c7\\U000109c8\\U000109c9\\U000109ca\\U000109cb\\U000109cc\\U000109cd\\U000109ce\\U000109cf\\U000109d2\\U000109d3\\U000109d4\\U000109d5\\U000109d6\\U000109d7\\U000109d8\\U000109d9\\U000109da\\U000109db\\U000109dc\\U000109dd\\U000109de\\U000109df\\U000109e0\\U000109e1\\U000109e2\\U000109e3\\U000109e4\\U000109e5\\U000109e6\\U000109e7\\U000109e8\\U000109e9\\U000109ea\\U000109eb\\U000109ec\\U000109ed\\U000109ee\\U000109ef\\U000109f0\\U000109f1\\U000109f2\\U000109f3\\U000109f4\\U000109f5\\U000109f6\\U000109f7\\U000109f8\\U000109f9\\U000109fa\\U000109fb\\U000109fc\\U000109fd\\U000109fe\\U000109ff\\U00010a40\\U00010a41\\U00010a42\\U00010a43\\U00010a44\\U00010a45\\U00010a46\\U00010a47\\U00010a48\\U00010a7d\\U00010a7e\\U00010a9d\\U00010a9e\\U00010a9f\\U00010aeb\\U00010aec\\U00010aed\\U00010aee\\U00010aef\\U00010b58\\U00010b59\\U00010b5a\\U00010b5b\\U00010b5c\\U00010b5d\\U00010b5e\\U00010b5f\\U00010b78\\U00010b79\\U00010b7a\\U00010b7b\\U00010b7c\\U00010b7d\\U00010b7e\\U00010b7f\\U00010ba9\\U00010baa\\U00010bab\\U00010bac\\U00010bad\\U00010bae\\U00010baf\\U00010cfa\\U00010cfb\\U00010cfc\\U00010cfd\\U00010cfe\\U00010cff\\U00010e60\\U00010e61\\U00010e62\\U00010e63\\U00010e64\\U00010e65\\U00010e66\\U00010e67\\U00010e68\\U00010e69\\U00010e6a\\U00010e6b\\U00010e6c\\U00010e6d\\U00010e6e\\U00010e6f\\U00010e70\\U00010e71\\U00010e72\\U00010e73\\U00010e74\\U00010e75\\U00010e76\\U00010e77\\U00010e78\\U00010e79\\U00010e7a\\U00010e7b\\U00010e7c\\U00010e7d\\U00010e7e\\U00010f1d\\U00010f1e\\U00010f1f\\U00010f20\\U00010f21\\U00010f22\\U00010f23\\U00010f24\\U00010f25\\U00010f26\\U00010f51\\U00010f52\\U00010f53\\U00010f54\\U00011052\\U00011053\\U00011054\\U00011055\\U00011056\\U00011057\\U00011058\\U00011059\\U0001105a\\U0001105b\\U0001105c\\U0001105d\\U0001105e\\U0001105f\\U00011060\\U00011061\\U00011062\\U00011063\\U00011064\\U00011065\\U000111e1\\U000111e2\\U000111e3\\U000111e4\\U000111e5\\U000111e6\\U000111e7\\U000111e8\\U000111e9\\U000111ea\\U000111eb\\U000111ec\\U000111ed\\U000111ee\\U000111ef\\U000111f0\\U000111f1\\U000111f2\\U000111f3\\U000111f4\\U0001173a\\U0001173b\\U000118ea\\U000118eb\\U000118ec\\U000118ed\\U000118ee\\U000118ef\\U000118f0\\U000118f1\\U000118f2\\U00011c5a\\U00011c5b\\U00011c5c\\U00011c5d\\U00011c5e\\U00011c5f\\U00011c60\\U00011c61\\U00011c62\\U00011c63\\U00011c64\\U00011c65\\U00011c66\\U00011c67\\U00011c68\\U00011c69\\U00011c6a\\U00011c6b\\U00011c6c\\U00012400\\U00012401\\U00012402\\U00012403\\U00012404\\U00012405\\U00012406\\U00012407\\U00012408\\U00012409\\U0001240a\\U0001240b\\U0001240c\\U0001240d\\U0001240e\\U0001240f\\U00012410\\U00012411\\U00012412\\U00012413\\U00012414\\U00012415\\U00012416\\U00012417\\U00012418\\U00012419\\U0001241a\\U0001241b\\U0001241c\\U0001241d\\U0001241e\\U0001241f\\U00012420\\U00012421\\U00012422\\U00012423\\U00012424\\U00012425\\U00012426\\U00012427\\U00012428\\U00012429\\U0001242a\\U0001242b\\U0001242c\\U0001242d\\U0001242e\\U0001242f\\U00012430\\U00012431\\U00012432\\U00012433\\U00012434\\U00012435\\U00012436\\U00012437\\U00012438\\U00012439\\U0001243a\\U0001243b\\U0001243c\\U0001243d\\U0001243e\\U0001243f\\U00012440\\U00012441\\U00012442\\U00012443\\U00012444\\U00012445\\U00012446\\U00012447\\U00012448\\U00012449\\U0001244a\\U0001244b\\U0001244c\\U0001244d\\U0001244e\\U0001244f\\U00012450\\U00012451\\U00012452\\U00012453\\U00012454\\U00012455\\U00012456\\U00012457\\U00012458\\U00012459\\U0001245a\\U0001245b\\U0001245c\\U0001245d\\U0001245e\\U0001245f\\U00012460\\U00012461\\U00012462\\U00012463\\U00012464\\U00012465\\U00012466\\U00012467\\U00012468\\U00012469\\U0001246a\\U0001246b\\U0001246c\\U0001246d\\U0001246e\\U00016b5b\\U00016b5c\\U00016b5d\\U00016b5e\\U00016b5f\\U00016b60\\U00016b61\\U00016e80\\U00016e81\\U00016e82\\U00016e83\\U00016e84\\U00016e85\\U00016e86\\U00016e87\\U00016e88\\U00016e89\\U00016e8a\\U00016e8b\\U00016e8c\\U00016e8d\\U00016e8e\\U00016e8f\\U00016e90\\U00016e91\\U00016e92\\U00016e93\\U00016e94\\U00016e95\\U00016e96\\U0001d2e0\\U0001d2e1\\U0001d2e2\\U0001d2e3\\U0001d2e4\\U0001d2e5\\U0001d2e6\\U0001d2e7\\U0001d2e8\\U0001d2e9\\U0001d2ea\\U0001d2eb\\U0001d2ec\\U0001d2ed\\U0001d2ee\\U0001d2ef\\U0001d2f0\\U0001d2f1\\U0001d2f2\\U0001d2f3\\U0001d360\\U0001d361\\U0001d362\\U0001d363\\U0001d364\\U0001d365\\U0001d366\\U0001d367\\U0001d368\\U0001d369\\U0001d36a\\U0001d36b\\U0001d36c\\U0001d36d\\U0001d36e\\U0001d36f\\U0001d370\\U0001d371\\U0001d372\\U0001d373\\U0001d374\\U0001d375\\U0001d376\\U0001d377\\U0001d378\\U0001e8c7\\U0001e8c8\\U0001e8c9\\U0001e8ca\\U0001e8cb\\U0001e8cc\\U0001e8cd\\U0001e8ce\\U0001e8cf\\U0001ec71\\U0001ec72\\U0001ec73\\U0001ec74\\U0001ec75\\U0001ec76\\U0001ec77\\U0001ec78\\U0001ec79\\U0001ec7a\\U0001ec7b\\U0001ec7c\\U0001ec7d\\U0001ec7e\\U0001ec7f\\U0001ec80\\U0001ec81\\U0001ec82\\U0001ec83\\U0001ec84\\U0001ec85\\U0001ec86\\U0001ec87\\U0001ec88\\U0001ec89\\U0001ec8a\\U0001ec8b\\U0001ec8c\\U0001ec8d\\U0001ec8e\\U0001ec8f\\U0001ec90\\U0001ec91\\U0001ec92\\U0001ec93\\U0001ec94\\U0001ec95\\U0001ec96\\U0001ec97\\U0001ec98\\U0001ec99\\U0001ec9a\\U0001ec9b\\U0001ec9c\\U0001ec9d\\U0001ec9e\\U0001ec9f\\U0001eca0\\U0001eca1\\U0001eca2\\U0001eca3\\U0001eca4\\U0001eca5\\U0001eca6\\U0001eca7\\U0001eca8\\U0001eca9\\U0001ecaa\\U0001ecab\\U0001ecad\\U0001ecae\\U0001ecaf\\U0001ecb1\\U0001ecb2\\U0001ecb3\\U0001ecb4\\U0001f100\\U0001f101\\U0001f102\\U0001f103\\U0001f104\\U0001f105\\U0001f106\\U0001f107\\U0001f108\\U0001f109\\U0001f10a\\U0001f10b\\U0001f10c\\U00020001\\U00020064\\U000200e2\\U00020121\\U0002092a\\U00020983\\U0002098c\\U0002099c\\U00020aea\\U00020afd\\U00020b19\\U00022390\\U00022998\\U00023b1b\\U0002626d\\U0002f890])0]",
"tests/test_regex.py::test_regex_splits_correctly[-123.45e+67-int_sign]",
"tests/test_regex.py::test_regex_splits_correctly[12\\u2460\\u2461\\u2160\\u2161\\u2153-int_nosign]",
"tests/test_regex.py::test_regex_chooser[0-(\\\\d+|[\\xb2\\xb3\\xb9\\u1369\\u136a\\u136b\\u136c\\u136d\\u136e\\u136f\\u1370\\u1371\\u19da\\u2070\\u2074\\u2075\\u2076\\u2077\\u2078\\u2079\\u2080\\u2081\\u2082\\u2083\\u2084\\u2085\\u2086\\u2087\\u2088\\u2089\\u2460\\u2461\\u2462\\u2463\\u2464\\u2465\\u2466\\u2467\\u2468\\u2474\\u2475\\u2476\\u2477\\u2478\\u2479\\u247a\\u247b\\u247c\\u2488\\u2489\\u248a\\u248b\\u248c\\u248d\\u248e\\u248f\\u2490\\u24ea\\u24f5\\u24f6\\u24f7\\u24f8\\u24f9\\u24fa\\u24fb\\u24fc\\u24fd\\u24ff\\u2776\\u2777\\u2778\\u2779\\u277a\\u277b\\u277c\\u277d\\u277e\\u2780\\u2781\\u2782\\u2783\\u2784\\u2785\\u2786\\u2787\\u2788\\u278a\\u278b\\u278c\\u278d\\u278e\\u278f\\u2790\\u2791\\u2792\\U00010a40\\U00010a41\\U00010a42\\U00010a43\\U00010e60\\U00010e61\\U00010e62\\U00010e63\\U00010e64\\U00010e65\\U00010e66\\U00010e67\\U00010e68\\U00011052\\U00011053\\U00011054\\U00011055\\U00011056\\U00011057\\U00011058\\U00011059\\U0001105a\\U0001f100\\U0001f101\\U0001f102\\U0001f103\\U0001f104\\U0001f105\\U0001f106\\U0001f107\\U0001f108\\U0001f109\\U0001f10a])1]",
"tests/test_regex.py::test_regex_chooser[0-(\\\\d+|[\\xb2\\xb3\\xb9\\u1369\\u136a\\u136b\\u136c\\u136d\\u136e\\u136f\\u1370\\u1371\\u19da\\u2070\\u2074\\u2075\\u2076\\u2077\\u2078\\u2079\\u2080\\u2081\\u2082\\u2083\\u2084\\u2085\\u2086\\u2087\\u2088\\u2089\\u2460\\u2461\\u2462\\u2463\\u2464\\u2465\\u2466\\u2467\\u2468\\u2474\\u2475\\u2476\\u2477\\u2478\\u2479\\u247a\\u247b\\u247c\\u2488\\u2489\\u248a\\u248b\\u248c\\u248d\\u248e\\u248f\\u2490\\u24ea\\u24f5\\u24f6\\u24f7\\u24f8\\u24f9\\u24fa\\u24fb\\u24fc\\u24fd\\u24ff\\u2776\\u2777\\u2778\\u2779\\u277a\\u277b\\u277c\\u277d\\u277e\\u2780\\u2781\\u2782\\u2783\\u2784\\u2785\\u2786\\u2787\\u2788\\u278a\\u278b\\u278c\\u278d\\u278e\\u278f\\u2790\\u2791\\u2792\\U00010a40\\U00010a41\\U00010a42\\U00010a43\\U00010e60\\U00010e61\\U00010e62\\U00010e63\\U00010e64\\U00010e65\\U00010e66\\U00010e67\\U00010e68\\U00011052\\U00011053\\U00011054\\U00011055\\U00011056\\U00011057\\U00011058\\U00011059\\U0001105a\\U0001f100\\U0001f101\\U0001f102\\U0001f103\\U0001f104\\U0001f105\\U0001f106\\U0001f107\\U0001f108\\U0001f109\\U0001f10a])0]",
"tests/test_regex.py::test_regex_splits_correctly[a1b2c3d4e5e6-float_sign_exp]",
"tests/test_regex.py::test_regex_splits_correctly[12\\u2460\\u2461\\u2160\\u2161\\u2153-int_sign]",
"tests/test_regex.py::test_regex_splits_correctly[a1b2c3d4e5e6-int_nosign]",
"tests/test_regex.py::test_regex_splits_correctly[hello-int_sign]",
"tests/test_regex.py::test_regex_splits_correctly[-123.45e+67-float_sign_exp]",
"tests/test_regex.py::test_regex_splits_correctly[a1b2c3d4e5e6-float_nosign_exp]",
"tests/test_regex.py::test_regex_splits_correctly[-123.45e+67-float_nosign_noexp]",
"tests/test_regex.py::test_regex_splits_correctly[eleven\\u06f1\\u06f1eleven11eleven\\u09e7\\u09e7-float_nosign_noexp]",
"tests/test_regex.py::test_regex_splits_correctly[abc12.34.56-7def-float_sign_exp]",
"tests/test_regex.py::test_regex_chooser[1-((?:\\\\d+\\\\.?\\\\d*|\\\\.\\\\d+)(?:[eE][-+]?\\\\d+)?|[\\xb2\\xb3\\xb9\\xbc\\xbd\\xbe\\u09f4\\u09f5\\u09f6\\u09f7\\u09f8\\u09f9\\u0b72\\u0b73\\u0b74\\u0b75\\u0b76\\u0b77\\u0bf0\\u0bf1\\u0bf2\\u0c78\\u0c79\\u0c7a\\u0c7b\\u0c7c\\u0c7d\\u0c7e\\u0d58\\u0d59\\u0d5a\\u0d5b\\u0d5c\\u0d5d\\u0d5e\\u0d70\\u0d71\\u0d72\\u0d73\\u0d74\\u0d75\\u0d76\\u0d77\\u0d78\\u0f2a\\u0f2b\\u0f2c\\u0f2d\\u0f2e\\u0f2f\\u0f30\\u0f31\\u0f32\\u0f33\\u1369\\u136a\\u136b\\u136c\\u136d\\u136e\\u136f\\u1370\\u1371\\u1372\\u1373\\u1374\\u1375\\u1376\\u1377\\u1378\\u1379\\u137a\\u137b\\u137c\\u16ee\\u16ef\\u16f0\\u17f0\\u17f1\\u17f2\\u17f3\\u17f4\\u17f5\\u17f6\\u17f7\\u17f8\\u17f9\\u19da\\u2070\\u2074\\u2075\\u2076\\u2077\\u2078\\u2079\\u2080\\u2081\\u2082\\u2083\\u2084\\u2085\\u2086\\u2087\\u2088\\u2089\\u2150\\u2151\\u2152\\u2153\\u2154\\u2155\\u2156\\u2157\\u2158\\u2159\\u215a\\u215b\\u215c\\u215d\\u215e\\u215f\\u2160\\u2161\\u2162\\u2163\\u2164\\u2165\\u2166\\u2167\\u2168\\u2169\\u216a\\u216b\\u216c\\u216d\\u216e\\u216f\\u2170\\u2171\\u2172\\u2173\\u2174\\u2175\\u2176\\u2177\\u2178\\u2179\\u217a\\u217b\\u217c\\u217d\\u217e\\u217f\\u2180\\u2181\\u2182\\u2185\\u2186\\u2187\\u2188\\u2189\\u2460\\u2461\\u2462\\u2463\\u2464\\u2465\\u2466\\u2467\\u2468\\u2469\\u246a\\u246b\\u246c\\u246d\\u246e\\u246f\\u2470\\u2471\\u2472\\u2473\\u2474\\u2475\\u2476\\u2477\\u2478\\u2479\\u247a\\u247b\\u247c\\u247d\\u247e\\u247f\\u2480\\u2481\\u2482\\u2483\\u2484\\u2485\\u2486\\u2487\\u2488\\u2489\\u248a\\u248b\\u248c\\u248d\\u248e\\u248f\\u2490\\u2491\\u2492\\u2493\\u2494\\u2495\\u2496\\u2497\\u2498\\u2499\\u249a\\u249b\\u24ea\\u24eb\\u24ec\\u24ed\\u24ee\\u24ef\\u24f0\\u24f1\\u24f2\\u24f3\\u24f4\\u24f5\\u24f6\\u24f7\\u24f8\\u24f9\\u24fa\\u24fb\\u24fc\\u24fd\\u24fe\\u24ff\\u2776\\u2777\\u2778\\u2779\\u277a\\u277b\\u277c\\u277d\\u277e\\u277f\\u2780\\u2781\\u2782\\u2783\\u2784\\u2785\\u2786\\u2787\\u2788\\u2789\\u278a\\u278b\\u278c\\u278d\\u278e\\u278f\\u2790\\u2791\\u2792\\u2793\\u2cfd\\u3007\\u3021\\u3022\\u3023\\u3024\\u3025\\u3026\\u3027\\u3028\\u3029\\u3038\\u3039\\u303a\\u3192\\u3193\\u3194\\u3195\\u3220\\u3221\\u3222\\u3223\\u3224\\u3225\\u3226\\u3227\\u3228\\u3229\\u3248\\u3249\\u324a\\u324b\\u324c\\u324d\\u324e\\u324f\\u3251\\u3252\\u3253\\u3254\\u3255\\u3256\\u3257\\u3258\\u3259\\u325a\\u325b\\u325c\\u325d\\u325e\\u325f\\u3280\\u3281\\u3282\\u3283\\u3284\\u3285\\u3286\\u3287\\u3288\\u3289\\u32b1\\u32b2\\u32b3\\u32b4\\u32b5\\u32b6\\u32b7\\u32b8\\u32b9\\u32ba\\u32bb\\u32bc\\u32bd\\u32be\\u32bf\\u3405\\u3483\\u382a\\u3b4d\\u4e00\\u4e03\\u4e07\\u4e09\\u4e5d\\u4e8c\\u4e94\\u4e96\\u4ebf\\u4ec0\\u4edf\\u4ee8\\u4f0d\\u4f70\\u5104\\u5146\\u5169\\u516b\\u516d\\u5341\\u5343\\u5344\\u5345\\u534c\\u53c1\\u53c2\\u53c3\\u53c4\\u56db\\u58f1\\u58f9\\u5e7a\\u5efe\\u5eff\\u5f0c\\u5f0d\\u5f0e\\u5f10\\u62fe\\u634c\\u67d2\\u6f06\\u7396\\u767e\\u8086\\u842c\\u8cae\\u8cb3\\u8d30\\u9621\\u9646\\u964c\\u9678\\u96f6\\ua6e6\\ua6e7\\ua6e8\\ua6e9\\ua6ea\\ua6eb\\ua6ec\\ua6ed\\ua6ee\\ua6ef\\ua830\\ua831\\ua832\\ua833\\ua834\\ua835\\uf96b\\uf973\\uf978\\uf9b2\\uf9d1\\uf9d3\\uf9fd\\U00010107\\U00010108\\U00010109\\U0001010a\\U0001010b\\U0001010c\\U0001010d\\U0001010e\\U0001010f\\U00010110\\U00010111\\U00010112\\U00010113\\U00010114\\U00010115\\U00010116\\U00010117\\U00010118\\U00010119\\U0001011a\\U0001011b\\U0001011c\\U0001011d\\U0001011e\\U0001011f\\U00010120\\U00010121\\U00010122\\U00010123\\U00010124\\U00010125\\U00010126\\U00010127\\U00010128\\U00010129\\U0001012a\\U0001012b\\U0001012c\\U0001012d\\U0001012e\\U0001012f\\U00010130\\U00010131\\U00010132\\U00010133\\U00010140\\U00010141\\U00010142\\U00010143\\U00010144\\U00010145\\U00010146\\U00010147\\U00010148\\U00010149\\U0001014a\\U0001014b\\U0001014c\\U0001014d\\U0001014e\\U0001014f\\U00010150\\U00010151\\U00010152\\U00010153\\U00010154\\U00010155\\U00010156\\U00010157\\U00010158\\U00010159\\U0001015a\\U0001015b\\U0001015c\\U0001015d\\U0001015e\\U0001015f\\U00010160\\U00010161\\U00010162\\U00010163\\U00010164\\U00010165\\U00010166\\U00010167\\U00010168\\U00010169\\U0001016a\\U0001016b\\U0001016c\\U0001016d\\U0001016e\\U0001016f\\U00010170\\U00010171\\U00010172\\U00010173\\U00010174\\U00010175\\U00010176\\U00010177\\U00010178\\U0001018a\\U0001018b\\U000102e1\\U000102e2\\U000102e3\\U000102e4\\U000102e5\\U000102e6\\U000102e7\\U000102e8\\U000102e9\\U000102ea\\U000102eb\\U000102ec\\U000102ed\\U000102ee\\U000102ef\\U000102f0\\U000102f1\\U000102f2\\U000102f3\\U000102f4\\U000102f5\\U000102f6\\U000102f7\\U000102f8\\U000102f9\\U000102fa\\U000102fb\\U00010320\\U00010321\\U00010322\\U00010323\\U00010341\\U0001034a\\U000103d1\\U000103d2\\U000103d3\\U000103d4\\U000103d5\\U00010858\\U00010859\\U0001085a\\U0001085b\\U0001085c\\U0001085d\\U0001085e\\U0001085f\\U00010879\\U0001087a\\U0001087b\\U0001087c\\U0001087d\\U0001087e\\U0001087f\\U000108a7\\U000108a8\\U000108a9\\U000108aa\\U000108ab\\U000108ac\\U000108ad\\U000108ae\\U000108af\\U000108fb\\U000108fc\\U000108fd\\U000108fe\\U000108ff\\U00010916\\U00010917\\U00010918\\U00010919\\U0001091a\\U0001091b\\U000109bc\\U000109bd\\U000109c0\\U000109c1\\U000109c2\\U000109c3\\U000109c4\\U000109c5\\U000109c6\\U000109c7\\U000109c8\\U000109c9\\U000109ca\\U000109cb\\U000109cc\\U000109cd\\U000109ce\\U000109cf\\U000109d2\\U000109d3\\U000109d4\\U000109d5\\U000109d6\\U000109d7\\U000109d8\\U000109d9\\U000109da\\U000109db\\U000109dc\\U000109dd\\U000109de\\U000109df\\U000109e0\\U000109e1\\U000109e2\\U000109e3\\U000109e4\\U000109e5\\U000109e6\\U000109e7\\U000109e8\\U000109e9\\U000109ea\\U000109eb\\U000109ec\\U000109ed\\U000109ee\\U000109ef\\U000109f0\\U000109f1\\U000109f2\\U000109f3\\U000109f4\\U000109f5\\U000109f6\\U000109f7\\U000109f8\\U000109f9\\U000109fa\\U000109fb\\U000109fc\\U000109fd\\U000109fe\\U000109ff\\U00010a40\\U00010a41\\U00010a42\\U00010a43\\U00010a44\\U00010a45\\U00010a46\\U00010a47\\U00010a48\\U00010a7d\\U00010a7e\\U00010a9d\\U00010a9e\\U00010a9f\\U00010aeb\\U00010aec\\U00010aed\\U00010aee\\U00010aef\\U00010b58\\U00010b59\\U00010b5a\\U00010b5b\\U00010b5c\\U00010b5d\\U00010b5e\\U00010b5f\\U00010b78\\U00010b79\\U00010b7a\\U00010b7b\\U00010b7c\\U00010b7d\\U00010b7e\\U00010b7f\\U00010ba9\\U00010baa\\U00010bab\\U00010bac\\U00010bad\\U00010bae\\U00010baf\\U00010cfa\\U00010cfb\\U00010cfc\\U00010cfd\\U00010cfe\\U00010cff\\U00010e60\\U00010e61\\U00010e62\\U00010e63\\U00010e64\\U00010e65\\U00010e66\\U00010e67\\U00010e68\\U00010e69\\U00010e6a\\U00010e6b\\U00010e6c\\U00010e6d\\U00010e6e\\U00010e6f\\U00010e70\\U00010e71\\U00010e72\\U00010e73\\U00010e74\\U00010e75\\U00010e76\\U00010e77\\U00010e78\\U00010e79\\U00010e7a\\U00010e7b\\U00010e7c\\U00010e7d\\U00010e7e\\U00010f1d\\U00010f1e\\U00010f1f\\U00010f20\\U00010f21\\U00010f22\\U00010f23\\U00010f24\\U00010f25\\U00010f26\\U00010f51\\U00010f52\\U00010f53\\U00010f54\\U00011052\\U00011053\\U00011054\\U00011055\\U00011056\\U00011057\\U00011058\\U00011059\\U0001105a\\U0001105b\\U0001105c\\U0001105d\\U0001105e\\U0001105f\\U00011060\\U00011061\\U00011062\\U00011063\\U00011064\\U00011065\\U000111e1\\U000111e2\\U000111e3\\U000111e4\\U000111e5\\U000111e6\\U000111e7\\U000111e8\\U000111e9\\U000111ea\\U000111eb\\U000111ec\\U000111ed\\U000111ee\\U000111ef\\U000111f0\\U000111f1\\U000111f2\\U000111f3\\U000111f4\\U0001173a\\U0001173b\\U000118ea\\U000118eb\\U000118ec\\U000118ed\\U000118ee\\U000118ef\\U000118f0\\U000118f1\\U000118f2\\U00011c5a\\U00011c5b\\U00011c5c\\U00011c5d\\U00011c5e\\U00011c5f\\U00011c60\\U00011c61\\U00011c62\\U00011c63\\U00011c64\\U00011c65\\U00011c66\\U00011c67\\U00011c68\\U00011c69\\U00011c6a\\U00011c6b\\U00011c6c\\U00012400\\U00012401\\U00012402\\U00012403\\U00012404\\U00012405\\U00012406\\U00012407\\U00012408\\U00012409\\U0001240a\\U0001240b\\U0001240c\\U0001240d\\U0001240e\\U0001240f\\U00012410\\U00012411\\U00012412\\U00012413\\U00012414\\U00012415\\U00012416\\U00012417\\U00012418\\U00012419\\U0001241a\\U0001241b\\U0001241c\\U0001241d\\U0001241e\\U0001241f\\U00012420\\U00012421\\U00012422\\U00012423\\U00012424\\U00012425\\U00012426\\U00012427\\U00012428\\U00012429\\U0001242a\\U0001242b\\U0001242c\\U0001242d\\U0001242e\\U0001242f\\U00012430\\U00012431\\U00012432\\U00012433\\U00012434\\U00012435\\U00012436\\U00012437\\U00012438\\U00012439\\U0001243a\\U0001243b\\U0001243c\\U0001243d\\U0001243e\\U0001243f\\U00012440\\U00012441\\U00012442\\U00012443\\U00012444\\U00012445\\U00012446\\U00012447\\U00012448\\U00012449\\U0001244a\\U0001244b\\U0001244c\\U0001244d\\U0001244e\\U0001244f\\U00012450\\U00012451\\U00012452\\U00012453\\U00012454\\U00012455\\U00012456\\U00012457\\U00012458\\U00012459\\U0001245a\\U0001245b\\U0001245c\\U0001245d\\U0001245e\\U0001245f\\U00012460\\U00012461\\U00012462\\U00012463\\U00012464\\U00012465\\U00012466\\U00012467\\U00012468\\U00012469\\U0001246a\\U0001246b\\U0001246c\\U0001246d\\U0001246e\\U00016b5b\\U00016b5c\\U00016b5d\\U00016b5e\\U00016b5f\\U00016b60\\U00016b61\\U00016e80\\U00016e81\\U00016e82\\U00016e83\\U00016e84\\U00016e85\\U00016e86\\U00016e87\\U00016e88\\U00016e89\\U00016e8a\\U00016e8b\\U00016e8c\\U00016e8d\\U00016e8e\\U00016e8f\\U00016e90\\U00016e91\\U00016e92\\U00016e93\\U00016e94\\U00016e95\\U00016e96\\U0001d2e0\\U0001d2e1\\U0001d2e2\\U0001d2e3\\U0001d2e4\\U0001d2e5\\U0001d2e6\\U0001d2e7\\U0001d2e8\\U0001d2e9\\U0001d2ea\\U0001d2eb\\U0001d2ec\\U0001d2ed\\U0001d2ee\\U0001d2ef\\U0001d2f0\\U0001d2f1\\U0001d2f2\\U0001d2f3\\U0001d360\\U0001d361\\U0001d362\\U0001d363\\U0001d364\\U0001d365\\U0001d366\\U0001d367\\U0001d368\\U0001d369\\U0001d36a\\U0001d36b\\U0001d36c\\U0001d36d\\U0001d36e\\U0001d36f\\U0001d370\\U0001d371\\U0001d372\\U0001d373\\U0001d374\\U0001d375\\U0001d376\\U0001d377\\U0001d378\\U0001e8c7\\U0001e8c8\\U0001e8c9\\U0001e8ca\\U0001e8cb\\U0001e8cc\\U0001e8cd\\U0001e8ce\\U0001e8cf\\U0001ec71\\U0001ec72\\U0001ec73\\U0001ec74\\U0001ec75\\U0001ec76\\U0001ec77\\U0001ec78\\U0001ec79\\U0001ec7a\\U0001ec7b\\U0001ec7c\\U0001ec7d\\U0001ec7e\\U0001ec7f\\U0001ec80\\U0001ec81\\U0001ec82\\U0001ec83\\U0001ec84\\U0001ec85\\U0001ec86\\U0001ec87\\U0001ec88\\U0001ec89\\U0001ec8a\\U0001ec8b\\U0001ec8c\\U0001ec8d\\U0001ec8e\\U0001ec8f\\U0001ec90\\U0001ec91\\U0001ec92\\U0001ec93\\U0001ec94\\U0001ec95\\U0001ec96\\U0001ec97\\U0001ec98\\U0001ec99\\U0001ec9a\\U0001ec9b\\U0001ec9c\\U0001ec9d\\U0001ec9e\\U0001ec9f\\U0001eca0\\U0001eca1\\U0001eca2\\U0001eca3\\U0001eca4\\U0001eca5\\U0001eca6\\U0001eca7\\U0001eca8\\U0001eca9\\U0001ecaa\\U0001ecab\\U0001ecad\\U0001ecae\\U0001ecaf\\U0001ecb1\\U0001ecb2\\U0001ecb3\\U0001ecb4\\U0001f100\\U0001f101\\U0001f102\\U0001f103\\U0001f104\\U0001f105\\U0001f106\\U0001f107\\U0001f108\\U0001f109\\U0001f10a\\U0001f10b\\U0001f10c\\U00020001\\U00020064\\U000200e2\\U00020121\\U0002092a\\U00020983\\U0002098c\\U0002099c\\U00020aea\\U00020afd\\U00020b19\\U00022390\\U00022998\\U00023b1b\\U0002626d\\U0002f890])1]",
"tests/test_regex.py::test_regex_splits_correctly[12\\u2460\\u2461\\u2160\\u2161\\u2153-float_nosign_noexp]",
"tests/test_regex.py::test_regex_splits_correctly[hello-float_sign_exp]",
"tests/test_regex.py::test_regex_splits_correctly[12\\u2460\\u2461\\u2160\\u2161\\u2153-float_sign_noexp]",
"tests/test_regex.py::test_regex_splits_correctly[hello-float_nosign_exp]",
"tests/test_regex.py::test_regex_splits_correctly[hello-float_nosign_noexp]",
"tests/test_regex.py::test_regex_splits_correctly[abc12.34.56-7def-float_sign_noexp]",
"tests/test_regex.py::test_regex_chooser[4-(\\\\d+|[\\xb2\\xb3\\xb9\\u1369\\u136a\\u136b\\u136c\\u136d\\u136e\\u136f\\u1370\\u1371\\u19da\\u2070\\u2074\\u2075\\u2076\\u2077\\u2078\\u2079\\u2080\\u2081\\u2082\\u2083\\u2084\\u2085\\u2086\\u2087\\u2088\\u2089\\u2460\\u2461\\u2462\\u2463\\u2464\\u2465\\u2466\\u2467\\u2468\\u2474\\u2475\\u2476\\u2477\\u2478\\u2479\\u247a\\u247b\\u247c\\u2488\\u2489\\u248a\\u248b\\u248c\\u248d\\u248e\\u248f\\u2490\\u24ea\\u24f5\\u24f6\\u24f7\\u24f8\\u24f9\\u24fa\\u24fb\\u24fc\\u24fd\\u24ff\\u2776\\u2777\\u2778\\u2779\\u277a\\u277b\\u277c\\u277d\\u277e\\u2780\\u2781\\u2782\\u2783\\u2784\\u2785\\u2786\\u2787\\u2788\\u278a\\u278b\\u278c\\u278d\\u278e\\u278f\\u2790\\u2791\\u2792\\U00010a40\\U00010a41\\U00010a42\\U00010a43\\U00010e60\\U00010e61\\U00010e62\\U00010e63\\U00010e64\\U00010e65\\U00010e66\\U00010e67\\U00010e68\\U00011052\\U00011053\\U00011054\\U00011055\\U00011056\\U00011057\\U00011058\\U00011059\\U0001105a\\U0001f100\\U0001f101\\U0001f102\\U0001f103\\U0001f104\\U0001f105\\U0001f106\\U0001f107\\U0001f108\\U0001f109\\U0001f10a])]",
"tests/test_regex.py::test_regex_chooser[5-((?:\\\\d+\\\\.?\\\\d*|\\\\.\\\\d+)|[\\xb2\\xb3\\xb9\\xbc\\xbd\\xbe\\u09f4\\u09f5\\u09f6\\u09f7\\u09f8\\u09f9\\u0b72\\u0b73\\u0b74\\u0b75\\u0b76\\u0b77\\u0bf0\\u0bf1\\u0bf2\\u0c78\\u0c79\\u0c7a\\u0c7b\\u0c7c\\u0c7d\\u0c7e\\u0d58\\u0d59\\u0d5a\\u0d5b\\u0d5c\\u0d5d\\u0d5e\\u0d70\\u0d71\\u0d72\\u0d73\\u0d74\\u0d75\\u0d76\\u0d77\\u0d78\\u0f2a\\u0f2b\\u0f2c\\u0f2d\\u0f2e\\u0f2f\\u0f30\\u0f31\\u0f32\\u0f33\\u1369\\u136a\\u136b\\u136c\\u136d\\u136e\\u136f\\u1370\\u1371\\u1372\\u1373\\u1374\\u1375\\u1376\\u1377\\u1378\\u1379\\u137a\\u137b\\u137c\\u16ee\\u16ef\\u16f0\\u17f0\\u17f1\\u17f2\\u17f3\\u17f4\\u17f5\\u17f6\\u17f7\\u17f8\\u17f9\\u19da\\u2070\\u2074\\u2075\\u2076\\u2077\\u2078\\u2079\\u2080\\u2081\\u2082\\u2083\\u2084\\u2085\\u2086\\u2087\\u2088\\u2089\\u2150\\u2151\\u2152\\u2153\\u2154\\u2155\\u2156\\u2157\\u2158\\u2159\\u215a\\u215b\\u215c\\u215d\\u215e\\u215f\\u2160\\u2161\\u2162\\u2163\\u2164\\u2165\\u2166\\u2167\\u2168\\u2169\\u216a\\u216b\\u216c\\u216d\\u216e\\u216f\\u2170\\u2171\\u2172\\u2173\\u2174\\u2175\\u2176\\u2177\\u2178\\u2179\\u217a\\u217b\\u217c\\u217d\\u217e\\u217f\\u2180\\u2181\\u2182\\u2185\\u2186\\u2187\\u2188\\u2189\\u2460\\u2461\\u2462\\u2463\\u2464\\u2465\\u2466\\u2467\\u2468\\u2469\\u246a\\u246b\\u246c\\u246d\\u246e\\u246f\\u2470\\u2471\\u2472\\u2473\\u2474\\u2475\\u2476\\u2477\\u2478\\u2479\\u247a\\u247b\\u247c\\u247d\\u247e\\u247f\\u2480\\u2481\\u2482\\u2483\\u2484\\u2485\\u2486\\u2487\\u2488\\u2489\\u248a\\u248b\\u248c\\u248d\\u248e\\u248f\\u2490\\u2491\\u2492\\u2493\\u2494\\u2495\\u2496\\u2497\\u2498\\u2499\\u249a\\u249b\\u24ea\\u24eb\\u24ec\\u24ed\\u24ee\\u24ef\\u24f0\\u24f1\\u24f2\\u24f3\\u24f4\\u24f5\\u24f6\\u24f7\\u24f8\\u24f9\\u24fa\\u24fb\\u24fc\\u24fd\\u24fe\\u24ff\\u2776\\u2777\\u2778\\u2779\\u277a\\u277b\\u277c\\u277d\\u277e\\u277f\\u2780\\u2781\\u2782\\u2783\\u2784\\u2785\\u2786\\u2787\\u2788\\u2789\\u278a\\u278b\\u278c\\u278d\\u278e\\u278f\\u2790\\u2791\\u2792\\u2793\\u2cfd\\u3007\\u3021\\u3022\\u3023\\u3024\\u3025\\u3026\\u3027\\u3028\\u3029\\u3038\\u3039\\u303a\\u3192\\u3193\\u3194\\u3195\\u3220\\u3221\\u3222\\u3223\\u3224\\u3225\\u3226\\u3227\\u3228\\u3229\\u3248\\u3249\\u324a\\u324b\\u324c\\u324d\\u324e\\u324f\\u3251\\u3252\\u3253\\u3254\\u3255\\u3256\\u3257\\u3258\\u3259\\u325a\\u325b\\u325c\\u325d\\u325e\\u325f\\u3280\\u3281\\u3282\\u3283\\u3284\\u3285\\u3286\\u3287\\u3288\\u3289\\u32b1\\u32b2\\u32b3\\u32b4\\u32b5\\u32b6\\u32b7\\u32b8\\u32b9\\u32ba\\u32bb\\u32bc\\u32bd\\u32be\\u32bf\\u3405\\u3483\\u382a\\u3b4d\\u4e00\\u4e03\\u4e07\\u4e09\\u4e5d\\u4e8c\\u4e94\\u4e96\\u4ebf\\u4ec0\\u4edf\\u4ee8\\u4f0d\\u4f70\\u5104\\u5146\\u5169\\u516b\\u516d\\u5341\\u5343\\u5344\\u5345\\u534c\\u53c1\\u53c2\\u53c3\\u53c4\\u56db\\u58f1\\u58f9\\u5e7a\\u5efe\\u5eff\\u5f0c\\u5f0d\\u5f0e\\u5f10\\u62fe\\u634c\\u67d2\\u6f06\\u7396\\u767e\\u8086\\u842c\\u8cae\\u8cb3\\u8d30\\u9621\\u9646\\u964c\\u9678\\u96f6\\ua6e6\\ua6e7\\ua6e8\\ua6e9\\ua6ea\\ua6eb\\ua6ec\\ua6ed\\ua6ee\\ua6ef\\ua830\\ua831\\ua832\\ua833\\ua834\\ua835\\uf96b\\uf973\\uf978\\uf9b2\\uf9d1\\uf9d3\\uf9fd\\U00010107\\U00010108\\U00010109\\U0001010a\\U0001010b\\U0001010c\\U0001010d\\U0001010e\\U0001010f\\U00010110\\U00010111\\U00010112\\U00010113\\U00010114\\U00010115\\U00010116\\U00010117\\U00010118\\U00010119\\U0001011a\\U0001011b\\U0001011c\\U0001011d\\U0001011e\\U0001011f\\U00010120\\U00010121\\U00010122\\U00010123\\U00010124\\U00010125\\U00010126\\U00010127\\U00010128\\U00010129\\U0001012a\\U0001012b\\U0001012c\\U0001012d\\U0001012e\\U0001012f\\U00010130\\U00010131\\U00010132\\U00010133\\U00010140\\U00010141\\U00010142\\U00010143\\U00010144\\U00010145\\U00010146\\U00010147\\U00010148\\U00010149\\U0001014a\\U0001014b\\U0001014c\\U0001014d\\U0001014e\\U0001014f\\U00010150\\U00010151\\U00010152\\U00010153\\U00010154\\U00010155\\U00010156\\U00010157\\U00010158\\U00010159\\U0001015a\\U0001015b\\U0001015c\\U0001015d\\U0001015e\\U0001015f\\U00010160\\U00010161\\U00010162\\U00010163\\U00010164\\U00010165\\U00010166\\U00010167\\U00010168\\U00010169\\U0001016a\\U0001016b\\U0001016c\\U0001016d\\U0001016e\\U0001016f\\U00010170\\U00010171\\U00010172\\U00010173\\U00010174\\U00010175\\U00010176\\U00010177\\U00010178\\U0001018a\\U0001018b\\U000102e1\\U000102e2\\U000102e3\\U000102e4\\U000102e5\\U000102e6\\U000102e7\\U000102e8\\U000102e9\\U000102ea\\U000102eb\\U000102ec\\U000102ed\\U000102ee\\U000102ef\\U000102f0\\U000102f1\\U000102f2\\U000102f3\\U000102f4\\U000102f5\\U000102f6\\U000102f7\\U000102f8\\U000102f9\\U000102fa\\U000102fb\\U00010320\\U00010321\\U00010322\\U00010323\\U00010341\\U0001034a\\U000103d1\\U000103d2\\U000103d3\\U000103d4\\U000103d5\\U00010858\\U00010859\\U0001085a\\U0001085b\\U0001085c\\U0001085d\\U0001085e\\U0001085f\\U00010879\\U0001087a\\U0001087b\\U0001087c\\U0001087d\\U0001087e\\U0001087f\\U000108a7\\U000108a8\\U000108a9\\U000108aa\\U000108ab\\U000108ac\\U000108ad\\U000108ae\\U000108af\\U000108fb\\U000108fc\\U000108fd\\U000108fe\\U000108ff\\U00010916\\U00010917\\U00010918\\U00010919\\U0001091a\\U0001091b\\U000109bc\\U000109bd\\U000109c0\\U000109c1\\U000109c2\\U000109c3\\U000109c4\\U000109c5\\U000109c6\\U000109c7\\U000109c8\\U000109c9\\U000109ca\\U000109cb\\U000109cc\\U000109cd\\U000109ce\\U000109cf\\U000109d2\\U000109d3\\U000109d4\\U000109d5\\U000109d6\\U000109d7\\U000109d8\\U000109d9\\U000109da\\U000109db\\U000109dc\\U000109dd\\U000109de\\U000109df\\U000109e0\\U000109e1\\U000109e2\\U000109e3\\U000109e4\\U000109e5\\U000109e6\\U000109e7\\U000109e8\\U000109e9\\U000109ea\\U000109eb\\U000109ec\\U000109ed\\U000109ee\\U000109ef\\U000109f0\\U000109f1\\U000109f2\\U000109f3\\U000109f4\\U000109f5\\U000109f6\\U000109f7\\U000109f8\\U000109f9\\U000109fa\\U000109fb\\U000109fc\\U000109fd\\U000109fe\\U000109ff\\U00010a40\\U00010a41\\U00010a42\\U00010a43\\U00010a44\\U00010a45\\U00010a46\\U00010a47\\U00010a48\\U00010a7d\\U00010a7e\\U00010a9d\\U00010a9e\\U00010a9f\\U00010aeb\\U00010aec\\U00010aed\\U00010aee\\U00010aef\\U00010b58\\U00010b59\\U00010b5a\\U00010b5b\\U00010b5c\\U00010b5d\\U00010b5e\\U00010b5f\\U00010b78\\U00010b79\\U00010b7a\\U00010b7b\\U00010b7c\\U00010b7d\\U00010b7e\\U00010b7f\\U00010ba9\\U00010baa\\U00010bab\\U00010bac\\U00010bad\\U00010bae\\U00010baf\\U00010cfa\\U00010cfb\\U00010cfc\\U00010cfd\\U00010cfe\\U00010cff\\U00010e60\\U00010e61\\U00010e62\\U00010e63\\U00010e64\\U00010e65\\U00010e66\\U00010e67\\U00010e68\\U00010e69\\U00010e6a\\U00010e6b\\U00010e6c\\U00010e6d\\U00010e6e\\U00010e6f\\U00010e70\\U00010e71\\U00010e72\\U00010e73\\U00010e74\\U00010e75\\U00010e76\\U00010e77\\U00010e78\\U00010e79\\U00010e7a\\U00010e7b\\U00010e7c\\U00010e7d\\U00010e7e\\U00010f1d\\U00010f1e\\U00010f1f\\U00010f20\\U00010f21\\U00010f22\\U00010f23\\U00010f24\\U00010f25\\U00010f26\\U00010f51\\U00010f52\\U00010f53\\U00010f54\\U00011052\\U00011053\\U00011054\\U00011055\\U00011056\\U00011057\\U00011058\\U00011059\\U0001105a\\U0001105b\\U0001105c\\U0001105d\\U0001105e\\U0001105f\\U00011060\\U00011061\\U00011062\\U00011063\\U00011064\\U00011065\\U000111e1\\U000111e2\\U000111e3\\U000111e4\\U000111e5\\U000111e6\\U000111e7\\U000111e8\\U000111e9\\U000111ea\\U000111eb\\U000111ec\\U000111ed\\U000111ee\\U000111ef\\U000111f0\\U000111f1\\U000111f2\\U000111f3\\U000111f4\\U0001173a\\U0001173b\\U000118ea\\U000118eb\\U000118ec\\U000118ed\\U000118ee\\U000118ef\\U000118f0\\U000118f1\\U000118f2\\U00011c5a\\U00011c5b\\U00011c5c\\U00011c5d\\U00011c5e\\U00011c5f\\U00011c60\\U00011c61\\U00011c62\\U00011c63\\U00011c64\\U00011c65\\U00011c66\\U00011c67\\U00011c68\\U00011c69\\U00011c6a\\U00011c6b\\U00011c6c\\U00012400\\U00012401\\U00012402\\U00012403\\U00012404\\U00012405\\U00012406\\U00012407\\U00012408\\U00012409\\U0001240a\\U0001240b\\U0001240c\\U0001240d\\U0001240e\\U0001240f\\U00012410\\U00012411\\U00012412\\U00012413\\U00012414\\U00012415\\U00012416\\U00012417\\U00012418\\U00012419\\U0001241a\\U0001241b\\U0001241c\\U0001241d\\U0001241e\\U0001241f\\U00012420\\U00012421\\U00012422\\U00012423\\U00012424\\U00012425\\U00012426\\U00012427\\U00012428\\U00012429\\U0001242a\\U0001242b\\U0001242c\\U0001242d\\U0001242e\\U0001242f\\U00012430\\U00012431\\U00012432\\U00012433\\U00012434\\U00012435\\U00012436\\U00012437\\U00012438\\U00012439\\U0001243a\\U0001243b\\U0001243c\\U0001243d\\U0001243e\\U0001243f\\U00012440\\U00012441\\U00012442\\U00012443\\U00012444\\U00012445\\U00012446\\U00012447\\U00012448\\U00012449\\U0001244a\\U0001244b\\U0001244c\\U0001244d\\U0001244e\\U0001244f\\U00012450\\U00012451\\U00012452\\U00012453\\U00012454\\U00012455\\U00012456\\U00012457\\U00012458\\U00012459\\U0001245a\\U0001245b\\U0001245c\\U0001245d\\U0001245e\\U0001245f\\U00012460\\U00012461\\U00012462\\U00012463\\U00012464\\U00012465\\U00012466\\U00012467\\U00012468\\U00012469\\U0001246a\\U0001246b\\U0001246c\\U0001246d\\U0001246e\\U00016b5b\\U00016b5c\\U00016b5d\\U00016b5e\\U00016b5f\\U00016b60\\U00016b61\\U00016e80\\U00016e81\\U00016e82\\U00016e83\\U00016e84\\U00016e85\\U00016e86\\U00016e87\\U00016e88\\U00016e89\\U00016e8a\\U00016e8b\\U00016e8c\\U00016e8d\\U00016e8e\\U00016e8f\\U00016e90\\U00016e91\\U00016e92\\U00016e93\\U00016e94\\U00016e95\\U00016e96\\U0001d2e0\\U0001d2e1\\U0001d2e2\\U0001d2e3\\U0001d2e4\\U0001d2e5\\U0001d2e6\\U0001d2e7\\U0001d2e8\\U0001d2e9\\U0001d2ea\\U0001d2eb\\U0001d2ec\\U0001d2ed\\U0001d2ee\\U0001d2ef\\U0001d2f0\\U0001d2f1\\U0001d2f2\\U0001d2f3\\U0001d360\\U0001d361\\U0001d362\\U0001d363\\U0001d364\\U0001d365\\U0001d366\\U0001d367\\U0001d368\\U0001d369\\U0001d36a\\U0001d36b\\U0001d36c\\U0001d36d\\U0001d36e\\U0001d36f\\U0001d370\\U0001d371\\U0001d372\\U0001d373\\U0001d374\\U0001d375\\U0001d376\\U0001d377\\U0001d378\\U0001e8c7\\U0001e8c8\\U0001e8c9\\U0001e8ca\\U0001e8cb\\U0001e8cc\\U0001e8cd\\U0001e8ce\\U0001e8cf\\U0001ec71\\U0001ec72\\U0001ec73\\U0001ec74\\U0001ec75\\U0001ec76\\U0001ec77\\U0001ec78\\U0001ec79\\U0001ec7a\\U0001ec7b\\U0001ec7c\\U0001ec7d\\U0001ec7e\\U0001ec7f\\U0001ec80\\U0001ec81\\U0001ec82\\U0001ec83\\U0001ec84\\U0001ec85\\U0001ec86\\U0001ec87\\U0001ec88\\U0001ec89\\U0001ec8a\\U0001ec8b\\U0001ec8c\\U0001ec8d\\U0001ec8e\\U0001ec8f\\U0001ec90\\U0001ec91\\U0001ec92\\U0001ec93\\U0001ec94\\U0001ec95\\U0001ec96\\U0001ec97\\U0001ec98\\U0001ec99\\U0001ec9a\\U0001ec9b\\U0001ec9c\\U0001ec9d\\U0001ec9e\\U0001ec9f\\U0001eca0\\U0001eca1\\U0001eca2\\U0001eca3\\U0001eca4\\U0001eca5\\U0001eca6\\U0001eca7\\U0001eca8\\U0001eca9\\U0001ecaa\\U0001ecab\\U0001ecad\\U0001ecae\\U0001ecaf\\U0001ecb1\\U0001ecb2\\U0001ecb3\\U0001ecb4\\U0001f100\\U0001f101\\U0001f102\\U0001f103\\U0001f104\\U0001f105\\U0001f106\\U0001f107\\U0001f108\\U0001f109\\U0001f10a\\U0001f10b\\U0001f10c\\U00020001\\U00020064\\U000200e2\\U00020121\\U0002092a\\U00020983\\U0002098c\\U0002099c\\U00020aea\\U00020afd\\U00020b19\\U00022390\\U00022998\\U00023b1b\\U0002626d\\U0002f890])0]",
"tests/test_regex.py::test_regex_splits_correctly[-123.45e+67-float_nosign_exp]",
"tests/test_regex.py::test_regex_splits_correctly[12\\u2460\\u2461\\u2160\\u2161\\u2153-float_nosign_exp]",
"tests/test_regex.py::test_regex_splits_correctly[abc12.34.56-7def-float_nosign_noexp]",
"tests/test_regex.py::test_regex_splits_correctly[eleven\\u06f1\\u06f1eleven11eleven\\u09e7\\u09e7-float_sign_exp]",
"tests/test_regex.py::test_regex_chooser[5-((?:\\\\d+\\\\.?\\\\d*|\\\\.\\\\d+)|[\\xb2\\xb3\\xb9\\xbc\\xbd\\xbe\\u09f4\\u09f5\\u09f6\\u09f7\\u09f8\\u09f9\\u0b72\\u0b73\\u0b74\\u0b75\\u0b76\\u0b77\\u0bf0\\u0bf1\\u0bf2\\u0c78\\u0c79\\u0c7a\\u0c7b\\u0c7c\\u0c7d\\u0c7e\\u0d58\\u0d59\\u0d5a\\u0d5b\\u0d5c\\u0d5d\\u0d5e\\u0d70\\u0d71\\u0d72\\u0d73\\u0d74\\u0d75\\u0d76\\u0d77\\u0d78\\u0f2a\\u0f2b\\u0f2c\\u0f2d\\u0f2e\\u0f2f\\u0f30\\u0f31\\u0f32\\u0f33\\u1369\\u136a\\u136b\\u136c\\u136d\\u136e\\u136f\\u1370\\u1371\\u1372\\u1373\\u1374\\u1375\\u1376\\u1377\\u1378\\u1379\\u137a\\u137b\\u137c\\u16ee\\u16ef\\u16f0\\u17f0\\u17f1\\u17f2\\u17f3\\u17f4\\u17f5\\u17f6\\u17f7\\u17f8\\u17f9\\u19da\\u2070\\u2074\\u2075\\u2076\\u2077\\u2078\\u2079\\u2080\\u2081\\u2082\\u2083\\u2084\\u2085\\u2086\\u2087\\u2088\\u2089\\u2150\\u2151\\u2152\\u2153\\u2154\\u2155\\u2156\\u2157\\u2158\\u2159\\u215a\\u215b\\u215c\\u215d\\u215e\\u215f\\u2160\\u2161\\u2162\\u2163\\u2164\\u2165\\u2166\\u2167\\u2168\\u2169\\u216a\\u216b\\u216c\\u216d\\u216e\\u216f\\u2170\\u2171\\u2172\\u2173\\u2174\\u2175\\u2176\\u2177\\u2178\\u2179\\u217a\\u217b\\u217c\\u217d\\u217e\\u217f\\u2180\\u2181\\u2182\\u2185\\u2186\\u2187\\u2188\\u2189\\u2460\\u2461\\u2462\\u2463\\u2464\\u2465\\u2466\\u2467\\u2468\\u2469\\u246a\\u246b\\u246c\\u246d\\u246e\\u246f\\u2470\\u2471\\u2472\\u2473\\u2474\\u2475\\u2476\\u2477\\u2478\\u2479\\u247a\\u247b\\u247c\\u247d\\u247e\\u247f\\u2480\\u2481\\u2482\\u2483\\u2484\\u2485\\u2486\\u2487\\u2488\\u2489\\u248a\\u248b\\u248c\\u248d\\u248e\\u248f\\u2490\\u2491\\u2492\\u2493\\u2494\\u2495\\u2496\\u2497\\u2498\\u2499\\u249a\\u249b\\u24ea\\u24eb\\u24ec\\u24ed\\u24ee\\u24ef\\u24f0\\u24f1\\u24f2\\u24f3\\u24f4\\u24f5\\u24f6\\u24f7\\u24f8\\u24f9\\u24fa\\u24fb\\u24fc\\u24fd\\u24fe\\u24ff\\u2776\\u2777\\u2778\\u2779\\u277a\\u277b\\u277c\\u277d\\u277e\\u277f\\u2780\\u2781\\u2782\\u2783\\u2784\\u2785\\u2786\\u2787\\u2788\\u2789\\u278a\\u278b\\u278c\\u278d\\u278e\\u278f\\u2790\\u2791\\u2792\\u2793\\u2cfd\\u3007\\u3021\\u3022\\u3023\\u3024\\u3025\\u3026\\u3027\\u3028\\u3029\\u3038\\u3039\\u303a\\u3192\\u3193\\u3194\\u3195\\u3220\\u3221\\u3222\\u3223\\u3224\\u3225\\u3226\\u3227\\u3228\\u3229\\u3248\\u3249\\u324a\\u324b\\u324c\\u324d\\u324e\\u324f\\u3251\\u3252\\u3253\\u3254\\u3255\\u3256\\u3257\\u3258\\u3259\\u325a\\u325b\\u325c\\u325d\\u325e\\u325f\\u3280\\u3281\\u3282\\u3283\\u3284\\u3285\\u3286\\u3287\\u3288\\u3289\\u32b1\\u32b2\\u32b3\\u32b4\\u32b5\\u32b6\\u32b7\\u32b8\\u32b9\\u32ba\\u32bb\\u32bc\\u32bd\\u32be\\u32bf\\u3405\\u3483\\u382a\\u3b4d\\u4e00\\u4e03\\u4e07\\u4e09\\u4e5d\\u4e8c\\u4e94\\u4e96\\u4ebf\\u4ec0\\u4edf\\u4ee8\\u4f0d\\u4f70\\u5104\\u5146\\u5169\\u516b\\u516d\\u5341\\u5343\\u5344\\u5345\\u534c\\u53c1\\u53c2\\u53c3\\u53c4\\u56db\\u58f1\\u58f9\\u5e7a\\u5efe\\u5eff\\u5f0c\\u5f0d\\u5f0e\\u5f10\\u62fe\\u634c\\u67d2\\u6f06\\u7396\\u767e\\u8086\\u842c\\u8cae\\u8cb3\\u8d30\\u9621\\u9646\\u964c\\u9678\\u96f6\\ua6e6\\ua6e7\\ua6e8\\ua6e9\\ua6ea\\ua6eb\\ua6ec\\ua6ed\\ua6ee\\ua6ef\\ua830\\ua831\\ua832\\ua833\\ua834\\ua835\\uf96b\\uf973\\uf978\\uf9b2\\uf9d1\\uf9d3\\uf9fd\\U00010107\\U00010108\\U00010109\\U0001010a\\U0001010b\\U0001010c\\U0001010d\\U0001010e\\U0001010f\\U00010110\\U00010111\\U00010112\\U00010113\\U00010114\\U00010115\\U00010116\\U00010117\\U00010118\\U00010119\\U0001011a\\U0001011b\\U0001011c\\U0001011d\\U0001011e\\U0001011f\\U00010120\\U00010121\\U00010122\\U00010123\\U00010124\\U00010125\\U00010126\\U00010127\\U00010128\\U00010129\\U0001012a\\U0001012b\\U0001012c\\U0001012d\\U0001012e\\U0001012f\\U00010130\\U00010131\\U00010132\\U00010133\\U00010140\\U00010141\\U00010142\\U00010143\\U00010144\\U00010145\\U00010146\\U00010147\\U00010148\\U00010149\\U0001014a\\U0001014b\\U0001014c\\U0001014d\\U0001014e\\U0001014f\\U00010150\\U00010151\\U00010152\\U00010153\\U00010154\\U00010155\\U00010156\\U00010157\\U00010158\\U00010159\\U0001015a\\U0001015b\\U0001015c\\U0001015d\\U0001015e\\U0001015f\\U00010160\\U00010161\\U00010162\\U00010163\\U00010164\\U00010165\\U00010166\\U00010167\\U00010168\\U00010169\\U0001016a\\U0001016b\\U0001016c\\U0001016d\\U0001016e\\U0001016f\\U00010170\\U00010171\\U00010172\\U00010173\\U00010174\\U00010175\\U00010176\\U00010177\\U00010178\\U0001018a\\U0001018b\\U000102e1\\U000102e2\\U000102e3\\U000102e4\\U000102e5\\U000102e6\\U000102e7\\U000102e8\\U000102e9\\U000102ea\\U000102eb\\U000102ec\\U000102ed\\U000102ee\\U000102ef\\U000102f0\\U000102f1\\U000102f2\\U000102f3\\U000102f4\\U000102f5\\U000102f6\\U000102f7\\U000102f8\\U000102f9\\U000102fa\\U000102fb\\U00010320\\U00010321\\U00010322\\U00010323\\U00010341\\U0001034a\\U000103d1\\U000103d2\\U000103d3\\U000103d4\\U000103d5\\U00010858\\U00010859\\U0001085a\\U0001085b\\U0001085c\\U0001085d\\U0001085e\\U0001085f\\U00010879\\U0001087a\\U0001087b\\U0001087c\\U0001087d\\U0001087e\\U0001087f\\U000108a7\\U000108a8\\U000108a9\\U000108aa\\U000108ab\\U000108ac\\U000108ad\\U000108ae\\U000108af\\U000108fb\\U000108fc\\U000108fd\\U000108fe\\U000108ff\\U00010916\\U00010917\\U00010918\\U00010919\\U0001091a\\U0001091b\\U000109bc\\U000109bd\\U000109c0\\U000109c1\\U000109c2\\U000109c3\\U000109c4\\U000109c5\\U000109c6\\U000109c7\\U000109c8\\U000109c9\\U000109ca\\U000109cb\\U000109cc\\U000109cd\\U000109ce\\U000109cf\\U000109d2\\U000109d3\\U000109d4\\U000109d5\\U000109d6\\U000109d7\\U000109d8\\U000109d9\\U000109da\\U000109db\\U000109dc\\U000109dd\\U000109de\\U000109df\\U000109e0\\U000109e1\\U000109e2\\U000109e3\\U000109e4\\U000109e5\\U000109e6\\U000109e7\\U000109e8\\U000109e9\\U000109ea\\U000109eb\\U000109ec\\U000109ed\\U000109ee\\U000109ef\\U000109f0\\U000109f1\\U000109f2\\U000109f3\\U000109f4\\U000109f5\\U000109f6\\U000109f7\\U000109f8\\U000109f9\\U000109fa\\U000109fb\\U000109fc\\U000109fd\\U000109fe\\U000109ff\\U00010a40\\U00010a41\\U00010a42\\U00010a43\\U00010a44\\U00010a45\\U00010a46\\U00010a47\\U00010a48\\U00010a7d\\U00010a7e\\U00010a9d\\U00010a9e\\U00010a9f\\U00010aeb\\U00010aec\\U00010aed\\U00010aee\\U00010aef\\U00010b58\\U00010b59\\U00010b5a\\U00010b5b\\U00010b5c\\U00010b5d\\U00010b5e\\U00010b5f\\U00010b78\\U00010b79\\U00010b7a\\U00010b7b\\U00010b7c\\U00010b7d\\U00010b7e\\U00010b7f\\U00010ba9\\U00010baa\\U00010bab\\U00010bac\\U00010bad\\U00010bae\\U00010baf\\U00010cfa\\U00010cfb\\U00010cfc\\U00010cfd\\U00010cfe\\U00010cff\\U00010e60\\U00010e61\\U00010e62\\U00010e63\\U00010e64\\U00010e65\\U00010e66\\U00010e67\\U00010e68\\U00010e69\\U00010e6a\\U00010e6b\\U00010e6c\\U00010e6d\\U00010e6e\\U00010e6f\\U00010e70\\U00010e71\\U00010e72\\U00010e73\\U00010e74\\U00010e75\\U00010e76\\U00010e77\\U00010e78\\U00010e79\\U00010e7a\\U00010e7b\\U00010e7c\\U00010e7d\\U00010e7e\\U00010f1d\\U00010f1e\\U00010f1f\\U00010f20\\U00010f21\\U00010f22\\U00010f23\\U00010f24\\U00010f25\\U00010f26\\U00010f51\\U00010f52\\U00010f53\\U00010f54\\U00011052\\U00011053\\U00011054\\U00011055\\U00011056\\U00011057\\U00011058\\U00011059\\U0001105a\\U0001105b\\U0001105c\\U0001105d\\U0001105e\\U0001105f\\U00011060\\U00011061\\U00011062\\U00011063\\U00011064\\U00011065\\U000111e1\\U000111e2\\U000111e3\\U000111e4\\U000111e5\\U000111e6\\U000111e7\\U000111e8\\U000111e9\\U000111ea\\U000111eb\\U000111ec\\U000111ed\\U000111ee\\U000111ef\\U000111f0\\U000111f1\\U000111f2\\U000111f3\\U000111f4\\U0001173a\\U0001173b\\U000118ea\\U000118eb\\U000118ec\\U000118ed\\U000118ee\\U000118ef\\U000118f0\\U000118f1\\U000118f2\\U00011c5a\\U00011c5b\\U00011c5c\\U00011c5d\\U00011c5e\\U00011c5f\\U00011c60\\U00011c61\\U00011c62\\U00011c63\\U00011c64\\U00011c65\\U00011c66\\U00011c67\\U00011c68\\U00011c69\\U00011c6a\\U00011c6b\\U00011c6c\\U00012400\\U00012401\\U00012402\\U00012403\\U00012404\\U00012405\\U00012406\\U00012407\\U00012408\\U00012409\\U0001240a\\U0001240b\\U0001240c\\U0001240d\\U0001240e\\U0001240f\\U00012410\\U00012411\\U00012412\\U00012413\\U00012414\\U00012415\\U00012416\\U00012417\\U00012418\\U00012419\\U0001241a\\U0001241b\\U0001241c\\U0001241d\\U0001241e\\U0001241f\\U00012420\\U00012421\\U00012422\\U00012423\\U00012424\\U00012425\\U00012426\\U00012427\\U00012428\\U00012429\\U0001242a\\U0001242b\\U0001242c\\U0001242d\\U0001242e\\U0001242f\\U00012430\\U00012431\\U00012432\\U00012433\\U00012434\\U00012435\\U00012436\\U00012437\\U00012438\\U00012439\\U0001243a\\U0001243b\\U0001243c\\U0001243d\\U0001243e\\U0001243f\\U00012440\\U00012441\\U00012442\\U00012443\\U00012444\\U00012445\\U00012446\\U00012447\\U00012448\\U00012449\\U0001244a\\U0001244b\\U0001244c\\U0001244d\\U0001244e\\U0001244f\\U00012450\\U00012451\\U00012452\\U00012453\\U00012454\\U00012455\\U00012456\\U00012457\\U00012458\\U00012459\\U0001245a\\U0001245b\\U0001245c\\U0001245d\\U0001245e\\U0001245f\\U00012460\\U00012461\\U00012462\\U00012463\\U00012464\\U00012465\\U00012466\\U00012467\\U00012468\\U00012469\\U0001246a\\U0001246b\\U0001246c\\U0001246d\\U0001246e\\U00016b5b\\U00016b5c\\U00016b5d\\U00016b5e\\U00016b5f\\U00016b60\\U00016b61\\U00016e80\\U00016e81\\U00016e82\\U00016e83\\U00016e84\\U00016e85\\U00016e86\\U00016e87\\U00016e88\\U00016e89\\U00016e8a\\U00016e8b\\U00016e8c\\U00016e8d\\U00016e8e\\U00016e8f\\U00016e90\\U00016e91\\U00016e92\\U00016e93\\U00016e94\\U00016e95\\U00016e96\\U0001d2e0\\U0001d2e1\\U0001d2e2\\U0001d2e3\\U0001d2e4\\U0001d2e5\\U0001d2e6\\U0001d2e7\\U0001d2e8\\U0001d2e9\\U0001d2ea\\U0001d2eb\\U0001d2ec\\U0001d2ed\\U0001d2ee\\U0001d2ef\\U0001d2f0\\U0001d2f1\\U0001d2f2\\U0001d2f3\\U0001d360\\U0001d361\\U0001d362\\U0001d363\\U0001d364\\U0001d365\\U0001d366\\U0001d367\\U0001d368\\U0001d369\\U0001d36a\\U0001d36b\\U0001d36c\\U0001d36d\\U0001d36e\\U0001d36f\\U0001d370\\U0001d371\\U0001d372\\U0001d373\\U0001d374\\U0001d375\\U0001d376\\U0001d377\\U0001d378\\U0001e8c7\\U0001e8c8\\U0001e8c9\\U0001e8ca\\U0001e8cb\\U0001e8cc\\U0001e8cd\\U0001e8ce\\U0001e8cf\\U0001ec71\\U0001ec72\\U0001ec73\\U0001ec74\\U0001ec75\\U0001ec76\\U0001ec77\\U0001ec78\\U0001ec79\\U0001ec7a\\U0001ec7b\\U0001ec7c\\U0001ec7d\\U0001ec7e\\U0001ec7f\\U0001ec80\\U0001ec81\\U0001ec82\\U0001ec83\\U0001ec84\\U0001ec85\\U0001ec86\\U0001ec87\\U0001ec88\\U0001ec89\\U0001ec8a\\U0001ec8b\\U0001ec8c\\U0001ec8d\\U0001ec8e\\U0001ec8f\\U0001ec90\\U0001ec91\\U0001ec92\\U0001ec93\\U0001ec94\\U0001ec95\\U0001ec96\\U0001ec97\\U0001ec98\\U0001ec99\\U0001ec9a\\U0001ec9b\\U0001ec9c\\U0001ec9d\\U0001ec9e\\U0001ec9f\\U0001eca0\\U0001eca1\\U0001eca2\\U0001eca3\\U0001eca4\\U0001eca5\\U0001eca6\\U0001eca7\\U0001eca8\\U0001eca9\\U0001ecaa\\U0001ecab\\U0001ecad\\U0001ecae\\U0001ecaf\\U0001ecb1\\U0001ecb2\\U0001ecb3\\U0001ecb4\\U0001f100\\U0001f101\\U0001f102\\U0001f103\\U0001f104\\U0001f105\\U0001f106\\U0001f107\\U0001f108\\U0001f109\\U0001f10a\\U0001f10b\\U0001f10c\\U00020001\\U00020064\\U000200e2\\U00020121\\U0002092a\\U00020983\\U0002098c\\U0002099c\\U00020aea\\U00020afd\\U00020b19\\U00022390\\U00022998\\U00023b1b\\U0002626d\\U0002f890])1]",
"tests/test_regex.py::test_regex_splits_correctly[a1b2c3d4e5e6-float_nosign_noexp]",
"tests/test_regex.py::test_regex_splits_correctly[12\\u2460\\u2461\\u2160\\u2161\\u2153-float_sign_exp]",
"tests/test_regex.py::test_regex_splits_correctly[eleven\\u06f1\\u06f1eleven11eleven\\u09e7\\u09e7-int_nosign]",
"tests/test_regex.py::test_regex_splits_correctly[eleven\\u06f1\\u06f1eleven11eleven\\u09e7\\u09e7-float_nosign_exp]",
"tests/test_regex.py::test_regex_splits_correctly[a-123.45e+67b-int_nosign]",
"tests/test_regex.py::test_regex_splits_correctly[a-123.45e+67b-int_sign]",
"tests/test_regex.py::test_regex_chooser[2-([-+]?\\\\d+|[\\xb2\\xb3\\xb9\\u1369\\u136a\\u136b\\u136c\\u136d\\u136e\\u136f\\u1370\\u1371\\u19da\\u2070\\u2074\\u2075\\u2076\\u2077\\u2078\\u2079\\u2080\\u2081\\u2082\\u2083\\u2084\\u2085\\u2086\\u2087\\u2088\\u2089\\u2460\\u2461\\u2462\\u2463\\u2464\\u2465\\u2466\\u2467\\u2468\\u2474\\u2475\\u2476\\u2477\\u2478\\u2479\\u247a\\u247b\\u247c\\u2488\\u2489\\u248a\\u248b\\u248c\\u248d\\u248e\\u248f\\u2490\\u24ea\\u24f5\\u24f6\\u24f7\\u24f8\\u24f9\\u24fa\\u24fb\\u24fc\\u24fd\\u24ff\\u2776\\u2777\\u2778\\u2779\\u277a\\u277b\\u277c\\u277d\\u277e\\u2780\\u2781\\u2782\\u2783\\u2784\\u2785\\u2786\\u2787\\u2788\\u278a\\u278b\\u278c\\u278d\\u278e\\u278f\\u2790\\u2791\\u2792\\U00010a40\\U00010a41\\U00010a42\\U00010a43\\U00010e60\\U00010e61\\U00010e62\\U00010e63\\U00010e64\\U00010e65\\U00010e66\\U00010e67\\U00010e68\\U00011052\\U00011053\\U00011054\\U00011055\\U00011056\\U00011057\\U00011058\\U00011059\\U0001105a\\U0001f100\\U0001f101\\U0001f102\\U0001f103\\U0001f104\\U0001f105\\U0001f106\\U0001f107\\U0001f108\\U0001f109\\U0001f10a])]",
"tests/test_regex.py::test_regex_splits_correctly[a1b2c3d4e5e6-float_sign_noexp]",
"tests/test_regex.py::test_regex_splits_correctly[-123.45e+67-int_nosign]"
] | [] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2019-11-08T06:21:49Z" | mit |
|
SethMMorton__natsort-143 | diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0077605..159b16c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,6 +1,9 @@
Unreleased
---
+### Fixed
+- Bug where sorting paths fail if one of the paths is '.'.
+
[8.0.1] - 2021-12-10
---
diff --git a/natsort/utils.py b/natsort/utils.py
index c9448b4..8d56b06 100644
--- a/natsort/utils.py
+++ b/natsort/utils.py
@@ -887,7 +887,11 @@ def path_splitter(
s = PurePath(s)
# Split the path into parts.
- *path_parts, base = s.parts
+ try:
+ *path_parts, base = s.parts
+ except ValueError:
+ path_parts = []
+ base = str(s)
# Now, split off the file extensions until we reach a decimal number at
# the beginning of the suffix or there are no more extensions.
| SethMMorton/natsort | e76935512110ab03b06ec173273217438a450fb7 | diff --git a/tests/test_utils.py b/tests/test_utils.py
index 38df303..bb229b9 100644
--- a/tests/test_utils.py
+++ b/tests/test_utils.py
@@ -141,6 +141,14 @@ def test_path_splitter_splits_path_string_by_sep_example() -> None:
assert tuple(utils.path_splitter(pathlib.Path(given))) == tuple(expected)
[email protected]("given", [".", "./", "./././", ".\\"])
+def test_path_splitter_handles_dot_properly(given: str) -> None:
+ # https://github.com/SethMMorton/natsort/issues/142
+ expected = (os.path.normpath(given),)
+ assert tuple(utils.path_splitter(given)) == expected
+ assert tuple(utils.path_splitter(pathlib.Path(given))) == expected
+
+
@given(lists(sampled_from(string.ascii_letters), min_size=2).filter(all))
def test_path_splitter_splits_path_string_by_sep(x: List[str]) -> None:
z = str(pathlib.Path(*x))
| `os_sorted` fails to sort current directory
**Describe the bug**
`ValueError` is raised when sorting current directory `'.'` or `'./'` or `'.\\'`.
**Expected behavior**
The current directory should be sorted correctly without error.
**Environment (please complete the following information):**
- Python Version: 3.9
- OS: both Windows and Ubuntu
- If the bug involves `LOCALE` or `humansorted`:
- Is `PyICU` installed? No
- Do you have a locale set? If so, to what? No
**To Reproduce**
```python
Python 3.9.7 (tags/v3.9.7:1016ef3, Aug 30 2021, 20:19:38) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from natsort import os_sorted
>>> os_sorted(['.'])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "D:\Software\Python39\lib\site-packages\natsort\natsort.py", line 929, in os_sorted
return sorted(seq, key=os_sort_keygen(key), reverse=reverse)
File "D:\Software\Python39\lib\site-packages\natsort\natsort.py", line 786, in <lambda>
OSSortKeyType, lambda x: tuple(map(_winsort_key, _split_apply(x, key)))
File "D:\Software\Python39\lib\site-packages\natsort\natsort.py", line 770, in _split_apply
return utils.path_splitter(str(v))
File "D:\Software\Python39\lib\site-packages\natsort\utils.py", line 890, in path_splitter
*path_parts, base = s.parts
ValueError: not enough values to unpack (expected at least 1, got 0)
```
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_utils.py::test_path_splitter_handles_dot_properly[./././]",
"tests/test_utils.py::test_path_splitter_handles_dot_properly[.]",
"tests/test_utils.py::test_path_splitter_handles_dot_properly[./]"
] | [
"tests/test_utils.py::test_ns_enum_values_and_aliases[ns.DEFAULT-0_0]",
"tests/test_utils.py::test_ns_enum_values_and_aliases[ns.DEFAULT-ns.DEFAULT0]",
"tests/test_utils.py::test_regex_chooser_returns_correct_regular_expression_object[6-([-+]?\\\\d+|[\\xb2\\xb3\\xb9\\u1369\\u136a\\u136b\\u136c\\u136d\\u136e\\u136f\\u1370\\u1371\\u19da\\u2070\\u2074\\u2075\\u2076\\u2077\\u2078\\u2079\\u2080\\u2081\\u2082\\u2083\\u2084\\u2085\\u2086\\u2087\\u2088\\u2089\\u2460\\u2461\\u2462\\u2463\\u2464\\u2465\\u2466\\u2467\\u2468\\u2474\\u2475\\u2476\\u2477\\u2478\\u2479\\u247a\\u247b\\u247c\\u2488\\u2489\\u248a\\u248b\\u248c\\u248d\\u248e\\u248f\\u2490\\u24ea\\u24f5\\u24f6\\u24f7\\u24f8\\u24f9\\u24fa\\u24fb\\u24fc\\u24fd\\u24ff\\u2776\\u2777\\u2778\\u2779\\u277a\\u277b\\u277c\\u277d\\u277e\\u2780\\u2781\\u2782\\u2783\\u2784\\u2785\\u2786\\u2787\\u2788\\u278a\\u278b\\u278c\\u278d\\u278e\\u278f\\u2790\\u2791\\u2792\\U00010a40\\U00010a41\\U00010a42\\U00010a43\\U00010e60\\U00010e61\\U00010e62\\U00010e63\\U00010e64\\U00010e65\\U00010e66\\U00010e67\\U00010e68\\U00011052\\U00011053\\U00011054\\U00011055\\U00011056\\U00011057\\U00011058\\U00011059\\U0001105a\\U0001f100\\U0001f101\\U0001f102\\U0001f103\\U0001f104\\U0001f105\\U0001f106\\U0001f107\\U0001f108\\U0001f109\\U0001f10a])]",
"tests/test_utils.py::test_regex_chooser_returns_correct_regular_expression_object[4-(\\\\d+|[\\xb2\\xb3\\xb9\\u1369\\u136a\\u136b\\u136c\\u136d\\u136e\\u136f\\u1370\\u1371\\u19da\\u2070\\u2074\\u2075\\u2076\\u2077\\u2078\\u2079\\u2080\\u2081\\u2082\\u2083\\u2084\\u2085\\u2086\\u2087\\u2088\\u2089\\u2460\\u2461\\u2462\\u2463\\u2464\\u2465\\u2466\\u2467\\u2468\\u2474\\u2475\\u2476\\u2477\\u2478\\u2479\\u247a\\u247b\\u247c\\u2488\\u2489\\u248a\\u248b\\u248c\\u248d\\u248e\\u248f\\u2490\\u24ea\\u24f5\\u24f6\\u24f7\\u24f8\\u24f9\\u24fa\\u24fb\\u24fc\\u24fd\\u24ff\\u2776\\u2777\\u2778\\u2779\\u277a\\u277b\\u277c\\u277d\\u277e\\u2780\\u2781\\u2782\\u2783\\u2784\\u2785\\u2786\\u2787\\u2788\\u278a\\u278b\\u278c\\u278d\\u278e\\u278f\\u2790\\u2791\\u2792\\U00010a40\\U00010a41\\U00010a42\\U00010a43\\U00010e60\\U00010e61\\U00010e62\\U00010e63\\U00010e64\\U00010e65\\U00010e66\\U00010e67\\U00010e68\\U00011052\\U00011053\\U00011054\\U00011055\\U00011056\\U00011057\\U00011058\\U00011059\\U0001105a\\U0001f100\\U0001f101\\U0001f102\\U0001f103\\U0001f104\\U0001f105\\U0001f106\\U0001f107\\U0001f108\\U0001f109\\U0001f10a])]",
"tests/test_utils.py::test_path_splitter_splits_path_string_by_sep_and_removes_extension_example",
"tests/test_utils.py::test_ns_enum_values_and_aliases[ns.DEFAULT-0_2]",
"tests/test_utils.py::test_chain_functions_is_a_no_op_if_no_functions_are_given",
"tests/test_utils.py::test_regex_chooser_returns_correct_regular_expression_object[7-([-+]?(?:\\\\d+\\\\.?\\\\d*|\\\\.\\\\d+)|[\\xb2\\xb3\\xb9\\xbc\\xbd\\xbe\\u09f4\\u09f5\\u09f6\\u09f7\\u09f8\\u09f9\\u0b72\\u0b73\\u0b74\\u0b75\\u0b76\\u0b77\\u0bf0\\u0bf1\\u0bf2\\u0c78\\u0c79\\u0c7a\\u0c7b\\u0c7c\\u0c7d\\u0c7e\\u0d58\\u0d59\\u0d5a\\u0d5b\\u0d5c\\u0d5d\\u0d5e\\u0d70\\u0d71\\u0d72\\u0d73\\u0d74\\u0d75\\u0d76\\u0d77\\u0d78\\u0f2a\\u0f2b\\u0f2c\\u0f2d\\u0f2e\\u0f2f\\u0f30\\u0f31\\u0f32\\u0f33\\u1369\\u136a\\u136b\\u136c\\u136d\\u136e\\u136f\\u1370\\u1371\\u1372\\u1373\\u1374\\u1375\\u1376\\u1377\\u1378\\u1379\\u137a\\u137b\\u137c\\u16ee\\u16ef\\u16f0\\u17f0\\u17f1\\u17f2\\u17f3\\u17f4\\u17f5\\u17f6\\u17f7\\u17f8\\u17f9\\u19da\\u2070\\u2074\\u2075\\u2076\\u2077\\u2078\\u2079\\u2080\\u2081\\u2082\\u2083\\u2084\\u2085\\u2086\\u2087\\u2088\\u2089\\u2150\\u2151\\u2152\\u2153\\u2154\\u2155\\u2156\\u2157\\u2158\\u2159\\u215a\\u215b\\u215c\\u215d\\u215e\\u215f\\u2160\\u2161\\u2162\\u2163\\u2164\\u2165\\u2166\\u2167\\u2168\\u2169\\u216a\\u216b\\u216c\\u216d\\u216e\\u216f\\u2170\\u2171\\u2172\\u2173\\u2174\\u2175\\u2176\\u2177\\u2178\\u2179\\u217a\\u217b\\u217c\\u217d\\u217e\\u217f\\u2180\\u2181\\u2182\\u2185\\u2186\\u2187\\u2188\\u2189\\u2460\\u2461\\u2462\\u2463\\u2464\\u2465\\u2466\\u2467\\u2468\\u2469\\u246a\\u246b\\u246c\\u246d\\u246e\\u246f\\u2470\\u2471\\u2472\\u2473\\u2474\\u2475\\u2476\\u2477\\u2478\\u2479\\u247a\\u247b\\u247c\\u247d\\u247e\\u247f\\u2480\\u2481\\u2482\\u2483\\u2484\\u2485\\u2486\\u2487\\u2488\\u2489\\u248a\\u248b\\u248c\\u248d\\u248e\\u248f\\u2490\\u2491\\u2492\\u2493\\u2494\\u2495\\u2496\\u2497\\u2498\\u2499\\u249a\\u249b\\u24ea\\u24eb\\u24ec\\u24ed\\u24ee\\u24ef\\u24f0\\u24f1\\u24f2\\u24f3\\u24f4\\u24f5\\u24f6\\u24f7\\u24f8\\u24f9\\u24fa\\u24fb\\u24fc\\u24fd\\u24fe\\u24ff\\u2776\\u2777\\u2778\\u2779\\u277a\\u277b\\u277c\\u277d\\u277e\\u277f\\u2780\\u2781\\u2782\\u2783\\u2784\\u2785\\u2786\\u2787\\u2788\\u2789\\u278a\\u278b\\u278c\\u278d\\u278e\\u278f\\u2790\\u2791\\u2792\\u2793\\u2cfd\\u3007\\u3021\\u3022\\u3023\\u3024\\u3025\\u3026\\u3027\\u3028\\u3029\\u3038\\u3039\\u303a\\u3192\\u3193\\u3194\\u3195\\u3220\\u3221\\u3222\\u3223\\u3224\\u3225\\u3226\\u3227\\u3228\\u3229\\u3248\\u3249\\u324a\\u324b\\u324c\\u324d\\u324e\\u324f\\u3251\\u3252\\u3253\\u3254\\u3255\\u3256\\u3257\\u3258\\u3259\\u325a\\u325b\\u325c\\u325d\\u325e\\u325f\\u3280\\u3281\\u3282\\u3283\\u3284\\u3285\\u3286\\u3287\\u3288\\u3289\\u32b1\\u32b2\\u32b3\\u32b4\\u32b5\\u32b6\\u32b7\\u32b8\\u32b9\\u32ba\\u32bb\\u32bc\\u32bd\\u32be\\u32bf\\u3405\\u3483\\u382a\\u3b4d\\u4e00\\u4e03\\u4e07\\u4e09\\u4e5d\\u4e8c\\u4e94\\u4e96\\u4ebf\\u4ec0\\u4edf\\u4ee8\\u4f0d\\u4f70\\u5104\\u5146\\u5169\\u516b\\u516d\\u5341\\u5343\\u5344\\u5345\\u534c\\u53c1\\u53c2\\u53c3\\u53c4\\u56db\\u58f1\\u58f9\\u5e7a\\u5efe\\u5eff\\u5f0c\\u5f0d\\u5f0e\\u5f10\\u62fe\\u634c\\u67d2\\u6f06\\u7396\\u767e\\u8086\\u842c\\u8cae\\u8cb3\\u8d30\\u9621\\u9646\\u964c\\u9678\\u96f6\\ua6e6\\ua6e7\\ua6e8\\ua6e9\\ua6ea\\ua6eb\\ua6ec\\ua6ed\\ua6ee\\ua6ef\\ua830\\ua831\\ua832\\ua833\\ua834\\ua835\\uf96b\\uf973\\uf978\\uf9b2\\uf9d1\\uf9d3\\uf9fd\\U00010107\\U00010108\\U00010109\\U0001010a\\U0001010b\\U0001010c\\U0001010d\\U0001010e\\U0001010f\\U00010110\\U00010111\\U00010112\\U00010113\\U00010114\\U00010115\\U00010116\\U00010117\\U00010118\\U00010119\\U0001011a\\U0001011b\\U0001011c\\U0001011d\\U0001011e\\U0001011f\\U00010120\\U00010121\\U00010122\\U00010123\\U00010124\\U00010125\\U00010126\\U00010127\\U00010128\\U00010129\\U0001012a\\U0001012b\\U0001012c\\U0001012d\\U0001012e\\U0001012f\\U00010130\\U00010131\\U00010132\\U00010133\\U00010140\\U00010141\\U00010142\\U00010143\\U00010144\\U00010145\\U00010146\\U00010147\\U00010148\\U00010149\\U0001014a\\U0001014b\\U0001014c\\U0001014d\\U0001014e\\U0001014f\\U00010150\\U00010151\\U00010152\\U00010153\\U00010154\\U00010155\\U00010156\\U00010157\\U00010158\\U00010159\\U0001015a\\U0001015b\\U0001015c\\U0001015d\\U0001015e\\U0001015f\\U00010160\\U00010161\\U00010162\\U00010163\\U00010164\\U00010165\\U00010166\\U00010167\\U00010168\\U00010169\\U0001016a\\U0001016b\\U0001016c\\U0001016d\\U0001016e\\U0001016f\\U00010170\\U00010171\\U00010172\\U00010173\\U00010174\\U00010175\\U00010176\\U00010177\\U00010178\\U0001018a\\U0001018b\\U000102e1\\U000102e2\\U000102e3\\U000102e4\\U000102e5\\U000102e6\\U000102e7\\U000102e8\\U000102e9\\U000102ea\\U000102eb\\U000102ec\\U000102ed\\U000102ee\\U000102ef\\U000102f0\\U000102f1\\U000102f2\\U000102f3\\U000102f4\\U000102f5\\U000102f6\\U000102f7\\U000102f8\\U000102f9\\U000102fa\\U000102fb\\U00010320\\U00010321\\U00010322\\U00010323\\U00010341\\U0001034a\\U000103d1\\U000103d2\\U000103d3\\U000103d4\\U000103d5\\U00010858\\U00010859\\U0001085a\\U0001085b\\U0001085c\\U0001085d\\U0001085e\\U0001085f\\U00010879\\U0001087a\\U0001087b\\U0001087c\\U0001087d\\U0001087e\\U0001087f\\U000108a7\\U000108a8\\U000108a9\\U000108aa\\U000108ab\\U000108ac\\U000108ad\\U000108ae\\U000108af\\U000108fb\\U000108fc\\U000108fd\\U000108fe\\U000108ff\\U00010916\\U00010917\\U00010918\\U00010919\\U0001091a\\U0001091b\\U000109bc\\U000109bd\\U000109c0\\U000109c1\\U000109c2\\U000109c3\\U000109c4\\U000109c5\\U000109c6\\U000109c7\\U000109c8\\U000109c9\\U000109ca\\U000109cb\\U000109cc\\U000109cd\\U000109ce\\U000109cf\\U000109d2\\U000109d3\\U000109d4\\U000109d5\\U000109d6\\U000109d7\\U000109d8\\U000109d9\\U000109da\\U000109db\\U000109dc\\U000109dd\\U000109de\\U000109df\\U000109e0\\U000109e1\\U000109e2\\U000109e3\\U000109e4\\U000109e5\\U000109e6\\U000109e7\\U000109e8\\U000109e9\\U000109ea\\U000109eb\\U000109ec\\U000109ed\\U000109ee\\U000109ef\\U000109f0\\U000109f1\\U000109f2\\U000109f3\\U000109f4\\U000109f5\\U000109f6\\U000109f7\\U000109f8\\U000109f9\\U000109fa\\U000109fb\\U000109fc\\U000109fd\\U000109fe\\U000109ff\\U00010a40\\U00010a41\\U00010a42\\U00010a43\\U00010a44\\U00010a45\\U00010a46\\U00010a47\\U00010a48\\U00010a7d\\U00010a7e\\U00010a9d\\U00010a9e\\U00010a9f\\U00010aeb\\U00010aec\\U00010aed\\U00010aee\\U00010aef\\U00010b58\\U00010b59\\U00010b5a\\U00010b5b\\U00010b5c\\U00010b5d\\U00010b5e\\U00010b5f\\U00010b78\\U00010b79\\U00010b7a\\U00010b7b\\U00010b7c\\U00010b7d\\U00010b7e\\U00010b7f\\U00010ba9\\U00010baa\\U00010bab\\U00010bac\\U00010bad\\U00010bae\\U00010baf\\U00010cfa\\U00010cfb\\U00010cfc\\U00010cfd\\U00010cfe\\U00010cff\\U00010e60\\U00010e61\\U00010e62\\U00010e63\\U00010e64\\U00010e65\\U00010e66\\U00010e67\\U00010e68\\U00010e69\\U00010e6a\\U00010e6b\\U00010e6c\\U00010e6d\\U00010e6e\\U00010e6f\\U00010e70\\U00010e71\\U00010e72\\U00010e73\\U00010e74\\U00010e75\\U00010e76\\U00010e77\\U00010e78\\U00010e79\\U00010e7a\\U00010e7b\\U00010e7c\\U00010e7d\\U00010e7e\\U00010f1d\\U00010f1e\\U00010f1f\\U00010f20\\U00010f21\\U00010f22\\U00010f23\\U00010f24\\U00010f25\\U00010f26\\U00010f51\\U00010f52\\U00010f53\\U00010f54\\U00010fc5\\U00010fc6\\U00010fc7\\U00010fc8\\U00010fc9\\U00010fca\\U00010fcb\\U00011052\\U00011053\\U00011054\\U00011055\\U00011056\\U00011057\\U00011058\\U00011059\\U0001105a\\U0001105b\\U0001105c\\U0001105d\\U0001105e\\U0001105f\\U00011060\\U00011061\\U00011062\\U00011063\\U00011064\\U00011065\\U000111e1\\U000111e2\\U000111e3\\U000111e4\\U000111e5\\U000111e6\\U000111e7\\U000111e8\\U000111e9\\U000111ea\\U000111eb\\U000111ec\\U000111ed\\U000111ee\\U000111ef\\U000111f0\\U000111f1\\U000111f2\\U000111f3\\U000111f4\\U0001173a\\U0001173b\\U000118ea\\U000118eb\\U000118ec\\U000118ed\\U000118ee\\U000118ef\\U000118f0\\U000118f1\\U000118f2\\U00011c5a\\U00011c5b\\U00011c5c\\U00011c5d\\U00011c5e\\U00011c5f\\U00011c60\\U00011c61\\U00011c62\\U00011c63\\U00011c64\\U00011c65\\U00011c66\\U00011c67\\U00011c68\\U00011c69\\U00011c6a\\U00011c6b\\U00011c6c\\U00011fc0\\U00011fc1\\U00011fc2\\U00011fc3\\U00011fc4\\U00011fc5\\U00011fc6\\U00011fc7\\U00011fc8\\U00011fc9\\U00011fca\\U00011fcb\\U00011fcc\\U00011fcd\\U00011fce\\U00011fcf\\U00011fd0\\U00011fd1\\U00011fd2\\U00011fd3\\U00011fd4\\U00012400\\U00012401\\U00012402\\U00012403\\U00012404\\U00012405\\U00012406\\U00012407\\U00012408\\U00012409\\U0001240a\\U0001240b\\U0001240c\\U0001240d\\U0001240e\\U0001240f\\U00012410\\U00012411\\U00012412\\U00012413\\U00012414\\U00012415\\U00012416\\U00012417\\U00012418\\U00012419\\U0001241a\\U0001241b\\U0001241c\\U0001241d\\U0001241e\\U0001241f\\U00012420\\U00012421\\U00012422\\U00012423\\U00012424\\U00012425\\U00012426\\U00012427\\U00012428\\U00012429\\U0001242a\\U0001242b\\U0001242c\\U0001242d\\U0001242e\\U0001242f\\U00012430\\U00012431\\U00012432\\U00012433\\U00012434\\U00012435\\U00012436\\U00012437\\U00012438\\U00012439\\U0001243a\\U0001243b\\U0001243c\\U0001243d\\U0001243e\\U0001243f\\U00012440\\U00012441\\U00012442\\U00012443\\U00012444\\U00012445\\U00012446\\U00012447\\U00012448\\U00012449\\U0001244a\\U0001244b\\U0001244c\\U0001244d\\U0001244e\\U0001244f\\U00012450\\U00012451\\U00012452\\U00012453\\U00012454\\U00012455\\U00012456\\U00012457\\U00012458\\U00012459\\U0001245a\\U0001245b\\U0001245c\\U0001245d\\U0001245e\\U0001245f\\U00012460\\U00012461\\U00012462\\U00012463\\U00012464\\U00012465\\U00012466\\U00012467\\U00012468\\U00012469\\U0001246a\\U0001246b\\U0001246c\\U0001246d\\U0001246e\\U00016b5b\\U00016b5c\\U00016b5d\\U00016b5e\\U00016b5f\\U00016b60\\U00016b61\\U00016e80\\U00016e81\\U00016e82\\U00016e83\\U00016e84\\U00016e85\\U00016e86\\U00016e87\\U00016e88\\U00016e89\\U00016e8a\\U00016e8b\\U00016e8c\\U00016e8d\\U00016e8e\\U00016e8f\\U00016e90\\U00016e91\\U00016e92\\U00016e93\\U00016e94\\U00016e95\\U00016e96\\U0001d2e0\\U0001d2e1\\U0001d2e2\\U0001d2e3\\U0001d2e4\\U0001d2e5\\U0001d2e6\\U0001d2e7\\U0001d2e8\\U0001d2e9\\U0001d2ea\\U0001d2eb\\U0001d2ec\\U0001d2ed\\U0001d2ee\\U0001d2ef\\U0001d2f0\\U0001d2f1\\U0001d2f2\\U0001d2f3\\U0001d360\\U0001d361\\U0001d362\\U0001d363\\U0001d364\\U0001d365\\U0001d366\\U0001d367\\U0001d368\\U0001d369\\U0001d36a\\U0001d36b\\U0001d36c\\U0001d36d\\U0001d36e\\U0001d36f\\U0001d370\\U0001d371\\U0001d372\\U0001d373\\U0001d374\\U0001d375\\U0001d376\\U0001d377\\U0001d378\\U0001e8c7\\U0001e8c8\\U0001e8c9\\U0001e8ca\\U0001e8cb\\U0001e8cc\\U0001e8cd\\U0001e8ce\\U0001e8cf\\U0001ec71\\U0001ec72\\U0001ec73\\U0001ec74\\U0001ec75\\U0001ec76\\U0001ec77\\U0001ec78\\U0001ec79\\U0001ec7a\\U0001ec7b\\U0001ec7c\\U0001ec7d\\U0001ec7e\\U0001ec7f\\U0001ec80\\U0001ec81\\U0001ec82\\U0001ec83\\U0001ec84\\U0001ec85\\U0001ec86\\U0001ec87\\U0001ec88\\U0001ec89\\U0001ec8a\\U0001ec8b\\U0001ec8c\\U0001ec8d\\U0001ec8e\\U0001ec8f\\U0001ec90\\U0001ec91\\U0001ec92\\U0001ec93\\U0001ec94\\U0001ec95\\U0001ec96\\U0001ec97\\U0001ec98\\U0001ec99\\U0001ec9a\\U0001ec9b\\U0001ec9c\\U0001ec9d\\U0001ec9e\\U0001ec9f\\U0001eca0\\U0001eca1\\U0001eca2\\U0001eca3\\U0001eca4\\U0001eca5\\U0001eca6\\U0001eca7\\U0001eca8\\U0001eca9\\U0001ecaa\\U0001ecab\\U0001ecad\\U0001ecae\\U0001ecaf\\U0001ecb1\\U0001ecb2\\U0001ecb3\\U0001ecb4\\U0001ed01\\U0001ed02\\U0001ed03\\U0001ed04\\U0001ed05\\U0001ed06\\U0001ed07\\U0001ed08\\U0001ed09\\U0001ed0a\\U0001ed0b\\U0001ed0c\\U0001ed0d\\U0001ed0e\\U0001ed0f\\U0001ed10\\U0001ed11\\U0001ed12\\U0001ed13\\U0001ed14\\U0001ed15\\U0001ed16\\U0001ed17\\U0001ed18\\U0001ed19\\U0001ed1a\\U0001ed1b\\U0001ed1c\\U0001ed1d\\U0001ed1e\\U0001ed1f\\U0001ed20\\U0001ed21\\U0001ed22\\U0001ed23\\U0001ed24\\U0001ed25\\U0001ed26\\U0001ed27\\U0001ed28\\U0001ed29\\U0001ed2a\\U0001ed2b\\U0001ed2c\\U0001ed2d\\U0001ed2f\\U0001ed30\\U0001ed31\\U0001ed32\\U0001ed33\\U0001ed34\\U0001ed35\\U0001ed36\\U0001ed37\\U0001ed38\\U0001ed39\\U0001ed3a\\U0001ed3b\\U0001ed3c\\U0001ed3d\\U0001f100\\U0001f101\\U0001f102\\U0001f103\\U0001f104\\U0001f105\\U0001f106\\U0001f107\\U0001f108\\U0001f109\\U0001f10a\\U0001f10b\\U0001f10c\\U00020001\\U00020064\\U000200e2\\U00020121\\U0002092a\\U00020983\\U0002098c\\U0002099c\\U00020aea\\U00020afd\\U00020b19\\U00022390\\U00022998\\U00023b1b\\U0002626d\\U0002f890])]",
"tests/test_utils.py::test_regex_chooser_returns_correct_regular_expression_object[5-((?:\\\\d+\\\\.?\\\\d*|\\\\.\\\\d+)|[\\xb2\\xb3\\xb9\\xbc\\xbd\\xbe\\u09f4\\u09f5\\u09f6\\u09f7\\u09f8\\u09f9\\u0b72\\u0b73\\u0b74\\u0b75\\u0b76\\u0b77\\u0bf0\\u0bf1\\u0bf2\\u0c78\\u0c79\\u0c7a\\u0c7b\\u0c7c\\u0c7d\\u0c7e\\u0d58\\u0d59\\u0d5a\\u0d5b\\u0d5c\\u0d5d\\u0d5e\\u0d70\\u0d71\\u0d72\\u0d73\\u0d74\\u0d75\\u0d76\\u0d77\\u0d78\\u0f2a\\u0f2b\\u0f2c\\u0f2d\\u0f2e\\u0f2f\\u0f30\\u0f31\\u0f32\\u0f33\\u1369\\u136a\\u136b\\u136c\\u136d\\u136e\\u136f\\u1370\\u1371\\u1372\\u1373\\u1374\\u1375\\u1376\\u1377\\u1378\\u1379\\u137a\\u137b\\u137c\\u16ee\\u16ef\\u16f0\\u17f0\\u17f1\\u17f2\\u17f3\\u17f4\\u17f5\\u17f6\\u17f7\\u17f8\\u17f9\\u19da\\u2070\\u2074\\u2075\\u2076\\u2077\\u2078\\u2079\\u2080\\u2081\\u2082\\u2083\\u2084\\u2085\\u2086\\u2087\\u2088\\u2089\\u2150\\u2151\\u2152\\u2153\\u2154\\u2155\\u2156\\u2157\\u2158\\u2159\\u215a\\u215b\\u215c\\u215d\\u215e\\u215f\\u2160\\u2161\\u2162\\u2163\\u2164\\u2165\\u2166\\u2167\\u2168\\u2169\\u216a\\u216b\\u216c\\u216d\\u216e\\u216f\\u2170\\u2171\\u2172\\u2173\\u2174\\u2175\\u2176\\u2177\\u2178\\u2179\\u217a\\u217b\\u217c\\u217d\\u217e\\u217f\\u2180\\u2181\\u2182\\u2185\\u2186\\u2187\\u2188\\u2189\\u2460\\u2461\\u2462\\u2463\\u2464\\u2465\\u2466\\u2467\\u2468\\u2469\\u246a\\u246b\\u246c\\u246d\\u246e\\u246f\\u2470\\u2471\\u2472\\u2473\\u2474\\u2475\\u2476\\u2477\\u2478\\u2479\\u247a\\u247b\\u247c\\u247d\\u247e\\u247f\\u2480\\u2481\\u2482\\u2483\\u2484\\u2485\\u2486\\u2487\\u2488\\u2489\\u248a\\u248b\\u248c\\u248d\\u248e\\u248f\\u2490\\u2491\\u2492\\u2493\\u2494\\u2495\\u2496\\u2497\\u2498\\u2499\\u249a\\u249b\\u24ea\\u24eb\\u24ec\\u24ed\\u24ee\\u24ef\\u24f0\\u24f1\\u24f2\\u24f3\\u24f4\\u24f5\\u24f6\\u24f7\\u24f8\\u24f9\\u24fa\\u24fb\\u24fc\\u24fd\\u24fe\\u24ff\\u2776\\u2777\\u2778\\u2779\\u277a\\u277b\\u277c\\u277d\\u277e\\u277f\\u2780\\u2781\\u2782\\u2783\\u2784\\u2785\\u2786\\u2787\\u2788\\u2789\\u278a\\u278b\\u278c\\u278d\\u278e\\u278f\\u2790\\u2791\\u2792\\u2793\\u2cfd\\u3007\\u3021\\u3022\\u3023\\u3024\\u3025\\u3026\\u3027\\u3028\\u3029\\u3038\\u3039\\u303a\\u3192\\u3193\\u3194\\u3195\\u3220\\u3221\\u3222\\u3223\\u3224\\u3225\\u3226\\u3227\\u3228\\u3229\\u3248\\u3249\\u324a\\u324b\\u324c\\u324d\\u324e\\u324f\\u3251\\u3252\\u3253\\u3254\\u3255\\u3256\\u3257\\u3258\\u3259\\u325a\\u325b\\u325c\\u325d\\u325e\\u325f\\u3280\\u3281\\u3282\\u3283\\u3284\\u3285\\u3286\\u3287\\u3288\\u3289\\u32b1\\u32b2\\u32b3\\u32b4\\u32b5\\u32b6\\u32b7\\u32b8\\u32b9\\u32ba\\u32bb\\u32bc\\u32bd\\u32be\\u32bf\\u3405\\u3483\\u382a\\u3b4d\\u4e00\\u4e03\\u4e07\\u4e09\\u4e5d\\u4e8c\\u4e94\\u4e96\\u4ebf\\u4ec0\\u4edf\\u4ee8\\u4f0d\\u4f70\\u5104\\u5146\\u5169\\u516b\\u516d\\u5341\\u5343\\u5344\\u5345\\u534c\\u53c1\\u53c2\\u53c3\\u53c4\\u56db\\u58f1\\u58f9\\u5e7a\\u5efe\\u5eff\\u5f0c\\u5f0d\\u5f0e\\u5f10\\u62fe\\u634c\\u67d2\\u6f06\\u7396\\u767e\\u8086\\u842c\\u8cae\\u8cb3\\u8d30\\u9621\\u9646\\u964c\\u9678\\u96f6\\ua6e6\\ua6e7\\ua6e8\\ua6e9\\ua6ea\\ua6eb\\ua6ec\\ua6ed\\ua6ee\\ua6ef\\ua830\\ua831\\ua832\\ua833\\ua834\\ua835\\uf96b\\uf973\\uf978\\uf9b2\\uf9d1\\uf9d3\\uf9fd\\U00010107\\U00010108\\U00010109\\U0001010a\\U0001010b\\U0001010c\\U0001010d\\U0001010e\\U0001010f\\U00010110\\U00010111\\U00010112\\U00010113\\U00010114\\U00010115\\U00010116\\U00010117\\U00010118\\U00010119\\U0001011a\\U0001011b\\U0001011c\\U0001011d\\U0001011e\\U0001011f\\U00010120\\U00010121\\U00010122\\U00010123\\U00010124\\U00010125\\U00010126\\U00010127\\U00010128\\U00010129\\U0001012a\\U0001012b\\U0001012c\\U0001012d\\U0001012e\\U0001012f\\U00010130\\U00010131\\U00010132\\U00010133\\U00010140\\U00010141\\U00010142\\U00010143\\U00010144\\U00010145\\U00010146\\U00010147\\U00010148\\U00010149\\U0001014a\\U0001014b\\U0001014c\\U0001014d\\U0001014e\\U0001014f\\U00010150\\U00010151\\U00010152\\U00010153\\U00010154\\U00010155\\U00010156\\U00010157\\U00010158\\U00010159\\U0001015a\\U0001015b\\U0001015c\\U0001015d\\U0001015e\\U0001015f\\U00010160\\U00010161\\U00010162\\U00010163\\U00010164\\U00010165\\U00010166\\U00010167\\U00010168\\U00010169\\U0001016a\\U0001016b\\U0001016c\\U0001016d\\U0001016e\\U0001016f\\U00010170\\U00010171\\U00010172\\U00010173\\U00010174\\U00010175\\U00010176\\U00010177\\U00010178\\U0001018a\\U0001018b\\U000102e1\\U000102e2\\U000102e3\\U000102e4\\U000102e5\\U000102e6\\U000102e7\\U000102e8\\U000102e9\\U000102ea\\U000102eb\\U000102ec\\U000102ed\\U000102ee\\U000102ef\\U000102f0\\U000102f1\\U000102f2\\U000102f3\\U000102f4\\U000102f5\\U000102f6\\U000102f7\\U000102f8\\U000102f9\\U000102fa\\U000102fb\\U00010320\\U00010321\\U00010322\\U00010323\\U00010341\\U0001034a\\U000103d1\\U000103d2\\U000103d3\\U000103d4\\U000103d5\\U00010858\\U00010859\\U0001085a\\U0001085b\\U0001085c\\U0001085d\\U0001085e\\U0001085f\\U00010879\\U0001087a\\U0001087b\\U0001087c\\U0001087d\\U0001087e\\U0001087f\\U000108a7\\U000108a8\\U000108a9\\U000108aa\\U000108ab\\U000108ac\\U000108ad\\U000108ae\\U000108af\\U000108fb\\U000108fc\\U000108fd\\U000108fe\\U000108ff\\U00010916\\U00010917\\U00010918\\U00010919\\U0001091a\\U0001091b\\U000109bc\\U000109bd\\U000109c0\\U000109c1\\U000109c2\\U000109c3\\U000109c4\\U000109c5\\U000109c6\\U000109c7\\U000109c8\\U000109c9\\U000109ca\\U000109cb\\U000109cc\\U000109cd\\U000109ce\\U000109cf\\U000109d2\\U000109d3\\U000109d4\\U000109d5\\U000109d6\\U000109d7\\U000109d8\\U000109d9\\U000109da\\U000109db\\U000109dc\\U000109dd\\U000109de\\U000109df\\U000109e0\\U000109e1\\U000109e2\\U000109e3\\U000109e4\\U000109e5\\U000109e6\\U000109e7\\U000109e8\\U000109e9\\U000109ea\\U000109eb\\U000109ec\\U000109ed\\U000109ee\\U000109ef\\U000109f0\\U000109f1\\U000109f2\\U000109f3\\U000109f4\\U000109f5\\U000109f6\\U000109f7\\U000109f8\\U000109f9\\U000109fa\\U000109fb\\U000109fc\\U000109fd\\U000109fe\\U000109ff\\U00010a40\\U00010a41\\U00010a42\\U00010a43\\U00010a44\\U00010a45\\U00010a46\\U00010a47\\U00010a48\\U00010a7d\\U00010a7e\\U00010a9d\\U00010a9e\\U00010a9f\\U00010aeb\\U00010aec\\U00010aed\\U00010aee\\U00010aef\\U00010b58\\U00010b59\\U00010b5a\\U00010b5b\\U00010b5c\\U00010b5d\\U00010b5e\\U00010b5f\\U00010b78\\U00010b79\\U00010b7a\\U00010b7b\\U00010b7c\\U00010b7d\\U00010b7e\\U00010b7f\\U00010ba9\\U00010baa\\U00010bab\\U00010bac\\U00010bad\\U00010bae\\U00010baf\\U00010cfa\\U00010cfb\\U00010cfc\\U00010cfd\\U00010cfe\\U00010cff\\U00010e60\\U00010e61\\U00010e62\\U00010e63\\U00010e64\\U00010e65\\U00010e66\\U00010e67\\U00010e68\\U00010e69\\U00010e6a\\U00010e6b\\U00010e6c\\U00010e6d\\U00010e6e\\U00010e6f\\U00010e70\\U00010e71\\U00010e72\\U00010e73\\U00010e74\\U00010e75\\U00010e76\\U00010e77\\U00010e78\\U00010e79\\U00010e7a\\U00010e7b\\U00010e7c\\U00010e7d\\U00010e7e\\U00010f1d\\U00010f1e\\U00010f1f\\U00010f20\\U00010f21\\U00010f22\\U00010f23\\U00010f24\\U00010f25\\U00010f26\\U00010f51\\U00010f52\\U00010f53\\U00010f54\\U00010fc5\\U00010fc6\\U00010fc7\\U00010fc8\\U00010fc9\\U00010fca\\U00010fcb\\U00011052\\U00011053\\U00011054\\U00011055\\U00011056\\U00011057\\U00011058\\U00011059\\U0001105a\\U0001105b\\U0001105c\\U0001105d\\U0001105e\\U0001105f\\U00011060\\U00011061\\U00011062\\U00011063\\U00011064\\U00011065\\U000111e1\\U000111e2\\U000111e3\\U000111e4\\U000111e5\\U000111e6\\U000111e7\\U000111e8\\U000111e9\\U000111ea\\U000111eb\\U000111ec\\U000111ed\\U000111ee\\U000111ef\\U000111f0\\U000111f1\\U000111f2\\U000111f3\\U000111f4\\U0001173a\\U0001173b\\U000118ea\\U000118eb\\U000118ec\\U000118ed\\U000118ee\\U000118ef\\U000118f0\\U000118f1\\U000118f2\\U00011c5a\\U00011c5b\\U00011c5c\\U00011c5d\\U00011c5e\\U00011c5f\\U00011c60\\U00011c61\\U00011c62\\U00011c63\\U00011c64\\U00011c65\\U00011c66\\U00011c67\\U00011c68\\U00011c69\\U00011c6a\\U00011c6b\\U00011c6c\\U00011fc0\\U00011fc1\\U00011fc2\\U00011fc3\\U00011fc4\\U00011fc5\\U00011fc6\\U00011fc7\\U00011fc8\\U00011fc9\\U00011fca\\U00011fcb\\U00011fcc\\U00011fcd\\U00011fce\\U00011fcf\\U00011fd0\\U00011fd1\\U00011fd2\\U00011fd3\\U00011fd4\\U00012400\\U00012401\\U00012402\\U00012403\\U00012404\\U00012405\\U00012406\\U00012407\\U00012408\\U00012409\\U0001240a\\U0001240b\\U0001240c\\U0001240d\\U0001240e\\U0001240f\\U00012410\\U00012411\\U00012412\\U00012413\\U00012414\\U00012415\\U00012416\\U00012417\\U00012418\\U00012419\\U0001241a\\U0001241b\\U0001241c\\U0001241d\\U0001241e\\U0001241f\\U00012420\\U00012421\\U00012422\\U00012423\\U00012424\\U00012425\\U00012426\\U00012427\\U00012428\\U00012429\\U0001242a\\U0001242b\\U0001242c\\U0001242d\\U0001242e\\U0001242f\\U00012430\\U00012431\\U00012432\\U00012433\\U00012434\\U00012435\\U00012436\\U00012437\\U00012438\\U00012439\\U0001243a\\U0001243b\\U0001243c\\U0001243d\\U0001243e\\U0001243f\\U00012440\\U00012441\\U00012442\\U00012443\\U00012444\\U00012445\\U00012446\\U00012447\\U00012448\\U00012449\\U0001244a\\U0001244b\\U0001244c\\U0001244d\\U0001244e\\U0001244f\\U00012450\\U00012451\\U00012452\\U00012453\\U00012454\\U00012455\\U00012456\\U00012457\\U00012458\\U00012459\\U0001245a\\U0001245b\\U0001245c\\U0001245d\\U0001245e\\U0001245f\\U00012460\\U00012461\\U00012462\\U00012463\\U00012464\\U00012465\\U00012466\\U00012467\\U00012468\\U00012469\\U0001246a\\U0001246b\\U0001246c\\U0001246d\\U0001246e\\U00016b5b\\U00016b5c\\U00016b5d\\U00016b5e\\U00016b5f\\U00016b60\\U00016b61\\U00016e80\\U00016e81\\U00016e82\\U00016e83\\U00016e84\\U00016e85\\U00016e86\\U00016e87\\U00016e88\\U00016e89\\U00016e8a\\U00016e8b\\U00016e8c\\U00016e8d\\U00016e8e\\U00016e8f\\U00016e90\\U00016e91\\U00016e92\\U00016e93\\U00016e94\\U00016e95\\U00016e96\\U0001d2e0\\U0001d2e1\\U0001d2e2\\U0001d2e3\\U0001d2e4\\U0001d2e5\\U0001d2e6\\U0001d2e7\\U0001d2e8\\U0001d2e9\\U0001d2ea\\U0001d2eb\\U0001d2ec\\U0001d2ed\\U0001d2ee\\U0001d2ef\\U0001d2f0\\U0001d2f1\\U0001d2f2\\U0001d2f3\\U0001d360\\U0001d361\\U0001d362\\U0001d363\\U0001d364\\U0001d365\\U0001d366\\U0001d367\\U0001d368\\U0001d369\\U0001d36a\\U0001d36b\\U0001d36c\\U0001d36d\\U0001d36e\\U0001d36f\\U0001d370\\U0001d371\\U0001d372\\U0001d373\\U0001d374\\U0001d375\\U0001d376\\U0001d377\\U0001d378\\U0001e8c7\\U0001e8c8\\U0001e8c9\\U0001e8ca\\U0001e8cb\\U0001e8cc\\U0001e8cd\\U0001e8ce\\U0001e8cf\\U0001ec71\\U0001ec72\\U0001ec73\\U0001ec74\\U0001ec75\\U0001ec76\\U0001ec77\\U0001ec78\\U0001ec79\\U0001ec7a\\U0001ec7b\\U0001ec7c\\U0001ec7d\\U0001ec7e\\U0001ec7f\\U0001ec80\\U0001ec81\\U0001ec82\\U0001ec83\\U0001ec84\\U0001ec85\\U0001ec86\\U0001ec87\\U0001ec88\\U0001ec89\\U0001ec8a\\U0001ec8b\\U0001ec8c\\U0001ec8d\\U0001ec8e\\U0001ec8f\\U0001ec90\\U0001ec91\\U0001ec92\\U0001ec93\\U0001ec94\\U0001ec95\\U0001ec96\\U0001ec97\\U0001ec98\\U0001ec99\\U0001ec9a\\U0001ec9b\\U0001ec9c\\U0001ec9d\\U0001ec9e\\U0001ec9f\\U0001eca0\\U0001eca1\\U0001eca2\\U0001eca3\\U0001eca4\\U0001eca5\\U0001eca6\\U0001eca7\\U0001eca8\\U0001eca9\\U0001ecaa\\U0001ecab\\U0001ecad\\U0001ecae\\U0001ecaf\\U0001ecb1\\U0001ecb2\\U0001ecb3\\U0001ecb4\\U0001ed01\\U0001ed02\\U0001ed03\\U0001ed04\\U0001ed05\\U0001ed06\\U0001ed07\\U0001ed08\\U0001ed09\\U0001ed0a\\U0001ed0b\\U0001ed0c\\U0001ed0d\\U0001ed0e\\U0001ed0f\\U0001ed10\\U0001ed11\\U0001ed12\\U0001ed13\\U0001ed14\\U0001ed15\\U0001ed16\\U0001ed17\\U0001ed18\\U0001ed19\\U0001ed1a\\U0001ed1b\\U0001ed1c\\U0001ed1d\\U0001ed1e\\U0001ed1f\\U0001ed20\\U0001ed21\\U0001ed22\\U0001ed23\\U0001ed24\\U0001ed25\\U0001ed26\\U0001ed27\\U0001ed28\\U0001ed29\\U0001ed2a\\U0001ed2b\\U0001ed2c\\U0001ed2d\\U0001ed2f\\U0001ed30\\U0001ed31\\U0001ed32\\U0001ed33\\U0001ed34\\U0001ed35\\U0001ed36\\U0001ed37\\U0001ed38\\U0001ed39\\U0001ed3a\\U0001ed3b\\U0001ed3c\\U0001ed3d\\U0001f100\\U0001f101\\U0001f102\\U0001f103\\U0001f104\\U0001f105\\U0001f106\\U0001f107\\U0001f108\\U0001f109\\U0001f10a\\U0001f10b\\U0001f10c\\U00020001\\U00020064\\U000200e2\\U00020121\\U0002092a\\U00020983\\U0002098c\\U0002099c\\U00020aea\\U00020afd\\U00020b19\\U00022390\\U00022998\\U00023b1b\\U0002626d\\U0002f890])]",
"tests/test_utils.py::test_chain_functions_combines_functions_in_given_order",
"tests/test_utils.py::test_ns_enum_values_and_aliases[ns.PATH-ns.PATH]",
"tests/test_utils.py::test_path_splitter_handles_dot_properly[.\\\\]",
"tests/test_utils.py::test_ns_enum_values_and_aliases[ns.LOCALE-48]",
"tests/test_utils.py::test_sep_inserter_does_nothing_if_no_numbers_example",
"tests/test_utils.py::test_ns_enum_values_and_aliases[ns.LOCALE-ns.LOCALE]",
"tests/test_utils.py::test_ns_enum_values_and_aliases[ns.REAL-3]",
"tests/test_utils.py::test_ns_enum_values_and_aliases[ns.GROUPLETTERS-ns.GROUPLETTERS]",
"tests/test_utils.py::test_groupletters_gives_letters_with_lowercase_letter_transform_example",
"tests/test_utils.py::test_ns_enum_values_and_aliases[ns.UNGROUPLETTERS-ns.UNGROUPLETTERS0]",
"tests/test_utils.py::test_regex_chooser_returns_correct_regular_expression_object[ns.DEFAULT-(\\\\d+|[\\xb2\\xb3\\xb9\\u1369\\u136a\\u136b\\u136c\\u136d\\u136e\\u136f\\u1370\\u1371\\u19da\\u2070\\u2074\\u2075\\u2076\\u2077\\u2078\\u2079\\u2080\\u2081\\u2082\\u2083\\u2084\\u2085\\u2086\\u2087\\u2088\\u2089\\u2460\\u2461\\u2462\\u2463\\u2464\\u2465\\u2466\\u2467\\u2468\\u2474\\u2475\\u2476\\u2477\\u2478\\u2479\\u247a\\u247b\\u247c\\u2488\\u2489\\u248a\\u248b\\u248c\\u248d\\u248e\\u248f\\u2490\\u24ea\\u24f5\\u24f6\\u24f7\\u24f8\\u24f9\\u24fa\\u24fb\\u24fc\\u24fd\\u24ff\\u2776\\u2777\\u2778\\u2779\\u277a\\u277b\\u277c\\u277d\\u277e\\u2780\\u2781\\u2782\\u2783\\u2784\\u2785\\u2786\\u2787\\u2788\\u278a\\u278b\\u278c\\u278d\\u278e\\u278f\\u2790\\u2791\\u2792\\U00010a40\\U00010a41\\U00010a42\\U00010a43\\U00010e60\\U00010e61\\U00010e62\\U00010e63\\U00010e64\\U00010e65\\U00010e66\\U00010e67\\U00010e68\\U00011052\\U00011053\\U00011054\\U00011055\\U00011056\\U00011057\\U00011058\\U00011059\\U0001105a\\U0001f100\\U0001f101\\U0001f102\\U0001f103\\U0001f104\\U0001f105\\U0001f106\\U0001f107\\U0001f108\\U0001f109\\U0001f10a])]",
"tests/test_utils.py::test_sep_inserter_inserts_separator_string_between_two_numbers_example",
"tests/test_utils.py::test_ns_enum_values_and_aliases[ns.UNGROUPLETTERS-ns.UNGROUPLETTERS2]",
"tests/test_utils.py::test_ns_enum_values_and_aliases[ns.NANLAST-ns.NANLAST]",
"tests/test_utils.py::test_ns_enum_values_and_aliases[ns.DEFAULT-0_1]",
"tests/test_utils.py::test_ns_enum_values_and_aliases[ns.FLOAT-ns.FLOAT]",
"tests/test_utils.py::test_sep_inserter_does_nothing_if_only_one_number_example",
"tests/test_utils.py::test_regex_chooser_returns_correct_regular_expression_object[3-([-+]?(?:\\\\d+\\\\.?\\\\d*|\\\\.\\\\d+)(?:[eE][-+]?\\\\d+)?|[\\xb2\\xb3\\xb9\\xbc\\xbd\\xbe\\u09f4\\u09f5\\u09f6\\u09f7\\u09f8\\u09f9\\u0b72\\u0b73\\u0b74\\u0b75\\u0b76\\u0b77\\u0bf0\\u0bf1\\u0bf2\\u0c78\\u0c79\\u0c7a\\u0c7b\\u0c7c\\u0c7d\\u0c7e\\u0d58\\u0d59\\u0d5a\\u0d5b\\u0d5c\\u0d5d\\u0d5e\\u0d70\\u0d71\\u0d72\\u0d73\\u0d74\\u0d75\\u0d76\\u0d77\\u0d78\\u0f2a\\u0f2b\\u0f2c\\u0f2d\\u0f2e\\u0f2f\\u0f30\\u0f31\\u0f32\\u0f33\\u1369\\u136a\\u136b\\u136c\\u136d\\u136e\\u136f\\u1370\\u1371\\u1372\\u1373\\u1374\\u1375\\u1376\\u1377\\u1378\\u1379\\u137a\\u137b\\u137c\\u16ee\\u16ef\\u16f0\\u17f0\\u17f1\\u17f2\\u17f3\\u17f4\\u17f5\\u17f6\\u17f7\\u17f8\\u17f9\\u19da\\u2070\\u2074\\u2075\\u2076\\u2077\\u2078\\u2079\\u2080\\u2081\\u2082\\u2083\\u2084\\u2085\\u2086\\u2087\\u2088\\u2089\\u2150\\u2151\\u2152\\u2153\\u2154\\u2155\\u2156\\u2157\\u2158\\u2159\\u215a\\u215b\\u215c\\u215d\\u215e\\u215f\\u2160\\u2161\\u2162\\u2163\\u2164\\u2165\\u2166\\u2167\\u2168\\u2169\\u216a\\u216b\\u216c\\u216d\\u216e\\u216f\\u2170\\u2171\\u2172\\u2173\\u2174\\u2175\\u2176\\u2177\\u2178\\u2179\\u217a\\u217b\\u217c\\u217d\\u217e\\u217f\\u2180\\u2181\\u2182\\u2185\\u2186\\u2187\\u2188\\u2189\\u2460\\u2461\\u2462\\u2463\\u2464\\u2465\\u2466\\u2467\\u2468\\u2469\\u246a\\u246b\\u246c\\u246d\\u246e\\u246f\\u2470\\u2471\\u2472\\u2473\\u2474\\u2475\\u2476\\u2477\\u2478\\u2479\\u247a\\u247b\\u247c\\u247d\\u247e\\u247f\\u2480\\u2481\\u2482\\u2483\\u2484\\u2485\\u2486\\u2487\\u2488\\u2489\\u248a\\u248b\\u248c\\u248d\\u248e\\u248f\\u2490\\u2491\\u2492\\u2493\\u2494\\u2495\\u2496\\u2497\\u2498\\u2499\\u249a\\u249b\\u24ea\\u24eb\\u24ec\\u24ed\\u24ee\\u24ef\\u24f0\\u24f1\\u24f2\\u24f3\\u24f4\\u24f5\\u24f6\\u24f7\\u24f8\\u24f9\\u24fa\\u24fb\\u24fc\\u24fd\\u24fe\\u24ff\\u2776\\u2777\\u2778\\u2779\\u277a\\u277b\\u277c\\u277d\\u277e\\u277f\\u2780\\u2781\\u2782\\u2783\\u2784\\u2785\\u2786\\u2787\\u2788\\u2789\\u278a\\u278b\\u278c\\u278d\\u278e\\u278f\\u2790\\u2791\\u2792\\u2793\\u2cfd\\u3007\\u3021\\u3022\\u3023\\u3024\\u3025\\u3026\\u3027\\u3028\\u3029\\u3038\\u3039\\u303a\\u3192\\u3193\\u3194\\u3195\\u3220\\u3221\\u3222\\u3223\\u3224\\u3225\\u3226\\u3227\\u3228\\u3229\\u3248\\u3249\\u324a\\u324b\\u324c\\u324d\\u324e\\u324f\\u3251\\u3252\\u3253\\u3254\\u3255\\u3256\\u3257\\u3258\\u3259\\u325a\\u325b\\u325c\\u325d\\u325e\\u325f\\u3280\\u3281\\u3282\\u3283\\u3284\\u3285\\u3286\\u3287\\u3288\\u3289\\u32b1\\u32b2\\u32b3\\u32b4\\u32b5\\u32b6\\u32b7\\u32b8\\u32b9\\u32ba\\u32bb\\u32bc\\u32bd\\u32be\\u32bf\\u3405\\u3483\\u382a\\u3b4d\\u4e00\\u4e03\\u4e07\\u4e09\\u4e5d\\u4e8c\\u4e94\\u4e96\\u4ebf\\u4ec0\\u4edf\\u4ee8\\u4f0d\\u4f70\\u5104\\u5146\\u5169\\u516b\\u516d\\u5341\\u5343\\u5344\\u5345\\u534c\\u53c1\\u53c2\\u53c3\\u53c4\\u56db\\u58f1\\u58f9\\u5e7a\\u5efe\\u5eff\\u5f0c\\u5f0d\\u5f0e\\u5f10\\u62fe\\u634c\\u67d2\\u6f06\\u7396\\u767e\\u8086\\u842c\\u8cae\\u8cb3\\u8d30\\u9621\\u9646\\u964c\\u9678\\u96f6\\ua6e6\\ua6e7\\ua6e8\\ua6e9\\ua6ea\\ua6eb\\ua6ec\\ua6ed\\ua6ee\\ua6ef\\ua830\\ua831\\ua832\\ua833\\ua834\\ua835\\uf96b\\uf973\\uf978\\uf9b2\\uf9d1\\uf9d3\\uf9fd\\U00010107\\U00010108\\U00010109\\U0001010a\\U0001010b\\U0001010c\\U0001010d\\U0001010e\\U0001010f\\U00010110\\U00010111\\U00010112\\U00010113\\U00010114\\U00010115\\U00010116\\U00010117\\U00010118\\U00010119\\U0001011a\\U0001011b\\U0001011c\\U0001011d\\U0001011e\\U0001011f\\U00010120\\U00010121\\U00010122\\U00010123\\U00010124\\U00010125\\U00010126\\U00010127\\U00010128\\U00010129\\U0001012a\\U0001012b\\U0001012c\\U0001012d\\U0001012e\\U0001012f\\U00010130\\U00010131\\U00010132\\U00010133\\U00010140\\U00010141\\U00010142\\U00010143\\U00010144\\U00010145\\U00010146\\U00010147\\U00010148\\U00010149\\U0001014a\\U0001014b\\U0001014c\\U0001014d\\U0001014e\\U0001014f\\U00010150\\U00010151\\U00010152\\U00010153\\U00010154\\U00010155\\U00010156\\U00010157\\U00010158\\U00010159\\U0001015a\\U0001015b\\U0001015c\\U0001015d\\U0001015e\\U0001015f\\U00010160\\U00010161\\U00010162\\U00010163\\U00010164\\U00010165\\U00010166\\U00010167\\U00010168\\U00010169\\U0001016a\\U0001016b\\U0001016c\\U0001016d\\U0001016e\\U0001016f\\U00010170\\U00010171\\U00010172\\U00010173\\U00010174\\U00010175\\U00010176\\U00010177\\U00010178\\U0001018a\\U0001018b\\U000102e1\\U000102e2\\U000102e3\\U000102e4\\U000102e5\\U000102e6\\U000102e7\\U000102e8\\U000102e9\\U000102ea\\U000102eb\\U000102ec\\U000102ed\\U000102ee\\U000102ef\\U000102f0\\U000102f1\\U000102f2\\U000102f3\\U000102f4\\U000102f5\\U000102f6\\U000102f7\\U000102f8\\U000102f9\\U000102fa\\U000102fb\\U00010320\\U00010321\\U00010322\\U00010323\\U00010341\\U0001034a\\U000103d1\\U000103d2\\U000103d3\\U000103d4\\U000103d5\\U00010858\\U00010859\\U0001085a\\U0001085b\\U0001085c\\U0001085d\\U0001085e\\U0001085f\\U00010879\\U0001087a\\U0001087b\\U0001087c\\U0001087d\\U0001087e\\U0001087f\\U000108a7\\U000108a8\\U000108a9\\U000108aa\\U000108ab\\U000108ac\\U000108ad\\U000108ae\\U000108af\\U000108fb\\U000108fc\\U000108fd\\U000108fe\\U000108ff\\U00010916\\U00010917\\U00010918\\U00010919\\U0001091a\\U0001091b\\U000109bc\\U000109bd\\U000109c0\\U000109c1\\U000109c2\\U000109c3\\U000109c4\\U000109c5\\U000109c6\\U000109c7\\U000109c8\\U000109c9\\U000109ca\\U000109cb\\U000109cc\\U000109cd\\U000109ce\\U000109cf\\U000109d2\\U000109d3\\U000109d4\\U000109d5\\U000109d6\\U000109d7\\U000109d8\\U000109d9\\U000109da\\U000109db\\U000109dc\\U000109dd\\U000109de\\U000109df\\U000109e0\\U000109e1\\U000109e2\\U000109e3\\U000109e4\\U000109e5\\U000109e6\\U000109e7\\U000109e8\\U000109e9\\U000109ea\\U000109eb\\U000109ec\\U000109ed\\U000109ee\\U000109ef\\U000109f0\\U000109f1\\U000109f2\\U000109f3\\U000109f4\\U000109f5\\U000109f6\\U000109f7\\U000109f8\\U000109f9\\U000109fa\\U000109fb\\U000109fc\\U000109fd\\U000109fe\\U000109ff\\U00010a40\\U00010a41\\U00010a42\\U00010a43\\U00010a44\\U00010a45\\U00010a46\\U00010a47\\U00010a48\\U00010a7d\\U00010a7e\\U00010a9d\\U00010a9e\\U00010a9f\\U00010aeb\\U00010aec\\U00010aed\\U00010aee\\U00010aef\\U00010b58\\U00010b59\\U00010b5a\\U00010b5b\\U00010b5c\\U00010b5d\\U00010b5e\\U00010b5f\\U00010b78\\U00010b79\\U00010b7a\\U00010b7b\\U00010b7c\\U00010b7d\\U00010b7e\\U00010b7f\\U00010ba9\\U00010baa\\U00010bab\\U00010bac\\U00010bad\\U00010bae\\U00010baf\\U00010cfa\\U00010cfb\\U00010cfc\\U00010cfd\\U00010cfe\\U00010cff\\U00010e60\\U00010e61\\U00010e62\\U00010e63\\U00010e64\\U00010e65\\U00010e66\\U00010e67\\U00010e68\\U00010e69\\U00010e6a\\U00010e6b\\U00010e6c\\U00010e6d\\U00010e6e\\U00010e6f\\U00010e70\\U00010e71\\U00010e72\\U00010e73\\U00010e74\\U00010e75\\U00010e76\\U00010e77\\U00010e78\\U00010e79\\U00010e7a\\U00010e7b\\U00010e7c\\U00010e7d\\U00010e7e\\U00010f1d\\U00010f1e\\U00010f1f\\U00010f20\\U00010f21\\U00010f22\\U00010f23\\U00010f24\\U00010f25\\U00010f26\\U00010f51\\U00010f52\\U00010f53\\U00010f54\\U00010fc5\\U00010fc6\\U00010fc7\\U00010fc8\\U00010fc9\\U00010fca\\U00010fcb\\U00011052\\U00011053\\U00011054\\U00011055\\U00011056\\U00011057\\U00011058\\U00011059\\U0001105a\\U0001105b\\U0001105c\\U0001105d\\U0001105e\\U0001105f\\U00011060\\U00011061\\U00011062\\U00011063\\U00011064\\U00011065\\U000111e1\\U000111e2\\U000111e3\\U000111e4\\U000111e5\\U000111e6\\U000111e7\\U000111e8\\U000111e9\\U000111ea\\U000111eb\\U000111ec\\U000111ed\\U000111ee\\U000111ef\\U000111f0\\U000111f1\\U000111f2\\U000111f3\\U000111f4\\U0001173a\\U0001173b\\U000118ea\\U000118eb\\U000118ec\\U000118ed\\U000118ee\\U000118ef\\U000118f0\\U000118f1\\U000118f2\\U00011c5a\\U00011c5b\\U00011c5c\\U00011c5d\\U00011c5e\\U00011c5f\\U00011c60\\U00011c61\\U00011c62\\U00011c63\\U00011c64\\U00011c65\\U00011c66\\U00011c67\\U00011c68\\U00011c69\\U00011c6a\\U00011c6b\\U00011c6c\\U00011fc0\\U00011fc1\\U00011fc2\\U00011fc3\\U00011fc4\\U00011fc5\\U00011fc6\\U00011fc7\\U00011fc8\\U00011fc9\\U00011fca\\U00011fcb\\U00011fcc\\U00011fcd\\U00011fce\\U00011fcf\\U00011fd0\\U00011fd1\\U00011fd2\\U00011fd3\\U00011fd4\\U00012400\\U00012401\\U00012402\\U00012403\\U00012404\\U00012405\\U00012406\\U00012407\\U00012408\\U00012409\\U0001240a\\U0001240b\\U0001240c\\U0001240d\\U0001240e\\U0001240f\\U00012410\\U00012411\\U00012412\\U00012413\\U00012414\\U00012415\\U00012416\\U00012417\\U00012418\\U00012419\\U0001241a\\U0001241b\\U0001241c\\U0001241d\\U0001241e\\U0001241f\\U00012420\\U00012421\\U00012422\\U00012423\\U00012424\\U00012425\\U00012426\\U00012427\\U00012428\\U00012429\\U0001242a\\U0001242b\\U0001242c\\U0001242d\\U0001242e\\U0001242f\\U00012430\\U00012431\\U00012432\\U00012433\\U00012434\\U00012435\\U00012436\\U00012437\\U00012438\\U00012439\\U0001243a\\U0001243b\\U0001243c\\U0001243d\\U0001243e\\U0001243f\\U00012440\\U00012441\\U00012442\\U00012443\\U00012444\\U00012445\\U00012446\\U00012447\\U00012448\\U00012449\\U0001244a\\U0001244b\\U0001244c\\U0001244d\\U0001244e\\U0001244f\\U00012450\\U00012451\\U00012452\\U00012453\\U00012454\\U00012455\\U00012456\\U00012457\\U00012458\\U00012459\\U0001245a\\U0001245b\\U0001245c\\U0001245d\\U0001245e\\U0001245f\\U00012460\\U00012461\\U00012462\\U00012463\\U00012464\\U00012465\\U00012466\\U00012467\\U00012468\\U00012469\\U0001246a\\U0001246b\\U0001246c\\U0001246d\\U0001246e\\U00016b5b\\U00016b5c\\U00016b5d\\U00016b5e\\U00016b5f\\U00016b60\\U00016b61\\U00016e80\\U00016e81\\U00016e82\\U00016e83\\U00016e84\\U00016e85\\U00016e86\\U00016e87\\U00016e88\\U00016e89\\U00016e8a\\U00016e8b\\U00016e8c\\U00016e8d\\U00016e8e\\U00016e8f\\U00016e90\\U00016e91\\U00016e92\\U00016e93\\U00016e94\\U00016e95\\U00016e96\\U0001d2e0\\U0001d2e1\\U0001d2e2\\U0001d2e3\\U0001d2e4\\U0001d2e5\\U0001d2e6\\U0001d2e7\\U0001d2e8\\U0001d2e9\\U0001d2ea\\U0001d2eb\\U0001d2ec\\U0001d2ed\\U0001d2ee\\U0001d2ef\\U0001d2f0\\U0001d2f1\\U0001d2f2\\U0001d2f3\\U0001d360\\U0001d361\\U0001d362\\U0001d363\\U0001d364\\U0001d365\\U0001d366\\U0001d367\\U0001d368\\U0001d369\\U0001d36a\\U0001d36b\\U0001d36c\\U0001d36d\\U0001d36e\\U0001d36f\\U0001d370\\U0001d371\\U0001d372\\U0001d373\\U0001d374\\U0001d375\\U0001d376\\U0001d377\\U0001d378\\U0001e8c7\\U0001e8c8\\U0001e8c9\\U0001e8ca\\U0001e8cb\\U0001e8cc\\U0001e8cd\\U0001e8ce\\U0001e8cf\\U0001ec71\\U0001ec72\\U0001ec73\\U0001ec74\\U0001ec75\\U0001ec76\\U0001ec77\\U0001ec78\\U0001ec79\\U0001ec7a\\U0001ec7b\\U0001ec7c\\U0001ec7d\\U0001ec7e\\U0001ec7f\\U0001ec80\\U0001ec81\\U0001ec82\\U0001ec83\\U0001ec84\\U0001ec85\\U0001ec86\\U0001ec87\\U0001ec88\\U0001ec89\\U0001ec8a\\U0001ec8b\\U0001ec8c\\U0001ec8d\\U0001ec8e\\U0001ec8f\\U0001ec90\\U0001ec91\\U0001ec92\\U0001ec93\\U0001ec94\\U0001ec95\\U0001ec96\\U0001ec97\\U0001ec98\\U0001ec99\\U0001ec9a\\U0001ec9b\\U0001ec9c\\U0001ec9d\\U0001ec9e\\U0001ec9f\\U0001eca0\\U0001eca1\\U0001eca2\\U0001eca3\\U0001eca4\\U0001eca5\\U0001eca6\\U0001eca7\\U0001eca8\\U0001eca9\\U0001ecaa\\U0001ecab\\U0001ecad\\U0001ecae\\U0001ecaf\\U0001ecb1\\U0001ecb2\\U0001ecb3\\U0001ecb4\\U0001ed01\\U0001ed02\\U0001ed03\\U0001ed04\\U0001ed05\\U0001ed06\\U0001ed07\\U0001ed08\\U0001ed09\\U0001ed0a\\U0001ed0b\\U0001ed0c\\U0001ed0d\\U0001ed0e\\U0001ed0f\\U0001ed10\\U0001ed11\\U0001ed12\\U0001ed13\\U0001ed14\\U0001ed15\\U0001ed16\\U0001ed17\\U0001ed18\\U0001ed19\\U0001ed1a\\U0001ed1b\\U0001ed1c\\U0001ed1d\\U0001ed1e\\U0001ed1f\\U0001ed20\\U0001ed21\\U0001ed22\\U0001ed23\\U0001ed24\\U0001ed25\\U0001ed26\\U0001ed27\\U0001ed28\\U0001ed29\\U0001ed2a\\U0001ed2b\\U0001ed2c\\U0001ed2d\\U0001ed2f\\U0001ed30\\U0001ed31\\U0001ed32\\U0001ed33\\U0001ed34\\U0001ed35\\U0001ed36\\U0001ed37\\U0001ed38\\U0001ed39\\U0001ed3a\\U0001ed3b\\U0001ed3c\\U0001ed3d\\U0001f100\\U0001f101\\U0001f102\\U0001f103\\U0001f104\\U0001f105\\U0001f106\\U0001f107\\U0001f108\\U0001f109\\U0001f10a\\U0001f10b\\U0001f10c\\U00020001\\U00020064\\U000200e2\\U00020121\\U0002092a\\U00020983\\U0002098c\\U0002099c\\U00020aea\\U00020afd\\U00020b19\\U00022390\\U00022998\\U00023b1b\\U0002626d\\U0002f890])]",
"tests/test_utils.py::test_ns_enum_values_and_aliases[ns.UNGROUPLETTERS-ns.UNGROUPLETTERS1]",
"tests/test_utils.py::test_ns_enum_values_and_aliases[ns.COMPATIBILITYNORMALIZE-ns.COMPATIBILITYNORMALIZE]",
"tests/test_utils.py::test_path_splitter_splits_path_string_by_sep",
"tests/test_utils.py::test_do_decoding_decodes_bytes_string_to_unicode",
"tests/test_utils.py::test_groupletters_gives_letters_with_lowercase_letter_transform",
"tests/test_utils.py::test_ns_enum_values_and_aliases[ns.LOCALENUM-ns.LOCALENUM]",
"tests/test_utils.py::test_regex_chooser_returns_correct_regular_expression_object[2-([-+]?\\\\d+|[\\xb2\\xb3\\xb9\\u1369\\u136a\\u136b\\u136c\\u136d\\u136e\\u136f\\u1370\\u1371\\u19da\\u2070\\u2074\\u2075\\u2076\\u2077\\u2078\\u2079\\u2080\\u2081\\u2082\\u2083\\u2084\\u2085\\u2086\\u2087\\u2088\\u2089\\u2460\\u2461\\u2462\\u2463\\u2464\\u2465\\u2466\\u2467\\u2468\\u2474\\u2475\\u2476\\u2477\\u2478\\u2479\\u247a\\u247b\\u247c\\u2488\\u2489\\u248a\\u248b\\u248c\\u248d\\u248e\\u248f\\u2490\\u24ea\\u24f5\\u24f6\\u24f7\\u24f8\\u24f9\\u24fa\\u24fb\\u24fc\\u24fd\\u24ff\\u2776\\u2777\\u2778\\u2779\\u277a\\u277b\\u277c\\u277d\\u277e\\u2780\\u2781\\u2782\\u2783\\u2784\\u2785\\u2786\\u2787\\u2788\\u278a\\u278b\\u278c\\u278d\\u278e\\u278f\\u2790\\u2791\\u2792\\U00010a40\\U00010a41\\U00010a42\\U00010a43\\U00010e60\\U00010e61\\U00010e62\\U00010e63\\U00010e64\\U00010e65\\U00010e66\\U00010e67\\U00010e68\\U00011052\\U00011053\\U00011054\\U00011055\\U00011056\\U00011057\\U00011058\\U00011059\\U0001105a\\U0001f100\\U0001f101\\U0001f102\\U0001f103\\U0001f104\\U0001f105\\U0001f106\\U0001f107\\U0001f108\\U0001f109\\U0001f10a])]",
"tests/test_utils.py::test_ns_enum_values_and_aliases[ns.SIGNED-ns.SIGNED]",
"tests/test_utils.py::test_path_splitter_splits_path_string_by_sep_example",
"tests/test_utils.py::test_ns_enum_values_and_aliases[ns.IGNORECASE-ns.IGNORECASE]",
"tests/test_utils.py::test_ns_enum_values_and_aliases[ns.LOCALEALPHA-ns.LOCALEALPHA]",
"tests/test_utils.py::test_sep_inserter_inserts_separator_between_two_numbers",
"tests/test_utils.py::test_ns_enum_values_and_aliases[ns.LOWERCASEFIRST-ns.LOWERCASEFIRST]",
"tests/test_utils.py::test_ns_enum_values_and_aliases[ns.DEFAULT-ns.DEFAULT1]",
"tests/test_utils.py::test_ns_enum_values_and_aliases[ns.NUMAFTER-ns.NUMAFTER]",
"tests/test_utils.py::test_ns_enum_values_and_aliases[ns.NOEXP-ns.NOEXP]",
"tests/test_utils.py::test_chain_functions_does_one_function_if_one_function_is_given",
"tests/test_utils.py::test_path_splitter_splits_path_string_by_sep_and_removes_extension",
"tests/test_utils.py::test_regex_chooser_returns_correct_regular_expression_object[ns.FLOAT-((?:\\\\d+\\\\.?\\\\d*|\\\\.\\\\d+)(?:[eE][-+]?\\\\d+)?|[\\xb2\\xb3\\xb9\\xbc\\xbd\\xbe\\u09f4\\u09f5\\u09f6\\u09f7\\u09f8\\u09f9\\u0b72\\u0b73\\u0b74\\u0b75\\u0b76\\u0b77\\u0bf0\\u0bf1\\u0bf2\\u0c78\\u0c79\\u0c7a\\u0c7b\\u0c7c\\u0c7d\\u0c7e\\u0d58\\u0d59\\u0d5a\\u0d5b\\u0d5c\\u0d5d\\u0d5e\\u0d70\\u0d71\\u0d72\\u0d73\\u0d74\\u0d75\\u0d76\\u0d77\\u0d78\\u0f2a\\u0f2b\\u0f2c\\u0f2d\\u0f2e\\u0f2f\\u0f30\\u0f31\\u0f32\\u0f33\\u1369\\u136a\\u136b\\u136c\\u136d\\u136e\\u136f\\u1370\\u1371\\u1372\\u1373\\u1374\\u1375\\u1376\\u1377\\u1378\\u1379\\u137a\\u137b\\u137c\\u16ee\\u16ef\\u16f0\\u17f0\\u17f1\\u17f2\\u17f3\\u17f4\\u17f5\\u17f6\\u17f7\\u17f8\\u17f9\\u19da\\u2070\\u2074\\u2075\\u2076\\u2077\\u2078\\u2079\\u2080\\u2081\\u2082\\u2083\\u2084\\u2085\\u2086\\u2087\\u2088\\u2089\\u2150\\u2151\\u2152\\u2153\\u2154\\u2155\\u2156\\u2157\\u2158\\u2159\\u215a\\u215b\\u215c\\u215d\\u215e\\u215f\\u2160\\u2161\\u2162\\u2163\\u2164\\u2165\\u2166\\u2167\\u2168\\u2169\\u216a\\u216b\\u216c\\u216d\\u216e\\u216f\\u2170\\u2171\\u2172\\u2173\\u2174\\u2175\\u2176\\u2177\\u2178\\u2179\\u217a\\u217b\\u217c\\u217d\\u217e\\u217f\\u2180\\u2181\\u2182\\u2185\\u2186\\u2187\\u2188\\u2189\\u2460\\u2461\\u2462\\u2463\\u2464\\u2465\\u2466\\u2467\\u2468\\u2469\\u246a\\u246b\\u246c\\u246d\\u246e\\u246f\\u2470\\u2471\\u2472\\u2473\\u2474\\u2475\\u2476\\u2477\\u2478\\u2479\\u247a\\u247b\\u247c\\u247d\\u247e\\u247f\\u2480\\u2481\\u2482\\u2483\\u2484\\u2485\\u2486\\u2487\\u2488\\u2489\\u248a\\u248b\\u248c\\u248d\\u248e\\u248f\\u2490\\u2491\\u2492\\u2493\\u2494\\u2495\\u2496\\u2497\\u2498\\u2499\\u249a\\u249b\\u24ea\\u24eb\\u24ec\\u24ed\\u24ee\\u24ef\\u24f0\\u24f1\\u24f2\\u24f3\\u24f4\\u24f5\\u24f6\\u24f7\\u24f8\\u24f9\\u24fa\\u24fb\\u24fc\\u24fd\\u24fe\\u24ff\\u2776\\u2777\\u2778\\u2779\\u277a\\u277b\\u277c\\u277d\\u277e\\u277f\\u2780\\u2781\\u2782\\u2783\\u2784\\u2785\\u2786\\u2787\\u2788\\u2789\\u278a\\u278b\\u278c\\u278d\\u278e\\u278f\\u2790\\u2791\\u2792\\u2793\\u2cfd\\u3007\\u3021\\u3022\\u3023\\u3024\\u3025\\u3026\\u3027\\u3028\\u3029\\u3038\\u3039\\u303a\\u3192\\u3193\\u3194\\u3195\\u3220\\u3221\\u3222\\u3223\\u3224\\u3225\\u3226\\u3227\\u3228\\u3229\\u3248\\u3249\\u324a\\u324b\\u324c\\u324d\\u324e\\u324f\\u3251\\u3252\\u3253\\u3254\\u3255\\u3256\\u3257\\u3258\\u3259\\u325a\\u325b\\u325c\\u325d\\u325e\\u325f\\u3280\\u3281\\u3282\\u3283\\u3284\\u3285\\u3286\\u3287\\u3288\\u3289\\u32b1\\u32b2\\u32b3\\u32b4\\u32b5\\u32b6\\u32b7\\u32b8\\u32b9\\u32ba\\u32bb\\u32bc\\u32bd\\u32be\\u32bf\\u3405\\u3483\\u382a\\u3b4d\\u4e00\\u4e03\\u4e07\\u4e09\\u4e5d\\u4e8c\\u4e94\\u4e96\\u4ebf\\u4ec0\\u4edf\\u4ee8\\u4f0d\\u4f70\\u5104\\u5146\\u5169\\u516b\\u516d\\u5341\\u5343\\u5344\\u5345\\u534c\\u53c1\\u53c2\\u53c3\\u53c4\\u56db\\u58f1\\u58f9\\u5e7a\\u5efe\\u5eff\\u5f0c\\u5f0d\\u5f0e\\u5f10\\u62fe\\u634c\\u67d2\\u6f06\\u7396\\u767e\\u8086\\u842c\\u8cae\\u8cb3\\u8d30\\u9621\\u9646\\u964c\\u9678\\u96f6\\ua6e6\\ua6e7\\ua6e8\\ua6e9\\ua6ea\\ua6eb\\ua6ec\\ua6ed\\ua6ee\\ua6ef\\ua830\\ua831\\ua832\\ua833\\ua834\\ua835\\uf96b\\uf973\\uf978\\uf9b2\\uf9d1\\uf9d3\\uf9fd\\U00010107\\U00010108\\U00010109\\U0001010a\\U0001010b\\U0001010c\\U0001010d\\U0001010e\\U0001010f\\U00010110\\U00010111\\U00010112\\U00010113\\U00010114\\U00010115\\U00010116\\U00010117\\U00010118\\U00010119\\U0001011a\\U0001011b\\U0001011c\\U0001011d\\U0001011e\\U0001011f\\U00010120\\U00010121\\U00010122\\U00010123\\U00010124\\U00010125\\U00010126\\U00010127\\U00010128\\U00010129\\U0001012a\\U0001012b\\U0001012c\\U0001012d\\U0001012e\\U0001012f\\U00010130\\U00010131\\U00010132\\U00010133\\U00010140\\U00010141\\U00010142\\U00010143\\U00010144\\U00010145\\U00010146\\U00010147\\U00010148\\U00010149\\U0001014a\\U0001014b\\U0001014c\\U0001014d\\U0001014e\\U0001014f\\U00010150\\U00010151\\U00010152\\U00010153\\U00010154\\U00010155\\U00010156\\U00010157\\U00010158\\U00010159\\U0001015a\\U0001015b\\U0001015c\\U0001015d\\U0001015e\\U0001015f\\U00010160\\U00010161\\U00010162\\U00010163\\U00010164\\U00010165\\U00010166\\U00010167\\U00010168\\U00010169\\U0001016a\\U0001016b\\U0001016c\\U0001016d\\U0001016e\\U0001016f\\U00010170\\U00010171\\U00010172\\U00010173\\U00010174\\U00010175\\U00010176\\U00010177\\U00010178\\U0001018a\\U0001018b\\U000102e1\\U000102e2\\U000102e3\\U000102e4\\U000102e5\\U000102e6\\U000102e7\\U000102e8\\U000102e9\\U000102ea\\U000102eb\\U000102ec\\U000102ed\\U000102ee\\U000102ef\\U000102f0\\U000102f1\\U000102f2\\U000102f3\\U000102f4\\U000102f5\\U000102f6\\U000102f7\\U000102f8\\U000102f9\\U000102fa\\U000102fb\\U00010320\\U00010321\\U00010322\\U00010323\\U00010341\\U0001034a\\U000103d1\\U000103d2\\U000103d3\\U000103d4\\U000103d5\\U00010858\\U00010859\\U0001085a\\U0001085b\\U0001085c\\U0001085d\\U0001085e\\U0001085f\\U00010879\\U0001087a\\U0001087b\\U0001087c\\U0001087d\\U0001087e\\U0001087f\\U000108a7\\U000108a8\\U000108a9\\U000108aa\\U000108ab\\U000108ac\\U000108ad\\U000108ae\\U000108af\\U000108fb\\U000108fc\\U000108fd\\U000108fe\\U000108ff\\U00010916\\U00010917\\U00010918\\U00010919\\U0001091a\\U0001091b\\U000109bc\\U000109bd\\U000109c0\\U000109c1\\U000109c2\\U000109c3\\U000109c4\\U000109c5\\U000109c6\\U000109c7\\U000109c8\\U000109c9\\U000109ca\\U000109cb\\U000109cc\\U000109cd\\U000109ce\\U000109cf\\U000109d2\\U000109d3\\U000109d4\\U000109d5\\U000109d6\\U000109d7\\U000109d8\\U000109d9\\U000109da\\U000109db\\U000109dc\\U000109dd\\U000109de\\U000109df\\U000109e0\\U000109e1\\U000109e2\\U000109e3\\U000109e4\\U000109e5\\U000109e6\\U000109e7\\U000109e8\\U000109e9\\U000109ea\\U000109eb\\U000109ec\\U000109ed\\U000109ee\\U000109ef\\U000109f0\\U000109f1\\U000109f2\\U000109f3\\U000109f4\\U000109f5\\U000109f6\\U000109f7\\U000109f8\\U000109f9\\U000109fa\\U000109fb\\U000109fc\\U000109fd\\U000109fe\\U000109ff\\U00010a40\\U00010a41\\U00010a42\\U00010a43\\U00010a44\\U00010a45\\U00010a46\\U00010a47\\U00010a48\\U00010a7d\\U00010a7e\\U00010a9d\\U00010a9e\\U00010a9f\\U00010aeb\\U00010aec\\U00010aed\\U00010aee\\U00010aef\\U00010b58\\U00010b59\\U00010b5a\\U00010b5b\\U00010b5c\\U00010b5d\\U00010b5e\\U00010b5f\\U00010b78\\U00010b79\\U00010b7a\\U00010b7b\\U00010b7c\\U00010b7d\\U00010b7e\\U00010b7f\\U00010ba9\\U00010baa\\U00010bab\\U00010bac\\U00010bad\\U00010bae\\U00010baf\\U00010cfa\\U00010cfb\\U00010cfc\\U00010cfd\\U00010cfe\\U00010cff\\U00010e60\\U00010e61\\U00010e62\\U00010e63\\U00010e64\\U00010e65\\U00010e66\\U00010e67\\U00010e68\\U00010e69\\U00010e6a\\U00010e6b\\U00010e6c\\U00010e6d\\U00010e6e\\U00010e6f\\U00010e70\\U00010e71\\U00010e72\\U00010e73\\U00010e74\\U00010e75\\U00010e76\\U00010e77\\U00010e78\\U00010e79\\U00010e7a\\U00010e7b\\U00010e7c\\U00010e7d\\U00010e7e\\U00010f1d\\U00010f1e\\U00010f1f\\U00010f20\\U00010f21\\U00010f22\\U00010f23\\U00010f24\\U00010f25\\U00010f26\\U00010f51\\U00010f52\\U00010f53\\U00010f54\\U00010fc5\\U00010fc6\\U00010fc7\\U00010fc8\\U00010fc9\\U00010fca\\U00010fcb\\U00011052\\U00011053\\U00011054\\U00011055\\U00011056\\U00011057\\U00011058\\U00011059\\U0001105a\\U0001105b\\U0001105c\\U0001105d\\U0001105e\\U0001105f\\U00011060\\U00011061\\U00011062\\U00011063\\U00011064\\U00011065\\U000111e1\\U000111e2\\U000111e3\\U000111e4\\U000111e5\\U000111e6\\U000111e7\\U000111e8\\U000111e9\\U000111ea\\U000111eb\\U000111ec\\U000111ed\\U000111ee\\U000111ef\\U000111f0\\U000111f1\\U000111f2\\U000111f3\\U000111f4\\U0001173a\\U0001173b\\U000118ea\\U000118eb\\U000118ec\\U000118ed\\U000118ee\\U000118ef\\U000118f0\\U000118f1\\U000118f2\\U00011c5a\\U00011c5b\\U00011c5c\\U00011c5d\\U00011c5e\\U00011c5f\\U00011c60\\U00011c61\\U00011c62\\U00011c63\\U00011c64\\U00011c65\\U00011c66\\U00011c67\\U00011c68\\U00011c69\\U00011c6a\\U00011c6b\\U00011c6c\\U00011fc0\\U00011fc1\\U00011fc2\\U00011fc3\\U00011fc4\\U00011fc5\\U00011fc6\\U00011fc7\\U00011fc8\\U00011fc9\\U00011fca\\U00011fcb\\U00011fcc\\U00011fcd\\U00011fce\\U00011fcf\\U00011fd0\\U00011fd1\\U00011fd2\\U00011fd3\\U00011fd4\\U00012400\\U00012401\\U00012402\\U00012403\\U00012404\\U00012405\\U00012406\\U00012407\\U00012408\\U00012409\\U0001240a\\U0001240b\\U0001240c\\U0001240d\\U0001240e\\U0001240f\\U00012410\\U00012411\\U00012412\\U00012413\\U00012414\\U00012415\\U00012416\\U00012417\\U00012418\\U00012419\\U0001241a\\U0001241b\\U0001241c\\U0001241d\\U0001241e\\U0001241f\\U00012420\\U00012421\\U00012422\\U00012423\\U00012424\\U00012425\\U00012426\\U00012427\\U00012428\\U00012429\\U0001242a\\U0001242b\\U0001242c\\U0001242d\\U0001242e\\U0001242f\\U00012430\\U00012431\\U00012432\\U00012433\\U00012434\\U00012435\\U00012436\\U00012437\\U00012438\\U00012439\\U0001243a\\U0001243b\\U0001243c\\U0001243d\\U0001243e\\U0001243f\\U00012440\\U00012441\\U00012442\\U00012443\\U00012444\\U00012445\\U00012446\\U00012447\\U00012448\\U00012449\\U0001244a\\U0001244b\\U0001244c\\U0001244d\\U0001244e\\U0001244f\\U00012450\\U00012451\\U00012452\\U00012453\\U00012454\\U00012455\\U00012456\\U00012457\\U00012458\\U00012459\\U0001245a\\U0001245b\\U0001245c\\U0001245d\\U0001245e\\U0001245f\\U00012460\\U00012461\\U00012462\\U00012463\\U00012464\\U00012465\\U00012466\\U00012467\\U00012468\\U00012469\\U0001246a\\U0001246b\\U0001246c\\U0001246d\\U0001246e\\U00016b5b\\U00016b5c\\U00016b5d\\U00016b5e\\U00016b5f\\U00016b60\\U00016b61\\U00016e80\\U00016e81\\U00016e82\\U00016e83\\U00016e84\\U00016e85\\U00016e86\\U00016e87\\U00016e88\\U00016e89\\U00016e8a\\U00016e8b\\U00016e8c\\U00016e8d\\U00016e8e\\U00016e8f\\U00016e90\\U00016e91\\U00016e92\\U00016e93\\U00016e94\\U00016e95\\U00016e96\\U0001d2e0\\U0001d2e1\\U0001d2e2\\U0001d2e3\\U0001d2e4\\U0001d2e5\\U0001d2e6\\U0001d2e7\\U0001d2e8\\U0001d2e9\\U0001d2ea\\U0001d2eb\\U0001d2ec\\U0001d2ed\\U0001d2ee\\U0001d2ef\\U0001d2f0\\U0001d2f1\\U0001d2f2\\U0001d2f3\\U0001d360\\U0001d361\\U0001d362\\U0001d363\\U0001d364\\U0001d365\\U0001d366\\U0001d367\\U0001d368\\U0001d369\\U0001d36a\\U0001d36b\\U0001d36c\\U0001d36d\\U0001d36e\\U0001d36f\\U0001d370\\U0001d371\\U0001d372\\U0001d373\\U0001d374\\U0001d375\\U0001d376\\U0001d377\\U0001d378\\U0001e8c7\\U0001e8c8\\U0001e8c9\\U0001e8ca\\U0001e8cb\\U0001e8cc\\U0001e8cd\\U0001e8ce\\U0001e8cf\\U0001ec71\\U0001ec72\\U0001ec73\\U0001ec74\\U0001ec75\\U0001ec76\\U0001ec77\\U0001ec78\\U0001ec79\\U0001ec7a\\U0001ec7b\\U0001ec7c\\U0001ec7d\\U0001ec7e\\U0001ec7f\\U0001ec80\\U0001ec81\\U0001ec82\\U0001ec83\\U0001ec84\\U0001ec85\\U0001ec86\\U0001ec87\\U0001ec88\\U0001ec89\\U0001ec8a\\U0001ec8b\\U0001ec8c\\U0001ec8d\\U0001ec8e\\U0001ec8f\\U0001ec90\\U0001ec91\\U0001ec92\\U0001ec93\\U0001ec94\\U0001ec95\\U0001ec96\\U0001ec97\\U0001ec98\\U0001ec99\\U0001ec9a\\U0001ec9b\\U0001ec9c\\U0001ec9d\\U0001ec9e\\U0001ec9f\\U0001eca0\\U0001eca1\\U0001eca2\\U0001eca3\\U0001eca4\\U0001eca5\\U0001eca6\\U0001eca7\\U0001eca8\\U0001eca9\\U0001ecaa\\U0001ecab\\U0001ecad\\U0001ecae\\U0001ecaf\\U0001ecb1\\U0001ecb2\\U0001ecb3\\U0001ecb4\\U0001ed01\\U0001ed02\\U0001ed03\\U0001ed04\\U0001ed05\\U0001ed06\\U0001ed07\\U0001ed08\\U0001ed09\\U0001ed0a\\U0001ed0b\\U0001ed0c\\U0001ed0d\\U0001ed0e\\U0001ed0f\\U0001ed10\\U0001ed11\\U0001ed12\\U0001ed13\\U0001ed14\\U0001ed15\\U0001ed16\\U0001ed17\\U0001ed18\\U0001ed19\\U0001ed1a\\U0001ed1b\\U0001ed1c\\U0001ed1d\\U0001ed1e\\U0001ed1f\\U0001ed20\\U0001ed21\\U0001ed22\\U0001ed23\\U0001ed24\\U0001ed25\\U0001ed26\\U0001ed27\\U0001ed28\\U0001ed29\\U0001ed2a\\U0001ed2b\\U0001ed2c\\U0001ed2d\\U0001ed2f\\U0001ed30\\U0001ed31\\U0001ed32\\U0001ed33\\U0001ed34\\U0001ed35\\U0001ed36\\U0001ed37\\U0001ed38\\U0001ed39\\U0001ed3a\\U0001ed3b\\U0001ed3c\\U0001ed3d\\U0001f100\\U0001f101\\U0001f102\\U0001f103\\U0001f104\\U0001f105\\U0001f106\\U0001f107\\U0001f108\\U0001f109\\U0001f10a\\U0001f10b\\U0001f10c\\U00020001\\U00020064\\U000200e2\\U00020121\\U0002092a\\U00020983\\U0002098c\\U0002099c\\U00020aea\\U00020afd\\U00020b19\\U00022390\\U00022998\\U00023b1b\\U0002626d\\U0002f890])]"
] | {
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2021-12-14T17:04:50Z" | mit |
|
SethMMorton__natsort-146 | diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2f81376..b1475fc 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,18 +1,22 @@
Unreleased
---
+### Changed
+- When using `ns.PATH`, only split off a maximum of two suffixes from
+ a file name (issues #145, #146).
+
[8.0.2] - 2021-12-14
---
### Fixed
-- Bug where sorting paths fail if one of the paths is '.'.
+- Bug where sorting paths fail if one of the paths is '.' (issues #142, #143)
[8.0.1] - 2021-12-10
---
### Fixed
- Compose unicode characters when using locale to ensure sorting is correct
- across all locales.
+ across all locales (issues #140, #141)
[8.0.0] - 2021-11-03
---
diff --git a/natsort/utils.py b/natsort/utils.py
index 8d56b06..3832318 100644
--- a/natsort/utils.py
+++ b/natsort/utils.py
@@ -893,16 +893,21 @@ def path_splitter(
path_parts = []
base = str(s)
- # Now, split off the file extensions until we reach a decimal number at
- # the beginning of the suffix or there are no more extensions.
- suffixes = PurePath(base).suffixes
- try:
- digit_index = next(i for i, x in enumerate(reversed(suffixes)) if _d_match(x))
- except StopIteration:
- pass
- else:
- digit_index = len(suffixes) - digit_index
- suffixes = suffixes[digit_index:]
-
+ # Now, split off the file extensions until
+ # - we reach a decimal number at the beginning of the suffix
+ # - more than two suffixes have been seen
+ # - a suffix is more than five characters (including leading ".")
+ # - there are no more extensions
+ suffixes = []
+ for i, suffix in enumerate(reversed(PurePath(base).suffixes)):
+ if _d_match(suffix) or i > 1 or len(suffix) > 5:
+ break
+ suffixes.append(suffix)
+ suffixes.reverse()
+
+ # Remove the suffixes from the base component
base = base.replace("".join(suffixes), "")
- return filter(None, ichain(path_parts, [base], suffixes))
+ base_component = [base] if base else []
+
+ # Join all path comonents in an iterator
+ return filter(None, ichain(path_parts, base_component, suffixes))
| SethMMorton/natsort | 4f0b3a8b005a0a43d2c21cf0b1e11c89186603b3 | diff --git a/tests/test_natsorted.py b/tests/test_natsorted.py
index 4a64a27..eb3aefe 100644
--- a/tests/test_natsorted.py
+++ b/tests/test_natsorted.py
@@ -182,6 +182,21 @@ def test_natsorted_handles_numbers_and_filesystem_paths_simultaneously() -> None
assert natsorted(given, alg=ns.PATH) == expected
+def test_natsorted_path_extensions_heuristic() -> None:
+ # https://github.com/SethMMorton/natsort/issues/145
+ given = [
+ "Try.Me.Bug - 09 - One.Two.Three.[text].mkv",
+ "Try.Me.Bug - 07 - One.Two.5.[text].mkv",
+ "Try.Me.Bug - 08 - One.Two.Three[text].mkv",
+ ]
+ expected = [
+ "Try.Me.Bug - 07 - One.Two.5.[text].mkv",
+ "Try.Me.Bug - 08 - One.Two.Three[text].mkv",
+ "Try.Me.Bug - 09 - One.Two.Three.[text].mkv",
+ ]
+ assert natsorted(given, alg=ns.PATH) == expected
+
+
@pytest.mark.parametrize(
"alg, expected",
[
diff --git a/tests/test_utils.py b/tests/test_utils.py
index bb229b9..b140682 100644
--- a/tests/test_utils.py
+++ b/tests/test_utils.py
@@ -6,7 +6,7 @@ import pathlib
import string
from itertools import chain
from operator import neg as op_neg
-from typing import List, Pattern, Union
+from typing import List, Pattern, Tuple, Union
import pytest
from hypothesis import given
@@ -155,9 +155,26 @@ def test_path_splitter_splits_path_string_by_sep(x: List[str]) -> None:
assert tuple(utils.path_splitter(z)) == tuple(pathlib.Path(z).parts)
-def test_path_splitter_splits_path_string_by_sep_and_removes_extension_example() -> None:
- given = "/this/is/a/path/file.x1.10.tar.gz"
- expected = (os.sep, "this", "is", "a", "path", "file.x1.10", ".tar", ".gz")
[email protected](
+ "given, expected",
+ [
+ (
+ "/this/is/a/path/file.x1.10.tar.gz",
+ (os.sep, "this", "is", "a", "path", "file.x1.10", ".tar", ".gz"),
+ ),
+ (
+ "/this/is/a/path/file.x1.10.tar",
+ (os.sep, "this", "is", "a", "path", "file.x1.10", ".tar"),
+ ),
+ (
+ "/this/is/a/path/file.x1.threethousand.tar",
+ (os.sep, "this", "is", "a", "path", "file.x1.threethousand", ".tar"),
+ ),
+ ],
+)
+def test_path_splitter_splits_path_string_by_sep_and_removes_extension_example(
+ given: str, expected: Tuple[str, ...]
+) -> None:
assert tuple(utils.path_splitter(given)) == tuple(expected)
| Wrong os_sorted sorting with special character in filename
**Describe the bug**
It can happen that the `os_sorted` functionality does not sort correctly files with special character inside
**Expected behavior**
File sorting equal to Windows Explorer
**Environment (please complete the following information):**
- Python Version: 3.9
- Natsort Version: 8.0.2
- OS Windows
- If the bug involves `LOCALE` or `humansorted`:
- Is `PyICU` installed? No
- Do you have a locale set? If so, to what? Italian
**To Reproduce**
```
from natsort import os_sorted
file_list = ['Try.Me.Bug - 09 - One.Two.Three.[text].mkv',
'Try.Me.Bug - 07 - One.Two.5.[text].mkv',
'Try.Me.Bug - 08 - One.Two.Three[text].mkv']
file_list2 = ['TryMe - 02 - One Two Three [text].mkv',
'TryMe_-_03_-_One_Two_Three_[text].mkv',
'TryMe_-_01_-_One_Two_Three_[text].mkv']
for file in os_sorted(file_list):
print(file)
for file in os_sorted(file_list2):
print(file)
```
**Expected sorting:**
file_list
Try.Me.Bug - 07 - One.Two.5.[text].mkv
Try.Me.Bug - 08 - One.Two.Three[text].mkv
Try.Me.Bug - 09 - One.Two.Three.[text].mkv
file_list2
TryMe\_-\_01\_-\_One\_Two\_Three\_[text].mkv
TryMe - 02 - One Two Three [text].mkv
TryMe\_-\_03_-\_One\_Two\_Three\_[text].mkv
**Actual sorting**
file_list
Try.Me.Bug - 08 - One.Two.Three[text].mkv
Try.Me.Bug - 09 - One.Two.Three.[text].mkv
Try.Me.Bug - 07 - One.Two.5.[text].mkv
file_list2
TryMe - 02 - One Two Three [text].mkv
TryMe\_-\_01\_-\_One\_Two\_Three\_[text].mkv
TryMe\_-\_03\_-\_One\_Two\_Three\_[text].mkv
------
At the moment the only way to overcome this issue is to use `os_sorted` along with `key=lambda x: re.sub(r'[^a-zA-Z0-9]+', ' ', x)` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_utils.py::test_path_splitter_splits_path_string_by_sep_and_removes_extension_example[/this/is/a/path/file.x1.threethousand.tar-expected2]",
"tests/test_natsorted.py::test_natsorted_path_extensions_heuristic"
] | [
"tests/test_utils.py::test_ns_enum_values_and_aliases[ns.COMPATIBILITYNORMALIZE-ns.COMPATIBILITYNORMALIZE]",
"tests/test_utils.py::test_ns_enum_values_and_aliases[ns.PATH-ns.PATH]",
"tests/test_utils.py::test_regex_chooser_returns_correct_regular_expression_object[6-([-+]?\\\\d+|[\\xb2\\xb3\\xb9\\u1369\\u136a\\u136b\\u136c\\u136d\\u136e\\u136f\\u1370\\u1371\\u19da\\u2070\\u2074\\u2075\\u2076\\u2077\\u2078\\u2079\\u2080\\u2081\\u2082\\u2083\\u2084\\u2085\\u2086\\u2087\\u2088\\u2089\\u2460\\u2461\\u2462\\u2463\\u2464\\u2465\\u2466\\u2467\\u2468\\u2474\\u2475\\u2476\\u2477\\u2478\\u2479\\u247a\\u247b\\u247c\\u2488\\u2489\\u248a\\u248b\\u248c\\u248d\\u248e\\u248f\\u2490\\u24ea\\u24f5\\u24f6\\u24f7\\u24f8\\u24f9\\u24fa\\u24fb\\u24fc\\u24fd\\u24ff\\u2776\\u2777\\u2778\\u2779\\u277a\\u277b\\u277c\\u277d\\u277e\\u2780\\u2781\\u2782\\u2783\\u2784\\u2785\\u2786\\u2787\\u2788\\u278a\\u278b\\u278c\\u278d\\u278e\\u278f\\u2790\\u2791\\u2792\\U00010a40\\U00010a41\\U00010a42\\U00010a43\\U00010e60\\U00010e61\\U00010e62\\U00010e63\\U00010e64\\U00010e65\\U00010e66\\U00010e67\\U00010e68\\U00011052\\U00011053\\U00011054\\U00011055\\U00011056\\U00011057\\U00011058\\U00011059\\U0001105a\\U0001f100\\U0001f101\\U0001f102\\U0001f103\\U0001f104\\U0001f105\\U0001f106\\U0001f107\\U0001f108\\U0001f109\\U0001f10a])]",
"tests/test_utils.py::test_path_splitter_handles_dot_properly[./]",
"tests/test_utils.py::test_regex_chooser_returns_correct_regular_expression_object[5-((?:\\\\d+\\\\.?\\\\d*|\\\\.\\\\d+)|[\\xb2\\xb3\\xb9\\xbc\\xbd\\xbe\\u09f4\\u09f5\\u09f6\\u09f7\\u09f8\\u09f9\\u0b72\\u0b73\\u0b74\\u0b75\\u0b76\\u0b77\\u0bf0\\u0bf1\\u0bf2\\u0c78\\u0c79\\u0c7a\\u0c7b\\u0c7c\\u0c7d\\u0c7e\\u0d58\\u0d59\\u0d5a\\u0d5b\\u0d5c\\u0d5d\\u0d5e\\u0d70\\u0d71\\u0d72\\u0d73\\u0d74\\u0d75\\u0d76\\u0d77\\u0d78\\u0f2a\\u0f2b\\u0f2c\\u0f2d\\u0f2e\\u0f2f\\u0f30\\u0f31\\u0f32\\u0f33\\u1369\\u136a\\u136b\\u136c\\u136d\\u136e\\u136f\\u1370\\u1371\\u1372\\u1373\\u1374\\u1375\\u1376\\u1377\\u1378\\u1379\\u137a\\u137b\\u137c\\u16ee\\u16ef\\u16f0\\u17f0\\u17f1\\u17f2\\u17f3\\u17f4\\u17f5\\u17f6\\u17f7\\u17f8\\u17f9\\u19da\\u2070\\u2074\\u2075\\u2076\\u2077\\u2078\\u2079\\u2080\\u2081\\u2082\\u2083\\u2084\\u2085\\u2086\\u2087\\u2088\\u2089\\u2150\\u2151\\u2152\\u2153\\u2154\\u2155\\u2156\\u2157\\u2158\\u2159\\u215a\\u215b\\u215c\\u215d\\u215e\\u215f\\u2160\\u2161\\u2162\\u2163\\u2164\\u2165\\u2166\\u2167\\u2168\\u2169\\u216a\\u216b\\u216c\\u216d\\u216e\\u216f\\u2170\\u2171\\u2172\\u2173\\u2174\\u2175\\u2176\\u2177\\u2178\\u2179\\u217a\\u217b\\u217c\\u217d\\u217e\\u217f\\u2180\\u2181\\u2182\\u2185\\u2186\\u2187\\u2188\\u2189\\u2460\\u2461\\u2462\\u2463\\u2464\\u2465\\u2466\\u2467\\u2468\\u2469\\u246a\\u246b\\u246c\\u246d\\u246e\\u246f\\u2470\\u2471\\u2472\\u2473\\u2474\\u2475\\u2476\\u2477\\u2478\\u2479\\u247a\\u247b\\u247c\\u247d\\u247e\\u247f\\u2480\\u2481\\u2482\\u2483\\u2484\\u2485\\u2486\\u2487\\u2488\\u2489\\u248a\\u248b\\u248c\\u248d\\u248e\\u248f\\u2490\\u2491\\u2492\\u2493\\u2494\\u2495\\u2496\\u2497\\u2498\\u2499\\u249a\\u249b\\u24ea\\u24eb\\u24ec\\u24ed\\u24ee\\u24ef\\u24f0\\u24f1\\u24f2\\u24f3\\u24f4\\u24f5\\u24f6\\u24f7\\u24f8\\u24f9\\u24fa\\u24fb\\u24fc\\u24fd\\u24fe\\u24ff\\u2776\\u2777\\u2778\\u2779\\u277a\\u277b\\u277c\\u277d\\u277e\\u277f\\u2780\\u2781\\u2782\\u2783\\u2784\\u2785\\u2786\\u2787\\u2788\\u2789\\u278a\\u278b\\u278c\\u278d\\u278e\\u278f\\u2790\\u2791\\u2792\\u2793\\u2cfd\\u3007\\u3021\\u3022\\u3023\\u3024\\u3025\\u3026\\u3027\\u3028\\u3029\\u3038\\u3039\\u303a\\u3192\\u3193\\u3194\\u3195\\u3220\\u3221\\u3222\\u3223\\u3224\\u3225\\u3226\\u3227\\u3228\\u3229\\u3248\\u3249\\u324a\\u324b\\u324c\\u324d\\u324e\\u324f\\u3251\\u3252\\u3253\\u3254\\u3255\\u3256\\u3257\\u3258\\u3259\\u325a\\u325b\\u325c\\u325d\\u325e\\u325f\\u3280\\u3281\\u3282\\u3283\\u3284\\u3285\\u3286\\u3287\\u3288\\u3289\\u32b1\\u32b2\\u32b3\\u32b4\\u32b5\\u32b6\\u32b7\\u32b8\\u32b9\\u32ba\\u32bb\\u32bc\\u32bd\\u32be\\u32bf\\u3405\\u3483\\u382a\\u3b4d\\u4e00\\u4e03\\u4e07\\u4e09\\u4e5d\\u4e8c\\u4e94\\u4e96\\u4ebf\\u4ec0\\u4edf\\u4ee8\\u4f0d\\u4f70\\u5104\\u5146\\u5169\\u516b\\u516d\\u5341\\u5343\\u5344\\u5345\\u534c\\u53c1\\u53c2\\u53c3\\u53c4\\u56db\\u58f1\\u58f9\\u5e7a\\u5efe\\u5eff\\u5f0c\\u5f0d\\u5f0e\\u5f10\\u62fe\\u634c\\u67d2\\u6f06\\u7396\\u767e\\u8086\\u842c\\u8cae\\u8cb3\\u8d30\\u9621\\u9646\\u964c\\u9678\\u96f6\\ua6e6\\ua6e7\\ua6e8\\ua6e9\\ua6ea\\ua6eb\\ua6ec\\ua6ed\\ua6ee\\ua6ef\\ua830\\ua831\\ua832\\ua833\\ua834\\ua835\\uf96b\\uf973\\uf978\\uf9b2\\uf9d1\\uf9d3\\uf9fd\\U00010107\\U00010108\\U00010109\\U0001010a\\U0001010b\\U0001010c\\U0001010d\\U0001010e\\U0001010f\\U00010110\\U00010111\\U00010112\\U00010113\\U00010114\\U00010115\\U00010116\\U00010117\\U00010118\\U00010119\\U0001011a\\U0001011b\\U0001011c\\U0001011d\\U0001011e\\U0001011f\\U00010120\\U00010121\\U00010122\\U00010123\\U00010124\\U00010125\\U00010126\\U00010127\\U00010128\\U00010129\\U0001012a\\U0001012b\\U0001012c\\U0001012d\\U0001012e\\U0001012f\\U00010130\\U00010131\\U00010132\\U00010133\\U00010140\\U00010141\\U00010142\\U00010143\\U00010144\\U00010145\\U00010146\\U00010147\\U00010148\\U00010149\\U0001014a\\U0001014b\\U0001014c\\U0001014d\\U0001014e\\U0001014f\\U00010150\\U00010151\\U00010152\\U00010153\\U00010154\\U00010155\\U00010156\\U00010157\\U00010158\\U00010159\\U0001015a\\U0001015b\\U0001015c\\U0001015d\\U0001015e\\U0001015f\\U00010160\\U00010161\\U00010162\\U00010163\\U00010164\\U00010165\\U00010166\\U00010167\\U00010168\\U00010169\\U0001016a\\U0001016b\\U0001016c\\U0001016d\\U0001016e\\U0001016f\\U00010170\\U00010171\\U00010172\\U00010173\\U00010174\\U00010175\\U00010176\\U00010177\\U00010178\\U0001018a\\U0001018b\\U000102e1\\U000102e2\\U000102e3\\U000102e4\\U000102e5\\U000102e6\\U000102e7\\U000102e8\\U000102e9\\U000102ea\\U000102eb\\U000102ec\\U000102ed\\U000102ee\\U000102ef\\U000102f0\\U000102f1\\U000102f2\\U000102f3\\U000102f4\\U000102f5\\U000102f6\\U000102f7\\U000102f8\\U000102f9\\U000102fa\\U000102fb\\U00010320\\U00010321\\U00010322\\U00010323\\U00010341\\U0001034a\\U000103d1\\U000103d2\\U000103d3\\U000103d4\\U000103d5\\U00010858\\U00010859\\U0001085a\\U0001085b\\U0001085c\\U0001085d\\U0001085e\\U0001085f\\U00010879\\U0001087a\\U0001087b\\U0001087c\\U0001087d\\U0001087e\\U0001087f\\U000108a7\\U000108a8\\U000108a9\\U000108aa\\U000108ab\\U000108ac\\U000108ad\\U000108ae\\U000108af\\U000108fb\\U000108fc\\U000108fd\\U000108fe\\U000108ff\\U00010916\\U00010917\\U00010918\\U00010919\\U0001091a\\U0001091b\\U000109bc\\U000109bd\\U000109c0\\U000109c1\\U000109c2\\U000109c3\\U000109c4\\U000109c5\\U000109c6\\U000109c7\\U000109c8\\U000109c9\\U000109ca\\U000109cb\\U000109cc\\U000109cd\\U000109ce\\U000109cf\\U000109d2\\U000109d3\\U000109d4\\U000109d5\\U000109d6\\U000109d7\\U000109d8\\U000109d9\\U000109da\\U000109db\\U000109dc\\U000109dd\\U000109de\\U000109df\\U000109e0\\U000109e1\\U000109e2\\U000109e3\\U000109e4\\U000109e5\\U000109e6\\U000109e7\\U000109e8\\U000109e9\\U000109ea\\U000109eb\\U000109ec\\U000109ed\\U000109ee\\U000109ef\\U000109f0\\U000109f1\\U000109f2\\U000109f3\\U000109f4\\U000109f5\\U000109f6\\U000109f7\\U000109f8\\U000109f9\\U000109fa\\U000109fb\\U000109fc\\U000109fd\\U000109fe\\U000109ff\\U00010a40\\U00010a41\\U00010a42\\U00010a43\\U00010a44\\U00010a45\\U00010a46\\U00010a47\\U00010a48\\U00010a7d\\U00010a7e\\U00010a9d\\U00010a9e\\U00010a9f\\U00010aeb\\U00010aec\\U00010aed\\U00010aee\\U00010aef\\U00010b58\\U00010b59\\U00010b5a\\U00010b5b\\U00010b5c\\U00010b5d\\U00010b5e\\U00010b5f\\U00010b78\\U00010b79\\U00010b7a\\U00010b7b\\U00010b7c\\U00010b7d\\U00010b7e\\U00010b7f\\U00010ba9\\U00010baa\\U00010bab\\U00010bac\\U00010bad\\U00010bae\\U00010baf\\U00010cfa\\U00010cfb\\U00010cfc\\U00010cfd\\U00010cfe\\U00010cff\\U00010e60\\U00010e61\\U00010e62\\U00010e63\\U00010e64\\U00010e65\\U00010e66\\U00010e67\\U00010e68\\U00010e69\\U00010e6a\\U00010e6b\\U00010e6c\\U00010e6d\\U00010e6e\\U00010e6f\\U00010e70\\U00010e71\\U00010e72\\U00010e73\\U00010e74\\U00010e75\\U00010e76\\U00010e77\\U00010e78\\U00010e79\\U00010e7a\\U00010e7b\\U00010e7c\\U00010e7d\\U00010e7e\\U00010f1d\\U00010f1e\\U00010f1f\\U00010f20\\U00010f21\\U00010f22\\U00010f23\\U00010f24\\U00010f25\\U00010f26\\U00010f51\\U00010f52\\U00010f53\\U00010f54\\U00010fc5\\U00010fc6\\U00010fc7\\U00010fc8\\U00010fc9\\U00010fca\\U00010fcb\\U00011052\\U00011053\\U00011054\\U00011055\\U00011056\\U00011057\\U00011058\\U00011059\\U0001105a\\U0001105b\\U0001105c\\U0001105d\\U0001105e\\U0001105f\\U00011060\\U00011061\\U00011062\\U00011063\\U00011064\\U00011065\\U000111e1\\U000111e2\\U000111e3\\U000111e4\\U000111e5\\U000111e6\\U000111e7\\U000111e8\\U000111e9\\U000111ea\\U000111eb\\U000111ec\\U000111ed\\U000111ee\\U000111ef\\U000111f0\\U000111f1\\U000111f2\\U000111f3\\U000111f4\\U0001173a\\U0001173b\\U000118ea\\U000118eb\\U000118ec\\U000118ed\\U000118ee\\U000118ef\\U000118f0\\U000118f1\\U000118f2\\U00011c5a\\U00011c5b\\U00011c5c\\U00011c5d\\U00011c5e\\U00011c5f\\U00011c60\\U00011c61\\U00011c62\\U00011c63\\U00011c64\\U00011c65\\U00011c66\\U00011c67\\U00011c68\\U00011c69\\U00011c6a\\U00011c6b\\U00011c6c\\U00011fc0\\U00011fc1\\U00011fc2\\U00011fc3\\U00011fc4\\U00011fc5\\U00011fc6\\U00011fc7\\U00011fc8\\U00011fc9\\U00011fca\\U00011fcb\\U00011fcc\\U00011fcd\\U00011fce\\U00011fcf\\U00011fd0\\U00011fd1\\U00011fd2\\U00011fd3\\U00011fd4\\U00012400\\U00012401\\U00012402\\U00012403\\U00012404\\U00012405\\U00012406\\U00012407\\U00012408\\U00012409\\U0001240a\\U0001240b\\U0001240c\\U0001240d\\U0001240e\\U0001240f\\U00012410\\U00012411\\U00012412\\U00012413\\U00012414\\U00012415\\U00012416\\U00012417\\U00012418\\U00012419\\U0001241a\\U0001241b\\U0001241c\\U0001241d\\U0001241e\\U0001241f\\U00012420\\U00012421\\U00012422\\U00012423\\U00012424\\U00012425\\U00012426\\U00012427\\U00012428\\U00012429\\U0001242a\\U0001242b\\U0001242c\\U0001242d\\U0001242e\\U0001242f\\U00012430\\U00012431\\U00012432\\U00012433\\U00012434\\U00012435\\U00012436\\U00012437\\U00012438\\U00012439\\U0001243a\\U0001243b\\U0001243c\\U0001243d\\U0001243e\\U0001243f\\U00012440\\U00012441\\U00012442\\U00012443\\U00012444\\U00012445\\U00012446\\U00012447\\U00012448\\U00012449\\U0001244a\\U0001244b\\U0001244c\\U0001244d\\U0001244e\\U0001244f\\U00012450\\U00012451\\U00012452\\U00012453\\U00012454\\U00012455\\U00012456\\U00012457\\U00012458\\U00012459\\U0001245a\\U0001245b\\U0001245c\\U0001245d\\U0001245e\\U0001245f\\U00012460\\U00012461\\U00012462\\U00012463\\U00012464\\U00012465\\U00012466\\U00012467\\U00012468\\U00012469\\U0001246a\\U0001246b\\U0001246c\\U0001246d\\U0001246e\\U00016b5b\\U00016b5c\\U00016b5d\\U00016b5e\\U00016b5f\\U00016b60\\U00016b61\\U00016e80\\U00016e81\\U00016e82\\U00016e83\\U00016e84\\U00016e85\\U00016e86\\U00016e87\\U00016e88\\U00016e89\\U00016e8a\\U00016e8b\\U00016e8c\\U00016e8d\\U00016e8e\\U00016e8f\\U00016e90\\U00016e91\\U00016e92\\U00016e93\\U00016e94\\U00016e95\\U00016e96\\U0001d2e0\\U0001d2e1\\U0001d2e2\\U0001d2e3\\U0001d2e4\\U0001d2e5\\U0001d2e6\\U0001d2e7\\U0001d2e8\\U0001d2e9\\U0001d2ea\\U0001d2eb\\U0001d2ec\\U0001d2ed\\U0001d2ee\\U0001d2ef\\U0001d2f0\\U0001d2f1\\U0001d2f2\\U0001d2f3\\U0001d360\\U0001d361\\U0001d362\\U0001d363\\U0001d364\\U0001d365\\U0001d366\\U0001d367\\U0001d368\\U0001d369\\U0001d36a\\U0001d36b\\U0001d36c\\U0001d36d\\U0001d36e\\U0001d36f\\U0001d370\\U0001d371\\U0001d372\\U0001d373\\U0001d374\\U0001d375\\U0001d376\\U0001d377\\U0001d378\\U0001e8c7\\U0001e8c8\\U0001e8c9\\U0001e8ca\\U0001e8cb\\U0001e8cc\\U0001e8cd\\U0001e8ce\\U0001e8cf\\U0001ec71\\U0001ec72\\U0001ec73\\U0001ec74\\U0001ec75\\U0001ec76\\U0001ec77\\U0001ec78\\U0001ec79\\U0001ec7a\\U0001ec7b\\U0001ec7c\\U0001ec7d\\U0001ec7e\\U0001ec7f\\U0001ec80\\U0001ec81\\U0001ec82\\U0001ec83\\U0001ec84\\U0001ec85\\U0001ec86\\U0001ec87\\U0001ec88\\U0001ec89\\U0001ec8a\\U0001ec8b\\U0001ec8c\\U0001ec8d\\U0001ec8e\\U0001ec8f\\U0001ec90\\U0001ec91\\U0001ec92\\U0001ec93\\U0001ec94\\U0001ec95\\U0001ec96\\U0001ec97\\U0001ec98\\U0001ec99\\U0001ec9a\\U0001ec9b\\U0001ec9c\\U0001ec9d\\U0001ec9e\\U0001ec9f\\U0001eca0\\U0001eca1\\U0001eca2\\U0001eca3\\U0001eca4\\U0001eca5\\U0001eca6\\U0001eca7\\U0001eca8\\U0001eca9\\U0001ecaa\\U0001ecab\\U0001ecad\\U0001ecae\\U0001ecaf\\U0001ecb1\\U0001ecb2\\U0001ecb3\\U0001ecb4\\U0001ed01\\U0001ed02\\U0001ed03\\U0001ed04\\U0001ed05\\U0001ed06\\U0001ed07\\U0001ed08\\U0001ed09\\U0001ed0a\\U0001ed0b\\U0001ed0c\\U0001ed0d\\U0001ed0e\\U0001ed0f\\U0001ed10\\U0001ed11\\U0001ed12\\U0001ed13\\U0001ed14\\U0001ed15\\U0001ed16\\U0001ed17\\U0001ed18\\U0001ed19\\U0001ed1a\\U0001ed1b\\U0001ed1c\\U0001ed1d\\U0001ed1e\\U0001ed1f\\U0001ed20\\U0001ed21\\U0001ed22\\U0001ed23\\U0001ed24\\U0001ed25\\U0001ed26\\U0001ed27\\U0001ed28\\U0001ed29\\U0001ed2a\\U0001ed2b\\U0001ed2c\\U0001ed2d\\U0001ed2f\\U0001ed30\\U0001ed31\\U0001ed32\\U0001ed33\\U0001ed34\\U0001ed35\\U0001ed36\\U0001ed37\\U0001ed38\\U0001ed39\\U0001ed3a\\U0001ed3b\\U0001ed3c\\U0001ed3d\\U0001f100\\U0001f101\\U0001f102\\U0001f103\\U0001f104\\U0001f105\\U0001f106\\U0001f107\\U0001f108\\U0001f109\\U0001f10a\\U0001f10b\\U0001f10c\\U00020001\\U00020064\\U000200e2\\U00020121\\U0002092a\\U00020983\\U0002098c\\U0002099c\\U00020aea\\U00020afd\\U00020b19\\U00022390\\U00022998\\U00023b1b\\U0002626d\\U0002f890])]",
"tests/test_utils.py::test_ns_enum_values_and_aliases[ns.DEFAULT-ns.DEFAULT0]",
"tests/test_utils.py::test_ns_enum_values_and_aliases[ns.DEFAULT-ns.DEFAULT1]",
"tests/test_utils.py::test_ns_enum_values_and_aliases[ns.LOCALENUM-ns.LOCALENUM]",
"tests/test_utils.py::test_ns_enum_values_and_aliases[ns.LOCALE-ns.LOCALE]",
"tests/test_utils.py::test_ns_enum_values_and_aliases[ns.UNGROUPLETTERS-ns.UNGROUPLETTERS1]",
"tests/test_utils.py::test_path_splitter_splits_path_string_by_sep",
"tests/test_utils.py::test_path_splitter_splits_path_string_by_sep_example",
"tests/test_utils.py::test_chain_functions_does_one_function_if_one_function_is_given",
"tests/test_utils.py::test_path_splitter_splits_path_string_by_sep_and_removes_extension",
"tests/test_utils.py::test_do_decoding_decodes_bytes_string_to_unicode",
"tests/test_utils.py::test_path_splitter_handles_dot_properly[./././]",
"tests/test_utils.py::test_ns_enum_values_and_aliases[ns.DEFAULT-0_0]",
"tests/test_utils.py::test_path_splitter_splits_path_string_by_sep_and_removes_extension_example[/this/is/a/path/file.x1.10.tar-expected1]",
"tests/test_utils.py::test_ns_enum_values_and_aliases[ns.UNGROUPLETTERS-ns.UNGROUPLETTERS2]",
"tests/test_utils.py::test_regex_chooser_returns_correct_regular_expression_object[ns.FLOAT-((?:\\\\d+\\\\.?\\\\d*|\\\\.\\\\d+)(?:[eE][-+]?\\\\d+)?|[\\xb2\\xb3\\xb9\\xbc\\xbd\\xbe\\u09f4\\u09f5\\u09f6\\u09f7\\u09f8\\u09f9\\u0b72\\u0b73\\u0b74\\u0b75\\u0b76\\u0b77\\u0bf0\\u0bf1\\u0bf2\\u0c78\\u0c79\\u0c7a\\u0c7b\\u0c7c\\u0c7d\\u0c7e\\u0d58\\u0d59\\u0d5a\\u0d5b\\u0d5c\\u0d5d\\u0d5e\\u0d70\\u0d71\\u0d72\\u0d73\\u0d74\\u0d75\\u0d76\\u0d77\\u0d78\\u0f2a\\u0f2b\\u0f2c\\u0f2d\\u0f2e\\u0f2f\\u0f30\\u0f31\\u0f32\\u0f33\\u1369\\u136a\\u136b\\u136c\\u136d\\u136e\\u136f\\u1370\\u1371\\u1372\\u1373\\u1374\\u1375\\u1376\\u1377\\u1378\\u1379\\u137a\\u137b\\u137c\\u16ee\\u16ef\\u16f0\\u17f0\\u17f1\\u17f2\\u17f3\\u17f4\\u17f5\\u17f6\\u17f7\\u17f8\\u17f9\\u19da\\u2070\\u2074\\u2075\\u2076\\u2077\\u2078\\u2079\\u2080\\u2081\\u2082\\u2083\\u2084\\u2085\\u2086\\u2087\\u2088\\u2089\\u2150\\u2151\\u2152\\u2153\\u2154\\u2155\\u2156\\u2157\\u2158\\u2159\\u215a\\u215b\\u215c\\u215d\\u215e\\u215f\\u2160\\u2161\\u2162\\u2163\\u2164\\u2165\\u2166\\u2167\\u2168\\u2169\\u216a\\u216b\\u216c\\u216d\\u216e\\u216f\\u2170\\u2171\\u2172\\u2173\\u2174\\u2175\\u2176\\u2177\\u2178\\u2179\\u217a\\u217b\\u217c\\u217d\\u217e\\u217f\\u2180\\u2181\\u2182\\u2185\\u2186\\u2187\\u2188\\u2189\\u2460\\u2461\\u2462\\u2463\\u2464\\u2465\\u2466\\u2467\\u2468\\u2469\\u246a\\u246b\\u246c\\u246d\\u246e\\u246f\\u2470\\u2471\\u2472\\u2473\\u2474\\u2475\\u2476\\u2477\\u2478\\u2479\\u247a\\u247b\\u247c\\u247d\\u247e\\u247f\\u2480\\u2481\\u2482\\u2483\\u2484\\u2485\\u2486\\u2487\\u2488\\u2489\\u248a\\u248b\\u248c\\u248d\\u248e\\u248f\\u2490\\u2491\\u2492\\u2493\\u2494\\u2495\\u2496\\u2497\\u2498\\u2499\\u249a\\u249b\\u24ea\\u24eb\\u24ec\\u24ed\\u24ee\\u24ef\\u24f0\\u24f1\\u24f2\\u24f3\\u24f4\\u24f5\\u24f6\\u24f7\\u24f8\\u24f9\\u24fa\\u24fb\\u24fc\\u24fd\\u24fe\\u24ff\\u2776\\u2777\\u2778\\u2779\\u277a\\u277b\\u277c\\u277d\\u277e\\u277f\\u2780\\u2781\\u2782\\u2783\\u2784\\u2785\\u2786\\u2787\\u2788\\u2789\\u278a\\u278b\\u278c\\u278d\\u278e\\u278f\\u2790\\u2791\\u2792\\u2793\\u2cfd\\u3007\\u3021\\u3022\\u3023\\u3024\\u3025\\u3026\\u3027\\u3028\\u3029\\u3038\\u3039\\u303a\\u3192\\u3193\\u3194\\u3195\\u3220\\u3221\\u3222\\u3223\\u3224\\u3225\\u3226\\u3227\\u3228\\u3229\\u3248\\u3249\\u324a\\u324b\\u324c\\u324d\\u324e\\u324f\\u3251\\u3252\\u3253\\u3254\\u3255\\u3256\\u3257\\u3258\\u3259\\u325a\\u325b\\u325c\\u325d\\u325e\\u325f\\u3280\\u3281\\u3282\\u3283\\u3284\\u3285\\u3286\\u3287\\u3288\\u3289\\u32b1\\u32b2\\u32b3\\u32b4\\u32b5\\u32b6\\u32b7\\u32b8\\u32b9\\u32ba\\u32bb\\u32bc\\u32bd\\u32be\\u32bf\\u3405\\u3483\\u382a\\u3b4d\\u4e00\\u4e03\\u4e07\\u4e09\\u4e5d\\u4e8c\\u4e94\\u4e96\\u4ebf\\u4ec0\\u4edf\\u4ee8\\u4f0d\\u4f70\\u5104\\u5146\\u5169\\u516b\\u516d\\u5341\\u5343\\u5344\\u5345\\u534c\\u53c1\\u53c2\\u53c3\\u53c4\\u56db\\u58f1\\u58f9\\u5e7a\\u5efe\\u5eff\\u5f0c\\u5f0d\\u5f0e\\u5f10\\u62fe\\u634c\\u67d2\\u6f06\\u7396\\u767e\\u8086\\u842c\\u8cae\\u8cb3\\u8d30\\u9621\\u9646\\u964c\\u9678\\u96f6\\ua6e6\\ua6e7\\ua6e8\\ua6e9\\ua6ea\\ua6eb\\ua6ec\\ua6ed\\ua6ee\\ua6ef\\ua830\\ua831\\ua832\\ua833\\ua834\\ua835\\uf96b\\uf973\\uf978\\uf9b2\\uf9d1\\uf9d3\\uf9fd\\U00010107\\U00010108\\U00010109\\U0001010a\\U0001010b\\U0001010c\\U0001010d\\U0001010e\\U0001010f\\U00010110\\U00010111\\U00010112\\U00010113\\U00010114\\U00010115\\U00010116\\U00010117\\U00010118\\U00010119\\U0001011a\\U0001011b\\U0001011c\\U0001011d\\U0001011e\\U0001011f\\U00010120\\U00010121\\U00010122\\U00010123\\U00010124\\U00010125\\U00010126\\U00010127\\U00010128\\U00010129\\U0001012a\\U0001012b\\U0001012c\\U0001012d\\U0001012e\\U0001012f\\U00010130\\U00010131\\U00010132\\U00010133\\U00010140\\U00010141\\U00010142\\U00010143\\U00010144\\U00010145\\U00010146\\U00010147\\U00010148\\U00010149\\U0001014a\\U0001014b\\U0001014c\\U0001014d\\U0001014e\\U0001014f\\U00010150\\U00010151\\U00010152\\U00010153\\U00010154\\U00010155\\U00010156\\U00010157\\U00010158\\U00010159\\U0001015a\\U0001015b\\U0001015c\\U0001015d\\U0001015e\\U0001015f\\U00010160\\U00010161\\U00010162\\U00010163\\U00010164\\U00010165\\U00010166\\U00010167\\U00010168\\U00010169\\U0001016a\\U0001016b\\U0001016c\\U0001016d\\U0001016e\\U0001016f\\U00010170\\U00010171\\U00010172\\U00010173\\U00010174\\U00010175\\U00010176\\U00010177\\U00010178\\U0001018a\\U0001018b\\U000102e1\\U000102e2\\U000102e3\\U000102e4\\U000102e5\\U000102e6\\U000102e7\\U000102e8\\U000102e9\\U000102ea\\U000102eb\\U000102ec\\U000102ed\\U000102ee\\U000102ef\\U000102f0\\U000102f1\\U000102f2\\U000102f3\\U000102f4\\U000102f5\\U000102f6\\U000102f7\\U000102f8\\U000102f9\\U000102fa\\U000102fb\\U00010320\\U00010321\\U00010322\\U00010323\\U00010341\\U0001034a\\U000103d1\\U000103d2\\U000103d3\\U000103d4\\U000103d5\\U00010858\\U00010859\\U0001085a\\U0001085b\\U0001085c\\U0001085d\\U0001085e\\U0001085f\\U00010879\\U0001087a\\U0001087b\\U0001087c\\U0001087d\\U0001087e\\U0001087f\\U000108a7\\U000108a8\\U000108a9\\U000108aa\\U000108ab\\U000108ac\\U000108ad\\U000108ae\\U000108af\\U000108fb\\U000108fc\\U000108fd\\U000108fe\\U000108ff\\U00010916\\U00010917\\U00010918\\U00010919\\U0001091a\\U0001091b\\U000109bc\\U000109bd\\U000109c0\\U000109c1\\U000109c2\\U000109c3\\U000109c4\\U000109c5\\U000109c6\\U000109c7\\U000109c8\\U000109c9\\U000109ca\\U000109cb\\U000109cc\\U000109cd\\U000109ce\\U000109cf\\U000109d2\\U000109d3\\U000109d4\\U000109d5\\U000109d6\\U000109d7\\U000109d8\\U000109d9\\U000109da\\U000109db\\U000109dc\\U000109dd\\U000109de\\U000109df\\U000109e0\\U000109e1\\U000109e2\\U000109e3\\U000109e4\\U000109e5\\U000109e6\\U000109e7\\U000109e8\\U000109e9\\U000109ea\\U000109eb\\U000109ec\\U000109ed\\U000109ee\\U000109ef\\U000109f0\\U000109f1\\U000109f2\\U000109f3\\U000109f4\\U000109f5\\U000109f6\\U000109f7\\U000109f8\\U000109f9\\U000109fa\\U000109fb\\U000109fc\\U000109fd\\U000109fe\\U000109ff\\U00010a40\\U00010a41\\U00010a42\\U00010a43\\U00010a44\\U00010a45\\U00010a46\\U00010a47\\U00010a48\\U00010a7d\\U00010a7e\\U00010a9d\\U00010a9e\\U00010a9f\\U00010aeb\\U00010aec\\U00010aed\\U00010aee\\U00010aef\\U00010b58\\U00010b59\\U00010b5a\\U00010b5b\\U00010b5c\\U00010b5d\\U00010b5e\\U00010b5f\\U00010b78\\U00010b79\\U00010b7a\\U00010b7b\\U00010b7c\\U00010b7d\\U00010b7e\\U00010b7f\\U00010ba9\\U00010baa\\U00010bab\\U00010bac\\U00010bad\\U00010bae\\U00010baf\\U00010cfa\\U00010cfb\\U00010cfc\\U00010cfd\\U00010cfe\\U00010cff\\U00010e60\\U00010e61\\U00010e62\\U00010e63\\U00010e64\\U00010e65\\U00010e66\\U00010e67\\U00010e68\\U00010e69\\U00010e6a\\U00010e6b\\U00010e6c\\U00010e6d\\U00010e6e\\U00010e6f\\U00010e70\\U00010e71\\U00010e72\\U00010e73\\U00010e74\\U00010e75\\U00010e76\\U00010e77\\U00010e78\\U00010e79\\U00010e7a\\U00010e7b\\U00010e7c\\U00010e7d\\U00010e7e\\U00010f1d\\U00010f1e\\U00010f1f\\U00010f20\\U00010f21\\U00010f22\\U00010f23\\U00010f24\\U00010f25\\U00010f26\\U00010f51\\U00010f52\\U00010f53\\U00010f54\\U00010fc5\\U00010fc6\\U00010fc7\\U00010fc8\\U00010fc9\\U00010fca\\U00010fcb\\U00011052\\U00011053\\U00011054\\U00011055\\U00011056\\U00011057\\U00011058\\U00011059\\U0001105a\\U0001105b\\U0001105c\\U0001105d\\U0001105e\\U0001105f\\U00011060\\U00011061\\U00011062\\U00011063\\U00011064\\U00011065\\U000111e1\\U000111e2\\U000111e3\\U000111e4\\U000111e5\\U000111e6\\U000111e7\\U000111e8\\U000111e9\\U000111ea\\U000111eb\\U000111ec\\U000111ed\\U000111ee\\U000111ef\\U000111f0\\U000111f1\\U000111f2\\U000111f3\\U000111f4\\U0001173a\\U0001173b\\U000118ea\\U000118eb\\U000118ec\\U000118ed\\U000118ee\\U000118ef\\U000118f0\\U000118f1\\U000118f2\\U00011c5a\\U00011c5b\\U00011c5c\\U00011c5d\\U00011c5e\\U00011c5f\\U00011c60\\U00011c61\\U00011c62\\U00011c63\\U00011c64\\U00011c65\\U00011c66\\U00011c67\\U00011c68\\U00011c69\\U00011c6a\\U00011c6b\\U00011c6c\\U00011fc0\\U00011fc1\\U00011fc2\\U00011fc3\\U00011fc4\\U00011fc5\\U00011fc6\\U00011fc7\\U00011fc8\\U00011fc9\\U00011fca\\U00011fcb\\U00011fcc\\U00011fcd\\U00011fce\\U00011fcf\\U00011fd0\\U00011fd1\\U00011fd2\\U00011fd3\\U00011fd4\\U00012400\\U00012401\\U00012402\\U00012403\\U00012404\\U00012405\\U00012406\\U00012407\\U00012408\\U00012409\\U0001240a\\U0001240b\\U0001240c\\U0001240d\\U0001240e\\U0001240f\\U00012410\\U00012411\\U00012412\\U00012413\\U00012414\\U00012415\\U00012416\\U00012417\\U00012418\\U00012419\\U0001241a\\U0001241b\\U0001241c\\U0001241d\\U0001241e\\U0001241f\\U00012420\\U00012421\\U00012422\\U00012423\\U00012424\\U00012425\\U00012426\\U00012427\\U00012428\\U00012429\\U0001242a\\U0001242b\\U0001242c\\U0001242d\\U0001242e\\U0001242f\\U00012430\\U00012431\\U00012432\\U00012433\\U00012434\\U00012435\\U00012436\\U00012437\\U00012438\\U00012439\\U0001243a\\U0001243b\\U0001243c\\U0001243d\\U0001243e\\U0001243f\\U00012440\\U00012441\\U00012442\\U00012443\\U00012444\\U00012445\\U00012446\\U00012447\\U00012448\\U00012449\\U0001244a\\U0001244b\\U0001244c\\U0001244d\\U0001244e\\U0001244f\\U00012450\\U00012451\\U00012452\\U00012453\\U00012454\\U00012455\\U00012456\\U00012457\\U00012458\\U00012459\\U0001245a\\U0001245b\\U0001245c\\U0001245d\\U0001245e\\U0001245f\\U00012460\\U00012461\\U00012462\\U00012463\\U00012464\\U00012465\\U00012466\\U00012467\\U00012468\\U00012469\\U0001246a\\U0001246b\\U0001246c\\U0001246d\\U0001246e\\U00016b5b\\U00016b5c\\U00016b5d\\U00016b5e\\U00016b5f\\U00016b60\\U00016b61\\U00016e80\\U00016e81\\U00016e82\\U00016e83\\U00016e84\\U00016e85\\U00016e86\\U00016e87\\U00016e88\\U00016e89\\U00016e8a\\U00016e8b\\U00016e8c\\U00016e8d\\U00016e8e\\U00016e8f\\U00016e90\\U00016e91\\U00016e92\\U00016e93\\U00016e94\\U00016e95\\U00016e96\\U0001d2e0\\U0001d2e1\\U0001d2e2\\U0001d2e3\\U0001d2e4\\U0001d2e5\\U0001d2e6\\U0001d2e7\\U0001d2e8\\U0001d2e9\\U0001d2ea\\U0001d2eb\\U0001d2ec\\U0001d2ed\\U0001d2ee\\U0001d2ef\\U0001d2f0\\U0001d2f1\\U0001d2f2\\U0001d2f3\\U0001d360\\U0001d361\\U0001d362\\U0001d363\\U0001d364\\U0001d365\\U0001d366\\U0001d367\\U0001d368\\U0001d369\\U0001d36a\\U0001d36b\\U0001d36c\\U0001d36d\\U0001d36e\\U0001d36f\\U0001d370\\U0001d371\\U0001d372\\U0001d373\\U0001d374\\U0001d375\\U0001d376\\U0001d377\\U0001d378\\U0001e8c7\\U0001e8c8\\U0001e8c9\\U0001e8ca\\U0001e8cb\\U0001e8cc\\U0001e8cd\\U0001e8ce\\U0001e8cf\\U0001ec71\\U0001ec72\\U0001ec73\\U0001ec74\\U0001ec75\\U0001ec76\\U0001ec77\\U0001ec78\\U0001ec79\\U0001ec7a\\U0001ec7b\\U0001ec7c\\U0001ec7d\\U0001ec7e\\U0001ec7f\\U0001ec80\\U0001ec81\\U0001ec82\\U0001ec83\\U0001ec84\\U0001ec85\\U0001ec86\\U0001ec87\\U0001ec88\\U0001ec89\\U0001ec8a\\U0001ec8b\\U0001ec8c\\U0001ec8d\\U0001ec8e\\U0001ec8f\\U0001ec90\\U0001ec91\\U0001ec92\\U0001ec93\\U0001ec94\\U0001ec95\\U0001ec96\\U0001ec97\\U0001ec98\\U0001ec99\\U0001ec9a\\U0001ec9b\\U0001ec9c\\U0001ec9d\\U0001ec9e\\U0001ec9f\\U0001eca0\\U0001eca1\\U0001eca2\\U0001eca3\\U0001eca4\\U0001eca5\\U0001eca6\\U0001eca7\\U0001eca8\\U0001eca9\\U0001ecaa\\U0001ecab\\U0001ecad\\U0001ecae\\U0001ecaf\\U0001ecb1\\U0001ecb2\\U0001ecb3\\U0001ecb4\\U0001ed01\\U0001ed02\\U0001ed03\\U0001ed04\\U0001ed05\\U0001ed06\\U0001ed07\\U0001ed08\\U0001ed09\\U0001ed0a\\U0001ed0b\\U0001ed0c\\U0001ed0d\\U0001ed0e\\U0001ed0f\\U0001ed10\\U0001ed11\\U0001ed12\\U0001ed13\\U0001ed14\\U0001ed15\\U0001ed16\\U0001ed17\\U0001ed18\\U0001ed19\\U0001ed1a\\U0001ed1b\\U0001ed1c\\U0001ed1d\\U0001ed1e\\U0001ed1f\\U0001ed20\\U0001ed21\\U0001ed22\\U0001ed23\\U0001ed24\\U0001ed25\\U0001ed26\\U0001ed27\\U0001ed28\\U0001ed29\\U0001ed2a\\U0001ed2b\\U0001ed2c\\U0001ed2d\\U0001ed2f\\U0001ed30\\U0001ed31\\U0001ed32\\U0001ed33\\U0001ed34\\U0001ed35\\U0001ed36\\U0001ed37\\U0001ed38\\U0001ed39\\U0001ed3a\\U0001ed3b\\U0001ed3c\\U0001ed3d\\U0001f100\\U0001f101\\U0001f102\\U0001f103\\U0001f104\\U0001f105\\U0001f106\\U0001f107\\U0001f108\\U0001f109\\U0001f10a\\U0001f10b\\U0001f10c\\U00020001\\U00020064\\U000200e2\\U00020121\\U0002092a\\U00020983\\U0002098c\\U0002099c\\U00020aea\\U00020afd\\U00020b19\\U00022390\\U00022998\\U00023b1b\\U0002626d\\U0002f890])]",
"tests/test_utils.py::test_ns_enum_values_and_aliases[ns.LOCALEALPHA-ns.LOCALEALPHA]",
"tests/test_utils.py::test_chain_functions_is_a_no_op_if_no_functions_are_given",
"tests/test_utils.py::test_ns_enum_values_and_aliases[ns.DEFAULT-0_2]",
"tests/test_utils.py::test_regex_chooser_returns_correct_regular_expression_object[3-([-+]?(?:\\\\d+\\\\.?\\\\d*|\\\\.\\\\d+)(?:[eE][-+]?\\\\d+)?|[\\xb2\\xb3\\xb9\\xbc\\xbd\\xbe\\u09f4\\u09f5\\u09f6\\u09f7\\u09f8\\u09f9\\u0b72\\u0b73\\u0b74\\u0b75\\u0b76\\u0b77\\u0bf0\\u0bf1\\u0bf2\\u0c78\\u0c79\\u0c7a\\u0c7b\\u0c7c\\u0c7d\\u0c7e\\u0d58\\u0d59\\u0d5a\\u0d5b\\u0d5c\\u0d5d\\u0d5e\\u0d70\\u0d71\\u0d72\\u0d73\\u0d74\\u0d75\\u0d76\\u0d77\\u0d78\\u0f2a\\u0f2b\\u0f2c\\u0f2d\\u0f2e\\u0f2f\\u0f30\\u0f31\\u0f32\\u0f33\\u1369\\u136a\\u136b\\u136c\\u136d\\u136e\\u136f\\u1370\\u1371\\u1372\\u1373\\u1374\\u1375\\u1376\\u1377\\u1378\\u1379\\u137a\\u137b\\u137c\\u16ee\\u16ef\\u16f0\\u17f0\\u17f1\\u17f2\\u17f3\\u17f4\\u17f5\\u17f6\\u17f7\\u17f8\\u17f9\\u19da\\u2070\\u2074\\u2075\\u2076\\u2077\\u2078\\u2079\\u2080\\u2081\\u2082\\u2083\\u2084\\u2085\\u2086\\u2087\\u2088\\u2089\\u2150\\u2151\\u2152\\u2153\\u2154\\u2155\\u2156\\u2157\\u2158\\u2159\\u215a\\u215b\\u215c\\u215d\\u215e\\u215f\\u2160\\u2161\\u2162\\u2163\\u2164\\u2165\\u2166\\u2167\\u2168\\u2169\\u216a\\u216b\\u216c\\u216d\\u216e\\u216f\\u2170\\u2171\\u2172\\u2173\\u2174\\u2175\\u2176\\u2177\\u2178\\u2179\\u217a\\u217b\\u217c\\u217d\\u217e\\u217f\\u2180\\u2181\\u2182\\u2185\\u2186\\u2187\\u2188\\u2189\\u2460\\u2461\\u2462\\u2463\\u2464\\u2465\\u2466\\u2467\\u2468\\u2469\\u246a\\u246b\\u246c\\u246d\\u246e\\u246f\\u2470\\u2471\\u2472\\u2473\\u2474\\u2475\\u2476\\u2477\\u2478\\u2479\\u247a\\u247b\\u247c\\u247d\\u247e\\u247f\\u2480\\u2481\\u2482\\u2483\\u2484\\u2485\\u2486\\u2487\\u2488\\u2489\\u248a\\u248b\\u248c\\u248d\\u248e\\u248f\\u2490\\u2491\\u2492\\u2493\\u2494\\u2495\\u2496\\u2497\\u2498\\u2499\\u249a\\u249b\\u24ea\\u24eb\\u24ec\\u24ed\\u24ee\\u24ef\\u24f0\\u24f1\\u24f2\\u24f3\\u24f4\\u24f5\\u24f6\\u24f7\\u24f8\\u24f9\\u24fa\\u24fb\\u24fc\\u24fd\\u24fe\\u24ff\\u2776\\u2777\\u2778\\u2779\\u277a\\u277b\\u277c\\u277d\\u277e\\u277f\\u2780\\u2781\\u2782\\u2783\\u2784\\u2785\\u2786\\u2787\\u2788\\u2789\\u278a\\u278b\\u278c\\u278d\\u278e\\u278f\\u2790\\u2791\\u2792\\u2793\\u2cfd\\u3007\\u3021\\u3022\\u3023\\u3024\\u3025\\u3026\\u3027\\u3028\\u3029\\u3038\\u3039\\u303a\\u3192\\u3193\\u3194\\u3195\\u3220\\u3221\\u3222\\u3223\\u3224\\u3225\\u3226\\u3227\\u3228\\u3229\\u3248\\u3249\\u324a\\u324b\\u324c\\u324d\\u324e\\u324f\\u3251\\u3252\\u3253\\u3254\\u3255\\u3256\\u3257\\u3258\\u3259\\u325a\\u325b\\u325c\\u325d\\u325e\\u325f\\u3280\\u3281\\u3282\\u3283\\u3284\\u3285\\u3286\\u3287\\u3288\\u3289\\u32b1\\u32b2\\u32b3\\u32b4\\u32b5\\u32b6\\u32b7\\u32b8\\u32b9\\u32ba\\u32bb\\u32bc\\u32bd\\u32be\\u32bf\\u3405\\u3483\\u382a\\u3b4d\\u4e00\\u4e03\\u4e07\\u4e09\\u4e5d\\u4e8c\\u4e94\\u4e96\\u4ebf\\u4ec0\\u4edf\\u4ee8\\u4f0d\\u4f70\\u5104\\u5146\\u5169\\u516b\\u516d\\u5341\\u5343\\u5344\\u5345\\u534c\\u53c1\\u53c2\\u53c3\\u53c4\\u56db\\u58f1\\u58f9\\u5e7a\\u5efe\\u5eff\\u5f0c\\u5f0d\\u5f0e\\u5f10\\u62fe\\u634c\\u67d2\\u6f06\\u7396\\u767e\\u8086\\u842c\\u8cae\\u8cb3\\u8d30\\u9621\\u9646\\u964c\\u9678\\u96f6\\ua6e6\\ua6e7\\ua6e8\\ua6e9\\ua6ea\\ua6eb\\ua6ec\\ua6ed\\ua6ee\\ua6ef\\ua830\\ua831\\ua832\\ua833\\ua834\\ua835\\uf96b\\uf973\\uf978\\uf9b2\\uf9d1\\uf9d3\\uf9fd\\U00010107\\U00010108\\U00010109\\U0001010a\\U0001010b\\U0001010c\\U0001010d\\U0001010e\\U0001010f\\U00010110\\U00010111\\U00010112\\U00010113\\U00010114\\U00010115\\U00010116\\U00010117\\U00010118\\U00010119\\U0001011a\\U0001011b\\U0001011c\\U0001011d\\U0001011e\\U0001011f\\U00010120\\U00010121\\U00010122\\U00010123\\U00010124\\U00010125\\U00010126\\U00010127\\U00010128\\U00010129\\U0001012a\\U0001012b\\U0001012c\\U0001012d\\U0001012e\\U0001012f\\U00010130\\U00010131\\U00010132\\U00010133\\U00010140\\U00010141\\U00010142\\U00010143\\U00010144\\U00010145\\U00010146\\U00010147\\U00010148\\U00010149\\U0001014a\\U0001014b\\U0001014c\\U0001014d\\U0001014e\\U0001014f\\U00010150\\U00010151\\U00010152\\U00010153\\U00010154\\U00010155\\U00010156\\U00010157\\U00010158\\U00010159\\U0001015a\\U0001015b\\U0001015c\\U0001015d\\U0001015e\\U0001015f\\U00010160\\U00010161\\U00010162\\U00010163\\U00010164\\U00010165\\U00010166\\U00010167\\U00010168\\U00010169\\U0001016a\\U0001016b\\U0001016c\\U0001016d\\U0001016e\\U0001016f\\U00010170\\U00010171\\U00010172\\U00010173\\U00010174\\U00010175\\U00010176\\U00010177\\U00010178\\U0001018a\\U0001018b\\U000102e1\\U000102e2\\U000102e3\\U000102e4\\U000102e5\\U000102e6\\U000102e7\\U000102e8\\U000102e9\\U000102ea\\U000102eb\\U000102ec\\U000102ed\\U000102ee\\U000102ef\\U000102f0\\U000102f1\\U000102f2\\U000102f3\\U000102f4\\U000102f5\\U000102f6\\U000102f7\\U000102f8\\U000102f9\\U000102fa\\U000102fb\\U00010320\\U00010321\\U00010322\\U00010323\\U00010341\\U0001034a\\U000103d1\\U000103d2\\U000103d3\\U000103d4\\U000103d5\\U00010858\\U00010859\\U0001085a\\U0001085b\\U0001085c\\U0001085d\\U0001085e\\U0001085f\\U00010879\\U0001087a\\U0001087b\\U0001087c\\U0001087d\\U0001087e\\U0001087f\\U000108a7\\U000108a8\\U000108a9\\U000108aa\\U000108ab\\U000108ac\\U000108ad\\U000108ae\\U000108af\\U000108fb\\U000108fc\\U000108fd\\U000108fe\\U000108ff\\U00010916\\U00010917\\U00010918\\U00010919\\U0001091a\\U0001091b\\U000109bc\\U000109bd\\U000109c0\\U000109c1\\U000109c2\\U000109c3\\U000109c4\\U000109c5\\U000109c6\\U000109c7\\U000109c8\\U000109c9\\U000109ca\\U000109cb\\U000109cc\\U000109cd\\U000109ce\\U000109cf\\U000109d2\\U000109d3\\U000109d4\\U000109d5\\U000109d6\\U000109d7\\U000109d8\\U000109d9\\U000109da\\U000109db\\U000109dc\\U000109dd\\U000109de\\U000109df\\U000109e0\\U000109e1\\U000109e2\\U000109e3\\U000109e4\\U000109e5\\U000109e6\\U000109e7\\U000109e8\\U000109e9\\U000109ea\\U000109eb\\U000109ec\\U000109ed\\U000109ee\\U000109ef\\U000109f0\\U000109f1\\U000109f2\\U000109f3\\U000109f4\\U000109f5\\U000109f6\\U000109f7\\U000109f8\\U000109f9\\U000109fa\\U000109fb\\U000109fc\\U000109fd\\U000109fe\\U000109ff\\U00010a40\\U00010a41\\U00010a42\\U00010a43\\U00010a44\\U00010a45\\U00010a46\\U00010a47\\U00010a48\\U00010a7d\\U00010a7e\\U00010a9d\\U00010a9e\\U00010a9f\\U00010aeb\\U00010aec\\U00010aed\\U00010aee\\U00010aef\\U00010b58\\U00010b59\\U00010b5a\\U00010b5b\\U00010b5c\\U00010b5d\\U00010b5e\\U00010b5f\\U00010b78\\U00010b79\\U00010b7a\\U00010b7b\\U00010b7c\\U00010b7d\\U00010b7e\\U00010b7f\\U00010ba9\\U00010baa\\U00010bab\\U00010bac\\U00010bad\\U00010bae\\U00010baf\\U00010cfa\\U00010cfb\\U00010cfc\\U00010cfd\\U00010cfe\\U00010cff\\U00010e60\\U00010e61\\U00010e62\\U00010e63\\U00010e64\\U00010e65\\U00010e66\\U00010e67\\U00010e68\\U00010e69\\U00010e6a\\U00010e6b\\U00010e6c\\U00010e6d\\U00010e6e\\U00010e6f\\U00010e70\\U00010e71\\U00010e72\\U00010e73\\U00010e74\\U00010e75\\U00010e76\\U00010e77\\U00010e78\\U00010e79\\U00010e7a\\U00010e7b\\U00010e7c\\U00010e7d\\U00010e7e\\U00010f1d\\U00010f1e\\U00010f1f\\U00010f20\\U00010f21\\U00010f22\\U00010f23\\U00010f24\\U00010f25\\U00010f26\\U00010f51\\U00010f52\\U00010f53\\U00010f54\\U00010fc5\\U00010fc6\\U00010fc7\\U00010fc8\\U00010fc9\\U00010fca\\U00010fcb\\U00011052\\U00011053\\U00011054\\U00011055\\U00011056\\U00011057\\U00011058\\U00011059\\U0001105a\\U0001105b\\U0001105c\\U0001105d\\U0001105e\\U0001105f\\U00011060\\U00011061\\U00011062\\U00011063\\U00011064\\U00011065\\U000111e1\\U000111e2\\U000111e3\\U000111e4\\U000111e5\\U000111e6\\U000111e7\\U000111e8\\U000111e9\\U000111ea\\U000111eb\\U000111ec\\U000111ed\\U000111ee\\U000111ef\\U000111f0\\U000111f1\\U000111f2\\U000111f3\\U000111f4\\U0001173a\\U0001173b\\U000118ea\\U000118eb\\U000118ec\\U000118ed\\U000118ee\\U000118ef\\U000118f0\\U000118f1\\U000118f2\\U00011c5a\\U00011c5b\\U00011c5c\\U00011c5d\\U00011c5e\\U00011c5f\\U00011c60\\U00011c61\\U00011c62\\U00011c63\\U00011c64\\U00011c65\\U00011c66\\U00011c67\\U00011c68\\U00011c69\\U00011c6a\\U00011c6b\\U00011c6c\\U00011fc0\\U00011fc1\\U00011fc2\\U00011fc3\\U00011fc4\\U00011fc5\\U00011fc6\\U00011fc7\\U00011fc8\\U00011fc9\\U00011fca\\U00011fcb\\U00011fcc\\U00011fcd\\U00011fce\\U00011fcf\\U00011fd0\\U00011fd1\\U00011fd2\\U00011fd3\\U00011fd4\\U00012400\\U00012401\\U00012402\\U00012403\\U00012404\\U00012405\\U00012406\\U00012407\\U00012408\\U00012409\\U0001240a\\U0001240b\\U0001240c\\U0001240d\\U0001240e\\U0001240f\\U00012410\\U00012411\\U00012412\\U00012413\\U00012414\\U00012415\\U00012416\\U00012417\\U00012418\\U00012419\\U0001241a\\U0001241b\\U0001241c\\U0001241d\\U0001241e\\U0001241f\\U00012420\\U00012421\\U00012422\\U00012423\\U00012424\\U00012425\\U00012426\\U00012427\\U00012428\\U00012429\\U0001242a\\U0001242b\\U0001242c\\U0001242d\\U0001242e\\U0001242f\\U00012430\\U00012431\\U00012432\\U00012433\\U00012434\\U00012435\\U00012436\\U00012437\\U00012438\\U00012439\\U0001243a\\U0001243b\\U0001243c\\U0001243d\\U0001243e\\U0001243f\\U00012440\\U00012441\\U00012442\\U00012443\\U00012444\\U00012445\\U00012446\\U00012447\\U00012448\\U00012449\\U0001244a\\U0001244b\\U0001244c\\U0001244d\\U0001244e\\U0001244f\\U00012450\\U00012451\\U00012452\\U00012453\\U00012454\\U00012455\\U00012456\\U00012457\\U00012458\\U00012459\\U0001245a\\U0001245b\\U0001245c\\U0001245d\\U0001245e\\U0001245f\\U00012460\\U00012461\\U00012462\\U00012463\\U00012464\\U00012465\\U00012466\\U00012467\\U00012468\\U00012469\\U0001246a\\U0001246b\\U0001246c\\U0001246d\\U0001246e\\U00016b5b\\U00016b5c\\U00016b5d\\U00016b5e\\U00016b5f\\U00016b60\\U00016b61\\U00016e80\\U00016e81\\U00016e82\\U00016e83\\U00016e84\\U00016e85\\U00016e86\\U00016e87\\U00016e88\\U00016e89\\U00016e8a\\U00016e8b\\U00016e8c\\U00016e8d\\U00016e8e\\U00016e8f\\U00016e90\\U00016e91\\U00016e92\\U00016e93\\U00016e94\\U00016e95\\U00016e96\\U0001d2e0\\U0001d2e1\\U0001d2e2\\U0001d2e3\\U0001d2e4\\U0001d2e5\\U0001d2e6\\U0001d2e7\\U0001d2e8\\U0001d2e9\\U0001d2ea\\U0001d2eb\\U0001d2ec\\U0001d2ed\\U0001d2ee\\U0001d2ef\\U0001d2f0\\U0001d2f1\\U0001d2f2\\U0001d2f3\\U0001d360\\U0001d361\\U0001d362\\U0001d363\\U0001d364\\U0001d365\\U0001d366\\U0001d367\\U0001d368\\U0001d369\\U0001d36a\\U0001d36b\\U0001d36c\\U0001d36d\\U0001d36e\\U0001d36f\\U0001d370\\U0001d371\\U0001d372\\U0001d373\\U0001d374\\U0001d375\\U0001d376\\U0001d377\\U0001d378\\U0001e8c7\\U0001e8c8\\U0001e8c9\\U0001e8ca\\U0001e8cb\\U0001e8cc\\U0001e8cd\\U0001e8ce\\U0001e8cf\\U0001ec71\\U0001ec72\\U0001ec73\\U0001ec74\\U0001ec75\\U0001ec76\\U0001ec77\\U0001ec78\\U0001ec79\\U0001ec7a\\U0001ec7b\\U0001ec7c\\U0001ec7d\\U0001ec7e\\U0001ec7f\\U0001ec80\\U0001ec81\\U0001ec82\\U0001ec83\\U0001ec84\\U0001ec85\\U0001ec86\\U0001ec87\\U0001ec88\\U0001ec89\\U0001ec8a\\U0001ec8b\\U0001ec8c\\U0001ec8d\\U0001ec8e\\U0001ec8f\\U0001ec90\\U0001ec91\\U0001ec92\\U0001ec93\\U0001ec94\\U0001ec95\\U0001ec96\\U0001ec97\\U0001ec98\\U0001ec99\\U0001ec9a\\U0001ec9b\\U0001ec9c\\U0001ec9d\\U0001ec9e\\U0001ec9f\\U0001eca0\\U0001eca1\\U0001eca2\\U0001eca3\\U0001eca4\\U0001eca5\\U0001eca6\\U0001eca7\\U0001eca8\\U0001eca9\\U0001ecaa\\U0001ecab\\U0001ecad\\U0001ecae\\U0001ecaf\\U0001ecb1\\U0001ecb2\\U0001ecb3\\U0001ecb4\\U0001ed01\\U0001ed02\\U0001ed03\\U0001ed04\\U0001ed05\\U0001ed06\\U0001ed07\\U0001ed08\\U0001ed09\\U0001ed0a\\U0001ed0b\\U0001ed0c\\U0001ed0d\\U0001ed0e\\U0001ed0f\\U0001ed10\\U0001ed11\\U0001ed12\\U0001ed13\\U0001ed14\\U0001ed15\\U0001ed16\\U0001ed17\\U0001ed18\\U0001ed19\\U0001ed1a\\U0001ed1b\\U0001ed1c\\U0001ed1d\\U0001ed1e\\U0001ed1f\\U0001ed20\\U0001ed21\\U0001ed22\\U0001ed23\\U0001ed24\\U0001ed25\\U0001ed26\\U0001ed27\\U0001ed28\\U0001ed29\\U0001ed2a\\U0001ed2b\\U0001ed2c\\U0001ed2d\\U0001ed2f\\U0001ed30\\U0001ed31\\U0001ed32\\U0001ed33\\U0001ed34\\U0001ed35\\U0001ed36\\U0001ed37\\U0001ed38\\U0001ed39\\U0001ed3a\\U0001ed3b\\U0001ed3c\\U0001ed3d\\U0001f100\\U0001f101\\U0001f102\\U0001f103\\U0001f104\\U0001f105\\U0001f106\\U0001f107\\U0001f108\\U0001f109\\U0001f10a\\U0001f10b\\U0001f10c\\U00020001\\U00020064\\U000200e2\\U00020121\\U0002092a\\U00020983\\U0002098c\\U0002099c\\U00020aea\\U00020afd\\U00020b19\\U00022390\\U00022998\\U00023b1b\\U0002626d\\U0002f890])]",
"tests/test_utils.py::test_groupletters_gives_letters_with_lowercase_letter_transform",
"tests/test_utils.py::test_sep_inserter_does_nothing_if_no_numbers_example",
"tests/test_utils.py::test_ns_enum_values_and_aliases[ns.LOWERCASEFIRST-ns.LOWERCASEFIRST]",
"tests/test_utils.py::test_ns_enum_values_and_aliases[ns.LOCALE-48]",
"tests/test_utils.py::test_ns_enum_values_and_aliases[ns.DEFAULT-0_1]",
"tests/test_utils.py::test_ns_enum_values_and_aliases[ns.NUMAFTER-ns.NUMAFTER]",
"tests/test_utils.py::test_ns_enum_values_and_aliases[ns.NANLAST-ns.NANLAST]",
"tests/test_utils.py::test_chain_functions_combines_functions_in_given_order",
"tests/test_utils.py::test_ns_enum_values_and_aliases[ns.UNGROUPLETTERS-ns.UNGROUPLETTERS0]",
"tests/test_utils.py::test_path_splitter_handles_dot_properly[.\\\\]",
"tests/test_utils.py::test_ns_enum_values_and_aliases[ns.GROUPLETTERS-ns.GROUPLETTERS]",
"tests/test_utils.py::test_ns_enum_values_and_aliases[ns.IGNORECASE-ns.IGNORECASE]",
"tests/test_utils.py::test_ns_enum_values_and_aliases[ns.REAL-3]",
"tests/test_utils.py::test_regex_chooser_returns_correct_regular_expression_object[7-([-+]?(?:\\\\d+\\\\.?\\\\d*|\\\\.\\\\d+)|[\\xb2\\xb3\\xb9\\xbc\\xbd\\xbe\\u09f4\\u09f5\\u09f6\\u09f7\\u09f8\\u09f9\\u0b72\\u0b73\\u0b74\\u0b75\\u0b76\\u0b77\\u0bf0\\u0bf1\\u0bf2\\u0c78\\u0c79\\u0c7a\\u0c7b\\u0c7c\\u0c7d\\u0c7e\\u0d58\\u0d59\\u0d5a\\u0d5b\\u0d5c\\u0d5d\\u0d5e\\u0d70\\u0d71\\u0d72\\u0d73\\u0d74\\u0d75\\u0d76\\u0d77\\u0d78\\u0f2a\\u0f2b\\u0f2c\\u0f2d\\u0f2e\\u0f2f\\u0f30\\u0f31\\u0f32\\u0f33\\u1369\\u136a\\u136b\\u136c\\u136d\\u136e\\u136f\\u1370\\u1371\\u1372\\u1373\\u1374\\u1375\\u1376\\u1377\\u1378\\u1379\\u137a\\u137b\\u137c\\u16ee\\u16ef\\u16f0\\u17f0\\u17f1\\u17f2\\u17f3\\u17f4\\u17f5\\u17f6\\u17f7\\u17f8\\u17f9\\u19da\\u2070\\u2074\\u2075\\u2076\\u2077\\u2078\\u2079\\u2080\\u2081\\u2082\\u2083\\u2084\\u2085\\u2086\\u2087\\u2088\\u2089\\u2150\\u2151\\u2152\\u2153\\u2154\\u2155\\u2156\\u2157\\u2158\\u2159\\u215a\\u215b\\u215c\\u215d\\u215e\\u215f\\u2160\\u2161\\u2162\\u2163\\u2164\\u2165\\u2166\\u2167\\u2168\\u2169\\u216a\\u216b\\u216c\\u216d\\u216e\\u216f\\u2170\\u2171\\u2172\\u2173\\u2174\\u2175\\u2176\\u2177\\u2178\\u2179\\u217a\\u217b\\u217c\\u217d\\u217e\\u217f\\u2180\\u2181\\u2182\\u2185\\u2186\\u2187\\u2188\\u2189\\u2460\\u2461\\u2462\\u2463\\u2464\\u2465\\u2466\\u2467\\u2468\\u2469\\u246a\\u246b\\u246c\\u246d\\u246e\\u246f\\u2470\\u2471\\u2472\\u2473\\u2474\\u2475\\u2476\\u2477\\u2478\\u2479\\u247a\\u247b\\u247c\\u247d\\u247e\\u247f\\u2480\\u2481\\u2482\\u2483\\u2484\\u2485\\u2486\\u2487\\u2488\\u2489\\u248a\\u248b\\u248c\\u248d\\u248e\\u248f\\u2490\\u2491\\u2492\\u2493\\u2494\\u2495\\u2496\\u2497\\u2498\\u2499\\u249a\\u249b\\u24ea\\u24eb\\u24ec\\u24ed\\u24ee\\u24ef\\u24f0\\u24f1\\u24f2\\u24f3\\u24f4\\u24f5\\u24f6\\u24f7\\u24f8\\u24f9\\u24fa\\u24fb\\u24fc\\u24fd\\u24fe\\u24ff\\u2776\\u2777\\u2778\\u2779\\u277a\\u277b\\u277c\\u277d\\u277e\\u277f\\u2780\\u2781\\u2782\\u2783\\u2784\\u2785\\u2786\\u2787\\u2788\\u2789\\u278a\\u278b\\u278c\\u278d\\u278e\\u278f\\u2790\\u2791\\u2792\\u2793\\u2cfd\\u3007\\u3021\\u3022\\u3023\\u3024\\u3025\\u3026\\u3027\\u3028\\u3029\\u3038\\u3039\\u303a\\u3192\\u3193\\u3194\\u3195\\u3220\\u3221\\u3222\\u3223\\u3224\\u3225\\u3226\\u3227\\u3228\\u3229\\u3248\\u3249\\u324a\\u324b\\u324c\\u324d\\u324e\\u324f\\u3251\\u3252\\u3253\\u3254\\u3255\\u3256\\u3257\\u3258\\u3259\\u325a\\u325b\\u325c\\u325d\\u325e\\u325f\\u3280\\u3281\\u3282\\u3283\\u3284\\u3285\\u3286\\u3287\\u3288\\u3289\\u32b1\\u32b2\\u32b3\\u32b4\\u32b5\\u32b6\\u32b7\\u32b8\\u32b9\\u32ba\\u32bb\\u32bc\\u32bd\\u32be\\u32bf\\u3405\\u3483\\u382a\\u3b4d\\u4e00\\u4e03\\u4e07\\u4e09\\u4e5d\\u4e8c\\u4e94\\u4e96\\u4ebf\\u4ec0\\u4edf\\u4ee8\\u4f0d\\u4f70\\u5104\\u5146\\u5169\\u516b\\u516d\\u5341\\u5343\\u5344\\u5345\\u534c\\u53c1\\u53c2\\u53c3\\u53c4\\u56db\\u58f1\\u58f9\\u5e7a\\u5efe\\u5eff\\u5f0c\\u5f0d\\u5f0e\\u5f10\\u62fe\\u634c\\u67d2\\u6f06\\u7396\\u767e\\u8086\\u842c\\u8cae\\u8cb3\\u8d30\\u9621\\u9646\\u964c\\u9678\\u96f6\\ua6e6\\ua6e7\\ua6e8\\ua6e9\\ua6ea\\ua6eb\\ua6ec\\ua6ed\\ua6ee\\ua6ef\\ua830\\ua831\\ua832\\ua833\\ua834\\ua835\\uf96b\\uf973\\uf978\\uf9b2\\uf9d1\\uf9d3\\uf9fd\\U00010107\\U00010108\\U00010109\\U0001010a\\U0001010b\\U0001010c\\U0001010d\\U0001010e\\U0001010f\\U00010110\\U00010111\\U00010112\\U00010113\\U00010114\\U00010115\\U00010116\\U00010117\\U00010118\\U00010119\\U0001011a\\U0001011b\\U0001011c\\U0001011d\\U0001011e\\U0001011f\\U00010120\\U00010121\\U00010122\\U00010123\\U00010124\\U00010125\\U00010126\\U00010127\\U00010128\\U00010129\\U0001012a\\U0001012b\\U0001012c\\U0001012d\\U0001012e\\U0001012f\\U00010130\\U00010131\\U00010132\\U00010133\\U00010140\\U00010141\\U00010142\\U00010143\\U00010144\\U00010145\\U00010146\\U00010147\\U00010148\\U00010149\\U0001014a\\U0001014b\\U0001014c\\U0001014d\\U0001014e\\U0001014f\\U00010150\\U00010151\\U00010152\\U00010153\\U00010154\\U00010155\\U00010156\\U00010157\\U00010158\\U00010159\\U0001015a\\U0001015b\\U0001015c\\U0001015d\\U0001015e\\U0001015f\\U00010160\\U00010161\\U00010162\\U00010163\\U00010164\\U00010165\\U00010166\\U00010167\\U00010168\\U00010169\\U0001016a\\U0001016b\\U0001016c\\U0001016d\\U0001016e\\U0001016f\\U00010170\\U00010171\\U00010172\\U00010173\\U00010174\\U00010175\\U00010176\\U00010177\\U00010178\\U0001018a\\U0001018b\\U000102e1\\U000102e2\\U000102e3\\U000102e4\\U000102e5\\U000102e6\\U000102e7\\U000102e8\\U000102e9\\U000102ea\\U000102eb\\U000102ec\\U000102ed\\U000102ee\\U000102ef\\U000102f0\\U000102f1\\U000102f2\\U000102f3\\U000102f4\\U000102f5\\U000102f6\\U000102f7\\U000102f8\\U000102f9\\U000102fa\\U000102fb\\U00010320\\U00010321\\U00010322\\U00010323\\U00010341\\U0001034a\\U000103d1\\U000103d2\\U000103d3\\U000103d4\\U000103d5\\U00010858\\U00010859\\U0001085a\\U0001085b\\U0001085c\\U0001085d\\U0001085e\\U0001085f\\U00010879\\U0001087a\\U0001087b\\U0001087c\\U0001087d\\U0001087e\\U0001087f\\U000108a7\\U000108a8\\U000108a9\\U000108aa\\U000108ab\\U000108ac\\U000108ad\\U000108ae\\U000108af\\U000108fb\\U000108fc\\U000108fd\\U000108fe\\U000108ff\\U00010916\\U00010917\\U00010918\\U00010919\\U0001091a\\U0001091b\\U000109bc\\U000109bd\\U000109c0\\U000109c1\\U000109c2\\U000109c3\\U000109c4\\U000109c5\\U000109c6\\U000109c7\\U000109c8\\U000109c9\\U000109ca\\U000109cb\\U000109cc\\U000109cd\\U000109ce\\U000109cf\\U000109d2\\U000109d3\\U000109d4\\U000109d5\\U000109d6\\U000109d7\\U000109d8\\U000109d9\\U000109da\\U000109db\\U000109dc\\U000109dd\\U000109de\\U000109df\\U000109e0\\U000109e1\\U000109e2\\U000109e3\\U000109e4\\U000109e5\\U000109e6\\U000109e7\\U000109e8\\U000109e9\\U000109ea\\U000109eb\\U000109ec\\U000109ed\\U000109ee\\U000109ef\\U000109f0\\U000109f1\\U000109f2\\U000109f3\\U000109f4\\U000109f5\\U000109f6\\U000109f7\\U000109f8\\U000109f9\\U000109fa\\U000109fb\\U000109fc\\U000109fd\\U000109fe\\U000109ff\\U00010a40\\U00010a41\\U00010a42\\U00010a43\\U00010a44\\U00010a45\\U00010a46\\U00010a47\\U00010a48\\U00010a7d\\U00010a7e\\U00010a9d\\U00010a9e\\U00010a9f\\U00010aeb\\U00010aec\\U00010aed\\U00010aee\\U00010aef\\U00010b58\\U00010b59\\U00010b5a\\U00010b5b\\U00010b5c\\U00010b5d\\U00010b5e\\U00010b5f\\U00010b78\\U00010b79\\U00010b7a\\U00010b7b\\U00010b7c\\U00010b7d\\U00010b7e\\U00010b7f\\U00010ba9\\U00010baa\\U00010bab\\U00010bac\\U00010bad\\U00010bae\\U00010baf\\U00010cfa\\U00010cfb\\U00010cfc\\U00010cfd\\U00010cfe\\U00010cff\\U00010e60\\U00010e61\\U00010e62\\U00010e63\\U00010e64\\U00010e65\\U00010e66\\U00010e67\\U00010e68\\U00010e69\\U00010e6a\\U00010e6b\\U00010e6c\\U00010e6d\\U00010e6e\\U00010e6f\\U00010e70\\U00010e71\\U00010e72\\U00010e73\\U00010e74\\U00010e75\\U00010e76\\U00010e77\\U00010e78\\U00010e79\\U00010e7a\\U00010e7b\\U00010e7c\\U00010e7d\\U00010e7e\\U00010f1d\\U00010f1e\\U00010f1f\\U00010f20\\U00010f21\\U00010f22\\U00010f23\\U00010f24\\U00010f25\\U00010f26\\U00010f51\\U00010f52\\U00010f53\\U00010f54\\U00010fc5\\U00010fc6\\U00010fc7\\U00010fc8\\U00010fc9\\U00010fca\\U00010fcb\\U00011052\\U00011053\\U00011054\\U00011055\\U00011056\\U00011057\\U00011058\\U00011059\\U0001105a\\U0001105b\\U0001105c\\U0001105d\\U0001105e\\U0001105f\\U00011060\\U00011061\\U00011062\\U00011063\\U00011064\\U00011065\\U000111e1\\U000111e2\\U000111e3\\U000111e4\\U000111e5\\U000111e6\\U000111e7\\U000111e8\\U000111e9\\U000111ea\\U000111eb\\U000111ec\\U000111ed\\U000111ee\\U000111ef\\U000111f0\\U000111f1\\U000111f2\\U000111f3\\U000111f4\\U0001173a\\U0001173b\\U000118ea\\U000118eb\\U000118ec\\U000118ed\\U000118ee\\U000118ef\\U000118f0\\U000118f1\\U000118f2\\U00011c5a\\U00011c5b\\U00011c5c\\U00011c5d\\U00011c5e\\U00011c5f\\U00011c60\\U00011c61\\U00011c62\\U00011c63\\U00011c64\\U00011c65\\U00011c66\\U00011c67\\U00011c68\\U00011c69\\U00011c6a\\U00011c6b\\U00011c6c\\U00011fc0\\U00011fc1\\U00011fc2\\U00011fc3\\U00011fc4\\U00011fc5\\U00011fc6\\U00011fc7\\U00011fc8\\U00011fc9\\U00011fca\\U00011fcb\\U00011fcc\\U00011fcd\\U00011fce\\U00011fcf\\U00011fd0\\U00011fd1\\U00011fd2\\U00011fd3\\U00011fd4\\U00012400\\U00012401\\U00012402\\U00012403\\U00012404\\U00012405\\U00012406\\U00012407\\U00012408\\U00012409\\U0001240a\\U0001240b\\U0001240c\\U0001240d\\U0001240e\\U0001240f\\U00012410\\U00012411\\U00012412\\U00012413\\U00012414\\U00012415\\U00012416\\U00012417\\U00012418\\U00012419\\U0001241a\\U0001241b\\U0001241c\\U0001241d\\U0001241e\\U0001241f\\U00012420\\U00012421\\U00012422\\U00012423\\U00012424\\U00012425\\U00012426\\U00012427\\U00012428\\U00012429\\U0001242a\\U0001242b\\U0001242c\\U0001242d\\U0001242e\\U0001242f\\U00012430\\U00012431\\U00012432\\U00012433\\U00012434\\U00012435\\U00012436\\U00012437\\U00012438\\U00012439\\U0001243a\\U0001243b\\U0001243c\\U0001243d\\U0001243e\\U0001243f\\U00012440\\U00012441\\U00012442\\U00012443\\U00012444\\U00012445\\U00012446\\U00012447\\U00012448\\U00012449\\U0001244a\\U0001244b\\U0001244c\\U0001244d\\U0001244e\\U0001244f\\U00012450\\U00012451\\U00012452\\U00012453\\U00012454\\U00012455\\U00012456\\U00012457\\U00012458\\U00012459\\U0001245a\\U0001245b\\U0001245c\\U0001245d\\U0001245e\\U0001245f\\U00012460\\U00012461\\U00012462\\U00012463\\U00012464\\U00012465\\U00012466\\U00012467\\U00012468\\U00012469\\U0001246a\\U0001246b\\U0001246c\\U0001246d\\U0001246e\\U00016b5b\\U00016b5c\\U00016b5d\\U00016b5e\\U00016b5f\\U00016b60\\U00016b61\\U00016e80\\U00016e81\\U00016e82\\U00016e83\\U00016e84\\U00016e85\\U00016e86\\U00016e87\\U00016e88\\U00016e89\\U00016e8a\\U00016e8b\\U00016e8c\\U00016e8d\\U00016e8e\\U00016e8f\\U00016e90\\U00016e91\\U00016e92\\U00016e93\\U00016e94\\U00016e95\\U00016e96\\U0001d2e0\\U0001d2e1\\U0001d2e2\\U0001d2e3\\U0001d2e4\\U0001d2e5\\U0001d2e6\\U0001d2e7\\U0001d2e8\\U0001d2e9\\U0001d2ea\\U0001d2eb\\U0001d2ec\\U0001d2ed\\U0001d2ee\\U0001d2ef\\U0001d2f0\\U0001d2f1\\U0001d2f2\\U0001d2f3\\U0001d360\\U0001d361\\U0001d362\\U0001d363\\U0001d364\\U0001d365\\U0001d366\\U0001d367\\U0001d368\\U0001d369\\U0001d36a\\U0001d36b\\U0001d36c\\U0001d36d\\U0001d36e\\U0001d36f\\U0001d370\\U0001d371\\U0001d372\\U0001d373\\U0001d374\\U0001d375\\U0001d376\\U0001d377\\U0001d378\\U0001e8c7\\U0001e8c8\\U0001e8c9\\U0001e8ca\\U0001e8cb\\U0001e8cc\\U0001e8cd\\U0001e8ce\\U0001e8cf\\U0001ec71\\U0001ec72\\U0001ec73\\U0001ec74\\U0001ec75\\U0001ec76\\U0001ec77\\U0001ec78\\U0001ec79\\U0001ec7a\\U0001ec7b\\U0001ec7c\\U0001ec7d\\U0001ec7e\\U0001ec7f\\U0001ec80\\U0001ec81\\U0001ec82\\U0001ec83\\U0001ec84\\U0001ec85\\U0001ec86\\U0001ec87\\U0001ec88\\U0001ec89\\U0001ec8a\\U0001ec8b\\U0001ec8c\\U0001ec8d\\U0001ec8e\\U0001ec8f\\U0001ec90\\U0001ec91\\U0001ec92\\U0001ec93\\U0001ec94\\U0001ec95\\U0001ec96\\U0001ec97\\U0001ec98\\U0001ec99\\U0001ec9a\\U0001ec9b\\U0001ec9c\\U0001ec9d\\U0001ec9e\\U0001ec9f\\U0001eca0\\U0001eca1\\U0001eca2\\U0001eca3\\U0001eca4\\U0001eca5\\U0001eca6\\U0001eca7\\U0001eca8\\U0001eca9\\U0001ecaa\\U0001ecab\\U0001ecad\\U0001ecae\\U0001ecaf\\U0001ecb1\\U0001ecb2\\U0001ecb3\\U0001ecb4\\U0001ed01\\U0001ed02\\U0001ed03\\U0001ed04\\U0001ed05\\U0001ed06\\U0001ed07\\U0001ed08\\U0001ed09\\U0001ed0a\\U0001ed0b\\U0001ed0c\\U0001ed0d\\U0001ed0e\\U0001ed0f\\U0001ed10\\U0001ed11\\U0001ed12\\U0001ed13\\U0001ed14\\U0001ed15\\U0001ed16\\U0001ed17\\U0001ed18\\U0001ed19\\U0001ed1a\\U0001ed1b\\U0001ed1c\\U0001ed1d\\U0001ed1e\\U0001ed1f\\U0001ed20\\U0001ed21\\U0001ed22\\U0001ed23\\U0001ed24\\U0001ed25\\U0001ed26\\U0001ed27\\U0001ed28\\U0001ed29\\U0001ed2a\\U0001ed2b\\U0001ed2c\\U0001ed2d\\U0001ed2f\\U0001ed30\\U0001ed31\\U0001ed32\\U0001ed33\\U0001ed34\\U0001ed35\\U0001ed36\\U0001ed37\\U0001ed38\\U0001ed39\\U0001ed3a\\U0001ed3b\\U0001ed3c\\U0001ed3d\\U0001f100\\U0001f101\\U0001f102\\U0001f103\\U0001f104\\U0001f105\\U0001f106\\U0001f107\\U0001f108\\U0001f109\\U0001f10a\\U0001f10b\\U0001f10c\\U00020001\\U00020064\\U000200e2\\U00020121\\U0002092a\\U00020983\\U0002098c\\U0002099c\\U00020aea\\U00020afd\\U00020b19\\U00022390\\U00022998\\U00023b1b\\U0002626d\\U0002f890])]",
"tests/test_utils.py::test_ns_enum_values_and_aliases[ns.SIGNED-ns.SIGNED]",
"tests/test_utils.py::test_groupletters_gives_letters_with_lowercase_letter_transform_example",
"tests/test_utils.py::test_regex_chooser_returns_correct_regular_expression_object[4-(\\\\d+|[\\xb2\\xb3\\xb9\\u1369\\u136a\\u136b\\u136c\\u136d\\u136e\\u136f\\u1370\\u1371\\u19da\\u2070\\u2074\\u2075\\u2076\\u2077\\u2078\\u2079\\u2080\\u2081\\u2082\\u2083\\u2084\\u2085\\u2086\\u2087\\u2088\\u2089\\u2460\\u2461\\u2462\\u2463\\u2464\\u2465\\u2466\\u2467\\u2468\\u2474\\u2475\\u2476\\u2477\\u2478\\u2479\\u247a\\u247b\\u247c\\u2488\\u2489\\u248a\\u248b\\u248c\\u248d\\u248e\\u248f\\u2490\\u24ea\\u24f5\\u24f6\\u24f7\\u24f8\\u24f9\\u24fa\\u24fb\\u24fc\\u24fd\\u24ff\\u2776\\u2777\\u2778\\u2779\\u277a\\u277b\\u277c\\u277d\\u277e\\u2780\\u2781\\u2782\\u2783\\u2784\\u2785\\u2786\\u2787\\u2788\\u278a\\u278b\\u278c\\u278d\\u278e\\u278f\\u2790\\u2791\\u2792\\U00010a40\\U00010a41\\U00010a42\\U00010a43\\U00010e60\\U00010e61\\U00010e62\\U00010e63\\U00010e64\\U00010e65\\U00010e66\\U00010e67\\U00010e68\\U00011052\\U00011053\\U00011054\\U00011055\\U00011056\\U00011057\\U00011058\\U00011059\\U0001105a\\U0001f100\\U0001f101\\U0001f102\\U0001f103\\U0001f104\\U0001f105\\U0001f106\\U0001f107\\U0001f108\\U0001f109\\U0001f10a])]",
"tests/test_utils.py::test_path_splitter_handles_dot_properly[.]",
"tests/test_utils.py::test_sep_inserter_inserts_separator_between_two_numbers",
"tests/test_utils.py::test_ns_enum_values_and_aliases[ns.FLOAT-ns.FLOAT]",
"tests/test_utils.py::test_regex_chooser_returns_correct_regular_expression_object[ns.DEFAULT-(\\\\d+|[\\xb2\\xb3\\xb9\\u1369\\u136a\\u136b\\u136c\\u136d\\u136e\\u136f\\u1370\\u1371\\u19da\\u2070\\u2074\\u2075\\u2076\\u2077\\u2078\\u2079\\u2080\\u2081\\u2082\\u2083\\u2084\\u2085\\u2086\\u2087\\u2088\\u2089\\u2460\\u2461\\u2462\\u2463\\u2464\\u2465\\u2466\\u2467\\u2468\\u2474\\u2475\\u2476\\u2477\\u2478\\u2479\\u247a\\u247b\\u247c\\u2488\\u2489\\u248a\\u248b\\u248c\\u248d\\u248e\\u248f\\u2490\\u24ea\\u24f5\\u24f6\\u24f7\\u24f8\\u24f9\\u24fa\\u24fb\\u24fc\\u24fd\\u24ff\\u2776\\u2777\\u2778\\u2779\\u277a\\u277b\\u277c\\u277d\\u277e\\u2780\\u2781\\u2782\\u2783\\u2784\\u2785\\u2786\\u2787\\u2788\\u278a\\u278b\\u278c\\u278d\\u278e\\u278f\\u2790\\u2791\\u2792\\U00010a40\\U00010a41\\U00010a42\\U00010a43\\U00010e60\\U00010e61\\U00010e62\\U00010e63\\U00010e64\\U00010e65\\U00010e66\\U00010e67\\U00010e68\\U00011052\\U00011053\\U00011054\\U00011055\\U00011056\\U00011057\\U00011058\\U00011059\\U0001105a\\U0001f100\\U0001f101\\U0001f102\\U0001f103\\U0001f104\\U0001f105\\U0001f106\\U0001f107\\U0001f108\\U0001f109\\U0001f10a])]",
"tests/test_utils.py::test_sep_inserter_inserts_separator_string_between_two_numbers_example",
"tests/test_utils.py::test_regex_chooser_returns_correct_regular_expression_object[2-([-+]?\\\\d+|[\\xb2\\xb3\\xb9\\u1369\\u136a\\u136b\\u136c\\u136d\\u136e\\u136f\\u1370\\u1371\\u19da\\u2070\\u2074\\u2075\\u2076\\u2077\\u2078\\u2079\\u2080\\u2081\\u2082\\u2083\\u2084\\u2085\\u2086\\u2087\\u2088\\u2089\\u2460\\u2461\\u2462\\u2463\\u2464\\u2465\\u2466\\u2467\\u2468\\u2474\\u2475\\u2476\\u2477\\u2478\\u2479\\u247a\\u247b\\u247c\\u2488\\u2489\\u248a\\u248b\\u248c\\u248d\\u248e\\u248f\\u2490\\u24ea\\u24f5\\u24f6\\u24f7\\u24f8\\u24f9\\u24fa\\u24fb\\u24fc\\u24fd\\u24ff\\u2776\\u2777\\u2778\\u2779\\u277a\\u277b\\u277c\\u277d\\u277e\\u2780\\u2781\\u2782\\u2783\\u2784\\u2785\\u2786\\u2787\\u2788\\u278a\\u278b\\u278c\\u278d\\u278e\\u278f\\u2790\\u2791\\u2792\\U00010a40\\U00010a41\\U00010a42\\U00010a43\\U00010e60\\U00010e61\\U00010e62\\U00010e63\\U00010e64\\U00010e65\\U00010e66\\U00010e67\\U00010e68\\U00011052\\U00011053\\U00011054\\U00011055\\U00011056\\U00011057\\U00011058\\U00011059\\U0001105a\\U0001f100\\U0001f101\\U0001f102\\U0001f103\\U0001f104\\U0001f105\\U0001f106\\U0001f107\\U0001f108\\U0001f109\\U0001f10a])]",
"tests/test_utils.py::test_ns_enum_values_and_aliases[ns.NOEXP-ns.NOEXP]",
"tests/test_utils.py::test_path_splitter_splits_path_string_by_sep_and_removes_extension_example[/this/is/a/path/file.x1.10.tar.gz-expected0]",
"tests/test_utils.py::test_sep_inserter_does_nothing_if_only_one_number_example",
"tests/test_natsorted.py::test_natsorted_applies_key_to_each_list_element_before_sorting_list",
"tests/test_natsorted.py::test_natsorted_recurses_into_nested_lists",
"tests/test_natsorted.py::test_natsorted_supports_nested_case_handling[ns.LOWERCASEFIRST-expected1]",
"tests/test_natsorted.py::test_natsorted_can_sort_as_unsigned_and_ignore_exponents[5_1]",
"tests/test_natsorted.py::test_natsorted_can_sort_as_unsigned_ints_which_is_default[ns.DEFAULT0]",
"tests/test_natsorted.py::test_natsorted_supports_case_handling[ns.GROUPLETTERS-expected3]",
"tests/test_natsorted.py::test_natsorted_returns_list_in_reversed_order_with_reverse_option",
"tests/test_natsorted.py::test_natsorted_sorts_an_odd_collection_of_strings[ns.DEFAULT-expected0]",
"tests/test_natsorted.py::test_natsorted_can_sort_as_unsigned_and_ignore_exponents[5_0]",
"tests/test_natsorted.py::test_natsorted_can_sort_as_signed_ints",
"tests/test_natsorted.py::test_natsorted_can_sort_as_unsigned_ints_which_is_default[ns.DEFAULT1]",
"tests/test_natsorted.py::test_natsorted_supports_case_handling[384-expected4]",
"tests/test_natsorted.py::test_natsorted_handles_nan[ns.DEFAULT-expected0-slc0]",
"tests/test_natsorted.py::test_natsorted_numbers_in_ascending_order",
"tests/test_natsorted.py::test_natsorted_supports_case_handling[ns.DEFAULT-expected0]",
"tests/test_natsorted.py::test_natsorted_supports_case_handling[ns.LOWERCASEFIRST-expected2]",
"tests/test_natsorted.py::test_natsorted_can_sort_with_or_without_accounting_for_sign[ns.SIGNED-expected1]",
"tests/test_natsorted.py::test_natsorted_sorts_an_odd_collection_of_strings[ns.NUMAFTER-expected1]",
"tests/test_natsorted.py::test_natsorted_with_mixed_bytes_and_str_input_raises_type_error",
"tests/test_natsorted.py::test_natsorted_can_sort_as_version_numbers",
"tests/test_natsorted.py::test_natsorted_sorts_mixed_ascii_and_non_ascii_numbers",
"tests/test_natsorted.py::test_natsorted_handles_nan[ns.NANLAST-expected1-slc1]",
"tests/test_natsorted.py::test_natsorted_can_sort_with_or_without_accounting_for_sign[ns.DEFAULT-expected0]",
"tests/test_natsorted.py::test_natsorted_handles_mixed_types[ns.NUMAFTER-expected1]",
"tests/test_natsorted.py::test_natsorted_supports_nested_case_handling[ns.IGNORECASE-expected2]",
"tests/test_natsorted.py::test_natsorted_supports_nested_case_handling[ns.DEFAULT-expected0]",
"tests/test_natsorted.py::test_natsorted_can_sort_as_signed_floats_with_exponents",
"tests/test_natsorted.py::test_natsorted_handles_mixed_types[ns.DEFAULT-expected0]",
"tests/test_natsorted.py::test_natsorted_supports_case_handling[ns.IGNORECASE-expected1]",
"tests/test_natsorted.py::test_natsorted_raises_type_error_for_non_iterable_input",
"tests/test_natsorted.py::test_natsorted_handles_numbers_and_filesystem_paths_simultaneously",
"tests/test_natsorted.py::test_natsorted_handles_filesystem_paths"
] | {
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2022-01-30T01:38:26Z" | mit |
|
ShailChoksi__text2digits-32 | diff --git a/setup.py b/setup.py
index 7c315ef..f61f06c 100644
--- a/setup.py
+++ b/setup.py
@@ -5,7 +5,7 @@ with open("README.md", "r") as fh:
setuptools.setup(
name="text2digits",
- version="0.0.9",
+ version="0.1.0",
author="Shail Choksi",
author_email="[email protected]",
description="A small library to convert text numbers to digits in a string",
diff --git a/text2digits/rules.py b/text2digits/rules.py
index b892c4b..bc7a96e 100644
--- a/text2digits/rules.py
+++ b/text2digits/rules.py
@@ -119,15 +119,16 @@ class CombinationRule(Rule):
result = Decimal(0)
last_glue = ''
prev_scale = 1
+ all_scales = [token.scale() for token in tokens]
- for token in tokens:
+ for index, token in enumerate(tokens):
assert token.type != WordType.OTHER, 'Invalid token type (only numbers are allowed here)'
if token.has_large_scale():
# Multiply the scale at least with a value of 1 (and not 0)
current = max(1, current)
- if token.scale() < prev_scale:
+ if token.scale() < prev_scale and prev_scale > max(all_scales[index:]):
# Flush the result when switching from a larger to a smaller scale
# e.g. one thousand *FLUSH* six hundred *FLUSH* sixty six
result += current
@@ -141,7 +142,6 @@ class CombinationRule(Rule):
return CombinedToken(tokens, result, last_glue)
-
class ConcatenationRule(Rule):
"""
This rule handles all the "year cases" like twenty twenty where we simply concatenate the numbers together. The numbers are already transformed to digits by the CombinationRule.
@@ -154,7 +154,8 @@ class ConcatenationRule(Rule):
# Find all numeric tokens
while i < len(tokens):
- if tokens[i].type in self.valid_types:
+ if tokens[i].type in self.valid_types and not tokens[i].is_ordinal():
+ # Avoid ordinals. Example: 'look at the second one' should convert into '2nd 1' not '21'
i += 1
else:
break
diff --git a/text2digits/tokens_basic.py b/text2digits/tokens_basic.py
index 1a8e006..b6238e6 100644
--- a/text2digits/tokens_basic.py
+++ b/text2digits/tokens_basic.py
@@ -22,6 +22,7 @@ class Token(object):
'nineteen']
TENS = ['twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']
SCALES = ['hundred', 'thousand', 'million', 'billion', 'trillion']
+ SCALE_VALUES = [100, 1000, 1000000, 1000000000, 1000000000000] # used for has_large_scale
CONJUNCTION = ['and']
ORDINAL_WORDS = {'oh': 'zero', 'first': 'one', 'second': 'two', 'third': 'three', 'fifth': 'five',
'eighth': 'eight', 'ninth': 'nine', 'twelfth': 'twelve'}
@@ -96,7 +97,8 @@ class Token(object):
if self.type == WordType.SCALES:
return True
elif self.type in [WordType.LITERAL_INT, WordType.LITERAL_FLOAT]:
- return Decimal(self._word) >= 100 and Decimal(self._word) % 10 == 0
+ # whether the value is a scale (e.g. 100, 1000, 1000000, etc.)
+ return Decimal(self._word) in self.SCALE_VALUES
else:
return False
| ShailChoksi/text2digits | d96df03444b621b23e3ad444f39da73ca15c8011 | diff --git a/tests/test_number_conversion.py b/tests/test_number_conversion.py
index 4679158..a483bcd 100644
--- a/tests/test_number_conversion.py
+++ b/tests/test_number_conversion.py
@@ -29,6 +29,8 @@ def test_str_unchanged_if_no_numbers(input_text):
("I am the fourth cousin", "I am the 4 cousin"),
("forty-two", "42"),
("forty_two", "42"),
+ ("six hundred seventy five thousand word book", "675000 word book"),
+ ("one million two hundred twenty nine thousand three hundred and eighty six", "1229386"),
])
def test_positive_integers(input_text, expected):
t2d_default = text2digits.Text2Digits()
@@ -114,6 +116,7 @@ def test_spelling_correction(input_text, expected):
("1.2345 hundred", "123.45"),
("twenty 1.0", "20 1.0"),
("100 and two", "102"),
+ ('6 2020', '6 2020'),
])
def test_number_literals(input_text, expected):
t2d_default = text2digits.Text2Digits()
| Problems to convert date in format like "January sixth twenty twenty"
from text2digits import text2digits
t2d = text2digits.Text2Digits()
print(t2d.convert("january six twenty nineteen"))
print(t2d.convert("january 6 2019"))
print(t2d.convert("january six twenty twenty"))
print(t2d.convert("january 6 2020"))
print(t2d.convert("january six twenty twenty one"))
print(t2d.convert("january six in twenty twenty one"))
print(t2d.convert("january 6 2021"))
Output:
january 62019
january 6 2019
january 62020
january 12120 (!! pay attention to number)
january 62021
january 6 in 2021
january 6 2021 | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_number_conversion.py::test_positive_integers[one",
"tests/test_number_conversion.py::test_positive_integers[six",
"tests/test_number_conversion.py::test_number_literals[6"
] | [
"tests/test_number_conversion.py::test_str_unchanged_if_no_numbers[A",
"tests/test_number_conversion.py::test_str_unchanged_if_no_numbers[Hello",
"tests/test_number_conversion.py::test_positive_integers[ten",
"tests/test_number_conversion.py::test_positive_integers[hundred",
"tests/test_number_conversion.py::test_positive_integers[fifty",
"tests/test_number_conversion.py::test_positive_integers[thousand",
"tests/test_number_conversion.py::test_positive_integers[two",
"tests/test_number_conversion.py::test_positive_integers[I",
"tests/test_number_conversion.py::test_positive_integers[forty-two-42]",
"tests/test_number_conversion.py::test_positive_integers[forty_two-42]",
"tests/test_number_conversion.py::test_years[I",
"tests/test_number_conversion.py::test_years[thirty",
"tests/test_number_conversion.py::test_years[sixteen",
"tests/test_number_conversion.py::test_years[twenty",
"tests/test_number_conversion.py::test_years[fifty",
"tests/test_number_conversion.py::test_years[sixty",
"tests/test_number_conversion.py::test_multiple_types_of_numbers[it",
"tests/test_number_conversion.py::test_multiple_types_of_numbers[I",
"tests/test_number_conversion.py::test_multiple_types_of_numbers[asb",
"tests/test_number_conversion.py::test_multiple_types_of_numbers[twenty",
"tests/test_number_conversion.py::test_others[eleven",
"tests/test_number_conversion.py::test_others[Sixteen",
"tests/test_number_conversion.py::test_others[twenty",
"tests/test_number_conversion.py::test_others[three",
"tests/test_number_conversion.py::test_others[nineteen-19]",
"tests/test_number_conversion.py::test_others[ninteen-ninteen]",
"tests/test_number_conversion.py::test_others[nintteen-nintteen]",
"tests/test_number_conversion.py::test_others[ninten-ninten]",
"tests/test_number_conversion.py::test_others[ninetin-ninetin]",
"tests/test_number_conversion.py::test_others[ninteen",
"tests/test_number_conversion.py::test_others[sixty",
"tests/test_number_conversion.py::test_others[one",
"tests/test_number_conversion.py::test_others[zero",
"tests/test_number_conversion.py::test_others[twelve",
"tests/test_number_conversion.py::test_others[hundred",
"tests/test_number_conversion.py::test_spelling_correction[ninteen-19]",
"tests/test_number_conversion.py::test_spelling_correction[nintteen-19]",
"tests/test_number_conversion.py::test_spelling_correction[ninten-ninten]",
"tests/test_number_conversion.py::test_spelling_correction[ninetin-90]",
"tests/test_number_conversion.py::test_spelling_correction[ninteen",
"tests/test_number_conversion.py::test_number_literals[forty",
"tests/test_number_conversion.py::test_number_literals[1,000",
"tests/test_number_conversion.py::test_number_literals[1,000-1,000]",
"tests/test_number_conversion.py::test_number_literals[10,",
"tests/test_number_conversion.py::test_number_literals[2.5",
"tests/test_number_conversion.py::test_number_literals[1.2345",
"tests/test_number_conversion.py::test_number_literals[twenty",
"tests/test_number_conversion.py::test_number_literals[100",
"tests/test_number_conversion.py::test_ordinal_conversion_switch_disabled[third-True-False-3]",
"tests/test_number_conversion.py::test_ordinal_conversion_switch_disabled[third-False-False-third]",
"tests/test_number_conversion.py::test_ordinal_conversion_switch_disabled[third-True-True-3rd]",
"tests/test_number_conversion.py::test_ordinal_conversion_switch_disabled[twenty-first-True-False-21]",
"tests/test_number_conversion.py::test_ordinal_conversion_switch_disabled[twenty-first-False-False-twenty-first]",
"tests/test_number_conversion.py::test_ordinal_conversion_switch_disabled[twenty-first-True-True-21st]",
"tests/test_number_conversion.py::test_ordinal_conversion_switch_disabled[thirty-second-True-False-32]",
"tests/test_number_conversion.py::test_ordinal_conversion_switch_disabled[thirty-second-False-False-thirty-second]",
"tests/test_number_conversion.py::test_ordinal_conversion_switch_disabled[thirty-second-True-True-32nd]",
"tests/test_number_conversion.py::test_ordinal_conversion_switch_disabled[forty-third-True-False-43]",
"tests/test_number_conversion.py::test_ordinal_conversion_switch_disabled[forty-third-False-False-forty-third]",
"tests/test_number_conversion.py::test_ordinal_conversion_switch_disabled[forty-third-True-True-43rd]",
"tests/test_number_conversion.py::test_ordinal_conversion_switch_disabled[tenth-True-False-10]",
"tests/test_number_conversion.py::test_ordinal_conversion_switch_disabled[tenth-False-False-tenth]",
"tests/test_number_conversion.py::test_ordinal_conversion_switch_disabled[tenth-True-True-10th]",
"tests/test_number_conversion.py::test_ordinal_conversion_switch_disabled[fifty-fourth-True-False-54]",
"tests/test_number_conversion.py::test_ordinal_conversion_switch_disabled[fifty-fourth-False-False-fifty-fourth]",
"tests/test_number_conversion.py::test_ordinal_conversion_switch_disabled[fifty-fourth-True-True-54th]",
"tests/test_number_conversion.py::test_ordinal_conversion_switch_disabled[twentieth-True-False-20]",
"tests/test_number_conversion.py::test_ordinal_conversion_switch_disabled[twentieth-False-False-twentieth]",
"tests/test_number_conversion.py::test_ordinal_conversion_switch_disabled[twentieth-True-True-20th]",
"tests/test_number_conversion.py::test_ordinal_conversion_switch_disabled[seventieth-True-False-70]",
"tests/test_number_conversion.py::test_ordinal_conversion_switch_disabled[seventieth-False-False-seventieth]",
"tests/test_number_conversion.py::test_ordinal_conversion_switch_disabled[seventieth-True-True-70th]",
"tests/test_number_conversion.py::test_ordinal_conversion_switch_disabled[hundredth-True-False-100]",
"tests/test_number_conversion.py::test_ordinal_conversion_switch_disabled[hundredth-False-False-hundredth]",
"tests/test_number_conversion.py::test_ordinal_conversion_switch_disabled[hundredth-True-True-100th]",
"tests/test_number_conversion.py::test_ordinal_conversion_switch_disabled[seven-hundredth-True-False-700]",
"tests/test_number_conversion.py::test_ordinal_conversion_switch_disabled[seven-hundredth-False-False-seven-hundredth]",
"tests/test_number_conversion.py::test_ordinal_conversion_switch_disabled[seven-hundredth-True-True-700th]",
"tests/test_number_conversion.py::test_ordinal_conversion_switch_disabled[thousandth-True-False-1000]",
"tests/test_number_conversion.py::test_ordinal_conversion_switch_disabled[thousandth-False-False-thousandth]",
"tests/test_number_conversion.py::test_ordinal_conversion_switch_disabled[thousandth-True-True-1000th]",
"tests/test_number_conversion.py::test_ordinal_conversion_switch_disabled[ten-thousandth-True-False-10000]",
"tests/test_number_conversion.py::test_ordinal_conversion_switch_disabled[ten-thousandth-False-False-ten-thousandth]",
"tests/test_number_conversion.py::test_ordinal_conversion_switch_disabled[ten-thousandth-True-True-10000th]",
"tests/test_number_conversion.py::test_ordinal_conversion_switch_disabled[two-hundred-thousandth-True-False-200000]",
"tests/test_number_conversion.py::test_ordinal_conversion_switch_disabled[two-hundred-thousandth-False-False-two-hundred-thousandth]",
"tests/test_number_conversion.py::test_ordinal_conversion_switch_disabled[two-hundred-thousandth-True-True-200000th]",
"tests/test_number_conversion.py::test_ordinal_conversion_switch_disabled[millionth-True-False-1000000]",
"tests/test_number_conversion.py::test_ordinal_conversion_switch_disabled[millionth-False-False-millionth]",
"tests/test_number_conversion.py::test_ordinal_conversion_switch_disabled[millionth-True-True-1000000th]",
"tests/test_number_conversion.py::test_ordinal_conversion_switch_disabled[millionth-False-True-1000000th]",
"tests/test_number_conversion.py::test_ordinal_at_the_end_of_the_sentence[eighth-True-False-8]",
"tests/test_number_conversion.py::test_ordinal_at_the_end_of_the_sentence[eighth-False-False-eighth]",
"tests/test_number_conversion.py::test_ordinal_at_the_end_of_the_sentence[eighth-True-True-8th]",
"tests/test_number_conversion.py::test_ordinal_at_the_end_of_the_sentence[ninety-seventh-True-False-97]",
"tests/test_number_conversion.py::test_ordinal_at_the_end_of_the_sentence[ninety-seventh-False-False-ninety-seventh]",
"tests/test_number_conversion.py::test_ordinal_at_the_end_of_the_sentence[ninety-seventh-True-True-97th]",
"tests/test_number_conversion.py::test_ordinal_multi_occurrence_and_cardinal",
"tests/test_number_conversion.py::test_time_formats[its",
"tests/test_number_conversion.py::test_time_formats[when",
"tests/test_number_conversion.py::test_time_formats[at"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2020-07-07T15:46:10Z" | mit |
|
ShaneKent__PyEventLogViewer-133 | diff --git a/winlogtimeline/collector/parser.py b/winlogtimeline/collector/parser.py
index 8ebc740..72276ff 100644
--- a/winlogtimeline/collector/parser.py
+++ b/winlogtimeline/collector/parser.py
@@ -379,6 +379,10 @@ def parser(raw, record):
# if user_parsers.get(record['event_source'], {}).get(record['event_id'], None) is not None:
# parse_record = user_parser
+ if get_event_data_section(raw) is False:
+ print('NOTE: A corrupted record was almost parsed with EventID ', record['event_id'])
+ return None
+
if parse_record is not None:
try:
record = parse_record(raw, record)
@@ -400,3 +404,17 @@ def get_string(string):
if isinstance(string, str):
return string
return string["#text"]
+
+
+def get_event_data_section(raw):
+ """
+ Helper to get the 'EventData' or 'UserData' key of the base XML for each record. If this fails, it is very likely that the
+ record is corrupted due to the log recovery software.
+ :param raw:
+ :return: whether or not the key exists.
+ """
+
+ if 'EventData' not in raw['Event'] and 'UserData' not in raw['Event']:
+ return False
+
+ return True
diff --git a/winlogtimeline/ui/ui.py b/winlogtimeline/ui/ui.py
index ab367b2..7f0c94b 100644
--- a/winlogtimeline/ui/ui.py
+++ b/winlogtimeline/ui/ui.py
@@ -52,22 +52,11 @@ class GUI(Tk):
self.system = platform.system()
self.changes_made = False
- self.try_create_startup_window()
+ self.create_startup_window()
self.__disable__()
self.protocol('WM_DELETE_WINDOW', self.__destroy__)
- def try_create_startup_window(self):
- """
- Checks the config to determine whether or not a start-up window should be created.
- :return:
- """
- if self.program_config.get("startup_window", None):
- window = StartupWindow(self)
- window.attributes('-topmost', True)
- else:
- print("NOTE: Please delete your local 'config.json' file.")
-
def update_status_bar(self, text):
"""
Updates the status bar.
@@ -213,6 +202,25 @@ class GUI(Tk):
t = Thread(target=callback)
t.start()
+ def create_startup_window(self):
+ """
+ Helper function that checks the config.json file and decides whether or not to display the startup window.
+ :return:
+ """
+ startup_window = self.program_config.get("startup_window", None)
+
+ # Check to see if the config.json file has a startup_window key.
+ if startup_window is None:
+ # self.program_config.update({"startup_window": True})
+ self.program_config["startup_window"] = True
+ startup_window = True
+
+ util.data.write_config(self.program_config)
+
+ if startup_window:
+ window = StartupWindow(self)
+ window.attributes('-topmost', True)
+
def __disable__(self):
self.enabled = False
if self.system != 'Darwin':
| ShaneKent/PyEventLogViewer | 13467e8bad378480d9e4e5abe7b9c7875fd28e04 | diff --git a/tests/test_parser.py b/tests/test_parser.py
index 25cdbe1..f05251c 100644
--- a/tests/test_parser.py
+++ b/tests/test_parser.py
@@ -1177,6 +1177,49 @@ def test_parse_wanted():
}
assert parser.parser(d, rec) is not None
+
+def test_corrupt_record():
+ xml_corrupt = (
+ '<Event xmlns = "http://schemas.microsoft.com/win/2004/08/events/event">'
+ '<System>'
+ '<Provider Name="Microsoft-Windows-Power-Troubleshooter" Guid="{A68CA8B7-004F-D7B6-A698-07E2DE0F1F5D}"/>'
+ '<EventID>1</EventID>'
+ '<Version>1</Version>'
+ '<Level>4</Level>'
+ '<Task>5</Task>'
+ '<Opcode>0</Opcode>'
+ '<Keywords>0x8000000000000010</Keywords>'
+ '<TimeCreated SystemTime="2017-01-02T00:28:02.499911900Z"/>'
+ '<EventRecordID>521</EventRecordID>'
+ '<Correlation/>'
+ '<Execution ProcessID="4" ThreadID="372"/>'
+ '<Channel>System</Channel>'
+ '<Computer>LAPTOP-9KUQNI2Q</Computer>'
+ '<Security/>'
+ '</System>'
+ 'CORRUPTED'
+ 'LIGHTNING STRIKES THE WIRE'
+ 'ZZZZZAAAAAAAPPPPPPP!!!!!'
+ '</Event>'
+ )
+ d = xmltodict.parse(xml_corrupt)
+ sys = d['Event']['System']
+ rec = {'timestamp_utc': sys['TimeCreated']['@SystemTime'],
+ 'event_id': sys['EventID'],
+ 'description': '',
+ 'details': '',
+ 'event_source': sys['Provider']['@Name'],
+ 'event_log': sys['Channel'],
+ 'session_id': '',
+ 'account': '',
+ 'computer_name': sys['Computer'],
+ 'record_number': sys['EventRecordID'],
+ 'recovered': True,
+ 'alias': 'Sample'
+ }
+
+ assert parser.parser(d, rec) is None
+
# def test_parser():
# for record in records:
# try:
| Unit test to check that parsing errors are handled
Originally from issue #89, failed during that sprint.
Add a unit test which passes invalid data to the parser and tests that errors are handled. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_parser.py::test_corrupt_record"
] | [
"tests/test_parser.py::test_parser_id_1",
"tests/test_parser.py::test_parser_id_12",
"tests/test_parser.py::test_parser_id_13",
"tests/test_parser.py::test_parser_id_41",
"tests/test_parser.py::test_parser_id_42",
"tests/test_parser.py::test_parser_id_104",
"tests/test_parser.py::test_parser_id_1074_unwanted",
"tests/test_parser.py::test_parser_id_1074_wanted",
"tests/test_parser.py::test_parser_id_1102",
"tests/test_parser.py::test_parser_id_4616",
"tests/test_parser.py::test_parser_id_4624",
"tests/test_parser.py::test_parser_id_4634",
"tests/test_parser.py::test_parser_id_4647",
"tests/test_parser.py::test_parser_id_4720",
"tests/test_parser.py::test_parser_id_4724",
"tests/test_parser.py::test_parser_id_6008",
"tests/test_parser.py::test_parser_id_6013",
"tests/test_parser.py::test_parse_unwanted",
"tests/test_parser.py::test_parse_wanted"
] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_issue_reference",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2018-02-24T07:34:12Z" | mit |