Dataset Viewer
repo
stringlengths 13
49
| pull_number
int64 2
368
| instance_id
stringlengths 17
53
| issue_numbers
stringlengths 5
14
| base_commit
stringlengths 40
40
| patch
stringlengths 332
42.9k
| test_patch
stringlengths 364
15.2k
| problem_statement
stringlengths 23
3.55k
| hints_text
stringlengths 0
4.13k
| created_at
stringdate 2016-04-14 18:10:09
2025-03-28 13:44:43
| version
stringclasses 1
value | FAIL_TO_PASS
sequencelengths 1
23
| PASS_TO_PASS
sequencelengths 0
236
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
DiamondLightSource/ispyb-api | 73 | DiamondLightSource__ispyb-api-73 | ['68'] | 7be86ec8aff0d1a2aecdb99efeb858f16992bff4 | diff --git a/ispyb/model/__init__.py b/ispyb/model/__init__.py
index c75c2f60..4f6d1ec3 100644
--- a/ispyb/model/__init__.py
+++ b/ispyb/model/__init__.py
@@ -7,9 +7,6 @@ class DBCache(object):
in self._data. Cached data should be accessed as self._data. On first
uncached access reload() is called.'''
- def __init__(self):
- '''Data has not yet been loaded from the database.'''
-
def load(self):
'''Ensure data is loaded from the database.'''
if not self.cached:
@@ -95,6 +92,10 @@ def __nonzero__(self):
'''Python 2: value when used in bool() context.'''
return bool(self._value)
+ def __hash__(self):
+ '''Pass on the hash value of the inner object.'''
+ return hash(self._value)
+
def add_properties(objectclass, property_list):
'''Generate class properties for a model that provide read-only access
diff --git a/ispyb/model/datacollection.py b/ispyb/model/datacollection.py
index 861d3bcf..d701c651 100644
--- a/ispyb/model/datacollection.py
+++ b/ispyb/model/datacollection.py
@@ -29,7 +29,7 @@ def __init__(self, dcid, db_area, preload=None):
def reload(self):
'''Load/update information from the database.'''
- self._data = self._db.retrieve_data_collection_main(self._dcid)[0]
+ self._data = self._db.retrieve_data_collection(self._dcid)[0]
@property
def dcid(self):
@@ -98,15 +98,26 @@ def __str__(self):
))).format(self)
ispyb.model.add_properties(DataCollection, (
+ ('comment', 'comments', 'A free comment field for the data collection.'),
('dcgid', 'groupId', 'Returns the Data Collection Group ID associated with this data collection. '
'You can use .group to get the data collection group model object instead'),
+ ('detector_distance', 'detectorDistance', 'Distance from the sample to the detector in mm'),
+ ('detector_2theta', 'detector2Theta', '2Theta angle between the main beam and the detector normal in degrees'),
('file_template', 'fileTemplate', 'Template for file names with the character \'#\' standing in for image number digits.'),
('file_directory', 'imgDir', 'Fully qualified path to the image files'),
('time_start', 'startTime', None),
+ ('time_exposure', 'exposureTime', 'Exposure time per frame in seconds'),
('time_end', 'endTime', None),
('image_count', 'noImages', None),
('image_start_number', 'startImgNumber', None),
+ ('resolution', 'resolution', 'Inscribed resolution circle in Angstrom. Currently only well-defined for data collections with 2theta=0'),
('status', 'status', 'Returns a string representing the current data collection status.'),
+ ('snapshot1', 'snapshot1', 'One of four possible fields to store file paths to image files relating to the data collection'),
+ ('snapshot2', 'snapshot2', 'One of four possible fields to store file paths to image files relating to the data collection'),
+ ('snapshot3', 'snapshot3', 'One of four possible fields to store file paths to image files relating to the data collection'),
+ ('snapshot4', 'snapshot4', 'One of four possible fields to store file paths to image files relating to the data collection'),
+ ('transmission', 'transmission', 'Beam transmission, in per cent'),
+ ('wavelength', 'wavelength', 'Beam wavelength in Angstrom'),
))
| diff --git a/tests/model/test_datacollection.py b/tests/model/test_datacollection.py
index 9efe3efc..3cea6d4e 100644
--- a/tests/model/test_datacollection.py
+++ b/tests/model/test_datacollection.py
@@ -4,72 +4,110 @@
import mock
import pytest
+
def test_datacollection_model_retrieves_database_records():
- db, record = mock.Mock(), mock.Mock()
- db.retrieve_data_collection_main.return_value = [record]
+ db, record = mock.Mock(), mock.Mock()
+ db.retrieve_data_collection.return_value = [record]
- dc = ispyb.model.datacollection.DataCollection(1234, db)
- assert not db.retrieve_data_collection_main.called
- assert '1234' in str(dc)
- assert '1234' in repr(dc)
- assert 'uncached' in repr(dc)
+ dc = ispyb.model.datacollection.DataCollection(1234, db)
+ assert not db.retrieve_data_collection.called
+ assert "1234" in str(dc)
+ assert "1234" in repr(dc)
+ assert "uncached" in repr(dc)
- dc.load()
- db.retrieve_data_collection_main.assert_called_once_with(1234)
- assert dc._data == record
- assert '1234' in repr(dc)
- assert 'cached' in repr(dc) and 'uncached' not in repr(dc)
+ dc.load()
+ db.retrieve_data_collection.assert_called_once_with(1234)
+ assert dc._data == record
+ assert "1234" in repr(dc)
+ assert "cached" in repr(dc) and "uncached" not in repr(dc)
- # Test caching behaviour
- dc.load()
- db.retrieve_data_collection_main.assert_called_once()
+ # Test caching behaviour
+ dc.load()
+ db.retrieve_data_collection.assert_called_once()
def test_datacollection_model_accepts_preloading():
- db, record = mock.Mock(), mock.Mock()
+ db, record = mock.Mock(), mock.Mock()
- dc = ispyb.model.datacollection.DataCollection(1234, db, preload=record)
- assert dc._data == record
+ dc = ispyb.model.datacollection.DataCollection(1234, db, preload=record)
+ assert dc._data == record
- dc.load()
- assert not db.retrieve_data_collection_main.called
+ dc.load()
+ assert not db.retrieve_data_collection.called
database_column_to_attribute_name = {
- "groupId": None,
- "detectorId": None,
+ "apertureSizeX": None,
+ "axisEnd": None,
+ "axisRange": None,
+ "axisStart": None,
+ "beamSizeAtSampleX": None,
+ "beamSizeAtSampleY": None,
+ "bestWilsonPlotPath": None,
"blSubSampleId": None,
+ "chiStart": None,
+ "comments": "comment",
"dcNumber": None,
- "startTime": "time_start",
+ "detector2Theta": "detector_2theta",
+ "detectorDistance": "detector_distance",
+ "detectorId": None,
"endTime": "time_end",
- "status": None,
- "noImages": "image_count",
- "startImgNumber": "image_start_number",
- "noPasses": None,
+ "exposureTime": "time_exposure",
+ "fileTemplate": "file_template",
+ "flux": None,
+ "fluxEnd": None,
+ "focalSpotSizeAtSampleX": None,
+ "focalSpotSizeAtSampleY": None,
+ "groupId": None,
+ "imgContainerSubPath": None,
"imgDir": None,
"imgPrefix": None,
"imgSuffix": None,
- "fileTemplate": None,
- "snapshot1": None,
- "snapshot2": None,
- "snapshot3": None,
- "snapshot4": None,
- "comments": None,
-}
-record = {
- k: getattr(mock.sentinel, k)
- for k in database_column_to_attribute_name
+ "kappaStart": None,
+ "noImages": "image_count",
+ "noPasses": None,
+ "omegaStart": None,
+ "overlap": None,
+ "phiStart": None,
+ "resolution": "resolution",
+ "resolutionAtCorner": None,
+ "rotationAxis": None,
+ "slitGapHorizontal": None,
+ "slitGapVertical": None,
+ "snapshot1": "snapshot1",
+ "snapshot2": "snapshot2",
+ "snapshot3": "snapshot3",
+ "snapshot4": "snapshot4",
+ "startImgNumber": "image_start_number",
+ "startTime": "time_start",
+ "status": "status",
+ "synchrotronMode": None,
+ "transmission": "transmission",
+ "undulatorGap1": None,
+ "undulatorGap2": None,
+ "undulatorGap3": None,
+ "wavelength": "wavelength",
+ "xBeam": None,
+ "yBeam": None,
}
+record = {k: getattr(mock.sentinel, k) for k in database_column_to_attribute_name}
record["imgDir"] = "/path/to/some/images/"
record["fileTemplate"] = "file_####.cbf"
[email protected]('column,attribute', filter(lambda ca: ca[1], database_column_to_attribute_name.items()))
+
[email protected](
+ "column,attribute",
+ filter(lambda ca: ca[1], database_column_to_attribute_name.items()),
+)
def test_datacollection_model_attributes_return_correct_values(column, attribute):
- dc = ispyb.model.datacollection.DataCollection(1234, None, preload=record)
- assert getattr(dc, attribute) == record[column]
+ dc = ispyb.model.datacollection.DataCollection(1234, None, preload=record)
+ assert getattr(dc, attribute) == record[column]
+
[email protected]('printed_attribute', ('startTime', 'endTime', 'imgDir', 'fileTemplate'))
[email protected](
+ "printed_attribute", ("startTime", "endTime", "imgDir", "fileTemplate")
+)
def test_pretty_printing_datacollection_shows_attribute(printed_attribute):
- dc_str = str(ispyb.model.datacollection.DataCollection(1234, None, preload=record))
- assert "1234" in dc_str
- assert str(record[printed_attribute]) in dc_str
+ dc_str = str(ispyb.model.datacollection.DataCollection(1234, None, preload=record))
+ assert "1234" in dc_str
+ assert str(record[printed_attribute]) in dc_str
| Make extended data collection information accessible via DCID model
Currently it is not possible to access eg. the resolution column of a data collection when given the DCID.
| Yes, I think that calls for a new stored procedure. The `retrieve_dc_main_v2` is meant to retrieve only a certain subset of the columns, as we also have `upsert_dc_main_v2` that upserts the same columns, and `update_dc_experiment_v2` which updates the "experiment" columns which includes resolution.
I will write a new stored procedure that retrieves all the columns (except deprecated ones and other undesirables).
OK, I've made a PR for this: https://github.com/DiamondLightSource/ispyb-api/pull/71
Thanks, I'll pick it up from here | 2019-04-16T11:53:05.000 | -1.0 | [
"tests/model/test_datacollection.py::test_datacollection_model_attributes_return_correct_values[comments-comment]",
"tests/model/test_datacollection.py::test_datacollection_model_retrieves_database_records",
"tests/model/test_datacollection.py::test_datacollection_model_attributes_return_correct_values[wavelength-wavelength]",
"tests/model/test_datacollection.py::test_datacollection_model_attributes_return_correct_values[snapshot3-snapshot3]",
"tests/model/test_datacollection.py::test_datacollection_model_attributes_return_correct_values[snapshot4-snapshot4]",
"tests/model/test_datacollection.py::test_datacollection_model_attributes_return_correct_values[snapshot1-snapshot1]",
"tests/model/test_datacollection.py::test_datacollection_model_attributes_return_correct_values[detector2Theta-detector_2theta]",
"tests/model/test_datacollection.py::test_datacollection_model_attributes_return_correct_values[resolution-resolution]",
"tests/model/test_datacollection.py::test_datacollection_model_attributes_return_correct_values[exposureTime-time_exposure]",
"tests/model/test_datacollection.py::test_datacollection_model_attributes_return_correct_values[detectorDistance-detector_distance]",
"tests/model/test_datacollection.py::test_datacollection_model_attributes_return_correct_values[transmission-transmission]",
"tests/model/test_datacollection.py::test_datacollection_model_attributes_return_correct_values[snapshot2-snapshot2]"
] | [
"tests/model/test_datacollection.py::test_datacollection_model_attributes_return_correct_values[noImages-image_count]",
"tests/model/test_datacollection.py::test_pretty_printing_datacollection_shows_attribute[fileTemplate]",
"tests/model/test_datacollection.py::test_pretty_printing_datacollection_shows_attribute[imgDir]",
"tests/model/test_datacollection.py::test_datacollection_model_attributes_return_correct_values[fileTemplate-file_template]",
"tests/model/test_datacollection.py::test_datacollection_model_attributes_return_correct_values[startTime-time_start]",
"tests/model/test_datacollection.py::test_datacollection_model_attributes_return_correct_values[startImgNumber-image_start_number]",
"tests/model/test_datacollection.py::test_pretty_printing_datacollection_shows_attribute[endTime]",
"tests/model/test_datacollection.py::test_pretty_printing_datacollection_shows_attribute[startTime]",
"tests/model/test_datacollection.py::test_datacollection_model_attributes_return_correct_values[endTime-time_end]",
"tests/model/test_datacollection.py::test_datacollection_model_attributes_return_correct_values[status-status]",
"tests/model/test_datacollection.py::test_datacollection_model_accepts_preloading"
] |
encukou/freezeyt | 368 | encukou__freezeyt-368 | ['352'] | 5326af4463108200321d7860371cd68b704b261d | diff --git a/freezeyt/freezer.py b/freezeyt/freezer.py
index 634fa491..24739996 100644
--- a/freezeyt/freezer.py
+++ b/freezeyt/freezer.py
@@ -368,6 +368,14 @@ async def finish(self):
result = await self.saver.finish(success, cleanup)
if success:
self.call_hook('success', self.freeze_info)
+
+ for task in self.done_tasks.values():
+ if len(task.urls) > 1:
+ self.warnings.append(
+ f"Static file '{task.path}' is requested from"
+ f" different URLs {sorted([url.path for url in task.urls])}"
+ )
+
for warning in self.warnings:
print(f"[WARNING] {warning}")
return result
| diff --git a/tests/test_logging.py b/tests/test_logging.py
index 8d83a041..c091d163 100644
--- a/tests/test_logging.py
+++ b/tests/test_logging.py
@@ -1,7 +1,8 @@
import pytest
-from freezeyt import freeze
+from flask import Flask
+from freezeyt import freeze
from testutil import context_for_test
@@ -26,3 +27,70 @@ def test_warn_multi_slashes_prefix(capsys, prefix):
)
assert expected_output in captured.out
+
+
+def test_warn_one_page_from_different_URLs(capsys):
+ """App can define different URLs with different content,
+ which are saved then as one static file by Freezeyt
+ (e.g. '/' and '/index.html'). One content will be always lost.
+ If this situation occurs, we should get a warning at least.
+ """
+
+ app = Flask(__name__)
+
+ index_routes = ['/', '/index.html']
+ second_page_routes = ['/second_page/', '/second_page/index.html']
+
+ @app.route(index_routes[0])
+ def index():
+ return """
+ <a href='/index.html'>INDEX FILE</a>
+ <a href='/second_page/index.html'>SECOND PAGE FILE</a>
+"""
+
+ @app.route(index_routes[1])
+ def index_html():
+ return "INDEX FILE"
+
+ @app.route(second_page_routes[0])
+ def second_page():
+ return "SECOND PAGE"
+
+ @app.route(second_page_routes[1])
+ def second_page_html():
+ # Link to index.html test if warning is
+ # printing out only once
+ return """
+ <a href='/second_page/'>SECOND PAGE</a>
+ <a href='/index.html'>INDEX FILE</a>
+"""
+
+ config = {
+ 'prefix': 'http://example.test/',
+ 'output': {'type': 'dict'},
+ }
+
+ freeze(app, config)
+
+ captured = capsys.readouterr()
+ stdout = captured.out
+
+ warnings_counter = 0
+ for l in stdout.splitlines():
+ if l.startswith("[WARNING]"):
+ warnings_counter += 1
+
+ assert warnings_counter == 2
+
+ index_warn = (
+ "[WARNING] Static file 'index.html' is requested"
+ f" from different URLs {index_routes}"
+ )
+ second_page_warn = (
+ "[WARNING] Static file 'second_page/index.html' is requested"
+ f" from different URLs {second_page_routes}"
+ )
+
+ assert index_warn in stdout
+ assert second_page_warn in stdout
+
| Warn if different URLs are saved to the same file
Both `/` and `/index.html` are saved as `index.html`, but can be different in a dynamic app.
Links in apps designed to be frozen should be consistent, and we can warn if they're not.
Same for `x/y` and `x//y`.
| Do we want to solve `x/y` and `x//y`? I can not test it with nowadays tools as `browsers`, `curl`, `wget`. I've always get status `308` as redirect to `x/y`. Same for quoted `/` as `%2F`.
`wget` output:
```
127.0.0.1 - - "GET /x/%2Fy HTTP/1.1" 308
127.0.0.1 - - "GET /x/y HTTP/1.1" 200
127.0.0.1 - - "GET /x//y HTTP/1.1" 308
127.0.0.1 - - "GET /x/y HTTP/1.1" 200
```
OK, if all tools we know of normalize `//` to `/`, let's not warn about the difference. | 2023-09-21T12:51:23.000 | -1.0 | [
"tests/test_logging.py::test_warn_one_page_from_different_URLs"
] | [
"tests/test_logging.py::test_warn_multi_slashes_prefix[https://example.test////a/]",
"tests/test_logging.py::test_warn_multi_slashes_prefix[https://example.test/a//]"
] |
encukou/freezeyt | 364 | encukou__freezeyt-364 | ['355'] | 337eca82ff071e9f1f6d23bb6a412662107cad3b | diff --git a/freezeyt/freezer.py b/freezeyt/freezer.py
index d09b7376..3d6f7b59 100644
--- a/freezeyt/freezer.py
+++ b/freezeyt/freezer.py
@@ -314,6 +314,10 @@ def __init__(self, app: WSGIApplication, config: dict):
TaskStatus.IN_PROGRESS: self.inprogress_tasks,
TaskStatus.FAILED: self.failed_tasks,
}
+ if "//" in prefix_parsed.path:
+ self.warnings.append(
+ f"Freezeyt reduces multiple consecutive slashes in {prefix!r} to one"
+ )
self.hooks = {}
for name, funcs in config.get('hooks', {}).items():
| diff --git a/tests/test_logging.py b/tests/test_logging.py
new file mode 100644
index 00000000..8d83a041
--- /dev/null
+++ b/tests/test_logging.py
@@ -0,0 +1,28 @@
+import pytest
+
+from freezeyt import freeze
+
+from testutil import context_for_test
+
+
+PREFIX_MULTI_SLASH = (
+ "https://example.test/a//",
+ "https://example.test////a/",
+)
[email protected]('prefix', PREFIX_MULTI_SLASH)
+def test_warn_multi_slashes_prefix(capsys, prefix):
+ config = {
+ 'prefix': prefix,
+ 'output': {'type': 'dict'},
+ }
+
+ with context_for_test('app_simple') as module:
+ freeze(module.app, config)
+ captured = capsys.readouterr()
+
+ expected_output = (
+ "[WARNING] Freezeyt reduces multiple consecutive"
+ f" slashes in {prefix!r} to one\n"
+ )
+
+ assert expected_output in captured.out
| Test and fix prefix with multiple slashes
- `url_parse("https://example.org/////freezeyt")`
- `url_parse("https://example.org/////freezeyt/")`
- `url_parse("https://example.org/////freezeyt////abcd////")`
multiple slashes are valid: https://superuser.com/questions/1286325/why-is-there-no-error-when-i-enter-many-slashes-in-a-file-url-in-a-browser
| ```shell
>>> urllib.parse.urlsplit("https://example.com///a/")
SplitResult(scheme='https', netloc='example.com', path='///a/', query='', fragment='')
>>> p = urllib.parse.urljoin("https://example.com///a/", "b/")
>>> p
'https://example.com/a/b/'
```
Fix it just with warning!
check https://docs.python.org/3/library/logging.html
`python -m freezeyt tests.fixtures.app_simple.app build --prefix "https://example.com/a//"`
`python -m freezeyt tests.fixtures.app_simple.app build --prefix "https://example.com////a/"` | 2023-08-30T14:04:16.000 | -1.0 | [
"tests/test_logging.py::test_warn_multi_slashes_prefix[https://example.test////a/]",
"tests/test_logging.py::test_warn_multi_slashes_prefix[https://example.test/a//]"
] | [] |
cldf/cltoolkit | 18 | cldf__cltoolkit-18 | ['17'] | 3f70bea96f8de4efd0707dd018f0a2e47644c785 | diff --git a/src/cltoolkit/features/__init__.py b/src/cltoolkit/features/__init__.py
index 5645efe..a8774f6 100644
--- a/src/cltoolkit/features/__init__.py
+++ b/src/cltoolkit/features/__init__.py
@@ -1,1 +1,1 @@
-from cltoolkit.features.collection import *
+from cltoolkit.features.collection import * # noqa: F403, F401
diff --git a/src/cltoolkit/features/collection.py b/src/cltoolkit/features/collection.py
index 3471d22..b5434aa 100644
--- a/src/cltoolkit/features/collection.py
+++ b/src/cltoolkit/features/collection.py
@@ -10,6 +10,8 @@
from cltoolkit import pkg_path
+__all__ = ['feature_data', 'Feature', 'FeatureCollection']
+
def feature_data():
return jsonlib.load(pkg_path / 'features' / 'features.json')
diff --git a/src/cltoolkit/features/lexicon.py b/src/cltoolkit/features/lexicon.py
index b656ba3..f2bd70a 100644
--- a/src/cltoolkit/features/lexicon.py
+++ b/src/cltoolkit/features/lexicon.py
@@ -25,6 +25,7 @@ def has_a_b_colexified(language, alist=None, blist=None, ablist=None):
if abforms:
return True
+
def has_a_in_b(
language, alist=None, blist=None):
"""
@@ -82,38 +83,38 @@ def has_a_in_b(
)
has_toe_and_foot_colexified = partial(
- has_a_b_colexified,
- alist=["FOOT", "FOOT OR LEG"],
- blist=["TOE", "FINGER OR TOE"]
+ has_a_b_colexified,
+ alist=["FOOT", "FOOT OR LEG"],
+ blist=["TOE", "FINGER OR TOE"]
)
has_eye_in_tear = partial(
- has_a_in_b,
- alist=["EYE"],
- blist=["TEAR (OF EYE)"]
+ has_a_in_b,
+ alist=["EYE"],
+ blist=["TEAR (OF EYE)"]
)
has_water_in_tear = partial(
- has_a_in_b,
- alist=["WATER"],
- blist=["TEAR (OF EYE)"]
+ has_a_in_b,
+ alist=["WATER"],
+ blist=["TEAR (OF EYE)"]
)
has_bark_and_skin_colexified = partial(
- has_a_b_colexified,
- alist=["BARK", "BARK OR SHELL"],
- blist=["SKIN", "SKIN (HUMAN)", "SKIN (ANIMAL)"],
- clist=["BARK OR SKIN"]
- )
+ has_a_b_colexified,
+ alist=["BARK", "BARK OR SHELL"],
+ blist=["SKIN", "SKIN (HUMAN)", "SKIN (ANIMAL)"],
+ clist=["BARK OR SKIN"]
+)
has_skin_in_bark = partial(
- has_a_in_b,
- alist=["SKIN", "SKIN (HUMAN)", "SKIN (ANIMAL)"],
- blist=["BARK"]
+ has_a_in_b,
+ alist=["SKIN", "SKIN (HUMAN)", "SKIN (ANIMAL)"],
+ blist=["BARK"]
)
has_tree_in_bark = partial(
- has_a_in_b,
- alist=["TREE", "TREE OR WOOD"],
- blist=["BARK"]
+ has_a_in_b,
+ alist=["TREE", "TREE OR WOOD"],
+ blist=["BARK"]
)
diff --git a/src/cltoolkit/features/phonology.py b/src/cltoolkit/features/phonology.py
index dcde0f7..81856a0 100644
--- a/src/cltoolkit/features/phonology.py
+++ b/src/cltoolkit/features/phonology.py
@@ -17,7 +17,7 @@ def base_yes_no_query(language, attr=None):
def base_ratio(language, attr1=None, attr2=None):
return len(getattr(language.sound_inventory, attr1)) / len(
- getattr(language.sound_inventory, attr2))
+ getattr(language.sound_inventory, attr2))
vowel_quality_size = functools.partial(base_inventory_query, attr="vowels_by_quality")
@@ -29,12 +29,12 @@ def base_ratio(language, attr1=None, attr2=None):
has_tones = functools.partial(base_yes_no_query, attr="tones")
cv_ratio = functools.partial(base_ratio, attr1="consonants", attr2="vowels")
cv_quality_ratio = functools.partial(
- base_ratio, attr1="consonants_by_quality",
- attr2="vowels_by_quality")
+ base_ratio, attr1="consonants_by_quality",
+ attr2="vowels_by_quality")
cv_sounds_ratio = functools.partial(
- base_ratio,
- attr1="consonant_sounds",
- attr2="vowel_sounds")
+ base_ratio,
+ attr1="consonant_sounds",
+ attr2="vowel_sounds")
def plosive_fricative_voicing(language):
@@ -48,12 +48,10 @@ def plosive_fricative_voicing(language):
- 4: in both plosives and fricatives
"""
inv = language.sound_inventory
- voiced = set([sound.obj.manner for sound in inv.consonants if
- (sound.obj.phonation=='voiced' and sound.obj.manner in
- ['stop', 'fricative']) or (sound.obj.breathiness and
- sound.obj.manner in ['stop', 'fricative']) or (
- sound.obj.voicing and sound.obj.manner in
- ['stop', 'fricative'])])
+ voiced = {
+ sound.obj.manner for sound in inv.consonants if
+ sound.obj.manner in ['stop', 'fricative'] and # noqa: W504
+ (sound.obj.phonation == 'voiced' or sound.obj.breathiness or sound.obj.voicing)}
if not voiced:
return 1
if len(voiced) == 2:
@@ -77,15 +75,15 @@ def has_ptk(language):
"""
inv = language.sound_inventory
sounds = [sound.obj.s for sound in inv.consonants]
-
- if not 'p' in sounds and not 'g' in sounds:
+
+ if 'p' not in sounds and 'g' not in sounds:
return 1
- elif not 'g' in sounds:
+ elif 'g' not in sounds:
return 2
- elif not 'p' in sounds:
+ elif 'p' not in sounds:
return 3
elif len(set([x for x in sounds if x in ['p', 't', 't̪', 'k', 'b', 'd',
- 'g', 'd̪']])) >= 6:
+ 'g', 'd̪']])) >= 6:
return 5
else:
return 4
@@ -103,7 +101,7 @@ def has_uvular(language):
"""
inv = language.sound_inventory
uvulars = set([sound.obj.manner for sound in inv.consonants if
- sound.obj.place=='uvular'])
+ sound.obj.place == 'uvular'])
if len(uvulars) == 0:
return 1
elif len(uvulars) == 1:
@@ -118,7 +116,7 @@ def has_uvular(language):
def has_glottalized(language):
"""
WALS Feature 7A, check for glottalized or implosive consonants.
-
+
Values:
- 1: no ejectives, no implosives
- 2: has ejective stops or affricates, but no implosives
@@ -127,17 +125,17 @@ def has_glottalized(language):
- 5: has ejectives and implosives but no ejective resonants
- 6: has ejectives and ejective resonants, but no implosives
- 7: has implosives and ejective resonants but no ejective stops
- - 8:
+ - 8:
"""
inv = language.sound_inventory
ejectives = [sound for sound in inv.consonants if
- sound.obj.ejection and sound.obj.manner in
- ['stop', 'affricate']]
- resonants = [sound for sound in inv.consonants if
- sound.obj.ejection and sound.obj.manner not in
- ['stop', 'affricate']]
- implosives = [sound for sound in inv.consonants if
- sound.obj.manner == 'implosive']
+ sound.obj.ejection and sound.obj.manner in
+ ['stop', 'affricate']]
+ resonants = [sound for sound in inv.consonants if
+ sound.obj.ejection and sound.obj.manner not in
+ ['stop', 'affricate']]
+ implosives = [sound for sound in inv.consonants if
+ sound.obj.manner == 'implosive']
if not ejectives and not implosives and not resonants:
return 1
elif ejectives and not implosives and not resonants:
@@ -159,29 +157,28 @@ def has_glottalized(language):
def has_laterals(language):
"""
WALS Feature 8A, check for lateral sounds.
-
+
Values:
- 1: no laterals
- 2: one lateral, and the lateral is l
- 3: has laterals, but no stops and no l
- 4: has laterals, including l and stops
- 5: has laterals, including stops, but no l
- - 6:
-
+ - 6:
"""
inv = language.sound_inventory
laterals = set([sound.obj.manner for sound in
- inv.consonants if
- sound.obj.airstream == 'lateral'])
+ inv.consonants if
+ sound.obj.airstream == 'lateral'])
if not laterals:
return 1
elif len(laterals) == 1 and 'l' in inv.sounds:
return 2
- elif not 'stop' in laterals and not 'l' in inv.sounds:
+ elif 'stop' not in laterals and 'l' not in inv.sounds:
return 3
elif 'stop' in laterals and 'l' in inv.sounds:
return 4
- elif 'stop' in laterals and not 'l' in inv.sounds:
+ elif 'stop' in laterals and 'l' not in inv.sounds:
return 5
else:
return 6
@@ -190,7 +187,7 @@ def has_laterals(language):
def has_engma(language):
"""
WALS Feature 9A, check for nasals.
-
+
Values:
- 1: ŋ occurs in the beginning of a word
- 2: ŋ occurs but not in the beginning off words
@@ -211,7 +208,7 @@ def has_nasal_vowels(language):
WALS Feature 10A, check for nasal vowels.
"""
vowels = [sound for sound in language.sound_inventory.vowels if
- sound.obj.nasalization]
+ sound.obj.nasalization]
if vowels:
return 1
return 2
@@ -225,8 +222,7 @@ def has_rounded_vowels(language):
sound.obj.roundedness == 'rounded' and sound.obj.height in
['open', 'near-open']]
mid = [sound for sound in language.sound_inventory.vowels if
- sound.obj.roundedness == 'rounded' and
- sound.obj.height in ['open-mid', 'mid']]
+ sound.obj.roundedness == 'rounded' and sound.obj.height in ['open-mid', 'mid']]
if not high and not mid:
return 1
elif high and mid:
@@ -237,7 +233,6 @@ def has_rounded_vowels(language):
return 4
-
def syllable_structure(language):
"""
WALS Feature 12A, check for syllable complexity.
@@ -261,8 +256,6 @@ def syllable_structure(language):
return 3
-
-
def syllable_complexity(language):
"""
Compute the major syllabic patterns for a language.
@@ -275,9 +268,8 @@ def syllable_complexity(language):
it. For a given syllable, we store the form, the consonantal sounds, and
the index of the syllable in the word. These values are returned in the
form of two dictionaries, in which the number of sounds is the key.
-
"""
-
+
preceding, following = collections.defaultdict(list), collections.defaultdict(list)
for form in language.forms:
for i, syllable in enumerate(iter_syllables(form)):
@@ -286,7 +278,7 @@ def syllable_complexity(language):
if sound.type == 'marker':
log.warning(syllable, form.id, form.segments)
if sound.type not in ['vowel', 'diphthong', 'tone', 'marker'] and \
- not 'syllabic' in sound.featureset:
+ 'syllabic' not in sound.featureset:
count += 1
sounds += [sound]
else:
@@ -311,11 +303,11 @@ def lacks_common_consonants(language):
"""
inv = language.sound_inventory
bilabials = [sound for sound in inv.consonants if 'bilabial' in
- sound.obj.featureset]
+ sound.obj.featureset]
fricatives = [sound for sound in inv.consonants if 'fricative' in
- sound.obj.featureset]
+ sound.obj.featureset]
nasals = [sound for sound in inv.consonants if 'nasal' in
- sound.obj.featureset]
+ sound.obj.featureset]
if bilabials and fricatives and nasals:
return 1
elif not bilabials and fricatives and nasals:
@@ -336,12 +328,13 @@ def has_uncommon_consonants(language):
"""
inv = language.sound_inventory
clicks = [sound for sound in inv.consonants if sound.obj.manner == "click"]
- labiovelars = [sound for sound in inv.consonants if sound.obj.labialization ==
- "labialized" and sound.obj.place in ["velar", "uvular"]]
+ labiovelars = [sound for sound in inv.consonants if sound.obj.labialization == # noqa: W504
+ "labialized" and sound.obj.place in ["velar", "uvular"]]
dentalfrics = [sound for sound in inv.consonants if sound.obj.place == "dental"
- and not sound.obj.airstream == "sibilant" and sound.obj.manner == "fricative"]
- pharyngeals = [sound for sound in inv.consonants if \
- sound.obj.place == "pharyngeal" or sound.obj.pharyngealization == "pharyngealized"]
+ and not sound.obj.airstream == "sibilant" and sound.obj.manner == "fricative"]
+ pharyngeals = [sound for sound in inv.consonants if
+ sound.obj.place == "pharyngeal" or # noqa: W504
+ sound.obj.pharyngealization == "pharyngealized"]
if not clicks and not dentalfrics and not labiovelars and not pharyngeals:
return 1
if clicks and pharyngeals and dentalfrics:
diff --git a/src/cltoolkit/log.py b/src/cltoolkit/log.py
index 70c9622..9beb73a 100644
--- a/src/cltoolkit/log.py
+++ b/src/cltoolkit/log.py
@@ -1,11 +1,6 @@
"""Logging utilities"""
-from __future__ import unicode_literals, print_function, absolute_import, division
-import os
import sys
import logging
-from logging.config import fileConfig
-from tempfile import NamedTemporaryFile
-import warnings
LOGGING = """
diff --git a/src/cltoolkit/models.py b/src/cltoolkit/models.py
index 91b2f43..61941db 100644
--- a/src/cltoolkit/models.py
+++ b/src/cltoolkit/models.py
@@ -1,15 +1,17 @@
"""
Basic models.
"""
+import typing
+import statistics
import collections
-from collections import OrderedDict
+
import attr
-from cltoolkit.util import NestedAttribute, DictTuple, jaccard, MutatedDataValue
import lingpy
-from pycldf.util import DictTuple
-from pyclts import CLTS
from clldutils.misc import lazyproperty as cached_property
-import statistics
+import pyclts
+from pyclts.models import Sound as CLTSSound, Symbol
+
+from cltoolkit.util import NestedAttribute, DictTuple, jaccard, MutatedDataValue
@attr.s(repr=False)
@@ -22,7 +24,7 @@ class CLCore:
data = attr.ib(default=None)
def __repr__(self):
- return "<"+self.__class__.__name__+" "+self.id+">"
+ return "<" + self.__class__.__name__ + " " + self.id + ">"
@attr.s(repr=False)
@@ -31,7 +33,7 @@ class CLCoreWithForms(CLCore):
Base class to represent data in a wordlist that contains forms.
"""
forms = attr.ib(default=None)
-
+
@cached_property
def bipa_forms(self):
return DictTuple([f for f in self.forms if f.tokens])
@@ -65,8 +67,8 @@ class Language(CLBaseWithForms):
Base class for handling languages.
.. note::
-
- A language variety is defined for a specific dataset only.
+
+ A language variety is defined for a specific dataset only.
"""
senses = attr.ib(default=None)
concepts = attr.ib(default=None)
@@ -93,14 +95,15 @@ class Sense(CLBaseWithForms):
Concepts in source are the original concepts in the individual wordlists.
.. note::
-
- Unlike senses in a wordlist, which are dataset-specific, concepts in a wordlist are defined for all datasets.
+
+ Unlike senses in a wordlist, which are dataset-specific, concepts in a wordlist are defined
+ for all datasets.
"""
language = attr.ib(default=None)
name = MutatedDataValue("Name")
def __repr__(self):
- return '<Sense '+self.id+'>'
+ return '<Sense ' + self.id + '>'
def __eq__(self, other):
if isinstance(other, self.__class__):
@@ -110,13 +113,13 @@ def __eq__(self, other):
@classmethod
def from_sense(cls, sense, language, forms):
return cls(
- id=sense.id,
- data=sense.data,
- obj=sense.obj,
- forms=forms,
- dataset=sense.dataset,
- wordlist=sense.wordlist,
- language=language)
+ id=sense.id,
+ data=sense.data,
+ obj=sense.obj,
+ forms=forms,
+ dataset=sense.dataset,
+ wordlist=sense.wordlist,
+ language=language)
@attr.s(repr=False, eq=False)
@@ -125,7 +128,7 @@ class Concept(CLCoreWithForms):
Base class for the concepts in a dataset.
.. note::
-
+
Unlike senses in a wordlist, which are dataset-specific, concepts in a
wordlist are defined for all datasets. As a result, they lack a
reference to the original dataset in which they occur, but they have an
@@ -140,32 +143,29 @@ class Concept(CLCoreWithForms):
concepticon_gloss = attr.ib(default=None)
@classmethod
- def from_sense(
- cls, concept, id=None, name=None, wordlist=None, forms=None,
- senses=None):
+ def from_sense(cls, concept, id=None, name=None, forms=None, senses=None):
return cls(
- name=name,
- id=id,
- concepticon_id=concept.data.get("Concepticon_ID", ""),
- concepticon_gloss=concept.data.get("Concepticon_Gloss", ""),
- forms=forms,
- senses=senses
- )
+ name=name,
+ id=id,
+ concepticon_id=concept.data.get("Concepticon_ID", ""),
+ concepticon_gloss=concept.data.get("Concepticon_Gloss", ""),
+ forms=forms,
+ senses=senses
+ )
@classmethod
- def from_concept(cls, concept, language, forms=None,
- senses=None, wordlist=None, dataset=None):
+ def from_concept(cls, concept, forms=None, senses=None):
return cls(
- id=concept.id,
- name=concept.name,
- concepticon_id=concept.concepticon_id,
- concepticon_gloss=concept.concepticon_gloss,
- senses=senses,
- forms=forms,
- )
+ id=concept.id,
+ name=concept.name,
+ concepticon_id=concept.concepticon_id,
+ concepticon_gloss=concept.concepticon_gloss,
+ senses=senses,
+ forms=forms,
+ )
def __repr__(self):
- return "<Concept "+ self.name+">"
+ return "<Concept " + self.name + ">"
@attr.s(repr=False)
@@ -177,9 +177,7 @@ class Form(CLBase):
:param language: The language in which the form occurs.
:param sense: The meaning expressed by the form.
:param tokens: The segmented strings defined by the B(road) IPA.
-
"""
-
concept = attr.ib(default=None, repr=False)
language = attr.ib(default=None, repr=False)
sense = attr.ib(default=None, repr=False)
@@ -198,16 +196,15 @@ def sounds(self):
@property
def graphemes(self):
if self.segments:
- return [self.wordlist.graphemes[self.dataset+'-'+s] for s in
+ return [self.wordlist.graphemes[self.dataset + '-' + s] for s in
self.segments]
def __repr__(self):
- return "<"+self.__class__.__name__+" "+self.form+">"
+ return "<" + self.__class__.__name__ + " " + self.form + ">"
@attr.s(repr=False)
class Cognate(CLBase):
-
form = attr.ib(default=None, repr=False)
contribution = attr.ib(default=None, repr=False)
@@ -220,7 +217,7 @@ class Grapheme(CLBaseWithForms):
def __str__(self):
return self.grapheme
-
+
@attr.s(repr=False, eq=False)
class Sound(CLCoreWithForms):
@@ -238,17 +235,18 @@ class Sound(CLCoreWithForms):
featureset = NestedAttribute("obj", "featureset")
@classmethod
- def from_grapheme(cls, grapheme_, grapheme=None, occs=None, forms=None,
+ def from_grapheme(
+ cls, grapheme_, grapheme=None, occs=None, forms=None,
id=None, graphemes_in_source=None, obj=None):
return cls(
- id=id,
- grapheme=grapheme,
- wordlist=grapheme_.wordlist,
- occs=occs,
- data=obj.__dict__,
- graphemes_in_source=graphemes_in_source,
- forms=forms,
- obj=obj)
+ id=id,
+ grapheme=grapheme,
+ wordlist=grapheme_.wordlist,
+ occs=occs,
+ data=obj.__dict__,
+ graphemes_in_source=graphemes_in_source,
+ forms=forms,
+ obj=obj)
def __len__(self):
return len(self.occs or [])
@@ -262,10 +260,11 @@ def __eq__(self, other):
return False
def __repr__(self):
- return "<"+self.__class__.__name__+" "+self.grapheme+">"
+ return "<" + self.__class__.__name__ + " " + self.grapheme + ">"
def similarity(self, other):
- if self.type not in ["marker", "unknownsound"] and other.type not in ["marker", "unknownsound"]:
+ if self.type not in ["marker", "unknownsound"] and \
+ other.type not in ["marker", "unknownsound"]:
return self.obj.similarity(other.obj)
elif self.type in ["marker", "unknownsound"] and other.type in ["marker", "unknownsound"]:
if self == other:
@@ -276,23 +275,20 @@ def similarity(self, other):
@classmethod
def from_sound(cls, sound, language):
return cls(
- id=str(sound),
- language=language,
- data=sound.data,
- obj=sound.obj,
- wordlist=sound.wordlist,
- grapheme=sound.grapheme,
- occs=sound.occs[language.id]
- )
-
+ id=str(sound),
+ language=language,
+ data=sound.data,
+ obj=sound.obj,
+ wordlist=sound.wordlist,
+ grapheme=sound.grapheme,
+ occs=sound.occs[language.id],
+ )
class GetSubInventoryByType:
def __init__(self, types):
def select_sounds(inventory):
- return DictTuple(
- [v for v in inventory if v.type in types]
- )
+ return DictTuple([v for v in inventory if v.type in types])
self.select_sounds = select_sounds
def __get__(self, obj, objtype=None):
@@ -344,15 +340,13 @@ class Inventory:
@classmethod
def from_list(
- cls,
- *list_of_sounds,
- language=None,
- ts=None,
- wordlist=None,
- dataset=None
- ):
- ts = ts or CLTS().bipa
- sounds = OrderedDict()
+ cls,
+ ts: pyclts.TranscriptionSystem,
+ *list_of_sounds: typing.Union[CLTSSound, Symbol, str],
+ language=None,
+ wordlist=None,
+ ):
+ sounds = collections.OrderedDict()
for itm in list_of_sounds:
sound = ts[itm]
try:
@@ -366,7 +360,7 @@ def from_list(
graphemes_in_source=[sound.grapheme],
occs=[],
data=sound.__dict__
- )
+ )
return cls(sounds=DictTuple(sounds.values()), ts=ts, language=language)
def __len__(self):
diff --git a/src/cltoolkit/wordlist.py b/src/cltoolkit/wordlist.py
index 02fd334..bdc4061 100644
--- a/src/cltoolkit/wordlist.py
+++ b/src/cltoolkit/wordlist.py
@@ -4,8 +4,7 @@
import importlib
import collections
-from cldfbench.dataset import dataset_from_module
-from pyclts import CLTS
+from pyclts import TranscriptionSystem
import lingpy
from tqdm import tqdm as progressbar
@@ -22,9 +21,12 @@ class Wordlist:
"""
A collection of one or more lexibank datasets, aligned by concept.
"""
- def __init__(self, datasets, ts=None, concept_id_factory=lambda x: x["Concepticon_Gloss"]):
+ def __init__(self,
+ datasets,
+ ts: TranscriptionSystem,
+ concept_id_factory=lambda x: x["Concepticon_Gloss"]):
self.datasets = DictTuple(datasets, key=lambda x: x.metadata_dict["rdf:ID"])
- self.ts = ts or CLTS().transcriptionsystem_dict['bipa']
+ self.ts = ts
self.concept_id_factory = concept_id_factory
# During data loading, we use flexible, mutable dicts.
@@ -79,9 +81,9 @@ def __init__(self, datasets, ts=None, concept_id_factory=lambda x: x["Conceptico
s.forms = DictTuple(s.forms.values())
@classmethod
- def from_lexibank(cls, datasets, **kw):
+ def from_lexibank(cls, datasets, ts: TranscriptionSystem, **kw):
dsets = [dataset_from_module(importlib.import_module('lexibank_' + ds)) for ds in datasets]
- return cls(dsets, **kw)
+ return cls(dsets, ts, **kw)
def _add_languages(self, dsid, dataset):
"""Append languages to the wordlist.
@@ -115,7 +117,6 @@ def _add_senses(self, dsid, dataset):
new_sense,
id=concept_id,
name=concept_id.lower(),
- wordlist=self,
forms=collections.OrderedDict(),
senses=collections.OrderedDict(),
)
@@ -156,7 +157,7 @@ def _add_forms(self, dsid, dataset):
id=gid,
grapheme=segment,
dataset=dsid,
- wordlist=self,
+ wordlist=self,
obj=sound,
occs=collections.OrderedDict(),
forms=collections.OrderedDict([(new_form.id, new_form)]))
@@ -185,10 +186,7 @@ def _add_forms(self, dsid, dataset):
if cid and cid not in self.languages[lid].concepts:
self.languages[lid].concepts[cid] = Concept.from_concept(
self.concepts[cid],
- self.languages[lid],
senses=collections.OrderedDict(),
- wordlist=self,
- dataset=dsid,
forms=collections.OrderedDict(),
)
@@ -197,7 +195,7 @@ def _add_forms(self, dsid, dataset):
self.concepts[cid].forms[new_form.id] = new_form
if pid not in self.languages[lid].concepts[cid].senses:
self.languages[lid].concepts[cid].senses[pid] = self.senses[pid]
-
+
if pid not in self.languages[lid].senses:
self.languages[lid].senses[pid] = Sense.from_sense(
self.senses[pid], self.languages[lid], collections.OrderedDict())
@@ -207,7 +205,7 @@ def _add_forms(self, dsid, dataset):
def __len__(self):
return len(self.forms)
-
+
def load_cognates(self):
self.cognates = collections.OrderedDict()
for dsid, dataset in self.datasets.items():
@@ -221,21 +219,19 @@ def _add_cognates(self, dsid, dataset):
"""
for cog in progressbar(
dataset.objects("CognateTable"), desc="loading cognates for {0}".format(dsid)):
- contribution_id = getattr(
- cog.cldf, "contributionReference", "default")
# note that the cognateset Reference can be None, this needs to be
# caught up here
if cog.cldf.cognatesetReference:
form_id = idjoin(dsid, cog.cldf.formReference)
cogset = Cognate(
- id=idjoin(dsid, cog.cldf.cognatesetReference),
- wordlist=self,
- obj=cog.cldf,
- dataset=dsid,
- data=cog.data,
- form=self.forms[form_id],
- contribution=cog.data.get("contribution", "default")
- )
+ id=idjoin(dsid, cog.cldf.cognatesetReference),
+ wordlist=self,
+ obj=cog.cldf,
+ dataset=dsid,
+ data=cog.data,
+ form=self.forms[form_id],
+ contribution=cog.data.get("contribution", "default")
+ )
try:
self.forms[form_id].cognates[cogset.contribution] = cogset
except:
@@ -243,7 +239,6 @@ def _add_cognates(self, dsid, dataset):
self.cognates[cogset.id] = cogset
self.cognates = DictTuple(self.cognates.values())
-
def as_lingpy(
self,
language_filter=identity,
@@ -280,43 +275,43 @@ def as_lingpy(
return transform(D)
def iter_forms_by_concepts(
- self,
- concepts=None,
+ self,
+ concepts=None,
languages=None,
aspect=None,
filter_by=None,
flat=False,
- ):
+ ):
"""
Iterate over the concepts in the data and return forms for a given language.
:param concepts: List of concept identifiers, all concepts if not specified.
:param language: List of language identifiers, all languages if not specified.
:param aspect: Select attribute of the Form object instead of the Form object.
- :param filter_by: Use a function to filter the data to be output.
+ :param filter_by: Use a function to filter the data to be output.
:param flatten: Return a one-dimensional array of the data.
.. note::
The function returns for each concept (selected by ID) the form for
each language, or the specific aspect (attribute) of the form,
- provided this exists.
+ provided this exists.
"""
- flatten = identity if not flat else lambda x: [item for sublist in x
- for item in sublist]
+ flatten = identity if not flat else \
+ lambda x: [item for sublist in x for item in sublist]
transform = identity if not aspect else lambda x: getattr(x, aspect)
concepts = [self.concepts[c] for c in concepts] if concepts else self.concepts
- languages = [self.languages[l] for l in languages] if languages else self.languages
+ languages = [self.languages[i] for i in languages] if languages else self.languages
for concept in concepts:
out = []
for language in languages:
try:
out.append(
- list(filter(
- filter_by,
- [transform(f) for f in language.concepts[concept.id].forms]
- )))
+ list(filter(
+ filter_by,
+ [transform(f) for f in language.concepts[concept.id].forms]
+ )))
except KeyError:
out.append([])
if any(out):
| diff --git a/tests/test_features_collection.py b/tests/test_features_collection.py
index c12eea0..4829ffa 100644
--- a/tests/test_features_collection.py
+++ b/tests/test_features_collection.py
@@ -3,8 +3,8 @@
from cltoolkit.features.collection import FeatureCollection, feature_data
-def test_FeatureCollection(ds_carvalhopurus):
- wl = Wordlist([ds_carvalhopurus])
+def test_FeatureCollection(ds_carvalhopurus, clts):
+ wl = Wordlist([ds_carvalhopurus], clts.bipa)
c = FeatureCollection.from_metadata(pkg_path / 'features' / 'features.json')
_ = c('ConsonantQualitySize', wl.languages['carvalhopurus-Apurina'])
assert repr(FeatureCollection.from_data(feature_data()).features['ConsonantQualitySize'])
diff --git a/tests/test_models.py b/tests/test_models.py
index d80c149..136355f 100644
--- a/tests/test_models.py
+++ b/tests/test_models.py
@@ -7,7 +7,7 @@
def test_core_models(clts, ds_dummy):
datasets = [ds_dummy]
- wl = Wordlist(datasets)
+ wl = Wordlist(datasets, clts.bipa)
clc = CLCore(id="a", wordlist=wl, data={})
assert clc.__repr__() == "<CLCore a>"
@@ -31,7 +31,7 @@ def test_core_models(clts, ds_dummy):
id="dummy-Anyi", wordlist=wl, data=wl.languages[0].data, senses=[],
concepts=[], forms=[wl.forms[0], wl.forms[1]])
- inv = Inventory.from_list(*[s for s in
+ inv = Inventory.from_list(clts.bipa, *[s for s in
wl.forms[0].segments]+[s for s in wl.forms[1].segments])
assert len(lng.sound_inventory) == len(inv)
assert wl.senses[0].__repr__() == "<Sense dummy-all>"
@@ -69,24 +69,24 @@ def test_core_models(clts, ds_dummy):
assert str(form.graphemes[0]) == str(form.sounds[0])
-def test_inventory():
- invA = Inventory.from_list("a", "u", "p", "k")
- invB = Inventory.from_list("a", "u", "b", "g")
- invC = Inventory.from_list("aː", "a", "u:", "b")
+def test_inventory(clts):
+ invA = Inventory.from_list(clts.bipa, "a", "u", "p", "k")
+ invB = Inventory.from_list(clts.bipa, "a", "u", "b", "g")
+ invC = Inventory.from_list(clts.bipa, "aː", "a", "u:", "b")
assert len(invC.vowels_by_quality) == 2
assert round(invA.strict_similarity(invB), 2) == 0.33
assert invA.strict_similarity(invB, aspects=["vowels"]) == 1
assert invA.approximate_similarity(invB) > 0.33
- assert Inventory.from_list("A", "u").approximate_similarity(invB) > 0.1
+ assert Inventory.from_list(clts.bipa, "A", "u").approximate_similarity(invB) > 0.1
assert invA.sounds['a'].__eq__(invB.sounds['a']) == True
- assert Inventory.from_list().strict_similarity(Inventory.from_list()) == 0
- assert Inventory.from_list().approximate_similarity(Inventory.from_list()) == 0
- assert Inventory.from_list("p", "t", "k", "a", "e", "u").approximate_similarity(
- Inventory.from_list("a", "e", "u"), aspects=["consonants",
+ assert Inventory.from_list(clts.bipa).strict_similarity(Inventory.from_list(clts.bipa)) == 0
+ assert Inventory.from_list(clts.bipa).approximate_similarity(Inventory.from_list(clts.bipa)) == 0
+ assert Inventory.from_list(clts.bipa, "p", "t", "k", "a", "e", "u").approximate_similarity(
+ Inventory.from_list(clts.bipa, "a", "e", "u"), aspects=["consonants",
"vowels"]) == 0.5
- assert Inventory.from_list("p", "t", "k", ).approximate_similarity(
- Inventory.from_list("a", "e", "u"), aspects=["consonants",
+ assert Inventory.from_list(clts.bipa, "p", "t", "k", ).approximate_similarity(
+ Inventory.from_list(clts.bipa, "a", "e", "u"), aspects=["consonants",
"vowels"]) == 0.0
for sound in invA:
diff --git a/tests/test_wordlist.py b/tests/test_wordlist.py
index 1256c36..acaa79d 100644
--- a/tests/test_wordlist.py
+++ b/tests/test_wordlist.py
@@ -4,14 +4,14 @@
from cltoolkit.util import lingpy_columns
-def test_Wordlist(repos, ds_carvalhopurus, ds_wangbcd):
+def test_Wordlist(repos, ds_carvalhopurus, ds_wangbcd, clts):
# for lexibank load testing
datasets = [ds_carvalhopurus, ds_wangbcd]
with sys_path(repos / "carvalhopurus"):
with sys_path(repos / "wangbcd"):
- wl2 = Wordlist.from_lexibank(["carvalhopurus", "wangbcd"])
- wl = Wordlist(datasets)
+ wl2 = Wordlist.from_lexibank(["carvalhopurus", "wangbcd"], clts.bipa)
+ wl = Wordlist(datasets, clts.bipa)
assert wl2.height == wl.height
@@ -50,7 +50,7 @@ def test_Wordlist(repos, ds_carvalhopurus, ds_wangbcd):
assert wl.coverage(aspect="segmented_forms")[apurina.id] == len(apurina.concepts)
- wl = Wordlist(datasets=[datasets[0]])
+ wl = Wordlist([datasets[0]], clts.bipa)
wl.load_cognates()
lpwl = wl.as_lingpy(columns=lingpy_columns(cognates="default"))
assert "cognacy" in lpwl.columns
| Catalogs must be passed into functions and classes
Acquiring a catalog as done here
https://github.com/cldf/cltoolkit/blob/3f70bea96f8de4efd0707dd018f0a2e47644c785/src/cltoolkit/wordlist.py#L27
is not ok. Instead, either an initialized `CLTS` object or the path to the proper checkout of a catalog must be passed in by the calling code (and eventually from the command line).
| I think even fallbacks such as here
https://github.com/cldf/cltoolkit/blob/3f70bea96f8de4efd0707dd018f0a2e47644c785/src/cltoolkit/models.py#L354
are dangerous - i.e. may lead to non-reproducible behaviour across different machines.
Would
```python
ts = CLTS(Config.from_file().get_clone('clts'))
```
be okay? And one sets a keyword `clts_path=None`, and if this is None, one goes via catconfig, otehrwise via the user-path?
No, because that would require checking out appropriate versions before calling the code.
That's one of the core functionalities of `cldfbench`, I think: Consistent access to catalog versions.
So what should one do then? Not from the perspective of a CLI, where
paths etc. are passed by commandline, but from a user who wants to
quickly check data with CLTS?
If it is a user who knows python and is familiar with where the system will look up catalog data, expecting them to pass in `CLTS(...).bipa` to `Inventory.from_list` doesn't seem to bad.
Or to `Wordlist=(datasets=[...], ts=CLTS().bipa)`, if it was me having configured my CLTS with catconfig?
I think it makes the code a lot more transparent, if it is clear that the `Inventory` class (or `Wordlist`) needs a `pyclts.TranscriptionSystem` to do its job. And the way to make this clear is via required, positional parameters. The convenience of optional parameters and the system trying implicitly to grab a TranscriptionSystem from somewhere is too dangerous from my POV.
Just fixed this (locally) for Inventory. Will do for Wordlist now, and then submit a PR.
I am fine with that solution. I was worried that it would imply that it works in the end only inside CLI applications, in which case it would miss the main purpose that we started with cltoolkit: to make it easier to develop new methods to analyze cldf data and integrate them with existing packages like lingpy.
And I have to admit: given issues we had with lexibank applications by not so experienced Python users, where it turned out the problem was just that the CLTS path was wrongly specified, shows that it is really important to make these things explicit. | 2021-07-14T15:34:09.000 | -1.0 | [
"tests/test_models.py::test_core_models",
"tests/test_models.py::test_inventory",
"tests/test_wordlist.py::test_Wordlist"
] | [
"tests/test_features_collection.py::test_FeatureCollection"
] |
equinor/cwrap | 39 | equinor__cwrap-39 | ['30'] | 2508302d089ff5733da3d3241ed49c17e9ceb33f | diff --git a/cwrap/prototype.py b/cwrap/prototype.py
index 67340f6..2637faa 100644
--- a/cwrap/prototype.py
+++ b/cwrap/prototype.py
@@ -223,7 +223,8 @@ def __call__(self, *args):
# ArgumentError.message will look like this
# `argument 4: <type 'exceptions.TypeError'>: wrong type`
# The only useful information here is the index of the argument
- tokens = re.split("[ :]", err.message)
+ errMsg = err.message if hasattr(err, "message") else str(err)
+ tokens = re.split("[ :]", errMsg)
argidx = int(tokens[1]) - 1 # it starts from 1
raise TypeError((
"Argument {argidx}: cannot create a {argtype} from the given "
@@ -233,7 +234,7 @@ def __call__(self, *args):
actval=repr(args[argidx]),
acttype=type(args[argidx]),
)
- )
+ ) from err
def __get__(self, instance, owner):
if not self._resolved:
| diff --git a/tests/test_libc.py b/tests/test_libc.py
index b91b0e0..153be16 100644
--- a/tests/test_libc.py
+++ b/tests/test_libc.py
@@ -55,3 +55,6 @@ def test_libc(self):
with self.assertRaises(NotImplementedError):
lib._missing_function(100)
+
+ with self.assertRaises(TypeError):
+ self.assertEqual(lib.abs("SPAM"), 3)
| ArgumentError has no message attribute
On python 3.6 https://github.com/equinor/cwrap/blob/f5cd74913d7e77a5fe14fea11190e8e61057b37e/cwrap/prototype.py#L226 will cause an `AttributeError: ArgumentError object has no attribute 'message'.`
| still hitting this as `another exception occured...` - i'm sorry, how was this completed? is this will not fix?
and after experimenting with a fix locally, i can see that it actually stops me from getting a meaningful error message. reopening. | 2022-08-31T19:34:06.000 | -1.0 | [
"tests/test_libc.py::LibCTest::test_libc"
] | [] |
bcgsc/pori_graphkb_python | 40 | bcgsc__pori_graphkb_python-40 | ['39'] | 6ebf0d5bc9f201ed0572d3c984b4380f621bb0e8 | diff --git a/graphkb/statement.py b/graphkb/statement.py
index 72dbd41..70fe87c 100644
--- a/graphkb/statement.py
+++ b/graphkb/statement.py
@@ -1,7 +1,7 @@
from . import GraphKBConnection
-from .vocab import get_terms_set
from .constants import RELEVANCE_BASE_TERMS
from .types import CategoryBaseTermMapping
+from .vocab import get_terms_set
def categorize_relevance(
diff --git a/graphkb/util.py b/graphkb/util.py
index 02f7d6a..78349f0 100644
--- a/graphkb/util.py
+++ b/graphkb/util.py
@@ -43,7 +43,13 @@ def convert_to_rid_list(records: Iterable[Record]) -> List[str]:
"""
Given a list of records, return their record IDs
"""
- return [record['@rid'] for record in records]
+ result = []
+ for record in records:
+ try:
+ result.append(record['@rid'])
+ except TypeError:
+ result.append(record)
+ return result
class FeatureNotFoundError(Exception):
diff --git a/graphkb/vocab.py b/graphkb/vocab.py
index 7196da1..1e0199e 100644
--- a/graphkb/vocab.py
+++ b/graphkb/vocab.py
@@ -1,16 +1,24 @@
-from typing import List, cast, Iterable, Set
+from typing import Callable, Dict, Iterable, List, Set, cast
from . import GraphKBConnection
from .types import Ontology
from .util import convert_to_rid_list
+def query_by_name(ontology_class: str, base_term_name: str) -> Dict:
+ return {
+ 'target': ontology_class,
+ 'filters': {'name': base_term_name},
+ }
+
+
def get_equivalent_terms(
conn: GraphKBConnection,
base_term_name: str,
root_exclude_term: str = '',
ontology_class: str = 'Vocabulary',
ignore_cache: bool = False,
+ build_base_query: Callable = query_by_name,
) -> List[Ontology]:
"""
Get a list of terms equivalent to the current term up to the root term
@@ -19,15 +27,14 @@ def get_equivalent_terms(
base_term_name: the name to get superclasses of
root_exclude_term: the parent term to exlcude along with all of its parent terms
"""
+ base_records = convert_to_rid_list(conn.query(build_base_query(ontology_class, base_term_name)))
+ if not base_records:
+ return []
base_term_parents = cast(
List[Ontology],
conn.query(
{
- 'target': {
- 'target': ontology_class,
- 'queryType': 'descendants',
- 'filters': {'name': base_term_name},
- },
+ 'target': {'target': base_records, 'queryType': 'descendants'},
'queryType': 'similarTo',
'treeEdges': [],
'returnProperties': ['sourceId', 'sourceIdVersion', 'deprecated', 'name', '@rid'],
@@ -36,14 +43,19 @@ def get_equivalent_terms(
),
)
if root_exclude_term:
+ root_records = convert_to_rid_list(
+ conn.query(build_base_query(ontology_class, root_exclude_term))
+ )
+ if not root_records:
+ return base_term_parents
+
exclude = set(
convert_to_rid_list(
conn.query(
{
'target': {
- 'target': ontology_class,
+ 'target': root_records,
'queryType': 'descendants',
- 'filters': {'name': root_exclude_term},
},
'queryType': 'similarTo',
'treeEdges': [],
@@ -70,6 +82,7 @@ def get_term_tree(
ontology_class: str = 'Vocabulary',
include_superclasses: bool = True,
ignore_cache: bool = False,
+ build_base_query: Callable = query_by_name,
) -> List[Ontology]:
"""
Get terms equivalent to the base term by traversing the subclassOf tree and expanding related
@@ -87,14 +100,16 @@ def get_term_tree(
Note: this must be done in 2 calls to avoid going up and down the tree in a single query (exclude adjacent siblings)
"""
# get all child terms of the subclass tree and disambiguate them
+ base_records = convert_to_rid_list(conn.query(build_base_query(ontology_class, base_term_name)))
+ if not base_records:
+ return []
child_terms = cast(
List[Ontology],
conn.query(
{
'target': {
- 'target': ontology_class,
+ 'target': base_records,
'queryType': 'ancestors',
- 'filters': {'name': base_term_name},
},
'queryType': 'similarTo',
'treeEdges': [],
@@ -111,6 +126,7 @@ def get_term_tree(
root_exclude_term=root_exclude_term,
ontology_class=ontology_class,
ignore_cache=ignore_cache,
+ build_base_query=build_base_query,
)
else:
parent_terms = []
| diff --git a/tests/test_statement.py b/tests/test_statement.py
index 18ea234..abfb6af 100644
--- a/tests/test_statement.py
+++ b/tests/test_statement.py
@@ -1,6 +1,7 @@
-import pytest
from unittest.mock import Mock
+import pytest
+
from graphkb import statement
@@ -9,16 +10,21 @@ def graphkb_conn():
def make_rid_list(*values):
return [{'@rid': v} for v in values]
+ def term_tree_calls(*final_values):
+ # this function makes 2 calls to conn.query here
+ sets = [['fake'], final_values]
+ return [make_rid_list(*s) for s in sets]
+
return_values = [
- make_rid_list('1'), # cat1: therapeutic
- make_rid_list('2'),
- make_rid_list('3'), # cat2: diagnositic
- make_rid_list('2'),
- [], # cat3: prognostic
- [],
- [], # cat4: biological
- [],
+ *term_tree_calls('1'), # therapeutic
+ *term_tree_calls('2'), # therapeutic (2nd base term)
+ *term_tree_calls('3'), # diagnostic
+ *term_tree_calls(), # prognostic
+ *term_tree_calls(), # biological
+ *term_tree_calls(), # biological (2nd base term)
+ *term_tree_calls(), # biological (3rd base term)
]
+
query_mock = Mock()
query_mock.side_effect = return_values
conn = Mock(query=query_mock, cache={})
| Support Arbitrary base Queries
For most of the helper functions they query by name. It would be helpful to allow a function to be passed to build the base query instead which could use any arbitrary query to fetch the starting records. This would enable things like fetching a vocabulary tree based on its sourceId instead of its name
| 2021-07-16T17:52:42.000 | -1.0 | [
"tests/test_statement.py::TestCategorizeRelevance::test_first_match_returns",
"tests/test_statement.py::TestCategorizeRelevance::test_second_categoary"
] | [
"tests/test_statement.py::TestCategorizeRelevance::test_no_match",
"tests/test_statement.py::TestCategorizeRelevance::test_custom_categories",
"tests/test_statement.py::TestCategorizeRelevance::test_default_categories"
] |
|
dafnifacility/cli | 112 | dafnifacility__cli-112 | ['106'] | cb61df88e9400850eaa51e7d03ba773398bb3dda | diff --git a/dafni_cli/commands/download.py b/dafni_cli/commands/download.py
index 41dbd478..c314b3f0 100644
--- a/dafni_cli/commands/download.py
+++ b/dafni_cli/commands/download.py
@@ -5,7 +5,11 @@
from click import Context
from dafni_cli.api.session import DAFNISession
-from dafni_cli.commands.helpers import cli_get_latest_dataset_metadata
+from dafni_cli.commands.helpers import (
+ cli_get_latest_dataset_metadata,
+ cli_select_dataset_files,
+)
+from dafni_cli.commands.options import click_optional_tuple_none_callback
from dafni_cli.datasets.dataset_download import download_dataset
from dafni_cli.datasets.dataset_metadata import parse_dataset_metadata
@@ -29,11 +33,19 @@ def download(ctx: Context):
help="Directory to save the zipped Dataset files to. Default is the current working directory",
)
@click.argument("version-id", nargs=1, required=True, type=str)
[email protected](
+ "files",
+ nargs=-1,
+ required=False,
+ type=str,
+ callback=click_optional_tuple_none_callback,
+)
@click.pass_context
def dataset(
ctx: Context,
version_id: List[str],
directory: Optional[Path],
+ files: Optional[List[str]],
):
"""Download all files associated with the given Dataset Version.
@@ -42,13 +54,19 @@ def dataset(
version_id (str): Dataset version ID
directory (Optional[Path]): Directory to download files to (when None
will use the current working directory)
+ files (Optional[List[str]]): List of specific files to download (allows
+ glob-like wildcards)
"""
metadata = parse_dataset_metadata(
cli_get_latest_dataset_metadata(ctx.obj["session"], version_id)
)
if len(metadata.files) > 0:
- download_dataset(ctx.obj["session"], metadata.files, directory)
+ selected_files = cli_select_dataset_files(metadata, files=files)
+ if len(selected_files) > 0:
+ download_dataset(ctx.obj["session"], selected_files, directory)
+ else:
+ click.echo("No files selected to download")
else:
click.echo(
"There are no files currently associated with the Dataset to download"
diff --git a/dafni_cli/commands/helpers.py b/dafni_cli/commands/helpers.py
index 0f985a5d..31ec3ee9 100644
--- a/dafni_cli/commands/helpers.py
+++ b/dafni_cli/commands/helpers.py
@@ -1,4 +1,5 @@
-from typing import Tuple
+import fnmatch
+from typing import List, Optional, Tuple
import click
@@ -7,6 +8,7 @@
from dafni_cli.api.models_api import get_model
from dafni_cli.api.session import DAFNISession
from dafni_cli.api.workflows_api import get_workflow, get_workflow_instance
+from dafni_cli.datasets.dataset_metadata import DataFile, DatasetMetadata
from dafni_cli.workflows.parameter_set import WorkflowParameterSet
from dafni_cli.workflows.workflow import Workflow, parse_workflow
@@ -43,6 +45,32 @@ def cli_get_latest_dataset_metadata(session: DAFNISession, version_id: str) -> d
raise SystemExit(1) from err
+def cli_select_dataset_files(
+ dataset_metadata: DatasetMetadata,
+ files: Optional[List[str]],
+) -> List[DataFile]:
+ """Returns a list of DataFile's that have file names that match the given
+ 'files' using glob-like matching
+
+ Args:
+ files (Optional[List[str]]): List of specific file names to match.
+ When None returns all the files.
+ """
+
+ if files is None:
+ return dataset_metadata.files
+
+ selected_files = []
+ for file in dataset_metadata.files:
+ # Check if any one of the supplied file names matches
+ for file_name in files:
+ if fnmatch.fnmatch(file.name, file_name):
+ selected_files.append(file)
+ break
+
+ return selected_files
+
+
def cli_get_workflow(session: DAFNISession, version_id: str) -> dict:
"""Attempts to get a workflow from a version id with a nice CLI error
message if it's not found
diff --git a/dafni_cli/commands/options.py b/dafni_cli/commands/options.py
index 5f1fa99c..ab9384d9 100644
--- a/dafni_cli/commands/options.py
+++ b/dafni_cli/commands/options.py
@@ -38,6 +38,15 @@ def convert(self, value, param, ctx):
self.fail(f"'{value}' is not a valid URL")
+def click_optional_tuple_none_callback(ctx, param, value):
+ """By default click returns an empty tuple instead of None for options with
+ multiple=True, this ensures None is returned instead for consistency
+
+ To use supply callback=click_optional_tuple_none_callback to click.option
+ """
+ return None if len(value) == 0 else value
+
+
class EmailAddressParamType(click.ParamType):
"""Email address parameter type for Click that checks if a string is a
valid email address"""
@@ -90,18 +99,16 @@ def dataset_metadata_common_options(all_optional: bool):
version_message (str): Version message
"""
- # By default click returns an empty tuple instead of None for options with
- # multiple=True, override here for consistency
- def default_none(ctx, _, value):
- return None if len(value) == 0 else value
-
# Arguments that will be used to indicate something as required
# Will use the default required = False and have a default of None in the
# case all_optional is True
required_args = {"required": True}
if all_optional:
required_args = {"default": None}
- required_args_tuple = {**required_args, "callback": default_none}
+ required_args_tuple = {
+ **required_args,
+ "callback": click_optional_tuple_none_callback,
+ }
def decorator(function):
function = click.option(
@@ -119,7 +126,7 @@ def decorator(function):
function = click.option(
"--identifier",
type=str,
- callback=default_none,
+ callback=click_optional_tuple_none_callback,
multiple=True,
help="Permanent URL of external identifier for this dataset (e.g. DOI). (Can have multiple)",
)(function)
@@ -132,7 +139,7 @@ def decorator(function):
function = click.option(
"--theme",
type=click.Choice(DATASET_METADATA_THEMES),
- callback=default_none,
+ callback=click_optional_tuple_none_callback,
multiple=True,
help="Theme, one of those found at https://inspire.ec.europa.eu/Themes/Data-Specifications/2892. Can have multiple.",
)(function)
@@ -176,7 +183,7 @@ def decorator(function):
function = click.option(
"--person",
type=(str, URLParamType(optional=True)),
- callback=default_none,
+ callback=click_optional_tuple_none_callback,
multiple=True,
help='Name and ID of a person who created the dataset. Either value may be empty using "". When given the ID must be a valid URL, and can be an ORCID id or similar. (Can have multiple)',
)(function)
diff --git a/docs/dafni_cli.md b/docs/dafni_cli.md
index 80f1325f..981b67d0 100644
--- a/docs/dafni_cli.md
+++ b/docs/dafni_cli.md
@@ -184,6 +184,22 @@ You may download all the files of a dataset using its version id via the command
dafni download dataset <version-id>
```
+You may also select specific files by using their names e.g.
+
+```bash
+dafni download dataset <version-id> file1.csv file2.zip
+```
+
+As with the dataset upload you may also use wildcards. For example
+
+```bash
+dafni download dataset <version-id> "*.csv"
+```
+
+will download all `.csv` files in the dataset.
+
+> **_NOTE:_** You should use quotation marks, `""`, here to avoid any confusion with local files that may be in your current directory.
+
### Deleting entities
You may delete entities on the platform using one of the `dafni delete` commands. All of these will take an existing version id for a dataset, model or workflow and will display a brief summary with a confirmation prompt prior to actual deletion. e.g.
@@ -205,7 +221,7 @@ There are two options for datasets. You may either delete an entire dataset with
dafni delete dataset <version-id>
```
-> **_NOTE_** This still takes a version id. It doesn't matter which is given in this case as it will delete the associated parent dataset
+> **_NOTE:_** This still takes a version id. It doesn't matter which is given in this case as it will delete the associated parent dataset
or just a version with
| diff --git a/dafni_cli/tests/commands/test_download.py b/dafni_cli/tests/commands/test_download.py
index f3158994..efed6658 100644
--- a/dafni_cli/tests/commands/test_download.py
+++ b/dafni_cli/tests/commands/test_download.py
@@ -1,4 +1,5 @@
from pathlib import Path
+from typing import List, Optional
from unittest import TestCase
from unittest.mock import MagicMock, patch
@@ -30,55 +31,93 @@ def test_session_retrieved_and_set_on_context(self, _, mock_DAFNISession):
self.assertEqual(result.exit_code, 0)
-@patch("dafni_cli.commands.download.DAFNISession")
-@patch("dafni_cli.commands.download.cli_get_latest_dataset_metadata")
-@patch("dafni_cli.commands.download.parse_dataset_metadata")
-@patch("dafni_cli.commands.download.download_dataset")
class TestDownloadDataset(TestCase):
"""Test class to test the download dataset command"""
- def test_download_dataset(
- self,
- mock_download_dataset,
- mock_parse_dataset_metadata,
- mock_cli_get_latest_dataset_metadata,
- mock_DAFNISession,
- ):
- """Tests that the 'download dataset' command works correctly (with no
- optional arguments)"""
- # SETUP
- session = MagicMock()
- mock_DAFNISession.return_value = session
- runner = CliRunner()
-
- version_id = "version-id"
+ def setUp(self) -> None:
+ super().setUp()
+
+ self.mock_DAFNISession = patch(
+ "dafni_cli.commands.download.DAFNISession"
+ ).start()
+ self.mock_cli_get_latest_dataset_metadata = patch(
+ "dafni_cli.commands.download.cli_get_latest_dataset_metadata"
+ ).start()
+ self.mock_cli_select_dataset_files = patch(
+ "dafni_cli.commands.download.cli_select_dataset_files"
+ ).start()
+ self.mock_parse_dataset_metadata = patch(
+ "dafni_cli.commands.download.parse_dataset_metadata"
+ ).start()
+ self.mock_download_dataset = patch(
+ "dafni_cli.commands.download.download_dataset"
+ ).start()
+
+ self.mock_session = MagicMock()
+ self.mock_DAFNISession.return_value = self.mock_session
+
+ # Mock metadata and files
+ self.version_id = "version-id"
file_names = ["file_name1", "file_name2"]
file_contents = ["file_contents1", "file_contents2"]
- metadata = MagicMock()
- metadata.dataset_id = "dataset-id"
- metadata.files = [MagicMock(), MagicMock()]
- metadata.download_dataset_files = MagicMock()
- metadata.download_dataset_files.return_value = (
+ self.metadata = MagicMock()
+ self.metadata.dataset_id = "dataset-id"
+ self.metadata.files = [MagicMock(), MagicMock()]
+ self.metadata.download_dataset_files = MagicMock()
+ self.metadata.download_dataset_files.return_value = (
file_names,
file_contents,
)
- mock_parse_dataset_metadata.return_value = metadata
+ self.selected_dataset_files = [MagicMock() for file in self.metadata.files]
+ self.mock_parse_dataset_metadata.return_value = self.metadata
+ self.mock_cli_select_dataset_files.return_value = self.selected_dataset_files
+
+ self.addCleanup(patch.stopall)
+
+ def _run_command(
+ self,
+ directory: Optional[str],
+ files: Optional[List[str]],
+ ):
+ """Executes the 'download dataset' command and returns the result"""
+ runner = CliRunner()
+
+ with runner.isolated_filesystem():
+ args = ["dataset", self.version_id]
+ if directory:
+ args.extend(["--directory", directory])
+ Path(directory).mkdir()
+ if files:
+ args.extend([file_name for file_name in files])
+
+ result = runner.invoke(download.download, args)
+
+ return result
+
+ def test_download_dataset(
+ self,
+ ):
+ """Tests that the 'download dataset' command works correctly (with no
+ optional arguments)"""
# CALL
- result = runner.invoke(download.download, ["dataset", version_id])
+ result = self._run_command(directory=None, files=None)
# ASSERT
- mock_DAFNISession.assert_called_once()
- mock_cli_get_latest_dataset_metadata.assert_called_once_with(
- session, version_id
+ self.mock_DAFNISession.assert_called_once()
+ self.mock_cli_get_latest_dataset_metadata.assert_called_once_with(
+ self.mock_session, self.version_id
+ )
+ self.mock_parse_dataset_metadata.assert_called_once_with(
+ self.mock_cli_get_latest_dataset_metadata.return_value
)
- mock_parse_dataset_metadata.assert_called_once_with(
- mock_cli_get_latest_dataset_metadata.return_value
+ self.mock_cli_select_dataset_files.assert_called_once_with(
+ self.metadata, files=None
)
- mock_download_dataset.assert_called_once_with(
- session,
- metadata.files,
+ self.mock_download_dataset.assert_called_once_with(
+ self.mock_session,
+ self.selected_dataset_files,
None,
)
@@ -86,53 +125,31 @@ def test_download_dataset(
def test_download_dataset_with_specific_directory(
self,
- mock_download_dataset,
- mock_parse_dataset_metadata,
- mock_cli_get_latest_dataset_metadata,
- mock_DAFNISession,
):
"""Tests that the 'download dataset' command works correctly with a
specific directory specified"""
- # SETUP
- session = MagicMock()
- mock_DAFNISession.return_value = session
- runner = CliRunner()
- version_id = "version-id"
- file_names = ["file_name1", "file_name2"]
- file_contents = [b"file_contents1", b"file_contents2"]
+ # SETUP
directory = "some_folder"
- metadata = MagicMock()
- metadata.dataset_id = "dataset-id"
- metadata.files = [MagicMock(), MagicMock()]
- metadata.download_dataset_files = MagicMock()
- metadata.download_dataset_files.return_value = (
- file_names,
- file_contents,
- )
- mock_parse_dataset_metadata.return_value = metadata
# CALL
- with runner.isolated_filesystem():
- Path(directory).mkdir()
-
- result = runner.invoke(
- download.download,
- ["dataset", version_id, "--directory", directory],
- )
+ result = self._run_command(directory=directory, files=None)
# ASSERT
- mock_DAFNISession.assert_called_once()
- mock_cli_get_latest_dataset_metadata.assert_called_once_with(
- session, version_id
+ self.mock_DAFNISession.assert_called_once()
+ self.mock_cli_get_latest_dataset_metadata.assert_called_once_with(
+ self.mock_session, self.version_id
)
- mock_parse_dataset_metadata.assert_called_once_with(
- mock_cli_get_latest_dataset_metadata.return_value
+ self.mock_parse_dataset_metadata.assert_called_once_with(
+ self.mock_cli_get_latest_dataset_metadata.return_value
+ )
+ self.mock_cli_select_dataset_files.assert_called_once_with(
+ self.metadata, files=None
)
- mock_download_dataset.assert_called_once_with(
- session,
- metadata.files,
+ self.mock_download_dataset.assert_called_once_with(
+ self.mock_session,
+ self.selected_dataset_files,
Path(directory),
)
@@ -140,34 +157,26 @@ def test_download_dataset_with_specific_directory(
def test_download_dataset_with_no_files(
self,
- mock_download_dataset,
- mock_parse_dataset_metadata,
- mock_cli_get_latest_dataset_metadata,
- mock_DAFNISession,
):
"""Tests that the 'download dataset' command works correctly when
there are no files to download"""
+
# SETUP
- session = MagicMock()
- mock_DAFNISession.return_value = session
- runner = CliRunner()
- metadata = MagicMock()
- metadata.dataset_id = "dataset-id"
- metadata.files = []
- mock_parse_dataset_metadata.return_value = metadata
+ self.metadata.files = []
# CALL
- result = runner.invoke(download.download, ["dataset", "version-id"])
+ result = self._run_command(directory=None, files=None)
# ASSERT
- mock_DAFNISession.assert_called_once()
- mock_cli_get_latest_dataset_metadata.assert_called_once_with(
- session, "version-id"
+ self.mock_DAFNISession.assert_called_once()
+ self.mock_cli_get_latest_dataset_metadata.assert_called_once_with(
+ self.mock_session, self.version_id
)
- mock_parse_dataset_metadata.assert_called_once_with(
- mock_cli_get_latest_dataset_metadata.return_value
+ self.mock_parse_dataset_metadata.assert_called_once_with(
+ self.mock_cli_get_latest_dataset_metadata.return_value
)
- mock_download_dataset.assert_not_called()
+ self.mock_cli_select_dataset_files.assert_not_called()
+ self.mock_download_dataset.assert_not_called()
self.assertEqual(
result.output,
@@ -175,3 +184,67 @@ def test_download_dataset_with_no_files(
)
self.assertEqual(result.exit_code, 0)
+
+ def test_download_dataset_with_specific_files_given(
+ self,
+ ):
+ """Tests that the 'download dataset' command works correctly (when given
+ a list of files match to)"""
+
+ # CALL
+ files = ["filename1.zip", "filename2.zip", "*.csv"]
+ result = self._run_command(directory=None, files=files)
+
+ # ASSERT
+ self.mock_DAFNISession.assert_called_once()
+ self.mock_cli_get_latest_dataset_metadata.assert_called_once_with(
+ self.mock_session, self.version_id
+ )
+ self.mock_parse_dataset_metadata.assert_called_once_with(
+ self.mock_cli_get_latest_dataset_metadata.return_value
+ )
+ self.mock_cli_select_dataset_files.assert_called_once_with(
+ self.metadata, files=tuple(files)
+ )
+
+ self.mock_download_dataset.assert_called_once_with(
+ self.mock_session,
+ self.selected_dataset_files,
+ None,
+ )
+
+ self.assertEqual(result.exit_code, 0)
+
+ def test_download_dataset_with_no_selected_files(
+ self,
+ ):
+ """Tests that the 'download dataset' command works correctly when
+ there are no selected files to download"""
+
+ # SETUP
+ self.selected_dataset_files = []
+ self.mock_cli_select_dataset_files.return_value = self.selected_dataset_files
+
+ # CALL
+ files = ["filename1.zip", "filename2.zip", "*.csv"]
+ result = self._run_command(directory=None, files=files)
+
+ # ASSERT
+ self.mock_DAFNISession.assert_called_once()
+ self.mock_cli_get_latest_dataset_metadata.assert_called_once_with(
+ self.mock_session, self.version_id
+ )
+ self.mock_parse_dataset_metadata.assert_called_once_with(
+ self.mock_cli_get_latest_dataset_metadata.return_value
+ )
+ self.mock_cli_select_dataset_files.assert_called_once_with(
+ self.metadata, files=tuple(files)
+ )
+ self.mock_download_dataset.assert_not_called()
+
+ self.assertEqual(
+ result.output,
+ "No files selected to download\n",
+ )
+
+ self.assertEqual(result.exit_code, 0)
diff --git a/dafni_cli/tests/commands/test_helpers.py b/dafni_cli/tests/commands/test_helpers.py
index f68a4cde..12295afd 100644
--- a/dafni_cli/tests/commands/test_helpers.py
+++ b/dafni_cli/tests/commands/test_helpers.py
@@ -1,8 +1,9 @@
from unittest import TestCase
-from unittest.mock import MagicMock, patch
+from unittest.mock import MagicMock, call, patch
from dafni_cli.api.exceptions import ResourceNotFoundError
from dafni_cli.commands import helpers
+from dafni_cli.datasets.dataset_metadata import DataFile
@patch("dafni_cli.commands.helpers.get_model")
@@ -89,6 +90,66 @@ def test_resource_not_found(self, mock_click, mock_get_latest_dataset_metadata):
self.assertEqual(err.exception.code, 1)
+class TestCliSelectDatasetFiles(TestCase):
+ """Test class to test cli_select_dataset_files"""
+
+ def setUp(self) -> None:
+ super().setUp()
+
+ self.file_names = ["file1.csv", "file2.zip", "file3.csv"]
+ self.dataset_metadata = MagicMock(
+ files=[DataFile(name=file_name, size=0) for file_name in self.file_names]
+ )
+
+ def test_all_optionals_none_returns_whole_list(self):
+ """Tests that the entire list of files is returned when the given list
+ of files is None"""
+ # CALL
+ result = helpers.cli_select_dataset_files(self.dataset_metadata, files=None)
+
+ # ASSERT
+ self.assertEqual(result, self.dataset_metadata.files)
+
+ def test_given_exact_file_names_selects_correct_files(self):
+ """Tests that only files found in the given list of files are returned"""
+ # CALL
+ result = helpers.cli_select_dataset_files(
+ self.dataset_metadata,
+ files=["file1.csv", "file2.zip"],
+ )
+
+ # ASSERT
+ self.assertEqual(
+ result, [self.dataset_metadata.files[0], self.dataset_metadata.files[1]]
+ )
+
+ def test_given_file_wildcard_selects_correct_files(self):
+ """Tests that only files with names matching the given glob-like file
+ name is returned when given"""
+ # CALL
+ result = helpers.cli_select_dataset_files(
+ self.dataset_metadata,
+ files=["*.csv"],
+ )
+
+ # ASSERT
+ self.assertEqual(
+ result, [self.dataset_metadata.files[0], self.dataset_metadata.files[2]]
+ )
+
+ def test_given_file_name_and_wildcard_selects_correct_files(self):
+ """Tests that only files with names found explicitly given or that match
+ the a separate glob-like filename are returned when both are given"""
+ # CALL
+ result = helpers.cli_select_dataset_files(
+ self.dataset_metadata,
+ files=["*.csv", "file2.zip"],
+ )
+
+ # ASSERT
+ self.assertEqual(result, self.dataset_metadata.files)
+
+
@patch("dafni_cli.commands.helpers.get_workflow")
@patch("dafni_cli.commands.helpers.click")
class TestCliGetWorkflow(TestCase):
diff --git a/dafni_cli/tests/test_utils.py b/dafni_cli/tests/test_utils.py
index 6e81fae4..2704a10f 100644
--- a/dafni_cli/tests/test_utils.py
+++ b/dafni_cli/tests/test_utils.py
@@ -1,7 +1,5 @@
-import tempfile
from dataclasses import dataclass
from datetime import datetime
-from io import BytesIO
from pathlib import Path
from typing import List, Optional
from unittest import TestCase
| option to download one file from a dataset
As I understand it, the download command in the CLI currently downloads all files in a dataset. I was wondering if it would be useful to have an option to download one file by name.
This might be useful for working with a part/sample of a dataset when doing initial analyses or for obtaining specific files to store/check outside of DAFNI (e.g. logging files).
| 2023-08-09T15:05:00.000 | -1.0 | [
"dafni_cli/tests/commands/test_download.py::TestDownloadDataset::test_download_dataset_with_no_files",
"dafni_cli/tests/commands/test_helpers.py::TestCliSelectDatasetFiles::test_given_exact_file_names_selects_correct_files",
"dafni_cli/tests/commands/test_download.py::TestDownloadDataset::test_download_dataset_with_specific_directory",
"dafni_cli/tests/commands/test_download.py::TestDownloadDataset::test_download_dataset",
"dafni_cli/tests/commands/test_download.py::TestDownloadDataset::test_download_dataset_with_specific_files_given",
"dafni_cli/tests/commands/test_helpers.py::TestCliSelectDatasetFiles::test_all_optionals_none_returns_whole_list",
"dafni_cli/tests/commands/test_helpers.py::TestCliSelectDatasetFiles::test_given_file_name_and_wildcard_selects_correct_files",
"dafni_cli/tests/commands/test_download.py::TestDownloadDataset::test_download_dataset_with_no_selected_files",
"dafni_cli/tests/commands/test_helpers.py::TestCliSelectDatasetFiles::test_given_file_wildcard_selects_correct_files"
] | [
"dafni_cli/tests/test_utils.py::TestCreateFileProgressBar::test_create_file_progress_bar",
"dafni_cli/tests/commands/test_helpers.py::TestCliGetLatestDatasetMetadata::test_returns_correctly",
"dafni_cli/tests/test_utils.py::TestFormatTable::test_format_table_with_no_max_widths",
"dafni_cli/tests/test_utils.py::TestDataclassFromDict::test_dataclass_from_dict_raises_type_error",
"dafni_cli/tests/test_utils.py::TestFormatTable::test_format_table_with_column_width_without_wrapping",
"dafni_cli/tests/test_utils.py::TestConstructValidationErrorsFromDict::test_formats_correctly",
"dafni_cli/tests/test_utils.py::TestFormatTable::test_format_table_with_column_width_with_wrapping",
"dafni_cli/tests/commands/test_helpers.py::TestCliGetWorkflowParameterSet::test_resource_not_found",
"dafni_cli/tests/commands/test_helpers.py::TestCliGetModel::test_resource_not_found",
"dafni_cli/tests/test_utils.py::TestFormatFileSize::test_empty_string_returned_if_non_integer_or_float_value_given",
"dafni_cli/tests/test_utils.py::TestOptionalEcho::test_does_not_output_when_passed_true",
"dafni_cli/tests/test_utils.py::TestIsValidDefinitionFile::test_false_returned_if_no_definition_file_type_given",
"dafni_cli/tests/commands/test_helpers.py::TestCliGetWorkflowParameterSet::test_returns_correctly",
"dafni_cli/tests/test_utils.py::TestFormatDataFormat::test_formats_none_correctly",
"dafni_cli/tests/test_utils.py::TestFormatDataFormat::test_formats_correctly",
"dafni_cli/tests/test_utils.py::TestIsValidURL::test_valid_url_returns_true",
"dafni_cli/tests/test_utils.py::TestDataclassFromDict::test_dataclass_from_dict_with_missing_default",
"dafni_cli/tests/test_utils.py::TestIsValidEmailAddress::test_valid_email_returns_true",
"dafni_cli/tests/test_utils.py::TestProsePrint::test_string_without_line_breaks_or_spaces_is_split_correctly_and_printed_sequentially",
"dafni_cli/tests/test_utils.py::TestIsValidDefinitionFile::test_true_returned_if_correct_definition_file_type",
"dafni_cli/tests/test_utils.py::TestArgumentConfirmation::test_nothing_happens_when_skip_is_true",
"dafni_cli/tests/test_utils.py::TestIsValidImageFile::test_false_returned_if_incorrect_file_type_is_given",
"dafni_cli/tests/commands/test_download.py::TestDownload::test_session_retrieved_and_set_on_context",
"dafni_cli/tests/test_utils.py::TestFormatDatetime::test_formats_correctly_when_include_time_true",
"dafni_cli/tests/test_utils.py::TestArgumentConfirmation::test_arguments_are_printed_correctly_with_additional_messages",
"dafni_cli/tests/test_utils.py::TestArgumentConfirmation::test_arguments_are_printed_correctly_without_additional_messages",
"dafni_cli/tests/test_utils.py::TestFormatDatetime::test_formats_correctly_when_include_time_false",
"dafni_cli/tests/test_utils.py::TestProsePrint::test_string_with_line_break_splits_at_line_break",
"dafni_cli/tests/test_utils.py::TestFormatDataFormat::test_formats_invalid_values_correctly",
"dafni_cli/tests/test_utils.py::TestFormatTable::test_format_table_with_one_max_column_width_without_wrapping",
"dafni_cli/tests/test_utils.py::TestOverallFileProgressBar::test_overall_file_progress_bar",
"dafni_cli/tests/test_utils.py::TestFormatFileSize::test_file_size_processed_correctly",
"dafni_cli/tests/test_utils.py::TestFormatTable::test_format_table_with_one_max_column_width_with_wrapping",
"dafni_cli/tests/test_utils.py::TestIsValidURL::test_invalid_url_returns_false",
"dafni_cli/tests/test_utils.py::TestFormatDatetime::test_returns_none_when_value_none_and_include_time_true",
"dafni_cli/tests/test_utils.py::TestDataclassFromDict::test_dataclass_from_dict",
"dafni_cli/tests/test_utils.py::TestIsValidImageFile::test_false_returned_if_path_given_without_file_type",
"dafni_cli/tests/test_utils.py::TestPrintJSON::test_print_json",
"dafni_cli/tests/test_utils.py::TestProsePrint::test_string_shorter_than_width_prints_as_one_string",
"dafni_cli/tests/test_utils.py::TestIsValidEmailAddress::test_invalid_email_returns_false",
"dafni_cli/tests/commands/test_helpers.py::TestCliGetWorkflow::test_resource_not_found",
"dafni_cli/tests/test_utils.py::TestProsePrint::test_string_with_space_before_width_but_no_line_break_splits_at_space",
"dafni_cli/tests/commands/test_helpers.py::TestCliGetLatestDatasetMetadata::test_resource_not_found",
"dafni_cli/tests/test_utils.py::TestIsValidImageFile::test_true_returned_if_correct_file_type_is_given",
"dafni_cli/tests/commands/test_helpers.py::TestCliGetWorkflowInstance::test_resource_not_found",
"dafni_cli/tests/test_utils.py::TestIsValidURL::test_valid_url_returns_false_on_value_error",
"dafni_cli/tests/commands/test_helpers.py::TestCliGetWorkflow::test_returns_correctly",
"dafni_cli/tests/commands/test_helpers.py::TestCliGetWorkflowInstance::test_returns_correctly",
"dafni_cli/tests/test_utils.py::TestOptionalEcho::test_outputs_when_passed_false",
"dafni_cli/tests/commands/test_helpers.py::TestCliGetModel::test_returns_correctly",
"dafni_cli/tests/test_utils.py::TestFormatDatetime::test_returns_none_when_value_none_and_include_time_false",
"dafni_cli/tests/test_utils.py::TestIsValidDefinitionFile::test_false_returned_if_incorrect_definition_file_type"
] |
|
Duke-GCB/DukeDSClient | 343 | Duke-GCB__DukeDSClient-343 | ['342'] | 0f7332be2a5ba058ff77f6940cc6fcce8f32b6b3 | diff --git a/ddsc/cmdparser.py b/ddsc/cmdparser.py
index f851eec..d278756 100644
--- a/ddsc/cmdparser.py
+++ b/ddsc/cmdparser.py
@@ -360,14 +360,19 @@ def register_upload_command(self, upload_func):
Add the upload command to the parser and call upload_func(project_name, folders, follow_symlinks) when chosen.
:param upload_func: func Called when this option is chosen: upload_func(project_name, folders, follow_symlinks).
"""
- description = "Uploads local files and folders to a remote host."
+ description = "Uploads local files and folders to a remote store. After files are uploaded this command waits for all files to be valid/downloadable."
upload_parser = self.subparsers.add_parser('upload', description=description)
_add_dry_run(upload_parser, help_text="Instead of uploading displays a list of folders/files that "
"need to be uploaded.")
add_project_name_or_id_arg(upload_parser, help_text_suffix="upload files/folders to.")
_add_folders_positional_arg(upload_parser)
_add_follow_symlinks_arg(upload_parser)
- _add_azure_arg(upload_parser)
+ upload_parser.add_argument(
+ "--no-check",
+ help="Skip checking/waiting for uploaded files to be in the valid/downloadable state.",
+ action='store_false',
+ dest='check',
+ default=True)
upload_parser.set_defaults(func=upload_func)
def register_add_user_command(self, add_user_func):
@@ -383,7 +388,6 @@ def register_add_user_command(self, add_user_func):
add_user_arg(user_or_email)
add_email_arg(user_or_email)
_add_auth_role_arg(add_user_parser, default_permissions='project_admin')
- _add_azure_arg(add_user_parser)
add_user_parser.set_defaults(func=add_user_func)
def register_remove_user_command(self, remove_user_func):
@@ -397,7 +401,6 @@ def register_remove_user_command(self, remove_user_func):
user_or_email = remove_user_parser.add_mutually_exclusive_group(required=True)
add_user_arg(user_or_email)
add_email_arg(user_or_email)
- _add_azure_arg(remove_user_parser)
remove_user_parser.set_defaults(func=remove_user_func)
def register_download_command(self, download_func):
@@ -413,7 +416,6 @@ def register_download_command(self, download_func):
include_or_exclude = download_parser.add_mutually_exclusive_group(required=False)
_add_include_arg(include_or_exclude)
_add_exclude_arg(include_or_exclude)
- _add_azure_arg(download_parser)
download_parser.set_defaults(func=download_func)
def register_share_command(self, share_func):
@@ -433,7 +435,6 @@ def register_share_command(self, share_func):
_add_resend_arg(share_parser, "Resend share")
_add_message_file(share_parser, "Filename containing a message to be sent with the share. "
"Pass - to read from stdin.")
- _add_azure_arg(share_parser)
share_parser.set_defaults(func=share_func)
def register_deliver_command(self, deliver_func):
@@ -458,7 +459,6 @@ def register_deliver_command(self, deliver_func):
_add_exclude_arg(include_or_exclude)
_add_message_file(deliver_parser, "Filename containing a message to be sent with the delivery. "
"Pass - to read from stdin.")
- _add_azure_arg(deliver_parser)
deliver_parser.set_defaults(func=deliver_func)
def register_list_command(self, list_func):
@@ -473,7 +473,6 @@ def register_list_command(self, list_func):
add_project_name_or_id_arg(project_name_or_auth_role, required=False,
help_text_suffix="show details for")
_add_long_format_option(list_parser, 'Display long format.')
- _add_azure_arg(list_parser)
list_parser.set_defaults(func=list_func)
def register_delete_command(self, delete_func):
@@ -490,7 +489,6 @@ def register_delete_command(self, delete_func):
dest='remote_path',
help="remote path specifying the file/folder to be deleted instead of the entire project")
_add_force_arg(delete_parser, "Do not prompt before deleting.")
- _add_azure_arg(delete_parser)
delete_parser.set_defaults(func=delete_func)
def register_list_auth_roles_command(self, list_auth_roles_func):
@@ -501,7 +499,6 @@ def register_list_auth_roles_command(self, list_auth_roles_func):
description = "List authorization roles for use with add_user command."
list_auth_roles_parser = self.subparsers.add_parser('list-auth-roles', description=description)
list_auth_roles_parser.set_defaults(func=list_auth_roles_func)
- _add_azure_arg(list_auth_roles_parser)
def register_move_command(self, move_func):
"""
@@ -522,7 +519,6 @@ def register_move_command(self, move_func):
metavar='Target',
type=to_unicode,
help='remote path specifying where to move the file/folder to')
- _add_azure_arg(parser)
parser.set_defaults(func=move_func)
def register_info_command(self, info_func):
@@ -533,7 +529,6 @@ def register_info_command(self, info_func):
description = "Print information about a project."
parser = self.subparsers.add_parser('info', description=description)
add_project_name_or_id_arg(parser, help_text_suffix="to show the information about")
- _add_azure_arg(parser)
parser.set_defaults(func=info_func)
def register_check_command(self, check_func):
@@ -547,7 +542,6 @@ def register_check_command(self, check_func):
check_parser.add_argument('--wait',
help="Wait for project to become consistent.",
action='store_true')
- _add_azure_arg(check_parser)
check_parser.set_defaults(func=check_func)
def run_command(self, args):
diff --git a/ddsc/core/consistency.py b/ddsc/core/consistency.py
index ea69e16..0f4a287 100644
--- a/ddsc/core/consistency.py
+++ b/ddsc/core/consistency.py
@@ -99,7 +99,7 @@ def print_bad_uploads_table(self):
def wait_for_consistency(self, wait_sec=5):
while True:
try:
- print("Checking files for project {}".format(self.project.name))
+ print("Checking files for project {}.".format(self.project.name))
self._try_fetch_project_files()
# if we are able to fetch all files project is in a consistent state
print("Project {} is consistent.".format(self.project.name))
diff --git a/ddsc/ddsclient.py b/ddsc/ddsclient.py
index 8d501ee..37ffdd4 100644
--- a/ddsc/ddsclient.py
+++ b/ddsc/ddsclient.py
@@ -64,7 +64,7 @@ def _create_parser(self):
return parser
def use_azure_commands(self, args):
- return args.azure or self.config.backing_storage == "azure"
+ return False
def list_command(self, args):
command_constructor = ListCommand
@@ -253,6 +253,7 @@ def run(self, args):
folders = args.folders # list of local files/folders to upload into the project
follow_symlinks = args.follow_symlinks # should we follow symlinks when traversing folders
dry_run = args.dry_run # do not upload anything, instead print out what you would upload
+ check_file_consistency = args.check # should we check download URLs after uploading
# Find files and folders to upload
local_project = LocalProject(followsymlinks=follow_symlinks, file_exclude_regex=self.config.file_exclude_regex)
@@ -286,6 +287,22 @@ def run(self, args):
print(project_upload.get_url_msg())
project_upload.cleanup()
+ # check for consistency unless user passes --no-check flag
+ if check_file_consistency:
+ self.wait_for_consistency(local_project.remote_id)
+
+ def wait_for_consistency(self, project_id):
+ client = Client(self.config)
+ project = client.get_project_by_id(project_id)
+ checker = ProjectChecker(self.config, project)
+ try:
+ checker.wait_for_consistency()
+ except DSHashMismatchError:
+ checker.print_bad_uploads_table()
+ sys.exit(1)
+ finally:
+ client.close()
+
class DownloadCommand(ClientCommand):
"""
| diff --git a/ddsc/core/tests/test_consistency.py b/ddsc/core/tests/test_consistency.py
index 6ff59a2..ebccb72 100644
--- a/ddsc/core/tests/test_consistency.py
+++ b/ddsc/core/tests/test_consistency.py
@@ -131,9 +131,9 @@ def test_wait_for_consistency(self, mock_time, mock_print):
]
self.checker.wait_for_consistency(wait_sec=10)
mock_print.assert_has_calls([
- call('Checking files for project Mouse'),
+ call('Checking files for project Mouse.'),
call('Project not consistent yet. Waiting.'),
- call('Checking files for project Mouse'),
+ call('Checking files for project Mouse.'),
call('Project Mouse is consistent.')
])
mock_time.sleep.assert_called_with(10)
diff --git a/ddsc/tests/test_cmdparser.py b/ddsc/tests/test_cmdparser.py
index 45f28a2..9981a0b 100644
--- a/ddsc/tests/test_cmdparser.py
+++ b/ddsc/tests/test_cmdparser.py
@@ -227,3 +227,23 @@ def test_register_check_command(self):
command_parser.run_command(['check', '-p', 'mouse'])
self.assertEqual(self.parsed_args.project_name, 'mouse')
self.assertEqual(self.parsed_args.project_id, None)
+
+ def test_register_upload_command_project_name(self):
+ command_parser = CommandParser(version_str='1.0')
+ command_parser.register_upload_command(self.set_parsed_args)
+ self.assertEqual(['upload'], list(command_parser.subparsers.choices.keys()))
+ command_parser.run_command(['upload', '-p', 'myproj', '/tmp'])
+ self.assertEqual('myproj', self.parsed_args.project_name)
+ self.assertEqual(None, self.parsed_args.project_id)
+ self.assertEqual(['/tmp'], self.parsed_args.folders)
+ self.assertEqual(True, self.parsed_args.check)
+
+ def test_register_upload_command_project_name__no_check(self):
+ command_parser = CommandParser(version_str='1.0')
+ command_parser.register_upload_command(self.set_parsed_args)
+ self.assertEqual(['upload'], list(command_parser.subparsers.choices.keys()))
+ command_parser.run_command(['upload', '-p', 'myproj', '/tmp', '--no-check'])
+ self.assertEqual('myproj', self.parsed_args.project_name)
+ self.assertEqual(None, self.parsed_args.project_id)
+ self.assertEqual(['/tmp'], self.parsed_args.folders)
+ self.assertEqual(False, self.parsed_args.check)
diff --git a/ddsc/tests/test_ddsclient.py b/ddsc/tests/test_ddsclient.py
index 325bb38..8df2e0e 100644
--- a/ddsc/tests/test_ddsclient.py
+++ b/ddsc/tests/test_ddsclient.py
@@ -86,7 +86,9 @@ class TestUploadCommand(TestCase):
@patch("ddsc.ddsclient.ProjectUploadDryRun")
@patch('ddsc.ddsclient.RemoteStore')
@patch('ddsc.ddsclient.print')
- def test_without_dry_run(self, mock_print, mock_remote_store, mock_project_upload_dry_run, mock_local_project,
+ @patch('ddsc.ddsclient.Client')
+ @patch('ddsc.ddsclient.ProjectChecker')
+ def test_without_dry_run(self, mock_project_checker, mock_client, mock_print, mock_remote_store, mock_project_upload_dry_run, mock_local_project,
mock_project_name_or_id, mock_project_upload):
mock_config = MagicMock()
cmd = UploadCommand(mock_config)
@@ -96,6 +98,7 @@ def test_without_dry_run(self, mock_print, mock_remote_store, mock_project_uploa
args.folders = ["data", "scripts"]
args.follow_symlinks = False
args.dry_run = False
+ args.check = True
cmd.run(args)
mock_project_name_or_id.create_from_name.assert_called_with("test")
@@ -122,6 +125,8 @@ def test_without_dry_run(self, mock_print, mock_remote_store, mock_project_uploa
call(mock_project_upload.return_value.get_url_msg.return_value),
])
mock_project_upload.return_value.cleanup.assert_called_with()
+ mock_client.return_value.get_project_by_id.assert_called_with(mock_local_project.return_value.remote_id)
+ mock_project_checker.return_value.wait_for_consistency.assert_called_with()
@patch("ddsc.ddsclient.ProjectUpload")
@patch("ddsc.ddsclient.ProjectNameOrId")
@@ -129,7 +134,32 @@ def test_without_dry_run(self, mock_print, mock_remote_store, mock_project_uploa
@patch("ddsc.ddsclient.ProjectUploadDryRun")
@patch('ddsc.ddsclient.RemoteStore')
@patch('ddsc.ddsclient.print')
- def test_without_dry_run_project_id(self, mock_print, mock_remote_store, mock_project_upload_dry_run,
+ @patch('ddsc.ddsclient.Client')
+ @patch('ddsc.ddsclient.ProjectChecker')
+ def test_without_dry_run__no_check(self, mock_project_checker, mock_client, mock_print, mock_remote_store,
+ mock_project_upload_dry_run, mock_local_project, mock_project_name_or_id,
+ mock_project_upload):
+ mock_config = MagicMock()
+ cmd = UploadCommand(mock_config)
+ args = Mock()
+ args.project_name = "test"
+ args.project_id = None
+ args.folders = ["data", "scripts"]
+ args.follow_symlinks = False
+ args.dry_run = False
+ args.check = False
+ cmd.run(args)
+ mock_client.return_value.get_project_by_id.assert_not_called()
+ mock_project_checker.return_value.wait_for_consistency.assert_not_called()
+
+ @patch("ddsc.ddsclient.ProjectUpload")
+ @patch("ddsc.ddsclient.ProjectNameOrId")
+ @patch("ddsc.ddsclient.LocalProject")
+ @patch("ddsc.ddsclient.ProjectUploadDryRun")
+ @patch('ddsc.ddsclient.RemoteStore')
+ @patch('ddsc.ddsclient.print')
+ @patch('ddsc.ddsclient.Client')
+ def test_without_dry_run_project_id(self, mock_client, mock_print, mock_remote_store, mock_project_upload_dry_run,
mock_local_project, mock_project_name_or_id, mock_project_upload):
mock_config = MagicMock()
cmd = UploadCommand(mock_config)
@@ -139,6 +169,7 @@ def test_without_dry_run_project_id(self, mock_print, mock_remote_store, mock_pr
args.folders = ["data", "scripts"]
args.follow_symlinks = False
args.dry_run = False
+ args.check = True
cmd.run(args)
mock_project_name_or_id.create_from_project_id.assert_called_with("123")
@@ -168,6 +199,7 @@ def test_with_dry_run(self, mock_print, mock_remote_store, mock_project_upload_d
args.folders = ["data", "scripts"]
args.follow_symlinks = False
args.dry_run = True
+ args.check = True
cmd.run(args)
mock_local_project.assert_called_with(followsymlinks=False, file_exclude_regex=mock_config.file_exclude_regex)
| Add download URL checking to upload command
Due to recent errors with the DDS API just checking the API responses when uploading is no longer sufficient.
The DDS Team suggested we retrieve download URLs for all uploaded files to make sure everything is correct.
By default the upload command should run a check process to wait/poll for all files to have valid download URLs.
Add a `--no-check` option to disable this functionality.
| 2022-01-25T21:19:46.000 | -1.0 | [
"ddsc/core/tests/test_consistency.py::TestProjectChecker::test_wait_for_consistency",
"ddsc/tests/test_cmdparser.py::TestCommandParser::test_register_upload_command_project_name__no_check",
"ddsc/tests/test_cmdparser.py::TestCommandParser::test_register_upload_command_project_name",
"ddsc/tests/test_ddsclient.py::TestUploadCommand::test_without_dry_run"
] | [
"ddsc/tests/test_ddsclient.py::TestShareCommand::test_run_no_message",
"ddsc/tests/test_cmdparser.py::TestCommandParser::test_list_command",
"ddsc/tests/test_cmdparser.py::TestCommandParser::test_register_download_command",
"ddsc/tests/test_ddsclient.py::TestListCommand::test_print_project_list_details_with_auth_role_long_format",
"ddsc/tests/test_cmdparser.py::TestCommandParser::test_register_info_command",
"ddsc/core/tests/test_consistency.py::TestProjectChecker::test_files_are_ok__DDS_400",
"ddsc/tests/test_ddsclient.py::TestDDSClient::test_run_command",
"ddsc/tests/test_cmdparser.py::TestCommandParser::test_register_delete_command",
"ddsc/tests/test_ddsclient.py::TestUploadCommand::test_with_dry_run",
"ddsc/tests/test_cmdparser.py::TestCommandParser::test_share_no_msg",
"ddsc/tests/test_ddsclient.py::TestDeliverCommand::test_run_share_users_invalid",
"ddsc/tests/test_cmdparser.py::TestCommandParser::test_share_with_msg",
"ddsc/tests/test_cmdparser.py::TestCommandParser::test_deliver_with_msg",
"ddsc/tests/test_ddsclient.py::TestListCommand::test_print_project_list_details_long_format",
"ddsc/tests/test_ddsclient.py::TestDownloadCommand::test_run_project_id",
"ddsc/tests/test_ddsclient.py::TestBaseCommand::test_cleanup",
"ddsc/tests/test_ddsclient.py::TestShareCommand::test_run_message",
"ddsc/tests/test_cmdparser.py::TestCommandParser::test_deliver_no_msg",
"ddsc/tests/test_cmdparser.py::TestCommandParser::test_format_destination_path_ok_when_dir_empty",
"ddsc/core/tests/test_consistency.py::TestProjectChecker::test_files_are_ok__good",
"ddsc/tests/test_ddsclient.py::TestUploadCommand::test_without_dry_run__no_check",
"ddsc/tests/test_ddsclient.py::TestDeliverCommand::test_run_share_users_good",
"ddsc/tests/test_ddsclient.py::TestDeleteCommand::test_run_project_delete",
"ddsc/tests/test_cmdparser.py::TestCommandParser::test_register_add_user_command_project_name",
"ddsc/tests/test_ddsclient.py::TestUploadCommand::test_without_dry_run_project_id",
"ddsc/tests/test_cmdparser.py::TestCommandParser::test_description",
"ddsc/tests/test_ddsclient.py::TestListCommand::test_print_project_list_details",
"ddsc/tests/test_ddsclient.py::TestClientCommand::test_get_project_by_name_or_id__with_id",
"ddsc/tests/test_ddsclient.py::TestBaseCommand::test_project_name_or_id_from_args",
"ddsc/tests/test_ddsclient.py::TestDeliverCommand::test_run_message",
"ddsc/tests/test_ddsclient.py::TestCheckCommand::test_run_bad",
"ddsc/tests/test_ddsclient.py::TestCheckCommand::test_run",
"ddsc/tests/test_cmdparser.py::TestCommandParser::test_deliver_with_share_users",
"ddsc/tests/test_ddsclient.py::TestDownloadCommand::test_run_project_name",
"ddsc/tests/test_ddsclient.py::TestMoveCommand::test_run",
"ddsc/tests/test_cmdparser.py::TestCommandParser::test_register_move_command",
"ddsc/tests/test_ddsclient.py::TestClientCommand::test_get_project_by_name_or_id__with_name",
"ddsc/tests/test_ddsclient.py::TestDeliverCommand::test_run_no_message_and_copy",
"ddsc/tests/test_ddsclient.py::TestBaseCommand::test_fetch_project",
"ddsc/tests/test_ddsclient.py::TestInfoCommand::test_run",
"ddsc/tests/test_ddsclient.py::TestDDSClient::test_read_argument_file_contents",
"ddsc/tests/test_cmdparser.py::TestCommandParser::test_list_command_long",
"ddsc/tests/test_cmdparser.py::TestCommandParser::test_register_add_user_command_project_id",
"ddsc/tests/test_cmdparser.py::TestCommandParser::test_register_check_command",
"ddsc/tests/test_ddsclient.py::TestCheckCommand::test_run_wait_ok",
"ddsc/core/tests/test_consistency.py::TestProjectChecker::test_print_bad_uploads_table",
"ddsc/core/tests/test_consistency.py::TestUploadDetails::test_error_status",
"ddsc/tests/test_cmdparser.py::TestCommandParser::test_register_remove_user_command_project_id",
"ddsc/tests/test_ddsclient.py::TestListCommand::test_get_project_info_line",
"ddsc/tests/test_ddsclient.py::TestListCommand::test_pprint_project_list_details_with_auth_role",
"ddsc/tests/test_ddsclient.py::TestCheckCommand::test_run_wait_bad",
"ddsc/tests/test_ddsclient.py::TestClientCommand::test_cleanup",
"ddsc/tests/test_cmdparser.py::TestCommandParser::test_register_remove_user_command_project_name",
"ddsc/tests/test_ddsclient.py::TestDeleteCommand::test_run_project_delete_path",
"ddsc/core/tests/test_consistency.py::TestUploadDetails::test_error_ok",
"ddsc/core/tests/test_consistency.py::TestProjectChecker::test_files_are_ok__error",
"ddsc/tests/test_ddsclient.py::TestBaseCommand::test_make_user_list",
"ddsc/core/tests/test_consistency.py::TestUploadDetails::test_inconsistent_status",
"ddsc/tests/test_cmdparser.py::TestCommandParser::test_deliver_with_copy"
] |
|
cpp-linter/clang-tools-pip | 60 | cpp-linter__clang-tools-pip-60 | ['27'] | 9d65ac1f2523eccd50cd92f4d8de3623d91da4cd | diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 7652217..a9d114f 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -1,6 +1,6 @@
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
- rev: v4.3.0
+ rev: v4.5.0
hooks:
- id: trailing-whitespace
exclude: \.output
@@ -12,11 +12,11 @@ repos:
- id: debug-statements
- id: requirements-txt-fixer
- repo: https://github.com/asottile/pyupgrade
- rev: v2.37.3
+ rev: v3.15.0
hooks:
- id: pyupgrade
- repo: https://github.com/pycqa/flake8
- rev: '5.0.4'
+ rev: '7.0.0'
hooks:
- id: flake8
args: [--max-line-length=120]
diff --git a/README.rst b/README.rst
index 5ff9b0e..ce53b8b 100644
--- a/README.rst
+++ b/README.rst
@@ -21,7 +21,7 @@ clang-tools Introduction
:alt: PyPI - Downloads
-Install clang-tools binaries (clang-format, clang-tidy) with pip.
+Install clang-tools binaries (clang-format, clang-tidy, clang-query and clang-apply-replacements) with pip.
.. important::
This package only manages binary executables (& corresponding symbolic links) that
@@ -32,6 +32,7 @@ Features
--------
- Binaries are statically linked for improved portability.
+- Binaries can be specified installed for increased flexibility.
- Binaries are checked with SHA512 checksum. This ensures:
1. Downloads are not corrupted.
@@ -102,6 +103,12 @@ Or install to a specified directory
clang-tools --install 13 --directory .
+Or install a specified tool, such as clang-format and clang-query version 14.
+
+.. code-block:: shell
+
+ clang-tools --install 14 --tool clang-format clang-query
+
If the installed directory is in your path, you can run the installed tools.
.. code-block:: shell
@@ -121,18 +128,8 @@ If the installed directory is in your path, you can run the installed tools.
Supported versions
------------------
-clang-format
-************
-.. csv-table::
- :header: "Version", "17", "16", "15", "14", "13", "12", "11", "10", "9", "8", "7"
- :stub-columns: 1
-
- Linux,✔️,✔️,✔️,✔️,✔️,✔️,✔️,✔️,✔️,✔️,✔️
- Windows,✔️,✔️,✔️,✔️,✔️,✔️,✔️,✔️,✔️,✔️,✔️
- macOS,✔️,✔️,✔️,✔️,✔️,✔️,✔️,✔️,✔️,✔️,✔️
-
-clang-tidy
-**********
+clang-format, clang-tidy, clang-query, clang-apply-replacements
+***************************************************************
.. csv-table::
:header: "Version", "17", "16", "15", "14", "13", "12", "11", "10", "9", "8", "7"
:stub-columns: 1
diff --git a/clang_tools/install.py b/clang_tools/install.py
index 27c05b1..b270885 100644
--- a/clang_tools/install.py
+++ b/clang_tools/install.py
@@ -249,11 +249,12 @@ def uninstall_clang_tools(version: str, directory: str):
def install_clang_tools(
- version: str, directory: str, overwrite: bool, no_progress_bar: bool
+ version: str, tools: str, directory: str, overwrite: bool, no_progress_bar: bool
) -> None:
"""Wraps functions used to individually install tools.
:param version: The version of the tools to install.
+ :param tools: The specify tool(s) to install.
:param directory: The installation directory.
:param overwrite: A flag to indicate if the creation of a symlink has
permission to overwrite an existing symlink.
@@ -265,7 +266,7 @@ def install_clang_tools(
f"{YELLOW}{install_dir}",
f"directory is not in your environment variable PATH.{RESET_COLOR}",
)
- for tool_name in ("clang-format", "clang-tidy"):
+ for tool_name in tools:
native_bin = is_installed(tool_name, version)
if native_bin is None: # (not already installed)
# `install_tool()` guarantees that the binary exists now
diff --git a/clang_tools/main.py b/clang_tools/main.py
index f82caab..2617956 100644
--- a/clang_tools/main.py
+++ b/clang_tools/main.py
@@ -20,6 +20,14 @@ def get_parser() -> argparse.ArgumentParser:
metavar="VERSION",
help="Install clang-tools about a specific version.",
)
+ parser.add_argument(
+ "-t",
+ "--tool",
+ nargs='+',
+ default=['clang-format', 'clang-tidy'],
+ metavar="TOOL",
+ help="Specify which tool(s) to install.",
+ )
parser.add_argument(
"-d",
"--directory",
@@ -54,19 +62,19 @@ def main():
"""The main entrypoint to the CLI program."""
parser = get_parser()
args = parser.parse_args()
- if not args.install and not args.uninstall:
+
+ if args.uninstall:
+ uninstall_clang_tools(args.uninstall, args.directory)
+ if args.install:
+ install_clang_tools(
+ args.install, args.tool, args.directory, args.overwrite, args.no_progress_bar
+ )
+ else:
print(
f"{YELLOW}Nothing to do because `--install` and `--uninstall`",
f"was not specified.{RESET_COLOR}"
)
parser.print_help()
- else:
- if args.uninstall:
- uninstall_clang_tools(args.uninstall, args.directory)
- if args.install:
- install_clang_tools(
- args.install, args.directory, args.overwrite, args.no_progress_bar
- )
if __name__ == "__main__":
diff --git a/clang_tools/util.py b/clang_tools/util.py
index 0783061..87d296c 100644
--- a/clang_tools/util.py
+++ b/clang_tools/util.py
@@ -48,7 +48,7 @@ def download_file(url: str, file_name: str, no_progress_bar: bool) -> Optional[s
return None
assert response.length is not None
length = response.length
- buffer = bytes()
+ buffer = b''
progress_bar = "=" if check_install_os() == "windows" else "█"
while len(buffer) < length:
block_size = int(length / 20)
| diff --git a/tests/test_install.py b/tests/test_install.py
index 54b0a7c..374d9e8 100644
--- a/tests/test_install.py
+++ b/tests/test_install.py
@@ -14,7 +14,7 @@
@pytest.mark.parametrize("version", [str(v) for v in range(7, 17)] + ["12.0.1"])
[email protected]("tool_name", ["clang-format", "clang-tidy"])
[email protected]("tool_name", ["clang-format", "clang-tidy", "clang-query", "clang-apply-replacements"])
def test_clang_tools_binary_url(tool_name: str, version: str):
"""Test `clang_tools_binary_url()`"""
url = clang_tools_binary_url(tool_name, version)
@@ -72,7 +72,7 @@ def test_path_warning(capsys: pytest.CaptureFixture):
2. indicates a failure to download a tool
"""
try:
- install_clang_tools("x", ".", False, False)
+ install_clang_tools("x", "x", ".", False, False)
except OSError as exc:
result = capsys.readouterr()
assert "directory is not in your environment variable PATH" in result.out
diff --git a/tests/test_main.py b/tests/test_main.py
index 513bbbd..8419c49 100644
--- a/tests/test_main.py
+++ b/tests/test_main.py
@@ -37,8 +37,15 @@ def test_cli_switch(switch_name: str, parser: ArgumentParser):
assert getattr(args, switch_name.replace("-", "_"))
-def test_default_args(parser: ArgumentParser):
[email protected]("name, default_value", [
+ ("install", None),
+ ("uninstall", None),
+ ("overwrite", False),
+ ("no_progress_bar", False),
+ ("directory", ""),
+ ("tool", ['clang-format', 'clang-tidy'])
+])
+def test_default_args(parser: ArgumentParser, name, default_value):
"""Test the default values of CLI args"""
args = parser.parse_args([])
- for name, value in args.__dict__.items():
- assert getattr(Args, name) == value
+ assert getattr(args, name) == default_value
| specify which tool(s) to install
It would be nice to let the user choose which tool(s) to install. This way we could only install clang-tidy in the cpp-linter-action (composite form) if `inputs.tidy-checks != '-*`. Or we could avoid installing clang-format if the `inputs.style != ''`.
Since the releases of binary builds also include the clang-query tool, users could specify that as well.
## Implementation
### Option 1
```
clang-tools -t clang-format -t clang-tidy -t clang-query
```
### Option 2
```
clang-tools -t clang-format,clang-tidy,clang-query
```
I haven't decided which way to support. Maybe there's a way to support either or both options.
I would expect the current default ( clang-tidy + clang-format) to be overridden when `-t` is specified.
| It would be nice to support users in installing specific tools.
For cpp-linter-action, I think it's OK to provide both tools (including clang-format and clang-tidy) if the user only uses one of them. It will add a small amount of download time, but the logic is more simple than adding more `if else` to check users' inputs, less code fewer bugs 😆
clang-format or clang-tidy is installed with `clang-tools` command before running `cpp-linter`, so it should be hard to know which needs to be installed in the preparation stage
> This way we could only install clang-tidy in the cpp-linter-action (composite form) if `inputs.tidy-checks != '-*`. Or we could avoid installing clang-format if the `inputs.style != ''`.
This an advanced example. The defaults should suffice for our needs. What if someone wants to use this pkg to get the statically linked clang-query binary?
> What if someone wants to use this pkg to get the statically linked clang-query binary?
Your implementation proposal like great, users could use this way to install clang-query binary.
Option 1
`clang-tools -t clang-format -t clang-tidy -t clang-query`
Option 2
`clang-tools -t clang-format,clang-tidy,clang-query`
I saw that the user from the upstream repo of cpp-linter/clang-tools-static-binaries was asking to have `clang-apply-replacements` binary, so I added it to the latest release [master-a2d1eff4](https://github.com/cpp-linter/clang-tools-static-binaries/releases/tag/master-a2d1eff4). so this enhancement becomes more and more worth to implement.
I don't have much of an impression of how other tools implement similar functionality, and so far I prefer option 1 (option 2 is also not bad)
| 2024-01-15T09:25:13.000 | -1.0 | [
"tests/test_main.py::test_default_args[tool-default_value5]"
] | [
"tests/test_install.py::test_clang_tools_binary_url[clang-tidy-10]",
"tests/test_install.py::test_clang_tools_binary_url[clang-apply-replacements-12.0.1]",
"tests/test_main.py::test_arg_parser[12-uninstall]",
"tests/test_install.py::test_clang_tools_binary_url[clang-tidy-12]",
"tests/test_install.py::test_clang_tools_binary_url[clang-apply-replacements-15]",
"tests/test_install.py::test_install_tools[16]",
"tests/test_main.py::test_arg_parser[7-directory]",
"tests/test_main.py::test_arg_parser[7-uninstall]",
"tests/test_install.py::test_clang_tools_binary_url[clang-query-15]",
"tests/test_install.py::test_clang_tools_binary_url[clang-query-11]",
"tests/test_install.py::test_clang_tools_binary_url[clang-tidy-14]",
"tests/test_main.py::test_cli_switch[no-progress-bar]",
"tests/test_install.py::test_clang_tools_binary_url[clang-format-13]",
"tests/test_install.py::test_clang_tools_binary_url[clang-format-7]",
"tests/test_install.py::test_create_symlink",
"tests/test_install.py::test_clang_tools_binary_url[clang-format-12.0.1]",
"tests/test_install.py::test_clang_tools_binary_url[clang-query-16]",
"tests/test_install.py::test_install_tools[13]",
"tests/test_install.py::test_clang_tools_binary_url[clang-tidy-16]",
"tests/test_install.py::test_clang_tools_binary_url[clang-format-10]",
"tests/test_main.py::test_arg_parser[11-directory]",
"tests/test_main.py::test_arg_parser[8-install]",
"tests/test_install.py::test_clang_tools_binary_url[clang-apply-replacements-13]",
"tests/test_install.py::test_clang_tools_binary_url[clang-tidy-12.0.1]",
"tests/test_main.py::test_arg_parser[12-directory]",
"tests/test_main.py::test_arg_parser[12.0.1-install]",
"tests/test_install.py::test_clang_tools_binary_url[clang-query-13]",
"tests/test_install.py::test_dir_name[.]",
"tests/test_install.py::test_clang_tools_binary_url[clang-format-11]",
"tests/test_main.py::test_arg_parser[10-install]",
"tests/test_main.py::test_arg_parser[15-install]",
"tests/test_install.py::test_install_tools[14]",
"tests/test_install.py::test_clang_tools_binary_url[clang-tidy-7]",
"tests/test_main.py::test_arg_parser[11-install]",
"tests/test_install.py::test_clang_tools_binary_url[clang-apply-replacements-9]",
"tests/test_install.py::test_clang_tools_binary_url[clang-format-9]",
"tests/test_main.py::test_arg_parser[8-uninstall]",
"tests/test_main.py::test_default_args[install-None]",
"tests/test_install.py::test_clang_tools_binary_url[clang-apply-replacements-11]",
"tests/test_install.py::test_clang_tools_binary_url[clang-query-12.0.1]",
"tests/test_install.py::test_clang_tools_binary_url[clang-apply-replacements-10]",
"tests/test_install.py::test_clang_tools_binary_url[clang-tidy-9]",
"tests/test_install.py::test_clang_tools_binary_url[clang-tidy-11]",
"tests/test_main.py::test_default_args[overwrite-False]",
"tests/test_main.py::test_arg_parser[12.0.1-directory]",
"tests/test_install.py::test_clang_tools_binary_url[clang-apply-replacements-14]",
"tests/test_main.py::test_default_args[no_progress_bar-False]",
"tests/test_main.py::test_arg_parser[14-install]",
"tests/test_install.py::test_clang_tools_binary_url[clang-query-12]",
"tests/test_install.py::test_clang_tools_binary_url[clang-tidy-15]",
"tests/test_main.py::test_arg_parser[16-directory]",
"tests/test_main.py::test_arg_parser[15-directory]",
"tests/test_main.py::test_arg_parser[16-uninstall]",
"tests/test_install.py::test_clang_tools_binary_url[clang-query-14]",
"tests/test_main.py::test_default_args[directory-]",
"tests/test_main.py::test_default_args[uninstall-None]",
"tests/test_main.py::test_arg_parser[12-install]",
"tests/test_main.py::test_arg_parser[9-uninstall]",
"tests/test_install.py::test_clang_tools_binary_url[clang-format-14]",
"tests/test_install.py::test_clang_tools_binary_url[clang-query-10]",
"tests/test_main.py::test_arg_parser[15-uninstall]",
"tests/test_install.py::test_install_tools[15]",
"tests/test_install.py::test_clang_tools_binary_url[clang-tidy-13]",
"tests/test_install.py::test_clang_tools_binary_url[clang-format-16]",
"tests/test_main.py::test_arg_parser[13-directory]",
"tests/test_main.py::test_arg_parser[7-install]",
"tests/test_main.py::test_arg_parser[13-uninstall]",
"tests/test_install.py::test_dir_name[]",
"tests/test_main.py::test_arg_parser[13-install]",
"tests/test_install.py::test_install_tools[11]",
"tests/test_main.py::test_arg_parser[8-directory]",
"tests/test_main.py::test_arg_parser[16-install]",
"tests/test_main.py::test_cli_switch[overwrite]",
"tests/test_install.py::test_install_tools[12]",
"tests/test_install.py::test_clang_tools_binary_url[clang-apply-replacements-7]",
"tests/test_main.py::test_arg_parser[14-directory]",
"tests/test_main.py::test_arg_parser[12.0.1-uninstall]",
"tests/test_install.py::test_clang_tools_binary_url[clang-apply-replacements-12]",
"tests/test_install.py::test_clang_tools_binary_url[clang-apply-replacements-8]",
"tests/test_main.py::test_arg_parser[10-directory]",
"tests/test_install.py::test_clang_tools_binary_url[clang-query-8]",
"tests/test_install.py::test_clang_tools_binary_url[clang-query-7]",
"tests/test_main.py::test_arg_parser[10-uninstall]",
"tests/test_main.py::test_arg_parser[14-uninstall]",
"tests/test_main.py::test_arg_parser[9-directory]",
"tests/test_install.py::test_clang_tools_binary_url[clang-format-15]",
"tests/test_install.py::test_clang_tools_binary_url[clang-format-12]",
"tests/test_install.py::test_clang_tools_binary_url[clang-apply-replacements-16]",
"tests/test_main.py::test_arg_parser[11-uninstall]",
"tests/test_main.py::test_arg_parser[9-install]",
"tests/test_install.py::test_clang_tools_binary_url[clang-format-8]",
"tests/test_install.py::test_clang_tools_binary_url[clang-tidy-8]",
"tests/test_install.py::test_clang_tools_binary_url[clang-query-9]",
"tests/test_install.py::test_install_tools[10]",
"tests/test_install.py::test_install_tools[12.0.1]"
] |
dafnifacility/cli | 102 | dafnifacility__cli-102 | ['95'] | c8f0a04af3abeeab7bb58c9b9302b6b91c6ee25e | diff --git a/dafni_cli/commands/options.py b/dafni_cli/commands/options.py
index e93a7c00..cea2a93a 100644
--- a/dafni_cli/commands/options.py
+++ b/dafni_cli/commands/options.py
@@ -251,3 +251,20 @@ def decorator(function):
return function
return decorator
+
+
+def confirmation_skip_option(function):
+ """Decorator function for adding a -y click option for skipping
+ any confirmation prompts
+
+ Flag will be named 'yes' and will be True or False
+ """
+ function = click.option(
+ "--yes",
+ "-y",
+ is_flag=True,
+ default=False,
+ help="Flag for skipping any confirmation prompts",
+ )(function)
+
+ return function
diff --git a/dafni_cli/commands/upload.py b/dafni_cli/commands/upload.py
index 36048edd..4ff08484 100644
--- a/dafni_cli/commands/upload.py
+++ b/dafni_cli/commands/upload.py
@@ -14,7 +14,10 @@
validate_parameter_set_definition,
)
from dafni_cli.commands.helpers import cli_get_latest_dataset_metadata
-from dafni_cli.commands.options import dataset_metadata_common_options
+from dafni_cli.commands.options import (
+ confirmation_skip_option,
+ dataset_metadata_common_options,
+)
from dafni_cli.datasets.dataset_metadata import parse_dataset_metadata
from dafni_cli.datasets.dataset_upload import (
modify_dataset_metadata_for_upload,
@@ -64,6 +67,7 @@ def upload(ctx: Context):
help="Parent ID of the parent model if this is an updated version of an existing model",
default=None,
)
+@confirmation_skip_option
@click.pass_context
def model(
ctx: Context,
@@ -71,6 +75,7 @@ def model(
image: Path,
version_message: str,
parent_id: Optional[str],
+ yes: bool,
):
"""Uploads model to DAFNI from metadata and image files
@@ -80,6 +85,7 @@ def model(
image (Path): File path to the image file
version_message (str): Version message to be included with this model version
parent_id (str): ID of the parent model that this is an update of
+ yes (bool): Used to skip confirmations before they are displayed
"""
arguments = [
("Model definition file path", definition),
@@ -92,7 +98,7 @@ def model(
additional_message = None
else:
additional_message = ["No parent model: New model to be created"]
- argument_confirmation(arguments, confirmation_message, additional_message)
+ argument_confirmation(arguments, confirmation_message, additional_message, yes=yes)
upload_model(
ctx.obj["session"],
@@ -119,21 +125,28 @@ def model(
required=True,
type=click.Path(exists=True, path_type=Path),
)
+@confirmation_skip_option
@click.pass_context
-def dataset(ctx: Context, metadata_path: Path, files: List[Path]):
+def dataset(
+ ctx: Context,
+ metadata_path: Path,
+ files: List[Path],
+ yes: bool,
+):
"""Uploads a new Dataset to DAFNI from metadata and dataset files.
Args:
ctx (Context): contains user session for authentication
metadata_path (Path): Dataset metadata file path
files (List[Path]): Dataset data files
+ yes (bool): Used to skip confirmations before they are displayed
"""
# Confirm upload details
arguments = [("Dataset metadata file path", metadata_path)] + [
("Dataset file path", file) for file in files
]
confirmation_message = "Confirm dataset upload?"
- argument_confirmation(arguments, confirmation_message)
+ argument_confirmation(arguments, confirmation_message, yes=yes)
# Obtain the metadata
with open(metadata_path, "r", encoding="utf-8") as metadata_file:
@@ -166,6 +179,7 @@ def dataset(ctx: Context, metadata_path: Path, files: List[Path]):
help="When given will only save the existing metadata to the specified file allowing it to be modified.",
)
@dataset_metadata_common_options(all_optional=True)
+@confirmation_skip_option
@click.pass_context
def dataset_version(
ctx: Context,
@@ -192,6 +206,7 @@ def dataset_version(
license: Optional[str],
rights: Optional[str],
version_message: Optional[str],
+ yes: bool,
):
"""Uploads a new version of a Dataset to DAFNI from dataset files
@@ -202,6 +217,7 @@ def dataset_version(
files (List[Path]): Dataset data files
metadata (Optional[Path]): Dataset metadata file
save (Optional[Path]): Path to save existing metadata in for editing
+ yes (bool): Used to skip confirmations before they are displayed
For the rest see dataset_metadata_common_options in options.py
"""
@@ -257,7 +273,7 @@ def dataset_version(
arguments.append(("Dataset metadata file path", metadata))
confirmation_message = "Confirm dataset upload?"
- argument_confirmation(arguments, confirmation_message)
+ argument_confirmation(arguments, confirmation_message, yes=yes)
# Upload all files
upload_dataset(
@@ -285,6 +301,7 @@ def dataset_version(
help="When given will only save the existing metadata to the specified file allowing it to be modified.",
)
@dataset_metadata_common_options(all_optional=True)
+@confirmation_skip_option
@click.pass_context
def dataset_metadata(
ctx: Context,
@@ -310,6 +327,7 @@ def dataset_metadata(
license: Optional[str],
rights: Optional[str],
version_message: Optional[str],
+ yes: bool,
):
"""Uploads a new version of a Dataset's metadata to DAFNI
@@ -319,6 +337,7 @@ def dataset_metadata(
new version to
metadata (Optional[Path]): Dataset metadata file
save (Optional[Path]): Path to save existing metadata in for editing
+ yes (bool): Used to skip confirmations before they are displayed
For the rest see dataset_metadata_common_options in options.py
"""
@@ -374,7 +393,7 @@ def dataset_metadata(
arguments.append(("Dataset metadata file path", metadata))
confirmation_message = "Confirm metadata upload?"
- argument_confirmation(arguments, confirmation_message)
+ argument_confirmation(arguments, confirmation_message, yes=yes)
# Upload
upload_dataset_metadata_version(
@@ -409,12 +428,14 @@ def dataset_metadata(
default=None,
help="Parent workflow ID if this is an updated version of an existing workflow",
)
+@confirmation_skip_option
@click.pass_context
def workflow(
ctx: Context,
definition: Path,
version_message: str,
parent_id: str,
+ yes: bool,
):
"""
Uploads a workflow in JSON form to DAFNI.
@@ -424,6 +445,7 @@ def workflow(
definition (Path): File path to the workflow definition file
version_message (str): Version message to be included with this workflow version
parent_id (str): ID of the parent workflow that this is an update of
+ yes (bool): Used to skip confirmations before they are displayed
"""
arguments = [
("Workflow definition file path", definition),
@@ -435,7 +457,7 @@ def workflow(
additional_message = None
else:
additional_message = ["No parent workflow: new workflow to be created"]
- argument_confirmation(arguments, confirmation_message, additional_message)
+ argument_confirmation(arguments, confirmation_message, additional_message, yes=yes)
# TODO: Validate workflow definition using workflows/validate?
@@ -455,22 +477,25 @@ def workflow(
@click.argument(
"definition", nargs=1, required=True, type=click.Path(exists=True, path_type=Path)
)
+@confirmation_skip_option
@click.pass_context
def workflow_parameter_set(
ctx: Context,
definition: Path,
+ yes: bool,
):
"""Uploads workflow parameter set to DAFNI
Args:
ctx (Context): contains user session for authentication
definition (Path): File path to the parameter set definition file
+ yes (bool): Used to skip confirmations before they are displayed
"""
arguments = [
("Parameter set definition file path", definition),
]
confirmation_message = "Confirm parameter set upload?"
- argument_confirmation(arguments, confirmation_message)
+ argument_confirmation(arguments, confirmation_message, yes=yes)
click.echo("Validating parameter set definition")
try:
diff --git a/dafni_cli/utils.py b/dafni_cli/utils.py
index cc85444f..1af93ff8 100644
--- a/dafni_cli/utils.py
+++ b/dafni_cli/utils.py
@@ -69,6 +69,7 @@ def argument_confirmation(
arguments: List[Tuple[str, str]],
confirmation_message: str,
additional_messages: Optional[List[str]] = None,
+ yes: bool = False,
):
"""Function to display the arguments and options chosen by the user
and ask for confirmation
@@ -80,13 +81,18 @@ def argument_confirmation(
prompts the user to confirm or reject
additional_messages (Optional[List[str]]): Other messages to be added
after options are listed
+ yes (bool): Meant to correspond to the --yes command line option from
+ confirmation_skip_option. A value of True skips the entire
+ confirmation, whereas False will request input from the user
+ after printing out any given messages.
"""
- for name, value in arguments:
- click.echo(f"{name}: {value}")
- if additional_messages:
- for message in additional_messages:
- click.echo(message)
- click.confirm(confirmation_message, abort=True)
+ if not yes:
+ for name, value in arguments:
+ click.echo(f"{name}: {value}")
+ if additional_messages:
+ for message in additional_messages:
+ click.echo(message)
+ click.confirm(confirmation_message, abort=True)
def write_files_to_zip(
| diff --git a/scripts/test_script.py b/scripts/test_script.py
index 4ff5f922..3fb49ac7 100644
--- a/scripts/test_script.py
+++ b/scripts/test_script.py
@@ -64,8 +64,8 @@ def get_snapshot_file_name(self, command_str: str) -> str:
},
# Used for download test
{
- "id": "b71f0880-ff95-4b68-82a1-aafa2e949825",
- "version_id": "c052d9b8-dbca-42b0-85b5-135016a2fbb1",
+ "id": "ff6790db-1602-437f-bd6c-d355ed8f04e2",
+ "version_id": "74d40b2a-030f-4181-ba2c-63c8901df512",
},
],
"workflows": [
diff --git a/test/commands/test_upload.py b/test/commands/test_upload.py
index 1ae188f6..cbb5d7c4 100644
--- a/test/commands/test_upload.py
+++ b/test/commands/test_upload.py
@@ -163,6 +163,53 @@ def test_upload_model_with_parent(
)
self.assertEqual(result.exit_code, 0)
+ def test_upload_model_skipping_confirmation(
+ self,
+ mock_upload_model,
+ mock_DAFNISession,
+ ):
+ """Tests that the 'upload model' command works correctly when
+ given a -y flag to skip the confirmation"""
+
+ # SETUP
+ session = MagicMock()
+ mock_DAFNISession.return_value = session
+ runner = CliRunner()
+ definition_path = "test_definition.yaml"
+ image_path = "test_image.txt"
+ version_message = "version_message"
+
+ # CALL
+ with runner.isolated_filesystem():
+ with open(definition_path, "w", encoding="utf-8") as file:
+ file.write("test definition file")
+ with open(image_path, "w", encoding="utf-8") as file:
+ file.write("test image file")
+ result = runner.invoke(
+ upload.upload,
+ [
+ "model",
+ definition_path,
+ image_path,
+ "--version-message",
+ version_message,
+ "-y",
+ ],
+ )
+
+ # ASSERT
+ mock_DAFNISession.assert_called_once()
+ mock_upload_model.assert_called_with(
+ session,
+ definition_path=Path(definition_path),
+ image_path=Path(image_path),
+ version_message=version_message,
+ parent_id=None,
+ )
+
+ self.assertEqual(result.output, "")
+ self.assertEqual(result.exit_code, 0)
+
def test_upload_model_cancel(
self,
mock_model_upload,
@@ -308,6 +355,39 @@ def test_upload_dataset_with_multiple_files(
)
self.assertEqual(result.exit_code, 0)
+ def test_upload_dataset_skipping_confirmation(
+ self,
+ mock_upload_dataset,
+ mock_DAFNISession,
+ ):
+ """Tests that the 'upload dataset' command works correctly when
+ given a -y flag to skip the confirmation"""
+
+ # SETUP
+ session = MagicMock()
+ mock_DAFNISession.return_value = session
+ runner = CliRunner()
+
+ # CALL
+ with runner.isolated_filesystem():
+ with open("test_metadata.json", "w", encoding="utf-8") as file:
+ file.write("{}")
+ with open("test_dataset.txt", "w", encoding="utf-8") as file:
+ file.write("test dataset file")
+ result = runner.invoke(
+ upload.upload,
+ ["dataset", "test_metadata.json", "test_dataset.txt", "-y"],
+ )
+
+ # ASSERT
+ mock_DAFNISession.assert_called_once()
+ mock_upload_dataset.assert_called_once_with(
+ session, {}, (Path("test_dataset.txt"),)
+ )
+
+ self.assertEqual(result.output, "")
+ self.assertEqual(result.exit_code, 0)
+
def test_upload_dataset_cancel(
self,
mock_upload_dataset,
@@ -587,6 +667,72 @@ def test_upload_dataset_version_saving_existing_metadata(
)
self.assertEqual(result.exit_code, 0)
+ def test_upload_dataset_version_skipping_confirmation(
+ self,
+ mock_modify_dataset_metadata_for_upload,
+ mock_cli_get_latest_dataset_metadata,
+ mock_upload_dataset,
+ mock_DAFNISession,
+ ):
+ """Tests that the 'upload dataset-version' command works correctly when
+ given a -y flag to skip the confirmation"""
+
+ # SETUP
+ session = MagicMock()
+ mock_DAFNISession.return_value = session
+ runner = CliRunner()
+ dataset_version_id = "some-existing-version-id"
+ file_path = "test_dataset.txt"
+ mock_cli_get_latest_dataset_metadata.return_value = TEST_DATASET_METADATA
+ metadata = parse_dataset_metadata(TEST_DATASET_METADATA)
+
+ # CALL
+ with runner.isolated_filesystem():
+ with open("test_dataset.txt", "w", encoding="utf-8") as file:
+ file.write("test dataset file")
+ result = runner.invoke(
+ upload.upload,
+ ["dataset-version", dataset_version_id, file_path, "-y"],
+ )
+
+ # ASSERT
+ mock_DAFNISession.assert_called_once()
+ mock_cli_get_latest_dataset_metadata.assert_called_once_with(
+ session, dataset_version_id
+ )
+ mock_modify_dataset_metadata_for_upload.assert_called_once_with(
+ existing_metadata=TEST_DATASET_METADATA,
+ metadata_path=None,
+ title=None,
+ description=None,
+ subject=None,
+ identifiers=None,
+ themes=None,
+ language=None,
+ keywords=None,
+ standard=None,
+ start_date=None,
+ end_date=None,
+ organisation=None,
+ people=None,
+ created_date=None,
+ update_frequency=None,
+ publisher=None,
+ contact=None,
+ license=None,
+ rights=None,
+ version_message=None,
+ )
+ mock_upload_dataset.assert_called_once_with(
+ session,
+ dataset_id=metadata.dataset_id,
+ metadata=mock_modify_dataset_metadata_for_upload.return_value,
+ file_paths=(Path(file_path),),
+ )
+
+ self.assertEqual(result.output, "")
+ self.assertEqual(result.exit_code, 0)
+
def test_upload_dataset_version_cancel(
self,
mock_modify_dataset_metadata_for_upload,
@@ -1003,6 +1149,69 @@ def test_upload_dataset_metadata_with_metadata_and_all_optional_modifications(
)
self.assertEqual(result.exit_code, 0)
+ def test_upload_dataset_metadata_skipping_confirmation(
+ self,
+ mock_modify_dataset_metadata_for_upload,
+ mock_cli_get_latest_dataset_metadata,
+ mock_upload_dataset_metadata_version,
+ mock_DAFNISession,
+ ):
+ """Tests that the 'upload dataset-metadata' command works correctly when
+ given a -y flag to skip the confirmation"""
+
+ # SETUP
+ session = MagicMock()
+ mock_DAFNISession.return_value = session
+ runner = CliRunner()
+ dataset_version_id = "some-existing-version-id"
+ mock_cli_get_latest_dataset_metadata.return_value = TEST_DATASET_METADATA
+ metadata = parse_dataset_metadata(TEST_DATASET_METADATA)
+
+ # CALL
+ with runner.isolated_filesystem():
+ result = runner.invoke(
+ upload.upload,
+ ["dataset-metadata", dataset_version_id, "-y"],
+ )
+
+ # ASSERT
+ mock_DAFNISession.assert_called_once()
+ mock_cli_get_latest_dataset_metadata.assert_called_once_with(
+ session, dataset_version_id
+ )
+ mock_modify_dataset_metadata_for_upload.assert_called_once_with(
+ existing_metadata=TEST_DATASET_METADATA,
+ metadata_path=None,
+ title=None,
+ description=None,
+ subject=None,
+ identifiers=None,
+ themes=None,
+ language=None,
+ keywords=None,
+ standard=None,
+ start_date=None,
+ end_date=None,
+ organisation=None,
+ people=None,
+ created_date=None,
+ update_frequency=None,
+ publisher=None,
+ contact=None,
+ license=None,
+ rights=None,
+ version_message=None,
+ )
+ mock_upload_dataset_metadata_version.assert_called_once_with(
+ session,
+ dataset_id=metadata.dataset_id,
+ version_id=dataset_version_id,
+ metadata=mock_modify_dataset_metadata_for_upload.return_value,
+ )
+
+ self.assertEqual(result.output, "")
+ self.assertEqual(result.exit_code, 0)
+
def test_upload_metadata_cancel(
self,
mock_modify_dataset_metadata_for_upload,
@@ -1177,6 +1386,51 @@ def test_upload_workflow_with_parent(
)
self.assertEqual(result.exit_code, 0)
+ def test_upload_workflow_skipping_confirmation(
+ self,
+ mock_upload_workflow,
+ mock_DAFNISession,
+ ):
+ """Tests that the 'upload workflow' command works correctly when
+ given a -y flag to skip the confirmation"""
+
+ # SETUP
+ session = MagicMock()
+ mock_DAFNISession.return_value = session
+ runner = CliRunner()
+ version_message = "Initial version"
+ version_id = "version-id"
+ mock_upload_workflow.return_value = {"id": version_id}
+
+ # CALL
+ with runner.isolated_filesystem():
+ with open("test_definition.json", "w", encoding="utf-8") as file:
+ file.write("test definition file")
+ result = runner.invoke(
+ upload.upload,
+ [
+ "workflow",
+ "test_definition.json",
+ "--version-message",
+ version_message,
+ "-y",
+ ],
+ )
+
+ # ASSERT
+ mock_DAFNISession.assert_called_once()
+ mock_upload_workflow.assert_called_once_with(
+ session, Path("test_definition.json"), version_message, None
+ )
+
+ self.assertEqual(
+ result.output,
+ "Uploading workflow\n"
+ "\nUpload successful\n"
+ f"Version ID: {version_id}\n",
+ )
+ self.assertEqual(result.exit_code, 0)
+
def test_upload_workflow_cancel(
self,
mock_upload_workflow,
@@ -1322,6 +1576,49 @@ def test_upload_workflow_parameter_set_validation_error(
)
self.assertEqual(result.exit_code, 1)
+ def test_upload_workflow_parameter_set_skipping_confirmation(
+ self,
+ mock_upload_parameter_set,
+ mock_validate_parameter_set_definition,
+ mock_DAFNISession,
+ ):
+ """Tests that the 'upload workflow-parameter-set' command works
+ correctly when given a -y flag to skip the confirmation"""
+
+ # SETUP
+ session = MagicMock()
+ mock_DAFNISession.return_value = session
+ runner = CliRunner()
+ parameter_set_id = "parameter-set-id"
+ mock_upload_parameter_set.return_value = {"id": parameter_set_id}
+
+ # CALL
+ with runner.isolated_filesystem():
+ with open("test_definition.json", "w", encoding="utf-8") as file:
+ file.write("test definition file")
+ result = runner.invoke(
+ upload.upload,
+ ["workflow-parameter-set", "test_definition.json", "-y"],
+ )
+
+ # ASSERT
+ mock_DAFNISession.assert_called_once()
+ mock_validate_parameter_set_definition.assert_called_once_with(
+ session, Path("test_definition.json")
+ )
+ mock_upload_parameter_set.assert_called_once_with(
+ session, Path("test_definition.json")
+ )
+
+ self.assertEqual(
+ result.output,
+ "Validating parameter set definition\n"
+ "Uploading parameter set\n"
+ "\nUpload successful\n"
+ f"Parameter set ID: {parameter_set_id}\n",
+ )
+ self.assertEqual(result.exit_code, 0)
+
def test_upload_workflow_parameter_set_cancel(
self,
mock_upload_parameter_set,
diff --git a/test/test_utils.py b/test/test_utils.py
index b8bd91e1..eb39b92f 100644
--- a/test/test_utils.py
+++ b/test/test_utils.py
@@ -201,6 +201,24 @@ def test_arguments_are_printed_correctly_with_additional_messages(self, mock_cli
)
mock_click.confirm.assert_called_once_with(confirmation_message, abort=True)
+ def test_nothing_happens_when_yes_is_true(self, mock_click):
+ """Tests that nothing is done when 'yes' is True"""
+ # CALL
+ utils.argument_confirmation(
+ [
+ ("arg 1", "string option"),
+ ("arg 2", "12"),
+ ("arg 3", "{'key': 'value'}"),
+ ],
+ "confirmation message",
+ ["additional message 1", "additional message 2"],
+ yes=True,
+ )
+
+ # ASSERT
+ mock_click.echo.assert_not_called()
+ mock_click.confirm.assert_not_called()
+
class TestWriteFilesToZip(TestCase):
"""Test class to test the write_files_to_zip function"""
| Support non-interactive use
Thanks for the work on this, it looks nicely put together and is already super useful!
I'd like to use this in GitHub Actions and non-interactive scripts.. could there be an escape hatch anywhere the CLI currently prompts for input?
For example:
- I can currently `echo "y" | dafni upload dataset-version ...` to clear the confirmation prompt. Something like `dafni upload dataset-version -y ...` or `DAFNI_FRONTEND=noninteractive dafni upload ...` would be a little cleaner and hopefully more robust.
- Instead of prompting for username/password if the `~/.dafni-cli` token file is not available, the CLI could accept them as arguments, or first check for `DAFNI_USERNAME` and `DAFNI_PASSWORD` or similar environment variables, and finally fall back to an interactive prompt.
| 2023-07-19T08:05:32.000 | -1.0 | [
"test/commands/test_upload.py::TestUploadDataset::test_upload_dataset_skipping_confirmation",
"test/commands/test_upload.py::TestUploadModel::test_upload_model_skipping_confirmation",
"test/test_utils.py::TestArgumentConfirmation::test_nothing_happens_when_yes_is_true",
"test/commands/test_upload.py::TestUploadDatasetVersion::test_upload_dataset_version_skipping_confirmation",
"test/commands/test_upload.py::TestUploadDatasetMetadata::test_upload_dataset_metadata_skipping_confirmation",
"test/commands/test_upload.py::TestUploadWorkflow::test_upload_workflow_skipping_confirmation",
"test/commands/test_upload.py::TestUploadWorkflowParameterSet::test_upload_workflow_parameter_set_skipping_confirmation"
] | [
"test/test_utils.py::TestFormatTable::test_format_table_with_one_max_column_width_without_wrapping",
"test/test_utils.py::TestConstructValidationErrorsFromDict::test_formats_correctly",
"test/test_utils.py::TestIsValidEmailAddress::test_valid_email_returns_true",
"test/test_utils.py::TestFormatTable::test_format_table_with_column_width_with_wrapping",
"test/test_utils.py::TestFormatFileSize::test_empty_string_returned_if_non_integer_or_float_value_given",
"test/commands/test_upload.py::TestUploadDatasetVersion::test_upload_dataset_version",
"test/test_utils.py::TestWriteFilesToZip::test_given_files_written_as_zip_file_to_given_location_with_correct_contents",
"test/commands/test_upload.py::TestUploadDatasetMetadata::test_upload_dataset_metadata_saving_existing_metadata",
"test/commands/test_upload.py::TestUploadDatasetVersion::test_upload_dataset_version_with_multiple_files",
"test/test_utils.py::TestIsValidURL::test_valid_url_returns_false_on_value_error",
"test/commands/test_upload.py::TestUploadWorkflowParameterSet::test_upload_workflow_parameter_set",
"test/test_utils.py::TestIsValidURL::test_invalid_url_returns_false",
"test/commands/test_upload.py::TestUploadDatasetVersion::test_upload_dataset_version_saving_existing_metadata",
"test/commands/test_upload.py::TestUploadDatasetMetadata::test_upload_metadata_cancel",
"test/commands/test_upload.py::TestUploadDatasetVersion::test_upload_dataset_version_cancel",
"test/test_utils.py::TestFormatDataFormat::test_formats_correctly",
"test/commands/test_upload.py::TestUpload::test_session_retrieved_and_set_on_context",
"test/commands/test_upload.py::TestUploadWorkflow::test_upload_workflow",
"test/commands/test_upload.py::TestUploadModel::test_upload_model_with_parent",
"test/commands/test_upload.py::TestUploadDataset::test_upload_dataset",
"test/commands/test_upload.py::TestUploadModel::test_upload_model_cancel",
"test/commands/test_upload.py::TestUploadDatasetVersion::test_upload_dataset_version_with_metadata_and_all_optional_modifications",
"test/test_utils.py::TestFormatDatetime::test_returns_none_when_value_none_and_include_time_true",
"test/test_utils.py::TestFormatDataFormat::test_formats_invalid_values_correctly",
"test/test_utils.py::TestFormatFileSize::test_file_size_processed_correctly",
"test/commands/test_upload.py::TestUploadModel::test_upload_model",
"test/test_utils.py::TestFormatDatetime::test_formats_correctly_when_include_time_false",
"test/commands/test_upload.py::TestUploadWorkflowParameterSet::test_upload_workflow_parameter_set_cancel",
"test/test_utils.py::TestFormatDataFormat::test_formats_none_correctly",
"test/commands/test_upload.py::TestUploadDatasetMetadata::test_upload_dataset_metadata_with_metadata_and_all_optional_modifications",
"test/test_utils.py::TestDataclassFromDict::test_dataclass_from_dict_raises_type_error",
"test/test_utils.py::TestIsValidEmailAddress::test_invalid_email_returns_false",
"test/commands/test_upload.py::TestUploadDataset::test_upload_dataset_with_multiple_files",
"test/test_utils.py::TestProsePrint::test_string_with_line_break_splits_at_line_break",
"test/test_utils.py::TestDataclassFromDict::test_dataclass_from_dict_with_missing_default",
"test/test_utils.py::TestIsValidURL::test_valid_url_returns_true",
"test/commands/test_upload.py::TestUploadWorkflowParameterSet::test_upload_workflow_parameter_set_validation_error",
"test/test_utils.py::TestProsePrint::test_string_without_line_breaks_or_spaces_is_split_correctly_and_printed_sequentially",
"test/test_utils.py::TestArgumentConfirmation::test_arguments_are_printed_correctly_without_additional_messages",
"test/test_utils.py::TestFormatDatetime::test_returns_none_when_value_none_and_include_time_false",
"test/test_utils.py::TestFormatDatetime::test_formats_correctly_when_include_time_true",
"test/test_utils.py::TestDataclassFromDict::test_dataclass_from_dict",
"test/test_utils.py::TestFormatTable::test_format_table_with_column_width_without_wrapping",
"test/test_utils.py::TestFormatTable::test_format_table_with_one_max_column_width_with_wrapping",
"test/commands/test_upload.py::TestUploadWorkflow::test_upload_workflow_with_parent",
"test/test_utils.py::TestProsePrint::test_string_shorter_than_width_prints_as_one_string",
"test/test_utils.py::TestFormatTable::test_format_table_with_no_max_widths",
"test/test_utils.py::TestPrintJSON::test_print_json",
"test/test_utils.py::TestArgumentConfirmation::test_arguments_are_printed_correctly_with_additional_messages",
"test/commands/test_upload.py::TestUploadWorkflow::test_upload_workflow_cancel",
"test/commands/test_upload.py::TestUploadDatasetMetadata::test_upload_dataset_metadata",
"test/commands/test_upload.py::TestUploadDataset::test_upload_dataset_cancel",
"test/test_utils.py::TestProsePrint::test_string_with_space_before_width_but_no_line_break_splits_at_space"
] |
|
PrincetonUniversity/blocklint | 21 | PrincetonUniversity__blocklint-21 | ['20'] | 386b45c72150c41a16f0c14c202191120a0d753e | diff --git a/.gitignore b/.gitignore
index 6f93177..3270e7b 100644
--- a/.gitignore
+++ b/.gitignore
@@ -2,3 +2,4 @@ __pycache__
*.pyc
*.egg-info/
.tox/
+blocklint/version.py
diff --git a/blocklint/main.py b/blocklint/main.py
index d93c8be..6d45f85 100644
--- a/blocklint/main.py
+++ b/blocklint/main.py
@@ -38,7 +38,6 @@ def main(args=None):
with open(file, 'r') as handle:
total_issues += process_file(handle, file, word_checkers,
args['end_pos'])
-
if (args['max_issue_threshold'] is not None
and args['max_issue_threshold'] <= total_issues):
print(("Found {issues} issues, with maximum set to "
@@ -48,10 +47,38 @@ def main(args=None):
sys.exit(1)
+def clean_ignored_docstrings(lines):
+ end_pattern = re.compile(r'(("""|\'\'\')\s*#\s*blocklint:.*pragma\s*$)')
+ lines_to_clear = []
+
+ for i, line in enumerate(lines):
+ match = end_pattern.search(line)
+ if match:
+ start_quote = match.group(1)[:3] # This is either """ or '''
+
+ if start_quote in line[:-(len(match.group(1)))]:
+ # single line docstring
+ lines_to_clear.append((i, i+1))
+ else:
+ # multi line docstring - scan backwards from the current line
+ for j in range(i-1, -1, -1):
+ if start_quote in lines[j]:
+ lines_to_clear.append((j, i+1))
+ break
+
+ for start_line, stop_line in lines_to_clear:
+ for ignored_line in range(start_line, stop_line):
+ lines[ignored_line] = ""
+
+ return lines
+
+
def process_file(input_file, file_name, word_checkers, end_pos):
num_matched = 0
try:
- for i, line in enumerate(input_file, 1):
+ lines = input_file.readlines()
+ lines = clean_ignored_docstrings(lines)
+ for i, line in enumerate(lines, 1):
for match in check_line(line, word_checkers,
file_name, i, end_pos):
num_matched += 1
| diff --git a/tests/docstring_tests/sample_files/docstring_test_file_1.py b/tests/docstring_tests/sample_files/docstring_test_file_1.py
new file mode 100644
index 0000000..2386b84
--- /dev/null
+++ b/tests/docstring_tests/sample_files/docstring_test_file_1.py
@@ -0,0 +1,73 @@
+# multi-line doublequote docstring containing blocked words, not ignored
+def process_data(data):
+ """
+ Process the given data and return a modified version to add to whitelist.
+
+ Parameters:
+ - data: The master data to be processed, can be a list or dict.
+
+ Returns:
+ - A modified version of the input data, where each element or value is doubled.
+ """
+ if isinstance(data, list):
+ return [item * 2 for item in data]
+ elif isinstance(data, dict):
+ return {k: v * 2 for k, v in data.items()}
+ return data
+
+# multi-line singlequote docstring containing blocked words, full docstring ignored
+def compile_allowlist_rules(rules):
+ '''
+ Compile whitelist rules into a usable format.
+
+ Parameters:
+ - rules: A list or dictionary of rules to compile.
+
+ Returns:
+ - A dictionary with each rule mapped to its compiled form. This is a placeholder for actual compilation logic.
+ ''' # blocklint: pragma
+ compiled_rules = {rule: "compiled" for rule in rules}
+ return compiled_rules
+
+# single-line singlequote docstring containing blocked words, not ignored
+def relay_to_slave_nodes(message):
+ '''Relay a message to all slave nodes in the network.'''
+ slave_nodes = ["Node 1", "Node 2", "Node 3"]
+ for node in slave_nodes:
+ print(f"Message '{message}' relayed to {node}")
+
+# single-line doublequote docstring containing blocked words, ignored
+def filter_blocklist_items(items, blocklist):
+ """Filter out items that are in the blacklist.""" # blocklint: pragma
+ filtered_items = [item for item in items if item not in blocklist]
+ return filtered_items
+
+
+# multi-line doublequote raw docstring containing blocked words, full docstring ignored
+def create_generic_function():
+ r"""
+ A generic function that performs a simple operation.
+
+ Side Effects:
+ - Prints a master message indicating a simple operation has been performed.
+ """ # blocklint: pragma
+ print("Performing a simple operation...")
+
+# multi-line singlequote raw docstring containing blocked words, not ignored
+def synchronize_slave_database(database):
+ r"""
+ Synchronize the slave database with the master database.
+
+ Parameters:
+ - database: The slave database to be synchronized. This is a placeholder for the actual database object.
+
+ Side Effects:
+ - Assumes synchronization logic is implemented, updates the slave database to match the master database.
+ """
+ slave_database = database
+ print("Slave database synchronized.")
+
+# single-line doublequote raw docstring containing blocked words, ignored
+def create_generic_function():
+ r"""A generic function that performs a simple whitelist operation.""" # blocklint: pragma
+ print("Performing a simple whitelist operation...") # blocklint: pragma
diff --git a/tests/docstring_tests/sample_files/docstring_test_file_2.py b/tests/docstring_tests/sample_files/docstring_test_file_2.py
new file mode 100644
index 0000000..36e46fb
--- /dev/null
+++ b/tests/docstring_tests/sample_files/docstring_test_file_2.py
@@ -0,0 +1,39 @@
+# check directly before and after ignored docstrings
+
+# blocked word in a comment whitelist
+"""single line docstring blacklist that is ignored""" # blocklint: pragma
+# blocked word on first line master
+
+
+# blocked word slave before a multiline ignored docstring
+""" a test multi line docstring
+what happens if I put
+things before and
+after it
+""" # blocklint: pragma
+# blocked word in a comment blacklist
+
+"""
+A weird example of a docstring
+within a docstring
+''' a docstring here
+here in the middle of
+another blacklist docstring
+'''
+Who would
+even do this?
+""" # blocklint: I don't even own a cat pragma
+
+'''
+Nobody would ever do this
+"""
+but if they did
+it would be a
+masterful
+piece of work
+""" # blocklint: pragma
+and it would still be
+properly caught
+whitelisted
+blaarg
+'''
diff --git a/tests/docstring_tests/test_docstring_processing.py b/tests/docstring_tests/test_docstring_processing.py
new file mode 100644
index 0000000..3a3b6c6
--- /dev/null
+++ b/tests/docstring_tests/test_docstring_processing.py
@@ -0,0 +1,57 @@
+import pytest
+import blocklint.main as bl
+import io
+import sys
+from contextlib import redirect_stdout
+
+
+args = {
+ "blocklist": ["blacklist", "whitelist", "master", "slave"],
+ "wordlist": [],
+ "exactlist": [],
+}
+re_args = bl.generate_re(args)
+
+def capture_stdout(func, *args, **kwargs):
+ """
+ Captures and returns the stdout output of a function call.
+
+ :param func: The function to call.
+ :param args: Positional arguments to pass to the function.
+ :param kwargs: Keyword arguments to pass to the function.
+ :return: A tuple containing the function's result and the captured stdout output.
+ """
+ f = io.StringIO()
+ with redirect_stdout(f):
+ result = func(*args, **kwargs)
+ output = f.getvalue()
+ return result, output
+
+
[email protected](
+ "test_file, test_name, expected_issues_count, expected_output",
+ [
+ (
+ "tests/docstring_tests/sample_files/docstring_test_file_1.py",
+ "docstring_test_1",
+ 14,
+ 'docstring_test_1:4:68: use of "whitelist"\ndocstring_test_1:7:17: use of "master"\ndocstring_test_1:33:14: use of "slave"\ndocstring_test_1:34:31: use of "slave"\ndocstring_test_1:35:5: use of "slave"\ndocstring_test_1:36:17: use of "slave"\ndocstring_test_1:57:17: use of "slave"\ndocstring_test_1:59:45: use of "master"\ndocstring_test_1:59:21: use of "slave"\ndocstring_test_1:62:21: use of "slave"\ndocstring_test_1:65:93: use of "master"\ndocstring_test_1:65:65: use of "slave"\ndocstring_test_1:67:5: use of "slave"\ndocstring_test_1:68:12: use of "slave"\n',
+ ),
+ (
+ "tests/docstring_tests/sample_files/docstring_test_file_2.py",
+ "docstring_test_2",
+ 5,
+ 'docstring_test_2:3:29: use of "whitelist"\ndocstring_test_2:5:30: use of "master"\ndocstring_test_2:8:16: use of "slave"\ndocstring_test_2:14:29: use of "blacklist"\ndocstring_test_2:37:1: use of "whitelist"\n',
+ ),
+ ]
+
+)
+def test_docstring_processing(test_file, test_name, expected_issues_count, expected_output):
+
+ total_issues = 0
+ with open(test_file) as handle:
+ issue_count, output = capture_stdout(bl.process_file, handle, test_name, re_args, False)
+ total_issues += issue_count
+
+ assert total_issues == expected_issues_count
+ assert output == expected_output
| Support single-line ignore for docstrings
Given a docstring that contains a blocked word:
``` python
def my_func():
"""
Function that does stuff. More detail at:
https://github.com/repo/that/still/uses/master/file.md
Returns: other stuff
"""
```
Other linting tools, such as mypy or flake8, allow the `# ignore:` to be placed after the closing `"""` so as to not mess with the docstring.
Current solutions are to put the `# blocklint...` on the same line, which won't work because it shows up in docs, or to ignore the whole file, which misses any future additions.
Please add support for single-line ignore to be placed after a multi-line docstring.
| I like this idea but don't have time to implement. I'd be open to any PRs. | 2024-03-24T16:20:07.000 | -1.0 | [
"tests/docstring_tests/test_docstring_processing.py::test_docstring_processing[tests/docstring_tests/sample_files/docstring_test_file_1.py-docstring_test_1-14-docstring_test_1:4:68:",
"tests/docstring_tests/test_docstring_processing.py::test_docstring_processing[tests/docstring_tests/sample_files/docstring_test_file_2.py-docstring_test_2-5-docstring_test_2:3:29:"
] | [] |
Duke-GCB/DukeDSClient | 317 | Duke-GCB__DukeDSClient-317 | ['316'] | 6df1eb9f210f98d4ff826f89f89309f48c4e8c5b | diff --git a/ddsc/config.py b/ddsc/config.py
index f74ab5d4..582c9aa8 100644
--- a/ddsc/config.py
+++ b/ddsc/config.py
@@ -88,7 +88,11 @@ def add_properties(self, filename):
filename = os.path.expanduser(filename)
if os.path.exists(filename):
with open(filename, 'r') as yaml_file:
- self.update_properties(yaml.safe_load(yaml_file))
+ config_data = yaml.safe_load(yaml_file)
+ if config_data:
+ self.update_properties(config_data)
+ else:
+ raise ValueError("Error: Empty config file {}".format(filename))
def update_properties(self, new_values):
"""
| diff --git a/ddsc/tests/test_config.py b/ddsc/tests/test_config.py
index 58e21ad1..073ad896 100644
--- a/ddsc/tests/test_config.py
+++ b/ddsc/tests/test_config.py
@@ -2,7 +2,7 @@
import math
import ddsc.config
import multiprocessing
-from mock.mock import patch
+from mock.mock import patch, mock_open
class TestConfig(TestCase):
@@ -159,3 +159,13 @@ def test_storage_provider_id(self, mock_os):
}
config.update_properties(some_config)
self.assertEqual(config.storage_provider_id, '123456')
+
+ @patch('ddsc.config.os')
+ def test_add_properties_empty_file(self, mock_os):
+ mock_os.path.expanduser.return_value = '/home/user/.ddsclient'
+ mock_os.path.exists.return_value = True
+ config = ddsc.config.Config()
+ with self.assertRaises(ValueError) as raised_exception:
+ with patch('builtins.open', mock_open(read_data='')):
+ config.add_properties('~/.ddsclient')
+ self.assertEqual(str(raised_exception.exception), 'Error: Empty config file /home/user/.ddsclient')
| Fix error when the .ddsclient config file is empty
When a the .ddsclient config file is empty the following error is produced when running a command such as `ddsclient list`:
```
type object argument after ** must be a mapping, not NoneType
```
See #315 for more
| 2020-11-20T14:09:53.000 | -1.0 | [
"ddsc/tests/test_config.py::TestConfig::test_add_properties_empty_file"
] | [
"ddsc/tests/test_config.py::TestConfig::test_empty_config",
"ddsc/tests/test_config.py::TestConfig::test_create_config_with_env_set",
"ddsc/tests/test_config.py::TestConfig::test_MB_chunk_convert",
"ddsc/tests/test_config.py::TestConfig::test_get_user_config_filename",
"ddsc/tests/test_config.py::TestConfig::test_parse_bytes_str",
"ddsc/tests/test_config.py::TestConfig::test_create_config_no_env_set",
"ddsc/tests/test_config.py::TestConfig::test_storage_provider_id",
"ddsc/tests/test_config.py::TestConfig::test_global_then_local",
"ddsc/tests/test_config.py::TestConfig::test_get_user_config_get_page_size",
"ddsc/tests/test_config.py::TestConfig::test_get_portal_url_base",
"ddsc/tests/test_config.py::TestConfig::test_default_num_workers"
] |
End of preview. Expand
in Data Studio
No dataset card yet
- Downloads last month
- 11