instance_id
stringlengths 10
57
| patch
stringlengths 261
37.7k
| repo
stringlengths 7
53
| base_commit
stringlengths 40
40
| hints_text
stringclasses 301
values | test_patch
stringlengths 212
2.22M
| problem_statement
stringlengths 23
37.7k
| version
int64 0
0
| environment_setup_commit
stringclasses 89
values | FAIL_TO_PASS
sequencelengths 1
4.94k
| PASS_TO_PASS
sequencelengths 0
7.82k
| meta
dict | created_at
unknown | license
stringclasses 8
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
DiamondLightSource__ispyb-api-46 | diff --git a/conf/config.example.cfg b/conf/config.example.cfg
index bd9d446..d1d5272 100644
--- a/conf/config.example.cfg
+++ b/conf/config.example.cfg
@@ -5,4 +5,3 @@ pw =
host = localhost
port = 3306
db = ispybtest
-conn_inactivity = 360
diff --git a/ispyb/__init__.py b/ispyb/__init__.py
index 3073240..377498b 100644
--- a/ispyb/__init__.py
+++ b/ispyb/__init__.py
@@ -6,7 +6,7 @@ except ImportError:
import ConfigParser as configparser
import logging
-__version__ = '4.11.1'
+__version__ = '4.12.0'
_log = logging.getLogger('ispyb')
diff --git a/ispyb/connector/mysqlsp/main.py b/ispyb/connector/mysqlsp/main.py
index f39556a..e5ba3fd 100644
--- a/ispyb/connector/mysqlsp/main.py
+++ b/ispyb/connector/mysqlsp/main.py
@@ -1,9 +1,9 @@
-import datetime
+from __future__ import absolute_import, division, print_function
+
import os
import sys
-import traceback
import threading
-import time
+import traceback
import ispyb.interface.connection
import mysql.connector
@@ -17,7 +17,7 @@ class ISPyBMySQLSPConnector(ispyb.interface.connection.IF):
def __init__(self, user=None, pw=None, host='localhost', db=None, port=3306, conn_inactivity=360):
self.lock = threading.Lock()
- self.connect(user=user, pw=pw, host=host, db=db, port=port, conn_inactivity=conn_inactivity)
+ self.connect(user=user, pw=pw, host=host, db=db, port=port)
def __enter__(self):
if hasattr(self, 'conn') and self.conn is not None:
@@ -30,23 +30,15 @@ class ISPyBMySQLSPConnector(ispyb.interface.connection.IF):
def connect(self, user=None, pw=None, host='localhost', db=None, port=3306, conn_inactivity=360):
self.disconnect()
- self.user = user
- self.pw = pw
- self.host = host
- self.db = db
- self.port = port
- self.conn_inactivity = int(conn_inactivity)
self.conn = mysql.connector.connect(user=user,
password=pw,
host=host,
database=db,
port=int(port))
- if self.conn is not None:
- self.conn.autocommit=True
- else:
- raise ISPyBConnectionException
- self.last_activity_ts = time.time()
+ if not self.conn:
+ raise ISPyBConnectionException('Could not connect to database')
+ self.conn.autocommit = True
def __del__(self):
self.disconnect()
@@ -61,17 +53,13 @@ class ISPyBMySQLSPConnector(ispyb.interface.connection.IF):
return 'ispyb.sp'
def create_cursor(self, dictionary=False):
- if time.time() - self.last_activity_ts > self.conn_inactivity:
- # re-connect:
- self.connect(self.user, self.pw, self.host, self.db, self.port)
- self.last_activity_ts = time.time()
- if self.conn is None:
- raise ISPyBConnectionException
-
- cursor = self.conn.cursor(dictionary=dictionary)
- if cursor is None:
- raise ISPyBConnectionException
- return cursor
+ if not self.conn:
+ raise ISPyBConnectionException('Not connected to database')
+ self.conn.ping(reconnect=True)
+ cursor = self.conn.cursor(dictionary=dictionary)
+ if not cursor:
+ raise ISPyBConnectionException('Could not create database cursor')
+ return cursor
def call_sp_write(self, procname, args):
with self.lock:
diff --git a/ispyb/model/__future__.py b/ispyb/model/__future__.py
index f69d9e2..0f9367a 100644
--- a/ispyb/model/__future__.py
+++ b/ispyb/model/__future__.py
@@ -15,7 +15,7 @@ import mysql.connector
_db_config = None
-def enable(configuration_file):
+def enable(configuration_file, section='ispyb'):
'''Enable access to features that are currently under development.'''
global _db, _db_cc, _db_config
@@ -37,19 +37,46 @@ def enable(configuration_file):
cfgparser = configparser.RawConfigParser()
if not cfgparser.read(configuration_file):
raise RuntimeError('Could not read from configuration file %s' % configuration_file)
- cfgsection = dict(cfgparser.items('ispyb'))
+ cfgsection = dict(cfgparser.items(section))
host = cfgsection.get('host')
port = cfgsection.get('port', 3306)
- database = cfgsection.get('database')
- username = cfgsection.get('username')
- password = cfgsection.get('password')
+ database = cfgsection.get('database', cfgsection.get('db'))
+ username = cfgsection.get('username', cfgsection.get('user'))
+ password = cfgsection.get('password', cfgsection.get('pw'))
# Open a direct MySQL connection
_db = mysql.connector.connect(host=host, port=port, user=username, password=password, database=database)
_db.autocommit = True
- _db_cc = DictionaryContextcursorFactory(_db.cursor)
_db_config = configuration_file
+ class DictionaryCursorContextManager(object):
+ '''This class creates dictionary cursors for mysql.connector connections.
+ By using a context manager it is ensured that cursors are closed
+ immediately after use.
+ Cursors created with this context manager return results as a dictionary
+ and offer a .run() function, which is an alias to .execute that accepts
+ query parameters as function parameters rather than a list.
+ '''
+
+ def __enter__(cm):
+ '''Enter context. Ensure the database is alive and return a cursor
+ with an extra .run() function.'''
+ _db.ping(reconnect=True)
+ cm.cursor = _db.cursor(dictionary=True)
+
+ def flat_execute(stmt, *parameters):
+ '''Pass all given function parameters as a list to the existing
+ .execute() function.'''
+ return cm.cursor.execute(stmt, parameters)
+ setattr(cm.cursor, 'run', flat_execute)
+ return cm.cursor
+
+ def __exit__(cm, *args):
+ '''Leave context. Close cursor. Destroy reference.'''
+ cm.cursor.close()
+ cm.cursor = None
+ _db_cc = DictionaryCursorContextManager
+
import ispyb.model.datacollection
ispyb.model.datacollection.DataCollection.integrations = _get_linked_autoprocintegration_for_dc
import ispyb.model.gridinfo
@@ -57,52 +84,6 @@ def enable(configuration_file):
import ispyb.model.processingprogram
ispyb.model.processingprogram.ProcessingProgram.reload = _get_autoprocprogram
-class DictionaryContextcursorFactory(object):
- '''This class creates dictionary context manager objects for mysql.connector
- cursors. By using a context manager it is ensured that cursors are
- closed immediately after use.
- Context managers created via this factory return results as a dictionary
- by default, and offer a .run() function, which is an alias to .execute
- that accepts query parameters as function parameters rather than a list.
- '''
-
- def __init__(self, cursor_factory_function):
- '''Set up the context manager factory.'''
-
- class ContextManager(object):
- '''The context manager object which is actually used in the
- with .. as ..:
- clause.'''
-
- def __init__(cm, parameters):
- '''Store any constructor parameters, given as dictionary, so that they
- can be passed to the cursor factory later.'''
- cm.cursorparams = { 'dictionary': True }
- cm.cursorparams.update(parameters)
-
- def __enter__(cm):
- '''Enter context. Instantiate and return the actual cursor using the
- given constructor, parameters, and an extra .run() function.'''
- cm.cursor = cursor_factory_function(**cm.cursorparams)
-
- def flat_execute(stmt, *parameters):
- '''Pass all given function parameters as a list to the existing
- .execute() function.'''
- return cm.cursor.execute(stmt, parameters)
- setattr(cm.cursor, 'run', flat_execute)
- return cm.cursor
-
- def __exit__(cm, *args):
- '''Leave context. Close cursor. Destroy reference.'''
- cm.cursor.close()
- cm.cursor = None
-
- self._contextmanager_factory = ContextManager
-
- def __call__(self, **parameters):
- '''Creates and returns a context manager object.'''
- return self._contextmanager_factory(parameters)
-
def _get_gridinfo(self):
# https://jira.diamond.ac.uk/browse/MXSW-1173
with _db_cc() as cursor:
diff --git a/ispyb/model/integration.py b/ispyb/model/integration.py
index 16b57a2..ef33a7d 100644
--- a/ispyb/model/integration.py
+++ b/ispyb/model/integration.py
@@ -50,6 +50,12 @@ class IntegrationResult(ispyb.model.DBCache):
self._cache_dc = self._db.get_data_collection(self.DCID)
return self._cache_dc
+ @property
+ def unit_cell(self):
+ '''Returns the unit cell model'''
+ return ispyb.model.integration.UnitCell(self._data['cell_a'], self._data['cell_b'],self._data['cell_c'],
+ self._data['cell_alpha'], self._data['cell_beta'], self._data['cell_gamma'])
+
@property
def APIID(self):
'''Returns the AutoProcIntegrationID.'''
@@ -85,3 +91,68 @@ ispyb.model.add_properties(IntegrationResult, (
('detector_distance', 'refinedDetectorDistance'),
('timestamp', 'recordTimeStamp'),
))
+
+class UnitCell():
+ '''An object representing the parameters of the unit cell I.e unit cell edges and angles
+ '''
+
+ def __init__(self, a, b, c, alpha, beta, gamma):
+ '''Unit cell object
+
+ :param a: Edge a
+ :param b: Edge b
+ :param c: Edge c
+ :param alpha: Angle alpha
+ :param beta: Angle beta
+ :param gamma: Angle gamma
+ :return: A unitcell object
+ '''
+ self._a = a
+ self._b = b
+ self._c = c
+ self._alpha = alpha
+ self._beta = beta
+ self._gamma = gamma
+
+
+ @property
+ def a(self):
+ '''Returns dimension a of unit cell in Angstroms'''
+ return self._a
+
+ @property
+ def b(self):
+ '''Returns dimension b of unit cell in Angstroms'''
+ return self._b
+
+ @property
+ def c(self):
+ '''Returns dimension c of unit cell in Angstroms'''
+ return self._c
+
+ @property
+ def alpha(self):
+ '''Returns angle alpha of unit cell'''
+ return self._alpha
+
+ @property
+ def beta(self):
+ '''Returns angle beta of unit cell'''
+ return self._beta
+
+ @property
+ def gamma(self):
+ '''Returns angle gamma of unit cell'''
+ return self._gamma
+
+ def __str__(self):
+ '''Returns a pretty-printed object representation.'''
+ return ('\n'.join((
+ ' a : {uc.a}',
+ ' b : {uc.b}',
+ ' c : {uc.c}',
+ ' alpha : {uc.alpha}',
+ ' beta : {uc.beta}',
+ ' gamma : {uc.gamma}',
+ ))).format(uc=self)
+
| DiamondLightSource/ispyb-api | 09dd224f8a861ab0019b223e1dfb7bcbbc5bfab2 | diff --git a/ispyb/model/test_unitcell.py b/ispyb/model/test_unitcell.py
new file mode 100644
index 0000000..e499ab4
--- /dev/null
+++ b/ispyb/model/test_unitcell.py
@@ -0,0 +1,12 @@
+from __future__ import absolute_import, division, print_function
+import ispyb.model.integration
+
+
+def test_value_in_equals_value_out():
+ uc = ispyb.model.integration.UnitCell(10,20,30,40,50,60)
+ assert uc.a == 10
+ assert uc.b == 20
+ assert uc.c == 30
+ assert uc.alpha == 40
+ assert uc.beta == 50
+ assert uc.gamma == 60
diff --git a/tests/conftest.py b/tests/conftest.py
index 6f3fc3f..75a4f92 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -4,6 +4,7 @@ from __future__ import absolute_import, division, print_function
import os
+import ispyb
import pytest
@pytest.fixture
diff --git a/tests/test_misc.py b/tests/test_misc.py
index 07977e1..522d16f 100644
--- a/tests/test_misc.py
+++ b/tests/test_misc.py
@@ -3,7 +3,10 @@ from __future__ import absolute_import, division, print_function
import threading
import context
+import ispyb
import ispyb.exception
+import ispyb.model.__future__
+import mysql.connector.errors
import pytest
def test_multi_threads_upsert(testconfig):
@@ -42,3 +45,45 @@ def test_retrieve_failure(testconfig):
with ispyb.open(testconfig) as conn:
with pytest.raises(ispyb.exception.ISPyBNoResultException):
rs = conn.mx_acquisition.retrieve_data_collection_main(0)
+
+def test_database_reconnects_on_connection_failure(testconfig, testdb):
+ ispyb.model.__future__.enable(testconfig, section='ispyb_mysql_sp')
+
+ # Create minimal data collection and data collection group for test
+ params = testdb.mx_acquisition.get_data_collection_group_params()
+ params['parentid'] = 55168
+ dcgid = testdb.mx_acquisition.insert_data_collection_group(list(params.values()))
+ assert dcgid, "Could not create dummy data collection group"
+ params = testdb.mx_acquisition.get_data_collection_params()
+ params['parentid'] = dcgid
+ dcid = testdb.mx_acquisition.insert_data_collection(list(params.values()))
+ assert dcid, "Could not create dummy data collection"
+
+ # Test the database connections
+ # This goes from DCID to DCGID using the default connection,
+ # and looks into the GridInfo table using the __future__ connection.
+ assert bool(testdb.get_data_collection(dcid).group.gridinfo) is False
+
+ fconn = ispyb.model.__future__._db
+ iconn = testdb.conn
+
+ # Break both connections from the server side
+ c = iconn.cursor()
+ with pytest.raises(mysql.connector.errors.DatabaseError):
+ c.execute("KILL CONNECTION_ID();")
+ c.close()
+
+ c = fconn.cursor()
+ with pytest.raises(mysql.connector.errors.DatabaseError):
+ c.execute("KILL CONNECTION_ID();")
+ c.close()
+
+ # Confirm both connections are broken
+ with pytest.raises(mysql.connector.errors.OperationalError):
+ iconn.cursor()
+
+ with pytest.raises(mysql.connector.errors.OperationalError):
+ fconn.cursor()
+
+ # Test implicit reconnect
+ assert bool(testdb.get_data_collection(dcid).group.gridinfo) is False
| Protection against DB connection loss
Should handle database connection loss by catching the exception and attempt reconnecting.
Should possibly 'ping' at set intervals to keep the connection alive. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"ispyb/model/test_unitcell.py::test_value_in_equals_value_out"
] | [] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2018-09-24T08:10:25Z" | apache-2.0 |
|
DinoTools__python-overpy-64 | diff --git a/overpy/__init__.py b/overpy/__init__.py
index 13de583..377c28d 100644
--- a/overpy/__init__.py
+++ b/overpy/__init__.py
@@ -349,23 +349,39 @@ class Result(object):
return result
@classmethod
- def from_xml(cls, data, api=None, parser=XML_PARSER_SAX):
+ def from_xml(cls, data, api=None, parser=None):
"""
- Create a new instance and load data from xml object.
+ Create a new instance and load data from xml data or object.
+
+ .. note::
+ If parser is set to None, the functions tries to find the best parse.
+ By default the SAX parser is chosen if a string is provided as data.
+ The parser is set to DOM if an xml.etree.ElementTree.Element is provided as data value.
:param data: Root element
- :type data: xml.etree.ElementTree.Element
- :param api:
+ :type data: str | xml.etree.ElementTree.Element
+ :param api: The instance to query additional information if required.
:type api: Overpass
- :param parser: Specify the parser to use(DOM or SAX)
- :type parser: Integer
+ :param parser: Specify the parser to use(DOM or SAX)(Default: None = autodetect, defaults to SAX)
+ :type parser: Integer | None
:return: New instance of Result object
:rtype: Result
"""
+ if parser is None:
+ if isinstance(data, str):
+ parser = XML_PARSER_SAX
+ else:
+ parser = XML_PARSER_DOM
+
result = cls(api=api)
if parser == XML_PARSER_DOM:
import xml.etree.ElementTree as ET
- root = ET.fromstring(data)
+ if isinstance(data, str):
+ root = ET.fromstring(data)
+ elif isinstance(data, ET.Element):
+ root = data
+ else:
+ raise exception.OverPyException("Unable to detect data type.")
for elem_cls in [Node, Way, Relation, Area]:
for child in root:
| DinoTools/python-overpy | d49ad8080ff9e9da3081a240380915b159172a87 | diff --git a/tests/test_xml.py b/tests/test_xml.py
index d81f003..e414ad4 100644
--- a/tests/test_xml.py
+++ b/tests/test_xml.py
@@ -171,6 +171,28 @@ class TestDataError(object):
overpy.Way.from_xml(node)
+class TestParser(BaseTestNodes):
+ def test_exception(self):
+ with pytest.raises(overpy.exception.OverPyException):
+ overpy.Result.from_xml(123)
+
+ def test_xml_element(self):
+ import xml.etree.ElementTree as ET
+ data = read_file("xml/node-01.xml")
+ root = ET.fromstring(data)
+ result = overpy.Result.from_xml(root)
+
+ assert isinstance(result, overpy.Result)
+ self._test_node01(result)
+
+ def test_xml_autodetect_parser(self):
+ data = read_file("xml/node-01.xml")
+ result = overpy.Result.from_xml(data)
+
+ assert isinstance(result, overpy.Result)
+ self._test_node01(result)
+
+
class TestRemark(object):
def test_remark_runtime_error(self):
api = overpy.Overpass()
| Result.from_xml data argument has a wrong type doc
Passing Element as a data argument to Result.from_xml() as docstring suggests raises Exception.
```
>>> overpy.Result.from_xml(xml.etree.ElementTree.fromstring("<osm />"))
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/home/w/osm-borders/lib/python3.5/site-packages/overpy/__init__.py", line 310, in from_xml
source = StringIO(data)
TypeError: initial_value must be str or None, not xml.etree.ElementTree.Element
```
It looks like it expects string right now:
```
>>> overpy.Result.from_xml("<osm />")
<overpy.Result object at 0x7faf632b2eb8>
```
My python version is:
$ python --version
Python 3.5.2
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=16.10
DISTRIB_CODENAME=yakkety
DISTRIB_DESCRIPTION="Ubuntu 16.10"
(My guess that Ubuntu's Python 3.5.2 is far more similar to Python 3.6 than to 3.5) | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_xml.py::TestParser::test_exception",
"tests/test_xml.py::TestParser::test_xml_element"
] | [
"tests/test_xml.py::TestAreas::test_node01",
"tests/test_xml.py::TestNodes::test_node01",
"tests/test_xml.py::TestRelation::test_relation01",
"tests/test_xml.py::TestRelation::test_relation02",
"tests/test_xml.py::TestRelation::test_relation03",
"tests/test_xml.py::TestRelation::test_relation04",
"tests/test_xml.py::TestWay::test_way01",
"tests/test_xml.py::TestWay::test_way02",
"tests/test_xml.py::TestWay::test_way03",
"tests/test_xml.py::TestWay::test_way04",
"tests/test_xml.py::TestDataError::test_element_wrong_type",
"tests/test_xml.py::TestDataError::test_node_missing_data",
"tests/test_xml.py::TestDataError::test_relation_missing_data",
"tests/test_xml.py::TestDataError::test_way_missing_data",
"tests/test_xml.py::TestParser::test_xml_autodetect_parser",
"tests/test_xml.py::TestRemark::test_remark_runtime_error",
"tests/test_xml.py::TestRemark::test_remark_runtime_remark",
"tests/test_xml.py::TestRemark::test_remark_unknown"
] | {
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
} | "2017-04-07T12:09:15Z" | mit |
|
Dorthu__openapi3-76 | diff --git a/openapi3/openapi.py b/openapi3/openapi.py
index 5b79b14..0b2c753 100644
--- a/openapi3/openapi.py
+++ b/openapi3/openapi.py
@@ -101,16 +101,27 @@ class OpenAPI(ObjectBase):
node = self
for part in path:
+ part = part.replace('~1','/').replace('~0','~')
if isinstance(node, Map):
- if part not in node: # pylint: disable=unsupported-membership-test
+ try:
+ node = node[part]
+ except KeyError:
err_msg = "Invalid path {} in Reference".format(path)
raise ReferenceResolutionError(err_msg)
- node = node.get(part)
else:
- if not hasattr(node, part):
+ try:
+ ipart = int(part)
+ except ValueError:
+ pass
+ else:
+ if ipart>=0 and ipart<len(node):
+ node = node[ipart]
+ continue
+ try:
+ node = getattr(node, part)
+ except AttributeError:
err_msg = "Invalid path {} in Reference".format(path)
raise ReferenceResolutionError(err_msg)
- node = getattr(node, part)
return node
diff --git a/setup.py b/setup.py
index 16d07b3..e5955e9 100755
--- a/setup.py
+++ b/setup.py
@@ -22,5 +22,7 @@ setup(
packages=["openapi3"],
license="BSD 3-Clause License",
install_requires=["PyYaml", "requests"],
- tests_require=["pytest", "pytest-asyncio", "uvloop", "hypercorn", "pydantic", "fastapi"],
+ extras_require={
+ "test": ["pytest", "pytest-asyncio==0.16", "uvloop", "hypercorn", "pydantic", "fastapi"],
+ },
)
| Dorthu/openapi3 | 0e02198948258b69e666f53aa2b22fcf4da62f97 | diff --git a/tests/conftest.py b/tests/conftest.py
index 5a10c1b..b4e83cf 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -178,3 +178,11 @@ def schema_without_properties():
Provides a spec that includes a schema with no properties defined
"""
yield _get_parsed_yaml("schema-without-properties.yaml")
+
+
[email protected]
+def rfc_6901():
+ """
+ Provides a spec that includes RFC 6901 escape codes in ref paths
+ """
+ yield _get_parsed_yaml("rfc_6901.yaml")
diff --git a/tests/fixtures/rfc_6901.yaml b/tests/fixtures/rfc_6901.yaml
new file mode 100644
index 0000000..3b85030
--- /dev/null
+++ b/tests/fixtures/rfc_6901.yaml
@@ -0,0 +1,79 @@
+# this schema has refs whose paths include the escaped `~` and `/` characters
+# (escaped as ~0 and ~1 respectively). This also purposefully includes the ~01
+# escape sequence to ensure parsing ends in `~1` and not `/`
+openapi: "3.1.0"
+info:
+ version: 1.0.0
+ title: RFC 6901 Test
+paths:
+ /ref-test:
+ parameters:
+ - $ref: '#/paths/~1parameters-holder/parameters/1'
+ get:
+ operationId: refTestGet
+ responses:
+ '200':
+ description: Test
+ content:
+ application/json:
+ schema:
+ description: |
+ References all other fields in components/schemas to ensure all references
+ are tested.
+ type: object
+ properties:
+ one:
+ $ref: '#/components/schemas/test~1one'
+ two:
+ $ref: '#/components/schemas/test~0two'
+ three:
+ $ref: '#/components/schemas/test~01three'
+ four:
+ $ref: '#/components/schemas/01/properties/example'
+ /parameters-holder:
+ parameters:
+ - name: example
+ in: query
+ schema:
+ type: int
+ - name: example2
+ in: query
+ schema:
+ type: int
+ get:
+ operationId: parametersHolderGet
+ responses:
+ '200':
+ description: Placeholder
+ content:
+ application/json:
+ schema:
+ type: object
+components:
+ schemas:
+ test/one:
+ description: |
+ Tests that refs can reference paths with a `/` character; this should be
+ escaped as `#/components/schemas/test~1one`
+ type: string
+ test~two:
+ description: |
+ Tests that refs can reference paths with a `~` character; this should be
+ escaped as `#/components/schemas/test~0two`
+ type: int
+ test~1three:
+ description: |
+ Tests that refs can reference paths with a ~1 sequence in them; this should
+ be escaped as `#/components/schemas/test~01three`
+ type: array
+ items:
+ type: string
+ '01':
+ description: |
+ Tests that paths parsed using integer-like segments are handled correctly.
+ This will be referenced as `#/components/schemas/0/properties/example`
+ type: object
+ properties:
+ example:
+ type: string
+ example: it worked
diff --git a/tests/ref_test.py b/tests/ref_test.py
index f7999be..3a15f5f 100644
--- a/tests/ref_test.py
+++ b/tests/ref_test.py
@@ -84,7 +84,7 @@ def test_ref_allof_handling(with_ref_allof):
spec = OpenAPI(with_ref_allof)
referenced_schema = spec.components.schemas['Example']
- # this should have only one property; the allOf from
+ # this should have only one property; the allOf from
# paths['/allof-example']get.responses['200'].content['application/json'].schema
# should not modify the component
assert len(referenced_schema.properties) == 1, \
@@ -92,3 +92,26 @@ def test_ref_allof_handling(with_ref_allof):
len(referenced_schema.properties),
", ".join(referenced_schema.properties.keys()),
)
+
+def test_ref_6901_refs(rfc_6901):
+ """
+ Tests that RFC 6901 escape codes, such as ~0 and ~1, are pared correctly
+ """
+ spec = OpenAPI(rfc_6901, validate=True)
+ assert len(spec.errors()) == 0, spec.errors()
+
+ # spec parsed, make sure our refs got the right values
+ path = spec.paths['/ref-test']
+ response = path.get.responses['200'].content['application/json'].schema
+
+ assert response.properties['one'].type == 'string'
+ assert response.properties['two'].type == 'int'
+ assert response.properties['three'].type == 'array'
+
+ # ensure the integer path components parsed as expected too
+ assert response.properties['four'].type == 'string'
+ assert response.properties['four'].example == 'it worked'
+
+ # ensure integer path parsing does work as expected
+ assert len(path.parameters) == 1
+ assert path.parameters[0].name == 'example2'
| Testing doesn't work
```
$ PYTHONPATH=. python3 -mpytest -sxv tests/
Test session starts (platform: linux, Python 3.9.9, pytest 6.0.2, pytest-sugar 0.9.4)
cachedir: .pytest_cache
rootdir: /src/openapi3
plugins: asyncio-0.14.0, xdist-2.2.0, gc-0.0.1, sugar-0.9.4, cov-2.10.1, anyio-3.3.0.1, forked-1.3.0, mock-1.10.4
collecting ...
βββββββββββββββββββββββββββββββββββ ERROR at setup of test_createPet ββββββββββββββββββββββββββββββββββββ
ScopeMismatch: You tried to access the 'function' scoped fixture 'unused_tcp_port_factory' with a 'session' scoped request object, involved factories
tests/fastapi_test.py:30: def server(event_loop, config)
tests/fastapi_test.py:17: def config(unused_tcp_port_factory)
../../usr/lib/python3/dist-packages/pytest_asyncio/plugin.py:225: def unused_tcp_port_factory()
4% β
======================================== short test summary info ========================================
FAILED tests/fastapi_test.py::test_createPet
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! stopping after 1 failures !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Results (0.22s):
1 error
``` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/ref_test.py::test_ref_6901_refs"
] | [
"tests/ref_test.py::test_ref_resolution",
"tests/ref_test.py::test_allOf_resolution",
"tests/ref_test.py::test_resolving_nested_allof_ref",
"tests/ref_test.py::test_ref_allof_handling"
] | {
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2022-03-08T13:18:13Z" | bsd-3-clause |
|
Dorthu__openapi3-94 | diff --git a/openapi3/schemas.py b/openapi3/schemas.py
index 0796552..d454e47 100644
--- a/openapi3/schemas.py
+++ b/openapi3/schemas.py
@@ -8,6 +8,7 @@ TYPE_LOOKUP = {
"object": dict,
"string": str,
"boolean": bool,
+ "number": float,
}
| Dorthu/openapi3 | fba9f2785a822e951e9e13f44486840f4e03d80e | diff --git a/tests/conftest.py b/tests/conftest.py
index 7dffe2a..ffa7925 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -213,6 +213,7 @@ def with_external_docs():
@pytest.fixture
+
def with_openapi_310_references():
"""
Provides a spec with OpenAPI 3.1.0 expanded Reference Objects
@@ -226,3 +227,11 @@ def with_reference_referencing_reference():
Provides a spec with a reference that references a reference
"""
yield _get_parsed_yaml("reference-reference-reference.yaml")
+
+
[email protected]
+def with_all_default_types():
+ """
+ Provides a spec with defaults defined in various schemas of all types
+ """
+ yield _get_parsed_yaml("with_all_default_types.yaml")
diff --git a/tests/fixtures/with_all_default_types.yaml b/tests/fixtures/with_all_default_types.yaml
new file mode 100644
index 0000000..16b36e4
--- /dev/null
+++ b/tests/fixtures/with_all_default_types.yaml
@@ -0,0 +1,55 @@
+openapi: 3.0.0
+info:
+ title: Numeric default parameter
+ version: 0.0.1
+paths:
+ /example:
+ get:
+ requestBody:
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ int:
+ type: integer
+ default: 0
+ str:
+ type: string
+ default: "test"
+ bool:
+ type: boolean
+ default: true
+ float:
+ type: number
+ default: 0.1
+ required: true
+ responses:
+ 200:
+ description: it worked
+components:
+ parameters:
+ int:
+ name: exampleParam
+ in: query
+ schema:
+ type: integer
+ default: 0
+ str:
+ name: exampleParam2
+ in: query
+ schema:
+ type: string
+ default: "test"
+ bool:
+ name: exampleParam3
+ in: query
+ schema:
+ type: boolean
+ default: true
+ float:
+ name: exampleParam4
+ in: query
+ schema:
+ type: number
+ default: 0.1
diff --git a/tests/parsing_test.py b/tests/parsing_test.py
index 8ad8704..7cf1919 100644
--- a/tests/parsing_test.py
+++ b/tests/parsing_test.py
@@ -159,3 +159,20 @@ def test_external_docs(with_external_docs):
assert spec.tags[0].externalDocs.url == "http://example.org/tags"
assert spec.paths["/example"].get.externalDocs.url == "http://example.org/operation"
assert spec.paths["/example"].get.responses['200'].content['application/json'].schema.externalDocs.url == "http://example.org/schema"
+
+
+def test_schema_default_types(with_all_default_types):
+ """
+ Tests that schemas accept defaults in their defined types
+ """
+ spec = OpenAPI(with_all_default_types)
+ assert spec.components.parameters["int"].schema.default == 0
+ assert spec.components.parameters["str"].schema.default == "test"
+ assert spec.components.parameters["bool"].schema.default == True
+ assert spec.components.parameters["float"].schema.default == 0.1
+
+ schema = spec.paths["/example"].get.requestBody.content["application/json"].schema
+ assert schema.properties["int"].default == 0
+ assert schema.properties["str"].default == "test"
+ assert schema.properties["bool"].default == True
+ assert schema.properties["float"].default == 0.1
| [Bug] - Expects incorrect type on parameter default
Trying to parse a spec containing a parameter component with a numeric default with incorrectly throw and states that a string default was expected.
Version: `1.7.0`
Minimal example spec:
```yaml
openapi: 3.0.0
info:
title: Test api
description: test
version: 0.1.0
paths:
/test:
get:
requestBody:
content:
application/json:
schema:
type: string
required: true
responses:
200:
description: A good test
components:
parameters:
someComponent:
name: someComponent
in: query
schema:
type: number
minimum: 0
default: 0
```
To experience the error, load the specfile with yaml and try `OpenAPI(spec)`. It should throw.
If you replace `default: 0` with `default: '0'`, it will not throw.
The given spec is valid yaml | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/parsing_test.py::test_schema_default_types"
] | [
"tests/parsing_test.py::test_parse_from_yaml",
"tests/parsing_test.py::test_parsing_fails",
"tests/parsing_test.py::test_parsing_broken_reference",
"tests/parsing_test.py::test_parsing_wrong_parameter_name",
"tests/parsing_test.py::test_parsing_dupe_operation_id",
"tests/parsing_test.py::test_parsing_parameter_name_with_underscores",
"tests/parsing_test.py::test_object_example",
"tests/parsing_test.py::test_parsing_float_validation",
"tests/parsing_test.py::test_parsing_with_links",
"tests/parsing_test.py::test_param_types",
"tests/parsing_test.py::test_parsing_broken_links",
"tests/parsing_test.py::test_securityparameters",
"tests/parsing_test.py::test_example_type_array",
"tests/parsing_test.py::test_empty_contact",
"tests/parsing_test.py::test_external_docs"
] | {
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
} | "2023-03-08T03:22:35Z" | bsd-3-clause |
|
DropD__reentry-50 | diff --git a/README.rst b/README.rst
index 79101b2..6b33db1 100644
--- a/README.rst
+++ b/README.rst
@@ -20,7 +20,7 @@ Features
Note that ``reentry_register`` creates a *build-time*
dependency on ``reentry``. The suggested way to resolve that is using the
method described in `PEP518 <https://www.python.org/dev/peps/pep-0518/>`_, for
-which `support has been added in pip 10 <https://pip.pypa.io/en/latest/reference/pip/#pep-518-support>`_:
+which `support has been added in pip 10 <https://pip.pypa.io/en/latest/reference/pip/#pep-518-support>`_:
next to ``setup.py``, put a file ``pyproject.toml`` containing::
[build-system]
@@ -35,7 +35,7 @@ An alternative way for specifying a build dependency is to put::
...
)
-in your ``setup.py``.
+in your ``setup.py``.
This alternative works with all versions of ``pip``, but fails on systems,
where python is linked to old ``SSL`` libraries (such as the system python for
some versions of OS X).
@@ -80,6 +80,39 @@ The syntax is consistent with ``setuptools``'s ``pkg_resources``, so you may use
entry_pt_manager.iter_entry_points(...)
...
+Reentry Configuration
+---------------------
+Reentry supports getting information from a configuration file. The file will
+be searched at the following paths:
+
+* <HOME>/.reentryrc
+* <HOME>/.config/reentry/config
+
+The configuration file has an ``ini`` format and supports the following keys::
+
+ [general]
+ datadir=/path/to/data/dir
+ data_filename=name
+
+The ``datadir`` is the folder in which ``reentry`` stores the data file
+that contains the information about the registered entry points.
+If the config file doesn't exist in one of the above paths, the ``datadir`` is
+set to ``<HOME>/.config/reentry/data``.
+``data_filename`` is the name of the data file, in case you want to pick the
+name by your own instead of letting ``reentry`` choose it.
+Warning: By default, ``reentry`` creates a separate data file for every python
+interpreter in order not to mix entry points between different python
+environments on your system. Setting a ``data_filename`` in the configuration
+file tells ``reentry`` to *always* use this data file and may result in
+unexpected behavior if you use ``reentry`` in multiple python environments.
+
+You can also set configuration options for ``reentry`` via environment
+variables:
+
+* ``datadir`` can be defined by ``REENTRY_DATADIR``.
+* ``data_filename`` can be defined by ``REENTRY_DATA_FILENAME``.
+
+Environment variables take precedence over the configuration file.
What for?
---------
@@ -112,20 +145,20 @@ Standalone Manager Usage
Sometimes it might be necessary to update the cached entry points, for example
- * after uninstalling a plugin (there are no uninstall hooks by setuptools at the moment)
- * after installing a plugin that does not use install hooks
- * while developing a plugin / plugin host
+* after uninstalling a plugin (there are no uninstall hooks by setuptools at the moment)
+* after installing a plugin that does not use install hooks
+* while developing a plugin / plugin host
for those cases reentry has a commandline interface::
$ reentry --help
Usage: reentry [OPTIONS] COMMAND [ARGS]...
-
+
manage your reentry python entry point cache
-
+
Options:
--help Show this message and exit.
-
+
Commands:
clear Clear entry point map.
dev Development related commands.
@@ -149,7 +182,7 @@ for those cases reentry has a commandline interface::
$ reentry map --help
Usage: reentry map [OPTIONS]
-
+
Options:
--dist TEXT limit map to a distribution
--group TEXT limit map to an entry point group
diff --git a/reentry/config.py b/reentry/config.py
index 8ef957a..1513702 100644
--- a/reentry/config.py
+++ b/reentry/config.py
@@ -49,7 +49,8 @@ def make_config_parser(*args, **kwargs):
def get_config(config_file_name=str(find_config())):
"""Create config parser with defaults and read in the config file."""
default_config_dir = _get_default_config_dir()
- parser = make_config_parser({'datadir': str(default_config_dir.joinpath('data'))})
+ default_config_values = {'datadir': str(default_config_dir.joinpath('data')), 'data_filename': hashed_data_file_name()}
+ parser = make_config_parser(default_config_values)
parser.add_section('general')
parser.read([config_file_name])
@@ -60,25 +61,11 @@ def get_config(config_file_name=str(find_config())):
raise ValueError('environment variable $REENTRY_DATADIR={} exists, but is not a directory'.format(env_datadir))
parser.set('general', 'datadir', str(env_datadir_path))
- return parser
-
-
-def make_data_file_name():
- """Find the path to the reentry executable and mangle it into a file name.
-
- Note: In order to avoid long filenames (e.g. on conda forge), the relevant info is hashed.
- """
- sep = os.path.sep
- python_bin_dir = str(Path(sys.executable).resolve().parent)
- py_version = 'UNKNOWN'
- if six.PY2:
- py_version = 'PY2'
- elif six.PY3:
- py_version = 'PY3'
- file_name = python_bin_dir.lstrip(sep).replace(sep, '.').replace('.', '_') + '_' + py_version
+ env_data_filename = os.getenv('REENTRY_DATA_FILENAME')
+ if env_data_filename:
+ parser.set('general', 'data_filename', env_data_filename)
- file_name_hash = hashlib.sha256(file_name.encode('utf-8'))
- return file_name_hash.hexdigest()
+ return parser
def hashed_data_file_name():
@@ -96,12 +83,7 @@ def get_datafile():
"""Create the path to the data file used to store entry points."""
config = get_config()
- pkg_path_filename = make_data_file_name()
- datafile = Path(config.get('general', 'datadir')).joinpath(pkg_path_filename)
- if datafile.exists(): # pylint: disable=no-member
- return str(datafile) # if the unhashed exists, continue to use that one
-
- pkg_path_filename = hashed_data_file_name()
+ pkg_path_filename = config.get('general', 'data_filename')
datafile = Path(config.get('general', 'datadir')).joinpath(pkg_path_filename)
if not datafile.exists(): # pylint: disable=no-member
datafile.parent.mkdir(parents=True, exist_ok=True)
| DropD/reentry | 06cabf7841d1fdb78d68cbd8395598d16d8ab286 | diff --git a/reentry/tests/test_config.py b/reentry/tests/test_config.py
index a18d4e6..7c600cf 100644
--- a/reentry/tests/test_config.py
+++ b/reentry/tests/test_config.py
@@ -6,6 +6,7 @@ try:
except ImportError:
from pathlib import Path
+import os
import pytest # pylint: disable=unused-import
import six
from six.moves import configparser
@@ -27,16 +28,36 @@ def test_make_config_parser():
assert isinstance(parser, configparser.ConfigParser)
-def test_get_config():
- """Make sure the configparser gets created correctly."""
- parser = config.get_config()
-
+def _check_config_valid(parser, expected_filename=None):
+ """
+ Perform validations for a given config.
+ If expected_filename is given, check its value too.
+ """
if six.PY2:
assert isinstance(parser, configparser.SafeConfigParser)
else:
assert isinstance(parser, configparser.ConfigParser)
assert parser.get('general', 'datadir')
+ assert parser.get('general', 'data_filename')
+ if expected_filename:
+ assert parser.get('general', 'data_filename') == expected_filename
+
+
+def test_get_config():
+ """Make sure the configparser gets created correctly."""
+ parser = config.get_config()
+ _check_config_valid(parser)
+
+
+def test_get_config_with_env_var():
+ """Make sure the configparser gets created correctly when REENTRY_DATA_FILENAME is set."""
+ data_filename = 'entrypoints'
+ os.environ['REENTRY_DATA_FILENAME'] = data_filename
+ parser = config.get_config()
+ os.environ.pop('REENTRY_DATA_FILENAME')
+
+ _check_config_valid(parser, data_filename)
def test_get_datafile():
| What is the rational behind pkg_path_filename in get_datafile()?
Hi :)
First of all, thanks for a great package!
I would like to know if the name of the filename created in get_datafile function (config.py) has some important meaning and weather of not it can be changed.
This name can be a little problematic when compiling code for embedded systems, since you compile with one python interpreter on your host, but use another one on your target. Therefore, the name of the file created during compilation won't match the name that will be checked when trying to traverse the registered entry points on the board.
For example, if you compile with Buildroot, the python executable you use will probably reside at something like /home/user/buildroot/output/host/bin/python. This will lead to a configuration file with the name home.user.buildroot.output.host.bin.python. But on the board itself your python interpreter would probably be just "/usr/bin/python" and hence reentry will look for usr.bin.python, which of course won't be found.
I think this package can be very useful, especially on embedded systems, in which you will more likely to have limited resources.
I already tried to rename the file created with Buildroot after the compilation and use it on a board, and everything seems to look fine.
Thanks! | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"reentry/tests/test_config.py::test_get_config",
"reentry/tests/test_config.py::test_get_config_with_env_var"
] | [
"reentry/tests/test_config.py::test_find_config",
"reentry/tests/test_config.py::test_make_config_parser",
"reentry/tests/test_config.py::test_get_datafile"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2019-04-27T07:31:22Z" | mit |
|
Duke-GCB__DukeDSClient-61 | diff --git a/ddsc/core/filedownloader.py b/ddsc/core/filedownloader.py
index 5049aac..e8ab7f5 100644
--- a/ddsc/core/filedownloader.py
+++ b/ddsc/core/filedownloader.py
@@ -106,8 +106,9 @@ class FileDownloader(object):
Write out a empty file so the workers can seek to where they should write and write their data.
"""
with open(self.path, "wb") as outfile:
- outfile.seek(int(self.file_size) - 1)
- outfile.write(b'\0')
+ if self.file_size > 0:
+ outfile.seek(int(self.file_size) - 1)
+ outfile.write(b'\0')
def make_and_start_process(self, range_start, range_end, progress_queue):
"""
diff --git a/ddsc/core/fileuploader.py b/ddsc/core/fileuploader.py
index 43356c5..4b57b61 100644
--- a/ddsc/core/fileuploader.py
+++ b/ddsc/core/fileuploader.py
@@ -181,12 +181,14 @@ class ParallelChunkProcessor(object):
processes.append(self.make_and_start_process(index, num_items, progress_queue))
wait_for_processes(processes, num_chunks, progress_queue, self.watcher, self.local_file)
-
@staticmethod
def determine_num_chunks(chunk_size, file_size):
"""
Figure out how many pieces we are sending the file in.
+ NOTE: duke-data-service requires an empty chunk to be uploaded for empty files.
"""
+ if file_size == 0:
+ return 1
return int(math.ceil(float(file_size) / float(chunk_size)))
@staticmethod
diff --git a/ddsc/tests/empty_file b/ddsc/tests/empty_file
new file mode 100644
index 0000000..e69de29
diff --git a/setup.py b/setup.py
index 8fee84a..2fe9f5b 100644
--- a/setup.py
+++ b/setup.py
@@ -2,7 +2,7 @@ from setuptools import setup
setup(name='DukeDSClient',
- version='0.2.8',
+ version='0.2.9',
description='Command line tool(ddsclient) to upload/manage projects on the duke-data-service.',
url='https://github.com/Duke-GCB/DukeDSClient',
keywords='duke dds dukedataservice',
| Duke-GCB/DukeDSClient | 81d8fc03fdbb9209d949f319bf4b4691b1615a59 | diff --git a/ddsc/core/tests/test_fileuploader.py b/ddsc/core/tests/test_fileuploader.py
index f8ca72b..44bfb7e 100644
--- a/ddsc/core/tests/test_fileuploader.py
+++ b/ddsc/core/tests/test_fileuploader.py
@@ -47,6 +47,7 @@ class TestParallelChunkProcessor(TestCase):
(100, 900000, 9000),
(125, 123, 1),
(122, 123, 2),
+ (100, 0, 1)
]
for chunk_size, file_size, expected in values:
num_chunks = ParallelChunkProcessor.determine_num_chunks(chunk_size, file_size)
@@ -63,4 +64,4 @@ class TestParallelChunkProcessor(TestCase):
]
for upload_workers, num_chunks, expected in values:
result = ParallelChunkProcessor.make_work_parcels(upload_workers, num_chunks)
- self.assertEqual(expected, result)
\ No newline at end of file
+ self.assertEqual(expected, result)
| βrange() step argument must not be zeroβ
Crash at approx. 30% completion, uploading a folder to a new project: βrange() step argument must not be zeroβ
<img width="806" alt="screen shot 2016-05-25 at 1 31 11 pm" src="https://cloud.githubusercontent.com/assets/11540881/15551266/38d08f16-2283-11e6-9708-c5f93edb99d9.png">
Is there a verbose logging option we can use to determine where, exactly, this is failing? | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"ddsc/core/tests/test_fileuploader.py::TestParallelChunkProcessor::test_determine_num_chunks"
] | [
"ddsc/core/tests/test_fileuploader.py::TestFileUploader::test_make_chunk_processor_with_none",
"ddsc/core/tests/test_fileuploader.py::TestFileUploader::test_make_chunk_processor_with_one",
"ddsc/core/tests/test_fileuploader.py::TestFileUploader::test_make_chunk_processor_with_two",
"ddsc/core/tests/test_fileuploader.py::TestParallelChunkProcessor::test_make_work_parcels"
] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_media",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2016-05-25T18:51:33Z" | mit |
|
Duke-GCB__lando-169 | diff --git a/lando/k8s/jobmanager.py b/lando/k8s/jobmanager.py
index 456a8f2..6774189 100644
--- a/lando/k8s/jobmanager.py
+++ b/lando/k8s/jobmanager.py
@@ -171,7 +171,8 @@ class JobManager(object):
command_parts.extend(["--tmp-outdir-prefix", Paths.TMPOUT_DATA + "/",
"--outdir", Paths.OUTPUT_RESULTS_DIR + "/",
"--max-ram", self.job.job_flavor_memory,
- "--max-cores", str(self.job.job_flavor_cpus)
+ "--max-cores", str(self.job.job_flavor_cpus),
+ "--usage-report", str(self.names.usage_report_path),
])
command_parts.extend([
self.names.workflow_path,
@@ -400,6 +401,7 @@ class Names(object):
self.run_workflow_stdout_path = '{}/bespin-workflow-output.json'.format(Paths.OUTPUT_DATA)
self.run_workflow_stderr_path = '{}/bespin-workflow-output.log'.format(Paths.OUTPUT_DATA)
self.annotate_project_details_path = '{}/annotate_project_details.sh'.format(Paths.OUTPUT_DATA)
+ self.usage_report_path = '{}/job-{}-resource-usage.json'.format(Paths.OUTPUT_DATA, suffix)
class Paths(object):
| Duke-GCB/lando | 76f981ebff4ae0abbabbc4461308e9e5ea0bc830 | diff --git a/lando/k8s/tests/test_jobmanager.py b/lando/k8s/tests/test_jobmanager.py
index e98c2a4..73c5ed6 100644
--- a/lando/k8s/tests/test_jobmanager.py
+++ b/lando/k8s/tests/test_jobmanager.py
@@ -193,6 +193,7 @@ class TestJobManager(TestCase):
expected_bash_command = 'cwltool --tmp-outdir-prefix /bespin/tmpout/ ' \
'--outdir /bespin/output-data/results/ ' \
'--max-ram 1G --max-cores 2 ' \
+ '--usage-report /bespin/output-data/job-51-jpb-resource-usage.json ' \
'/bespin/job-data/workflow/someurl ' \
'/bespin/job-data/job-order.json ' \
'>/bespin/output-data/bespin-workflow-output.json ' \
| k8s save calrissian record usage report
Calrissian has a usage report option that will record statistics about how memory/cpu usage when running a job. Add the `--usage-report <report.json>` flag to the calrissian command line.
Relevant code:
https://github.com/Duke-GCB/lando/blob/da2c40ef588578993a45c46f20676a691ef68067/lando/k8s/jobmanager.py#L171-L175
This report should be saved into the output directory that is uploaded to DukeDS. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"lando/k8s/tests/test_jobmanager.py::TestJobManager::test_create_run_workflow_job"
] | [
"lando/k8s/tests/test_jobmanager.py::TestJobManager::test_cleanup_all",
"lando/k8s/tests/test_jobmanager.py::TestJobManager::test_cleanup_organize_output_project_job",
"lando/k8s/tests/test_jobmanager.py::TestJobManager::test_cleanup_record_output_project_job",
"lando/k8s/tests/test_jobmanager.py::TestJobManager::test_cleanup_run_workflow_job",
"lando/k8s/tests/test_jobmanager.py::TestJobManager::test_cleanup_save_output_job",
"lando/k8s/tests/test_jobmanager.py::TestJobManager::test_cleanup_stage_data_job",
"lando/k8s/tests/test_jobmanager.py::TestJobManager::test_create_organize_output_project_job",
"lando/k8s/tests/test_jobmanager.py::TestJobManager::test_create_record_output_project_job",
"lando/k8s/tests/test_jobmanager.py::TestJobManager::test_create_run_workflow_persistent_volumes",
"lando/k8s/tests/test_jobmanager.py::TestJobManager::test_create_save_output_job",
"lando/k8s/tests/test_jobmanager.py::TestJobManager::test_create_stage_data_job",
"lando/k8s/tests/test_jobmanager.py::TestJobManager::test_create_stage_data_persistent_volumes",
"lando/k8s/tests/test_jobmanager.py::TestJobManager::test_make_job_labels",
"lando/k8s/tests/test_jobmanager.py::TestJobManager::test_read_record_output_project_details",
"lando/k8s/tests/test_jobmanager.py::TestJobManager::test_read_record_output_project_details_missing_fields",
"lando/k8s/tests/test_jobmanager.py::TestJobManager::test_read_record_output_project_details_pod_not_found",
"lando/k8s/tests/test_jobmanager.py::TestNames::test_constructor",
"lando/k8s/tests/test_jobmanager.py::TestNames::test_strips_username_after_at_sign",
"lando/k8s/tests/test_jobmanager.py::TestStageDataConfig::test_constructor",
"lando/k8s/tests/test_jobmanager.py::TestRunWorkflowConfig::test_constructor",
"lando/k8s/tests/test_jobmanager.py::TestOrganizeOutputConfig::test_constructor",
"lando/k8s/tests/test_jobmanager.py::TestSaveOutputConfig::test_constructor",
"lando/k8s/tests/test_jobmanager.py::TestRecordOutputProjectConfig::test_constructor"
] | {
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
} | "2019-03-12T18:31:43Z" | mit |
|
E3SM-Project__zstash-168 | diff --git a/zstash/extract.py b/zstash/extract.py
index 5382609..9918bf4 100644
--- a/zstash/extract.py
+++ b/zstash/extract.py
@@ -57,7 +57,11 @@ def extract(keep_files: bool = True):
logger.error(tar)
else:
verb: str = "extracting" if keep_files else "checking"
- logger.info("No failures detected when {} the files.".format(verb))
+ logger.info(
+ 'No failures detected when {} the files. If you have a log file, run "grep -i Exception <log-file>" to double check.'.format(
+ verb
+ )
+ )
def setup_extract() -> Tuple[argparse.Namespace, str]:
@@ -352,7 +356,9 @@ def multiprocess_extract(
monitor, tars_for_this_worker, failure_queue
)
process: multiprocessing.Process = multiprocessing.Process(
- target=extractFiles, args=(matches, keep_files, keep_tars, cache, worker)
+ target=extractFiles,
+ args=(matches, keep_files, keep_tars, cache, worker),
+ daemon=True,
)
process.start()
processes.append(process)
| E3SM-Project/zstash | fb39bbc5272177e1de7f5f65e767b6013340d981 | diff --git a/tests/test_check.py b/tests/test_check.py
index 6bc3910..1a97239 100644
--- a/tests/test_check.py
+++ b/tests/test_check.py
@@ -189,7 +189,7 @@ class TestCheck(TestZstash):
)
self.assertEqualOrStop(
output + err,
- "INFO: Opening tar archive {}/000000.tar\nINFO: Checking file1.txt\nINFO: Checking file2.txt\nINFO: No failures detected when checking the files.\n".format(
+ 'INFO: Opening tar archive {}/000000.tar\nINFO: Checking file1.txt\nINFO: Checking file2.txt\nINFO: No failures detected when checking the files. If you have a log file, run "grep -i Exception <log-file>" to double check.\n'.format(
self.cache
),
)
| zstash check reports success even if exceptions occur
`zstash check` reports success even if exceptions occur.
Exceptions like the following may occur, but `zstash check` still ends with `INFO: No failures detected when checking the files.`:
```
Process Process-3:
Traceback (most recent call last):
File "/global/common/software/e3sm/anaconda_envs/base/envs/e3sm_unified_1.5.0_nompi/lib/python3.8/multiprocessing/process.py", line 315, in _bootstrap
self.run()
File "/global/common/software/e3sm/anaconda_envs/base/envs/e3sm_unified_1.5.0_nompi/lib/python3.8/multiprocessing/process.py", line 108, in run
self._target(*self._args, **self._kwargs)
File "/global/common/software/e3sm/anaconda_envs/base/envs/e3sm_unified_1.5.0_nompi/lib/python3.8/site-packages/zstash/extract.py", line 374, in extractFiles
hpss_get(hpss, tfname, cache)
File "/global/common/software/e3sm/anaconda_envs/base/envs/e3sm_unified_1.5.0_nompi/lib/python3.8/site-packages/zstash/hpss.py", line 99, in hpss_get
hpss_transfer(hpss, file_path, "get", cache, False)
File "/global/common/software/e3sm/anaconda_envs/base/envs/e3sm_unified_1.5.0_nompi/lib/python3.8/site-packages/zstash/hpss.py", line 76, in hpss_transfer
run_command(command, error_str)
File "/global/common/software/e3sm/anaconda_envs/base/envs/e3sm_unified_1.5.0_nompi/lib/python3.8/site-packages/zstash/utils.py", line 55, in run_command
raise Exception(error_str)
Exception: Error=Transferring file from HPSS: 000029.tar, Command was `hsi -q "cd /home/f/forsyth/E3SMv2/v2.LR.hist-aer_0251; get 000029.tar"`. This command includes `hsi`. Be sure that you have logged into `hsi`.
```
Possible solutions:
- Fail on first `Exception`
- Create list of all `Exceptions` before failing | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_check.py::TestCheck::testCheckKeepTars"
] | [] | {
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
} | "2021-11-19T23:44:15Z" | bsd-3-clause |
|
ECCO-GROUP__ECCOv4-py-63 | diff --git a/ecco_v4_py/get_section_masks.py b/ecco_v4_py/get_section_masks.py
index a03db6f..6ffa665 100644
--- a/ecco_v4_py/get_section_masks.py
+++ b/ecco_v4_py/get_section_masks.py
@@ -90,6 +90,9 @@ def get_section_endpoints(section_name):
elif section_name == 'icelandfaroe':
pt1 = [-16, 65]
pt2 = [ -7, 62.5]
+ elif section_name == 'faroescotland':
+ pt1 = [-6.5, 62.5]
+ pt2 = [-4, 57]
elif section_name == 'scotlandnorway':
pt1 = [-4, 57]
pt2 = [ 8, 62]
| ECCO-GROUP/ECCOv4-py | 82c2327427fba0d90acdf7b87ffab607387fa331 | diff --git a/ecco_v4_py/test/test_section_masks.py b/ecco_v4_py/test/test_section_masks.py
new file mode 100644
index 0000000..9610842
--- /dev/null
+++ b/ecco_v4_py/test/test_section_masks.py
@@ -0,0 +1,11 @@
+
+from __future__ import division, print_function
+import ecco_v4_py as ecco
+
+
+def test_section_endpoints():
+ """Ensure that the listed available sections are actually there
+ """
+
+ for section in ecco.get_available_sections():
+ assert ecco.get_section_endpoints(section) is not None
| 'Faroe Scotland' is included in the get_available_sections() but not included in get_section_endpoints()
get_section_endpoints() returns and error for 'Faroe Scotland'. I think this is because the coordinates for this section is actually not included in the function. I assume that the info exists but was accidentally removed. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"ecco_v4_py/test/test_section_masks.py::test_section_endpoints"
] | [] | {
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
} | "2019-08-25T11:55:09Z" | mit |
|
EFForg__starttls-policy-cli-24 | diff --git a/starttls_policy_cli/configure.py b/starttls_policy_cli/configure.py
index 8ec010d..bb13dec 100644
--- a/starttls_policy_cli/configure.py
+++ b/starttls_policy_cli/configure.py
@@ -20,8 +20,9 @@ class ConfigGenerator(object):
"""
__metaclass__ = abc.ABCMeta
- def __init__(self, policy_dir):
+ def __init__(self, policy_dir, enforce_testing=False):
self._policy_dir = policy_dir
+ self._enforce_testing = enforce_testing
self._policy_filename = os.path.join(self._policy_dir, constants.POLICY_FILENAME)
self._config_filename = os.path.join(self._policy_dir, self.default_filename)
self._policy_config = None
@@ -86,15 +87,6 @@ class ConfigGenerator(object):
def default_filename(self):
"""The expected default filename of the generated configuration file."""
-def _policy_for_domain(domain, tls_policy, max_domain_len):
- line = ("{0:%d} " % max_domain_len).format(domain)
- if tls_policy.mode == "enforce":
- line += " secure match="
- line += ":".join(tls_policy.mxs)
- elif tls_policy.mode == "testing":
- line = "# " + line + "undefined due to testing policy"
- return line
-
class PostfixGenerator(ConfigGenerator):
"""Configuration generator for postfix.
"""
@@ -103,7 +95,7 @@ class PostfixGenerator(ConfigGenerator):
policies = []
max_domain_len = len(max(policy_list, key=len))
for domain, tls_policy in sorted(six.iteritems(policy_list)):
- policies.append(_policy_for_domain(domain, tls_policy, max_domain_len))
+ policies.append(self._policy_for_domain(domain, tls_policy, max_domain_len))
return "\n".join(policies)
def _generate_expired_fallback(self, policy_list):
@@ -122,6 +114,16 @@ class PostfixGenerator(ConfigGenerator):
"And finally:\n\n"
"postfix reload\n").format(abs_path=abs_path, filename=filename)
+ def _policy_for_domain(self, domain, tls_policy, max_domain_len):
+ line = ("{0:%d} " % max_domain_len).format(domain)
+ mode = tls_policy.mode
+ if mode == "enforce" or self._enforce_testing and mode == "testing":
+ line += " secure match="
+ line += ":".join(tls_policy.mxs)
+ elif mode == "testing":
+ line = "# " + line + "undefined due to testing policy"
+ return line
+
@property
def mta_name(self):
return "Postfix"
diff --git a/starttls_policy_cli/main.py b/starttls_policy_cli/main.py
index 2963964..fe553e6 100644
--- a/starttls_policy_cli/main.py
+++ b/starttls_policy_cli/main.py
@@ -9,12 +9,26 @@ GENERATORS = {
}
def _argument_parser():
- parser = argparse.ArgumentParser()
- parser.add_argument("--generate", help="The MTA you want to generate a configuration file for.",
+ parser = argparse.ArgumentParser(
+ description="Generates MTA configuration file according to STARTTLS-Everywhere policy",
+ formatter_class=argparse.ArgumentDefaultsHelpFormatter)
+ parser.add_argument("-g", "--generate",
+ choices=GENERATORS,
+ help="The MTA you want to generate a configuration file for.",
dest="generate", required=True)
# TODO: decide whether to use /etc/ for policy list home
- parser.add_argument("--policy-dir", help="Policy file directory on this computer.",
+ parser.add_argument("-d", "--policy-dir",
+ help="Policy file directory on this computer.",
default="/etc/starttls-policy/", dest="policy_dir")
+ parser.add_argument("-e", "--early-adopter",
+ help="Early Adopter mode. Processes all \"testing\" domains in policy list "
+ "same way as domains in \"enforce\" mode, effectively requiring strong TLS "
+ "for domains in \"testing\" mode too. This mode is useful for participating"
+ " in tests of recently added domains with real communications and earlier "
+ "security hardening at the cost of increased probability of delivery "
+ "degradation. Use this mode with awareness about all implications.",
+ action="store_true",
+ dest="early_adopter")
return parser
@@ -24,19 +38,15 @@ def _ensure_directory(directory):
def _generate(arguments):
_ensure_directory(arguments.policy_dir)
- config_generator = GENERATORS[arguments.generate](arguments.policy_dir)
+ config_generator = GENERATORS[arguments.generate](arguments.policy_dir,
+ arguments.early_adopter)
config_generator.generate()
config_generator.manual_instructions()
-def _perform(arguments, parser):
- if arguments.generate not in GENERATORS:
- parser.error("no configuration generator exists for '%s'" % arguments.generate)
- _generate(arguments)
-
def main():
""" Entrypoint for CLI tool. """
parser = _argument_parser()
- _perform(parser.parse_args(), parser)
+ _generate(parser.parse_args())
if __name__ == "__main__":
main() # pragma: no cover
diff --git a/starttls_policy_cli/policy.py b/starttls_policy_cli/policy.py
index b4ab17a..1cb0212 100644
--- a/starttls_policy_cli/policy.py
+++ b/starttls_policy_cli/policy.py
@@ -1,5 +1,4 @@
""" Policy config wrapper """
-import collections
import logging
import datetime
import io
@@ -8,6 +7,12 @@ import six
from starttls_policy_cli import util
from starttls_policy_cli import constants
+try:
+ # Python 3.3+
+ from collections.abc import Mapping
+except ImportError:
+ from collections import Mapping
+
logger = logging.getLogger(__name__)
logger.addHandler(logging.StreamHandler())
@@ -210,7 +215,6 @@ class PolicyNoAlias(Policy):
@property
def policy_alias(self):
""" This type of policy can't be aliased. Returns None."""
- pass
@policy_alias.setter
def policy_alias(self, value):
@@ -218,7 +222,7 @@ class PolicyNoAlias(Policy):
# pylint: disable=unused-argument
raise util.ConfigError('PolicyNoAlias object cannot have policy-alias field!')
-class Config(MergableConfig, collections.Mapping):
+class Config(MergableConfig, Mapping):
"""Class for retrieving properties in TLS Policy config.
If `policy_aliases` is specified, they must be set before `policies`,
so policy format validation can work properly.
@@ -238,6 +242,7 @@ class Config(MergableConfig, collections.Mapping):
yield domain
def keys(self):
+ """ Returns iterable over policies even if this attribute is not set """
if self.policies is None:
return set([])
return self.policies.keys()
diff --git a/starttls_policy_cli/util.py b/starttls_policy_cli/util.py
index 8f7da53..6b703a7 100644
--- a/starttls_policy_cli/util.py
+++ b/starttls_policy_cli/util.py
@@ -103,20 +103,14 @@ TLS_VERSIONS = ('TLSv1', 'TLSv1.1', 'TLSv1.2', 'TLSv1.3')
ENFORCE_MODES = ('testing', 'enforce')
POLICY_SCHEMA = {
- 'min-tls-version': {
- 'enforce': partial(enforce_in, TLS_VERSIONS),
- 'default': 'TLSv1.2',
- },
'mode': {
'enforce': partial(enforce_in, ENFORCE_MODES),
'default': 'testing',
},
- # TODO (#50) Validate mxs as FQDNs (using public suffix list)
'mxs': {
'enforce': partial(enforce_list, partial(enforce_type, six.string_types)),
'default': [],
},
- # TODO (#50) Validate reporting endpoint as https: or mailto:
'policy-alias': partial(enforce_type, six.string_types),
}
| EFForg/starttls-policy-cli | be1143dcfb2d54fe638a850f63f603aedb068e0c | diff --git a/starttls_policy_cli/tests/configure_test.py b/starttls_policy_cli/tests/configure_test.py
index 5bd4b2e..706c16a 100644
--- a/starttls_policy_cli/tests/configure_test.py
+++ b/starttls_policy_cli/tests/configure_test.py
@@ -104,11 +104,15 @@ test_json_expired = '{\
}'
testgen_data = [
- param("simple_policy", test_json, "# .testing.example-recipient.com "
+ param("simple_policy", test_json, False, "# .testing.example-recipient.com "
"undefined due to testing policy\n"
".valid.example-recipient.com "
"secure match=.valid.example-recipient.com\n"),
- param("expired_policy", test_json_expired, "# Policy list is outdated. "
+ param("simple_policy_early", test_json, True, ".testing.example-recipient.com "
+ "secure match=.testing.example-recipient.com\n"
+ ".valid.example-recipient.com "
+ "secure match=.valid.example-recipient.com\n"),
+ param("expired_policy", test_json_expired, False, "# Policy list is outdated. "
"Falling back to opportunistic encryption.\n"),
]
@@ -127,10 +131,10 @@ class TestPostfixGenerator(unittest.TestCase):
self.assertTrue("postfix reload" in instructions)
self.assertTrue(generator.default_filename in instructions)
- def config_test(self, conf, expected):
+ def config_test(self, conf, enforce_testing, expected):
"""PostfixGenerator test parameterized over various policies"""
with TempPolicyDir(conf) as testdir:
- generator = configure.PostfixGenerator(testdir)
+ generator = configure.PostfixGenerator(testdir, enforce_testing)
generator.generate()
pol_filename = os.path.join(testdir, generator.default_filename)
with open(pol_filename) as pol_file:
diff --git a/starttls_policy_cli/tests/main_test.py b/starttls_policy_cli/tests/main_test.py
index 7c4a593..edca7de 100644
--- a/starttls_policy_cli/tests/main_test.py
+++ b/starttls_policy_cli/tests/main_test.py
@@ -24,21 +24,21 @@ class TestArguments(unittest.TestCase):
def test_generate_arg(self):
# pylint: disable=protected-access
- sys.argv = ["_", "--generate", "lol"]
+ sys.argv = ["_", "--generate", "postfix"]
parser = main._argument_parser()
arguments = parser.parse_args()
- self.assertEqual(arguments.generate, "lol")
+ self.assertEqual(arguments.generate, "postfix")
def test_default_dir(self):
# pylint: disable=protected-access
- sys.argv = ["_", "--generate", "lol"]
+ sys.argv = ["_", "--generate", "postfix"]
parser = main._argument_parser()
arguments = parser.parse_args()
self.assertEqual(arguments.policy_dir, "/etc/starttls-policy/")
def test_policy_dir(self):
# pylint: disable=protected-access
- sys.argv = ["_", "--generate", "lol", "--policy-dir", "lmao"]
+ sys.argv = ["_", "--generate", "postfix", "--policy-dir", "lmao"]
parser = main._argument_parser()
arguments = parser.parse_args()
self.assertEqual(arguments.policy_dir, "lmao")
@@ -50,7 +50,7 @@ class TestPerform(unittest.TestCase):
sys.argv = ["_", "--generate", "lmao"]
parser = main._argument_parser()
parser.error = mock.MagicMock(side_effect=Exception)
- self.assertRaises(Exception, main._perform, parser.parse_args(), parser)
+ self.assertRaises(Exception, parser.parse_args)
@mock.patch("starttls_policy_cli.main._ensure_directory")
def test_generate(self, ensure_directory):
@@ -58,7 +58,7 @@ class TestPerform(unittest.TestCase):
main.GENERATORS = {"exists": mock.MagicMock()}
sys.argv = ["_", "--generate", "exists"]
parser = main._argument_parser()
- main._perform(parser.parse_args(), parser)
+ main._generate(parser.parse_args())
self.assertTrue(main.GENERATORS["exists"].called_with("/etc/starttls-policy"))
@mock.patch("os.path.exists")
diff --git a/starttls_policy_cli/tests/policy_test.py b/starttls_policy_cli/tests/policy_test.py
index 81a8fb1..994c7bd 100644
--- a/starttls_policy_cli/tests/policy_test.py
+++ b/starttls_policy_cli/tests/policy_test.py
@@ -16,7 +16,6 @@ test_json = '{\
"timestamp": "2014-05-26T01:35:33+0000",\
"policies": {\
".valid.example-recipient.com": {\
- "min-tls-version": "TLSv1.1",\
"mode": "enforce",\
"mxs": [".valid.example-recipient.com"]\
}\
@@ -166,8 +165,8 @@ class TestConfig(unittest.TestCase):
with self.assertRaises(util.ConfigError):
policy.Config().policies = {'invalid': invalid_policy}
conf = policy.Config()
- conf.policies = {'valid': {}}
- self.assertEqual(conf.get_policy_for('valid').min_tls_version, 'TLSv1.2')
+ conf.policies = {'valid': {'mxs': ['example.com']}}
+ self.assertEqual(conf.get_policy_for('valid').mxs, ['example.com'])
def test_set_aliased_policy(self):
conf = policy.Config()
@@ -175,7 +174,7 @@ class TestConfig(unittest.TestCase):
with self.assertRaises(util.ConfigError):
conf.policies = {'invalid': {'policy-alias': 'invalid'}}
conf.policies = {'valid': {'policy-alias': 'valid'}}
- self.assertEqual(conf.get_policy_for('valid').min_tls_version, 'TLSv1.2')
+ self.assertEqual(conf.get_policy_for('valid').mode, 'testing')
def test_iter_policies_aliased(self):
conf = policy.Config()
@@ -226,23 +225,10 @@ class TestPolicy(unittest.TestCase):
self.assertFalse('eff.org' in new_conf.mxs)
self.assertTrue('example.com' in new_conf.mxs)
- def test_tls_version_default(self):
- p = policy.Policy({})
- self.assertEqual(p.min_tls_version, 'TLSv1.2')
-
def test_mode_default(self):
p = policy.Policy({})
self.assertEqual(p.mode, 'testing')
- def test_tls_version_valid(self):
- with self.assertRaises(util.ConfigError):
- policy.Policy({'min-tls-version': 'SSLv3'})
- p = policy.Policy({})
- with self.assertRaises(util.ConfigError):
- p.min_tls_version = 'SSLv3'
- p.min_tls_version = 'TLSv1.1'
- self.assertEqual(p.min_tls_version, 'TLSv1.1')
-
def test_mode_valid(self):
p = policy.Policy({})
with self.assertRaises(util.ConfigError):
| Implement Early Adopter mode
Actual issue is created for tracking implementation progress of feature described [here](https://github.com/EFForg/starttls-everywhere/issues/124). | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"starttls_policy_cli/tests/configure_test.py::TestPostfixGenerator::test_expired_policy",
"starttls_policy_cli/tests/configure_test.py::TestPostfixGenerator::test_simple_policy",
"starttls_policy_cli/tests/configure_test.py::TestPostfixGenerator::test_simple_policy_early",
"starttls_policy_cli/tests/main_test.py::TestPerform::test_generate_unknown",
"starttls_policy_cli/tests/policy_test.py::TestConfig::test_basic_parsing"
] | [
"starttls_policy_cli/tests/configure_test.py::TestConfigGenerator::test_generate",
"starttls_policy_cli/tests/configure_test.py::TestConfigGenerator::test_manual_instructions",
"starttls_policy_cli/tests/configure_test.py::TestPostfixGenerator::test_instruct_string",
"starttls_policy_cli/tests/configure_test.py::TestPostfixGenerator::test_mta_name",
"starttls_policy_cli/tests/main_test.py::TestArguments::test_default_dir",
"starttls_policy_cli/tests/main_test.py::TestArguments::test_generate_arg",
"starttls_policy_cli/tests/main_test.py::TestArguments::test_generate_no_arg",
"starttls_policy_cli/tests/main_test.py::TestArguments::test_no_args_require_generate",
"starttls_policy_cli/tests/main_test.py::TestArguments::test_policy_dir",
"starttls_policy_cli/tests/main_test.py::TestPerform::test_ensure_directory",
"starttls_policy_cli/tests/policy_test.py::TestConfigEncoder::test_encode_datetime",
"starttls_policy_cli/tests/policy_test.py::TestConfigEncoder::test_encode_empty_dict",
"starttls_policy_cli/tests/policy_test.py::TestConfigEncoder::test_encode_empty_list",
"starttls_policy_cli/tests/policy_test.py::TestConfigEncoder::test_encode_empty_string",
"starttls_policy_cli/tests/policy_test.py::TestConfigEncoder::test_encode_false",
"starttls_policy_cli/tests/policy_test.py::TestConfigEncoder::test_encode_float",
"starttls_policy_cli/tests/policy_test.py::TestConfigEncoder::test_encode_integer",
"starttls_policy_cli/tests/policy_test.py::TestConfigEncoder::test_encode_none",
"starttls_policy_cli/tests/policy_test.py::TestConfigEncoder::test_encode_true",
"starttls_policy_cli/tests/policy_test.py::TestConfig::test_bad_schema",
"starttls_policy_cli/tests/policy_test.py::TestConfig::test_flush",
"starttls_policy_cli/tests/policy_test.py::TestConfig::test_flush_default",
"starttls_policy_cli/tests/policy_test.py::TestConfig::test_iter_policies",
"starttls_policy_cli/tests/policy_test.py::TestConfig::test_iter_policies_aliased",
"starttls_policy_cli/tests/policy_test.py::TestConfig::test_keys_empty_policy",
"starttls_policy_cli/tests/policy_test.py::TestConfig::test_len_method",
"starttls_policy_cli/tests/policy_test.py::TestConfig::test_merge_keeps_old_policies",
"starttls_policy_cli/tests/policy_test.py::TestConfig::test_merge_keeps_old_settings",
"starttls_policy_cli/tests/policy_test.py::TestConfig::test_no_aliasing_in_alias",
"starttls_policy_cli/tests/policy_test.py::TestConfig::test_set_aliased_policy",
"starttls_policy_cli/tests/policy_test.py::TestConfig::test_set_author",
"starttls_policy_cli/tests/policy_test.py::TestConfig::test_set_policies",
"starttls_policy_cli/tests/policy_test.py::TestConfig::test_should_update_invalid_type",
"starttls_policy_cli/tests/policy_test.py::TestConfig::test_should_update_valid_type",
"starttls_policy_cli/tests/policy_test.py::TestConfig::test_timestamp_and_expires_required",
"starttls_policy_cli/tests/policy_test.py::TestConfig::test_update_drops_old_policies",
"starttls_policy_cli/tests/policy_test.py::TestConfig::test_update_drops_old_settings",
"starttls_policy_cli/tests/policy_test.py::TestConfig::test_updateble_checks_types",
"starttls_policy_cli/tests/policy_test.py::TestPolicy::test_alias_valid",
"starttls_policy_cli/tests/policy_test.py::TestPolicy::test_merge_keeps_old_mxs",
"starttls_policy_cli/tests/policy_test.py::TestPolicy::test_mode_default",
"starttls_policy_cli/tests/policy_test.py::TestPolicy::test_mode_valid",
"starttls_policy_cli/tests/policy_test.py::TestPolicy::test_mxs",
"starttls_policy_cli/tests/policy_test.py::TestPolicy::test_no_alias_policy_getter",
"starttls_policy_cli/tests/policy_test.py::TestPolicy::test_no_alias_policy_setter",
"starttls_policy_cli/tests/policy_test.py::TestPolicy::test_update_drops_old_mxs"
] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
} | "2019-03-06T18:59:16Z" | apache-2.0 |
|
EFForg__starttls-policy-cli-26 | diff --git a/starttls_policy_cli/policy.py b/starttls_policy_cli/policy.py
index b4ab17a..1cb0212 100644
--- a/starttls_policy_cli/policy.py
+++ b/starttls_policy_cli/policy.py
@@ -1,5 +1,4 @@
""" Policy config wrapper """
-import collections
import logging
import datetime
import io
@@ -8,6 +7,12 @@ import six
from starttls_policy_cli import util
from starttls_policy_cli import constants
+try:
+ # Python 3.3+
+ from collections.abc import Mapping
+except ImportError:
+ from collections import Mapping
+
logger = logging.getLogger(__name__)
logger.addHandler(logging.StreamHandler())
@@ -210,7 +215,6 @@ class PolicyNoAlias(Policy):
@property
def policy_alias(self):
""" This type of policy can't be aliased. Returns None."""
- pass
@policy_alias.setter
def policy_alias(self, value):
@@ -218,7 +222,7 @@ class PolicyNoAlias(Policy):
# pylint: disable=unused-argument
raise util.ConfigError('PolicyNoAlias object cannot have policy-alias field!')
-class Config(MergableConfig, collections.Mapping):
+class Config(MergableConfig, Mapping):
"""Class for retrieving properties in TLS Policy config.
If `policy_aliases` is specified, they must be set before `policies`,
so policy format validation can work properly.
@@ -238,6 +242,7 @@ class Config(MergableConfig, collections.Mapping):
yield domain
def keys(self):
+ """ Returns iterable over policies even if this attribute is not set """
if self.policies is None:
return set([])
return self.policies.keys()
diff --git a/starttls_policy_cli/util.py b/starttls_policy_cli/util.py
index 8f7da53..6b703a7 100644
--- a/starttls_policy_cli/util.py
+++ b/starttls_policy_cli/util.py
@@ -103,20 +103,14 @@ TLS_VERSIONS = ('TLSv1', 'TLSv1.1', 'TLSv1.2', 'TLSv1.3')
ENFORCE_MODES = ('testing', 'enforce')
POLICY_SCHEMA = {
- 'min-tls-version': {
- 'enforce': partial(enforce_in, TLS_VERSIONS),
- 'default': 'TLSv1.2',
- },
'mode': {
'enforce': partial(enforce_in, ENFORCE_MODES),
'default': 'testing',
},
- # TODO (#50) Validate mxs as FQDNs (using public suffix list)
'mxs': {
'enforce': partial(enforce_list, partial(enforce_type, six.string_types)),
'default': [],
},
- # TODO (#50) Validate reporting endpoint as https: or mailto:
'policy-alias': partial(enforce_type, six.string_types),
}
| EFForg/starttls-policy-cli | be1143dcfb2d54fe638a850f63f603aedb068e0c | diff --git a/starttls_policy_cli/tests/policy_test.py b/starttls_policy_cli/tests/policy_test.py
index 81a8fb1..994c7bd 100644
--- a/starttls_policy_cli/tests/policy_test.py
+++ b/starttls_policy_cli/tests/policy_test.py
@@ -16,7 +16,6 @@ test_json = '{\
"timestamp": "2014-05-26T01:35:33+0000",\
"policies": {\
".valid.example-recipient.com": {\
- "min-tls-version": "TLSv1.1",\
"mode": "enforce",\
"mxs": [".valid.example-recipient.com"]\
}\
@@ -166,8 +165,8 @@ class TestConfig(unittest.TestCase):
with self.assertRaises(util.ConfigError):
policy.Config().policies = {'invalid': invalid_policy}
conf = policy.Config()
- conf.policies = {'valid': {}}
- self.assertEqual(conf.get_policy_for('valid').min_tls_version, 'TLSv1.2')
+ conf.policies = {'valid': {'mxs': ['example.com']}}
+ self.assertEqual(conf.get_policy_for('valid').mxs, ['example.com'])
def test_set_aliased_policy(self):
conf = policy.Config()
@@ -175,7 +174,7 @@ class TestConfig(unittest.TestCase):
with self.assertRaises(util.ConfigError):
conf.policies = {'invalid': {'policy-alias': 'invalid'}}
conf.policies = {'valid': {'policy-alias': 'valid'}}
- self.assertEqual(conf.get_policy_for('valid').min_tls_version, 'TLSv1.2')
+ self.assertEqual(conf.get_policy_for('valid').mode, 'testing')
def test_iter_policies_aliased(self):
conf = policy.Config()
@@ -226,23 +225,10 @@ class TestPolicy(unittest.TestCase):
self.assertFalse('eff.org' in new_conf.mxs)
self.assertTrue('example.com' in new_conf.mxs)
- def test_tls_version_default(self):
- p = policy.Policy({})
- self.assertEqual(p.min_tls_version, 'TLSv1.2')
-
def test_mode_default(self):
p = policy.Policy({})
self.assertEqual(p.mode, 'testing')
- def test_tls_version_valid(self):
- with self.assertRaises(util.ConfigError):
- policy.Policy({'min-tls-version': 'SSLv3'})
- p = policy.Policy({})
- with self.assertRaises(util.ConfigError):
- p.min_tls_version = 'SSLv3'
- p.min_tls_version = 'TLSv1.1'
- self.assertEqual(p.min_tls_version, 'TLSv1.1')
-
def test_mode_valid(self):
p = policy.Policy({})
with self.assertRaises(util.ConfigError):
| policy.py: Deprecation Warning
Run of testsuite showed to me following warning:
```
starttls_policy_cli/policy.py:220
/home/user/starttls-policy-cli/starttls_policy_cli/policy.py:220: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working
class Config(MergableConfig, collections.Mapping):
```
This issue should be addressed ASAP because Python 3.8.0 has already reached alpha 2 release. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"starttls_policy_cli/tests/policy_test.py::TestConfig::test_basic_parsing"
] | [
"starttls_policy_cli/tests/policy_test.py::TestConfigEncoder::test_encode_datetime",
"starttls_policy_cli/tests/policy_test.py::TestConfigEncoder::test_encode_empty_dict",
"starttls_policy_cli/tests/policy_test.py::TestConfigEncoder::test_encode_empty_list",
"starttls_policy_cli/tests/policy_test.py::TestConfigEncoder::test_encode_empty_string",
"starttls_policy_cli/tests/policy_test.py::TestConfigEncoder::test_encode_false",
"starttls_policy_cli/tests/policy_test.py::TestConfigEncoder::test_encode_float",
"starttls_policy_cli/tests/policy_test.py::TestConfigEncoder::test_encode_integer",
"starttls_policy_cli/tests/policy_test.py::TestConfigEncoder::test_encode_none",
"starttls_policy_cli/tests/policy_test.py::TestConfigEncoder::test_encode_true",
"starttls_policy_cli/tests/policy_test.py::TestConfig::test_bad_schema",
"starttls_policy_cli/tests/policy_test.py::TestConfig::test_flush",
"starttls_policy_cli/tests/policy_test.py::TestConfig::test_flush_default",
"starttls_policy_cli/tests/policy_test.py::TestConfig::test_iter_policies",
"starttls_policy_cli/tests/policy_test.py::TestConfig::test_iter_policies_aliased",
"starttls_policy_cli/tests/policy_test.py::TestConfig::test_keys_empty_policy",
"starttls_policy_cli/tests/policy_test.py::TestConfig::test_len_method",
"starttls_policy_cli/tests/policy_test.py::TestConfig::test_merge_keeps_old_policies",
"starttls_policy_cli/tests/policy_test.py::TestConfig::test_merge_keeps_old_settings",
"starttls_policy_cli/tests/policy_test.py::TestConfig::test_no_aliasing_in_alias",
"starttls_policy_cli/tests/policy_test.py::TestConfig::test_set_aliased_policy",
"starttls_policy_cli/tests/policy_test.py::TestConfig::test_set_author",
"starttls_policy_cli/tests/policy_test.py::TestConfig::test_set_policies",
"starttls_policy_cli/tests/policy_test.py::TestConfig::test_should_update_invalid_type",
"starttls_policy_cli/tests/policy_test.py::TestConfig::test_should_update_valid_type",
"starttls_policy_cli/tests/policy_test.py::TestConfig::test_timestamp_and_expires_required",
"starttls_policy_cli/tests/policy_test.py::TestConfig::test_update_drops_old_policies",
"starttls_policy_cli/tests/policy_test.py::TestConfig::test_update_drops_old_settings",
"starttls_policy_cli/tests/policy_test.py::TestConfig::test_updateble_checks_types",
"starttls_policy_cli/tests/policy_test.py::TestPolicy::test_alias_valid",
"starttls_policy_cli/tests/policy_test.py::TestPolicy::test_merge_keeps_old_mxs",
"starttls_policy_cli/tests/policy_test.py::TestPolicy::test_mode_default",
"starttls_policy_cli/tests/policy_test.py::TestPolicy::test_mode_valid",
"starttls_policy_cli/tests/policy_test.py::TestPolicy::test_mxs",
"starttls_policy_cli/tests/policy_test.py::TestPolicy::test_no_alias_policy_getter",
"starttls_policy_cli/tests/policy_test.py::TestPolicy::test_no_alias_policy_setter",
"starttls_policy_cli/tests/policy_test.py::TestPolicy::test_update_drops_old_mxs"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
} | "2019-03-06T19:31:28Z" | apache-2.0 |
|
EFForg__starttls-policy-cli-27 | diff --git a/starttls_policy_cli/policy.py b/starttls_policy_cli/policy.py
index b4ab17a..8b5aedb 100644
--- a/starttls_policy_cli/policy.py
+++ b/starttls_policy_cli/policy.py
@@ -210,7 +210,6 @@ class PolicyNoAlias(Policy):
@property
def policy_alias(self):
""" This type of policy can't be aliased. Returns None."""
- pass
@policy_alias.setter
def policy_alias(self, value):
@@ -238,6 +237,7 @@ class Config(MergableConfig, collections.Mapping):
yield domain
def keys(self):
+ """ Returns iterable over policies even if this attribute is not set """
if self.policies is None:
return set([])
return self.policies.keys()
diff --git a/starttls_policy_cli/util.py b/starttls_policy_cli/util.py
index 8f7da53..6b703a7 100644
--- a/starttls_policy_cli/util.py
+++ b/starttls_policy_cli/util.py
@@ -103,20 +103,14 @@ TLS_VERSIONS = ('TLSv1', 'TLSv1.1', 'TLSv1.2', 'TLSv1.3')
ENFORCE_MODES = ('testing', 'enforce')
POLICY_SCHEMA = {
- 'min-tls-version': {
- 'enforce': partial(enforce_in, TLS_VERSIONS),
- 'default': 'TLSv1.2',
- },
'mode': {
'enforce': partial(enforce_in, ENFORCE_MODES),
'default': 'testing',
},
- # TODO (#50) Validate mxs as FQDNs (using public suffix list)
'mxs': {
'enforce': partial(enforce_list, partial(enforce_type, six.string_types)),
'default': [],
},
- # TODO (#50) Validate reporting endpoint as https: or mailto:
'policy-alias': partial(enforce_type, six.string_types),
}
| EFForg/starttls-policy-cli | be1143dcfb2d54fe638a850f63f603aedb068e0c | diff --git a/starttls_policy_cli/tests/policy_test.py b/starttls_policy_cli/tests/policy_test.py
index 81a8fb1..994c7bd 100644
--- a/starttls_policy_cli/tests/policy_test.py
+++ b/starttls_policy_cli/tests/policy_test.py
@@ -16,7 +16,6 @@ test_json = '{\
"timestamp": "2014-05-26T01:35:33+0000",\
"policies": {\
".valid.example-recipient.com": {\
- "min-tls-version": "TLSv1.1",\
"mode": "enforce",\
"mxs": [".valid.example-recipient.com"]\
}\
@@ -166,8 +165,8 @@ class TestConfig(unittest.TestCase):
with self.assertRaises(util.ConfigError):
policy.Config().policies = {'invalid': invalid_policy}
conf = policy.Config()
- conf.policies = {'valid': {}}
- self.assertEqual(conf.get_policy_for('valid').min_tls_version, 'TLSv1.2')
+ conf.policies = {'valid': {'mxs': ['example.com']}}
+ self.assertEqual(conf.get_policy_for('valid').mxs, ['example.com'])
def test_set_aliased_policy(self):
conf = policy.Config()
@@ -175,7 +174,7 @@ class TestConfig(unittest.TestCase):
with self.assertRaises(util.ConfigError):
conf.policies = {'invalid': {'policy-alias': 'invalid'}}
conf.policies = {'valid': {'policy-alias': 'valid'}}
- self.assertEqual(conf.get_policy_for('valid').min_tls_version, 'TLSv1.2')
+ self.assertEqual(conf.get_policy_for('valid').mode, 'testing')
def test_iter_policies_aliased(self):
conf = policy.Config()
@@ -226,23 +225,10 @@ class TestPolicy(unittest.TestCase):
self.assertFalse('eff.org' in new_conf.mxs)
self.assertTrue('example.com' in new_conf.mxs)
- def test_tls_version_default(self):
- p = policy.Policy({})
- self.assertEqual(p.min_tls_version, 'TLSv1.2')
-
def test_mode_default(self):
p = policy.Policy({})
self.assertEqual(p.mode, 'testing')
- def test_tls_version_valid(self):
- with self.assertRaises(util.ConfigError):
- policy.Policy({'min-tls-version': 'SSLv3'})
- p = policy.Policy({})
- with self.assertRaises(util.ConfigError):
- p.min_tls_version = 'SSLv3'
- p.min_tls_version = 'TLSv1.1'
- self.assertEqual(p.min_tls_version, 'TLSv1.1')
-
def test_mode_valid(self):
p = policy.Policy({})
with self.assertRaises(util.ConfigError):
| Config parser schema contains field not present in format spec
[Field Enforcer](https://github.com/EFForg/starttls-policy-cli/blob/687dbbf99b683eebceb524fb93286d5ebfe57204/starttls_policy_cli/util.py#L102-L105) β [Format Spec](https://github.com/EFForg/starttls-everywhere/blob/master/RULES.md) | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"starttls_policy_cli/tests/policy_test.py::TestConfig::test_basic_parsing"
] | [
"starttls_policy_cli/tests/policy_test.py::TestConfigEncoder::test_encode_datetime",
"starttls_policy_cli/tests/policy_test.py::TestConfigEncoder::test_encode_empty_dict",
"starttls_policy_cli/tests/policy_test.py::TestConfigEncoder::test_encode_empty_list",
"starttls_policy_cli/tests/policy_test.py::TestConfigEncoder::test_encode_empty_string",
"starttls_policy_cli/tests/policy_test.py::TestConfigEncoder::test_encode_false",
"starttls_policy_cli/tests/policy_test.py::TestConfigEncoder::test_encode_float",
"starttls_policy_cli/tests/policy_test.py::TestConfigEncoder::test_encode_integer",
"starttls_policy_cli/tests/policy_test.py::TestConfigEncoder::test_encode_none",
"starttls_policy_cli/tests/policy_test.py::TestConfigEncoder::test_encode_true",
"starttls_policy_cli/tests/policy_test.py::TestConfig::test_bad_schema",
"starttls_policy_cli/tests/policy_test.py::TestConfig::test_flush",
"starttls_policy_cli/tests/policy_test.py::TestConfig::test_flush_default",
"starttls_policy_cli/tests/policy_test.py::TestConfig::test_iter_policies",
"starttls_policy_cli/tests/policy_test.py::TestConfig::test_iter_policies_aliased",
"starttls_policy_cli/tests/policy_test.py::TestConfig::test_keys_empty_policy",
"starttls_policy_cli/tests/policy_test.py::TestConfig::test_len_method",
"starttls_policy_cli/tests/policy_test.py::TestConfig::test_merge_keeps_old_policies",
"starttls_policy_cli/tests/policy_test.py::TestConfig::test_merge_keeps_old_settings",
"starttls_policy_cli/tests/policy_test.py::TestConfig::test_no_aliasing_in_alias",
"starttls_policy_cli/tests/policy_test.py::TestConfig::test_set_aliased_policy",
"starttls_policy_cli/tests/policy_test.py::TestConfig::test_set_author",
"starttls_policy_cli/tests/policy_test.py::TestConfig::test_set_policies",
"starttls_policy_cli/tests/policy_test.py::TestConfig::test_should_update_invalid_type",
"starttls_policy_cli/tests/policy_test.py::TestConfig::test_should_update_valid_type",
"starttls_policy_cli/tests/policy_test.py::TestConfig::test_timestamp_and_expires_required",
"starttls_policy_cli/tests/policy_test.py::TestConfig::test_update_drops_old_policies",
"starttls_policy_cli/tests/policy_test.py::TestConfig::test_update_drops_old_settings",
"starttls_policy_cli/tests/policy_test.py::TestConfig::test_updateble_checks_types",
"starttls_policy_cli/tests/policy_test.py::TestPolicy::test_alias_valid",
"starttls_policy_cli/tests/policy_test.py::TestPolicy::test_merge_keeps_old_mxs",
"starttls_policy_cli/tests/policy_test.py::TestPolicy::test_mode_default",
"starttls_policy_cli/tests/policy_test.py::TestPolicy::test_mode_valid",
"starttls_policy_cli/tests/policy_test.py::TestPolicy::test_mxs",
"starttls_policy_cli/tests/policy_test.py::TestPolicy::test_no_alias_policy_getter",
"starttls_policy_cli/tests/policy_test.py::TestPolicy::test_no_alias_policy_setter",
"starttls_policy_cli/tests/policy_test.py::TestPolicy::test_update_drops_old_mxs"
] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks",
"has_many_modified_files",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
} | "2019-03-08T19:23:07Z" | apache-2.0 |
|
ESMCI__cime-4019 | diff --git a/config/xml_schemas/config_machines.xsd b/config/xml_schemas/config_machines.xsd
index 1d8dba900..3dd64f15e 100644
--- a/config/xml_schemas/config_machines.xsd
+++ b/config/xml_schemas/config_machines.xsd
@@ -159,7 +159,7 @@
<xs:element ref="SUPPORTED_BY" minOccurs="1" maxOccurs="1"/>
<!-- MAX_TASKS_PER_NODE: maximum number of threads*tasks per
shared memory node on this machine-->
- <xs:element ref="MAX_TASKS_PER_NODE" minOccurs="1" maxOccurs="1"/>
+ <xs:element ref="MAX_TASKS_PER_NODE" minOccurs="1" maxOccurs="4"/>
<!-- MAX_GPUS_PER_NODE: maximum number of GPUs per node on this machine-->
<xs:element ref="MAX_GPUS_PER_NODE" minOccurs="0" maxOccurs="1"/>
<!-- MAX_MPITASKS_PER_NODE: number of physical PES per shared node on
diff --git a/scripts/lib/CIME/build.py b/scripts/lib/CIME/build.py
index 5ddeb50fd..d1b78e9e4 100644
--- a/scripts/lib/CIME/build.py
+++ b/scripts/lib/CIME/build.py
@@ -1,9 +1,12 @@
"""
functions for building CIME models
"""
-import glob, shutil, time, threading, subprocess, imp
+import glob, shutil, time, threading, subprocess
from CIME.XML.standard_module_setup import *
-from CIME.utils import get_model, analyze_build_log, stringify_bool, run_and_log_case_status, get_timestamp, run_sub_or_cmd, run_cmd, get_batch_script_for_job, gzip_existing_file, safe_copy, check_for_python, get_logging_options
+from CIME.utils import get_model, analyze_build_log, \
+ stringify_bool, run_and_log_case_status, get_timestamp, run_sub_or_cmd, \
+ run_cmd, get_batch_script_for_job, gzip_existing_file, safe_copy, \
+ check_for_python, get_logging_options, import_from_file
from CIME.provenance import save_build_provenance as save_build_provenance_sub
from CIME.locked_files import lock_file, unlock_file
from CIME.XML.files import Files
@@ -543,7 +546,8 @@ def _create_build_metadata_for_component(config_dir, libroot, bldroot, case):
"""
bc_path = os.path.join(config_dir, "buildlib_cmake")
expect(os.path.exists(bc_path), "Missing: {}".format(bc_path))
- buildlib = imp.load_source("buildlib_cmake", os.path.join(config_dir, "buildlib_cmake"))
+ buildlib = import_from_file("buildlib_cmake", os.path.join(config_dir,
+ "buildlib_cmake"))
cmake_args = buildlib.buildlib(bldroot, libroot, case)
return "" if cmake_args is None else cmake_args
diff --git a/scripts/lib/CIME/utils.py b/scripts/lib/CIME/utils.py
index 10b98228d..e4ef4dd97 100644
--- a/scripts/lib/CIME/utils.py
+++ b/scripts/lib/CIME/utils.py
@@ -2,7 +2,9 @@
Common functions used by cime python scripts
Warning: you cannot use CIME Classes in this module as it causes circular dependencies
"""
-import io, logging, gzip, sys, os, time, re, shutil, glob, string, random, imp, fnmatch
+import io, logging, gzip, sys, os, time, re, shutil, glob, string, random, \
+ importlib, fnmatch
+import importlib.util
import errno, signal, warnings, filecmp
import stat as statlib
import six
@@ -15,6 +17,19 @@ from distutils import file_util
TESTS_FAILED_ERR_CODE = 100
logger = logging.getLogger(__name__)
+def import_from_file(name, file_path):
+ loader = importlib.machinery.SourceFileLoader(name, file_path)
+
+ spec = importlib.util.spec_from_loader(loader.name, loader)
+
+ module = importlib.util.module_from_spec(spec)
+
+ sys.modules[name] = module
+
+ spec.loader.exec_module(module)
+
+ return module
+
@contextmanager
def redirect_stdout(new_target):
old_target, sys.stdout = sys.stdout, new_target # replace sys.stdout
@@ -414,7 +429,7 @@ def run_sub_or_cmd(cmd, cmdargs, subname, subargs, logfile=None, case=None,
if not do_run_cmd:
try:
- mod = imp.load_source(subname, cmd)
+ mod = import_from_file(subname, cmd)
logger.info(" Calling {}".format(cmd))
# Careful: logfile code is not thread safe!
if logfile:
| ESMCI/cime | f919e5809e34fe5564f306e9b70ff85458c13bca | diff --git a/scripts/lib/CIME/tests/test_utils.py b/scripts/lib/CIME/tests/test_utils.py
index dde52eff8..2759b5352 100644
--- a/scripts/lib/CIME/tests/test_utils.py
+++ b/scripts/lib/CIME/tests/test_utils.py
@@ -2,10 +2,12 @@
import os
import sys
+import tempfile
import unittest
from unittest import mock
-from CIME.utils import indent_string, run_and_log_case_status
+from CIME.utils import indent_string, run_and_log_case_status, \
+ import_from_file
from . import utils
@@ -87,6 +89,19 @@ class TestUtils(unittest.TestCase):
self.assertTrue(result, msg="\n".join(error))
+ def test_import_from_file(self):
+ with tempfile.NamedTemporaryFile() as fd:
+ fd.writelines([
+ b"def test():\n",
+ b" return 'value'",
+ ])
+
+ fd.flush()
+
+ module = import_from_file("test.py", fd.name)
+
+ assert module.test() == "value"
+
def test_run_and_log_case_status(self):
test_lines = [
"00:00:00 default starting \n",
diff --git a/scripts/tests/scripts_regression_tests.py b/scripts/tests/scripts_regression_tests.py
index 5c2377a97..6279fbbb1 100755
--- a/scripts/tests/scripts_regression_tests.py
+++ b/scripts/tests/scripts_regression_tests.py
@@ -22,7 +22,9 @@ import stat as osstat
import collections
-from CIME.utils import run_cmd, run_cmd_no_fail, get_lids, get_current_commit, safe_copy, CIMEError, get_cime_root, get_src_root, Timeout
+from CIME.utils import run_cmd, run_cmd_no_fail, get_lids, get_current_commit, \
+ safe_copy, CIMEError, get_cime_root, get_src_root, Timeout, \
+ import_from_file
import get_tests
import CIME.test_scheduler, CIME.wait_for_tests
from CIME.test_scheduler import TestScheduler
@@ -2431,19 +2433,16 @@ class K_TestCimeCase(TestCreateTestCommon):
###########################################################################
def test_case_submit_interface(self):
###########################################################################
- try:
- import imp
- except ImportError:
- print("imp not found, skipping case.submit interface test")
- return
# the current directory may not exist, so make sure we are in a real directory
os.chdir(os.getenv("HOME"))
sys.path.append(TOOLS_DIR)
case_submit_path = os.path.join(TOOLS_DIR, "case.submit")
- submit_interface = imp.load_source("case_submit_interface", case_submit_path)
+
+ module = import_from_file("case.submit", case_submit_path)
+
sys.argv = ["case.submit", "--batch-args", "'random_arguments_here.%j'",
"--mail-type", "fail", "--mail-user", "'random_arguments_here.%j'"]
- submit_interface._main_func(None, True)
+ module._main_func(None, True)
###########################################################################
def test_xml_caching(self):
| maxOccurs set to 1 for MAX_TASKS_PER_NODE breaks E3SM machine
PR #3989 introduced a change that breaks some E3SM machines.
Commit introducing the change https://github.com/sjsprecious/cime/commit/89a4292be3c78244e5042a8ad36453ae5407a7d8.
Machines broken with change
- **summit** https://github.com/E3SM-Project/E3SM/blob/d28e8771e4d33ea5e7179eeccf2e031a9838ac8c/cime_config/machines/config_machines.xml#L2715-L2742
- **ascent** https://github.com/E3SM-Project/E3SM/blob/d28e8771e4d33ea5e7179eeccf2e031a9838ac8c/cime_config/machines/config_machines.xml#L2867-L2894
Original error:
```bash
ERROR: Command: '/usr/bin/xmllint --xinclude --noout --schema E3SM/cime/config/xml_schemas/config_machines.xsd E3SM/cime_config/machines/config_machines.xml' failed with error 'E3SM/cime_config/machines/config_machines.xml:2737: element MAX_TASKS_PER_NODE: Schemas validity error : Element 'MAX_TASKS_PER_NODE': This element is not expected. Expected is one of ( MAX_GPUS_PER_NODE, MAX_MPITASKS_PER_NODE ).
E3SM/cime_config/machines/config_machines.xml:2896: element MAX_TASKS_PER_NODE: Schemas validity error : Element 'MAX_TASKS_PER_NODE': This element is not expected. Expected is one of ( MAX_GPUS_PER_NODE, MAX_MPITASKS_PER_NODE ).
E3SM/cime_config/machines/config_machines.xml fails to validate' from dir 'E3SM/cime/scripts'
``` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"scripts/lib/CIME/tests/test_utils.py::TestIndentStr::test_indent_string_multiline",
"scripts/lib/CIME/tests/test_utils.py::TestIndentStr::test_indent_string_singleline",
"scripts/lib/CIME/tests/test_utils.py::TestUtils::test_import_from_file",
"scripts/lib/CIME/tests/test_utils.py::TestUtils::test_run_and_log_case_status",
"scripts/lib/CIME/tests/test_utils.py::TestUtils::test_run_and_log_case_status_case_submit_error_on_batch",
"scripts/lib/CIME/tests/test_utils.py::TestUtils::test_run_and_log_case_status_case_submit_no_batch",
"scripts/lib/CIME/tests/test_utils.py::TestUtils::test_run_and_log_case_status_case_submit_on_batch",
"scripts/lib/CIME/tests/test_utils.py::TestUtils::test_run_and_log_case_status_custom_msg",
"scripts/lib/CIME/tests/test_utils.py::TestUtils::test_run_and_log_case_status_custom_msg_error_on_batch",
"scripts/lib/CIME/tests/test_utils.py::TestUtils::test_run_and_log_case_status_error"
] | [] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2021-06-28T22:31:10Z" | bsd-3-clause |
|
ESMCI__cime-4053 | diff --git a/scripts/lib/CIME/case/case.py b/scripts/lib/CIME/case/case.py
index e35b576da..d6f66c29f 100644
--- a/scripts/lib/CIME/case/case.py
+++ b/scripts/lib/CIME/case/case.py
@@ -1729,8 +1729,11 @@ directory, NOT in this subdirectory."""
lines_len = len(lines)
lines.insert(lines_len-1 if init else lines_len, "{}\n\n".format(cmd))
- with open(os.path.join(caseroot, "replay.sh"), "a") as fd:
- fd.writelines(lines)
+ try:
+ with open(os.path.join(caseroot, "replay.sh"), "a") as fd:
+ fd.writelines(lines)
+ except PermissionError:
+ logger.warning("Could not write to 'replay.sh' script")
def create(self, casename, srcroot, compset_name, grid_name,
user_mods_dirs=None, machine_name=None,
diff --git a/scripts/lib/CIME/provenance.py b/scripts/lib/CIME/provenance.py
index 6db56b6a6..30b0fc987 100644
--- a/scripts/lib/CIME/provenance.py
+++ b/scripts/lib/CIME/provenance.py
@@ -481,6 +481,7 @@ def _save_postrun_timing_e3sm(case, lid):
globs_to_copy.append("timing/*.{}*".format(lid))
globs_to_copy.append("CaseStatus")
globs_to_copy.append(os.path.join(rundir, "spio_stats.{}.tar.gz".format(lid)))
+ globs_to_copy.append(os.path.join(caseroot, "replay.sh"))
# Can't use a single glob, similar files e.g. {filename}.{lid} get picked up.
bld_filenames = ["GIT_STATUS", "GIT_DIFF", "GIT_LOG", "GIT_REMOTE",
"GIT_CONFIG", "GIT_SUBMODULE_STATUS"]
| ESMCI/cime | dbaa9b2d2b8e24e6ebbed33e252ba3b2f434b8cc | diff --git a/scripts/lib/CIME/tests/test_case.py b/scripts/lib/CIME/tests/test_case.py
index 6595b861b..8585fb2dd 100644
--- a/scripts/lib/CIME/tests/test_case.py
+++ b/scripts/lib/CIME/tests/test_case.py
@@ -216,6 +216,25 @@ class TestCase_RecordCmd(unittest.TestCase):
for x, y in zip(calls, expected):
self.assertTrue(x == y, calls)
+ @mock.patch("CIME.case.case.Case.__init__", return_value=None)
+ @mock.patch("CIME.case.case.Case.flush")
+ @mock.patch("CIME.case.case.Case.get_value")
+ @mock.patch("CIME.case.case.open", mock.mock_open())
+ @mock.patch("time.strftime", return_value="00:00:00")
+ @mock.patch("sys.argv", ["/src/create_newcase"])
+ def test_error(self, strftime, get_value, flush, init): # pylint: disable=unused-argument
+ Case._force_read_only = False # pylint: disable=protected-access
+
+ with self.tempdir as tempdir, mock.patch("CIME.case.case.open", mock.mock_open()) as m:
+ m.side_effect = PermissionError()
+
+ with Case(tempdir) as case:
+ get_value.side_effect = [
+ tempdir,
+ "/src"
+ ]
+
+ case.record_cmd()
@mock.patch("CIME.case.case.Case.__init__", return_value=None)
@mock.patch("CIME.case.case.Case.flush")
diff --git a/scripts/lib/CIME/tests/test_provenance.py b/scripts/lib/CIME/tests/test_provenance.py
index 89b619779..0263bac2d 100644
--- a/scripts/lib/CIME/tests/test_provenance.py
+++ b/scripts/lib/CIME/tests/test_provenance.py
@@ -1,125 +1,94 @@
import os
import sys
import unittest
+from unittest import mock
from CIME import provenance
-from . import utils
-
class TestProvenance(unittest.TestCase):
- def test_run_git_cmd_recursively(self):
- with utils.Mocker() as mock:
- open_mock = mock.patch(
- "builtins.open" if sys.version_info.major > 2 else
- "__builtin__.open",
- ret=utils.Mocker()
- )
- provenance.run_cmd = utils.Mocker(return_value=(0, "data", None))
- provenance._run_git_cmd_recursively('status', '/srcroot', '/output.txt') # pylint: disable=protected-access
-
- self.assertTrue(
- open_mock.calls[0]["args"] == ("/output.txt", "w"),
- open_mock.calls
- )
-
- write = open_mock.ret.method_calls["write"]
-
- self.assertTrue(write[0]["args"][0] == "data\n\n", write)
- self.assertTrue(write[1]["args"][0] == "data\n", write)
-
- run_cmd = provenance.run_cmd.calls
-
- self.assertTrue(run_cmd[0]["args"][0] == "git status")
- self.assertTrue(run_cmd[0]["kwargs"]["from_dir"] == "/srcroot")
-
- self.assertTrue(run_cmd[1]["args"][0] == "git submodule foreach"
- " --recursive \"git status; echo\"", run_cmd)
- self.assertTrue(run_cmd[1]["kwargs"]["from_dir"] == "/srcroot")
-
- def test_run_git_cmd_recursively_error(self):
- with utils.Mocker() as mock:
- open_mock = mock.patch(
- "builtins.open" if sys.version_info.major > 2 else
- "__builtin__.open",
- ret=utils.Mocker()
- )
- provenance.run_cmd = utils.Mocker(return_value=(1, "data", "error"))
- provenance._run_git_cmd_recursively('status', '/srcroot', '/output.txt') # pylint: disable=protected-access
-
- write = open_mock.ret.method_calls["write"]
-
- self.assertTrue(write[0]["args"][0] == "error\n\n", write)
- self.assertTrue(write[1]["args"][0] == "error\n", write)
-
- run_cmd = provenance.run_cmd.calls
-
- self.assertTrue(run_cmd[0]["args"][0] == "git status")
- self.assertTrue(run_cmd[0]["kwargs"]["from_dir"] == "/srcroot")
-
- self.assertTrue(run_cmd[1]["args"][0] == "git submodule foreach"
- " --recursive \"git status; echo\"", run_cmd)
- self.assertTrue(run_cmd[1]["kwargs"]["from_dir"] == "/srcroot")
-
- def test_record_git_provenance(self):
- with utils.Mocker() as mock:
- open_mock = mock.patch(
- "builtins.open" if sys.version_info.major > 2 else
- "__builtin__.open",
- ret=utils.Mocker()
- )
-
- provenance.safe_copy = utils.Mocker()
- provenance.run_cmd = utils.Mocker(return_value=(0, "data", None))
- provenance._record_git_provenance("/srcroot", "/output", "5") # pylint: disable=protected-access
+ @mock.patch("CIME.provenance.run_cmd")
+ def test_run_git_cmd_recursively(self, run_cmd):
+ run_cmd.return_value = (0, "data", None)
+
+ with mock.patch("CIME.provenance.open", mock.mock_open()) as m:
+ provenance._run_git_cmd_recursively("status", "/srcroot", "/output.txt") # pylint: disable=protected-access
+
+ m.assert_called_with("/output.txt", "w")
+
+ write = m.return_value.__enter__.return_value.write
+
+ write.assert_any_call("data\n\n")
+ write.assert_any_call("data\n")
+
+ run_cmd.assert_any_call("git status", from_dir="/srcroot")
+ run_cmd.assert_any_call(
+ "git submodule foreach --recursive \"git status; echo\"",
+ from_dir="/srcroot")
- expected = [
- ("/output/GIT_STATUS.5", "w"),
- ("/output/GIT_DIFF.5", "w"),
- ("/output/GIT_LOG.5", "w"),
- ("/output/GIT_REMOTE.5", "w")
- ]
+ @mock.patch("CIME.provenance.run_cmd")
+ def test_run_git_cmd_recursively_error(self, run_cmd):
+ run_cmd.return_value = (1, "data", "error")
- for i in range(4):
- self.assertTrue(
- open_mock.calls[i]["args"] == expected[i],
- open_mock.calls
- )
+ with mock.patch("CIME.provenance.open", mock.mock_open()) as m:
+ provenance._run_git_cmd_recursively("status", "/srcroot", "/output.txt") # pylint: disable=protected-access
- write = open_mock.ret.method_calls["write"]
+ m.assert_called_with("/output.txt", "w")
- expected = [
- "data\n\n",
- "data\n",
- ]
+ write = m.return_value.__enter__.return_value.write
- for x in range(8):
- self.assertTrue(write[x]["args"][0] == expected[x%2], write)
+ write.assert_any_call("error\n\n")
+ write.assert_any_call("error\n")
- run_cmd = provenance.run_cmd.calls
+ run_cmd.assert_any_call("git status", from_dir="/srcroot")
+ run_cmd.assert_any_call(
+ "git submodule foreach --recursive \"git status; echo\"",
+ from_dir="/srcroot")
+
+ @mock.patch("CIME.provenance.safe_copy")
+ @mock.patch("CIME.provenance.run_cmd")
+ def test_record_git_provenance(self, run_cmd, safe_copy):
+ run_cmd.return_value = (0, "data", None)
+
+ with mock.patch("CIME.provenance.open", mock.mock_open()) as m:
+ provenance._record_git_provenance("/srcroot", "/output", "5") # pylint: disable=protected-access
- expected = [
- "git status",
+ m.assert_any_call("/output/GIT_STATUS.5", "w")
+ m.assert_any_call("/output/GIT_DIFF.5", "w")
+ m.assert_any_call("/output/GIT_LOG.5", "w")
+ m.assert_any_call("/output/GIT_REMOTE.5", "w")
+
+ write = m.return_value.__enter__.return_value.write
+
+ write.assert_any_call("data\n\n")
+ write.assert_any_call("data\n")
+
+ run_cmd.assert_any_call("git status", from_dir="/srcroot")
+ run_cmd.assert_any_call(
"git submodule foreach --recursive \"git status; echo\"",
+ from_dir="/srcroot")
+ run_cmd.assert_any_call(
"git diff",
+ from_dir="/srcroot")
+ run_cmd.assert_any_call(
"git submodule foreach --recursive \"git diff; echo\"",
+ from_dir="/srcroot")
+ run_cmd.assert_any_call(
"git log --first-parent --pretty=oneline -n 5",
+ from_dir="/srcroot")
+ run_cmd.assert_any_call(
"git submodule foreach --recursive \"git log --first-parent"
- " --pretty=oneline -n 5; echo\"",
+ " --pretty=oneline -n 5; echo\"",
+ from_dir="/srcroot")
+ run_cmd.assert_any_call(
"git remote -v",
+ from_dir="/srcroot")
+ run_cmd.assert_any_call(
"git submodule foreach --recursive \"git remote -v; echo\"",
- ]
-
- for x in range(len(run_cmd)):
- self.assertTrue(run_cmd[x]["args"][0] == expected[x], run_cmd[x])
-
- self.assertTrue(
- provenance.safe_copy.calls[0]["args"][0] == "/srcroot/.git/config",
- provenance.safe_copy.calls
- )
- self.assertTrue(
- provenance.safe_copy.calls[0]["args"][1] == "/output/GIT_CONFIG.5",
- provenance.safe_copy.calls
- )
+ from_dir="/srcroot")
+
+ safe_copy.assert_any_call("/srcroot/.git/config",
+ "/output/GIT_CONFIG.5",
+ preserve_meta=False)
if __name__ == '__main__':
sys.path.insert(0, os.path.abspath(os.path.join('.', '..', '..', 'lib')))
| replay.sh: Capture script in provenance.py for archiving (E3SM)
We need to archive replay.sh in performance archive so that it can be picked up by PACE for E3SM.
Logic needs to be added to https://github.com/ESMCI/cime/blob/master/scripts/lib/CIME/provenance.py#L400
cc @jasonb5 @rljacob | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"scripts/lib/CIME/tests/test_case.py::TestCase_RecordCmd::test_error"
] | [
"scripts/lib/CIME/tests/test_case.py::TestCaseSubmit::test__submit",
"scripts/lib/CIME/tests/test_case.py::TestCaseSubmit::test_check_case",
"scripts/lib/CIME/tests/test_case.py::TestCaseSubmit::test_submit",
"scripts/lib/CIME/tests/test_case.py::TestCase::test_copy",
"scripts/lib/CIME/tests/test_case.py::TestCase::test_create",
"scripts/lib/CIME/tests/test_case.py::TestCase::test_new_hash",
"scripts/lib/CIME/tests/test_case.py::TestCase_RecordCmd::test_cmd_arg",
"scripts/lib/CIME/tests/test_case.py::TestCase_RecordCmd::test_init",
"scripts/lib/CIME/tests/test_case.py::TestCase_RecordCmd::test_sub_relative",
"scripts/lib/CIME/tests/test_provenance.py::TestProvenance::test_record_git_provenance",
"scripts/lib/CIME/tests/test_provenance.py::TestProvenance::test_run_git_cmd_recursively",
"scripts/lib/CIME/tests/test_provenance.py::TestProvenance::test_run_git_cmd_recursively_error"
] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2021-07-22T23:14:28Z" | bsd-3-clause |
|
ESMCI__cime-4058 | diff --git a/ChangeLog b/ChangeLog
index 546ffca7e..b715a4a20 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,5 +1,55 @@
======================================================================
+Originator: Chris Fischer
+Date: 8-2-2021
+Tag: cime6.0.4
+Answer Changes: None
+Tests: scripts_regression_tests
+Dependencies:
+
+Brief Summary:
+ - Fix replay archive.
+ - Prepend the casename to mpas component restart file search in st_archive.
+ - Fix e3sm archiving.
+ - Check the size of read only xml files.
+ - Ensure Cmake is available for wait_for_tests.
+ - Fix the failure of ensemble consistency tests for PGI/NVHPC compiler on Casper.
+ - Fix type in centos7-linux definition.
+ - jenkins_generic_job: no reason for this magic config setting here.
+
+User interface changes:
+
+PR summary: git log --oneline --first-parent [previous_tag]..master
+c6f489356 Merge pull request #4053 from jasonb5/fix_replay_archive
+dbaa9b2d2 Merge pull request #4057 from ESMCI/jonbob/fix_mpas_archive_naming
+1ee229961 Merge pull request #4055 from jasonb5/fix_e3sm_archiving
+705640271 Merge pull request #4056 from jedwards4b/jedwards/checksize_of_xml
+231c8e783 Merge pull request #4052 from ESMCI/jgfouca/fix_cmake_avail_for_wft
+4961a210a Merge pull request #4048 from sjsprecious/fix_ect_failure
+d72fc45f1 fix typo in centos7-linux definition
+49342dca5 Merge pull request #4046 from ESMCI/jgfouca/remove_dumb_config
+
+
+Modified files: git diff --name-status [previous_tag]
+M config/cesm/machines/Depends.nvhpc-gpu
+M config/cesm/machines/Depends.pgi-gpu
+M config/cesm/machines/config_compilers.xml
+M config/cesm/machines/config_machines.xml
+M scripts/Tools/jenkins_generic_job
+M scripts/lib/CIME/XML/generic_xml.py
+M scripts/lib/CIME/case/case.py
+M scripts/lib/CIME/case/case_st_archive.py
+M scripts/lib/CIME/provenance.py
+M scripts/lib/CIME/tests/test_case.py
+M scripts/lib/CIME/tests/test_provenance.py
+M scripts/lib/CIME/wait_for_tests.py
+M scripts/tests/scripts_regression_tests.py
+
+
+======================================================================
+
+======================================================================
+
Originator: Bill Sacks
Date: 7-15-2021
Tag: cime6.0.3
diff --git a/scripts/lib/CIME/build.py b/scripts/lib/CIME/build.py
index d1b78e9e4..10841e553 100644
--- a/scripts/lib/CIME/build.py
+++ b/scripts/lib/CIME/build.py
@@ -6,7 +6,7 @@ from CIME.XML.standard_module_setup import *
from CIME.utils import get_model, analyze_build_log, \
stringify_bool, run_and_log_case_status, get_timestamp, run_sub_or_cmd, \
run_cmd, get_batch_script_for_job, gzip_existing_file, safe_copy, \
- check_for_python, get_logging_options, import_from_file
+ is_python_executable, get_logging_options, import_from_file
from CIME.provenance import save_build_provenance as save_build_provenance_sub
from CIME.locked_files import lock_file, unlock_file
from CIME.XML.files import Files
@@ -516,7 +516,7 @@ def _build_model_thread(config_dir, compclass, compname, caseroot, libroot, bldr
if get_model() != "ufs":
compile_cmd = "SMP={} {}".format(stringify_bool(smp), compile_cmd)
- if check_for_python(cmd):
+ if is_python_executable(cmd):
logging_options = get_logging_options()
if logging_options != "":
compile_cmd = compile_cmd + logging_options
diff --git a/scripts/lib/CIME/case/case_setup.py b/scripts/lib/CIME/case/case_setup.py
index f2d0e5cdf..d40c83777 100644
--- a/scripts/lib/CIME/case/case_setup.py
+++ b/scripts/lib/CIME/case/case_setup.py
@@ -3,16 +3,18 @@ Library for case.setup.
case_setup is a member of class Case from file case.py
"""
+import errno
+
from CIME.XML.standard_module_setup import *
from CIME.XML.machines import Machines
from CIME.BuildTools.configure import configure
-from CIME.utils import get_cime_root, run_and_log_case_status, get_model, get_batch_script_for_job, safe_copy
+from CIME.utils import run_and_log_case_status, get_model, \
+ get_batch_script_for_job, safe_copy, file_contains_python_function, import_from_file
from CIME.utils import batch_jobid
from CIME.utils import transform_vars
from CIME.test_status import *
from CIME.locked_files import unlock_file, lock_file
-import errno
logger = logging.getLogger(__name__)
@@ -50,24 +52,60 @@ def _build_usernl_files(case, model, comp):
ninst = case.get_value("NINST")
elif ninst == 1:
ninst = case.get_value("NINST_{}".format(model))
- nlfile = "user_nl_{}".format(comp)
- model_nl = os.path.join(model_dir, nlfile)
- if ninst > 1:
- for inst_counter in range(1, ninst+1):
- inst_nlfile = "{}_{:04d}".format(nlfile, inst_counter)
- if not os.path.exists(inst_nlfile):
- # If there is a user_nl_foo in the case directory, copy it
- # to user_nl_foo_INST; otherwise, copy the original
- # user_nl_foo from model_dir
- if os.path.exists(nlfile):
- safe_copy(nlfile, inst_nlfile)
- elif os.path.exists(model_nl):
- safe_copy(model_nl, inst_nlfile)
- else:
- # ninst = 1
- if not os.path.exists(nlfile):
- if os.path.exists(model_nl):
- safe_copy(model_nl, nlfile)
+ default_nlfile = "user_nl_{}".format(comp)
+ model_nl = os.path.join(model_dir, default_nlfile)
+ user_nl_list = _get_user_nl_list(case, default_nlfile, model_dir)
+ # Note that, even if there are multiple elements of user_nl_list (i.e., we are
+ # creating multiple user_nl files for this component with different names), all of
+ # them will start out as copies of the single user_nl_comp file in the model's
+ # source tree.
+ for nlfile in user_nl_list:
+ if ninst > 1:
+ for inst_counter in range(1, ninst+1):
+ inst_nlfile = "{}_{:04d}".format(nlfile, inst_counter)
+ if not os.path.exists(inst_nlfile):
+ # If there is a user_nl_foo in the case directory, copy it
+ # to user_nl_foo_INST; otherwise, copy the original
+ # user_nl_foo from model_dir
+ if os.path.exists(nlfile):
+ safe_copy(nlfile, inst_nlfile)
+ elif os.path.exists(model_nl):
+ safe_copy(model_nl, inst_nlfile)
+ else:
+ # ninst = 1
+ if not os.path.exists(nlfile):
+ if os.path.exists(model_nl):
+ safe_copy(model_nl, nlfile)
+
+###############################################################################
+def _get_user_nl_list(case, default_nlfile, model_dir):
+ """Get a list of user_nl files needed by this component
+
+ Typically, each component has a single user_nl file: user_nl_comp. However, some
+ components use multiple user_nl files. These components can define a function in
+ cime_config/buildnml named get_user_nl_list, which returns a list of user_nl files
+ that need to be staged in the case directory. For example, in a run where CISM is
+ modeling both Antarctica and Greenland, its get_user_nl_list function will return
+ ['user_nl_cism', 'user_nl_cism_ais', 'user_nl_cism_gris'].
+
+ If that function is NOT defined in the component's buildnml, then we return the given
+ default_nlfile.
+
+ """
+ # Check if buildnml is present in the expected location, and if so, whether it
+ # contains the function "get_user_nl_list"; if so, we'll import the module and call
+ # that function; if not, we'll fall back on the default value.
+ buildnml_path = os.path.join(model_dir, "buildnml")
+ has_function = False
+ if (os.path.isfile(buildnml_path) and
+ file_contains_python_function(buildnml_path, "get_user_nl_list")):
+ has_function = True
+
+ if has_function:
+ comp_buildnml = import_from_file("comp_buildnml", buildnml_path)
+ return comp_buildnml.get_user_nl_list(case)
+ else:
+ return [default_nlfile]
###############################################################################
def _case_setup_impl(case, caseroot, clean=False, test_mode=False, reset=False, keep=None):
diff --git a/scripts/lib/CIME/nmlgen.py b/scripts/lib/CIME/nmlgen.py
index 58cd182fd..a4891cf15 100644
--- a/scripts/lib/CIME/nmlgen.py
+++ b/scripts/lib/CIME/nmlgen.py
@@ -106,10 +106,15 @@ class NamelistGenerator(object):
skip_default_for_groups=None):
"""Return array of names of all definition nodes
+ infiles should be a list of file paths, each one giving namelist settings that
+ take precedence over the default values. Often there will be only one file in this
+ list. If there are multiple files, earlier files take precedence over later files.
+
If skip_default_for_groups is provided, it should be a list of namelist group
names; the add_default call will not be done for any variables in these
groups. This is often paired with later conditional calls to
add_defaults_for_group.
+
"""
if skip_default_for_groups is None:
skip_default_for_groups = []
diff --git a/scripts/lib/CIME/utils.py b/scripts/lib/CIME/utils.py
index c77f9f044..b88bbfcd1 100644
--- a/scripts/lib/CIME/utils.py
+++ b/scripts/lib/CIME/utils.py
@@ -396,18 +396,31 @@ def _convert_to_fd(filearg, from_dir, mode="a"):
_hack=object()
-def check_for_python(filepath, funcname=None):
- is_python = is_python_executable(filepath)
- has_function = True
- if funcname is not None:
- has_function = False
- with open(filepath, 'r') as fd:
- for line in fd.readlines():
- if re.search(r"^def\s+{}\(".format(funcname), line) or re.search(r"^from.+import.+\s{}".format(funcname), line):
- has_function = True
- break
+def _line_defines_python_function(line, funcname):
+ """Returns True if the given line defines the function 'funcname' as a top-level definition
+
+ ("top-level definition" means: not something like a class method; i.e., the def should
+ be at the start of the line, not indented)
+
+ """
+ if (re.search(r"^def\s+{}\s*\(".format(funcname), line) or
+ re.search(r"^from\s.+\simport.*\s{}(?:,|\s|$)".format(funcname), line)):
+ return True
+ return False
+
+def file_contains_python_function(filepath, funcname):
+ """Checks whether the given file contains a top-level definition of the function 'funcname'
+
+ Returns a boolean value (True if the file contains this function definition, False otherwise)
+ """
+ has_function = False
+ with open(filepath, 'r') as fd:
+ for line in fd.readlines():
+ if (_line_defines_python_function(line, funcname)):
+ has_function = True
+ break
- return is_python and has_function
+ return has_function
def run_sub_or_cmd(cmd, cmdargs, subname, subargs, logfile=None, case=None,
from_dir=None, timeout=None):
@@ -417,15 +430,10 @@ def run_sub_or_cmd(cmd, cmdargs, subname, subargs, logfile=None, case=None,
Raises exception on failure.
"""
- do_run_cmd = True
-
- # Before attempting to load the script make sure it contains the subroutine
- # we are expecting
- with open(cmd, 'r') as fd:
- for line in fd.readlines():
- if re.search(r"^def {}\(".format(subname), line):
- do_run_cmd = False
- break
+ if file_contains_python_function(cmd, subname):
+ do_run_cmd = False
+ else:
+ do_run_cmd = True
if not do_run_cmd:
try:
| ESMCI/cime | c6f489356fd385c465eec285b0321c09c12b2e97 | diff --git a/scripts/lib/CIME/tests/test_utils.py b/scripts/lib/CIME/tests/test_utils.py
old mode 100644
new mode 100755
index ed7ea3d7b..dad176b8e
--- a/scripts/lib/CIME/tests/test_utils.py
+++ b/scripts/lib/CIME/tests/test_utils.py
@@ -1,15 +1,17 @@
#!/usr/bin/env python3
import os
+import shutil
import sys
import tempfile
import unittest
from unittest import mock
from CIME.utils import indent_string, run_and_log_case_status, \
- import_from_file
+ import_from_file, \
+ _line_defines_python_function, file_contains_python_function
-from . import utils
+from CIME.tests import utils
class TestIndentStr(unittest.TestCase):
"""Test the indent_string function.
@@ -40,6 +42,120 @@ goodbye
"""
self.assertEqual(expected, result)
+class TestLineDefinesPythonFunction(unittest.TestCase):
+ """Tests of _line_defines_python_function"""
+
+ # ------------------------------------------------------------------------
+ # Tests of _line_defines_python_function that should return True
+ # ------------------------------------------------------------------------
+
+ def test_def_foo(self):
+ """Test of a def of the function of interest"""
+ line = "def foo():"
+ self.assertTrue(_line_defines_python_function(line, "foo"))
+
+ def test_def_foo_space(self):
+ """Test of a def of the function of interest, with an extra space before the parentheses"""
+ line = "def foo ():"
+ self.assertTrue(_line_defines_python_function(line, "foo"))
+
+ def test_import_foo(self):
+ """Test of an import of the function of interest"""
+ line = "from bar.baz import foo"
+ self.assertTrue(_line_defines_python_function(line, "foo"))
+
+ def test_import_foo_space(self):
+ """Test of an import of the function of interest, with trailing spaces"""
+ line = "from bar.baz import foo "
+ self.assertTrue(_line_defines_python_function(line, "foo"))
+
+ def test_import_foo_then_others(self):
+ """Test of an import of the function of interest, along with others"""
+ line = "from bar.baz import foo, bar"
+ self.assertTrue(_line_defines_python_function(line, "foo"))
+
+ def test_import_others_then_foo(self):
+ """Test of an import of the function of interest, after others"""
+ line = "from bar.baz import bar, foo"
+ self.assertTrue(_line_defines_python_function(line, "foo"))
+
+ # ------------------------------------------------------------------------
+ # Tests of _line_defines_python_function that should return False
+ # ------------------------------------------------------------------------
+
+ def test_def_barfoo(self):
+ """Test of a def of a different function"""
+ line = "def barfoo():"
+ self.assertFalse(_line_defines_python_function(line, "foo"))
+
+ def test_def_foobar(self):
+ """Test of a def of a different function"""
+ line = "def foobar():"
+ self.assertFalse(_line_defines_python_function(line, "foo"))
+
+ def test_def_foo_indented(self):
+ """Test of a def of the function of interest, but indented"""
+ line = " def foo():"
+ self.assertFalse(_line_defines_python_function(line, "foo"))
+
+ def test_def_foo_no_parens(self):
+ """Test of a def of the function of interest, but without parentheses"""
+ line = "def foo:"
+ self.assertFalse(_line_defines_python_function(line, "foo"))
+
+ def test_import_foo_indented(self):
+ """Test of an import of the function of interest, but indented"""
+ line = " from bar.baz import foo"
+ self.assertFalse(_line_defines_python_function(line, "foo"))
+
+ def test_import_barfoo(self):
+ """Test of an import of a different function"""
+ line = "from bar.baz import barfoo"
+ self.assertFalse(_line_defines_python_function(line, "foo"))
+
+ def test_import_foobar(self):
+ """Test of an import of a different function"""
+ line = "from bar.baz import foobar"
+ self.assertFalse(_line_defines_python_function(line, "foo"))
+
+class TestFileContainsPythonFunction(unittest.TestCase):
+ """Tests of file_contains_python_function"""
+
+ def setUp(self):
+ self._workdir = tempfile.mkdtemp()
+
+ def tearDown(self):
+ shutil.rmtree(self._workdir, ignore_errors=True)
+
+ def create_test_file(self, contents):
+ """Creates a test file with the given contents, and returns the path to that file"""
+
+ filepath = os.path.join(self._workdir, "testfile")
+ with open(filepath, 'w') as fd:
+ fd.write(contents)
+
+ return filepath
+
+ def test_contains_correct_def_and_others(self):
+ """Test file_contains_python_function with a correct def mixed with other defs"""
+ contents = """
+def bar():
+def foo():
+def baz():
+"""
+ filepath = self.create_test_file(contents)
+ self.assertTrue(file_contains_python_function(filepath, "foo"))
+
+ def test_does_not_contain_correct_def(self):
+ """Test file_contains_python_function without the correct def"""
+ contents = """
+def bar():
+def notfoo():
+def baz():
+"""
+ filepath = self.create_test_file(contents)
+ self.assertFalse(file_contains_python_function(filepath, "foo"))
+
class MockTime(object):
def __init__(self):
self._old = None
@@ -216,4 +332,3 @@ class TestUtils(unittest.TestCase):
if __name__ == '__main__':
unittest.main()
-
| Support the creation of multiple user_nl files for a component
CISM in CESM will soon support running multiple ice sheets in the same case. Each of these ice sheets will have its own config file (similar to a namelist file), with different settings. Therefore, in a run containing Greenland and Antarctica (for example) we need a way for users to be able to separately specify settings in the `user_nl_cism` file that apply (1) to both ice sheets; (2) just Greenland; (3) just Antarctica.
Based on discussion here https://github.com/ESCOMP/CISM-wrapper/issues/50 the user_nl_cism file will look like this:
```
! Settings that apply to all ice sheets go here
myvar = myvalue
[gris]
! Settings that apply to Greenland (if present) go here
foo = value1
bar = value2
[ais]
! Settings that apply to Antarctica (if present) go here
foo = value3
baz = value4
```
I propose adding a function to CIME (in `user_mod_support.py`) to parse a file like this, outputting a new file that just contains the requested subset of settings. In CISM's buildnml, we would then call this function three times:
First, we'd request a file that just contains settings that apply to all ice sheets (this is needed to create the top-level `cism_in` file): `separate_user_nl(..., section=None)`, which would produce:
```
! Settings that apply to all ice sheets go here
myvar = myvalue
```
Then we would call `separate_user_nl(..., section='gris')`, which would produce:
```
! Settings that apply to all ice sheets go here
myvar = myvalue
[gris]
! Settings that apply to Greenland (if present) go here
foo = value1
bar = value2
```
Finally, we would call `separate_user_nl(..., section='ais')`, which would produce:
```
! Settings that apply to all ice sheets go here
myvar = myvalue
[ais]
! Settings that apply to Antarctica (if present) go here
foo = value3
baz = value4
```
(Note: It's intentional that the settings that apply to all ice sheets appear in all cases. This section can contain a mix of settings that (a) go in `cism_in`, which contains non-icesheet-specific settings, and (b) go in *all* `cism.config` files β i.e., ice sheet-specific settings, but for which the user wants the same setting to apply to all ice sheets.)
I hope to implement this in the next week or so. I am opening this to gather any feedback on:
1. **Are there any objections to putting this functionality in CIME?** I could put it in CISM, but I prefer putting it in CIME for two reasons: (i) I would like to cover this functionality with unit tests; putting it in CISM would require me to build up a new python unit testing infrastructure in CISM. (ii) Maybe this could be useful for other components for some related or different purpose.
2. **Are there any objections to the format of the `user_nl` file proposed above?** We are not completely tied to this format, though we (@whlipscomb, @mvertens and I) prefer it over other options we considered (see https://github.com/ESCOMP/CISM-wrapper/issues/50). | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"scripts/lib/CIME/tests/test_utils.py::TestIndentStr::test_indent_string_multiline",
"scripts/lib/CIME/tests/test_utils.py::TestIndentStr::test_indent_string_singleline",
"scripts/lib/CIME/tests/test_utils.py::TestLineDefinesPythonFunction::test_def_barfoo",
"scripts/lib/CIME/tests/test_utils.py::TestLineDefinesPythonFunction::test_def_foo",
"scripts/lib/CIME/tests/test_utils.py::TestLineDefinesPythonFunction::test_def_foo_indented",
"scripts/lib/CIME/tests/test_utils.py::TestLineDefinesPythonFunction::test_def_foo_no_parens",
"scripts/lib/CIME/tests/test_utils.py::TestLineDefinesPythonFunction::test_def_foo_space",
"scripts/lib/CIME/tests/test_utils.py::TestLineDefinesPythonFunction::test_def_foobar",
"scripts/lib/CIME/tests/test_utils.py::TestLineDefinesPythonFunction::test_import_barfoo",
"scripts/lib/CIME/tests/test_utils.py::TestLineDefinesPythonFunction::test_import_foo",
"scripts/lib/CIME/tests/test_utils.py::TestLineDefinesPythonFunction::test_import_foo_indented",
"scripts/lib/CIME/tests/test_utils.py::TestLineDefinesPythonFunction::test_import_foo_space",
"scripts/lib/CIME/tests/test_utils.py::TestLineDefinesPythonFunction::test_import_foo_then_others",
"scripts/lib/CIME/tests/test_utils.py::TestLineDefinesPythonFunction::test_import_foobar",
"scripts/lib/CIME/tests/test_utils.py::TestLineDefinesPythonFunction::test_import_others_then_foo",
"scripts/lib/CIME/tests/test_utils.py::TestFileContainsPythonFunction::test_contains_correct_def_and_others",
"scripts/lib/CIME/tests/test_utils.py::TestFileContainsPythonFunction::test_does_not_contain_correct_def",
"scripts/lib/CIME/tests/test_utils.py::TestUtils::test_import_from_file",
"scripts/lib/CIME/tests/test_utils.py::TestUtils::test_run_and_log_case_status",
"scripts/lib/CIME/tests/test_utils.py::TestUtils::test_run_and_log_case_status_case_submit_error_on_batch",
"scripts/lib/CIME/tests/test_utils.py::TestUtils::test_run_and_log_case_status_case_submit_no_batch",
"scripts/lib/CIME/tests/test_utils.py::TestUtils::test_run_and_log_case_status_case_submit_on_batch",
"scripts/lib/CIME/tests/test_utils.py::TestUtils::test_run_and_log_case_status_custom_msg",
"scripts/lib/CIME/tests/test_utils.py::TestUtils::test_run_and_log_case_status_custom_msg_error_on_batch",
"scripts/lib/CIME/tests/test_utils.py::TestUtils::test_run_and_log_case_status_error"
] | [] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2021-07-30T22:02:39Z" | bsd-3-clause |
|
ESSS__conda-devenv-51 | diff --git a/HISTORY.rst b/HISTORY.rst
index 608aaa0..f9fafd4 100644
--- a/HISTORY.rst
+++ b/HISTORY.rst
@@ -3,6 +3,12 @@ History
=======
+0.9.5 (2017-04-24)
+------------------
+
+* Handle ``None`` correctly, which actually fixes (`#49`_).
+
+
0.9.4 (2017-04-20)
------------------
diff --git a/conda_devenv/devenv.py b/conda_devenv/devenv.py
index 16d174c..44df72e 100644
--- a/conda_devenv/devenv.py
+++ b/conda_devenv/devenv.py
@@ -373,7 +373,7 @@ def main(args=None):
# Call conda-env update
retcode = __call_conda_env_update(args, output_filename)
- if retcode != 0:
+ if retcode:
return retcode
if is_devenv_input_file:
| ESSS/conda-devenv | 320f7fdd672abf4122506850982a6b4095614e55 | diff --git a/tests/test_main.py b/tests/test_main.py
index 4f0db10..feb2425 100644
--- a/tests/test_main.py
+++ b/tests/test_main.py
@@ -21,16 +21,20 @@ def patch_conda_calls(mocker):
('environment.devenv.yml', 1),
('environment.yml', 0),
])
[email protected]('return_none', [True, False])
@pytest.mark.usefixtures('patch_conda_calls')
-def test_handle_input_file(tmpdir, input_name, write_scripts_call_count):
+def test_handle_input_file(tmpdir, input_name, write_scripts_call_count, return_none):
"""
Test how conda-devenv handles input files: devenv.yml and pure .yml files.
"""
argv = []
def call_conda_mock():
argv[:] = sys.argv[:]
- # simulate that we actually called conda's main, which calls sys.exit()
- sys.exit(0)
+ # conda's env main() function sometimes returns None and other times raises SystemExit
+ if return_none:
+ return None
+ else:
+ sys.exit(0)
devenv._call_conda.side_effect = call_conda_mock
| 0.9.3 broken: no longer generates activate/deactivate scripts
#46 introduced a bug: `conda-devenv` now calls `conda_env.main` directly, which probably calls `sys.exit()`, which skips activate/deactivate scripts generation. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_main.py::test_handle_input_file[True-environment.yml-0]"
] | [
"tests/test_main.py::test_handle_input_file[False-environment.yml-0]",
"tests/test_main.py::test_print[environment.yml]"
] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2017-04-24T13:37:58Z" | mit |
|
ESSS__conda-devenv-72 | diff --git a/conda_devenv/devenv.py b/conda_devenv/devenv.py
index a89cf89..aad9646 100644
--- a/conda_devenv/devenv.py
+++ b/conda_devenv/devenv.py
@@ -7,16 +7,17 @@ import sys
import six
-def render_jinja(contents, filename):
+def render_jinja(contents, filename, is_included):
import jinja2
import sys
import platform
jinja_dict = {
- "root": os.path.dirname(os.path.abspath(filename)),
+ "is_included": is_included,
"os": os,
- "sys": sys,
"platform": platform,
+ "root": os.path.dirname(os.path.abspath(filename)),
+ "sys": sys,
}
return jinja2.Template(contents).render(**jinja_dict)
@@ -49,7 +50,7 @@ def handle_includes(root_filename, root_yaml):
filename=filename
))
with open(included_filename, "r") as f:
- jinja_contents = render_jinja(f.read(), included_filename)
+ jinja_contents = render_jinja(f.read(), included_filename, is_included=True)
included_yaml_dict = yaml.safe_load(jinja_contents)
if included_yaml_dict is None:
raise ValueError("The file '{included_filename}' which was"
@@ -182,7 +183,7 @@ def merge_dependencies_version_specifications(yaml_dict, key_to_merge):
def load_yaml_dict(filename):
with open(filename, "r") as f:
contents = f.read()
- rendered_contents = render_jinja(contents, filename)
+ rendered_contents = render_jinja(contents, filename, is_included=False)
import yaml
root_yaml = yaml.load(rendered_contents)
| ESSS/conda-devenv | f74b1ebc267d9c765e0f4851cf1154d3434a0e49 | diff --git a/tests/test_include.py b/tests/test_include.py
index f3eb7fc..308206d 100644
--- a/tests/test_include.py
+++ b/tests/test_include.py
@@ -7,7 +7,7 @@ from conda_devenv.devenv import handle_includes, render_jinja
def obtain_yaml_dicts(root_yaml_filename):
contents = open(root_yaml_filename, "r").read()
- contents = render_jinja(contents, filename=root_yaml_filename)
+ contents = render_jinja(contents, filename=root_yaml_filename, is_included=False)
root_yaml = yaml.load(contents)
dicts = handle_includes(root_yaml_filename, root_yaml).values()
dicts = list(dicts)
diff --git a/tests/test_jinja.py b/tests/test_jinja.py
index 551305e..b3ff3d8 100644
--- a/tests/test_jinja.py
+++ b/tests/test_jinja.py
@@ -10,7 +10,11 @@ from conda_devenv.devenv import render_jinja
def test_jinja_root():
- assert render_jinja("{{root}}", filename="path/to/file") == os.path.abspath("path/to")
+ assert render_jinja(
+ "{{root}}",
+ filename="path/to/file",
+ is_included=False,
+ ) == os.path.abspath("path/to")
def test_jinja_os(monkeypatch):
@@ -22,13 +26,13 @@ def test_jinja_os(monkeypatch):
{%- endif %}
""").strip()
- assert render_jinja(template, filename="") == "variable is not set"
+ assert render_jinja(template, filename="", is_included=False) == "variable is not set"
monkeypatch.setenv('ENV_VARIABLE', '1')
- assert render_jinja(template, filename="") == "variable is set"
+ assert render_jinja(template, filename="", is_included=False) == "variable is set"
monkeypatch.setenv('ENV_VARIABLE', '2')
- assert render_jinja(template, filename="") == "variable is not set"
+ assert render_jinja(template, filename="", is_included=False) == "variable is not set"
def test_jinja_sys(monkeypatch):
@@ -43,27 +47,27 @@ def test_jinja_sys(monkeypatch):
""").strip()
monkeypatch.setattr(sys, 'platform', 'linux')
- assert render_jinja(template, filename="") == "linux!"
+ assert render_jinja(template, filename="", is_included=False) == "linux!"
monkeypatch.setattr(sys, 'platform', 'windows')
- assert render_jinja(template, filename="") == "windows!"
+ assert render_jinja(template, filename="", is_included=False) == "windows!"
monkeypatch.setattr(sys, 'platform', 'darwin')
- assert render_jinja(template, filename="") == "others!"
+ assert render_jinja(template, filename="", is_included=False) == "others!"
def test_jinja_platform(monkeypatch):
template = "{{ platform.python_revision() }}"
- assert render_jinja(template, filename="") == platform.python_revision()
+ assert render_jinja(template, filename="", is_included=False) == platform.python_revision()
def test_jinja_invalid_template():
- # TODO: change this to pytest's nicer syntax: with pytest.raises()
- try:
- render_jinja(textwrap.dedent("""\
+ with pytest.raises(jinja2.exceptions.TemplateSyntaxError):
+ render_jinja(
+ textwrap.dedent("""\
{%- if os.environ['ENV_VARIABLE'] == '1' %}
{% %}
- """), filename="")
- pytest.fail("Should raise an exception")
- except jinja2.exceptions.TemplateSyntaxError as e:
- pass
+ """),
+ filename="",
+ is_included=False,
+ )
diff --git a/tests/test_load_yaml_dict.py b/tests/test_load_yaml_dict.py
index 43ed3d5..3c9d6eb 100644
--- a/tests/test_load_yaml_dict.py
+++ b/tests/test_load_yaml_dict.py
@@ -63,3 +63,34 @@ def test_get_env_name(mocker, tmpdir, cmd_line_name):
assert name == 'foo'
else:
assert name == 'bar'
+
+
+def test_is_included_var(datadir):
+ import six
+ import textwrap
+ a_env_file = datadir / 'a.devenv.yml'
+ a_env_file.write_text(six.text_type(textwrap.dedent('''\
+ name: a
+ includes:
+ - {{root}}/b.devenv.yml
+ environment:
+ VARIABLE: value_a
+ IS_A_INCLUDED: {{is_included}}
+ ''')))
+ b_env_file = datadir / 'b.devenv.yml'
+ b_env_file.write_text(six.text_type(textwrap.dedent('''\
+ name: b
+ environment:
+ {% if not is_included %}
+ VARIABLE: value_b
+ {% endif %}
+ IS_B_INCLUDED: {{is_included}}
+ ''')))
+
+ conda_env, os_env = load_yaml_dict(str(a_env_file))
+ assert conda_env == {'name': 'a'}
+ assert os_env == {
+ 'IS_A_INCLUDED': False,
+ 'IS_B_INCLUDED': True,
+ 'VARIABLE': 'value_a',
+ }
| Add a way to identify if the current file is the "main" devenv file | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_jinja.py::test_jinja_root",
"tests/test_jinja.py::test_jinja_os",
"tests/test_jinja.py::test_jinja_sys",
"tests/test_jinja.py::test_jinja_platform",
"tests/test_jinja.py::test_jinja_invalid_template"
] | [
"tests/test_load_yaml_dict.py::test_get_env_name[True]",
"tests/test_load_yaml_dict.py::test_get_env_name[False]"
] | {
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false
} | "2018-12-13T23:55:40Z" | mit |
|
Edinburgh-Genome-Foundry__DnaChisel-61 | diff --git a/dnachisel/Location.py b/dnachisel/Location.py
index 853064f..6a3fdca 100644
--- a/dnachisel/Location.py
+++ b/dnachisel/Location.py
@@ -40,20 +40,25 @@ class Location:
def overlap_region(self, other_location):
"""Return the overlap span between two locations (None if None)."""
- strand = self.strand
if other_location.start < self.start:
- self, other_location = other_location, self
-
- if other_location.start < self.end:
- start = other_location.start
- end = min(self.end, other_location.end)
- strand = self.strand
- return Location(start, end, strand)
+ left_location, right_location = other_location, self
else:
+ left_location, right_location = self, other_location
+
+ if right_location.start >= left_location.end:
return None
+ start = right_location.start
+ end = min(left_location.end, right_location.end)
+ return Location(start, end, self.strand)
+
def extended(
- self, extension_length, lower_limit=0, upper_limit=None, left=True, right=True,
+ self,
+ extension_length,
+ lower_limit=0,
+ upper_limit=None,
+ left=True,
+ right=True,
):
"""Extend the location of a few basepairs on each side."""
@@ -183,5 +188,7 @@ class Location:
"""Return a Biopython SeqFeature with same location and custom
qualifiers."""
return SeqFeature(
- self.to_biopython_location(), type=feature_type, qualifiers=qualifiers,
+ self.to_biopython_location(),
+ type=feature_type,
+ qualifiers=qualifiers,
)
diff --git a/dnachisel/builtin_specifications/AvoidPattern.py b/dnachisel/builtin_specifications/AvoidPattern.py
index e367e35..28642bd 100644
--- a/dnachisel/builtin_specifications/AvoidPattern.py
+++ b/dnachisel/builtin_specifications/AvoidPattern.py
@@ -38,9 +38,7 @@ class AvoidPattern(Specification):
priority = 1
shorthand_name = "no" # will appear as, for instance, @no(BsmBI_site)
- def __init__(
- self, pattern=None, location=None, strand="from_location", boost=1.0
- ):
+ def __init__(self, pattern=None, location=None, strand="from_location", boost=1.0):
"""Initialize."""
if isinstance(pattern, str):
pattern = SequencePattern.from_string(pattern)
@@ -72,7 +70,7 @@ class AvoidPattern(Specification):
return "No %s" % self.pattern.name
else:
return "No %s" % self.pattern
-
+
def breach_label(self):
if self.pattern.name is not None:
return str(self.pattern.name)
| Edinburgh-Genome-Foundry/DnaChisel | 0678f74bc0b92e0e7daa975f1ea6c94992cb3792 | diff --git a/tests/builtin_specifications/test_AvoidPattern.py b/tests/builtin_specifications/test_AvoidPattern.py
index 46633e7..bed081e 100644
--- a/tests/builtin_specifications/test_AvoidPattern.py
+++ b/tests/builtin_specifications/test_AvoidPattern.py
@@ -8,6 +8,7 @@ from dnachisel import (
RepeatedKmerPattern,
AvoidChanges,
MotifPssmPattern,
+ Location,
)
import numpy
@@ -89,7 +90,9 @@ def test_AvoidPattern_on_strands():
# Both strands
sequence = "CATGCTATGC"
problem = DnaOptimizationProblem(
- sequence, constraints=[AvoidPattern("CAT")], logger=None,
+ sequence,
+ constraints=[AvoidPattern("CAT")],
+ logger=None,
)
problem.resolve_constraints()
assert "CAT" not in problem.sequence
@@ -138,3 +141,10 @@ def test_AvoidPattern_with_regular_expression():
assert not problem.all_constraints_pass()
problem.resolve_constraints()
assert problem.all_constraints_pass()
+
+
+def test_location_strand_gets_conserved():
+ cst = AvoidPattern("AACAAAT", Location(4, 1624, -1))
+ location = Location(9, 10)
+ new_cst = cst.localized(location)
+ assert new_cst.location.to_tuple() == (4, 16, -1)
| Issue with AvoidPattern (and potentially other builtin_specifications)
It looks as though AvoidPattern doesn't preserve its strand information when being localized if the original strand information is 'from_location'
https://github.com/Edinburgh-Genome-Foundry/DnaChisel/blob/db0b606ec993a509de9f3bb4d8acde9baadeef99/dnachisel/builtin_specifications/AvoidPattern.py#L85
Example illustrating this:
```
ipdb> cst
# AvoidPattern[4-1624(-)](pattern:AACAAAT)
ipdb> location
# 9-10
ipdb> new_cst = cst.localized(location, problem=self)
ipdb> new_cst
# AvoidPattern[4-16](pattern:AACAAAT)
ipdb> new_cst.location
# 4-16
ipdb> new_cst.strand
# 'from_location'
```
The `from_location` is strand argument is preserved, but the original strand in the location is lost, so the resulting constraint loses the strandedness. I ran into this today when my optimization kept failing and the violated constraint was being reported on the positive strand even though that constraint should only be on the negative.
This was in version 3.2.6 (though the current code looks unchanged)
To fix this in the short term, it looks like I can specify the strand directly with its own argument when creating the constraint (let me know if this is not good for some reason).
This tool is very useful, thank you for the continued development! | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/builtin_specifications/test_AvoidPattern.py::test_location_strand_gets_conserved"
] | [
"tests/builtin_specifications/test_AvoidPattern.py::test_AvoidPattern_on_strands",
"tests/builtin_specifications/test_AvoidPattern.py::test_AvoidPattern_with_regular_expression",
"tests/builtin_specifications/test_AvoidPattern.py::test_avoid_repeated_small_kmers",
"tests/builtin_specifications/test_AvoidPattern.py::test_AvoidPattern_with_jaspar_motifs",
"tests/builtin_specifications/test_AvoidPattern.py::test_pattern_and_reverse",
"tests/builtin_specifications/test_AvoidPattern.py::test_avoid_pattern_overlapping_locations",
"tests/builtin_specifications/test_AvoidPattern.py::test_avoid_pattern_basics"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2021-07-21T19:51:09Z" | mit |
|
EdinburghGenomics__EGCG-Core-11 | diff --git a/egcg_core/ncbi.py b/egcg_core/ncbi.py
index 13f74d6..69cc44c 100644
--- a/egcg_core/ncbi.py
+++ b/egcg_core/ncbi.py
@@ -76,7 +76,7 @@ def _fetch_from_eutils(species):
rank = None
if match:
rank = match.group(1)
- if rank == 'species':
+ if rank in ['species', 'subspecies']:
scientific_name = common_name = None
match = re.search('<ScientificName>(.+?)</ScientificName>', r.text, re.MULTILINE)
if match:
| EdinburghGenomics/EGCG-Core | a835cffab69da2193d4653f31230f0d487596b78 | diff --git a/tests/test_ncbi.py b/tests/test_ncbi.py
index ef931bb..af10556 100644
--- a/tests/test_ncbi.py
+++ b/tests/test_ncbi.py
@@ -24,6 +24,11 @@ def test_fetch_from_eutils():
<OtherNames><CommonName>a common name</CommonName></OtherNames>
<Rank>species</Rank>
'''
+ ncbi_fetch_data_sub_spe = '''
+ <ScientificName>Genus species</ScientificName>
+ <OtherNames><CommonName>a common name</CommonName></OtherNames>
+ <Rank>subspecies</Rank>
+ '''
patched_get = patch(
'egcg_core.ncbi.requests.get',
@@ -34,7 +39,15 @@ def test_fetch_from_eutils():
FakeRestResponse(content=ncbi_fetch_data)
)
)
-
+ patched_get2 = patch(
+ 'egcg_core.ncbi.requests.get',
+ side_effect=(
+ FakeRestResponse(content=ncbi_search_data),
+ FakeRestResponse(content=ncbi_fetch_data_sub_spe),
+ FakeRestResponse(content=ncbi_fetch_data_sub_spe),
+ FakeRestResponse(content=ncbi_fetch_data_sub_spe)
+ )
+ )
with patched_get as mocked_get:
obs = fetch_from_eutils('a_species')
assert obs == ('1337', 'Genus species', 'a common name')
@@ -46,6 +59,10 @@ def test_fetch_from_eutils():
'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi',
params={'db': 'Taxonomy', 'id': '1337'}
)
+ with patched_get2:
+ obs = fetch_from_eutils('a_species')
+ assert obs == ('1337', 'Genus species', 'a common name')
+
def test_cache():
| Canis lupus familiaris NCBI query returns None
Because _C. l. familiaris_ has `subspecies` in its efetch, the regex system in `fetch_from_eutils` breaks down. We should query the XML more robustly. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_ncbi.py::test_fetch_from_eutils"
] | [
"tests/test_ncbi.py::test_cache",
"tests/test_ncbi.py::test_get_species_name"
] | {
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false
} | "2016-07-15T13:03:14Z" | mit |
|
EdinburghGenomics__EGCG-Core-12 | diff --git a/egcg_core/__init__.py b/egcg_core/__init__.py
index e1424ed..58d168b 100644
--- a/egcg_core/__init__.py
+++ b/egcg_core/__init__.py
@@ -1,1 +1,1 @@
-__version__ = '0.3.1'
+__version__ = '0.4'
diff --git a/egcg_core/clarity.py b/egcg_core/clarity.py
index 4691f7c..e896d04 100644
--- a/egcg_core/clarity.py
+++ b/egcg_core/clarity.py
@@ -2,13 +2,16 @@ import re
from genologics.lims import Lims
from egcg_core.config import cfg
from egcg_core.app_logging import logging_default as log_cfg
-from egcg_core.exceptions import LimsCommunicationError
+from egcg_core.exceptions import EGCGError
app_logger = log_cfg.get_logger('clarity')
try:
from egcg_core.ncbi import get_species_name
except ImportError:
- app_logger.error('Could not import egcg_core.ncbi. Is sqlite3 available?')
+ app_logger.warning('Could not import egcg_core.ncbi. Is sqlite3 available?')
+
+ def get_species_name(query_species):
+ raise EGCGError('Could not import egcg_core.ncbi.get_species_name - sqlite3 seems to be unavailable.')
_lims = None
@@ -91,8 +94,8 @@ def sanitize_user_id(user_id):
substitutions = (
(None, None),
- (re.compile('_(\d{2})$'), ':\g<1>'),
- (re.compile('__(\w):(\d{2})'), ' _\g<1>:\g<2>')
+ (re.compile('_(\d{2})$'), ':\g<1>'), # '_01' -> ':01'
+ (re.compile('__(\w):(\d{2})'), ' _\g<1>:\g<2>') # '__L:01' -> ' _L:01'
)
@@ -115,11 +118,12 @@ def _get_list_of_samples(sample_names, sub=0):
lims.get_batch(samples)
if len(samples) != len(sample_names): # haven't got all the samples because some had _01/__L:01
+ sub += 1
+ remainder = sorted(set(_sample_names).difference(set([s.name for s in samples])))
if sub < len(substitutions):
- remainder = sorted(set(_sample_names).difference(set([s.name for s in samples])))
- samples.extend(_get_list_of_samples(remainder, sub + 1))
- else:
- raise LimsCommunicationError('Expected %s back, got %s' % (_sample_names, len(samples)))
+ samples.extend(_get_list_of_samples(remainder, sub))
+ else: # end recursion
+ app_logger.warning('Could not find %s in Lims' % remainder)
return samples
diff --git a/egcg_core/executor/cluster_executor.py b/egcg_core/executor/cluster_executor.py
index ce66a44..f9b29d1 100644
--- a/egcg_core/executor/cluster_executor.py
+++ b/egcg_core/executor/cluster_executor.py
@@ -38,9 +38,8 @@ class ClusterExecutor(AppLogger):
sleep(30)
return self._job_exit_code()
- @classmethod
- def _get_writer(cls, job_name, working_dir, walltime=None, cpus=1, mem=2, jobs=1, log_commands=True):
- return cls.script_writer(job_name, working_dir, cfg['job_queue'], cpus, mem, walltime, jobs, log_commands)
+ def _get_writer(self, job_name, working_dir, walltime=None, cpus=1, mem=2, jobs=1, log_commands=True):
+ return self.script_writer(job_name, working_dir, self.job_queue, cpus, mem, walltime, jobs, log_commands)
def _job_status(self):
raise NotImplementedError
| EdinburghGenomics/EGCG-Core | 43f124d6f77db73cff13117003295ad715d9aabc | diff --git a/tests/test_clarity.py b/tests/test_clarity.py
index b4c3684..6e963a2 100644
--- a/tests/test_clarity.py
+++ b/tests/test_clarity.py
@@ -104,10 +104,9 @@ def test_get_list_of_samples():
exp_lims_sample_ids = ['this', 'that:01', 'other _L:01']
calling_sample_ids = ['this', 'that_01', 'other__L_01']
fake_list_samples = [[FakeEntity(n)] for n in exp_lims_sample_ids]
- pbatch = patched_lims('get_batch')
psamples = patched_lims('get_samples', side_effect=fake_list_samples)
- with pbatch, psamples as mocked_get_samples:
+ with patched_lims('get_batch'), psamples as mocked_get_samples:
samples = clarity.get_list_of_samples(calling_sample_ids)
assert [s.name for s in samples] == exp_lims_sample_ids
mocked_get_samples.assert_any_call(name=['this', 'that_01', 'other__L_01'])
@@ -115,6 +114,23 @@ def test_get_list_of_samples():
mocked_get_samples.assert_any_call(name=['other _L:01'])
+def test_get_list_of_samples_broken():
+ exp_lims_sample_ids = ['this', 'that:01', 'other _L:01']
+ calling_sample_ids = ['this', 'that_01', 'other__L_01']
+ fake_list_samples = [[FakeEntity(n)] for n in exp_lims_sample_ids]
+ psamples = patched_lims('get_samples', side_effect=fake_list_samples)
+ log_msgs = []
+ pwarn = patched('app_logger.warning', new=log_msgs.append)
+
+ with patched_lims('get_batch'), psamples as mocked_get_samples, pwarn:
+ samples = clarity.get_list_of_samples(calling_sample_ids + ['sample_not_in_lims'])
+ assert [s.name for s in samples] == exp_lims_sample_ids
+ mocked_get_samples.assert_any_call(name=['this', 'that_01', 'other__L_01', 'sample_not_in_lims'])
+ mocked_get_samples.assert_any_call(name=['other__L:01', 'sample_not_in_lims', 'that:01'])
+ mocked_get_samples.assert_any_call(name=['other _L:01', 'sample_not_in_lims'])
+ assert log_msgs == ["Could not find ['sample_not_in_lims'] in Lims"]
+
+
@patched_lims('get_samples', side_effect=[[], [], [None]])
def test_get_samples(mocked_lims):
assert clarity.get_samples('a_sample_name__L_01') == [None]
@@ -206,8 +222,7 @@ def test_get_output_containers_from_sample_and_step_name(mocked_get_sample, mock
@patched_clarity('get_sample_names_from_plate', ['this', 'that', 'other'])
-@patched_clarity('get_sample',
- Mock(artifact=Mock(container=FakeEntity('a_container', type=FakeEntity('96 well plate')))))
+@patched_clarity('get_sample', Mock(artifact=Mock(container=FakeEntity('a_container', type=FakeEntity('96 well plate')))))
def test_get_samples_arrived_with(mocked_get_sample, mocked_names_from_plate):
assert clarity.get_samples_arrived_with('a_sample_name') == ['this', 'that', 'other']
mocked_get_sample.assert_called_with('a_sample_name')
| clarity.get_list_of_samples crashes if a sample doesn't exist in the Lims
The error is because of the way we're processing sample names. The stacktrace is misleading:
```
File "clarity.py", line 98, in get_list_of_samples
results.extend(_get_list_of_samples(sample_names[start:start+max_query]))
File "clarity.py", line 114, in _get_list_of_samples
samples.extend(_get_list_of_samples(remainder, sub + 1))
File "clarity.py", line 114, in _get_list_of_samples
samples.extend(_get_list_of_samples(remainder, sub + 1))
File "clarity.py", line 114, in _get_list_of_samples
samples.extend(_get_list_of_samples(remainder, sub + 1))
File "clarity.py", line 102, in _get_list_of_samples
pattern, repl = substitutions[sub]
```
We should return None for non-existent samples, or leave them out of the returned list. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_clarity.py::test_get_list_of_samples_broken"
] | [
"tests/test_clarity.py::test_get_sample_gender",
"tests/test_clarity.py::test_get_sample_names_from_plate_from_lims",
"tests/test_clarity.py::test_get_expected_yield_for_sample",
"tests/test_clarity.py::test_get_samples",
"tests/test_clarity.py::test_get_output_containers_from_sample_and_step_name",
"tests/test_clarity.py::test_find_run_elements_from_sample",
"tests/test_clarity.py::test_find_project_from_sample",
"tests/test_clarity.py::test_get_samples_sequenced_with",
"tests/test_clarity.py::test_sanitize_user_id",
"tests/test_clarity.py::test_get_sample_release_date",
"tests/test_clarity.py::test_get_sample_names_from_project_from_lims",
"tests/test_clarity.py::test_get_user_sample_name",
"tests/test_clarity.py::test_get_species_from_sample",
"tests/test_clarity.py::test_get_list_of_samples",
"tests/test_clarity.py::test_get_released_samples",
"tests/test_clarity.py::test_get_plate_id_and_well_from_lims",
"tests/test_clarity.py::test_get_run",
"tests/test_clarity.py::test_get_valid_lanes",
"tests/test_clarity.py::test_get_genotype_information_from_lims",
"tests/test_clarity.py::test_get_samples_genotyped_with",
"tests/test_clarity.py::test_get_sample",
"tests/test_clarity.py::test_route_samples_to_delivery_workflow",
"tests/test_clarity.py::test_get_samples_arrived_with"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2016-07-15T14:25:56Z" | mit |
|
EdinburghGenomics__EGCG-Core-52 | diff --git a/egcg_core/archive_management.py b/egcg_core/archive_management.py
index 3437925..58c5eb9 100644
--- a/egcg_core/archive_management.py
+++ b/egcg_core/archive_management.py
@@ -1,6 +1,8 @@
import os
import re
import subprocess
+from time import sleep
+
from egcg_core.app_logging import logging_default as log_cfg
from egcg_core.exceptions import EGCGError
@@ -83,13 +85,18 @@ def release_file_from_lustre(file_path):
return True
-def register_for_archiving(file_path):
+def register_for_archiving(file_path, strict=False):
if is_register_for_archiving(file_path):
return True
cmd = 'lfs hsm_archive %s' % file_path
val = _get_stdout(cmd)
if val is None or not is_register_for_archiving(file_path):
- raise ArchivingError('Registering %s for archiving to tape failed' % file_path)
+ if strict:
+ raise ArchivingError('Registering %s for archiving to tape failed' % file_path)
+ # Registering for archive can sometime take time so give it a second
+ sleep(1)
+ return register_for_archiving(filter, strict=True)
+
return True
| EdinburghGenomics/EGCG-Core | 5a073c8d79148ed29379e4818e4dcebd5180eb15 | diff --git a/tests/test_archive_management.py b/tests/test_archive_management.py
index c087706..5d45646 100644
--- a/tests/test_archive_management.py
+++ b/tests/test_archive_management.py
@@ -76,7 +76,7 @@ class TestArchiveManagement(TestEGCG):
'',
'testfile: (0x00000001)',
]) as get_stdout:
- self.assertRaises(ArchivingError, register_for_archiving, 'testfile')
+ self.assertRaises(ArchivingError, register_for_archiving, 'testfile', True)
assert get_stdout.call_count == 3
assert get_stdout.call_args_list[1][0] == ('lfs hsm_archive testfile',)
| Failure to register for archiving cause pipeline crash
We should make the registering for archiving more robust by sleeping trying again to register the file after 1 second.
https://github.com/EdinburghGenomics/EGCG-Core/blob/master/egcg_core/archive_management.py#L92
This raising can cause Analysis Driver to crash at the end of the processing rather randomly.
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_archive_management.py::TestArchiveManagement::test_register_for_archiving"
] | [
"tests/test_archive_management.py::TestArchiveManagement::test_archive_states",
"tests/test_archive_management.py::TestArchiveManagement::test_archive_directory",
"tests/test_archive_management.py::TestArchiveManagement::test_recall_from_tape",
"tests/test_archive_management.py::TestArchiveManagement::test_release_file_from_lustre"
] | {
"failed_lite_validators": [
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
} | "2017-05-23T21:56:31Z" | mit |
|
EdinburghGenomics__EGCG-Core-6 | diff --git a/egcg_core/rest_communication.py b/egcg_core/rest_communication.py
index 942039b..39acd98 100644
--- a/egcg_core/rest_communication.py
+++ b/egcg_core/rest_communication.py
@@ -1,9 +1,10 @@
import requests
from urllib.parse import urljoin
-from egcg_core.config import default as cfg
+from egcg_core.config import default
from egcg_core.app_logging import logging_default as log_cfg
from egcg_core.exceptions import RestCommunicationError
+cfg = default['rest_api']
app_logger = log_cfg.get_logger(__name__)
table = {' ': '', '\'': '"', 'None': 'null'}
@@ -17,7 +18,7 @@ def _translate(s):
def api_url(endpoint, **query_args):
url = '{base_url}/{endpoint}/'.format(
- base_url=cfg.query('rest_api', 'url').rstrip('/'), endpoint=endpoint
+ base_url=cfg['url'].rstrip('/'), endpoint=endpoint
)
if query_args:
query = '?' + '&'.join(['%s=%s' % (k, v) for k, v in query_args.items()])
@@ -38,7 +39,11 @@ def _parse_query_string(query_string, requires=None):
def _req(method, url, quiet=False, **kwargs):
- r = requests.request(method, url, **kwargs)
+ auth = None
+ if 'username' in cfg and 'password' in cfg:
+ auth = (cfg['username'], cfg['password'])
+
+ r = requests.request(method, url, auth=auth, **kwargs)
# e.g: 'POST <url> ({"some": "args"}) -> {"some": "content"}. Status code 201. Reason: CREATED
report = '%s %s (%s) -> %s. Status code %s. Reason: %s' % (
r.request.method, r.request.path_url, kwargs, r.content.decode('utf-8'), r.status_code, r.reason
@@ -46,6 +51,8 @@ def _req(method, url, quiet=False, **kwargs):
if r.status_code in (200, 201):
if not quiet:
app_logger.debug(report)
+ elif r.status_code == 401:
+ raise RestCommunicationError('Invalid auth credentials')
else:
app_logger.error(report)
return r
@@ -58,7 +65,6 @@ def get_content(endpoint, paginate=True, quiet=False, **query_args):
page=query_args.pop('page', 1)
)
url = api_url(endpoint, **query_args)
-
return _req('GET', url, quiet=quiet).json()
@@ -170,7 +176,7 @@ def post_or_patch(endpoint, input_json, id_field=None, update_lists=None):
doc = get_document(endpoint, where={id_field: _payload[id_field]})
if doc:
_payload.pop(id_field)
- s = _patch_entry(endpoint, doc, _payload, update_lists)
+ s = _patch_entry(endpoint, doc, _payload, update_lists)
else:
s = post_entry(endpoint, _payload)
success = success and s
diff --git a/etc/example_egcg.yaml b/etc/example_egcg.yaml
index 11b9ade..c6d764e 100644
--- a/etc/example_egcg.yaml
+++ b/etc/example_egcg.yaml
@@ -4,6 +4,8 @@ default:
rest_api:
url: 'http://localhost:4999/api/0.1'
+ username: 'a_user'
+ password: 'a_password'
ncbi_cache: ':memory:'
| EdinburghGenomics/EGCG-Core | 0309bf8fdd5d64705fc62184fe31e27c20172fbc | diff --git a/tests/test_rest_communication.py b/tests/test_rest_communication.py
index c43d6b7..b9905c2 100644
--- a/tests/test_rest_communication.py
+++ b/tests/test_rest_communication.py
@@ -21,6 +21,7 @@ patched_response = patch(
'requests.request',
return_value=FakeRestResponse(status_code=200, content=test_request_content)
)
+auth = ('a_user', 'a_password')
def query_args_from_url(url):
@@ -74,7 +75,7 @@ def test_req(mocked_response):
response = rest_communication._req('METHOD', rest_url(test_endpoint), json=json_content)
assert response.status_code == 200
assert json.loads(response.content.decode('utf-8')) == response.json() == test_request_content
- mocked_response.assert_called_with('METHOD', rest_url(test_endpoint), json=json_content)
+ mocked_response.assert_called_with('METHOD', rest_url(test_endpoint), auth=auth, json=json_content)
def test_get_documents_depaginate():
@@ -122,13 +123,13 @@ def test_get_document():
@patched_response
def test_post_entry(mocked_response):
rest_communication.post_entry(test_endpoint, payload=test_request_content)
- mocked_response.assert_called_with('POST', rest_url(test_endpoint), json=test_request_content)
+ mocked_response.assert_called_with('POST', rest_url(test_endpoint), auth=auth, json=test_request_content)
@patched_response
def test_put_entry(mocked_response):
rest_communication.put_entry(test_endpoint, 'an_element_id', payload=test_request_content)
- mocked_response.assert_called_with('PUT', rest_url(test_endpoint) + 'an_element_id', json=test_request_content)
+ mocked_response.assert_called_with('PUT', rest_url(test_endpoint) + 'an_element_id', auth=auth, json=test_request_content)
test_patch_document = {
@@ -138,7 +139,7 @@ test_patch_document = {
@patch('egcg_core.rest_communication.get_document', return_value=test_patch_document)
@patched_response
-def test_patch_entry(mocked_request, mocked_get_doc):
+def test_patch_entry(mocked_response, mocked_get_doc):
patching_payload = {'list_to_update': ['another']}
rest_communication.patch_entry(
test_endpoint,
@@ -149,10 +150,11 @@ def test_patch_entry(mocked_request, mocked_get_doc):
)
mocked_get_doc.assert_called_with(test_endpoint, where={'uid': 'a_unique_id'})
- mocked_request.assert_called_with(
+ mocked_response.assert_called_with(
'PATCH',
rest_url(test_endpoint) + '1337',
headers={'If-Match': 1234567},
+ auth=auth,
json={'list_to_update': ['this', 'that', 'other', 'another']}
)
| Authentication
Since EdinburghGenomics/Reporting-App will be adding authentication, we should add auth headers to `rest_communication`. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_rest_communication.py::test_post_entry",
"tests/test_rest_communication.py::test_req",
"tests/test_rest_communication.py::test_put_entry",
"tests/test_rest_communication.py::test_patch_entry"
] | [
"tests/test_rest_communication.py::test_parse_query_string",
"tests/test_rest_communication.py::test_get_documents",
"tests/test_rest_communication.py::test_get_document",
"tests/test_rest_communication.py::test_get_documents_depaginate",
"tests/test_rest_communication.py::test_test_content",
"tests/test_rest_communication.py::test_api_url_query_strings",
"tests/test_rest_communication.py::test_post_or_patch"
] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2016-06-30T09:54:47Z" | mit |
|
EdinburghGenomics__EGCG-Core-60 | diff --git a/CHANGELOG.md b/CHANGELOG.md
index 58a261b..6db3fe5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,10 +1,10 @@
Changelog for EGCG-Core
===========================
-0.8 (unreleased)
+0.7.3 (unreleased)
----------------
-- Nothing changed yet.
+- Add new option to rest_communication.post_entry to submit payload without json
0.7.2 (2017-08-03)
diff --git a/egcg_core/rest_communication.py b/egcg_core/rest_communication.py
index 949e97c..bc78e7d 100644
--- a/egcg_core/rest_communication.py
+++ b/egcg_core/rest_communication.py
@@ -165,9 +165,12 @@ class Communicator(AppLogger):
else:
self.warning('No document found in endpoint %s for %s', endpoint, query_args)
- def post_entry(self, endpoint, payload):
+ def post_entry(self, endpoint, payload, use_data=False):
files, payload = self._detect_files_in_json(payload)
- return self._req('POST', self.api_url(endpoint), json=payload, files=files)
+ if use_data:
+ return self._req('POST', self.api_url(endpoint), data=payload, files=files)
+ else:
+ return self._req('POST', self.api_url(endpoint), json=payload, files=files)
def put_entry(self, endpoint, element_id, payload):
files, payload = self._detect_files_in_json(payload)
diff --git a/requirements.txt b/requirements.txt
index b55e6f8..b0f950e 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -1,6 +1,7 @@
pytest>=2.7.2
+requests==2.14.2
PyYAML>=3.11
pyclarity_lims>=0.4
jinja2==2.8
-asana==0.6.2
+asana==0.6.5
cached_property
| EdinburghGenomics/EGCG-Core | dff158066e922124e05d2d93cca14b2ee4ad6bfc | diff --git a/tests/test_rest_communication.py b/tests/test_rest_communication.py
index 3f920be..fcc907f 100644
--- a/tests/test_rest_communication.py
+++ b/tests/test_rest_communication.py
@@ -180,6 +180,24 @@ class TestRestCommunication(TestEGCG):
files={'f': (file_path, b'test content', 'text/plain')}
)
+ self.comm.post_entry(test_endpoint, payload=test_flat_request_content, use_data=True)
+ mocked_response.assert_called_with(
+ 'POST',
+ rest_url(test_endpoint),
+ auth=auth,
+ data=test_flat_request_content,
+ files=None
+ )
+
+ self.comm.post_entry(test_endpoint, payload=test_request_content_plus_files, use_data=True)
+ mocked_response.assert_called_with(
+ 'POST',
+ rest_url(test_endpoint),
+ auth=auth,
+ data=test_flat_request_content,
+ files={'f': (file_path, b'test content', 'text/plain')}
+ )
+
@patched_response
def test_put_entry(self, mocked_response):
self.comm.put_entry(test_endpoint, 'an_element_id', payload=test_nested_request_content)
| rest_communication: post data as form instead of json
`post_entry` should have an option to specify a post where the data is stored in the form instead of the query string.
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_rest_communication.py::TestRestCommunication::test_post_entry"
] | [
"tests/test_rest_communication.py::TestRestCommunication::test_put_entry",
"tests/test_rest_communication.py::TestRestCommunication::test_token_auth",
"tests/test_rest_communication.py::TestRestCommunication::test_detect_files_in_json",
"tests/test_rest_communication.py::TestRestCommunication::test_get_documents",
"tests/test_rest_communication.py::TestRestCommunication::test_post_or_patch",
"tests/test_rest_communication.py::TestRestCommunication::test_get_document",
"tests/test_rest_communication.py::TestRestCommunication::test_auth_token_and_if_match",
"tests/test_rest_communication.py::TestRestCommunication::test_get_content",
"tests/test_rest_communication.py::TestRestCommunication::test_req",
"tests/test_rest_communication.py::TestRestCommunication::test_patch_entry",
"tests/test_rest_communication.py::TestRestCommunication::test_api_url",
"tests/test_rest_communication.py::TestRestCommunication::test_get_documents_depaginate",
"tests/test_rest_communication.py::TestRestCommunication::test_parse_query_string"
] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2017-09-01T14:24:56Z" | mit |
|
EdinburghGenomics__EGCG-Core-64 | diff --git a/CHANGELOG.md b/CHANGELOG.md
index f304aea..260484f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,10 +1,10 @@
Changelog for EGCG-Core
===========================
-0.8 (unreleased)
+0.7.4 (unreleased)
----------------
-- Nothing changed yet.
+- Bugfix in archive management.
0.7.3 (2017-09-01)
diff --git a/egcg_core/archive_management.py b/egcg_core/archive_management.py
index 58c5eb9..c5f5f2c 100644
--- a/egcg_core/archive_management.py
+++ b/egcg_core/archive_management.py
@@ -95,7 +95,7 @@ def register_for_archiving(file_path, strict=False):
raise ArchivingError('Registering %s for archiving to tape failed' % file_path)
# Registering for archive can sometime take time so give it a second
sleep(1)
- return register_for_archiving(filter, strict=True)
+ return register_for_archiving(file_path, strict=True)
return True
| EdinburghGenomics/EGCG-Core | 5be3adbce57f2efd3afc6d15f59bb288ce0c1b50 | diff --git a/tests/test_archive_management.py b/tests/test_archive_management.py
index 5d45646..0506957 100644
--- a/tests/test_archive_management.py
+++ b/tests/test_archive_management.py
@@ -80,6 +80,16 @@ class TestArchiveManagement(TestEGCG):
assert get_stdout.call_count == 3
assert get_stdout.call_args_list[1][0] == ('lfs hsm_archive testfile',)
+ with patch('egcg_core.archive_management._get_stdout',
+ side_effect=[
+ 'testfile: (0x00000001)', '', 'testfile: (0x00000001)',
+ 'testfile: (0x00000001)', '', 'testfile: (0x00000001)',
+ ]) as get_stdout:
+ self.assertRaises(ArchivingError, register_for_archiving, 'testfile', False)
+ assert get_stdout.call_count == 6
+ assert get_stdout.call_args_list[1][0] == ('lfs hsm_archive testfile',)
+ assert get_stdout.call_args_list[4][0] == ('lfs hsm_archive testfile',)
+
def test_recall_from_tape(self):
with patch('egcg_core.archive_management._get_stdout',
side_effect=[
| Broken recursion in archive_management
In archive_management.register_for_archiving, the recursion is called with the built-in function `filter`, which can only be a typo. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_archive_management.py::TestArchiveManagement::test_register_for_archiving"
] | [
"tests/test_archive_management.py::TestArchiveManagement::test_archive_directory",
"tests/test_archive_management.py::TestArchiveManagement::test_archive_states",
"tests/test_archive_management.py::TestArchiveManagement::test_recall_from_tape",
"tests/test_archive_management.py::TestArchiveManagement::test_release_file_from_lustre"
] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
} | "2017-10-31T13:35:10Z" | mit |
|
EdinburghGenomics__EGCG-Core-88 | diff --git a/egcg_core/clarity.py b/egcg_core/clarity.py
index 0068e9d..39d03f8 100644
--- a/egcg_core/clarity.py
+++ b/egcg_core/clarity.py
@@ -113,7 +113,7 @@ def get_genome_version(sample_id, species=None):
def sanitize_user_id(user_id):
if isinstance(user_id, str):
- return re.sub("[^\w_\-.]", "_", user_id)
+ return re.sub("[^\w]", "_", user_id)
substitutions = (
| EdinburghGenomics/EGCG-Core | f54591f5420dc4b4f8241e080e594a5fd6c5f87a | diff --git a/tests/test_clarity.py b/tests/test_clarity.py
index c4446fb..271d1d2 100644
--- a/tests/test_clarity.py
+++ b/tests/test_clarity.py
@@ -117,6 +117,7 @@ class TestClarity(TestEGCG):
def test_sanitize_user_id(self):
assert clarity.sanitize_user_id('this?that$other another:more') == 'this_that_other_another_more'
+ assert clarity.sanitize_user_id('this.that$other another:more') == 'this_that_other_another_more'
def test_get_list_of_samples(self):
exp_lims_sample_ids = ['this', 'that:01', 'other _L:01']
| Replace (.) dots in user sample name with underscores
Change the sanitize_user_id function to remove dots
https://github.com/EdinburghGenomics/EGCG-Core/blob/f54591f5420dc4b4f8241e080e594a5fd6c5f87a/egcg_core/clarity.py#L114 | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_clarity.py::TestClarity::test_sanitize_user_id"
] | [
"tests/test_clarity.py::TestClarity::test_find_run_elements_from_sample",
"tests/test_clarity.py::TestClarity::test_get_valid_lanes",
"tests/test_clarity.py::TestClarity::test_find_project_from_sample",
"tests/test_clarity.py::TestClarity::test_get_samples_arrived_with",
"tests/test_clarity.py::TestClarity::test_get_samples",
"tests/test_clarity.py::TestClarity::test_get_sample",
"tests/test_clarity.py::TestClarity::test_connection",
"tests/test_clarity.py::TestClarity::test_get_run",
"tests/test_clarity.py::TestClarity::test_get_species_from_sample",
"tests/test_clarity.py::TestClarity::test_get_samples_genotyped_with",
"tests/test_clarity.py::TestClarity::test_get_output_containers_from_sample_and_step_name",
"tests/test_clarity.py::TestClarity::test_get_sample_names_from_plate_from_lims",
"tests/test_clarity.py::TestClarity::test_route_samples_to_delivery_workflow_with_name",
"tests/test_clarity.py::TestClarity::test_get_user_sample_name",
"tests/test_clarity.py::TestClarity::test_get_samples_sequenced_with",
"tests/test_clarity.py::TestClarity::test_get_list_of_samples_broken",
"tests/test_clarity.py::TestClarity::test_route_samples_to_delivery_workflow_no_name",
"tests/test_clarity.py::TestClarity::test_get_genotype_information_from_lims",
"tests/test_clarity.py::TestClarity::test_get_plate_id_and_well_from_lims",
"tests/test_clarity.py::TestClarity::test_get_sample_gender",
"tests/test_clarity.py::TestClarity::test_get_list_of_samples",
"tests/test_clarity.py::TestClarity::test_get_released_samples",
"tests/test_clarity.py::TestClarity::test_get_sample_release_date",
"tests/test_clarity.py::TestClarity::test_get_sample_names_from_project_from_lims"
] | {
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false
} | "2018-10-11T09:01:18Z" | mit |
|
EdinburghGenomics__EGCG-Core-90 | diff --git a/egcg_core/rest_communication.py b/egcg_core/rest_communication.py
index 0a9e0cc..096648e 100644
--- a/egcg_core/rest_communication.py
+++ b/egcg_core/rest_communication.py
@@ -1,5 +1,6 @@
import json
import mimetypes
+import os
from urllib.parse import urljoin
import requests
from multiprocessing import Lock
@@ -18,7 +19,7 @@ class Communicator(AppLogger):
self._baseurl = baseurl
self._auth = auth
self.retries = retries
- self._session = None
+ self._sessions = {}
self.lock = Lock()
def begin_session(self):
@@ -36,9 +37,11 @@ class Communicator(AppLogger):
@property
def session(self):
- if self._session is None:
- self._session = self.begin_session()
- return self._session
+ """Create and return a session per PID so each sub-processes will use their own session"""
+ pid = os.getpid()
+ if pid not in self._sessions:
+ self._sessions[pid] = self.begin_session()
+ return self._sessions[pid]
@staticmethod
def serialise(queries):
@@ -137,23 +140,22 @@ class Communicator(AppLogger):
kwargs['data'] = kwargs.pop('json')
self.lock.acquire()
- r = self.session.request(method, url, **kwargs)
+ try:
+ r = self.session.request(method, url, **kwargs)
+ finally:
+ self.lock.release()
kwargs.pop('files', None)
# e.g: 'POST <url> ({"some": "args"}) -> {"some": "content"}. Status code 201. Reason: CREATED
report = '%s %s (%s) -> %s. Status code %s. Reason: %s' % (
r.request.method, r.request.path_url, kwargs, r.content.decode('utf-8'), r.status_code, r.reason
)
-
if r.status_code in self.successful_statuses:
if not quiet:
self.debug(report)
-
- self.lock.release()
return r
else:
self.error(report)
- self.lock.release()
raise RestCommunicationError('Encountered a %s status code: %s' % (r.status_code, r.reason))
def get_content(self, endpoint, paginate=True, quiet=False, **query_args):
@@ -258,6 +260,15 @@ class Communicator(AppLogger):
else:
self.post_entry(endpoint, _payload)
+ def close(self):
+ for s in self._sessions.values():
+ s.close()
+
+ def __del__(self):
+ try:
+ self.close()
+ except ReferenceError:
+ pass
default = Communicator()
api_url = default.api_url
| EdinburghGenomics/EGCG-Core | 8f4fefbdc4383b345ed58c7352b8125fcbe95f44 | diff --git a/tests/test_rest_communication.py b/tests/test_rest_communication.py
index ddb3fdb..e3f372b 100644
--- a/tests/test_rest_communication.py
+++ b/tests/test_rest_communication.py
@@ -1,7 +1,13 @@
+import multiprocessing
import os
import json
+
+import pytest
from requests import Session
from unittest.mock import Mock, patch, call
+
+from requests.exceptions import SSLError
+
from tests import FakeRestResponse, TestEGCG
from egcg_core import rest_communication
from egcg_core.util import check_if_nested
@@ -30,6 +36,7 @@ def fake_request(method, url, **kwargs):
patched_request = patch.object(Session, 'request', side_effect=fake_request)
+patched_failed_request = patch.object(Session, 'request', side_effect=SSLError('SSL error'))
auth = ('a_user', 'a_password')
@@ -97,6 +104,47 @@ class TestRestCommunication(TestEGCG):
assert json.loads(response.content.decode('utf-8')) == response.json() == test_nested_request_content
mocked_request.assert_called_with('METHOD', rest_url(test_endpoint), json=json_content)
+ @patched_failed_request
+ def test_failed_req(self, mocked_request):
+ json_content = ['some', {'test': 'json'}]
+ self.comm.lock = Mock()
+ self.comm.lock.acquire.assert_not_called()
+ self.comm.lock.release.assert_not_called()
+
+ with pytest.raises(SSLError):
+ _ = self.comm._req('METHOD', rest_url(test_endpoint), json=json_content)
+
+ self.comm.lock.acquire.assert_called_once()
+ self.comm.lock.release.assert_called_once() # exception raised, but lock still released
+
+ @patched_request
+ def test_multi_session(self, mocked_request):
+ json_content = ['some', {'test': 'json'}]
+ with patch('os.getpid', return_value=1):
+ _ = self.comm._req('METHOD', rest_url(test_endpoint), json=json_content)
+ with patch('os.getpid', return_value=2):
+ _ = self.comm._req('METHOD', rest_url(test_endpoint), json=json_content)
+ assert len(self.comm._sessions) == 2
+
+ @patched_request
+ def test_with_multiprocessing(self, mocked_request):
+ json_content = ['some', {'test': 'json'}]
+
+ def assert_request():
+ _ = self.comm._req('METHOD', rest_url(test_endpoint), json=json_content)
+ assert mocked_request.call_count == 2
+ assert len(self.comm._sessions) == 2
+
+ # initiate in the Session in the main thread
+ self.comm._req('METHOD', rest_url(test_endpoint), json=json_content)
+ procs = []
+ for i in range(10):
+ procs.append(multiprocessing.Process(target=assert_request))
+ for p in procs:
+ p.start()
+ for p in procs:
+ p.join()
+
@patch.object(Session, '__exit__')
@patch.object(Session, '__enter__')
@patched_request
| Rest_communication cause SSL error in multiprocessing
In some circumstances rest_communication will generate SSL error when communicating with the reporting app over https.
This occurs in the pipeline when it uses multiprocessing. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_rest_communication.py::TestRestCommunication::test_failed_req",
"tests/test_rest_communication.py::TestRestCommunication::test_multi_session"
] | [
"tests/test_rest_communication.py::TestRestCommunication::test_req",
"tests/test_rest_communication.py::TestRestCommunication::test_begin_session",
"tests/test_rest_communication.py::TestRestCommunication::test_get_documents",
"tests/test_rest_communication.py::TestRestCommunication::test_parse_query_string",
"tests/test_rest_communication.py::TestRestCommunication::test_api_url",
"tests/test_rest_communication.py::TestRestCommunication::test_put_entry",
"tests/test_rest_communication.py::TestRestCommunication::test_communication_error",
"tests/test_rest_communication.py::TestRestCommunication::test_post_entry",
"tests/test_rest_communication.py::TestRestCommunication::test_get_content",
"tests/test_rest_communication.py::TestRestCommunication::test_if_match",
"tests/test_rest_communication.py::TestRestCommunication::test_post_or_patch",
"tests/test_rest_communication.py::TestRestCommunication::test_context_manager",
"tests/test_rest_communication.py::TestRestCommunication::test_detect_files_in_json",
"tests/test_rest_communication.py::TestRestCommunication::test_get_document",
"tests/test_rest_communication.py::TestRestCommunication::test_patch_entry",
"tests/test_rest_communication.py::TestRestCommunication::test_get_documents_depaginate",
"tests/test_rest_communication.py::TestRestCommunication::test_with_multiprocessing"
] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2018-11-22T11:15:37Z" | mit |
|
EdinburghGenomics__pyclarity-lims-19 | diff --git a/pyclarity_lims/descriptors.py b/pyclarity_lims/descriptors.py
index b33666f..a5a4c28 100644
--- a/pyclarity_lims/descriptors.py
+++ b/pyclarity_lims/descriptors.py
@@ -721,6 +721,48 @@ class ExternalidList(XmlList):
list.append(self, (element.attrib.get('id'), element.attrib.get('uri')))
+class QueuedArtifactList(TagXmlList):
+ """This is a list of Artifact associated with the time they spent in the queue and their location on a plate.
+ The list contains tuples organise as follow:
+ (A, B, (C, D)) where
+ A is an artifact
+ B is a datetime object,
+ C is a container
+ D is a string specifying the location such as "1:1"
+ """
+
+ def __init__(self, instance, *args, **kwargs):
+ TagXmlList.__init__(self, instance, tag='artifact', nesting=['artifacts'], *args, **kwargs)
+
+ def _parse_element(self, element, lims, **kwargs):
+ from pyclarity_lims.entities import Artifact, Container
+ input_art = Artifact(lims, uri=element.attrib['uri'])
+ loc = element.find('location')
+ location = (None, None)
+ if loc:
+ location = (
+ Container(lims, uri=loc.find('container').attrib['uri']),
+ loc.find('value').text
+ )
+ qt = element.find('queue-time')
+ queue_date = None
+ if qt is not None:
+ h, s, t = qt.text.rpartition(':')
+ qt = h + t
+ microsec = ''
+ if '.' in qt:
+ microsec = '.%f'
+ date_format = '%Y-%m-%dT%H:%M:%S' + microsec
+ try:
+ queue_date = datetime.datetime.strptime(qt, date_format + '%z')
+ except ValueError:
+ # support for python 2.7 ignore time zone
+ # use python 3 for timezone support
+ qt = qt.split('+')[0]
+ queue_date = datetime.datetime.strptime(qt, date_format)
+ list.append(self, (input_art, queue_date, location))
+
+
# Descriptors: This section contains the object that can be used in entities
class BaseDescriptor(XmlElement):
"""Abstract base descriptor for an instance attribute."""
diff --git a/pyclarity_lims/entities.py b/pyclarity_lims/entities.py
index 4a51878..c51eb7c 100644
--- a/pyclarity_lims/entities.py
+++ b/pyclarity_lims/entities.py
@@ -5,7 +5,7 @@ from pyclarity_lims.descriptors import StringDescriptor, UdfDictionaryDescriptor
InputOutputMapList, LocationDescriptor, IntegerAttributeDescriptor, \
StringAttributeDescriptor, EntityListDescriptor, StringListDescriptor, PlacementDictionaryDescriptor, \
ReagentLabelList, AttributeListDescriptor, StringDictionaryDescriptor, OutputPlacementListDescriptor, \
- XmlActionList, MutableDescriptor, XmlPooledInputDict
+ XmlActionList, MutableDescriptor, XmlPooledInputDict, QueuedArtifactList
try:
from urllib.parse import urlsplit, urlparse, parse_qs, urlunparse
@@ -1041,13 +1041,28 @@ class ReagentType(Entity):
self.sequence = child.attrib.get("value")
class Queue(Entity):
- """Queue of a given step"""
+ """Queue of a given workflow stage"""
_URI = "queues"
_TAG= "queue"
_PREFIX = "que"
- artifacts = EntityListDescriptor("artifact", Artifact, nesting=["artifacts"])
- """List of :py:class:`artifacts <pyclarity_lims.entities.Artifact>` associated with this workflow."""
+ queued_artifacts = MutableDescriptor(QueuedArtifactList)
+ """
+ List of :py:class:`artifacts <pyclarity_lims.entities.Artifact>` associated with this workflow stage.
+ alongside the time the've been added to that queue and the container they're in.
+ The list contains tuples organise as follow:
+ (A, B, (C, D)) where
+ A is an :py:class:`artifacts <pyclarity_lims.entities.Artifact>`
+ B is a :py:class:`datetime <datetime.datetime>` object,
+ C is a :py:class:`container <pyclarity_lims.entities.Container>`
+ D is a string specifying the location such as "1:1"
+ """
+
+ @property
+ def artifacts(self):
+ """List of :py:class:`artifacts <pyclarity_lims.entities.Artifact>` associated with this workflow stage."""
+ return [i[0] for i in self.queued_artifacts]
+
Sample.artifact = EntityDescriptor('artifact', Artifact)
StepActions.step = EntityDescriptor('step', Step)
| EdinburghGenomics/pyclarity-lims | 82c1b93217a26395d5068fb0080ce09a0578121e | diff --git a/tests/test_descriptors.py b/tests/test_descriptors.py
index 7cfea0a..be7c731 100644
--- a/tests/test_descriptors.py
+++ b/tests/test_descriptors.py
@@ -3,14 +3,15 @@ from sys import version_info
from unittest import TestCase
from xml.etree import ElementTree
+import datetime
import pytest
from pyclarity_lims.constants import nsmap
from pyclarity_lims.descriptors import StringDescriptor, StringAttributeDescriptor, StringListDescriptor, \
StringDictionaryDescriptor, IntegerDescriptor, BooleanDescriptor, UdfDictionary, EntityDescriptor, \
InputOutputMapList, EntityListDescriptor, PlacementDictionary, EntityList, SubTagDictionary, ExternalidList,\
- XmlElementAttributeDict, XmlAttributeList, XmlReagentLabelList, XmlPooledInputDict, XmlAction
-from pyclarity_lims.entities import Artifact, ProtocolStep
+ XmlElementAttributeDict, XmlAttributeList, XmlReagentLabelList, XmlPooledInputDict, XmlAction, QueuedArtifactList
+from pyclarity_lims.entities import Artifact, ProtocolStep, Container
from pyclarity_lims.lims import Lims
from tests import elements_equal
@@ -728,3 +729,58 @@ class TestXmlAction(TestCase):
with pytest.raises(KeyError):
action['whatever'] = 'youwant'
+
+
+class TestQueuedArtifactList(TestCase):
+ def setUp(self):
+ et = ElementTree.fromstring('''<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+ <test-entry>
+ <artifacts>
+ <artifact uri="{url}/artifacts/a1">
+ <queue-time>2011-12-25T01:10:10.050+00:00</queue-time>
+ <location>
+ <container uri="{url}/containers/c1"/>
+ <value>A:1</value>
+ </location>
+ </artifact>
+ <artifact uri="{url}/artifacts/a2">
+ <queue-time>2011-12-25T01:10:10.200+01:00</queue-time>
+ <location>
+ <container uri="{url}/containers/c1"/>
+ <value>A:2</value>
+ </location>
+ </artifact>
+ </artifacts>
+ </test-entry>'''.format(url='http://testgenologics.com:4040/api/v2'))
+
+ self.lims = Lims('http://testgenologics.com:4040', username='test', password='password')
+ self.instance1 = Mock(root=et, lims=self.lims)
+
+ def get_queue_art(self, art_id, pos, microsec, time_delta):
+ if version_info[0] == 2:
+ return (
+ Artifact(self.lims, id=art_id),
+ datetime.datetime(2011, 12, 25, 1, 10, 10, microsec),
+ (Container(self.lims, id='c1'), pos)
+ )
+ else:
+ return (
+ Artifact(self.lims, id=art_id),
+ datetime.datetime(2011, 12, 25, 1, 10, 10, microsec, tzinfo=datetime.timezone(time_delta)),
+ (Container(self.lims, id='c1'), pos)
+ )
+
+ def test_parse(self):
+ queued_artifacts = QueuedArtifactList(self.instance1)
+ qart = self.get_queue_art('a1', 'A:1', 50000, datetime.timedelta(0, 0))
+ assert queued_artifacts[0] == qart
+ qart = self.get_queue_art('a2', 'A:2', 200000, datetime.timedelta(0, 3600))
+ assert queued_artifacts[1] == qart
+
+ def test_set(self):
+ queued_artifacts = QueuedArtifactList(self.instance1)
+ qart = self.get_queue_art('a1', 'A:3', 50000, datetime.timedelta(0, 0))
+ with pytest.raises(NotImplementedError):
+ queued_artifacts.append(qart)
+
+
| Queue Class does not have an easily acessible "queue-time" member variable
In the Queue Class I feel as if the "queue-time" member variable should exist under artifacts just like location does. However, I have to traverse artifacts._elems[0]._children[0].text to get the queue time. Can we make this so something like artifacts[0].queue_time works? Thanks. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_descriptors.py::TestIntegerDescriptor::test__set__",
"tests/test_descriptors.py::TestIntegerDescriptor::test__get__",
"tests/test_descriptors.py::TestIntegerDescriptor::test_create",
"tests/test_descriptors.py::TestXmlAttributeList::test_append",
"tests/test_descriptors.py::TestXmlAttributeList::test_insert",
"tests/test_descriptors.py::TestXmlAttributeList::test_get",
"tests/test_descriptors.py::TestXmlAction::test_set",
"tests/test_descriptors.py::TestXmlAction::test_parse",
"tests/test_descriptors.py::TestXmlReagentLabelList::test_append",
"tests/test_descriptors.py::TestXmlReagentLabelList::test_get",
"tests/test_descriptors.py::TestEntityDescriptor::test_create",
"tests/test_descriptors.py::TestEntityDescriptor::test__get__",
"tests/test_descriptors.py::TestEntityDescriptor::test__set__",
"tests/test_descriptors.py::TestXmlPooledInputDict::test___getitem__",
"tests/test_descriptors.py::TestXmlPooledInputDict::test___setitem__",
"tests/test_descriptors.py::TestStringDescriptor::test__get__",
"tests/test_descriptors.py::TestStringDescriptor::test_create",
"tests/test_descriptors.py::TestStringDescriptor::test__set__",
"tests/test_descriptors.py::TestBooleanDescriptor::test__get__",
"tests/test_descriptors.py::TestBooleanDescriptor::test_create",
"tests/test_descriptors.py::TestBooleanDescriptor::test__set__",
"tests/test_descriptors.py::TestStringListDescriptor::test__set__",
"tests/test_descriptors.py::TestStringListDescriptor::test__get__",
"tests/test_descriptors.py::TestUdfDictionary::test_create_with_nesting",
"tests/test_descriptors.py::TestUdfDictionary::test_clear",
"tests/test_descriptors.py::TestUdfDictionary::test_create",
"tests/test_descriptors.py::TestUdfDictionary::test___iter__",
"tests/test_descriptors.py::TestUdfDictionary::test___setitem__",
"tests/test_descriptors.py::TestUdfDictionary::test_items",
"tests/test_descriptors.py::TestUdfDictionary::test___getitem__",
"tests/test_descriptors.py::TestUdfDictionary::test___setitem__new",
"tests/test_descriptors.py::TestUdfDictionary::test___delitem__",
"tests/test_descriptors.py::TestUdfDictionary::test___setitem__unicode",
"tests/test_descriptors.py::TestEntityListDescriptor::test__get__",
"tests/test_descriptors.py::TestEntityList::test_insert",
"tests/test_descriptors.py::TestEntityList::test_append",
"tests/test_descriptors.py::TestEntityList::test_set",
"tests/test_descriptors.py::TestEntityList::test_set_list",
"tests/test_descriptors.py::TestEntityList::test__get__",
"tests/test_descriptors.py::TestExternalidList::test_get",
"tests/test_descriptors.py::TestExternalidList::test_append",
"tests/test_descriptors.py::TestInputOutputMapList::test___get__",
"tests/test_descriptors.py::TestXmlElementAttributeDict::test__len__",
"tests/test_descriptors.py::TestXmlElementAttributeDict::test___setitem__",
"tests/test_descriptors.py::TestXmlElementAttributeDict::test___getitem__",
"tests/test_descriptors.py::TestQueuedArtifactList::test_parse",
"tests/test_descriptors.py::TestQueuedArtifactList::test_set",
"tests/test_descriptors.py::TestPlacementDictionary::test___getitem__",
"tests/test_descriptors.py::TestPlacementDictionary::test___setitem__",
"tests/test_descriptors.py::TestPlacementDictionary::test___setitem__2",
"tests/test_descriptors.py::TestPlacementDictionary::test___delitem__",
"tests/test_descriptors.py::TestStringAttributeDescriptor::test__get__",
"tests/test_descriptors.py::TestStringAttributeDescriptor::test_create",
"tests/test_descriptors.py::TestStringAttributeDescriptor::test__set__"
] | [] | {
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2018-01-03T16:43:34Z" | mit |
|
EdinburghGenomics__pyclarity-lims-54 | diff --git a/pyclarity_lims/descriptors.py b/pyclarity_lims/descriptors.py
index 91e2a4d..6ac8565 100644
--- a/pyclarity_lims/descriptors.py
+++ b/pyclarity_lims/descriptors.py
@@ -278,21 +278,25 @@ class XmlAction(XmlElementAttributeDict):
action: The type of action to perform. (leave, repeat, remove, review, complete, store, nextstep, rework, completerepeat, unknown)
"""
def _parse_element(self, element, **kwargs):
- from pyclarity_lims.entities import Artifact, ProtocolStep
+ from pyclarity_lims.entities import Artifact, ProtocolStep, Step
for k, v in element.attrib.items():
if k == 'artifact-uri':
k = 'artifact'
v = Artifact(self.instance.lims, uri=v)
- elif k in ('step-uri', 'rework-step-uri'):
+ elif k == 'step-uri':
k = k[:-(len('-uri'))]
v = ProtocolStep(self.instance.lims, uri=v)
+ elif k == 'rework-step-uri':
+ k = k[:-(len('-uri'))]
+ v = Step(self.instance.lims, uri=v)
dict.__setitem__(self, k, v)
def _setitem(self, key, value):
- from pyclarity_lims.entities import Artifact, ProtocolStep
- if (key in ['artifact'] and isinstance(value, Artifact)) or \
- (key in ['step', 'rework-step'] and isinstance(value, ProtocolStep)):
+ from pyclarity_lims.entities import Artifact, ProtocolStep, Step
+ if key == 'artifact' and isinstance(value, Artifact) or \
+ key == 'step' and isinstance(value, ProtocolStep) or \
+ key == 'rework-step' and isinstance(value, Step):
key += '-uri'
value = value.uri
elif key in ['action']:
| EdinburghGenomics/pyclarity-lims | a03be6eda34f0d8adaf776d2286198a34e40ecf5 | diff --git a/tests/test_descriptors.py b/tests/test_descriptors.py
index 2523475..407b430 100644
--- a/tests/test_descriptors.py
+++ b/tests/test_descriptors.py
@@ -11,7 +11,7 @@ from pyclarity_lims.descriptors import StringDescriptor, StringAttributeDescript
StringDictionaryDescriptor, IntegerDescriptor, BooleanDescriptor, UdfDictionary, EntityDescriptor, \
InputOutputMapList, EntityListDescriptor, PlacementDictionary, EntityList, SubTagDictionary, ExternalidList,\
XmlElementAttributeDict, XmlAttributeList, XmlReagentLabelList, XmlPooledInputDict, XmlAction, QueuedArtifactList
-from pyclarity_lims.entities import Artifact, ProtocolStep, Container, Process
+from pyclarity_lims.entities import Artifact, ProtocolStep, Container, Process, Step
from pyclarity_lims.lims import Lims
from tests import elements_equal
@@ -780,7 +780,7 @@ class TestXmlAction(TestCase):
def setUp(self):
et = ElementTree.fromstring('''<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<test-entry>
- <next-action step-uri="{url}/prt/1/stp/1" action="nextstep" artifact-uri="{url}/arts/a1"/>
+ <next-action step-uri="{url}/prt/1/stp/1" rework-step-uri="{url}/steps/1" action="nextstep" artifact-uri="{url}/arts/a1"/>
</test-entry>'''.format(url='http://testgenologics.com:4040'))
et1 = ElementTree.fromstring('''<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
@@ -797,6 +797,7 @@ class TestXmlAction(TestCase):
assert action['action'] == 'nextstep'
assert action['step'] == ProtocolStep(self.lims, uri='http://testgenologics.com:4040/prt/1/stp/1')
assert action['artifact'] == Artifact(self.lims, uri='http://testgenologics.com:4040/arts/a1')
+ assert action['rework-step'] == Step(self.lims, uri='http://testgenologics.com:4040/steps/1')
def test_set(self):
action = XmlAction(self.instance_empty, tag='next-action')
@@ -804,6 +805,8 @@ class TestXmlAction(TestCase):
assert action.instance.root.find('next-action').attrib['step-uri'] == 'http://testgenologics.com:4040/prt/1/stp/1'
action['action'] = 'nextstep'
assert action.instance.root.find('next-action').attrib['action'] == 'nextstep'
+ action['rework-step'] = Step(self.lims, uri='http://testgenologics.com:4040/steps/1')
+ assert action.instance.root.find('next-action').attrib['rework-step-uri'] == 'http://testgenologics.com:4040/steps/1'
with pytest.raises(KeyError):
action['whatever'] = 'youwant'
| StepAction rework-step take a Step
It currently accept a protocolStep which is incorrect | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_descriptors.py::TestXmlAction::test_set"
] | [
"tests/test_descriptors.py::TestStringDescriptor::test__get__",
"tests/test_descriptors.py::TestStringDescriptor::test__set__",
"tests/test_descriptors.py::TestStringDescriptor::test_create",
"tests/test_descriptors.py::TestIntegerDescriptor::test__get__",
"tests/test_descriptors.py::TestIntegerDescriptor::test__set__",
"tests/test_descriptors.py::TestIntegerDescriptor::test_create",
"tests/test_descriptors.py::TestBooleanDescriptor::test__get__",
"tests/test_descriptors.py::TestBooleanDescriptor::test__set__",
"tests/test_descriptors.py::TestBooleanDescriptor::test_create",
"tests/test_descriptors.py::TestEntityDescriptor::test__get__",
"tests/test_descriptors.py::TestEntityDescriptor::test__set__",
"tests/test_descriptors.py::TestEntityDescriptor::test_create",
"tests/test_descriptors.py::TestEntityListDescriptor::test__get__",
"tests/test_descriptors.py::TestStringAttributeDescriptor::test__get__",
"tests/test_descriptors.py::TestStringAttributeDescriptor::test__set__",
"tests/test_descriptors.py::TestStringAttributeDescriptor::test_create",
"tests/test_descriptors.py::TestStringListDescriptor::test__get__",
"tests/test_descriptors.py::TestStringListDescriptor::test__set__",
"tests/test_descriptors.py::TestUdfDictionary::test___delitem__",
"tests/test_descriptors.py::TestUdfDictionary::test___getitem__",
"tests/test_descriptors.py::TestUdfDictionary::test___iter__",
"tests/test_descriptors.py::TestUdfDictionary::test___setitem__",
"tests/test_descriptors.py::TestUdfDictionary::test___setitem__new",
"tests/test_descriptors.py::TestUdfDictionary::test___setitem__unicode",
"tests/test_descriptors.py::TestUdfDictionary::test_clear",
"tests/test_descriptors.py::TestUdfDictionary::test_create",
"tests/test_descriptors.py::TestUdfDictionary::test_create_with_nesting",
"tests/test_descriptors.py::TestUdfDictionary::test_items",
"tests/test_descriptors.py::TestPlacementDictionary::test___delitem__",
"tests/test_descriptors.py::TestPlacementDictionary::test___getitem__",
"tests/test_descriptors.py::TestPlacementDictionary::test___setitem__",
"tests/test_descriptors.py::TestPlacementDictionary::test___setitem__2",
"tests/test_descriptors.py::TestPlacementDictionary::test_clear",
"tests/test_descriptors.py::TestXmlElementAttributeDict::test___getitem__",
"tests/test_descriptors.py::TestXmlElementAttributeDict::test___setitem__",
"tests/test_descriptors.py::TestXmlElementAttributeDict::test__len__",
"tests/test_descriptors.py::TestXmlPooledInputDict::test___getitem__",
"tests/test_descriptors.py::TestXmlPooledInputDict::test___setitem1__",
"tests/test_descriptors.py::TestXmlPooledInputDict::test___setitem2__",
"tests/test_descriptors.py::TestEntityList::test___add__",
"tests/test_descriptors.py::TestEntityList::test__get__",
"tests/test_descriptors.py::TestEntityList::test__iadd__",
"tests/test_descriptors.py::TestEntityList::test_append",
"tests/test_descriptors.py::TestEntityList::test_clear",
"tests/test_descriptors.py::TestEntityList::test_insert",
"tests/test_descriptors.py::TestEntityList::test_set",
"tests/test_descriptors.py::TestEntityList::test_set_list",
"tests/test_descriptors.py::TestInputOutputMapList::test___get__",
"tests/test_descriptors.py::TestInputOutputMapList::test_create",
"tests/test_descriptors.py::TestExternalidList::test_append",
"tests/test_descriptors.py::TestExternalidList::test_get",
"tests/test_descriptors.py::TestXmlAttributeList::test_append",
"tests/test_descriptors.py::TestXmlAttributeList::test_get",
"tests/test_descriptors.py::TestXmlAttributeList::test_insert",
"tests/test_descriptors.py::TestXmlReagentLabelList::test_append",
"tests/test_descriptors.py::TestXmlReagentLabelList::test_get",
"tests/test_descriptors.py::TestXmlAction::test_parse",
"tests/test_descriptors.py::TestQueuedArtifactList::test_parse",
"tests/test_descriptors.py::TestQueuedArtifactList::test_parse_multipage",
"tests/test_descriptors.py::TestQueuedArtifactList::test_set"
] | {
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false
} | "2019-03-12T12:44:38Z" | mit |
|
Electrostatics__mmcif_pdbx-23 | diff --git a/pdbx/reader.py b/pdbx/reader.py
index 2a91215..c5bd339 100644
--- a/pdbx/reader.py
+++ b/pdbx/reader.py
@@ -46,9 +46,7 @@ class PdbxReader:
try:
self.__parser(self.__tokenizer(self.__input_file), container_list)
except StopIteration:
- pass
- else:
- raise PdbxError()
+ self.__syntax_error("Unexpected end of file")
def __syntax_error(self, error_text):
"""Raise a PdbxSyntaxError."""
@@ -97,14 +95,16 @@ class PdbxReader:
state = None
# Find the first reserved word and begin capturing data.
- while True:
- current_category_name, current_attribute_name, \
- current_quoted_string, current_word = next(tokenizer)
+ for (current_category_name, current_attribute_name,
+ current_quoted_string, current_word) in tokenizer:
if current_word is None:
continue
reserved_word, state = self.__get_state(current_word)
if reserved_word is not None:
break
+ else:
+ # empty file
+ return
while True:
# Set the current state: at this point in the processing cycle we
@@ -174,8 +174,8 @@ class PdbxReader:
try:
current_category_name, current_attribute_name, \
current_quoted_string, current_word = next(tokenizer)
- except RuntimeError as err:
- raise StopIteration(err)
+ except StopIteration:
+ return
continue
# Process a loop_ declaration and associated data
@@ -205,9 +205,8 @@ class PdbxReader:
return
current_category.append_attribute(current_attribute_name)
# Read the rest of the loop_ declaration
- while True:
- current_category_name, current_attribute_name, \
- current_quoted_string, current_word = next(tokenizer)
+ for (current_category_name, current_attribute_name,
+ current_quoted_string, current_word) in tokenizer:
if current_category_name is None:
break
if current_category_name != current_category.name:
@@ -215,6 +214,9 @@ class PdbxReader:
"Changed category name in loop_ declaration")
return
current_category.append_attribute(current_attribute_name)
+ else:
+ # formal CIF 1.1 grammar expects at least one value
+ self.__syntax_error("loop_ without values")
# If the next token is a 'word', check it for any reserved
# words
if current_word is not None:
@@ -239,8 +241,8 @@ class PdbxReader:
current_category_name, current_attribute_name, \
current_quoted_string, current_word = next(
tokenizer)
- except RuntimeError as err:
- raise StopIteration(err)
+ except StopIteration:
+ return
# loop_ data processing ends if a new _category.attribute
# is encountered
if current_category_name is not None:
@@ -260,8 +262,6 @@ class PdbxReader:
container_list.append(current_container)
category_index = {}
current_category = None
- current_category_name, current_attribute_name, \
- current_quoted_string, current_word = next(tokenizer)
elif state == "ST_DATA_CONTAINER":
data_name = self.__get_container_name(current_word)
if data_name:
@@ -270,23 +270,26 @@ class PdbxReader:
container_list.append(current_container)
category_index = {}
current_category = None
- current_category_name, current_attribute_name, \
- current_quoted_string, current_word = next(tokenizer)
elif state == "ST_STOP":
return
-
- if state == "ST_GLOBAL":
+ elif state == "ST_GLOBAL":
current_container = DataContainer("blank-global")
current_container.set_global()
container_list.append(current_container)
category_index = {}
current_category = None
- current_category_name, current_attribute_name, \
- current_quoted_string, current_word = next(tokenizer)
elif state == "ST_UNKNOWN":
self.__syntax_error(
"Unrecognized syntax element: " + str(current_word))
return
+ else:
+ assert False, f"unhandled state {state}"
+
+ try:
+ current_category_name, current_attribute_name, \
+ current_quoted_string, current_word = next(tokenizer)
+ except StopIteration:
+ return
def __tokenizer(self, input_file):
"""Tokenizer method for the mmCIF syntax file.
@@ -311,8 +314,7 @@ class PdbxReader:
)
file_iterator = iter(input_file)
# Tokenizer loop begins here
- while True:
- line = next(file_iterator)
+ for line in file_iterator:
self.__current_line_number += 1
# Dump comments
if line.startswith("#"):
@@ -321,12 +323,13 @@ class PdbxReader:
# and stuff this into the string slot in the return tuple
if line.startswith(";"):
multiline_string = [line[1:]]
- while True:
- line = next(file_iterator)
+ for line in file_iterator:
self.__current_line_number += 1
if line.startswith(";"):
break
multiline_string.append(line)
+ else:
+ self.__syntax_error("unterminated multi-line string")
# remove trailing new-line that is part of the \n; delimiter
multiline_string[-1] = multiline_string[-1].rstrip()
yield (None, None, "".join(multiline_string), None)
| Electrostatics/mmcif_pdbx | 2d5204cb5fb9ec85ae219bcc51a3733a40645687 | diff --git a/tests/reader_test.py b/tests/reader_test.py
index 4307ad9..e1fb3d5 100644
--- a/tests/reader_test.py
+++ b/tests/reader_test.py
@@ -9,9 +9,11 @@
#
##
"""Test cases for reading PDBx/mmCIF data files reader class."""
+import io
import logging
from pathlib import Path
import pytest
+from pdbx.errors import PdbxSyntaxError
from pdbx.reader import PdbxReader
@@ -40,3 +42,80 @@ def test_structure_factor_file(input_cif):
container = container_list[0]
refln_object = container.get_object("refln")
assert refln_object is not None
+
+
+def read_cifstr(cifstr: str) -> list:
+ """Helper function"""
+ data = []
+ PdbxReader(io.StringIO(cifstr)).read(data)
+ return data
+
+
+def test_empty_file():
+ assert read_cifstr('') == []
+
+
+def test_empty_data_block():
+ assert read_cifstr('data_test')[0].get_object_name_list() == []
+
+
+def test_missing_value_eof():
+ with pytest.raises(PdbxSyntaxError) as excinfo:
+ read_cifstr('data_test _a.x')
+ assert "end of file" in str(excinfo.value)
+
+
+def test_missing_value_not_eof():
+ with pytest.raises(PdbxSyntaxError) as excinfo:
+ read_cifstr('data_test _a.x _a.y A')
+ assert "Missing data for item _a.x" in str(excinfo.value)
+
+
+def test_missing_key():
+ with pytest.raises(PdbxSyntaxError) as excinfo:
+ read_cifstr('data_test _a.x A B')
+ assert "Unrecognized syntax element: B" in str(excinfo.value)
+
+
+def test_empty_loop_header_eof():
+ # formal CIF 1.1 grammar expects at least one tag
+ with pytest.raises(PdbxSyntaxError) as excinfo:
+ read_cifstr('data_test loop_')
+ assert "end of file" in str(excinfo.value)
+
+
+def test_empty_loop_header_not_eof():
+ # formal CIF 1.1 grammar expects at least one tag
+ with pytest.raises(PdbxSyntaxError) as excinfo:
+ read_cifstr('data_test loop_ loop_')
+ assert "Unexpected token" in str(excinfo.value)
+
+
+def test_empty_loop_body_eof():
+ # formal CIF 1.1 grammar expects at least one value
+ with pytest.raises(PdbxSyntaxError) as excinfo:
+ read_cifstr('data_test loop_ _a.x')
+ assert "loop_ without values" in str(excinfo.value)
+
+
+def test_empty_loop_body_not_eof():
+ # formal CIF 1.1 grammar expects at least one value
+ with pytest.raises(PdbxSyntaxError) as excinfo:
+ read_cifstr('data_test loop_ _a.x loop_')
+ assert "Unexpected reserved word" in str(excinfo.value)
+
+
+def test_loop_value_count_mismatch():
+ # https://www.iucr.org/resources/cif/spec/version1.1/cifsyntax Β§ 63:
+ # The number of values in the body must be a multiple of the number of tags in the header
+ with pytest.raises(PdbxSyntaxError) as excinfo:
+ read_cifstr('data_test loop_ _a.x _a.y A')
+ pytest.skip("does not raise yet") # TODO
+
+
+def test_incomplete_multiline_string():
+ read_cifstr('data_test _a.x\n;A\n;') # correct (terminated)
+ read_cifstr('data_test _a.x ;A') # correct (not a multi-line string)
+ with pytest.raises(PdbxSyntaxError) as excinfo:
+ read_cifstr('data_test _a.x\n;A')
+ assert "unterminated multi-line" in str(excinfo.value)
| Refactor usage of StopIteration in pdbx.reader
`pdbx.reader` follows a pre-[PEP 479](https://www.python.org/dev/peps/pep-0479/) pattern of `StopIteration` usage with a `RuntimeError` band-aid. This should be refactored.
@sobolevnrm I'd be happy to send a pull request, unless this code is already being worked on. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/reader_test.py::test_missing_value_eof",
"tests/reader_test.py::test_empty_loop_body_eof",
"tests/reader_test.py::test_empty_data_block",
"tests/reader_test.py::test_empty_loop_header_eof",
"tests/reader_test.py::test_empty_file",
"tests/reader_test.py::test_incomplete_multiline_string"
] | [
"tests/reader_test.py::test_missing_value_not_eof",
"tests/reader_test.py::test_missing_key",
"tests/reader_test.py::test_empty_loop_body_not_eof",
"tests/reader_test.py::test_empty_loop_header_not_eof",
"tests/reader_test.py::test_structure_factor_file[1kip-sf.cif]",
"tests/reader_test.py::test_data_file[1ffk.cif]",
"tests/reader_test.py::test_data_file[1kip.cif]"
] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
} | "2020-07-07T18:18:14Z" | cc0-1.0 |
|
Electrostatics__mmcif_pdbx-27 | diff --git a/pdbx/__init__.py b/pdbx/__init__.py
index 17ecc8a..1ad970d 100644
--- a/pdbx/__init__.py
+++ b/pdbx/__init__.py
@@ -8,3 +8,31 @@ http://mmcif.wwpdb.org/docs/sw-examples/python/html/.
See http://mmcif.wwpdb.org/docs/sw-examples/python/html/ for more information
about this package, including examples.
"""
+
+
+def load(fp) -> list:
+ """Parse a CIF file into a list of DataContainer objects"""
+ from .reader import PdbxReader
+ data = []
+ PdbxReader(fp).read(data)
+ return data
+
+
+def loads(s: str) -> list:
+ """Parse a CIF string into a list of DataContainer objects"""
+ import io
+ return load(io.StringIO(s))
+
+
+def dump(datacontainers: list, fp):
+ """Write a list of DataContainer objects to a CIF file"""
+ from .writer import PdbxWriter
+ PdbxWriter(fp).write(datacontainers)
+
+
+def dumps(datacontainers: list) -> str:
+ """Serialize a list of DataContainer objects to a CIF formatted string"""
+ import io
+ fp = io.StringIO()
+ dump(datacontainers, fp)
+ return fp.getvalue()
diff --git a/pdbx/containers.py b/pdbx/containers.py
index 8664573..e185162 100644
--- a/pdbx/containers.py
+++ b/pdbx/containers.py
@@ -628,7 +628,8 @@ class DataCategory(DataCategoryBase):
return ([str(inp)], 'DT_FLOAT')
# null value handling
if inp in (".", "?"):
- return ([inp], 'DT_NULL_VALUE')
+ return (self.__double_quoted_list(inp),
+ 'DT_DOUBLE_QUOTED_STRING')
if inp == "":
return (["."], 'DT_NULL_VALUE')
# Contains white space or quotes ?
@@ -689,7 +690,7 @@ class DataCategory(DataCategoryBase):
return 'DT_FLOAT'
# null value handling
if inp in (".", "?"):
- return 'DT_NULL_VALUE'
+ return 'DT_DOUBLE_QUOTED_STRING'
if inp == "":
return 'DT_NULL_VALUE'
# Contains white space or quotes ?
diff --git a/pdbx/reader.py b/pdbx/reader.py
index c5bd339..95394f5 100644
--- a/pdbx/reader.py
+++ b/pdbx/reader.py
@@ -160,7 +160,11 @@ class PdbxReader:
self.__syntax_error(
"Missing data for item _%s.%s" % (
current_category_name, current_attribute_name))
- if current_word is not None:
+ if current_word == '?':
+ current_row.append(None)
+ elif current_word == '.':
+ current_row.append('')
+ elif current_word is not None:
# Validation check token for misplaced reserved words
reserved_word, state = self.__get_state(current_word)
if reserved_word is not None:
@@ -233,7 +237,11 @@ class PdbxReader:
current_row = []
current_category.append(current_row)
for _ in current_category.attribute_list:
- if current_word is not None:
+ if current_word == '?':
+ current_row.append(None)
+ elif current_word == '.':
+ current_row.append('')
+ elif current_word is not None:
current_row.append(current_word)
elif current_quoted_string is not None:
current_row.append(current_quoted_string)
@@ -264,7 +272,7 @@ class PdbxReader:
current_category = None
elif state == "ST_DATA_CONTAINER":
data_name = self.__get_container_name(current_word)
- if data_name:
+ if not data_name:
data_name = "unidentified"
current_container = DataContainer(data_name)
container_list.append(current_container)
| Electrostatics/mmcif_pdbx | aa5510885133259139f355a6a14a080386745dbd | diff --git a/tests/reader_test.py b/tests/reader_test.py
index e1fb3d5..f685180 100644
--- a/tests/reader_test.py
+++ b/tests/reader_test.py
@@ -15,6 +15,7 @@ from pathlib import Path
import pytest
from pdbx.errors import PdbxSyntaxError
from pdbx.reader import PdbxReader
+from pdbx import loads as read_cifstr
DATA_DIR = Path("tests/data")
@@ -44,13 +45,6 @@ def test_structure_factor_file(input_cif):
assert refln_object is not None
-def read_cifstr(cifstr: str) -> list:
- """Helper function"""
- data = []
- PdbxReader(io.StringIO(cifstr)).read(data)
- return data
-
-
def test_empty_file():
assert read_cifstr('') == []
| Distinguish unknown (?) and inapplicable (.) values from strings
CIF has two special values: `?` for unknown data, and `.` for inapplicable data. As far as I can tell, the API in this library doesn't distinguish these values from strings.
I think it would be very useful if these values are represented by a special constant, just like the JSON `null` value corresponds to `None` in the standard library [json](https://docs.python.org/3/library/json.html) module.
### Example
```python
import io
from pdbx.reader import PdbxReader
cif_str = '''
data_example
_unknown.a ?
_unknown.b "?"
_inapplicable.a .
_inapplicable.b "."
'''
cfr = PdbxReader(io.StringIO(cif_str))
data = []
cfr.read(data)
for cat in ['unknown', 'inapplicable']:
for key in ['a', 'b']:
value = data[0].get_object(cat).get_value(key)
print(type(value), repr(value))
```
### Output
```
<class 'str'> '?'
<class 'str'> '?'
<class 'str'> '.'
<class 'str'> '.'
```
### Expected Output
Option 1: Custom constants. This is the most expressive/explicit option.
```
<class 'pdbx.UnknownType'> Unknown
<class 'str'> '?'
<class 'pdbx.InapplicableType'> Inapplicable
<class 'str'> '.'
```
Option 2: Just use `None` for both. For **reading only**, this would be perfectly sufficient (haven't seen a use case yet were data interpretation of `?` and `.` was different). But information is lost when writing back a CIF file.
```
<class 'NoneType'> None
<class 'str'> '?'
<class 'NoneType'> None
<class 'str'> '.'
```
Option 3: Use `None` for one of the values, and a custom constant for the other one. In the spirit of `dict.get(missing-key) -> None` this might be the most Pythonic option.
```
<class 'NoneType'> None
<class 'str'> '?'
<class 'pdbx.InapplicableType'> Inapplicable
<class 'str'> '.'
``` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/reader_test.py::test_data_file[1kip.cif]",
"tests/reader_test.py::test_data_file[1ffk.cif]",
"tests/reader_test.py::test_structure_factor_file[1kip-sf.cif]",
"tests/reader_test.py::test_empty_file",
"tests/reader_test.py::test_empty_data_block",
"tests/reader_test.py::test_missing_value_eof",
"tests/reader_test.py::test_missing_value_not_eof",
"tests/reader_test.py::test_missing_key",
"tests/reader_test.py::test_empty_loop_header_eof",
"tests/reader_test.py::test_empty_loop_header_not_eof",
"tests/reader_test.py::test_empty_loop_body_eof",
"tests/reader_test.py::test_empty_loop_body_not_eof",
"tests/reader_test.py::test_incomplete_multiline_string"
] | [] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2020-07-08T07:32:45Z" | cc0-1.0 |
|
EmilStenstrom__conllu-35 | diff --git a/conllu/parser.py b/conllu/parser.py
index 16ec94b..7456879 100644
--- a/conllu/parser.py
+++ b/conllu/parser.py
@@ -141,7 +141,7 @@ def parse_id_value(value):
ANY_ID = re.compile(ID_SINGLE.pattern + "|" + ID_RANGE.pattern + "|" + ID_DOT_ID.pattern)
-DEPS_RE = re.compile("(" + ANY_ID.pattern + r"):[a-z][a-z_-]*(\:[a-z][a-z_-]*)?")
+DEPS_RE = re.compile("(" + ANY_ID.pattern + r"):[a-zA-Z][a-zA-Z0-9_-]*(\:[a-zA-Z][a-zA-Z0-9_-]*)?")
MULTI_DEPS_PATTERN = re.compile(r"{}(\|{})*".format(DEPS_RE.pattern, DEPS_RE.pattern))
def parse_paired_list_value(value):
| EmilStenstrom/conllu | 6da39c07ccafc4c280f10eb51b12165472a609a9 | diff --git a/tests/test_parser.py b/tests/test_parser.py
index 0e13a77..2733b58 100644
--- a/tests/test_parser.py
+++ b/tests/test_parser.py
@@ -361,6 +361,14 @@ class TestParsePairedListValue(unittest.TestCase):
parse_paired_list_value("5:conj:and|8.1:nsubj:pass|9:nsubj:xsubj"),
[("conj:and", 5), ("nsubj:pass", (8, ".", 1)), ("nsubj:xsubj", 9)]
)
+ self.assertEqual(
+ parse_paired_list_value("1:compound|6:ARG|9:ARG1|10:ARG2"),
+ [('compound', 1), ('ARG', 6), ('ARG1', 9), ('ARG2', 10)]
+ )
+ self.assertNotEqual(
+ parse_paired_list_value("1:compound|6:ARG|9:ARG1|10:2ARG"),
+ [('compound', 1), ('ARG', 6), ('ARG1', 9), ('2ARG', 10)]
+ )
def test_parse_empty(self):
testcases = [
| Column 'deps' is not being parsed most of the time
Given the following sentence:
```
Removed.
```
The code at `parser.py:152` looks like this:
```python
def parse_paired_list_value(value):
if fullmatch(MULTI_DEPS_PATTERN, value):
return [
(part.split(":", 1)[1], parse_id_value(part.split(":")[0]))
for part in value.split("|")
]
return parse_nullable_value(value)
```
Is seems like the definition of `MULTI_DEPS_PATTERN` is not correct. Most `deps` values are returned as strings instead of a list of tuples, because the parsing fails. For example `'1:compound|6:ARG1|9:ARG1'` is considered bad, but according to [the specification](https://universaldependencies.org/format.html#syntactic-annotation) this should be alright. Actually the code for parsing inside of the if-statement works perfectly on this line. `'4:ARG1'` is also being considered flawed, but `'5:measure'` is being considered okay. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_parser.py::TestParsePairedListValue::test_parse_paired_list"
] | [
"tests/test_parser.py::TestParseLine::test_parse_line_nullable_fields",
"tests/test_parser.py::TestParseLine::test_parse_line_with_spaces",
"tests/test_parser.py::TestParseLine::test_parse_line_only_id_head",
"tests/test_parser.py::TestParseLine::test_parse_line_without_spacing",
"tests/test_parser.py::TestParseLine::test_parse_line_fewer_columns",
"tests/test_parser.py::TestParseLine::test_parse_line",
"tests/test_parser.py::TestParseLine::test_empty",
"tests/test_parser.py::TestParseLine::test_parse_line_two_spaces",
"tests/test_parser.py::TestParseDictValue::test_parse_dict_value",
"tests/test_parser.py::TestParseIDValue::test_decimal",
"tests/test_parser.py::TestParseIDValue::test_range",
"tests/test_parser.py::TestParseIDValue::test_none",
"tests/test_parser.py::TestParseIDValue::test_single",
"tests/test_parser.py::TestHeadToToken::test_simple",
"tests/test_parser.py::TestHeadToToken::test_decimal_ids_ignored",
"tests/test_parser.py::TestHeadToToken::test_range_ids_ignored",
"tests/test_parser.py::TestHeadToToken::test_missing_head",
"tests/test_parser.py::TestHeadToToken::test_negative_head",
"tests/test_parser.py::TestSerializeField::test_tuple",
"tests/test_parser.py::TestSerializeField::test_string",
"tests/test_parser.py::TestSerializeField::test_list",
"tests/test_parser.py::TestSerializeField::test_ordered_dict",
"tests/test_parser.py::TestSerializeField::test_none",
"tests/test_parser.py::TestParseIntValue::test_parse_int_value",
"tests/test_parser.py::TestParseTokenAndMetadata::test_invalid_metadata",
"tests/test_parser.py::TestParseTokenAndMetadata::test_newlines_in_sentence",
"tests/test_parser.py::TestParseTokenAndMetadata::test_custom_field_parsers",
"tests/test_parser.py::TestParseTokenAndMetadata::test_empty",
"tests/test_parser.py::TestParseTokenAndMetadata::test_custom_fields",
"tests/test_parser.py::TestParseTokenAndMetadata::test_default_field_parsers_when_undefined",
"tests/test_parser.py::TestParseNullableValue::test_parse_nullable_value",
"tests/test_parser.py::TestParseSentencesGenerator::test_ends_without_newline",
"tests/test_parser.py::TestParseSentencesGenerator::test_empty",
"tests/test_parser.py::TestParseSentencesGenerator::test_multiple_newlines",
"tests/test_parser.py::TestParseSentencesGenerator::test_simple",
"tests/test_parser.py::TestParseCommentLine::test_parse_comment_line_without_square",
"tests/test_parser.py::TestParseCommentLine::test_parse_comment_line_optional_value",
"tests/test_parser.py::TestParseCommentLine::test_parse_comment_line_optional_value_no_space",
"tests/test_parser.py::TestParseCommentLine::test_parse_comment_line",
"tests/test_parser.py::TestParseCommentLine::test_parse_comment_line_multiple_equals",
"tests/test_parser.py::TestParseCommentLine::test_parse_comment_line_without_equals",
"tests/test_parser.py::TestParseCommentLine::test_parse_spaces_before_square",
"tests/test_parser.py::TestParseCommentLine::test_parse_comment_line_without_space",
"tests/test_parser.py::TestParsePairedListValue::test_parse_empty",
"tests/test_parser.py::TestParsePairedListValue::test_parse_invalid",
"tests/test_parser.py::TestSerialize::test_serialize_tricky_fields",
"tests/test_parser.py::TestSerialize::test_metadata",
"tests/test_parser.py::TestSerialize::test_identity_unicode"
] | {
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
} | "2019-09-29T18:14:22Z" | mit |
|
EricssonResearch__arms-38 | diff --git a/arms/misc/__init__.py b/arms/misc/__init__.py
new file mode 100644
index 0000000..cb98f04
--- /dev/null
+++ b/arms/misc/__init__.py
@@ -0,0 +1,1 @@
+"""Modules related to misc"""
diff --git a/arms/misc/socket.py b/arms/misc/socket.py
new file mode 100644
index 0000000..0ca3fd3
--- /dev/null
+++ b/arms/misc/socket.py
@@ -0,0 +1,176 @@
+"""Utilities related to socket communication."""
+
+import socket
+from arms.utils import log
+from arms.config import config
+
+
+class SocketClient:
+
+ """A socket client with the capability to send/receive strings.
+
+ Attributes:
+ name: The client name; used to find the needed settings (host, port)
+ in the config file to be able to connect with the respective server.
+ sock: The socket interface.
+ """
+
+ def __init__(self, client_name):
+ self.name = client_name
+ self.sock = None
+
+ def get_config_and_connect(self):
+ """Reads the host and port number of the client (client_name)
+ defined in the config file and tries to connect with the respective
+ server.
+
+ Return:
+ - True, if a setting entry belonging to the client (client_name)
+ could be found and no data type violation occurred.
+ - False, if not.
+ """
+ try:
+ c = config.var.data['socket'][self.name]
+ host = c['host']
+ port = c['port']
+ except (TypeError, KeyError):
+ log.socket.error('Could not find (appropriate) settings for the '
+ 'socket {} in the configuration file ('
+ 'arms/config/config.json). Hence, no '
+ 'connection could be made.'.format(self.name))
+ return False
+
+ if isinstance(host, str) and isinstance(port, int):
+ ok = self.connect(host, port)
+ return ok
+ else:
+ log.socket.error('Data type violation. The host number has to be '
+ 'provided as a string and the port number as an '
+ 'integer in the configuration file ('
+ 'arms/config/config.json). In consequence, the '
+ 'socket {} could not connect to the server.'
+ .format(self.name))
+ return False
+
+ def connect(self, host, port):
+ """Establishes a connection to a server.
+
+ Args:
+ host: Represents either a hostname or an IPv4 address.
+ port: The port.
+
+ Return:
+ - True, if a connection could be made.
+ - False, if not.
+ """
+ self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ self.sock.settimeout(2.0)
+ try:
+ self.sock.connect((host, port))
+ self.sock.settimeout(None)
+ log.socket.info('Client {} | Connected to server at '
+ '(host, port) = ({}, {}).'
+ .format(self.name, host, port))
+ except (socket.error, socket.timeout) as e:
+ self.sock = None
+ log.socket.error('Client {} | No connection could be made to '
+ 'server at (host, port) = ({}, {}). Reason: {}'
+ .format(self.name, host, port, e))
+ return False
+ return True
+
+ def close(self):
+ """Closes the connection in a timely fashion."""
+ if self.sock is None:
+ return
+
+ self.sock.close()
+ self.sock = None
+ log.socket.info('Client {}: Disconnected from server.'.format(
+ self.name))
+
+ def send(self, data):
+ """Sends data to the socket in two steps.
+ 1. step: Sends the length of the original message.
+ 2. step: Sends the original message.
+
+ Args:
+ data: The data to send.
+
+ Return:
+ - True, if the data could be sent.
+ - False, if not.
+ """
+ if self.sock is None:
+ return False
+
+ if not isinstance(data, str):
+ data = str(data)
+
+ length = len(data)
+
+ try:
+ # 1. step: Send the length of the original message.
+ self.sock.sendall(b'a%d\n' % length)
+
+ # 2. step: Send the original message.
+ self.sock.sendall(data.encode())
+ except (socket.error, socket.timeout) as e:
+ self.sock = None
+ log.socket.error('SERVER | Error, can not send data. '
+ 'Reason: {}.'.format(e))
+ return False
+
+ return True
+
+ def recv(self):
+ """Receives data from the socket in two steps.
+ 1. step: Get the length of the original message.
+ 2. step: Receive the original message with respect to step one.
+
+ Return:
+ - [#1, #2]
+ #1: True if a client is connected, False if not.
+ #2: The received data.
+ """
+ if self.sock is None:
+ return [False, ""]
+
+ # 1. Get the length of the original message.
+ length_str = ""
+ char = ""
+ while char != '\n':
+ length_str += char
+ try:
+ char = self.sock.recv(1).decode()
+ except (socket.error, socket.timeout) as e:
+ self.sock = None
+ log.socket.error('SERVER | Error, can not receive data. '
+ 'Reason: {}.'.format(e))
+ return [False, ""]
+ if not char:
+ self.sock = None
+ log.socket.error('SERVER | Error, can not receive data. '
+ 'Reason: Not connected to server.')
+ return [False, ""]
+ if (char.isdigit() is False) and (char != '\n'):
+ length_str = ""
+ char = ""
+ total = int(length_str)
+
+ # 2. Receive the data chunk by chunk.
+ view = memoryview(bytearray(total))
+ next_offset = 0
+ while total - next_offset > 0:
+ try:
+ recv_size = self.sock.recv_into(view[next_offset:],
+ total - next_offset)
+ except (socket.error, socket.timeout) as e:
+ self.sock = None
+ log.socket.error('SERVER | Error, can not receive data. '
+ 'Reason: {}.'.format(e))
+ return [False, ""]
+ next_offset += recv_size
+
+ data = view.tobytes().decode()
+ return [True, data]
diff --git a/arms/utils/log.py b/arms/utils/log.py
index 9bab20d..672e910 100644
--- a/arms/utils/log.py
+++ b/arms/utils/log.py
@@ -71,7 +71,8 @@ def get_logger(name):
# The different loggers used (alphabetical order).
app = get_logger('app')
+ard_log = get_logger('ard_log')
+camera = get_logger('camera')
config = get_logger('config')
log = get_logger('log')
-camera = get_logger('camera')
-ard_log = get_logger('ard_log')
+socket = get_logger('socket')
diff --git a/requirements.txt b/requirements.txt
index c76c3a1..a6b2e32 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -1,1 +1,2 @@
-# List of files to be installed using pip install.
\ No newline at end of file
+# List of files to be installed using pip install.
+pytest
\ No newline at end of file
| EricssonResearch/arms | 331f9d63bcfee438fada298186e88743fda4e37e | diff --git a/tests/unit/test_socket.py b/tests/unit/test_socket.py
new file mode 100644
index 0000000..a1a9b3c
--- /dev/null
+++ b/tests/unit/test_socket.py
@@ -0,0 +1,270 @@
+"""Tests for arms.misc.socket"""
+
+import pytest
+import socket
+import threading
+from unittest import mock
+from unittest.mock import call
+from arms.config import config
+from arms.misc.socket import SocketClient
+
+# Global variables.
+host = "127.0.0.1"
+port = 5000
+
+
+def test_init():
+ """The instance attributes 'client_name' and 'sock' shall be changeable."""
+ # Test changeability of 'client_name'.
+ client = SocketClient("test_init")
+ tmp = client.name
+ client.name = "test_init"
+ assert client.name == "test_init"
+ client.name = tmp
+ assert client.name == tmp
+
+ # Test changeability of 'sock'.
+ tmp = client.sock
+ client.sock = "test_init"
+ assert client.sock == "test_init"
+ client.sock = tmp
+ assert client.sock == tmp
+
+
+def test_get_config_and_connect():
+ """WHEN the function 'get_config_and_connect' is called, and a config entry
+ containing the host name (string) and port number (integer) to the
+ specified client (client_name) is available and is of the correct format,
+ an attempt to connect with the respective server shall be made.
+ """
+ client = SocketClient("test_socket")
+ data = {"socket": {"test_socket": {"host": host, "port": port}}}
+ client.connect = mock.MagicMock()
+
+ with mock.patch.object(config.var, 'data', data):
+ client.get_config_and_connect()
+ client.connect.assert_called_with(host, port)
+
+
+config_none = None
+config_empty = {}
+config_only_socket = {"socket": 1}
+config_only_host = {"socket": {"test_socket": {"host": 1}}}
+config_only_port = {"socket": {"test_socket": {"port": 2}}}
+config_wrong_host = {"socket": {"test_socket": {"host": 1, "port": 2}}}
+config_wrong_port = {"socket": {"test_socket": {"host": '1', "port": '2'}}}
+config_wrong_host_port = {"socket": {"test_socket": {"host": 1, "port": '2'}}}
+
+
[email protected]('config_data', [config_none, config_empty,
+ config_only_socket,
+ config_only_host, config_only_port,
+ config_wrong_host, config_wrong_port,
+ config_wrong_host_port])
+def test_get_config_and_connect_fail(config_data):
+ """WHEN the function 'get_config_and_connect' is called, IF the config
+ entry containing the host name and port number to the specified client
+ (client_name) is of the wrong format or does not exist, THEN no attempt
+ to connect with the respective server shall be made and the boolean value
+ False shall be returned.
+ """
+ client = SocketClient("test_socket")
+ client.connect = mock.MagicMock()
+
+ with mock.patch.object(config.var, 'data', config_data):
+ ok = client.get_config_and_connect()
+ client.connect.assert_not_called()
+ assert ok is False
+
+
+def test_connect():
+ """WHEN the function function 'connect' is called, and the host name
+ (string) and port number (integer) are given, an attempt to connect with
+ the respective server (socket) shall be made.
+ """
+ client = SocketClient("test_connect")
+
+ with mock.patch('socket.socket'):
+ client.connect(host, port)
+ client.sock.connect.assert_called_with((host, port))
+
+
+def test_connect_fail():
+ """WHEN the function function 'connect' is called, IF the server
+ belonging to the given host name (string) and port number (integer) is
+ not available, THEN the boolean value False shall be returned and the
+ instance attribute "sock" shall be set to None.
+ """
+ client = SocketClient("test_connect_fail")
+
+ with mock.patch('socket.socket') as mock_socket:
+ mock_sock = mock.Mock()
+ mock_socket.return_value = mock_sock
+ mock_sock.connect.side_effect = socket.error
+
+ ok = client.connect(host, port)
+ assert client.sock is None
+ assert ok is False
+
+
+def test_close():
+ """WHEN the function 'close' is called, the connection to the server
+ shall be closed in a timely fashion.
+ """
+ client = SocketClient("test_close")
+ mock_socket = mock.Mock()
+ client.sock = mock_socket
+
+ client.close()
+ mock_socket.close.assert_called()
+
+
+def test_send():
+ """The function 'send' shall transmit data to the socket in two steps:
+ 1. Send the length of the data to transmit in bytes followed by
+ the delimiter '\n', 2. Send the data; and shall return the boolean
+ value True if no error occurred during this operation.
+ """
+ client = SocketClient("test_send")
+ mock_socket = mock.Mock()
+ client.sock = mock_socket
+
+ data = 123
+ ok = client.send(data)
+ expected = [call.sendall(b'a%d\n' % len(str(data))),
+ call.sendall(str(data).encode())]
+ assert mock_socket.mock_calls == expected
+ assert ok is True
+
+
+def test_send_fail():
+ """WHEN the function 'send' is called, IF the server is not available,
+ THEN the boolean value False shall be returned and the instance variable
+ 'sock' shall be set to None if its value differ from None.
+ """
+ # Test 1: Socket error occurs; the variable 'sock' differs from None.
+ client = SocketClient("test_send_fail")
+ mock_socket = mock.Mock()
+ client.sock = mock_socket
+ mock_socket.sendall.side_effect = socket.error
+
+ ok = client.send(123)
+ assert client.sock is None
+ assert ok is False
+
+ # Test 2: Variable 'sock' equals already None.
+ client.sock = None
+ ok = client.send(123)
+ assert ok is False
+
+
+class SocketServer:
+
+ """A socket server to be able to connect with.
+
+ Attributes:
+ sock: The socket interface.
+ conn: Socket object usable to send and receive data on the connection.
+ addr: Address bound to the socket on the other end of the connection.
+ """
+
+ def __init__(self):
+ self.sock = None
+ self.conn = None
+ self.addr = None
+
+ def create(self):
+ """Creates a server."""
+ self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ self.sock.settimeout(5)
+ self.sock.bind((host, port))
+ self.sock.listen(1)
+ self.conn, self.addr = self.sock.accept()
+
+ def close(self):
+ """Closes the socket and the connection to the client."""
+ if self.conn is not None:
+ self.conn.close()
+
+ if self.sock is not None:
+ self.sock.close()
+
+
[email protected](scope="class")
+def server_client():
+ # Setup: create socket.
+ server = SocketServer()
+
+ thread = threading.Thread(target=server.create)
+ thread.start()
+
+ client = SocketClient("test_recv")
+ client.connect(host, port)
+
+ yield server, client
+
+ # Teardown: close socket and thread.
+ server.close()
+ thread.join()
+
+
+class TestRecv:
+
+ @pytest.mark.parametrize("msg, expected", [
+ (b"3\nabc", [True, "abc"]),
+ (b"abc3\nabc", [True, "abc"])
+ ])
+ def test_recv(self, server_client, msg, expected):
+ """WHEN the function 'recv' is called, and a message of the form
+ <length of data in bytes><delimiter = \n><data> is available,
+ only the received data and the boolean value True indicating that no
+ error occurred during this operation shall be returned.
+ """
+ server, client = server_client
+ server.conn.sendall(msg)
+ respond = client.recv()
+ assert respond == expected
+
+ def test_recv_no_connection(self, server_client):
+ """WHEN the function 'recv' is called, IF the server is not
+ available, THEN the boolean value False and an empty string shall be
+ returned."""
+ server, client = server_client
+ server.conn.close()
+ ok, data = client.recv()
+ assert ok is False
+ assert data == ""
+
+ def test_recv_sock_is_none(self, server_client):
+ """WHEN the function 'recv' is called, IF the instance variable
+ 'sock' equals None, THEN the boolean value False and an empty string
+ shall be returned."""
+ server, client = server_client
+ client.sock = None
+ ok, data = client.recv()
+ assert ok is False
+ assert data == ""
+
+ def test_recv_error(self, server_client):
+ """WHEN the function 'recv' is called, IF a socket error occurs,
+ THEN the boolean value False and an empty string shall be returned."""
+ server, client = server_client
+
+ # Socket error occurs during the first step of reading the length
+ # of the data to receive.
+ mock_socket = mock.Mock()
+ client.sock = mock_socket
+ mock_socket.recv.side_effect = socket.error
+ ok, data = client.recv()
+ assert ok is False
+ assert data == ""
+
+ # Socket error occurs during the second step of reading the data
+ # to receive.
+ mock_socket = mock.Mock()
+ client.sock = mock_socket
+ mock_socket.recv.side_effect = [b"1", b"0", b"\n"]
+ mock_socket.recv_into.side_effect = socket.error
+ ok, data = client.recv()
+ assert ok is False
+ assert data == ""
| Create class for socket communication
Provide a python class to be able to connect with a server via socket communication. The class should include the ability to
- establish a connection to a server,
- close the socket in a timely fashion,
- send and receive messages.
In addition, appropriate tests should be included. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/unit/test_socket.py::test_get_config_and_connect_fail[config_data6]",
"tests/unit/test_socket.py::test_send_fail",
"tests/unit/test_socket.py::test_connect_fail",
"tests/unit/test_socket.py::test_connect",
"tests/unit/test_socket.py::test_get_config_and_connect_fail[config_data4]",
"tests/unit/test_socket.py::test_get_config_and_connect_fail[config_data2]",
"tests/unit/test_socket.py::test_get_config_and_connect_fail[config_data1]",
"tests/unit/test_socket.py::test_get_config_and_connect_fail[config_data3]",
"tests/unit/test_socket.py::test_get_config_and_connect_fail[None]",
"tests/unit/test_socket.py::test_init",
"tests/unit/test_socket.py::test_get_config_and_connect_fail[config_data7]",
"tests/unit/test_socket.py::test_get_config_and_connect_fail[config_data5]",
"tests/unit/test_socket.py::test_close",
"tests/unit/test_socket.py::test_get_config_and_connect",
"tests/unit/test_socket.py::test_send",
"tests/unit/test_socket.py::TestRecv::test_recv_sock_is_none",
"tests/unit/test_socket.py::TestRecv::test_recv_error",
"tests/unit/test_socket.py::TestRecv::test_recv_no_connection"
] | [] | {
"failed_lite_validators": [
"has_added_files",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2018-11-21T21:35:48Z" | apache-2.0 |
|
EricssonResearch__arms-41 | diff --git a/arms/units/__init__.py b/arms/units/__init__.py
new file mode 100644
index 0000000..631db19
--- /dev/null
+++ b/arms/units/__init__.py
@@ -0,0 +1,1 @@
+"""Modules related to units"""
diff --git a/arms/units/abb.py b/arms/units/abb.py
new file mode 100644
index 0000000..5d39fa1
--- /dev/null
+++ b/arms/units/abb.py
@@ -0,0 +1,137 @@
+"""Utilities related to the communication with the ABB robotic arm."""
+
+import ast
+import json
+from arms.misc.socket import SocketClient
+from arms.utils import log
+
+
+class ABB:
+ """Handles the communication with the ABB robot with respect to
+ - sending command requests to and
+ - receiving/evaluating the responds from the ABB robot.
+
+ Attributes:
+ client: The socket interface.
+ """
+ def __init__(self):
+ self.client = SocketClient("abb")
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, exc_type, exc_val, exc_tb):
+ self.close()
+
+ def close(self):
+ """Close connection."""
+ case = 0
+ self._send(case)
+ self.client.close()
+
+ def get_system_information(self):
+ """Get system information."""
+ case = 1
+ ok, data = self._exchange(case)
+ return ok, data
+
+ def get_joint_coordinates(self):
+ """Get joint coordinates."""
+ case = 10
+ ok, data = self._exchange(case)
+ return ok, data
+
+ def _exchange(self, case, data=None):
+ """Exchanges messages with the ABB robot in two steps:
+ 1. step: Send a command to the ABB robot.
+ 2. step: Receive the answer from the ABB robot.
+
+ Moreover, the message to expect from the ABB robot is of JSON format
+ and is sent as a string; e.g.:
+ "{'id':1,'ok':1,'data':'[1, 2, 3]'}"
+ Hence, the 3. step is to convert this string into a dictionary.
+
+ Args:
+ case: The case to address in the RAPID code running on the IRC5
+ (ABB robot).
+ data: The data to send to the IRC5 (ABB robot), e.g. coordinates.
+ """
+
+ # 1. Send a command to the ABB robot.
+ ok = self._send(case, data)
+ if not ok:
+ return [False, []]
+
+ # 2. Receive the answer from the ABB robot.
+ [ok_client, recv_msg] = self.client.recv()
+ if not ok_client:
+ return [False, []]
+
+ # 3. Convert the received message into a dictionary.
+ recv_msg = recv_msg.replace("'", '\"')
+ recv_msg = recv_msg.replace("|", "'")
+ try:
+ recv_msg = json.loads(recv_msg)
+ recv_id = recv_msg['id']
+ recv_ok = bool(recv_msg['ok'])
+ recv_data = ast.literal_eval(recv_msg['data'])
+ except (OSError, ValueError, TypeError, KeyError) as e:
+ log.abb.error("The received message is of the wrong "
+ "format. The received message is {}; reason for "
+ "error: {}.".format(recv_msg, e))
+ return [False, []]
+
+ # Check if the stated case in the received message equals the
+ # given (expected) case.
+ if recv_id != case:
+ log.abb.critical("The case in the received message {} does not "
+ "equal the given (expected) case.")
+ return [False, []]
+ else:
+ return [recv_ok, recv_data]
+
+ def _send(self, case, data=None):
+ """Sends a command to the ABB robot in the expected format:
+ <length of data in bytes><delimiter = \n><data>
+ , where
+ <length of data in bytes><delimiter = \n>: Handled by the
+ class SocketClient.
+ <data>: array/list of 10 elements; first element is the case.
+
+ Args:
+ case: The case to address in the RAPID code running on the IRC5
+ (ABB robot).
+ data: The data to send to the IRC5 (ABB robot), e.g. coordinates.
+
+ Return:
+ - True, if the message could be send to the ABB robot successfully.
+ - False, if not.
+ """
+ if not isinstance(case, int):
+ log.abb.error('The case has to be provided as an integer. The '
+ 'given case was: '.format(case))
+ return False
+
+ if data is None:
+ data = []
+
+ if len(str(data)) > 80:
+ log.abb.error('The data list {} is bigger than 80 bytes and '
+ 'therefore can not be send to the ABB robot.'
+ .format(data))
+ return False
+
+ msg = [case]
+ msg = msg + data
+ if len(msg) <= 10:
+ msg = msg + (10-len(msg))*[0]
+ else:
+ log.abb.error('The data list {} has more than 9 elements and '
+ 'therefore can not be send to the ABB robot.'
+ .format(data))
+ return False
+
+ log.abb.info('An attempt to send a command request to the ABB robot '
+ 'is made. The message is {}.'.format(msg))
+ ok = self.client.send(msg)
+ return ok
diff --git a/arms/utils/log.py b/arms/utils/log.py
index 672e910..68f1f0b 100644
--- a/arms/utils/log.py
+++ b/arms/utils/log.py
@@ -70,6 +70,7 @@ def get_logger(name):
# The different loggers used (alphabetical order).
+abb = get_logger('abb')
app = get_logger('app')
ard_log = get_logger('ard_log')
camera = get_logger('camera')
| EricssonResearch/arms | 60d720fd6e3f70dc54f5159f645774664663d425 | diff --git a/tests/unit/test_abb.py b/tests/unit/test_abb.py
new file mode 100644
index 0000000..eed3285
--- /dev/null
+++ b/tests/unit/test_abb.py
@@ -0,0 +1,118 @@
+"""Tests for arms.units.abb"""
+
+import pytest
+from unittest import mock
+from arms.units.abb import ABB
+
+
+def test_init():
+ """The instance attribute 'client' of the class 'ABB' shall be an instance
+ of the class 'SocketClient' with the attribute value 'abb'.
+ """
+ with mock.patch('arms.units.abb.SocketClient') as mock_client:
+ ABB()
+ mock_client.assert_called_with("abb")
+
+
+def test_with():
+ """The class 'ABB' shall be able to work with Python with statements and
+ by leaving its scope the connection to the ABB robot shall be closed.
+ """
+ with mock.patch('arms.units.abb.ABB.close') as mock_close:
+ with ABB():
+ pass
+ mock_close.assert_called()
+
+
[email protected]("case, msg, expected", [
+ (1, "{'id':1,'ok':1,'data':'[]'}", [True, []]),
+ (1, "{'id':1,'ok':1,'data':'[1,2,3]'}", [True, [1, 2, 3]]),
+])
+def test_exchange(case, msg, expected):
+ """WHEN the function '_exchange' is called, a command request to the ABB
+ robot shall be send by calling the function 'send(case, data)', and the
+ received message (answer) from the ABB robot shall be converted into a
+ dictionary.
+
+ Comment:
+ This requires a working connection to the ABB robot and in addition a
+ received message from the ABB robot of the format:
+ "{'id':<id number>,
+ 'ok':<bool as number (1 = True, 0 = False)>,
+ 'data':<array of variable size>}"
+ """
+ abb = ABB()
+
+ mock_send = mock.Mock()
+ abb._send = mock_send
+ mock_send.return_value = True
+
+ mock_client = mock.Mock()
+ abb.client = mock_client
+ mock_client.recv.return_value = [True, msg]
+
+ received = abb._exchange(case)
+ abb._send.assert_called_with(case, None)
+ assert received == expected
+
+
[email protected]("ok_send, case, ok_recv, msg, expected", [
+ (False, 1, True, "", [False, []]),
+ (True, 1, False, "{'id':1,'ok':1,'data':'[1,2,3]'}", [False, []]),
+ (True, 1, True, "Not expected.", [False, []]),
+ (True, 2, True, "{'id':1,'ok':1,'data':'[1,2,3]'}", [False, []]),
+])
+def test_exchange_error(ok_send, case, ok_recv, msg, expected):
+ """WHEN the function '_exchange' is called, IF there is no working
+ connection to the ABB robot or the received message from the ABB robot is
+ not of the expected form, THEN the boolean value False and an empty
+ list shall be returned.
+
+ Comment:
+ The format of the message to expect from the ABB robot is explained in
+ the test 'test_exchange'.
+ """
+ abb = ABB()
+
+ mock_send = mock.Mock()
+ abb._send = mock_send
+ mock_send.return_value = ok_send
+
+ mock_client = mock.Mock()
+ abb.client = mock_client
+ mock_client.recv.return_value = [ok_recv, msg]
+
+ received = abb._exchange(case)
+ assert received == expected
+
+
[email protected]("case, data, expected", [
+ (0, None, [0] + 9*[0]),
+ (1, [1, 2, 3], [1] + [1, 2, 3] + 6*[0]),
+])
+def test_send(case, data, expected):
+ """WHEN the function '_send' is called, a command request to the ABB robot
+ of the expected form for the data entry shall be made.
+ """
+ abb = ABB()
+
+ mock_send = mock.Mock()
+ abb.client = mock_send
+
+ abb._send(case, data)
+ abb.client.send.assert_called_with(expected)
+
+
[email protected]("case, data", [
+ ("a", []),
+ (1, None),
+ (1, 81*"a"),
+ (1, 10*[0]),
+])
+def test_send_error(case, data):
+ """WHEN the function '_send' is called, IF there is no working connection to
+ the ABB robot, THEN the boolean value False shall be returned.
+ """
+ abb = ABB()
+ ok = abb._send(case, data)
+ assert ok is False
| Communication with the ABB robot (IRC5)
A class that handles the communication with the IRC5. Requirements:
- Creating/ closing the socket.
- Sending/ receiving of messages in a readable way.
- Implementing of some example cases.
In addition, tests shall show that the class works as intended. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/unit/test_abb.py::test_send_error[a-data0]",
"tests/unit/test_abb.py::test_send_error[1-data3]",
"tests/unit/test_abb.py::test_init",
"tests/unit/test_abb.py::test_send_error[1-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]",
"tests/unit/test_abb.py::test_exchange_error[False-1-True--expected0]",
"tests/unit/test_abb.py::test_with",
"tests/unit/test_abb.py::test_exchange_error[True-1-False-{'id':1,'ok':1,'data':'[1,2,3]'}-expected1]",
"tests/unit/test_abb.py::test_exchange[1-{'id':1,'ok':1,'data':'[]'}-expected0]",
"tests/unit/test_abb.py::test_send[0-None-expected0]",
"tests/unit/test_abb.py::test_exchange[1-{'id':1,'ok':1,'data':'[1,2,3]'}-expected1]",
"tests/unit/test_abb.py::test_send[1-data1-expected1]",
"tests/unit/test_abb.py::test_exchange_error[True-2-True-{'id':1,'ok':1,'data':'[1,2,3]'}-expected3]",
"tests/unit/test_abb.py::test_exchange_error[True-1-True-Not",
"tests/unit/test_abb.py::test_send_error[1-None]"
] | [] | {
"failed_lite_validators": [
"has_added_files"
],
"has_test_patch": true,
"is_lite": false
} | "2018-11-22T14:17:44Z" | apache-2.0 |
|
EricssonResearch__arms-60 | diff --git a/arms/misc/socket.py b/arms/misc/socket.py
index 0ca3fd3..a04eb19 100644
--- a/arms/misc/socket.py
+++ b/arms/misc/socket.py
@@ -25,9 +25,10 @@ class SocketClient:
server.
Return:
- - True, if a setting entry belonging to the client (client_name)
- could be found and no data type violation occurred.
- - False, if not.
+ - [#1, #2]
+ #1: True, if a setting entry belonging to the client (client_name)
+ could be found and no data type violation occurred. False, if not.
+ #2: True, if a connection could be made. False, if not.
"""
try:
c = config.var.data['socket'][self.name]
@@ -38,11 +39,11 @@ class SocketClient:
'socket {} in the configuration file ('
'arms/config/config.json). Hence, no '
'connection could be made.'.format(self.name))
- return False
+ return [False, False]
if isinstance(host, str) and isinstance(port, int):
ok = self.connect(host, port)
- return ok
+ return [True, ok]
else:
log.socket.error('Data type violation. The host number has to be '
'provided as a string and the port number as an '
@@ -50,7 +51,7 @@ class SocketClient:
'arms/config/config.json). In consequence, the '
'socket {} could not connect to the server.'
.format(self.name))
- return False
+ return [False, False]
def connect(self, host, port):
"""Establishes a connection to a server.
diff --git a/arms/units/abb.py b/arms/units/abb.py
index 5d39fa1..76c3cb0 100644
--- a/arms/units/abb.py
+++ b/arms/units/abb.py
@@ -23,6 +23,11 @@ class ABB:
def __exit__(self, exc_type, exc_val, exc_tb):
self.close()
+ def connect(self):
+ """Connects to the socket server."""
+ ok, connected = self.client.get_config_and_connect()
+ return ok, connected
+
def close(self):
"""Close connection."""
case = 0
| EricssonResearch/arms | f5dd81f13d6035a9a3729862cae1b0b37a5ac44e | diff --git a/tests/unit/test_socket.py b/tests/unit/test_socket.py
index a1a9b3c..a56d6e7 100644
--- a/tests/unit/test_socket.py
+++ b/tests/unit/test_socket.py
@@ -39,11 +39,12 @@ def test_get_config_and_connect():
"""
client = SocketClient("test_socket")
data = {"socket": {"test_socket": {"host": host, "port": port}}}
- client.connect = mock.MagicMock()
+ mock_connect = mock.MagicMock()
+ client.connect = mock_connect
with mock.patch.object(config.var, 'data', data):
client.get_config_and_connect()
- client.connect.assert_called_with(host, port)
+ mock_connect.assert_called_with(host, port)
config_none = None
@@ -65,16 +66,17 @@ def test_get_config_and_connect_fail(config_data):
"""WHEN the function 'get_config_and_connect' is called, IF the config
entry containing the host name and port number to the specified client
(client_name) is of the wrong format or does not exist, THEN no attempt
- to connect with the respective server shall be made and the boolean value
- False shall be returned.
+ to connect with the respective server shall be made and the boolean values
+ [False, False] shall be returned.
"""
client = SocketClient("test_socket")
- client.connect = mock.MagicMock()
+ mock_connect = mock.MagicMock()
+ client.connect = mock_connect
with mock.patch.object(config.var, 'data', config_data):
ok = client.get_config_and_connect()
- client.connect.assert_not_called()
- assert ok is False
+ mock_connect.assert_not_called()
+ assert ok == [False, False]
def test_connect():
@@ -185,7 +187,7 @@ class SocketServer:
"""Closes the socket and the connection to the client."""
if self.conn is not None:
self.conn.close()
-
+
if self.sock is not None:
self.sock.close()
| Refactor of SocketClient.get_config_and_connect
By now the method SocketClient.get_config_and_connect only returns one value, which equals True if the settings to the client could be found and False if not.
It seems necessary that this function returns two values [*1, *2], because usually this function is only called to connect with the respective server and overall a better feedback is needed:
- *1: True, if a setting entry belonging to the client (client_name) could be found and no data type violation occurred. False, if not.
- *2: True, if a connection could be made. False, if not. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/unit/test_socket.py::test_get_config_and_connect_fail[config_data5]",
"tests/unit/test_socket.py::test_get_config_and_connect_fail[config_data1]",
"tests/unit/test_socket.py::test_get_config_and_connect_fail[config_data6]",
"tests/unit/test_socket.py::test_get_config_and_connect_fail[config_data7]",
"tests/unit/test_socket.py::test_get_config_and_connect_fail[None]",
"tests/unit/test_socket.py::test_get_config_and_connect_fail[config_data2]",
"tests/unit/test_socket.py::test_get_config_and_connect_fail[config_data4]",
"tests/unit/test_socket.py::test_get_config_and_connect_fail[config_data3]"
] | [
"tests/unit/test_socket.py::test_send",
"tests/unit/test_socket.py::test_connect_fail",
"tests/unit/test_socket.py::test_send_fail",
"tests/unit/test_socket.py::test_init",
"tests/unit/test_socket.py::test_get_config_and_connect",
"tests/unit/test_socket.py::test_connect",
"tests/unit/test_socket.py::test_close",
"tests/unit/test_socket.py::TestRecv::test_recv_sock_is_none",
"tests/unit/test_socket.py::TestRecv::test_recv_error"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2018-12-04T10:45:09Z" | apache-2.0 |
|
EricssonResearch__arms-63 | diff --git a/arms/misc/socket.py b/arms/misc/socket.py
index 0ca3fd3..a04eb19 100644
--- a/arms/misc/socket.py
+++ b/arms/misc/socket.py
@@ -25,9 +25,10 @@ class SocketClient:
server.
Return:
- - True, if a setting entry belonging to the client (client_name)
- could be found and no data type violation occurred.
- - False, if not.
+ - [#1, #2]
+ #1: True, if a setting entry belonging to the client (client_name)
+ could be found and no data type violation occurred. False, if not.
+ #2: True, if a connection could be made. False, if not.
"""
try:
c = config.var.data['socket'][self.name]
@@ -38,11 +39,11 @@ class SocketClient:
'socket {} in the configuration file ('
'arms/config/config.json). Hence, no '
'connection could be made.'.format(self.name))
- return False
+ return [False, False]
if isinstance(host, str) and isinstance(port, int):
ok = self.connect(host, port)
- return ok
+ return [True, ok]
else:
log.socket.error('Data type violation. The host number has to be '
'provided as a string and the port number as an '
@@ -50,7 +51,7 @@ class SocketClient:
'arms/config/config.json). In consequence, the '
'socket {} could not connect to the server.'
.format(self.name))
- return False
+ return [False, False]
def connect(self, host, port):
"""Establishes a connection to a server.
diff --git a/arms/units/abb.py b/arms/units/abb.py
index 5d39fa1..76c3cb0 100644
--- a/arms/units/abb.py
+++ b/arms/units/abb.py
@@ -23,6 +23,11 @@ class ABB:
def __exit__(self, exc_type, exc_val, exc_tb):
self.close()
+ def connect(self):
+ """Connects to the socket server."""
+ ok, connected = self.client.get_config_and_connect()
+ return ok, connected
+
def close(self):
"""Close connection."""
case = 0
diff --git a/arms/units/alarms.py b/arms/units/alarms.py
new file mode 100644
index 0000000..8d3ff68
--- /dev/null
+++ b/arms/units/alarms.py
@@ -0,0 +1,46 @@
+"""Utilities related to receiving and evaluating of DU failure reports."""
+
+import requests
+import time
+from arms.config import config
+from arms.utils import log
+
+
+class Alarms:
+
+ """Receiving and evaluating of DU failure reports."""
+
+ def listen(self):
+ """Connects with the web server 'alarms' specified in the settings
+ (arms/config/config.json -> web -> alarms) and waits for an error
+ message.
+
+ Return:
+ - True, if a hardware link failure was reported.
+ - False, if an internal error occurred.
+ """
+
+ try:
+ host = config.var.data['web']['alarms']['host']
+ port = config.var.data['web']['alarms']['port']
+ url = config.var.data['web']['alarms']['url']
+ webpage = host + ":" + str(port) + url
+ response = requests.get(webpage).text
+ except (TypeError, KeyError):
+ log.alarms.critical("Could not find (appropriate) settings in the "
+ "configuration file (arms/config/config.json) "
+ "to reach the website responsible for sending "
+ "failure reports. Hence, this service will be "
+ "closed.")
+ return False
+ except requests.exceptions.RequestException:
+ time.sleep(60)
+ return self.listen()
+
+ if response == "A":
+ log.alarms.info("The error code ({}) was received. The healing "
+ "process will be started.".format(response))
+ return True
+ else:
+ time.sleep(60)
+ return self.listen()
diff --git a/arms/utils/log.py b/arms/utils/log.py
index 5c1a8b6..72a7217 100644
--- a/arms/utils/log.py
+++ b/arms/utils/log.py
@@ -71,6 +71,7 @@ def get_logger(name):
# The different loggers used (alphabetical order).
abb = get_logger('abb')
+alarms = get_logger('alarms')
app = get_logger('app')
ard_log = get_logger('ard_log')
camera = get_logger('camera')
diff --git a/other/alarms/alarmSample.txt b/other/alarms/alarmSample.txt
new file mode 100644
index 0000000..f45e1a4
--- /dev/null
+++ b/other/alarms/alarmSample.txt
@@ -0,0 +1,7 @@
+===================================================================================================================================================================================================================
+Date & Time (Local) S Specific Problem MO (Cause/AdditionalInfo)
+===================================================================================================================================================================================================================
+2018-11-22 15:52:19 M Gigabit Ethernet Link Fault Subrack=1,Slot=1,PlugInUnit=1,ExchangeTerminalIp=1,GigaBitEthernet=1 (Autonegotiation Failed to Meet Minimum Requirements.)
+2018-11-22 16:03:19 M Network Synch Time from GPS Missing Subrack=1,Slot=1,PlugInUnit=1,TimingUnit=1,GpsSyncRef=1 (Cause: Loss of signal)
+2018-11-23 10:23:52 m Link Failure RiLink=1 (No signal detected (link start time-out) ManagedElement=1,Equipment=1,Subrack=1,Slot=1,PlugInUnit=1,RiPort=A (transportType=NOT_SET)
+
diff --git a/other/alarms/alservice_rest.py b/other/alarms/alservice_rest.py
new file mode 100644
index 0000000..e501c44
--- /dev/null
+++ b/other/alarms/alservice_rest.py
@@ -0,0 +1,21 @@
+from flask import Flask
+import os
+import sys
+
+app = Flask(__name__)
+
[email protected]('/alarms')
+def alarms():
+
+ with open(os.getcwd() + '/alarmSample.txt', 'r') as f:
+ lines = f.readlines()
+ f.close()
+ for line in lines:
+ if "Link Failure" in line:
+ return line[line.find("RiPort") + 7:line.find("RiPort") + 8]
+
+ return "no alarm"
+
+
+if __name__ == '__main__':
+ app.run(host='0.0.0.0', port=8000)
diff --git a/requirements.txt b/requirements.txt
index a6b2e32..cd20793 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -1,2 +1,3 @@
# List of files to be installed using pip install.
+requests
pytest
\ No newline at end of file
| EricssonResearch/arms | f5dd81f13d6035a9a3729862cae1b0b37a5ac44e | diff --git a/tests/unit/test_alarms.py b/tests/unit/test_alarms.py
new file mode 100644
index 0000000..094319a
--- /dev/null
+++ b/tests/unit/test_alarms.py
@@ -0,0 +1,90 @@
+"""Tests for arms.units.alarms.Alarms.listen"""
+
+import pytest
+import requests
+from unittest import mock
+from arms.config import config
+from arms.units import alarms
+
+
+class DotDict(dict):
+ """Access the keys of a dictionary via a dot notation.
+
+ Example:
+ val = Map({'text': "No error"})
+ val.text -> "No error"
+ """
+ __getattr__ = dict.get
+ __setattr__ = dict.__setitem__
+ __delattr__ = dict.__delitem__
+
+
[email protected](alarms.requests, 'get', return_value=DotDict({'text': "A"}))
+def test_listen_alarm(mock_requests):
+ """WHILE the webpage information for 'alarms' could be found in the
+ settings (see details below), WHILE the requested server is online,
+ the method 'listen' shall fetch the information from the server and return
+ the boolean value True if the received error message equals the letter 'A'.
+
+ Note that the following config entry is needed:
+ arms.config.config.json -> web -> alarms -> host, port, url
+ """
+ alarm = alarms.Alarms()
+ config_data = {"web": {"alarms": {"host": "a", "port": "b", "url": "c"}}}
+ with mock.patch.object(config.var, 'data', config_data):
+ assert alarm.listen() is True
+ mock_requests.assert_called()
+
+
[email protected]("config_data", [
+ None,
+ {},
+ ({"color": "blue"}),
+ ({"web": {"color": "blue"}}),
+ ({"web": {"alarms": {"color": "blue"}}}),
+ ({"web": {"alarms": {"host": "a", "color": "b", "url": "c"}}}),
+])
+def test_listen_dict_error(config_data):
+ """IF no webpage information for 'alarms' could be found or if they are
+ incomplete, THEN the boolean value False shall be returned.
+ """
+ alarm = alarms.Alarms()
+ with mock.patch.object(config.var, 'data', config_data):
+ assert alarm.listen() is False
+
+
[email protected](alarms.requests, 'get', return_value=None,
+ side_effect=requests.exceptions.RequestException)
[email protected]('time.sleep', return_value=None)
+def test_listen_request_error(mock_time, mock_requests):
+ """IF the requested server is offline, WHILE the webpage information for
+ 'alarms' are available, the system shall sleep for awhile and try to
+ fetch the information from the server again.
+ """
+ alarm = alarms.Alarms()
+ listen = alarm.listen
+ config_data = {"web": {"alarms": {"host": "a", "port": "b", "url": "c"}}}
+ with mock.patch.object(config.var, 'data', config_data):
+ with mock.patch.object(alarms.Alarms, 'listen', return_value="loop"):
+ assert listen() == "loop"
+ mock_requests.assert_called()
+ mock_time.assert_called()
+
+
[email protected](alarms.requests, 'get',
+ return_value=DotDict({'text': "No error"}))
[email protected]('time.sleep', return_value=None)
+def test_listen_no_alarm(mock_time, mock_requests):
+ """WHILE the webpage information for 'alarms' could be found in the
+ settings, WHILE the requested server is online, the method 'listen' shall
+ sleep awhile and make a request again if the fetched information does not
+ equal the letter 'A'.
+ """
+ alarm = alarms.Alarms()
+ listen = alarm.listen
+ config_data = {"web": {"alarms": {"host": "a", "port": "b", "url": "c"}}}
+ with mock.patch.object(config.var, 'data', config_data):
+ with mock.patch.object(alarms.Alarms, 'listen', return_value="loop"):
+ assert listen() == "loop"
+ mock_requests.assert_called()
+ mock_time.assert_called()
diff --git a/tests/unit/test_socket.py b/tests/unit/test_socket.py
index a1a9b3c..a56d6e7 100644
--- a/tests/unit/test_socket.py
+++ b/tests/unit/test_socket.py
@@ -39,11 +39,12 @@ def test_get_config_and_connect():
"""
client = SocketClient("test_socket")
data = {"socket": {"test_socket": {"host": host, "port": port}}}
- client.connect = mock.MagicMock()
+ mock_connect = mock.MagicMock()
+ client.connect = mock_connect
with mock.patch.object(config.var, 'data', data):
client.get_config_and_connect()
- client.connect.assert_called_with(host, port)
+ mock_connect.assert_called_with(host, port)
config_none = None
@@ -65,16 +66,17 @@ def test_get_config_and_connect_fail(config_data):
"""WHEN the function 'get_config_and_connect' is called, IF the config
entry containing the host name and port number to the specified client
(client_name) is of the wrong format or does not exist, THEN no attempt
- to connect with the respective server shall be made and the boolean value
- False shall be returned.
+ to connect with the respective server shall be made and the boolean values
+ [False, False] shall be returned.
"""
client = SocketClient("test_socket")
- client.connect = mock.MagicMock()
+ mock_connect = mock.MagicMock()
+ client.connect = mock_connect
with mock.patch.object(config.var, 'data', config_data):
ok = client.get_config_and_connect()
- client.connect.assert_not_called()
- assert ok is False
+ mock_connect.assert_not_called()
+ assert ok == [False, False]
def test_connect():
@@ -185,7 +187,7 @@ class SocketServer:
"""Closes the socket and the connection to the client."""
if self.conn is not None:
self.conn.close()
-
+
if self.sock is not None:
self.sock.close()
| Fetching and evaluating of DU failure reports
In total two things have to be implemented to fulfill this issue:
- A small script that starts a server and provides the DU link failure. For simplification, the DU failure simply equals the letter _A_. For more details see the example failure report we got from Ericsson.
- A python class that fetches the information from the server and returns the boolean value True if the error message _A_ was received. If an internal error occurred, the boolean value False shall be returned.
In addition, tests should show that the python class works as intended. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/unit/test_socket.py::TestRecv::test_recv_sock_is_none",
"tests/unit/test_socket.py::TestRecv::test_recv_error",
"tests/unit/test_socket.py::TestRecv::test_recv_no_connection",
"tests/unit/test_socket.py::test_get_config_and_connect_fail[config_data6]",
"tests/unit/test_socket.py::test_get_config_and_connect_fail[config_data1]",
"tests/unit/test_socket.py::test_get_config_and_connect_fail[config_data4]",
"tests/unit/test_socket.py::test_send_fail",
"tests/unit/test_socket.py::test_get_config_and_connect_fail[None]",
"tests/unit/test_socket.py::test_connect_fail",
"tests/unit/test_socket.py::test_send",
"tests/unit/test_socket.py::test_get_config_and_connect_fail[config_data7]",
"tests/unit/test_socket.py::test_get_config_and_connect",
"tests/unit/test_socket.py::test_get_config_and_connect_fail[config_data5]",
"tests/unit/test_socket.py::test_close",
"tests/unit/test_socket.py::test_get_config_and_connect_fail[config_data3]",
"tests/unit/test_socket.py::test_init",
"tests/unit/test_socket.py::test_connect",
"tests/unit/test_socket.py::test_get_config_and_connect_fail[config_data2]",
"tests/unit/test_alarms.py::test_listen_dict_error[config_data5]",
"tests/unit/test_alarms.py::test_listen_dict_error[config_data1]",
"tests/unit/test_alarms.py::test_listen_alarm",
"tests/unit/test_alarms.py::test_listen_no_alarm",
"tests/unit/test_alarms.py::test_listen_dict_error[None]",
"tests/unit/test_alarms.py::test_listen_dict_error[config_data3]",
"tests/unit/test_alarms.py::test_listen_dict_error[config_data4]",
"tests/unit/test_alarms.py::test_listen_request_error",
"tests/unit/test_alarms.py::test_listen_dict_error[config_data2]"
] | [] | {
"failed_lite_validators": [
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2018-12-04T12:06:07Z" | apache-2.0 |
|
Erotemic__ubelt-64 | diff --git a/ubelt/util_path.py b/ubelt/util_path.py
index c028ba2..5241209 100644
--- a/ubelt/util_path.py
+++ b/ubelt/util_path.py
@@ -291,9 +291,9 @@ def ensuredir(dpath, mode=0o1777, verbose=None, recreate=False):
>>> assert exists(dpath)
>>> os.rmdir(dpath)
"""
- if verbose is None: # nocover
+ if verbose is None:
verbose = 0
- if isinstance(dpath, (list, tuple)): # nocover
+ if isinstance(dpath, (list, tuple)):
dpath = join(*dpath)
if recreate:
@@ -301,15 +301,15 @@ def ensuredir(dpath, mode=0o1777, verbose=None, recreate=False):
ub.delete(dpath, verbose=verbose)
if not exists(dpath):
- if verbose: # nocover
- print('Ensuring new directory (%r)' % dpath)
+ if verbose:
+ print('Ensuring directory (creating {!r})'.format(dpath))
if sys.version_info.major == 2: # nocover
os.makedirs(normpath(dpath), mode=mode)
else:
os.makedirs(normpath(dpath), mode=mode, exist_ok=True)
else:
- if verbose: # nocover
- print('Ensuring existing directory (%r)' % dpath)
+ if verbose:
+ print('Ensuring directory (existing {!r})'.format(dpath))
return dpath
| Erotemic/ubelt | 89085f148ace79aa0dfdc17383423e3dfe138017 | diff --git a/tests/test_path.py b/tests/test_path.py
index 49ea0c8..fafadd2 100644
--- a/tests/test_path.py
+++ b/tests/test_path.py
@@ -55,8 +55,31 @@ def test_augpath_dpath():
def test_ensuredir_recreate():
- ub.ensuredir('foo', recreate=True)
- ub.ensuredir('foo/bar')
- assert exists('foo/bar')
- ub.ensuredir('foo', recreate=True)
- assert not exists('foo/bar')
+ base = ub.ensure_app_cache_dir('ubelt/tests')
+ folder = join(base, 'foo')
+ member = join(folder, 'bar')
+ ub.ensuredir(folder, recreate=True)
+ ub.ensuredir(member)
+ assert exists(member)
+ ub.ensuredir(folder, recreate=True)
+ assert not exists(member)
+
+
+def test_ensuredir_verbosity():
+ base = ub.ensure_app_cache_dir('ubelt/tests')
+
+ with ub.CaptureStdout() as cap:
+ ub.ensuredir(join(base, 'foo'), verbose=0)
+ assert cap.text == ''
+ # None defaults to verbose=0
+ with ub.CaptureStdout() as cap:
+ ub.ensuredir((base, 'foo'), verbose=None)
+ assert cap.text == ''
+
+ ub.delete(join(base, 'foo'))
+ with ub.CaptureStdout() as cap:
+ ub.ensuredir(join(base, 'foo'), verbose=1)
+ assert 'creating' in cap.text
+ with ub.CaptureStdout() as cap:
+ ub.ensuredir(join(base, 'foo'), verbose=1)
+ assert 'existing' in cap.text
| Request: ensure director verbose mentions if it created a new directory
It would be nice if the verbose mode actually said something like
Ensuring directory ('...') status: existing
Ensuring directory ('...') status: creating
Maybe have a second verbose level if you want to maintain the original way. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_path.py::test_ensuredir_verbosity"
] | [
"tests/test_path.py::test_augpath_identity",
"tests/test_path.py::test_ensuredir_recreate",
"tests/test_path.py::test_tempdir",
"tests/test_path.py::test_augpath_dpath"
] | {
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
} | "2019-10-27T22:57:44Z" | apache-2.0 |
|
European-XFEL__EXtra-data-128 | diff --git a/extra_data/reader.py b/extra_data/reader.py
index 263c848..c388030 100644
--- a/extra_data/reader.py
+++ b/extra_data/reader.py
@@ -570,16 +570,54 @@ class DataCollection:
res = defaultdict(set)
if isinstance(selection, dict):
# {source: {key1, key2}}
- # {source: {}} -> all keys for this source
- for source, keys in selection.items(): #
+ # {source: {}} or {source: None} -> all keys for this source
+ for source, in_keys in selection.items():
if source not in self.all_sources:
raise SourceNameError(source)
- if keys:
- res[source].update(keys)
+ # Keys of the current DataCollection.
+ cur_keys = self.selection[source]
+
+ # Keys input as the new selection.
+ if in_keys:
+ # If a specific set of keys is selected, make sure
+ # they are all valid.
+ for key in in_keys:
+ if not self._has_source_key(source, key):
+ raise PropertyNameError(key, source)
else:
+ # Catches both an empty set and None.
+ # While the public API describes an empty set to
+ # refer to all keys, the internal API actually uses
+ # None for this case. This method is supposed to
+ # accept both cases in order to natively support
+ # passing a DataCollection as the selector. To keep
+ # the conditions below clearer, any non-True value
+ # is converted to None.
+ in_keys = None
+
+ if cur_keys is None and in_keys is None:
+ # Both the new and current keys select all.
res[source] = None
+ elif cur_keys is not None and in_keys is not None:
+ # Both the new and current keys are specific, take
+ # the intersection of both. This should never be
+ # able to result in an empty set, but to prevent the
+ # code further below from breaking, assert it.
+ res[source] = cur_keys & in_keys
+ assert res[source]
+
+ elif cur_keys is None and in_keys is not None:
+ # Current keys are unspecific but new ones are, just
+ # use the new keys.
+ res[source] = in_keys
+
+ elif cur_keys is not None and in_keys is None:
+ # The current keys are specific but new ones are
+ # not, use the current keys.
+ res[source] = cur_keys
+
elif isinstance(selection, Iterable):
# selection = [('src_glob', 'key_glob'), ...]
res = union_selections(
@@ -612,7 +650,14 @@ class DataCollection:
continue
if key_glob == '*':
- matched[source] = None
+ # When the selection refers to all keys, make sure this
+ # is restricted to the current selection of keys for
+ # this source.
+
+ if self.selection[source] is None:
+ matched[source] = None
+ else:
+ matched[source] = self.selection[source]
else:
r = ctrl_key_re if source in self.control_sources else key_re
keys = set(filter(r.match, self.keys_for_source(source)))
| European-XFEL/EXtra-data | 76c30bf18529ed0c3eb9de9c3d1c15494f807ac5 | diff --git a/extra_data/tests/test_reader_mockdata.py b/extra_data/tests/test_reader_mockdata.py
index aa84f1b..8668764 100644
--- a/extra_data/tests/test_reader_mockdata.py
+++ b/extra_data/tests/test_reader_mockdata.py
@@ -476,17 +476,46 @@ def test_select(mock_fxe_raw_run):
assert 'SPB_XTD9_XGM/DOOCS/MAIN' in run.control_sources
+ # Basic selection machinery, glob API
sel = run.select('*/DET/*', 'image.pulseId')
assert 'SPB_XTD9_XGM/DOOCS/MAIN' not in sel.control_sources
assert 'FXE_DET_LPD1M-1/DET/0CH0:xtdf' in sel.instrument_sources
_, data = sel.train_from_id(10000)
for source, source_data in data.items():
- print(source)
assert set(source_data.keys()) == {'image.pulseId', 'metadata'}
- sel2 = run.select(sel)
- assert 'SPB_XTD9_XGM/DOOCS/MAIN' not in sel2.control_sources
- assert 'FXE_DET_LPD1M-1/DET/0CH0:xtdf' in sel2.instrument_sources
+ # Basic selection machinery, dict-based API
+ sel_by_dict = run.select({
+ 'SA1_XTD2_XGM/DOOCS/MAIN': None,
+ 'FXE_DET_LPD1M-1/DET/0CH0:xtdf': {'image.pulseId'}
+ })
+ assert sel_by_dict.control_sources == {'SA1_XTD2_XGM/DOOCS/MAIN'}
+ assert sel_by_dict.instrument_sources == {'FXE_DET_LPD1M-1/DET/0CH0:xtdf'}
+ assert sel_by_dict.keys_for_source('FXE_DET_LPD1M-1/DET/0CH0:xtdf') == \
+ sel.keys_for_source('FXE_DET_LPD1M-1/DET/0CH0:xtdf')
+
+ # Re-select using * selection, should yield the same keys.
+ assert sel.keys_for_source('FXE_DET_LPD1M-1/DET/0CH0:xtdf') == \
+ sel.select('FXE_DET_LPD1M-1/DET/0CH0:xtdf', '*') \
+ .keys_for_source('FXE_DET_LPD1M-1/DET/0CH0:xtdf')
+ assert sel.keys_for_source('FXE_DET_LPD1M-1/DET/0CH0:xtdf') == \
+ sel.select({'FXE_DET_LPD1M-1/DET/0CH0:xtdf': {}}) \
+ .keys_for_source('FXE_DET_LPD1M-1/DET/0CH0:xtdf')
+
+ # Re-select a different but originally valid key, should fail.
+ with pytest.raises(ValueError):
+ # ValueError due to globbing.
+ sel.select('FXE_DET_LPD1M-1/DET/0CH0:xtdf', 'image.trainId')
+
+ with pytest.raises(PropertyNameError):
+ # PropertyNameError via explicit key.
+ sel.select({'FXE_DET_LPD1M-1/DET/0CH0:xtdf': {'image.trainId'}})
+
+ # Select by another DataCollection.
+ sel_by_dc = run.select(sel)
+ assert sel_by_dc.control_sources == sel.control_sources
+ assert sel_by_dc.instrument_sources == sel.instrument_sources
+ assert sel_by_dc.train_ids == sel.train_ids
@pytest.mark.parametrize('select_str',
| Selected keys can be overridden
`.select()` is meant to always make a narrower selection from the current one, but @daviddoji found a case where it can get broader again:
```python
source = 'FXE_DET_LPD1M-1/DET/2CH0:xtdf'
sel = run.select(source, "image.data")
print(sel.keys_for_source(source))
sel = sel.select(source, '*')
print(sel.keys_for_source(source))
``` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"extra_data/tests/test_reader_mockdata.py::test_select[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_select[0.5]"
] | [
"extra_data/tests/test_reader_mockdata.py::test_train_by_id_fxe_run_selection[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_file_get_series_control[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_read_skip_invalid[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_iterate_trains_fxe[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_array_roi[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_file_get_array[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_file_get_array_missing_trains[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_file_get_series_instrument[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_properties_fxe_raw_run[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_file_get_array_control_roi[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_array_empty[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_iterate_fxe_run[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_array[1.0-defaultName]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_dataframe[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_get_data_counts[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_select_require_all[1.0-*]",
"extra_data/tests/test_reader_mockdata.py::test_open_file[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_train_from_index_fxe_run[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_iterate_trains[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_open_run[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_iterate_trains_flat_keys[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_select_require_all[1.0-*/BEAMVIEW2*]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_series_control[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_select_require_all[1.0-*/BEAMVIEW2:daqOutput]",
"extra_data/tests/test_reader_mockdata.py::test_iterate_run_glob_devices[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_select_trains[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_train_info[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_array_error[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_iterate_trains_select_keys[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_detector_info_oldfmt[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_array[1.0-explicitName]",
"extra_data/tests/test_reader_mockdata.py::test_iterate_spb_raw_run[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_array_select_trains[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_iterate_file_select_trains[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_iterate_select_trains[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_array_multiple_per_train[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_virtual_dataset[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_get_train_bad_device_name[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_read_fxe_raw_run_selective[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_union_raw_proc[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_deselect[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_iterate_trains_require_all[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_union[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_virtual_dataset_filename[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_run_immutable_sources[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_train_by_id_fxe_run[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_detector_info[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_series_select_trains[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_train_by_id_fxe_run_selection[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_read_fxe_raw_run_selective[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_series_select_trains[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_array[0.5-defaultName]",
"extra_data/tests/test_reader_mockdata.py::test_select_trains[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_dataframe[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_array_multiple_per_train[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_iterate_file_select_trains[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_array_error[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_run_immutable_sources[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_train_info[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_select_require_all[0.5-*]",
"extra_data/tests/test_reader_mockdata.py::test_iterate_trains_fxe[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_open_file[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_detector_info_oldfmt[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_array_empty[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_iterate_fxe_run[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_detector_info[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_iterate_trains_select_keys[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_train_by_id_fxe_run[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_array_select_trains[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_iterate_select_trains[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_file_get_array_control_roi[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_union_raw_proc[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_array[0.5-explicitName]",
"extra_data/tests/test_reader_mockdata.py::test_iterate_trains_require_all[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_select_require_all[0.5-*/BEAMVIEW2*]",
"extra_data/tests/test_reader_mockdata.py::test_union[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_iterate_spb_raw_run[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_train_from_index_fxe_run[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_iterate_trains_flat_keys[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_array_roi[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_series_control[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_get_data_counts[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_select_require_all[0.5-*/BEAMVIEW2:daqOutput]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_virtual_dataset[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_virtual_dataset_filename[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_properties_fxe_raw_run[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_file_get_series_instrument[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_file_get_series_control[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_iterate_trains[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_open_run[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_file_get_array[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_read_skip_invalid[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_deselect[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_file_get_array_missing_trains[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_iterate_run_glob_devices[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_get_train_bad_device_name[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_empty_file_info"
] | {
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
} | "2021-01-15T18:12:55Z" | bsd-3-clause |
|
European-XFEL__EXtra-data-165 | diff --git a/docs/reading_files.rst b/docs/reading_files.rst
index faabbfa..f8b6b4a 100644
--- a/docs/reading_files.rst
+++ b/docs/reading_files.rst
@@ -67,6 +67,8 @@ to refer to all data associated with that 0.1 second window.
.. automethod:: get_data_counts
+ .. automethod:: train_timestamps
+
.. automethod:: info
.. _data-by-source-and-key:
diff --git a/extra_data/reader.py b/extra_data/reader.py
index 916382f..e6d885b 100644
--- a/extra_data/reader.py
+++ b/extra_data/reader.py
@@ -1084,6 +1084,46 @@ class DataCollection:
print('\tControls')
[print('\t-', d) for d in sorted(ctrl)] or print('\t-')
+ def train_timestamps(self, labelled=False):
+ """Get approximate timestamps for each train
+
+ Timestamps are stored and returned in UTC (not local time).
+ Older files (before format version 1.0) do not have timestamp data,
+ and the returned data in those cases will have the special value NaT
+ (Not a Time).
+
+ If *labelled* is True, they are returned in a pandas series, labelled
+ with train IDs. If False (default), they are returned in a NumPy array
+ of the same length as data.train_ids.
+ """
+ arr = np.zeros(len(self.train_ids), dtype=np.uint64)
+ id_to_ix = {tid: i for (i, tid) in enumerate(self.train_ids)}
+ missing_tids = np.array(self.train_ids)
+ for fa in self.files:
+ tids, file_ixs, _ = np.intersect1d(
+ fa.train_ids, missing_tids, return_indices=True
+ )
+ if not self.inc_suspect_trains:
+ valid = fa.validity_flag[file_ixs]
+ tids, file_ixs = tids[valid], file_ixs[valid]
+ if tids.size == 0 or 'INDEX/timestamp' not in fa.file:
+ continue
+ file_tss = fa.file['INDEX/timestamp'][:]
+ for tid, ts in zip(tids, file_tss[file_ixs]):
+ arr[id_to_ix[tid]] = ts
+
+ missing_tids = np.setdiff1d(missing_tids, tids)
+ if missing_tids.size == 0: # We've got a timestamp for every train
+ break
+
+ arr = arr.astype('datetime64[ns]')
+ epoch = np.uint64(0).astype('datetime64[ns]')
+ arr[arr == epoch] = 'NaT' # Not a Time
+ if labelled:
+ import pandas as pd
+ return pd.Series(arr, index=self.train_ids)
+ return arr
+
def write(self, filename):
"""Write the selected data to a new HDF5 file
| European-XFEL/EXtra-data | 05de22b55fdc424473127335d2ca6b3a7026ab6d | diff --git a/extra_data/tests/mockdata/base.py b/extra_data/tests/mockdata/base.py
index 0b10de9..ad725cc 100644
--- a/extra_data/tests/mockdata/base.py
+++ b/extra_data/tests/mockdata/base.py
@@ -1,4 +1,4 @@
-from datetime import datetime, timedelta
+from datetime import datetime, timedelta, timezone
import os.path as osp
import re
@@ -191,7 +191,7 @@ def write_base_index(f, N, first=10000, chunksize=16, format_version='0.5'):
# timestamps
ds = f.create_dataset('INDEX/timestamp', (Npad,), 'u8', maxshape=(None,))
# timestamps are stored as a single uint64 with nanoseconds resolution
- ts = datetime.utcnow().timestamp() * 10**9
+ ts = datetime.now(tz=timezone.utc).timestamp() * 10**9
ds[:N] = [ts + i * 10**8 for i in range(N)]
# trainIds
diff --git a/extra_data/tests/test_reader_mockdata.py b/extra_data/tests/test_reader_mockdata.py
index 0863028..2e8544e 100644
--- a/extra_data/tests/test_reader_mockdata.py
+++ b/extra_data/tests/test_reader_mockdata.py
@@ -1,3 +1,4 @@
+from datetime import datetime, timedelta, timezone
from itertools import islice
import h5py
@@ -588,6 +589,37 @@ def test_select_trains(mock_fxe_raw_run):
run.select_trains(by_index[[480]])
+def test_train_timestamps(mock_scs_run):
+ run = RunDirectory(mock_scs_run)
+
+ tss = run.train_timestamps(labelled=False)
+ assert isinstance(tss, np.ndarray)
+ assert tss.shape == (len(run.train_ids),)
+ assert tss.dtype == np.dtype('datetime64[ns]')
+ assert np.all(np.diff(tss).astype(np.uint64) > 0)
+
+ # Convert numpy datetime64[ns] to Python datetime (dropping some precision)
+ dt0 = tss[0].astype('datetime64[ms]').item().replace(tzinfo=timezone.utc)
+ now = datetime.now(timezone.utc)
+ assert dt0 > (now - timedelta(days=1)) # assuming tests take < 1 day to run
+ assert dt0 < now
+
+ tss_ser = run.train_timestamps(labelled=True)
+ assert isinstance(tss_ser, pd.Series)
+ np.testing.assert_array_equal(tss_ser.values, tss)
+ np.testing.assert_array_equal(tss_ser.index, run.train_ids)
+
+
+def test_train_timestamps_nat(mock_fxe_control_data):
+ f = H5File(mock_fxe_control_data)
+ tss = f.train_timestamps()
+ assert tss.shape == (len(f.train_ids),)
+ if f.files[0].format_version == '0.5':
+ assert np.all(np.isnat(tss))
+ else:
+ assert not np.any(np.isnat(tss))
+
+
def test_union(mock_fxe_raw_run):
run = RunDirectory(mock_fxe_raw_run)
| Provide a means to get train timestamps
The new DAQ version adds a timestamp field in the INDEX section, with a timestamp matching each train ID. We should have a way to access these. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"extra_data/tests/test_reader_mockdata.py::test_train_timestamps_nat[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_train_timestamps_nat[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_train_timestamps"
] | [
"extra_data/tests/test_reader_mockdata.py::test_iterate_trains[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_iterate_trains_flat_keys[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_get_train_bad_device_name[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_detector_info_oldfmt[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_detector_info[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_train_info[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_iterate_trains_fxe[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_iterate_file_select_trains[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_iterate_trains_select_keys[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_iterate_trains_require_all[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_read_fxe_raw_run_selective[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_iterate_spb_raw_run[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_properties_fxe_raw_run[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_iterate_fxe_run[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_iterate_select_trains[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_iterate_run_glob_devices[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_train_by_id_fxe_run[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_train_by_id_fxe_run_selection[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_train_from_index_fxe_run[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_file_get_series_control[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_file_get_series_instrument[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_series_control[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_series_select_trains[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_dataframe[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_file_get_array[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_file_get_array_missing_trains[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_file_get_array_control_roi[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_array[0.5-defaultName]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_array[0.5-explicitName]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_array_empty[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_array_error[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_array_select_trains[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_array_roi[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_array_multiple_per_train[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_virtual_dataset[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_virtual_dataset_filename[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_select[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_select_require_all[0.5-*/BEAMVIEW2:daqOutput]",
"extra_data/tests/test_reader_mockdata.py::test_select_require_all[0.5-*/BEAMVIEW2*]",
"extra_data/tests/test_reader_mockdata.py::test_select_require_all[0.5-*]",
"extra_data/tests/test_reader_mockdata.py::test_deselect[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_select_trains[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_union[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_union_raw_proc[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_read_skip_invalid[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_run_immutable_sources[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_open_run[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_open_file[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_get_data_counts[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_iterate_trains[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_iterate_trains_flat_keys[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_get_train_bad_device_name[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_detector_info_oldfmt[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_detector_info[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_train_info[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_iterate_trains_fxe[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_iterate_file_select_trains[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_iterate_trains_select_keys[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_iterate_trains_require_all[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_read_fxe_raw_run_selective[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_iterate_spb_raw_run[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_properties_fxe_raw_run[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_iterate_fxe_run[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_iterate_select_trains[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_iterate_run_glob_devices[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_train_by_id_fxe_run[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_train_by_id_fxe_run_selection[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_train_from_index_fxe_run[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_file_get_series_control[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_file_get_series_instrument[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_series_control[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_series_select_trains[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_dataframe[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_file_get_array[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_file_get_array_missing_trains[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_file_get_array_control_roi[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_array[1.0-defaultName]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_array[1.0-explicitName]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_array_empty[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_array_error[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_array_select_trains[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_array_roi[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_array_multiple_per_train[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_virtual_dataset[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_virtual_dataset_filename[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_select[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_select_require_all[1.0-*/BEAMVIEW2:daqOutput]",
"extra_data/tests/test_reader_mockdata.py::test_select_require_all[1.0-*/BEAMVIEW2*]",
"extra_data/tests/test_reader_mockdata.py::test_select_require_all[1.0-*]",
"extra_data/tests/test_reader_mockdata.py::test_deselect[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_select_trains[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_union[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_union_raw_proc[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_read_skip_invalid[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_run_immutable_sources[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_open_run[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_open_file[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_get_data_counts[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_empty_file_info"
] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2021-04-09T14:59:14Z" | bsd-3-clause |
|
European-XFEL__EXtra-data-175 | diff --git a/.github/dependabot/constraints.txt b/.github/dependabot/constraints.txt
index 7cd24d9..7d680cb 100644
--- a/.github/dependabot/constraints.txt
+++ b/.github/dependabot/constraints.txt
@@ -14,5 +14,5 @@ pyparsing==2.4.7
python-dateutil==2.8.1
pytz==2021.1
pyzmq==22.0.3
-six==1.15.0
-xarray<=0.17.0
+six==1.16.0
+xarray<0.19.0
diff --git a/extra_data/components.py b/extra_data/components.py
index a00930a..3f7a8b2 100644
--- a/extra_data/components.py
+++ b/extra_data/components.py
@@ -372,24 +372,31 @@ class XtdfDetectorBase(MultimodDetectorBase):
inner_ids = get_inner_ids(f, data_slice, inner_index)
+ trainids = np.repeat(
+ np.arange(first_tid, last_tid + 1, dtype=np.uint64),
+ chunk_counts.astype(np.intp),
+ )
+ index = self._make_image_index(
+ trainids, inner_ids, inner_index[:-2]
+ )
+
if isinstance(pulses, by_id):
+ # Get the pulse ID values out of the MultiIndex rather than
+ # using inner_ids, because LPD1M in parallel_gain mode
+ # makes the MultiIndex differently, repeating pulse IDs.
if inner_index == 'pulseId':
- pulse_id = inner_ids
+ pulse_id = index.get_level_values('pulse')
else:
- pulse_id = get_inner_ids(f, data_slice, 'pulseId')
+ pulse_id = self._make_image_index(
+ trainids, get_inner_ids(f, data_slice, 'pulseId'),
+ ).get_level_values('pulse')
positions = self._select_pulse_ids(pulses, pulse_id)
else: # by_index
positions = self._select_pulse_indices(
pulses, chunk_firsts - data_slice.start, chunk_counts
)
- trainids = np.repeat(
- np.arange(first_tid, last_tid + 1, dtype=np.uint64),
- chunk_counts.astype(np.intp),
- )
- index = self._make_image_index(
- trainids, inner_ids, inner_index[:-2]
- )[positions]
+ index = index[positions]
if isinstance(positions, slice):
data_positions = slice(
@@ -398,12 +405,7 @@ class XtdfDetectorBase(MultimodDetectorBase):
positions.step
)
else: # ndarray
- # h5py fancy indexing needs a list, not an ndarray
- data_positions = list(data_slice.start + positions)
- if data_positions == []:
- # Work around a limitation of h5py
- # https://github.com/h5py/h5py/issues/1169
- data_positions = slice(0, 0)
+ data_positions = data_slice.start + positions
dset = f.file[data_path]
if dset.ndim >= 2 and dset.shape[1] == 1:
@@ -765,8 +767,7 @@ class MPxDetectorTrainIterator:
positions.step
)
else: # ndarray
- # h5py fancy indexing needs a list, not an ndarray
- data_positions = list(first + positions)
+ data_positions = first + positions
return self.data._guess_axes(ds[data_positions], train_pulse_ids, unstack_pulses=True)
@@ -931,6 +932,30 @@ class LPD1M(XtdfDetectorBase):
"parallel_gain=True needs the frames in each train to be divisible by 3"
)
+ def _select_pulse_indices(self, pulses, firsts, counts):
+ if not self.parallel_gain:
+ return super()._select_pulse_indices(pulses, firsts, counts)
+
+ if isinstance(pulses.value, slice):
+ if pulses.value == slice(0, MAX_PULSES, 1):
+ # All pulses included
+ return slice(0, counts.sum())
+ else:
+ s = pulses.value
+ desired = np.arange(s.start, s.stop, step=s.step, dtype=np.uint64)
+ else:
+ desired = pulses.value
+
+ positions = []
+ for ix, frames in zip(firsts, counts):
+ n_per_gain_stage = int(frames // 3)
+ train_desired = desired[desired < n_per_gain_stage]
+ for stage in range(3):
+ start = ix + np.uint64(stage * n_per_gain_stage)
+ positions.append(start + train_desired)
+
+ return np.concatenate(positions)
+
def _make_image_index(self, tids, inner_ids, inner_name='pulse'):
if not self.parallel_gain:
return super()._make_image_index(tids, inner_ids, inner_name)
diff --git a/extra_data/file_access.py b/extra_data/file_access.py
index f70edb8..6ef8bea 100644
--- a/extra_data/file_access.py
+++ b/extra_data/file_access.py
@@ -292,6 +292,25 @@ class FileAccess:
counts = np.uint64((ix_group['last'][:ntrains] - firsts + 1) * status)
return firsts, counts
+ def metadata(self) -> dict:
+ """Get the contents of the METADATA group as a dict
+
+ Not including the lists of data sources
+ """
+ if self.format_version == '0.5':
+ # Pretend this is actually there, like format version 1.0
+ return {'dataFormatVersion': '0.5'}
+
+ r = {}
+ for k, ds in self.file['METADATA'].items():
+ if not isinstance(ds, h5py.Dataset):
+ continue
+ v = ds[0]
+ if isinstance(v, bytes):
+ v = v.decode('utf-8', 'surrogateescape')
+ r[k] = v
+ return r
+
def get_keys(self, source):
"""Get keys for a given source name
diff --git a/extra_data/reader.py b/extra_data/reader.py
index e92934e..075d04b 100644
--- a/extra_data/reader.py
+++ b/extra_data/reader.py
@@ -1220,6 +1220,18 @@ class DataCollection:
return pd.Series(arr, index=self.train_ids)
return arr
+ def run_metadata(self) -> dict:
+ """Get a dictionary of metadata about the run
+
+ From file format version 1.0, the files capture: creationDate,
+ daqLibrary, dataFormatVersion, karaboFramework, proposalNumber,
+ runNumber, sequenceNumber, updateDate.
+ """
+ if not self.is_single_run:
+ raise MultiRunError()
+
+ return self.files[0].metadata()
+
def write(self, filename):
"""Write the selected data to a new HDF5 file
@@ -1473,8 +1485,9 @@ def open_run(
run: str, int
A run number such as 243, '243' or 'r0243'.
data: str
- 'raw' or 'proc' (processed) to access data from one of those folders.
- The default is 'raw'.
+ 'raw', 'proc' (processed) or 'all' (both 'raw' and 'proc') to access
+ data from either or both of those folders. If 'all' is used, sources
+ present in 'proc' overwrite those in 'raw'. The default is 'raw'.
include: str
Wildcard string to filter data files.
file_filter: callable
@@ -1486,6 +1499,24 @@ def open_run(
files which don't have this flag, out-of-sequence train IDs are suspect.
If True, it tries to include these trains.
"""
+ if data == 'all':
+ common_args = dict(
+ proposal=proposal, run=run, include=include,
+ file_filter=file_filter, inc_suspect_trains=inc_suspect_trains)
+
+ # Create separate data collections for raw and proc.
+ raw_dc = open_run(**common_args, data='raw')
+ proc_dc = open_run(**common_args, data='proc')
+
+ # Deselect to those raw sources not present in proc.
+ raw_extra = raw_dc.deselect(
+ [(src, '*') for src in raw_dc.all_sources & proc_dc.all_sources])
+
+ # Merge extra raw sources into proc sources and re-enable is_single_run.
+ dc = proc_dc.union(raw_extra)
+ dc.is_single_run = True
+ return dc
+
if isinstance(proposal, str):
if ('/' not in proposal) and not proposal.startswith('p'):
proposal = 'p' + proposal.rjust(6, '0')
diff --git a/setup.py b/setup.py
index a4bb1b7..3f31ec5 100755
--- a/setup.py
+++ b/setup.py
@@ -46,7 +46,7 @@ setup(name="EXtra-data",
},
install_requires=[
'fabio',
- 'h5py>=2.7.1',
+ 'h5py>=2.10',
'karabo-bridge >=0.6',
'matplotlib',
'numpy',
| European-XFEL/EXtra-data | 13a2af8210d71d8a5e97d6e94a36091fc2ebd458 | diff --git a/extra_data/tests/test_components.py b/extra_data/tests/test_components.py
index fa0b125..0454a3f 100644
--- a/extra_data/tests/test_components.py
+++ b/extra_data/tests/test_components.py
@@ -164,6 +164,22 @@ def test_get_array_lpd_parallelgain(mock_lpd_parallelgain_run):
np.testing.assert_array_equal(arr.coords['pulse'], np.arange(100))
+def test_get_array_lpd_parallelgain_select_pulses(mock_lpd_parallelgain_run):
+ run = RunDirectory(mock_lpd_parallelgain_run)
+ det = LPD1M(run.select_trains(by_index[:2]), parallel_gain=True)
+ assert det.detector_name == 'FXE_DET_LPD1M-1'
+
+ arr = det.get_array('image.data', pulses=np.s_[:5])
+ assert arr.shape == (16, 2, 3, 5, 256, 256)
+ assert arr.dims == ('module', 'train', 'gain', 'pulse', 'slow_scan', 'fast_scan')
+ np.testing.assert_array_equal(arr.coords['gain'], np.arange(3))
+ np.testing.assert_array_equal(arr.coords['pulse'], np.arange(5))
+
+ arr = det.get_array('image.data', pulses=by_id[:5])
+ assert arr.shape == (16, 2, 3, 5, 256, 256)
+ np.testing.assert_array_equal(arr.coords['pulse'], np.arange(5))
+
+
def test_get_array_jungfrau(mock_jungfrau_run):
run = RunDirectory(mock_jungfrau_run)
jf = JUNGFRAU(run.select_trains(by_index[:2]))
diff --git a/extra_data/tests/test_reader_mockdata.py b/extra_data/tests/test_reader_mockdata.py
index 3646df6..8ba3844 100644
--- a/extra_data/tests/test_reader_mockdata.py
+++ b/extra_data/tests/test_reader_mockdata.py
@@ -694,13 +694,32 @@ def test_open_run(mock_spb_raw_run, mock_spb_proc_run, tmpdir):
assert {f.filename for f in run.files} == paths
# Proc folder
- run = open_run(proposal=2012, run=238, data='proc')
+ proc_run = open_run(proposal=2012, run=238, data='proc')
- proc_paths = {f.filename for f in run.files}
+ proc_paths = {f.filename for f in proc_run.files}
assert proc_paths
for path in proc_paths:
assert '/raw/' not in path
+ # All folders
+ all_run = open_run(proposal=2012, run=238, data='all')
+
+ # Raw contains all sources.
+ assert run.all_sources == all_run.all_sources
+
+ # Proc is a true subset.
+ assert proc_run.all_sources < all_run.all_sources
+
+ for source, files in all_run._source_index.items():
+ for file in files:
+ if '/DET/' in source:
+ # AGIPD data is in proc.
+ assert '/raw/' not in file.filename
+ else:
+ # Non-AGIPD data is in raw.
+ # (CAM, XGM)
+ assert '/proc/' not in file.filename
+
# Run that doesn't exist
with pytest.raises(Exception):
open_run(proposal=2012, run=999)
@@ -770,3 +789,18 @@ def test_get_run_values(mock_fxe_control_data):
d = f.get_run_values(src, )
assert isinstance(d['firmwareVersion.value'], np.int32)
assert isinstance(d['enableShutter.value'], np.uint8)
+
+
+def test_run_metadata(mock_spb_raw_run):
+ run = RunDirectory(mock_spb_raw_run)
+ md = run.run_metadata()
+ if run.files[0].format_version == '0.5':
+ assert md == {'dataFormatVersion': '0.5'}
+ else:
+ assert md['dataFormatVersion'] == '1.0'
+ assert set(md) == {
+ 'dataFormatVersion', 'creationDate', 'updateDate', 'daqLibrary',
+ 'karaboFramework', 'proposalNumber', 'runNumber', 'runType',
+ 'sample', 'sequenceNumber',
+ }
+ assert isinstance(md['creationDate'], str)
| Provide a means to access metadata fields
The new DAQ version records a few extra fields in the `METADATA` section of files, including start time and DAQ version. It should be possible to get this information through EXtra-data.
Complication: we allow combining data from more than one run. What should happen where the metadata differs? | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"extra_data/tests/test_reader_mockdata.py::test_run_metadata[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_open_run[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_run_metadata[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_open_run[0.5]"
] | [
"extra_data/tests/test_components.py::test_get_array[1.0]",
"extra_data/tests/test_components.py::test_iterate[1.0]",
"extra_data/tests/test_components.py::test_get_array_pulse_indexes_reduced_data[1.0]",
"extra_data/tests/test_components.py::test_identify_multimod_detectors[1.0]",
"extra_data/tests/test_components.py::test_iterate_pulse_index[1.0]",
"extra_data/tests/test_components.py::test_write_selected_frames[1.0]",
"extra_data/tests/test_components.py::test_get_array_roi[1.0]",
"extra_data/tests/test_components.py::test_get_array_pulse_indexes[1.0]",
"extra_data/tests/test_components.py::test_write_selected_frames_proc[1.0]",
"extra_data/tests/test_components.py::test_identify_multimod_detectors_multi[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_select_trains[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_virtual_dataset[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_train_by_id_fxe_run_selection[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_array_empty[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_file_get_array_missing_trains[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_detector_info[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_select[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_iterate_select_trains[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_iterate_trains_flat_keys[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_series_control[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_get_train_bad_device_name[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_iterate_run_glob_devices[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_train_by_id_fxe_run[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_file_get_array[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_iterate_trains[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_iterate_trains_fxe[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_properties_fxe_raw_run[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_get_run_values[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_iterate_spb_raw_run[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_union[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_file_get_array_control_roi[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_series_select_trains[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_array[1.0-explicitName]",
"extra_data/tests/test_reader_mockdata.py::test_train_info[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_open_file[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_train_timestamps_nat[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_file_get_series_instrument[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_iterate_file_select_trains[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_get_data_counts[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_detector_info_oldfmt[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_get_run_value[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_select_require_all[1.0-*/BEAMVIEW2:daqOutput]",
"extra_data/tests/test_reader_mockdata.py::test_union_raw_proc[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_array[1.0-defaultName]",
"extra_data/tests/test_reader_mockdata.py::test_train_from_index_fxe_run[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_select_require_all[1.0-*]",
"extra_data/tests/test_reader_mockdata.py::test_file_get_series_control[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_array_multiple_per_train[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_run_immutable_sources[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_array_select_trains[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_select_require_all[1.0-*/BEAMVIEW2*]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_dataframe[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_virtual_dataset_filename[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_iterate_trains_require_all[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_read_fxe_raw_run_selective[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_deselect[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_iterate_fxe_run[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_array_roi[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_iterate_trains_select_keys[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_get_run_value_union[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_read_skip_invalid[1.0]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_array_error[1.0]",
"extra_data/tests/test_components.py::test_write_selected_frames[0.5]",
"extra_data/tests/test_components.py::test_get_array_pulse_indexes_reduced_data[0.5]",
"extra_data/tests/test_components.py::test_identify_multimod_detectors[0.5]",
"extra_data/tests/test_components.py::test_identify_multimod_detectors_multi[0.5]",
"extra_data/tests/test_components.py::test_get_array_roi[0.5]",
"extra_data/tests/test_components.py::test_get_array[0.5]",
"extra_data/tests/test_components.py::test_iterate_pulse_index[0.5]",
"extra_data/tests/test_components.py::test_get_array_pulse_indexes[0.5]",
"extra_data/tests/test_components.py::test_iterate[0.5]",
"extra_data/tests/test_components.py::test_write_selected_frames_proc[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_array_empty[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_get_run_values[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_get_data_counts[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_series_control[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_virtual_dataset[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_select_trains[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_iterate_spb_raw_run[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_train_info[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_union_raw_proc[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_iterate_trains_fxe[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_file_get_array_missing_trains[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_get_run_value[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_dataframe[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_array_select_trains[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_read_fxe_raw_run_selective[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_detector_info[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_file_get_array_control_roi[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_file_get_series_instrument[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_train_by_id_fxe_run_selection[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_train_timestamps_nat[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_iterate_trains_select_keys[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_deselect[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_series_select_trains[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_iterate_select_trains[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_select_require_all[0.5-*/BEAMVIEW2:daqOutput]",
"extra_data/tests/test_reader_mockdata.py::test_iterate_run_glob_devices[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_iterate_fxe_run[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_array[0.5-explicitName]",
"extra_data/tests/test_reader_mockdata.py::test_get_train_bad_device_name[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_run_immutable_sources[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_train_by_id_fxe_run[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_file_get_array[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_array[0.5-defaultName]",
"extra_data/tests/test_reader_mockdata.py::test_iterate_trains[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_open_file[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_train_from_index_fxe_run[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_iterate_file_select_trains[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_detector_info_oldfmt[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_select[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_virtual_dataset_filename[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_array_roi[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_array_multiple_per_train[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_read_skip_invalid[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_union[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_file_get_series_control[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_properties_fxe_raw_run[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_select_require_all[0.5-*]",
"extra_data/tests/test_reader_mockdata.py::test_iterate_trains_flat_keys[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_get_run_value_union[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_run_get_array_error[0.5]",
"extra_data/tests/test_reader_mockdata.py::test_select_require_all[0.5-*/BEAMVIEW2*]",
"extra_data/tests/test_reader_mockdata.py::test_iterate_trains_require_all[0.5]",
"extra_data/tests/test_components.py::test_get_array_roi_dssc",
"extra_data/tests/test_components.py::test_iterate_jungfrau",
"extra_data/tests/test_components.py::test_get_array_jungfrau",
"extra_data/tests/test_components.py::test_get_array_lpd_parallelgain",
"extra_data/tests/test_components.py::test_iterate_lpd_parallel_gain",
"extra_data/tests/test_reader_mockdata.py::test_empty_file_info",
"extra_data/tests/test_reader_mockdata.py::test_train_timestamps"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2021-05-04T10:10:30Z" | bsd-3-clause |
|
European-XFEL__EXtra-data-222 | diff --git a/extra_data/keydata.py b/extra_data/keydata.py
index 86fc141..167b173 100644
--- a/extra_data/keydata.py
+++ b/extra_data/keydata.py
@@ -53,11 +53,14 @@ class KeyData:
"""An ordered list of chunks containing data"""
if self._cached_chunks is None:
self._cached_chunks = sorted(
- [c for c in self._find_chunks() if c.total_count],
- key=lambda c: c.train_ids[0]
+ self._find_chunks(), key=lambda c: c.train_ids[0]
)
return self._cached_chunks
+ @property
+ def _data_chunks_nonempty(self) -> List[DataChunk]:
+ return [c for c in self._data_chunks if c.total_count]
+
def __repr__(self):
return f"<extra_data.KeyData source={self.source!r} key={self.key!r} " \
f"for {len(self.train_ids)} trains>"
@@ -148,8 +151,11 @@ class KeyData:
If *labelled* is True, returns a pandas series with an index of train
IDs. Otherwise, returns a NumPy array of counts to match ``.train_ids``.
"""
- train_ids = np.concatenate([c.train_ids for c in self._data_chunks])
- counts = np.concatenate([c.counts for c in self._data_chunks])
+ if self._data_chunks:
+ train_ids = np.concatenate([c.train_ids for c in self._data_chunks])
+ counts = np.concatenate([c.counts for c in self._data_chunks])
+ else:
+ train_ids = counts = np.zeros(0, dtype=np.uint64)
if labelled:
import pandas as pd
@@ -182,7 +188,7 @@ class KeyData:
# Read the data from each chunk into the result array
dest_cursor = 0
- for chunk in self._data_chunks:
+ for chunk in self._data_chunks_nonempty:
dest_chunk_end = dest_cursor + chunk.total_count
slices = (chunk.slice,) + roi
@@ -195,6 +201,8 @@ class KeyData:
def _trainid_index(self):
"""A 1D array of train IDs, corresponding to self.shape[0]"""
+ if not self._data_chunks:
+ return np.zeros(0, dtype=np.uint64)
chunks_trainids = [
np.repeat(chunk.train_ids, chunk.counts.astype(np.intp))
for chunk in self._data_chunks
@@ -234,9 +242,7 @@ class KeyData:
dims = ['trainId'] + extra_dims
# Train ID index
- coords = {}
- if self.shape[0]:
- coords = {'trainId': self._trainid_index()}
+ coords = {'trainId': self._trainid_index()}
if name is None:
name = f'{self.source}.{self.key}'
@@ -287,7 +293,7 @@ class KeyData:
chunks_darrs = []
- for chunk in self._data_chunks:
+ for chunk in self._data_chunks_nonempty:
chunk_dim0 = chunk.total_count
chunk_shape = (chunk_dim0,) + chunk.dataset.shape[1:]
itemsize = chunk.dataset.dtype.itemsize
@@ -310,7 +316,11 @@ class KeyData:
)[chunk.slice]
)
- dask_arr = da.concatenate(chunks_darrs, axis=0)
+ if chunks_darrs:
+ dask_arr = da.concatenate(chunks_darrs, axis=0)
+ else:
+ shape = (0,) + self.entry_shape
+ dask_arr = da.zeros(shape=shape, dtype=self.dtype, chunks=shape)
if labelled:
# Dimension labels
@@ -369,7 +379,7 @@ class KeyData:
Yields pairs of (train ID, array). Skips trains where data is missing.
"""
- for chunk in self._data_chunks:
+ for chunk in self._data_chunks_nonempty:
start = chunk.first
ds = chunk.dataset
for tid, count in zip(chunk.train_ids, chunk.counts):
| European-XFEL/EXtra-data | b738290e6dbb09ed2906f43f985cce9f16513ba3 | diff --git a/extra_data/tests/test_keydata.py b/extra_data/tests/test_keydata.py
index cb7406f..abdf9e8 100644
--- a/extra_data/tests/test_keydata.py
+++ b/extra_data/tests/test_keydata.py
@@ -68,6 +68,10 @@ def test_nodata(mock_fxe_raw_run):
assert arr.shape == (0, 255, 1024)
assert arr.dtype == np.dtype('u2')
+ dask_arr = cam_pix.dask_array(labelled=True)
+ assert dask_arr.shape == (0, 255, 1024)
+ assert dask_arr.dtype == np.dtype('u2')
+
assert list(cam_pix.trains()) == []
tid, data = cam_pix.train_from_id(10010)
assert tid == 10010
@@ -121,6 +125,24 @@ def test_data_counts(mock_reduced_spb_proc_run):
assert count.values.sum() == mod.shape[0]
+def test_data_counts_empty(mock_fxe_raw_run):
+ run = RunDirectory(mock_fxe_raw_run)
+ cam_nodata = run['FXE_XAD_GEC/CAM/CAMERA_NODATA:daqOutput', 'data.image.pixels']
+
+ count_ser = cam_nodata.data_counts(labelled=True)
+ assert len(count_ser) == 480
+ assert count_ser.sum() == 0
+
+ count_arr = cam_nodata.data_counts(labelled=False)
+ assert len(count_arr) == 480
+ assert count_arr.sum() == 0
+
+ count_none_ser = cam_nodata.drop_empty_trains().data_counts(labelled=True)
+ assert len(count_none_ser) == 0
+
+ count_none_arr = cam_nodata.drop_empty_trains().data_counts(labelled=False)
+ assert len(count_none_arr) == 0
+
def test_select_by(mock_spb_raw_run):
run = RunDirectory(mock_spb_raw_run)
am0 = run['SPB_DET_AGIPD1M-1/DET/0CH0:xtdf', 'image.data']
| Can't instantiate multi-module detector access if any module has no data
This happens a lot with LPD data. It looks like the root cause is a problem with `.data_counts()`.
```python
run = open_run(2729, 44)
LPD1M(run.select_trains(np.s_[:100])
```
```
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-12-fb113b52e6e9> in <module>
----> 1 LPD1M(run_trains, parallel_gain=True)
~/Code/EXtra-data/extra_data/components.py in __init__(self, data, detector_name, modules, min_modules, parallel_gain)
1210 def __init__(self, data: DataCollection, detector_name=None, modules=None,
1211 *, min_modules=1, parallel_gain=False):
-> 1212 super().__init__(data, detector_name, modules, min_modules=min_modules)
1213
1214 self.parallel_gain = parallel_gain
~/Code/EXtra-data/extra_data/components.py in __init__(self, data, detector_name, modules, min_modules)
393 def __init__(self, data: DataCollection, detector_name=None, modules=None,
394 *, min_modules=1):
--> 395 super().__init__(data, detector_name, modules, min_modules=min_modules)
396
397 @staticmethod
~/Code/EXtra-data/extra_data/components.py in __init__(self, data, detector_name, modules, min_modules)
116 mod_data_counts = pd.DataFrame({
117 src: data.get_data_counts(src, self._main_data_key)
--> 118 for src in source_to_modno
119 }).fillna(0).astype(np.uint64)
120
~/Code/EXtra-data/extra_data/components.py in <dictcomp>(.0)
116 mod_data_counts = pd.DataFrame({
117 src: data.get_data_counts(src, self._main_data_key)
--> 118 for src in source_to_modno
119 }).fillna(0).astype(np.uint64)
120
~/Code/EXtra-data/extra_data/reader.py in get_data_counts(self, source, key)
442 Key of parameter within that device, e.g. "image.data".
443 """
--> 444 return self._get_key_data(source, key).data_counts()
445
446 def get_series(self, source, key):
~/Code/EXtra-data/extra_data/keydata.py in data_counts(self, labelled)
149 IDs. Otherwise, returns a NumPy array of counts to match ``.train_ids``.
150 """
--> 151 train_ids = np.concatenate([c.train_ids for c in self._data_chunks])
152 counts = np.concatenate([c.counts for c in self._data_chunks])
153
<__array_function__ internals> in concatenate(*args, **kwargs)
ValueError: need at least one array to concatenate
``` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"extra_data/tests/test_keydata.py::test_data_counts_empty[1.0]",
"extra_data/tests/test_keydata.py::test_nodata[1.0]",
"extra_data/tests/test_keydata.py::test_nodata[0.5]",
"extra_data/tests/test_keydata.py::test_data_counts_empty[0.5]"
] | [
"extra_data/tests/test_keydata.py::test_get_keydata[1.0]",
"extra_data/tests/test_keydata.py::test_drop_empty_trains[1.0]",
"extra_data/tests/test_keydata.py::test_iter_trains[1.0]",
"extra_data/tests/test_keydata.py::test_split_trains[1.0]",
"extra_data/tests/test_keydata.py::test_data_counts[1.0]",
"extra_data/tests/test_keydata.py::test_select_by[1.0]",
"extra_data/tests/test_keydata.py::test_select_trains[1.0]",
"extra_data/tests/test_keydata.py::test_get_train[1.0]",
"extra_data/tests/test_keydata.py::test_split_trains[0.5]",
"extra_data/tests/test_keydata.py::test_data_counts[0.5]",
"extra_data/tests/test_keydata.py::test_drop_empty_trains[0.5]",
"extra_data/tests/test_keydata.py::test_select_by[0.5]",
"extra_data/tests/test_keydata.py::test_select_trains[0.5]",
"extra_data/tests/test_keydata.py::test_get_keydata[0.5]",
"extra_data/tests/test_keydata.py::test_iter_trains[0.5]",
"extra_data/tests/test_keydata.py::test_get_train[0.5]"
] | {
"failed_lite_validators": [
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2021-09-27T11:02:16Z" | bsd-3-clause |
|
European-XFEL__EXtra-data-257 | diff --git a/.github/dependabot/constraints.txt b/.github/dependabot/constraints.txt
index ee3a594..7cfce9f 100644
--- a/.github/dependabot/constraints.txt
+++ b/.github/dependabot/constraints.txt
@@ -1,3 +1,4 @@
+coverage==6.1.2
cycler==0.11.0
h5py<3.7.0
karabo-bridge==0.6.1
diff --git a/extra_data/keydata.py b/extra_data/keydata.py
index e81e88e..d753525 100644
--- a/extra_data/keydata.py
+++ b/extra_data/keydata.py
@@ -164,13 +164,16 @@ class KeyData:
import pandas as pd
return pd.Series(counts, index=train_ids)
else:
- # self.train_ids is always sorted. The train IDs from chunks
- # should be in order, but sometimes trains are written out of order.
- # Reorder the counts to match self.train_ids.
- assert len(train_ids) == len(self.train_ids)
+ # We may be missing some train IDs, if they're not in any file
+ # for this source, and they're sometimes out of order within chunks
+ # (they shouldn't be, but we try not to fail too badly if they are).
assert np.isin(train_ids, self.train_ids).all()
- idxs = np.argsort(train_ids)
- return counts[idxs]
+ tid_to_ix = {t: i for (i, t) in enumerate(self.train_ids)}
+ res = np.zeros(len(self.train_ids), dtype=np.uint64)
+ for tid, ct in zip(train_ids, counts):
+ res[tid_to_ix[tid]] = ct
+
+ return res
def as_single_value(self, rtol=1e-5, atol=0.0, reduce_by='median'):
"""Retrieve a single reduced value if within tolerances.
| European-XFEL/EXtra-data | dac73a279511b033937bde2f1b239c0dd80b657b | diff --git a/extra_data/tests/test_keydata.py b/extra_data/tests/test_keydata.py
index 2d107b1..3930cfb 100644
--- a/extra_data/tests/test_keydata.py
+++ b/extra_data/tests/test_keydata.py
@@ -2,8 +2,11 @@ import os
import numpy as np
import pytest
+import h5py
+
from extra_data import RunDirectory, H5File
from extra_data.exceptions import TrainIDError, NoDataError
+from . import make_examples
from .mockdata import write_file
from .mockdata.xgm import XGM
@@ -146,6 +149,46 @@ def test_data_counts_empty(mock_fxe_raw_run):
count_none_arr = cam_nodata.drop_empty_trains().data_counts(labelled=False)
assert len(count_none_arr) == 0
+
[email protected]()
+def fxe_run_module_offset(tmp_path):
+ run_dir = tmp_path / 'fxe-run-mod-offset'
+ run_dir.mkdir()
+ make_examples.make_fxe_run(run_dir, format_version='1.0')
+
+ # Shift the train IDs for a module by 1, so it has data for a different set
+ # of train IDs to other sources.
+ with h5py.File(run_dir / 'RAW-R0450-LPD08-S00000.h5', 'r+') as f:
+ tids_dset = f['INDEX/trainId']
+ tids_dset[:] = tids_dset[:] + 1
+
+ return run_dir
+
+
+def test_data_counts_missing_train(fxe_run_module_offset):
+ run = RunDirectory(fxe_run_module_offset)
+ assert len(run.train_ids) == 481
+ lpd_m8 = run['FXE_DET_LPD1M-1/DET/8CH0:xtdf', 'image.cellId']
+
+ ser = lpd_m8.data_counts(labelled=True)
+ assert len(ser) == 480
+ np.testing.assert_array_equal(ser.index, run.train_ids[1:])
+
+ arr = lpd_m8.data_counts(labelled=False)
+ assert len(arr) == 481
+ assert arr[0] == 0
+ np.testing.assert_array_equal(arr[1:], 128)
+
+ lpd_m8_w_data = lpd_m8.drop_empty_trains()
+ ser = lpd_m8_w_data.data_counts(labelled=True)
+ assert len(ser) == 480
+ np.testing.assert_array_equal(ser.index, run.train_ids[1:])
+
+ arr = lpd_m8_w_data.data_counts(labelled=False)
+ assert len(arr) == 480
+ np.testing.assert_array_equal(arr, 128)
+
+
def test_select_by(mock_spb_raw_run):
run = RunDirectory(mock_spb_raw_run)
am0 = run['SPB_DET_AGIPD1M-1/DET/0CH0:xtdf', 'image.data']
| AssertionError in .data_counts(labelled=False)
@yohey-uemura discovered this over the weekend. When writing this method, I had overlooked the possibility of having a selected train which doesn't correspond to any data for the given source. For instance, in this run, LPD08 starts from train 1232492275, but other sources in the run start from 1232492274.
```python
run = open_run(2958, 172)
run[
'FXE_DET_LPD1M-1/DET/8CH0:xtdf', 'image.cellId'
].data_counts(labelled=False)
```
```
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
<ipython-input-14-749f3505f4df> in <module>
1 run[
2 'FXE_DET_LPD1M-1/DET/8CH0:xtdf', 'image.cellId'
----> 3 ].data_counts(labelled=False)
/gpfs/exfel/sw/software/xfel_anaconda3/1.1.2/lib/python3.7/site-packages/extra_data/keydata.py in data_counts(self, labelled)
168 # should be in order, but sometimes trains are written out of order.
169 # Reorder the counts to match self.train_ids.
--> 170 assert len(train_ids) == len(self.train_ids)
171 assert np.isin(train_ids, self.train_ids).all()
172 idxs = np.argsort(train_ids)
AssertionError:
``` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"extra_data/tests/test_keydata.py::test_data_counts_missing_train"
] | [
"extra_data/tests/test_keydata.py::test_iter_trains[0.5]",
"extra_data/tests/test_keydata.py::test_drop_empty_trains[0.5]",
"extra_data/tests/test_keydata.py::test_data_counts[0.5]",
"extra_data/tests/test_keydata.py::test_get_keydata[0.5]",
"extra_data/tests/test_keydata.py::test_file_no_trains[0.5]",
"extra_data/tests/test_keydata.py::test_single_value[0.5]",
"extra_data/tests/test_keydata.py::test_select_trains[0.5]",
"extra_data/tests/test_keydata.py::test_nodata[0.5]",
"extra_data/tests/test_keydata.py::test_data_counts_empty[0.5]",
"extra_data/tests/test_keydata.py::test_get_train[0.5]",
"extra_data/tests/test_keydata.py::test_select_by[0.5]",
"extra_data/tests/test_keydata.py::test_split_trains[0.5]",
"extra_data/tests/test_keydata.py::test_get_keydata[1.0]",
"extra_data/tests/test_keydata.py::test_single_value[1.0]",
"extra_data/tests/test_keydata.py::test_drop_empty_trains[1.0]",
"extra_data/tests/test_keydata.py::test_data_counts_empty[1.0]",
"extra_data/tests/test_keydata.py::test_select_trains[1.0]",
"extra_data/tests/test_keydata.py::test_split_trains[1.0]",
"extra_data/tests/test_keydata.py::test_data_counts[1.0]",
"extra_data/tests/test_keydata.py::test_get_train[1.0]",
"extra_data/tests/test_keydata.py::test_file_no_trains[1.0]",
"extra_data/tests/test_keydata.py::test_iter_trains[1.0]",
"extra_data/tests/test_keydata.py::test_nodata[1.0]",
"extra_data/tests/test_keydata.py::test_select_by[1.0]"
] | {
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2021-11-29T15:38:38Z" | bsd-3-clause |
|
European-XFEL__EXtra-data-375 | diff --git a/extra_data/reader.py b/extra_data/reader.py
index 21ad0f4..90643e5 100644
--- a/extra_data/reader.py
+++ b/extra_data/reader.py
@@ -1398,7 +1398,9 @@ def RunDirectory(
if _use_voview and (sel_files == files):
voview_file_acc = voview.find_file_valid(path)
if voview_file_acc is not None:
- return DataCollection([voview_file_acc], is_single_run=True)
+ return DataCollection([voview_file_acc],
+ is_single_run=True,
+ ctx_closes=True)
files_map = RunFilesMap(path)
t0 = time.monotonic()
diff --git a/setup.py b/setup.py
index 4237df0..1e974b9 100755
--- a/setup.py
+++ b/setup.py
@@ -76,6 +76,7 @@ setup(name="EXtra-data",
'pytest',
'pytest-cov',
'testpath',
+ 'psutil',
]
},
python_requires='>=3.6',
| European-XFEL/EXtra-data | 2ae9f5eafd9a7661c653cbb57eb6f25373fe519c | diff --git a/extra_data/tests/test_voview.py b/extra_data/tests/test_voview.py
index 3f0bb96..3179802 100644
--- a/extra_data/tests/test_voview.py
+++ b/extra_data/tests/test_voview.py
@@ -35,6 +35,10 @@ def test_use_voview(mock_spb_raw_run, tmp_path):
assert 'SPB_DET_AGIPD1M-1/DET/0CH0:xtdf' in run.instrument_sources
assert 'SA1_XTD2_XGM/DOOCS/MAIN' in run.control_sources
+ with RunDirectory(str(new_run_dir)) as run:
+ assert 'SPB_DET_AGIPD1M-1/DET/0CH0:xtdf' in run.instrument_sources
+ assert 'SA1_XTD2_XGM/DOOCS/MAIN' in run.control_sources
+
def open_run_with_voview(run_src, new_run_dir):
copytree(run_src, new_run_dir)
| RunDirectory does not work as context manager when voview file present
[In the Jungfrau correction notebook, the raw run files are opened using a context manager](https://git.xfel.eu/detectors/pycalibration/-/blob/master/notebooks/Jungfrau/Jungfrau_Gain_Correct_and_Verify_NBC.ipynb#L697).
This works fine when no voview files were created, as the files are opened directly.
It's also fine to use the voview file when using `RunDirectory` as a regular object.
However, when opening a run using a voview file ([the default behaviour when available](https://github.com/European-XFEL/EXtra-data/blob/d4c547c3af9a993ec2da41b5bf3d830dce9ab43e/extra_data/reader.py#L1398:L1401)), an [error is raised](https://github.com/European-XFEL/EXtra-data/blob/master/extra_data/reader.py#L186:L194) as files cannot be closed when leaving the context.
We noticed this recently as HED is using the RunValidator which creates such files, whereas other instruments do not (yet).
## How to Reproduce
This can be reproduced with the following:
```python
In [15]: from extra_data import RunDirectory
...: with RunDirectory("/gpfs/exfel/exp/HED/202330/p900338/raw/r0052", "*S00000*") as
...: fd:
...: print(fd)
...:
---------------------------------------------------------------------------
Exception Traceback (most recent call last)
<ipython-input-15-53c99aa5c4ec> in <module>
1 from extra_data import RunDirectory
----> 2 with RunDirectory("/gpfs/exfel/exp/HED/202330/p900338/raw/r0052", "*S00000*") as fd:
3 print(fd)
4
~/EXtra-data/extra_data/reader.py in __enter__(self)
186 def __enter__(self):
187 if not self.ctx_closes:
--> 188 raise Exception(
189 "Only DataCollection objects created by opening "
190 "files directly can be used in a 'with' statement, "
Exception: Only DataCollection objects created by opening files directly can be used in a 'with' statement, not those created by selecting from or merging others.
```
## Possible fixes
The current behaviour is not necessarily wrong, as it's difficult to know before hand if the `DataCollection` is going to be used as a context manager.
In the case of the correction, [we explicitly ignore the voview file](https://git.xfel.eu/detectors/pycalibration/-/merge_requests/793) as we want to simplify file access.
I think it would be beneficial to clarify the error message and suggest to pass `_use_voview=False`.
Another solution would be to [remove the check in `__enter__`](https://github.com/European-XFEL/EXtra-data/blob/d4c547c3af9a993ec2da41b5bf3d830dce9ab43e/extra_data/reader.py#L187) as the check whether to close files is done again in [`__exit__`](https://github.com/European-XFEL/EXtra-data/blob/d4c547c3af9a993ec2da41b5bf3d830dce9ab43e/extra_data/reader.py#L198).
I'm happy to contribute a solution, but would need guidance.
Thanks,
Cyril
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"extra_data/tests/test_voview.py::test_use_voview[0.5]",
"extra_data/tests/test_voview.py::test_use_voview[1.0]"
] | [
"extra_data/tests/test_voview.py::test_main[0.5]",
"extra_data/tests/test_voview.py::test_combine_voview[0.5]",
"extra_data/tests/test_voview.py::test_main[1.0]",
"extra_data/tests/test_voview.py::test_combine_voview[1.0]",
"extra_data/tests/test_voview.py::test_voview_paths"
] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2023-01-26T17:04:14Z" | bsd-3-clause |
|
Eyepea__aiosip-111 | diff --git a/aiosip/transaction.py b/aiosip/transaction.py
index da61942..4f2b0ab 100644
--- a/aiosip/transaction.py
+++ b/aiosip/transaction.py
@@ -145,6 +145,9 @@ class FutureTransaction(BaseTransaction):
self.dialog.end_transaction(self)
def _result(self, msg):
+ if self.authentification:
+ self.authentification.cancel()
+ self.authentification = None
self._future.set_result(msg)
self.dialog.end_transaction(self)
| Eyepea/aiosip | 3219ca46cdfd115a72101d92cd1f717f78d9f7b9 | diff --git a/tests/test_sip_scenario.py b/tests/test_sip_scenario.py
index d38e7c3..fdb1a89 100644
--- a/tests/test_sip_scenario.py
+++ b/tests/test_sip_scenario.py
@@ -92,6 +92,53 @@ async def test_authentication(test_server, protocol, loop, from_details, to_deta
await app.close()
+async def test_authentication_rejection(test_server, protocol, loop, from_details, to_details):
+ received_messages = list()
+
+ class Dialplan(aiosip.BaseDialplan):
+
+ async def resolve(self, *args, **kwargs):
+ await super().resolve(*args, **kwargs)
+ return self.subscribe
+
+ async def subscribe(self, request, message):
+ dialog = request._create_dialog()
+
+ received_messages.append(message)
+ await dialog.unauthorized(message)
+
+ async for message in dialog:
+ received_messages.append(message)
+ await dialog.reply(message, 401)
+
+ app = aiosip.Application(loop=loop)
+ server_app = aiosip.Application(loop=loop, dialplan=Dialplan())
+ server = await test_server(server_app)
+
+ peer = await app.connect(
+ protocol=protocol,
+ remote_addr=(
+ server.sip_config['server_host'],
+ server.sip_config['server_port'],
+ )
+ )
+
+ result = await peer.register(
+ expires=1800,
+ from_details=aiosip.Contact.from_header(from_details),
+ to_details=aiosip.Contact.from_header(to_details),
+ password='testing_pass',
+ )
+
+ # wait long enough to ensure no improper retransmit
+ await asyncio.sleep(1)
+ assert len(received_messages) == 2
+ assert result.status_code == 401
+
+ await server_app.close()
+ await app.close()
+
+
async def test_invite(test_server, protocol, loop, from_details, to_details):
call_established = loop.create_future()
call_disconnected = loop.create_future()
| Improper handling of 401 authentication failures
In a call flow such as
* send REGISTER
* get 401 response with auth challenge
* send REGISTER with valid authentication
* get 401 response with no challenge (ie: your credentials are fine, but still denied)
The client will continue to retransmit the request with the authorization header | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_sip_scenario.py::test_notify[tcp]"
] | [] | {
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
} | "2018-04-23T21:51:49Z" | apache-2.0 |
|
F5Networks__f5-icontrol-rest-python-115 | diff --git a/icontrol/exceptions.py b/icontrol/exceptions.py
index 81aed7f..c897800 100644
--- a/icontrol/exceptions.py
+++ b/icontrol/exceptions.py
@@ -51,3 +51,9 @@ class InvalidInstanceNameOrFolder(BigIPInvalidURL):
class InvalidSuffixCollection(BigIPInvalidURL):
# must start with a '/' since there may be a partition or name before it
pass
+
+
+class InvalidURIComponentPart(BigIPInvalidURL):
+ # When a consumer gives the subPath of a uri, the partition should be
+ # included as well
+ pass
diff --git a/icontrol/session.py b/icontrol/session.py
index f06180a..a038484 100644
--- a/icontrol/session.py
+++ b/icontrol/session.py
@@ -66,6 +66,7 @@ from icontrol.exceptions import InvalidInstanceNameOrFolder
from icontrol.exceptions import InvalidPrefixCollection
from icontrol.exceptions import InvalidScheme
from icontrol.exceptions import InvalidSuffixCollection
+from icontrol.exceptions import InvalidURIComponentPart
import logging
import requests
@@ -106,19 +107,19 @@ def _validate_prefix_collections(prefix_collections):
return True
-def _validate_name_or_partition(inst_or_partition):
+def _validate_name_partition_subpath(element):
# '/' and '~' are illegal characters
- if inst_or_partition == '':
+ if element == '':
return True
- if '~' in inst_or_partition:
+ if '~' in element:
error_message =\
"instance names and partitions cannot contain '~', but it's: %s"\
- % inst_or_partition
+ % element
raise InvalidInstanceNameOrFolder(error_message)
- elif '/' in inst_or_partition:
+ elif '/' in element:
error_message =\
"instance names and partitions cannot contain '/', but it's: %s"\
- % inst_or_partition
+ % element
raise InvalidInstanceNameOrFolder(error_message)
return True
@@ -142,17 +143,19 @@ def _validate_suffix_collections(suffix_collections):
return True
-def _validate_uri_parts(base_uri, partition, name, suffix_collections):
+def _validate_uri_parts(
+ base_uri, partition, name, sub_path, suffix_collections):
# Apply the above validators to the correct components.
_validate_icruri(base_uri)
- _validate_name_or_partition(partition)
- _validate_name_or_partition(name)
+ _validate_name_partition_subpath(partition)
+ _validate_name_partition_subpath(name)
+ _validate_name_partition_subpath(sub_path)
if suffix_collections:
_validate_suffix_collections(suffix_collections)
return True
-def generate_bigip_uri(base_uri, partition, name, suffix, **kwargs):
+def generate_bigip_uri(base_uri, partition, name, sub_path, suffix, **kwargs):
'''(str, str, str) --> str
This function checks the supplied elements to see if each conforms to
@@ -171,12 +174,19 @@ def generate_bigip_uri(base_uri, partition, name, suffix, **kwargs):
params={'a':1}, suffix='/thwocky')
'https://0.0.0.0/mgmt/tm/ltm/nat/thwocky'
'''
- _validate_uri_parts(base_uri, name, partition, suffix)
+ _validate_uri_parts(base_uri, partition, name, sub_path, suffix)
if partition != '':
- partition = '~'+partition
+ partition = '~' + partition
+ else:
+ if sub_path:
+ msg = 'When giving the subPath component include partition ' \
+ 'as well.'
+ raise InvalidURIComponentPart(msg)
+ if sub_path != '' and partition != '':
+ sub_path = '~' + sub_path
if name != '' and partition != '':
- name = '~'+name
- tilded_partition_and_instance = partition+name
+ name = '~' + name
+ tilded_partition_and_instance = partition + sub_path + name
if suffix and not tilded_partition_and_instance:
suffix = suffix.lstrip('/')
REST_uri = base_uri + tilded_partition_and_instance + suffix
@@ -203,11 +213,12 @@ def decorate_HTTP_verb_method(method):
def wrapper(self, RIC_base_uri, **kwargs):
partition = kwargs.pop('partition', '')
name = kwargs.pop('name', '')
+ sub_path = kwargs.pop('subPath', '')
suffix = kwargs.pop('suffix', '')
uri_as_parts = kwargs.pop('uri_as_parts', False)
if uri_as_parts:
REST_uri = generate_bigip_uri(RIC_base_uri, partition, name,
- suffix, **kwargs)
+ sub_path, suffix, **kwargs)
else:
REST_uri = RIC_base_uri
pre_message = "%s WITH uri: %s AND suffix: %s AND kwargs: %s" %\
| F5Networks/f5-icontrol-rest-python | 5c43b0f6424a5f495c50fd2a318e172d5c3d7e37 | diff --git a/conftest.py b/conftest.py
index d11adba..b882e7b 100644
--- a/conftest.py
+++ b/conftest.py
@@ -93,3 +93,8 @@ def POST_URL(opt_bigip, opt_port):
def FAKE_URL(opt_bigip, opt_port):
fake_url = 'https://' + opt_bigip + ':' + opt_port + '/mgmt/tm/bogus/'
return fake_url
+
+
[email protected]
+def BASE_URL(opt_bigip):
+ return 'https://' + opt_bigip + '/mgmt/tm/'
diff --git a/icontrol/test/test_session.py b/icontrol/test/test_session.py
index df65187..e1aa136 100644
--- a/icontrol/test/test_session.py
+++ b/icontrol/test/test_session.py
@@ -37,6 +37,17 @@ def uparts():
parts_dict = {'base_uri': 'https://0.0.0.0/mgmt/tm/root/RESTiface/',
'partition': 'BIGCUSTOMER',
'name': 'foobar1',
+ 'sub_path': '',
+ 'suffix': '/members/m1'}
+ return parts_dict
+
+
[email protected]()
+def uparts_with_subpath():
+ parts_dict = {'base_uri': 'https://0.0.0.0/mgmt/tm/root/RESTiface/',
+ 'partition': 'BIGCUSTOMER',
+ 'name': 'foobar1',
+ 'sub_path': 'sp',
'suffix': '/members/m1'}
return parts_dict
@@ -116,6 +127,14 @@ def test_correct_uri_construction_partitionless(uparts):
assert uri == 'https://0.0.0.0/mgmt/tm/root/RESTiface/foobar1/members/m1'
+def test_correct_uri_construction_partitionless_subpath(uparts_with_subpath):
+ uparts_with_subpath['partition'] = ''
+ with pytest.raises(session.InvalidURIComponentPart) as IC:
+ session.generate_bigip_uri(**uparts_with_subpath)
+ assert str(IC.value) == \
+ 'When giving the subPath component include partition as well.'
+
+
def test_correct_uri_construction_nameless(uparts):
uparts['name'] = ''
uri = session.generate_bigip_uri(**uparts)
@@ -123,6 +142,13 @@ def test_correct_uri_construction_nameless(uparts):
"https://0.0.0.0/mgmt/tm/root/RESTiface/~BIGCUSTOMER/members/m1"
+def test_correct_uri_construction_nameless_subpath(uparts_with_subpath):
+ uparts_with_subpath['name'] = ''
+ uri = session.generate_bigip_uri(**uparts_with_subpath)
+ assert uri ==\
+ "https://0.0.0.0/mgmt/tm/root/RESTiface/~BIGCUSTOMER~sp/members/m1"
+
+
def test_correct_uri_construction_partitionless_and_nameless(uparts):
uparts['partition'] = ''
uparts['name'] = ''
@@ -130,6 +156,16 @@ def test_correct_uri_construction_partitionless_and_nameless(uparts):
assert uri == "https://0.0.0.0/mgmt/tm/root/RESTiface/members/m1"
+def test_correct_uri_construction_partitionless_and_nameless_subpath(
+ uparts_with_subpath):
+ uparts_with_subpath['partition'] = ''
+ uparts_with_subpath['name'] = ''
+ with pytest.raises(session.InvalidURIComponentPart) as IC:
+ session.generate_bigip_uri(**uparts_with_subpath)
+ assert str(IC.value) == \
+ 'When giving the subPath component include partition as well.'
+
+
def test_correct_uri_construction_partition_name_and_suffixless(uparts):
uparts['partition'] = ''
uparts['name'] = ''
@@ -138,6 +174,17 @@ def test_correct_uri_construction_partition_name_and_suffixless(uparts):
assert uri == "https://0.0.0.0/mgmt/tm/root/RESTiface/"
+def test_correct_uri_construction_partition_name_and_suffixless_subpath(
+ uparts_with_subpath):
+ uparts_with_subpath['partition'] = ''
+ uparts_with_subpath['name'] = ''
+ uparts_with_subpath['suffix'] = ''
+ with pytest.raises(session.InvalidURIComponentPart) as IC:
+ session.generate_bigip_uri(**uparts_with_subpath)
+ assert str(IC.value) == \
+ 'When giving the subPath component include partition as well.'
+
+
def test_correct_uri_construction_partitionless_and_suffixless(uparts):
uparts['partition'] = ''
uparts['suffix'] = ''
@@ -145,6 +192,16 @@ def test_correct_uri_construction_partitionless_and_suffixless(uparts):
assert uri == 'https://0.0.0.0/mgmt/tm/root/RESTiface/foobar1'
+def test_correct_uri_construction_partitionless_and_suffixless_subpath(
+ uparts_with_subpath):
+ uparts_with_subpath['partition'] = ''
+ uparts_with_subpath['suffix'] = ''
+ with pytest.raises(session.InvalidURIComponentPart) as IC:
+ session.generate_bigip_uri(**uparts_with_subpath)
+ assert str(IC.value) == \
+ 'When giving the subPath component include partition as well.'
+
+
def test_correct_uri_construction_nameless_and_suffixless(uparts):
uparts['name'] = ''
uparts['suffix'] = ''
@@ -152,6 +209,14 @@ def test_correct_uri_construction_nameless_and_suffixless(uparts):
assert uri == 'https://0.0.0.0/mgmt/tm/root/RESTiface/~BIGCUSTOMER'
+def test_correct_uri_construction_nameless_and_suffixless_subpath(
+ uparts_with_subpath):
+ uparts_with_subpath['name'] = ''
+ uparts_with_subpath['suffix'] = ''
+ uri = session.generate_bigip_uri(**uparts_with_subpath)
+ assert uri == 'https://0.0.0.0/mgmt/tm/root/RESTiface/~BIGCUSTOMER~sp'
+
+
# Test exception handling
def test_wrapped_delete_success(iCRS, uparts):
iCRS.delete(uparts['base_uri'], partition='AFN', name='AIN',
diff --git a/test/functional/test_session.py b/test/functional/test_session.py
index ef4e613..568d5b1 100644
--- a/test/functional/test_session.py
+++ b/test/functional/test_session.py
@@ -35,6 +35,64 @@ nat_data = {
}
+iapp_templ_data = {
+ "name": "test_templ",
+ "partition": "Common",
+ "actions": {
+ "definition":
+ {
+ "implementation": '''tmsh::create {
+ ltm pool /Common/test_serv.app/test_pool
+ load-balancing-mode least-connections-node
+ members replace-all-with {128.0.0.2:8080{address 128.0.0.2}}
+ }''',
+ "presentation": ""
+ }
+ }
+}
+
+
+iapp_serv_data = {
+ "name": "test_serv",
+ "partition": "Common",
+ "template": "/Common/test_templ"
+}
+
+
[email protected]
+def setup_subpath(request, ICR, BASE_URL):
+ app_templ_url = BASE_URL + 'sys/application/template/'
+ app_serv_url = BASE_URL + 'sys/application/service/'
+
+ def teardown_iapp():
+ try:
+ ICR.delete(
+ app_serv_url, uri_as_parts=True,
+ name='test_serv', partition='Common',
+ subPath='test_serv.app')
+ except Exception:
+ pass
+
+ try:
+ ICR.delete(
+ app_templ_url, uri_as_parts=True,
+ name='test_templ', partition='Common')
+ except Exception:
+ pass
+
+ teardown_iapp()
+ ICR.post(app_templ_url, json=iapp_templ_data)
+ try:
+ ICR.post(app_serv_url, json=iapp_serv_data)
+ except HTTPError as ex:
+ # The creation of an iapp service does cause a 404 error in bigip
+ # versions up to but excluding 12.0
+ if ex.response.status_code == 404:
+ pass
+ request.addfinalizer(teardown_iapp)
+ return app_serv_url
+
+
def teardown_nat(request, icr, url, name, partition):
'''Remove the nat object that we create during a test '''
def teardown():
@@ -69,6 +127,23 @@ def invalid_token_credentials(user, password, url):
'Authentication required!' in err.value.message)
+def test_get_with_subpath(setup_subpath, ICR, BASE_URL):
+ # The iapp creates a pool. We should be able to get that pool with subPath
+ app_serv_url = setup_subpath
+ res = ICR.get(
+ app_serv_url, name='test_serv',
+ partition='Common', subPath='test_serv.app')
+ assert res.status_code == 200
+ pool_uri = BASE_URL + 'ltm/pool/'
+ pool_res = ICR.get(
+ pool_uri, name='test_pool',
+ partition='Common', subPath='test_serv.app')
+ assert pool_res.status_code == 200
+ data = pool_res.json()
+ assert data['items'][0]['subPath'] == 'test_serv.app'
+ assert data['items'][0]['name'] == 'test_pool'
+
+
def test_get(ICR, GET_URL):
'''Test a GET request to a valid url
| Requests should be able to specify the subPath in addition to partition and name
In order to service the issue https://github.com/F5Networks/f5-common-python/issues/468, the icontrolsession needs to be able to support a subPath keyword argument to requests. This allows a consumer to get access to an object created in an iapp or an object in the drafts folder (in BIG-IP 12.1). | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"icontrol/test/test_session.py::test_correct_uri_construction_partitionless_and_nameless_subpath",
"icontrol/test/test_session.py::test_correct_uri_construction_nameless_subpath",
"icontrol/test/test_session.py::test_correct_uri_construction_partitionless_and_suffixless_subpath",
"icontrol/test/test_session.py::test_correct_uri_construction_partitionless_subpath",
"icontrol/test/test_session.py::test_correct_uri_construction_nameless_and_suffixless_subpath",
"icontrol/test/test_session.py::test_correct_uri_construction_partition_name_and_suffixless_subpath"
] | [
"icontrol/test/test_session.py::test_wrapped_delete_207_fail",
"icontrol/test/test_session.py::test_wrapped_post_success_with_json_and_data",
"icontrol/test/test_session.py::test_wrapped_get_207_fail",
"icontrol/test/test_session.py::test_wrapped_put_success_with_data",
"icontrol/test/test_session.py::test_wrapped_post_207_fail",
"icontrol/test/test_session.py::test_wrapped_post_success_with_json",
"icontrol/test/test_session.py::test_incorrect_uri_construction_illegal_suffix_nonslash_first",
"icontrol/test/test_session.py::test_correct_uri_construction_partitionless_and_suffixless",
"icontrol/test/test_session.py::test_wrapped_put_207_fail",
"icontrol/test/test_session.py::test_incorrect_uri_construction_illegal_suffix_slash_last",
"icontrol/test/test_session.py::test_wrapped_put_success",
"icontrol/test/test_session.py::test_iCRS_with_invalid_construction",
"icontrol/test/test_session.py::test_wrapped_delete_success",
"icontrol/test/test_session.py::test_wrapped_get_success",
"icontrol/test/test_session.py::test_wrapped_patch_207_fail",
"icontrol/test/test_session.py::test___init__with_2_9_1_requests_pkg",
"icontrol/test/test_session.py::test_wrapped_post_success_with_data",
"icontrol/test/test_session.py::test_incorrect_uri_construction_bad_mgmt_path",
"icontrol/test/test_session.py::test_incorrect_uri_construction_illegal_tilde_partition_char",
"icontrol/test/test_session.py::test_wrapped_post_success",
"icontrol/test/test_session.py::test_wrapped_get_success_with_suffix",
"icontrol/test/test_session.py::test_incorrect_uri_construction_bad_scheme",
"icontrol/test/test_session.py::test___init__with_older_requests_pkg",
"icontrol/test/test_session.py::test_correct_uri_construction_nameless",
"icontrol/test/test_session.py::test_incorrect_uri_construction_illegal_slash_partition_char",
"icontrol/test/test_session.py::test_incorrect_uri_construction_bad_base_nonslash_last",
"icontrol/test/test_session.py::test_correct_uri_construction_partition_name_and_suffixless",
"icontrol/test/test_session.py::test_correct_uri_construction_nameless_and_suffixless",
"icontrol/test/test_session.py::test___init__with_newer_requests_pkg",
"icontrol/test/test_session.py::test_correct_uri_construction_partitionless",
"icontrol/test/test_session.py::test_wrapped_patch_success",
"icontrol/test/test_session.py::test_correct_uri_construction_partitionless_and_nameless"
] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2016-09-21T04:29:30Z" | apache-2.0 |
|
F5Networks__f5-icontrol-rest-python-124 | diff --git a/icontrol/session.py b/icontrol/session.py
index 6abdb0a..376541f 100644
--- a/icontrol/session.py
+++ b/icontrol/session.py
@@ -58,7 +58,7 @@ against the BigIP REST Server, by pre- and post- processing the above methods.
"""
from distutils.version import StrictVersion
-import functools
+from icontrol import __version__ as version
from icontrol.authtoken import iControlRESTTokenAuth
from icontrol.exceptions import iControlUnexpectedHTTPError
from icontrol.exceptions import InvalidBigIP_ICRURI
@@ -67,6 +67,8 @@ from icontrol.exceptions import InvalidPrefixCollection
from icontrol.exceptions import InvalidScheme
from icontrol.exceptions import InvalidSuffixCollection
from icontrol.exceptions import InvalidURIComponentPart
+
+import functools
import logging
import requests
@@ -266,9 +268,20 @@ class iControlRESTSession(object):
All transactions are Trust On First Use (TOFU) to the BigIP device,
since no PKI exists for this purpose in general, hence the
"disable_warnings" statement.
+
+ :param str username: The user to connect with.
+ :param str password: The password of the user.
+ :param int timeout: The timeout, in seconds, to wait before closing
+ the session.
+ :param bool token: True or False, specifying whether to use token
+ authentication or not.
+ :param str user_agent: A string to append to the user agent header
+ that is sent during a session.
"""
timeout = kwargs.pop('timeout', 30)
token_auth = kwargs.pop('token', None)
+ user_agent = kwargs.pop('user_agent', None)
+
if kwargs:
raise TypeError('Unexpected **kwargs: %r' % kwargs)
requests_version = requests.__version__
@@ -295,6 +308,11 @@ class iControlRESTSession(object):
self.session.verify = False # XXXmake TOFU
self.session.headers.update({'Content-Type': 'application/json'})
+ # Add a user agent for this library and any specified UA
+ self.append_user_agent('f5-icontrol-rest-python/' + version)
+ if user_agent:
+ self.append_user_agent(user_agent)
+
@decorate_HTTP_verb_method
def delete(self, uri, **kwargs):
"""Sends a HTTP DELETE command to the BIGIP REST Server.
@@ -409,8 +427,21 @@ class iControlRESTSession(object):
:type json: dict
:param name: The object name that will be appended to the uri
:type name: str
- :arg partition: The partition name that will be appened to the uri
+ :arg partition: The partition name that will be appended to the uri
:type partition: str
:param **kwargs: The :meth:`reqeusts.Session.put` optional params
"""
return self.session.put(uri, data=data, **kwargs)
+
+ def append_user_agent(self, user_agent):
+ """Append text to the User-Agent header for the request.
+
+ Use this method to update the User-Agent header by appending the
+ given string to the session's User-Agent header separated by a space.
+
+ :param user_agent: A string to append to the User-Agent header
+ :type user_agent: str
+ """
+ old_ua = self.session.headers.get('User-Agent', '')
+ ua = old_ua + ' ' + user_agent
+ self.session.headers['User-Agent'] = ua.strip()
| F5Networks/f5-icontrol-rest-python | 4c5067c403a0018bd7b26bc64f43056a1fc54b6e | diff --git a/icontrol/test/unit/test_session.py b/icontrol/test/unit/test_session.py
index e1aa136..240505c 100644
--- a/icontrol/test/unit/test_session.py
+++ b/icontrol/test/unit/test_session.py
@@ -15,8 +15,11 @@
import mock
import pytest
+from icontrol import __version__ as VERSION
from icontrol import session
+UA = 'f5-icontrol-rest-python/%s' % VERSION
+
@pytest.fixture()
def iCRS():
@@ -353,3 +356,32 @@ def test___init__with_2_9_1_requests_pkg():
mock_requests.__version__ = '2.9.1'
session.iControlRESTSession('test_name', 'test_pw')
assert mock_requests.packages.urllib3.disable_warnings.called is False
+
+
+def test___init__user_agent():
+ icrs = session.iControlRESTSession('admin', 'admin')
+ assert UA in icrs.session.headers['User-Agent']
+
+
+def test__append_user_agent():
+ icrs = session.iControlRESTSession('admin', 'admin')
+ icrs.append_user_agent('test-user-agent/1.1.1')
+ assert icrs.session.headers['User-Agent'].endswith('test-user-agent/1.1.1')
+ assert UA in icrs.session.headers['User-Agent']
+
+
+def test_append_user_agent_empty_start():
+ icrs = session.iControlRESTSession('admin', 'admin')
+ icrs.session.headers['User-Agent'] = ''
+ icrs.append_user_agent('test-agent')
+ assert icrs.session.headers['User-Agent'] == 'test-agent'
+
+
+def test___init__with_additional_user_agent():
+ icrs = session.iControlRESTSession(
+ 'admin',
+ 'admin',
+ user_agent='test-agent/1.2.3'
+ )
+ assert icrs.session.headers['User-Agent'].endswith('test-agent/1.2.3')
+ assert 'f5-icontrol-rest-python' in icrs.session.headers['User-Agent']
| Update the User-Agent to include library and version
Add the library and version to the user agent header that is sent to the BIG-IP so that it can be logged to track usage and help debug problems. This needs to be done in a way that allows users of this library to add additional strings to the end of the header.
The user agent string should be `f5-icontrol-rest-python/<version>` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"icontrol/test/unit/test_session.py::test__append_user_agent",
"icontrol/test/unit/test_session.py::test_append_user_agent_empty_start",
"icontrol/test/unit/test_session.py::test___init__user_agent",
"icontrol/test/unit/test_session.py::test___init__with_additional_user_agent"
] | [
"icontrol/test/unit/test_session.py::test_incorrect_uri_construction_bad_scheme",
"icontrol/test/unit/test_session.py::test_correct_uri_construction_partitionless_subpath",
"icontrol/test/unit/test_session.py::test_iCRS_with_invalid_construction",
"icontrol/test/unit/test_session.py::test_incorrect_uri_construction_illegal_suffix_slash_last",
"icontrol/test/unit/test_session.py::test_wrapped_get_success",
"icontrol/test/unit/test_session.py::test_correct_uri_construction_partitionless_and_nameless_subpath",
"icontrol/test/unit/test_session.py::test_wrapped_put_success",
"icontrol/test/unit/test_session.py::test_correct_uri_construction_nameless_and_suffixless",
"icontrol/test/unit/test_session.py::test_correct_uri_construction_nameless_subpath",
"icontrol/test/unit/test_session.py::test_correct_uri_construction_partitionless_and_suffixless",
"icontrol/test/unit/test_session.py::test_wrapped_post_success",
"icontrol/test/unit/test_session.py::test_wrapped_get_success_with_suffix",
"icontrol/test/unit/test_session.py::test___init__with_older_requests_pkg",
"icontrol/test/unit/test_session.py::test_incorrect_uri_construction_illegal_suffix_nonslash_first",
"icontrol/test/unit/test_session.py::test_correct_uri_construction_partitionless",
"icontrol/test/unit/test_session.py::test___init__with_newer_requests_pkg",
"icontrol/test/unit/test_session.py::test_incorrect_uri_construction_illegal_slash_partition_char",
"icontrol/test/unit/test_session.py::test_correct_uri_construction_partitionless_and_nameless",
"icontrol/test/unit/test_session.py::test_correct_uri_construction_partition_name_and_suffixless",
"icontrol/test/unit/test_session.py::test_wrapped_put_207_fail",
"icontrol/test/unit/test_session.py::test_correct_uri_construction_nameless_and_suffixless_subpath",
"icontrol/test/unit/test_session.py::test_incorrect_uri_construction_illegal_tilde_partition_char",
"icontrol/test/unit/test_session.py::test_correct_uri_construction_nameless",
"icontrol/test/unit/test_session.py::test_wrapped_put_success_with_data",
"icontrol/test/unit/test_session.py::test_wrapped_post_success_with_json_and_data",
"icontrol/test/unit/test_session.py::test_wrapped_post_207_fail",
"icontrol/test/unit/test_session.py::test_correct_uri_construction_partition_name_and_suffixless_subpath",
"icontrol/test/unit/test_session.py::test_wrapped_patch_207_fail",
"icontrol/test/unit/test_session.py::test_incorrect_uri_construction_bad_base_nonslash_last",
"icontrol/test/unit/test_session.py::test_wrapped_post_success_with_data",
"icontrol/test/unit/test_session.py::test_incorrect_uri_construction_bad_mgmt_path",
"icontrol/test/unit/test_session.py::test_correct_uri_construction_partitionless_and_suffixless_subpath",
"icontrol/test/unit/test_session.py::test_wrapped_delete_success",
"icontrol/test/unit/test_session.py::test_wrapped_post_success_with_json",
"icontrol/test/unit/test_session.py::test_wrapped_get_207_fail",
"icontrol/test/unit/test_session.py::test___init__with_2_9_1_requests_pkg",
"icontrol/test/unit/test_session.py::test_wrapped_patch_success",
"icontrol/test/unit/test_session.py::test_wrapped_delete_207_fail"
] | {
"failed_lite_validators": [
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2016-11-23T05:04:06Z" | apache-2.0 |
|
F5Networks__f5-icontrol-rest-python-125 | diff --git a/icontrol/session.py b/icontrol/session.py
index 376541f..d05ec3f 100644
--- a/icontrol/session.py
+++ b/icontrol/session.py
@@ -86,11 +86,22 @@ def _validate_icruri(base_uri):
scheme, netloc, path, _, _ = urlsplit(base_uri)
if scheme != 'https':
raise InvalidScheme(scheme)
- if not path.startswith('/mgmt/tm/'):
- error_message = "The path must start with '/mgmt/tm/'!! But it's:" +\
- " '%s'" % path[:10]
+
+ if path.startswith('/mgmt/tm/'):
+ # Most of the time this is BIG-IP
+ sub_path = path[9:]
+ elif path.startswith('/mgmt/cm/'):
+ # This can also be in iWorkflow or BIG-IQ
+ sub_path = path[9:]
+ elif path.startswith('/mgmt/shared/'):
+ # This can be iWorkflow or BIG-IQ
+ sub_path = path[13:]
+ else:
+ error_message = "The path must start with either '/mgmt/tm/'," \
+ "'/mgmt/cm/', or '/mgmt/shared/'! But it's:" \
+ " '%s'" % path
raise InvalidBigIP_ICRURI(error_message)
- return _validate_prefix_collections(path[9:])
+ return _validate_prefix_collections(sub_path)
def _validate_prefix_collections(prefix_collections):
| F5Networks/f5-icontrol-rest-python | 6499f3c6a59ebaa3863b9230a52c200b4f1762a4 | diff --git a/icontrol/test/unit/test_session.py b/icontrol/test/unit/test_session.py
index 240505c..9742ae4 100644
--- a/icontrol/test/unit/test_session.py
+++ b/icontrol/test/unit/test_session.py
@@ -55,6 +55,26 @@ def uparts_with_subpath():
return parts_dict
[email protected]()
+def uparts_shared():
+ parts_dict = {'base_uri': 'https://0.0.0.0/mgmt/shared/root/RESTiface/',
+ 'partition': 'BIGCUSTOMER',
+ 'name': 'foobar1',
+ 'sub_path': '',
+ 'suffix': '/members/m1'}
+ return parts_dict
+
+
[email protected]()
+def uparts_cm():
+ parts_dict = {'base_uri': 'https://0.0.0.0/mgmt/cm/root/RESTiface/',
+ 'partition': 'BIGCUSTOMER',
+ 'name': 'foobar1',
+ 'sub_path': '',
+ 'suffix': '/members/m1'}
+ return parts_dict
+
+
# Test invalid args
def test_iCRS_with_invalid_construction():
with pytest.raises(TypeError) as UTE:
@@ -74,8 +94,7 @@ def test_incorrect_uri_construction_bad_mgmt_path(uparts):
uparts['base_uri'] = 'https://0.0.0.0/magmt/tm/root/RESTiface'
with pytest.raises(session.InvalidBigIP_ICRURI) as IR:
session.generate_bigip_uri(**uparts)
- assert str(IR.value) ==\
- "The path must start with '/mgmt/tm/'!! But it's: '/magmt/tm/'"
+ assert "But it's: '/magmt/tm/root/RESTiface'" in str(IR.value)
def test_incorrect_uri_construction_bad_base_nonslash_last(uparts):
@@ -220,6 +239,20 @@ def test_correct_uri_construction_nameless_and_suffixless_subpath(
assert uri == 'https://0.0.0.0/mgmt/tm/root/RESTiface/~BIGCUSTOMER~sp'
+def test_correct_uri_construction_mgmt_shared(uparts_shared):
+ uparts_shared['name'] = ''
+ uparts_shared['suffix'] = ''
+ uri = session.generate_bigip_uri(**uparts_shared)
+ assert uri == 'https://0.0.0.0/mgmt/shared/root/RESTiface/~BIGCUSTOMER'
+
+
+def test_correct_uri_construction_mgmt_cm(uparts_cm):
+ uparts_cm['name'] = ''
+ uparts_cm['suffix'] = ''
+ uri = session.generate_bigip_uri(**uparts_cm)
+ assert uri == 'https://0.0.0.0/mgmt/cm/root/RESTiface/~BIGCUSTOMER'
+
+
# Test exception handling
def test_wrapped_delete_success(iCRS, uparts):
iCRS.delete(uparts['base_uri'], partition='AFN', name='AIN',
| support rest-proxy URI
iWorkflow / BIG-IQ (?) support REST proxy URI. This makes it possible to apply tenant RBAC on the REST endpoints (i.e. limit a user to only be able to modify a single BIG-IP LTM pool in a single Partition).
Documented here: https://devcentral.f5.com/wiki/iControl.REST_proxy_APIs.ashx
Example of one of the changes required (this is not meant to be a "good" example, but it gets the job done). This was done to monkey patch the library:
```
def _validate_icruri(base_uri):
# The icr_uri should specify https, the server name/address, and the path
# to the REST-or-tm management interface "/mgmt/tm/"
scheme, netloc, path, _, _ = urlsplit(base_uri)
if scheme != 'https':
raise InvalidScheme(scheme)
if path.startswith('/mgmt/shared/'):
return icontrol.session._validate_prefix_collections(path[9:])
if not path.startswith('/mgmt/tm/'):
error_message = "The path must start with '/mgmt/tm/'!! But it's:" +\
" '%s'" % path[:10]
raise InvalidBigIP_ICRURI(error_message)
return icontrol.session._validate_prefix_collections(path[9:])
icontrol.session._validate_icruri = _validate_icruri
```
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"icontrol/test/unit/test_session.py::test_correct_uri_construction_mgmt_shared",
"icontrol/test/unit/test_session.py::test_incorrect_uri_construction_bad_mgmt_path",
"icontrol/test/unit/test_session.py::test_correct_uri_construction_mgmt_cm"
] | [
"icontrol/test/unit/test_session.py::test_wrapped_delete_207_fail",
"icontrol/test/unit/test_session.py::test_correct_uri_construction_partitionless_and_nameless",
"icontrol/test/unit/test_session.py::test_wrapped_get_success_with_suffix",
"icontrol/test/unit/test_session.py::test_wrapped_post_success_with_json",
"icontrol/test/unit/test_session.py::test_correct_uri_construction_partitionless_and_nameless_subpath",
"icontrol/test/unit/test_session.py::test_wrapped_get_success",
"icontrol/test/unit/test_session.py::test_incorrect_uri_construction_illegal_tilde_partition_char",
"icontrol/test/unit/test_session.py::test_correct_uri_construction_nameless_and_suffixless_subpath",
"icontrol/test/unit/test_session.py::test_correct_uri_construction_partition_name_and_suffixless",
"icontrol/test/unit/test_session.py::test_append_user_agent_empty_start",
"icontrol/test/unit/test_session.py::test___init__with_older_requests_pkg",
"icontrol/test/unit/test_session.py::test_wrapped_post_207_fail",
"icontrol/test/unit/test_session.py::test_correct_uri_construction_partitionless_and_suffixless",
"icontrol/test/unit/test_session.py::test___init__user_agent",
"icontrol/test/unit/test_session.py::test_wrapped_post_success_with_json_and_data",
"icontrol/test/unit/test_session.py::test_correct_uri_construction_nameless_subpath",
"icontrol/test/unit/test_session.py::test_correct_uri_construction_nameless_and_suffixless",
"icontrol/test/unit/test_session.py::test_incorrect_uri_construction_illegal_slash_partition_char",
"icontrol/test/unit/test_session.py::test_correct_uri_construction_nameless",
"icontrol/test/unit/test_session.py::test_wrapped_post_success_with_data",
"icontrol/test/unit/test_session.py::test_wrapped_patch_success",
"icontrol/test/unit/test_session.py::test_correct_uri_construction_partitionless",
"icontrol/test/unit/test_session.py::test_wrapped_delete_success",
"icontrol/test/unit/test_session.py::test_wrapped_patch_207_fail",
"icontrol/test/unit/test_session.py::test___init__with_2_9_1_requests_pkg",
"icontrol/test/unit/test_session.py::test___init__with_newer_requests_pkg",
"icontrol/test/unit/test_session.py::test__append_user_agent",
"icontrol/test/unit/test_session.py::test_wrapped_get_207_fail",
"icontrol/test/unit/test_session.py::test_incorrect_uri_construction_illegal_suffix_nonslash_first",
"icontrol/test/unit/test_session.py::test_wrapped_put_success_with_data",
"icontrol/test/unit/test_session.py::test_correct_uri_construction_partitionless_and_suffixless_subpath",
"icontrol/test/unit/test_session.py::test_wrapped_put_success",
"icontrol/test/unit/test_session.py::test_wrapped_post_success",
"icontrol/test/unit/test_session.py::test_incorrect_uri_construction_illegal_suffix_slash_last",
"icontrol/test/unit/test_session.py::test_incorrect_uri_construction_bad_base_nonslash_last",
"icontrol/test/unit/test_session.py::test___init__with_additional_user_agent",
"icontrol/test/unit/test_session.py::test_wrapped_put_207_fail",
"icontrol/test/unit/test_session.py::test_correct_uri_construction_partitionless_subpath",
"icontrol/test/unit/test_session.py::test_correct_uri_construction_partition_name_and_suffixless_subpath",
"icontrol/test/unit/test_session.py::test_incorrect_uri_construction_bad_scheme",
"icontrol/test/unit/test_session.py::test_iCRS_with_invalid_construction"
] | {
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
} | "2016-12-22T01:35:09Z" | apache-2.0 |
|
FactoryBoy__factory_boy-1006 | diff --git a/docs/reference.rst b/docs/reference.rst
index a7e9be0..9efd1a2 100644
--- a/docs/reference.rst
+++ b/docs/reference.rst
@@ -907,21 +907,22 @@ return value of the method:
Transformer
"""""""""""
-.. class:: Transformer(transform, value)
+.. class:: Transformer(default_value, *, transform)
A :class:`Transformer` applies a ``transform`` function to the provided value
before to set the transformed value on the generated object.
-It expects two arguments:
+It expects one positional argument and one keyword argument:
-- ``transform``: function taking the value as parameter and returning the
+- ``default_value``: the default value, which passes through the ``transform``
+ function.
+- ``transform``: a function taking the value as parameter and returning the
transformed value,
-- ``value``: the default value.
.. code-block:: python
- class UpperFactory(Factory):
- name = Transformer(lambda x: x.upper(), "Joe")
+ class UpperFactory(factory.Factory):
+ name = factory.Transformer("Joe", transform=str.upper)
class Meta:
model = Upper
@@ -933,6 +934,14 @@ It expects two arguments:
>>> UpperFactory(name="John").name
'JOHN'
+Disabling
+~~~~~~~~~
+To disable a :class:`Transformer`, wrap the value in ``Transformer.Force``:
+
+.. code-block:: pycon
+
+ >>> UpperFactory(name=factory.Transformer.Force("John")).name
+ 'John'
Sequence
""""""""
diff --git a/factory/builder.py b/factory/builder.py
index 9d810fb..e76e755 100644
--- a/factory/builder.py
+++ b/factory/builder.py
@@ -2,7 +2,7 @@
import collections
-from . import declarations, enums, errors, utils
+from . import enums, errors, utils
DeclarationWithContext = collections.namedtuple(
'DeclarationWithContext',
@@ -134,6 +134,14 @@ class DeclarationSet:
return '<DeclarationSet: %r>' % self.as_dict()
+def _captures_overrides(declaration_with_context):
+ declaration = declaration_with_context.declaration
+ if enums.get_builder_phase(declaration) == enums.BuilderPhase.ATTRIBUTE_RESOLUTION:
+ return declaration.CAPTURE_OVERRIDES
+ else:
+ return False
+
+
def parse_declarations(decls, base_pre=None, base_post=None):
pre_declarations = base_pre.copy() if base_pre else DeclarationSet()
post_declarations = base_post.copy() if base_post else DeclarationSet()
@@ -156,10 +164,6 @@ def parse_declarations(decls, base_pre=None, base_post=None):
# Set it as `key__`
magic_key = post_declarations.join(k, '')
extra_post[magic_key] = v
- elif k in pre_declarations and isinstance(
- pre_declarations[k].declaration, declarations.Transformer
- ):
- extra_maybenonpost[k] = pre_declarations[k].declaration.function(v)
else:
extra_maybenonpost[k] = v
@@ -173,6 +177,12 @@ def parse_declarations(decls, base_pre=None, base_post=None):
for k, v in extra_maybenonpost.items():
if k in post_overrides:
extra_post_declarations[k] = v
+ elif k in pre_declarations and _captures_overrides(pre_declarations[k]):
+ # Send the overriding value to the existing declaration.
+ # By symmetry with the behaviour of PostGenerationDeclaration,
+ # we send it as `key__` -- i.e under the '' key.
+ magic_key = pre_declarations.join(k, '')
+ extra_pre_declarations[magic_key] = v
else:
# Anything else is pre_declarations
extra_pre_declarations[k] = v
diff --git a/factory/declarations.py b/factory/declarations.py
index 40ae99c..70abe35 100644
--- a/factory/declarations.py
+++ b/factory/declarations.py
@@ -20,6 +20,11 @@ class BaseDeclaration(utils.OrderedBase):
FACTORY_BUILDER_PHASE = enums.BuilderPhase.ATTRIBUTE_RESOLUTION
+ #: Whether this declaration has a special handling for call-time overrides
+ #: (e.g. Tranformer).
+ #: Overridden values will be passed in the `extra` args.
+ CAPTURE_OVERRIDES = False
+
#: Whether to unroll the context before evaluating the declaration.
#: Set to False on declarations that perform their own unrolling.
UNROLL_CONTEXT_BEFORE_EVALUATION = True
@@ -43,6 +48,20 @@ class BaseDeclaration(utils.OrderedBase):
subfactory = factory.base.DictFactory
return step.recurse(subfactory, full_context, force_sequence=step.sequence)
+ def _unwrap_evaluate_pre(self, wrapped, *, instance, step, overrides):
+ """Evaluate a wrapped pre-declaration.
+
+ This is especially useful for declarations wrapping another one,
+ e.g. Maybe or Transformer.
+ """
+ if isinstance(wrapped, BaseDeclaration):
+ return wrapped.evaluate_pre(
+ instance=instance,
+ step=step,
+ overrides=overrides,
+ )
+ return wrapped
+
def evaluate_pre(self, instance, step, overrides):
context = self.unroll_context(instance, step, overrides)
return self.evaluate(instance, step, context)
@@ -100,20 +119,47 @@ class LazyAttribute(BaseDeclaration):
return self.function(instance)
-class Transformer(LazyFunction):
- """Transform value using given function.
+class Transformer(BaseDeclaration):
+ CAPTURE_OVERRIDES = True
+ UNROLL_CONTEXT_BEFORE_EVALUATION = False
- Attributes:
- transform (function): returns the transformed value.
- value: passed as the first argument to the transform function.
- """
+ class Force:
+ """
+ Bypass a transformer's transformation.
- def __init__(self, transform, value, *args, **kwargs):
- super().__init__(transform, *args, **kwargs)
- self.value = value
+ The forced value can be any declaration, and will be evaluated as if it
+ had been passed instead of the Transformer declaration.
+ """
+ def __init__(self, forced_value):
+ self.forced_value = forced_value
- def evaluate(self, instance, step, extra):
- return self.function(self.value)
+ def __repr__(self):
+ return f'Transformer.Force({repr(self.forced_value)})'
+
+ def __init__(self, default, *, transform):
+ super().__init__()
+ self.default = default
+ self.transform = transform
+
+ def evaluate_pre(self, instance, step, overrides):
+ # The call-time value, if present, is set under the "" key.
+ value_or_declaration = overrides.pop("", self.default)
+
+ if isinstance(value_or_declaration, self.Force):
+ bypass_transform = True
+ value_or_declaration = value_or_declaration.forced_value
+ else:
+ bypass_transform = False
+
+ value = self._unwrap_evaluate_pre(
+ value_or_declaration,
+ instance=instance,
+ step=step,
+ overrides=overrides,
+ )
+ if bypass_transform:
+ return value
+ return self.transform(value)
class _UNSPECIFIED:
@@ -492,16 +538,14 @@ class Maybe(BaseDeclaration):
def evaluate_pre(self, instance, step, overrides):
choice = self.decider.evaluate(instance=instance, step=step, extra={})
target = self.yes if choice else self.no
-
- if isinstance(target, BaseDeclaration):
- return target.evaluate_pre(
- instance=instance,
- step=step,
- overrides=overrides,
- )
- else:
- # Flat value (can't be POST_INSTANTIATION, checked in __init__)
- return target
+ # The value can't be POST_INSTANTIATION, checked in __init__;
+ # evaluate it as `evaluate_pre`
+ return self._unwrap_evaluate_pre(
+ target,
+ instance=instance,
+ step=step,
+ overrides=overrides,
+ )
def __repr__(self):
return f'Maybe({self.decider!r}, yes={self.yes!r}, no={self.no!r})'
diff --git a/factory/django.py b/factory/django.py
index dee35d6..87b6fd5 100644
--- a/factory/django.py
+++ b/factory/django.py
@@ -192,8 +192,8 @@ class DjangoModelFactory(base.Factory):
class Password(declarations.Transformer):
- def __init__(self, password, *args, **kwargs):
- super().__init__(make_password, password, *args, **kwargs)
+ def __init__(self, password, transform=make_password, **kwargs):
+ super().__init__(password, transform=transform, **kwargs)
class FileField(declarations.BaseDeclaration):
| FactoryBoy/factory_boy | 53b34d504fad05dd1887a7eb0056ce9516fd4646 | diff --git a/tests/test_declarations.py b/tests/test_declarations.py
index c9458ff..c49bbba 100644
--- a/tests/test_declarations.py
+++ b/tests/test_declarations.py
@@ -134,7 +134,7 @@ class IteratorTestCase(unittest.TestCase):
class TransformerTestCase(unittest.TestCase):
def test_transform(self):
- t = declarations.Transformer(lambda x: x.upper(), 'foo')
+ t = declarations.Transformer('foo', transform=str.upper)
self.assertEqual("FOO", utils.evaluate_declaration(t))
diff --git a/tests/test_transformer.py b/tests/test_transformer.py
index 0065845..b21a8da 100644
--- a/tests/test_transformer.py
+++ b/tests/test_transformer.py
@@ -2,7 +2,7 @@
from unittest import TestCase
-from factory import Factory, Transformer
+import factory
class TransformCounter:
@@ -22,12 +22,13 @@ transform = TransformCounter()
class Upper:
- def __init__(self, name):
+ def __init__(self, name, **extra):
self.name = name
+ self.extra = extra
-class UpperFactory(Factory):
- name = Transformer(transform, "value")
+class UpperFactory(factory.Factory):
+ name = factory.Transformer("value", transform=transform)
class Meta:
model = Upper
@@ -44,3 +45,186 @@ class TransformerTest(TestCase):
def test_transform_kwarg(self):
self.assertEqual("TEST", UpperFactory(name="test").name)
self.assertEqual(transform.calls_count, 1)
+ self.assertEqual("VALUE", UpperFactory().name)
+ self.assertEqual(transform.calls_count, 2)
+
+ def test_transform_faker(self):
+ value = UpperFactory(name=factory.Faker("first_name_female", locale="fr")).name
+ self.assertIs(value.isupper(), True)
+
+ def test_transform_linked(self):
+ value = UpperFactory(
+ name=factory.LazyAttribute(lambda o: o.username.replace(".", " ")),
+ username="john.doe",
+ ).name
+ self.assertEqual(value, "JOHN DOE")
+
+ def test_force_value(self):
+ value = UpperFactory(name=factory.Transformer.Force("Mia")).name
+ self.assertEqual(value, "Mia")
+
+ def test_force_value_declaration(self):
+ """Pretty unlikely use case, but easy enough to cover."""
+ value = UpperFactory(
+ name=factory.Transformer.Force(
+ factory.LazyFunction(lambda: "infinity")
+ )
+ ).name
+ self.assertEqual(value, "infinity")
+
+ def test_force_value_declaration_context(self):
+ """Ensure "forced" values run at the right level."""
+ value = UpperFactory(
+ name=factory.Transformer.Force(
+ factory.LazyAttribute(lambda o: o.username.replace(".", " ")),
+ ),
+ username="john.doe",
+ ).name
+ self.assertEqual(value, "john doe")
+
+
+class TestObject:
+ def __init__(self, one=None, two=None, three=None):
+ self.one = one
+ self.two = two
+ self.three = three
+
+
+class TransformDeclarationFactory(factory.Factory):
+ class Meta:
+ model = TestObject
+ one = factory.Transformer("", transform=str.upper)
+ two = factory.Transformer(factory.Sequence(int), transform=lambda n: n ** 2)
+
+
+class TransformerSequenceTest(TestCase):
+ def test_on_sequence(self):
+ instance = TransformDeclarationFactory(__sequence=2)
+ self.assertEqual(instance.one, "")
+ self.assertEqual(instance.two, 4)
+ self.assertIsNone(instance.three)
+
+ def test_on_user_supplied(self):
+ """A transformer can wrap a call-time declaration"""
+ instance = TransformDeclarationFactory(
+ one=factory.Sequence(str),
+ two=2,
+ __sequence=2,
+ )
+ self.assertEqual(instance.one, "2")
+ self.assertEqual(instance.two, 4)
+ self.assertIsNone(instance.three)
+
+
+class WithMaybeFactory(factory.Factory):
+ class Meta:
+ model = TestObject
+
+ one = True
+ two = factory.Maybe(
+ 'one',
+ yes_declaration=factory.Transformer("yes", transform=str.upper),
+ no_declaration=factory.Transformer("no", transform=str.upper),
+ )
+ three = factory.Maybe('one', no_declaration=factory.Transformer("three", transform=str.upper))
+
+
+class TransformerMaybeTest(TestCase):
+ def test_default_transform(self):
+ instance = WithMaybeFactory()
+ self.assertIs(instance.one, True)
+ self.assertEqual(instance.two, "YES")
+ self.assertIsNone(instance.three)
+
+ def test_yes_transform(self):
+ instance = WithMaybeFactory(one=True)
+ self.assertIs(instance.one, True)
+ self.assertEqual(instance.two, "YES")
+ self.assertIsNone(instance.three)
+
+ def test_no_transform(self):
+ instance = WithMaybeFactory(one=False)
+ self.assertIs(instance.one, False)
+ self.assertEqual(instance.two, "NO")
+ self.assertEqual(instance.three, "THREE")
+
+ def test_override(self):
+ instance = WithMaybeFactory(one=True, two="NI")
+ self.assertIs(instance.one, True)
+ self.assertEqual(instance.two, "NI")
+ self.assertIsNone(instance.three)
+
+
+class RelatedTest(TestCase):
+ def test_default_transform(self):
+ cities = []
+
+ class City:
+ def __init__(self, capital_of, name):
+ self.capital_of = capital_of
+ self.name = name
+ cities.append(self)
+
+ class Country:
+ def __init__(self, name):
+ self.name = name
+
+ class CityFactory(factory.Factory):
+ class Meta:
+ model = City
+
+ name = "Rennes"
+
+ class CountryFactory(factory.Factory):
+ class Meta:
+ model = Country
+
+ name = "France"
+ capital_city = factory.RelatedFactory(
+ CityFactory,
+ factory_related_name="capital_of",
+ name=factory.Transformer("Paris", transform=str.upper),
+ )
+
+ instance = CountryFactory()
+ self.assertEqual(instance.name, "France")
+ [city] = cities
+ self.assertEqual(city.capital_of, instance)
+ self.assertEqual(city.name, "PARIS")
+
+
+class WithTraitFactory(factory.Factory):
+ class Meta:
+ model = TestObject
+
+ class Params:
+ upper_two = factory.Trait(
+ two=factory.Transformer("two", transform=str.upper)
+ )
+ odds = factory.Trait(
+ one="one",
+ three="three",
+ )
+ one = factory.Transformer("one", transform=str.upper)
+
+
+class TransformerTraitTest(TestCase):
+ def test_traits_off(self):
+ instance = WithTraitFactory()
+ self.assertEqual(instance.one, "ONE")
+ self.assertIsNone(instance.two)
+ self.assertIsNone(instance.three)
+
+ def test_trait_transform_applies(self):
+ """A trait-provided transformer should apply to existing values"""
+ instance = WithTraitFactory(upper_two=True)
+ self.assertEqual(instance.one, "ONE")
+ self.assertEqual(instance.two, "TWO")
+ self.assertIsNone(instance.three)
+
+ def test_trait_transform_applies_supplied(self):
+ """A trait-provided transformer should be overridden by caller-provided values"""
+ instance = WithTraitFactory(upper_two=True, two="two")
+ self.assertEqual(instance.one, "ONE")
+ self.assertEqual(instance.two, "two")
+ self.assertIsNone(instance.three)
| The unreleased `Transformer` has a conflicting API with the overall design
#### Description
For most declarations, I can override the default mechanism by passing an explicit value:
```python
>>> UserFactory().email
"[email protected]"
>>> UserFactory(email="[email protected]").email
"[email protected]"
```
If the factory uses a `factory.Transformer` field, I can't force a value:
```python
>>> UserFactory().password
"pbkdf2_sha256$216000$Gj2b9f0Ln1ms$1dBlLEYrtGiwEA219JU831VAdscD2f9nFY37PrNfCDU="
>>> UserFactory(
... password="pbkdf2_sha256$216000$Gj2b9f0Ln1ms$1dBlLEYrtGiwEA219JU831VAdscD2f9nFY37PrNfCDU="
... ).password
"pbkdf2_sha256$216000$EUKlFdNViyB5$vcfPaK6H7pDiQAa9ZIbFoj5oj55tUyHKHDUfxI4GIeY="
```
As a user, it is quite confusing to have very different behaviours for fields; if I have a specific password hash (in this example), I need to have a way to set it.
#### Next steps
I'm not sure we can officially release the `factory.Transformer` (and related code) without addressing this topic first; how can a user bypass the transform? | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_declarations.py::OrderedDeclarationTestCase::test_errors",
"tests/test_declarations.py::DigTestCase::test_chaining",
"tests/test_declarations.py::MaybeTestCase::test_init",
"tests/test_declarations.py::SelfAttributeTestCase::test_default",
"tests/test_declarations.py::SelfAttributeTestCase::test_dot",
"tests/test_declarations.py::SelfAttributeTestCase::test_grandparent",
"tests/test_declarations.py::SelfAttributeTestCase::test_parent",
"tests/test_declarations.py::SelfAttributeTestCase::test_standard",
"tests/test_declarations.py::IteratorTestCase::test_cycle",
"tests/test_declarations.py::IteratorTestCase::test_getter",
"tests/test_declarations.py::IteratorTestCase::test_initial_reset",
"tests/test_declarations.py::IteratorTestCase::test_no_cycling",
"tests/test_declarations.py::IteratorTestCase::test_reset_cycle",
"tests/test_declarations.py::IteratorTestCase::test_reset_no_cycling",
"tests/test_declarations.py::TransformerTestCase::test_transform",
"tests/test_declarations.py::PostGenerationDeclarationTestCase::test_decorator_simple",
"tests/test_declarations.py::PostGenerationDeclarationTestCase::test_post_generation",
"tests/test_declarations.py::FactoryWrapperTestCase::test_cache",
"tests/test_declarations.py::FactoryWrapperTestCase::test_class",
"tests/test_declarations.py::FactoryWrapperTestCase::test_invalid_path",
"tests/test_declarations.py::FactoryWrapperTestCase::test_lazyness",
"tests/test_declarations.py::FactoryWrapperTestCase::test_path",
"tests/test_declarations.py::PostGenerationMethodCallTestCase::test_call_with_method_args",
"tests/test_declarations.py::PostGenerationMethodCallTestCase::test_call_with_method_kwargs",
"tests/test_declarations.py::PostGenerationMethodCallTestCase::test_call_with_passed_extracted_int",
"tests/test_declarations.py::PostGenerationMethodCallTestCase::test_call_with_passed_extracted_iterable",
"tests/test_declarations.py::PostGenerationMethodCallTestCase::test_call_with_passed_extracted_string",
"tests/test_declarations.py::PostGenerationMethodCallTestCase::test_call_with_passed_kwargs",
"tests/test_declarations.py::PostGenerationMethodCallTestCase::test_multi_call_with_multi_method_args",
"tests/test_declarations.py::PostGenerationMethodCallTestCase::test_simplest_setup_and_call",
"tests/test_declarations.py::PostGenerationOrdering::test_post_generation_declaration_order",
"tests/test_transformer.py::TransformerTest::test_force_value",
"tests/test_transformer.py::TransformerTest::test_force_value_declaration",
"tests/test_transformer.py::TransformerTest::test_force_value_declaration_context",
"tests/test_transformer.py::TransformerTest::test_transform_count",
"tests/test_transformer.py::TransformerTest::test_transform_faker",
"tests/test_transformer.py::TransformerTest::test_transform_kwarg",
"tests/test_transformer.py::TransformerTest::test_transform_linked",
"tests/test_transformer.py::TransformerSequenceTest::test_on_sequence",
"tests/test_transformer.py::TransformerSequenceTest::test_on_user_supplied",
"tests/test_transformer.py::TransformerMaybeTest::test_default_transform",
"tests/test_transformer.py::TransformerMaybeTest::test_no_transform",
"tests/test_transformer.py::TransformerMaybeTest::test_override",
"tests/test_transformer.py::TransformerMaybeTest::test_yes_transform",
"tests/test_transformer.py::RelatedTest::test_default_transform",
"tests/test_transformer.py::TransformerTraitTest::test_trait_transform_applies",
"tests/test_transformer.py::TransformerTraitTest::test_trait_transform_applies_supplied",
"tests/test_transformer.py::TransformerTraitTest::test_traits_off"
] | [] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2023-03-17T19:56:38Z" | mit |
|
FactoryBoy__factory_boy-1045 | diff --git a/docs/orms.rst b/docs/orms.rst
index 3839707..5967e1b 100644
--- a/docs/orms.rst
+++ b/docs/orms.rst
@@ -128,7 +128,11 @@ Extra fields
.. method:: __init__(self, password)
- :param str password: Default password.
+ :param str or None password: Default password.
+
+ .. note:: When the ``password`` argument is ``None``, the resulting password is
+ unusable as if ``set_unusable_password()`` were used. This is distinct
+ from setting the password to an empty string.
.. code-block:: python
@@ -149,6 +153,10 @@ Extra fields
>>> other_user = UserFactory.create(password='other_pw')
>>> check_password('other_pw', other_user.password)
True
+ >>> # Set unusable password
+ >>> no_password_user = UserFactory.create(password=None)
+ >>> no_password_user.has_usable_password()
+ False
.. class:: FileField
diff --git a/factory/django.py b/factory/django.py
index 87b6fd5..9526b77 100644
--- a/factory/django.py
+++ b/factory/django.py
@@ -311,7 +311,7 @@ class mute_signals:
logger.debug('mute_signals: Restoring signal handlers %r',
receivers)
- signal.receivers += receivers
+ signal.receivers = receivers + signal.receivers
with signal.lock:
# Django uses some caching for its signals.
# Since we're bypassing signal.connect and signal.disconnect,
| FactoryBoy/factory_boy | 63c2df43ea640adb08d68c2b09c542667691f588 | diff --git a/tests/test_django.py b/tests/test_django.py
index 19729e0..066d792 100644
--- a/tests/test_django.py
+++ b/tests/test_django.py
@@ -941,6 +941,22 @@ class PreventSignalsTestCase(django_test.TestCase):
self.assertTrue(self.handlers.created_during_instantiation.called)
+ def test_signal_receiver_order_restored_after_mute_signals(self):
+ def must_be_first(*args, **kwargs):
+ self.handlers.do_stuff(1)
+
+ def must_be_second(*args, **kwargs):
+ self.handlers.do_stuff(2)
+
+ signals.post_save.connect(must_be_first)
+ with factory.django.mute_signals(signals.post_save):
+ WithSignalsFactory(post_save_signal_receiver=must_be_second)
+ self.assertEqual(self.handlers.do_stuff.call_args_list, [mock.call(2)])
+
+ self.handlers.reset_mock()
+ WithSignalsFactory(post_save_signal_receiver=must_be_second)
+ self.assertEqual(self.handlers.do_stuff.call_args_list, [mock.call(1), mock.call(2)])
+
def test_signal_cache(self):
with factory.django.mute_signals(signals.pre_save, signals.post_save):
signals.post_save.connect(self.handlers.mute_block_receiver)
| Unusable password generator for Django
#### The problem
The recently added `Password` generator for Django is helpful, but it's not clear how to use it to create an unusable password (similar to calling `set_unusable_password` on the generated user).
#### Proposed solution
Django's `set_unusable_password` is a call to `make_password` with `None` as the password argument:
https://github.com/django/django/blob/0b506bfe1ab9f1c38e439c77b3c3f81c8ac663ea/django/contrib/auth/base_user.py#L118-L120
Using `password = factory.django.Password(None)` will actually work (and will allow factory users to override the password if desired). However, currently the password argument to this factory is documented as a string and this option is not mentioned.
#### Extra notes
The default value of the `password` argument to `factory.django.Password` could also be set to `None`. This would make that factory generate unusable passwords by default, which may or may not be desired.
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_django.py::PreventSignalsTestCase::test_signal_receiver_order_restored_after_mute_signals"
] | [
"tests/test_django.py::ModelTests::test_cross_database",
"tests/test_django.py::ModelTests::test_unset_model",
"tests/test_django.py::DjangoPkSequenceTestCase::test_pk_creation",
"tests/test_django.py::DjangoPkSequenceTestCase::test_pk_first",
"tests/test_django.py::DjangoPkSequenceTestCase::test_pk_force_value",
"tests/test_django.py::DjangoPkSequenceTestCase::test_pk_many",
"tests/test_django.py::DjangoGetOrCreateTests::test_missing_arg",
"tests/test_django.py::DjangoGetOrCreateTests::test_multicall",
"tests/test_django.py::DjangoGetOrCreateTests::test_simple_call",
"tests/test_django.py::MultipleGetOrCreateFieldsTest::test_both_defined",
"tests/test_django.py::MultipleGetOrCreateFieldsTest::test_one_defined",
"tests/test_django.py::MultipleGetOrCreateFieldsTest::test_unique_field_not_in_get_or_create",
"tests/test_django.py::DjangoPkForceTestCase::test_force_pk",
"tests/test_django.py::DjangoPkForceTestCase::test_no_pk",
"tests/test_django.py::DjangoPkForceTestCase::test_reuse_pk",
"tests/test_django.py::DjangoModelLoadingTestCase::test_building",
"tests/test_django.py::DjangoModelLoadingTestCase::test_inherited_loading",
"tests/test_django.py::DjangoModelLoadingTestCase::test_inherited_loading_and_sequence",
"tests/test_django.py::DjangoModelLoadingTestCase::test_loading",
"tests/test_django.py::DjangoNonIntegerPkTestCase::test_creation",
"tests/test_django.py::DjangoNonIntegerPkTestCase::test_first",
"tests/test_django.py::DjangoNonIntegerPkTestCase::test_force_pk",
"tests/test_django.py::DjangoNonIntegerPkTestCase::test_many",
"tests/test_django.py::DjangoAbstractBaseSequenceTestCase::test_auto_sequence_grandson",
"tests/test_django.py::DjangoAbstractBaseSequenceTestCase::test_auto_sequence_son",
"tests/test_django.py::DjangoAbstractBaseSequenceTestCase::test_optional_abstract",
"tests/test_django.py::DjangoRelatedFieldTestCase::test_create_pointed",
"tests/test_django.py::DjangoRelatedFieldTestCase::test_create_pointed_related",
"tests/test_django.py::DjangoRelatedFieldTestCase::test_create_pointed_related_extra",
"tests/test_django.py::DjangoRelatedFieldTestCase::test_create_pointed_related_with_deep_context",
"tests/test_django.py::DjangoRelatedFieldTestCase::test_create_pointed_related_with_trait",
"tests/test_django.py::DjangoRelatedFieldTestCase::test_create_pointer",
"tests/test_django.py::DjangoRelatedFieldTestCase::test_create_pointer_extra",
"tests/test_django.py::DjangoRelatedFieldTestCase::test_create_pointer_with_deep_context",
"tests/test_django.py::DjangoPasswordTestCase::test_build",
"tests/test_django.py::DjangoPasswordTestCase::test_build_with_kwargs",
"tests/test_django.py::DjangoPasswordTestCase::test_create",
"tests/test_django.py::DjangoFileFieldTestCase::test_default_build",
"tests/test_django.py::DjangoFileFieldTestCase::test_default_create",
"tests/test_django.py::DjangoFileFieldTestCase::test_error_both_file_and_path",
"tests/test_django.py::DjangoFileFieldTestCase::test_existing_file",
"tests/test_django.py::DjangoFileFieldTestCase::test_no_file",
"tests/test_django.py::DjangoFileFieldTestCase::test_override_filename_with_path",
"tests/test_django.py::DjangoFileFieldTestCase::test_with_content",
"tests/test_django.py::DjangoFileFieldTestCase::test_with_file",
"tests/test_django.py::DjangoFileFieldTestCase::test_with_file_empty_path",
"tests/test_django.py::DjangoFileFieldTestCase::test_with_path",
"tests/test_django.py::DjangoFileFieldTestCase::test_with_path_empty_file",
"tests/test_django.py::DjangoParamsTestCase::test_pointing_with_traits_using_same_name",
"tests/test_django.py::DjangoParamsTestCase::test_undeclared_fields",
"tests/test_django.py::DjangoFakerTestCase::test_random",
"tests/test_django.py::DjangoImageFieldTestCase::test_complex_create",
"tests/test_django.py::DjangoImageFieldTestCase::test_default_build",
"tests/test_django.py::DjangoImageFieldTestCase::test_default_create",
"tests/test_django.py::DjangoImageFieldTestCase::test_error_both_file_and_path",
"tests/test_django.py::DjangoImageFieldTestCase::test_existing_file",
"tests/test_django.py::DjangoImageFieldTestCase::test_gif",
"tests/test_django.py::DjangoImageFieldTestCase::test_no_file",
"tests/test_django.py::DjangoImageFieldTestCase::test_override_filename_with_path",
"tests/test_django.py::DjangoImageFieldTestCase::test_rgba_image",
"tests/test_django.py::DjangoImageFieldTestCase::test_with_content",
"tests/test_django.py::DjangoImageFieldTestCase::test_with_file",
"tests/test_django.py::DjangoImageFieldTestCase::test_with_file_empty_path",
"tests/test_django.py::DjangoImageFieldTestCase::test_with_func",
"tests/test_django.py::DjangoImageFieldTestCase::test_with_path",
"tests/test_django.py::DjangoImageFieldTestCase::test_with_path_empty_file",
"tests/test_django.py::PreventSignalsTestCase::test_class_decorator",
"tests/test_django.py::PreventSignalsTestCase::test_class_decorator_build",
"tests/test_django.py::PreventSignalsTestCase::test_class_decorator_related_model_with_post_hook",
"tests/test_django.py::PreventSignalsTestCase::test_class_decorator_with_subfactory",
"tests/test_django.py::PreventSignalsTestCase::test_classmethod_decorator",
"tests/test_django.py::PreventSignalsTestCase::test_context_manager",
"tests/test_django.py::PreventSignalsTestCase::test_function_decorator",
"tests/test_django.py::PreventSignalsTestCase::test_receiver_created_during_model_instantiation_is_not_lost",
"tests/test_django.py::PreventSignalsTestCase::test_signal_cache",
"tests/test_django.py::PreventChainedSignalsTestCase::test_class_decorator_with_muted_related_factory",
"tests/test_django.py::PreventChainedSignalsTestCase::test_class_decorator_with_muted_subfactory",
"tests/test_django.py::DjangoCustomManagerTestCase::test_extra_args",
"tests/test_django.py::DjangoCustomManagerTestCase::test_with_manager_on_abstract",
"tests/test_django.py::DjangoModelFactoryDuplicateSaveDeprecationTest::test_build_no_warning",
"tests/test_django.py::DjangoModelFactoryDuplicateSaveDeprecationTest::test_create_warning",
"tests/test_django.py::IntegrityErrorForMissingOriginalParamsTest::test_raises_integrity_error"
] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2023-09-20T14:12:11Z" | mit |
|
FactoryBoy__factory_boy-752 | diff --git a/docs/changelog.rst b/docs/changelog.rst
index 0c6043a..5e919bc 100644
--- a/docs/changelog.rst
+++ b/docs/changelog.rst
@@ -43,6 +43,10 @@ The following aliases were removed:
- :py:meth:`get_random_state()` now represents the state of Faker and ``factory_boy`` fuzzy attributes.
- Add SQLAlchemy ``get_or_create`` support
+*Improvements:*
+
+ - :issue:`561`: Display a developer-friendly error message when providing a model instead of a factory in a :class:`~factory.declarations.SubFactory` class.
+
*Bugfix:*
- Fix issue with SubFactory not preserving signal muting behaviour of the used factory, thanks `Patrick Stein <https://github.com/PFStein>`_.
diff --git a/factory/base.py b/factory/base.py
index 2f1d122..bd00bf6 100644
--- a/factory/base.py
+++ b/factory/base.py
@@ -375,7 +375,7 @@ class FactoryOptions:
return self.model
def __str__(self):
- return "<%s for %s>" % (self.__class__.__name__, self.factory.__class__.__name__)
+ return "<%s for %s>" % (self.__class__.__name__, self.factory.__name__)
def __repr__(self):
return str(self)
diff --git a/factory/builder.py b/factory/builder.py
index b494cc3..09153f7 100644
--- a/factory/builder.py
+++ b/factory/builder.py
@@ -225,9 +225,17 @@ class BuildStep:
return (self.stub,) + parent_chain
def recurse(self, factory, declarations, force_sequence=None):
+ from . import base
+ if not issubclass(factory, base.BaseFactory):
+ raise errors.AssociatedClassError(
+ "%r: Attempting to recursing into a non-factory object %r"
+ % (self, factory))
builder = self.builder.recurse(factory._meta, declarations)
return builder.build(parent_step=self, force_sequence=force_sequence)
+ def __repr__(self):
+ return "<BuildStep for {!r}>".format(self.builder)
+
class StepBuilder:
"""A factory instantiation step.
@@ -305,6 +313,9 @@ class StepBuilder:
"""Recurse into a sub-factory call."""
return self.__class__(factory_meta, extras, strategy=self.strategy)
+ def __repr__(self):
+ return "<StepBuilder(%r, strategy=%r)>" % (self.factory_meta, self.strategy)
+
class Resolver:
"""Resolve a set of declarations.
| FactoryBoy/factory_boy | 85543a502eed7a3d5de17669a98e761e92a78add | diff --git a/tests/test_dev_experience.py b/tests/test_dev_experience.py
new file mode 100644
index 0000000..6677b08
--- /dev/null
+++ b/tests/test_dev_experience.py
@@ -0,0 +1,58 @@
+# Copyright: See the LICENSE file.
+
+"""Tests about developer experience: help messages, errors, etc."""
+
+import collections
+import unittest
+
+import factory
+import factory.errors
+
+Country = collections.namedtuple('Country', ['name', 'continent', 'capital_city'])
+City = collections.namedtuple('City', ['name', 'population'])
+
+
+class DeclarationTests(unittest.TestCase):
+ def test_subfactory_to_model(self):
+ """A helpful error message occurs when pointing a subfactory to a model."""
+ class CountryFactory(factory.Factory):
+ class Meta:
+ model = Country
+
+ name = factory.Faker('country')
+ continent = "Antarctica"
+
+ # Error here: pointing the SubFactory to a model, not a factory.
+ capital_city = factory.SubFactory(City)
+
+ with self.assertRaises(factory.errors.AssociatedClassError) as raised:
+ CountryFactory()
+
+ self.assertIn('City', str(raised.exception))
+ self.assertIn('Country', str(raised.exception))
+
+ def test_subfactory_to_factorylike_model(self):
+ """A helpful error message occurs when pointing a subfactory to a model.
+
+ This time with a model that looks more like a factory (ie has a `._meta`)."""
+
+ class CityModel:
+ _meta = None
+ name = "Coruscant"
+ population = 0
+
+ class CountryFactory(factory.Factory):
+ class Meta:
+ model = Country
+
+ name = factory.Faker('country')
+ continent = "Antarctica"
+
+ # Error here: pointing the SubFactory to a model, not a factory.
+ capital_city = factory.SubFactory(CityModel)
+
+ with self.assertRaises(factory.errors.AssociatedClassError) as raised:
+ CountryFactory()
+
+ self.assertIn('CityModel', str(raised.exception))
+ self.assertIn('Country', str(raised.exception))
| 'Options' object has no attribute 'pre_declarations' is too ambiguous
#### The problem
Typo incorrectly specifying the Model for a Factory.
#### Proposed solution
Check if any specified factories are actually Models, in which case give a more clear error message.
#### Extra notes
Thanks for the good work on this neat lib!
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_dev_experience.py::DeclarationTests::test_subfactory_to_factorylike_model",
"tests/test_dev_experience.py::DeclarationTests::test_subfactory_to_model"
] | [] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
} | "2020-06-26T08:09:30Z" | mit |
|
Fatal1ty__mashumaro-122 | diff --git a/mashumaro/jsonschema/schema.py b/mashumaro/jsonschema/schema.py
index 90fa19f..65c3ec3 100644
--- a/mashumaro/jsonschema/schema.py
+++ b/mashumaro/jsonschema/schema.py
@@ -154,7 +154,7 @@ class Instance:
self.__builder = CodeBuilder(self.origin_type, type_args)
self.__builder.reset()
- def fields(self) -> Iterable[Tuple[str, Type, Any]]:
+ def fields(self) -> Iterable[Tuple[str, Type, bool, Any]]:
for f_name, f_type in self._builder.get_field_types(
include_extras=True
).items():
@@ -166,7 +166,12 @@ class Instance:
f_default = self._builder.namespace.get(f_name, MISSING)
if f_default is not MISSING:
f_default = _default(f_type, f_default)
- yield f_name, f_type, f_default
+
+ has_default = (
+ f.default is not MISSING or f.default_factory is not MISSING
+ )
+
+ yield f_name, f_type, has_default, f_default
def get_overridden_serialization_method(
self,
@@ -289,7 +294,7 @@ def on_dataclass(instance: Instance, ctx: Context) -> Optional[JSONSchema]:
field_schema_overrides = instance.get_config().json_schema.get(
"properties", {}
)
- for f_name, f_type, f_default in instance.fields():
+ for f_name, f_type, has_default, f_default in instance.fields():
override = field_schema_overrides.get(f_name)
f_instance = instance.copy(type=f_type, name=f_name)
if override:
@@ -301,8 +306,10 @@ def on_dataclass(instance: Instance, ctx: Context) -> Optional[JSONSchema]:
f_name = f_instance.alias
if f_default is not MISSING:
f_schema.default = f_default
- else:
+
+ if not has_default:
required.append(f_name)
+
properties[f_name] = f_schema
if properties:
schema.properties = properties
| Fatal1ty/mashumaro | 41b90d2a0505c2a5d463150d880df8cf917227a8 | diff --git a/tests/test_jsonschema/test_jsonschema_generation.py b/tests/test_jsonschema/test_jsonschema_generation.py
index 875d719..626f977 100644
--- a/tests/test_jsonschema/test_jsonschema_generation.py
+++ b/tests/test_jsonschema/test_jsonschema_generation.py
@@ -126,6 +126,7 @@ def test_jsonschema_for_dataclass():
c: Optional[int] = field(default=None, metadata={"alias": "cc"})
d: str = ""
e: int = field(init=False)
+ f: List[int] = field(default_factory=list)
class Config:
aliases = {"a": "aa", "d": "dd"}
@@ -143,6 +144,9 @@ def test_jsonschema_for_dataclass():
default=None,
),
"dd": JSONSchema(type=JSONSchemaInstanceType.STRING, default=""),
+ "f": JSONArraySchema(
+ items=JSONSchema(type=JSONSchemaInstanceType.INTEGER)
+ ),
},
additionalProperties=False,
required=["aa"],
| JSON Schema generator doesn't honor `default_factory`
* mashumaro version: 3.7
* Python version: 3.11 (but 3.10 is the same)
* Operating System: macOS Ventura
### Description
See the full code and output below. When using default value, directly or via `field(default=...)` the schema correctly recognizes the field as not required. But it doesn't work with `default_factory` unfortunately.
Shall I open a PR?
### What I Did
```
import json
from dataclasses import dataclass, field
from functools import partial
from mashumaro import DataClassDictMixin
from mashumaro.jsonschema import build_json_schema
@dataclass
class Foo(DataClassDictMixin):
bar: frozenset[str] = field(default_factory=frozenset)
print(build_json_schema(Foo).to_json(encoder=partial(json.dumps, indent=2)))
# {
# "type": "object",
# "title": "Foo",
# "properties": {
# "bar": {
# "type": "array",
# "items": {
# "type": "string"
# },
# "uniqueItems": true
# }
# },
# "additionalProperties": false,
# "required": [
# "bar"
# ]
# }
```
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_dataclass"
] | [
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_any",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_literal",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_special_typing_primitives",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_number[int-JSONSchemaInstanceType.INTEGER]",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_number[float-JSONSchemaInstanceType.NUMBER]",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_bool",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_none",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_datetime_objects[datetime-JSONSchemaStringFormat.DATETIME]",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_datetime_objects[date-JSONSchemaStringFormat.DATE]",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_datetime_objects[time-JSONSchemaStringFormat.TIME]",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_timedelta",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_timezone",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_zone_info",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_uuid",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_ipaddress[IPv4Address-JSONSchemaStringFormat.IPV4ADDRESS]",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_ipaddress[IPv6Address-JSONSchemaStringFormat.IPV6ADDRESS]",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_ipaddress[IPv4Network-JSONSchemaInstanceFormatExtension.IPV4NETWORK0]",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_ipaddress[IPv6Network-JSONSchemaInstanceFormatExtension.IPV6NETWORK0]",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_ipaddress[IPv4Network-JSONSchemaInstanceFormatExtension.IPV4NETWORK1]",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_ipaddress[IPv6Network-JSONSchemaInstanceFormatExtension.IPV6NETWORK1]",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_decimal",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_fraction",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_bytestring",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_str",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_list",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_deque",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_tuple",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_named_tuple",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_named_tuple_as_dict",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_named_tuple_as_list",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_named_tuple_with_overridden_serialization_method",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_set",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_chainmap",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_counter",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_typeddict",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_mapping",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_sequence",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_pathlike",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_array_like_with_constraints",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_enum",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_type_var_tuple",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_unsupported_type",
"tests/test_jsonschema/test_jsonschema_generation.py::test_overridden_serialization_method_without_signature",
"tests/test_jsonschema/test_jsonschema_generation.py::test_overridden_serialization_method_without_return_annotation",
"tests/test_jsonschema/test_jsonschema_generation.py::test_overridden_serialization_method_with_return_annotation",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_with_override_for_properties",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_with_dialect_uri",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_with_ref_prefix"
] | {
"failed_lite_validators": [
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2023-06-30T21:12:15Z" | apache-2.0 |
|
Fatal1ty__mashumaro-142 | diff --git a/mashumaro/jsonschema/schema.py b/mashumaro/jsonschema/schema.py
index 9dc6edc..34760e8 100644
--- a/mashumaro/jsonschema/schema.py
+++ b/mashumaro/jsonschema/schema.py
@@ -178,7 +178,7 @@ class Instance:
if f_default is MISSING:
f_default = self._self_builder.namespace.get(f_name, MISSING)
if f_default is not MISSING:
- f_default = _default(f_type, f_default)
+ f_default = _default(f_type, f_default, self.get_self_config())
has_default = (
f.default is not MISSING or f.default_factory is not MISSING
@@ -270,11 +270,14 @@ def _get_schema_or_none(
return schema
-def _default(f_type: Type, f_value: Any) -> Any:
+def _default(f_type: Type, f_value: Any, config_cls: Type[BaseConfig]) -> Any:
@dataclass
class CC(DataClassJSONMixin):
x: f_type = f_value # type: ignore
+ class Config(config_cls): # type: ignore
+ pass
+
return CC(f_value).to_dict()["x"]
@@ -615,7 +618,11 @@ def on_named_tuple(instance: Instance, ctx: Context) -> JSONSchema:
if f_default is not MISSING:
if isinstance(f_schema, EmptyJSONSchema):
f_schema = JSONSchema()
- f_schema.default = _default(f_type, f_default) # type: ignore
+ f_schema.default = _default(
+ f_type, # type: ignore[arg-type]
+ f_default,
+ instance.get_self_config(),
+ )
properties[f_name] = f_schema
if as_dict:
return JSONObjectSchema(
| Fatal1ty/mashumaro | 89f4b1ad2048877e72dc4c86a3c532683753ea8a | diff --git a/tests/test_jsonschema/test_jsonschema_generation.py b/tests/test_jsonschema/test_jsonschema_generation.py
index 5e88282..6b5404d 100644
--- a/tests/test_jsonschema/test_jsonschema_generation.py
+++ b/tests/test_jsonschema/test_jsonschema_generation.py
@@ -118,6 +118,30 @@ if PY_39_MIN:
Ts = TypeVarTuple("Ts")
+def dummy_serialize_as_str(_: Any) -> str:
+ return "dummy" # pragma no cover
+
+
+class ThirdPartyType:
+ pass
+
+
+@dataclass
+class DataClassWithThirdPartyType:
+ a: ThirdPartyType
+ b: Optional[ThirdPartyType]
+ c: ThirdPartyType = ThirdPartyType()
+ d: Optional[ThirdPartyType] = None
+
+ class Config(BaseConfig):
+ serialization_strategy = {
+ ThirdPartyType: {
+ "deserialize": ThirdPartyType,
+ "serialize": dummy_serialize_as_str,
+ }
+ }
+
+
def test_jsonschema_for_dataclass():
@dataclass
class DataClass:
@@ -1041,6 +1065,29 @@ def test_dataclass_overridden_serialization_method():
)
+def test_third_party_overridden_serialization_method():
+ schema = build_json_schema(DataClassWithThirdPartyType)
+ assert schema.properties["a"] == JSONSchema(
+ type=JSONSchemaInstanceType.STRING
+ )
+ assert schema.properties["b"] == JSONSchema(
+ anyOf=[
+ JSONSchema(type=JSONSchemaInstanceType.STRING),
+ JSONSchema(type=JSONSchemaInstanceType.NULL),
+ ]
+ )
+ assert schema.properties["c"] == JSONSchema(
+ type=JSONSchemaInstanceType.STRING, default="dummy"
+ )
+ assert schema.properties["d"] == JSONSchema(
+ anyOf=[
+ JSONSchema(type=JSONSchemaInstanceType.STRING),
+ JSONSchema(type=JSONSchemaInstanceType.NULL),
+ ],
+ default=None,
+ )
+
+
def test_jsonschema_with_override_for_properties():
@dataclass
class DataClass:
| Third party default is not reflected in the generated JSON Schema
* mashumaro version: 3.9
* Python version: 3.11
* Operating System: MacOS 3.13.1
### Description
```python
from dataclasses import dataclass
from mashumaro.config import BaseConfig
from mashumaro.jsonschema import build_json_schema
def as_str(value) -> str:
return str(value)
class Bar:
pass
@dataclass
class Foo:
bar: Bar = Bar()
class Config(BaseConfig):
serialization_strategy = {
Bar: {
"serialize": as_str,
"deserialize": Bar,
}
}
print(build_json_schema(Foo).to_json())
```
will raise an exception: `mashumaro.exceptions.UnserializableField: Field "x" of type Bar in _default.<locals>.CC is not serializable`
Expected:
```json
{
"type": "object",
"title": "Foo",
"properties": {
"bar": {
"type": "string",
"default": "<__main__.Bar object at 0x1006e54d0>"
}
},
"additionalProperties": false
}
``` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_jsonschema/test_jsonschema_generation.py::test_third_party_overridden_serialization_method"
] | [
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_dataclass",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_any",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_literal",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_special_typing_primitives",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_number[int-JSONSchemaInstanceType.INTEGER]",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_number[float-JSONSchemaInstanceType.NUMBER]",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_bool",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_none",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_datetime_objects[datetime-JSONSchemaStringFormat.DATETIME]",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_datetime_objects[date-JSONSchemaStringFormat.DATE]",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_datetime_objects[time-JSONSchemaStringFormat.TIME]",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_timedelta",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_timezone",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_zone_info",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_uuid",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_ipaddress[IPv4Address-JSONSchemaStringFormat.IPV4ADDRESS]",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_ipaddress[IPv6Address-JSONSchemaStringFormat.IPV6ADDRESS]",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_ipaddress[IPv4Network-JSONSchemaInstanceFormatExtension.IPV4NETWORK0]",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_ipaddress[IPv6Network-JSONSchemaInstanceFormatExtension.IPV6NETWORK0]",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_ipaddress[IPv4Network-JSONSchemaInstanceFormatExtension.IPV4NETWORK1]",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_ipaddress[IPv6Network-JSONSchemaInstanceFormatExtension.IPV6NETWORK1]",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_decimal",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_fraction",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_bytestring",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_str",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_list",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_deque",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_tuple",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_named_tuple",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_named_tuple_as_dict",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_named_tuple_as_list",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_named_tuple_with_overridden_serialization_method",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_set",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_chainmap",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_counter",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_typeddict",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_mapping",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_sequence",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_pathlike",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_array_like_with_constraints",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_enum",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_type_var_tuple",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_for_unsupported_type",
"tests/test_jsonschema/test_jsonschema_generation.py::test_overridden_serialization_method_without_signature",
"tests/test_jsonschema/test_jsonschema_generation.py::test_overridden_serialization_method_without_return_annotation",
"tests/test_jsonschema/test_jsonschema_generation.py::test_overridden_serialization_method_with_return_annotation",
"tests/test_jsonschema/test_jsonschema_generation.py::test_dataclass_overridden_serialization_method",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_with_override_for_properties",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_with_dialect_uri",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_with_ref_prefix",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_with_additional_properties_true",
"tests/test_jsonschema/test_jsonschema_generation.py::test_jsonschema_with_additional_properties_schema"
] | {
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
} | "2023-08-21T15:43:35Z" | apache-2.0 |
|
Fatal1ty__mashumaro-146 | diff --git a/mashumaro/core/meta/code/builder.py b/mashumaro/core/meta/code/builder.py
index 7ba9d0e..00c16db 100644
--- a/mashumaro/core/meta/code/builder.py
+++ b/mashumaro/core/meta/code/builder.py
@@ -330,6 +330,7 @@ class CodeBuilder:
# prevent RecursionError
field=discr.field,
include_subtypes=discr.include_subtypes,
+ variant_tagger_fn=discr.variant_tagger_fn,
)
self.add_type_modules(self.cls)
method = SubtypeUnpackerBuilder(discr).build(
diff --git a/mashumaro/core/meta/types/unpack.py b/mashumaro/core/meta/types/unpack.py
index 0b5bacb..7cc7a1c 100644
--- a/mashumaro/core/meta/types/unpack.py
+++ b/mashumaro/core/meta/types/unpack.py
@@ -317,6 +317,13 @@ class DiscriminatedUnionUnpackerBuilder(AbstractUnpackerBuilder):
variant_method_call = self._get_variant_method_call(
variant_method_name, spec
)
+ if discriminator.variant_tagger_fn:
+ spec.builder.ensure_object_imported(
+ discriminator.variant_tagger_fn, "variant_tagger_fn"
+ )
+ variant_tagger_expr = "variant_tagger_fn(variant)"
+ else:
+ variant_tagger_expr = f"variant.__dict__['{discriminator.field}']"
if spec.builder.dialect:
spec.builder.ensure_object_imported(
@@ -345,8 +352,7 @@ class DiscriminatedUnionUnpackerBuilder(AbstractUnpackerBuilder):
with lines.indent(f"for variant in {variants}:"):
with lines.indent("try:"):
lines.append(
- f"variants_map[variant.__dict__["
- f"'{discriminator.field}']] = variant"
+ f"variants_map[{variant_tagger_expr}] = variant"
)
with lines.indent("except KeyError:"):
lines.append("continue")
diff --git a/mashumaro/types.py b/mashumaro/types.py
index 01f87c7..823a52e 100644
--- a/mashumaro/types.py
+++ b/mashumaro/types.py
@@ -1,6 +1,6 @@
import decimal
from dataclasses import dataclass
-from typing import Any, List, Optional, Type, Union
+from typing import Any, Callable, List, Optional, Type, Union
from typing_extensions import Literal
@@ -93,6 +93,7 @@ class Discriminator:
field: Optional[str] = None
include_supertypes: bool = False
include_subtypes: bool = False
+ variant_tagger_fn: Optional[Callable[[Any], Any]] = None
def __post_init__(self) -> None:
if not self.include_supertypes and not self.include_subtypes:
| Fatal1ty/mashumaro | 8c32badea5a5005e2243fd8c0ec8aa0dcc6b8c5d | diff --git a/tests/test_discriminated_unions/test_parent_by_field.py b/tests/test_discriminated_unions/test_parent_by_field.py
index 1f0b7d0..d1a9b5b 100644
--- a/tests/test_discriminated_unions/test_parent_by_field.py
+++ b/tests/test_discriminated_unions/test_parent_by_field.py
@@ -145,6 +145,33 @@ class Bar(DataClassDictMixin):
baz2: Annotated[Foo1, Discriminator(include_subtypes=True)]
+@dataclass
+class BaseVariantWitCustomTagger(DataClassDictMixin):
+ pass
+
+
+@dataclass
+class VariantWitCustomTaggerSub1(BaseVariantWitCustomTagger):
+ pass
+
+
+@dataclass
+class VariantWitCustomTaggerSub2(BaseVariantWitCustomTagger):
+ pass
+
+
+@dataclass
+class VariantWitCustomTaggerOwner(DataClassDictMixin):
+ x: Annotated[
+ BaseVariantWitCustomTagger,
+ Discriminator(
+ field="type",
+ include_subtypes=True,
+ variant_tagger_fn=lambda cls: cls.__name__.lower(),
+ ),
+ ]
+
+
@pytest.mark.parametrize(
["variant_data", "variant"],
[
@@ -257,3 +284,14 @@ def test_subclass_tree_with_class_without_field():
"baz2": {"type": 4, "x1": 1, "x2": 2, "x": 42},
}
) == Bar(baz1=Foo4(1, 2, 42), baz2=Foo2(1, 2))
+
+
+def test_by_field_with_custom_variant_tagger():
+ assert VariantWitCustomTaggerOwner.from_dict(
+ {"x": {"type": "variantwitcustomtaggersub1"}}
+ ) == VariantWitCustomTaggerOwner(VariantWitCustomTaggerSub1())
+ assert VariantWitCustomTaggerOwner.from_dict(
+ {"x": {"type": "variantwitcustomtaggersub2"}}
+ ) == VariantWitCustomTaggerOwner(VariantWitCustomTaggerSub2())
+ with pytest.raises(InvalidFieldValue):
+ VariantWitCustomTaggerOwner.from_dict({"x": {"type": "unknown"}})
diff --git a/tests/test_discriminated_unions/test_parent_via_config.py b/tests/test_discriminated_unions/test_parent_via_config.py
index d5b854b..e5eba15 100644
--- a/tests/test_discriminated_unions/test_parent_via_config.py
+++ b/tests/test_discriminated_unions/test_parent_via_config.py
@@ -203,6 +203,26 @@ class Bar4(Bar2):
type = 4
+@dataclass
+class VariantWitCustomTagger(DataClassDictMixin):
+ class Config(BaseConfig):
+ discriminator = Discriminator(
+ field="type",
+ include_subtypes=True,
+ variant_tagger_fn=lambda cls: cls.__name__.lower(),
+ )
+
+
+@dataclass
+class VariantWitCustomTaggerSub1(VariantWitCustomTagger):
+ pass
+
+
+@dataclass
+class VariantWitCustomTaggerSub2(VariantWitCustomTagger):
+ pass
+
+
def test_by_subtypes():
assert VariantBySubtypes.from_dict(X_1) == VariantBySubtypesSub1(x=DT_STR)
@@ -385,3 +405,20 @@ def test_subclass_tree_with_class_without_field():
assert Bar1.from_dict({"type": 3, "x1": 1, "x2": 2, "x": 42}) == Bar2(1, 2)
assert Bar1.from_dict({"type": 4, "x1": 1, "x2": 2, "x": 42}) == Bar2(1, 2)
+
+
+def test_by_subtypes_with_custom_variant_tagger():
+ assert (
+ VariantWitCustomTagger.from_dict(
+ {"type": "variantwitcustomtaggersub1"}
+ )
+ == VariantWitCustomTaggerSub1()
+ )
+ assert (
+ VariantWitCustomTagger.from_dict(
+ {"type": "variantwitcustomtaggersub2"}
+ )
+ == VariantWitCustomTaggerSub2()
+ )
+ with pytest.raises(SuitableVariantNotFoundError):
+ VariantWitCustomTagger.from_dict({"type": "unknown"})
diff --git a/tests/test_discriminated_unions/test_union_by_field.py b/tests/test_discriminated_unions/test_union_by_field.py
index 2e1fc98..deea794 100644
--- a/tests/test_discriminated_unions/test_union_by_field.py
+++ b/tests/test_discriminated_unions/test_union_by_field.py
@@ -272,6 +272,28 @@ class ByFieldAndByFieldWithSubtypesInOneField(DataClassDictMixin):
]
+@dataclass
+class VariantWitCustomTagger1:
+ pass
+
+
+@dataclass
+class VariantWitCustomTagger2:
+ pass
+
+
+@dataclass
+class VariantWitCustomTaggerOwner(DataClassDictMixin):
+ x: Annotated[
+ Union[VariantWitCustomTagger1, VariantWitCustomTagger2],
+ Discriminator(
+ field="type",
+ include_supertypes=True,
+ variant_tagger_fn=lambda cls: cls.__name__.lower(),
+ ),
+ ]
+
+
def test_by_field_with_supertypes():
assert ByFieldWithSupertypes.from_dict(
{
@@ -573,3 +595,14 @@ def test_tuple_with_discriminated_elements():
ByFieldAndByFieldWithSubtypesInOneField.from_dict(
{"x": [X_STR, X_STR]}
)
+
+
+def test_by_field_with_subtypes_with_custom_variant_tagger():
+ assert VariantWitCustomTaggerOwner.from_dict(
+ {"x": {"type": "variantwitcustomtagger1"}}
+ ) == VariantWitCustomTaggerOwner(VariantWitCustomTagger1())
+ assert VariantWitCustomTaggerOwner.from_dict(
+ {"x": {"type": "variantwitcustomtagger2"}}
+ ) == VariantWitCustomTaggerOwner(VariantWitCustomTagger2())
+ with pytest.raises(InvalidFieldValue):
+ VariantWitCustomTaggerOwner.from_dict({"x": {"type": "unknown"}})
| Allow discrimination based on a key that is not part of the model
**Is your feature request related to a problem? Please describe.**
I'am using mashumaro as (de)serialization backend of my [AST library](https://github.com/mishamsk/pyoak/)
What this means is that I (de)serialize huge (millions of nodes) nested dataclasses with fields usually having a general type that may have tens and sometimes hunderds subclasses. E.g. borrowing from the example in my own docs:
```python
@dataclass
class Expr(ASTNode):
"""Base for all expressions"""
pass
@dataclass
class Literal(Expr):
"""Base for all literals"""
value: Any
@dataclass
class NumberLiteral(Literal):
value: int
@dataclass
class NoneLiteral(Literal):
value: None = field(default=None, init=False)
@dataclass
class BinExpr(Expr):
"""Base for all binary expressions"""
left: Expr
right: Expr
```
`Expr` can (or rather has in real life) hundreds of subclasses.
Thus it is impractical to let mashumaro try discriminating the actual type by iteratively trying every subclass during deserialization. Also, it will be incorrect in some cases because two subclasses may have the same structure, but I need exactly the same type as it was written during serialization.
I am already handling this via my own extension: [see code](https://github.com/mishamsk/pyoak/blob/f030f71d7ced2ab04a77b7f2497599fce5c1abad/src/pyoak/serialize.py#L111)
My custom implementation adds `__type` key during serialization which is read during deserialization and then dropped. If it is not available, it falls back to the default logic.
However, this way I can't use some of the other mashumaro features, such as annotations in _serialize/_deserialize, and I have to resort to "dirty" class state to pass additional options (what has been discussed in #100)
**Describe the solution you'd like**
I suggest adding an option to the discriminator feature to allow using keys that are not part of the data class itself.
**Describe alternatives you've considered**
See above my current implementation
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_discriminated_unions/test_parent_by_field.py::test_by_subtypes[variant_data0-variant0]",
"tests/test_discriminated_unions/test_parent_by_field.py::test_by_subtypes[variant_data1-variant1]",
"tests/test_discriminated_unions/test_parent_by_field.py::test_by_subtypes[variant_data2-variant2]",
"tests/test_discriminated_unions/test_parent_by_field.py::test_by_subtypes[variant_data3-variant3]",
"tests/test_discriminated_unions/test_parent_by_field.py::test_by_subtypes[variant_data4-variant4]",
"tests/test_discriminated_unions/test_parent_by_field.py::test_by_subtypes[variant_data5-variant5]",
"tests/test_discriminated_unions/test_parent_by_field.py::test_by_subtypes_exceptions",
"tests/test_discriminated_unions/test_parent_by_field.py::test_by_supertypes",
"tests/test_discriminated_unions/test_parent_by_field.py::test_by_field_with_subtypes[variant_data0-variant0]",
"tests/test_discriminated_unions/test_parent_by_field.py::test_by_field_with_subtypes[variant_data1-variant1]",
"tests/test_discriminated_unions/test_parent_by_field.py::test_by_field_with_subtypes[variant_data2-variant2]",
"tests/test_discriminated_unions/test_parent_by_field.py::test_by_field_with_subtypes[variant_data3-variant3]",
"tests/test_discriminated_unions/test_parent_by_field.py::test_by_field_with_subtypes[variant_data4-variant4]",
"tests/test_discriminated_unions/test_parent_by_field.py::test_by_field_with_subtypes[variant_data5-variant5]",
"tests/test_discriminated_unions/test_parent_by_field.py::test_by_field_with_subtypes_exceptions",
"tests/test_discriminated_unions/test_parent_by_field.py::test_by_field_with_supertypes",
"tests/test_discriminated_unions/test_parent_by_field.py::test_by_field_with_supertypes_and_subtypes[ByFieldWithSupertypesAndSubtypes]",
"tests/test_discriminated_unions/test_parent_by_field.py::test_by_field_with_supertypes_and_subtypes[BySupertypesAndSubtypes]",
"tests/test_discriminated_unions/test_parent_by_field.py::test_subclass_tree_with_class_without_field",
"tests/test_discriminated_unions/test_parent_by_field.py::test_by_field_with_custom_variant_tagger",
"tests/test_discriminated_unions/test_parent_via_config.py::test_by_subtypes",
"tests/test_discriminated_unions/test_parent_via_config.py::test_by_supertypes",
"tests/test_discriminated_unions/test_parent_via_config.py::test_by_field_with_subtypes",
"tests/test_discriminated_unions/test_parent_via_config.py::test_by_field_with_supertypes",
"tests/test_discriminated_unions/test_parent_via_config.py::test_by_field_with_supertypes_and_subtypes",
"tests/test_discriminated_unions/test_parent_via_config.py::test_by_supertypes_and_subtypes",
"tests/test_discriminated_unions/test_parent_via_config.py::test_subclass_tree_with_class_without_field",
"tests/test_discriminated_unions/test_parent_via_config.py::test_by_subtypes_with_custom_variant_tagger",
"tests/test_discriminated_unions/test_union_by_field.py::test_by_field_with_supertypes",
"tests/test_discriminated_unions/test_union_by_field.py::test_by_field_with_subtypes",
"tests/test_discriminated_unions/test_union_by_field.py::test_by_field_with_supertypes_and_subtypes",
"tests/test_discriminated_unions/test_union_by_field.py::test_by_supertypes",
"tests/test_discriminated_unions/test_union_by_field.py::test_by_subtypes",
"tests/test_discriminated_unions/test_union_by_field.py::test_by_supertypes_and_subtypes",
"tests/test_discriminated_unions/test_union_by_field.py::test_tuple_with_discriminated_elements",
"tests/test_discriminated_unions/test_union_by_field.py::test_by_field_with_subtypes_with_custom_variant_tagger"
] | [] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_issue_reference",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2023-08-23T20:11:28Z" | apache-2.0 |
|
Fatal1ty__mashumaro-185 | diff --git a/README.md b/README.md
index e224048..3dc602a 100644
--- a/README.md
+++ b/README.md
@@ -2020,7 +2020,7 @@ It has the following parameters that affects class selection rules:
by which all the variants can be distinguished
* `include_subtypes` β allow to deserialize subclasses
* `include_supertypes` β allow to deserialize superclasses
-* `variant_tagger_fn` β a custom function used to generate a tag value
+* `variant_tagger_fn` β a custom function used to generate tag values
associated with a variant
By default, each variant that you want to discriminate by tags should have a
@@ -2039,10 +2039,11 @@ following forms:
> processed during serialization.
However, it is possible to use discriminator without the class-level
-attribute. You can provide a custom function that generates a variant tag
-value. This function should take a class as the only argument and return a
-value of the basic type like `str` or `int`. The common practice is to use
-a class name as a tag value:
+attribute. You can provide a custom function that generates one or many variant
+tag values. This function should take a class as the only argument and return
+either a single value of the basic type like `str` or `int` or a list of them
+to associate multiple tags with a variant. The common practice is to use
+a class name as a single tag value:
```python
variant_tagger_fn = lambda cls: cls.__name__
@@ -2466,6 +2467,15 @@ disconnected_event = ClientEvent.from_dict(
assert disconnected_event == ClientDisconnectedEvent(IPv4Address("10.0.0.42"))
```
+If we need to associate multiple tags with a single variant, we can return
+a list of tags:
+
+```python
+def client_event_tagger(cls):
+ name = cls.__name__[6:-5]
+ return [name.lower(), name.upper()]
+```
+
### Code generation options
#### Add `omit_none` keyword argument
diff --git a/mashumaro/core/meta/types/unpack.py b/mashumaro/core/meta/types/unpack.py
index b979d2a..b6b1853 100644
--- a/mashumaro/core/meta/types/unpack.py
+++ b/mashumaro/core/meta/types/unpack.py
@@ -347,12 +347,17 @@ class DiscriminatedUnionUnpackerBuilder(AbstractUnpackerBuilder):
with lines.indent("except (KeyError, AttributeError):"):
lines.append(f"variants_map = {variants_map}")
with lines.indent(f"for variant in {variants}:"):
- with lines.indent("try:"):
- lines.append(
- f"variants_map[{variant_tagger_expr}] = variant"
+ if discriminator.variant_tagger_fn is not None:
+ self._add_register_variant_tags(
+ lines, variant_tagger_expr
)
- with lines.indent("except KeyError:"):
- lines.append("continue")
+ else:
+ with lines.indent("try:"):
+ self._add_register_variant_tags(
+ lines, variant_tagger_expr
+ )
+ with lines.indent("except KeyError:"):
+ lines.append("continue")
self._add_build_variant_unpacker(
spec, lines, variant_method_name, variant_method_call
)
@@ -457,6 +462,19 @@ class DiscriminatedUnionUnpackerBuilder(AbstractUnpackerBuilder):
lines.append(f"return {attrs}.{variant_method_call}")
lines.append("except Exception: pass")
+ def _add_register_variant_tags(
+ self, lines: CodeLines, variant_tagger_expr: str
+ ) -> None:
+ if self.discriminator.variant_tagger_fn:
+ lines.append(f"variant_tags = {variant_tagger_expr}")
+ with lines.indent("if type(variant_tags) is list:"):
+ with lines.indent("for varint_tag in variant_tags:"):
+ lines.append("variants_map[varint_tag] = variant")
+ with lines.indent("else:"):
+ lines.append("variants_map[variant_tags] = variant")
+ else:
+ lines.append(f"variants_map[{variant_tagger_expr}] = variant")
+
class SubtypeUnpackerBuilder(DiscriminatedUnionUnpackerBuilder):
def _get_variants_attr(self, spec: ValueSpec) -> str:
| Fatal1ty/mashumaro | 6cd3924476872a913faf68b5165e2620c645abbd | diff --git a/tests/test_discriminated_unions/test_parent_via_config.py b/tests/test_discriminated_unions/test_parent_via_config.py
index 6b9dd90..d73f4db 100644
--- a/tests/test_discriminated_unions/test_parent_via_config.py
+++ b/tests/test_discriminated_unions/test_parent_via_config.py
@@ -426,6 +426,52 @@ class _VariantWitCustomTaggerSub2(_VariantWitCustomTagger):
pass
+@dataclass
+class VariantWithMultipleTags(DataClassDictMixin):
+ class Config(BaseConfig):
+ discriminator = Discriminator(
+ field="type",
+ include_subtypes=True,
+ variant_tagger_fn=lambda cls: [
+ cls.__name__.lower(),
+ cls.__name__.upper(),
+ ],
+ )
+
+
+@dataclass
+class VariantWithMultipleTagsOne(VariantWithMultipleTags):
+ pass
+
+
+@dataclass
+class VariantWithMultipleTagsTwo(VariantWithMultipleTags):
+ pass
+
+
+@dataclass
+class _VariantWithMultipleTags:
+ class Config(BaseConfig):
+ discriminator = Discriminator(
+ field="type",
+ include_subtypes=True,
+ variant_tagger_fn=lambda cls: [
+ cls.__name__.lower(),
+ cls.__name__.upper(),
+ ],
+ )
+
+
+@dataclass
+class _VariantWithMultipleTagsOne(_VariantWithMultipleTags):
+ pass
+
+
+@dataclass
+class _VariantWithMultipleTagsTwo(_VariantWithMultipleTags):
+ pass
+
+
def test_by_subtypes():
assert VariantBySubtypes.from_dict(X_1) == VariantBySubtypesSub1(x=DT_STR)
assert decode(X_1, _VariantBySubtypes) == _VariantBySubtypesSub1(x=DT_STR)
@@ -749,3 +795,19 @@ def test_by_subtypes_with_custom_variant_tagger():
VariantWitCustomTagger.from_dict({"type": "unknown"})
with pytest.raises(SuitableVariantNotFoundError):
decode({"type": "unknown"}, _VariantWitCustomTagger)
+
+
+def test_by_subtypes_with_custom_variant_tagger_and_multiple_tags():
+ for variant in (VariantWithMultipleTagsOne, VariantWithMultipleTagsTwo):
+ for tag in (variant.__name__.lower(), variant.__name__.upper()):
+ assert (
+ VariantWithMultipleTags.from_dict({"type": tag}) == variant()
+ )
+ for variant in (_VariantWithMultipleTagsOne, _VariantWithMultipleTagsTwo):
+ for tag in (variant.__name__.lower(), variant.__name__.upper()):
+ assert decode({"type": tag}, _VariantWithMultipleTags) == variant()
+
+ with pytest.raises(SuitableVariantNotFoundError):
+ VariantWithMultipleTags.from_dict({"type": "unknown"})
+ with pytest.raises(SuitableVariantNotFoundError):
+ decode({"type": "unknown"}, _VariantWithMultipleTags)
diff --git a/tests/test_discriminated_unions/test_union_by_field.py b/tests/test_discriminated_unions/test_union_by_field.py
index ad8db13..0ca230b 100644
--- a/tests/test_discriminated_unions/test_union_by_field.py
+++ b/tests/test_discriminated_unions/test_union_by_field.py
@@ -341,6 +341,28 @@ class VariantWitCustomTaggerOwner(
pass
+@dataclass
+class _VariantWitCustomTaggerWithMultipleTagsOwner:
+ x: Annotated[
+ Union[VariantWitCustomTagger1, VariantWitCustomTagger2],
+ Discriminator(
+ field="type",
+ include_supertypes=True,
+ variant_tagger_fn=lambda cls: [
+ cls.__name__.lower(),
+ cls.__name__.upper(),
+ ],
+ ),
+ ]
+
+
+@dataclass
+class VariantWitCustomTaggerWithMultipleTagsOwner(
+ _VariantWitCustomTaggerWithMultipleTagsOwner, DataClassDictMixin
+):
+ pass
+
+
def test_by_field_with_supertypes():
decoder = BasicDecoder(_ByFieldWithSupertypes)
@@ -748,3 +770,29 @@ def test_by_field_with_subtypes_with_custom_variant_tagger():
)
with pytest.raises(InvalidFieldValue):
func({"x": {"type": "unknown"}})
+
+
+def test_by_field_with_subtypes_with_custom_variant_tagger_and_multiple_tags():
+ decoder = BasicDecoder(_VariantWitCustomTaggerWithMultipleTagsOwner)
+
+ for func, cls in (
+ (
+ VariantWitCustomTaggerWithMultipleTagsOwner.from_dict,
+ VariantWitCustomTaggerWithMultipleTagsOwner,
+ ),
+ (decoder.decode, _VariantWitCustomTaggerWithMultipleTagsOwner),
+ ):
+ assert func({"x": {"type": "variantwitcustomtagger1"}}) == cls(
+ VariantWitCustomTagger1()
+ )
+ assert func({"x": {"type": "variantwitcustomtagger2"}}) == cls(
+ VariantWitCustomTagger2()
+ )
+ assert func({"x": {"type": "VARIANTWITCUSTOMTAGGER1"}}) == cls(
+ VariantWitCustomTagger1()
+ )
+ assert func({"x": {"type": "VARIANTWITCUSTOMTAGGER2"}}) == cls(
+ VariantWitCustomTagger2()
+ )
+ with pytest.raises(InvalidFieldValue):
+ func({"x": {"type": "unknown"}})
| Allow for more complex logic for subclass Discrimnator field matching
**Is your feature request related to a problem? Please describe.**
In building a deserializer for a large complex configuration file, some subclasses have identical shapes, but it would still be useful to distinguish by a `type` field. Unfortunately, in our situation there are multiple values for `type` that map to the same subclass.
**Describe the solution you'd like**
I haven't dug into the existing code deep enough to know what's feasible, so there are probably a number of possible solutions (or maybe none, I suppose).
The least intrusive I could see would be having `variant_trigger_fn` return a `list[str]` instead of `str`.
A more involved solution might be adding an inverse to the `variant_trigger_fn` that takes a `str` and returns a `class`.
Finally, the workaround below could be improved upon if there was a hook in the base class that could accomplish the same thing.
**Describe alternatives you've considered**
I have been able to work around this using `__pre_deserialize__`:
```
@dataclass
class ClientEvent(DataClassDictMixin):
client_ip: str
type: str
_type = "unknown"
@dataclass
class ClientConnectedEvent(ClientEvent):
_type = "connected"
@dataclass
class ClientDisconnectedEvent(ClientEvent):
_type = "disconnected"
def get_type(typ: str):
if typ in ["disconnected", "connected"]:
return typ
if typ == "d/c":
return "disconnected"
return "unknown"
@dataclass
class AggregatedEvents(DataClassDictMixin):
list: List[
Annotated[
ClientEvent, Discriminator(field="_type", include_subtypes=True, include_supertypes=True)
]
]
@classmethod
def __pre_deserialize__(cls, d: dict[Any, Any]) -> dict[Any, Any]:
d["list"] = [dict({"_type": get_type(event["type"])}, **event) for event in d["list"]]
return d
events = AggregatedEvents.from_dict(
{
"list": [
{"type": "connected", "client_ip": "10.0.0.42"},
{"type": "disconnected", "client_ip": "10.0.0.42"},
{"type": "N/A", "client_ip": "10.0.0.42"},
{"type": "d/c", "client_ip": "10.0.0.42"},
]
}
)
# Produces:
AggregatedEvents(list=[ClientConnectedEvent(client_ip='10.0.0.42', type='connected'), ClientDisconnectedEvent(client_ip='10.0.0.42', type='disconnected'), ClientEvent(client_ip='10.0.0.42', type='N/A'), ClientDisconnectedEvent(client_ip='10.0.0.42', type='d/c')])
```
This works reasonably well (and preserves the original `type` which can be useful). The major downside is that the `__pre_deserialize__` method needs to be implemented in each class that makes use of `ClientEvent`, and in our situation that ends up being several. It would be more convenient if there was a hook in the `ClientEvent` base class that could accomplish the same thing.
**Additional context**
I'm just getting started with this library and it's great so far. It's possible I'm missing something and this is already doable. Alternatively, the workaround, well, works, so feel free to close this if this is not a feature you're looking to add. Thanks! | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_discriminated_unions/test_parent_via_config.py::test_by_subtypes_with_custom_variant_tagger_and_multiple_tags",
"tests/test_discriminated_unions/test_union_by_field.py::test_by_field_with_subtypes_with_custom_variant_tagger_and_multiple_tags"
] | [
"tests/test_discriminated_unions/test_parent_via_config.py::test_by_subtypes",
"tests/test_discriminated_unions/test_parent_via_config.py::test_by_supertypes",
"tests/test_discriminated_unions/test_parent_via_config.py::test_by_field_with_subtypes",
"tests/test_discriminated_unions/test_parent_via_config.py::test_by_field_with_supertypes",
"tests/test_discriminated_unions/test_parent_via_config.py::test_by_field_with_supertypes_and_subtypes",
"tests/test_discriminated_unions/test_parent_via_config.py::test_by_supertypes_and_subtypes",
"tests/test_discriminated_unions/test_parent_via_config.py::test_subclass_tree_with_class_without_field",
"tests/test_discriminated_unions/test_parent_via_config.py::test_by_subtypes_with_custom_variant_tagger",
"tests/test_discriminated_unions/test_union_by_field.py::test_by_field_with_supertypes",
"tests/test_discriminated_unions/test_union_by_field.py::test_by_field_with_subtypes",
"tests/test_discriminated_unions/test_union_by_field.py::test_by_field_with_supertypes_and_subtypes",
"tests/test_discriminated_unions/test_union_by_field.py::test_by_supertypes",
"tests/test_discriminated_unions/test_union_by_field.py::test_by_subtypes",
"tests/test_discriminated_unions/test_union_by_field.py::test_by_supertypes_and_subtypes",
"tests/test_discriminated_unions/test_union_by_field.py::test_tuple_with_discriminated_elements",
"tests/test_discriminated_unions/test_union_by_field.py::test_by_field_with_subtypes_with_custom_variant_tagger"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2023-12-23T12:39:31Z" | apache-2.0 |
|
Fatal1ty__mashumaro-94 | diff --git a/mashumaro/config.py b/mashumaro/config.py
index 719e249..6c8bad4 100644
--- a/mashumaro/config.py
+++ b/mashumaro/config.py
@@ -10,6 +10,15 @@ else:
from typing_extensions import Literal # type: ignore
+__all__ = [
+ "BaseConfig",
+ "TO_DICT_ADD_BY_ALIAS_FLAG",
+ "TO_DICT_ADD_OMIT_NONE_FLAG",
+ "ADD_DIALECT_SUPPORT",
+ "SerializationStrategyValueType",
+]
+
+
TO_DICT_ADD_BY_ALIAS_FLAG = "TO_DICT_ADD_BY_ALIAS_FLAG"
TO_DICT_ADD_OMIT_NONE_FLAG = "TO_DICT_ADD_OMIT_NONE_FLAG"
ADD_DIALECT_SUPPORT = "ADD_DIALECT_SUPPORT"
@@ -38,12 +47,3 @@ class BaseConfig:
dialect: Optional[Type[Dialect]] = None
omit_none: Union[bool, Literal[Sentinel.MISSING]] = Sentinel.MISSING
orjson_options: Optional[int] = 0
-
-
-__all__ = [
- "BaseConfig",
- "TO_DICT_ADD_BY_ALIAS_FLAG",
- "TO_DICT_ADD_OMIT_NONE_FLAG",
- "ADD_DIALECT_SUPPORT",
- "SerializationStrategyValueType",
-]
diff --git a/mashumaro/core/meta/code/builder.py b/mashumaro/core/meta/code/builder.py
index 453da7f..dde2889 100644
--- a/mashumaro/core/meta/code/builder.py
+++ b/mashumaro/core/meta/code/builder.py
@@ -1,6 +1,5 @@
import importlib
import inspect
-import sys
import types
import typing
from contextlib import contextmanager
@@ -115,12 +114,8 @@ class CodeBuilder:
self, recursive: bool = True
) -> typing.Dict[str, typing.Any]:
fields = {}
- globalns = sys.modules[self.cls.__module__].__dict__.copy()
- globalns[self.cls.__name__] = self.cls
try:
- field_type_hints = typing.get_type_hints(
- self.cls, globalns, self.cls.__dict__ # type: ignore
- )
+ field_type_hints = typing.get_type_hints(self.cls)
except NameError as e:
name = get_name_error_name(e)
raise UnresolvedTypeReferenceError(self.cls, name) from None
@@ -899,7 +894,6 @@ class CodeBuilder:
yield metadata.get("serialization_strategy")
yield from self.__iter_serialization_strategies(ftype)
- @lru_cache()
@typing.no_type_check
def __iter_serialization_strategies(
self, ftype: typing.Type
diff --git a/mashumaro/dialect.py b/mashumaro/dialect.py
index e6aba5f..b3ec3f0 100644
--- a/mashumaro/dialect.py
+++ b/mashumaro/dialect.py
@@ -5,6 +5,9 @@ from typing_extensions import Literal
from mashumaro.core.const import Sentinel
from mashumaro.types import SerializationStrategy
+__all__ = ["Dialect"]
+
+
SerializationStrategyValueType = Union[
SerializationStrategy, Dict[str, Union[str, Callable]]
]
@@ -13,6 +16,3 @@ SerializationStrategyValueType = Union[
class Dialect:
serialization_strategy: Dict[Any, SerializationStrategyValueType] = {}
omit_none: Union[bool, Literal[Sentinel.MISSING]] = Sentinel.MISSING
-
-
-__all__ = ["Dialect"]
diff --git a/mashumaro/helper.py b/mashumaro/helper.py
index 96c9fec..f21f7fa 100644
--- a/mashumaro/helper.py
+++ b/mashumaro/helper.py
@@ -4,6 +4,12 @@ from typing_extensions import Literal
from mashumaro.types import SerializationStrategy
+__all__ = [
+ "field_options",
+ "pass_through",
+]
+
+
NamedTupleDeserializationEngine = Literal["as_dict", "as_list"]
DateTimeDeserializationEngine = Literal["ciso8601", "pendulum"]
AnyDeserializationEngine = Literal[
@@ -47,6 +53,3 @@ class _PassThrough(SerializationStrategy):
pass_through = _PassThrough()
-
-
-__all__ = ["field_options", "pass_through"]
diff --git a/mashumaro/types.py b/mashumaro/types.py
index b1cab34..6a45eeb 100644
--- a/mashumaro/types.py
+++ b/mashumaro/types.py
@@ -5,6 +5,13 @@ from typing_extensions import Literal
from mashumaro.core.const import Sentinel
+__all__ = [
+ "SerializableType",
+ "GenericSerializableType",
+ "SerializationStrategy",
+ "RoundedDecimal",
+]
+
class SerializableType:
__use_annotations__ = False
@@ -65,11 +72,3 @@ class RoundedDecimal(SerializationStrategy):
def deserialize(self, value: str) -> decimal.Decimal:
return decimal.Decimal(str(value))
-
-
-__all__ = [
- "SerializableType",
- "GenericSerializableType",
- "SerializationStrategy",
- "RoundedDecimal",
-]
| Fatal1ty/mashumaro | 76381804fe0ddd6eec7b9aabb7dddb950eca2b47 | diff --git a/tests/test_config.py b/tests/test_config.py
index 17f0abb..c7ffa68 100644
--- a/tests/test_config.py
+++ b/tests/test_config.py
@@ -142,6 +142,7 @@ def test_serialization_strategy():
class DataClass(DataClassDictMixin):
a: int
b: str
+ c: int
class Config(BaseConfig):
serialization_strategy = {
@@ -152,9 +153,9 @@ def test_serialization_strategy():
},
}
- instance = DataClass(a=123, b="abc")
- assert DataClass.from_dict({"a": [123], "b": ["abc"]}) == instance
- assert instance.to_dict() == {"a": [123], "b": ["abc"]}
+ instance = DataClass(a=123, b="abc", c=123)
+ assert DataClass.from_dict({"a": [123], "b": ["abc"], "c": [123]}) == instance
+ assert instance.to_dict() == {"a": [123], "b": ["abc"], "c": [123]}
def test_named_tuple_as_dict():
diff --git a/tests/test_forward_refs/__init__.py b/tests/test_forward_refs/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/tests/test_forward_refs/test_baz.py b/tests/test_forward_refs/test_baz.py
new file mode 100644
index 0000000..495441c
--- /dev/null
+++ b/tests/test_forward_refs/test_baz.py
@@ -0,0 +1,15 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+from .test_foobar import Bar, Foo
+
+
+@dataclass
+class Baz(Foo[int]):
+ pass
+
+
+def test_class_with_base_in_another_module():
+ assert Bar(x=1).to_json() == '{"x": 1}'
+ assert Baz(x=1).to_json() == '{"x": 1}'
diff --git a/tests/test_forward_refs/test_foobar.py b/tests/test_forward_refs/test_foobar.py
new file mode 100644
index 0000000..effbe3a
--- /dev/null
+++ b/tests/test_forward_refs/test_foobar.py
@@ -0,0 +1,18 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Generic, TypeVar
+
+from mashumaro.mixins.json import DataClassJSONMixin
+
+T = TypeVar("T")
+
+
+@dataclass
+class Foo(Generic[T], DataClassJSONMixin):
+ x: T
+
+
+@dataclass
+class Bar(Foo[int]):
+ pass
| Inconsistent Application of serialization_strategy
* mashumaro version: 3.2 and 3.3
* Python version: 3.10
* Operating System: macOS
### Description
There is an apparent regression in serialization behavior when the serialization_strategy object is being used and there are multiple properties of the same type on the class being serialized. It worked as I expected in 3.1.1, but fails in 3.2 and 3.3.
If the existing unit test `test_config.test_serialization_strategy` is modified to include a third property called `c` of type `str`, it will fail to properly deserialize `c`. Here's what the modified test looks like in full:
```
def test_serialization_strategy():
class TestSerializationStrategy(SerializationStrategy):
def serialize(self, value):
return [value]
def deserialize(self, value):
return value[0]
@dataclass
class DataClass(DataClassDictMixin):
a: int
b: str
c: str
class Config(BaseConfig):
serialization_strategy = {
int: TestSerializationStrategy(),
str: {
"serialize": lambda v: [v],
"deserialize": lambda v: v[0],
},
}
instance = DataClass(a=123, b="abc", c="abc")
assert DataClass.from_dict({"a": [123], "b": ["abc"], "c": ["abc"]}) == instance
assert instance.to_dict() == {"a": [123], "b": ["abc"], "c": ["abc"]}
```
It appears to fail because the custom serialize/deserialize methods are called for b, but not for c.
```AssertionError: assert test_serialization_strategy.<locals>.DataClass(a=123, b='abc', c=['abc']) == test_serialization_strategy.<locals>.DataClass(a=123, b='abc', c='abc')``` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_config.py::test_serialization_strategy",
"tests/test_forward_refs/test_baz.py::test_class_with_base_in_another_module"
] | [
"tests/test_config.py::test_config_without_base_config_base",
"tests/test_config.py::test_debug_false_option",
"tests/test_config.py::test_omit_none_code_generation_flag",
"tests/test_config.py::test_no_omit_none_code_generation_flag",
"tests/test_config.py::test_omit_none_flag_for_inner_class_without_it",
"tests/test_config.py::test_omit_none_flag_for_inner_class_with_it",
"tests/test_config.py::test_passing_omit_none_into_union",
"tests/test_config.py::test_named_tuple_as_dict",
"tests/test_config.py::test_untyped_named_tuple_with_defaults_as_dict",
"tests/test_config.py::test_named_tuple_as_dict_and_as_list_engine",
"tests/test_config.py::test_omit_none_code_generation_flag_with_omit_none_by_default"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2023-01-06T19:50:23Z" | apache-2.0 |
|
G-Node__python-odml-304 | diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9e7f4ae..845c973 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -24,6 +24,19 @@ XML files via lxml. See #301.
The `odmlconversion` convenience console script has been added to convert multiple
previous odML version files to the latest odML version.
+## Changes in cloning behaviour
+
+When cloning a `Section` or a `Property` by default the id of any object is changed
+to a new UUID. The cloning methods now feature a new `keep_id` attribute. If set to
+`True`, the cloned object and any cloned children retain their original id. This
+is meant to create exact copies of Section-Property trees in different documents.
+
+## Additional validation
+
+When a document is saved, a new validation check makes sure, that a document
+contains only unique UUIDs this is required due to the introduction of creating
+clones with identical ids.
+
# Version 1.4.1
diff --git a/odml/base.py b/odml/base.py
index 979e54f..1c64e5b 100644
--- a/odml/base.py
+++ b/odml/base.py
@@ -581,7 +581,7 @@ class Sectionable(BaseObject):
for i in self:
i.clean()
- def clone(self, children=True):
+ def clone(self, children=True, keep_id=False):
"""
Clone this object recursively allowing to copy it independently
to another document
@@ -592,7 +592,7 @@ class Sectionable(BaseObject):
obj._sections = SmartList(BaseSection)
if children:
for s in self._sections:
- obj.append(s.clone())
+ obj.append(s.clone(keep_id=keep_id))
return obj
diff --git a/odml/property.py b/odml/property.py
index d3ea8b8..92f9245 100644
--- a/odml/property.py
+++ b/odml/property.py
@@ -407,15 +407,20 @@ class BaseProperty(base.BaseObject):
return self.parent.get_path() + ":" + self.name
- def clone(self):
+ def clone(self, keep_id=False):
"""
- Clone this object to copy it independently to another document.
- The id of the cloned object will be set to a different uuid.
+ Clone this property to copy it independently to another document.
+ By default the id of the cloned object will be set to a different uuid.
+
+ :param keep_id: If this attribute is set to True, the uuid of the
+ object will remain unchanged.
+ :return: The cloned property
"""
obj = super(BaseProperty, self).clone()
obj._parent = None
obj.value = self._value
- obj._id = str(uuid.uuid4())
+ if not keep_id:
+ obj.new_id()
return obj
diff --git a/odml/section.py b/odml/section.py
index b026043..3c47630 100644
--- a/odml/section.py
+++ b/odml/section.py
@@ -390,18 +390,26 @@ class BaseSection(base.Sectionable):
else:
raise ValueError("Can only remove sections and properties")
- def clone(self, children=True):
+ def clone(self, children=True, keep_id=False):
"""
- Clone this object recursively allowing to copy it independently
- to another document
+ Clone this Section allowing to copy it independently
+ to another document. By default the id of any cloned
+ object will be set to a new uuid.
+
+ :param children: If True, also clone child sections and properties
+ recursively.
+ :param keep_id: If this attribute is set to True, the uuids of the
+ Section and all child objects will remain unchanged.
+ :return: The cloned Section.
"""
- obj = super(BaseSection, self).clone(children)
- obj._id = str(uuid.uuid4())
+ obj = super(BaseSection, self).clone(children, keep_id)
+ if not keep_id:
+ obj.new_id()
obj._props = base.SmartList(BaseProperty)
if children:
for p in self._props:
- obj.append(p.clone())
+ obj.append(p.clone(keep_id))
return obj
diff --git a/odml/tools/odmlparser.py b/odml/tools/odmlparser.py
index 27fc9eb..00dbdec 100644
--- a/odml/tools/odmlparser.py
+++ b/odml/tools/odmlparser.py
@@ -50,7 +50,7 @@ class ODMLWriter:
msg = ""
for err in validation.errors:
if err.is_error:
- msg += "\n\t- %s %s: %s" % (err.obj, err.type, err.msg)
+ msg += "\n\t- %s %s: %s" % (err.obj, err.rank, err.msg)
if msg != "":
msg = "Resolve document validation errors before saving %s" % msg
raise ParserException(msg)
diff --git a/odml/validation.py b/odml/validation.py
index 3113683..0940f33 100644
--- a/odml/validation.py
+++ b/odml/validation.py
@@ -174,7 +174,7 @@ def section_unique_ids(parent, id_map=None):
yield i
if sec.id in id_map:
- yield ValidationError(sec, "Duplicate id in Section '%s' and '%s'" %
+ yield ValidationError(sec, "Duplicate id in Section '%s' and %s" %
(sec.get_path(), id_map[sec.id]))
else:
id_map[sec.id] = "Section '%s'" % sec.get_path()
@@ -203,7 +203,7 @@ def property_unique_ids(section, id_map=None):
for prop in section.properties:
if prop.id in id_map:
- yield ValidationError(prop, "Duplicate id in Property '%s' and '%s'" %
+ yield ValidationError(prop, "Duplicate id in Property '%s' and %s" %
(prop.get_path(), id_map[prop.id]))
else:
id_map[prop.id] = "Property '%s'" % prop.get_path()
| G-Node/python-odml | 040fe230166c642810a991d801207090fe01382a | diff --git a/test/test_property.py b/test/test_property.py
index 0877e3b..e99a20d 100644
--- a/test/test_property.py
+++ b/test/test_property.py
@@ -623,6 +623,11 @@ class TestProperty(unittest.TestCase):
self.assertIsNotNone(prop.parent)
self.assertIsNone(clone_prop.parent)
+ # Check keep_id
+ prop = Property(name="keepid")
+ clone_prop = prop.clone(True)
+ self.assertEqual(prop.id, clone_prop.id)
+
def test_get_merged_equivalent(self):
sec = Section(name="parent")
mersec = Section(name="merged_section")
diff --git a/test/test_section.py b/test/test_section.py
index f4b8252..395a26d 100644
--- a/test/test_section.py
+++ b/test/test_section.py
@@ -274,6 +274,30 @@ class TestSection(unittest.TestCase):
self.assertListEqual(clone_sec.sections, [])
self.assertListEqual(clone_sec.properties, [])
+ def test_clone_keep_id(self):
+ # Check id kept in clone.
+ sec = Section(name="original")
+ clone_sec = sec.clone(keep_id=True)
+ self.assertEqual(sec, clone_sec)
+ self.assertEqual(sec.id, clone_sec.id)
+
+ # Check cloned child Sections keep their ids.
+ Section(name="sec_one", parent=sec)
+ Section(name="sec_two", parent=sec)
+ clone_sec = sec.clone(keep_id=True)
+ self.assertListEqual(sec.sections, clone_sec.sections)
+ self.assertEqual(sec.sections["sec_one"], clone_sec.sections["sec_one"])
+ self.assertEqual(sec.sections["sec_one"].id, clone_sec.sections["sec_one"].id)
+
+ # Check cloned child Properties keep their ids.
+ Property(name="prop_one", parent=sec)
+ Property(name="prop_two", parent=sec)
+ clone_sec = sec.clone(keep_id=True)
+ self.assertListEqual(sec.properties, clone_sec.properties)
+ self.assertEqual(sec.properties["prop_one"], clone_sec.properties["prop_one"])
+ self.assertEqual(sec.properties["prop_one"].id,
+ clone_sec.properties["prop_one"].id)
+
def test_reorder(self):
# Test reorder of document sections
doc = Document()
diff --git a/test/test_validation.py b/test/test_validation.py
index b2e5f7d..df616fe 100644
--- a/test/test_validation.py
+++ b/test/test_validation.py
@@ -98,3 +98,31 @@ class TestValidation(unittest.TestCase):
p.dependency = "p2"
res = validate(doc)
self.assertError(res, "non-existent dependency object")
+
+ def test_property_unique_ids(self):
+ """
+ Test if identical ids in properties raise a validation error
+ """
+ doc = odml.Document()
+ sec_one = odml.Section("sec1", parent=doc)
+ sec_two = odml.Section("sec2", parent=doc)
+ prop = odml.Property("prop", parent=sec_one)
+
+ cprop = prop.clone(keep_id=True)
+ sec_two.append(cprop)
+
+ res = validate(doc)
+ self.assertError(res, "Duplicate id in Property")
+
+ def test_section_unique_ids(self):
+ """
+ Test if identical ids in sections raise a validation error.
+ """
+ doc = odml.Document()
+ sec = odml.Section("sec", parent=doc)
+
+ csec = sec.clone(keep_id=True)
+ sec.append(csec)
+
+ res = validate(doc)
+ self.assertError(res, "Duplicate id in Section")
| Clone id handling
Currently the `id` of a Property, Section or a Document (and their children) remains the same if the object is cloned.
- Since these ids should be used only once in a Document, by default the id of the clone and all potentially cloned children should be set to new UUIDs.
- The id attribute has to be excluded in the `baseobject.__eq__()` method.
- The clone method should also contain a `keep_id` flag which by default is `False`. If set to `True`, the old id value is kept e.g. when attaching the exact same odML object to another Document.
- An additional validation check needs to prohibit the saving of a Document containing odML objects with identical ids.
- Currently ids of an odML entity cannot be set or changed after they have been created. Add a method `new_id()` to assign a new UUID to an odML entity analogous to the UUID assignment in the odML Entity `__init__`.
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/test_property.py::TestProperty::test_clone",
"test/test_section.py::TestSection::test_clone_keep_id",
"test/test_validation.py::TestValidation::test_property_unique_ids",
"test/test_validation.py::TestValidation::test_section_unique_ids"
] | [
"test/test_property.py::TestProperty::test_bool_conversion",
"test/test_property.py::TestProperty::test_comparison",
"test/test_property.py::TestProperty::test_dtype",
"test/test_property.py::TestProperty::test_get_merged_equivalent",
"test/test_property.py::TestProperty::test_get_path",
"test/test_property.py::TestProperty::test_get_set_value",
"test/test_property.py::TestProperty::test_id",
"test/test_property.py::TestProperty::test_merge",
"test/test_property.py::TestProperty::test_merge_check",
"test/test_property.py::TestProperty::test_name",
"test/test_property.py::TestProperty::test_new_id",
"test/test_property.py::TestProperty::test_parent",
"test/test_property.py::TestProperty::test_simple_attributes",
"test/test_property.py::TestProperty::test_str_to_int_convert",
"test/test_property.py::TestProperty::test_value",
"test/test_property.py::TestProperty::test_value_append",
"test/test_property.py::TestProperty::test_value_extend",
"test/test_section.py::TestSection::test_append",
"test/test_section.py::TestSection::test_children",
"test/test_section.py::TestSection::test_clone",
"test/test_section.py::TestSection::test_comparison",
"test/test_section.py::TestSection::test_contains",
"test/test_section.py::TestSection::test_extend",
"test/test_section.py::TestSection::test_id",
"test/test_section.py::TestSection::test_include",
"test/test_section.py::TestSection::test_insert",
"test/test_section.py::TestSection::test_link",
"test/test_section.py::TestSection::test_merge",
"test/test_section.py::TestSection::test_merge_check",
"test/test_section.py::TestSection::test_name",
"test/test_section.py::TestSection::test_new_id",
"test/test_section.py::TestSection::test_parent",
"test/test_section.py::TestSection::test_path",
"test/test_section.py::TestSection::test_remove",
"test/test_section.py::TestSection::test_reorder",
"test/test_section.py::TestSection::test_repository",
"test/test_section.py::TestSection::test_simple_attributes",
"test/test_section.py::TestSection::test_unmerge",
"test/test_validation.py::TestValidation::test_errorfree",
"test/test_validation.py::TestValidation::test_property_in_terminology",
"test/test_validation.py::TestValidation::test_property_values",
"test/test_validation.py::TestValidation::test_section_in_terminology",
"test/test_validation.py::TestValidation::test_section_type",
"test/test_validation.py::TestValidation::test_uniques"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2018-10-25T15:56:47Z" | bsd-4-clause |
|
GAA-UAM__scikit-fda-142 | diff --git a/skfda/representation/_functional_data.py b/skfda/representation/_functional_data.py
index a1458587..e423b205 100644
--- a/skfda/representation/_functional_data.py
+++ b/skfda/representation/_functional_data.py
@@ -6,16 +6,15 @@ objects of the package and contains some commons methods.
from abc import ABC, abstractmethod, abstractproperty
-import numpy as np
-
-import matplotlib.patches as mpatches
-
-import matplotlib.pyplot as plt
from matplotlib.axes import Axes
import mpl_toolkits.mplot3d
import pandas.api.extensions
-from skfda.representation.extrapolation import _parse_extrapolation
+import matplotlib.patches as mpatches
+import matplotlib.pyplot as plt
+import numpy as np
+from .extrapolation import _parse_extrapolation
+
from .._utils import _coordinate_list, _list_of_arrays, constants
@@ -997,7 +996,7 @@ class FData(ABC, pandas.api.extensions.ExtensionArray):
# Selects the number of points
if npoints is None:
- npoints = 2*(constants.N_POINTS_SURFACE_PLOT_AX,)
+ npoints = 2 * (constants.N_POINTS_SURFACE_PLOT_AX,)
elif np.isscalar(npoints):
npoints = (npoints, npoints)
elif len(npoints) != 2:
@@ -1218,22 +1217,29 @@ class FData(ABC, pandas.api.extensions.ExtensionArray):
@classmethod
def _from_sequence(cls, scalars, dtype=None, copy=False):
- return cls(scalars, dtype=dtype)
+ if copy:
+ scalars = [f.copy() for f in scalars]
+
+ if dtype is not None and dtype != cls.dtype.fget(None):
+ raise ValueError(f"Invalid dtype {dtype}")
+
+ return cls._concat_same_type(scalars)
@classmethod
def _from_factorized(cls, values, original):
- return cls(values)
+ raise NotImplementedError("Factorization does not make sense for "
+ "functional data")
def isna(self):
"""
A 1-D array indicating if each value is missing.
Returns:
- na_values (np.ndarray): Array full of True values.
+ na_values (np.ndarray): Array full of False values.
"""
- return np.ones(self.nsamples, dtype=bool)
+ return np.zeros(self.nsamples, dtype=bool)
- def take(self, indices, allow_fill=False, fill_value=None):
+ def take(self, indices, allow_fill=False, fill_value=None, axis=0):
"""Take elements from an array.
Parameters:
@@ -1278,6 +1284,12 @@ class FData(ABC, pandas.api.extensions.ExtensionArray):
pandas.api.extensions.take
"""
from pandas.core.algorithms import take
+
+ # The axis parameter must exist, because sklearn tries to use take
+ # instead of __getitem__
+ if axis != 0:
+ raise ValueError(f"Axis must be 0, not {axis}")
+
# If the ExtensionArray is backed by an ndarray, then
# just pass that here instead of coercing to object.
data = self.astype(object)
@@ -1307,10 +1319,4 @@ class FData(ABC, pandas.api.extensions.ExtensionArray):
first, *others = to_concat
- for o in others:
- first = first.concatenate(o)
-
- # When #101 is ready
- # return first.concatenate(others)
-
- return first
+ return first.concatenate(*others)
diff --git a/skfda/representation/grid.py b/skfda/representation/grid.py
index e28b69e2..e9a3f279 100644
--- a/skfda/representation/grid.py
+++ b/skfda/representation/grid.py
@@ -6,18 +6,18 @@ list of discretisation points.
"""
+import copy
import numbers
-import copy
-import numpy as np
-import scipy.stats.mstats
import pandas.api.extensions
+import scipy.stats.mstats
+import numpy as np
-from . import basis as fdbasis
-from .interpolation import SplineInterpolator
from . import FData
+from . import basis as fdbasis
from .._utils import _list_of_arrays, constants
+from .interpolation import SplineInterpolator
__author__ = "Miguel Carbajo Berrocal"
@@ -302,16 +302,6 @@ class FDataGrid(FData):
return FDataGrid._CoordinateIterator(self)
- @property
- def ndim(self):
- """Return number of dimensions of the data matrix.
-
- Returns:
- int: Number of dimensions of the data matrix.
-
- """
- return self.data_matrix.ndim
-
@property
def nsamples(self):
"""Return number of rows of the data_matrix. Also the number of samples.
@@ -580,6 +570,47 @@ class FDataGrid(FData):
return self.copy(data_matrix=[
scipy.stats.mstats.gmean(self.data_matrix, 0)])
+ def __eq__(self, other):
+ """Comparison of FDataGrid objects"""
+ if not isinstance(other, FDataGrid):
+ return NotImplemented
+
+ if not np.array_equal(self.data_matrix, other.data_matrix):
+ return False
+
+ if len(self.sample_points) != len(other.sample_points):
+ return False
+
+ for a, b in zip(self.sample_points, other.sample_points):
+ if not np.array_equal(a, b):
+ return False
+
+ if not np.array_equal(self.domain_range, other.domain_range):
+ return False
+
+ if self.dataset_label != other.dataset_label:
+ return False
+
+ if self.axes_labels is None or other.axes_labels is None:
+ # Both must be None
+ if self.axes_labels is not other.axes_labels:
+ return False
+ else:
+ if len(self.axes_labels) != len(other.axes_labels):
+ return False
+
+ for a, b in zip(self.axes_labels, other.axes_labels):
+ if a != b:
+ return False
+
+ if self.extrapolation != other.extrapolation:
+ return False
+
+ if self.interpolator != other.interpolator:
+ return False
+
+ return True
+
def __add__(self, other):
"""Addition for FDataGrid object.
diff --git a/skfda/representation/interpolation.py b/skfda/representation/interpolation.py
index 435973bf..a8ec37f4 100644
--- a/skfda/representation/interpolation.py
+++ b/skfda/representation/interpolation.py
@@ -3,15 +3,15 @@ Module to interpolate functional data objects.
"""
-import numpy as np
-
-# Scipy interpolator methods used internally
from scipy.interpolate import (PchipInterpolator, UnivariateSpline,
RectBivariateSpline, RegularGridInterpolator)
+import numpy as np
+
from .evaluator import Evaluator, EvaluatorConstructor
+# Scipy interpolator methods used internally
class SplineInterpolator(EvaluatorConstructor):
r"""Spline interpolator of :class:`FDataGrid`.
@@ -85,7 +85,7 @@ class SplineInterpolator(EvaluatorConstructor):
return (super().__eq__(other) and
self.interpolation_order == other.interpolation_order and
self.smoothness_parameter == other.smoothness_parameter and
- self.monoton == other.monotone)
+ self.monotone == other.monotone)
def evaluator(self, fdatagrid):
"""Construct a SplineInterpolatorEvaluator used in the evaluation.
| GAA-UAM/scikit-fda | 2e5f88a3ba9c97696fabcf44b86579d879a851d3 | diff --git a/tests/test_grid.py b/tests/test_grid.py
index 483a5cab..52a31d98 100644
--- a/tests/test_grid.py
+++ b/tests/test_grid.py
@@ -1,10 +1,10 @@
import unittest
-import numpy as np
import scipy.stats.mstats
-from skfda.exploratory import stats
+import numpy as np
from skfda import FDataGrid
+from skfda.exploratory import stats
class TestFDataGrid(unittest.TestCase):
@@ -20,6 +20,10 @@ class TestFDataGrid(unittest.TestCase):
np.testing.assert_array_equal(
fd.sample_points, np.array([[0., 0.25, 0.5, 0.75, 1.]]))
+ def test_copy_equals(self):
+ fd = FDataGrid([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6]])
+ self.assertEqual(fd, fd.copy())
+
def test_mean(self):
fd = FDataGrid([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6]])
mean = stats.mean(fd)
@@ -69,21 +73,6 @@ class TestFDataGrid(unittest.TestCase):
[3, 4, 5, 6, 7], [4, 5, 6, 7, 8]])
np.testing.assert_array_equal(fd1.axes_labels, fd.axes_labels)
- def test_concatenate(self):
- fd1 = FDataGrid([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6]])
- fd2 = FDataGrid([[3, 4, 5, 6, 7], [4, 5, 6, 7, 8]])
-
- fd1.axes_labels = ["x", "y"]
- fd = fd1.concatenate(fd2)
-
- np.testing.assert_equal(fd.nsamples, 4)
- np.testing.assert_equal(fd.ndim_image, 1)
- np.testing.assert_equal(fd.ndim_domain, 1)
- np.testing.assert_array_equal(fd.data_matrix[..., 0],
- [[1, 2, 3, 4, 5], [2, 3, 4, 5, 6],
- [3, 4, 5, 6, 7], [4, 5, 6, 7, 8]])
- np.testing.assert_array_equal(fd1.axes_labels, fd.axes_labels)
-
def test_concatenate_coordinates(self):
fd1 = FDataGrid([[1, 2, 3, 4], [2, 3, 4, 5]])
fd2 = FDataGrid([[3, 4, 5, 6], [4, 5, 6, 7]])
diff --git a/tests/test_pandas.py b/tests/test_pandas.py
new file mode 100644
index 00000000..cf25e9b3
--- /dev/null
+++ b/tests/test_pandas.py
@@ -0,0 +1,45 @@
+import unittest
+
+import pandas as pd
+import skfda
+
+
+class TestPandas(unittest.TestCase):
+
+ def setUp(self):
+ self.fd = skfda.FDataGrid(
+ [[1, 2, 3, 4, 5, 6, 7], [2, 3, 4, 5, 6, 7, 9]])
+ self.fd_basis = self.fd.to_basis(skfda.representation.basis.BSpline(
+ domain_range=self.fd.domain_range, nbasis=5))
+
+ def test_fdatagrid_series(self):
+ series = pd.Series(self.fd)
+ self.assertEqual(
+ series.dtype, skfda.representation.grid.FDataGridDType)
+ self.assertEqual(len(series), self.fd.nsamples)
+ self.assertEqual(series[0], self.fd[0])
+
+ def test_fdatabasis_series(self):
+ series = pd.Series(self.fd_basis)
+ self.assertEqual(
+ series.dtype, skfda.representation.basis.FDataBasisDType)
+ self.assertEqual(len(series), self.fd_basis.nsamples)
+ self.assertEqual(series[0], self.fd_basis[0])
+
+ def test_fdatagrid_dataframe(self):
+ df = pd.DataFrame({"function": self.fd})
+ self.assertEqual(
+ df["function"].dtype, skfda.representation.grid.FDataGridDType)
+ self.assertEqual(len(df["function"]), self.fd.nsamples)
+ self.assertEqual(df["function"][0], self.fd[0])
+
+ def test_fdatabasis_dataframe(self):
+ df = pd.DataFrame({"function": self.fd_basis})
+ self.assertEqual(
+ df["function"].dtype, skfda.representation.basis.FDataBasisDType)
+ self.assertEqual(len(df["function"]), self.fd_basis.nsamples)
+ self.assertEqual(df["function"][0], self.fd_basis[0])
+
+ def test_take(self):
+ self.assertEqual(self.fd.take(0), self.fd[0])
+ self.assertEqual(self.fd.take(0, axis=0), self.fd[0])
| Problem with pandas methods
After update the neighbors brach (#112), I have an error on this line:
https://github.com/GAA-UAM/scikit-fda/blob/91d96eceee49400962515b8b10ee21d842fdc97f/examples/plot_k_neighbors_classification.py#L61
> Traceback (most recent call last):
File "plot_k_neighbors_classification.py", line 63, in <module>
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=0)
File "/Users/pablomm/anaconda3/lib/python3.6/site-packages/sklearn/model_selection/_split.py", line 2124, in train_test_split
safe_indexing(a, test)) for a in arrays))
File "/Users/pablomm/anaconda3/lib/python3.6/site-packages/sklearn/model_selection/_split.py", line 2124, in <genexpr>
safe_indexing(a, test)) for a in arrays))
File "/Users/pablomm/anaconda3/lib/python3.6/site-packages/sklearn/utils/__init__.py", line 219, in safe_indexing
return X.take(indices, axis=0)
TypeError: take() got an unexpected keyword argument 'axis'
It seems that the sklearn API detects that the FData has the ``take`` method and uses it to slice the samples, but using the axis argument.
In fact, the take method also does not work properly without the axis parameter.
```python
>>> import skfda
>>> a = skfda.datasets.make_sinusoidal_process()
>>> a.take([1,2,3])
```
> Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/pablomm/anaconda3/lib/python3.6/site-packages/scikit_fda-0.2.3-py3.6-macosx-10.7-x86_64.egg/skfda/representation/_functional_data.py", line 1288, in take
return self._from_sequence(result, dtype=self.dtype)
File "/Users/pablomm/anaconda3/lib/python3.6/site-packages/scikit_fda-0.2.3-py3.6-macosx-10.7-x86_64.egg/skfda/representation/_functional_data.py", line 1224, in _from_sequence
return cls(scalars, dtype=dtype)
TypeError: __init__() got an unexpected keyword argument 'dtype' | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_grid.py::TestFDataGrid::test_copy_equals",
"tests/test_pandas.py::TestPandas::test_fdatagrid_series"
] | [
"tests/test_grid.py::TestFDataGrid::test_concatenate",
"tests/test_grid.py::TestFDataGrid::test_concatenate_coordinates",
"tests/test_grid.py::TestFDataGrid::test_coordinates",
"tests/test_grid.py::TestFDataGrid::test_gmean",
"tests/test_grid.py::TestFDataGrid::test_init",
"tests/test_grid.py::TestFDataGrid::test_mean",
"tests/test_grid.py::TestFDataGrid::test_slice",
"tests/test_pandas.py::TestPandas::test_fdatabasis_series"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2019-07-25T13:46:16Z" | bsd-3-clause |
|
GIScience__openrouteservice-py-17 | diff --git a/openrouteservice/isochrones.py b/openrouteservice/isochrones.py
index 5e6850c..14a8d73 100644
--- a/openrouteservice/isochrones.py
+++ b/openrouteservice/isochrones.py
@@ -20,16 +20,17 @@ from openrouteservice import convert
def isochrones(client, locations,
- profile='driving-car',
- range_type=None,
- intervals=[60],
- segments=30,
- units=None,
- location_type=None,
- attributes=None,
- #options=None,
- intersections=None,
- dry_run=None):
+ profile='driving-car',
+ range_type=None,
+ intervals=[60],
+ segments=30,
+ units=None,
+ location_type=None,
+ smoothing=None,
+ attributes=None,
+ # options=None,
+ intersections=None,
+ dry_run=None):
""" Gets travel distance and time for a matrix of origins and destinations.
:param locations: One pair of lng/lat values.
@@ -65,6 +66,10 @@ def isochrones(client, locations,
'destination' as goal. Default 'start'.
:type location_type: string
+ :param smoothing: Applies a level of generalisation to the isochrone polygons generated.
+ Value between 0 and 1, whereas a value closer to 1 will result in a more generalised shape.
+ :type smoothing: float
+
:param attributes: 'area' returns the area of each polygon in its feature
properties. 'reachfactor' returns a reachability score between 0 and 1.
'total_pop' returns population statistics from https://ghsl.jrc.ec.europa.eu/about.php.
@@ -120,6 +125,9 @@ def isochrones(client, locations,
if location_type:
params["location_type"] = location_type
+ if smoothing:
+ params["smoothing"] = convert._format_float(smoothing)
+
if attributes:
params["attributes"] = convert._pipe_list(attributes)
| GIScience/openrouteservice-py | 0d3a56f242f668429f91f87dc9b4e7baf4fc581c | diff --git a/test/test_client.py b/test/test_client.py
index e45e60d..12aeb1a 100644
--- a/test/test_client.py
+++ b/test/test_client.py
@@ -74,19 +74,13 @@ class ClientTest(_test.TestCase):
# Assume more queries_per_minute than allowed by API policy and
# don't allow retries if API throws 'rate exceeded' error, which
# should be caught.
- queries_per_minute = 60
+ queries_per_minute = 110
query_range = range(queries_per_minute * 2)
-
- for _ in query_range:
- responses.add(responses.GET,
- 'https://api.openrouteservice.org/directions',
- body='{"status":"OK","results":[]}',
- status=200,
- content_type='application/json')
- client = openrouteservice.Client(key='58d904a497c67e00015b45fcb6f22c2dd2774733ad9f56f9662de7d3',
+ client = openrouteservice.Client(key='5b3ce3597851110001cf624870cf2f2a58d44c718542b3088221b684',
queries_per_minute=queries_per_minute,
retry_over_query_limit=False)
+
with self.assertRaises(openrouteservice.exceptions._OverQueryLimit):
for _ in query_range:
client.directions(self.coords_valid)
diff --git a/test/test_distance_matrix.py b/test/test_distance_matrix.py
index db4c0f9..46d8f86 100644
--- a/test/test_distance_matrix.py
+++ b/test/test_distance_matrix.py
@@ -56,7 +56,7 @@ class DistanceMatrixTest(_test.TestCase):
destinations=destinations)
self.assertEqual(1, len(responses.calls))
- self.assertURLEqual('https://api.openrouteservice.org/matrix?api_key={}'.format(self.key),
+ self.assertURLEqual('https://api.openrouteservice.org/matrix?api_key={}&profile=driving-car'.format(self.key),
responses.calls[0].request.url)
@responses.activate
@@ -93,6 +93,6 @@ class DistanceMatrixTest(_test.TestCase):
resp = self.client.distance_matrix(**query)
self.assertEqual(1, len(responses.calls))
- self.assertURLEqual('https://api.openrouteservice.org/matrix?api_key={}'.format(self.key),
+ self.assertURLEqual('https://api.openrouteservice.org/matrix?api_key={}&profile=cycling-regular'.format(self.key),
responses.calls[0].request.url)
self.assertEqual(resp, payload)
\ No newline at end of file
diff --git a/test/test_isochrones.py b/test/test_isochrones.py
index 0f9b574..b83bb21 100644
--- a/test/test_isochrones.py
+++ b/test/test_isochrones.py
@@ -71,6 +71,7 @@ class DistanceMatrixTest(_test.TestCase):
intervals=[1000,2000],
units='m',
location_type='destination',
+ smoothing=0.5,
attributes=['area', 'reachfactor']
)
@@ -81,5 +82,6 @@ class DistanceMatrixTest(_test.TestCase):
'%2C38.106467%7C8.34234%2C48.23424&profile=cycling-regular&'
'range_type=distance&range=1000%2C2000&'
'units=m&location_type=destination&'
+ 'smoothing=0.5&'
'attributes=area|reachfactor&interval=30'.format(self.key),
responses.calls[0].request.url)
\ No newline at end of file
| Implement smoothing parameter for isochrone endpoint | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/test_isochrones.py::DistanceMatrixTest::test_all_params"
] | [
"test/test_isochrones.py::DistanceMatrixTest::test_basic_params",
"test/test_isochrones.py::DistanceMatrixTest::test_units_with_time",
"test/test_distance_matrix.py::DistanceMatrixTest::test_basic_params",
"test/test_distance_matrix.py::DistanceMatrixTest::test_all_params",
"test/test_client.py::ClientTest::test_queries_per_minute_sleep_function",
"test/test_client.py::ClientTest::test_dry_run",
"test/test_client.py::ClientTest::test_raise_timeout_retriable_requests",
"test/test_client.py::ClientTest::test_urlencode",
"test/test_client.py::ClientTest::test_invalid_api_key",
"test/test_client.py::ClientTest::test_no_api_key",
"test/test_client.py::ClientTest::test_host_override_with_parameters"
] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
} | "2018-09-27T08:53:08Z" | apache-2.0 |
|
GIScience__openrouteservice-py-31 | diff --git a/openrouteservice/__init__.py b/openrouteservice/__init__.py
index 6f697ff..d88a857 100644
--- a/openrouteservice/__init__.py
+++ b/openrouteservice/__init__.py
@@ -17,7 +17,7 @@
# the License.
#
-__version__ = "1.1.6"
+__version__ = "1.1.7"
# Make sure QGIS plugin can import openrouteservice-py
diff --git a/openrouteservice/client.py b/openrouteservice/client.py
index 5026041..0a75583 100644
--- a/openrouteservice/client.py
+++ b/openrouteservice/client.py
@@ -47,7 +47,7 @@ class Client(object):
def __init__(self, key=None,
base_url=_DEFAULT_BASE_URL,
- timeout=None,
+ timeout=60,
retry_timeout=60,
requests_kwargs=None,
queries_per_minute=40,
diff --git a/openrouteservice/geocode.py b/openrouteservice/geocode.py
index 6c008b4..ceca106 100644
--- a/openrouteservice/geocode.py
+++ b/openrouteservice/geocode.py
@@ -75,9 +75,9 @@ def pelias_search(client, text,
for details.
:type layers: list of strings
- :param country: Constrain query by country. Accepts alpha-2 or alpha-3
- digit ISO-3166 country codes.
- :type country: list of strings
+ :param country: Constrain query by country. Accepts a alpha-2 or alpha-3
+ digit ISO-3166 country code.
+ :type country: str
:param size: The amount of results returned. Default 10.
:type size: integer
@@ -125,7 +125,7 @@ def pelias_search(client, text,
params['layers'] = convert._comma_list(layers)
if country:
- params['country'] = country
+ params['boundary.country'] = country
if size:
params['size'] = size
@@ -170,9 +170,9 @@ def pelias_autocomplete(client, text,
:param rect_max_y: Max latitude by which to constrain request geographically.
:type rect_max_y: float
- :param country: Constrain query by country. Accepts alpha-2 or alpha-3
+ :param country: Constrain query by country. Accepts a alpha-2 or alpha-3
digit ISO-3166 country codes.
- :type country: list of strings
+ :type country: str
:param sources: The originating source of the data. One or more of
['osm', 'oa', 'wof', 'gn']. Currently only 'osm', 'wof' and 'gn' are
@@ -345,9 +345,9 @@ def pelias_reverse(client, point,
for details.
:type layers: list of strings
- :param country: Constrain query by country. Accepts alpha-2 or alpha-3
+ :param country: Constrain query by country. Accepts a alpha-2 or alpha-3
digit ISO-3166 country codes.
- :type country: list of strings
+ :type country: str
:param size: The amount of results returned. Default 10.
:type size: integer
@@ -377,7 +377,7 @@ def pelias_reverse(client, point,
params['layers'] = convert._comma_list(layers)
if country:
- params['country'] = country
+ params['boundary.country'] = country
if size:
params['size'] = size
diff --git a/openrouteservice/isochrones.py b/openrouteservice/isochrones.py
index 2ab933d..f83766a 100644
--- a/openrouteservice/isochrones.py
+++ b/openrouteservice/isochrones.py
@@ -22,9 +22,9 @@ from openrouteservice import convert, validator
def isochrones(client, locations,
profile='driving-car',
- range_type=None,
- intervals=[60],
- segments=30,
+ range_type='time',
+ intervals=None,
+ segments=None,
units=None,
location_type=None,
smoothing=None,
diff --git a/setup.py b/setup.py
index 9f4af14..3d12d4d 100644
--- a/setup.py
+++ b/setup.py
@@ -20,7 +20,7 @@ def readme():
return f.read()
setup(name='openrouteservice',
- version='1.1.6',
+ version='1.1.7',
description='Python client for requests to openrouteservice API services',
long_description=readme(),
classifiers=[
| GIScience/openrouteservice-py | a93c3ac62f31de39e92901598e779dde5ad7a306 | diff --git a/test/test_geocode.py b/test/test_geocode.py
index c4d8ab6..24ecc80 100644
--- a/test/test_geocode.py
+++ b/test/test_geocode.py
@@ -83,7 +83,7 @@ class GeocodingPeliasTest(_test.TestCase):
self.assertEqual(1, len(responses.calls))
self.assertURLEqual(
- 'https://api.openrouteservice.org/geocode/search?boundary.circle.lat=49.418431&boundary.circle.lon=8.675786&boundary.circle.radius=50&boundary.rect.max_lon=8.79405&boundary.rect.max_lat=49.459693&boundary.rect.min_lat=49.351764&boundary.rect.min_lon=8.573179&country=de&focus.point.lat=49.418431&focus.point.lon=8.675786&layers=locality%2Ccounty%2Cregion&size=5&sources=osm%2Cwof%2Cgn&text=Heidelberg&api_key=sample_key'.format(
+ 'https://api.openrouteservice.org/geocode/search?boundary.circle.lat=49.418431&boundary.circle.lon=8.675786&boundary.circle.radius=50&boundary.rect.max_lon=8.79405&boundary.rect.max_lat=49.459693&boundary.rect.min_lat=49.351764&boundary.rect.min_lon=8.573179&boundary.country=de&focus.point.lat=49.418431&focus.point.lon=8.675786&layers=locality%2Ccounty%2Cregion&size=5&sources=osm%2Cwof%2Cgn&text=Heidelberg&api_key=sample_key'.format(
self.key),
responses.calls[0].request.url)
@@ -131,6 +131,6 @@ class GeocodingPeliasTest(_test.TestCase):
self.assertEqual(1, len(responses.calls))
self.assertURLEqual(
- 'https://api.openrouteservice.org/geocode/reverse?boundary.circle.radius=50&country=de&layers=locality%2Ccounty%2Cregion&point.lat=49.418431&point.lon=8.675786&size=5&sources=osm%2Cwof%2Cgn&api_key=sample_key'.format(
+ 'https://api.openrouteservice.org/geocode/reverse?boundary.circle.radius=50&boundary.country=de&layers=locality%2Ccounty%2Cregion&point.lat=49.418431&point.lon=8.675786&size=5&sources=osm%2Cwof%2Cgn&api_key=sample_key'.format(
self.key),
responses.calls[0].request.url)
diff --git a/test/test_isochrones.py b/test/test_isochrones.py
index 964f8c0..0d69ac2 100644
--- a/test/test_isochrones.py
+++ b/test/test_isochrones.py
@@ -22,7 +22,7 @@ import test as _test
import openrouteservice
-class DistanceMatrixTest(_test.TestCase):
+class IsochronesTest(_test.TestCase):
def setUp(self):
self.key = 'sample_key'
@@ -41,12 +41,13 @@ class DistanceMatrixTest(_test.TestCase):
status=200,
content_type='application/json')
- isochrone = self.client.isochrones(self.coords_valid[0])
+ isochrone = self.client.isochrones(self.coords_valid[0],
+ intervals=[60])
self.assertEqual(1, len(responses.calls))
self.assertURLEqual('https://api.openrouteservice.org/isochrones?api_key={}&'
'locations=9.970093%2C48.477473&'
- 'profile=driving-car&range=60&interval=30'.format(self.key),
+ 'profile=driving-car&range=60&range_type=time'.format(self.key),
responses.calls[0].request.url)
@responses.activate
@@ -67,16 +68,6 @@ class DistanceMatrixTest(_test.TestCase):
attributes=['area', 'reachfactor']
)
- iso_parameter = {'locations': [[9.970093, 48.477473], [9.207916, 49.153868]],
- 'profile': 'cycling-regular',
- 'range_type': 'distance',
- 'range': [1000, 2000],
- 'units': 'm',
- 'location_type': 'destination',
- 'attributes': ['area', 'reachfactor'],
- 'interval': [30]
- }
-
self.assertEqual(1, len(responses.calls))
self.assertURLEqual('https://api.openrouteservice.org/isochrones?api_key={}&'
'locations=9.970093%2C48.477473%7C9.207916'
@@ -85,5 +76,5 @@ class DistanceMatrixTest(_test.TestCase):
'range_type=distance&range=1000%2C2000&'
'units=m&location_type=destination&'
'smoothing=0.5&'
- 'attributes=area|reachfactor&interval=30'.format(self.key),
+ 'attributes=area|reachfactor'.format(self.key),
responses.calls[0].request.url)
| 'Country' restriction has wrong parameter
`boundary.country` instead of `country` for `/search` and `/reverse`, `/autocomplete` is fine. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/test_geocode.py::GeocodingPeliasTest::test_full_reverse",
"test/test_geocode.py::GeocodingPeliasTest::test_full_search",
"test/test_isochrones.py::IsochronesTest::test_all_params",
"test/test_isochrones.py::IsochronesTest::test_basic_params"
] | [
"test/test_geocode.py::GeocodingPeliasTest::test_full_autocomplete",
"test/test_geocode.py::GeocodingPeliasTest::test_full_structured"
] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2019-01-24T06:25:17Z" | apache-2.0 |
|
GIScience__openrouteservice-py-42 | diff --git a/docs/source/openrouteservice.rst b/docs/source/openrouteservice.rst
index 0139f7b..fff8892 100644
--- a/docs/source/openrouteservice.rst
+++ b/docs/source/openrouteservice.rst
@@ -76,14 +76,6 @@ openrouteservice\.optimization module
:undoc-members:
:show-inheritance:
-openrouteservice\.validator module
-------------------------------------
-
-.. automodule:: openrouteservice.validator
- :members:
- :undoc-members:
- :show-inheritance:
-
openrouteservice\.exceptions module
-----------------------------------
diff --git a/openrouteservice/directions.py b/openrouteservice/directions.py
index 1c28b06..39f0475 100644
--- a/openrouteservice/directions.py
+++ b/openrouteservice/directions.py
@@ -37,11 +37,13 @@ def directions(client,
geometry_simplify=None,
instructions=None,
instructions_format=None,
+ alternative_routes=None,
roundabout_exits=None,
attributes=None,
maneuvers=None,
radiuses=None,
bearings=None,
+ skip_segments=None,
continue_straight=None,
elevation=None,
extra_info=None,
@@ -103,6 +105,12 @@ def directions(client,
One of ["text", "html"]. Default "text".
:type instructions_format: string
+ :param alternative_routes: Specifies whether alternative routes are computed,
+ and parameters for the algorithm determining suitable alternatives. Expects
+ 3 keys: share_factor (float), target_count (int), weight_factor (float).
+ More on https://openrouteservice.org/dev/#/api-docs/v2/directions/{profile}/geojson/post.
+ :type alternative_routes: dict[int|float]
+
:param roundabout_exits: Provides bearings of the entrance and all passed
roundabout exits. Adds the 'exit_bearings' array to the 'step' object
in the response. Default False.
@@ -137,6 +145,11 @@ def directions(client,
waypoint may be reached.
:type bearings: list or tuple or lists or tuples
+ :param skip_segments: Specifies the segments that should be skipped in the route calculation.
+ A segment is the connection between two given coordinates and the counting starts with 1
+ for the connection between the first and second coordinate.
+ :type skip_segments: list[int]
+
:param continue_straight: Forces the route to keep going straight at waypoints
restricting u-turns even if u-turns would be faster. This setting
will work for all profiles except for driving-*. In this case you will
@@ -159,7 +172,7 @@ def directions(client,
:param optimized: If set False, forces to not use Contraction Hierarchies.
:type optimized: bool
- :param options: Refer to https://go.openrouteservice.org/documentation for
+ :param options: Refer to https://openrouteservice.org/dev/#/api-docs/v2/directions/{profile}/geojson/post for
detailed documentation. Construct your own dict() following the example
of the minified options object. Will be converted to json automatically.
:type options: dict
@@ -222,6 +235,9 @@ def directions(client,
if instructions_format:
params["instructions_format"] = instructions_format
+ if alternative_routes:
+ params["alternative_routes"] = alternative_routes
+
if roundabout_exits is not None:
params["roundabout_exits"] = roundabout_exits
@@ -237,6 +253,9 @@ def directions(client,
if bearings:
params["bearings"] = bearings
+ if skip_segments:
+ params["skip_segments"] = skip_segments
+
if continue_straight is not None:
params["continue_straight"] = continue_straight
diff --git a/openrouteservice/optimization.py b/openrouteservice/optimization.py
index 2f4b733..0c05c8c 100644
--- a/openrouteservice/optimization.py
+++ b/openrouteservice/optimization.py
@@ -19,8 +19,9 @@
def optimization(client,
- jobs,
- vehicles,
+ jobs=None,
+ vehicles=None,
+ shipments=None,
matrix=None,
geometry=None,
dry_run=None):
@@ -40,10 +41,13 @@ def optimization(client,
>>> result = api.optimization(jobs=jobs, vehicles=vehicles)
:param jobs: The Job objects to fulfill.
- :type jobs: list of :class:`openrouteservice.optimization.Job`
+ :type jobs: list of Job
:param vehicles: The vehicles to fulfill the :class:`openrouteservice.optimization.Job`'s.
- :type vehicles: list of :class:`openrouteservice.optimization.Vehicle`
+ :type vehicles: list of Vehicle
+
+ :param shipments: The Shipment objects to fulfill.
+ :type shipments: list of Shipment
:param matrix: Specify a custom cost matrix. If not specified, it will be calculated with
the :meth:`openrouteservice.matrix.matrix` endpoint.
@@ -59,11 +63,30 @@ def optimization(client,
:rtype: dict
"""
- assert all([isinstance(x, Job) for x in jobs])
assert all([isinstance(x, Vehicle) for x in vehicles])
- params = {"jobs": [job.__dict__ for job in jobs],
- "vehicles": [vehicle.__dict__ for vehicle in vehicles]}
+ params = {"vehicles": [vehicle.__dict__ for vehicle in vehicles]}
+
+ if jobs:
+ assert all([isinstance(x, Job) for x in jobs])
+ params['jobs'] = [job.__dict__ for job in jobs]
+ if shipments:
+ assert all([isinstance(x, Shipment) for x in shipments])
+ params['shipments'] = list()
+
+ for shipment in shipments:
+ shipment_dict = dict()
+ if getattr(shipment, 'pickup'):
+ assert isinstance(shipment.pickup, ShipmentStep)
+ shipment_dict['pickup'] = shipment.pickup.__dict__
+ if getattr(shipment, 'delivery'):
+ assert isinstance(shipment.delivery, ShipmentStep)
+ shipment_dict['delivery'] = shipment.delivery.__dict__
+ shipment_dict['amount'] = shipment.amount
+ shipment_dict['skills'] = shipment.skills
+ shipment_dict['priority'] = shipment.priority
+
+ params['shipments'].append(shipment_dict)
if geometry is not None:
params.update({"options": {"g": geometry}})
@@ -87,6 +110,7 @@ class Job(object):
service=None,
amount=None,
skills=None,
+ priority=None,
time_windows=None
):
"""
@@ -111,6 +135,9 @@ class Job(object):
:param skills: An array of integers defining mandatory skills for this job.
:type skills: list of int or tuple of int
+ :param priority: An integer in the [0, 10] range describing priority level (defaults to 0).
+ :type priority: int
+
:param time_windows: An array of time_window objects describing valid slots for job service start.
:type time_windows: list of lists of int
"""
@@ -132,10 +159,109 @@ class Job(object):
if skills is not None:
self.skills = skills
+ if priority is not None:
+ self.priority = priority
+
+ if time_windows is not None:
+ self.time_windows = time_windows
+
+
+class ShipmentStep(object):
+ """
+ Class to create a Shipment object for optimization endpoint.
+
+ Full documentation at https://github.com/VROOM-Project/vroom/blob/master/docs/API.md#shipments.
+ """
+ def __init__(self,
+ id=None,
+ location=None,
+ location_index=None,
+ service=None,
+ time_windows=None
+ ):
+ """
+ Create a shipment step object for the optimization endpoint.
+
+ :param id: Integer used as unique identifier.
+ :type id: int
+
+ :param location: Location of the job, as [lon, lat]. Optional if custom matrix is provided.
+ :type location: tuple of float or list of float
+
+ :param location_index: Index of relevant row and column in custom matrix. Mandatory if custom
+ matrix is provided. Irrelevant when no custom matrix is provided.
+ :type location_index: int
+
+ :param service: Optional job service duration in seconds
+ :type service: int
+
+ :param time_windows: An array of time_window objects describing valid slots for job service start.
+ :type time_windows: list of lists of int
+ """
+
+ self.id = id
+
+ if location is not None:
+ self.location = location
+
+ if location_index is not None:
+ self.location_index = location_index
+
+ if service is not None:
+ self.service = service
+
if time_windows is not None:
self.time_windows = time_windows
+class Shipment(object):
+ """
+ Class to create a Shipment object for optimization endpoint.
+
+ Full documentation at https://github.com/VROOM-Project/vroom/blob/master/docs/API.md#shipments.
+ """
+ def __init__(self,
+ pickup=None,
+ delivery=None,
+ amount=None,
+ skills=None,
+ priority=None
+ ):
+ """
+ Create a shipment object for the optimization endpoint.
+
+ :param pickup: a ShipmentStep object describing pickup
+ :type pickup: ShipmentStep
+
+ :param delivery: a ShipmentStep object describing delivery
+ :type delivery: ShipmentStep
+
+ :param amount: An array of integers describing multidimensional quantities.
+ :type amount: list of int or tuple of int
+
+ :param skills: An array of integers defining mandatory skills.
+ :type skills: list of int or tuple of int
+
+ :param priority: An integer in the [0, 10] range describing priority level (defaults to 0).
+ :type priority: int
+ """
+
+ if pickup is not None:
+ self.pickup = pickup
+
+ if delivery is not None:
+ self.delivery = delivery
+
+ if amount is not None:
+ self.amount = amount
+
+ if skills is not None:
+ self.skills = skills
+
+ if priority is not None:
+ self.priority = priority
+
+
class Vehicle(object):
"""
Class to create a Vehicle object for optimization endpoint.
| GIScience/openrouteservice-py | e8eb1e0ad4e13c810440c087512080b9ecf809b5 | diff --git a/test/test_helper.py b/test/test_helper.py
index 08afc2c..916002e 100644
--- a/test/test_helper.py
+++ b/test/test_helper.py
@@ -27,10 +27,16 @@ ENDPOINT_DICT = {
'suppress_warnings': False,
'instructions': 'false',
'instructions_format': 'html',
+ 'alternative_routes': {
+ 'share_factor': 0.6,
+ 'target_count': 2,
+ 'weight_factor': 1.4
+ },
'roundabout_exits': 'true',
'attributes': ['avgspeed'],
'radiuses': PARAM_LIST_ONE,
'bearings': PARAM_LIST_TWO,
+ 'skip_segments': [0, 1],
'elevation': 'true',
'extra_info': ['roadaccessrestrictions'],
'optimized': 'false',
@@ -129,6 +135,88 @@ ENDPOINT_DICT = {
'sortby': 'distance',
},
'optimization': {
+ "shipments": [
+ {
+ "pickup": {
+ "id": 0,
+ "location": [
+ 8.688641,
+ 49.420577
+ ],
+ "location_index": 0,
+ "service": 500,
+ "time_windows": [
+ [
+ 50,
+ 50
+ ]
+ ]
+ },
+ "delivery": {
+ "id": 0,
+ "location": [
+ 8.688641,
+ 49.420577
+ ],
+ "location_index": 0,
+ "service": 500,
+ "time_windows": [
+ [
+ 50,
+ 50
+ ]
+ ]
+ },
+ "amount": [
+ 50
+ ],
+ "skills": [
+ 50,
+ 50
+ ],
+ "priority": 50
+ },
+ {
+ "pickup": {
+ "id": 1,
+ "location": [
+ 8.680916,
+ 49.415776
+ ],
+ "location_index": 1,
+ "service": 500,
+ "time_windows": [
+ [
+ 50,
+ 50
+ ]
+ ]
+ },
+ "delivery": {
+ "id": 1,
+ "location": [
+ 8.680916,
+ 49.415776
+ ],
+ "location_index": 1,
+ "service": 500,
+ "time_windows": [
+ [
+ 50,
+ 50
+ ]
+ ]
+ },
+ "amount": [
+ 50
+ ],
+ "skills": [
+ 50,
+ 50
+ ],
+ "priority": 50
+ }
+ ],
"jobs": [
{
"id": 0,
@@ -137,6 +225,7 @@ ENDPOINT_DICT = {
"service": PARAM_INT_BIG,
"amount": [PARAM_INT_SMALL],
"skills": PARAM_LIST_ONE,
+ "priority": PARAM_INT_SMALL,
"time_windows": [PARAM_LIST_ONE]
},
{
@@ -146,6 +235,7 @@ ENDPOINT_DICT = {
"service": PARAM_INT_BIG,
"amount": [PARAM_INT_SMALL],
"skills": PARAM_LIST_ONE,
+ "priority": PARAM_INT_SMALL,
"time_windows": [PARAM_LIST_ONE]
}
],
diff --git a/test/test_optimization.py b/test/test_optimization.py
index f9e4cca..c2ced67 100644
--- a/test/test_optimization.py
+++ b/test/test_optimization.py
@@ -24,13 +24,13 @@ from copy import deepcopy
import json
from test.test_helper import *
-from openrouteservice.optimization import Job, Vehicle
+from openrouteservice.optimization import Job, Vehicle, ShipmentStep, Shipment
class OptimizationTest(_test.TestCase):
def _get_params(self):
- jobs, vehicles = list(), list()
+ jobs, vehicles, shipments = list(), list(), list()
for idx, coord in enumerate(PARAM_LINE):
jobs.append(Job(idx, location=coord,
@@ -38,6 +38,7 @@ class OptimizationTest(_test.TestCase):
location_index=idx,
amount=[PARAM_INT_SMALL],
skills=PARAM_LIST_ONE,
+ priority=PARAM_INT_SMALL,
time_windows=[PARAM_LIST_ONE]
))
@@ -49,11 +50,32 @@ class OptimizationTest(_test.TestCase):
capacity=[PARAM_INT_SMALL],
skills=PARAM_LIST_ONE,
time_window=PARAM_LIST_ONE))
- return jobs, vehicles
+
+ shipments.append(Shipment(
+ pickup=ShipmentStep(
+ idx,
+ location=coord,
+ location_index=idx,
+ service=PARAM_INT_BIG,
+ time_windows=[PARAM_LIST_ONE]
+ ),
+ delivery=ShipmentStep(
+ idx,
+ location=coord,
+ location_index=idx,
+ service=PARAM_INT_BIG,
+ time_windows=[PARAM_LIST_ONE]
+ ),
+ amount=[PARAM_INT_SMALL],
+ skills=PARAM_LIST_ONE,
+ priority=PARAM_INT_SMALL
+ ))
+
+ return jobs, vehicles, shipments
def test_jobs_vehicles_classes(self):
- jobs, vehicles = self._get_params()
+ jobs, vehicles, shipments = self._get_params()
self.assertEqual(ENDPOINT_DICT['optimization']['jobs'], [j.__dict__ for j in jobs])
self.assertEqual(ENDPOINT_DICT['optimization']['vehicles'], [v.__dict__ for v in vehicles])
@@ -62,7 +84,7 @@ class OptimizationTest(_test.TestCase):
def test_full_optimization(self):
query = deepcopy(ENDPOINT_DICT['optimization'])
- jobs, vehicles = self._get_params()
+ jobs, vehicles, shipments = self._get_params()
responses.add(responses.POST,
'https://api.openrouteservice.org/optimization',
@@ -70,6 +92,6 @@ class OptimizationTest(_test.TestCase):
status=200,
content_type='application/json')
- self.client.optimization(jobs, vehicles, geometry=False, matrix=PARAM_LIST_TWO)
+ self.client.optimization(jobs, vehicles, shipments, geometry=False, matrix=PARAM_LIST_TWO)
self.assertEqual(query, json.loads(responses.calls[0].request.body.decode('utf-8')))
| Add skip_segments and alternative_routes parameters | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/test_optimization.py::OptimizationTest::test_jobs_vehicles_classes",
"test/test_optimization.py::OptimizationTest::test_full_optimization"
] | [] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2020-05-11T19:29:16Z" | apache-2.0 |
|
GIScience__openrouteservice-py-67 | diff --git a/openrouteservice/client.py b/openrouteservice/client.py
index ea763c4..3711d80 100644
--- a/openrouteservice/client.py
+++ b/openrouteservice/client.py
@@ -20,6 +20,7 @@
from datetime import datetime
from datetime import timedelta
+import cgi
import functools
import requests
import json
@@ -257,10 +258,15 @@ class Client(object):
@staticmethod
def _get_body(response):
"""Returns the body of a response object, raises status code exceptions if necessary."""
- try:
- body = response.json()
- except json.JSONDecodeError: # pragma: no cover
- raise exceptions.HTTPError(response.status_code)
+ content_type = response.headers["Content-Type"]
+ mime_type, _ = cgi.parse_header(content_type)
+ if mime_type == "application/gpx+xml":
+ body = response.text
+ else:
+ try:
+ body = response.json()
+ except json.JSONDecodeError: # pragma: no cover
+ raise exceptions.HTTPError(response.status_code)
# error = body.get('error')
status_code = response.status_code
diff --git a/openrouteservice/directions.py b/openrouteservice/directions.py
index c42cdc1..5b6a69b 100644
--- a/openrouteservice/directions.py
+++ b/openrouteservice/directions.py
@@ -71,7 +71,7 @@ def directions(
:param format: Specifies the response format. One of ['json', 'geojson', 'gpx']. Default "json".
Geometry format for "json" is Google's encodedpolyline. The GPX schema the response is validated
against can be found here:
- https://raw.githubusercontent.com/GIScience/openrouteservice-schema/master/gpx/v1/ors-gpx.xsd.
+ https://raw.githubusercontent.com/GIScience/openrouteservice-schema/master/gpx/v2/ors-gpx.xsd.
:type format: str
:param format_out: DEPRECATED.
| GIScience/openrouteservice-py | ed5e5cd8ec406fad05381bf7bda64a77ce4bfe89 | diff --git a/test/test_directions.py b/test/test_directions.py
index b6e2db8..6fb3b66 100644
--- a/test/test_directions.py
+++ b/test/test_directions.py
@@ -25,7 +25,7 @@ import test as _test
from copy import deepcopy
from openrouteservice import exceptions
-from test.test_helper import ENDPOINT_DICT
+from test.test_helper import ENDPOINT_DICT, GPX_RESPONSE
class DirectionsTest(_test.TestCase):
@@ -48,6 +48,26 @@ class DirectionsTest(_test.TestCase):
self.assertEqual(resp, self.valid_query)
self.assertIn("sample_key", responses.calls[0].request.headers.values())
+ @responses.activate
+ def test_directions_gpx(self):
+ query = deepcopy(self.valid_query)
+ query["format"] = "gpx"
+
+ responses.add(
+ responses.POST,
+ "https://api.openrouteservice.org/v2/directions/{}/gpx".format(
+ self.valid_query["profile"]
+ ),
+ body=GPX_RESPONSE,
+ status=200,
+ content_type="application/gpx+xml;charset=UTF-8",
+ )
+
+ resp = self.client.directions(**query)
+
+ self.assertEqual(resp, GPX_RESPONSE)
+ self.assertIn("sample_key", responses.calls[0].request.headers.values())
+
@responses.activate
def test_directions_incompatible_parameters(self):
self.valid_query["optimized"] = True
diff --git a/test/test_helper.py b/test/test_helper.py
index f2d12b8..459e554 100644
--- a/test/test_helper.py
+++ b/test/test_helper.py
@@ -225,3 +225,29 @@ ENDPOINT_DICT = {
"matrix": PARAM_LIST_TWO,
},
}
+
+GPX_RESPONSE = """
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<gpx version="1.0" creator="openrouteservice" xmlns="https://raw.githubusercontent.com/GIScience/openrouteservice-schema/master/gpx/v2/ors-gpx.xsd">
+ <metadata>
+ <name>openrouteservice directions</name>
+ <desc>This is a directions instructions file as GPX, generated from openrouteservice</desc>
+ <author><name>openrouteservice</name>
+ <email id="support" domain="openrouteservice.heigit.org"/>
+ <link href="https://openrouteservice.org/">
+ <text>https://openrouteservice.org/</text>
+ <type>text/html</type>
+ </link>
+ </author>
+ <copyright author="openrouteservice.org | OpenStreetMap contributors">
+ <year>2021</year>
+ <license>LGPL 3.0</license>
+ </copyright>
+ <time>2021-07-25T17:26:59.023Z</time>
+ <bounds maxLat="51.501602" maxLon="0.147508" minLat="51.185303" minLon="-0.076743"/>
+ <extensions>
+ <system-message></system-message>
+ </extensions>
+ </metadata>
+</gpx>
+"""
| JSONDecodeError when requesting directions in gpx format
<!-- If you have a question rather than an actual issue, pls use our forum:-->
<!-- https://ask.openrouteservice.org/c/sdks-->
#### Here's what I did
<!-- best paste the results of 'dry_run' (see README.md), so we can see your configuration -->
```coordinates_lon_lat = [[-0.0858923, 51.5050313],
[-0.0743414, 51.5015841],
[-0.05273140000000039, 51.46430039999999],
[-0.0531279, 51.4637547],
[0.0320358, 51.3579627],
[0.030053528946478628, 51.3510888399767],
[0.0373899, 51.3508184],
[0.05585272964791204, 51.33450105290082],
[0.0528395, 51.3311335],
[0.1014503, 51.246361],
[0.14227140698558516, 51.18576100547525],
[0.1458905, 51.1853518],
[0.1459325, 51.1858536]]
gpx = directions.directions(clnt, coordinates_lon_lat, profile ='cycling-regular',
format = 'gpx',preference = 'recommended' )
```
The same request is processed without any errors with format='json' or format='geojson' and the correct route is returned
dry_run output:
```url:
https://api.openrouteservice.org/v2/directions/driving-car/json?
Headers:
{
"headers": {
"User-Agent": "ORSClientPython.v2.3.0",
"Content-type": "application/json",
"Authorization": "5b3ce3597851110001cf62484bacb83d2107475198ea22650a25b872"
},
"timeout": 60,
"json": {
"coordinates": [
[
8.34234,
48.23424
],
[
8.34423,
48.26424
]
]
}
}```
---
#### Here's what I got
<!-- we :heart: json outputs -->
```---------------------------------------------------------------------------
JSONDecodeError Traceback (most recent call last)
~/miniconda3/envs/ox/lib/python3.8/site-packages/openrouteservice/client.py in _get_body(response)
228 try:
--> 229 body = response.json()
230 except json.JSONDecodeError:
~/miniconda3/envs/ox/lib/python3.8/site-packages/requests/models.py in json(self, **kwargs)
897 pass
--> 898 return complexjson.loads(self.text, **kwargs)
899
~/miniconda3/envs/ox/lib/python3.8/json/__init__.py in loads(s, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
356 parse_constant is None and object_pairs_hook is None and not kw):
--> 357 return _default_decoder.decode(s)
358 if cls is None:
~/miniconda3/envs/ox/lib/python3.8/json/decoder.py in decode(self, s, _w)
336 """
--> 337 obj, end = self.raw_decode(s, idx=_w(s, 0).end())
338 end = _w(s, end).end()
~/miniconda3/envs/ox/lib/python3.8/json/decoder.py in raw_decode(self, s, idx)
354 except StopIteration as err:
--> 355 raise JSONDecodeError("Expecting value", s, err.value) from None
356 return obj, end
JSONDecodeError: Expecting value: line 1 column 1 (char 0)
During handling of the above exception, another exception occurred:
HTTPError Traceback (most recent call last)
<ipython-input-129-0570940137d3> in <module>
----> 1 gpx = directions.directions(clnt, coordinates_lon_lat, profile ='cycling-regular',
2 format = 'gpx',preference = 'recommended' )
~/miniconda3/envs/ox/lib/python3.8/site-packages/openrouteservice/directions.py in directions(client, coordinates, profile, format_out, format, preference, units, language, geometry, geometry_simplify, instructions, instructions_format, alternative_routes, roundabout_exits, attributes, maneuvers, radiuses, bearings, skip_segments, continue_straight, elevation, extra_info, suppress_warnings, optimized, optimize_waypoints, options, validate, dry_run)
279 params['options'] = options
280
--> 281 return client.request("/v2/directions/" + profile + '/' + format, {}, post_json=params, dry_run=dry_run)
282
283
~/miniconda3/envs/ox/lib/python3.8/site-packages/openrouteservice/client.py in request(self, url, get_params, first_request_time, retry_counter, requests_kwargs, post_json, dry_run)
202
203 try:
--> 204 result = self._get_body(response)
205
206 return result
~/miniconda3/envs/ox/lib/python3.8/site-packages/openrouteservice/client.py in _get_body(response)
229 body = response.json()
230 except json.JSONDecodeError:
--> 231 raise exceptions.HTTPError(response.status_code)
232
233 # error = body.get('error')
HTTPError: HTTP Error: 200
```
---
#### Here's what I was expecting
<!-- try being as explicit as possible here so we know how to fix this issue -->
Same directions in GPX format
The same request generated as Python snippet from ORS API playground works correctly:
```import requests
body = {"coordinates":[[-0.0858923,51.5050313],[-0.0743414,51.5015841],[-0.05273140000000039,51.46430039999999],[-0.0531279,51.4637547],[0.0320358,51.3579627],[0.030053528946478628,51.3510888399767],[0.0373899,51.3508184],[0.05585272964791204,51.33450105290082],[0.0528395,51.3311335],[0.1014503,51.246361],[0.14227140698558516,51.18576100547525],[0.1458905,51.1853518],[0.1459325,51.1858536]],"preference":"recommended"}
headers = {
'Accept': 'application/json, application/geo+json, application/gpx+xml, img/png; charset=utf-8',
'Authorization': '5b3ce3597851110001cf62484bacb83d2107475198ea22650a25b872',
'Content-Type': 'application/json; charset=utf-8'
}
call = requests.post('https://api.openrouteservice.org/v2/directions/cycling-regular/gpx', json=body, headers=headers)
print(call.status_code, call.reason)
print(call.text)
```
---
#### Here's what I think could be improved
API response in GPX format should be correctly parsed or delivered as is | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/test_directions.py::DirectionsTest::test_directions_gpx",
"test/test_directions.py::DirectionsTest::test_optimized_waypoints"
] | [
"test/test_directions.py::DirectionsTest::test_format_out_deprecation",
"test/test_directions.py::DirectionsTest::test_optimized_waypoints_shuffle"
] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2021-07-25T19:39:05Z" | apache-2.0 |
|
GSTT-CSC__hazen-312 | diff --git a/hazenlib/tasks/acr_geometric_accuracy.py b/hazenlib/tasks/acr_geometric_accuracy.py
new file mode 100644
index 0000000..b71f00b
--- /dev/null
+++ b/hazenlib/tasks/acr_geometric_accuracy.py
@@ -0,0 +1,241 @@
+"""
+ACR Geometric Accuracy
+https://www.acraccreditation.org/-/media/acraccreditation/documents/mri/largephantomguidance.pdf
+
+Calculates geometric accuracy for slices 1 and 5 of the ACR phantom.
+
+This script calculates the horizontal and vertical lengths of the ACR phantom in Slice 1 in accordance with the ACR Guidance.
+This script calculates the horizontal, vertical and diagonal lengths of the ACR phantom in Slice 5 in accordance with the ACR Guidance.
+The average distance measurement error, maximum distance measurement error and coefficient of variation of all distance
+measurements is reported as recommended by IPEM Report 112, "Quality Control and Artefacts in Magnetic Resonance Imaging".
+
+This is done by first producing a binary mask for each respective slice. Line profiles are drawn with aid of rotation
+matrices around the centre of the test object to determine each respective length. The results are also visualised.
+
+Created by Yassine Azma
[email protected]
+
+18/11/2022
+"""
+
+import sys
+import traceback
+import os
+import numpy as np
+import skimage.morphology
+import skimage.measure
+import skimage.transform
+
+from hazenlib.HazenTask import HazenTask
+
+
+class ACRGeometricAccuracy(HazenTask):
+
+ def __init__(self, **kwargs):
+ super().__init__(**kwargs)
+
+ def run(self) -> dict:
+ results = {}
+ z = []
+ for dcm in self.data:
+ z.append(dcm.ImagePositionPatient[2])
+
+ idx_sort = np.argsort(z)
+
+ for dcm in self.data:
+ if dcm.ImagePositionPatient[2] == z[idx_sort[0]]:
+ try:
+ result1 = self.get_geometric_accuracy_slice1(dcm)
+ except Exception as e:
+ print(f"Could not calculate the geometric accuracy for {self.key(dcm)} because of : {e}")
+ traceback.print_exc(file=sys.stdout)
+ continue
+
+ results[self.key(dcm)] = result1
+ elif dcm.ImagePositionPatient[2] == z[idx_sort[4]]:
+ try:
+ result5 = self.get_geometric_accuracy_slice5(dcm)
+ except Exception as e:
+ print(f"Could not calculate the geometric accuracy for {self.key(dcm)} because of : {e}")
+ traceback.print_exc(file=sys.stdout)
+ continue
+
+ results[self.key(dcm)] = result5
+
+ results['reports'] = {'images': self.report_files}
+
+ L = result1 + result5
+ mean_err, max_err, cov_l = self.distortion_metric(L)
+ print(f"Mean relative measurement error is equal to {np.round(mean_err, 2)}mm")
+ print(f"Maximum absolute measurement error is equal to {np.round(max_err, 2)}mm")
+ print(f"Coefficient of variation of measurements is equal to {np.round(cov_l, 2)}%")
+ return results
+
+ def centroid_com(self, dcm):
+ # Calculate centroid of object using a centre-of-mass calculation
+ thresh_img = dcm > 0.25 * np.max(dcm)
+ open_img = skimage.morphology.area_opening(thresh_img, area_threshold=500)
+ bhull = skimage.morphology.convex_hull_image(open_img)
+ coords = np.nonzero(bhull) # row major - first array is columns
+
+ sum_x = np.sum(coords[1])
+ sum_y = np.sum(coords[0])
+ cx, cy = sum_x / coords[0].shape[0], sum_y / coords[1].shape[0]
+ cxy = (round(cx), round(cy))
+
+ return bhull, cxy
+
+ def horizontal_length(self, res, mask, cxy):
+ dims = mask.shape
+ start_h = (cxy[1], 0)
+ end_h = (cxy[1], dims[0] - 1)
+ line_profile_h = skimage.measure.profile_line(mask, start_h, end_h, mode='reflect')
+ extent_h = np.nonzero(line_profile_h)[0]
+ dist_h = (extent_h[-1] - extent_h[0]) * res[0]
+
+ h_dict = {
+ 'Start': start_h,
+ 'End': end_h,
+ 'Extent': extent_h,
+ 'Distance': dist_h
+ }
+ return h_dict
+
+ def vertical_length(self, res, mask, cxy):
+ dims = mask.shape
+ start_v = (0, cxy[0])
+ end_v = (dims[1] - 1, cxy[0])
+ line_profile_v = skimage.measure.profile_line(mask, start_v, end_v, mode='reflect')
+ extent_v = np.nonzero(line_profile_v)[0]
+ dist_v = (extent_v[-1] - extent_v[0]) * res[1]
+
+ v_dict = {
+ 'Start': start_v,
+ 'End': end_v,
+ 'Extent': extent_v,
+ 'Distance': dist_v
+ }
+ return v_dict
+
+ def rotate_point(self, origin, point, angle):
+ theta = np.radians(angle)
+ c, s = np.cos(theta), np.sin(theta)
+
+ x_prime = origin[0] + c * (point[0] - origin[0]) - s * (point[1] - origin[1])
+ y_prime = origin[1] + s * (point[0] - origin[0]) + c * (point[1] - origin[1])
+ return x_prime, y_prime
+
+ def diagonal_lengths(self, res, mask, cxy):
+ eff_res = np.sqrt(np.mean(np.square(res)))
+ mask_rotate = skimage.transform.rotate(mask, 45, center=(cxy[0], cxy[1]))
+
+ h_dict = self.horizontal_length(res, mask_rotate, cxy)
+ extent_h = h_dict['Extent']
+
+ origin = (cxy[0], cxy[1])
+ start = (extent_h[0], cxy[1])
+ end = (extent_h[-1], cxy[1])
+ se_x_start, se_y_start = self.rotate_point(origin, start, 45)
+ se_x_end, se_y_end = self.rotate_point(origin, end, 45)
+
+ dist_se = np.sqrt(np.sum(np.square([se_x_end - se_x_start, se_y_end - se_y_start]))) * eff_res
+ se_dict = {
+ 'Start': (se_x_start, se_y_start),
+ 'End': (se_x_end, se_y_end),
+ 'Extent': (se_x_end - se_x_start, se_y_end - se_y_start),
+ 'Distance': dist_se
+ }
+
+ v_dict = self.vertical_length(res, mask_rotate, cxy)
+ extent_v = v_dict['Extent']
+
+ start = (cxy[0], extent_v[0])
+ end = (cxy[0], extent_v[-1])
+ sw_x_start, sw_y_start = self.rotate_point(origin, start, 45)
+ sw_x_end, sw_y_end = self.rotate_point(origin, end, 45)
+
+ dist_sw = np.sqrt(np.sum(np.square([sw_x_end - sw_x_start, sw_y_end - sw_y_start]))) * eff_res
+ sw_dict = {
+ 'Start': (sw_x_start, sw_y_start),
+ 'End': (sw_x_end, sw_y_end),
+ 'Extent': (sw_x_end - sw_x_start, sw_y_end - sw_y_start),
+ 'Distance': dist_sw
+ }
+
+ return sw_dict, se_dict
+
+ def get_geometric_accuracy_slice1(self, dcm):
+ img = dcm.pixel_array
+ res = dcm.PixelSpacing
+ mask, cxy = self.centroid_com(img)
+
+ h_dict = self.horizontal_length(res, mask, cxy)
+ v_dict = self.vertical_length(res, mask, cxy)
+
+ if self.report:
+ import matplotlib.pyplot as plt
+ fig = plt.figure()
+ fig.set_size_inches(8, 8)
+ plt.imshow(img)
+
+ plt.arrow(h_dict['Extent'][0], cxy[1], h_dict['Extent'][-1] - h_dict['Extent'][0], 1, color='blue',
+ length_includes_head=True, head_width=5)
+ plt.arrow(cxy[0], v_dict['Extent'][0], 1, v_dict['Extent'][-1] - v_dict['Extent'][0], color='orange',
+ length_includes_head=True, head_width=5)
+ plt.legend([str(np.round(h_dict['Distance'], 2)) + 'mm',
+ str(np.round(v_dict['Distance'], 2)) + 'mm'])
+ plt.axis('off')
+ plt.title('Geometric Accuracy for Slice 1')
+
+ img_path = os.path.realpath(os.path.join(self.report_path, f'{self.key(dcm)}.png'))
+ fig.savefig(img_path)
+ self.report_files.append(img_path)
+
+ return h_dict['Distance'], v_dict['Distance']
+
+ def get_geometric_accuracy_slice5(self, dcm):
+ img = dcm.pixel_array
+ res = dcm.PixelSpacing
+ mask, cxy = self.centroid_com(img)
+
+ h_dict = self.horizontal_length(res, mask, cxy)
+ v_dict = self.vertical_length(res, mask, cxy)
+ sw_dict, se_dict = self.diagonal_lengths(res, mask, cxy)
+
+ if self.report:
+ import matplotlib.pyplot as plt
+ fig = plt.figure()
+ fig.set_size_inches(8, 8)
+ plt.imshow(img)
+
+ plt.arrow(h_dict['Extent'][0], cxy[1], h_dict['Extent'][-1] - h_dict['Extent'][0], 1, color='blue',
+ length_includes_head=True, head_width=5)
+ plt.arrow(cxy[0], v_dict['Extent'][0], 1, v_dict['Extent'][-1] - v_dict['Extent'][0], color='orange',
+ length_includes_head=True, head_width=5)
+
+ plt.arrow(se_dict['Start'][0], se_dict['Start'][1], se_dict['Extent'][0], se_dict['Extent'][1],
+ color='purple', length_includes_head=True, head_width=5)
+ plt.arrow(sw_dict['Start'][0], sw_dict['Start'][1], sw_dict['Extent'][0], sw_dict['Extent'][1],
+ color='yellow', length_includes_head=True, head_width=5)
+
+ plt.legend([str(np.round(h_dict['Distance'], 2)) + 'mm',
+ str(np.round(v_dict['Distance'], 2)) + 'mm',
+ str(np.round(sw_dict['Distance'], 2)) + 'mm',
+ str(np.round(se_dict['Distance'], 2)) + 'mm'])
+ plt.axis('off')
+ plt.title('Geometric Accuracy for Slice 5')
+
+ img_path = os.path.realpath(os.path.join(self.report_path, f'{self.key(dcm)}.png'))
+ fig.savefig(img_path)
+ self.report_files.append(img_path)
+
+ return h_dict['Distance'], v_dict['Distance'], sw_dict['Distance'], se_dict['Distance']
+
+ def distortion_metric(self, L):
+ err = [x - 190 for x in L]
+ mean_err = np.mean(err)
+
+ max_err = np.max(np.absolute(err))
+ cov_l = 100 * np.std(L) / np.mean(L)
+
+ return mean_err, max_err, cov_l
| GSTT-CSC/hazen | 8aaa233168a543c493961f193802fc4607ac4997 | diff --git a/.github/workflows/test_cli.yml b/.github/workflows/test_cli.yml
index 9082b13..203650d 100644
--- a/.github/workflows/test_cli.yml
+++ b/.github/workflows/test_cli.yml
@@ -55,6 +55,11 @@ jobs:
run: |
hazen acr_ghosting tests/data/acr/Siemens --report
+ - name: test acr_geometric_accuracy
+ if: always() # will always run regardless of whether previous step fails - useful to ensure all CLI functions tested
+ run: |
+ hazen acr_geometric_accuracy tests/data/acr/Siemens --report
+
- name: test slice_position
if: always() # will always run regardless of whether previous step fails - useful to ensure all CLI functions tested
run: |
diff --git a/tests/test_acr_geometric_accuracy.py b/tests/test_acr_geometric_accuracy.py
new file mode 100644
index 0000000..0de6d26
--- /dev/null
+++ b/tests/test_acr_geometric_accuracy.py
@@ -0,0 +1,72 @@
+import os
+import unittest
+import pathlib
+import pydicom
+import numpy as np
+
+from hazenlib.tasks.acr_geometric_accuracy import ACRGeometricAccuracy
+from tests import TEST_DATA_DIR, TEST_REPORT_DIR
+
+
+class TestACRGeometricAccuracySiemens(unittest.TestCase):
+ ACR_GEOMETRIC_ACCURACY_DATA = pathlib.Path(TEST_DATA_DIR / 'acr')
+ centre = (128, 129)
+ L1 = 190.43, 186.52
+ L5 = 190.43, 186.52, 189.45, 191.41
+ test_point = (-60.98, -45.62)
+
+ def setUp(self):
+ self.acr_geometric_accuracy_task = ACRGeometricAccuracy(data_paths=[os.path.join(TEST_DATA_DIR, 'acr')],
+ report_dir=pathlib.PurePath.joinpath(TEST_REPORT_DIR))
+ self.dcm = pydicom.read_file(os.path.join(TEST_DATA_DIR, 'acr', 'Siemens', '0.dcm'))
+ self.dcm2 = pydicom.read_file(os.path.join(TEST_DATA_DIR, 'acr', 'Siemens', '4.dcm'))
+
+ def test_object_centre(self):
+ data = self.dcm.pixel_array
+ assert self.acr_geometric_accuracy_task.centroid_com(data)[1] == self.centre
+
+ def test_geo_accuracy_slice1(self):
+ slice1_vals = np.array(self.acr_geometric_accuracy_task.get_geometric_accuracy_slice1(self.dcm))
+ slice1_vals = np.round(slice1_vals, 2)
+ assert (slice1_vals == self.L1).all() == True
+
+ def test_geo_accuracy_slice5(self):
+ slice5_vals = np.array(self.acr_geometric_accuracy_task.get_geometric_accuracy_slice5(self.dcm2))
+ slice5_vals = np.round(slice5_vals, 2)
+ assert (slice5_vals == self.L5).all() == True
+
+ def test_rotate_point(self):
+ rotated_point = np.array(self.acr_geometric_accuracy_task.rotate_point((0, 0), (30, 70), 150))
+ rotated_point = np.round(rotated_point, 2)
+ print(rotated_point)
+ assert (rotated_point == self.test_point).all() == True
+
+
+# class TestACRUniformityPhilips(unittest.TestCase):
+
+class TestACRGeometricAccuracyGE(unittest.TestCase):
+ ACR_GEOMETRIC_ACCURACY_DATA = pathlib.Path(TEST_DATA_DIR / 'acr')
+ L1 = 189.92, 187.89
+ L5 = 189.92, 188.39, 190.43, 189.92
+ distortion_metrics = [-0.59, 2.11, 0.49]
+
+ def setUp(self):
+ self.acr_geometric_accuracy_task = ACRGeometricAccuracy(data_paths=[os.path.join(TEST_DATA_DIR, 'acr')],
+ report_dir=pathlib.PurePath.joinpath(TEST_REPORT_DIR))
+ self.dcm = pydicom.read_file(os.path.join(TEST_DATA_DIR, 'acr', 'GE', '10.dcm'))
+ self.dcm2 = pydicom.read_file(os.path.join(TEST_DATA_DIR, 'acr', 'GE', '6.dcm'))
+
+ def test_geo_accuracy_slice1(self):
+ slice1_vals = np.array(self.acr_geometric_accuracy_task.get_geometric_accuracy_slice1(self.dcm))
+ slice1_vals = np.round(slice1_vals, 2)
+ assert (slice1_vals == self.L1).all() == True
+
+ def test_geo_accuracy_slice5(self):
+ slice5_vals = np.array(self.acr_geometric_accuracy_task.get_geometric_accuracy_slice5(self.dcm2))
+ slice5_vals = np.round(slice5_vals, 2)
+ assert (slice5_vals == self.L5).all() == True
+
+ def test_distortion_metrics(self):
+ metrics = np.array(self.acr_geometric_accuracy_task.distortion_metric(self.L1+self.L5))
+ metrics = np.round(metrics, 2)
+ assert (metrics == self.distortion_metrics).all() == True
| [ACR5] Geometric accuracy
For the geometric accuracy - currently under slice width in hazen - use slice 1 and slice 5 of an ACR_TRA_T1_NORMOFF series. In slice 1, measure the diameter of the phantom: top-to-bottom and left-to-right and on slice 5 measure the diameter of the phantom in 4 directions: top-to-bottom, left-to-right, and both diagonals. The diameter is 190 mm and all lengths should be within Β± 2 mm. Beware that on top of the phantom due to a water bubble there will be a n extended dark area.
Priority: High for ACR
![image](https://user-images.githubusercontent.com/93722461/146515895-16ef0d2b-817c-428a-8cdf-1526635c8217.png)
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_acr_geometric_accuracy.py::TestACRGeometricAccuracySiemens::test_geo_accuracy_slice1",
"tests/test_acr_geometric_accuracy.py::TestACRGeometricAccuracySiemens::test_geo_accuracy_slice5",
"tests/test_acr_geometric_accuracy.py::TestACRGeometricAccuracySiemens::test_object_centre",
"tests/test_acr_geometric_accuracy.py::TestACRGeometricAccuracySiemens::test_rotate_point",
"tests/test_acr_geometric_accuracy.py::TestACRGeometricAccuracyGE::test_distortion_metrics",
"tests/test_acr_geometric_accuracy.py::TestACRGeometricAccuracyGE::test_geo_accuracy_slice1",
"tests/test_acr_geometric_accuracy.py::TestACRGeometricAccuracyGE::test_geo_accuracy_slice5"
] | [] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_media",
"has_added_files"
],
"has_test_patch": true,
"is_lite": false
} | "2023-01-18T12:44:41Z" | apache-2.0 |
|
GSTT-CSC__hazen-363 | diff --git a/hazenlib/__init__.py b/hazenlib/__init__.py
index dafcf1a..309c585 100644
--- a/hazenlib/__init__.py
+++ b/hazenlib/__init__.py
@@ -112,7 +112,7 @@ import importlib
import inspect
import logging
import sys
-import pprint
+import json
import os
from docopt import docopt
@@ -156,7 +156,6 @@ def init_task(selected_task, files, report, report_dir):
def main():
arguments = docopt(__doc__, version=__version__)
files = get_dicom_files(arguments['<folder>'])
- pp = pprint.PrettyPrinter(indent=4, depth=1, width=1)
# Set common options
log_levels = {
@@ -203,7 +202,8 @@ def main():
task = init_task(selected_task, files, report, report_dir)
result = task.run()
- print(pp.pformat(result))
+ result_string = json.dumps(result, indent=2)
+ print(result_string)
if __name__ == "__main__":
diff --git a/hazenlib/tasks/acr_snr.py b/hazenlib/tasks/acr_snr.py
index 087c3de..4dc21b3 100644
--- a/hazenlib/tasks/acr_snr.py
+++ b/hazenlib/tasks/acr_snr.py
@@ -74,7 +74,7 @@ class ACRSNR(HazenTask):
traceback.print_exc(file=sys.stdout)
- results = {self.key(snr_dcm): snr_results, 'reports': {'images': self.report_files}}
+ results = {self.key(snr_dcm): snr_results}
# only return reports if requested
if self.report:
diff --git a/hazenlib/tasks/uniformity.py b/hazenlib/tasks/uniformity.py
index 4e57e7e..e54d8b1 100644
--- a/hazenlib/tasks/uniformity.py
+++ b/hazenlib/tasks/uniformity.py
@@ -148,5 +148,5 @@ class Uniformity(HazenTask):
fig.savefig(img_path)
self.report_files.append(img_path)
- return {'horizontal': {'IPEM': fractional_uniformity_horizontal},
- 'vertical': {'IPEM': fractional_uniformity_vertical}}
+ return {'horizontal': fractional_uniformity_horizontal,
+ 'vertical': fractional_uniformity_vertical}
| GSTT-CSC/hazen | 5d9e4d747ccd1c908ac5cc0bfbbdb60c470e9bfb | diff --git a/tests/test_uniformity.py b/tests/test_uniformity.py
index 8fe2611..2fa43ec 100644
--- a/tests/test_uniformity.py
+++ b/tests/test_uniformity.py
@@ -18,8 +18,8 @@ class TestUniformity(unittest.TestCase):
def test_uniformity(self):
results = self.uniformity_task.run()
key = self.uniformity_task.key(self.uniformity_task.data[0])
- horizontal_ipem = results[key]['horizontal']['IPEM']
- vertical_ipem = results[key]['vertical']['IPEM']
+ horizontal_ipem = results[key]['horizontal']
+ vertical_ipem = results[key]['vertical']
print("\ntest_uniformity.py::TestUniformity::test_uniformity")
| Improve displaying results on terminal
PrettyPrinter could be replaced with `json.dumps()` that can format and display the result dictionary in a simple structured way with less configuration needed.
currently with PrettyPrint: (more compact)
<img width="759" alt="Screenshot 2023-07-15 at 18 27 16" src="https://github.com/GSTT-CSC/hazen/assets/15593138/f22dad3d-c0b2-4b41-88b1-1a48d52758cf">
with json.dumps: (more easy to understand)
<img width="686" alt="image" src="https://github.com/GSTT-CSC/hazen/assets/15593138/63af6d46-fddc-4acc-84fc-da5a92c936f5">
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_uniformity.py::TestUniformity::test_uniformity",
"tests/test_uniformity.py::TestSagUniformity::test_uniformity",
"tests/test_uniformity.py::TestCorUniformity::test_uniformity"
] | [] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2023-07-28T18:22:43Z" | apache-2.0 |
|
GazzolaLab__PyElastica-123 | diff --git a/docs/api/damping.rst b/docs/api/damping.rst
index 510496e..3daa919 100644
--- a/docs/api/damping.rst
+++ b/docs/api/damping.rst
@@ -15,6 +15,7 @@ Damping is used to numerically stabilize the simulations.
DamperBase
ExponentialDamper
+ LaplaceDissipationFilter
Compatibility
~~~~~~~~~~~~~
@@ -23,7 +24,8 @@ Compatibility
Damping/Numerical Dissipation Rod Rigid Body
=============================== ==== ===========
ExponentialDamper β
β
-=============================== ==== ===========
+LaplaceDissipationFilter β
β
+=============================== ==== ===========
Built-in Constraints
@@ -37,3 +39,6 @@ Built-in Constraints
.. autoclass:: ExponentialDamper
:special-members: __init__
+
+.. autoclass:: LaplaceDissipationFilter
+ :special-members: __init__
diff --git a/elastica/dissipation.py b/elastica/dissipation.py
index 04e7dc2..e10b200 100644
--- a/elastica/dissipation.py
+++ b/elastica/dissipation.py
@@ -6,10 +6,13 @@ Built in damper module implementations
__all__ = [
"DamperBase",
"ExponentialDamper",
+ "LaplaceDissipationFilter",
]
from abc import ABC, abstractmethod
-from elastica.typing import SystemType
+from elastica.typing import RodType, SystemType
+
+from numba import njit
import numpy as np
@@ -85,7 +88,7 @@ class ExponentialDamper(DamperBase):
--------
How to set exponential damper for rod or rigid body:
- >>> simulator.dampin(rod).using(
+ >>> simulator.dampen(rod).using(
... ExponentialDamper,
... damping_constant=0.1,
... time_step = 1E-4, # Simulation time-step
@@ -151,3 +154,128 @@ class ExponentialDamper(DamperBase):
rod.omega_collection[:] = rod.omega_collection * np.power(
self.rotational_exponential_damping_coefficient, rod.dilatation
)
+
+
+class LaplaceDissipationFilter(DamperBase):
+ """
+ Laplace Dissipation Filter class. This class corresponds qualitatively to a
+ low-pass filter generated via the 1D Laplacian operator. It is applied to the
+ translational and rotational velocities, where it filters out the high
+ frequency (noise) modes, while having negligible effect on the low frequency
+ smooth modes.
+
+ Examples
+ --------
+ How to set Laplace dissipation filter for rod:
+
+ >>> simulator.dampen(rod).using(
+ ... LaplaceDissipationFilter,
+ ... filter_order=3, # order of the filter
+ ... )
+
+ Notes
+ -----
+ The extent of filtering can be controlled by the `filter_order`, which refers
+ to the number of times the Laplacian operator is applied. Small
+ integer values (1, 2, etc.) result in aggressive filtering, and can lead to
+ the "physics" being filtered out. While high values (9, 10, etc.) imply
+ minimal filtering, and thus negligible effect on the velocities.
+ Values in the range of 3-7 are usually recommended.
+
+ For details regarding the numerics behind the filtering, refer to:
+
+ .. [1] Jeanmart, H., & Winckelmans, G. (2007). Investigation of eddy-viscosity
+ models modified using discrete filters: a simplified βregularized variational
+ multiscale modelβ and an βenhanced field modelβ. Physics of fluids, 19(5), 055110.
+ .. [2] Lorieul, G. (2018). Development and validation of a 2D Vortex Particle-Mesh
+ method for incompressible multiphase flows (Doctoral dissertation,
+ UniversitΓ© Catholique de Louvain).
+
+ Attributes
+ ----------
+ filter_order : int
+ Filter order, which corresponds to the number of times the Laplacian
+ operator is applied. Increasing `filter_order` implies higher-order/weaker
+ filtering.
+ velocity_filter_term: numpy.ndarray
+ 2D array containing data with 'float' type.
+ Filter term that modifies rod translational velocity.
+ omega_filter_term: numpy.ndarray
+ 2D array containing data with 'float' type.
+ Filter term that modifies rod rotational velocity.
+ """
+
+ def __init__(self, filter_order: int, **kwargs):
+ """
+ Filter damper initializer
+
+ Parameters
+ ----------
+ filter_order : int
+ Filter order, which corresponds to the number of times the Laplacian
+ operator is applied. Increasing `filter_order` implies higher-order/weaker
+ filtering.
+ """
+ super().__init__(**kwargs)
+ if not (filter_order > 0 and isinstance(filter_order, int)):
+ raise ValueError(
+ "Invalid filter order! Filter order must be a positive integer."
+ )
+ self.filter_order = filter_order
+ self.velocity_filter_term = np.zeros_like(self._system.velocity_collection)
+ self.omega_filter_term = np.zeros_like(self._system.omega_collection)
+
+ def dampen_rates(self, rod: RodType, time: float) -> None:
+ nb_filter_rate(
+ rate_collection=rod.velocity_collection,
+ filter_term=self.velocity_filter_term,
+ filter_order=self.filter_order,
+ )
+ nb_filter_rate(
+ rate_collection=rod.omega_collection,
+ filter_term=self.omega_filter_term,
+ filter_order=self.filter_order,
+ )
+
+
+@njit(cache=True)
+def nb_filter_rate(
+ rate_collection: np.ndarray, filter_term: np.ndarray, filter_order: int
+) -> None:
+ """
+ Filters the rod rates (velocities) in numba njit decorator
+
+ Parameters
+ ----------
+ rate_collection : numpy.ndarray
+ 2D array containing data with 'float' type.
+ Array containing rod rates (velocities).
+ filter_term: numpy.ndarray
+ 2D array containing data with 'float' type.
+ Filter term that modifies rod rates (velocities).
+ filter_order : int
+ Filter order, which corresponds to the number of times the Laplacian
+ operator is applied. Increasing `filter_order` implies higher order/weaker
+ filtering.
+
+ Notes
+ -----
+ For details regarding the numerics behind the filtering, refer to:
+
+ .. [1] Jeanmart, H., & Winckelmans, G. (2007). Investigation of eddy-viscosity
+ models modified using discrete filters: a simplified βregularized variational
+ multiscale modelβ and an βenhanced field modelβ. Physics of fluids, 19(5), 055110.
+ .. [2] Lorieul, G. (2018). Development and validation of a 2D Vortex Particle-Mesh
+ method for incompressible multiphase flows (Doctoral dissertation,
+ UniversitΓ© Catholique de Louvain).
+ """
+
+ filter_term[...] = rate_collection
+ for i in range(filter_order):
+ filter_term[..., 1:-1] = (
+ -filter_term[..., 2:] - filter_term[..., :-2] + 2.0 * filter_term[..., 1:-1]
+ ) / 4.0
+ # dont touch boundary values
+ filter_term[..., 0] = 0.0
+ filter_term[..., -1] = 0.0
+ rate_collection[...] = rate_collection - filter_term
diff --git a/elastica/typing.py b/elastica/typing.py
index 3f89087..b438264 100644
--- a/elastica/typing.py
+++ b/elastica/typing.py
@@ -3,4 +3,5 @@ from elastica.rigidbody import RigidBodyBase
from typing import Type, Union
-SystemType = Union[Type[RodBase], Type[RigidBodyBase]]
+RodType = Type[RodBase]
+SystemType = Union[RodType, Type[RigidBodyBase]]
| GazzolaLab/PyElastica | 2008f299028561d232f80e7bd993585e96615309 | diff --git a/tests/test_dissipation.py b/tests/test_dissipation.py
index cfa1637..9ea021a 100644
--- a/tests/test_dissipation.py
+++ b/tests/test_dissipation.py
@@ -1,11 +1,15 @@
__doc__ = """ Test Dissipation module for in Elastica implementation"""
# System imports
+from elastica.dissipation import DamperBase, ExponentialDamper, LaplaceDissipationFilter
+from elastica.utils import Tolerance
+
import numpy as np
-from test_rod.test_rods import MockTestRod
-from elastica.dissipation import DamperBase, ExponentialDamper
from numpy.testing import assert_allclose
-from elastica.utils import Tolerance
+
+import pytest
+
+from test_rod.test_rods import MockTestRod
def test_damper_base():
@@ -114,3 +118,91 @@ def test_exponential_damper():
assert_allclose(
post_damping_omega_collection, test_rod.omega_collection, atol=Tolerance.atol()
)
+
+
[email protected]("filter_order", [-1, 0, 3.2])
+def test_laplace_dissipation_filter_init_invalid_filter_order(filter_order):
+ test_rod = MockTestRod()
+ with pytest.raises(ValueError) as exc_info:
+ _ = LaplaceDissipationFilter(
+ _system=test_rod,
+ filter_order=filter_order,
+ )
+ assert (
+ exc_info.value.args[0]
+ == "Invalid filter order! Filter order must be a positive integer."
+ )
+
+
[email protected]("filter_order", [2, 3, 4])
+def test_laplace_dissipation_filter_init(filter_order):
+
+ test_rod = MockTestRod()
+ filter_damper = LaplaceDissipationFilter(
+ _system=test_rod,
+ filter_order=filter_order,
+ )
+ assert filter_damper.filter_order == filter_order
+ assert_allclose(
+ filter_damper.velocity_filter_term, np.zeros((3, test_rod.n_elem + 1))
+ )
+ assert_allclose(filter_damper.omega_filter_term, np.zeros((3, test_rod.n_elem)))
+
+
[email protected]("filter_order", [2, 3, 4])
+def test_laplace_dissipation_filter_for_constant_field(filter_order):
+ test_rod = MockTestRod()
+ filter_damper = LaplaceDissipationFilter(
+ _system=test_rod,
+ filter_order=filter_order,
+ )
+ test_rod.velocity_collection[...] = 2.0
+ test_rod.omega_collection[...] = 3.0
+ filter_damper.dampen_rates(rod=test_rod, time=0)
+ # filter should keep a spatially invariant field unaffected
+ post_damping_velocity_collection = 2.0 * np.ones_like(test_rod.velocity_collection)
+ post_damping_omega_collection = 3.0 * np.ones_like(test_rod.omega_collection)
+ assert_allclose(
+ post_damping_velocity_collection,
+ test_rod.velocity_collection,
+ atol=Tolerance.atol(),
+ )
+ assert_allclose(
+ post_damping_omega_collection, test_rod.omega_collection, atol=Tolerance.atol()
+ )
+
+
+def test_laplace_dissipation_filter_for_flip_flop_field():
+ filter_order = 1
+ test_rod = MockTestRod()
+ filter_damper = LaplaceDissipationFilter(
+ _system=test_rod,
+ filter_order=filter_order,
+ )
+ test_rod.velocity_collection[...] = 0.0
+ test_rod.velocity_collection[..., 1::2] = 2.0
+ test_rod.omega_collection[...] = 0.0
+ test_rod.omega_collection[..., 1::2] = 3.0
+ pre_damping_velocity_collection = test_rod.velocity_collection.copy()
+ pre_damping_omega_collection = test_rod.omega_collection.copy()
+ filter_damper.dampen_rates(rod=test_rod, time=0)
+ post_damping_velocity_collection = np.zeros_like(test_rod.velocity_collection)
+ post_damping_omega_collection = np.zeros_like(test_rod.omega_collection)
+ # filter should remove the flip-flop mode th give the average constant mode
+ post_damping_velocity_collection[..., 1:-1] = 2.0 / 2
+ post_damping_omega_collection[..., 1:-1] = 3.0 / 2
+ # end values remain untouched
+ post_damping_velocity_collection[
+ ..., 0 :: test_rod.n_elem
+ ] = pre_damping_velocity_collection[..., 0 :: test_rod.n_elem]
+ post_damping_omega_collection[
+ ..., 0 :: test_rod.n_elem - 1
+ ] = pre_damping_omega_collection[..., 0 :: test_rod.n_elem - 1]
+ assert_allclose(
+ post_damping_velocity_collection,
+ test_rod.velocity_collection,
+ atol=Tolerance.atol(),
+ )
+ assert_allclose(
+ post_damping_omega_collection, test_rod.omega_collection, atol=Tolerance.atol()
+ )
| Filter Damping addition to the damping module
The Filter Damping method (adapted from [here](https://aip.scitation.org/doi/full/10.1063/1.2728935?casa_token=9v62oae0XN0AAAAA%3AhfV-OcYFBb_uB6cE0yBfsdf9HMIem1vZ0JJVhoJT-WNgxoM5jPXAPfqctpkn3aXP5wN75sVnHLFw)), which basically damps velocities similar to a low pass filter, has shown advantages (reduced noise, oscillations, and larger stable timesteps) in complex scenarios involving Cosserat rods, as noticed by @armantekinalp. Thus, adding this to the damping module (#114) can be an important factor in improving the stability of Cosserat rod simulations. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_dissipation.py::test_exponential_damper",
"tests/test_dissipation.py::test_laplace_dissipation_filter_for_constant_field[2]",
"tests/test_dissipation.py::test_laplace_dissipation_filter_init[3]",
"tests/test_dissipation.py::test_damper_base_properties_access",
"tests/test_dissipation.py::test_laplace_dissipation_filter_for_constant_field[4]",
"tests/test_dissipation.py::test_laplace_dissipation_filter_init_invalid_filter_order[-1]",
"tests/test_dissipation.py::test_laplace_dissipation_filter_init[2]",
"tests/test_dissipation.py::test_laplace_dissipation_filter_init_invalid_filter_order[0]",
"tests/test_dissipation.py::test_damper_base",
"tests/test_dissipation.py::test_laplace_dissipation_filter_for_constant_field[3]",
"tests/test_dissipation.py::test_laplace_dissipation_filter_for_flip_flop_field",
"tests/test_dissipation.py::test_laplace_dissipation_filter_init[4]",
"tests/test_dissipation.py::test_laplace_dissipation_filter_init_invalid_filter_order[3.2]"
] | [] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_issue_reference",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2022-07-04T00:44:47Z" | mit |
|
GazzolaLab__PyElastica-249 | diff --git a/elastica/__init__.py b/elastica/__init__.py
index 7622bf2..f60bc90 100644
--- a/elastica/__init__.py
+++ b/elastica/__init__.py
@@ -71,3 +71,4 @@ from elastica.timestepper import (
)
from elastica.memory_block.memory_block_rigid_body import MemoryBlockRigidBody
from elastica.memory_block.memory_block_rod import MemoryBlockCosseratRod
+from elastica.restart import save_state, load_state
diff --git a/elastica/restart.py b/elastica/restart.py
index 7e97cb8..1b5fab2 100644
--- a/elastica/restart.py
+++ b/elastica/restart.py
@@ -3,6 +3,7 @@ __doc__ = """Generate or load restart file implementations."""
import numpy as np
import os
from itertools import groupby
+from .memory_block import MemoryBlockCosseratRod, MemoryBlockRigidBody
def all_equal(iterable):
@@ -41,6 +42,10 @@ def save_state(simulator, directory: str = "", time=0.0, verbose: bool = False):
"""
os.makedirs(directory, exist_ok=True)
for idx, rod in enumerate(simulator):
+ if isinstance(rod, MemoryBlockCosseratRod) or isinstance(
+ rod, MemoryBlockRigidBody
+ ):
+ continue
path = os.path.join(directory, "system_{}.npz".format(idx))
np.savez(path, time=time, **rod.__dict__)
@@ -69,6 +74,10 @@ def load_state(simulator, directory: str = "", verbose: bool = False):
"""
time_list = [] # Simulation time of rods when they are saved.
for idx, rod in enumerate(simulator):
+ if isinstance(rod, MemoryBlockCosseratRod) or isinstance(
+ rod, MemoryBlockRigidBody
+ ):
+ continue
path = os.path.join(directory, "system_{}.npz".format(idx))
data = np.load(path, allow_pickle=True)
for key, value in data.items():
@@ -88,10 +97,6 @@ def load_state(simulator, directory: str = "", verbose: bool = False):
"Restart time of loaded rods are different, check your inputs!"
)
- # Apply boundary conditions, after loading the systems.
- simulator.constrain_values(0.0)
- simulator.constrain_rates(0.0)
-
if verbose:
print("Load complete: {}".format(directory))
| GazzolaLab/PyElastica | b271ad41fbeaa78fbd03887573b9a364c949ef5b | diff --git a/tests/test_restart.py b/tests/test_restart.py
index 0ba52df..0f814b2 100644
--- a/tests/test_restart.py
+++ b/tests/test_restart.py
@@ -12,6 +12,7 @@ from elastica.modules import (
CallBacks,
)
from elastica.restart import save_state, load_state
+import elastica as ea
class GenericSimulatorClass(
@@ -78,6 +79,98 @@ class TestRestartFunctionsWithFeaturesUsingCosseratRod:
assert_allclose(test_value, correct_value)
+ def run_sim(self, final_time, load_from_restart, save_data_restart):
+ class BaseSimulatorClass(
+ BaseSystemCollection, Constraints, Forcing, Connections, CallBacks
+ ):
+ pass
+
+ simulator_class = BaseSimulatorClass()
+
+ rod_list = []
+ for _ in range(5):
+ rod = ea.CosseratRod.straight_rod(
+ n_elements=10,
+ start=np.zeros((3)),
+ direction=np.array([0, 1, 0.0]),
+ normal=np.array([1, 0, 0.0]),
+ base_length=1,
+ base_radius=1,
+ density=1,
+ youngs_modulus=1,
+ )
+ # Bypass check, but its fine for testing
+ simulator_class._systems.append(rod)
+
+ # Also add rods to a separate list
+ rod_list.append(rod)
+
+ for rod in rod_list:
+ simulator_class.add_forcing_to(rod).using(
+ ea.EndpointForces,
+ start_force=np.zeros(
+ 3,
+ ),
+ end_force=np.array([0, 0.1, 0]),
+ ramp_up_time=0.1,
+ )
+
+ # Finalize simulator
+ simulator_class.finalize()
+
+ directory = "restart_test_data/"
+
+ time_step = 1e-4
+ total_steps = int(final_time / time_step)
+
+ if load_from_restart:
+ restart_time = ea.load_state(simulator_class, directory, True)
+
+ else:
+ restart_time = np.float64(0.0)
+
+ timestepper = ea.PositionVerlet()
+ time = ea.integrate(
+ timestepper,
+ simulator_class,
+ final_time,
+ total_steps,
+ restart_time=restart_time,
+ )
+
+ if save_data_restart:
+ ea.save_state(simulator_class, directory, time, True)
+
+ # Compute final time accelerations
+ recorded_list = np.zeros((len(rod_list), rod_list[0].n_elems + 1))
+ for i, rod in enumerate(rod_list):
+ recorded_list[i, :] = rod.acceleration_collection[1, :]
+
+ return recorded_list
+
+ @pytest.mark.parametrize("final_time", [0.2, 1.0])
+ def test_save_restart_run_sim(self, final_time):
+
+ # First half of simulation
+ _ = self.run_sim(
+ final_time / 2, load_from_restart=False, save_data_restart=True
+ )
+
+ # Second half of simulation
+ recorded_list = self.run_sim(
+ final_time / 2, load_from_restart=True, save_data_restart=False
+ )
+ recorded_list_second_half = recorded_list.copy()
+
+ # Full simulation
+ recorded_list = self.run_sim(
+ final_time, load_from_restart=False, save_data_restart=False
+ )
+ recorded_list_full_sim = recorded_list.copy()
+
+ # Compare final accelerations of rods
+ assert_allclose(recorded_list_second_half, recorded_list_full_sim)
+
class TestRestartFunctionsWithFeaturesUsingRigidBodies:
@pytest.fixture(scope="function")
| Possible Bug: Test restart functionality and applying constrains
We should test the below line in the restart code. We suspect it creates incorrect results, when we load and time-step.
https://github.com/GazzolaLab/PyElastica/blob/7b3fe2d0204a175c9e5e64265c70b9577b4ca8c9/elastica/restart.py#L92-L93 | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_restart.py::TestRestartFunctionsWithFeaturesUsingCosseratRod::test_save_restart_run_sim[1.0]",
"tests/test_restart.py::TestRestartFunctionsWithFeaturesUsingCosseratRod::test_save_restart_run_sim[0.2]"
] | [
"tests/test_restart.py::TestRestartFunctionsWithFeaturesUsingRigidBodies::test_restart_save_load",
"tests/test_restart.py::TestRestartFunctionsWithFeaturesUsingCosseratRod::test_restart_save_load"
] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2023-05-11T16:58:29Z" | mit |
|
GazzolaLab__PyElastica-98 | diff --git a/elastica/interaction.py b/elastica/interaction.py
index 7504670..587598d 100644
--- a/elastica/interaction.py
+++ b/elastica/interaction.py
@@ -8,14 +8,11 @@ __all__ = [
import numpy as np
-from elastica.utils import MaxDimension
from elastica.external_forces import NoForces
-import numba
from numba import njit
from elastica._linalg import (
- _batch_matmul,
_batch_matvec,
_batch_cross,
_batch_norm,
@@ -27,6 +24,7 @@ from elastica._linalg import (
_batch_matrix_transpose,
_batch_vec_oneD_vec_cross,
)
+import warnings
@njit(cache=True)
@@ -71,21 +69,22 @@ def find_slipping_elements(velocity_slip, velocity_threshold):
@njit(cache=True)
-def nodes_to_elements(input):
+def node_to_element_mass_or_force(input):
"""
- This function converts the rod-like object dofs on nodes to
- dofs on elements. For example, node velocity is converted to
- element velocity.
+ This function converts the mass/forces on rod nodes to
+ elements, where special treatment is necessary at the ends.
Parameters
----------
input: numpy.ndarray
- 2D (dim, blocksize) array containing data with 'float' type.
+ 2D (dim, blocksize) array containing nodal mass/forces
+ with 'float' type.
Returns
-------
output: numpy.ndarray
- 2D (dim, blocksize) array containing data with 'float' type.
+ 2D (dim, blocksize) array containing elemental mass/forces
+ with 'float' type.
"""
"""
Developer Notes
@@ -107,6 +106,19 @@ def nodes_to_elements(input):
return output
+def nodes_to_elements(input):
+ warnings.warn(
+ # Change the warning to error on v0.3.1
+ # Remove the function beyond v0.4.0
+ "This function is now deprecated (issue #80). Please use "
+ "elastica.interaction.node_to_element_mass_or_force() "
+ "instead for node-to-element interpolation of mass/forces. "
+ "The function will be removed in the future (v0.3.1).",
+ DeprecationWarning,
+ )
+ return node_to_element_mass_or_force(input)
+
+
@njit(cache=True)
def elements_to_nodes_inplace(vector_in_element_frame, vector_in_node_frame):
"""
@@ -202,6 +214,7 @@ class InteractionPlane:
self.k,
self.nu,
system.radius,
+ system.mass,
system.position_collection,
system.velocity_collection,
system.internal_forces,
@@ -217,6 +230,7 @@ def apply_normal_force_numba(
k,
nu,
radius,
+ mass,
position_collection,
velocity_collection,
internal_forces,
@@ -238,7 +252,7 @@ def apply_normal_force_numba(
# Compute plane response force
nodal_total_forces = _batch_vector_sum(internal_forces, external_forces)
- element_total_forces = nodes_to_elements(nodal_total_forces)
+ element_total_forces = node_to_element_mass_or_force(nodal_total_forces)
force_component_along_normal_direction = _batch_product_i_ik_to_k(
plane_normal, element_total_forces
@@ -259,7 +273,7 @@ def apply_normal_force_numba(
plane_response_force = -forces_along_normal_direction
# Elastic force response due to penetration
- element_position = node_to_element_pos_or_vel(position_collection)
+ element_position = node_to_element_position(position_collection)
distance_from_plane = _batch_product_i_ik_to_k(
plane_normal, (element_position - plane_origin)
)
@@ -267,7 +281,9 @@ def apply_normal_force_numba(
elastic_force = -k * _batch_product_i_k_to_ik(plane_normal, plane_penetration)
# Damping force response due to velocity towards the plane
- element_velocity = node_to_element_pos_or_vel(velocity_collection)
+ element_velocity = node_to_element_velocity(
+ mass=mass, node_velocity_collection=velocity_collection
+ )
normal_component_of_element_velocity = _batch_product_i_ik_to_k(
plane_normal, element_velocity
)
@@ -400,6 +416,7 @@ class AnisotropicFrictionalPlane(NoForces, InteractionPlane):
self.static_mu_backward,
self.static_mu_sideways,
system.radius,
+ system.mass,
system.tangents,
system.position_collection,
system.director_collection,
@@ -427,6 +444,7 @@ def anisotropic_friction(
static_mu_backward,
static_mu_sideways,
radius,
+ mass,
tangents,
position_collection,
director_collection,
@@ -444,6 +462,7 @@ def anisotropic_friction(
k,
nu,
radius,
+ mass,
position_collection,
velocity_collection,
internal_forces,
@@ -466,7 +485,9 @@ def anisotropic_friction(
1 / (tangent_perpendicular_to_normal_direction_mag + 1e-14),
tangent_perpendicular_to_normal_direction,
)
- element_velocity = node_to_element_pos_or_vel(velocity_collection)
+ element_velocity = node_to_element_velocity(
+ mass=mass, node_velocity_collection=velocity_collection
+ )
# first apply axial kinetic friction
velocity_mag_along_axial_direction = _batch_dot(element_velocity, axial_direction)
velocity_along_axial_direction = _batch_product_k_ik_to_ik(
@@ -550,7 +571,7 @@ def anisotropic_friction(
# now axial static friction
nodal_total_forces = _batch_vector_sum(internal_forces, external_forces)
- element_total_forces = nodes_to_elements(nodal_total_forces)
+ element_total_forces = node_to_element_mass_or_force(nodal_total_forces)
force_component_along_axial_direction = _batch_dot(
element_total_forces, axial_direction
)
@@ -661,21 +682,24 @@ def sum_over_elements(input):
@njit(cache=True)
-def node_to_element_pos_or_vel(vector_in_node_frame):
+def node_to_element_position(node_position_collection):
"""
- This function computes the velocity of the elements.
+ This function computes the position of the elements
+ from the nodal values.
Here we define a separate function because benchmark results
showed that using Numba, we get more than 3 times faster calculation.
Parameters
----------
- vector_in_node_frame: numpy.ndarray
- 2D (dim, blocksize) array containing data with 'float' type.
+ node_position_collection: numpy.ndarray
+ 2D (dim, blocksize) array containing nodal positions with
+ 'float' type.
Returns
-------
- vector_in_element_frame: numpy.ndarray
- 2D (dim, blocksize) array containing data with 'float' type.
+ element_position_collection: numpy.ndarray
+ 2D (dim, blocksize) array containing elemental positions with
+ 'float' type.
"""
"""
Developer Notes
@@ -687,25 +711,77 @@ def node_to_element_pos_or_vel(vector_in_node_frame):
This version: 729 ns Β± 14.3 ns per loop
"""
- n_elem = vector_in_node_frame.shape[1] - 1
- vector_in_element_frame = np.empty((3, n_elem))
+ n_elem = node_position_collection.shape[1] - 1
+ element_position_collection = np.empty((3, n_elem))
+ for k in range(n_elem):
+ element_position_collection[0, k] = 0.5 * (
+ node_position_collection[0, k + 1] + node_position_collection[0, k]
+ )
+ element_position_collection[1, k] = 0.5 * (
+ node_position_collection[1, k + 1] + node_position_collection[1, k]
+ )
+ element_position_collection[2, k] = 0.5 * (
+ node_position_collection[2, k + 1] + node_position_collection[2, k]
+ )
+
+ return element_position_collection
+
+
+@njit(cache=True)
+def node_to_element_velocity(mass, node_velocity_collection):
+ """
+ This function computes the velocity of the elements
+ from the nodal values. Uses the velocity of center of mass
+ in order to conserve momentum during computation.
+
+ Parameters
+ ----------
+ mass: numpy.ndarray
+ 2D (dim, blocksize) array containing nodal masses with
+ 'float' type.
+ node_velocity_collection: numpy.ndarray
+ 2D (dim, blocksize) array containing nodal velocities with
+ 'float' type.
+
+ Returns
+ -------
+ element_velocity_collection: numpy.ndarray
+ 2D (dim, blocksize) array containing elemental velocities with
+ 'float' type.
+ """
+ n_elem = node_velocity_collection.shape[1] - 1
+ element_velocity_collection = np.empty((3, n_elem))
for k in range(n_elem):
- vector_in_element_frame[0, k] = 0.5 * (
- vector_in_node_frame[0, k + 1] + vector_in_node_frame[0, k]
+ element_velocity_collection[0, k] = (
+ mass[k + 1] * node_velocity_collection[0, k + 1]
+ + mass[k] * node_velocity_collection[0, k]
)
- vector_in_element_frame[1, k] = 0.5 * (
- vector_in_node_frame[1, k + 1] + vector_in_node_frame[1, k]
+ element_velocity_collection[1, k] = (
+ mass[k + 1] * node_velocity_collection[1, k + 1]
+ + mass[k] * node_velocity_collection[1, k]
)
- vector_in_element_frame[2, k] = 0.5 * (
- vector_in_node_frame[2, k + 1] + vector_in_node_frame[2, k]
+ element_velocity_collection[2, k] = (
+ mass[k + 1] * node_velocity_collection[2, k + 1]
+ + mass[k] * node_velocity_collection[2, k]
)
+ element_velocity_collection[:, k] /= mass[k + 1] + mass[k]
+
+ return element_velocity_collection
+
- return vector_in_element_frame
+def node_to_element_pos_or_vel(vector_in_node_frame):
+ # Remove the function beyond v0.4.0
+ raise NotImplementedError(
+ "This function is removed in v0.3.0. For node-to-element interpolation please use: \n"
+ "elastica.interaction.node_to_element_position() for rod position \n"
+ "elastica.interaction.node_to_element_velocity() for rod velocity. \n"
+ "For detail, refer to issue #80."
+ )
@njit(cache=True)
def slender_body_forces(
- tangents, velocity_collection, dynamic_viscosity, lengths, radius
+ tangents, velocity_collection, dynamic_viscosity, lengths, radius, mass
):
r"""
This function computes hydrodynamic forces on a body using slender body theory.
@@ -732,6 +808,9 @@ def slender_body_forces(
radius: numpy.ndarray
1D (blocksize) array containing data with 'float' type.
Rod-like object element radius.
+ mass: numpy.ndarray
+ 1D (blocksize) array containing data with 'float' type.
+ Rod-like object node mass.
Returns
-------
@@ -751,7 +830,9 @@ def slender_body_forces(
f = np.empty((tangents.shape[0], tangents.shape[1]))
total_length = sum_over_elements(lengths)
- element_velocity = node_to_element_pos_or_vel(velocity_collection)
+ element_velocity = node_to_element_velocity(
+ mass=mass, node_velocity_collection=velocity_collection
+ )
for k in range(tangents.shape[1]):
# compute the entries of t`t. a[#][#] are the the
@@ -844,6 +925,7 @@ class SlenderBodyTheory(NoForces):
self.dynamic_viscosity,
system.lengths,
system.radius,
+ system.mass,
)
elements_to_nodes_inplace(stokes_force, system.external_forces)
| GazzolaLab/PyElastica | cbc24d9865532d5dbc87e1c5bd18645a02e1c498 | diff --git a/tests/test_interaction.py b/tests/test_interaction.py
index 82ac01a..a7c7a84 100644
--- a/tests/test_interaction.py
+++ b/tests/test_interaction.py
@@ -8,6 +8,7 @@ from elastica.interaction import (
InteractionPlane,
find_slipping_elements,
AnisotropicFrictionalPlane,
+ node_to_element_mass_or_force,
nodes_to_elements,
SlenderBodyTheory,
)
@@ -48,6 +49,7 @@ class BaseRodClass(MockTestRod):
self.internal_forces = np.zeros((MaxDimension.value(), n_elem + 1))
self.internal_torques = np.zeros((MaxDimension.value(), n_elem))
self.lengths = np.ones(n_elem) * base_length / n_elem
+ self.mass = np.ones(n_elem + 1)
def _compute_internal_forces(self):
return np.zeros((MaxDimension.value(), self.n_elem + 1))
@@ -365,13 +367,32 @@ class TestAuxiliaryFunctions:
assert_allclose(correct_slip_function, slip_function, atol=Tolerance.atol())
@pytest.mark.parametrize("n_elem", [2, 3, 5, 10, 20])
- def test_nodes_to_elements(self, n_elem):
+ def test_node_to_element_mass_or_force(self, n_elem):
random_vector = np.random.rand(3).reshape(3, 1)
input = np.repeat(random_vector, n_elem + 1, axis=1)
input[..., 0] *= 0.5
input[..., -1] *= 0.5
correct_output = np.repeat(random_vector, n_elem, axis=1)
- output = nodes_to_elements(input)
+ output = node_to_element_mass_or_force(input)
+ assert_allclose(correct_output, output, atol=Tolerance.atol())
+ assert_allclose(np.sum(input), np.sum(output), atol=Tolerance.atol())
+
+ @pytest.mark.parametrize("n_elem", [2, 3, 5, 10, 20])
+ def test_deprecated_nodes_to_elements(self, n_elem):
+ random_vector = np.random.rand(3).reshape(3, 1)
+ input = np.repeat(random_vector, n_elem + 1, axis=1)
+ input[..., 0] *= 0.5
+ input[..., -1] *= 0.5
+ correct_output = np.repeat(random_vector, n_elem, axis=1)
+ correct_warning_message = (
+ "This function is now deprecated (issue #80). Please use "
+ "elastica.interaction.node_to_element_mass_or_force() "
+ "instead for node-to-element interpolation of mass/forces. "
+ "The function will be removed in the future (v0.3.1)."
+ )
+ with pytest.warns(DeprecationWarning) as record:
+ output = nodes_to_elements(input)
+ assert record[0].message.args[0] == correct_warning_message
assert_allclose(correct_output, output, atol=Tolerance.atol())
assert_allclose(np.sum(input), np.sum(output), atol=Tolerance.atol())
@@ -566,7 +587,7 @@ class TestAnisotropicFriction:
)
assert_allclose(correct_forces, rod.external_forces, atol=Tolerance.atol())
- forces_on_elements = nodes_to_elements(external_forces_collection)
+ forces_on_elements = node_to_element_mass_or_force(external_forces_collection)
correct_torques = np.zeros((3, n_elem))
correct_torques[2] += (
-1.0
@@ -607,7 +628,7 @@ class TestAnisotropicFriction:
correct_forces[0] = 2.0 / 3.0 * external_forces_collection[0]
assert_allclose(correct_forces, rod.external_forces, atol=Tolerance.atol())
- forces_on_elements = nodes_to_elements(external_forces_collection)
+ forces_on_elements = node_to_element_mass_or_force(external_forces_collection)
correct_torques = np.zeros((3, n_elem))
correct_torques[2] += (
-1.0
@@ -650,7 +671,7 @@ class TestAnisotropicFriction:
) * np.fabs(external_forces_collection[1])
assert_allclose(correct_forces, rod.external_forces, atol=Tolerance.atol())
- forces_on_elements = nodes_to_elements(external_forces_collection)
+ forces_on_elements = node_to_element_mass_or_force(external_forces_collection)
correct_torques = np.zeros((3, n_elem))
correct_torques[2] += (
-1.0
@@ -736,7 +757,7 @@ class TestAnisotropicFriction:
)
assert_allclose(correct_forces, rod.external_forces, atol=Tolerance.atol())
- forces_on_elements = nodes_to_elements(external_forces_collection)
+ forces_on_elements = node_to_element_mass_or_force(external_forces_collection)
correct_torques = external_torques
correct_torques[2] += -(
np.sign(torque_mag) * np.fabs(forces_on_elements[1]) * rod.radius
@@ -748,7 +769,12 @@ class TestAnisotropicFriction:
# Slender Body Theory Unit Tests
try:
- from elastica.interaction import sum_over_elements, node_to_element_pos_or_vel
+ from elastica.interaction import (
+ sum_over_elements,
+ node_to_element_position,
+ node_to_element_velocity,
+ node_to_element_pos_or_vel,
+ )
# These functions are used in the case if Numba is available
class TestAuxiliaryFunctionsForSlenderBodyTheory:
@@ -774,9 +800,31 @@ try:
assert_allclose(correct_output, output, atol=Tolerance.atol())
@pytest.mark.parametrize("n_elem", [2, 3, 5, 10, 20])
- def test_node_to_elements(self, n_elem):
+ def test_node_to_element_position(self, n_elem):
"""
- This function test node_to_element_velocity function. We are
+ This function tests node_to_element_position function. We are
+ converting node positions to element positions. Here also
+ we are using numba to speed up the process.
+
+ Parameters
+ ----------
+ n_elem
+
+ Returns
+ -------
+
+ """
+ random = np.random.rand() # Adding some random numbers
+ input_position = random * np.ones((3, n_elem + 1))
+ correct_output = random * np.ones((3, n_elem))
+
+ output = node_to_element_position(input_position)
+ assert_allclose(correct_output, output, atol=Tolerance.atol())
+
+ @pytest.mark.parametrize("n_elem", [2, 3, 5, 10, 20])
+ def test_node_to_element_velocity(self, n_elem):
+ """
+ This function tests node_to_element_velocity function. We are
converting node velocities to element velocities. Here also
we are using numba to speed up the process.
@@ -789,12 +837,29 @@ try:
"""
random = np.random.rand() # Adding some random numbers
- input_variable = random * np.ones((3, n_elem + 1))
+ input_velocity = random * np.ones((3, n_elem + 1))
+ input_mass = 2.0 * random * np.ones(n_elem + 1)
correct_output = random * np.ones((3, n_elem))
- output = node_to_element_pos_or_vel(input_variable)
+ output = node_to_element_velocity(
+ mass=input_mass, node_velocity_collection=input_velocity
+ )
assert_allclose(correct_output, output, atol=Tolerance.atol())
+ @pytest.mark.parametrize("n_elem", [2, 3, 5, 10, 20])
+ def test_not_impl_error_for_node_to_element_pos_or_vel(self, n_elem):
+ random = np.random.rand() # Adding some random numbers
+ input_velocity = random * np.ones((3, n_elem + 1))
+ error_message = (
+ "This function is removed in v0.3.0. For node-to-element interpolation please use: \n"
+ "elastica.interaction.node_to_element_position() for rod position \n"
+ "elastica.interaction.node_to_element_velocity() for rod velocity. \n"
+ "For detail, refer to issue #80."
+ )
+ with pytest.raises(NotImplementedError) as error_info:
+ node_to_element_pos_or_vel(input_velocity)
+ assert error_info.value.args[0] == error_message
+
except ImportError:
pass
| Converting nodal velocities to element velocities
In PyElastica we store `velocity` on nodes and for some computations (i.e. rod damping, plane damping or stokes flow) we have to convert `velocity` from `nodes` to `elements`. Currently we are averaging the neigboring node velocity to compute element velocity using the following function.
https://github.com/GazzolaLab/PyElastica/blob/fee87b9da22e310ff925c16fdc839bf8405c51a4/elastica/interaction.py#L664-L703
Although this function is correct for uniform rods (uniform cross-section, element length and density) for tapered rods, momentum is not conserved since neighboring node masses are not the same. Thus, we have to first compute the total momentum of element and divide by the element mass to compute element velocity.
**How to fix** :
1. Use the following function to compute element velocities
``` python
def node_to_element_velocity(mass, velocity_collection):
"""
"""
n_elem = velocity_collection.shape[1] - 1
element_velocity = np.empty((3, n_elem))
for k in range(n_elem):
element_velocity[0, k] = (
mass[k+1] * velocity_collection[0, k + 1] + mass[k] * velocity_collection[0, k]
)
element_velocity[1, k] = (
mass[k+1] * velocity_collection[1, k + 1] + mass[k] * velocity_collection[1, k]
)
element_velocity[2, k] =(
mass[k+1] * velocity_collection[2, k + 1] + mass[k] * velocity_collection[2, k]
)
element_velocity[:,k] /= (mass[k+1] + mass[k])
return element_velocity
```
2. Rename the function `node_to_element_pos_or_vel` as `node_to_element_position`, since this will be only used to compute the element positions. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_interaction.py::TestInteractionPlane::test_interaction_without_contact[2]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_without_contact[3]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_without_contact[5]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_without_contact[10]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_without_contact[20]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_plane_without_k_and_nu[2]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_plane_without_k_and_nu[3]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_plane_without_k_and_nu[5]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_plane_without_k_and_nu[10]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_plane_without_k_and_nu[20]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_plane_with_k_without_nu[0.1-2]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_plane_with_k_without_nu[0.1-3]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_plane_with_k_without_nu[0.1-5]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_plane_with_k_without_nu[0.1-10]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_plane_with_k_without_nu[0.1-20]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_plane_with_k_without_nu[0.5-2]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_plane_with_k_without_nu[0.5-3]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_plane_with_k_without_nu[0.5-5]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_plane_with_k_without_nu[0.5-10]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_plane_with_k_without_nu[0.5-20]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_plane_with_k_without_nu[1.0-2]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_plane_with_k_without_nu[1.0-3]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_plane_with_k_without_nu[1.0-5]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_plane_with_k_without_nu[1.0-10]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_plane_with_k_without_nu[1.0-20]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_plane_with_k_without_nu[2-2]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_plane_with_k_without_nu[2-3]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_plane_with_k_without_nu[2-5]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_plane_with_k_without_nu[2-10]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_plane_with_k_without_nu[2-20]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_plane_with_k_without_nu[10-2]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_plane_with_k_without_nu[10-3]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_plane_with_k_without_nu[10-5]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_plane_with_k_without_nu[10-10]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_plane_with_k_without_nu[10-20]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_plane_without_k_with_nu[0.5-2]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_plane_without_k_with_nu[0.5-3]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_plane_without_k_with_nu[0.5-5]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_plane_without_k_with_nu[0.5-10]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_plane_without_k_with_nu[0.5-20]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_plane_without_k_with_nu[1.0-2]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_plane_without_k_with_nu[1.0-3]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_plane_without_k_with_nu[1.0-5]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_plane_without_k_with_nu[1.0-10]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_plane_without_k_with_nu[1.0-20]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_plane_without_k_with_nu[5.0-2]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_plane_without_k_with_nu[5.0-3]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_plane_without_k_with_nu[5.0-5]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_plane_without_k_with_nu[5.0-10]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_plane_without_k_with_nu[5.0-20]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_plane_without_k_with_nu[7.0-2]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_plane_without_k_with_nu[7.0-3]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_plane_without_k_with_nu[7.0-5]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_plane_without_k_with_nu[7.0-10]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_plane_without_k_with_nu[7.0-20]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_plane_without_k_with_nu[12.0-2]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_plane_without_k_with_nu[12.0-3]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_plane_without_k_with_nu[12.0-5]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_plane_without_k_with_nu[12.0-10]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_plane_without_k_with_nu[12.0-20]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_when_rod_is_under_plane[2]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_when_rod_is_under_plane[3]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_when_rod_is_under_plane[5]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_when_rod_is_under_plane[10]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_when_rod_is_under_plane[20]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_when_rod_is_under_plane_with_k_without_nu[0.1-2]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_when_rod_is_under_plane_with_k_without_nu[0.1-3]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_when_rod_is_under_plane_with_k_without_nu[0.1-5]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_when_rod_is_under_plane_with_k_without_nu[0.1-10]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_when_rod_is_under_plane_with_k_without_nu[0.1-20]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_when_rod_is_under_plane_with_k_without_nu[0.5-2]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_when_rod_is_under_plane_with_k_without_nu[0.5-3]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_when_rod_is_under_plane_with_k_without_nu[0.5-5]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_when_rod_is_under_plane_with_k_without_nu[0.5-10]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_when_rod_is_under_plane_with_k_without_nu[0.5-20]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_when_rod_is_under_plane_with_k_without_nu[1.0-2]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_when_rod_is_under_plane_with_k_without_nu[1.0-3]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_when_rod_is_under_plane_with_k_without_nu[1.0-5]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_when_rod_is_under_plane_with_k_without_nu[1.0-10]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_when_rod_is_under_plane_with_k_without_nu[1.0-20]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_when_rod_is_under_plane_with_k_without_nu[2-2]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_when_rod_is_under_plane_with_k_without_nu[2-3]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_when_rod_is_under_plane_with_k_without_nu[2-5]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_when_rod_is_under_plane_with_k_without_nu[2-10]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_when_rod_is_under_plane_with_k_without_nu[2-20]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_when_rod_is_under_plane_with_k_without_nu[10-2]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_when_rod_is_under_plane_with_k_without_nu[10-3]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_when_rod_is_under_plane_with_k_without_nu[10-5]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_when_rod_is_under_plane_with_k_without_nu[10-10]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_when_rod_is_under_plane_with_k_without_nu[10-20]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_when_rod_is_under_plane_without_k_with_nu[0.5-2]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_when_rod_is_under_plane_without_k_with_nu[0.5-3]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_when_rod_is_under_plane_without_k_with_nu[0.5-5]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_when_rod_is_under_plane_without_k_with_nu[0.5-10]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_when_rod_is_under_plane_without_k_with_nu[0.5-20]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_when_rod_is_under_plane_without_k_with_nu[1.0-2]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_when_rod_is_under_plane_without_k_with_nu[1.0-3]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_when_rod_is_under_plane_without_k_with_nu[1.0-5]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_when_rod_is_under_plane_without_k_with_nu[1.0-10]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_when_rod_is_under_plane_without_k_with_nu[1.0-20]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_when_rod_is_under_plane_without_k_with_nu[5.0-2]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_when_rod_is_under_plane_without_k_with_nu[5.0-3]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_when_rod_is_under_plane_without_k_with_nu[5.0-5]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_when_rod_is_under_plane_without_k_with_nu[5.0-10]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_when_rod_is_under_plane_without_k_with_nu[5.0-20]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_when_rod_is_under_plane_without_k_with_nu[7.0-2]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_when_rod_is_under_plane_without_k_with_nu[7.0-3]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_when_rod_is_under_plane_without_k_with_nu[7.0-5]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_when_rod_is_under_plane_without_k_with_nu[7.0-10]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_when_rod_is_under_plane_without_k_with_nu[7.0-20]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_when_rod_is_under_plane_without_k_with_nu[12.0-2]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_when_rod_is_under_plane_without_k_with_nu[12.0-3]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_when_rod_is_under_plane_without_k_with_nu[12.0-5]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_when_rod_is_under_plane_without_k_with_nu[12.0-10]",
"tests/test_interaction.py::TestInteractionPlane::test_interaction_when_rod_is_under_plane_without_k_with_nu[12.0-20]",
"tests/test_interaction.py::TestAuxiliaryFunctions::test_linear_interpolation_slip[2]",
"tests/test_interaction.py::TestAuxiliaryFunctions::test_linear_interpolation_slip[3]",
"tests/test_interaction.py::TestAuxiliaryFunctions::test_linear_interpolation_slip[5]",
"tests/test_interaction.py::TestAuxiliaryFunctions::test_linear_interpolation_slip[10]",
"tests/test_interaction.py::TestAuxiliaryFunctions::test_linear_interpolation_slip[20]",
"tests/test_interaction.py::TestAuxiliaryFunctions::test_node_to_element_mass_or_force[2]",
"tests/test_interaction.py::TestAuxiliaryFunctions::test_node_to_element_mass_or_force[3]",
"tests/test_interaction.py::TestAuxiliaryFunctions::test_node_to_element_mass_or_force[5]",
"tests/test_interaction.py::TestAuxiliaryFunctions::test_node_to_element_mass_or_force[10]",
"tests/test_interaction.py::TestAuxiliaryFunctions::test_node_to_element_mass_or_force[20]",
"tests/test_interaction.py::TestAuxiliaryFunctions::test_deprecated_nodes_to_elements[2]",
"tests/test_interaction.py::TestAuxiliaryFunctions::test_deprecated_nodes_to_elements[3]",
"tests/test_interaction.py::TestAuxiliaryFunctions::test_deprecated_nodes_to_elements[5]",
"tests/test_interaction.py::TestAuxiliaryFunctions::test_deprecated_nodes_to_elements[10]",
"tests/test_interaction.py::TestAuxiliaryFunctions::test_deprecated_nodes_to_elements[20]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_kinetic_friction[-1.0-2]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_kinetic_friction[-1.0-3]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_kinetic_friction[-1.0-5]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_kinetic_friction[-1.0-10]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_kinetic_friction[-1.0-20]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_kinetic_friction[-3.0-2]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_kinetic_friction[-3.0-3]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_kinetic_friction[-3.0-5]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_kinetic_friction[-3.0-10]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_kinetic_friction[-3.0-20]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_kinetic_friction[1.0-2]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_kinetic_friction[1.0-3]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_kinetic_friction[1.0-5]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_kinetic_friction[1.0-10]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_kinetic_friction[1.0-20]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_kinetic_friction[5.0-2]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_kinetic_friction[5.0-3]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_kinetic_friction[5.0-5]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_kinetic_friction[5.0-10]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_kinetic_friction[5.0-20]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_kinetic_friction[2.0-2]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_kinetic_friction[2.0-3]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_kinetic_friction[2.0-5]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_kinetic_friction[2.0-10]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_kinetic_friction[2.0-20]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_static_friction_total_force_smaller_than_static_friction_force[-1.0-2]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_static_friction_total_force_smaller_than_static_friction_force[-1.0-3]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_static_friction_total_force_smaller_than_static_friction_force[-1.0-5]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_static_friction_total_force_smaller_than_static_friction_force[-1.0-10]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_static_friction_total_force_smaller_than_static_friction_force[-1.0-20]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_static_friction_total_force_smaller_than_static_friction_force[-3.0-2]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_static_friction_total_force_smaller_than_static_friction_force[-3.0-3]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_static_friction_total_force_smaller_than_static_friction_force[-3.0-5]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_static_friction_total_force_smaller_than_static_friction_force[-3.0-10]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_static_friction_total_force_smaller_than_static_friction_force[-3.0-20]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_static_friction_total_force_smaller_than_static_friction_force[1.0-2]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_static_friction_total_force_smaller_than_static_friction_force[1.0-3]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_static_friction_total_force_smaller_than_static_friction_force[1.0-5]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_static_friction_total_force_smaller_than_static_friction_force[1.0-10]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_static_friction_total_force_smaller_than_static_friction_force[1.0-20]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_static_friction_total_force_smaller_than_static_friction_force[5.0-2]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_static_friction_total_force_smaller_than_static_friction_force[5.0-3]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_static_friction_total_force_smaller_than_static_friction_force[5.0-5]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_static_friction_total_force_smaller_than_static_friction_force[5.0-10]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_static_friction_total_force_smaller_than_static_friction_force[5.0-20]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_static_friction_total_force_smaller_than_static_friction_force[2.0-2]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_static_friction_total_force_smaller_than_static_friction_force[2.0-3]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_static_friction_total_force_smaller_than_static_friction_force[2.0-5]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_static_friction_total_force_smaller_than_static_friction_force[2.0-10]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_static_friction_total_force_smaller_than_static_friction_force[2.0-20]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_static_friction_total_force_larger_than_static_friction_force[-20.0-2]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_static_friction_total_force_larger_than_static_friction_force[-20.0-3]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_static_friction_total_force_larger_than_static_friction_force[-20.0-5]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_static_friction_total_force_larger_than_static_friction_force[-20.0-10]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_static_friction_total_force_larger_than_static_friction_force[-20.0-20]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_static_friction_total_force_larger_than_static_friction_force[-15.0-2]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_static_friction_total_force_larger_than_static_friction_force[-15.0-3]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_static_friction_total_force_larger_than_static_friction_force[-15.0-5]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_static_friction_total_force_larger_than_static_friction_force[-15.0-10]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_static_friction_total_force_larger_than_static_friction_force[-15.0-20]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_static_friction_total_force_larger_than_static_friction_force[15.0-2]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_static_friction_total_force_larger_than_static_friction_force[15.0-3]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_static_friction_total_force_larger_than_static_friction_force[15.0-5]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_static_friction_total_force_larger_than_static_friction_force[15.0-10]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_static_friction_total_force_larger_than_static_friction_force[15.0-20]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_static_friction_total_force_larger_than_static_friction_force[20.0-2]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_static_friction_total_force_larger_than_static_friction_force[20.0-3]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_static_friction_total_force_larger_than_static_friction_force[20.0-5]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_static_friction_total_force_larger_than_static_friction_force[20.0-10]",
"tests/test_interaction.py::TestAnisotropicFriction::test_axial_static_friction_total_force_larger_than_static_friction_force[20.0-20]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[-5.0--1.0-2]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[-5.0--1.0-3]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[-5.0--1.0-5]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[-5.0--1.0-10]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[-5.0--1.0-20]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[-5.0--3.0-2]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[-5.0--3.0-3]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[-5.0--3.0-5]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[-5.0--3.0-10]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[-5.0--3.0-20]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[-5.0-1.0-2]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[-5.0-1.0-3]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[-5.0-1.0-5]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[-5.0-1.0-10]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[-5.0-1.0-20]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[-5.0-2.0-2]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[-5.0-2.0-3]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[-5.0-2.0-5]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[-5.0-2.0-10]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[-5.0-2.0-20]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[-5.0-5.0-2]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[-5.0-5.0-3]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[-5.0-5.0-5]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[-5.0-5.0-10]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[-5.0-5.0-20]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[-2.0--1.0-2]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[-2.0--1.0-3]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[-2.0--1.0-5]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[-2.0--1.0-10]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[-2.0--1.0-20]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[-2.0--3.0-2]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[-2.0--3.0-3]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[-2.0--3.0-5]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[-2.0--3.0-10]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[-2.0--3.0-20]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[-2.0-1.0-2]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[-2.0-1.0-3]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[-2.0-1.0-5]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[-2.0-1.0-10]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[-2.0-1.0-20]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[-2.0-2.0-2]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[-2.0-2.0-3]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[-2.0-2.0-5]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[-2.0-2.0-10]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[-2.0-2.0-20]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[-2.0-5.0-2]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[-2.0-5.0-3]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[-2.0-5.0-5]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[-2.0-5.0-10]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[-2.0-5.0-20]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[0.0--1.0-2]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[0.0--1.0-3]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[0.0--1.0-5]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[0.0--1.0-10]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[0.0--1.0-20]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[0.0--3.0-2]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[0.0--3.0-3]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[0.0--3.0-5]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[0.0--3.0-10]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[0.0--3.0-20]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[0.0-1.0-2]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[0.0-1.0-3]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[0.0-1.0-5]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[0.0-1.0-10]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[0.0-1.0-20]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[0.0-2.0-2]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[0.0-2.0-3]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[0.0-2.0-5]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[0.0-2.0-10]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[0.0-2.0-20]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[0.0-5.0-2]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[0.0-5.0-3]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[0.0-5.0-5]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[0.0-5.0-10]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[0.0-5.0-20]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[4.0--1.0-2]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[4.0--1.0-3]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[4.0--1.0-5]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[4.0--1.0-10]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[4.0--1.0-20]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[4.0--3.0-2]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[4.0--3.0-3]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[4.0--3.0-5]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[4.0--3.0-10]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[4.0--3.0-20]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[4.0-1.0-2]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[4.0-1.0-3]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[4.0-1.0-5]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[4.0-1.0-10]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[4.0-1.0-20]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[4.0-2.0-2]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[4.0-2.0-3]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[4.0-2.0-5]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[4.0-2.0-10]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[4.0-2.0-20]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[4.0-5.0-2]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[4.0-5.0-3]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[4.0-5.0-5]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[4.0-5.0-10]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[4.0-5.0-20]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[6.0--1.0-2]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[6.0--1.0-3]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[6.0--1.0-5]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[6.0--1.0-10]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[6.0--1.0-20]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[6.0--3.0-2]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[6.0--3.0-3]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[6.0--3.0-5]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[6.0--3.0-10]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[6.0--3.0-20]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[6.0-1.0-2]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[6.0-1.0-3]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[6.0-1.0-5]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[6.0-1.0-10]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[6.0-1.0-20]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[6.0-2.0-2]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[6.0-2.0-3]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[6.0-2.0-5]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[6.0-2.0-10]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[6.0-2.0-20]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[6.0-5.0-2]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[6.0-5.0-3]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[6.0-5.0-5]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[6.0-5.0-10]",
"tests/test_interaction.py::TestAnisotropicFriction::test_kinetic_rolling_friction[6.0-5.0-20]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_force_smaller_than_static_friction_force[-20.0-2]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_force_smaller_than_static_friction_force[-20.0-3]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_force_smaller_than_static_friction_force[-20.0-5]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_force_smaller_than_static_friction_force[-20.0-10]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_force_smaller_than_static_friction_force[-20.0-20]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_force_smaller_than_static_friction_force[-15.0-2]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_force_smaller_than_static_friction_force[-15.0-3]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_force_smaller_than_static_friction_force[-15.0-5]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_force_smaller_than_static_friction_force[-15.0-10]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_force_smaller_than_static_friction_force[-15.0-20]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_force_smaller_than_static_friction_force[15.0-2]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_force_smaller_than_static_friction_force[15.0-3]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_force_smaller_than_static_friction_force[15.0-5]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_force_smaller_than_static_friction_force[15.0-10]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_force_smaller_than_static_friction_force[15.0-20]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_force_smaller_than_static_friction_force[20.0-2]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_force_smaller_than_static_friction_force[20.0-3]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_force_smaller_than_static_friction_force[20.0-5]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_force_smaller_than_static_friction_force[20.0-10]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_force_smaller_than_static_friction_force[20.0-20]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_force_larger_than_static_friction_force[-100.0-2]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_force_larger_than_static_friction_force[-100.0-3]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_force_larger_than_static_friction_force[-100.0-5]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_force_larger_than_static_friction_force[-100.0-10]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_force_larger_than_static_friction_force[-100.0-20]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_force_larger_than_static_friction_force[-80.0-2]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_force_larger_than_static_friction_force[-80.0-3]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_force_larger_than_static_friction_force[-80.0-5]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_force_larger_than_static_friction_force[-80.0-10]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_force_larger_than_static_friction_force[-80.0-20]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_force_larger_than_static_friction_force[65.0-2]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_force_larger_than_static_friction_force[65.0-3]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_force_larger_than_static_friction_force[65.0-5]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_force_larger_than_static_friction_force[65.0-10]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_force_larger_than_static_friction_force[65.0-20]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_force_larger_than_static_friction_force[95.0-2]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_force_larger_than_static_friction_force[95.0-3]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_force_larger_than_static_friction_force[95.0-5]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_force_larger_than_static_friction_force[95.0-10]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_force_larger_than_static_friction_force[95.0-20]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_torque_smaller_than_static_friction_force[-3.0-2]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_torque_smaller_than_static_friction_force[-3.0-3]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_torque_smaller_than_static_friction_force[-3.0-5]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_torque_smaller_than_static_friction_force[-3.0-10]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_torque_smaller_than_static_friction_force[-3.0-20]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_torque_smaller_than_static_friction_force[-1.0-2]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_torque_smaller_than_static_friction_force[-1.0-3]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_torque_smaller_than_static_friction_force[-1.0-5]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_torque_smaller_than_static_friction_force[-1.0-10]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_torque_smaller_than_static_friction_force[-1.0-20]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_torque_smaller_than_static_friction_force[2.0-2]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_torque_smaller_than_static_friction_force[2.0-3]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_torque_smaller_than_static_friction_force[2.0-5]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_torque_smaller_than_static_friction_force[2.0-10]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_torque_smaller_than_static_friction_force[2.0-20]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_torque_smaller_than_static_friction_force[3.5-2]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_torque_smaller_than_static_friction_force[3.5-3]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_torque_smaller_than_static_friction_force[3.5-5]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_torque_smaller_than_static_friction_force[3.5-10]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_torque_smaller_than_static_friction_force[3.5-20]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_torque_larger_than_static_friction_force[-10.0-2]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_torque_larger_than_static_friction_force[-10.0-3]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_torque_larger_than_static_friction_force[-10.0-5]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_torque_larger_than_static_friction_force[-10.0-10]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_torque_larger_than_static_friction_force[-10.0-20]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_torque_larger_than_static_friction_force[-5.0-2]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_torque_larger_than_static_friction_force[-5.0-3]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_torque_larger_than_static_friction_force[-5.0-5]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_torque_larger_than_static_friction_force[-5.0-10]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_torque_larger_than_static_friction_force[-5.0-20]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_torque_larger_than_static_friction_force[6.0-2]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_torque_larger_than_static_friction_force[6.0-3]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_torque_larger_than_static_friction_force[6.0-5]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_torque_larger_than_static_friction_force[6.0-10]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_torque_larger_than_static_friction_force[6.0-20]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_torque_larger_than_static_friction_force[7.5-2]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_torque_larger_than_static_friction_force[7.5-3]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_torque_larger_than_static_friction_force[7.5-5]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_torque_larger_than_static_friction_force[7.5-10]",
"tests/test_interaction.py::TestAnisotropicFriction::test_static_rolling_friction_total_torque_larger_than_static_friction_force[7.5-20]",
"tests/test_interaction.py::TestAuxiliaryFunctionsForSlenderBodyTheory::test_sum_over_elements[2]",
"tests/test_interaction.py::TestAuxiliaryFunctionsForSlenderBodyTheory::test_sum_over_elements[3]",
"tests/test_interaction.py::TestAuxiliaryFunctionsForSlenderBodyTheory::test_sum_over_elements[5]",
"tests/test_interaction.py::TestAuxiliaryFunctionsForSlenderBodyTheory::test_sum_over_elements[10]",
"tests/test_interaction.py::TestAuxiliaryFunctionsForSlenderBodyTheory::test_sum_over_elements[20]",
"tests/test_interaction.py::TestAuxiliaryFunctionsForSlenderBodyTheory::test_node_to_element_position[2]",
"tests/test_interaction.py::TestAuxiliaryFunctionsForSlenderBodyTheory::test_node_to_element_position[3]",
"tests/test_interaction.py::TestAuxiliaryFunctionsForSlenderBodyTheory::test_node_to_element_position[5]",
"tests/test_interaction.py::TestAuxiliaryFunctionsForSlenderBodyTheory::test_node_to_element_position[10]",
"tests/test_interaction.py::TestAuxiliaryFunctionsForSlenderBodyTheory::test_node_to_element_position[20]",
"tests/test_interaction.py::TestAuxiliaryFunctionsForSlenderBodyTheory::test_node_to_element_velocity[2]",
"tests/test_interaction.py::TestAuxiliaryFunctionsForSlenderBodyTheory::test_node_to_element_velocity[3]",
"tests/test_interaction.py::TestAuxiliaryFunctionsForSlenderBodyTheory::test_node_to_element_velocity[5]",
"tests/test_interaction.py::TestAuxiliaryFunctionsForSlenderBodyTheory::test_node_to_element_velocity[10]",
"tests/test_interaction.py::TestAuxiliaryFunctionsForSlenderBodyTheory::test_node_to_element_velocity[20]",
"tests/test_interaction.py::TestAuxiliaryFunctionsForSlenderBodyTheory::test_not_impl_error_for_node_to_element_pos_or_vel[2]",
"tests/test_interaction.py::TestAuxiliaryFunctionsForSlenderBodyTheory::test_not_impl_error_for_node_to_element_pos_or_vel[3]",
"tests/test_interaction.py::TestAuxiliaryFunctionsForSlenderBodyTheory::test_not_impl_error_for_node_to_element_pos_or_vel[5]",
"tests/test_interaction.py::TestAuxiliaryFunctionsForSlenderBodyTheory::test_not_impl_error_for_node_to_element_pos_or_vel[10]",
"tests/test_interaction.py::TestAuxiliaryFunctionsForSlenderBodyTheory::test_not_impl_error_for_node_to_element_pos_or_vel[20]",
"tests/test_interaction.py::TestSlenderBody::test_slender_body_theory_only_factor[2-2]",
"tests/test_interaction.py::TestSlenderBody::test_slender_body_theory_only_factor[2-3]",
"tests/test_interaction.py::TestSlenderBody::test_slender_body_theory_only_factor[2-5]",
"tests/test_interaction.py::TestSlenderBody::test_slender_body_theory_only_factor[2-10]",
"tests/test_interaction.py::TestSlenderBody::test_slender_body_theory_only_factor[2-20]",
"tests/test_interaction.py::TestSlenderBody::test_slender_body_theory_only_factor[3-2]",
"tests/test_interaction.py::TestSlenderBody::test_slender_body_theory_only_factor[3-3]",
"tests/test_interaction.py::TestSlenderBody::test_slender_body_theory_only_factor[3-5]",
"tests/test_interaction.py::TestSlenderBody::test_slender_body_theory_only_factor[3-10]",
"tests/test_interaction.py::TestSlenderBody::test_slender_body_theory_only_factor[3-20]",
"tests/test_interaction.py::TestSlenderBody::test_slender_body_theory_only_factor[5-2]",
"tests/test_interaction.py::TestSlenderBody::test_slender_body_theory_only_factor[5-3]",
"tests/test_interaction.py::TestSlenderBody::test_slender_body_theory_only_factor[5-5]",
"tests/test_interaction.py::TestSlenderBody::test_slender_body_theory_only_factor[5-10]",
"tests/test_interaction.py::TestSlenderBody::test_slender_body_theory_only_factor[5-20]",
"tests/test_interaction.py::TestSlenderBody::test_slender_body_theory_only_factor[10-2]",
"tests/test_interaction.py::TestSlenderBody::test_slender_body_theory_only_factor[10-3]",
"tests/test_interaction.py::TestSlenderBody::test_slender_body_theory_only_factor[10-5]",
"tests/test_interaction.py::TestSlenderBody::test_slender_body_theory_only_factor[10-10]",
"tests/test_interaction.py::TestSlenderBody::test_slender_body_theory_only_factor[10-20]",
"tests/test_interaction.py::TestSlenderBody::test_slender_body_theory_only_factor[20-2]",
"tests/test_interaction.py::TestSlenderBody::test_slender_body_theory_only_factor[20-3]",
"tests/test_interaction.py::TestSlenderBody::test_slender_body_theory_only_factor[20-5]",
"tests/test_interaction.py::TestSlenderBody::test_slender_body_theory_only_factor[20-10]",
"tests/test_interaction.py::TestSlenderBody::test_slender_body_theory_only_factor[20-20]",
"tests/test_interaction.py::TestSlenderBody::test_slender_body_matrix_product_only_xz[2]",
"tests/test_interaction.py::TestSlenderBody::test_slender_body_matrix_product_only_xz[3]",
"tests/test_interaction.py::TestSlenderBody::test_slender_body_matrix_product_only_xz[5]",
"tests/test_interaction.py::TestSlenderBody::test_slender_body_matrix_product_only_xz[10]",
"tests/test_interaction.py::TestSlenderBody::test_slender_body_matrix_product_only_xz[20]",
"tests/test_interaction.py::TestSlenderBody::test_slender_body_matrix_product_only_yz[2]",
"tests/test_interaction.py::TestSlenderBody::test_slender_body_matrix_product_only_yz[3]",
"tests/test_interaction.py::TestSlenderBody::test_slender_body_matrix_product_only_yz[5]",
"tests/test_interaction.py::TestSlenderBody::test_slender_body_matrix_product_only_yz[10]",
"tests/test_interaction.py::TestSlenderBody::test_slender_body_matrix_product_only_yz[20]",
"tests/test_interaction.py::TestSlenderBody::test_slender_body_matrix_product_only_xy[2]",
"tests/test_interaction.py::TestSlenderBody::test_slender_body_matrix_product_only_xy[3]",
"tests/test_interaction.py::TestSlenderBody::test_slender_body_matrix_product_only_xy[5]",
"tests/test_interaction.py::TestSlenderBody::test_slender_body_matrix_product_only_xy[10]",
"tests/test_interaction.py::TestSlenderBody::test_slender_body_matrix_product_only_xy[20]"
] | [] | {
"failed_lite_validators": [
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2022-06-01T04:26:40Z" | mit |
|
GeneralMills__pytrends-409 | diff --git a/README.md b/README.md
index d348f16..3d4d350 100644
--- a/README.md
+++ b/README.md
@@ -39,7 +39,7 @@ Only good until Google changes their backend again :-P. When that happens feel f
## Requirements
-* Written for both Python 2.7+ and Python 3.3+
+* Written for Python 3.3+
* Requires Requests, lxml, Pandas
<sub><sup>[back to top](#pytrends)</sub></sup>
diff --git a/pytrends/request.py b/pytrends/request.py
index e2ae29d..8e7d48c 100644
--- a/pytrends/request.py
+++ b/pytrends/request.py
@@ -1,5 +1,3 @@
-from __future__ import absolute_import, print_function, unicode_literals
-
import json
import sys
import time
@@ -14,10 +12,7 @@ from requests.packages.urllib3.util.retry import Retry
from pytrends import exceptions
-if sys.version_info[0] == 2: # Python 2
- from urllib import quote
-else: # Python 3
- from urllib.parse import quote
+from urllib.parse import quote
class TrendReq(object):
@@ -150,6 +145,8 @@ class TrendReq(object):
def build_payload(self, kw_list, cat=0, timeframe='today 5-y', geo='',
gprop=''):
"""Create the payload for related queries, interest over time and interest by region"""
+ if gprop not in ['', 'images', 'news', 'youtube', 'froogle']:
+ raise ValueError('gprop must be empty (to indicate web), images, news, youtube, or froogle')
self.kw_list = kw_list
self.geo = geo or self.geo
self.token_payload = {
@@ -241,6 +238,8 @@ class TrendReq(object):
result_df2 = df['isPartial'].apply(lambda x: pd.Series(
str(x).replace('[', '').replace(']', '').split(',')))
result_df2.columns = ['isPartial']
+ # Change to a bool type.
+ result_df2.isPartial = result_df2.isPartial == 'True'
# concatenate the two dataframes
final = pd.concat([result_df, result_df2], axis=1)
else:
@@ -285,7 +284,7 @@ class TrendReq(object):
# rename the column with the search keyword
df = df[['geoName', 'geoCode', 'value']].set_index(
['geoName']).sort_index()
- # split list columns into seperate ones, remove brackets and split on comma
+ # split list columns into separate ones, remove brackets and split on comma
result_df = df['value'].apply(lambda x: pd.Series(
str(x).replace('[', '').replace(']', '').split(',')))
if inc_geo_code:
@@ -398,7 +397,7 @@ class TrendReq(object):
"""Request data from Google's Hot Searches section and return a dataframe"""
# make the request
- # forms become obsolute due to the new TRENDING_SEACHES_URL
+ # forms become obsolete due to the new TRENDING_SEARCHES_URL
# forms = {'ajax': 1, 'pn': pn, 'htd': '', 'htv': 'l'}
req_json = self._get_data(
url=TrendReq.TRENDING_SEARCHES_URL,
@@ -479,7 +478,7 @@ class TrendReq(object):
geo='', gprop='', sleep=0):
"""Gets historical hourly data for interest by chunking requests to 1 week at a time (which is what Google allows)"""
- # construct datetime obejcts - raises ValueError if invalid parameters
+ # construct datetime objects - raises ValueError if invalid parameters
initial_start_date = start_date = datetime(year_start, month_start,
day_start, hour_start)
end_date = datetime(year_end, month_end, day_end, hour_end)
diff --git a/setup.py b/setup.py
index 717fc7a..8ced39d 100644
--- a/setup.py
+++ b/setup.py
@@ -21,7 +21,6 @@ setup(
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
- 'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
| GeneralMills/pytrends | 938ab0b7f71ce3827605322cf4475d1756f40909 | diff --git a/pytrends/test_trendReq.py b/pytrends/test_trendReq.py
index 80a4748..8c3efd3 100644
--- a/pytrends/test_trendReq.py
+++ b/pytrends/test_trendReq.py
@@ -1,4 +1,5 @@
from unittest import TestCase
+import pandas.api.types as ptypes
from pytrends.request import TrendReq
@@ -29,6 +30,31 @@ class TestTrendReq(TestCase):
pytrend.build_payload(kw_list=['pizza', 'bagel'])
self.assertIsNotNone(pytrend.interest_over_time())
+ def test_interest_over_time_images(self):
+ pytrend = TrendReq()
+ pytrend.build_payload(kw_list=['pizza', 'bagel'], gprop='images')
+ self.assertIsNotNone(pytrend.interest_over_time())
+
+ def test_interest_over_time_news(self):
+ pytrend = TrendReq()
+ pytrend.build_payload(kw_list=['pizza', 'bagel'], gprop='news')
+ self.assertIsNotNone(pytrend.interest_over_time())
+
+ def test_interest_over_time_youtube(self):
+ pytrend = TrendReq()
+ pytrend.build_payload(kw_list=['pizza', 'bagel'], gprop='youtube')
+ self.assertIsNotNone(pytrend.interest_over_time())
+
+ def test_interest_over_time_froogle(self):
+ pytrend = TrendReq()
+ pytrend.build_payload(kw_list=['pizza', 'bagel'], gprop='froogle')
+ self.assertIsNotNone(pytrend.interest_over_time())
+
+ def test_interest_over_time_bad_gprop(self):
+ pytrend = TrendReq()
+ with self.assertRaises(ValueError):
+ pytrend.build_payload(kw_list=['pizza', 'bagel'], gprop=' ')
+
def test_interest_by_region(self):
pytrend = TrendReq()
pytrend.build_payload(kw_list=['pizza', 'bagel'])
@@ -47,14 +73,27 @@ class TestTrendReq(TestCase):
def test_trending_searches(self):
pytrend = TrendReq()
pytrend.build_payload(kw_list=['pizza', 'bagel'])
- self.assertIsNotNone(pytrend.trending_searches(pn='p1'))
+ self.assertIsNotNone(pytrend.trending_searches())
def test_top_charts(self):
pytrend = TrendReq()
pytrend.build_payload(kw_list=['pizza', 'bagel'])
- self.assertIsNotNone(pytrend.top_charts(cid='actors', date=201611))
+ self.assertIsNotNone(pytrend.top_charts(date=2019))
def test_suggestions(self):
pytrend = TrendReq()
pytrend.build_payload(kw_list=['pizza', 'bagel'])
self.assertIsNotNone(pytrend.suggestions(keyword='pizza'))
+
+ def test_ispartial_dtype(self):
+ pytrend = TrendReq()
+ pytrend.build_payload(kw_list=['pizza', 'bagel'])
+ df = pytrend.interest_over_time()
+ assert ptypes.is_bool_dtype(df.isPartial)
+
+ def test_ispartial_dtype_timeframe_all(self):
+ pytrend = TrendReq()
+ pytrend.build_payload(kw_list=['pizza', 'bagel'],
+ timeframe='all')
+ df = pytrend.interest_over_time()
+ assert ptypes.is_bool_dtype(df.isPartial)
| Pytrends error 400
Hi all,
I am trying to pull some data from Google Trends but I keep getting the error "The request failed: Google returned a response with code 400.". I think it might has something to do with pytrend.interest_over_time() but I haven't been able to fix it.
import csv
import time
import pandas as pd
from pytrends.request import TrendReq
pytrend = TrendReq(hl='DK', tz=360)
keywords =['Scandlines']
pytrend.build_payload(
kw_list=keywords,
cat=0,
timeframe='2016-12-14 2017-01-25',
geo='DK',
gprop=' '
)
data = pytrend.interest_over_time()
data.to_csv('Uge 16', encoding='utf_8_sig')
Anybody having similar issues?
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"pytrends/test_trendReq.py::TestTrendReq::test_interest_over_time_bad_gprop",
"pytrends/test_trendReq.py::TestTrendReq::test_ispartial_dtype",
"pytrends/test_trendReq.py::TestTrendReq::test_ispartial_dtype_timeframe_all"
] | [
"pytrends/test_trendReq.py::TestTrendReq::test__get_data",
"pytrends/test_trendReq.py::TestTrendReq::test__tokens",
"pytrends/test_trendReq.py::TestTrendReq::test_build_payload",
"pytrends/test_trendReq.py::TestTrendReq::test_interest_by_region",
"pytrends/test_trendReq.py::TestTrendReq::test_interest_over_time",
"pytrends/test_trendReq.py::TestTrendReq::test_interest_over_time_froogle",
"pytrends/test_trendReq.py::TestTrendReq::test_interest_over_time_images",
"pytrends/test_trendReq.py::TestTrendReq::test_interest_over_time_news",
"pytrends/test_trendReq.py::TestTrendReq::test_interest_over_time_youtube",
"pytrends/test_trendReq.py::TestTrendReq::test_related_queries",
"pytrends/test_trendReq.py::TestTrendReq::test_related_topics",
"pytrends/test_trendReq.py::TestTrendReq::test_suggestions",
"pytrends/test_trendReq.py::TestTrendReq::test_top_charts",
"pytrends/test_trendReq.py::TestTrendReq::test_trending_searches"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
} | "2020-06-09T14:34:48Z" | apache-2.0 |
|
GeneralMills__pytrends-410 | diff --git a/README.md b/README.md
index d348f16..3d4d350 100644
--- a/README.md
+++ b/README.md
@@ -39,7 +39,7 @@ Only good until Google changes their backend again :-P. When that happens feel f
## Requirements
-* Written for both Python 2.7+ and Python 3.3+
+* Written for Python 3.3+
* Requires Requests, lxml, Pandas
<sub><sup>[back to top](#pytrends)</sub></sup>
diff --git a/pytrends/request.py b/pytrends/request.py
index e2ae29d..93f0f6b 100644
--- a/pytrends/request.py
+++ b/pytrends/request.py
@@ -1,5 +1,3 @@
-from __future__ import absolute_import, print_function, unicode_literals
-
import json
import sys
import time
@@ -14,10 +12,7 @@ from requests.packages.urllib3.util.retry import Retry
from pytrends import exceptions
-if sys.version_info[0] == 2: # Python 2
- from urllib import quote
-else: # Python 3
- from urllib.parse import quote
+from urllib.parse import quote
class TrendReq(object):
@@ -241,6 +236,8 @@ class TrendReq(object):
result_df2 = df['isPartial'].apply(lambda x: pd.Series(
str(x).replace('[', '').replace(']', '').split(',')))
result_df2.columns = ['isPartial']
+ # Change to a bool type.
+ result_df2.isPartial = result_df2.isPartial == 'True'
# concatenate the two dataframes
final = pd.concat([result_df, result_df2], axis=1)
else:
@@ -285,7 +282,7 @@ class TrendReq(object):
# rename the column with the search keyword
df = df[['geoName', 'geoCode', 'value']].set_index(
['geoName']).sort_index()
- # split list columns into seperate ones, remove brackets and split on comma
+ # split list columns into separate ones, remove brackets and split on comma
result_df = df['value'].apply(lambda x: pd.Series(
str(x).replace('[', '').replace(']', '').split(',')))
if inc_geo_code:
@@ -398,7 +395,7 @@ class TrendReq(object):
"""Request data from Google's Hot Searches section and return a dataframe"""
# make the request
- # forms become obsolute due to the new TRENDING_SEACHES_URL
+ # forms become obsolete due to the new TRENDING_SEARCHES_URL
# forms = {'ajax': 1, 'pn': pn, 'htd': '', 'htv': 'l'}
req_json = self._get_data(
url=TrendReq.TRENDING_SEARCHES_URL,
@@ -479,7 +476,7 @@ class TrendReq(object):
geo='', gprop='', sleep=0):
"""Gets historical hourly data for interest by chunking requests to 1 week at a time (which is what Google allows)"""
- # construct datetime obejcts - raises ValueError if invalid parameters
+ # construct datetime objects - raises ValueError if invalid parameters
initial_start_date = start_date = datetime(year_start, month_start,
day_start, hour_start)
end_date = datetime(year_end, month_end, day_end, hour_end)
diff --git a/setup.py b/setup.py
index 717fc7a..8ced39d 100644
--- a/setup.py
+++ b/setup.py
@@ -21,7 +21,6 @@ setup(
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
- 'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
| GeneralMills/pytrends | 938ab0b7f71ce3827605322cf4475d1756f40909 | diff --git a/pytrends/test_trendReq.py b/pytrends/test_trendReq.py
index 80a4748..1a70d6b 100644
--- a/pytrends/test_trendReq.py
+++ b/pytrends/test_trendReq.py
@@ -1,4 +1,5 @@
from unittest import TestCase
+import pandas.api.types as ptypes
from pytrends.request import TrendReq
@@ -47,14 +48,27 @@ class TestTrendReq(TestCase):
def test_trending_searches(self):
pytrend = TrendReq()
pytrend.build_payload(kw_list=['pizza', 'bagel'])
- self.assertIsNotNone(pytrend.trending_searches(pn='p1'))
+ self.assertIsNotNone(pytrend.trending_searches())
def test_top_charts(self):
pytrend = TrendReq()
pytrend.build_payload(kw_list=['pizza', 'bagel'])
- self.assertIsNotNone(pytrend.top_charts(cid='actors', date=201611))
+ self.assertIsNotNone(pytrend.top_charts(date=2019))
def test_suggestions(self):
pytrend = TrendReq()
pytrend.build_payload(kw_list=['pizza', 'bagel'])
self.assertIsNotNone(pytrend.suggestions(keyword='pizza'))
+
+ def test_ispartial_dtype(self):
+ pytrend = TrendReq()
+ pytrend.build_payload(kw_list=['pizza', 'bagel'])
+ df = pytrend.interest_over_time()
+ assert ptypes.is_bool_dtype(df.isPartial)
+
+ def test_ispartial_dtype_timeframe_all(self):
+ pytrend = TrendReq()
+ pytrend.build_payload(kw_list=['pizza', 'bagel'],
+ timeframe='all')
+ df = pytrend.interest_over_time()
+ assert ptypes.is_bool_dtype(df.isPartial)
| isPartial field dtype is "object" instead of "bool" for gprop='news' and timeframe='all'
pytrends 4.7.2
from pytrends.request import TrendReq
pytrend = TrendReq()
pytrend.build_payload(kw_list=["apple"], gprop='news', timeframe='all')
result = pytrend.interest_over_time()
print(result.dtypes)
Output:
apple int64
isPartial object
dtype: object | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"pytrends/test_trendReq.py::TestTrendReq::test_ispartial_dtype",
"pytrends/test_trendReq.py::TestTrendReq::test_ispartial_dtype_timeframe_all"
] | [
"pytrends/test_trendReq.py::TestTrendReq::test__get_data",
"pytrends/test_trendReq.py::TestTrendReq::test__tokens",
"pytrends/test_trendReq.py::TestTrendReq::test_build_payload",
"pytrends/test_trendReq.py::TestTrendReq::test_interest_by_region",
"pytrends/test_trendReq.py::TestTrendReq::test_interest_over_time",
"pytrends/test_trendReq.py::TestTrendReq::test_related_queries",
"pytrends/test_trendReq.py::TestTrendReq::test_related_topics",
"pytrends/test_trendReq.py::TestTrendReq::test_suggestions",
"pytrends/test_trendReq.py::TestTrendReq::test_top_charts",
"pytrends/test_trendReq.py::TestTrendReq::test_trending_searches"
] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2020-06-09T15:05:02Z" | apache-2.0 |
|
GeneralMills__pytrends-478 | diff --git a/README.md b/README.md
index 7515d36..d7cf567 100644
--- a/README.md
+++ b/README.md
@@ -7,10 +7,10 @@ Unofficial API for Google Trends
Allows simple interface for automating downloading of reports from Google Trends.
Only good until Google changes their backend again :-P. When that happens feel free to contribute!
-**Looking for maintainers!**
+**Looking for maintainers!** Please open an issue with a method of contacting you if you're interested.
-## Table of contens
+## Table of Contents
* [Installation](#installation)
@@ -18,7 +18,7 @@ Only good until Google changes their backend again :-P. When that happens feel f
* [API Methods](#api-methods)
- * [Common API parameters](#common-api-parameters)
+ * [Common API Parameters](#common-api-parameters)
* [Interest Over Time](#interest-over-time)
* [Historical Hourly Interest](#historical-hourly-interest)
@@ -26,6 +26,7 @@ Only good until Google changes their backend again :-P. When that happens feel f
* [Related Topics](#related-topics)
* [Related Queries](#related-queries)
* [Trending Searches](#trending-searches)
+ * [Realtime Search Trends](#realtime-search-trends)
* [Top Charts](#top-charts)
* [Suggestions](#suggestions)
@@ -136,13 +137,13 @@ Many API methods use the following:
- For example ```"iron"``` will have a drop down of ```"Iron Chemical Element, Iron Cross, Iron Man, etc"```.
- Find the encoded topic by using the get_suggestions() function and choose the most relevant one for you.
- For example: ```https://www.google.com/trends/explore#q=%2Fm%2F025rw19&cmpt=q```
- - ```"%2Fm%2F025rw19"``` is the topic "Iron Chemical Element" to use this with pytrends
+ - ```"/m/025rw19"``` is the topic "Iron Chemical Element" to use this with pytrends
- You can also use `pytrends.suggestions()` to automate this.
* `cat`
- Category to narrow results
- - Find available cateogies by inspecting the url when manually using Google Trends. The category starts after ```cat=``` and ends before the next ```&``` or view this [wiki page containing all available categories](https://github.com/pat310/google-trends-api/wiki/Google-Trends-Categories)
+ - Find available categories by inspecting the url when manually using Google Trends. The category starts after ```cat=``` and ends before the next ```&``` or view this [wiki page containing all available categories](https://github.com/pat310/google-trends-api/wiki/Google-Trends-Categories)
- For example: ```"https://www.google.com/trends/explore#q=pizza&cat=71"```
- ```'71'``` is the category
- Defaults to no category
@@ -152,7 +153,7 @@ Many API methods use the following:
- Two letter country abbreviation
- For example United States is ```'US'```
- Defaults to World
- - More detail available for States/Provinces by specifying additonal abbreviations
+ - More detail available for States/Provinces by specifying additional abbreviations
- For example: Alabama would be ```'US-AL'```
- For example: England would be ```'GB-ENG'```
@@ -278,6 +279,15 @@ Returns pandas.DataFrame
<sub><sup>[back to top](#trending_searches)</sub></sup>
+### Realtime Search Trends
+
+ pytrends.realtime_trending_searches(pn='US') # realtime search trends for United States
+ pytrends.realtime_trending_searches(pn='IN') # India
+
+Returns pandas.DataFrame
+
+<sub><sup>[back to top](#realtime-search-trends)</sub></sup>
+
### Top Charts
pytrends.top_charts(date, hl='en-US', tz=300, geo='GLOBAL')
@@ -325,7 +335,7 @@ Returns dictionary
* Google may change aggregation level for items with very large or very small search volume
* Rate Limit is not publicly known, let me know if you have a consistent estimate
* One user reports that 1,400 sequential requests of a 4 hours timeframe got them to the limit. (Replicated on 2 networks)
- * It has been tested, and 60 seconds of sleep between requests (successful or not) is the correct amount once you reach the limit.
+ * It has been tested, and 60 seconds of sleep between requests (successful or not) appears to be the correct amount once you reach the limit.
* For certain configurations the dependency lib certifi requires the environment variable REQUESTS_CA_BUNDLE to be explicitly set and exported. This variable must contain the path where the ca-certificates are saved or a SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] error is given at runtime.
# Credits
diff --git a/examples/example.py b/examples/example.py
index 0fb84ae..41a49a5 100644
--- a/examples/example.py
+++ b/examples/example.py
@@ -33,3 +33,8 @@ print(top_charts_df.head())
# Get Google Keyword Suggestions
suggestions_dict = pytrend.suggestions(keyword='pizza')
print(suggestions_dict)
+
+# Get Google Realtime Search Trends
+
+realtime_searches = pytrend.realtime_trending_searches(pn='IN')
+print(realtime_searches.head())
diff --git a/pytrends/request.py b/pytrends/request.py
index 5a333e6..6cb9f8d 100644
--- a/pytrends/request.py
+++ b/pytrends/request.py
@@ -30,6 +30,7 @@ class TrendReq(object):
SUGGESTIONS_URL = 'https://trends.google.com/trends/api/autocomplete/'
CATEGORIES_URL = 'https://trends.google.com/trends/api/explore/pickers/category'
TODAY_SEARCHES_URL = 'https://trends.google.com/trends/api/dailytrends'
+ REALTIME_TRENDING_SEARCHES_URL = 'https://trends.google.com/trends/api/realtimetrends'
ERROR_CODES = (500, 502, 504, 429)
def __init__(self, hl='en-US', tz=360, geo='', timeout=(2, 5), proxies='',
@@ -324,8 +325,11 @@ class TrendReq(object):
result_dict = dict()
for request_json in self.related_topics_widget_list:
# ensure we know which keyword we are looking at rather than relying on order
- kw = request_json['request']['restriction'][
- 'complexKeywordsRestriction']['keyword'][0]['value']
+ try:
+ kw = request_json['request']['restriction'][
+ 'complexKeywordsRestriction']['keyword'][0]['value']
+ except KeyError:
+ kw = ''
# convert to string as requests will mangle
related_payload['req'] = json.dumps(request_json['request'])
related_payload['token'] = request_json['token']
@@ -373,8 +377,11 @@ class TrendReq(object):
result_dict = dict()
for request_json in self.related_queries_widget_list:
# ensure we know which keyword we are looking at rather than relying on order
- kw = request_json['request']['restriction'][
- 'complexKeywordsRestriction']['keyword'][0]['value']
+ try:
+ kw = request_json['request']['restriction'][
+ 'complexKeywordsRestriction']['keyword'][0]['value']
+ except KeyError:
+ kw = ''
# convert to string as requests will mangle
related_payload['req'] = json.dumps(request_json['request'])
related_payload['token'] = request_json['token']
@@ -441,6 +448,44 @@ class TrendReq(object):
result_df = pd.concat([result_df, sub_df])
return result_df.iloc[:, -1]
+ def realtime_trending_searches(self, pn='US', cat='all', count =300):
+ """Request data from Google Realtime Search Trends section and returns a dataframe"""
+ # Don't know what some of the params mean here, followed the nodejs library
+ # https://github.com/pat310/google-trends-api/ 's implemenration
+
+
+ #sort: api accepts only 0 as the value, optional parameter
+
+ # ri: number of trending stories IDs returned,
+ # max value of ri supported is 300, based on emperical evidence
+
+ ri_value = 300
+ if count < ri_value:
+ ri_value = count
+
+ # rs : don't know what is does but it's max value is never more than the ri_value based on emperical evidence
+ # max value of ri supported is 200, based on emperical evidence
+ rs_value = 200
+ if count < rs_value:
+ rs_value = count-1
+
+ forms = {'ns': 15, 'geo': pn, 'tz': '300', 'hl': 'en-US', 'cat': cat, 'fi' : '0', 'fs' : '0', 'ri' : ri_value, 'rs' : rs_value, 'sort' : 0}
+ req_json = self._get_data(
+ url=TrendReq.REALTIME_TRENDING_SEARCHES_URL,
+ method=TrendReq.GET_METHOD,
+ trim_chars=5,
+ params=forms
+ )['storySummaries']['trendingStories']
+
+ # parse the returned json
+ wanted_keys = ["entityNames", "title"]
+
+ final_json = [{ key: ts[key] for key in ts.keys() if key in wanted_keys} for ts in req_json ]
+
+ result_df = pd.DataFrame(final_json)
+
+ return result_df
+
def top_charts(self, date, hl='en-US', tz=300, geo='GLOBAL'):
"""Request data from Google's Top Charts section and return a dataframe"""
@@ -501,7 +546,7 @@ class TrendReq(object):
def get_historical_interest(self, keywords, year_start=2018, month_start=1,
day_start=1, hour_start=0, year_end=2018,
month_end=2, day_end=1, hour_end=0, cat=0,
- geo='', gprop='', sleep=0):
+ geo='', gprop='', sleep=0, frequency='hourly'):
"""Gets historical hourly data for interest by chunking requests to 1 week at a time (which is what Google allows)"""
# construct datetime objects - raises ValueError if invalid parameters
@@ -509,8 +554,17 @@ class TrendReq(object):
day_start, hour_start)
end_date = datetime(year_end, month_end, day_end, hour_end)
- # the timeframe has to be in 1 week intervals or Google will reject it
- delta = timedelta(days=7)
+ # Timedeltas:
+ # 7 days for hourly
+ # ~250 days for daily (270 seems to be max but sometimes breaks?)
+ # For weekly can pull any date range so no method required here
+
+ if frequency == 'hourly':
+ delta = timedelta(days=7)
+ elif frequency == 'daily':
+ delta = timedelta(days=250)
+ else:
+ raise(ValueError('Frequency must be hourly or daily'))
df = pd.DataFrame()
@@ -518,10 +572,14 @@ class TrendReq(object):
date_iterator += delta
while True:
- # format date to comply with API call
+ # format date to comply with API call (different for hourly/daily)
- start_date_str = start_date.strftime('%Y-%m-%dT%H')
- date_iterator_str = date_iterator.strftime('%Y-%m-%dT%H')
+ if frequency == 'hourly':
+ start_date_str = start_date.strftime('%Y-%m-%dT%H')
+ date_iterator_str = date_iterator.strftime('%Y-%m-%dT%H')
+ elif frequency == 'daily':
+ start_date_str = start_date.strftime('%Y-%m-%d')
+ date_iterator_str = date_iterator.strftime('%Y-%m-%d')
tf = start_date_str + ' ' + date_iterator_str
@@ -537,10 +595,13 @@ class TrendReq(object):
date_iterator += delta
if (date_iterator > end_date):
- # Run for 7 more days to get remaining data that would have been truncated if we stopped now
- # This is needed because google requires 7 days yet we may end up with a week result less than a full week
- start_date_str = start_date.strftime('%Y-%m-%dT%H')
- date_iterator_str = date_iterator.strftime('%Y-%m-%dT%H')
+ # Run more days to get remaining data that would have been truncated if we stopped now
+ if frequency == 'hourly':
+ start_date_str = start_date.strftime('%Y-%m-%dT%H')
+ date_iterator_str = date_iterator.strftime('%Y-%m-%dT%H')
+ elif frequency == 'daily':
+ start_date_str = start_date.strftime('%Y-%m-%d')
+ date_iterator_str = date_iterator.strftime('%Y-%m-%d')
tf = start_date_str + ' ' + date_iterator_str
| GeneralMills/pytrends | bac0caea18817630e98b503a38e9b445e7b5add1 | diff --git a/pytrends/test_trendReq.py b/pytrends/test_trendReq.py
index 8c3efd3..3e774b9 100644
--- a/pytrends/test_trendReq.py
+++ b/pytrends/test_trendReq.py
@@ -75,6 +75,11 @@ class TestTrendReq(TestCase):
pytrend.build_payload(kw_list=['pizza', 'bagel'])
self.assertIsNotNone(pytrend.trending_searches())
+ def test_realtime_trending_searches(self):
+ pytrend = TrendReq()
+ pytrend.build_payload(kw_list=['pizza', 'bagel'])
+ self.assertIsNotNone(pytrend.realtime_trending_searches(pn='IN'))
+
def test_top_charts(self):
pytrend = TrendReq()
pytrend.build_payload(kw_list=['pizza', 'bagel'])
| Example in readme for extracting topic doesn't work
See [notebook](https://colab.research.google.com/drive/13tOcn6AyUGMBqRXcm6hcsVDT8qpEUOld#scrollTo=d057Oqr7GIE2), which follows the topic example in the readme:
```
from pytrends.request import TrendReq
pytrend = TrendReq(hl='en-US', tz=360)
pytrend.build_payload(kw_list=['"%2Fm%2F025rw19"'],
cat=0, timeframe='today 5-y', geo='', gprop='')
pytrend.interest_over_time()
```
This returns nothing. Replacing `%2F` with `/` works though:
```
pytrend.build_payload(kw_list=['/m/025rw19'],
cat=0, timeframe='today 5-y', geo='', gprop='')
pytrend.interest_over_time()
```
```
/m/025rw19 | isPartial
-- | --
61 | False
59 | False
...
``` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"pytrends/test_trendReq.py::TestTrendReq::test_realtime_trending_searches"
] | [
"pytrends/test_trendReq.py::TestTrendReq::test__get_data",
"pytrends/test_trendReq.py::TestTrendReq::test__tokens",
"pytrends/test_trendReq.py::TestTrendReq::test_build_payload",
"pytrends/test_trendReq.py::TestTrendReq::test_interest_by_region",
"pytrends/test_trendReq.py::TestTrendReq::test_interest_over_time",
"pytrends/test_trendReq.py::TestTrendReq::test_interest_over_time_bad_gprop",
"pytrends/test_trendReq.py::TestTrendReq::test_interest_over_time_froogle",
"pytrends/test_trendReq.py::TestTrendReq::test_interest_over_time_images",
"pytrends/test_trendReq.py::TestTrendReq::test_interest_over_time_news",
"pytrends/test_trendReq.py::TestTrendReq::test_interest_over_time_youtube",
"pytrends/test_trendReq.py::TestTrendReq::test_ispartial_dtype",
"pytrends/test_trendReq.py::TestTrendReq::test_ispartial_dtype_timeframe_all",
"pytrends/test_trendReq.py::TestTrendReq::test_related_queries",
"pytrends/test_trendReq.py::TestTrendReq::test_related_topics",
"pytrends/test_trendReq.py::TestTrendReq::test_suggestions",
"pytrends/test_trendReq.py::TestTrendReq::test_top_charts",
"pytrends/test_trendReq.py::TestTrendReq::test_trending_searches"
] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2021-06-02T05:08:47Z" | apache-2.0 |
|
GeneralMills__pytrends-509 | diff --git a/pytrends/request.py b/pytrends/request.py
index 6cb9f8d..446cf41 100644
--- a/pytrends/request.py
+++ b/pytrends/request.py
@@ -299,13 +299,17 @@ class TrendReq(object):
return df
# rename the column with the search keyword
- df = df[['geoName', 'geoCode', 'value']].set_index(
- ['geoName']).sort_index()
+ geo_column = 'geoCode' if 'geoCode' in df.columns else 'coordinates'
+ columns = ['geoName', geo_column, 'value']
+ df = df[columns].set_index(['geoName']).sort_index()
# split list columns into separate ones, remove brackets and split on comma
result_df = df['value'].apply(lambda x: pd.Series(
str(x).replace('[', '').replace(']', '').split(',')))
if inc_geo_code:
- result_df['geoCode'] = df['geoCode']
+ if geo_column in df.columns:
+ result_df[geo_column] = df[geo_column]
+ else:
+ print('Could not find geo_code column; Skipping')
# rename each column with its search term
for idx, kw in enumerate(self.kw_list):
| GeneralMills/pytrends | e1eec7a4822f1a2005a2ab12236c411a1b0ca3c7 | diff --git a/pytrends/test_trendReq.py b/pytrends/test_trendReq.py
index 3e774b9..6a9f178 100644
--- a/pytrends/test_trendReq.py
+++ b/pytrends/test_trendReq.py
@@ -60,6 +60,11 @@ class TestTrendReq(TestCase):
pytrend.build_payload(kw_list=['pizza', 'bagel'])
self.assertIsNotNone(pytrend.interest_by_region())
+ def test_interest_by_region_city_resolution(self):
+ pytrend = TrendReq()
+ pytrend.build_payload(kw_list=['pizza', 'bagel'])
+ self.assertIsNotNone(pytrend.interest_by_region(resolution='CITY'))
+
def test_related_topics(self):
pytrend = TrendReq()
pytrend.build_payload(kw_list=['pizza', 'bagel'])
| "['geoCode'] not in index" when request CITY LEVEL interest_by_region Google trends
Hi, the pytrends API developers and maintainers,
Thank you for developing this great API and I'm now just starting to use it for my research.
I recently ran into a key error when I tried to get Google treands data on city level.
My code is as follows:
import pandas as pd
from pytrends.request import TrendReq
pytrend = TrendReq()
kw_list=['Coronavirus']
pytrend.build_payload(kw_list, timeframe='today 3-m', geo='US', gprop='')
pytrend.interest_by_region(resolution='CITY',inc_low_vol=True, inc_geo_code=False)
**This is the error message.**
KeyError Traceback (most recent call last)
<ipython-input-19-91b520252342> in <module>
----> 1 pytrend.interest_by_region(resolution='CITY',inc_low_vol=False, inc_geo_code=False)
~/anaconda3/envs/pytorch_env/lib/python3.6/site-packages/pytrends/request.py in interest_by_region(self, resolution, inc_low_vol, inc_geo_code)
282
283 # rename the column with the search keyword
--> 284 df = df[['geoName', 'geoCode', 'value']].set_index(
285 ['geoName']).sort_index()
286 # split list columns into seperate ones, remove brackets and split on comma
~/anaconda3/envs/pytorch_env/lib/python3.6/site-packages/pandas/core/frame.py in __getitem__(self, key)
2999 if is_iterator(key):
3000 key = list(key)
-> 3001 indexer = self.loc._convert_to_indexer(key, axis=1, raise_missing=True)
3002
3003 # take() does not accept boolean indexers
~/anaconda3/envs/pytorch_env/lib/python3.6/site-packages/pandas/core/indexing.py in _convert_to_indexer(self, obj, axis, is_setter, raise_missing)
1283 # When setting, missing keys are not allowed, even with .loc:
1284 kwargs = {"raise_missing": True if is_setter else raise_missing}
-> 1285 return self._get_listlike_indexer(obj, axis, **kwargs)[1]
1286 else:
1287 try:
~/anaconda3/envs/pytorch_env/lib/python3.6/site-packages/pandas/core/indexing.py in _get_listlike_indexer(self, key, axis, raise_missing)
1090
1091 self._validate_read_indexer(
-> 1092 keyarr, indexer, o._get_axis_number(axis), raise_missing=raise_missing
1093 )
1094 return keyarr, indexer
~/anaconda3/envs/pytorch_env/lib/python3.6/site-packages/pandas/core/indexing.py in _validate_read_indexer(self, key, indexer, axis, raise_missing)
1183 if not (self.name == "loc" and not raise_missing):
1184 not_found = list(set(key) - set(ax))
-> 1185 raise KeyError("{} not in index".format(not_found))
1186
1187 # we skip the warning on Categorical/Interval
KeyError: "['geoCode'] not in index"
I actually tried all API methods, and they worked very well, except for this one.
Thank you for your time!
Best,
Han
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"pytrends/test_trendReq.py::TestTrendReq::test_interest_by_region_city_resolution"
] | [
"pytrends/test_trendReq.py::TestTrendReq::test__get_data",
"pytrends/test_trendReq.py::TestTrendReq::test__tokens",
"pytrends/test_trendReq.py::TestTrendReq::test_build_payload",
"pytrends/test_trendReq.py::TestTrendReq::test_interest_by_region",
"pytrends/test_trendReq.py::TestTrendReq::test_interest_over_time",
"pytrends/test_trendReq.py::TestTrendReq::test_interest_over_time_bad_gprop",
"pytrends/test_trendReq.py::TestTrendReq::test_interest_over_time_froogle",
"pytrends/test_trendReq.py::TestTrendReq::test_interest_over_time_images",
"pytrends/test_trendReq.py::TestTrendReq::test_interest_over_time_news",
"pytrends/test_trendReq.py::TestTrendReq::test_interest_over_time_youtube",
"pytrends/test_trendReq.py::TestTrendReq::test_ispartial_dtype",
"pytrends/test_trendReq.py::TestTrendReq::test_ispartial_dtype_timeframe_all",
"pytrends/test_trendReq.py::TestTrendReq::test_realtime_trending_searches",
"pytrends/test_trendReq.py::TestTrendReq::test_related_queries",
"pytrends/test_trendReq.py::TestTrendReq::test_related_topics",
"pytrends/test_trendReq.py::TestTrendReq::test_suggestions",
"pytrends/test_trendReq.py::TestTrendReq::test_top_charts",
"pytrends/test_trendReq.py::TestTrendReq::test_trending_searches"
] | {
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
} | "2022-02-18T20:36:49Z" | apache-2.0 |
|
GeneralMills__pytrends-518 | diff --git a/pytrends/request.py b/pytrends/request.py
index 446cf41..4644102 100644
--- a/pytrends/request.py
+++ b/pytrends/request.py
@@ -428,8 +428,7 @@ class TrendReq(object):
# forms = {'ajax': 1, 'pn': pn, 'htd': '', 'htv': 'l'}
req_json = self._get_data(
url=TrendReq.TRENDING_SEARCHES_URL,
- method=TrendReq.GET_METHOD,
- **self.requests_args
+ method=TrendReq.GET_METHOD
)[pn]
result_df = pd.DataFrame(req_json)
return result_df
@@ -441,8 +440,7 @@ class TrendReq(object):
url=TrendReq.TODAY_SEARCHES_URL,
method=TrendReq.GET_METHOD,
trim_chars=5,
- params=forms,
- **self.requests_args
+ params=forms
)['default']['trendingSearchesDays'][0]['trendingSearches']
result_df = pd.DataFrame()
# parse the returned json
@@ -508,8 +506,7 @@ class TrendReq(object):
url=TrendReq.TOP_CHARTS_URL,
method=TrendReq.GET_METHOD,
trim_chars=5,
- params=chart_payload,
- **self.requests_args
+ params=chart_payload
)
try:
df = pd.DataFrame(req_json['topCharts'][0]['listItems'])
@@ -528,8 +525,7 @@ class TrendReq(object):
url=TrendReq.SUGGESTIONS_URL + kw_param,
params=parameters,
method=TrendReq.GET_METHOD,
- trim_chars=5,
- **self.requests_args
+ trim_chars=5
)['default']['topics']
return req_json
@@ -542,8 +538,7 @@ class TrendReq(object):
url=TrendReq.CATEGORIES_URL,
params=params,
method=TrendReq.GET_METHOD,
- trim_chars=5,
- **self.requests_args
+ trim_chars=5
)
return req_json
@@ -562,7 +557,7 @@ class TrendReq(object):
# 7 days for hourly
# ~250 days for daily (270 seems to be max but sometimes breaks?)
# For weekly can pull any date range so no method required here
-
+
if frequency == 'hourly':
delta = timedelta(days=7)
elif frequency == 'daily':
| GeneralMills/pytrends | 0e887b8510c3023fb57796cb253fef03d688b2f7 | diff --git a/pytrends/test_trendReq.py b/pytrends/test_trendReq.py
index 6a9f178..ee2253c 100644
--- a/pytrends/test_trendReq.py
+++ b/pytrends/test_trendReq.py
@@ -85,6 +85,15 @@ class TestTrendReq(TestCase):
pytrend.build_payload(kw_list=['pizza', 'bagel'])
self.assertIsNotNone(pytrend.realtime_trending_searches(pn='IN'))
+ def test_request_args_passing(self):
+ requests_args = {'headers': {
+ 'User-Agent': 'pytrends',
+ }}
+ pytrend = TrendReq(requests_args=requests_args)
+ pytrend.build_payload(kw_list=['bananas'])
+ self.assertIsNotNone(pytrend.suggestions('bananas'))
+ self.assertIsNotNone(pytrend.trending_searches())
+
def test_top_charts(self):
pytrend = TrendReq()
pytrend.build_payload(kw_list=['pizza', 'bagel'])
| Bug on "suggestions" when "requests_args" is not empty
If requests_args is not empty, then in line 453 of the requests.py, the "self.requests_args" is included as kwargs and line 126 of the _get_data method includes it again. So it causes an error. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"pytrends/test_trendReq.py::TestTrendReq::test_interest_over_time_news",
"pytrends/test_trendReq.py::TestTrendReq::test_interest_over_time_youtube",
"pytrends/test_trendReq.py::TestTrendReq::test_ispartial_dtype",
"pytrends/test_trendReq.py::TestTrendReq::test_ispartial_dtype_timeframe_all",
"pytrends/test_trendReq.py::TestTrendReq::test_realtime_trending_searches",
"pytrends/test_trendReq.py::TestTrendReq::test_related_queries",
"pytrends/test_trendReq.py::TestTrendReq::test_request_args_passing"
] | [
"pytrends/test_trendReq.py::TestTrendReq::test__get_data",
"pytrends/test_trendReq.py::TestTrendReq::test__tokens",
"pytrends/test_trendReq.py::TestTrendReq::test_build_payload",
"pytrends/test_trendReq.py::TestTrendReq::test_interest_over_time_bad_gprop",
"pytrends/test_trendReq.py::TestTrendReq::test_interest_over_time_images",
"pytrends/test_trendReq.py::TestTrendReq::test_related_topics",
"pytrends/test_trendReq.py::TestTrendReq::test_suggestions",
"pytrends/test_trendReq.py::TestTrendReq::test_top_charts",
"pytrends/test_trendReq.py::TestTrendReq::test_trending_searches"
] | {
"failed_lite_validators": [
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2022-06-09T11:10:03Z" | apache-2.0 |
|
GreenBuildingRegistry__usaddress-scourgify-12 | diff --git a/scourgify/normalize.py b/scourgify/normalize.py
index 4270b68..8827088 100644
--- a/scourgify/normalize.py
+++ b/scourgify/normalize.py
@@ -535,7 +535,8 @@ def normalize_occupancy_type(parsed_addr, default=None):
default = default if default is not None else 'UNIT'
occupancy_type_label = 'OccupancyType'
occupancy_type = parsed_addr.pop(occupancy_type_label, None)
- occupancy_type_abbr = OCCUPANCY_TYPE_ABBREVIATIONS.get(occupancy_type)
+ occupancy_type_abbr = occupancy_type if occupancy_type in OCCUPANCY_TYPE_ABBREVIATIONS.values() \
+ else OCCUPANCY_TYPE_ABBREVIATIONS.get(occupancy_type)
occupancy_id = parsed_addr.get('OccupancyIdentifier')
if ((occupancy_id and not occupancy_id.startswith('#'))
and not occupancy_type_abbr):
| GreenBuildingRegistry/usaddress-scourgify | 29912c8c00bbb3d5c899fb64772ecf07d9020b1e | diff --git a/scourgify/tests/test_address_normalization.py b/scourgify/tests/test_address_normalization.py
index ac8ea09..66a9c42 100644
--- a/scourgify/tests/test_address_normalization.py
+++ b/scourgify/tests/test_address_normalization.py
@@ -263,6 +263,34 @@ class TestAddressNormalization(TestCase):
result = normalize_addr_dict(hashtag_unit, addr_map=dict_map)
self.assertDictEqual(expected, result)
+ expected = dict(
+ address_line_1='123 NOWHERE ST',
+ address_line_2='APT 345',
+ city='BORING',
+ state='OR',
+ postal_code='97009'
+ )
+
+ abbreviation = dict(
+ address1='123 Nowhere St',
+ address2='Apt 345',
+ city='Boring',
+ state='OR',
+ zip='97009'
+ )
+ result = normalize_addr_dict(abbreviation, addr_map=dict_map)
+ self.assertDictEqual(expected, result)
+
+ full_name = dict(
+ address1='123 Nowhere St',
+ address2='Apartment 345',
+ city='Boring',
+ state='OR',
+ zip='97009'
+ )
+ result = normalize_addr_dict(full_name, addr_map=dict_map)
+ self.assertDictEqual(expected, result)
+
class TestAddressNormalizationUtils(TestCase):
"""Unit tests for scourgify utils"""
| Valid occupancy types replaced by 'UNIT'
HI there, I appreciate your work on normalizing the US Address library!
I notice the following issue:
```
>>> from scourgify import normalize_address_record
>>> normalize_address_record('12345 Somewhere Street Apt 1, Town, MA 12345')
{'address_line_1': '12345 SOMEWHERE ST', 'address_line_2': 'UNIT 1', 'city': 'TOWN', 'state': 'MA', 'postal_code': '12345'}
```
I believe it has to do with the following bit of code in `scourgify.normalize.normalize_occupancy_type`:
```
default = default if default is not None else 'UNIT'
occupancy_type_label = 'OccupancyType'
occupancy_type = parsed_addr.pop(occupancy_type_label, None)
occupancy_type_abbr = OCCUPANCY_TYPE_ABBREVIATIONS.get(occupancy_type)
occupancy_id = parsed_addr.get('OccupancyIdentifier')
if ((occupancy_id and not occupancy_id.startswith('#'))
and not occupancy_type_abbr):
occupancy_type_abbr = default
...
```
When I step debug, the returned `occupancy_type` is `'APT'`. However, the `occupancy_type_abbr` is set as `None` considering the `OCCUPANCY_TYPE_ABBREVIATIONS` are currently in the format `<full_name> -> <abbreviation>`
I suggest the following fix:
```
if occupancy_type in OCCUPANCY_TYPE_ABBREVIATIONS.values():
occupancy_type_abbr = occupancy_type
else:
occupancy_type_abbr = OCCUPANCY_TYPE_ABBREVIATIONS.get(occupancy_type)
```
Then you can cover both cases.
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"scourgify/tests/test_address_normalization.py::TestAddressNormalization::test_normalize_occupancies"
] | [
"scourgify/tests/test_address_normalization.py::TestAddressNormalization::test_normalize_addr_dict",
"scourgify/tests/test_address_normalization.py::TestAddressNormalization::test_normalize_addr_str",
"scourgify/tests/test_address_normalization.py::TestAddressNormalization::test_normalize_address_record",
"scourgify/tests/test_address_normalization.py::TestAddressNormalization::test_parse_address_string",
"scourgify/tests/test_address_normalization.py::TestAddressNormalizationUtils::test_address_normalization_error",
"scourgify/tests/test_address_normalization.py::TestAddressNormalizationUtils::test_clean_ambiguous_street_types",
"scourgify/tests/test_address_normalization.py::TestAddressNormalizationUtils::test_clean_period_char",
"scourgify/tests/test_address_normalization.py::TestAddressNormalizationUtils::test_get_addr_line_str",
"scourgify/tests/test_address_normalization.py::TestAddressNormalizationUtils::test_get_geocoder_normalized_addr",
"scourgify/tests/test_address_normalization.py::TestAddressNormalizationUtils::test_get_norm_line_segment",
"scourgify/tests/test_address_normalization.py::TestAddressNormalizationUtils::test_get_ordinal_indicator",
"scourgify/tests/test_address_normalization.py::TestAddressNormalizationUtils::test_get_parsed_values",
"scourgify/tests/test_address_normalization.py::TestAddressNormalizationUtils::test_normalize_directionals",
"scourgify/tests/test_address_normalization.py::TestAddressNormalizationUtils::test_normalize_numbered_streets",
"scourgify/tests/test_address_normalization.py::TestAddressNormalizationUtils::test_normalize_occupancy_type",
"scourgify/tests/test_address_normalization.py::TestAddressNormalizationUtils::test_normalize_state",
"scourgify/tests/test_address_normalization.py::TestAddressNormalizationUtils::test_normalize_street_types",
"scourgify/tests/test_address_normalization.py::TestAddressNormalizationUtils::test_post_clean_addr_str",
"scourgify/tests/test_address_normalization.py::TestAddressNormalizationUtils::test_pre_clean_addr_str",
"scourgify/tests/test_address_normalization.py::TestAddressNormalizationUtils::test_validate_address",
"scourgify/tests/test_address_normalization.py::TestAddressNormalizationUtils::test_validate_parens_group_parsed",
"scourgify/tests/test_address_normalization.py::TestAddressNormalizationUtils::test_validate_postal_code"
] | {
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
} | "2020-05-14T16:25:16Z" | mit |
|
HBehrens__fixup_shaper_svg-3 | diff --git a/fixup_shaper_svg.py b/fixup_shaper_svg.py
index 2d304c5..0436b9c 100644
--- a/fixup_shaper_svg.py
+++ b/fixup_shaper_svg.py
@@ -61,13 +61,14 @@ def fixup_svg(infile, outfile):
svg = xml.etree.ElementTree.parse(infile)
for elem in svg.iter():
fixup_element(elem)
- svg.write(outfile, encoding='unicode', xml_declaration=True)
+ encoding = 'unicode' if outfile == sys.stdout else 'utf-8'
+ svg.write(outfile, encoding=encoding, xml_declaration=True)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('infile', nargs='?', type=argparse.FileType('r'), default=sys.stdin)
- parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'), default=sys.stdout)
+ parser.add_argument('outfile', nargs='?', type=argparse.FileType('wb'), default=sys.stdout)
args = parser.parse_args()
fixup_svg(infile=args.infile, outfile=args.outfile)
| HBehrens/fixup_shaper_svg | f28e93229db60d18bf6520e900b0ab84da5b6da5 | diff --git a/fixup_shaper_svg_tests.py b/fixup_shaper_svg_tests.py
index 362aa80..9e91696 100644
--- a/fixup_shaper_svg_tests.py
+++ b/fixup_shaper_svg_tests.py
@@ -1,6 +1,7 @@
import unittest
+import io
-from fixup_shaper_svg import length_value_without_spaces, style_attribute_without_fill_rule
+from fixup_shaper_svg import fixup_svg, length_value_without_spaces, style_attribute_without_fill_rule
class LengthWithUnit(unittest.TestCase):
@@ -42,5 +43,16 @@ class StyleWithUnsupportedAttributes(unittest.TestCase):
style_attribute_without_fill_rule(" fill-rule: evenodd; "))
+class XmlFileEncoding(unittest.TestCase):
+
+ def test_does_force_utf8(self):
+ infile = io.StringIO("""<?xml version='1.0' encoding='cp1252'?>
+<svg xmlns="http://www.w3.org/2000/svg"/>""")
+ with io.BytesIO() as outfile:
+ fixup_svg(infile, outfile)
+ self.assertEqual(b'<?xml version=\'1.0\' encoding=\'utf-8\'?>\n'
+ b'<svg xmlns="http://www.w3.org/2000/svg" />', outfile.getvalue())
+
+
if __name__ == '__main__':
unittest.main()
| Improvement Request: Modification to get SVG preview working on the Origin
The current script (fixup_shaper_svg.py) is working as such.
Converted SVG files can be used and inserted on Origin.
However the SVG image preview is not working.
Reason for this is that in the output file the following information will be added:
encoding='cp1252'
When removing the encoding statement the file can be used on the Origin and the SVG preview is also working.
Would be great if someone could update the python script to remove "encoding='cp1252'" to finally get preview working.
Unfortunately i do not have enough python skills to do this on my own. ;-) | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"fixup_shaper_svg_tests.py::XmlFileEncoding::test_does_force_utf8"
] | [
"fixup_shaper_svg_tests.py::LengthWithUnit::test_ignore_invalid_numbers",
"fixup_shaper_svg_tests.py::LengthWithUnit::test_ignores_complex_attributes",
"fixup_shaper_svg_tests.py::LengthWithUnit::test_number_formats",
"fixup_shaper_svg_tests.py::LengthWithUnit::test_spacing",
"fixup_shaper_svg_tests.py::StyleWithUnsupportedAttributes::test_removes_fill_rule"
] | {
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
} | "2024-04-21T16:45:13Z" | mit |
|
HDembinski__jacobi-16 | diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index d7ba3ca..d787190 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -47,5 +47,12 @@ repos:
rev: 'v0.971'
hooks:
- id: mypy
- args: [--allow-redefinition, --ignore-missing-imports, src]
+ args: [src]
pass_filenames: false
+
+# doc string checking
+- repo: https://github.com/PyCQA/pydocstyle
+ rev: 6.1.1
+ hooks:
+ - id: pydocstyle
+ files: src/jacobi/.*\.py
diff --git a/pyproject.toml b/pyproject.toml
index 6a2a1ea..c12514f 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -7,3 +7,7 @@ build-backend = "setuptools.build_meta"
[tool.setuptools_scm]
write_to = "src/jacobi/_version.py"
+
+[tool.mypy]
+ignore_missing_imports = true
+allow_redefinition = true
diff --git a/src/jacobi/__init__.py b/src/jacobi/__init__.py
index ee09996..be87199 100644
--- a/src/jacobi/__init__.py
+++ b/src/jacobi/__init__.py
@@ -1,7 +1,4 @@
-"""Jacobi
-
-Fast numerical derivatives for real analytic functions with arbitrary round-off error.
-"""
+"""Fast numerical derivatives for analytic functions with arbitrary round-off error."""
from .core import jacobi, propagate # noqa
from ._version import version as __version__ # noqa
diff --git a/src/jacobi/core.py b/src/jacobi/core.py
index 5e6ead8..1f4fe65 100644
--- a/src/jacobi/core.py
+++ b/src/jacobi/core.py
@@ -1,3 +1,5 @@
+"""Core functions of jacobi."""
+
import numpy as np
import typing as _tp
@@ -74,15 +76,15 @@ def _first(method, f0, f, x, i, h, args):
def jacobi(
fn: _tp.Callable,
- x: _tp.Union[int, float, _tp.Sequence],
+ x: _tp.Union[float, _Indexable[float]],
*args,
- method: _tp.Optional[int] = None,
- mask: _tp.Optional[np.ndarray] = None,
+ method: int = None,
+ mask: np.ndarray = None,
rtol: float = 0,
maxiter: int = 10,
maxgrad: int = 3,
- step: _tp.Optional[_tp.Tuple[float, float]] = None,
- diagnostic: _tp.Optional[dict] = None,
+ step: _tp.Tuple[float, float] = None,
+ diagnostic: dict = None,
):
"""
Return first derivative and its error estimate.
@@ -240,6 +242,7 @@ def propagate(
fn: _tp.Callable,
x: _tp.Union[float, _Indexable[float]],
cov: _tp.Union[float, _Indexable[float], _Indexable[_Indexable[float]]],
+ *args,
**kwargs,
) -> _tp.Tuple[np.ndarray, np.ndarray]:
"""
@@ -252,14 +255,21 @@ def propagate(
Parameters
----------
fn: callable
- Function that computes y = fn(x). x and y are each allowed to be scalars or
- one-dimensional arrays.
+ Function that computes r = fn(x, [y, ...]). The arguments of the function are
+ each allowed to be scalars or one-dimensional arrays. If the function accepts
+ several arguments, their uncertainties are treated as uncorrelated.
+ Functions that accept several correlated arguments must be wrapped, see examples.
+ The result of the function may be a scalar or a one-dimensional array with a
+ different lenth as the input.
x: float or array-like with shape (N,)
- Input vector.
+ Input vector. An array-like is converted before passing it to the callable.
cov: float or array-like with shape (N,) or shape(N, N)
Covariance matrix of input vector. If the array is one-dimensional, it is
interpreted as the diagonal of a covariance matrix with zero off-diagonal
elements.
+ *args:
+ If the function accepts several arguments that are mutually independent, these
+ is possible to pass those values and covariance matrices pairwise, see examples.
**kwargs:
Extra arguments are passed to :func:`jacobi`.
@@ -270,14 +280,93 @@ def propagate(
ycov is the propagated covariance matrix.
If ycov is a matrix, unless y is a number. In that case, ycov is also
reduced to a number.
+
+ Examples
+ --------
+ General error propagation maps input vectors to output vectors::
+
+ def fn(x):
+ return x ** 2 + 1
+
+ x = [1, 2]
+ xcov = [[3, 1],
+ [1, 4]]
+
+ y, ycov = propagate(fn, x, xcov)
+
+ If the function accepts several arguments, their uncertainties are treated as
+ uncorrelated::
+
+ def fn(x, y):
+ return x + y
+
+ x = 1
+ y = 2
+ xcov = 2
+ ycov = 3
+
+ z, zcov = propagate(fn, x, xcov, y, ycov)
+
+ Functions that accept several correlated arguments must be wrapped::
+
+ def fn(x, y):
+ return x + y
+
+ x = 1
+ y = 2
+ sigma_x = 3
+ sigma_y = 4
+ rho_xy = 0.5
+
+ r = [x, y]
+ cov_xy = rho_xy * sigma_x * sigma_y
+ rcov = [[sigma_x ** 2, cov_xy], [cov_xy, sigma_y ** 2]]
+
+ def fn_wrapped(r):
+ return fn(r[0], r[1])
+
+ z, zcov = propagate(fn_wrapped, r, rcov)
+
+ See Also
+ --------
+ jacobi
"""
+ if args:
+ if len(args) % 2 != 0:
+ raise ValueError("number of extra positional arguments must be even")
+
+ x_parts: _tp.List[np.ndarray] = [
+ np.atleast_1d(_) for _ in ([x] + [a for a in args[::2]])
+ ]
+ cov_parts: _tp.List[np.ndarray] = [
+ np.atleast_1d(_) for _ in ([cov] + [a for a in args[1::2]])
+ ]
+ slices = []
+ i = 0
+ for xi in x_parts:
+ n = len(xi)
+ slices.append(slice(i, i + n))
+ i += n
+
+ r = np.concatenate(x_parts)
+ n = len(r)
+ rcov = np.zeros((n, n))
+ for sl, covi in zip(slices, cov_parts):
+ rcov[sl, sl] = np.diag(covi) if covi.ndim == 1 else covi
+
+ def wrapped(r):
+ args = [r[sl] for sl in slices]
+ return fn(*args)
+
+ return propagate(wrapped, r, rcov)
+
x = np.array(x)
y = fn(x)
jac = jacobi(fn, x, **kwargs)[0]
x_nd = np.ndim(x)
y_nd = np.ndim(y)
- x_len = len(x) if x_nd == 1 else 1
+ x_len = len(x) if x_nd == 1 else 1 # type: ignore
y_len = len(y) if y_nd == 1 else 1
jac_nd = np.ndim(jac)
| HDembinski/jacobi | 9b3811bb96b43f2a28f0d2c05ef570214ce50bf1 | diff --git a/test/test_propagate.py b/test/test_propagate.py
index 4975c5e..3f2e139 100644
--- a/test/test_propagate.py
+++ b/test/test_propagate.py
@@ -75,3 +75,66 @@ def test_11():
else:
xcov2 = xcov
assert_allclose(ycov, np.linalg.multi_dot([jac, xcov2, jac.T]))
+
+
[email protected]("ndim", (1, 2))
+def test_cov_1d_2d(ndim):
+ def fn(x):
+ return x
+
+ x = [1, 2]
+ xcov_1d = [3, 4]
+ xcov_2d = np.diag(xcov_1d)
+
+ y, ycov = propagate(fn, x, xcov_1d if ndim == 1 else xcov_2d)
+
+ assert np.ndim(ycov) == 2
+
+ assert_allclose(y, x)
+ assert_allclose(ycov, xcov_2d)
+
+
+def test_two_arguments_1():
+ def fn1(x, y):
+ return (x - y) / (x + y)
+
+ x = 1
+ xcov = 2
+ y = 3
+ ycov = 4
+
+ z1, zcov1 = propagate(fn1, x, xcov, y, ycov)
+
+ def fn2(r):
+ return fn1(r[0], r[1])
+
+ r = [x, y]
+ rcov = np.diag([xcov, ycov])
+
+ z2, zcov2 = propagate(fn2, r, rcov)
+
+ assert_allclose(z2, z1)
+ assert_allclose(zcov2, zcov1)
+
+
+def test_two_arguments_2():
+ def fn1(x, y):
+ return np.concatenate([x, np.atleast_1d(y)])
+
+ x = [1, 2]
+ xcov = [2, 3]
+ y = 3
+ ycov = 4
+
+ z1, zcov1 = propagate(fn1, x, xcov, y, ycov)
+
+ def fn2(r):
+ return fn1(r[:2], r[2])
+
+ r = [*x, y]
+ rcov = np.diag([*xcov, ycov])
+
+ z2, zcov2 = propagate(fn2, r, rcov)
+
+ assert_allclose(z2, z1)
+ assert_allclose(zcov2, zcov1)
| propagate: support functions with multiple independent arguments
Often, one has a function that takes independent arguments. Propagating this currently is a bit cumbersome, one has to combine the arguments into a vector and the covariances into joint block covariance matrix. `propagate` could be made more flexible to make this easier. I am not sure how the signature should look like, though.
```py
def func(a, b):
....
a = [...]
b = [...]
cov_a = [...]
cov_b = [...]
# option 1
propagate(func, a, b, cov_a, cov_b)
# option 2
propagate(func, a, cov_a, b, cov_b)
# option 3
propagate(func, (a, cov_a), (b, cov_b))
```
Options 1 and 2 are natural extensions of the current calling convention, just the order of values and covariances differ. I am not sure what is most natural. I am leaning towards option 2.
Option 3 requires more typing and is not really much safer. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/test_propagate.py::test_two_arguments_1",
"test/test_propagate.py::test_two_arguments_2"
] | [
"test/test_propagate.py::test_00",
"test/test_propagate.py::test_01",
"test/test_propagate.py::test_10",
"test/test_propagate.py::test_11",
"test/test_propagate.py::test_cov_1d_2d[1]",
"test/test_propagate.py::test_cov_1d_2d[2]"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2022-08-14T11:00:32Z" | mit |
|
HEPCloud__decisionengine-391 | diff --git a/package/rpm/install_section b/package/rpm/install_section
index 82c2966f..aa7d0ad1 100644
--- a/package/rpm/install_section
+++ b/package/rpm/install_section
@@ -28,3 +28,7 @@ echo "%dir %attr(0750,decisionengine,decisionengine) %{_sysconfdir}/decisionengi
mkdir -p %{buildroot}/%{_sysconfdir}/sysconfig
touch %{buildroot}/%{_sysconfdir}/sysconfig/decisionengine
echo "%attr(0640,root,decisionengine) %config(noreplace) %{_sysconfdir}/sysconfig/decisionengine" >> INSTALLED_FILES
+
+mkdir -p %{buildroot}/%{_defaultdocdir}/%{name}/datasources/
+install -m 0644 src/decisionengine/framework/dataspace/datasources/postgresql.sql %{buildroot}/%{_defaultdocdir}/%{name}/datasources/postgresql.sql
+echo "%doc %{_defaultdocdir}/%{name}" >> INSTALLED_FILES
diff --git a/src/decisionengine/framework/dataspace/datablock.py b/src/decisionengine/framework/dataspace/datablock.py
index ccfcca83..7d071fd4 100644
--- a/src/decisionengine/framework/dataspace/datablock.py
+++ b/src/decisionengine/framework/dataspace/datablock.py
@@ -445,7 +445,6 @@ class DataBlock:
Check if the dataproduct for a given key or any key is expired
"""
self.logger.info('datablock is checking for expired dataproducts')
- pass
def mark_expired(self, expiration_time):
"""
@@ -453,4 +452,3 @@ class DataBlock:
and mark it as expired if expiration_time <= current time
"""
self.logger.info('datablock is marking expired dataproducts')
- pass
diff --git a/src/decisionengine/framework/dataspace/datasources/postgresql.py b/src/decisionengine/framework/dataspace/datasources/postgresql.py
index 097a72ff..c06e4eb5 100644
--- a/src/decisionengine/framework/dataspace/datasources/postgresql.py
+++ b/src/decisionengine/framework/dataspace/datasources/postgresql.py
@@ -183,7 +183,6 @@ class Postgresql(ds.DataSource):
SELECT_TASKMANAGERS += " AND "
else:
SELECT_TASKMANAGERS += " WHERE "
- have_where = True
SELECT_TASKMANAGERS += " tm.datestamp <= '" + end_time + "'"
try:
return self._select_dictresult(SELECT_TASKMANAGERS +
@@ -470,10 +469,6 @@ class Postgresql(ds.DataSource):
except psycopg2.Error: # pragma: no cover
pass
raise
- except psycopg2.Error:
- if db:
- db.rollback()
- raise
finally:
list([x.close if x else None for x in (cursor, db)])
@@ -497,10 +492,6 @@ class Postgresql(ds.DataSource):
except psycopg2.Error: # pragma: no cover
pass
raise
- except psycopg2.Error:
- if db:
- db.rollback()
- raise
finally:
list([x.close if x else None for x in (cursor, db)])
diff --git a/src/decisionengine/framework/logicengine/Rule.py b/src/decisionengine/framework/logicengine/Rule.py
index 39923625..87282717 100644
--- a/src/decisionengine/framework/logicengine/Rule.py
+++ b/src/decisionengine/framework/logicengine/Rule.py
@@ -23,8 +23,8 @@ class Rule:
return self.expr.evaluate(evaluated_facts)
def __str__(self): # pragma: no cover
- return f"name: {self.name}\n"
- f"expression: '{self.expr}'\n"
- f"actions: {self.actions}\n"
- f"false_actions: {self.false_actions}\n"
- f"facts: {self.new_facts}"
+ return (f"name: {self.name}\n"
+ f"expression: '{self.expr}'\n"
+ f"actions: {self.actions}\n"
+ f"false_actions: {self.false_actions}\n"
+ f"facts: {self.new_facts}")
diff --git a/src/decisionengine/framework/modules/SourceProxy.py b/src/decisionengine/framework/modules/SourceProxy.py
index 5ed09edb..09030431 100644
--- a/src/decisionengine/framework/modules/SourceProxy.py
+++ b/src/decisionengine/framework/modules/SourceProxy.py
@@ -11,6 +11,7 @@ import decisionengine.framework.dataspace.datablock as datablock
import decisionengine.framework.dataspace.dataspace as dataspace
from decisionengine.framework.modules import Source
from decisionengine.framework.modules.Source import Parameter
+from decisionengine.framework.modules.translate_product_name import translate_all
RETRIES = 10
RETRY_TO = 60
@@ -27,7 +28,7 @@ class SourceProxy(Source.Source):
raise RuntimeError(
'SourceProxy misconfigured. Must have {} defined'.format(must_have))
self.source_channel = config['channel_name']
- self.data_keys = config['Dataproducts']
+ self.data_keys = translate_all(config['Dataproducts'])
self.retries = config.get('retries', RETRIES)
self.retry_to = config.get('retry_timeout', RETRY_TO)
self.logger = logging.getLogger()
@@ -35,7 +36,7 @@ class SourceProxy(Source.Source):
# Hack - it is possible for a subclass to declare @produces,
# in which case, we do not want to override that.
if not self._produces:
- self._produces = {k: Any for k in self.data_keys}
+ self._produces = {new_name: Any for new_name in self.data_keys.values()}
def post_create(self, global_config):
self.dataspace = dataspace.DataSpace(global_config)
@@ -85,18 +86,12 @@ class SourceProxy(Source.Source):
filled_keys = []
for _ in range(self.retries):
if len(filled_keys) != len(self.data_keys):
- for k in self.data_keys:
- if isinstance(k, tuple) or isinstance(k, list):
- k_in = k[0]
- k_out = k[1]
- else:
- k_in = k
- k_out = k
+ for k_in, k_out in self.data_keys.items():
if k_in not in filled_keys:
try:
rc[k_out] = pd.DataFrame(
self._get_data(data_block, k_in))
- filled_keys.append(k)
+ filled_keys.append(k_in)
except KeyError as ke:
self.logger.debug("KEYERROR %s", ke)
if len(filled_keys) == len(self.data_keys):
diff --git a/src/decisionengine/framework/modules/translate_product_name.py b/src/decisionengine/framework/modules/translate_product_name.py
new file mode 100644
index 00000000..480bba16
--- /dev/null
+++ b/src/decisionengine/framework/modules/translate_product_name.py
@@ -0,0 +1,39 @@
+# The functionality provided here supports the translation of one
+# string to another using the syntax 'old -> new', subject to the
+# following constraints:
+#
+# - The 'old' and 'new' strings may contain the following
+# characters: a-z, A-Z, 0-9, and _ (underscore).
+#
+# - If '->' is provided, it must be surrounded by at least one space
+# on either side.
+#
+# The behavior is the following:
+#
+# - translate("old") == ("old", None)
+# - translate("old -> new") == ("old", "new")
+# - translate_all(["old", "old1 -> new1"]) == {"old": "old", "old1": "new1"}
+
+import re
+
+
+def translate(spec):
+ """Break apart the string 'old -> new' into a tuple ('old', 'new')"""
+ match = re.fullmatch(R'(\w+)(\s+\->\s+(\w+))?', spec)
+ if match is None:
+ raise RuntimeError(f"The specification '{spec}' does not match the supported pattern "
+ '"old_name[ -> new_name]",\n'
+ "where the product names can consist of the characters a-z, a-Z, 0-9, "
+ "and an underscore '_'.\nIf an optional new name is specified, the '->' "
+ "token must be surrounded by at least\none space on either side.")
+ return match.group(1, 3)
+
+
+def translate_all(specs):
+ result = {}
+ for entry in specs:
+ old, new = translate(entry)
+ if new is None:
+ new = old
+ result[old] = new
+ return result
| HEPCloud/decisionengine | f6258c09a6452e1e2de324c828d8f4c990bd9664 | diff --git a/src/decisionengine/framework/modules/tests/test_translate_product_name.py b/src/decisionengine/framework/modules/tests/test_translate_product_name.py
new file mode 100644
index 00000000..cae42936
--- /dev/null
+++ b/src/decisionengine/framework/modules/tests/test_translate_product_name.py
@@ -0,0 +1,24 @@
+from decisionengine.framework.modules.translate_product_name import translate, translate_all
+
+import pytest
+
+def test_translate_none():
+ with pytest.raises(RuntimeError, match="does not match the supported pattern"):
+ translate("")
+ assert translate("old") == ("old", None)
+
+def test_translate_simple():
+ assert translate("old -> new") == ('old', 'new')
+
+def test_translate_with_underscores():
+ assert translate("old_v0 -> new_v1") == ('old_v0', 'new_v1')
+
+def test_translate_illegal_characters():
+ with pytest.raises(RuntimeError, match="does not match the supported pattern"):
+ translate("old-v0 -> new-v1")
+ with pytest.raises(RuntimeError, match="does not match the supported pattern"):
+ translate("old-<3=->=new-<3")
+
+def test_translate_all():
+ specs = ["old", "old1 -> new1"]
+ assert translate_all(specs) == {"old": "old", "old1": "new1"}
| Add postgresql.sql to distributed decisionengine rpm
There is a file src/decisionengine/framework/dataspace/datasources/postgresql.sql
which is needed to initialize the Postgres database. This is not currently packaged with the RPM.
Please add it to the RPM again.
Steve Timm
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"src/decisionengine/framework/modules/tests/test_translate_product_name.py::test_translate_none",
"src/decisionengine/framework/modules/tests/test_translate_product_name.py::test_translate_simple",
"src/decisionengine/framework/modules/tests/test_translate_product_name.py::test_translate_with_underscores",
"src/decisionengine/framework/modules/tests/test_translate_product_name.py::test_translate_illegal_characters",
"src/decisionengine/framework/modules/tests/test_translate_product_name.py::test_translate_all"
] | [] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_added_files",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
} | "2021-06-17T19:27:53Z" | bsd-3-clause |
|
HEPData__hepdata_lib-259 | diff --git a/README.md b/README.md
index 6f9ba74..4b716ce 100644
--- a/README.md
+++ b/README.md
@@ -72,8 +72,8 @@ There are a few more examples available that can directly be run using the [bind
- [Reading TGraph and TGraphError from '.C' files](https://github.com/HEPData/hepdata_lib/blob/main/examples/read_c_file.ipynb)
[![Binder](https://mybinder.org/badge.svg)](https://mybinder.org/v2/gh/HEPData/hepdata_lib/main?filepath=examples/read_c_file.ipynb)
<br/><br/>
-- [Preparing scikit-hep histograms](https://github.com/HEPData/hepdata_lib/blob/main/examples/reading_scikithep_histogram.ipynb)
-[![Binder](https://mybinder.org/badge.svg)](https://mybinder.org/v2/gh/HEPData/hepdata_lib/main?filepath=examples/reading_scikihep_histogram.ipynb)
+- [Preparing scikit-hep histograms](https://github.com/HEPData/hepdata_lib/blob/main/examples/reading_scikithep_histograms.ipynb)
+[![Binder](https://mybinder.org/badge.svg)](https://mybinder.org/v2/gh/HEPData/hepdata_lib/main?filepath=examples/reading_scikihep_histograms.ipynb)
<br/><br/>
## External dependencies
@@ -82,3 +82,8 @@ There are a few more examples available that can directly be run using the [bind
- [ImageMagick](https://www.imagemagick.org)
Make sure that you have `ROOT` in your `$PYTHONPATH` and that the `convert` command is available by adding its location to your `$PATH` if needed.
+
+A ROOT installation is not strictly required if your input data is not in a ROOT format, for example, if
+your input data is provided as text files or `scikit-hep/hist` histograms. Most of the `hepdata_lib`
+functionality can be used without a ROOT installation, other than the `RootFileReader` and `CFileReader` classes,
+and other functions of the `hepdata_lib.root_utils` module.
\ No newline at end of file
diff --git a/docs/dev.rst b/docs/dev.rst
index 86e1f5f..e3a5e1b 100644
--- a/docs/dev.rst
+++ b/docs/dev.rst
@@ -15,6 +15,12 @@ To run the tests, move into the ``hepdata_lib`` directory while in your virtual
It is a good idea to run the tests manually to ensure that your changes do not cause any issues.
+If you don't have a working ROOT installation, a subset of the tests can still be run without ROOT:
+
+::
+
+ pytest tests -m "not needs_root"
+
Definition of test cases
++++++++++++++++++++++++
diff --git a/hepdata_lib/c_file_reader.py b/hepdata_lib/c_file_reader.py
index a07c714..2c957e3 100644
--- a/hepdata_lib/c_file_reader.py
+++ b/hepdata_lib/c_file_reader.py
@@ -2,7 +2,10 @@
import io
from array import array
from future.utils import raise_from
-from ROOT import TGraph, TGraphErrors # pylint: disable=no-name-in-module
+try:
+ from ROOT import TGraph, TGraphErrors # pylint: disable=no-name-in-module
+except ImportError as e: # pragma: no cover
+ print(f'Cannot import ROOT: {str(e)}')
import hepdata_lib.root_utils as ru
from hepdata_lib.helpers import check_file_existence
diff --git a/hepdata_lib/root_utils.py b/hepdata_lib/root_utils.py
index c6d0269..ff1dd28 100644
--- a/hepdata_lib/root_utils.py
+++ b/hepdata_lib/root_utils.py
@@ -3,7 +3,10 @@ from collections import defaultdict
import ctypes
from future.utils import raise_from
import numpy as np
-import ROOT as r
+try:
+ import ROOT as r
+except ImportError as e: # pragma: no cover
+ print(f'Cannot import ROOT: {str(e)}')
from hepdata_lib.helpers import check_file_existence
class RootFileReader:
diff --git a/pyproject.toml b/pyproject.toml
index 456e710..afbb950 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -14,3 +14,6 @@ addopts = [
]
log_cli_level = "info"
testpaths = "tests"
+markers = [
+ "needs_root: requires a ROOT installation"
+]
\ No newline at end of file
diff --git a/setup.py b/setup.py
index 088f89d..7091159 100644
--- a/setup.py
+++ b/setup.py
@@ -34,6 +34,7 @@ setup(
'Programming Language :: Python :: 3.9',
'Programming Language :: Python :: 3.10',
'Programming Language :: Python :: 3.11',
+ 'Programming Language :: Python :: 3.12',
],
keywords='HEPData physics OpenData',
packages=find_packages(exclude=['contrib', 'docs', 'tests']),
| HEPData/hepdata_lib | db53815f4963bd11cc62f88c9111f45134ccac67 | diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
index 251d276..b560594 100644
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -25,7 +25,7 @@ jobs:
strategy:
matrix:
os: [ubuntu-latest]
- root-version: ["6.24", "6.26", "6.28", "6.30"]
+ root-version: ["", "6.24", "6.26", "6.28", "6.30"]
python-version: ["3.6", "3.7", "3.8", "3.9", "3.10", "3.11"]
exclude:
- root-version: "6.24"
@@ -55,6 +55,7 @@ jobs:
- uses: actions/checkout@v4
- name: Setup Micromamba environment
+ if: ${{ matrix.root-version }}
uses: mamba-org/setup-micromamba@v1
with:
environment-name: ci
@@ -68,7 +69,22 @@ jobs:
channels:
- conda-forge
+ - name: Setup Micromamba environment without ROOT
+ if: ${{ !matrix.root-version }}
+ uses: mamba-org/setup-micromamba@v1
+ with:
+ environment-name: ci
+ create-args: >-
+ python=${{ matrix.python-version }}
+ imagemagick
+ ghostscript
+ pip
+ condarc: |
+ channels:
+ - conda-forge
+
- name: ROOT info
+ if: ${{ matrix.root-version }}
run: |
root-config --version
root-config --python-version
@@ -94,23 +110,30 @@ jobs:
# Use python -m pytest to add current working dir as src/ dir layout not used
- name: Run pytest
+ if: ${{ matrix.root-version }}
run: |
python -m pytest tests
+ - name: Run pytest without ROOT
+ if: ${{ !matrix.root-version }}
+ run: |
+ python -m pytest tests -m 'not needs_root'
+
- name: Report coverage with Codecov
+ if: ${{ matrix.root-version }}
uses: codecov/codecov-action@v3
with:
files: ./coverage.xml
flags: unittests-${{ matrix.python-version }}
- name: Save notebooks
- if: ${{ always() }}
+ if: ${{ always() && matrix.root-version }}
run: |
python -m jupyter kernelspec list
python -m jupyter nbconvert --ExecutePreprocessor.timeout=600 --ExecutePreprocessor.allow_errors=True --to html --execute examples/*.ipynb
- name: Upload notebooks
- if: ${{ always() }}
+ if: ${{ always() && matrix.root-version }}
uses: actions/upload-artifact@v4
with:
name: notebooks-${{ matrix.root-version }}-${{ matrix.python-version }}-${{ matrix.os }} py3-${{ matrix.root-version }}-${{ matrix.python-version }}-${{ matrix.os }}
diff --git a/tests/test_cfilereader.py b/tests/test_cfilereader.py
index b77511f..d19c47a 100644
--- a/tests/test_cfilereader.py
+++ b/tests/test_cfilereader.py
@@ -3,8 +3,10 @@
from unittest import TestCase
import os
import numpy as np
+import pytest
from hepdata_lib.c_file_reader import CFileReader
[email protected]_root
class TestCFileReader(TestCase):
"""Test the CFileReader class."""
diff --git a/tests/test_notebooks.py b/tests/test_notebooks.py
index 7783579..b74b0de 100644
--- a/tests/test_notebooks.py
+++ b/tests/test_notebooks.py
@@ -13,6 +13,7 @@ def common_kwargs(tmpdir):
'cwd' : 'examples'
}
[email protected]_root
def test_correlation(common_kwargs):# pylint: disable=redefined-outer-name
"""Tests examples/correlation.ipynb"""
pm.execute_notebook('examples/correlation.ipynb', **common_kwargs)
@@ -21,14 +22,21 @@ def test_getting_started(common_kwargs):# pylint: disable=redefined-outer-name
"""Tests examples/Getting_started.ipynb"""
pm.execute_notebook('examples/Getting_started.ipynb', **common_kwargs)
[email protected]_root
def test_reading_histograms(common_kwargs):# pylint: disable=redefined-outer-name
"""Tests examples/reading_histograms.ipynb"""
pm.execute_notebook('examples/reading_histograms.ipynb', **common_kwargs)
[email protected]_root
def test_combine_limits(common_kwargs):# pylint: disable=redefined-outer-name
"""Tests examples/combine_limits.ipynb"""
pm.execute_notebook('examples/combine_limits.ipynb', **common_kwargs)
[email protected]_root
def test_c_file(common_kwargs):# pylint: disable=redefined-outer-name
"""Tests examples/read_c_file.ipynb"""
pm.execute_notebook('examples/read_c_file.ipynb', **common_kwargs)
+
+def test_scikithep_histograms(common_kwargs):# pylint: disable=redefined-outer-name
+ """Tests examples/reading_scikithep_histograms.ipynb"""
+ pm.execute_notebook('examples/reading_scikithep_histograms.ipynb', **common_kwargs)
diff --git a/tests/test_rootfilereader.py b/tests/test_rootfilereader.py
index 4cd0c52..23d1d94 100644
--- a/tests/test_rootfilereader.py
+++ b/tests/test_rootfilereader.py
@@ -5,12 +5,17 @@ from array import array
import os
import ctypes
import numpy as np
-import ROOT
+import pytest
+try:
+ import ROOT
+except ImportError as e:
+ print(f'Cannot import ROOT: {str(e)}')
from hepdata_lib.root_utils import (RootFileReader, get_graph_points,
get_hist_1d_points, get_hist_2d_points)
from .test_utilities import float_compare, tuple_compare, histogram_compare_1d, make_tmp_root_file
[email protected]_root
class TestRootFileReader(TestCase):
"""Test the RootFileReader class."""
diff --git a/tests/test_utilities.py b/tests/test_utilities.py
index eee8d9d..21ebbb0 100644
--- a/tests/test_utilities.py
+++ b/tests/test_utilities.py
@@ -4,8 +4,10 @@
import os
import random
import string
-
-import ROOT
+try:
+ import ROOT
+except ImportError as e:
+ print(f'Cannot import ROOT: {str(e)}')
from future.utils import raise_from
| Add flag to disable features requiring ROOT
There are use cases where the tool is used but no ROOT installation is available. We should add an option that disables all features that use ROOT to make the other features work independently (e.g. reading in a text file). For ROOT TTrees, we could fall back to uproot. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_cfilereader.py::TestCFileReader::test_cfile_setter",
"tests/test_cfilereader.py::TestCFileReader::test_check_for_comments",
"tests/test_cfilereader.py::TestCFileReader::test_find_graphs",
"tests/test_cfilereader.py::TestCFileReader::test_read_graph",
"tests/test_notebooks.py::test_scikithep_histograms",
"tests/test_rootfilereader.py::TestRootFileReader::test_get_hist_1d_and_2d_points"
] | [] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2024-03-15T04:27:20Z" | mit |
|
HK3-Lab-Team__pytrousse-66 | diff --git a/src/trousse/dataset.py b/src/trousse/dataset.py
index 450f923..ce949a1 100644
--- a/src/trousse/dataset.py
+++ b/src/trousse/dataset.py
@@ -141,7 +141,6 @@ class Dataset:
feature_cols: Tuple = None,
data_file: str = None,
df_object: pd.DataFrame = None,
- nan_percentage_threshold: float = 0.999,
new_columns_encoding_maps: Union[
DefaultDict[str, List[FeatureOperation]], None
] = None,
@@ -170,9 +169,6 @@ class Dataset:
Pandas DataFrame instance containing the data. Either this or data_file
must be provided. In case ``data_file`` is provided, only this will
be considered as data. Default set to None.
- nan_percentage_threshold: float, optional
- Float value in the range [0,1] describing the threshold of
- NaN values count to decide if the column is relevant or not.
new_columns_encoding_maps: Union[
DefaultDict[str, List[FeatureOperation]], None
], optional
@@ -193,7 +189,6 @@ class Dataset:
self._feature_cols = set(self.df.columns) - self.metadata_cols
else:
self._feature_cols = set(feature_cols)
- self.nan_percentage_threshold = nan_percentage_threshold
# Dict of Lists ->
# key: column_name,
@@ -232,31 +227,31 @@ class Dataset:
"""
return self._feature_cols
- @property
- def many_nan_columns(self) -> Set[str]:
- """
- Return name of the columns containing many NaN.
+ def nan_columns(self, nan_ratio: float = 1) -> Set[str]:
+ """Return name of the columns containing at least a ``nan_ratio`` ratio of NaNs.
+
+ Select the columns where the nan_ratio of NaN values over the
+ sample count is higher than ``nan_ratio`` (in range [0,1]).
- This property selects the columns where the ratio of NaN values over the
- sample count is higher than ``nan_percentage_threshold`` attribute
- (in range [0,1]).
+ Parameters
+ ----------
+ nan_ratio : float, optional
+ Minimum ratio βnan samplesβ/βtotal samplesβ for the column to be considered
+ a βnan columnβ. Default is 1, meaning that only the columns entirely composed
+ by NaNs will be returned.
Returns
-------
Set[str]
- Set of column names with NaN ratio higher than
- ``nan_percentage_threshold`` attribute.
+ Set of column names with NaN ratio higher than ``nan_ratio`` parameter.
"""
- many_nan_columns = set()
+ nan_columns = set()
for c in self.feature_cols:
# Check number of NaN
- if (
- sum(self.df[c].isna())
- > self.nan_percentage_threshold * self.df.shape[0]
- ):
- many_nan_columns.add(c)
+ if sum(self.df[c].isna()) > nan_ratio * self.df.shape[0]:
+ nan_columns.add(c)
- return many_nan_columns
+ return nan_columns
@property
def constant_cols(self) -> Set[str]:
@@ -276,8 +271,8 @@ class Dataset:
"""
Return name of the columns containing many NaN or only one repeated value.
- This function return the name of the column that were included in
- ``constant_cols`` or ``many_nan_cols`` attributes
+ This function return the name of the column that were returned by
+ ``constant_cols`` property or ``nan_columns`` method.
Returns
-------
@@ -285,7 +280,7 @@ class Dataset:
Set containing the name of the columns with many NaNs or with only
one repeated value
"""
- return self.many_nan_columns.union(self.constant_cols)
+ return self.nan_columns(nan_ratio=0.999).union(self.constant_cols)
@lazy_property
def _columns_type(self) -> _ColumnListByType:
@@ -552,30 +547,6 @@ class Dataset:
# = METHODS =
# =====================
- def least_nan_cols(self, threshold: int) -> Set:
- """
- Get the features with a count of NaN values lower than the ``threshold`` argument.
-
- Parameters
- ----------
- threshold: int
- Number of samples that have a NaN value. If the count of NaN values
- from a column is lower than ``threshold`` value, the name of the column
- will be in the returned set
-
- Returns
- -------
- Set
- Set of column names with a NaN count lower than the ``threshold`` argument
- """
- best_feature_list = set()
- # TODO: Add argument col_list to select the columns to analyze
- for c in self.med_exam_col_list:
- if sum(self.df[c].isna()) < threshold:
- best_feature_list.add(c)
-
- return best_feature_list
-
def get_encoded_string_values_map(
self, column_name: str
) -> Union[Dict[int, str], None]:
@@ -942,7 +913,7 @@ class Dataset:
"""
return (
f"{self._columns_type}"
- f"\nColumns with many NaN: {len(self.many_nan_columns)}"
+ f"\nColumns with many NaN: {len(self.nan_columns(0.999))}"
)
def __call__(self) -> pd.DataFrame:
| HK3-Lab-Team/pytrousse | 28ae6abc5c1c743050789c0e2be66161e8ee3073 | diff --git a/tests/integration/test_dataset.py b/tests/integration/test_dataset.py
index bfcb88a..6b4111d 100644
--- a/tests/integration/test_dataset.py
+++ b/tests/integration/test_dataset.py
@@ -25,7 +25,7 @@ from ..fixtures import CSV
class Describe_Dataset:
@pytest.mark.parametrize(
- "nan_ratio, n_columns, expected_many_nan_columns",
+ "nan_ratio, n_columns, expected_nan_columns",
[
(0.8, 2, {"nan_0", "nan_1"}),
(0.8, 1, {"nan_0"}),
@@ -46,17 +46,15 @@ class Describe_Dataset:
(1.0, 2, {"nan_0", "nan_1"}),
],
)
- def test_many_nan_columns(
- self, request, nan_ratio, n_columns, expected_many_nan_columns
- ):
+ def test_nan_columns(self, request, nan_ratio, n_columns, expected_nan_columns):
df = DataFrameMock.df_many_nans(nan_ratio, n_columns)
- dataset = Dataset(df_object=df, nan_percentage_threshold=nan_ratio - 0.01)
+ dataset = Dataset(df_object=df)
- many_nan_columns = dataset.many_nan_columns
+ nan_columns = dataset.nan_columns(nan_ratio - 0.01)
- assert len(many_nan_columns) == len(expected_many_nan_columns)
- assert isinstance(many_nan_columns, set)
- assert many_nan_columns == expected_many_nan_columns
+ assert len(nan_columns) == len(expected_nan_columns)
+ assert isinstance(nan_columns, set)
+ assert nan_columns == expected_nan_columns
@pytest.mark.parametrize(
"n_columns, expected_constant_columns",
@@ -318,24 +316,6 @@ class Describe_Dataset:
assert isinstance(med_exam_col_list, set)
assert med_exam_col_list == expected_med_exam_col_list
- @pytest.mark.parametrize(
- "nan_threshold, expected_least_nan_cols",
- [
- (10, {"0nan_col"}),
- (101, {"0nan_col", "50nan_col"}),
- (199, {"0nan_col", "50nan_col"}),
- (200, {"0nan_col", "50nan_col", "99nan_col"}),
- ],
- )
- def test_least_nan_cols(self, request, nan_threshold, expected_least_nan_cols):
- df_multi_type = DataFrameMock.df_multi_nan_ratio(sample_size=200)
- dataset = Dataset(df_object=df_multi_type)
-
- least_nan_cols = dataset.least_nan_cols(nan_threshold)
-
- assert isinstance(least_nan_cols, set)
- assert least_nan_cols == expected_least_nan_cols
-
@pytest.mark.parametrize(
"duplicated_cols_count, expected_contains_dupl_cols_bool",
[(0, False), (4, True), (2, True)],
@@ -778,6 +758,23 @@ class Describe_Dataset:
assert type(columns_name)
assert columns_name == expected_columns_name
+ def test_str(self):
+ df = DataFrameMock.df_multi_type(10)
+ dataset = Dataset(df_object=df)
+ expected_str = (
+ "Columns with:\n\t1.\tMixed types: "
+ "\t\t1\n\t2.\tNumerical types (float/int): \t6\n\t3.\tString types: "
+ "\t\t2\n\t4.\tBool types: \t\t1\n\t5.\tOther types: \t\t1\nAmong these "
+ "categories:\n\t1.\tString categorical columns: 1\n\t2.\tNumeric categorical"
+ " columns: 2\n\t3.\tMedical Exam columns (numerical, no metadata): 6\n\t4."
+ "\tOne repeated value: 1\nColumns with many NaN: 0"
+ )
+
+ str_ = str(dataset)
+
+ assert type(str_) == str
+ assert expected_str == str_
+
class Describe_FeatureOperation:
@pytest.mark.parametrize(
diff --git a/tests/unit/test_dataset.py b/tests/unit/test_dataset.py
index 5b175db..246d51e 100644
--- a/tests/unit/test_dataset.py
+++ b/tests/unit/test_dataset.py
@@ -3,7 +3,7 @@ import pytest
from trousse.dataset import Dataset, _ColumnListByType
from ..dataset_util import DataFrameMock
-from ..unitutil import initializer_mock, property_mock
+from ..unitutil import initializer_mock, method_mock, property_mock
class DescribeDataset:
@@ -177,3 +177,66 @@ class DescribeDataset:
assert type(other_type_columns_) == set
assert other_type_columns_ == {"other0", "other1"}
_columns_type.assert_called_once()
+
+ def it_knows_its_str(self, request):
+ column_list_by_type = _ColumnListByType(
+ mixed_type_cols={"mixed0", "mixed1"},
+ constant_cols={"constant"},
+ numerical_cols={"numerical0", "numerical1"},
+ med_exam_col_list={"med0", "med1", "med2"},
+ str_cols={"str0", "str1"},
+ str_categorical_cols={"strcat0", "strcat1"},
+ num_categorical_cols={"numcat0", "numcat1"},
+ bool_cols={"bool0", "bool1"},
+ other_cols={"other0", "other1"},
+ )
+ expected_str = (
+ "Columns with:\n\t1.\tMixed types: \t\t2\n\t2.\tNumerical types"
+ " (float/int): \t2\n\t3.\tString types: \t\t2\n\t4.\tBool types: \t\t2\n\t5."
+ "\tOther types: \t\t2\nAmong these categories:\n\t1.\tString categorical "
+ "columns: 2\n\t2.\tNumeric categorical columns: 2\n\t3.\tMedical Exam columns "
+ "(numerical, no metadata): 3\n\t4.\tOne repeated value: 1"
+ )
+
+ str_ = str(column_list_by_type)
+
+ assert type(str_) == str
+ assert str_ == expected_str
+
+
+class DescribeColumnListByType:
+ def it_knows_its_str(self, request):
+ column_list_by_type_str = (
+ "Columns with:\n\t1.\tMixed types: \t\t2\n\t2.\tNumerical types"
+ " (float/int): \t2\n\t3.\tString types: \t\t2\n\t4.\tBool types: \t\t2\n\t5."
+ "\tOther types: \t\t2\nAmong these categories:\n\t1.\tString categorical "
+ "columns: 2\n\t2.\tNumeric categorical columns: 2\n\t3.\tMedical Exam columns "
+ "(numerical, no metadata): 3\n\t4.\tOne repeated value: 1"
+ )
+ _column_list_by_type_str = method_mock(request, _ColumnListByType, "__str__")
+ _column_list_by_type_str.return_value = column_list_by_type_str
+ _column_list_by_type = property_mock(request, Dataset, "_columns_type")
+ column_list_by_type = _ColumnListByType(
+ mixed_type_cols={"mixed0", "mixed1"},
+ constant_cols={"constant"},
+ numerical_cols={"numerical0", "numerical1"},
+ med_exam_col_list={"med0", "med1", "med2"},
+ str_cols={"str0", "str1"},
+ str_categorical_cols={"strcat0", "strcat1"},
+ num_categorical_cols={"numcat0", "numcat1"},
+ bool_cols={"bool0", "bool1"},
+ other_cols={"other0", "other1"},
+ )
+ _column_list_by_type.return_value = column_list_by_type
+ _nan_columns = method_mock(request, Dataset, "nan_columns")
+ _nan_columns.return_value = {"nan0", "nan1"}
+ initializer_mock(request, Dataset)
+ dataset = Dataset(data_file="fake/path")
+ expected_str = column_list_by_type_str + "\nColumns with many NaN: 2"
+
+ str_ = str(dataset)
+
+ assert type(str_) == str
+ assert str_ == expected_str
+ _column_list_by_type.assert_called_once
+ _nan_columns.assert_called_once_with(dataset, 0.999)
| Dataset method: nan_columns
nan_columns(tolerance) [2c]
Tolerance is a (optional, default=1) float number (0 to 1) representing the ratio βnan samplesβ/βtotal samplesβ for the column to be considered a βnan columnβ.
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/integration/test_dataset.py::Describe_Dataset::test_nan_columns[0.8-2-expected_nan_columns0]",
"tests/integration/test_dataset.py::Describe_Dataset::test_nan_columns[0.8-1-expected_nan_columns1]",
"tests/integration/test_dataset.py::Describe_Dataset::test_nan_columns[0.8-0-expected_nan_columns2]",
"tests/integration/test_dataset.py::Describe_Dataset::test_nan_columns[0.0-2-expected_nan_columns3]",
"tests/integration/test_dataset.py::Describe_Dataset::test_nan_columns[1.0-2-expected_nan_columns4]",
"tests/unit/test_dataset.py::DescribeColumnListByType::it_knows_its_str"
] | [
"tests/integration/test_dataset.py::Describe_Dataset::test_get_categorical_cols[50-expected_categ_cols0]",
"tests/integration/test_dataset.py::Describe_Dataset::test_get_categorical_cols[100-expected_categ_cols1]",
"tests/integration/test_dataset.py::Describe_Dataset::test_get_categorical_cols[3000-expected_categ_cols2]",
"tests/integration/test_dataset.py::Describe_Dataset::test_get_categorical_cols[15000-expected_categ_cols3]",
"tests/integration/test_dataset.py::Describe_Dataset::test_contains_duplicated_features[0-False]",
"tests/integration/test_dataset.py::Describe_Dataset::test_contains_duplicated_features[4-True]",
"tests/integration/test_dataset.py::Describe_Dataset::test_contains_duplicated_features[2-True]",
"tests/integration/test_dataset.py::Describe_Dataset::test_show_columns_type",
"tests/integration/test_dataset.py::Describe_Dataset::test_add_operation[original_columns0-derived_columns0-OperationTypeEnum.BIN_SPLITTING-encoded_values_map0-encoder0-details0]",
"tests/integration/test_dataset.py::Describe_Dataset::test_add_operation[original_columns1-derived_columns1-OperationTypeEnum.CATEGORICAL_ENCODING-None-None-None]",
"tests/integration/test_dataset.py::Describe_Dataset::test_add_operation[original_columns2-derived_columns2-OperationTypeEnum.FEAT_COMBOS_ENCODING-encoded_values_map2-encoder2-details2]",
"tests/integration/test_dataset.py::Describe_Dataset::test_add_operation[original_columns3-derived_columns3-OperationTypeEnum.CATEGORICAL_ENCODING-encoded_values_map3-encoder3-details3]",
"tests/integration/test_dataset.py::Describe_Dataset::test_add_operation_on_previous_one",
"tests/integration/test_dataset.py::Describe_Dataset::test_find_operation_in_column[searched_feat_op0-expected_found_feat_op0]",
"tests/integration/test_dataset.py::Describe_Dataset::test_find_operation_in_column[searched_feat_op1-expected_found_feat_op1]",
"tests/integration/test_dataset.py::Describe_Dataset::test_find_operation_in_column[searched_feat_op2-expected_found_feat_op2]",
"tests/integration/test_dataset.py::Describe_Dataset::test_find_operation_in_column[searched_feat_op3-expected_found_feat_op3]",
"tests/integration/test_dataset.py::Describe_Dataset::test_find_operation_in_column[searched_feat_op4-expected_found_feat_op4]",
"tests/integration/test_dataset.py::Describe_Dataset::test_find_operation_in_column_not_found",
"tests/integration/test_dataset.py::Describe_Dataset::test_find_operation_in_column_raise_error",
"tests/integration/test_dataset.py::Describe_Dataset::test_get_enc_column_from_original_one_col_found[fop_original_col_0-encoder0-expected_encoded_columns0]",
"tests/integration/test_dataset.py::Describe_Dataset::test_get_enc_column_from_original_one_col_found[fop_original_col_2-None-expected_encoded_columns1]",
"tests/integration/test_dataset.py::Describe_Dataset::test_get_enc_column_from_original_not_found[fop_derived_col_1]",
"tests/integration/test_dataset.py::Describe_Dataset::test_get_enc_column_from_original_not_found[fop_original_col_10]",
"tests/integration/test_dataset.py::Describe_Dataset::test_get_enc_column_from_original_raise_multicolfound_error",
"tests/integration/test_dataset.py::Describe_Dataset::test_get_original_from_enc_column_one_col_found[fop_derived_col_0-encoder0-expected_original_columns0]",
"tests/integration/test_dataset.py::Describe_Dataset::test_get_original_from_enc_column_one_col_found[fop_derived_col_1-None-expected_original_columns1]",
"tests/integration/test_dataset.py::Describe_Dataset::test_get_original_from_enc_column_not_found[fop_derived_col_10]",
"tests/integration/test_dataset.py::Describe_Dataset::test_get_original_from_enc_column_not_found[fop_original_col_2]",
"tests/integration/test_dataset.py::Describe_Dataset::test_get_original_from_enc_column_raise_multicolfound_error",
"tests/integration/test_dataset.py::Describe_Dataset::test_convert_column_id_to_name[col_id_list0-expected_columns_name0]",
"tests/integration/test_dataset.py::Describe_Dataset::test_convert_column_id_to_name[col_id_list1-expected_columns_name1]",
"tests/integration/test_dataset.py::Describe_Dataset::test_convert_column_id_to_name[col_id_list2-expected_columns_name2]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict0-feat_op_2_dict0-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict1-feat_op_2_dict1-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict2-feat_op_2_dict2-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict3-feat_op_2_dict3-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict4-feat_op_2_dict4-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict5-feat_op_2_dict5-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict6-feat_op_2_dict6-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict7-feat_op_2_dict7-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict8-feat_op_2_dict8-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict9-feat_op_2_dict9-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict10-feat_op_2_dict10-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict11-feat_op_2_dict11-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict12-feat_op_2_dict12-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict13-feat_op_2_dict13-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict14-feat_op_2_dict14-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict15-feat_op_2_dict15-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict16-feat_op_2_dict16-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict17-feat_op_2_dict17-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict18-feat_op_2_dict18-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict19-feat_op_2_dict19-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict20-feat_op_2_dict20-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict21-feat_op_2_dict21-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict22-feat_op_2_dict22-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict23-feat_op_2_dict23-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict24-feat_op_2_dict24-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict25-feat_op_2_dict25-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict26-feat_op_2_dict26-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict27-feat_op_2_dict27-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict28-feat_op_2_dict28-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict29-feat_op_2_dict29-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict30-feat_op_2_dict30-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict31-feat_op_2_dict31-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict32-feat_op_2_dict32-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict33-feat_op_2_dict33-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict34-feat_op_2_dict34-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict35-feat_op_2_dict35-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict36-feat_op_2_dict36-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict37-feat_op_2_dict37-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict38-feat_op_2_dict38-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict39-feat_op_2_dict39-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict40-feat_op_2_dict40-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict41-feat_op_2_dict41-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict42-feat_op_2_dict42-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict43-feat_op_2_dict43-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict44-feat_op_2_dict44-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict45-feat_op_2_dict45-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict46-feat_op_2_dict46-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict47-feat_op_2_dict47-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict48-feat_op_2_dict48-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict49-feat_op_2_dict49-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict50-feat_op_2_dict50-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict51-feat_op_2_dict51-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict52-feat_op_2_dict52-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict53-feat_op_2_dict53-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict54-feat_op_2_dict54-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict55-feat_op_2_dict55-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict56-feat_op_2_dict56-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict57-feat_op_2_dict57-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict58-feat_op_2_dict58-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict59-feat_op_2_dict59-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict60-feat_op_2_dict60-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict61-feat_op_2_dict61-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict62-feat_op_2_dict62-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict63-feat_op_2_dict63-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict64-feat_op_2_dict64-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict65-feat_op_2_dict65-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict66-feat_op_2_dict66-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict67-feat_op_2_dict67-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict68-feat_op_2_dict68-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict69-feat_op_2_dict69-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict70-feat_op_2_dict70-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict71-feat_op_2_dict71-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict72-feat_op_2_dict72-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict73-feat_op_2_dict73-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict74-feat_op_2_dict74-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict75-feat_op_2_dict75-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict76-feat_op_2_dict76-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict77-feat_op_2_dict77-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict78-feat_op_2_dict78-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict79-feat_op_2_dict79-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict80-feat_op_2_dict80-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict81-feat_op_2_dict81-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict82-feat_op_2_dict82-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict83-feat_op_2_dict83-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict84-feat_op_2_dict84-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict85-feat_op_2_dict85-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict86-feat_op_2_dict86-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict87-feat_op_2_dict87-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict88-feat_op_2_dict88-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict89-feat_op_2_dict89-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict90-feat_op_2_dict90-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict91-feat_op_2_dict91-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict92-feat_op_2_dict92-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict93-feat_op_2_dict93-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict94-feat_op_2_dict94-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict95-feat_op_2_dict95-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict96-feat_op_2_dict96-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict97-feat_op_2_dict97-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict98-feat_op_2_dict98-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict99-feat_op_2_dict99-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict100-feat_op_2_dict100-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict101-feat_op_2_dict101-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict102-feat_op_2_dict102-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict103-feat_op_2_dict103-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict104-feat_op_2_dict104-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict105-feat_op_2_dict105-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict106-feat_op_2_dict106-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict107-feat_op_2_dict107-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict108-feat_op_2_dict108-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict109-feat_op_2_dict109-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict110-feat_op_2_dict110-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict111-feat_op_2_dict111-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict112-feat_op_2_dict112-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict113-feat_op_2_dict113-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict114-feat_op_2_dict114-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict115-feat_op_2_dict115-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict116-feat_op_2_dict116-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict117-feat_op_2_dict117-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict118-feat_op_2_dict118-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict119-feat_op_2_dict119-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict120-feat_op_2_dict120-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict121-feat_op_2_dict121-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict122-feat_op_2_dict122-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict123-feat_op_2_dict123-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict124-feat_op_2_dict124-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict125-feat_op_2_dict125-True]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict126-feat_op_2_dict126-True]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict127-feat_op_2_dict127-True]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict128-feat_op_2_dict128-True]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict129-feat_op_2_dict129-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict130-feat_op_2_dict130-True]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict131-feat_op_2_dict131-True]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict132-feat_op_2_dict132-True]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict133-feat_op_2_dict133-True]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict134-feat_op_2_dict134-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict135-feat_op_2_dict135-True]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict136-feat_op_2_dict136-True]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict137-feat_op_2_dict137-True]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict138-feat_op_2_dict138-True]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict139-feat_op_2_dict139-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict140-feat_op_2_dict140-True]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict141-feat_op_2_dict141-True]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict142-feat_op_2_dict142-True]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict143-feat_op_2_dict143-True]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict144-feat_op_2_dict144-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict145-feat_op_2_dict145-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict146-feat_op_2_dict146-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict147-feat_op_2_dict147-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict148-feat_op_2_dict148-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict149-feat_op_2_dict149-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict150-feat_op_2_dict150-True]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict151-feat_op_2_dict151-True]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict152-feat_op_2_dict152-True]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict153-feat_op_2_dict153-True]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict154-feat_op_2_dict154-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict155-feat_op_2_dict155-True]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict156-feat_op_2_dict156-True]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict157-feat_op_2_dict157-True]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict158-feat_op_2_dict158-True]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict159-feat_op_2_dict159-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict160-feat_op_2_dict160-True]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict161-feat_op_2_dict161-True]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict162-feat_op_2_dict162-True]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict163-feat_op_2_dict163-True]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict164-feat_op_2_dict164-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict165-feat_op_2_dict165-True]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict166-feat_op_2_dict166-True]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict167-feat_op_2_dict167-True]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict168-feat_op_2_dict168-True]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict169-feat_op_2_dict169-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict170-feat_op_2_dict170-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict171-feat_op_2_dict171-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict172-feat_op_2_dict172-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict173-feat_op_2_dict173-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict174-feat_op_2_dict174-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict175-feat_op_2_dict175-True]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict176-feat_op_2_dict176-True]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict177-feat_op_2_dict177-True]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict178-feat_op_2_dict178-True]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict179-feat_op_2_dict179-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict180-feat_op_2_dict180-True]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict181-feat_op_2_dict181-True]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict182-feat_op_2_dict182-True]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict183-feat_op_2_dict183-True]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict184-feat_op_2_dict184-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict185-feat_op_2_dict185-True]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict186-feat_op_2_dict186-True]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict187-feat_op_2_dict187-True]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict188-feat_op_2_dict188-True]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict189-feat_op_2_dict189-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict190-feat_op_2_dict190-True]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict191-feat_op_2_dict191-True]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict192-feat_op_2_dict192-True]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict193-feat_op_2_dict193-True]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict194-feat_op_2_dict194-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict195-feat_op_2_dict195-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict196-feat_op_2_dict196-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict197-feat_op_2_dict197-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict198-feat_op_2_dict198-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict199-feat_op_2_dict199-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict200-feat_op_2_dict200-True]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict201-feat_op_2_dict201-True]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict202-feat_op_2_dict202-True]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict203-feat_op_2_dict203-True]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict204-feat_op_2_dict204-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict205-feat_op_2_dict205-True]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict206-feat_op_2_dict206-True]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict207-feat_op_2_dict207-True]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict208-feat_op_2_dict208-True]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict209-feat_op_2_dict209-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict210-feat_op_2_dict210-True]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict211-feat_op_2_dict211-True]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict212-feat_op_2_dict212-True]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict213-feat_op_2_dict213-True]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict214-feat_op_2_dict214-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict215-feat_op_2_dict215-True]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict216-feat_op_2_dict216-True]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict217-feat_op_2_dict217-True]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict218-feat_op_2_dict218-True]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict219-feat_op_2_dict219-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict220-feat_op_2_dict220-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict221-feat_op_2_dict221-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict222-feat_op_2_dict222-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict223-feat_op_2_dict223-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict224-feat_op_2_dict224-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict225-feat_op_2_dict225-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict226-feat_op_2_dict226-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict227-feat_op_2_dict227-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict228-feat_op_2_dict228-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict229-feat_op_2_dict229-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict230-feat_op_2_dict230-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict231-feat_op_2_dict231-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict232-feat_op_2_dict232-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict233-feat_op_2_dict233-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict234-feat_op_2_dict234-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict235-feat_op_2_dict235-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict236-feat_op_2_dict236-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict237-feat_op_2_dict237-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict238-feat_op_2_dict238-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict239-feat_op_2_dict239-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict240-feat_op_2_dict240-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict241-feat_op_2_dict241-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict242-feat_op_2_dict242-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict243-feat_op_2_dict243-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict244-feat_op_2_dict244-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict245-feat_op_2_dict245-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict246-feat_op_2_dict246-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict247-feat_op_2_dict247-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict248-feat_op_2_dict248-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals[feat_op_1_dict249-feat_op_2_dict249-False]",
"tests/integration/test_dataset.py::Describe_FeatureOperation::test_featureoperation_equals_with_different_instance_types",
"tests/integration/test_dataset.py::test_find_single_column_type[bool-expected_col_type_dict0]",
"tests/integration/test_dataset.py::test_find_single_column_type[string-expected_col_type_dict1]",
"tests/integration/test_dataset.py::test_find_single_column_type[category-expected_col_type_dict2]",
"tests/integration/test_dataset.py::test_find_single_column_type[float-expected_col_type_dict3]",
"tests/integration/test_dataset.py::test_find_single_column_type[int-expected_col_type_dict4]",
"tests/integration/test_dataset.py::test_find_single_column_type[float_int-expected_col_type_dict5]",
"tests/integration/test_dataset.py::test_find_single_column_type[interval-expected_col_type_dict6]",
"tests/integration/test_dataset.py::test_find_single_column_type[date-expected_col_type_dict7]",
"tests/integration/test_dataset.py::test_find_single_column_type[mixed_0-expected_col_type_dict8]",
"tests/integration/test_dataset.py::test_find_single_column_type[mixed_1-expected_col_type_dict9]",
"tests/integration/test_dataset.py::test_find_single_column_type[mixed_2-expected_col_type_dict10]",
"tests/integration/test_dataset.py::test_copy_dataset_with_new_df_log_warning",
"tests/integration/test_dataset.py::test_to_file_raise_fileexistserror",
"tests/integration/test_dataset.py::test_read_file_raise_notshelvefileerror",
"tests/integration/test_dataset.py::test_read_file_raise_typeerror",
"tests/integration/test_dataset.py::test_df_from_csv",
"tests/integration/test_dataset.py::test_df_from_csv_notfound",
"tests/unit/test_dataset.py::DescribeDataset::it_knows_its_metadata_cols[metadata_num_col]",
"tests/unit/test_dataset.py::DescribeDataset::it_knows_its_metadata_cols[metadata_num_col,",
"tests/unit/test_dataset.py::DescribeDataset::it_knows_its_metadata_cols[metadata_cols2]",
"tests/unit/test_dataset.py::DescribeDataset::it_knows_its_feature_cols[metadata_cols0-feature_cols0-expected_feature_cols0]",
"tests/unit/test_dataset.py::DescribeDataset::it_knows_its_feature_cols[metadata_cols1-feature_cols1-expected_feature_cols1]",
"tests/unit/test_dataset.py::DescribeDataset::it_knows_its_feature_cols[metadata_cols2-None-expected_feature_cols2]",
"tests/unit/test_dataset.py::DescribeDataset::it_knows_its_mixed_type_columns",
"tests/unit/test_dataset.py::DescribeDataset::it_knows_its_numerical_columns",
"tests/unit/test_dataset.py::DescribeDataset::it_knows_its_med_exam_col_list",
"tests/unit/test_dataset.py::DescribeDataset::it_knows_its_str_columns",
"tests/unit/test_dataset.py::DescribeDataset::it_knows_its_str_categorical_columns",
"tests/unit/test_dataset.py::DescribeDataset::it_knows_its_num_categorical_columns",
"tests/unit/test_dataset.py::DescribeDataset::it_knows_its_bool_columns",
"tests/unit/test_dataset.py::DescribeDataset::it_knows_its_other_type_columns",
"tests/unit/test_dataset.py::DescribeDataset::it_knows_its_str"
] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2020-09-21T16:04:46Z" | mit |
|
HTTP-APIs__hydra-python-core-91 | diff --git a/hydra_python_core/doc_maker.py b/hydra_python_core/doc_maker.py
index 31996c4..aa80d4a 100644
--- a/hydra_python_core/doc_maker.py
+++ b/hydra_python_core/doc_maker.py
@@ -332,6 +332,17 @@ def create_property(supported_property: Dict[str, Any]) -> Union[HydraLink, Hydr
prop_require = supported_property[hydra['required']][0]['@value']
prop_write = supported_property[hydra['writeable']][0]['@value']
+ for namespace in supported_property:
+ if "range" in namespace:
+ prop_range = supported_property[namespace][0]['@id']
+ prop_ = HydraClassProp(prop=prop_id,
+ title=prop_title,
+ required=prop_require,
+ read=prop_read,
+ write=prop_write,
+ range=prop_range)
+ return prop_
+
prop_ = HydraClassProp(prop=prop_id,
title=prop_title,
required=prop_require,
diff --git a/hydra_python_core/doc_writer.py b/hydra_python_core/doc_writer.py
index 13183ca..635d6e5 100644
--- a/hydra_python_core/doc_writer.py
+++ b/hydra_python_core/doc_writer.py
@@ -186,7 +186,7 @@ class HydraClassProp():
write: bool,
required: bool,
desc: str = "",
- ) -> None:
+ **kwargs) -> None:
"""Initialize the Hydra_Prop."""
self.prop = prop
self.title = title
@@ -194,6 +194,7 @@ class HydraClassProp():
self.write = write
self.required = required
self.desc = desc
+ self.kwargs = kwargs
def generate(self) -> Dict[str, Any]:
"""Get the Hydra prop as a python dict."""
@@ -210,6 +211,8 @@ class HydraClassProp():
prop["property"] = self.prop
if len(self.desc) > 0:
prop["description"] = self.desc
+ if "range" in self.kwargs:
+ prop["range"] = self.kwargs["range"]
return prop
@@ -781,6 +784,7 @@ class Context():
"supportedOperation": "hydra:supportedOperation",
"label": "rdfs:label",
"rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
+ "xsd": "https://www.w3.org/TR/xmlschema-2/#",
"domain": {
"@type": "@id",
"@id": "rdfs:domain"
diff --git a/hydra_python_core/namespace.py b/hydra_python_core/namespace.py
index b586e5e..cb80176 100644
--- a/hydra_python_core/namespace.py
+++ b/hydra_python_core/namespace.py
@@ -71,6 +71,7 @@ hydra = {
"search": hydraNamespace + "search",
"view": hydraNamespace + "view"
}
+
rdfNamespace = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"
rdf = {
diff --git a/samples/doc_writer_sample_output.py b/samples/doc_writer_sample_output.py
index 948f770..48405f8 100644
--- a/samples/doc_writer_sample_output.py
+++ b/samples/doc_writer_sample_output.py
@@ -77,7 +77,7 @@ doc = {
"method": "POST",
"possibleStatus": [
{
- "@context": "https://raw.githubusercontent.com/HydraCG/Specifications/master/spec/latest/core/core.jsonld",
+ "@context": "https://www.w3.org/ns/hydra/core",
"@type": "Status",
"description": "dummyClass updated.",
"statusCode": 200,
@@ -98,7 +98,7 @@ doc = {
"method": "DELETE",
"possibleStatus": [
{
- "@context": "https://raw.githubusercontent.com/HydraCG/Specifications/master/spec/latest/core/core.jsonld",
+ "@context": "https://www.w3.org/ns/hydra/core",
"@type": "Status",
"description": "dummyClass deleted.",
"statusCode": 200,
@@ -116,7 +116,7 @@ doc = {
"method": "PUT",
"possibleStatus": [
{
- "@context": "https://raw.githubusercontent.com/HydraCG/Specifications/master/spec/latest/core/core.jsonld",
+ "@context": "https://www.w3.org/ns/hydra/core",
"@type": "Status",
"description": "dummyClass successfully added.",
"statusCode": 201,
@@ -134,7 +134,7 @@ doc = {
"method": "GET",
"possibleStatus": [
{
- "@context": "https://raw.githubusercontent.com/HydraCG/Specifications/master/spec/latest/core/core.jsonld",
+ "@context": "https://www.w3.org/ns/hydra/core",
"@type": "Status",
"description": "dummyClass returned.",
"statusCode": 200,
@@ -186,7 +186,7 @@ doc = {
"method": "POST",
"possibleStatus": [
{
- "@context": "https://raw.githubusercontent.com/HydraCG/Specifications/master/spec/latest/core/core.jsonld",
+ "@context": "https://www.w3.org/ns/hydra/core",
"@type": "Status",
"description": "singleClass changed.",
"statusCode": 200,
@@ -204,7 +204,7 @@ doc = {
"method": "DELETE",
"possibleStatus": [
{
- "@context": "https://raw.githubusercontent.com/HydraCG/Specifications/master/spec/latest/core/core.jsonld",
+ "@context": "https://www.w3.org/ns/hydra/core",
"@type": "Status",
"description": "singleClass deleted.",
"statusCode": 200,
@@ -222,7 +222,7 @@ doc = {
"method": "PUT",
"possibleStatus": [
{
- "@context": "https://raw.githubusercontent.com/HydraCG/Specifications/master/spec/latest/core/core.jsonld",
+ "@context": "https://www.w3.org/ns/hydra/core",
"@type": "Status",
"description": "singleClass successfully added.",
"statusCode": 201,
@@ -240,7 +240,7 @@ doc = {
"method": "GET",
"possibleStatus": [
{
- "@context": "https://raw.githubusercontent.com/HydraCG/Specifications/master/spec/latest/core/core.jsonld",
+ "@context": "https://www.w3.org/ns/hydra/core",
"@type": "Status",
"description": "singleClass returned.",
"statusCode": 200,
@@ -308,7 +308,7 @@ doc = {
"method": "GET",
"possibleStatus": [
{
- "@context": "https://raw.githubusercontent.com/HydraCG/Specifications/master/spec/latest/core/core.jsonld",
+ "@context": "https://www.w3.org/ns/hydra/core",
"@type": "Status",
"description": "anotherSingleClass returned.",
"statusCode": 200,
@@ -387,7 +387,7 @@ doc = {
"method": "PUT",
"possibleStatus": [
{
- "@context": "https://raw.githubusercontent.com/HydraCG/Specifications/master/spec/latest/core/core.jsonld",
+ "@context": "https://www.w3.org/ns/hydra/core",
"@type": "Status",
"description": "A new member in Extraclasses created",
"statusCode": 201,
@@ -406,7 +406,7 @@ doc = {
"method": "POST",
"possibleStatus": [
{
- "@context": "https://raw.githubusercontent.com/HydraCG/Specifications/master/spec/latest/core/core.jsonld",
+ "@context": "https://www.w3.org/ns/hydra/core",
"@type": "Status",
"description": "If the entity was updatedfrom Extraclasses.",
"statusCode": 200,
@@ -425,7 +425,7 @@ doc = {
"method": "DELETE",
"possibleStatus": [
{
- "@context": "https://raw.githubusercontent.com/HydraCG/Specifications/master/spec/latest/core/core.jsonld",
+ "@context": "https://www.w3.org/ns/hydra/core",
"@type": "Status",
"description": "If entity was deletedsuccessfully from Extraclasses.",
"statusCode": 200,
@@ -479,7 +479,7 @@ doc = {
"method": "PUT",
"possibleStatus": [
{
- "@context": "https://raw.githubusercontent.com/HydraCG/Specifications/master/spec/latest/core/core.jsonld",
+ "@context": "https://www.w3.org/ns/hydra/core",
"@type": "Status",
"description": "A new member in dummyclasses created",
"statusCode": 201,
@@ -498,7 +498,7 @@ doc = {
"method": "POST",
"possibleStatus": [
{
- "@context": "https://raw.githubusercontent.com/HydraCG/Specifications/master/spec/latest/core/core.jsonld",
+ "@context": "https://www.w3.org/ns/hydra/core",
"@type": "Status",
"description": "If the entity was updatedfrom dummyclasses.",
"statusCode": 200,
@@ -517,7 +517,7 @@ doc = {
"method": "DELETE",
"possibleStatus": [
{
- "@context": "https://raw.githubusercontent.com/HydraCG/Specifications/master/spec/latest/core/core.jsonld",
+ "@context": "https://www.w3.org/ns/hydra/core",
"@type": "Status",
"description": "If entity was deletedsuccessfully from dummyclasses.",
"statusCode": 200,
@@ -580,7 +580,7 @@ doc = {
"method": "POST",
"possibleStatus": [
{
- "@context": "https://raw.githubusercontent.com/HydraCG/Specifications/master/spec/latest/core/core.jsonld",
+ "@context": "https://www.w3.org/ns/hydra/core",
"@type": "Status",
"description": "singleClass changed.",
"statusCode": 200,
@@ -600,7 +600,7 @@ doc = {
"method": "DELETE",
"possibleStatus": [
{
- "@context": "https://raw.githubusercontent.com/HydraCG/Specifications/master/spec/latest/core/core.jsonld",
+ "@context": "https://www.w3.org/ns/hydra/core",
"@type": "Status",
"description": "singleClass deleted.",
"statusCode": 200,
@@ -620,7 +620,7 @@ doc = {
"method": "PUT",
"possibleStatus": [
{
- "@context": "https://raw.githubusercontent.com/HydraCG/Specifications/master/spec/latest/core/core.jsonld",
+ "@context": "https://www.w3.org/ns/hydra/core",
"@type": "Status",
"description": "singleClass successfully added.",
"statusCode": 201,
@@ -640,7 +640,7 @@ doc = {
"method": "GET",
"possibleStatus": [
{
- "@context": "https://raw.githubusercontent.com/HydraCG/Specifications/master/spec/latest/core/core.jsonld",
+ "@context": "https://www.w3.org/ns/hydra/core",
"@type": "Status",
"description": "singleClass returned.",
"statusCode": 200,
@@ -677,7 +677,7 @@ doc = {
"method": "GET",
"possibleStatus": [
{
- "@context": "https://raw.githubusercontent.com/HydraCG/Specifications/master/spec/latest/core/core.jsonld",
+ "@context": "https://www.w3.org/ns/hydra/core",
"@type": "Status",
"description": "anotherSingleClass returned.",
"statusCode": 200,
@@ -728,7 +728,7 @@ doc = {
"method": "PUT",
"possibleStatus": [
{
- "@context": "https://raw.githubusercontent.com/HydraCG/Specifications/master/spec/latest/core/core.jsonld",
+ "@context": "https://www.w3.org/ns/hydra/core",
"@type": "Status",
"description": "A new member in Extraclasses created",
"statusCode": 201,
@@ -747,7 +747,7 @@ doc = {
"method": "POST",
"possibleStatus": [
{
- "@context": "https://raw.githubusercontent.com/HydraCG/Specifications/master/spec/latest/core/core.jsonld",
+ "@context": "https://www.w3.org/ns/hydra/core",
"@type": "Status",
"description": "If the entity was updatedfrom Extraclasses.",
"statusCode": 200,
@@ -766,7 +766,7 @@ doc = {
"method": "DELETE",
"possibleStatus": [
{
- "@context": "https://raw.githubusercontent.com/HydraCG/Specifications/master/spec/latest/core/core.jsonld",
+ "@context": "https://www.w3.org/ns/hydra/core",
"@type": "Status",
"description": "If entity was deletedsuccessfully from Extraclasses.",
"statusCode": 200,
@@ -817,7 +817,7 @@ doc = {
"method": "PUT",
"possibleStatus": [
{
- "@context": "https://raw.githubusercontent.com/HydraCG/Specifications/master/spec/latest/core/core.jsonld",
+ "@context": "https://www.w3.org/ns/hydra/core",
"@type": "Status",
"description": "A new member in dummyclasses created",
"statusCode": 201,
@@ -836,7 +836,7 @@ doc = {
"method": "POST",
"possibleStatus": [
{
- "@context": "https://raw.githubusercontent.com/HydraCG/Specifications/master/spec/latest/core/core.jsonld",
+ "@context": "https://www.w3.org/ns/hydra/core",
"@type": "Status",
"description": "If the entity was updatedfrom dummyclasses.",
"statusCode": 200,
@@ -855,7 +855,7 @@ doc = {
"method": "DELETE",
"possibleStatus": [
{
- "@context": "https://raw.githubusercontent.com/HydraCG/Specifications/master/spec/latest/core/core.jsonld",
+ "@context": "https://www.w3.org/ns/hydra/core",
"@type": "Status",
"description": "If entity was deletedsuccessfully from dummyclasses.",
"statusCode": 200,
| HTTP-APIs/hydra-python-core | f191e9e58a7ab81552814303031aaa3bf90ff514 | diff --git a/tests/test_doc_writer.py b/tests/test_doc_writer.py
index e37e805..d497658 100644
--- a/tests/test_doc_writer.py
+++ b/tests/test_doc_writer.py
@@ -23,6 +23,7 @@ class TestDocWriter(unittest.TestCase):
'supportedOperation': 'hydra:supportedOperation',
'label': 'rdfs:label',
'rdf': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
+ "xsd": "https://www.w3.org/TR/xmlschema-2/#",
'domain': {
'@type': '@id',
'@id': 'rdfs:domain'
| Implement copying of data types properties
### I'm submitting a
- [x ] feature request.
If the declaration of a type for a field is present in the original ontology, it should be copied in the ApiDoc to allow `hydrus` to read it and genreate the right column type.
Necessary for https://github.com/HTTP-APIs/hydrus/issues/581 | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_doc_writer.py::TestDocWriter::test_context_with_nothing"
] | [
"tests/test_doc_writer.py::TestDocWriter::test_context_with_class",
"tests/test_doc_writer.py::TestDocWriter::test_context_with_collection"
] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2021-07-01T13:33:02Z" | mit |
|
IAMconsortium__nomenclature-9 | diff --git a/nomenclature/core.py b/nomenclature/core.py
index 93180ed..cb40464 100644
--- a/nomenclature/core.py
+++ b/nomenclature/core.py
@@ -7,10 +7,13 @@ from nomenclature.validation import validate
class Nomenclature:
"""A nomenclature with codelists for all dimensions used in the IAMC data format"""
- def __init__(self, path="definitions"):
+ def __init__(self, path):
if not isinstance(path, Path):
path = Path(path)
+ if not path.is_dir():
+ raise NotADirectoryError(f"Definitions directory not found: {path}")
+
self.variable = CodeList("variable").parse_files(path / "variables")
self.region = CodeList("region").parse_files(
path / "regions", top_level_attr="hierarchy"
diff --git a/nomenclature/validation.py b/nomenclature/validation.py
index ab04374..cefa394 100644
--- a/nomenclature/validation.py
+++ b/nomenclature/validation.py
@@ -1,5 +1,5 @@
import logging
-from pyam import to_list
+from pyam import IamDataFrame, to_list
# define logger for this script at logging level INFO
logger = logging.getLogger(__name__)
@@ -19,6 +19,9 @@ def is_subset(x, y):
def validate(nc, df):
"""Validation of an IamDataFrame against codelists of a Nomenclature"""
+ if not isinstance(df, IamDataFrame):
+ df = IamDataFrame(df)
+
error = False
# combined validation of variables and units
@@ -58,3 +61,5 @@ def validate(nc, df):
if error:
raise ValueError("The validation failed. Please check the log for details.")
+
+ return True
| IAMconsortium/nomenclature | 979ce2aeb281396110ab2a08ed734cf075fca8b6 | diff --git a/tests/test_core.py b/tests/test_core.py
new file mode 100644
index 0000000..58e5d9c
--- /dev/null
+++ b/tests/test_core.py
@@ -0,0 +1,8 @@
+import pytest
+import nomenclature as nc
+
+
+def test_nonexisting_path_raises():
+ """Check that initializing a Nomenclature with a non-existing path raises"""
+ with pytest.raises(NotADirectoryError, match="Definitions directory not found: foo"):
+ nc.Nomenclature("foo")
| Relative definition of path in Nomenclature
The relative definition of the `path` variable in the `__init__` of `Nomenclature` `def __init__(self, path="definitions")` can lead to problems when the workflow where it is used is not started from the parent directory of `definitions`.
One possible fix would be to remove the default and require it to be set explicitly in every workflow in the following pattern:
`Nomenclature(Path(__file__).absolute().parent / "definitions").validate(df)`
Another fix would be checking if the directory specified in `path` actually exists and throw an error if it doesn't. Might also be a usecase for pydantic as it specifies an `FilePath` datatype which does this validation automatically (https://pydantic-docs.helpmanual.io/usage/types/#pydantic-types) | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_core.py::test_nonexisting_path_raises"
] | [] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
} | "2021-06-29T09:08:32Z" | apache-2.0 |
|
IAMconsortium__pyam-697 | diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md
index 1f98daf..757e2f8 100644
--- a/RELEASE_NOTES.md
+++ b/RELEASE_NOTES.md
@@ -2,6 +2,7 @@
## Individual updates
+- [#697](https://github.com/IAMconsortium/pyam/pull/697) Add warning if IIASA API returns empty result
- [#695](https://github.com/IAMconsortium/pyam/pull/695) Remove unused meta levels during initialization
- [#688](https://github.com/IAMconsortium/pyam/pull/688) Remove ixmp as optional dependency
- [#684](https://github.com/IAMconsortium/pyam/pull/684) Use new IIASA-manager API with token refresh
diff --git a/pyam/iiasa.py b/pyam/iiasa.py
index d26ea75..f8d83af 100644
--- a/pyam/iiasa.py
+++ b/pyam/iiasa.py
@@ -2,6 +2,7 @@ from pathlib import Path
import json
import logging
import requests
+from fnmatch import fnmatch
import httpx
import jwt
@@ -251,21 +252,15 @@ class Connection(object):
"""Currently connected resource (database API connection)"""
return self._connected
- def index(self, default=True):
- """Return the index of models and scenarios in the connected resource
-
- Parameters
- ----------
- default : bool, optional
- If `True`, return *only* the default version of a model/scenario.
- Any model/scenario without a default version is omitted.
- If `False`, returns all versions.
- """
- cols = ["version"] if default else ["version", "is_default"]
- return self._query_index(default)[META_IDX + cols].set_index(META_IDX)
+ @property
+ def meta_columns(self):
+ """Return the list of meta indicators in the connected resource"""
+ url = "/".join([self._base_url, "metadata/types"])
+ r = requests.get(url, headers=self.auth())
+ _check_response(r)
+ return pd.read_json(r.text, orient="records")["name"]
- @lru_cache()
- def _query_index(self, default=True, meta=False):
+ def _query_index(self, default=True, meta=False, cols=[], **kwargs):
# TODO: at present this reads in all data for all scenarios,
# it could be sped up in the future to try to query a subset
_default = "true" if default else "false"
@@ -275,18 +270,39 @@ class Connection(object):
r = requests.get(url, headers=self.auth())
_check_response(r)
- # cast response to dataframe and return
- return pd.read_json(r.text, orient="records")
+ # cast response to dataframe, apply filter by kwargs, and return
+ runs = pd.read_json(r.text, orient="records")
+ if runs.empty:
+ logger.warning("No permission to view model(s) or no scenarios exist.")
+ return pd.DataFrame([], columns=META_IDX + ["version", "run_id"] + cols)
- @property
- def meta_columns(self):
- """Return the list of meta indicators in the connected resource"""
- url = "/".join([self._base_url, "metadata/types"])
- r = requests.get(url, headers=self.auth())
- _check_response(r)
- return pd.read_json(r.text, orient="records")["name"]
+ if kwargs:
+ keep = np.ones(len(runs), dtype=bool)
+ for key, values in kwargs.items():
+ if key not in META_IDX + ["version"]:
+ raise ValueError(f"Invalid filter: '{key}'")
+ keep_col = pd.Series([fnmatch(v, values) for v in runs[key].values])
+ keep = np.logical_and(keep, keep_col)
+ return runs[keep]
+ else:
+ return runs
- def meta(self, default=True, **kwargs):
+ def index(self, default=True, **kwargs):
+ """Return the index of models and scenarios
+
+ Parameters
+ ----------
+ default : bool, optional
+ If `True`, return *only* the default version of a model/scenario.
+ Any model/scenario without a default version is omitted.
+ If `False`, returns all versions.
+ kwargs
+ Arguments to filer by *model* and *scenario*, `*` can be used as wildcard
+ """
+ cols = ["version"] if default else ["version", "is_default"]
+ return self._query_index(default, **kwargs)[META_IDX + cols].set_index(META_IDX)
+
+ def meta(self, default=True, run_id=False, **kwargs):
"""Return categories and indicators (meta) of scenarios
Parameters
@@ -295,27 +311,25 @@ class Connection(object):
Return *only* the default version of each scenario.
Any (`model`, `scenario`) without a default version is omitted.
If `False`, return all versions.
+ run_id : bool, optional
+ Include "run id" column
+ kwargs
+ Arguments to filer by *model* and *scenario*, `*` can be used as wildcard
"""
- df = self._query_index(default, meta=True)
+ df = self._query_index(default, meta=True, **kwargs)
cols = ["version"] if default else ["version", "is_default"]
- if kwargs:
- if kwargs.get("run_id", False):
- cols.append("run_id")
+ if run_id:
+ cols.append("run_id")
- # catching an issue where the query above does not yield any scenarios
- if df.empty:
- logger.warning("No permission to view model(s) or they do not exist.")
- meta = pd.DataFrame([], columns=META_IDX + cols)
- else:
- meta = df[META_IDX + cols]
- if df.metadata.any():
- extra_meta = pd.DataFrame.from_records(df.metadata)
- meta = pd.concat([meta, extra_meta], axis=1)
+ meta = df[META_IDX + cols]
+ if not meta.empty and df.metadata.any():
+ extra_meta = pd.DataFrame.from_records(df.metadata)
+ meta = pd.concat([meta, extra_meta], axis=1)
return meta.set_index(META_IDX + ([] if default else ["version"]))
- def properties(self, default=True):
+ def properties(self, default=True, **kwargs):
"""Return the audit properties of scenarios
Parameters
@@ -324,17 +338,17 @@ class Connection(object):
Return *only* the default version of each scenario.
Any (`model`, `scenario`) without a default version is omitted.
If :obj:`False`, return all versions.
+ kwargs
+ Arguments to filer by *model* and *scenario*, `*` can be used as wildcard
"""
- _df = self._query_index(default, meta=True)
audit_cols = ["cre_user", "cre_date", "upd_user", "upd_date"]
- audit_mapping = dict([(i, i.replace("_", "ate_")) for i in audit_cols])
other_cols = ["version"] if default else ["version", "is_default"]
+ cols = audit_cols + other_cols
- return (
- _df[META_IDX + other_cols + audit_cols]
- .set_index(META_IDX)
- .rename(columns=audit_mapping)
- )
+ _df = self._query_index(default, meta=True, cols=cols, **kwargs)
+ audit_mapping = dict([(i, i.replace("_", "ate_")) for i in audit_cols])
+
+ return _df.set_index(META_IDX).rename(columns=audit_mapping)
def models(self):
"""List all models in the connected resource"""
@@ -504,6 +518,10 @@ class Connection(object):
else:
_meta = self._query_index(default=default).set_index(META_IDX)
+ # return nothing if no data exists at all
+ if _meta.empty:
+ return
+
# retrieve data
_args = json.dumps(self._query_post(_meta, default=default, **kwargs))
url = "/".join([self._base_url, "runs/bulk/ts"])
| IAMconsortium/pyam | 7f00c7951f5aae42238461506572163adb0697e2 | diff --git a/tests/test_iiasa.py b/tests/test_iiasa.py
index 8478e09..727e643 100644
--- a/tests/test_iiasa.py
+++ b/tests/test_iiasa.py
@@ -167,39 +167,71 @@ def test_meta_columns(conn):
npt.assert_array_equal(conn.meta_columns, META_COLS)
[email protected]("kwargs", [{}, dict(model="model_a")])
@pytest.mark.parametrize("default", [True, False])
-def test_index(conn, default):
+def test_index(conn, kwargs, default):
# test that connection returns the correct index
+ obs = conn.index(default=default, **kwargs)
+
if default:
exp = META_DF.loc[META_DF.is_default, ["version"]]
+ if kwargs:
+ exp = exp.iloc[0:2]
else:
exp = META_DF[VERSION_COLS]
+ if kwargs:
+ exp = exp.iloc[0:3]
+
+ pdt.assert_frame_equal(obs, exp, check_dtype=False)
+
+
+def test_index_empty(conn):
+ # test that an empty filter does not yield an error
+ # solves https://github.com/IAMconsortium/pyam/issues/676
+ conn.index(model="foo").empty
+
- pdt.assert_frame_equal(conn.index(default=default), exp, check_dtype=False)
+def test_index_illegal_column(conn):
+ # test that filtering by an illegal column raises an error
+ with pytest.raises(ValueError, match="Invalid filter: 'foo'"):
+ conn.index(foo="bar")
[email protected]("kwargs", [{}, dict(model="model_a")])
@pytest.mark.parametrize("default", [True, False])
-def test_meta(conn, default):
+def test_meta(conn, kwargs, default):
# test that connection returns the correct meta dataframe
+ obs = conn.meta(default=default, **kwargs)
+
v = "version"
if default:
exp = META_DF.loc[META_DF.is_default, [v] + META_COLS]
+ if kwargs:
+ exp = exp.iloc[0:2]
else:
exp = META_DF[VERSION_COLS + META_COLS].set_index(v, append=True)
+ if kwargs:
+ exp = exp.iloc[0:3]
- pdt.assert_frame_equal(conn.meta(default=default), exp, check_dtype=False)
+ pdt.assert_frame_equal(obs, exp, check_dtype=False)
[email protected]("kwargs", [{}, dict(model="model_a")])
@pytest.mark.parametrize("default", [True, False])
-def test_properties(conn, default):
+def test_properties(conn, kwargs, default):
# test that connection returns the correct properties dataframe
- obs = conn.properties(default=default)
+ obs = conn.properties(default, **kwargs)
+
if default:
exp_cols = ["version"]
exp = META_DF.loc[META_DF.is_default, exp_cols]
+ if kwargs:
+ exp = exp.iloc[0:2]
else:
exp_cols = VERSION_COLS
exp = META_DF[exp_cols]
+ if kwargs:
+ exp = exp.iloc[0:3]
# assert that the expected audit columns are included
for col in ["create_user", "create_date", "update_user", "update_date"]:
| Unexpected failures with incorrect permissions in the IIASA database system
When a user has access to a Scenario Explorer database instance but no permission to view any models (or no scenarios exist), querying data from the API fails with an error similar to
```
if nmissing == len(indexer):
if use_interval_msg:
key = list(key)
raise KeyError(f"None of [{key}] are in the [{axis_name}]")
E KeyError: "None of [Index(['model', 'scenario', 'version', 'is_default', 'run_id'], dtype='object')] are in the [columns]"
```
The pyam.iiasa module should check that a response exists before casting to an **IamDataFrame**. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_iiasa.py::test_index[True-kwargs1]",
"tests/test_iiasa.py::test_index[False-kwargs1]",
"tests/test_iiasa.py::test_index_empty",
"tests/test_iiasa.py::test_index_illegal_column",
"tests/test_iiasa.py::test_meta[True-kwargs1]",
"tests/test_iiasa.py::test_meta[False-kwargs1]",
"tests/test_iiasa.py::test_properties[True-kwargs1]",
"tests/test_iiasa.py::test_properties[False-kwargs1]"
] | [
"tests/test_iiasa.py::test_unknown_conn",
"tests/test_iiasa.py::test_valid_connections",
"tests/test_iiasa.py::test_anon_conn",
"tests/test_iiasa.py::test_conn_nonexisting_creds_file",
"tests/test_iiasa.py::test_conn_invalid_creds_file[creds0-Credentials",
"tests/test_iiasa.py::test_conn_invalid_creds_file[creds1-Unknown",
"tests/test_iiasa.py::test_conn_cleartext_creds_raises",
"tests/test_iiasa.py::test_variables",
"tests/test_iiasa.py::test_regions",
"tests/test_iiasa.py::test_regions_with_synonyms",
"tests/test_iiasa.py::test_regions_empty_response",
"tests/test_iiasa.py::test_regions_no_synonyms_response",
"tests/test_iiasa.py::test_regions_with_synonyms_response",
"tests/test_iiasa.py::test_meta_columns",
"tests/test_iiasa.py::test_index[True-kwargs0]",
"tests/test_iiasa.py::test_index[False-kwargs0]",
"tests/test_iiasa.py::test_meta[True-kwargs0]",
"tests/test_iiasa.py::test_meta[False-kwargs0]",
"tests/test_iiasa.py::test_properties[True-kwargs0]",
"tests/test_iiasa.py::test_properties[False-kwargs0]",
"tests/test_iiasa.py::test_query_year[kwargs0]",
"tests/test_iiasa.py::test_query_year[kwargs1]",
"tests/test_iiasa.py::test_query_year[kwargs2]",
"tests/test_iiasa.py::test_query_with_subannual[kwargs0]",
"tests/test_iiasa.py::test_query_with_subannual[kwargs1]",
"tests/test_iiasa.py::test_query_with_subannual[kwargs2]",
"tests/test_iiasa.py::test_query_with_meta_false[kwargs0]",
"tests/test_iiasa.py::test_query_with_meta_false[kwargs1]",
"tests/test_iiasa.py::test_query_with_meta_false[kwargs2]",
"tests/test_iiasa.py::test_query_non_default",
"tests/test_iiasa.py::test_query_empty_response"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
} | "2022-08-31T13:12:38Z" | apache-2.0 |
|
ICB-DCM__pyABC-295 | diff --git a/pyabc/acceptor/acceptor.py b/pyabc/acceptor/acceptor.py
index cc8ca36..3c6acac 100644
--- a/pyabc/acceptor/acceptor.py
+++ b/pyabc/acceptor/acceptor.py
@@ -19,7 +19,7 @@ import pandas as pd
from typing import Callable
import logging
-from ..distance import Distance, SCALE_LIN
+from ..distance import Distance, SCALE_LIN, StochasticKernel
from ..epsilon import Epsilon
from ..parameters import Parameter
from .pdf_norm import pdf_norm_max_found
@@ -354,7 +354,8 @@ class StochasticAcceptor(Acceptor):
usually only for testing purposes.
log_file: str, optional
A log file for storing data of the acceptor that are currently not
- saved in the database. The data are saved in json format.
+ saved in the database. The data are saved in json format and can
+ be retrieved via `pyabc.storage.load_dict_from_json`.
"""
super().__init__()
@@ -376,7 +377,7 @@ class StochasticAcceptor(Acceptor):
self,
t: int,
get_weighted_distances: Callable[[], pd.DataFrame],
- distance_function: Distance,
+ distance_function: StochasticKernel,
x_0: dict):
"""
Initialize temperature and maximum pdf.
@@ -430,7 +431,9 @@ class StochasticAcceptor(Acceptor):
kernel_scale=self.kernel_scale, # TODO Refactor
)
- def __call__(self, distance_function, eps, x, x_0, t, par):
+ def __call__(self,
+ distance_function: StochasticKernel,
+ eps, x, x_0, t, par):
# rename
kernel = distance_function
@@ -438,15 +441,15 @@ class StochasticAcceptor(Acceptor):
temp = eps(t)
# compute probability density
- pd = kernel(x, x_0, t, par)
+ density = kernel(x, x_0, t, par)
pdf_norm = self.pdf_norms[t]
# compute acceptance probability
if kernel.ret_scale == SCALE_LIN:
- acc_prob = (pd / pdf_norm) ** (1 / temp)
+ acc_prob = (density / pdf_norm) ** (1 / temp)
else: # kernel.ret_scale == SCALE_LOG
- acc_prob = np.exp((pd - pdf_norm) * (1 / temp))
+ acc_prob = np.exp((density - pdf_norm) * (1 / temp))
# accept
threshold = np.random.uniform(low=0, high=1)
@@ -464,10 +467,10 @@ class StochasticAcceptor(Acceptor):
weight = 1.0
# check pdf max ok
- if pdf_norm < pd:
+ if pdf_norm < density:
logger.debug(
- f"Encountered pd={pd:.4e} > c={pdf_norm:.4e}, "
+ f"Encountered density={density:.4e} > c={pdf_norm:.4e}, "
f"thus weight={weight:.4e}.")
# return unscaled density value and the acceptance flag
- return AcceptorResult(pd, accept, weight)
+ return AcceptorResult(density, accept, weight)
diff --git a/pyabc/distance/distance.py b/pyabc/distance/distance.py
index 992a2f6..2471e61 100644
--- a/pyabc/distance/distance.py
+++ b/pyabc/distance/distance.py
@@ -6,6 +6,7 @@ import logging
from ..sampler import Sampler
from .scale import standard_deviation, span
from .base import Distance, to_distance
+from ..storage import save_dict_to_json
logger = logging.getLogger("Distance")
@@ -141,32 +142,37 @@ class AdaptivePNormDistance(PNormDistance):
Parameters
----------
- p: float, optional (default = 2)
+ p:
p for p-norm. Required p >= 1, p = np.inf allowed (infinity-norm).
- initial_weights: dict, optional
+ Default: p=2.
+ initial_weights:
Weights to be used in the initial iteration. Dictionary with
observables as keys and weights as values.
- factors: dict, optional
+ factors:
As in PNormDistance.
- adaptive: bool, optional (default = True)
+ adaptive:
True: Adapt distance after each iteration.
False: Adapt distance only once at the beginning in initialize().
This corresponds to a pre-calibration.
- scale_function: Callable, optional (default = standard_deviation)
+ scale_function:
(data: list, x_0: float) -> scale: float. Computes the scale (i.e.
inverse weight s = 1 / w) for a given summary statistic. Here, data
denotes the list of simulated summary statistics, and x_0 the observed
summary statistic. Implemented are absolute_median_deviation,
standard_deviation (default), centered_absolute_median_deviation,
centered_standard_deviation.
- normalize_weights: bool, optional (default = True)
+ normalize_weights:
Whether to normalize the weights to have mean 1. This just possibly
smoothes the decrease of epsilon and might aid numeric stability, but
is not strictly necessary.
- max_weight_ratio: float, optional (default = None)
+ max_weight_ratio:
If not None, large weights will be bounded by the ratio times the
smallest non-zero absolute weight. In practice usually not necessary,
it is theoretically required to ensure convergence.
+ log_file:
+ A log file to store weights for each time point in. Weights are
+ currently not stored in the database. The data are saved in json
+ format and can be retrieved via `pyabc.storage.load_dict_from_json`.
.. [#prangle] Prangle, Dennis. "Adapting the ABC Distance Function".
@@ -178,9 +184,10 @@ class AdaptivePNormDistance(PNormDistance):
initial_weights: dict = None,
factors: dict = None,
adaptive: bool = True,
- scale_function=None,
+ scale_function: Callable = None,
normalize_weights: bool = True,
- max_weight_ratio: float = None):
+ max_weight_ratio: float = None,
+ log_file: str = None):
# call p-norm constructor
super().__init__(p=p, weights=None, factors=factors)
@@ -194,6 +201,7 @@ class AdaptivePNormDistance(PNormDistance):
self.normalize_weights = normalize_weights
self.max_weight_ratio = max_weight_ratio
+ self.log_file = log_file
self.x_0 = None
@@ -294,7 +302,7 @@ class AdaptivePNormDistance(PNormDistance):
self.weights[t] = w
# logging
- logger.debug(f"updated weights[{t}] = {self.weights[t]}")
+ self.log(t)
def _normalize_weights(self, w):
"""
@@ -346,6 +354,12 @@ class AdaptivePNormDistance(PNormDistance):
"normalize_weights": self.normalize_weights,
"max_weight_ratio": self.max_weight_ratio}
+ def log(self, t: int) -> None:
+ logger.debug(f"updated weights[{t}] = {self.weights[t]}")
+
+ if self.log_file:
+ save_dict_to_json(self.weights, self.log_file)
+
class AggregatedDistance(Distance):
"""
@@ -383,6 +397,8 @@ class AggregatedDistance(Distance):
can remain static while weights adapt over time, allowing for
greater flexibility.
"""
+ super().__init__()
+
if not isinstance(distances, list):
distances = [distances]
self.distances = [to_distance(distance) for distance in distances]
@@ -440,7 +456,7 @@ class AggregatedDistance(Distance):
self.format_weights_and_factors(t)
weights = AggregatedDistance.get_for_t_or_latest(self.weights, t)
factors = AggregatedDistance.get_for_t_or_latest(self.factors, t)
- return np.dot(weights * factors, values)
+ return float(np.dot(weights * factors, values))
def get_config(self) -> dict:
"""
@@ -495,23 +511,26 @@ class AdaptiveAggregatedDistance(AggregatedDistance):
Parameters
----------
-
- distances: List[Distance]
+ distances:
As in AggregatedDistance.
- initial_weights: list, optional
+ initial_weights:
Weights to be used in the initial iteration. List with
a weight for each distance function.
- factors: Union[List, dict]
+ factors:
As in AggregatedDistance.
- adaptive: bool, optional (default = True)
+ adaptive:
True: Adapt weights after each iteration.
False: Adapt weights only once at the beginning in initialize().
This corresponds to a pre-calibration.
- scale_function: Callable, optional (default = scale_span)
+ scale_function:
Function that takes a list of floats, namely the values obtained
by applying one of the distances passed to a set of samples,
and returns a single float, namely the weight to apply to this
- distance function.
+ distance function. Default: scale_span.
+ log_file:
+ A log file to store weights for each time point in. Weights are
+ currently not stored in the database. The data are saved in json
+ format and can be retrieved via `pyabc.storage.load_dict_from_json`.
"""
def __init__(
@@ -520,7 +539,8 @@ class AdaptiveAggregatedDistance(AggregatedDistance):
initial_weights: List = None,
factors: Union[List, dict] = None,
adaptive: bool = True,
- scale_function: Callable = None):
+ scale_function: Callable = None,
+ log_file: str = None):
super().__init__(distances=distances)
self.initial_weights = initial_weights
self.factors = factors
@@ -529,6 +549,7 @@ class AdaptiveAggregatedDistance(AggregatedDistance):
if scale_function is None:
scale_function = span
self.scale_function = scale_function
+ self.log_file = log_file
def initialize(self,
t: int,
@@ -599,8 +620,14 @@ class AdaptiveAggregatedDistance(AggregatedDistance):
self.weights[t] = np.array(w)
# logging
+ self.log(t)
+
+ def log(self, t: int) -> None:
logger.debug(f"updated weights[{t}] = {self.weights[t]}")
+ if self.log_file:
+ save_dict_to_json(self.weights, self.log_file)
+
class DistanceWithMeasureList(Distance):
"""
| ICB-DCM/pyABC | 45369a69df3fbb982529f5b2188e64783efe613a | diff --git a/test/test_distance_function.py b/test/test_distance_function.py
index e40c2fc..ef95c37 100644
--- a/test/test_distance_function.py
+++ b/test/test_distance_function.py
@@ -1,5 +1,8 @@
import numpy as np
import scipy as sp
+import scipy.stats
+import tempfile
+
from pyabc.distance import (
PercentileDistance,
MinMaxDistance,
@@ -27,6 +30,7 @@ from pyabc.distance import (
mean,
median,
SCALE_LIN,)
+from pyabc.storage import load_dict_from_json
class MockABC:
@@ -405,3 +409,31 @@ def test_negativebinomialkernel():
expected = np.sum(sp.stats.nbinom.logpmf(
k=[4, 5, 8], n=[7, 7, 7], p=[0.9, 0.8, 0.7]))
assert np.isclose(ret, expected)
+
+
+def test_store_weights():
+ """Test whether storing distance weights works."""
+ abc = MockABC([{'s1': -1, 's2': -1, 's3': -1},
+ {'s1': -1, 's2': 0, 's3': 1}])
+ x_0 = {'s1': 0, 's2': 0, 's3': 1}
+
+ weights_file = tempfile.mkstemp(suffix=".json")[1]
+ print(weights_file)
+
+ def distance0(x, x_0):
+ return abs(x['s0'] - x_0['s0'])
+
+ def distance1(x, x_0):
+ return np.sqrt((x['s1'] - x_0['s1'])**2)
+
+ for distance in [AdaptivePNormDistance(log_file=weights_file),
+ AdaptiveAggregatedDistance(
+ [distance0, distance1], log_file=weights_file)]:
+ distance = AdaptivePNormDistance(log_file=weights_file)
+ distance.initialize(0, abc.sample_from_prior, x_0=x_0)
+ distance.update(1, abc.sample_from_prior)
+ distance.update(2, abc.sample_from_prior)
+
+ weights = load_dict_from_json(weights_file)
+ assert set(weights.keys()) == {0, 1, 2}
+ assert weights == distance.weights
| Log distance weights
Until the near future, the distance weights will not be stored in the history due to legacy reasons. Thus, it may be good to add a callback function which is called after each update method.
Sidenote: Always possible by creating a SubClass, or, to some degree, using the `logging.getLogger("Distance")` logger. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/test_distance_function.py::test_store_weights"
] | [
"test/test_distance_function.py::test_single_parameter",
"test/test_distance_function.py::test_two_parameters_but_only_one_used",
"test/test_distance_function.py::test_two_parameters_and_two_used",
"test/test_distance_function.py::test_single_parameter_percentile",
"test/test_distance_function.py::test_pnormdistance",
"test/test_distance_function.py::test_adaptivepnormdistance",
"test/test_distance_function.py::test_adaptivepnormdistance_initial_weights",
"test/test_distance_function.py::test_aggregateddistance",
"test/test_distance_function.py::test_adaptiveaggregateddistance",
"test/test_distance_function.py::test_adaptiveaggregateddistance_calibration",
"test/test_distance_function.py::test_normalkernel",
"test/test_distance_function.py::test_independentnormalkernel",
"test/test_distance_function.py::test_independentlaplacekernel",
"test/test_distance_function.py::test_binomialkernel",
"test/test_distance_function.py::test_poissonkernel",
"test/test_distance_function.py::test_negativebinomialkernel"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2020-05-07T22:33:57Z" | bsd-3-clause |
|
ICB-DCM__pyABC-367 | diff --git a/.github/workflows/ci_push.yml b/.github/workflows/ci_push.yml
index 52bc7d5..635cb1d 100644
--- a/.github/workflows/ci_push.yml
+++ b/.github/workflows/ci_push.yml
@@ -8,7 +8,7 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
- python-version: [3.8]
+ python-version: [3.8, 3.7]
steps:
- name: Check out repository
@@ -47,7 +47,7 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
- python-version: [3.8]
+ python-version: [3.8, 3.7]
steps:
- name: Check out repository
@@ -85,7 +85,7 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
- python-version: [3.8]
+ python-version: [3.8, 3.7]
steps:
- name: Check out repository
@@ -123,7 +123,7 @@ jobs:
runs-on: macos-latest
strategy:
matrix:
- python-version: [3.8]
+ python-version: [3.8, 3.7]
steps:
- name: Check out repository
@@ -147,7 +147,7 @@ jobs:
pip install -e .[test]
- name: Run tests
- timeout-minutes: 3
+ timeout-minutes: 4
run: |
python -m pytest --cov=pyabc --cov-report=xml test/base/test_macos.py
@@ -184,7 +184,7 @@ jobs:
pip install -e .[quality]
- name: Run flake8
- timeout-minutes: 1
+ timeout-minutes: 2
run: ./run_flake8.sh
- name: Run pyroma
diff --git a/pyabc/sampler/mapping.py b/pyabc/sampler/mapping.py
index 6db46ad..92c49de 100644
--- a/pyabc/sampler/mapping.py
+++ b/pyabc/sampler/mapping.py
@@ -1,7 +1,7 @@
import functools
import random
-import dill as pickle
+import cloudpickle as pickle
import numpy as np
from .base import Sampler
diff --git a/setup.cfg b/setup.cfg
index 9b7e0e3..c14d398 100644
--- a/setup.cfg
+++ b/setup.cfg
@@ -53,7 +53,6 @@ install_requires =
flask >= 1.1.2
bokeh >= 2.1.1
redis >= 2.10.6
- dill >= 0.3.2
gitpython >= 3.1.7
scikit-learn >= 0.23.1
matplotlib >= 3.3.0
@@ -77,7 +76,7 @@ packages = find:
[options.extras_require]
R =
- rpy2 >= 3.2.0
+ rpy2 >= 3.3.6
cffi >= 1.13.1
petab =
petab >= 0.1.8
| ICB-DCM/pyABC | 70e669604c57e4f0a9d4bfad441aefcae4c3266a | diff --git a/test/base/test_transition.py b/test/base/test_transition.py
index 2aad858..c0632c7 100644
--- a/test/base/test_transition.py
+++ b/test/base/test_transition.py
@@ -265,16 +265,16 @@ def test_discrete_jump_transition():
def freq(weight):
return p_stay * weight + p_move * (1 - weight)
- assert 0 < sum(res.a == 5) / n_sample <= p_move + 0.05
- assert freq(0.45) < sum(res.a == 4) / n_sample < freq(0.55)
- assert freq(0.15) < sum(res.a == 2.5) / n_sample < freq(0.25)
- assert freq(0.25) < sum(res.a == 0.5) / n_sample < freq(0.35)
+ assert 0 < sum(res.a == 5) / n_sample <= p_move + 0.1
+ assert freq(0.4) < sum(res.a == 4) / n_sample < freq(0.6)
+ assert freq(0.1) < sum(res.a == 2.5) / n_sample < freq(0.3)
+ assert freq(0.2) < sum(res.a == 0.5) / n_sample < freq(0.4)
# test density calculation
- assert np.isclose(trans.pdf(pd.Series({'a': 5})), freq(0.))
- assert np.isclose(trans.pdf(pd.Series({'a': 4})), freq(0.5))
- assert np.isclose(trans.pdf(pd.Series({'a': 2.5})), freq(0.2))
- assert np.isclose(trans.pdf(pd.Series({'a': 0.5})), freq(0.3))
+ assert abs(trans.pdf(pd.Series({'a': 5})) - freq(0.)) < 1e-3
+ assert abs(trans.pdf(pd.Series({'a': 4})) - freq(0.5)) < 1e-3
+ assert abs(trans.pdf(pd.Series({'a': 2.5})) - freq(0.2)) < 1e-3
+ assert abs(trans.pdf(pd.Series({'a': 0.5})) - freq(0.3)) < 1e-3
def test_discrete_jump_transition_errors():
| Cloudpickle >=1.5.0 breaks on python<=3.7
TBD what changed in 1.5.0 https://github.com/cloudpipe/cloudpickle
Also, add a base test on legacy python versions as these are still quite popular. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/base/test_transition.py::test_rvs_return_type[LocalTransition]",
"test/base/test_transition.py::test_rvs_return_type[MultivariateNormalTransition]",
"test/base/test_transition.py::test_rvs_return_type[SimpleAggregatedTransition]",
"test/base/test_transition.py::test_rvs_return_type[SimpleAggregatedTransition2]",
"test/base/test_transition.py::test_pdf_return_types[LocalTransition]",
"test/base/test_transition.py::test_pdf_return_types[MultivariateNormalTransition]",
"test/base/test_transition.py::test_pdf_return_types[SimpleAggregatedTransition]",
"test/base/test_transition.py::test_pdf_return_types[SimpleAggregatedTransition2]",
"test/base/test_transition.py::test_many_particles_single_par[LocalTransition]",
"test/base/test_transition.py::test_many_particles_single_par[MultivariateNormalTransition]",
"test/base/test_transition.py::test_many_particles_single_par[SimpleAggregatedTransitionSingle]",
"test/base/test_transition.py::test_variance_estimate[LocalTransition]",
"test/base/test_transition.py::test_variance_estimate[MultivariateNormalTransition]",
"test/base/test_transition.py::test_variance_estimate[SimpleAggregatedTransition]",
"test/base/test_transition.py::test_variance_estimate[SimpleAggregatedTransition2]",
"test/base/test_transition.py::test_variance_estimate_higher_n_than_sample[LocalTransition]",
"test/base/test_transition.py::test_variance_estimate_higher_n_than_sample[MultivariateNormalTransition]",
"test/base/test_transition.py::test_variance_estimate_higher_n_than_sample[SimpleAggregatedTransition]",
"test/base/test_transition.py::test_variance_estimate_higher_n_than_sample[SimpleAggregatedTransition2]",
"test/base/test_transition.py::test_variance_no_side_effect[LocalTransition]",
"test/base/test_transition.py::test_variance_no_side_effect[MultivariateNormalTransition]",
"test/base/test_transition.py::test_variance_no_side_effect[SimpleAggregatedTransition]",
"test/base/test_transition.py::test_variance_no_side_effect[SimpleAggregatedTransition2]",
"test/base/test_transition.py::test_particles_no_parameters[LocalTransition]",
"test/base/test_transition.py::test_particles_no_parameters[MultivariateNormalTransition]",
"test/base/test_transition.py::test_particles_no_parameters[SimpleAggregatedTransition]",
"test/base/test_transition.py::test_particles_no_parameters[SimpleAggregatedTransition2]",
"test/base/test_transition.py::test_empty[LocalTransition]",
"test/base/test_transition.py::test_empty[MultivariateNormalTransition]",
"test/base/test_transition.py::test_empty[SimpleAggregatedTransition]",
"test/base/test_transition.py::test_empty[SimpleAggregatedTransition2]",
"test/base/test_transition.py::test_0_particles_fit[LocalTransition]",
"test/base/test_transition.py::test_0_particles_fit[MultivariateNormalTransition]",
"test/base/test_transition.py::test_0_particles_fit[SimpleAggregatedTransition]",
"test/base/test_transition.py::test_0_particles_fit[SimpleAggregatedTransition2]",
"test/base/test_transition.py::test_single_particle_fit[LocalTransition]",
"test/base/test_transition.py::test_single_particle_fit[MultivariateNormalTransition]",
"test/base/test_transition.py::test_single_particle_fit[SimpleAggregatedTransition]",
"test/base/test_transition.py::test_single_particle_fit[SimpleAggregatedTransition2]",
"test/base/test_transition.py::test_single_particle_required_nr_samples[LocalTransition]",
"test/base/test_transition.py::test_single_particle_required_nr_samples[MultivariateNormalTransition]",
"test/base/test_transition.py::test_single_particle_required_nr_samples[SimpleAggregatedTransition]",
"test/base/test_transition.py::test_single_particle_required_nr_samples[SimpleAggregatedTransition2]",
"test/base/test_transition.py::test_two_particles_fit[LocalTransition]",
"test/base/test_transition.py::test_two_particles_fit[MultivariateNormalTransition]",
"test/base/test_transition.py::test_two_particles_fit[SimpleAggregatedTransition]",
"test/base/test_transition.py::test_two_particles_fit[SimpleAggregatedTransition2]",
"test/base/test_transition.py::test_two_particles_required_nr_samples[LocalTransition]",
"test/base/test_transition.py::test_two_particles_required_nr_samples[MultivariateNormalTransition]",
"test/base/test_transition.py::test_two_particles_required_nr_samples[SimpleAggregatedTransition]",
"test/base/test_transition.py::test_two_particles_required_nr_samples[SimpleAggregatedTransition2]",
"test/base/test_transition.py::test_many_particles[LocalTransition]",
"test/base/test_transition.py::test_many_particles[MultivariateNormalTransition]",
"test/base/test_transition.py::test_many_particles[SimpleAggregatedTransition]",
"test/base/test_transition.py::test_many_particles[SimpleAggregatedTransition2]",
"test/base/test_transition.py::test_argument_order[LocalTransition]",
"test/base/test_transition.py::test_argument_order[MultivariateNormalTransition]",
"test/base/test_transition.py::test_argument_order[SimpleAggregatedTransition]",
"test/base/test_transition.py::test_argument_order[SimpleAggregatedTransition2]",
"test/base/test_transition.py::test_score[LocalTransition]",
"test/base/test_transition.py::test_score[MultivariateNormalTransition]",
"test/base/test_transition.py::test_score[SimpleAggregatedTransition]",
"test/base/test_transition.py::test_score[SimpleAggregatedTransition2]",
"test/base/test_transition.py::test_grid_search_multivariate_normal",
"test/base/test_transition.py::test_grid_search_two_samples_multivariate_normal",
"test/base/test_transition.py::test_grid_search_single_sample_multivariate_normal",
"test/base/test_transition.py::test_mean_coefficient_of_variation_sample_not_full_rank[LocalTransition]",
"test/base/test_transition.py::test_mean_coefficient_of_variation_sample_not_full_rank[MultivariateNormalTransition]",
"test/base/test_transition.py::test_mean_coefficient_of_variation_sample_not_full_rank[SimpleAggregatedTransition]",
"test/base/test_transition.py::test_mean_coefficient_of_variation_sample_not_full_rank[SimpleAggregatedTransition2]",
"test/base/test_transition.py::test_discrete_jump_transition",
"test/base/test_transition.py::test_discrete_jump_transition_errors"
] | [] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2020-11-27T21:44:03Z" | bsd-3-clause |
|
ICB-DCM__pyPESTO-658 | diff --git a/pypesto/problem.py b/pypesto/problem.py
index d43693f..445a0bc 100644
--- a/pypesto/problem.py
+++ b/pypesto/problem.py
@@ -200,10 +200,11 @@ class Problem:
raise AssertionError(f"{attr} dimension invalid.")
if self.x_guesses_full.shape[1] != self.dim_full:
- x_guesses = np.empty((self.x_guesses_full.shape[0], self.dim_full))
- x_guesses[:] = np.nan
- x_guesses[:, self.x_free_indices] = self.x_guesses_full
- self.x_guesses_full = x_guesses
+ x_guesses_full = \
+ np.empty((self.x_guesses_full.shape[0], self.dim_full))
+ x_guesses_full[:] = np.nan
+ x_guesses_full[:, self.x_free_indices] = self.x_guesses_full
+ self.x_guesses_full = x_guesses_full
# make objective aware of fixed parameters
self.objective.update_from_problem(
@@ -228,6 +229,21 @@ class Problem:
if np.any(self.lb >= self.ub):
raise ValueError('lb<ub not fulfilled.')
+ def set_x_guesses(self,
+ x_guesses: Iterable[float]):
+ """
+ Sets the x_guesses of a problem.
+
+ Parameters
+ ----------
+ x_guesses:
+ """
+ x_guesses_full = np.array(x_guesses)
+ if x_guesses_full.shape[1] != self.dim_full:
+ raise ValueError('The dimension of individual x_guesses must be '
+ 'dim_full.')
+ self.x_guesses_full = x_guesses_full
+
def fix_parameters(self,
parameter_indices: SupportsIntIterableOrValue,
parameter_vals: SupportsFloatIterableOrValue) -> None:
diff --git a/pypesto/profile/__init__.py b/pypesto/profile/__init__.py
index 6d86290..be0d118 100644
--- a/pypesto/profile/__init__.py
+++ b/pypesto/profile/__init__.py
@@ -11,6 +11,8 @@ from .options import (
ProfileOptions)
from .result import (
ProfilerResult)
+from .validation_intervals import (
+ validation_profile_significance)
from .util import (
chi2_quantile_to_ratio,
calculate_approximate_ci)
diff --git a/pypesto/profile/validation_intervals.py b/pypesto/profile/validation_intervals.py
new file mode 100644
index 0000000..15de409
--- /dev/null
+++ b/pypesto/profile/validation_intervals.py
@@ -0,0 +1,137 @@
+"""Validation intervals."""
+
+import logging
+from typing import Optional
+from copy import deepcopy
+
+from ..engine import Engine
+from ..optimize import Optimizer, minimize
+from ..problem import Problem
+from ..result import Result
+from scipy.stats import chi2
+
+
+logger = logging.getLogger(__name__)
+
+
+def validation_profile_significance(
+ problem_full_data: Problem,
+ result_training_data: Result,
+ result_full_data: Optional[Result] = None,
+ n_starts: Optional[int] = 1,
+ optimizer: Optional[Optimizer] = None,
+ engine: Optional[Engine] = None,
+ lsq_objective: bool = False,
+ return_significance: bool = True,
+) -> float:
+ """
+ A Validation Interval for significance alpha is a confidence region/
+ interval for a new validation experiment. [#Kreutz]_ et al.
+ (This method per default returns the significance = 1-alpha!)
+
+ The reasoning behind their approach is, that a validation data set
+ is outside the validation interval, if fitting the full data set
+ would lead to a fit $\theta_{new}$, that does not contain the old
+ fit $\theta_{train}$ in their (Profile-Likelihood) based
+ parameter-confidence intervals. (I.e. the old fit would be rejected by
+ the fit of the full data.)
+
+ This method returns the significance of the validation data set (where
+ `result_full_data` is the objective function for fitting both data sets).
+ I.e. the largest alpha, such that there is a validation region/interval
+ such that the validation data set lies outside this Validation
+ Interval with probability alpha. (If one is interested in the opposite,
+ set `return_significance=False`.)
+
+ Parameters
+ ----------
+ problem_full_data:
+ pypesto.problem, such that the objective is the
+ negative-log-likelihood of the training and validation data set.
+
+ result_training_data:
+ result object from the fitting of the training data set only.
+
+ result_full_data
+ pypesto.result object that contains the result of fitting
+ training and validation data combined.
+
+ n_starts
+ number of starts for fitting the full data set
+ (if result_full_data is not provided).
+
+ optimizer:
+ optimizer used for refitting the data (if result_full_data is not
+ provided).
+
+ engine
+ engine for refitting (if result_full_data is not provided).
+
+ lsq_objective:
+ indicates if the objective of problem_full_data corresponds to a nllh
+ (False), or a chi^2 value (True).
+ return_significance:
+ indicates, if the function should return the significance (True) (i.e.
+ the probability, that the new data set lies outside the Confidence
+ Interval for the validation experiment, as given by the method), or
+ the largest alpha, such that the validation experiment still lies
+ within the Confidence Interval (False). I.e. alpha = 1-significance.
+
+
+ .. [#Kreutz] Kreutz, Clemens, Raue, Andreas and Timmer, Jens.
+ βLikelihood based observability analysis and
+ confidence intervals for predictions of dynamic modelsβ.
+ BMC Systems Biology 2012/12.
+ doi:10.1186/1752-0509-6-120
+
+ """
+
+ if (result_full_data is not None) and (optimizer is not None):
+ raise UserWarning("optimizer will not be used, as a result object "
+ "for the full data set is provided.")
+
+ # if result for full data is not provided: minimize
+ if result_full_data is None:
+
+ x_0 = result_training_data.optimize_result.get_for_key('x')
+
+ # copy problem, in order to not change/overwrite x_guesses
+ problem = deepcopy(problem_full_data)
+ problem.set_x_guesses(x_0)
+
+ result_full_data = minimize(problem=problem,
+ optimizer=optimizer,
+ n_starts=n_starts,
+ engine=engine)
+
+ # Validation intervals compare the nllh value on the full data set
+ # of the parameter fits from the training and the full data set.
+
+ nllh_new = \
+ result_full_data.optimize_result.get_for_key('fval')[0]
+ nllh_old = \
+ problem_full_data.objective(
+ problem_full_data.get_reduced_vector(
+ result_training_data.optimize_result.get_for_key('x')[0]))
+
+ if nllh_new > nllh_old:
+ logger.warning("Fitting of the full data set provided a worse fit "
+ "than the fit only considering the training data. "
+ "Consider rerunning the not handing over "
+ "result_full_data or running the fitting from the "
+ "best parameters found from the training data.")
+
+ # compute the probability, that the validation data set is outside the CI
+ # => survival function chi.sf
+ if return_significance:
+ if lsq_objective:
+ return chi2.sf(nllh_new-nllh_old, 1)
+ else:
+ return chi2.sf(2*(nllh_new-nllh_old), 1)
+ # compute the probability, that the validation data set is inside the CI
+ # => cumulative density function chi.cdf
+ else:
+ if lsq_objective:
+ return chi2.cdf(nllh_new-nllh_old, 1)
+ else:
+ return chi2.cdf(2*(nllh_new-nllh_old), 1)
| ICB-DCM/pyPESTO | 69e834d8df4863becac9d92edfc6d70bf45df28b | diff --git a/test/profile/test_validation_intervals.py b/test/profile/test_validation_intervals.py
new file mode 100644
index 0000000..623153c
--- /dev/null
+++ b/test/profile/test_validation_intervals.py
@@ -0,0 +1,64 @@
+"""
+This is for testing profile based validation intervals.
+"""
+
+import numpy as np
+import unittest
+
+
+import pypesto
+import pypesto.optimize as optimize
+import pypesto.profile as profile
+
+
+class ValidationIntervalTest(unittest.TestCase):
+
+ @classmethod
+ def setUp(cls):
+
+ lb = np.array([-1])
+ ub = np.array([5])
+
+ cls.problem_training_data = pypesto.Problem(
+ lsq_residual_objective(0),
+ lb, ub)
+
+ cls.problem_all_data = pypesto.Problem(
+ pypesto.objective.AggregatedObjective(
+ [lsq_residual_objective(0),
+ lsq_residual_objective(2)]),
+ lb, ub)
+
+ # optimum f(0)=0
+ cls.result_training_data = optimize.minimize(cls.problem_training_data,
+ n_starts=5)
+ # Optimum f(1)=2
+ cls.result_all_data = optimize.minimize(cls.problem_all_data,
+ n_starts=5)
+
+ def test_validation_intervals(self):
+ """Test validation profiles."""
+
+ # fit with handing over all data
+ profile.validation_profile_significance(self.problem_all_data,
+ self.result_training_data,
+ self.result_all_data)
+
+ # fit with refitting inside function
+ profile.validation_profile_significance(self.problem_all_data,
+ self.result_training_data)
+
+
+def lsq_residual_objective(d: float):
+ """
+ Returns an objective for the function
+
+ f(x) = (x-d)^2
+ """
+ def f(x):
+ return np.sum((x[0]-d)**2)
+
+ def grad(x):
+ return 2 * (x-d)
+
+ return pypesto.Objective(fun=f, grad=grad)
| Prediction profiles
At some point in the more or less near future, we will want to have prediction profiles in pyPESTO. Pretty much of the parameter profiling code could be reused, I think/hope... | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/profile/test_validation_intervals.py::ValidationIntervalTest::test_validation_intervals"
] | [] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_added_files",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2021-05-07T12:28:41Z" | bsd-3-clause |
|
ICB-DCM__pyPESTO-676 | diff --git a/pypesto/profile/validation_intervals.py b/pypesto/profile/validation_intervals.py
index 15de409..c60a437 100644
--- a/pypesto/profile/validation_intervals.py
+++ b/pypesto/profile/validation_intervals.py
@@ -125,13 +125,13 @@ def validation_profile_significance(
# => survival function chi.sf
if return_significance:
if lsq_objective:
- return chi2.sf(nllh_new-nllh_old, 1)
+ return chi2.sf(nllh_old-nllh_new, 1)
else:
- return chi2.sf(2*(nllh_new-nllh_old), 1)
+ return chi2.sf(2*(nllh_old-nllh_new), 1)
# compute the probability, that the validation data set is inside the CI
# => cumulative density function chi.cdf
else:
if lsq_objective:
- return chi2.cdf(nllh_new-nllh_old, 1)
+ return chi2.cdf(nllh_old-nllh_new, 1)
else:
- return chi2.cdf(2*(nllh_new-nllh_old), 1)
+ return chi2.cdf(2*(nllh_old-nllh_new), 1)
| ICB-DCM/pyPESTO | 5cce409f5c053ed257329f74c31f050bfcfe938c | diff --git a/test/profile/test_validation_intervals.py b/test/profile/test_validation_intervals.py
index 623153c..a129b19 100644
--- a/test/profile/test_validation_intervals.py
+++ b/test/profile/test_validation_intervals.py
@@ -16,18 +16,18 @@ class ValidationIntervalTest(unittest.TestCase):
@classmethod
def setUp(cls):
- lb = np.array([-1])
- ub = np.array([5])
+ cls.lb = np.array([-1])
+ cls.ub = np.array([5])
cls.problem_training_data = pypesto.Problem(
lsq_residual_objective(0),
- lb, ub)
+ cls.lb, cls.ub)
cls.problem_all_data = pypesto.Problem(
pypesto.objective.AggregatedObjective(
[lsq_residual_objective(0),
lsq_residual_objective(2)]),
- lb, ub)
+ cls.lb, cls.ub)
# optimum f(0)=0
cls.result_training_data = optimize.minimize(cls.problem_training_data,
@@ -45,8 +45,58 @@ class ValidationIntervalTest(unittest.TestCase):
self.result_all_data)
# fit with refitting inside function
- profile.validation_profile_significance(self.problem_all_data,
- self.result_training_data)
+ res_with_significance_true = profile.validation_profile_significance(
+ self.problem_all_data,
+ self.result_training_data)
+
+ # test return_significance = False leads the result to 1-significance
+ res_with_significance_false = profile.validation_profile_significance(
+ self.problem_all_data,
+ self.result_training_data,
+ return_significance=False)
+
+ self.assertAlmostEqual(1-res_with_significance_true,
+ res_with_significance_false,
+ places=4)
+
+ # test if significance=1, if the validation experiment coincides with
+ # the Max Likelihood prediction
+
+ problem_val = pypesto.Problem(pypesto.objective.AggregatedObjective(
+ [lsq_residual_objective(0),
+ lsq_residual_objective(0)]),
+ self.lb, self.ub)
+
+ significance = profile.validation_profile_significance(
+ problem_val,
+ self.result_training_data)
+
+ self.assertAlmostEqual(significance, 1)
+
+ # Test if the significance approaches zero (monotonously decreasing)
+ # if the discrepancy between Max. Likelihood prediction and observed
+ # validation interval is increased
+
+ for d_val in [0.1, 1, 10, 100]:
+
+ # problem including d_val
+ problem_val = pypesto.Problem(
+ pypesto.objective.AggregatedObjective(
+ [lsq_residual_objective(0),
+ lsq_residual_objective(d_val)]),
+ self.lb, self.ub)
+
+ sig_d_val = profile.validation_profile_significance(
+ problem_val,
+ self.result_training_data)
+
+ # test, if the more extreme measurement leads to a more
+ # significant result
+ self.assertLessEqual(sig_d_val, significance)
+ significance = sig_d_val
+
+ # test if the significance approaches 0 for d_val=100
+ self.assertAlmostEqual(significance, 0)
def lsq_residual_objective(d: float):
| Add more tests to validation intervals
**Feature description**
It would be nice to check, if the prediction for `x_opt` leads to the significance `1` and if the significance approaches zero for larger and larger deviations. (I had some problems with that for one application of mine, but I would not exclude that the issue there is outside pyPESTO)
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/profile/test_validation_intervals.py::ValidationIntervalTest::test_validation_intervals"
] | [] | {
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
} | "2021-05-25T13:56:38Z" | bsd-3-clause |
|
INCATools__ontology-access-kit-183 | diff --git a/src/__init__.py b/src/__init__.py
deleted file mode 100644
index e69de29b..00000000
diff --git a/src/oaklib/cli.py b/src/oaklib/cli.py
index 1f3b0fc5..f92e7dd5 100644
--- a/src/oaklib/cli.py
+++ b/src/oaklib/cli.py
@@ -2354,10 +2354,25 @@ def apply_obsolete(output, output_type, terms):
show_default=True,
help="If true, then all sources are in the main input ontology",
)
[email protected](
+ "--add-labels/--no-add-labels",
+ default=False,
+ show_default=True,
+ help="Populate empty labels with URI fragments or CURIE local IDs, for ontologies that use semantic IDs",
+)
+@predicates_option
@output_option
@output_type_option
def diff_via_mappings(
- source, mapping_input, intra, other_input, other_input_type, output_type, output
+ source,
+ mapping_input,
+ intra,
+ add_labels,
+ other_input,
+ other_input_type,
+ predicates,
+ output_type,
+ output,
):
"""
Calculates a relational diff between ontologies in two sources using the combined mappings
@@ -2388,8 +2403,22 @@ def diff_via_mappings(
else:
mappings = None
logging.info("Mappings will be derived from ontologies")
+ if source:
+ sources = list(source)
+ if len(sources) == 1:
+ raise ValueError(
+ f"If --source is specified, must pass more than one. You specified: {sources}"
+ )
+ else:
+ sources = None
+ actual_predicates = _process_predicates_arg(predicates)
for r in calculate_pairwise_relational_diff(
- oi, other_oi, sources=list(source), mappings=mappings
+ oi,
+ other_oi,
+ sources=sources,
+ mappings=mappings,
+ add_labels=add_labels,
+ predicates=actual_predicates,
):
writer.emit(r)
diff --git a/src/oaklib/utilities/label_utilities.py b/src/oaklib/utilities/label_utilities.py
new file mode 100644
index 00000000..1aae84b8
--- /dev/null
+++ b/src/oaklib/utilities/label_utilities.py
@@ -0,0 +1,27 @@
+from typing import List, Tuple, Union
+
+from linkml_runtime.linkml_model import SlotDefinitionName
+from linkml_runtime.utils.yamlutils import YAMLRoot
+
+from oaklib import BasicOntologyInterface
+
+
+def add_labels_to_object(
+ oi: BasicOntologyInterface,
+ obj: YAMLRoot,
+ pairs: List[Tuple[Union[SlotDefinitionName, str], Union[SlotDefinitionName, str]]],
+) -> None:
+ """
+ Adds labels to an object, for a set of id-label relation pairs
+
+ :param oi: an ontology interface for making label lookups
+ :param obj: object to be filled
+ :param pairs: list of slot name pairs
+ :return: None
+ """
+ for curie_slot, label_slot in pairs:
+ curie = getattr(obj, curie_slot, None)
+ if curie is not None:
+ label = oi.get_label_by_curie(curie)
+ if label is not None:
+ setattr(obj, label_slot, label)
diff --git a/src/oaklib/utilities/mapping/cross_ontology_diffs.py b/src/oaklib/utilities/mapping/cross_ontology_diffs.py
index 1cbc3c5e..dfe93bca 100644
--- a/src/oaklib/utilities/mapping/cross_ontology_diffs.py
+++ b/src/oaklib/utilities/mapping/cross_ontology_diffs.py
@@ -16,6 +16,7 @@ from oaklib.interfaces import MappingProviderInterface, RelationGraphInterface
from oaklib.interfaces.obograph_interface import OboGraphInterface
from oaklib.types import CURIE, PRED_CURIE
from oaklib.utilities.graph.networkx_bridge import mappings_to_graph
+from oaklib.utilities.label_utilities import add_labels_to_object
ONE_TO_ZERO = MappingCardinalityEnum(MappingCardinalityEnum["1:0"])
ONE_TO_MANY = MappingCardinalityEnum(MappingCardinalityEnum["1:n"])
@@ -77,6 +78,8 @@ def calculate_pairwise_relational_diff(
right_oi: MappingProviderInterface,
sources: List[str],
mappings: Optional[List[Mapping]] = None,
+ predicates: Optional[List[PRED_CURIE]] = None,
+ add_labels=False,
) -> Iterator[RelationalDiff]:
"""
Calculates a relational diff between ontologies in two sources using the combined mappings
@@ -97,12 +100,42 @@ def calculate_pairwise_relational_diff(
g = mappings_to_graph(mappings)
if isinstance(left_oi, OboGraphInterface) and isinstance(right_oi, OboGraphInterface):
for subject_child in left_oi.all_entity_curies():
+ if not curie_has_prefix(subject_child, sources):
+ continue
for pred, subject_parent in relation_dict_as_tuples(
left_oi.get_outgoing_relationship_map_by_curie(subject_child)
):
+ if predicates and pred not in predicates:
+ continue
+ if not curie_has_prefix(subject_parent, sources):
+ continue
for r in calculate_pairwise_relational_diff_for_edge(
- left_oi, right_oi, sources, g, subject_child, pred, subject_parent
+ left_oi,
+ right_oi,
+ sources,
+ g,
+ subject_child,
+ pred,
+ subject_parent,
+ predicates=predicates,
):
+ if add_labels:
+ add_labels_to_object(
+ left_oi,
+ r,
+ [
+ ("left_subject_id", "left_subject_label"),
+ ("left_object_id", "left_object_label"),
+ ],
+ )
+ add_labels_to_object(
+ right_oi,
+ r,
+ [
+ ("right_subject_id", "right_subject_label"),
+ ("right_object_id", "right_object_label"),
+ ],
+ )
yield r
else:
raise NotImplementedError
@@ -157,6 +190,7 @@ def calculate_pairwise_relational_diff_for_edge(
candidates: List[RelationalDiff] = []
for right_subject in right_subject_list:
right_subject_ancs = list(right_oi.ancestors(right_subject, predicates=predicates))
+ # logging.debug(f"RIGHT: {right_subject} // ANCS[{predicates}] = {right_subject_ancs}")
right_subject_parents = []
right_subject_direct_outgoing = defaultdict(list)
for p, o in right_oi.get_outgoing_relationships(right_subject):
| INCATools/ontology-access-kit | 98812ee4d1046f10938704b303d870a3ecf77b75 | diff --git a/tests/test_utilities/test_cross_ontology_diff.py b/tests/test_utilities/test_cross_ontology_diff.py
index 33a3e800..09ace3de 100644
--- a/tests/test_utilities/test_cross_ontology_diff.py
+++ b/tests/test_utilities/test_cross_ontology_diff.py
@@ -4,6 +4,7 @@ import yaml
from linkml_runtime.dumpers import yaml_dumper
from oaklib.datamodels.cross_ontology_diff import RelationalDiff
+from oaklib.datamodels.vocabulary import IS_A, PART_OF
from oaklib.implementations.pronto.pronto_implementation import ProntoImplementation
from oaklib.implementations.sparql.sparql_implementation import SparqlImplementation
from oaklib.resource import OntologyResource
@@ -36,3 +37,25 @@ class TestStructuralDiff(unittest.TestCase):
results = list(calculate_pairwise_relational_diff(oi, oi, ["X", "Y", "Z"]))
yaml_dumper.dump(results, str(TEST_OUT))
self.assertCountEqual(expected_results, results)
+
+ def test_structural_diff_with_preds(self):
+ expected_results = yaml.safe_load(open(EXPECTED))
+ expected_results = [RelationalDiff(**obj) for obj in expected_results]
+ for oi in [self.oi, self.owl_oi]:
+ results = list(
+ calculate_pairwise_relational_diff(
+ oi, oi, ["X", "Y", "Z"], predicates=[IS_A, PART_OF]
+ )
+ )
+ yaml_dumper.dump(results, str(TEST_OUT))
+ self.assertCountEqual(expected_results, results)
+ results = list(
+ calculate_pairwise_relational_diff(oi, oi, ["X", "Y", "Z"], predicates=[PART_OF])
+ )
+ # print(yaml_dumper.dumps(results))
+ self.assertEqual(2, len(results))
+
+ def test_restrict_to_sources(self):
+ for oi in [self.oi, self.owl_oi]:
+ results = list(calculate_pairwise_relational_diff(oi, oi, ["Z"]))
+ self.assertEqual([], results)
| --verbose option no longer working
Previously `-v` logged at INFO level, `-vv` at debug, but now this has stopped working | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_utilities/test_cross_ontology_diff.py::TestStructuralDiff::test_restrict_to_sources",
"tests/test_utilities/test_cross_ontology_diff.py::TestStructuralDiff::test_structural_diff_with_preds"
] | [
"tests/test_utilities/test_cross_ontology_diff.py::TestStructuralDiff::test_structural_diff"
] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2022-07-12T02:45:06Z" | apache-2.0 |
|
INM-6__python-odmltables-120 | diff --git a/odmltables/odml_table.py b/odmltables/odml_table.py
index 7ac58aa..f6bf460 100644
--- a/odmltables/odml_table.py
+++ b/odmltables/odml_table.py
@@ -399,6 +399,8 @@ class OdmlTable(object):
# create a inverted header_titles dictionary for an inverted lookup
inv_header_titles = {v: k for (k, v) in list(self._header_titles.items())}
+ row_id = None
+
with open(load_from, 'r') as csvfile:
csvreader = csv.reader(csvfile)
@@ -489,10 +491,11 @@ class OdmlTable(object):
current_dic = new_dic
# copy final property
- if row_id == 0:
- self._odmldict.append(copy.deepcopy(new_dic))
- else:
- self._odmldict.append(copy.deepcopy(current_dic))
+ if not (row_id is None):
+ if row_id == 0:
+ self._odmldict.append(copy.deepcopy(new_dic))
+ else:
+ self._odmldict.append(copy.deepcopy(current_dic))
# value conversion for all properties
for current_dic in self._odmldict:
| INM-6/python-odmltables | f9787990e4865f222fb072e8c5c84f96a2bada6c | diff --git a/odmltables/tests/test_odml_csv_table.py b/odmltables/tests/test_odml_csv_table.py
index aee45c0..9d07022 100644
--- a/odmltables/tests/test_odml_csv_table.py
+++ b/odmltables/tests/test_odml_csv_table.py
@@ -76,6 +76,22 @@ class TestOdmlCsvTable(unittest.TestCase):
self.assertEqual(len(table._odmldict), 1)
self.assertDictEqual(table._odmldict[0], table2._odmldict[0])
+ def test_saveload_empty_header(self):
+ doc = odml.Document()
+
+ table = OdmlCsvTable()
+ table.load_from_odmldoc(doc)
+ table.change_header('full')
+ table.write2file(self.filename)
+
+ table2 = OdmlTable()
+ table2.load_from_csv_table(self.filename)
+
+ # comparing values which are written to xls by default
+ self.assertEqual(table._odmldict, [])
+ self.assertDictEqual({'author': None, 'date': None, 'repository': None, 'version': None},
+ table._docdict)
+
class TestShowallOdmlCsvTable(unittest.TestCase):
"""
diff --git a/odmltables/tests/test_odml_xls_table.py b/odmltables/tests/test_odml_xls_table.py
index 2998882..b386a1d 100644
--- a/odmltables/tests/test_odml_xls_table.py
+++ b/odmltables/tests/test_odml_xls_table.py
@@ -232,6 +232,22 @@ class TestOdmlXlsTable(unittest.TestCase):
self.assertEqual(len(table._odmldict), 1)
self.assertDictEqual(table._odmldict[0], table2._odmldict[0])
+ def test_saveload_empty_header(self):
+ doc = odml.Document()
+
+ table = OdmlXlsTable()
+ table.load_from_odmldoc(doc)
+ table.change_header('full')
+ table.write2file(self.filename)
+
+ table2 = OdmlTable()
+ table2.load_from_xls_table(self.filename)
+
+ # comparing values which are written to xls by default
+ self.assertEqual(table._odmldict, [])
+ self.assertDictEqual({'author': None, 'date': None, 'repository': None, 'version': None},
+ table._docdict)
+
class TestShowallOdmlXlsTable(unittest.TestCase):
"""
| Error when converting empty (apart from header) csv file
'row_id' is undefined here when the csv file only contains a header:
https://github.com/INM-6/python-odmltables/blob/f9787990e4865f222fb072e8c5c84f96a2bada6c/odmltables/odml_table.py#L492 | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"odmltables/tests/test_odml_csv_table.py::TestOdmlCsvTable::test_saveload_empty_header"
] | [
"odmltables/tests/test_odml_xls_table.py::TestShowallOdmlXlsTable::test_tf",
"odmltables/tests/test_odml_xls_table.py::TestShowallOdmlXlsTable::test_ft",
"odmltables/tests/test_odml_xls_table.py::TestShowallOdmlXlsTable::test_tt",
"odmltables/tests/test_odml_xls_table.py::TestShowallOdmlXlsTable::test_ff",
"odmltables/tests/test_odml_xls_table.py::TestOdmlXlsTable::test_xls_datatypes",
"odmltables/tests/test_odml_xls_table.py::TestOdmlXlsTable::test_write_read",
"odmltables/tests/test_odml_xls_table.py::TestOdmlXlsTable::test_empty_rows",
"odmltables/tests/test_odml_xls_table.py::TestOdmlXlsTable::test_saveload_empty_header",
"odmltables/tests/test_odml_xls_table.py::TestOdmlXlsTable::test_saveload_empty_value",
"odmltables/tests/test_odml_xls_table.py::TestOdmlXlsTableAttributes::test_highlight_defaults",
"odmltables/tests/test_odml_xls_table.py::TestOdmlXlsTableAttributes::test_change_changingpoint",
"odmltables/tests/test_odml_xls_table.py::TestOdmlXlsTableAttributes::test_mark_columns",
"odmltables/tests/test_odml_xls_table.py::TestOdmlXlsTableAttributes::test_change_pattern",
"odmltables/tests/test_odml_csv_table.py::TestOdmlCsvTable::test_saveload_empty_value",
"odmltables/tests/test_odml_csv_table.py::TestOdmlCsvTable::test_empty_rows",
"odmltables/tests/test_odml_csv_table.py::TestShowallOdmlCsvTable::test_ft",
"odmltables/tests/test_odml_csv_table.py::TestShowallOdmlCsvTable::test_tt",
"odmltables/tests/test_odml_csv_table.py::TestShowallOdmlCsvTable::test_tf",
"odmltables/tests/test_odml_csv_table.py::TestShowallOdmlCsvTable::test_ff"
] | {
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false
} | "2020-12-11T08:57:12Z" | bsd-3-clause |
|
ImagingDataCommons__highdicom-211 | diff --git a/src/highdicom/content.py b/src/highdicom/content.py
index 844cdee..ddbed2a 100644
--- a/src/highdicom/content.py
+++ b/src/highdicom/content.py
@@ -1867,7 +1867,7 @@ class VOILUTTransformation(Dataset):
)
for exp in window_explanation:
_check_long_string(exp)
- self.WindowCenterWidthExplanation = window_explanation
+ self.WindowCenterWidthExplanation = list(window_explanation)
if voi_lut_function is not None:
if window_center is None:
raise TypeError(
diff --git a/src/highdicom/pr/content.py b/src/highdicom/pr/content.py
index b9d000b..48809dd 100644
--- a/src/highdicom/pr/content.py
+++ b/src/highdicom/pr/content.py
@@ -1397,16 +1397,29 @@ def _get_softcopy_voi_lut_transformations(
for frame_number, frm_grp in enumerate(perframe_grps, 1):
if hasattr(frm_grp, 'FrameVOILUTSequence'):
voi_seq = frm_grp.FrameVOILUTSequence[0]
+
# Create unique ID for this VOI lookup as a tuple
# of the contents
+ width = voi_seq.WindowWidth
+ center = voi_seq.WindowCenter
+ exp = getattr(
+ voi_seq,
+ 'WindowCenterWidthExplanation',
+ None
+ )
+
+ # MultiValues are not hashable so make into tuples
+ if isinstance(width, MultiValue):
+ width = tuple(width)
+ if isinstance(center, MultiValue):
+ center = tuple(center)
+ if isinstance(exp, MultiValue):
+ exp = tuple(exp)
+
by_window[(
- voi_seq.WindowWidth,
- voi_seq.WindowCenter,
- getattr(
- voi_seq,
- 'WindowCenterWidthExplanation',
- None
- ),
+ width,
+ center,
+ exp,
getattr(voi_seq, 'VOILUTFunction', None),
)].append(frame_number)
@@ -1455,10 +1468,20 @@ def _get_softcopy_voi_lut_transformations(
)
if has_width:
+ width = ref_im.WindowWidth
+ center = ref_im.WindowCenter
+ exp = getattr(ref_im, 'WindowCenterWidthExplanation', None)
+ # MultiValues are not hashable so make into tuples
+ if isinstance(width, MultiValue):
+ width = tuple(width)
+ if isinstance(center, MultiValue):
+ center = tuple(center)
+ if isinstance(exp, MultiValue):
+ exp = tuple(exp)
by_window[(
- ref_im.WindowWidth,
- ref_im.WindowCenter,
- getattr(ref_im, 'WindowCenterWidthExplanation', None),
+ width,
+ center,
+ exp,
getattr(ref_im, 'VOILUTFunction', None),
)].append(ref_im)
elif has_lut:
| ImagingDataCommons/highdicom | eea1f075a5bf5159e80b4cd16a9a19aa295b2719 | diff --git a/tests/test_pr.py b/tests/test_pr.py
index 8139f1b..b77007d 100644
--- a/tests/test_pr.py
+++ b/tests/test_pr.py
@@ -1348,6 +1348,73 @@ class TestXSoftcopyPresentationState(unittest.TestCase):
assert gsps.SoftcopyVOILUTSequence[1].WindowWidth == expected_width
assert gsps.SoftcopyVOILUTSequence[1].WindowCenter == expected_center
+ def test_construction_with_copy_voi_lut_multival(self):
+ new_series = []
+ widths = [40.0, 20.0]
+ centers = [400.0, 600.0]
+ for dcm in self._ct_series:
+ new_dcm = deepcopy(dcm)
+ new_dcm.WindowCenter = centers
+ new_dcm.WindowWidth = widths
+ new_series.append(new_dcm)
+ gsps = GrayscaleSoftcopyPresentationState(
+ referenced_images=new_series,
+ series_instance_uid=self._series_uid,
+ series_number=123,
+ sop_instance_uid=self._sop_uid,
+ instance_number=456,
+ manufacturer='Foo Corp.',
+ manufacturer_model_name='Bar, Mark 2',
+ software_versions='0.0.1',
+ device_serial_number='12345',
+ content_label='DOODLE',
+ graphic_layers=[self._layer],
+ graphic_annotations=[self._ann_ct],
+ concept_name=codes.DCM.PresentationState,
+ institution_name='MGH',
+ institutional_department_name='Radiology',
+ content_creator_name='Doe^John'
+ )
+ assert len(gsps.SoftcopyVOILUTSequence) == 1
+ assert gsps.SoftcopyVOILUTSequence[0].WindowWidth == widths
+ assert gsps.SoftcopyVOILUTSequence[0].WindowCenter == centers
+
+ def test_construction_with_copy_voi_lut_multival_with_expl(self):
+ new_series = []
+ widths = [40.0, 20.0]
+ centers = [400.0, 600.0]
+ exps = ['WINDOW1', 'WINDOW2']
+ for dcm in self._ct_series:
+ new_dcm = deepcopy(dcm)
+ new_dcm.WindowCenter = centers
+ new_dcm.WindowWidth = widths
+ new_dcm.WindowCenterWidthExplanation = exps
+ new_series.append(new_dcm)
+ gsps = GrayscaleSoftcopyPresentationState(
+ referenced_images=new_series,
+ series_instance_uid=self._series_uid,
+ series_number=123,
+ sop_instance_uid=self._sop_uid,
+ instance_number=456,
+ manufacturer='Foo Corp.',
+ manufacturer_model_name='Bar, Mark 2',
+ software_versions='0.0.1',
+ device_serial_number='12345',
+ content_label='DOODLE',
+ graphic_layers=[self._layer],
+ graphic_annotations=[self._ann_ct],
+ concept_name=codes.DCM.PresentationState,
+ institution_name='MGH',
+ institutional_department_name='Radiology',
+ content_creator_name='Doe^John'
+ )
+ assert len(gsps.SoftcopyVOILUTSequence) == 1
+ assert gsps.SoftcopyVOILUTSequence[0].WindowWidth == widths
+ assert gsps.SoftcopyVOILUTSequence[0].WindowCenter == centers
+ assert (
+ gsps.SoftcopyVOILUTSequence[0].WindowCenterWidthExplanation == exps
+ )
+
def test_construction_with_copy_voi_lut_empty(self):
file_path = Path(__file__)
data_dir = file_path.parent.parent.joinpath('data')
| Failure to create GSPS when reference DICOM uses "MultiValue" for WindowCenter, WindowWidth
When I go to create a GSPS using hd.pr.GrayscaleSoftcopyPresentationState() I get an error for certain DICOM where WindowWidth and WindowCenter are not floats in the reference DICOM.
Here's the error I get:
```
~/anaconda3/lib/python3.8/site-packages/highdicom/pr/content.py in _get_softcopy_voi_lut_transformations(referenced_images)
1456
1457 if has_width:
-> 1458 by_window[(
1459 ref_im.WindowWidth,
1460 ref_im.WindowCenter,
TypeError: unhashable type: 'MultiValue'
```
I fixed it using the following code:
``` Python
if isinstance(image_dataset.WindowWidth, pydicom.multival.MultiValue):
image_dataset.WindowWidth = image_dataset.WindowWidth[0]
if isinstance(image_dataset.WindowCenter, pydicom.multival.MultiValue):
image_dataset.WindowCenter = image_dataset.WindowCenter[0]
```
This fix worked for two offending DICOM, but there is one more where I'm still getting the error. To get rid of the error there, I created the GSPS with my own windowing settings (using the argument voi_lut_transformations=[SoftcopyVOILUTObject]). | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_pr.py::TestXSoftcopyPresentationState::test_construction_with_copy_voi_lut_multival",
"tests/test_pr.py::TestXSoftcopyPresentationState::test_construction_with_copy_voi_lut_multival_with_expl"
] | [
"tests/test_pr.py::TestSoftcopyVOILUTTransformation::test_construction_basic",
"tests/test_pr.py::TestSoftcopyVOILUTTransformation::test_construction_both",
"tests/test_pr.py::TestSoftcopyVOILUTTransformation::test_construction_explanation",
"tests/test_pr.py::TestSoftcopyVOILUTTransformation::test_construction_explanation_mismatch",
"tests/test_pr.py::TestSoftcopyVOILUTTransformation::test_construction_explanation_mismatch2",
"tests/test_pr.py::TestSoftcopyVOILUTTransformation::test_construction_lut_function",
"tests/test_pr.py::TestSoftcopyVOILUTTransformation::test_construction_luts",
"tests/test_pr.py::TestSoftcopyVOILUTTransformation::test_construction_multiple",
"tests/test_pr.py::TestSoftcopyVOILUTTransformation::test_construction_multiple_mismatch1",
"tests/test_pr.py::TestSoftcopyVOILUTTransformation::test_construction_multiple_mismatch2",
"tests/test_pr.py::TestSoftcopyVOILUTTransformation::test_construction_multiple_mismatch3",
"tests/test_pr.py::TestSoftcopyVOILUTTransformation::test_construction_neither",
"tests/test_pr.py::TestSoftcopyVOILUTTransformation::test_construction_ref_ims",
"tests/test_pr.py::TestGraphicObject::test_circle",
"tests/test_pr.py::TestGraphicObject::test_circle_wrong_number",
"tests/test_pr.py::TestGraphicObject::test_ellipse",
"tests/test_pr.py::TestGraphicObject::test_ellipse_wrong_number",
"tests/test_pr.py::TestGraphicObject::test_filled",
"tests/test_pr.py::TestGraphicObject::test_filled_invalid",
"tests/test_pr.py::TestGraphicObject::test_group_id",
"tests/test_pr.py::TestGraphicObject::test_interpolated",
"tests/test_pr.py::TestGraphicObject::test_point",
"tests/test_pr.py::TestGraphicObject::test_point_wrong_number",
"tests/test_pr.py::TestGraphicObject::test_polyline",
"tests/test_pr.py::TestGraphicObject::test_polyline_wrong_number",
"tests/test_pr.py::TestGraphicObject::test_tracking_ids",
"tests/test_pr.py::TestGraphicObject::test_tracking_ids_invalid",
"tests/test_pr.py::TestGraphicObject::test_units",
"tests/test_pr.py::TestGraphicObject::test_units_invalid",
"tests/test_pr.py::TestTextObject::test_anchor_point_invalid_values",
"tests/test_pr.py::TestTextObject::test_anchor_point_invalid_values_display",
"tests/test_pr.py::TestTextObject::test_anchor_point_wrong_number",
"tests/test_pr.py::TestTextObject::test_bounding_box",
"tests/test_pr.py::TestTextObject::test_bounding_box_br_invalid_for_tl",
"tests/test_pr.py::TestTextObject::test_bounding_box_invalid_values",
"tests/test_pr.py::TestTextObject::test_bounding_box_invalid_values_display",
"tests/test_pr.py::TestTextObject::test_bounding_box_wrong_number",
"tests/test_pr.py::TestTextObject::test_tracking_uids",
"tests/test_pr.py::TestTextObject::test_tracking_uids_only_one",
"tests/test_pr.py::TestGraphicAnnotation::test_construction_both",
"tests/test_pr.py::TestGraphicAnnotation::test_construction_frame_number",
"tests/test_pr.py::TestGraphicAnnotation::test_construction_frame_number_invalid",
"tests/test_pr.py::TestGraphicAnnotation::test_construction_frame_number_single_frame",
"tests/test_pr.py::TestGraphicAnnotation::test_construction_frame_numbers",
"tests/test_pr.py::TestGraphicAnnotation::test_construction_frame_numbers_invalid",
"tests/test_pr.py::TestGraphicAnnotation::test_construction_full_graphic_layer",
"tests/test_pr.py::TestGraphicAnnotation::test_construction_graphic",
"tests/test_pr.py::TestGraphicAnnotation::test_construction_invalid_use_of_matrix",
"tests/test_pr.py::TestGraphicAnnotation::test_construction_multiframe",
"tests/test_pr.py::TestGraphicAnnotation::test_construction_multiple_multiframe",
"tests/test_pr.py::TestGraphicAnnotation::test_construction_out_of_bounds_matrix",
"tests/test_pr.py::TestGraphicAnnotation::test_construction_out_of_bounds_pixel",
"tests/test_pr.py::TestGraphicAnnotation::test_construction_segment_number",
"tests/test_pr.py::TestGraphicAnnotation::test_construction_segment_number_invalid",
"tests/test_pr.py::TestGraphicAnnotation::test_construction_segment_number_single_segment",
"tests/test_pr.py::TestGraphicAnnotation::test_construction_segment_numbers",
"tests/test_pr.py::TestGraphicAnnotation::test_construction_segment_numbers_invalid",
"tests/test_pr.py::TestGraphicAnnotation::test_construction_text",
"tests/test_pr.py::TestAdvancedBlending::test_construction",
"tests/test_pr.py::TestBlendingDisplay::test_construction_equal",
"tests/test_pr.py::TestBlendingDisplay::test_construction_equal_wrong_blending_display_input_type",
"tests/test_pr.py::TestBlendingDisplay::test_construction_equal_wrong_blending_display_input_value",
"tests/test_pr.py::TestBlendingDisplay::test_construction_forebround",
"tests/test_pr.py::TestBlendingDisplay::test_construction_foreground_wrong_blending_display_input_value",
"tests/test_pr.py::TestBlendingDisplay::test_construction_foreground_wrong_relative_opacity_type",
"tests/test_pr.py::TestXSoftcopyPresentationState::test_construction",
"tests/test_pr.py::TestXSoftcopyPresentationState::test_construction_color",
"tests/test_pr.py::TestXSoftcopyPresentationState::test_construction_color_with_gray_images",
"tests/test_pr.py::TestXSoftcopyPresentationState::test_construction_creator_id",
"tests/test_pr.py::TestXSoftcopyPresentationState::test_construction_gray_with_color_images",
"tests/test_pr.py::TestXSoftcopyPresentationState::test_construction_icc_profile",
"tests/test_pr.py::TestXSoftcopyPresentationState::test_construction_palette_color_lut_transformation",
"tests/test_pr.py::TestXSoftcopyPresentationState::test_construction_with_copy_modality_lut",
"tests/test_pr.py::TestXSoftcopyPresentationState::test_construction_with_copy_modality_lut_multiframe",
"tests/test_pr.py::TestXSoftcopyPresentationState::test_construction_with_copy_voi_lut",
"tests/test_pr.py::TestXSoftcopyPresentationState::test_construction_with_copy_voi_lut_data",
"tests/test_pr.py::TestXSoftcopyPresentationState::test_construction_with_copy_voi_lut_different",
"tests/test_pr.py::TestXSoftcopyPresentationState::test_construction_with_copy_voi_lut_empty",
"tests/test_pr.py::TestXSoftcopyPresentationState::test_construction_with_copy_voi_lut_multiframe",
"tests/test_pr.py::TestXSoftcopyPresentationState::test_construction_with_copy_voi_lut_multiframe_perframe",
"tests/test_pr.py::TestXSoftcopyPresentationState::test_construction_with_duplicate_group",
"tests/test_pr.py::TestXSoftcopyPresentationState::test_construction_with_duplicate_layers",
"tests/test_pr.py::TestXSoftcopyPresentationState::test_construction_with_group",
"tests/test_pr.py::TestXSoftcopyPresentationState::test_construction_with_group_missing",
"tests/test_pr.py::TestXSoftcopyPresentationState::test_construction_with_images_missing",
"tests/test_pr.py::TestXSoftcopyPresentationState::test_construction_with_missing_layer",
"tests/test_pr.py::TestXSoftcopyPresentationState::test_construction_with_modality_lut",
"tests/test_pr.py::TestXSoftcopyPresentationState::test_construction_with_modality_rescale",
"tests/test_pr.py::TestXSoftcopyPresentationState::test_construction_with_multiple_voi_luts_with_no_ref_ims",
"tests/test_pr.py::TestXSoftcopyPresentationState::test_construction_with_presentation_both",
"tests/test_pr.py::TestXSoftcopyPresentationState::test_construction_with_presentation_lut",
"tests/test_pr.py::TestXSoftcopyPresentationState::test_construction_with_presentation_lut_shape",
"tests/test_pr.py::TestXSoftcopyPresentationState::test_construction_with_softcopy_voi_lut_with_duplicate_frames",
"tests/test_pr.py::TestXSoftcopyPresentationState::test_construction_with_softcopy_voi_lut_with_duplicate_frames_2",
"tests/test_pr.py::TestXSoftcopyPresentationState::test_construction_with_softcopy_voi_lut_with_duplicate_segments",
"tests/test_pr.py::TestXSoftcopyPresentationState::test_construction_with_softcopy_voi_lut_with_duplicate_segments_2",
"tests/test_pr.py::TestXSoftcopyPresentationState::test_construction_with_softcopy_voi_lut_with_ref_frames",
"tests/test_pr.py::TestXSoftcopyPresentationState::test_construction_with_softcopy_voi_lut_with_ref_segments",
"tests/test_pr.py::TestXSoftcopyPresentationState::test_construction_with_voi_lut",
"tests/test_pr.py::TestXSoftcopyPresentationState::test_construction_with_voi_lut_missing_references",
"tests/test_pr.py::TestXSoftcopyPresentationState::test_construction_with_voi_lut_two_vois_for_image",
"tests/test_pr.py::TestXSoftcopyPresentationState::test_construction_with_voi_lut_with_ref_ims"
] | {
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2022-12-28T18:49:28Z" | mit |
|
ImagingDataCommons__highdicom-226 | diff --git a/src/highdicom/sr/coding.py b/src/highdicom/sr/coding.py
index d4305b6..3301e86 100644
--- a/src/highdicom/sr/coding.py
+++ b/src/highdicom/sr/coding.py
@@ -126,7 +126,14 @@ class CodedConcept(Dataset):
raise TypeError(
'Dataset must be a pydicom.dataset.Dataset.'
)
- for kw in ['CodeValue', 'CodeMeaning', 'CodingSchemeDesignator']:
+ code_value_kws = ['CodeValue', 'LongCodeValue', 'URNCodeValue']
+ num_code_values = sum(hasattr(dataset, kw) for kw in code_value_kws)
+ if num_code_values != 1:
+ raise AttributeError(
+ 'Dataset should have exactly one of the following attributes: '
+ f'{", ".join(code_value_kws)}.'
+ )
+ for kw in ['CodeMeaning', 'CodingSchemeDesignator']:
if not hasattr(dataset, kw):
raise AttributeError(
'Dataset does not contain the following attribute '
| ImagingDataCommons/highdicom | 5cb05291d59378919de3c53f9c315f38c51121ce | diff --git a/tests/test_sr.py b/tests/test_sr.py
index e1ccb7c..d4b94aa 100644
--- a/tests/test_sr.py
+++ b/tests/test_sr.py
@@ -444,6 +444,12 @@ class TestCodedConcept(unittest.TestCase):
def setUp(self):
super().setUp()
self._value = '373098007'
+ self._long_code_value = 'some_code_value_longer_than_sixteen_chars'
+ self._urn_code_value = (
+ 'https://browser.ihtsdotools.org/?perspective=full&conceptId1='
+ '373098007&edition=MAIN/SNOMEDCT-US/2023-03-01&release=&languages='
+ 'en'
+ )
self._meaning = 'Mean Value of population'
self._scheme_designator = 'SCT'
@@ -506,6 +512,81 @@ class TestCodedConcept(unittest.TestCase):
assert c.CodeMeaning == self._meaning
assert c.CodingSchemeVersion == version
+ def test_long_code_value(self):
+ version = 'v1.0'
+ c = CodedConcept(
+ self._long_code_value,
+ self._scheme_designator,
+ self._meaning,
+ version,
+ )
+ assert c.value == self._long_code_value
+ assert c.scheme_designator == self._scheme_designator
+ assert c.meaning == self._meaning
+ assert c.scheme_version == version
+ assert c.LongCodeValue == self._long_code_value
+ assert not hasattr(c, 'CodeValue')
+ assert c.CodingSchemeDesignator == self._scheme_designator
+ assert c.CodeMeaning == self._meaning
+ assert c.CodingSchemeVersion == version
+
+ def test_urn_code_value(self):
+ version = 'v1.0'
+ c = CodedConcept(
+ self._urn_code_value,
+ self._scheme_designator,
+ self._meaning,
+ version,
+ )
+ assert c.value == self._urn_code_value
+ assert c.scheme_designator == self._scheme_designator
+ assert c.meaning == self._meaning
+ assert c.scheme_version == version
+ assert c.URNCodeValue == self._urn_code_value
+ assert not hasattr(c, 'CodeValue')
+ assert c.CodingSchemeDesignator == self._scheme_designator
+ assert c.CodeMeaning == self._meaning
+ assert c.CodingSchemeVersion == version
+
+ def test_from_dataset(self):
+ ds = Dataset()
+ ds.CodeValue = self._value
+ ds.CodeMeaning = self._meaning
+ ds.CodingSchemeDesignator = self._scheme_designator
+ c = CodedConcept.from_dataset(ds)
+ assert c.value == self._value
+ assert c.scheme_designator == self._scheme_designator
+ assert c.meaning == self._meaning
+
+ def test_from_dataset_long_value(self):
+ ds = Dataset()
+ ds.LongCodeValue = self._long_code_value
+ ds.CodeMeaning = self._meaning
+ ds.CodingSchemeDesignator = self._scheme_designator
+ c = CodedConcept.from_dataset(ds)
+ assert c.value == self._long_code_value
+ assert c.scheme_designator == self._scheme_designator
+ assert c.meaning == self._meaning
+
+ def test_from_dataset_urn_value(self):
+ ds = Dataset()
+ ds.URNCodeValue = self._urn_code_value
+ ds.CodeMeaning = self._meaning
+ ds.CodingSchemeDesignator = self._scheme_designator
+ c = CodedConcept.from_dataset(ds)
+ assert c.value == self._urn_code_value
+ assert c.scheme_designator == self._scheme_designator
+ assert c.meaning == self._meaning
+
+ def test_from_dataset_multiple_value(self):
+ ds = Dataset()
+ ds.CodeValue = self._value
+ ds.URNCodeValue = self._urn_code_value # two code values, invalid
+ ds.CodeMeaning = self._meaning
+ ds.CodingSchemeDesignator = self._scheme_designator
+ with pytest.raises(AttributeError):
+ CodedConcept.from_dataset(ds)
+
def test_equal(self):
c1 = CodedConcept(self._value, self._scheme_designator, self._meaning)
c2 = CodedConcept(self._value, self._scheme_designator, self._meaning)
| Coded Concept with Long Code Value
The CodedConcept `__init()` assigns the value to a LongCodeValue tag if it is >16 characters, and the `value()` method also supports retrieving the value from either CodeValue, LongCodeValue, or URNCodeValue. But the `from_dataset()` classmethod raises an attribute error if the passed in dataset does not have the CodeValue tag.
[coding.py line 129](https://github.com/ImagingDataCommons/highdicom/blob/master/src/highdicom/sr/coding.py#L129)
Is there a way to handle LongCodeNames in this method? The exception doesn't occur when we create the actual CodedConcept, but it does when the concept is embedded in the dataset passed into hd.sr.EnhancedSR() which calls the `from_dataset()` method. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_sr.py::TestCodedConcept::test_from_dataset_long_value",
"tests/test_sr.py::TestCodedConcept::test_from_dataset_multiple_value",
"tests/test_sr.py::TestCodedConcept::test_from_dataset_urn_value"
] | [
"tests/test_sr.py::TestImageRegion::test_construction_ct_image",
"tests/test_sr.py::TestImageRegion::test_construction_sm_image_with_pixel_origin_interpretation",
"tests/test_sr.py::TestImageRegion::test_construction_sm_image_with_wrong_pixel_origin_interpretation",
"tests/test_sr.py::TestImageRegion::test_construction_sm_image_without_pixel_origin_interpretation",
"tests/test_sr.py::TestVolumeSurface::test_from_ellipses",
"tests/test_sr.py::TestVolumeSurface::test_from_ellipsoid",
"tests/test_sr.py::TestVolumeSurface::test_from_one_ellipse",
"tests/test_sr.py::TestVolumeSurface::test_from_one_polygon",
"tests/test_sr.py::TestVolumeSurface::test_from_point",
"tests/test_sr.py::TestVolumeSurface::test_from_point_with_series",
"tests/test_sr.py::TestVolumeSurface::test_from_polygons",
"tests/test_sr.py::TestVolumeSurface::test_from_two_ellipsoids",
"tests/test_sr.py::TestVolumeSurface::test_from_two_points",
"tests/test_sr.py::TestVolumeSurface::test_invalid_graphic_types",
"tests/test_sr.py::TestAlgorithmIdentification::test_construction_basic",
"tests/test_sr.py::TestAlgorithmIdentification::test_construction_parameters",
"tests/test_sr.py::TestMeasurementStatisticalProperties::test_construction_basic",
"tests/test_sr.py::TestMeasurementStatisticalProperties::test_construction_description",
"tests/test_sr.py::TestCodedConcept::test_construction_args",
"tests/test_sr.py::TestCodedConcept::test_construction_args_optional",
"tests/test_sr.py::TestCodedConcept::test_construction_kwargs",
"tests/test_sr.py::TestCodedConcept::test_construction_kwargs_optional",
"tests/test_sr.py::TestCodedConcept::test_equal",
"tests/test_sr.py::TestCodedConcept::test_equal_equivalent_coding",
"tests/test_sr.py::TestCodedConcept::test_equal_ignore_meaning",
"tests/test_sr.py::TestCodedConcept::test_from_dataset",
"tests/test_sr.py::TestCodedConcept::test_long_code_value",
"tests/test_sr.py::TestCodedConcept::test_not_equal",
"tests/test_sr.py::TestCodedConcept::test_urn_code_value",
"tests/test_sr.py::TestContentItem::test_code_item_construction",
"tests/test_sr.py::TestContentItem::test_composite_item_construction",
"tests/test_sr.py::TestContentItem::test_container_item_construction",
"tests/test_sr.py::TestContentItem::test_container_item_from_dataset",
"tests/test_sr.py::TestContentItem::test_date_item_construction_from_string",
"tests/test_sr.py::TestContentItem::test_date_item_construction_from_string_malformatted",
"tests/test_sr.py::TestContentItem::test_date_item_construction_from_time",
"tests/test_sr.py::TestContentItem::test_datetime_item_construction_from_datetime",
"tests/test_sr.py::TestContentItem::test_datetime_item_construction_from_string",
"tests/test_sr.py::TestContentItem::test_datetime_item_construction_from_string_malformatted",
"tests/test_sr.py::TestContentItem::test_image_item_construction",
"tests/test_sr.py::TestContentItem::test_image_item_construction_single_segment_number",
"tests/test_sr.py::TestContentItem::test_image_item_construction_with_multiple_frame_numbers",
"tests/test_sr.py::TestContentItem::test_image_item_construction_with_single_frame_number",
"tests/test_sr.py::TestContentItem::test_num_item_construction_from_float",
"tests/test_sr.py::TestContentItem::test_num_item_construction_from_integer",
"tests/test_sr.py::TestContentItem::test_num_item_construction_from_qualifier_code",
"tests/test_sr.py::TestContentItem::test_pname_content_item",
"tests/test_sr.py::TestContentItem::test_pname_content_item_from_person_name",
"tests/test_sr.py::TestContentItem::test_pname_content_item_invalid_name",
"tests/test_sr.py::TestContentItem::test_scoord3d_item_construction_point",
"tests/test_sr.py::TestContentItem::test_scoord3d_item_construction_polygon",
"tests/test_sr.py::TestContentItem::test_scoord_item_construction_circle",
"tests/test_sr.py::TestContentItem::test_scoord_item_construction_point",
"tests/test_sr.py::TestContentItem::test_text_item_construction",
"tests/test_sr.py::TestContentItem::test_text_item_from_dataset",
"tests/test_sr.py::TestContentItem::test_text_item_from_dataset_with_missing_name",
"tests/test_sr.py::TestContentItem::test_text_item_from_dataset_with_missing_value",
"tests/test_sr.py::TestContentItem::test_time_item_construction_from_string",
"tests/test_sr.py::TestContentItem::test_time_item_construction_from_string_malformatted",
"tests/test_sr.py::TestContentItem::test_time_item_construction_from_time",
"tests/test_sr.py::TestContentItem::test_uidref_item_construction_from_string",
"tests/test_sr.py::TestContentItem::test_uidref_item_construction_from_uid",
"tests/test_sr.py::TestContentItem::test_uidref_item_construction_wrong_value_type",
"tests/test_sr.py::TestContentSequence::test_append",
"tests/test_sr.py::TestContentSequence::test_append_root_item",
"tests/test_sr.py::TestContentSequence::test_append_root_item_with_relationship",
"tests/test_sr.py::TestContentSequence::test_append_with_no_relationship",
"tests/test_sr.py::TestContentSequence::test_construct",
"tests/test_sr.py::TestContentSequence::test_construct_root_item",
"tests/test_sr.py::TestContentSequence::test_construct_root_item_not_sr_iod",
"tests/test_sr.py::TestContentSequence::test_construct_root_with_relationship",
"tests/test_sr.py::TestContentSequence::test_construct_with_no_relationship",
"tests/test_sr.py::TestContentSequence::test_content_item_setattr",
"tests/test_sr.py::TestContentSequence::test_content_item_setattr_with_no_relationship",
"tests/test_sr.py::TestContentSequence::test_extend",
"tests/test_sr.py::TestContentSequence::test_extend_root_item",
"tests/test_sr.py::TestContentSequence::test_extend_root_item_with_relationship",
"tests/test_sr.py::TestContentSequence::test_extend_with_no_relationship",
"tests/test_sr.py::TestContentSequence::test_insert",
"tests/test_sr.py::TestContentSequence::test_insert_root_item",
"tests/test_sr.py::TestContentSequence::test_insert_root_item_with_relationship",
"tests/test_sr.py::TestContentSequence::test_insert_with_no_relationship",
"tests/test_sr.py::TestSubjectContextDevice::test_construction_all",
"tests/test_sr.py::TestSubjectContextDevice::test_construction_basic",
"tests/test_sr.py::TestObservationContext::test_content_length",
"tests/test_sr.py::TestObservationContext::test_observer_context",
"tests/test_sr.py::TestObservationContext::test_subject_context",
"tests/test_sr.py::TestPersonObserverIdentifyingAttributes::test_construction",
"tests/test_sr.py::TestPersonObserverIdentifyingAttributes::test_construction_all",
"tests/test_sr.py::TestPersonObserverIdentifyingAttributes::test_construction_invalid",
"tests/test_sr.py::TestFindingSiteOptional::test_finding_site",
"tests/test_sr.py::TestFindingSiteOptional::test_laterality",
"tests/test_sr.py::TestFindingSiteOptional::test_topographical_modifier",
"tests/test_sr.py::TestFindingSite::test_finding_site",
"tests/test_sr.py::TestSourceImageForSegmentation::test_construction",
"tests/test_sr.py::TestSourceImageForSegmentation::test_construction_with_frame_reference",
"tests/test_sr.py::TestSourceImageForSegmentation::test_from_invalid_source_image_seg",
"tests/test_sr.py::TestSourceImageForSegmentation::test_from_invalid_source_image_sr",
"tests/test_sr.py::TestSourceImageForSegmentation::test_from_source_image",
"tests/test_sr.py::TestSourceImageForSegmentation::test_from_source_image_with_invalid_referenced_frames",
"tests/test_sr.py::TestSourceImageForSegmentation::test_from_source_image_with_referenced_frames",
"tests/test_sr.py::TestSourceSeriesForSegmentation::test_construction",
"tests/test_sr.py::TestSourceSeriesForSegmentation::test_from_invalid_source_image_seg",
"tests/test_sr.py::TestSourceSeriesForSegmentation::test_from_invalid_source_image_sr",
"tests/test_sr.py::TestSourceSeriesForSegmentation::test_from_source_image",
"tests/test_sr.py::TestSourceImageForRegion::test_construction",
"tests/test_sr.py::TestSourceImageForRegion::test_construction_with_frame_reference_frames",
"tests/test_sr.py::TestSourceImageForRegion::test_from_invalid_source_image_seg",
"tests/test_sr.py::TestSourceImageForRegion::test_from_invalid_source_image_sr",
"tests/test_sr.py::TestSourceImageForRegion::test_from_source_image",
"tests/test_sr.py::TestSourceImageForRegion::test_from_source_image_with_invalid_referenced_frames",
"tests/test_sr.py::TestSourceImageForRegion::test_from_source_image_with_referenced_frames",
"tests/test_sr.py::TestSourceImage::test_construction",
"tests/test_sr.py::TestSourceImage::test_construction_with_frame_reference",
"tests/test_sr.py::TestSourceImage::test_from_invalid_source_image_seg",
"tests/test_sr.py::TestSourceImage::test_from_invalid_source_image_sr",
"tests/test_sr.py::TestSourceImage::test_from_source_image",
"tests/test_sr.py::TestSourceImage::test_from_source_image_with_invalid_referenced_frames",
"tests/test_sr.py::TestSourceImage::test_from_source_image_with_referenced_frames",
"tests/test_sr.py::TestSourceImageForMeasurement::test_construction",
"tests/test_sr.py::TestSourceImageForMeasurement::test_construction_with_frame_reference",
"tests/test_sr.py::TestSourceImageForMeasurement::test_from_invalid_source_image_seg",
"tests/test_sr.py::TestSourceImageForMeasurement::test_from_invalid_source_image_sr",
"tests/test_sr.py::TestSourceImageForMeasurement::test_from_source_image",
"tests/test_sr.py::TestSourceImageForMeasurement::test_from_source_image_with_invalid_referenced_frames",
"tests/test_sr.py::TestSourceImageForMeasurement::test_from_source_image_with_referenced_frames",
"tests/test_sr.py::TestReferencedSegment::test_construction",
"tests/test_sr.py::TestReferencedSegment::test_construction_series",
"tests/test_sr.py::TestReferencedSegment::test_construction_with_frame_reference",
"tests/test_sr.py::TestReferencedSegment::test_from_segmenation",
"tests/test_sr.py::TestReferencedSegment::test_from_segmentation_invalid_frame",
"tests/test_sr.py::TestReferencedSegment::test_from_segmentation_invalid_segment",
"tests/test_sr.py::TestReferencedSegment::test_from_segmentation_no_derivation_image",
"tests/test_sr.py::TestReferencedSegment::test_from_segmentation_no_derivation_image_no_instance_info",
"tests/test_sr.py::TestReferencedSegment::test_from_segmentation_no_referenced_series_sequence",
"tests/test_sr.py::TestReferencedSegment::test_from_segmentation_no_referenced_series_uid",
"tests/test_sr.py::TestReferencedSegment::test_from_segmentation_with_frames",
"tests/test_sr.py::TestReferencedSegment::test_from_segmentation_wrong_frame",
"tests/test_sr.py::TestReferencedSegmentationFrame::test_construction",
"tests/test_sr.py::TestReferencedSegmentationFrame::test_from_segmentation_invalid_frame",
"tests/test_sr.py::TestReferencedSegmentationFrame::test_from_segmentation_no_derivation_image",
"tests/test_sr.py::TestReferencedSegmentationFrame::test_from_segmentation_no_referenced_series_sequence",
"tests/test_sr.py::TestReferencedSegmentationFrame::test_from_segmentation_no_referenced_series_uid",
"tests/test_sr.py::TestReferencedSegmentationFrame::test_from_segmentation_with_frame_number",
"tests/test_sr.py::TestReferencedSegmentationFrame::test_from_segmentation_with_segment_number",
"tests/test_sr.py::TestTrackingIdentifierOptional::test_identifier",
"tests/test_sr.py::TestTrackingIdentifierOptional::test_uid",
"tests/test_sr.py::TestTrackingIdentifier::test_uid",
"tests/test_sr.py::TestTrackingIdentifierDefault::test_uid",
"tests/test_sr.py::TestTimePointContext::test_time_point",
"tests/test_sr.py::TestTimePointContextOptional::test_protocol_time_point_identifier",
"tests/test_sr.py::TestTimePointContextOptional::test_subject_time_point_identifier",
"tests/test_sr.py::TestTimePointContextOptional::test_temporal_offset_from_event",
"tests/test_sr.py::TestTimePointContextOptional::test_time_point_order",
"tests/test_sr.py::TestTimePointContextOptional::test_time_point_type",
"tests/test_sr.py::TestMeasurement::test_construction_with_missing_required_parameters",
"tests/test_sr.py::TestMeasurement::test_construction_with_optional_parameters",
"tests/test_sr.py::TestMeasurement::test_construction_with_required_parameters",
"tests/test_sr.py::TestQualitativeEvaluation::test_construction",
"tests/test_sr.py::TestMeasurementsAndQualitativeEvaluations::test_construction",
"tests/test_sr.py::TestMeasurementsAndQualitativeEvaluations::test_construction_with_source_images",
"tests/test_sr.py::TestPlanarROIMeasurementsAndQualitativeEvaluations::test_constructed_with_multiple_references",
"tests/test_sr.py::TestPlanarROIMeasurementsAndQualitativeEvaluations::test_constructed_without_human_readable_tracking_identifier",
"tests/test_sr.py::TestPlanarROIMeasurementsAndQualitativeEvaluations::test_constructed_without_reference",
"tests/test_sr.py::TestPlanarROIMeasurementsAndQualitativeEvaluations::test_construction_all_parameters",
"tests/test_sr.py::TestPlanarROIMeasurementsAndQualitativeEvaluations::test_construction_with_region",
"tests/test_sr.py::TestPlanarROIMeasurementsAndQualitativeEvaluations::test_construction_with_region_3d",
"tests/test_sr.py::TestPlanarROIMeasurementsAndQualitativeEvaluations::test_construction_with_segment",
"tests/test_sr.py::TestPlanarROIMeasurementsAndQualitativeEvaluations::test_from_sequence_with_region",
"tests/test_sr.py::TestVolumetricROIMeasurementsAndQualitativeEvaluations::test_constructed_with_multiple_references",
"tests/test_sr.py::TestVolumetricROIMeasurementsAndQualitativeEvaluations::test_constructed_with_regions",
"tests/test_sr.py::TestVolumetricROIMeasurementsAndQualitativeEvaluations::test_constructed_with_regions_3d",
"tests/test_sr.py::TestVolumetricROIMeasurementsAndQualitativeEvaluations::test_constructed_with_segment",
"tests/test_sr.py::TestVolumetricROIMeasurementsAndQualitativeEvaluations::test_constructed_with_segment_from_series",
"tests/test_sr.py::TestVolumetricROIMeasurementsAndQualitativeEvaluations::test_constructed_with_volume",
"tests/test_sr.py::TestVolumetricROIMeasurementsAndQualitativeEvaluations::test_constructed_without_reference",
"tests/test_sr.py::TestVolumetricROIMeasurementsAndQualitativeEvaluations::test_construction_all_parameters",
"tests/test_sr.py::TestVolumetricROIMeasurementsAndQualitativeEvaluations::test_from_sequence_with_region",
"tests/test_sr.py::TestMeasurementReport::test_construction_image",
"tests/test_sr.py::TestMeasurementReport::test_construction_planar",
"tests/test_sr.py::TestMeasurementReport::test_construction_volumetric",
"tests/test_sr.py::TestMeasurementReport::test_from_sequence",
"tests/test_sr.py::TestEnhancedSR::test_construction",
"tests/test_sr.py::TestEnhancedSR::test_construction_content_is_sequence",
"tests/test_sr.py::TestEnhancedSR::test_evidence_missing",
"tests/test_sr.py::TestComprehensiveSR::test_construction",
"tests/test_sr.py::TestComprehensiveSR::test_construction_content_is_sequence",
"tests/test_sr.py::TestComprehensiveSR::test_evidence_duplication",
"tests/test_sr.py::TestComprehensiveSR::test_evidence_missing",
"tests/test_sr.py::TestComprehensiveSR::test_evidence_multiple_studies",
"tests/test_sr.py::TestComprehensiveSR::test_srread",
"tests/test_sr.py::TestComprehensive3DSR::test_construction",
"tests/test_sr.py::TestComprehensive3DSR::test_construction_content_is_sequence",
"tests/test_sr.py::TestComprehensive3DSR::test_evidence_duplication",
"tests/test_sr.py::TestComprehensive3DSR::test_from_dataset",
"tests/test_sr.py::TestComprehensive3DSR::test_from_dataset_no_copy",
"tests/test_sr.py::TestSRUtilities::test_find_content_items",
"tests/test_sr.py::TestSRUtilities::test_find_content_items_filter_by_name_recursively",
"tests/test_sr.py::TestSRUtilities::test_find_content_items_filter_by_relationship_type_recursively",
"tests/test_sr.py::TestSRUtilities::test_find_content_items_filter_by_value_type_recursively",
"tests/test_sr.py::TestSRUtilities::test_find_content_items_filter_by_value_type_recursively_1",
"tests/test_sr.py::TestSRUtilities::test_find_content_items_filtered_by_name",
"tests/test_sr.py::TestSRUtilities::test_find_content_items_filtered_by_relationship_type",
"tests/test_sr.py::TestSRUtilities::test_find_content_items_filtered_by_value_type",
"tests/test_sr.py::TestSRUtilities::test_find_content_items_filtered_by_value_type_relationship_type",
"tests/test_sr.py::TestSRUtilities::test_find_content_items_recursively",
"tests/test_sr.py::TestGetPlanarMeasurementGroups::test_all_groups",
"tests/test_sr.py::TestGetPlanarMeasurementGroups::test_find_seg_groups",
"tests/test_sr.py::TestGetPlanarMeasurementGroups::test_get_circle_groups",
"tests/test_sr.py::TestGetPlanarMeasurementGroups::test_get_groups_by_ref_uid_1",
"tests/test_sr.py::TestGetPlanarMeasurementGroups::test_get_groups_by_ref_uid_2",
"tests/test_sr.py::TestGetPlanarMeasurementGroups::test_get_groups_by_ref_uid_3",
"tests/test_sr.py::TestGetPlanarMeasurementGroups::test_get_groups_by_tracking_id",
"tests/test_sr.py::TestGetPlanarMeasurementGroups::test_get_groups_invalid_graphic_type_1",
"tests/test_sr.py::TestGetPlanarMeasurementGroups::test_get_groups_invalid_graphic_type_2",
"tests/test_sr.py::TestGetPlanarMeasurementGroups::test_get_groups_invalid_graphic_type_3d",
"tests/test_sr.py::TestGetPlanarMeasurementGroups::test_get_groups_invalid_reference_types",
"tests/test_sr.py::TestGetPlanarMeasurementGroups::test_get_groups_with_ref_uid_and_graphic_type_3d",
"tests/test_sr.py::TestGetPlanarMeasurementGroups::test_get_image_region_groups",
"tests/test_sr.py::TestGetPlanarMeasurementGroups::test_get_point3d_groups",
"tests/test_sr.py::TestGetPlanarMeasurementGroups::test_get_point_groups",
"tests/test_sr.py::TestGetPlanarMeasurementGroups::test_get_polyline_groups",
"tests/test_sr.py::TestGetPlanarMeasurementGroups::test_get_volumetric_groups",
"tests/test_sr.py::TestGetVolumetricMeasurementGroups::test_all_groups",
"tests/test_sr.py::TestGetVolumetricMeasurementGroups::test_find_seg_groups",
"tests/test_sr.py::TestGetVolumetricMeasurementGroups::test_get_circle_groups",
"tests/test_sr.py::TestGetVolumetricMeasurementGroups::test_get_groups_by_ref_uid_1",
"tests/test_sr.py::TestGetVolumetricMeasurementGroups::test_get_groups_by_ref_uid_2",
"tests/test_sr.py::TestGetVolumetricMeasurementGroups::test_get_groups_by_ref_uid_3",
"tests/test_sr.py::TestGetVolumetricMeasurementGroups::test_get_groups_by_tracking_id",
"tests/test_sr.py::TestGetVolumetricMeasurementGroups::test_get_groups_invalid_graphic_type_1",
"tests/test_sr.py::TestGetVolumetricMeasurementGroups::test_get_groups_invalid_graphic_type_2",
"tests/test_sr.py::TestGetVolumetricMeasurementGroups::test_get_groups_invalid_graphic_type_3",
"tests/test_sr.py::TestGetVolumetricMeasurementGroups::test_get_groups_invalid_graphic_type_3d",
"tests/test_sr.py::TestGetVolumetricMeasurementGroups::test_get_groups_invalid_reference_types",
"tests/test_sr.py::TestGetVolumetricMeasurementGroups::test_get_groups_with_ref_uid_and_graphic_type_3d",
"tests/test_sr.py::TestGetVolumetricMeasurementGroups::test_get_image_region_groups",
"tests/test_sr.py::TestGetVolumetricMeasurementGroups::test_get_planar_groups",
"tests/test_sr.py::TestGetVolumetricMeasurementGroups::test_get_point3d_groups",
"tests/test_sr.py::TestGetVolumetricMeasurementGroups::test_get_point_groups",
"tests/test_sr.py::TestGetVolumetricMeasurementGroups::test_get_polygon3d_groups",
"tests/test_sr.py::TestGetVolumetricMeasurementGroups::test_get_polyline_groups",
"tests/test_sr.py::TestGetVolumetricMeasurementGroups::test_srread",
"tests/test_sr.py::TestImageLibraryEntryDescriptors::test_bad_ct_construction",
"tests/test_sr.py::TestImageLibraryEntryDescriptors::test_ct_construction",
"tests/test_sr.py::TestImageLibraryEntryDescriptors::test_dx_construction",
"tests/test_sr.py::TestImageLibraryEntryDescriptors::test_sm_construction",
"tests/test_sr.py::TestImageLibrary::test_construction"
] | {
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
} | "2023-04-24T21:16:46Z" | mit |
|
ImperialCollegeLondon__django-drf-filepond-54 | diff --git a/django_drf_filepond/apps.py b/django_drf_filepond/apps.py
index 4309bc3..c5904ca 100644
--- a/django_drf_filepond/apps.py
+++ b/django_drf_filepond/apps.py
@@ -14,9 +14,20 @@ class DjangoDrfFilepondConfig(AppConfig):
verbose_name = 'FilePond Server-side API'
def ready(self):
+ # Get BASE_DIR and process to ensure it works across platforms
+ # Handle py3.5 where pathlib exists but os.path.join can't accept a
+ # pathlib object (ensure we always pass a string to os.path.join)
+ BASE_DIR = local_settings.BASE_DIR
+ try:
+ from pathlib import Path
+ if isinstance(BASE_DIR, Path):
+ BASE_DIR = str(BASE_DIR)
+ except ImportError:
+ pass
+
upload_tmp = getattr(
local_settings, 'UPLOAD_TMP',
- os.path.join(local_settings.BASE_DIR, 'filepond_uploads'))
+ os.path.join(BASE_DIR, 'filepond_uploads'))
LOG.debug('Upload temp directory from top level settings: <%s>'
% (upload_tmp))
diff --git a/django_drf_filepond/drf_filepond_settings.py b/django_drf_filepond/drf_filepond_settings.py
index cf6956e..7e1d530 100644
--- a/django_drf_filepond/drf_filepond_settings.py
+++ b/django_drf_filepond/drf_filepond_settings.py
@@ -21,7 +21,16 @@ _app_prefix = 'DJANGO_DRF_FILEPOND_'
# installed app base directory to use as an alternative.
BASE_DIR = os.path.dirname(django_drf_filepond.__file__)
if hasattr(settings, 'BASE_DIR'):
+ # If BASE_DIR is set in the main settings, get it and process it to
+ # handle py3.5 where pathlib exists but os.path.join can't accept a
+ # pathlib object (ensure we always pass a string to os.path.join)
BASE_DIR = settings.BASE_DIR
+ try:
+ from pathlib import Path
+ if isinstance(BASE_DIR, Path):
+ BASE_DIR = str(BASE_DIR)
+ except ImportError:
+ pass
# The location where uploaded files are temporarily stored. At present,
# this must be a subdirectory of settings.BASE_DIR
diff --git a/django_drf_filepond/models.py b/django_drf_filepond/models.py
index 32a2f0b..4bf350c 100644
--- a/django_drf_filepond/models.py
+++ b/django_drf_filepond/models.py
@@ -19,9 +19,17 @@ from django_drf_filepond.storage_utils import _get_storage_backend
LOG = logging.getLogger(__name__)
+BASE_DIR = local_settings.BASE_DIR
+try:
+ from pathlib import Path
+ if isinstance(BASE_DIR, Path):
+ BASE_DIR = str(BASE_DIR)
+except ImportError:
+ pass
+
FILEPOND_UPLOAD_TMP = getattr(
local_settings, 'UPLOAD_TMP',
- os.path.join(local_settings.BASE_DIR, 'filepond_uploads'))
+ os.path.join(BASE_DIR, 'filepond_uploads'))
FILEPOND_FILE_STORE_PATH = getattr(local_settings, 'FILE_STORE_PATH', None)
diff --git a/django_drf_filepond/utils.py b/django_drf_filepond/utils.py
index d01da02..2949b71 100644
--- a/django_drf_filepond/utils.py
+++ b/django_drf_filepond/utils.py
@@ -1,4 +1,5 @@
# A module containing some utility functions used by the views and uploaders
+import django_drf_filepond.drf_filepond_settings as local_settings
from django.contrib.auth.models import AnonymousUser
import shortuuid
import six
@@ -18,3 +19,27 @@ def _get_user(request):
def _get_file_id():
file_id = shortuuid.uuid()
return six.ensure_text(file_id)
+
+
+# Get the BASE_DIR variable from local_settings and process it to ensure that
+# it can be used in django_drf_filepond across Python 2.7, 3.5 and 3.6+.
+# Need to take into account that this may be a regular string or a
+# pathlib.Path object. django-drf-filepond expects to work with BASE_DIR as a
+# string so return a string regardless of the type of BASE_DIR. To maintain
+# suport for Python 2.7, need to handle the case where pathlib.Path doesn't
+# exist...
+def get_local_settings_base_dir():
+ base_dir = local_settings.BASE_DIR
+ return _process_base_dir(base_dir)
+
+
+# Process the provided BASE_DIR variable
+def _process_base_dir(base_dir):
+ try:
+ from pathlib import Path
+ except ImportError:
+ return base_dir
+
+ if isinstance(base_dir, Path):
+ return str(base_dir)
+ return base_dir
diff --git a/django_drf_filepond/views.py b/django_drf_filepond/views.py
index 4d45ab2..a91b1c0 100644
--- a/django_drf_filepond/views.py
+++ b/django_drf_filepond/views.py
@@ -30,7 +30,8 @@ from rest_framework.parsers import MultiPartParser
from rest_framework.response import Response
from rest_framework.views import APIView
from django_drf_filepond.uploaders import FilepondFileUploader
-from django_drf_filepond.utils import _get_file_id, _get_user
+from django_drf_filepond.utils import _get_file_id, _get_user,\
+ get_local_settings_base_dir
LOG = logging.getLogger(__name__)
@@ -104,8 +105,9 @@ class ProcessView(APIView):
# TODO: Check whether this is necessary - maybe add a security
# parameter that can be disabled to turn off this check if the
# developer wishes?
- if ((not (storage.location).startswith(local_settings.BASE_DIR)) and
- (local_settings.BASE_DIR !=
+ LOCAL_BASE_DIR = get_local_settings_base_dir()
+ if ((not (storage.location).startswith(LOCAL_BASE_DIR)) and
+ (LOCAL_BASE_DIR !=
os.path.dirname(django_drf_filepond.__file__))):
if not local_settings.ALLOW_EXTERNAL_UPLOAD_DIR:
return Response('The file upload path settings are not '
diff --git a/setup.py b/setup.py
index c2d799d..668f740 100644
--- a/setup.py
+++ b/setup.py
@@ -5,7 +5,7 @@ with open("README.md", "r") as readme:
setup(
name="django-drf-filepond",
- version="0.3.0",
+ version="0.3.1",
description="Filepond server app for Django REST Framework",
long_description=long_description,
long_description_content_type='text/markdown',
@@ -26,9 +26,11 @@ setup(
"Django>=2.2;python_version>='3.6'",
"djangorestframework==3.9.3;python_version=='2.7'",
"djangorestframework>=3.9.3;python_version>='3.5'",
- "shortuuid>=0.5.0",
+ "shortuuid==0.5.0;python_version=='2.7'",
+ "shortuuid>=0.5.0;python_version>='3.5'",
"requests>=2.20.1",
- "django-storages>=1.8",
+ "django-storages==1.9.1;python_version=='2.7'",
+ "django-storages>=1.9.1;python_version>='3.5'",
"six>=1.14.0"
],
tests_require=[
| ImperialCollegeLondon/django-drf-filepond | 5cb99531523609c77762288ac09552651e431688 | diff --git a/tests/settings.py b/tests/settings.py
index 5c29306..892b914 100644
--- a/tests/settings.py
+++ b/tests/settings.py
@@ -14,6 +14,12 @@ import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+# For testing with pathlib.Path based BASE_DIR
+# from pathlib import Path
+# BASE_DIR = Path(__file__).resolve().parent.parent
+
+# Get a string representation of BASE_DIR in case it's provided as a Path
+BASE_DIR_STR = str(BASE_DIR)
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/
@@ -76,7 +82,7 @@ WSGI_APPLICATION = 'tests.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
- 'NAME': os.path.join(BASE_DIR, 'filepond_tests.db'),
+ 'NAME': os.path.join(BASE_DIR_STR, 'filepond_tests.db'),
}
}
@@ -126,7 +132,7 @@ STATIC_URL = '/static/'
# The URL base used for the URL import
URL_BASE = r'^fp/'
-DJANGO_DRF_FILEPOND_FILE_STORE_PATH = os.path.join(BASE_DIR, 'filestore')
+DJANGO_DRF_FILEPOND_FILE_STORE_PATH = os.path.join(BASE_DIR_STR, 'filestore')
LOGGING = {
'version': 1,
diff --git a/tests/test_process_view.py b/tests/test_process_view.py
index 938b4ae..ee555af 100644
--- a/tests/test_process_view.py
+++ b/tests/test_process_view.py
@@ -26,6 +26,8 @@ except ImportError:
from mock import patch, MagicMock, ANY
LOG = logging.getLogger(__name__)
+
+
#
# New tests for checking file storage outside of BASE_DIR (see #18)
#
@@ -44,8 +46,10 @@ LOG = logging.getLogger(__name__)
# test_new_chunked_upload_request: Check that a new chunked upload request
# results in handle_upload being called on the chunked uploader class.
#
-
-
+# UPDATE: June 2021:
+# test_process_data_BASE_DIR_pathlib: Tests the upload process when BASE_DIR
+# is set as a pathlib.Path object as it is by default in more recent Django
+# versions - at present, django-drf-filepond uses regular strings for paths
class ProcessTestCase(TestCase):
def setUp(self):
@@ -57,6 +61,31 @@ class ProcessTestCase(TestCase):
def test_process_data(self):
self._process_data()
+ def test_process_data_BASE_DIR_pathlib(self):
+ # In recent Django versions, BASE_DIR is set by default to
+ # Path(__file__).resolve().parent.parent when creating a new project
+ # using django-admin. Older versions of Django, in use when
+ # django-drf-filepond was originally created used regular strings
+ # for paths. Need to be able to handle both.
+ # Set modified BASE_DIR using context manager - on older Python
+ # versions that don't have pathlib support, fall back to strings
+ OLD_BASE_DIR = drf_filepond_settings.BASE_DIR
+ try:
+ from pathlib import Path
+ NEW_BASE_DIR = Path(__file__).resolve().parent.parent
+ LOG.debug('PATHLIB TEST: Old BASE_DIR: %s NEW_BASE_DIR: %s' %
+ (repr(drf_filepond_settings.BASE_DIR),
+ repr(NEW_BASE_DIR)))
+ drf_filepond_settings.BASE_DIR = NEW_BASE_DIR
+ except ImportError:
+ LOG.debug('NO PATHLIB SUPPORT FOR PATHLIB TEST. '
+ 'FALLING BACK TO USING REGULAR STRING PATHS...')
+
+ try:
+ self._process_data()
+ finally:
+ drf_filepond_settings.BASE_DIR = OLD_BASE_DIR
+
def test_UPLOAD_TMP_not_set(self):
upload_tmp = drf_filepond_settings.UPLOAD_TMP
delattr(drf_filepond_settings, 'UPLOAD_TMP')
diff --git a/tests/test_utils.py b/tests/test_utils.py
index def0044..1ba0cad 100644
--- a/tests/test_utils.py
+++ b/tests/test_utils.py
@@ -7,7 +7,9 @@ from rest_framework.request import Request
import shortuuid
from six import text_type
-from django_drf_filepond.utils import _get_user, _get_file_id
+import django_drf_filepond.drf_filepond_settings as local_settings
+from django_drf_filepond.utils import _get_user, _get_file_id, \
+ get_local_settings_base_dir
# Python 2/3 support
@@ -27,6 +29,15 @@ LOG = logging.getLogger(__name__)
# test_get_file_id: Test that get_file_id returns an ID that corresponds to
# the 22-character specification.
#
+# test_get_base_dir_with_str: Test that when the local settings BASE_DIR
+# is a string, a string is returned.
+#
+# test_get_base_dir_with_path: Test that when the local settings BASE_DIR
+# is a Path object, a string is returned.
+#
+# test_get_base_dir_join_path: Test that when the local settings BASE_DIR
+# is a Path object, a string is returned.
+#
class UtilsTestCase(TestCase):
def test_get_user_regular(self):
@@ -48,3 +59,35 @@ class UtilsTestCase(TestCase):
id_format = re.compile('^([%s]){22}$' % (shortuuid.get_alphabet()))
self.assertRegex(fid, id_format, ('The generated ID does not match '
'the defined ID format.'))
+
+ def test_get_base_dir_with_str(self):
+ test_dir_name = '/tmp/testdir'
+ old_base_dir = local_settings.BASE_DIR
+ try:
+ local_settings.BASE_DIR = test_dir_name
+ bd = get_local_settings_base_dir()
+ self.assertIsInstance(
+ bd, str, 'The base directory is not a string.')
+ self.assertEqual(
+ bd, test_dir_name, 'The test directory name doesn\'t match.')
+ finally:
+ local_settings.BASE_DIR = old_base_dir
+
+ def test_get_base_dir_with_path(self):
+ try:
+ from pathlib import Path
+ test_dir_name = Path('/tmp/testdir')
+ except ImportError:
+ test_dir_name = '/tmp/testdir'
+
+ old_base_dir = local_settings.BASE_DIR
+ try:
+ local_settings.BASE_DIR = test_dir_name
+ bd = get_local_settings_base_dir()
+ self.assertIsInstance(
+ bd, str, 'The base directory is not a string.')
+ self.assertEqual(
+ bd, str(test_dir_name),
+ 'The test directory name doesn\'t match.')
+ finally:
+ local_settings.BASE_DIR = old_base_dir
| Problem with Pathlib based paths
Hello and thanks a lot for this awesome app. it makes lives so much easier!
I recently started a new django project (Django 3.1) and as you know, django has moved from **os.path** to **Pathlib**. unfortunately, this breaks this app's functionality.
It throws an error in :
django_drf_filepond/views.py, line 107
where it contains the following:
`if ((not (storage.location).startswith(local_settings.BASE_DIR)) and
(local_settings.BASE_DIR !=
os.path.dirname(django_drf_filepond.__file__))):`
The error reads `TypeError: startswith first arg must be str or a tuple of str, not WindowsPath`, and everything works when I wrap `storage.location` in an `str` function (obviously, because `startswhth` expects strings.)
anyways, please forgive any mistakes I made, I am a newbie both in django and around github. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_utils.py::UtilsTestCase::test_get_file_id",
"tests/test_utils.py::UtilsTestCase::test_get_base_dir_with_path",
"tests/test_utils.py::UtilsTestCase::test_get_base_dir_with_str",
"tests/test_utils.py::UtilsTestCase::test_get_user_anonymous",
"tests/test_utils.py::UtilsTestCase::test_get_user_regular"
] | [] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2021-06-23T18:38:27Z" | bsd-3-clause |
|
Infinidat__munch-52 | diff --git a/CHANGELOG.md b/CHANGELOG.md
index 424148a..8823bcc 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,8 @@ Changelog
Next Version
------------
+* Support ``fromYAML`` classmethod for all Munch subclasses (PR [#52](https://github.com/Infinidat/munch/pull/52) fixes [#34](https://github.com/Infinidat/munch/issues/34)
+
2.4.0 (2019-10-29)
------------------
diff --git a/munch/__init__.py b/munch/__init__.py
index 83420a4..384c504 100644
--- a/munch/__init__.py
+++ b/munch/__init__.py
@@ -615,12 +615,13 @@ try:
else:
return yaml.dump(self, **opts)
- def fromYAML(*args, **kwargs):
- kwargs.setdefault('Loader', yaml.FullLoader)
- return munchify(yaml.load(*args, **kwargs))
+ def fromYAML(cls, stream, *args, **kwargs):
+ factory = lambda d: cls(*(args + (d,)), **kwargs)
+ loader_class = kwargs.pop('Loader', yaml.FullLoader)
+ return munchify(yaml.load(stream, Loader=loader_class), factory=factory)
Munch.toYAML = toYAML
- Munch.fromYAML = staticmethod(fromYAML)
+ Munch.fromYAML = classmethod(fromYAML)
except ImportError:
pass
| Infinidat/munch | dede29c5e8bde7ca575365d50dd44f8fc12a5991 | diff --git a/tests/test_yaml.py b/tests/test_yaml.py
index 92054a8..6d15261 100644
--- a/tests/test_yaml.py
+++ b/tests/test_yaml.py
@@ -1,5 +1,5 @@
import pytest
-from munch import Munch
+from munch import Munch, DefaultMunch
def test_from_yaml(yaml):
@@ -39,7 +39,22 @@ def test_toYAML(yaml):
@pytest.mark.usefixtures('yaml')
def test_fromYAML():
+ # pylint: disable=unidiomatic-typecheck
yaml_str = 'foo:\n bar:\n - 1\n - 2\n hello: world\n'
obj = Munch.fromYAML(yaml_str)
+ assert type(obj) == Munch
assert obj == Munch(foo=Munch(bar=[1, 2], hello='world'))
assert obj.toYAML() == yaml_str
+
+
[email protected]('yaml')
+def test_fromYAML_default_munch():
+ # pylint: disable=unidiomatic-typecheck
+ yaml_str = 'foo:\n bar:\n - 1\n - 2\n hello: world\n'
+ default_value = object()
+ obj = DefaultMunch.fromYAML(yaml_str, default_value)
+ assert type(obj) == DefaultMunch
+ assert obj == DefaultMunch(foo=Munch(bar=[1, 2], hello='world'))
+ assert obj['not_exist'] is default_value
+ assert obj.not_exist is default_value
+ assert obj.toYAML() == yaml_str
| DefaultMunch.fromYAML should take default argument
Currently, `DefaultMunch.fromYAML` is the same as `Munch.fromYAML`. This is confusing, and it is a pitty because a real `DefaultMunch.fromYAML` would add functionality which, FWIW, I could use. Thus, I propose to create a dedicated `DefaultMunch.fromYAML` function with a parameter for the default value. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_yaml.py::test_fromYAML_default_munch"
] | [
"tests/test_yaml.py::test_to_yaml",
"tests/test_yaml.py::test_fromYAML",
"tests/test_yaml.py::test_to_yaml_safe",
"tests/test_yaml.py::test_from_yaml",
"tests/test_yaml.py::test_toYAML"
] | {
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2019-10-29T15:16:08Z" | mit |
|
Infinidat__munch-54 | diff --git a/CHANGELOG.md b/CHANGELOG.md
index 424148a..3f5a26d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,6 +3,9 @@ Changelog
Next Version
------------
+* Fix return value of DefaultMunch and DefaultFactoryMunch's get method (fixes [#53](https://github.com/Infinidat/munch/issues/53))
+
+* Support ``fromYAML`` classmethod for all Munch subclasses (PR [#52](https://github.com/Infinidat/munch/pull/52) fixes [#34](https://github.com/Infinidat/munch/issues/34)
2.4.0 (2019-10-29)
------------------
diff --git a/munch/__init__.py b/munch/__init__.py
index 83420a4..98b92c7 100644
--- a/munch/__init__.py
+++ b/munch/__init__.py
@@ -238,10 +238,9 @@ class Munch(dict):
"""
D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.
"""
- try:
- return self[k]
- except KeyError:
+ if k not in self:
return d
+ return self[k]
def setdefault(self, k, d=None):
"""
@@ -615,12 +614,13 @@ try:
else:
return yaml.dump(self, **opts)
- def fromYAML(*args, **kwargs):
- kwargs.setdefault('Loader', yaml.FullLoader)
- return munchify(yaml.load(*args, **kwargs))
+ def fromYAML(cls, stream, *args, **kwargs):
+ factory = lambda d: cls(*(args + (d,)), **kwargs)
+ loader_class = kwargs.pop('Loader', yaml.FullLoader)
+ return munchify(yaml.load(stream, Loader=loader_class), factory=factory)
Munch.toYAML = toYAML
- Munch.fromYAML = staticmethod(fromYAML)
+ Munch.fromYAML = classmethod(fromYAML)
except ImportError:
pass
| Infinidat/munch | dede29c5e8bde7ca575365d50dd44f8fc12a5991 | diff --git a/tests/conftest.py b/tests/conftest.py
index 259071a..45d6b23 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -1,4 +1,5 @@
import pytest
+import munch
@pytest.fixture(name='yaml')
@@ -9,3 +10,12 @@ def yaml_module():
except ImportError:
pass
pytest.skip("Module 'PyYAML' is required")
+
+
[email protected](params=[munch.Munch, munch.AutoMunch, munch.DefaultMunch, munch.DefaultFactoryMunch])
+def munch_obj(request):
+ cls = request.param
+ args = tuple()
+ if cls == munch.DefaultFactoryMunch:
+ args = args + (lambda: None,)
+ return cls(*args, hello="world", number=5)
diff --git a/tests/test_munch.py b/tests/test_munch.py
index fc55165..9c645cc 100644
--- a/tests/test_munch.py
+++ b/tests/test_munch.py
@@ -533,3 +533,7 @@ def test_getitem_dunder_for_subclass():
assert custom_munch.a == 42
assert custom_munch.get('b') == 42
assert custom_munch.copy() == Munch(a=42, b=42)
+
+
+def test_get_default_value(munch_obj):
+ assert munch_obj.get("fake_key", "default_value") == "default_value"
diff --git a/tests/test_yaml.py b/tests/test_yaml.py
index 92054a8..6d15261 100644
--- a/tests/test_yaml.py
+++ b/tests/test_yaml.py
@@ -1,5 +1,5 @@
import pytest
-from munch import Munch
+from munch import Munch, DefaultMunch
def test_from_yaml(yaml):
@@ -39,7 +39,22 @@ def test_toYAML(yaml):
@pytest.mark.usefixtures('yaml')
def test_fromYAML():
+ # pylint: disable=unidiomatic-typecheck
yaml_str = 'foo:\n bar:\n - 1\n - 2\n hello: world\n'
obj = Munch.fromYAML(yaml_str)
+ assert type(obj) == Munch
assert obj == Munch(foo=Munch(bar=[1, 2], hello='world'))
assert obj.toYAML() == yaml_str
+
+
[email protected]('yaml')
+def test_fromYAML_default_munch():
+ # pylint: disable=unidiomatic-typecheck
+ yaml_str = 'foo:\n bar:\n - 1\n - 2\n hello: world\n'
+ default_value = object()
+ obj = DefaultMunch.fromYAML(yaml_str, default_value)
+ assert type(obj) == DefaultMunch
+ assert obj == DefaultMunch(foo=Munch(bar=[1, 2], hello='world'))
+ assert obj['not_exist'] is default_value
+ assert obj.not_exist is default_value
+ assert obj.toYAML() == yaml_str
| DefaultMunch getter now returns None instead of DefaultValue
If a DefaultMunch has a default value of None, munch.get(attr_name, default_value) will now return None instead of default_value
```
>>> from munch import DefaultMunch
>>> d = DefaultMunch(None, {'a': 1})
>>> d.get('a')
1
>>> d.get('b')
>>> d.get('b', 'test')
>>> d.get('b', 'test') is None
True
```
This is a devastating change in behavior from the previous version:
```
>>> from munch import DefaultMunch
>>> d = DefaultMunch(None, {'a': 1})
>>> d.get('a')
1
>>> d.get('b')
>>> d.get('b', 'test')
'test'
>>> d.get('b', 'test') is None
False
``` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_munch.py::test_get_default_value[DefaultFactoryMunch]",
"tests/test_munch.py::test_get_default_value[DefaultMunch]",
"tests/test_yaml.py::test_fromYAML_default_munch"
] | [
"tests/test_munch.py::test_repr_default",
"tests/test_munch.py::test_getattr_default_factory",
"tests/test_munch.py::test_reserved_attributes[__getitem__]",
"tests/test_munch.py::test_reserved_attributes[__iter__]",
"tests/test_munch.py::test_reserved_attributes[__contains__]",
"tests/test_munch.py::test_reserved_attributes[__class__]",
"tests/test_munch.py::test_reserved_attributes[__setattr__]",
"tests/test_munch.py::test_reserved_attributes[fromDict]",
"tests/test_munch.py::test_reserved_attributes[__lt__]",
"tests/test_munch.py::test_reserved_attributes[__getattr__]",
"tests/test_munch.py::test_copy",
"tests/test_munch.py::test_reserved_attributes[__ne__]",
"tests/test_munch.py::test_delattr_default_factory",
"tests/test_munch.py::test_reserved_attributes[__getstate__]",
"tests/test_munch.py::test_reserved_attributes[popitem]",
"tests/test_munch.py::test_reserved_attributes[copy]",
"tests/test_munch.py::test_getattr_default",
"tests/test_munch.py::test_fromDict_default",
"tests/test_munch.py::test_setattr_default",
"tests/test_munch.py::test_reserved_attributes[__ior__]",
"tests/test_munch.py::test_reserved_attributes[__getattribute__]",
"tests/test_munch.py::test_reserved_attributes[update]",
"tests/test_munch.py::test_setitem_dunder_for_subclass",
"tests/test_munch.py::test_reserved_attributes[__members__]",
"tests/test_munch.py::test_copy_default_factory",
"tests/test_munch.py::test_reserved_attributes[fromkeys]",
"tests/test_munch.py::test_setattr_default_factory",
"tests/test_munch.py::test_pickling_unpickling_nested",
"tests/test_munch.py::test_unmunchify",
"tests/test_munch.py::test_reserved_attributes[__init__]",
"tests/test_munch.py::test_reserved_attributes[__new__]",
"tests/test_munch.py::test_reserved_attributes[__subclasshook__]",
"tests/test_munch.py::test_reserved_attributes[__module__]",
"tests/test_munch.py::test_get_default_value[Munch]",
"tests/test_munch.py::test_reserved_attributes[__reduce__]",
"tests/test_munch.py::test_delattr",
"tests/test_munch.py::test_automunch",
"tests/test_munch.py::test_reserved_attributes[values]",
"tests/test_munch.py::test_reserved_attributes[__delitem__]",
"tests/test_munch.py::test_reserved_attributes[__delattr__]",
"tests/test_munch.py::test_repr",
"tests/test_munch.py::test_reserved_attributes[__str__]",
"tests/test_munch.py::test_reserved_attributes[__format__]",
"tests/test_munch.py::test_get_default_value[AutoMunch]",
"tests/test_munch.py::test_reserved_attributes[fromYAML]",
"tests/test_munch.py::test_reserved_attributes[__reduce_ex__]",
"tests/test_munch.py::test_fromDict",
"tests/test_munch.py::test_copy_default",
"tests/test_munch.py::test_contains",
"tests/test_munch.py::test_getattr",
"tests/test_munch.py::test_getitem_dunder_for_subclass",
"tests/test_munch.py::test_reserved_attributes[__ror__]",
"tests/test_munch.py::test_setattr",
"tests/test_munch.py::test_fromDict_default_factory",
"tests/test_munch.py::test_reserved_attributes[__dict__]",
"tests/test_munch.py::test_reserved_attributes[__reversed__]",
"tests/test_munch.py::test_reserved_attributes[__setitem__]",
"tests/test_munch.py::test_reserved_attributes[__hash__]",
"tests/test_munch.py::test_reserved_attributes[__weakref__]",
"tests/test_munch.py::test_reserved_attributes[setdefault]",
"tests/test_munch.py::test_reserved_attributes[keys]",
"tests/test_munch.py::test_repr_default_factory",
"tests/test_munch.py::test_base",
"tests/test_munch.py::test_dir",
"tests/test_munch.py::test_unmunchify_namedtuple",
"tests/test_munch.py::test_reserved_attributes[toDict]",
"tests/test_munch.py::test_reserved_attributes[__gt__]",
"tests/test_munch.py::test_munchify_default",
"tests/test_munch.py::test_reserved_attributes[toJSON]",
"tests/test_munch.py::test_reserved_attributes[__dir__]",
"tests/test_munch.py::test_pickle_default",
"tests/test_munch.py::test_reserved_attributes[__len__]",
"tests/test_munch.py::test_munchify_default_factory",
"tests/test_munch.py::test_reserved_attributes[__le__]",
"tests/test_munch.py::test_pickle",
"tests/test_munch.py::test_delattr_default",
"tests/test_munch.py::test_reserved_attributes[toYAML]",
"tests/test_munch.py::test_munchify",
"tests/test_munch.py::test_munchify_cycle",
"tests/test_munch.py::test_reserved_attributes[__eq__]",
"tests/test_munch.py::test_reserved_attributes[__ge__]",
"tests/test_munch.py::test_toJSON",
"tests/test_munch.py::test_reserved_attributes[items]",
"tests/test_munch.py::test_unmunchify_cycle",
"tests/test_munch.py::test_reserved_attributes[__init_subclass__]",
"tests/test_munch.py::test_reserved_attributes[__or__]",
"tests/test_munch.py::test_reserved_attributes[clear]",
"tests/test_munch.py::test_toDict",
"tests/test_munch.py::test_reserved_attributes[__repr__]",
"tests/test_munch.py::test_reserved_attributes[__sizeof__]",
"tests/test_munch.py::test_dict_property",
"tests/test_munch.py::test_reserved_attributes[get]",
"tests/test_munch.py::test_reserved_attributes[__class_getitem__]",
"tests/test_munch.py::test_reserved_attributes[pop]",
"tests/test_munch.py::test_munchify_with_namedtuple",
"tests/test_munch.py::test_reserved_attributes[__doc__]",
"tests/test_munch.py::test_reserved_attributes[__setstate__]",
"tests/test_yaml.py::test_toYAML",
"tests/test_yaml.py::test_from_yaml",
"tests/test_yaml.py::test_fromYAML",
"tests/test_yaml.py::test_to_yaml_safe",
"tests/test_yaml.py::test_to_yaml"
] | {
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2019-10-29T17:36:12Z" | mit |
|
Infinidat__munch-93 | diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 3880744..64954bd 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -40,11 +40,15 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- - uses: actions/setup-python@v4
- # Install the testing dependencies from setup.cfg, including pylint
+ - name: Set up Python ${{ matrix.python-version }}
+ uses: actions/setup-python@v4
+ with:
+ python-version: "3.10"
- name: Upgrade pip
run: python -m pip install --upgrade pip
- - name: Upgrade build tools
+ - name: Upgrade build tools and pytest
run: pip install --upgrade build wheel setuptools
- - run: pip install .[testing]
- - run: pylint munch setup.py tests
+ - name: Install dependencies
+ run: pip install ".[testing,yaml]"
+ - name: Lint
+ run: pylint munch setup.py tests
diff --git a/munch/__init__.py b/munch/__init__.py
index 9d5cde1..c331da0 100644
--- a/munch/__init__.py
+++ b/munch/__init__.py
@@ -442,16 +442,21 @@ def munchify(x, factory=Munch):
seen = dict()
def munchify_cycles(obj):
+ partial, already_seen = pre_munchify_cycles(obj)
+ if already_seen:
+ return partial
+ return post_munchify(partial, obj)
+
+ def pre_munchify_cycles(obj):
# If we've already begun munchifying obj, just return the already-created munchified obj
try:
- return seen[id(obj)]
+ return seen[id(obj)], True
except KeyError:
pass
# Otherwise, first partly munchify obj (but without descending into any lists or dicts) and save that
seen[id(obj)] = partial = pre_munchify(obj)
- # Then finish munchifying lists and dicts inside obj (reusing munchified obj if cycles are encountered)
- return post_munchify(partial, obj)
+ return partial, False
def pre_munchify(obj):
# Here we return a skeleton of munchified obj, which is enough to save for later (in case
@@ -462,7 +467,7 @@ def munchify(x, factory=Munch):
return type(obj)()
elif isinstance(obj, tuple):
type_factory = getattr(obj, "_make", type(obj))
- return type_factory(munchify_cycles(item) for item in obj)
+ return type_factory(pre_munchify_cycles(item)[0] for item in obj)
else:
return obj
| Infinidat/munch | 28c1256e76c00f42aa9315015283f0bba8819c4c | diff --git a/tests/test_munch.py b/tests/test_munch.py
index 9114e3d..c80b757 100644
--- a/tests/test_munch.py
+++ b/tests/test_munch.py
@@ -557,3 +557,17 @@ def test_get_default_value(munch_obj):
munch_cls = type(munch_obj)
kwargs = {} if munch_cls != DefaultFactoryMunch else {"default_factory": munch_obj.default_factory}
munch_cls.fromDict(data, **kwargs)
+
+
+def test_munchify_tuple_list():
+ data = ([{'A': 'B'}],)
+ actual = munchify(data)
+ expected = ([Munch(A='B')],)
+ assert actual == expected
+
+
+def test_munchify_tuple_list_more_elements():
+ data = (1, 2, [{'A': 'B'}])
+ actual = munchify(data)
+ expected = (1, 2, [Munch({'A': 'B'})])
+ assert actual == expected
| munchify broken?
Here is a minimal working example, which is broken. Is this already fixed?
`munchify((1,2,[{'A': 'B'}]))
Result: (1, 2, [Munch({'A': 'B'}), Munch({'A': 'B'})])
Expected: (1, 2, [Munch({'A': 'B'})])` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_munch.py::test_munchify_tuple_list",
"tests/test_munch.py::test_munchify_tuple_list_more_elements"
] | [
"tests/test_munch.py::test_copy",
"tests/test_munch.py::test_reserved_attributes[__getattribute__]",
"tests/test_munch.py::test_dict_property",
"tests/test_munch.py::test_get_default_value[Munch]",
"tests/test_munch.py::test_reserved_attributes[fromYAML]",
"tests/test_munch.py::test_pickling_unpickling_nested",
"tests/test_munch.py::test_repr",
"tests/test_munch.py::test_reserved_attributes[toJSON]",
"tests/test_munch.py::test_reserved_attributes[__str__]",
"tests/test_munch.py::test_reserved_attributes[copy]",
"tests/test_munch.py::test_reserved_attributes[__format__]",
"tests/test_munch.py::test_repr_default_factory",
"tests/test_munch.py::test_getattr_default_factory",
"tests/test_munch.py::test_reserved_attributes[__getattr__]",
"tests/test_munch.py::test_reserved_attributes[__len__]",
"tests/test_munch.py::test_unmunchify",
"tests/test_munch.py::test_fromDict",
"tests/test_munch.py::test_reserved_attributes[__or__]",
"tests/test_munch.py::test_getitem_dunder_for_subclass",
"tests/test_munch.py::test_pickle_default",
"tests/test_munch.py::test_unmunchify_namedtuple",
"tests/test_munch.py::test_repr_default",
"tests/test_munch.py::test_reserved_attributes[__ror__]",
"tests/test_munch.py::test_reserved_attributes[__iter__]",
"tests/test_munch.py::test_get_default_value[DefaultFactoryMunch]",
"tests/test_munch.py::test_delattr",
"tests/test_munch.py::test_reserved_attributes[__delattr__]",
"tests/test_munch.py::test_get_default_value[DefaultMunch]",
"tests/test_munch.py::test_fromDict_default",
"tests/test_munch.py::test_reserved_attributes[__sizeof__]",
"tests/test_munch.py::test_reserved_attributes[__weakref__]",
"tests/test_munch.py::test_reserved_attributes[__getstate__]",
"tests/test_munch.py::test_reserved_attributes[fromJSON]",
"tests/test_munch.py::test_reserved_attributes[keys]",
"tests/test_munch.py::test_setitem_dunder_for_subclass",
"tests/test_munch.py::test_reserved_attributes[__members__]",
"tests/test_munch.py::test_reserved_attributes[__lt__]",
"tests/test_munch.py::test_reserved_attributes[__setitem__]",
"tests/test_munch.py::test_reserved_attributes[__class__]",
"tests/test_munch.py::test_reserved_attributes[fromDict]",
"tests/test_munch.py::test_reserved_attributes[__contains__]",
"tests/test_munch.py::test_reserved_attributes[values]",
"tests/test_munch.py::test_reserved_attributes[__dir__]",
"tests/test_munch.py::test_copy_default_factory",
"tests/test_munch.py::test_reserved_attributes[toDict]",
"tests/test_munch.py::test_getattr_default",
"tests/test_munch.py::test_reserved_attributes[__dict__]",
"tests/test_munch.py::test_getattr",
"tests/test_munch.py::test_reserved_attributes[pop]",
"tests/test_munch.py::test_toDict",
"tests/test_munch.py::test_reserved_attributes[__setattr__]",
"tests/test_munch.py::test_munchify_cycle",
"tests/test_munch.py::test_reserved_attributes[__doc__]",
"tests/test_munch.py::test_contains",
"tests/test_munch.py::test_reserved_attributes[__init__]",
"tests/test_munch.py::test_reserved_attributes[__getitem__]",
"tests/test_munch.py::test_copy_default",
"tests/test_munch.py::test_reserved_attributes[get]",
"tests/test_munch.py::test_reserved_attributes[__setstate__]",
"tests/test_munch.py::test_base",
"tests/test_munch.py::test_unmunchify_cycle",
"tests/test_munch.py::test_munchify_with_namedtuple",
"tests/test_munch.py::test_setattr_default_factory",
"tests/test_munch.py::test_reserved_attributes[__reduce__]",
"tests/test_munch.py::test_reserved_attributes[__module__]",
"tests/test_munch.py::test_get_default_value[RecursiveMunch]",
"tests/test_munch.py::test_reserved_attributes[__reversed__]",
"tests/test_munch.py::test_setattr",
"tests/test_munch.py::test_reserved_attributes[__gt__]",
"tests/test_munch.py::test_reserved_attributes[fromkeys]",
"tests/test_munch.py::test_reserved_attributes[clear]",
"tests/test_munch.py::test_reserved_attributes[__subclasshook__]",
"tests/test_munch.py::test_reserved_attributes[__eq__]",
"tests/test_munch.py::test_reserved_attributes[__reduce_ex__]",
"tests/test_munch.py::test_reserved_attributes[__new__]",
"tests/test_munch.py::test_dir",
"tests/test_munch.py::test_reserved_attributes[__ne__]",
"tests/test_munch.py::test_reserved_attributes[setdefault]",
"tests/test_munch.py::test_reserved_attributes[__hash__]",
"tests/test_munch.py::test_reserved_attributes[popitem]",
"tests/test_munch.py::test_delattr_default",
"tests/test_munch.py::test_munchify_default_factory",
"tests/test_munch.py::test_reserved_attributes[__le__]",
"tests/test_munch.py::test_reserved_attributes[__class_getitem__]",
"tests/test_munch.py::test_reserved_attributes[update]",
"tests/test_munch.py::test_fromDict_default_factory",
"tests/test_munch.py::test_toJSON_and_fromJSON",
"tests/test_munch.py::test_setattr_default",
"tests/test_munch.py::test_reserved_attributes[toYAML]",
"tests/test_munch.py::test_reserved_attributes[__delitem__]",
"tests/test_munch.py::test_reserved_attributes[__init_subclass__]",
"tests/test_munch.py::test_pickle",
"tests/test_munch.py::test_munchify",
"tests/test_munch.py::test_get_default_value[AutoMunch]",
"tests/test_munch.py::test_reserved_attributes[__ge__]",
"tests/test_munch.py::test_reserved_attributes[__ior__]",
"tests/test_munch.py::test_delattr_default_factory",
"tests/test_munch.py::test_munchify_default",
"tests/test_munch.py::test_reserved_attributes[__repr__]",
"tests/test_munch.py::test_reserved_attributes[items]",
"tests/test_munch.py::test_automunch"
] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2023-01-17T07:12:19Z" | mit |
|
Informasjonsforvaltning__datacatalogtordf-69 | diff --git a/src/datacatalogtordf/dataset.py b/src/datacatalogtordf/dataset.py
index 419f9be..92eb7bb 100644
--- a/src/datacatalogtordf/dataset.py
+++ b/src/datacatalogtordf/dataset.py
@@ -54,7 +54,8 @@ class Dataset(Resource):
spatial_resolution (Decimal): Minimum spatial separation resolvable \
in a dataset, measured in meters.
temporal_coverage (PeriodOfTime): The temporal period that the dataset covers.
- temporal_resolution (str): Minimum time period resolvable in the dataset.
+ temporal_resolution (List[str]): A list of minimum time period resolvables in \
+ the dataset.
was_generated_by (URI): A link to an activity that generated, \
or provides the business context for, the creation of the dataset.
access_rights_comments (List[URI]): Referanse til hjemmel \
@@ -82,7 +83,7 @@ class Dataset(Resource):
_spatial: List[Union[Location, str]]
_spatial_resolution: Decimal
_temporal_coverage: PeriodOfTime
- _temporal_resolution: str
+ _temporal_resolution: List[str]
_was_generated_by: URI
_access_rights_comments: List[str]
_dct_identifier: str
@@ -143,12 +144,12 @@ class Dataset(Resource):
self._temporal_coverage = temporal_coverage
@property
- def temporal_resolution(self: Dataset) -> str:
+ def temporal_resolution(self: Dataset) -> List[str]:
"""Get/set for temporal_resolution."""
return self._temporal_resolution
@temporal_resolution.setter
- def temporal_resolution(self: Dataset, temporal_resolution: str) -> None:
+ def temporal_resolution(self: Dataset, temporal_resolution: List[str]) -> None:
self._temporal_resolution = temporal_resolution
@property
@@ -320,13 +321,14 @@ class Dataset(Resource):
def _temporal_resolution_to_graph(self: Dataset) -> None:
if getattr(self, "temporal_resolution", None):
- self._g.add(
- (
- URIRef(self.identifier),
- DCAT.temporalResolution,
- Literal(self.temporal_resolution, datatype=XSD.duration),
+ for temporal_resolution in self.temporal_resolution:
+ self._g.add(
+ (
+ URIRef(self.identifier),
+ DCAT.temporalResolution,
+ Literal(temporal_resolution, datatype=XSD.duration),
+ )
)
- )
def _was_generated_by_to_graph(self: Dataset) -> None:
if getattr(self, "was_generated_by", None):
diff --git a/src/datacatalogtordf/distribution.py b/src/datacatalogtordf/distribution.py
index 6555ddc..ae9013c 100644
--- a/src/datacatalogtordf/distribution.py
+++ b/src/datacatalogtordf/distribution.py
@@ -66,7 +66,7 @@ class Distribution:
byte_size (Decimal): The size of a distribution in bytes.
spatial_resolution (Decimal): The minimum spatial separation resolvable \
in a dataset distribution, measured in meters.
- temporal_resolution (str): Minimum time period resolvable in the \
+ temporal_resolution (List[str]): A list of minimum time period resolvables in the \
dataset distribution.
conforms_to (List[URI]): A list of links to established standards \
to which the distribution conforms.
@@ -120,7 +120,7 @@ class Distribution:
_download_URL: URI
_byte_size: Decimal
_spatial_resolution: Decimal
- _temporal_resolution: str
+ _temporal_resolution: List[str]
_conforms_to: List[str]
_media_types: List[str]
_formats: List[str]
@@ -263,12 +263,12 @@ class Distribution:
self._spatial_resolution = spatial_resolution
@property
- def temporal_resolution(self: Distribution) -> str:
+ def temporal_resolution(self: Distribution) -> List[str]:
"""Get/set for temporal_resolution."""
return self._temporal_resolution
@temporal_resolution.setter
- def temporal_resolution(self: Distribution, temporal_resolution: str) -> None:
+ def temporal_resolution(self: Distribution, temporal_resolution: List[str]) -> None:
self._temporal_resolution = temporal_resolution
@property
@@ -469,13 +469,14 @@ class Distribution:
def _temporal_resolution_to_graph(self: Distribution) -> None:
if getattr(self, "temporal_resolution", None):
- self._g.add(
- (
- URIRef(self.identifier),
- DCAT.temporalResolution,
- Literal(self.temporal_resolution, datatype=XSD.duration),
+ for temporal_resolution in self.temporal_resolution:
+ self._g.add(
+ (
+ URIRef(self.identifier),
+ DCAT.temporalResolution,
+ Literal(temporal_resolution, datatype=XSD.duration),
+ )
)
- )
def _conforms_to_to_graph(self: Distribution) -> None:
if getattr(self, "conforms_to", None):
| Informasjonsforvaltning/datacatalogtordf | 20d2ddbf36c19a2bd6621dec3ecf64e50d021866 | diff --git a/tests/test_dataset.py b/tests/test_dataset.py
index 0a8c0c9..c7467cf 100644
--- a/tests/test_dataset.py
+++ b/tests/test_dataset.py
@@ -311,7 +311,7 @@ def test_to_graph_should_return_temporal_resolution() -> None:
"""It returns a temporal resolution graph isomorphic to spec."""
dataset = Dataset()
dataset.identifier = "http://example.com/datasets/1"
- dataset.temporal_resolution = "PT15M"
+ dataset.temporal_resolution = ["PT15M"]
src = """
@prefix dct: <http://purl.org/dc/terms/> .
diff --git a/tests/test_distribution.py b/tests/test_distribution.py
index 9160e75..bb54cb8 100644
--- a/tests/test_distribution.py
+++ b/tests/test_distribution.py
@@ -452,7 +452,7 @@ def test_to_graph_should_return_temporal_resolution() -> None:
"""It returns a temporal resolution graph isomorphic to spec."""
distribution = Distribution()
distribution.identifier = "http://example.com/distributions/1"
- distribution.temporal_resolution = "PT15M"
+ distribution.temporal_resolution = ["PT15M"]
src = """
@prefix dct: <http://purl.org/dc/terms/> .
| temporal_resolution property should be a list | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_dataset.py::test_to_graph_should_return_temporal_resolution",
"tests/test_distribution.py::test_to_graph_should_return_temporal_resolution"
] | [
"tests/test_dataset.py::test_to_graph_should_return_identifier_set_at_constructor",
"tests/test_dataset.py::test_to_graph_should_return_skolemization",
"tests/test_dataset.py::test_to_graph_should_return_distribution_as_graph",
"tests/test_dataset.py::test_to_graph_should_return_distribution_skolemized",
"tests/test_dataset.py::test_to_graph_should_return_included_distribution_as_graph",
"tests/test_dataset.py::test_to_graph_should_return_frequency",
"tests/test_dataset.py::test_to_graph_should_return_spatial",
"tests/test_dataset.py::test_to_graph_should_return_spatial_resolution",
"tests/test_dataset.py::test_to_graph_should_return_temporal_coverage",
"tests/test_dataset.py::test_to_graph_should_return_was_generated_by",
"tests/test_dataset.py::test_to_graph_should_return_access_rights_comment",
"tests/test_dataset.py::test_to_graph_should_return_link_to_spatial",
"tests/test_dataset.py::test_to_graph_should_return_link_to_spatial_with_location_triple",
"tests/test_dataset.py::test_to_graph_should_return_dct_identifier_as_graph",
"tests/test_distribution.py::test_to_graph_should_return_identifier_set_at_constructor",
"tests/test_distribution.py::test_to_graph_should_return_skolemization",
"tests/test_distribution.py::test_to_graph_should_return_title_as_graph",
"tests/test_distribution.py::test_to_graph_should_return_description",
"tests/test_distribution.py::test_to_graph_should_return_release_date",
"tests/test_distribution.py::test_to_graph_should_return_modification_date",
"tests/test_distribution.py::test_to_graph_should_return_license",
"tests/test_distribution.py::test_to_graph_should_return_access_rights",
"tests/test_distribution.py::test_to_graph_should_return_rights",
"tests/test_distribution.py::test_to_graph_should_return_has_policy",
"tests/test_distribution.py::test_to_graph_should_return_access_URL",
"tests/test_distribution.py::test_to_graph_should_return_access_service",
"tests/test_distribution.py::test_to_graph_should_return_access_service_skolemized",
"tests/test_distribution.py::test_to_graph_should_return_download_URL",
"tests/test_distribution.py::test_to_graph_should_return_byte_size",
"tests/test_distribution.py::test_to_graph_should_return_spatial_resolution",
"tests/test_distribution.py::test_to_graph_should_return_conforms_to",
"tests/test_distribution.py::test_to_graph_should_return_media_type",
"tests/test_distribution.py::test_to_graph_should_return_format",
"tests/test_distribution.py::test_to_graph_should_return_compression_format",
"tests/test_distribution.py::test_to_graph_should_return_packaging_format"
] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2022-05-23T09:01:29Z" | apache-2.0 |
|
Instagram__LibCST-356 | diff --git a/libcst/matchers/_matcher_base.py b/libcst/matchers/_matcher_base.py
index 27475d5..0cf281c 100644
--- a/libcst/matchers/_matcher_base.py
+++ b/libcst/matchers/_matcher_base.py
@@ -932,6 +932,24 @@ def SaveMatchedNode(matcher: _OtherNodeT, name: str) -> _OtherNodeT:
return cast(_OtherNodeT, _ExtractMatchingNode(matcher, name))
+def _matches_zero_nodes(
+ matcher: Union[
+ BaseMatcherNode,
+ _BaseWildcardNode,
+ MatchIfTrue[Callable[[object], bool]],
+ _BaseMetadataMatcher,
+ DoNotCareSentinel,
+ ]
+) -> bool:
+ if isinstance(matcher, AtLeastN) and matcher.n == 0:
+ return True
+ if isinstance(matcher, AtMostN):
+ return True
+ if isinstance(matcher, _ExtractMatchingNode):
+ return _matches_zero_nodes(matcher.matcher)
+ return False
+
+
@dataclass(frozen=True)
class _SequenceMatchesResult:
sequence_capture: Optional[
@@ -960,14 +978,13 @@ def _sequence_matches( # noqa: C901
return _SequenceMatchesResult({}, None)
if not nodes and matchers:
# Base case, we have one or more matcher that wasn't matched
- return (
- _SequenceMatchesResult({}, [])
- if all(
- (isinstance(m, AtLeastN) and m.n == 0) or isinstance(m, AtMostN)
- for m in matchers
+ if all(_matches_zero_nodes(m) for m in matchers):
+ return _SequenceMatchesResult(
+ {m.name: () for m in matchers if isinstance(m, _ExtractMatchingNode)},
+ (),
)
- else _SequenceMatchesResult(None, None)
- )
+ else:
+ return _SequenceMatchesResult(None, None)
if nodes and not matchers:
# Base case, we have nodes left that don't match any matcher
return _SequenceMatchesResult(None, None)
| Instagram/LibCST | 3ada79ebcb14224e0c0cd4e40a622540656cc0e3 | diff --git a/libcst/matchers/tests/test_extract.py b/libcst/matchers/tests/test_extract.py
index 5c3cf12..77c134a 100644
--- a/libcst/matchers/tests/test_extract.py
+++ b/libcst/matchers/tests/test_extract.py
@@ -322,6 +322,34 @@ class MatchersExtractTest(UnitTest):
)
self.assertEqual(nodes, {})
+ def test_extract_optional_wildcard_head(self) -> None:
+ expression = cst.parse_expression("[3]")
+ nodes = m.extract(
+ expression,
+ m.List(
+ elements=[
+ m.SaveMatchedNode(m.ZeroOrMore(), "head1"),
+ m.SaveMatchedNode(m.ZeroOrMore(), "head2"),
+ m.Element(value=m.Integer(value="3")),
+ ]
+ ),
+ )
+ self.assertEqual(nodes, {"head1": (), "head2": ()})
+
+ def test_extract_optional_wildcard_tail(self) -> None:
+ expression = cst.parse_expression("[3]")
+ nodes = m.extract(
+ expression,
+ m.List(
+ elements=[
+ m.Element(value=m.Integer(value="3")),
+ m.SaveMatchedNode(m.ZeroOrMore(), "tail1"),
+ m.SaveMatchedNode(m.ZeroOrMore(), "tail2"),
+ ]
+ ),
+ )
+ self.assertEqual(nodes, {"tail1": (), "tail2": ()})
+
def test_extract_optional_wildcard_present(self) -> None:
expression = cst.parse_expression("a + b[c], d(e, f * g, h.i.j)")
nodes = m.extract(
| [BUG] SavedMatchedNode affects matching
Wrapping a matcher with `SaveMatchedNode` sometimes breaks the matching.
`libcst` version: 0.3.7 (installed with pip)
See the test below
```py
import libcst.matchers as m
import libcst
node = libcst.parse_expression("[1, 2, 3]")
matcher = m.List(
elements=[
m.SaveMatchedNode(m.AtMostN(n=2), "head"),
m.SaveMatchedNode(m.Element(value=m.Integer(value="3")), "element"),
m.AtMostN(n=1),
]
)
print(m.extract(node, matcher))
print(m.matches(node, matcher))
matcher = m.List(
elements=[
m.SaveMatchedNode(m.AtMostN(n=2), "head"),
m.SaveMatchedNode(m.Element(value=m.Integer(value="3")), "element"),
m.SaveMatchedNode(m.AtMostN(n=1), "tail"),
]
)
print(m.extract(node, matcher))
print(m.matches(node, matcher))
```
The first matcher fails, while the second succeeds. The only difference is the `tail` `SaveMatchedNode`. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"libcst/matchers/tests/test_extract.py::MatchersExtractTest::test_extract_optional_wildcard_tail"
] | [
"libcst/matchers/tests/test_extract.py::MatchersExtractTest::test_extract_precedence_sequence_wildcard",
"libcst/matchers/tests/test_extract.py::MatchersExtractTest::test_extract_sequence",
"libcst/matchers/tests/test_extract.py::MatchersExtractTest::test_extract_sentinel",
"libcst/matchers/tests/test_extract.py::MatchersExtractTest::test_extract_precedence_parent",
"libcst/matchers/tests/test_extract.py::MatchersExtractTest::test_extract_simple",
"libcst/matchers/tests/test_extract.py::MatchersExtractTest::test_extract_sequence_multiple_wildcards",
"libcst/matchers/tests/test_extract.py::MatchersExtractTest::test_extract_precedence_sequence",
"libcst/matchers/tests/test_extract.py::MatchersExtractTest::test_extract_tautology",
"libcst/matchers/tests/test_extract.py::MatchersExtractTest::test_extract_optional_wildcard",
"libcst/matchers/tests/test_extract.py::MatchersExtractTest::test_extract_optional_wildcard_head",
"libcst/matchers/tests/test_extract.py::MatchersExtractTest::test_extract_optional_wildcard_present",
"libcst/matchers/tests/test_extract.py::MatchersExtractTest::test_extract_metadata",
"libcst/matchers/tests/test_extract.py::MatchersExtractTest::test_extract_sequence_element",
"libcst/matchers/tests/test_extract.py::MatchersExtractTest::test_extract_predicates",
"libcst/matchers/tests/test_extract.py::MatchersExtractTest::test_extract_multiple"
] | {
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
} | "2020-08-02T14:27:42Z" | mit |
|
Instagram__LibCST-417 | diff --git a/libcst/_parser/conversions/expression.py b/libcst/_parser/conversions/expression.py
index 8edbf26..e66f836 100644
--- a/libcst/_parser/conversions/expression.py
+++ b/libcst/_parser/conversions/expression.py
@@ -1441,8 +1441,16 @@ def convert_arg_assign_comp_for(
elt, for_in = children
return Arg(value=GeneratorExp(elt.value, for_in, lpar=(), rpar=()))
else:
- # "key = value" assignment argument
lhs, equal, rhs = children
+ # "key := value" assignment; positional
+ if equal.string == ":=":
+ val = convert_namedexpr_test(config, children)
+ if not isinstance(val, WithLeadingWhitespace):
+ raise Exception(
+ f"convert_namedexpr_test returned {val!r}, not WithLeadingWhitespace"
+ )
+ return Arg(value=val.value)
+ # "key = value" assignment; keyword argument
return Arg(
keyword=lhs.value,
equal=AssignEqual(
| Instagram/LibCST | 7478d738ea4911b51fe8c0758a6a405f7ce9c98a | diff --git a/libcst/_nodes/tests/test_namedexpr.py b/libcst/_nodes/tests/test_namedexpr.py
index 4ba1485..3949bbe 100644
--- a/libcst/_nodes/tests/test_namedexpr.py
+++ b/libcst/_nodes/tests/test_namedexpr.py
@@ -101,6 +101,71 @@ class NamedExprTest(CSTNodeTest):
"parser": _parse_statement_force_38,
"expected_position": None,
},
+ # Function args
+ {
+ "node": cst.Call(
+ func=cst.Name(value="f"),
+ args=[
+ cst.Arg(
+ value=cst.NamedExpr(
+ target=cst.Name(value="y"),
+ value=cst.Integer(value="1"),
+ whitespace_before_walrus=cst.SimpleWhitespace(""),
+ whitespace_after_walrus=cst.SimpleWhitespace(""),
+ )
+ ),
+ ],
+ ),
+ "code": "f(y:=1)",
+ "parser": _parse_expression_force_38,
+ "expected_position": None,
+ },
+ # Whitespace handling on args is fragile
+ {
+ "node": cst.Call(
+ func=cst.Name(value="f"),
+ args=[
+ cst.Arg(
+ value=cst.Name(value="x"),
+ comma=cst.Comma(
+ whitespace_after=cst.SimpleWhitespace(" ")
+ ),
+ ),
+ cst.Arg(
+ value=cst.NamedExpr(
+ target=cst.Name(value="y"),
+ value=cst.Integer(value="1"),
+ whitespace_before_walrus=cst.SimpleWhitespace(" "),
+ whitespace_after_walrus=cst.SimpleWhitespace(" "),
+ ),
+ whitespace_after_arg=cst.SimpleWhitespace(" "),
+ ),
+ ],
+ ),
+ "code": "f(x, y := 1 )",
+ "parser": _parse_expression_force_38,
+ "expected_position": None,
+ },
+ {
+ "node": cst.Call(
+ func=cst.Name(value="f"),
+ args=[
+ cst.Arg(
+ value=cst.NamedExpr(
+ target=cst.Name(value="y"),
+ value=cst.Integer(value="1"),
+ whitespace_before_walrus=cst.SimpleWhitespace(" "),
+ whitespace_after_walrus=cst.SimpleWhitespace(" "),
+ ),
+ whitespace_after_arg=cst.SimpleWhitespace(" "),
+ ),
+ ],
+ whitespace_before_args=cst.SimpleWhitespace(" "),
+ ),
+ "code": "f( y := 1 )",
+ "parser": _parse_expression_force_38,
+ "expected_position": None,
+ },
)
)
def test_valid(self, **kwargs: Any) -> None:
| Function call with walrus loses colon in roundtrip
This input
```
f(x:=1)
```
is roundtripped as
```
f(x=1)
```
due to a parse error.
I'm fairly certain the problem is the grammar on https://github.com/Instagram/LibCST/blob/master/libcst/_parser/conversions/expression.py#L1430 not matching namedexpr_test nor doing anything but AssignEqual in the else case. I tried to alter the grammar there to use namedexpr_test, but that caused ambiguity.
Going the other route to fix, we'll need another case to fix because this is the first positional arg, not a kwarg. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"libcst/_nodes/tests/test_namedexpr.py::NamedExprTest::test_valid_8",
"libcst/_nodes/tests/test_namedexpr.py::NamedExprTest::test_valid_6",
"libcst/_nodes/tests/test_namedexpr.py::NamedExprTest::test_valid_7"
] | [
"libcst/_nodes/tests/test_namedexpr.py::NamedExprTest::test_invalid_1",
"libcst/_nodes/tests/test_namedexpr.py::NamedExprTest::test_valid_1",
"libcst/_nodes/tests/test_namedexpr.py::NamedExprTest::test_valid_4",
"libcst/_nodes/tests/test_namedexpr.py::NamedExprTest::test_invalid_0",
"libcst/_nodes/tests/test_namedexpr.py::NamedExprTest::test_valid_0",
"libcst/_nodes/tests/test_namedexpr.py::NamedExprTest::test_valid_3",
"libcst/_nodes/tests/test_namedexpr.py::NamedExprTest::test_valid_5",
"libcst/_nodes/tests/test_namedexpr.py::NamedExprTest::test_valid_2"
] | {
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
} | "2020-11-11T22:25:05Z" | mit |
|
Instagram__LibCST-419 | diff --git a/libcst/_parser/conversions/expression.py b/libcst/_parser/conversions/expression.py
index 8edbf26..b7e5c18 100644
--- a/libcst/_parser/conversions/expression.py
+++ b/libcst/_parser/conversions/expression.py
@@ -1038,12 +1038,12 @@ def convert_fstring_equality(
@with_production(
"fstring_expr",
- "'{' testlist [ fstring_equality ] [ fstring_conversion ] [ fstring_format_spec ] '}'",
+ "'{' testlist_comp_tuple [ fstring_equality ] [ fstring_conversion ] [ fstring_format_spec ] '}'",
version=">=3.8",
)
@with_production(
"fstring_expr",
- "'{' testlist [ fstring_conversion ] [ fstring_format_spec ] '}'",
+ "'{' testlist_comp_tuple [ fstring_conversion ] [ fstring_format_spec ] '}'",
version="<=3.7",
)
def convert_fstring_expr(
@@ -1441,8 +1441,16 @@ def convert_arg_assign_comp_for(
elt, for_in = children
return Arg(value=GeneratorExp(elt.value, for_in, lpar=(), rpar=()))
else:
- # "key = value" assignment argument
lhs, equal, rhs = children
+ # "key := value" assignment; positional
+ if equal.string == ":=":
+ val = convert_namedexpr_test(config, children)
+ if not isinstance(val, WithLeadingWhitespace):
+ raise Exception(
+ f"convert_namedexpr_test returned {val!r}, not WithLeadingWhitespace"
+ )
+ return Arg(value=val.value)
+ # "key = value" assignment; keyword argument
return Arg(
keyword=lhs.value,
equal=AssignEqual(
| Instagram/LibCST | 7478d738ea4911b51fe8c0758a6a405f7ce9c98a | diff --git a/libcst/_nodes/tests/test_atom.py b/libcst/_nodes/tests/test_atom.py
index 452c9f7..1a14e37 100644
--- a/libcst/_nodes/tests/test_atom.py
+++ b/libcst/_nodes/tests/test_atom.py
@@ -668,6 +668,35 @@ class AtomTest(CSTNodeTest):
"parser": parse_expression,
"expected_position": CodeRange((1, 1), (1, 4)),
},
+ # Generator expression (doesn't make sense, but legal syntax)
+ {
+ "node": cst.FormattedString(
+ start='f"',
+ parts=[
+ cst.FormattedStringExpression(
+ expression=cst.GeneratorExp(
+ elt=cst.Name(
+ value="x",
+ ),
+ for_in=cst.CompFor(
+ target=cst.Name(
+ value="x",
+ ),
+ iter=cst.Name(
+ value="y",
+ ),
+ ),
+ lpar=[],
+ rpar=[],
+ ),
+ ),
+ ],
+ end='"',
+ ),
+ "code": 'f"{x for x in y}"',
+ "parser": parse_expression,
+ "expected_position": None,
+ },
# Concatenated strings
{
"node": cst.ConcatenatedString(
diff --git a/libcst/_nodes/tests/test_namedexpr.py b/libcst/_nodes/tests/test_namedexpr.py
index 4ba1485..3949bbe 100644
--- a/libcst/_nodes/tests/test_namedexpr.py
+++ b/libcst/_nodes/tests/test_namedexpr.py
@@ -101,6 +101,71 @@ class NamedExprTest(CSTNodeTest):
"parser": _parse_statement_force_38,
"expected_position": None,
},
+ # Function args
+ {
+ "node": cst.Call(
+ func=cst.Name(value="f"),
+ args=[
+ cst.Arg(
+ value=cst.NamedExpr(
+ target=cst.Name(value="y"),
+ value=cst.Integer(value="1"),
+ whitespace_before_walrus=cst.SimpleWhitespace(""),
+ whitespace_after_walrus=cst.SimpleWhitespace(""),
+ )
+ ),
+ ],
+ ),
+ "code": "f(y:=1)",
+ "parser": _parse_expression_force_38,
+ "expected_position": None,
+ },
+ # Whitespace handling on args is fragile
+ {
+ "node": cst.Call(
+ func=cst.Name(value="f"),
+ args=[
+ cst.Arg(
+ value=cst.Name(value="x"),
+ comma=cst.Comma(
+ whitespace_after=cst.SimpleWhitespace(" ")
+ ),
+ ),
+ cst.Arg(
+ value=cst.NamedExpr(
+ target=cst.Name(value="y"),
+ value=cst.Integer(value="1"),
+ whitespace_before_walrus=cst.SimpleWhitespace(" "),
+ whitespace_after_walrus=cst.SimpleWhitespace(" "),
+ ),
+ whitespace_after_arg=cst.SimpleWhitespace(" "),
+ ),
+ ],
+ ),
+ "code": "f(x, y := 1 )",
+ "parser": _parse_expression_force_38,
+ "expected_position": None,
+ },
+ {
+ "node": cst.Call(
+ func=cst.Name(value="f"),
+ args=[
+ cst.Arg(
+ value=cst.NamedExpr(
+ target=cst.Name(value="y"),
+ value=cst.Integer(value="1"),
+ whitespace_before_walrus=cst.SimpleWhitespace(" "),
+ whitespace_after_walrus=cst.SimpleWhitespace(" "),
+ ),
+ whitespace_after_arg=cst.SimpleWhitespace(" "),
+ ),
+ ],
+ whitespace_before_args=cst.SimpleWhitespace(" "),
+ ),
+ "code": "f( y := 1 )",
+ "parser": _parse_expression_force_38,
+ "expected_position": None,
+ },
)
)
def test_valid(self, **kwargs: Any) -> None:
| parse error for comprehensions in f-strings
```
β― cat test.py
x = [1, 2]
print(f"List of: {y for y in x}")
β― python3 test.py
List of: <generator object <genexpr> at 0x7facdf7d8258>
β― libcst print test.py
Traceback (most recent call last):
File "/opt/instagram/virtualenv/lib/python3.7/site-packages/fbcode/libcst/_parser/base_parser.py", line 152, in _add_token
plan = stack[-1].dfa.transitions[transition]
KeyError: ReservedString(for)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/opt/instagram/virtualenv/lib/python3.7/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "/opt/instagram/virtualenv/lib/python3.7/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/opt/instagram/virtualenv/lib/python3.7/site-packages/fbcode/libcst/tool.py", line 832, in <module>
main(os.environ.get("LIBCST_TOOL_COMMAND_NAME", "libcst.tool"), sys.argv[1:])
File "/opt/instagram/virtualenv/lib/python3.7/site-packages/fbcode/libcst/tool.py", line 827, in main
return lookup.get(args.action or None, _invalid_command)(proc_name, command_args)
File "/opt/instagram/virtualenv/lib/python3.7/site-packages/fbcode/libcst/tool.py", line 277, in _print_tree_impl
else PartialParserConfig()
File "/opt/instagram/virtualenv/lib/python3.7/site-packages/fbcode/libcst/_parser/entrypoints.py", line 76, in parse_module
detect_default_newline=True,
File "/opt/instagram/virtualenv/lib/python3.7/site-packages/fbcode/libcst/_parser/entrypoints.py", line 51, in _parse
result = parser.parse()
File "/opt/instagram/virtualenv/lib/python3.7/site-packages/fbcode/libcst/_parser/base_parser.py", line 111, in parse
self._add_token(token)
File "/opt/instagram/virtualenv/lib/python3.7/site-packages/fbcode/libcst/_parser/base_parser.py", line 191, in _add_token
raw_column=token.start_pos[1],
libcst._exceptions.ParserSyntaxError: Syntax Error @ 2:21.
Incomplete input. Encountered 'for', but expected '!', ':', or '}'.
print(f"List of: {y for y in x}")
``` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_68",
"libcst/_nodes/tests/test_namedexpr.py::NamedExprTest::test_valid_7",
"libcst/_nodes/tests/test_namedexpr.py::NamedExprTest::test_valid_8",
"libcst/_nodes/tests/test_namedexpr.py::NamedExprTest::test_valid_6"
] | [
"libcst/_nodes/tests/test_atom.py::AtomTest::test_invalid_7",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_57",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_invalid_23",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_invalid_18",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_invalid_8",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_51",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_invalid_20",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_30",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_71",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_32",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_invalid_48",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_invalid_35",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_54",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_18",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_44",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_invalid_15",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_16",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_33",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_20",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_invalid_29",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_7",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_invalid_45",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_invalid_32",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_invalid_46",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_65",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_invalid_22",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_26",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_59",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_1",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_52",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_invalid_12",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_invalid_38",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_invalid_26",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_invalid_3",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_56",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_74",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_60",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_invalid_14",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_47",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_invalid_27",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_invalid_11",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_10",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_31",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_invalid_31",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_55",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_invalid_36",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_invalid_2",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_38",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_29",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_invalid_43",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_invalid_5",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_62",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_3",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_42",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_invalid_47",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_72",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_49",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_invalid_50",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_15",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_8",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_73",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_invalid_21",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_invalid_4",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_invalid_24",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_21",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_35",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_41",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_invalid_37",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_invalid_41",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_invalid_28",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_28",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_0",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_invalid_0",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_invalid_10",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_invalid_33",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_70",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_invalid_25",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_versions_0",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_invalid_49",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_invalid_39",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_64",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_11",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_invalid_30",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_invalid_44",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_69",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_61",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_19",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_5",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_invalid_1",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_58",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_no_parse_0",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_27",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_invalid_42",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_66",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_invalid_16",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_14",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_46",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_4",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_invalid_6",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_48",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_invalid_40",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_40",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_23",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_invalid_17",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_22",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_37",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_invalid_34",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_2",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_25",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_12",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_6",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_36",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_13",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_invalid_51",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_67",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_invalid_9",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_43",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_50",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_17",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_versions_1",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_invalid_13",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_39",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_45",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_9",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_53",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_24",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_34",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_invalid_19",
"libcst/_nodes/tests/test_atom.py::AtomTest::test_valid_63",
"libcst/_nodes/tests/test_atom.py::StringHelperTest::test_string_prefix_and_quotes",
"libcst/_nodes/tests/test_namedexpr.py::NamedExprTest::test_invalid_1",
"libcst/_nodes/tests/test_namedexpr.py::NamedExprTest::test_valid_2",
"libcst/_nodes/tests/test_namedexpr.py::NamedExprTest::test_valid_0",
"libcst/_nodes/tests/test_namedexpr.py::NamedExprTest::test_valid_1",
"libcst/_nodes/tests/test_namedexpr.py::NamedExprTest::test_valid_3",
"libcst/_nodes/tests/test_namedexpr.py::NamedExprTest::test_valid_5",
"libcst/_nodes/tests/test_namedexpr.py::NamedExprTest::test_invalid_0",
"libcst/_nodes/tests/test_namedexpr.py::NamedExprTest::test_valid_4"
] | {
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
} | "2020-11-13T03:15:50Z" | mit |
|
Instagram__LibCST-429 | diff --git a/libcst/matchers/_visitors.py b/libcst/matchers/_visitors.py
index 301e675..be50edf 100644
--- a/libcst/matchers/_visitors.py
+++ b/libcst/matchers/_visitors.py
@@ -79,8 +79,18 @@ def _get_possible_match_classes(matcher: BaseMatcherNode) -> List[Type[cst.CSTNo
return [getattr(cst, matcher.__class__.__name__)]
-def _get_possible_annotated_classes(annotation: object) -> List[Type[object]]:
+def _annotation_looks_like_union(annotation: object) -> bool:
if getattr(annotation, "__origin__", None) is Union:
+ return True
+ # support PEP-604 style unions introduced in Python 3.10
+ return (
+ annotation.__class__.__name__ == "Union"
+ and annotation.__class__.__module__ == "types"
+ )
+
+
+def _get_possible_annotated_classes(annotation: object) -> List[Type[object]]:
+ if _annotation_looks_like_union(annotation):
return getattr(annotation, "__args__", [])
else:
return [cast(Type[object], annotation)]
diff --git a/libcst/metadata/scope_provider.py b/libcst/metadata/scope_provider.py
index 580cc11..b5c6ba6 100644
--- a/libcst/metadata/scope_provider.py
+++ b/libcst/metadata/scope_provider.py
@@ -45,7 +45,6 @@ _ASSIGNMENT_LIKE_NODES = (
cst.AugAssign,
cst.ClassDef,
cst.CompFor,
- cst.For,
cst.FunctionDef,
cst.Global,
cst.Import,
@@ -125,7 +124,7 @@ class Access:
for assignment in assignments
if assignment.scope != self.scope or assignment._index < self.__index
}
- if not previous_assignments and assignments:
+ if not previous_assignments and assignments and self.scope.parent != self.scope:
previous_assignments = self.scope.parent[name]
self.__assignments |= previous_assignments
@@ -993,6 +992,14 @@ class ScopeVisitor(cst.CSTVisitor):
node.elt.visit(self)
return False
+ def visit_For(self, node: cst.For) -> Optional[bool]:
+ node.target.visit(self)
+ self.scope._assignment_count += 1
+ for child in [node.iter, node.body, node.orelse, node.asynchronous]:
+ if child is not None:
+ child.visit(self)
+ return False
+
def infer_accesses(self) -> None:
# Aggregate access with the same name and batch add with set union as an optimization.
# In worst case, all accesses (m) and assignments (n) refer to the same name,
| Instagram/LibCST | 2f117f0bc3f718b9cc203dfbd6c9f0530ec043c1 | diff --git a/libcst/matchers/tests/test_decorators.py b/libcst/matchers/tests/test_decorators.py
index c102f2a..b1ff3d0 100644
--- a/libcst/matchers/tests/test_decorators.py
+++ b/libcst/matchers/tests/test_decorators.py
@@ -6,6 +6,7 @@
from ast import literal_eval
from textwrap import dedent
from typing import List, Set
+from unittest.mock import Mock
import libcst as cst
import libcst.matchers as m
@@ -993,3 +994,25 @@ class MatchersVisitLeaveDecoratorsTest(UnitTest):
# We should have only visited a select number of nodes.
self.assertEqual(visitor.visits, ['"baz"'])
+
+
+# This is meant to simulate `cst.ImportFrom | cst.RemovalSentinel` in py3.10
+FakeUnionClass: Mock = Mock()
+setattr(FakeUnionClass, "__name__", "Union")
+setattr(FakeUnionClass, "__module__", "types")
+FakeUnion: Mock = Mock()
+FakeUnion.__class__ = FakeUnionClass
+FakeUnion.__args__ = [cst.ImportFrom, cst.RemovalSentinel]
+
+
+class MatchersUnionDecoratorsTest(UnitTest):
+ def test_init_with_new_union_annotation(self) -> None:
+ class TransformerWithUnionReturnAnnotation(m.MatcherDecoratableTransformer):
+ @m.leave(m.ImportFrom(module=m.Name(value="typing")))
+ def test(
+ self, original_node: cst.ImportFrom, updated_node: cst.ImportFrom
+ ) -> FakeUnion:
+ pass
+
+ # assert that init (specifically _check_types on return annotation) passes
+ TransformerWithUnionReturnAnnotation()
diff --git a/libcst/metadata/tests/test_scope_provider.py b/libcst/metadata/tests/test_scope_provider.py
index c8a2b74..d1566aa 100644
--- a/libcst/metadata/tests/test_scope_provider.py
+++ b/libcst/metadata/tests/test_scope_provider.py
@@ -1568,6 +1568,47 @@ class ScopeProviderTest(UnitTest):
self.assertEqual(len(a_comp_assignment.references), 1)
self.assertEqual(list(a_comp_assignment.references)[0].node, comp.elt)
+ def test_for_scope_ordering(self) -> None:
+ m, scopes = get_scope_metadata_provider(
+ """
+ def f():
+ for x in []:
+ x
+ class X:
+ def f():
+ for x in []:
+ x
+ """
+ )
+ for scope in scopes.values():
+ for acc in scope.accesses:
+ self.assertEqual(
+ len(acc.referents),
+ 1,
+ msg=(
+ "Access for node has incorrect number of referents: "
+ + f"{acc.node}"
+ ),
+ )
+
+ def test_no_out_of_order_references_in_global_scope(self) -> None:
+ m, scopes = get_scope_metadata_provider(
+ """
+ x = y
+ y = 1
+ """
+ )
+ for scope in scopes.values():
+ for acc in scope.accesses:
+ self.assertEqual(
+ len(acc.referents),
+ 0,
+ msg=(
+ "Access for node has incorrect number of referents: "
+ + f"{acc.node}"
+ ),
+ )
+
def test_cast(self) -> None:
with self.assertRaises(cst.ParserSyntaxError):
m, scopes = get_scope_metadata_provider(
| make @m.leave() recognize function return using new Union syntax |
`@m.leave` throws an exception when function return use new union syntax:
```
@m.call_if_inside(m.ImportFrom(module=m.Name(value="typing")))
@m.leave(m.ImportFrom(module=m.Name(value="typing")))
def test(
self, original_node: cst.ImportFrom, updated_node: cst.ImportFrom
) -> cst.ImportFrom | cst.RemovalSentinel:
```
```
Traceback (most recent call last):
File "/opt/instagram/virtualenv/lib/python3.7/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "/opt/instagram/virtualenv/lib/python3.7/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/opt/instagram/virtualenv/lib/python3.7/site-packages/fbcode/libcst/tool.py", line 832, in <module>
main(os.environ.get("LIBCST_TOOL_COMMAND_NAME", "libcst.tool"), sys.argv[1:])
File "/opt/instagram/virtualenv/lib/python3.7/site-packages/fbcode/libcst/tool.py", line 827, in main
return lookup.get(args.action or None, _invalid_command)(proc_name, command_args)
File "/opt/instagram/virtualenv/lib/python3.7/site-packages/fbcode/libcst/tool.py", line 532, in _codemod_impl
command_instance = command_class(CodemodContext(), **codemod_args)
File "/opt/instagram/virtualenv/lib/python3.7/site-packages/fbcode/libcst/codemod/_visitor.py", line 29, in __init__
MatcherDecoratableTransformer.__init__(self)
File "/opt/instagram/virtualenv/lib/python3.7/site-packages/fbcode/libcst/matchers/_visitors.py", line 473, in __init__
expected_none_return=False,
File "/opt/instagram/virtualenv/lib/python3.7/site-packages/fbcode/libcst/matchers/_visitors.py", line 242, in _check_types
expected_none=expected_none_return,
File "/opt/instagram/virtualenv/lib/python3.7/site-packages/fbcode/libcst/matchers/_visitors.py", line 142, in _verify_return_annotation
if issubclass(ret, annotation):
TypeError: issubclass() arg 1 must be a class
```
Old Union syntax works:
```
@m.call_if_inside(m.ImportFrom(module=m.Name(value="typing")))
@m.leave(m.ImportFrom(module=m.Name(value="typing")))
def test(
self, original_node: cst.ImportFrom, updated_node: cst.ImportFrom
) -> Union[cst.ImportFrom, cst.RemovalSentinel]:
```
Not using `@m.leave` works:
```
@m.call_if_inside(m.ImportFrom(module=m.Name(value="typing")))
def leave_ImportFrom(
self, original_node: cst.ImportFrom, updated_node: cst.ImportFrom
) -> cst.ImportFrom | cst.RemovalSentinel:
```
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"libcst/matchers/tests/test_decorators.py::MatchersUnionDecoratorsTest::test_init_with_new_union_annotation",
"libcst/metadata/tests/test_scope_provider.py::ScopeProviderTest::test_for_scope_ordering",
"libcst/metadata/tests/test_scope_provider.py::ScopeProviderTest::test_no_out_of_order_references_in_global_scope"
] | [
"libcst/matchers/tests/test_decorators.py::MatchersGatingDecoratorsTest::test_call_if_inside_collect_simple",
"libcst/matchers/tests/test_decorators.py::MatchersGatingDecoratorsTest::test_call_if_inside_transform_simple",
"libcst/matchers/tests/test_decorators.py::MatchersGatingDecoratorsTest::test_call_if_inside_verify_original_collect",
"libcst/matchers/tests/test_decorators.py::MatchersGatingDecoratorsTest::test_call_if_inside_verify_original_transform",
"libcst/matchers/tests/test_decorators.py::MatchersGatingDecoratorsTest::test_call_if_not_inside_collect_simple",
"libcst/matchers/tests/test_decorators.py::MatchersGatingDecoratorsTest::test_call_if_not_inside_transform_simple",
"libcst/matchers/tests/test_decorators.py::MatchersGatingDecoratorsTest::test_multiple_visitors_collect",
"libcst/matchers/tests/test_decorators.py::MatchersGatingDecoratorsTest::test_multiple_visitors_transform",
"libcst/matchers/tests/test_decorators.py::MatchersGatingDecoratorsTest::test_visit_if_inot_inside_verify_original_collect",
"libcst/matchers/tests/test_decorators.py::MatchersGatingDecoratorsTest::test_visit_if_inot_inside_verify_original_transform",
"libcst/matchers/tests/test_decorators.py::MatchersVisitLeaveDecoratorsTest::test_call_if_inside_transform_attribute",
"libcst/matchers/tests/test_decorators.py::MatchersVisitLeaveDecoratorsTest::test_call_if_inside_visitor_attribute",
"libcst/matchers/tests/test_decorators.py::MatchersVisitLeaveDecoratorsTest::test_call_if_not_inside_transform_attribute",
"libcst/matchers/tests/test_decorators.py::MatchersVisitLeaveDecoratorsTest::test_call_if_not_inside_visitor_attribute",
"libcst/matchers/tests/test_decorators.py::MatchersVisitLeaveDecoratorsTest::test_duplicate_visit_collector",
"libcst/matchers/tests/test_decorators.py::MatchersVisitLeaveDecoratorsTest::test_duplicate_visit_transform",
"libcst/matchers/tests/test_decorators.py::MatchersVisitLeaveDecoratorsTest::test_gated_visit_collect",
"libcst/matchers/tests/test_decorators.py::MatchersVisitLeaveDecoratorsTest::test_gated_visit_transform",
"libcst/matchers/tests/test_decorators.py::MatchersVisitLeaveDecoratorsTest::test_init_with_unhashable_types",
"libcst/matchers/tests/test_decorators.py::MatchersVisitLeaveDecoratorsTest::test_stacked_visit_collector",
"libcst/matchers/tests/test_decorators.py::MatchersVisitLeaveDecoratorsTest::test_stacked_visit_transform",
"libcst/matchers/tests/test_decorators.py::MatchersVisitLeaveDecoratorsTest::test_transform_order",
"libcst/matchers/tests/test_decorators.py::MatchersVisitLeaveDecoratorsTest::test_visit_collector",
"libcst/matchers/tests/test_decorators.py::MatchersVisitLeaveDecoratorsTest::test_visit_transform",
"libcst/metadata/tests/test_scope_provider.py::ScopeProviderTest::test_accesses",
"libcst/metadata/tests/test_scope_provider.py::ScopeProviderTest::test_annotation_access",
"libcst/metadata/tests/test_scope_provider.py::ScopeProviderTest::test_assignments_and_accesses",
"libcst/metadata/tests/test_scope_provider.py::ScopeProviderTest::test_attribute_of_function_call",
"libcst/metadata/tests/test_scope_provider.py::ScopeProviderTest::test_attribute_of_subscript_called",
"libcst/metadata/tests/test_scope_provider.py::ScopeProviderTest::test_builtins_0",
"libcst/metadata/tests/test_scope_provider.py::ScopeProviderTest::test_builtins_1",
"libcst/metadata/tests/test_scope_provider.py::ScopeProviderTest::test_builtins_2",
"libcst/metadata/tests/test_scope_provider.py::ScopeProviderTest::test_builtins_3",
"libcst/metadata/tests/test_scope_provider.py::ScopeProviderTest::test_cast",
"libcst/metadata/tests/test_scope_provider.py::ScopeProviderTest::test_class_scope",
"libcst/metadata/tests/test_scope_provider.py::ScopeProviderTest::test_comprehension_scope",
"libcst/metadata/tests/test_scope_provider.py::ScopeProviderTest::test_contains_is_read_only",
"libcst/metadata/tests/test_scope_provider.py::ScopeProviderTest::test_del_context_names",
"libcst/metadata/tests/test_scope_provider.py::ScopeProviderTest::test_dotted_import_access",
"libcst/metadata/tests/test_scope_provider.py::ScopeProviderTest::test_dotted_import_with_call_access",
"libcst/metadata/tests/test_scope_provider.py::ScopeProviderTest::test_except_handler",
"libcst/metadata/tests/test_scope_provider.py::ScopeProviderTest::test_fstring_accesses",
"libcst/metadata/tests/test_scope_provider.py::ScopeProviderTest::test_func_param_scope",
"libcst/metadata/tests/test_scope_provider.py::ScopeProviderTest::test_function_scope",
"libcst/metadata/tests/test_scope_provider.py::ScopeProviderTest::test_gen_dotted_names",
"libcst/metadata/tests/test_scope_provider.py::ScopeProviderTest::test_get_qualified_names_for",
"libcst/metadata/tests/test_scope_provider.py::ScopeProviderTest::test_get_qualified_names_for_dotted_imports",
"libcst/metadata/tests/test_scope_provider.py::ScopeProviderTest::test_get_qualified_names_for_is_read_only",
"libcst/metadata/tests/test_scope_provider.py::ScopeProviderTest::test_get_qualified_names_for_nested_cases",
"libcst/metadata/tests/test_scope_provider.py::ScopeProviderTest::test_global_contains_is_read_only",
"libcst/metadata/tests/test_scope_provider.py::ScopeProviderTest::test_global_scope_overwrites",
"libcst/metadata/tests/test_scope_provider.py::ScopeProviderTest::test_import",
"libcst/metadata/tests/test_scope_provider.py::ScopeProviderTest::test_import_from",
"libcst/metadata/tests/test_scope_provider.py::ScopeProviderTest::test_keyword_arg_in_call",
"libcst/metadata/tests/test_scope_provider.py::ScopeProviderTest::test_lambda_param_scope",
"libcst/metadata/tests/test_scope_provider.py::ScopeProviderTest::test_local_scope_shadowing_with_functions",
"libcst/metadata/tests/test_scope_provider.py::ScopeProviderTest::test_multiple_assignments",
"libcst/metadata/tests/test_scope_provider.py::ScopeProviderTest::test_nested_comprehension_scope",
"libcst/metadata/tests/test_scope_provider.py::ScopeProviderTest::test_node_of_scopes",
"libcst/metadata/tests/test_scope_provider.py::ScopeProviderTest::test_nonlocal_scope_overwrites",
"libcst/metadata/tests/test_scope_provider.py::ScopeProviderTest::test_not_in_scope",
"libcst/metadata/tests/test_scope_provider.py::ScopeProviderTest::test_ordering",
"libcst/metadata/tests/test_scope_provider.py::ScopeProviderTest::test_ordering_between_scopes",
"libcst/metadata/tests/test_scope_provider.py::ScopeProviderTest::test_ordering_comprehension",
"libcst/metadata/tests/test_scope_provider.py::ScopeProviderTest::test_ordering_comprehension_confusing",
"libcst/metadata/tests/test_scope_provider.py::ScopeProviderTest::test_self",
"libcst/metadata/tests/test_scope_provider.py::ScopeProviderTest::test_with_asname",
"libcst/metadata/tests/test_scope_provider.py::ScopeProviderTest::test_with_statement"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
} | "2020-12-08T17:56:12Z" | mit |
|
Instagram__LibCST-626 | diff --git a/libcst/_nodes/statement.py b/libcst/_nodes/statement.py
index ded7c7c..e4b8d28 100644
--- a/libcst/_nodes/statement.py
+++ b/libcst/_nodes/statement.py
@@ -2687,11 +2687,6 @@ class Match(BaseCompoundStatement):
if len(self.cases) == 0:
raise CSTValidationError("A match statement must have at least one case.")
- if self.whitespace_after_match.empty:
- raise CSTValidationError(
- "Must have at least one space after a 'match' keyword"
- )
-
indent = self.indent
if indent is not None:
if len(indent) == 0:
@@ -2848,6 +2843,14 @@ class MatchValue(MatchPattern):
def lpar(self, value: Sequence[LeftParen]) -> None:
self.value.lpar = value
+ @property
+ def rpar(self) -> Sequence[RightParen]:
+ return self.value.rpar
+
+ @rpar.setter
+ def rpar(self, value: Sequence[RightParen]) -> None:
+ self.value.rpar = value
+
@add_slots
@dataclass(frozen=True)
@@ -2881,6 +2884,15 @@ class MatchSingleton(MatchPattern):
# pyre-fixme[41]: Cannot reassign final attribute `lpar`.
self.value.lpar = value
+ @property
+ def rpar(self) -> Sequence[RightParen]:
+ return self.value.rpar
+
+ @rpar.setter
+ def rpar(self, value: Sequence[RightParen]) -> None:
+ # pyre-fixme[41]: Cannot reassign final attribute `rpar`.
+ self.value.rpar = value
+
@add_slots
@dataclass(frozen=True)
| Instagram/LibCST | 2345848d4a0f92af27f292befaccb11f87b7caa1 | diff --git a/libcst/_nodes/tests/test_match.py b/libcst/_nodes/tests/test_match.py
index edf51d8..a203ffe 100644
--- a/libcst/_nodes/tests/test_match.py
+++ b/libcst/_nodes/tests/test_match.py
@@ -39,6 +39,39 @@ class MatchTest(CSTNodeTest):
+ ' case "foo": pass\n',
"parser": parser,
},
+ # Parenthesized value
+ {
+ "node": cst.Match(
+ subject=cst.Name(
+ value="x",
+ ),
+ cases=[
+ cst.MatchCase(
+ pattern=cst.MatchAs(
+ pattern=cst.MatchValue(
+ value=cst.Integer(
+ value="1",
+ lpar=[
+ cst.LeftParen(),
+ ],
+ rpar=[
+ cst.RightParen(),
+ ],
+ ),
+ ),
+ name=cst.Name(
+ value="z",
+ ),
+ whitespace_before_as=cst.SimpleWhitespace(" "),
+ whitespace_after_as=cst.SimpleWhitespace(" "),
+ ),
+ body=cst.SimpleStatementSuite([cst.Pass()]),
+ ),
+ ],
+ ),
+ "code": "match x:\n case (1) as z: pass\n",
+ "parser": parser,
+ },
# List patterns
{
"node": cst.Match(
@@ -425,6 +458,34 @@ class MatchTest(CSTNodeTest):
+ " case None | False | True: pass\n",
"parser": None,
},
+ # Match without whitespace between keyword and the expr
+ {
+ "node": cst.Match(
+ subject=cst.Name(
+ "x", lpar=[cst.LeftParen()], rpar=[cst.RightParen()]
+ ),
+ cases=[
+ cst.MatchCase(
+ pattern=cst.MatchSingleton(
+ cst.Name(
+ "None",
+ lpar=[cst.LeftParen()],
+ rpar=[cst.RightParen()],
+ )
+ ),
+ body=cst.SimpleStatementSuite((cst.Pass(),)),
+ whitespace_after_case=cst.SimpleWhitespace(
+ value="",
+ ),
+ ),
+ ],
+ whitespace_after_match=cst.SimpleWhitespace(
+ value="",
+ ),
+ ),
+ "code": "match(x):\n case(None): pass\n",
+ "parser": parser,
+ },
)
)
def test_valid(self, **kwargs: Any) -> None:
| CST node validation is broken for parenthesized MatchAs objects
Simple reproducer:
```py
match x:
case (1) as z:
pass
```
```
thread '<unnamed>' panicked at 'conversion failed for MatchValue: PyErr { type: <class 'libcst._nodes.base.CSTValidationError'>, value: CSTValidationError('Cannot have left paren without right paren.'), traceback: Some(<traceback object at 0x7f533bb89340>) }', libcst/src/nodes/statement.rs:2338:35
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
Traceback (most recent call last):
File "/usr/lib/python3.9/runpy.py", line 197, in _run_module_as_main
return _run_code(code, main_globals, None,
File "/usr/lib/python3.9/runpy.py", line 87, in _run_code
exec(code, run_globals)
File "/home/isidentical/projects/LibCST/libcst/tool.py", line 839, in <module>
main(os.environ.get("LIBCST_TOOL_COMMAND_NAME", "libcst.tool"), sys.argv[1:])
File "/home/isidentical/projects/LibCST/libcst/tool.py", line 834, in main
return lookup.get(args.action or None, _invalid_command)(proc_name, command_args)
File "/home/isidentical/projects/LibCST/libcst/tool.py", line 278, in _print_tree_impl
tree = parse_module(
File "/home/isidentical/projects/LibCST/libcst/_parser/entrypoints.py", line 109, in parse_module
result = _parse(
File "/home/isidentical/projects/LibCST/libcst/_parser/entrypoints.py", line 55, in _parse
return parse(source_str)
pyo3_runtime.PanicException: conversion failed for MatchValue: PyErr { type: <class 'libcst._nodes.base.CSTValidationError'>, value: CSTValidationError('Cannot have left paren without right paren.'), traceback: Some(<traceback object at 0x7f533bb89340>) }
``` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"libcst/_nodes/tests/test_match.py::MatchTest::test_valid_0",
"libcst/_nodes/tests/test_match.py::MatchTest::test_valid_1",
"libcst/_nodes/tests/test_match.py::MatchTest::test_valid_2",
"libcst/_nodes/tests/test_match.py::MatchTest::test_valid_3",
"libcst/_nodes/tests/test_match.py::MatchTest::test_valid_4",
"libcst/_nodes/tests/test_match.py::MatchTest::test_valid_5",
"libcst/_nodes/tests/test_match.py::MatchTest::test_valid_6",
"libcst/_nodes/tests/test_match.py::MatchTest::test_valid_7",
"libcst/_nodes/tests/test_match.py::MatchTest::test_valid_8",
"libcst/_nodes/tests/test_match.py::MatchTest::test_valid_9"
] | [] | {
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
} | "2022-01-23T15:59:56Z" | mit |
|
Instagram__LibCST-628 | diff --git a/libcst/_nodes/statement.py b/libcst/_nodes/statement.py
index ded7c7c..0e1cefe 100644
--- a/libcst/_nodes/statement.py
+++ b/libcst/_nodes/statement.py
@@ -2687,11 +2687,6 @@ class Match(BaseCompoundStatement):
if len(self.cases) == 0:
raise CSTValidationError("A match statement must have at least one case.")
- if self.whitespace_after_match.empty:
- raise CSTValidationError(
- "Must have at least one space after a 'match' keyword"
- )
-
indent = self.indent
if indent is not None:
if len(indent) == 0:
| Instagram/LibCST | 2345848d4a0f92af27f292befaccb11f87b7caa1 | diff --git a/libcst/_nodes/tests/test_match.py b/libcst/_nodes/tests/test_match.py
index edf51d8..5ceea72 100644
--- a/libcst/_nodes/tests/test_match.py
+++ b/libcst/_nodes/tests/test_match.py
@@ -425,6 +425,34 @@ class MatchTest(CSTNodeTest):
+ " case None | False | True: pass\n",
"parser": None,
},
+ # Match without whitespace between keyword and the expr
+ {
+ "node": cst.Match(
+ subject=cst.Name(
+ "x", lpar=[cst.LeftParen()], rpar=[cst.RightParen()]
+ ),
+ cases=[
+ cst.MatchCase(
+ pattern=cst.MatchSingleton(
+ cst.Name(
+ "None",
+ lpar=[cst.LeftParen()],
+ rpar=[cst.RightParen()],
+ )
+ ),
+ body=cst.SimpleStatementSuite((cst.Pass(),)),
+ whitespace_after_case=cst.SimpleWhitespace(
+ value="",
+ ),
+ ),
+ ],
+ whitespace_after_match=cst.SimpleWhitespace(
+ value="",
+ ),
+ ),
+ "code": "match(x):\n case(None): pass\n",
+ "parser": parser,
+ },
)
)
def test_valid(self, **kwargs: Any) -> None:
| CST node validation error for match without whitespace
Short reproducer:
```
match(x):
case(y):
pass
```
Crash:
```
thread '<unnamed>' panicked at 'conversion failed for Match: PyErr { type: <class 'libcst._nodes.base.CSTValidationError'>, value: CSTValidationError("Must have at least one space after a 'match' keyword"), traceback: Some(<traceback object at 0x7f38d11c7fc0>) }', libcst/src/nodes/statement.rs:2185:35
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
Traceback (most recent call last):
File "/usr/lib/python3.9/runpy.py", line 197, in _run_module_as_main
return _run_code(code, main_globals, None,
File "/usr/lib/python3.9/runpy.py", line 87, in _run_code
exec(code, run_globals)
File "/home/isidentical/projects/LibCST/libcst/tool.py", line 839, in <module>
main(os.environ.get("LIBCST_TOOL_COMMAND_NAME", "libcst.tool"), sys.argv[1:])
File "/home/isidentical/projects/LibCST/libcst/tool.py", line 834, in main
return lookup.get(args.action or None, _invalid_command)(proc_name, command_args)
File "/home/isidentical/projects/LibCST/libcst/tool.py", line 278, in _print_tree_impl
tree = parse_module(
File "/home/isidentical/projects/LibCST/libcst/_parser/entrypoints.py", line 109, in parse_module
result = _parse(
File "/home/isidentical/projects/LibCST/libcst/_parser/entrypoints.py", line 55, in _parse
return parse(source_str)
pyo3_runtime.PanicException: conversion failed for Match: PyErr { type: <class 'libcst._nodes.base.CSTValidationError'>, value: CSTValidationError("Must have at least one space after a 'match' keyword"), traceback: Some(<traceback object at 0x7f38d11c7fc0>) }
``` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"libcst/_nodes/tests/test_match.py::MatchTest::test_valid_0",
"libcst/_nodes/tests/test_match.py::MatchTest::test_valid_1",
"libcst/_nodes/tests/test_match.py::MatchTest::test_valid_2",
"libcst/_nodes/tests/test_match.py::MatchTest::test_valid_3",
"libcst/_nodes/tests/test_match.py::MatchTest::test_valid_4",
"libcst/_nodes/tests/test_match.py::MatchTest::test_valid_5",
"libcst/_nodes/tests/test_match.py::MatchTest::test_valid_6",
"libcst/_nodes/tests/test_match.py::MatchTest::test_valid_7",
"libcst/_nodes/tests/test_match.py::MatchTest::test_valid_8"
] | [] | {
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
} | "2022-01-23T19:55:45Z" | mit |
|
J-CPelletier__webcomix-7 | diff --git a/webcomix/main.py b/webcomix/main.py
index 0053bbb..cba546d 100644
--- a/webcomix/main.py
+++ b/webcomix/main.py
@@ -56,7 +56,12 @@ def download(name, cbz):
default=False,
is_flag=True,
help="Outputs the comic as a cbz file")
-def search(name, start_url, cbz):
[email protected](
+ "-y",
+ default=False,
+ is_flag=True,
+ help="Assumes 'yes' as an answer to all prompts")
+def search(name, start_url, cbz, y):
"""
Downloads a webcomic using a general XPath
"""
@@ -67,8 +72,8 @@ def search(name, start_url, cbz):
comic.comic_image_selector)
print_verification(validation)
click.echo(
- "Verify that the links above are correct before proceeding.")
- if click.confirm("Are you sure you want to proceed?"):
+ "Verify that the links above are correct.")
+ if y or click.confirm("Are you sure you want to proceed?"):
comic.download(name)
if cbz:
comic.make_cbz(name, name)
@@ -100,7 +105,12 @@ def search(name, start_url, cbz):
default=False,
is_flag=True,
help="Outputs the comic as a cbz file")
-def custom(comic_name, start_url, next_page_xpath, image_xpath, cbz):
[email protected](
+ "-y",
+ default=False,
+ is_flag=True,
+ help="Assumes 'yes' as an answer to all prompts")
+def custom(comic_name, start_url, next_page_xpath, image_xpath, cbz, y):
"""
Downloads a user-defined webcomic
"""
@@ -109,8 +119,8 @@ def custom(comic_name, start_url, next_page_xpath, image_xpath, cbz):
comic.next_page_selector,
comic.comic_image_selector)
print_verification(validation)
- click.echo("Verify that the links above are correct before proceeding.")
- if click.confirm("Are you sure you want to proceed?"):
+ click.echo("Verify that the links above are correct.")
+ if y or click.confirm("Are you sure you want to proceed?"):
comic.download(comic_name)
if cbz:
comic.make_cbz(comic_name, comic_name)
| J-CPelletier/webcomix | 25d394314ce26816302e9c878f5cebfb853c16fb | diff --git a/webcomix/tests/test_main.py b/webcomix/tests/test_main.py
index ec2c718..c2dcf42 100644
--- a/webcomix/tests/test_main.py
+++ b/webcomix/tests/test_main.py
@@ -100,7 +100,7 @@ def test_custom(monkeypatch):
assert result.exit_code == 0
assert result.output.strip() == "\n".join([
"Verified", "Printed",
- "Verify that the links above are correct before proceeding.",
+ "Verify that the links above are correct.",
"Are you sure you want to proceed? [y/N]: yes", "foo"
])
@@ -119,7 +119,7 @@ def test_custom_make_cbz(monkeypatch):
assert result.exit_code == 0
assert result.output.strip() == "\n".join([
"Verified", "Printed",
- "Verify that the links above are correct before proceeding.",
+ "Verify that the links above are correct.",
"Are you sure you want to proceed? [y/N]: y", "foo", ".cbz created"
])
@@ -139,6 +139,6 @@ def test_search(monkeypatch):
assert result.exit_code == 0
assert result.output.strip() == "\n".join([
"Verified", "Printed",
- "Verify that the links above are correct before proceeding.",
+ "Verify that the links above are correct.",
"Are you sure you want to proceed? [y/N]: y", "foo"
])
| Custom: Add a -y (yes) option
Looking to use this as a replacement for Dosage, as this allows for custom comics. I'd like to run this daily (or every few days) on a number of comics to pull latest comic. The prompting on Custom Comics (are you sure) is a stumbling block to script it. Can you maybe add a -y to custom, for auto-acknowledging? | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"webcomix/tests/test_main.py::test_custom",
"webcomix/tests/test_main.py::test_custom_make_cbz",
"webcomix/tests/test_main.py::test_search"
] | [
"webcomix/tests/test_main.py::test_print_verification",
"webcomix/tests/test_main.py::test_comics",
"webcomix/tests/test_main.py::test_good_download",
"webcomix/tests/test_main.py::test_bad_download",
"webcomix/tests/test_main.py::test_good_download_makecbz",
"webcomix/tests/test_main.py::test_bad_download_make_cbz"
] | {
"failed_lite_validators": [
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2018-07-27T20:03:35Z" | mit |
|
J535D165__pyalex-13 | diff --git a/pyalex/api.py b/pyalex/api.py
index 034bafe..c2e95b4 100644
--- a/pyalex/api.py
+++ b/pyalex/api.py
@@ -21,21 +21,55 @@ class AlexConfig(dict):
config = AlexConfig(email=None, api_key=None, openalex_url="https://api.openalex.org")
-def _flatten_kv(k, v):
+def _flatten_kv(d, prefix=""):
- if isinstance(v, dict):
+ if isinstance(d, dict):
- if len(v.keys()) > 1:
- raise ValueError()
+ t = []
+ for k, v in d.items():
+ if isinstance(v, list):
+ t.extend([f"{prefix}.{k}:{i}" for i in v])
+ else:
+ new_prefix = f"{prefix}.{k}" if prefix else f"{k}"
+ x = _flatten_kv(v, prefix=new_prefix)
+ t.append(x)
- k_0 = list(v.keys())[0]
- return str(k) + "." + _flatten_kv(k_0, v[k_0])
+ return ",".join(t)
else:
# workaround for bug https://groups.google.com/u/1/g/openalex-users/c/t46RWnzZaXc
- v = str(v).lower() if isinstance(v, bool) else v
-
- return str(k) + ":" + str(v)
+ d = str(d).lower() if isinstance(d, bool) else d
+
+ return f"{prefix}:{d}"
+
+
+def _params_merge(params, add_params):
+
+ for k, v in add_params.items():
+ if (
+ k in params
+ and isinstance(params[k], dict)
+ and isinstance(add_params[k], dict)
+ ):
+ _params_merge(params[k], add_params[k])
+ elif (
+ k in params
+ and not isinstance(params[k], list)
+ and isinstance(add_params[k], list)
+ ):
+ # example: params="a" and add_params=["b", "c"]
+ params[k] = [params[k]] + add_params[k]
+ elif (
+ k in params
+ and isinstance(params[k], list)
+ and not isinstance(add_params[k], list)
+ ):
+ # example: params=["b", "c"] and add_params="a"
+ params[k] = params[k] + [add_params[k]]
+ elif k in params:
+ params[k] = [params[k], add_params[k]]
+ else:
+ params[k] = add_params[k]
def invert_abstract(inv_index):
@@ -104,6 +138,7 @@ class Publisher(OpenAlexEntity):
# deprecated
+
def Venue(*args, **kwargs):
# warn about deprecation
@@ -152,7 +187,7 @@ class BaseOpenAlex(object):
"""Base class for OpenAlex objects."""
- def __init__(self, params={}):
+ def __init__(self, params=None):
self.params = params
@@ -185,7 +220,7 @@ class BaseOpenAlex(object):
res = requests.get(
url,
headers={"User-Agent": "pyalex/" + __version__, "email": config.email},
- params=params
+ params=params,
)
res.raise_for_status()
res_json = res.json()
@@ -195,10 +230,13 @@ class BaseOpenAlex(object):
@property
def url(self):
+ if not self.params:
+ return self.url_collection
+
l = []
for k, v in self.params.items():
if k in ["filter", "sort"]:
- l.append(k + "=" + ",".join(_flatten_kv(k, d) for k, d in v.items()))
+ l.append(k + "=" + _flatten_kv(v))
elif v is None:
pass
else:
@@ -214,21 +252,24 @@ class BaseOpenAlex(object):
if per_page is not None and (per_page < 1 or per_page > 200):
raise ValueError("per_page should be a number between 1 and 200.")
- self.params["per-page"] = per_page
- self.params["page"] = page
- self.params["cursor"] = cursor
+ self._add_params("per-page", per_page)
+ self._add_params("page", page)
+ self._add_params("cursor", cursor)
params = {"api_key": config.api_key} if config.api_key else {}
res = requests.get(
self.url,
headers={"User-Agent": "pyalex/" + __version__, "email": config.email},
- params=params
+ params=params,
)
# handle query errors
if res.status_code == 403:
res_json = res.json()
- if isinstance(res_json["error"], str) and "query parameters" in res_json["error"]:
+ if (
+ isinstance(res_json["error"], str)
+ and "query parameters" in res_json["error"]
+ ):
raise QueryError(res_json["message"])
res.raise_for_status()
@@ -254,68 +295,40 @@ class BaseOpenAlex(object):
return self.__getitem__("random")
- def filter(self, **kwargs):
-
- p = self.params.copy()
+ def _add_params(self, argument, new_params):
- if "filter" in p:
- p["filter"] = {**p["filter"], **kwargs}
+ if self.params is None:
+ self.params = {argument: new_params}
+ elif argument in self.params and isinstance(self.params[argument], dict):
+ _params_merge(self.params[argument], new_params)
else:
- p["filter"] = kwargs
+ self.params[argument] = new_params
+
+ logging.debug("Params updated:", self.params)
- self.params = p
- logging.debug("Params updated:", p)
+ def filter(self, **kwargs):
+ self._add_params("filter", kwargs)
return self
def search_filter(self, **kwargs):
- search_kwargs = {f"{k}.search": v for k, v in kwargs.items()}
-
- p = self.params.copy()
-
- if "filter" in p:
- p["filter"] = {**p["filter"], **search_kwargs}
- else:
- p["filter"] = search_kwargs
-
- self.params = p
- logging.debug("Params updated:", p)
-
+ self._add_params("filter", {f"{k}.search": v for k, v in kwargs.items()})
return self
def sort(self, **kwargs):
- p = self.params.copy()
-
- if "sort" in p:
- p["sort"] = {**p["sort"], **kwargs}
- else:
- p["sort"] = kwargs
-
- self.params = p
- logging.debug("Params updated:", p)
-
+ self._add_params("sort", kwargs)
return self
def group_by(self, group_key):
- p = self.params.copy()
- p["group-by"] = group_key
- self.params = p
-
- logging.debug("Params updated:", p)
-
+ self._add_params("group-by", group_key)
return self
def search(self, s):
- p = self.params.copy()
- p["search"] = s
- self.params = p
-
- logging.debug("Params updated:", p)
-
+ self._add_params("search", s)
return self
@@ -357,6 +370,7 @@ class Publishers(BaseOpenAlex):
# deprecated
+
def Venues(*args, **kwargs):
# warn about deprecation
| J535D165/pyalex | c16060b29717b364be52bf4c2f935926c6b3b4f9 | diff --git a/tests/test_pyalex.py b/tests/test_pyalex.py
index 54a01ef..2ba60a8 100644
--- a/tests/test_pyalex.py
+++ b/tests/test_pyalex.py
@@ -348,3 +348,35 @@ def test_ngrams_with_metadata():
def test_random_publishers():
assert isinstance(Publishers().random(), dict)
+
+
+def test_and_operator():
+
+ # https://github.com/J535D165/pyalex/issues/11
+ url = "https://api.openalex.org/works?filter=institutions.country_code:tw,institutions.country_code:hk,institutions.country_code:us,publication_year:2022" # noqa
+
+ assert (
+ url
+ == Works()
+ .filter(
+ institutions={"country_code": ["tw", "hk", "us"]}, publication_year=2022
+ )
+ .url
+ )
+ assert (
+ url
+ == Works()
+ .filter(institutions={"country_code": "tw"})
+ .filter(institutions={"country_code": "hk"})
+ .filter(institutions={"country_code": "us"})
+ .filter(publication_year=2022)
+ .url
+ )
+ assert (
+ url
+ == Works()
+ .filter(institutions={"country_code": ["tw", "hk"]})
+ .filter(institutions={"country_code": "us"})
+ .filter(publication_year=2022)
+ .url
+ )
| Add example for boolean operators to documentation
Thanks for providing pyalex! It would be helpful to have an example for the use of different boolean filters in the Readme.
Example URL: https://api.openalex.org/works?filter=institutions.country_code:tw,institutions.country_code:hk | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_pyalex.py::test_and_operator"
] | [
"tests/test_pyalex.py::test_config",
"tests/test_pyalex.py::test_meta_entities",
"tests/test_pyalex.py::test_works_params",
"tests/test_pyalex.py::test_works",
"tests/test_pyalex.py::test_per_page",
"tests/test_pyalex.py::test_W4238809453_works",
"tests/test_pyalex.py::test_W4238809453_works_abstract",
"tests/test_pyalex.py::test_W4238809453_works_no_abstract",
"tests/test_pyalex.py::test_W3128349626_works_abstract",
"tests/test_pyalex.py::test_W3128349626_works_no_abstract",
"tests/test_pyalex.py::test_work_error",
"tests/test_pyalex.py::test_random_works",
"tests/test_pyalex.py::test_multi_works",
"tests/test_pyalex.py::test_works_multifilter",
"tests/test_pyalex.py::test_works_url",
"tests/test_pyalex.py::test_works_multifilter_meta",
"tests/test_pyalex.py::test_query_error",
"tests/test_pyalex.py::test_data_publications",
"tests/test_pyalex.py::test_search",
"tests/test_pyalex.py::test_search_filter",
"tests/test_pyalex.py::test_cursor_by_hand",
"tests/test_pyalex.py::test_basic_paging",
"tests/test_pyalex.py::test_cursor_paging",
"tests/test_pyalex.py::test_cursor_paging_n_max",
"tests/test_pyalex.py::test_cursor_paging_n_max_none",
"tests/test_pyalex.py::test_referenced_works",
"tests/test_pyalex.py::test_serializable",
"tests/test_pyalex.py::test_ngrams_without_metadata",
"tests/test_pyalex.py::test_ngrams_with_metadata",
"tests/test_pyalex.py::test_random_publishers"
] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2023-03-27T11:45:10Z" | mit |