instance_id
stringlengths 12
53
| patch
stringlengths 264
37.7k
| repo
stringlengths 8
49
| base_commit
stringlengths 40
40
| hints_text
stringclasses 114
values | test_patch
stringlengths 224
315k
| problem_statement
stringlengths 40
10.4k
| version
stringclasses 1
value | FAIL_TO_PASS
sequencelengths 1
4.94k
| PASS_TO_PASS
sequencelengths 0
6.23k
| created_at
stringlengths 25
25
| __index_level_0__
int64 4.13k
6.41k
|
---|---|---|---|---|---|---|---|---|---|---|---|
odufrn__odufrn-downloader-95 | diff --git a/.gitignore b/.gitignore
index 9593d84..ef43f41 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,5 +1,6 @@
Pipfile
Pipfile.lock
+env/
.vscode/*
.idea/*
venv/*
diff --git a/odufrn_downloader/exceptions.py b/odufrn_downloader/exceptions.py
new file mode 100644
index 0000000..e69e97b
--- /dev/null
+++ b/odufrn_downloader/exceptions.py
@@ -0,0 +1,10 @@
+class odufrException(Exception):
+ def __init__(self):
+ default_message = 'Default Exception!'
+ super().__init__()
+
+
+class odufrIOError(odufrException):
+ def __init__(self):
+ default_message = 'odufrIOError Exception!'
+ super().__init__()
diff --git a/odufrn_downloader/modules/File.py b/odufrn_downloader/modules/File.py
index 7eac2f4..1cdeec2 100644
--- a/odufrn_downloader/modules/File.py
+++ b/odufrn_downloader/modules/File.py
@@ -1,5 +1,6 @@
import os
from .Package import Package
+from odufrn_downloader.exceptions import odufrIOError
class File(Package):
@@ -34,5 +35,5 @@ class File(Package):
self.download_package(
packageName.rstrip(), path, dictionary, years
)
- except IOError as ex:
- self._print_exception(ex)
+ except IOError:
+ raise odufrIOError()
| odufrn/odufrn-downloader | 7ab1d9afb9f93ba620ee540d8e691c6ce3558271 | diff --git a/tests/test_file.py b/tests/test_file.py
index bb21fb0..4bd5fa3 100644
--- a/tests/test_file.py
+++ b/tests/test_file.py
@@ -1,5 +1,6 @@
from .utils import *
import tempfile
+from odufrn_downloader.modules.File import odufrIOError
class Group(unittest.TestCase):
@@ -25,8 +26,6 @@ class Group(unittest.TestCase):
def test_can_print_exception_download_packages_from_file(self):
"""Verifica se dado um arquivo com nomes errados de pacotes
lança-se exceção."""
- assert_console(
- lambda: self.ufrn_data.download_from_file(
- 'potato', './tmp'
- )
- )
+
+ with self.assertRaises(odufrIOError):
+ self.ufrn_data.download_from_file('potato', './tmp')
| Criar classes de exception
# Feature
Hoje tratamos as exceptions de forma bem geral, porém poderíamos criar classes de exceção para nos auxiliarmos a lidar com os erros. Isso ajuda bastante nos testes, tornando-os mais assertivos, visto que o unittest tem a função ` assertRaises() `
> #### Participe do Hacktoberfest!
> Contribua com uma issue com a label `hacktoberfest` e abra um pull request durante o mês de outubro para ganhar os brindes do GitHub! Para se inscrever, acesse https://hacktoberfest.digitalocean.com/register | 0.0 | [
"tests/test_file.py::Group::test_can_download_packages_from_file",
"tests/test_file.py::Group::test_can_print_exception_download_packages_from_file"
] | [] | 2019-10-05 22:30:32+00:00 | 4,331 |
|
oduwsdl__MementoEmbed-131 | diff --git a/docs/source/conf.py b/docs/source/conf.py
index c7c0614..9892732 100644
--- a/docs/source/conf.py
+++ b/docs/source/conf.py
@@ -26,7 +26,7 @@ author = 'Shawn M. Jones'
# The short X.Y version
version = ''
# The full version, including alpha/beta/rc tags
-release = '0.2018.09.05.234815'
+release = '0.2018.09.06.202242'
# -- General configuration ---------------------------------------------------
diff --git a/mementoembed/favicon.py b/mementoembed/favicon.py
index 60203f0..2d53036 100644
--- a/mementoembed/favicon.py
+++ b/mementoembed/favicon.py
@@ -52,18 +52,27 @@ def get_favicon_from_html(content):
for link in links:
- if 'icon' in link['rel']:
- favicon_uri = link['href']
- break
+ try:
+ if 'icon' in link['rel']:
+ favicon_uri = link['href']
+ break
+ except KeyError:
+ module_logger.exception("there was no 'rel' attribute in this link tag: {}".format(link))
+ favicon_uri == None
# if that fails, try the older, nonstandard relation 'shortcut'
if favicon_uri == None:
for link in links:
- if 'shortcut' in link['rel']:
- favicon_uri = link['href']
- break
+ try:
+ if 'shortcut' in link['rel']:
+ favicon_uri = link['href']
+ break
+ except KeyError:
+ module_logger.exception("there was no 'rel' attribute in this link tag: {}".format(link))
+ favicon_uri == None
+
return favicon_uri
diff --git a/mementoembed/version.py b/mementoembed/version.py
index 72f9069..d1f031b 100644
--- a/mementoembed/version.py
+++ b/mementoembed/version.py
@@ -1,3 +1,3 @@
__appname__ = "MementoEmbed"
-__appversion__ = '0.2018.09.05.234815'
+__appversion__ = '0.2018.09.06.202242'
__useragent__ = "{}/{}".format(__appname__, __appversion__)
| oduwsdl/MementoEmbed | dfff20f4d336e76de33851d77c3f4a4af83a5ed2 | diff --git a/tests/test_archiveresource.py b/tests/test_archiveresource.py
index 0be51a5..8c33160 100644
--- a/tests/test_archiveresource.py
+++ b/tests/test_archiveresource.py
@@ -279,3 +279,52 @@ class TestArchiveResource(unittest.TestCase):
x = ArchiveResource(urim, httpcache)
self.assertEqual(x.favicon, expected_favicon)
+
+ def test_link_tag_no_rel(self):
+
+ expected_favicon = None
+
+ cachedict = {
+ "http://myarchive.org":
+ mock_response(
+ headers={},
+ content="""<html>
+ <head>
+ <title>Is this a good title?</title>
+ <link title="a good title" href="content/favicon.ico">
+ </head>
+ <body>Is this all there is to content?</body>
+ </html>""",
+ status=200,
+ url = "testing-url://notused"
+ ),
+ expected_favicon:
+ mock_response(
+ headers = { 'content-type': 'image/x-testing'},
+ content = "a",
+ status=200,
+ url = "testing-url://notused"
+ ),
+ "http://myarchive.org/favicon.ico":
+ mock_response(
+ headers={},
+ content="not found",
+ status=404,
+ url="testing-url://notused"
+ ),
+ "https://www.google.com/s2/favicons?domain=myarchive.org":
+ mock_response(
+ headers={},
+ content="not found",
+ status=404,
+ url="testing-url://notused"
+ )
+ }
+
+ httpcache = mock_httpcache(cachedict)
+
+ urim = "http://myarchive.org/20160518000858/http://example.com/somecontent"
+
+ x = ArchiveResource(urim, httpcache)
+
+ self.assertEqual(x.favicon, expected_favicon)
| Exception while searching for favicon
MementoEmbed throws an exception for the following URI-M:
* http://wayback.archive-it.org/4887/20141104211213/http://time.com/3502740/ebola-virus-1976/
Here is the log entry:
```
[2018-09-06 14:07:36,093 -0600 ] - ERROR - [ /services/product/socialcard/http://wayback.archive-it.org/4887/20141104211213/http://time.com/3502740/ebola-virus-1976/ ]: mementoembed.services.errors - An unforeseen error has occurred
Traceback (most recent call last):
File "/Volumes/nerfherder External/Unsynced-Projects/MementoEmbed/mementoembed/services/errors.py", line 27, in handle_errors
return function_name(urim, preferences)
File "/Volumes/nerfherder External/Unsynced-Projects/MementoEmbed/mementoembed/services/product.py", line 77, in generate_socialcard_response
original_favicon_uri = s.original_favicon
File "/Volumes/nerfherder External/Unsynced-Projects/MementoEmbed/mementoembed/mementosurrogate.py", line 71, in original_favicon
return self.originalresource.favicon
File "/Volumes/nerfherder External/Unsynced-Projects/MementoEmbed/mementoembed/originalresource.py", line 49, in favicon
candidate_favicon = get_favicon_from_html(self.content)
File "/Volumes/nerfherder External/Unsynced-Projects/MementoEmbed/mementoembed/favicon.py", line 55, in get_favicon_from_html
if 'icon' in link['rel']:
File "/Users/smj/.virtualenvs/MementoEmbed-gkunwTeo/lib/python3.7/site-packages/bs4/element.py", line 1071, in __getitem__
return self.attrs[key]
KeyError: 'rel'
```
The problem is that the code assumes that all `link` tags in html have a `rel` attribute. | 0.0 | [
"tests/test_archiveresource.py::TestArchiveResource::test_link_tag_no_rel"
] | [
"tests/test_archiveresource.py::TestArchiveResource::test_404_favicon_from_constructed_favicon_uri_so_google_service",
"tests/test_archiveresource.py::TestArchiveResource::test_404_favicon_from_html_so_constructed_favicon_uri",
"tests/test_archiveresource.py::TestArchiveResource::test_collection_data_extraction",
"tests/test_archiveresource.py::TestArchiveResource::test_favicon_from_html",
"tests/test_archiveresource.py::TestArchiveResource::test_favicon_from_html_relative_uri",
"tests/test_archiveresource.py::TestArchiveResource::test_no_good_favicon",
"tests/test_archiveresource.py::TestArchiveResource::test_simplestuff"
] | 2018-09-06 20:43:09+00:00 | 4,332 |
|
oduwsdl__MementoEmbed-137 | diff --git a/docs/source/conf.py b/docs/source/conf.py
index 00e7098..230f9e2 100644
--- a/docs/source/conf.py
+++ b/docs/source/conf.py
@@ -26,7 +26,7 @@ author = 'Shawn M. Jones'
# The short X.Y version
version = ''
# The full version, including alpha/beta/rc tags
-release = '0.2018.10.11.153710'
+release = '0.2018.10.11.193540'
# -- General configuration ---------------------------------------------------
diff --git a/mementoembed/mementoresource.py b/mementoembed/mementoresource.py
index c444937..52f65c4 100644
--- a/mementoembed/mementoresource.py
+++ b/mementoembed/mementoresource.py
@@ -105,8 +105,9 @@ def get_timegate_from_response(response):
urig = None
try:
- urig = aiu.convert_LinkTimeMap_to_dict(
- response.headers['link'] )['timegate_uri']
+ # urig = aiu.convert_LinkTimeMap_to_dict(
+ # response.headers['link'] )['timegate_uri']
+ urig = response.links['timegate']['url']
except KeyError as e:
raise NotAMementoError(
"link header coult not be parsed for timegate URI",
@@ -119,8 +120,9 @@ def get_original_uri_from_response(response):
urir = None
try:
- urir = aiu.convert_LinkTimeMap_to_dict(
- response.headers['link'] )['original_uri']
+ # urir = aiu.convert_LinkTimeMap_to_dict(
+ # response.headers['link'] )['original_uri']
+ urir = response.links['original']['url']
except KeyError as e:
raise NotAMementoError(
"link header coult not be parsed for original URI",
diff --git a/mementoembed/version.py b/mementoembed/version.py
index fe6ad2b..74615bf 100644
--- a/mementoembed/version.py
+++ b/mementoembed/version.py
@@ -1,3 +1,3 @@
__appname__ = "MementoEmbed"
-__appversion__ = '0.2018.10.11.153710'
+__appversion__ = '0.2018.10.11.193540'
__useragent__ = "{}/{}".format(__appname__, __appversion__)
| oduwsdl/MementoEmbed | 124675643fd680804b50ab268ebcd60c958dc6a1 | diff --git a/tests/test_mementoresource.py b/tests/test_mementoresource.py
index aaff116..e9a45e5 100644
--- a/tests/test_mementoresource.py
+++ b/tests/test_mementoresource.py
@@ -13,10 +13,11 @@ testdir = os.path.dirname(os.path.realpath(__file__))
class mock_response:
- def __init__(self, headers, text, status, url, content=None):
+ def __init__(self, headers, text, status, url, content=None, links={}):
self.headers = headers
self.text = text
self.url = url
+ self.links = links
if content is None:
@@ -82,7 +83,15 @@ class TestMementoResource(unittest.TestCase):
},
text = expected_content,
status=200,
- url = urim
+ url = urim,
+ links = {
+ "original": {
+ "url": expected_original_uri
+ },
+ "timegate": {
+ "url": expected_urig
+ }
+ }
),
expected_urig: # requests follows all redirects, so we present the result at the end of the chain
mock_response(
@@ -97,7 +106,15 @@ class TestMementoResource(unittest.TestCase):
},
text = expected_content,
status=200,
- url = urim
+ url = urim,
+ links = {
+ "original": {
+ "url": expected_original_uri
+ },
+ "timegate": {
+ "url": expected_urig
+ }
+ }
)
}
@@ -160,7 +177,15 @@ class TestMementoResource(unittest.TestCase):
},
text = expected_content,
status=200,
- url = urim
+ url = urim,
+ links = {
+ "original": {
+ "url": expected_original_uri
+ },
+ "timegate": {
+ "url": expected_urig
+ }
+ }
),
raw_urim:
mock_response(
@@ -232,7 +257,15 @@ class TestMementoResource(unittest.TestCase):
},
text = expected_content,
status=200,
- url = urim
+ url = urim,
+ links = {
+ "original": {
+ "url": expected_original_uri
+ },
+ "timegate": {
+ "url": expected_urig
+ }
+ }
),
raw_urim:
mock_response(
@@ -314,7 +347,15 @@ class TestMementoResource(unittest.TestCase):
},
text = expected_content,
status=200,
- url = urim
+ url = urim,
+ links = {
+ "original": {
+ "url": expected_original_uri
+ },
+ "timegate": {
+ "url": expected_urig
+ }
+ }
),
zipurim:
mock_response(
@@ -476,7 +517,15 @@ class TestMementoResource(unittest.TestCase):
},
text = expected_content,
status=200,
- url = urim
+ url = urim,
+ links = {
+ "original": {
+ "url": expected_original_uri
+ },
+ "timegate": {
+ "url": expected_urig
+ }
+ }
),
"http://archive.is/20130508132946id_/http://flexispy.com/":
mock_response(
@@ -552,7 +601,15 @@ class TestMementoResource(unittest.TestCase):
text = metaredirecthtml,
content = metaredirecthtml,
status = 200,
- url = urim
+ url = urim,
+ links = {
+ "original": {
+ "url": expected_original_uri
+ },
+ "timegate": {
+ "url": expected_urig
+ }
+ }
),
redirurim:
mock_response(
@@ -568,7 +625,15 @@ class TestMementoResource(unittest.TestCase):
text = expected_content,
content = expected_content,
status = 200,
- url = redirurim
+ url = redirurim,
+ links = {
+ "original": {
+ "url": redir_expected_original_uri
+ },
+ "timegate": {
+ "url": redir_expected_urig
+ }
+ }
),
redirurim_raw:
mock_response(
@@ -624,7 +689,15 @@ class TestMementoResource(unittest.TestCase):
},
text = expected_content,
status=200,
- url = urim
+ url = urim,
+ links = {
+ "original": {
+ "url": expected_original_uri
+ },
+ "timegate": {
+ "url": expected_urig
+ }
+ }
),
expected_raw_uri:
mock_response(
@@ -639,7 +712,15 @@ class TestMementoResource(unittest.TestCase):
},
text = expected_raw_content,
status = 200,
- url = expected_raw_uri
+ url = expected_raw_uri,
+ links = {
+ "original": {
+ "url": expected_original_uri
+ },
+ "timegate": {
+ "url": expected_urig
+ }
+ }
),
expected_urig: # requests follows all redirects, so we present the result at the end of the chain
mock_response(
@@ -654,7 +735,15 @@ class TestMementoResource(unittest.TestCase):
},
text = expected_content,
status = 200, # after following redirects
- url = expected_urim
+ url = expected_urim,
+ links = {
+ "original": {
+ "url": expected_original_uri
+ },
+ "timegate": {
+ "url": expected_urig
+ }
+ }
),
expected_urim:
mock_response(
@@ -669,7 +758,15 @@ class TestMementoResource(unittest.TestCase):
},
text = expected_content,
status = 200, # after following redirects
- url = expected_urim
+ url = expected_urim,
+ links = {
+ "original": {
+ "url": expected_original_uri
+ },
+ "timegate": {
+ "url": expected_urig
+ }
+ }
)
}
diff --git a/tests/test_originalresource.py b/tests/test_originalresource.py
index 6f2e84e..db1a790 100644
--- a/tests/test_originalresource.py
+++ b/tests/test_originalresource.py
@@ -5,7 +5,7 @@ from mementoembed.originalresource import OriginalResource
class mock_response:
- def __init__(self, headers, text, status, url, content=None):
+ def __init__(self, headers, text, status, url, content=None, links={}):
self.headers = headers
self.text = text
if content is None:
@@ -16,6 +16,8 @@ class mock_response:
self.status_code = status
self.url = url
+ self.links = links
+
class mock_httpcache:
"""
rather than hitting the actual HTTP cache,
@@ -64,7 +66,15 @@ class TestOriginalResource(unittest.TestCase):
},
text = expected_content,
status=200,
- url = urim
+ url = urim,
+ links = {
+ "original": {
+ "url": expected_original_uri
+ },
+ "timegate": {
+ "url": expected_urig
+ }
+ }
),
expected_urig:
mock_response(
@@ -79,7 +89,15 @@ class TestOriginalResource(unittest.TestCase):
},
text = expected_content,
status=200,
- url = urim
+ url = urim,
+ links = {
+ "original": {
+ "url": expected_original_uri
+ },
+ "timegate": {
+ "url": expected_urig
+ }
+ }
),
expected_original_uri:
mock_response(
@@ -130,7 +148,15 @@ class TestOriginalResource(unittest.TestCase):
},
text = expected_content,
status=200,
- url = urim
+ url = urim,
+ links = {
+ "original": {
+ "url": expected_original_uri
+ },
+ "timegate": {
+ "url": expected_urig
+ }
+ }
),
expected_urig:
mock_response(
@@ -145,7 +171,15 @@ class TestOriginalResource(unittest.TestCase):
},
text = expected_content,
status=200,
- url = urim
+ url = urim,
+ links = {
+ "original": {
+ "url": expected_original_uri
+ },
+ "timegate": {
+ "url": expected_urig
+ }
+ }
),
expected_original_uri:
mock_response(
@@ -202,7 +236,15 @@ class TestOriginalResource(unittest.TestCase):
},
text = expected_content,
status=200,
- url = urim
+ url = urim,
+ links = {
+ "original": {
+ "url": expected_original_uri
+ },
+ "timegate": {
+ "url": expected_urig
+ }
+ }
),
expected_urig:
mock_response(
@@ -217,7 +259,15 @@ class TestOriginalResource(unittest.TestCase):
},
text = expected_content,
status=200,
- url = urim
+ url = urim,
+ links = {
+ "original": {
+ "url": expected_original_uri
+ },
+ "timegate": {
+ "url": expected_urig
+ }
+ }
),
expected_original_uri:
mock_response(
| parsing multiple Link: response headers
Martin brought this to my attention. Here's a sample URL:
https://scholarlyorphans.org/memento/20181009212548/https://ianmilligan.ca/
and it returns two different Link headers:
$ curl -IL https://scholarlyorphans.org/memento/20181009212548/https://ianmilligan.ca/
HTTP/1.1 200 OK
Server: nginx/1.12.1
Content-Type: text/html; charset=UTF-8
Connection: keep-alive
X-Archive-Orig-Server: nginx
Date: Tue, 09 Oct 2018 21:25:48 GMT
X-Archive-Orig-Transfer-Encoding: chunked
X-Archive-Orig-Connection: keep-alive
X-Archive-Orig-Strict-Transport-Security: max-age=86400
X-Archive-Orig-Vary: Accept-Encoding
X-Archive-Orig-Vary: Cookie
X-hacker: If you're reading this, you should visit automattic.com/jobs and apply to join the fun, mention this header.
Link: <https://wp.me/4cEB>; rel=shortlink
X-Archive-Orig-Content-Encoding: gzip
X-ac: 3.sea _bur
Memento-Datetime: Tue, 09 Oct 2018 21:25:48 GMT
Link: <https://ianmilligan.ca/>; rel="original", <https://scholarlyorphans.org/memento/https://ianmilligan.ca/>; rel="timegate", <https://scholarlyorphans.org/memento/timemap/link/https://ianmilligan.ca/>; rel="timemap"; type="application/link-format", <https://scholarlyorphans.org/memento/20181009212548/https://ianmilligan.ca/>; rel="memento"; datetime="Tue, 09 Oct 2018 21:25:48 GMT"; collection="memento"
Content-Location: https://scholarlyorphans.org/memento/20181009212548/https://ianmilligan.ca/
Content-Security-Policy: default-src 'unsafe-eval' 'unsafe-inline' 'self' data: blob: mediastream: ws: wss: ; form-action 'self'
Now, the first header is in error (it should be in X-Archive-orig-Link), but multiple Link headers *are* allowed as per RFC 2616 (and 7230). Martin said MementoEmbed wasn't finding link rel="original", probably bc it occurs in the 2nd Link header and not the first.
| 0.0 | [
"tests/test_mementoresource.py::TestMementoResource::test_archiveiscase",
"tests/test_mementoresource.py::TestMementoResource::test_archiveiscase_datetime_in_uri",
"tests/test_mementoresource.py::TestMementoResource::test_imfcase",
"tests/test_mementoresource.py::TestMementoResource::test_meta_redirect",
"tests/test_mementoresource.py::TestMementoResource::test_permacc_hashstyle_uris",
"tests/test_mementoresource.py::TestMementoResource::test_simplecase",
"tests/test_mementoresource.py::TestMementoResource::test_waybackcase",
"tests/test_originalresource.py::TestOriginalResource::test_favicon_from_html",
"tests/test_originalresource.py::TestOriginalResource::test_simplecase_live_resource",
"tests/test_originalresource.py::TestOriginalResource::test_simplecase_rotten_resource"
] | [
"tests/test_mementoresource.py::TestMementoResource::test_bad_headers"
] | 2018-10-11 19:37:39+00:00 | 4,333 |
|
oemof__oemof-network-31 | diff --git a/src/oemof/network/network/nodes.py b/src/oemof/network/network/nodes.py
index bc1e1e7..3cb72fa 100644
--- a/src/oemof/network/network/nodes.py
+++ b/src/oemof/network/network/nodes.py
@@ -11,6 +11,8 @@ SPDX-FileCopyrightText: Patrik Schönfeldt <[email protected]>
SPDX-License-Identifier: MIT
"""
+import warnings
+
from .edge import Edge
from .entity import Entity
@@ -24,9 +26,18 @@ class Node(Entity):
inputs: list or dict, optional
Either a list of this nodes' input nodes or a dictionary mapping input
nodes to corresponding inflows (i.e. input values).
+ List will be converted to dictionary with values set to None.
outputs: list or dict, optional
Either a list of this nodes' output nodes or a dictionary mapping
output nodes to corresponding outflows (i.e. output values).
+ List will be converted to dictionary with values set to None.
+
+ Attributes
+ ----------
+ inputs: dict
+ A dictionary mapping input nodes to corresponding inflows.
+ outputs: dict
+ A dictionary mapping output nodes to corresponding outflows.
"""
def __init__(self, *args, **kwargs):
@@ -59,12 +70,27 @@ class Node(Entity):
edge.output = o
+_deprecation_warning = (
+ "Usage of {} is deprecated. Use oemof.network.Node instead."
+)
+
+
class Bus(Node):
- pass
+ def __init__(self, *args, **kwargs):
+ warnings.warn(
+ _deprecation_warning.format(type(self)),
+ FutureWarning,
+ )
+ super().__init__(*args, **kwargs)
class Component(Node):
- pass
+ def __init__(self, *args, **kwargs):
+ warnings.warn(
+ _deprecation_warning.format(type(self)),
+ FutureWarning,
+ )
+ super().__init__(*args, **kwargs)
class Sink(Component):
| oemof/oemof-network | 2c298a7af84feceef8ce049d15c169ca7d28784e | diff --git a/tests/test_energy_system.py b/tests/test_energy_system.py
index 9af475e..6e602f5 100644
--- a/tests/test_energy_system.py
+++ b/tests/test_energy_system.py
@@ -42,6 +42,30 @@ class TestsEnergySystem:
assert node2 in self.es.nodes
assert (node1, node2) in self.es.flows().keys()
+ def test_add_flow_assignment(self):
+ assert not self.es.nodes
+
+ node0 = Node(label="node0")
+ node1 = Node(label="node1")
+ node2 = Node(label="node2", inputs={node0: Edge()})
+
+ self.es.add(node0, node1, node2)
+
+ assert (node0, node2) in self.es.flows().keys()
+ assert (node1, node2) not in self.es.flows().keys()
+ assert (node2, node1) not in self.es.flows().keys()
+
+ node2.inputs[node1] = Edge()
+
+ assert (node0, node2) in self.es.flows().keys()
+ assert (node1, node2) in self.es.flows().keys()
+ assert (node2, node1) not in self.es.flows().keys()
+
+ node2.outputs[node1] = Edge()
+ assert (node0, node2) in self.es.flows().keys()
+ assert (node1, node2) in self.es.flows().keys()
+ assert (node2, node1) in self.es.flows().keys()
+
def test_that_node_additions_are_signalled(self):
"""
When a node gets `add`ed, a corresponding signal should be emitted.
diff --git a/tests/test_network_classes.py b/tests/test_network_classes.py
index 507dfd4..6b49a58 100644
--- a/tests/test_network_classes.py
+++ b/tests/test_network_classes.py
@@ -21,6 +21,8 @@ import pytest
from oemof.network.energy_system import EnergySystem as EnSys
from oemof.network.network import Bus
+from oemof.network.network import Sink
+from oemof.network.network import Source
from oemof.network.network import Transformer
from oemof.network.network.edge import Edge
from oemof.network.network.entity import Entity
@@ -124,7 +126,7 @@ class TestsNode:
"""
flow = object()
old = Node(label="A reused label")
- bus = Bus(label="bus", inputs={old: flow})
+ bus = Node(label="bus", inputs={old: flow})
assert bus.inputs[old].flow == flow, (
("\n Expected: {0}" + "\n Got : {1} instead").format(
flow, bus.inputs[old].flow
@@ -172,7 +174,7 @@ class TestsNode:
def test_modifying_inputs_after_construction(self):
"""One should be able to add and delete inputs of a node."""
node = Node("N1")
- bus = Bus("N2")
+ bus = Node("N2")
flow = "flow"
assert node.inputs == {}, (
@@ -329,12 +331,23 @@ class TestsEnergySystemNodesIntegration:
self.es = EnSys()
def test_entity_registration(self):
- b1 = Bus(label="<B1>")
- self.es.add(b1)
- assert self.es.nodes[0] == b1
- b2 = Bus(label="<B2>")
- self.es.add(b2)
- assert self.es.nodes[1] == b2
- t1 = Transformer(label="<TF1>", inputs=[b1], outputs=[b2])
- self.es.add(t1)
- assert t1 in self.es.nodes
+ n1 = Node(label="<B1>")
+ self.es.add(n1)
+ assert self.es.nodes[0] == n1
+ n2 = Node(label="<B2>")
+ self.es.add(n2)
+ assert self.es.nodes[1] == n2
+ n3 = Node(label="<TF1>", inputs=[n1], outputs=[n2])
+ self.es.add(n3)
+ assert n3 in self.es.nodes
+
+
+def test_deprecated_classes():
+ with pytest.warns(FutureWarning):
+ Bus()
+ with pytest.warns(FutureWarning):
+ Sink()
+ with pytest.warns(FutureWarning):
+ Source()
+ with pytest.warns(FutureWarning):
+ Transformer()
| Node subclasses are useless
All subclasses to Node (Bus, Component, Sink, Source, and Transformer) do not implement any additional functionality. I think, we can delete them. | 0.0 | [
"tests/test_network_classes.py::test_deprecated_classes"
] | [
"tests/test_energy_system.py::TestsEnergySystem::test_add_nodes",
"tests/test_energy_system.py::TestsEnergySystem::test_add_flow_assignment",
"tests/test_energy_system.py::TestsEnergySystem::test_that_node_additions_are_signalled",
"tests/test_network_classes.py::TestsNode::test_that_attributes_cannot_be_added",
"tests/test_network_classes.py::TestsNode::test_symmetric_input_output_assignment",
"tests/test_network_classes.py::TestsNode::test_accessing_outputs_of_a_node_without_output_flows",
"tests/test_network_classes.py::TestsNode::test_accessing_inputs_of_a_node_without_input_flows",
"tests/test_network_classes.py::TestsNode::test_that_the_outputs_attribute_of_a_node_is_a_mapping",
"tests/test_network_classes.py::TestsNode::test_that_nodes_do_not_get_undead_flows",
"tests/test_network_classes.py::TestsNode::test_modifying_outputs_after_construction",
"tests/test_network_classes.py::TestsNode::test_modifying_inputs_after_construction",
"tests/test_network_classes.py::TestsNode::test_output_input_symmetry_after_modification",
"tests/test_network_classes.py::TestsNode::test_input_output_symmetry_after_modification",
"tests/test_network_classes.py::TestsNode::test_updating_inputs",
"tests/test_network_classes.py::TestsNode::test_updating_outputs",
"tests/test_network_classes.py::TestsNode::test_error_for_duplicate_label_argument",
"tests/test_network_classes.py::TestsNode::test_entity_input_output_type_assertions",
"tests/test_network_classes.py::TestsNode::test_node_label_without_private_attribute",
"tests/test_network_classes.py::TestsNode::test_node_label_if_its_not_explicitly_specified",
"tests/test_network_classes.py::TestsEdge::test_edge_construction_side_effects",
"tests/test_network_classes.py::TestsEdge::test_label_as_positional_argument",
"tests/test_network_classes.py::TestsEdge::test_edge_failure_for_colliding_arguments",
"tests/test_network_classes.py::TestsEdge::test_alternative_edge_construction_from_mapping",
"tests/test_network_classes.py::TestsEdge::test_flow_setter",
"tests/test_network_classes.py::TestsEnergySystemNodesIntegration::test_entity_registration"
] | 2023-09-29 18:56:35+00:00 | 4,334 |
|
oemof__tespy-362 | diff --git a/docs/whats_new/v0-6-1.rst b/docs/whats_new/v0-6-1.rst
index 5632686a..70e889fe 100644
--- a/docs/whats_new/v0-6-1.rst
+++ b/docs/whats_new/v0-6-1.rst
@@ -22,6 +22,14 @@ New Features
:py:class:`tespy.connections.connection.Ref` class
(`Discussion #352 <https://github.com/oemof/tespy/discussions/352>`__).
+Bug Fixes
+#########
+- The Network's component DataFrame is now available as soon as a connection
+ is added to the network. It is possible to use the
+ :py:meth:`tespy.networks.network.Network.get_comp` method prior to
+ initializing or solving
+ (`PR #362 <https://github.com/oemof/tespy/pull/362>`_).
+
Documentation
#############
- Fix some typos in the online documentation
diff --git a/src/tespy/networks/network.py b/src/tespy/networks/network.py
index 3d638986..c8108970 100644
--- a/src/tespy/networks/network.py
+++ b/src/tespy/networks/network.py
@@ -175,7 +175,10 @@ class Network:
# connection dataframe
self.conns = pd.DataFrame(
columns=['object', 'source', 'source_id', 'target', 'target_id'],
- dtype='object')
+ dtype='object'
+ )
+ # component dataframe
+ self.comps = pd.DataFrame(dtype='object')
# user defined function dictionary for fast access
self.user_defined_eq = {}
# bus dictionary
@@ -471,6 +474,7 @@ class Network:
logging.debug(msg)
# set status "checked" to false, if connection is added to network.
self.checked = False
+ self._add_comps(*args)
def del_conns(self, *args):
"""
@@ -525,6 +529,40 @@ class Network:
logging.error(msg)
raise hlp.TESPyNetworkError(msg)
+ def _add_comps(self, *args):
+ r"""
+ Add to network's component DataFrame from added connections.
+
+ Parameters
+ ----------
+ c : tespy.connections.connection.Connection
+ The connections, which have been added to the network. The
+ components are extracted from these information.
+ """
+ # get unique components in new connections
+ comps = list(set([cp for c in args for cp in [c.source, c.target]]))
+ # add to the dataframe of components
+ for comp in comps:
+ if comp.label in self.comps.index:
+ if self.comps.loc[comp.label, 'object'] == comp:
+ continue
+ else:
+ comp_type = comp.__class__.__name__
+ other_obj = self.comps.loc[comp.label, "object"]
+ other_comp_type = other_obj.__class__.__name__
+ msg = (
+ f"The component with the label {comp.label} of type "
+ f"{comp_type} cannot be added to the network as a "
+ f"different component of type {other_comp_type} with "
+ "the same label has already been added. All "
+ "components must have unique values!"
+ )
+ raise hlp.TESPyNetworkError(msg)
+
+ comp_type = comp.__class__.__name__
+ self.comps.loc[comp.label, 'comp_type'] = comp_type
+ self.comps.loc[comp.label, 'object'] = comp
+
def add_ude(self, *args):
r"""
Add a user defined function to the network.
@@ -644,21 +682,21 @@ class Network:
if len(self.conns) == 0:
msg = (
'No connections have been added to the network, please make '
- 'sure to add your connections with the .add_conns() method.')
+ 'sure to add your connections with the .add_conns() method.'
+ )
logging.error(msg)
raise hlp.TESPyNetworkError(msg)
if len(self.fluids) == 0:
- msg = ('Network has no fluids, please specify a list with fluids '
- 'on network creation.')
+ msg = (
+ 'Network has no fluids, please specify a list with fluids on '
+ 'network creation.'
+ )
logging.error(msg)
raise hlp.TESPyNetworkError(msg)
self.check_conns()
- # get unique components in connections dataframe
- comps = pd.unique(self.conns[['source', 'target']].values.ravel())
- # build the dataframe for components
- self.init_components(comps)
+ self.init_components()
# count number of incoming and outgoing connections and compare to
# expected values
for comp in self.comps['object']:
@@ -686,32 +724,9 @@ class Network:
msg = 'Networkcheck successful.'
logging.info(msg)
- def init_components(self, comps):
- r"""
- Set up a dataframe for the network's components.
-
- Additionally, check, if all components have unique labels.
-
- Parameters
- ----------
- comps : pandas.core.frame.DataFrame
- DataFrame containing all components of the network gathered from
- the network's connection information.
-
- Note
- ----
- The dataframe for the components is derived from the network's
- connections. Thus it does not hold any additional information, the
- dataframe is used to simplify the code, only.
- """
- self.comps = pd.DataFrame(dtype='object')
-
- labels = []
- for comp in comps:
- # this is required for printing and saving
- comp_type = comp.__class__.__name__
- self.comps.loc[comp, 'comp_type'] = comp_type
- self.comps.loc[comp, 'label'] = comp.label
+ def init_components(self):
+ r"""Set up necessary component information."""
+ for comp in self.comps["object"]:
# get incoming and outgoing connections of a component
sources = self.conns[self.conns['source'] == comp]
sources = sources['source_id'].sort_values().index.tolist()
@@ -723,13 +738,14 @@ class Network:
comp.outl = self.conns.loc[sources, 'object'].tolist()
comp.num_i = len(comp.inlets())
comp.num_o = len(comp.outlets())
- labels += [comp.label]
# save the connection locations to the components
comp.conn_loc = []
for c in comp.inl + comp.outl:
comp.conn_loc += [self.conns.index.get_loc(c.label)]
+ # set up restults and specification dataframes
+ comp_type = comp.__class__.__name__
if comp_type not in self.results:
cols = [col for col, data in comp.variables.items()
if isinstance(data, dc_cp)]
@@ -751,18 +767,6 @@ class Network:
'properties': pd.DataFrame(columns=cols, dtype='bool')
}
- self.comps = self.comps.reset_index().set_index('label')
- self.comps.rename(columns={'index': 'object'}, inplace=True)
-
- # check for duplicates in the component labels
- if len(labels) != len(list(set(labels))):
- duplicates = [
- item for item, count in Counter(labels).items() if count > 1]
- msg = ('All Components must have unique labels, duplicate labels '
- 'are: "' + '", "'.join(duplicates) + '".')
- logging.error(msg)
- raise hlp.TESPyNetworkError(msg)
-
def initialise(self):
r"""
Initilialise the network depending on calclation mode.
@@ -2627,9 +2631,12 @@ class Network:
if len(df) > 0:
# printout with tabulate
print('##### RESULTS (' + cp + ') #####')
- print(tabulate(
- df, headers='keys', tablefmt='psql',
- floatfmt='.2e'))
+ print(
+ tabulate(
+ df, headers='keys', tablefmt='psql',
+ floatfmt='.2e'
+ )
+ )
# connection properties
df = self.results['Connection'].loc[:, ['m', 'p', 'h', 'T']]
@@ -2648,7 +2655,8 @@ class Network:
if len(df) > 0:
print('##### RESULTS (Connection) #####')
print(
- tabulate(df, headers='keys', tablefmt='psql', floatfmt='.3e'))
+ tabulate(df, headers='keys', tablefmt='psql', floatfmt='.3e')
+ )
for b in self.busses.values():
if b.printout:
@@ -2661,8 +2669,12 @@ class Network:
coloring['set'] + str(df.loc['total', 'bus value']) +
coloring['end'])
print('##### RESULTS (Bus: ' + b.label + ') #####')
- print(tabulate(df, headers='keys', tablefmt='psql',
- floatfmt='.3e'))
+ print(
+ tabulate(
+ df, headers='keys', tablefmt='psql',
+ floatfmt='.3e'
+ )
+ )
def print_components(self, c, *args):
"""
| oemof/tespy | a7918b5f2f3c32c4272222d07e58c0a8a8f3afc7 | diff --git a/tests/test_errors.py b/tests/test_errors.py
index b5a9419f..58a516b7 100644
--- a/tests/test_errors.py
+++ b/tests/test_errors.py
@@ -515,9 +515,8 @@ class TestNetworkErrors:
source = Source('label')
sink = Sink('label')
a = Connection(source, 'out1', sink, 'in1')
- self.nw.add_conns(a)
with raises(TESPyNetworkError):
- self.nw.check_network()
+ self.nw.add_conns(a)
def test_missing_offdesign_path(self):
source = Source('source')
diff --git a/tests/test_networks/test_network.py b/tests/test_networks/test_network.py
index ab856c3d..8078f2c2 100644
--- a/tests/test_networks/test_network.py
+++ b/tests/test_networks/test_network.py
@@ -253,6 +253,33 @@ class TestNetworks:
shutil.rmtree('./tmp', ignore_errors=True)
+ def test_Network_get_comp_without_connections_added(self):
+ """Test if components are found prior to initialization."""
+ self.setup_Network_tests()
+ pi = Pipe('pipe')
+ a = Connection(self.source, 'out1', pi, 'in1')
+ b = Connection(pi, 'out1', self.sink, 'in1')
+ self.nw.add_conns(a)
+ msg = (
+ "A component with the label 'sink' has been created but must not "
+ "be part of the network as the respective connection has not "
+ "been added."
+ )
+ assert self.nw.get_comp("sink") == None, msg
+
+ def test_Network_get_comp_before_initialization(self):
+ """Test if components are found prior to initialization."""
+ self.setup_Network_tests()
+ pi = Pipe('pipe')
+ a = Connection(self.source, 'out1', pi, 'in1')
+ b = Connection(pi, 'out1', self.sink, 'in1')
+ self.nw.add_conns(a, b)
+ msg = (
+ "A component with the label 'pipe' is part of the network "
+ "and therefore must be found in the DataFrame."
+ )
+ assert self.nw.get_comp("pipe") == pi, msg
+
class TestNetworkIndividualOffdesign:
| get_comps of class Network does not work prior to first solve
### Discussed in https://github.com/oemof/tespy/discussions/359
<div type='discussions-op-text'>
<sup>Originally posted by **GoldenPotatis** September 22, 2022</sup>
Hi!
I'm a new user of TESPy and still learning. I found this small issue and would like to share with the community.
I'm using Python3.8.9 and TESPy0.6.0
In the Network Class, it is possible to view the network connections and components by calling the `network.conns` attributes and `network.comps` attributes. The `network.conns` works perfectly fine. However, the user may find that `network.comps` does not work. It returns `AttributeError: 'Network' object has no attribute 'comps'`.
The example I'm using is a simple condenser cooled by air, same as in the [Condenser example code in tespy.readthedocs](https://tespy.readthedocs.io/en/main/api/tespy.components.html#module-tespy.components.heat_exchangers.condenser):
```python
from tespy.networks import Network
from tespy.components import Source, Sink, Condenser
from tespy.connections import Connection
# create a network and components
nw = Network(fluids=['water', 'air'], T_unit='C', p_unit='bar', h_unit='kJ / kg')
air_in = Source(label='air inlet')
air_out = Sink('air outlet')
waste_steam = Source('waste steam')
water = Sink('condensate water')
condenser = Condenser('condenser')
# create connections
air_con = Connection(air_in, 'out1', condenser, 'in2', label='air to condenser')
con_air = Connection(condenser, 'out2', air_out, 'in1', label='condenser to air')
ws_con = Connection(waste_steam, 'out1', condenser, 'in1', label='ws to con')
con_water = Connection(condenser, 'out1', water, 'in1')
nw.add_conns(air_con, con_air, ws_con, con_water)
```
When calling the `nw.conns` attributes, it will return a Pandas DataFrame. But calling `nw.comps` will result in `AttributeError: 'Network' object has no attribute 'comps'`.

Correspondingly, the `Network.get_comp()` doesn't work neither.
After looking into the source code of Network, it is found that the `network.conns` is initiated at the beginning under `def __init__(self, fluids, memorise_fluid_properties=True, **kwargs)` and `def set_defaults(self)`. But `network.comps` is not initiated. The first time `network.comps` is initiated is actually under `def check_network(self)`, which is:
```python
comps = pd.unique(self.conns[['source', 'target']].values.ravel())
# build the dataframe for components
```
After running `nw.check_network()`, the `nw.comps` then works perfectly fine, which gives a dataframe of the components.

It is therefore suggested to initiate the `.comps` at the beginning of the code to avoid such error.
Another attached question is under the example code of Condenser in readthedocs, why the air inlet is Sink and air outlet is Source?
```python
amb_in = Sink('ambient air inlet')
amb_out = Source('air outlet')
```
Based on the definition of Source and Sink, should it be like air inlet is Source and air outlet is Sink?
</div> | 0.0 | [
"tests/test_networks/test_network.py::TestNetworks::test_Network_get_comp_without_connections_added",
"tests/test_networks/test_network.py::TestNetworks::test_Network_get_comp_before_initialization"
] | [
"tests/test_errors.py::test_set_attr_errors",
"tests/test_errors.py::test_get_attr_errors",
"tests/test_errors.py::test_cmp_instanciation_ValueError",
"tests/test_errors.py::test_Connection_creation_ValueError",
"tests/test_errors.py::test_Connection_creation_TypeError",
"tests/test_errors.py::test_Connection_creation_TESPyConnectionError",
"tests/test_errors.py::test_ref_creation_error",
"tests/test_errors.py::test_Bus_add_comps_errors",
"tests/test_errors.py::test_UserDefinedEquation_errors",
"tests/test_errors.py::test_CombustionChamber_missing_fuel",
"tests/test_errors.py::test_CombustionChamber_missing_oxygen",
"tests/test_errors.py::test_compressor_missing_char_parameter",
"tests/test_errors.py::test_subsys_label_str",
"tests/test_errors.py::test_subsys_label_forbidden",
"tests/test_errors.py::test_Turbine_missing_char_parameter",
"tests/test_errors.py::TestWaterElectrolyzerErrors::test_missing_hydrogen_in_Network",
"tests/test_errors.py::TestWaterElectrolyzerErrors::test_missing_oxygen_in_Network",
"tests/test_errors.py::TestWaterElectrolyzerErrors::test_missing_water_in_Network",
"tests/test_errors.py::test_wrong_Bus_param_func",
"tests/test_errors.py::test_wrong_Bus_param_deriv",
"tests/test_errors.py::test_Network_instanciation_no_fluids",
"tests/test_errors.py::test_Network_instanciation_single_fluid",
"tests/test_errors.py::test_char_number_of_points",
"tests/test_errors.py::test_CharMap_number_of_points",
"tests/test_errors.py::test_CharMap_number_of_dimensions",
"tests/test_errors.py::test_CharMap_y_z_dimension_mismatch",
"tests/test_errors.py::test_missing_CharLine_files",
"tests/test_errors.py::test_missing_CharMap_files",
"tests/test_errors.py::test_h_mix_pQ_on_mixtures",
"tests/test_networks/test_network.py::TestNetworks::test_Network_linear_dependency",
"tests/test_networks/test_network.py::TestNetworks::test_Network_no_progress",
"tests/test_networks/test_network.py::TestNetworks::test_Network_max_iter",
"tests/test_networks/test_network.py::TestNetworks::test_Network_delete_conns",
"tests/test_networks/test_network.py::TestNetworks::test_Network_missing_connection_in_init_path",
"tests/test_networks/test_network.py::TestNetworks::test_Network_export_no_chars_busses",
"tests/test_networks/test_network.py::TestNetworks::test_Network_reader_no_chars_busses",
"tests/test_networks/test_network.py::TestNetworks::test_Network_reader_deleted_chars",
"tests/test_networks/test_network.py::TestNetworks::test_Network_missing_data_in_design_case_files",
"tests/test_networks/test_network.py::TestNetworks::test_Network_missing_data_in_individual_design_case_file",
"tests/test_networks/test_network.py::TestNetworks::test_Network_missing_connection_in_design_path",
"tests/test_networks/test_network.py::TestNetworkIndividualOffdesign::test_individual_design_path_on_connections_and_components",
"tests/test_networks/test_network.py::TestNetworkIndividualOffdesign::test_local_offdesign_on_connections_and_components",
"tests/test_networks/test_network.py::TestNetworkIndividualOffdesign::test_missing_design_path_local_offdesign_on_connections"
] | 2022-10-02 08:53:00+00:00 | 4,335 |
|
oemof__tespy-459 | diff --git a/docs/whats_new.rst b/docs/whats_new.rst
index f03b829f..7f5718e0 100644
--- a/docs/whats_new.rst
+++ b/docs/whats_new.rst
@@ -3,6 +3,7 @@ What's New
Discover noteable new features and improvements in each release
+.. include:: whats_new/v0-7-2.rst
.. include:: whats_new/v0-7-1.rst
.. include:: whats_new/v0-7-0.rst
.. include:: whats_new/v0-6-3.rst
diff --git a/docs/whats_new/v0-7-2.rst b/docs/whats_new/v0-7-2.rst
new file mode 100644
index 00000000..ca1c1c59
--- /dev/null
+++ b/docs/whats_new/v0-7-2.rst
@@ -0,0 +1,12 @@
+v0.7.2 - Under development
+++++++++++++++++++++++++++
+
+Bug Fixes
+#########
+- The `delta` value of the :py:class:`tespy.connections.connection.Ref` class
+ was oriented with the wrong sign. A positive delta lead to a negative value.
+ Fixed in (`PR #459 <https://github.com/oemof/tespy/pull/459>`__).
+
+Contributors
+############
+- Francesco Witte (`@fwitte <https://github.com/fwitte>`__)
diff --git a/src/tespy/connections/connection.py b/src/tespy/connections/connection.py
index ceb64a66..459bcd14 100644
--- a/src/tespy/connections/connection.py
+++ b/src/tespy/connections/connection.py
@@ -726,7 +726,7 @@ class Connection:
ref = self.get_attr(f"{variable}_ref").ref
self.residual[k] = (
self.get_attr(variable).val_SI
- - ref.obj.get_attr(variable).val_SI * ref.factor + ref.delta_SI
+ - (ref.obj.get_attr(variable).val_SI * ref.factor + ref.delta_SI)
)
def primary_ref_deriv(self, k, **kwargs):
@@ -761,7 +761,7 @@ class Connection:
def T_ref_func(self, k, **kwargs):
ref = self.T_ref.ref
self.residual[k] = (
- self.calc_T() - ref.obj.calc_T() * ref.factor + ref.delta_SI
+ self.calc_T() - (ref.obj.calc_T() * ref.factor + ref.delta_SI)
)
def T_ref_deriv(self, k, **kwargs):
@@ -810,7 +810,7 @@ class Connection:
ref = self.v_ref.ref
self.residual[k] = (
self.calc_vol(T0=self.T.val_SI) * self.m.val_SI
- - ref.obj.calc_vol(T0=ref.obj.T.val_SI) * ref.obj.m.val_SI * ref.factor + ref.delta_SI
+ - (ref.obj.calc_vol(T0=ref.obj.T.val_SI) * ref.obj.m.val_SI * ref.factor + ref.delta_SI)
)
def v_ref_deriv(self, k, **kwargs):
diff --git a/src/tespy/tools/helpers.py b/src/tespy/tools/helpers.py
index e177474e..d92ebf04 100644
--- a/src/tespy/tools/helpers.py
+++ b/src/tespy/tools/helpers.py
@@ -628,7 +628,7 @@ def newton(func, deriv, params, y, **kwargs):
logger.debug(msg)
break
- if tol_mode == 'abs':
+ if tol_mode == 'abs' or y == 0:
expr = abs(res) >= tol_abs
elif tol_mode == 'rel':
expr = abs(res / y) >= tol_rel
@@ -680,7 +680,7 @@ def newton_with_kwargs(
logger.debug(msg)
break
- if tol_mode == 'abs':
+ if tol_mode == 'abs' or target_value == 0:
expr = abs(residual) >= tol_abs
elif tol_mode == 'rel':
expr = abs(residual / target_value) >= tol_rel
| oemof/tespy | a7f2de7cc1f967ba531fbfe877f1fe2b1f6a9af5 | diff --git a/tests/test_connections.py b/tests/test_connections.py
index acc620a2..6d35bdf8 100644
--- a/tests/test_connections.py
+++ b/tests/test_connections.py
@@ -58,7 +58,7 @@ class TestConnections:
c2.set_attr(v=Ref(c1, 2, 10))
self.nw.solve('design')
- v_expected = round(c1.v.val * 2 - 10, 4)
+ v_expected = round(c1.v.val * 2 + 10, 4)
v_is = round(c2.v.val, 4)
msg = (
'The mass flow of the connection 2 should be equal to '
@@ -87,7 +87,7 @@ class TestConnections:
c2.set_attr(T=Ref(c1, 1.5, -75))
self.nw.solve('design')
- T_expected = round(convert_from_SI("T", c1.T.val_SI * 1.5, c1.T.unit) + 75, 4)
+ T_expected = round(convert_from_SI("T", c1.T.val_SI * 1.5, c1.T.unit) - 75, 4)
T_is = round(c2.T.val, 4)
msg = (
'The temperature of the connection 2 should be equal to '
@@ -116,7 +116,7 @@ class TestConnections:
c2.set_attr(m=Ref(c1, 2, -0.5))
self.nw.solve('design')
- m_expected = round(convert_from_SI("m", c1.m.val_SI * 2, c1.m.unit) + 0.5, 4)
+ m_expected = round(convert_from_SI("m", c1.m.val_SI * 2, c1.m.unit) - 0.5, 4)
m_is = round(c2.m.val, 4)
msg = (
'The mass flow of the connection 2 should be equal to '
| The Ref class imposes negative value for delta
... which is unintuitive. | 0.0 | [
"tests/test_connections.py::TestConnections::test_volumetric_flow_reference",
"tests/test_connections.py::TestConnections::test_temperature_reference",
"tests/test_connections.py::TestConnections::test_primary_reference"
] | [] | 2023-12-07 17:55:36+00:00 | 4,336 |
|
ofek__bit-24 | diff --git a/bit/format.py b/bit/format.py
index 5ff8679..088d990 100644
--- a/bit/format.py
+++ b/bit/format.py
@@ -35,6 +35,8 @@ def verify_sig(signature, data, public_key):
def address_to_public_key_hash(address):
+ # Raise ValueError if we cannot identify the address.
+ get_version(address)
return b58decode_check(address)[1:]
| ofek/bit | 37182647309b54934fb49078d4c7a2fb21d7eb47 | diff --git a/tests/samples.py b/tests/samples.py
index 8a9ad70..82b64ae 100644
--- a/tests/samples.py
+++ b/tests/samples.py
@@ -1,8 +1,10 @@
BINARY_ADDRESS = b'\x00\x92F\x1b\xdeb\x83\xb4a\xec\xe7\xdd\xf4\xdb\xf1\xe0\xa4\x8b\xd1\x13\xd8&E\xb4\xbf'
BITCOIN_ADDRESS = '1ELReFsTCUY2mfaDTy32qxYiT49z786eFg'
BITCOIN_ADDRESS_COMPRESSED = '1ExJJsNLQDNVVM1s1sdyt1o5P3GC5r32UG'
+BITCOIN_ADDRESS_PAY2SH = '39SrGQEfFXcTYJhBvjZeQja66Cpz82EEUn'
BITCOIN_ADDRESS_TEST = 'mtrNwJxS1VyHYn3qBY1Qfsm3K3kh1mGRMS'
BITCOIN_ADDRESS_TEST_COMPRESSED = 'muUFbvTKDEokGTVUjScMhw1QF2rtv5hxCz'
+BITCOIN_ADDRESS_TEST_PAY2SH = '2NFKbBHzzh32q5DcZJNgZE9sF7gYmtPbawk'
PRIVATE_KEY_BYTES = b'\xc2\x8a\x9f\x80s\x8fw\rRx\x03\xa5f\xcfo\xc3\xed\xf6\xce\xa5\x86\xc4\xfcJR#\xa5\xady~\x1a\xc3'
PRIVATE_KEY_DER = (b"0\x81\x84\x02\x01\x000\x10\x06\x07*\x86H\xce=\x02\x01\x06"
b"\x05+\x81\x04\x00\n\x04m0k\x02\x01\x01\x04 \xc2\x8a\x9f"
diff --git a/tests/test_format.py b/tests/test_format.py
index b338b03..86dcace 100644
--- a/tests/test_format.py
+++ b/tests/test_format.py
@@ -6,9 +6,11 @@ from bit.format import (
public_key_to_address, verify_sig, wif_checksum_check, wif_to_bytes
)
from .samples import (
- BITCOIN_ADDRESS, BITCOIN_ADDRESS_COMPRESSED, BITCOIN_ADDRESS_TEST_COMPRESSED,
- BITCOIN_ADDRESS_TEST, PRIVATE_KEY_BYTES, PUBKEY_HASH, PUBKEY_HASH_COMPRESSED,
- PUBLIC_KEY_COMPRESSED, PUBLIC_KEY_UNCOMPRESSED, PUBLIC_KEY_X, PUBLIC_KEY_Y,
+ BITCOIN_ADDRESS, BITCOIN_ADDRESS_COMPRESSED, BITCOIN_ADDRESS_PAY2SH,
+ BITCOIN_ADDRESS_TEST_COMPRESSED, BITCOIN_ADDRESS_TEST,
+ BITCOIN_ADDRESS_TEST_PAY2SH, PRIVATE_KEY_BYTES, PUBKEY_HASH,
+ PUBKEY_HASH_COMPRESSED, PUBLIC_KEY_COMPRESSED, PUBLIC_KEY_UNCOMPRESSED,
+ PUBLIC_KEY_X, PUBLIC_KEY_Y,
WALLET_FORMAT_COMPRESSED_MAIN, WALLET_FORMAT_COMPRESSED_TEST,
WALLET_FORMAT_MAIN, WALLET_FORMAT_TEST
)
@@ -41,6 +43,14 @@ class TestGetVersion:
with pytest.raises(ValueError):
get_version('dg2dNAjuezub6iJVPNML5pW5ZQvtA9ocL')
+ def test_mainnet_pay2sh(self):
+ with pytest.raises(ValueError):
+ get_version(BITCOIN_ADDRESS_PAY2SH)
+
+ def test_testnet_pay2sh(self):
+ with pytest.raises(ValueError):
+ get_version(BITCOIN_ADDRESS_TEST_PAY2SH)
+
class TestVerifySig:
def test_valid(self):
@@ -146,3 +156,7 @@ def test_point_to_public_key():
def test_address_to_public_key_hash():
assert address_to_public_key_hash(BITCOIN_ADDRESS) == PUBKEY_HASH
assert address_to_public_key_hash(BITCOIN_ADDRESS_COMPRESSED) == PUBKEY_HASH_COMPRESSED
+ with pytest.raises(ValueError):
+ address_to_public_key_hash(BITCOIN_ADDRESS_PAY2SH)
+ with pytest.raises(ValueError):
+ address_to_public_key_hash(BITCOIN_ADDRESS_TEST_PAY2SH)
diff --git a/tests/test_wallet.py b/tests/test_wallet.py
index 44d882d..6fbbfdd 100644
--- a/tests/test_wallet.py
+++ b/tests/test_wallet.py
@@ -238,6 +238,21 @@ class TestPrivateKeyTestnet:
assert current > initial
+ def test_send_pay2sh(self):
+ """
+ We don't yet support pay2sh, so we must throw an exception if we get one.
+ Otherwise, we could send coins into an unrecoverable blackhole, needlessly.
+ pay2sh addresses begin with 2 in testnet and 3 on mainnet.
+ """
+ if TRAVIS and sys.version_info[:2] != (3, 6):
+ return
+
+ private_key = PrivateKeyTestnet(WALLET_FORMAT_COMPRESSED_TEST)
+ private_key.get_unspents()
+
+ with pytest.raises(ValueError):
+ private_key.send([('2NFKbBHzzh32q5DcZJNgZE9sF7gYmtPbawk', 1, 'jpy')])
+
def test_cold_storage(self):
if TRAVIS and sys.version_info[:2] != (3, 6):
return
| Pay to scripthash
I have no experience with paying to scripthashes except when it's worked automagically for me before.
In #12 it looks like the initial workins of P2SH are being added. I'm not sure how straight forward P2SH is.
But... for the time being shouldn't we throw an exception if we try to `send()` to an address that does not begin with 1? Are there any sideeffects to doing so?
I think I just lost a fair bit of coin not reviewing this properly. Hopefully if we add in an exception we can keep others from doing the same. | 0.0 | [
"tests/test_format.py::test_address_to_public_key_hash"
] | [
"tests/test_format.py::TestGetVersion::test_mainnet",
"tests/test_format.py::TestGetVersion::test_testnet",
"tests/test_format.py::TestGetVersion::test_invalid",
"tests/test_format.py::TestGetVersion::test_mainnet_pay2sh",
"tests/test_format.py::TestGetVersion::test_testnet_pay2sh",
"tests/test_format.py::TestVerifySig::test_valid",
"tests/test_format.py::TestVerifySig::test_invalid",
"tests/test_format.py::TestBytesToWIF::test_mainnet",
"tests/test_format.py::TestBytesToWIF::test_testnet",
"tests/test_format.py::TestBytesToWIF::test_compressed",
"tests/test_format.py::TestBytesToWIF::test_compressed_testnet",
"tests/test_format.py::TestWIFToBytes::test_mainnet",
"tests/test_format.py::TestWIFToBytes::test_testnet",
"tests/test_format.py::TestWIFToBytes::test_compressed",
"tests/test_format.py::TestWIFToBytes::test_invalid_network",
"tests/test_format.py::TestWIFChecksumCheck::test_wif_checksum_check_main_success",
"tests/test_format.py::TestWIFChecksumCheck::test_wif_checksum_check_test_success",
"tests/test_format.py::TestWIFChecksumCheck::test_wif_checksum_check_compressed_success",
"tests/test_format.py::TestWIFChecksumCheck::test_wif_checksum_check_decode_failure",
"tests/test_format.py::TestWIFChecksumCheck::test_wif_checksum_check_other_failure",
"tests/test_format.py::TestPublicKeyToCoords::test_public_key_to_coords_compressed",
"tests/test_format.py::TestPublicKeyToCoords::test_public_key_to_coords_uncompressed",
"tests/test_format.py::TestPublicKeyToCoords::test_public_key_to_coords_incorrect_length",
"tests/test_format.py::TestPublicKeyToAddress::test_public_key_to_address_compressed",
"tests/test_format.py::TestPublicKeyToAddress::test_public_key_to_address_uncompressed",
"tests/test_format.py::TestPublicKeyToAddress::test_public_key_to_address_incorrect_length",
"tests/test_format.py::TestPublicKeyToAddress::test_public_key_to_address_test_compressed",
"tests/test_format.py::TestPublicKeyToAddress::test_public_key_to_address_test_uncompressed",
"tests/test_format.py::TestCoordsToPublicKey::test_coords_to_public_key_compressed",
"tests/test_format.py::TestCoordsToPublicKey::test_coords_to_public_key_uncompressed",
"tests/test_format.py::test_point_to_public_key",
"tests/test_wallet.py::TestWIFToKey::test_compressed_main",
"tests/test_wallet.py::TestWIFToKey::test_uncompressed_main",
"tests/test_wallet.py::TestWIFToKey::test_compressed_test",
"tests/test_wallet.py::TestWIFToKey::test_uncompressed_test",
"tests/test_wallet.py::TestBaseKey::test_init_default",
"tests/test_wallet.py::TestBaseKey::test_init_from_key",
"tests/test_wallet.py::TestBaseKey::test_init_wif_error",
"tests/test_wallet.py::TestBaseKey::test_public_key_compressed",
"tests/test_wallet.py::TestBaseKey::test_public_key_uncompressed",
"tests/test_wallet.py::TestBaseKey::test_public_point",
"tests/test_wallet.py::TestBaseKey::test_sign",
"tests/test_wallet.py::TestBaseKey::test_verify_success",
"tests/test_wallet.py::TestBaseKey::test_verify_failure",
"tests/test_wallet.py::TestBaseKey::test_to_hex",
"tests/test_wallet.py::TestBaseKey::test_to_bytes",
"tests/test_wallet.py::TestBaseKey::test_to_der",
"tests/test_wallet.py::TestBaseKey::test_to_pem",
"tests/test_wallet.py::TestBaseKey::test_to_int",
"tests/test_wallet.py::TestBaseKey::test_is_compressed",
"tests/test_wallet.py::TestBaseKey::test_equal",
"tests/test_wallet.py::TestPrivateKey::test_alias",
"tests/test_wallet.py::TestPrivateKey::test_init_default",
"tests/test_wallet.py::TestPrivateKey::test_address",
"tests/test_wallet.py::TestPrivateKey::test_to_wif",
"tests/test_wallet.py::TestPrivateKey::test_get_balance",
"tests/test_wallet.py::TestPrivateKey::test_get_unspent",
"tests/test_wallet.py::TestPrivateKey::test_get_transactions",
"tests/test_wallet.py::TestPrivateKey::test_from_hex",
"tests/test_wallet.py::TestPrivateKey::test_from_der",
"tests/test_wallet.py::TestPrivateKey::test_from_pem",
"tests/test_wallet.py::TestPrivateKey::test_from_int",
"tests/test_wallet.py::TestPrivateKey::test_repr",
"tests/test_wallet.py::TestPrivateKeyTestnet::test_init_default",
"tests/test_wallet.py::TestPrivateKeyTestnet::test_address",
"tests/test_wallet.py::TestPrivateKeyTestnet::test_to_wif",
"tests/test_wallet.py::TestPrivateKeyTestnet::test_from_hex",
"tests/test_wallet.py::TestPrivateKeyTestnet::test_from_der",
"tests/test_wallet.py::TestPrivateKeyTestnet::test_from_pem",
"tests/test_wallet.py::TestPrivateKeyTestnet::test_from_int",
"tests/test_wallet.py::TestPrivateKeyTestnet::test_repr"
] | 2017-12-18 20:34:04+00:00 | 4,337 |
|
ofek__bit-32 | diff --git a/.gitignore b/.gitignore
index 9367500..ba62003 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,5 +1,6 @@
*.log
*.pyc
+*.orig
/.cache
/.idea
/.coverage
diff --git a/bit/network/fees.py b/bit/network/fees.py
index 58a783a..4204400 100644
--- a/bit/network/fees.py
+++ b/bit/network/fees.py
@@ -1,3 +1,4 @@
+import logging
from functools import wraps
from time import time
@@ -54,7 +55,12 @@ def get_fee_local_cache(f):
cached_fee_fast = request.json()['fastestFee']
fast_last_update = now
except (ConnectionError, HTTPError, Timeout): # pragma: no cover
- return cached_fee_fast or DEFAULT_FEE_FAST
+ if cached_fee_fast is None:
+ logging.warning('Connection to fee API failed, returning default fee (fast) of {}'.format(DEFAULT_FEE_FAST))
+ return DEFAULT_FEE_FAST
+ else:
+ logging.warning('Connection to fee API failed, returning cached fee (fast).')
+ return cached_fee_fast
return cached_fee_fast
@@ -71,7 +77,12 @@ def get_fee_local_cache(f):
cached_fee_hour = request.json()['hourFee']
hour_last_update = now
except (ConnectionError, HTTPError, Timeout): # pragma: no cover
- return cached_fee_hour or DEFAULT_FEE_HOUR
+ if cached_fee_hour is None:
+ logging.warning('Connection to fee API failed, returning default fee (hour) of {}'.format(DEFAULT_FEE_HOUR))
+ return DEFAULT_FEE_HOUR
+ else:
+ logging.warning('Connection to fee API failed, returning cached fee (hour).')
+ return cached_fee_hour
return cached_fee_hour
diff --git a/bit/transaction.py b/bit/transaction.py
index 7ef723c..4f38bdd 100644
--- a/bit/transaction.py
+++ b/bit/transaction.py
@@ -1,3 +1,4 @@
+import logging
from collections import namedtuple
from itertools import islice
@@ -70,10 +71,19 @@ def estimate_tx_fee(n_in, n_out, satoshis, compressed):
+ 8
)
- return estimated_size * satoshis
+ estimated_fee = estimated_size * satoshis
+
+ logging.debug('Estimated fee: {} satoshis for {} bytes'.format(estimated_fee, estimated_size))
+
+ return estimated_fee
def sanitize_tx_data(unspents, outputs, fee, leftover, combine=True, message=None, compressed=True):
+ """
+ sanitize_tx_data()
+
+ fee is in satoshis per byte.
+ """
outputs = outputs.copy()
@@ -94,12 +104,15 @@ def sanitize_tx_data(unspents, outputs, fee, leftover, combine=True, message=Non
messages.append((message, 0))
# Include return address in fee estimate.
- fee = estimate_tx_fee(len(unspents), len(outputs) + len(messages) + 1, fee, compressed)
- total_out = sum(out[1] for out in outputs) + fee
total_in = 0
+ num_outputs = len(outputs) + len(messages) + 1
+ sum_outputs = sum(out[1] for out in outputs)
if combine:
+ # calculated_fee is in total satoshis.
+ calculated_fee = estimate_tx_fee(len(unspents), num_outputs, fee, compressed)
+ total_out = sum_outputs + calculated_fee
unspents = unspents.copy()
total_in += sum(unspent.amount for unspent in unspents)
@@ -110,6 +123,8 @@ def sanitize_tx_data(unspents, outputs, fee, leftover, combine=True, message=Non
for index, unspent in enumerate(unspents):
total_in += unspent.amount
+ calculated_fee = estimate_tx_fee(len(unspents[:index + 1]), num_outputs, fee, compressed)
+ total_out = sum_outputs + calculated_fee
if total_in >= total_out:
break
| ofek/bit | 89dcd0a8d05b785691b34a9b28dee157ee419bea | diff --git a/tests/test_transaction.py b/tests/test_transaction.py
index 9f792ec..fc1a881 100644
--- a/tests/test_transaction.py
+++ b/tests/test_transaction.py
@@ -172,6 +172,48 @@ class TestSanitizeTxData:
assert outputs[1][0] == RETURN_ADDRESS
assert outputs[1][1] == 1000
+ def test_no_combine_remaining_small_inputs(self):
+ unspents_original = [Unspent(1500, 0, '', '', 0),
+ Unspent(1600, 0, '', '', 0),
+ Unspent(1700, 0, '', '', 0)]
+ outputs_original = [(RETURN_ADDRESS, 2000, 'satoshi')]
+
+ unspents, outputs = sanitize_tx_data(
+ unspents_original, outputs_original, fee=0, leftover=RETURN_ADDRESS,
+ combine=False, message=None
+ )
+ assert unspents == [Unspent(1500, 0, '', '', 0), Unspent(1600, 0, '', '', 0)]
+ assert len(outputs) == 2
+ assert outputs[1][0] == RETURN_ADDRESS
+ assert outputs[1][1] == 1100
+
+ def test_no_combine_with_fee(self):
+ """
+ Verify that unused unspents do not increase fee.
+ """
+ unspents_single = [Unspent(5000, 0, '', '', 0)]
+ unspents_original = [Unspent(5000, 0, '', '', 0),
+ Unspent(5000, 0, '', '', 0)]
+ outputs_original = [(RETURN_ADDRESS, 1000, 'satoshi')]
+
+ unspents, outputs = sanitize_tx_data(
+ unspents_original, outputs_original, fee=1, leftover=RETURN_ADDRESS,
+ combine=False, message=None
+ )
+
+ unspents_single, outputs_single = sanitize_tx_data(
+ unspents_single, outputs_original, fee=1, leftover=RETURN_ADDRESS,
+ combine=False, message=None
+ )
+
+ assert unspents == [Unspent(5000, 0, '', '', 0)]
+ assert unspents_single == [Unspent(5000, 0, '', '', 0)]
+ assert len(outputs) == 2
+ assert len(outputs_single) == 2
+ assert outputs[1][0] == RETURN_ADDRESS
+ assert outputs_single[1][0] == RETURN_ADDRESS
+ assert outputs[1][1] == outputs_single[1][1]
+
def test_no_combine_insufficient_funds(self):
unspents_original = [Unspent(1000, 0, '', '', 0),
Unspent(1000, 0, '', '', 0)]
| Bug with send(combine=False)
I think there's some weird behavior here.
https://blockchain.info/tx/6519c1977bf0863aed1b70caeaeb521c32fab43e5fd663c310f09cdee63d0ad6?show_adv=true
The fee was super high but I think that was a sideeffect of the main bug. | 0.0 | [
"tests/test_transaction.py::TestSanitizeTxData::test_no_combine_with_fee"
] | [
"tests/test_transaction.py::TestTxIn::test_init",
"tests/test_transaction.py::TestTxIn::test_equality",
"tests/test_transaction.py::TestTxIn::test_repr",
"tests/test_transaction.py::TestSanitizeTxData::test_no_input",
"tests/test_transaction.py::TestSanitizeTxData::test_message",
"tests/test_transaction.py::TestSanitizeTxData::test_fee_applied",
"tests/test_transaction.py::TestSanitizeTxData::test_zero_remaining",
"tests/test_transaction.py::TestSanitizeTxData::test_combine_remaining",
"tests/test_transaction.py::TestSanitizeTxData::test_combine_insufficient_funds",
"tests/test_transaction.py::TestSanitizeTxData::test_no_combine_remaining",
"tests/test_transaction.py::TestSanitizeTxData::test_no_combine_remaining_small_inputs",
"tests/test_transaction.py::TestSanitizeTxData::test_no_combine_insufficient_funds",
"tests/test_transaction.py::TestCreateSignedTransaction::test_matching",
"tests/test_transaction.py::TestEstimateTxFee::test_accurate_compressed",
"tests/test_transaction.py::TestEstimateTxFee::test_accurate_uncompressed",
"tests/test_transaction.py::TestEstimateTxFee::test_none",
"tests/test_transaction.py::TestConstructOutputBlock::test_no_message",
"tests/test_transaction.py::TestConstructOutputBlock::test_message",
"tests/test_transaction.py::TestConstructOutputBlock::test_long_message",
"tests/test_transaction.py::test_construct_input_block",
"tests/test_transaction.py::test_calc_txid"
] | 2018-03-11 19:22:19+00:00 | 4,338 |
|
ofek__bit-72 | diff --git a/bit/transaction.py b/bit/transaction.py
index 6d7c00b..95d0f71 100644
--- a/bit/transaction.py
+++ b/bit/transaction.py
@@ -621,13 +621,19 @@ def sign_tx(private_key, tx, *, unspents):
# Make input parameters for preimage calculation
inputs_parameters = []
+
+ # The TxObj in `tx` will below be modified to contain the scriptCodes used
+ # for the transaction structure to be signed
+
+ # `input_script_field` copies the scriptSigs for partially signed
+ # transactions to later extract signatures from it:
+ input_script_field = [tx.TxIn[i].script_sig for i in range(len(tx.TxIn))]
+
for i in sign_inputs:
# Create transaction object for preimage calculation
tx_input = tx.TxIn[i].txid + tx.TxIn[i].txindex
segwit_input = input_dict[tx_input]['segwit']
tx.TxIn[i].segwit_input = segwit_input
- # For partially signed transaction we must extract the signatures:
- input_script_field = tx.TxIn[i].script_sig
script_code = private_key.scriptcode
script_code_len = int_to_varint(len(script_code))
@@ -640,9 +646,10 @@ def sign_tx(private_key, tx, *, unspents):
try:
tx.TxIn[i].script_sig += input_dict[tx_input]['amount']\
.to_bytes(8, byteorder='little')
- # For partially signed transaction we must extract the
- # signatures:
- input_script_field = tx.TxIn[i].witness
+
+ # For partially signed Segwit transactions the signatures must
+ # be extracted from the witnessScript field:
+ input_script_field[i] = tx.TxIn[i].witness
except AttributeError:
raise ValueError(
'Cannot sign a segwit input when the input\'s amount is '
@@ -666,8 +673,8 @@ def sign_tx(private_key, tx, *, unspents):
sigs = {}
# Initial number of witness items (OP_0 + one signature + redeemscript).
witness_count = 3
- if input_script_field:
- sig_list = get_signatures_from_script(input_script_field)
+ if input_script_field[i]:
+ sig_list = get_signatures_from_script(input_script_field[i])
# Bitcoin Core convention: Every missing signature is denoted
# by 0x00. Only used for already partially-signed scriptSigs:
script_blob += b'\x00' * (private_key.m - len(sig_list)-1)
| ofek/bit | 20fc0e7047946c1f28f868008d99d659905c1af6 | diff --git a/tests/test_transaction.py b/tests/test_transaction.py
index 3548271..1410abf 100644
--- a/tests/test_transaction.py
+++ b/tests/test_transaction.py
@@ -99,6 +99,42 @@ FINAL_TX_BATCH = ('010000000001024623e78d68e72b428eb4f53f73086ad824a2c2b6be90'
'2cba96d3499410bbd90121021816325d19fd34fd87a039e83e35fc9de3'
'c9de64a501a6684b9bf9946364fbb700000000')
+FINAL_TX_MULTISIG_MANY = (
+ '010000000001040100000000000000000000000000000000000000000000000000000000'
+ '0000000000000023220020d3a4db6921782f78eb4f158f73adde471629dd5aca41c14a5b'
+ 'fc2ec2a8f39202ffffffff02000000000000000000000000000000000000000000000000'
+ '0000000000000001000000db00483045022100a9efd4418fc75749407ab9369c21a52f9e'
+ '105f0dac25e8e7020f16fd0738185f0220421930e517fe2cd015a9f1e0c884f07ca0b80f'
+ '0153cf413dfd926abfeb5bf81201483045022100afc30dd8dc8fc7d006458034bbd3f425'
+ '4cd5783d56ef6568fb21d074f44fa3ad02200e7b1207113c59525eb7376a7bc5fea42405'
+ '1152687e406fd90a435467f8b8db01475221021816325d19fd34fd87a039e83e35fc9de3'
+ 'c9de64a501a6684b9bf9946364fbb721037d696886864509ed63044d8f1bcd53b8def124'
+ '7bd2bbe056ff81b23e8c09280f52aeffffffff0300000000000000000000000000000000'
+ '0000000000000000000000000000000200000023220020d3a4db6921782f78eb4f158f73'
+ 'adde471629dd5aca41c14a5bfc2ec2a8f39202ffffffff04000000000000000000000000'
+ '0000000000000000000000000000000000000003000000db00483045022100a324e5256d'
+ 'c2621e4b185112ea80d95d170b6cd13dcf7a096e5a82cd85e94bad02200e9859d4b7af52'
+ '0eaab1bbcee6d25ad1e2dee1c9f428794a40fa8bcff82395c601483045022100ea77d456'
+ '5fd49b113df45507ebb2f1ee101d65798ecbf9a98f99212cb05d776a02207bc44b0e1f62'
+ '6c9072a6524f1459f9bc9965f75b863c705c8f6a07646ae4e9d901475221021816325d19'
+ 'fd34fd87a039e83e35fc9de3c9de64a501a6684b9bf9946364fbb721037d696886864509'
+ 'ed63044d8f1bcd53b8def1247bd2bbe056ff81b23e8c09280f52aeffffffff0200286bee'
+ '000000001600140ee268c86d05f290add1bfc9bdfc3992d785bce2505c9a3b0000000017'
+ 'a914d35515db546bb040e61651150343a218c87b471e8704004730440220279267d5c34f'
+ 'f4acb9b99cf5d28b1498be2c72dee87c0f331078ef906b9163bd02203b10bda36d7182a4'
+ '0c3d42df74484d5e1c32fa24b0ed708f8951e82a642c569d01483045022100c452fc9665'
+ '9792ac1f36846657b54c1b1dc319ef0018db53d4b9d96e2c7dbdd602203740cc070738d6'
+ '1e458be5cb330c0d221478b3564dfa3f5a7ecb82e384a2fa0601475221021816325d19fd'
+ '34fd87a039e83e35fc9de3c9de64a501a6684b9bf9946364fbb721037d696886864509ed'
+ '63044d8f1bcd53b8def1247bd2bbe056ff81b23e8c09280f52ae000400473044022015f6'
+ '687440590aec9e5f7bf2d2f69701474dd8d3df22cc314b8b557e4cd457fb02200e0f6ec2'
+ '4a125fa70fac34feb5244add0cb89b317b8da807b68cec62003d02ab0148304502210090'
+ '28061143f911ab7dbcfcd8851e253a14a58dd6320296be5cafcbd5f1f8af44022043b1f9'
+ '1ec311f2e351ad783a2bf9591754576a3a733917e0ce2b2a6c1e0f94c001475221021816'
+ '325d19fd34fd87a039e83e35fc9de3c9de64a501a6684b9bf9946364fbb721037d696886'
+ '864509ed63044d8f1bcd53b8def1247bd2bbe056ff81b23e8c09280f52ae0000000000'
+)
+
INPUTS = [
TxIn(
(b"G0D\x02 E\xb7C\xdb\xaa\xaa,\xd1\xef\x0b\x914oVD\xe3-\xc7\x0c\xde\x05\t"
@@ -153,6 +189,32 @@ UNSPENTS_BATCH = [
1,
'np2wkh')
]
+UNSPENTS_MULTISIG_MANY = [
+ Unspent(2000000000,
+ 1,
+ 'a914d35515db546bb040e61651150343a218c87b471e87',
+ '0000000000000000000000000000000000000000000000000000000000000001',
+ 0,
+ 'np2wsh'),
+ Unspent(2000000000,
+ 1,
+ 'a914f132346e75e3a317f3090a07560fe75d74e1f51087',
+ '0000000000000000000000000000000000000000000000000000000000000002',
+ 1,
+ 'p2sh'),
+ Unspent(2000000000,
+ 1,
+ 'a914d35515db546bb040e61651150343a218c87b471e87',
+ '0000000000000000000000000000000000000000000000000000000000000003',
+ 2,
+ 'np2wsh'),
+ Unspent(2000000000,
+ 1,
+ 'a914f132346e75e3a317f3090a07560fe75d74e1f51087',
+ '0000000000000000000000000000000000000000000000000000000000000004',
+ 3,
+ 'p2sh'),
+]
OUTPUTS = [
('n2eMqTT929pb1RDNuqEnxdaLau1rxy3efi', 50000),
('mtrNwJxS1VyHYn3qBY1Qfsm3K3kh1mGRMS', 83658760)
@@ -499,6 +561,21 @@ class TestCreateSignedTransaction:
tx2 = multi1.sign_transaction(tx1, unspents=UNSPENTS_BATCH[::-1])
assert tx2 == FINAL_TX_BATCH
+ def test_multisig_tx_many_inputs(self):
+ key1 = PrivateKeyTestnet(WALLET_FORMAT_TEST_1)
+ key2 = PrivateKeyTestnet(WALLET_FORMAT_TEST_2)
+ p = [key1.public_key.hex(), key2.public_key.hex()]
+ multi1 = MultiSigTestnet(key1, p, 2)
+ multi2 = MultiSigTestnet(key2, p, 2)
+ tx0 = create_new_transaction(
+ multi1,
+ UNSPENTS_MULTISIG_MANY,
+ [("bcrt1qpm3x3jrdqhefptw3hlymmlpejttct08zgzzd2t", 4000000000),
+ ("2NCWeVbWmaUp92dSFP3RddPk6r3GTd6cDd6", 999971920)]
+ )
+ tx1 = multi2.sign_transaction(tx0, unspents=UNSPENTS_MULTISIG_MANY)
+ assert tx1 == FINAL_TX_MULTISIG_MANY
+
class TestDeserializeTransaction:
def test_legacy_deserialize(self):
| Multisig error
What's wrong with that? The code below gives out an error `Traceback (most recent call last):
File "/home/tony/Documents/DLF/Dev/1.py", line 15, in <module>
NetworkAPI.broadcast_tx_testnet(tx_2)
File "/home/tony/.local/lib/python3.7/site-packages/bit/network/services.py", line 533, in broadcast_tx_testnet
raise ConnectionError('Transaction broadcast failed, or '
ConnectionError: Transaction broadcast failed, or Unspents were already used`
Balance = 0.04 BTC
```
from bit import MultiSigTestnet, PrivateKeyTestnet, wif_to_key
from bit.network import NetworkAPI
key1 = wif_to_key(WIF1)
key2 = wif_to_key(WIF2)
multisig1 = MultiSigTestnet(key1, {key1.public_key, key2.public_key}, 2)
multisig2 = MultiSigTestnet(key2, {key1.public_key, key2.public_key}, 2)
tx_1 = multisig1.create_transaction([('2Mxpa7jzh37ZuXKVxqnS5RLD7XCdGFrDFy1', 100000, 'satoshi')], fee=30)
tx_2 = multisig2.sign_transaction(tx_1)
print(tx_1, tx_2)
NetworkAPI.broadcast_tx_testnet(tx_2)
| 0.0 | [
"tests/test_transaction.py::TestCreateSignedTransaction::test_multisig_tx_many_inputs"
] | [
"tests/test_transaction.py::TestTxIn::test_init",
"tests/test_transaction.py::TestTxIn::test_init_segwit",
"tests/test_transaction.py::TestTxIn::test_equality",
"tests/test_transaction.py::TestTxIn::test_repr",
"tests/test_transaction.py::TestTxIn::test_repr_segwit",
"tests/test_transaction.py::TestTxIn::test_bytes_repr",
"tests/test_transaction.py::TestTxOut::test_init",
"tests/test_transaction.py::TestTxOut::test_equality",
"tests/test_transaction.py::TestTxOut::test_repr",
"tests/test_transaction.py::TestTxOut::test_bytes_repr",
"tests/test_transaction.py::TestTxObj::test_init",
"tests/test_transaction.py::TestTxObj::test_init_segwit",
"tests/test_transaction.py::TestTxObj::test_equality",
"tests/test_transaction.py::TestTxObj::test_repr",
"tests/test_transaction.py::TestTxObj::test_bytes_repr",
"tests/test_transaction.py::TestTxObj::test_bytes_repr_segwit",
"tests/test_transaction.py::TestTxObj::test_is_segwit",
"tests/test_transaction.py::TestSanitizeTxData::test_no_input",
"tests/test_transaction.py::TestSanitizeTxData::test_message",
"tests/test_transaction.py::TestSanitizeTxData::test_fee_applied",
"tests/test_transaction.py::TestSanitizeTxData::test_zero_remaining",
"tests/test_transaction.py::TestSanitizeTxData::test_combine_remaining",
"tests/test_transaction.py::TestSanitizeTxData::test_combine_insufficient_funds",
"tests/test_transaction.py::TestSanitizeTxData::test_no_combine_remaining",
"tests/test_transaction.py::TestSanitizeTxData::test_no_combine_with_fee",
"tests/test_transaction.py::TestSanitizeTxData::test_no_combine_insufficient_funds",
"tests/test_transaction.py::TestSanitizeTxData::test_no_combine_mainnet_with_testnet",
"tests/test_transaction.py::TestCreateSignedTransaction::test_matching",
"tests/test_transaction.py::TestCreateSignedTransaction::test_segwit_transaction",
"tests/test_transaction.py::TestCreateSignedTransaction::test_batch_and_multisig_tx",
"tests/test_transaction.py::TestDeserializeTransaction::test_legacy_deserialize",
"tests/test_transaction.py::TestDeserializeTransaction::test_segwit_deserialize",
"tests/test_transaction.py::TestGetSignaturesFromScript::test_get_signatures_1",
"tests/test_transaction.py::TestGetSignaturesFromScript::test_get_signatures_2",
"tests/test_transaction.py::TestAddressToScriptPubKey::test_address_to_scriptpubkey_legacy",
"tests/test_transaction.py::TestAddressToScriptPubKey::test_address_to_scriptpubkey_legacy_p2sh",
"tests/test_transaction.py::TestAddressToScriptPubKey::test_address_to_scriptpubkey_bech32",
"tests/test_transaction.py::TestAddressToScriptPubKey::test_address_to_scriptpubkey_bech32_p2sh",
"tests/test_transaction.py::TestAddressToScriptPubKey::test_address_to_scriptpubkey_legacy_test",
"tests/test_transaction.py::TestAddressToScriptPubKey::test_address_to_scriptpubkey_legacy_p2sh_test",
"tests/test_transaction.py::TestAddressToScriptPubKey::test_address_to_scriptpubkey_bech32_test",
"tests/test_transaction.py::TestAddressToScriptPubKey::test_address_to_scriptpubkey_bech32_p2sh_test",
"tests/test_transaction.py::TestAddressToScriptPubKey::test_address_to_scriptpubkey_invalid_checksum",
"tests/test_transaction.py::TestAddressToScriptPubKey::test_address_to_scriptpubkey_invalid_address",
"tests/test_transaction.py::TestCalculatePreimages::test_calculate_preimages",
"tests/test_transaction.py::TestCalculatePreimages::test_calculate_preimages_unsupported_hashtypes",
"tests/test_transaction.py::TestSignTx::test_sign_tx_legacy_input",
"tests/test_transaction.py::TestSignTx::test_sign_tx_segwit",
"tests/test_transaction.py::TestSignTx::test_sign_tx_multisig",
"tests/test_transaction.py::TestSignTx::test_sign_tx_invalid_unspents",
"tests/test_transaction.py::TestSignTx::test_sign_tx_invalid_segwit_no_amount",
"tests/test_transaction.py::TestSignTx::test_sign_tx_invalid_multisig_already_fully_signed",
"tests/test_transaction.py::TestEstimateTxFee::test_accurate_compressed",
"tests/test_transaction.py::TestEstimateTxFee::test_accurate_uncompressed",
"tests/test_transaction.py::TestEstimateTxFee::test_none",
"tests/test_transaction.py::TestSelectCoins::test_perfect_match",
"tests/test_transaction.py::TestSelectCoins::test_perfect_match_with_range",
"tests/test_transaction.py::TestSelectCoins::test_random_draw",
"tests/test_transaction.py::TestConstructOutputBlock::test_no_message",
"tests/test_transaction.py::TestConstructOutputBlock::test_message",
"tests/test_transaction.py::TestConstructOutputBlock::test_long_message",
"tests/test_transaction.py::TestConstructOutputBlock::test_outputs_pay2sh",
"tests/test_transaction.py::TestConstructOutputBlock::test_outputs_pay2sh_testnet",
"tests/test_transaction.py::TestConstructOutputBlock::test_outputs_pay2segwit",
"tests/test_transaction.py::TestConstructOutputBlock::test_outputs_pay2segwit_testnet",
"tests/test_transaction.py::TestCalcTxId::test_calc_txid_legacy",
"tests/test_transaction.py::TestCalcTxId::test_calc_txid_segwit"
] | 2019-05-16 11:15:13+00:00 | 4,339 |
|
ofek__hatch-vcs-17 | diff --git a/hatch_vcs/version_source.py b/hatch_vcs/version_source.py
index cc78d37..71d1e37 100644
--- a/hatch_vcs/version_source.py
+++ b/hatch_vcs/version_source.py
@@ -47,13 +47,11 @@ class VCSVersionSource(VersionSourceInterface):
return self.__config_raw_options
- def get_version_data(self):
+ def construct_setuptools_scm_config(self):
from copy import deepcopy
- from setuptools_scm import get_version
-
config = deepcopy(self.config_raw_options)
- config['root'] = self.root
+ config.setdefault('root', self.root)
config.setdefault('tag_regex', self.config_tag_pattern)
@@ -64,6 +62,10 @@ class VCSVersionSource(VersionSourceInterface):
# Writing only occurs when the build hook is enabled
config.pop('write_to', None)
config.pop('write_to_template', None)
+ return config
+
+ def get_version_data(self):
+ from setuptools_scm import get_version
- version = get_version(**config)
+ version = get_version(**self.construct_setuptools_scm_config())
return {'version': version}
| ofek/hatch-vcs | 753f5091c4387b05230e2d2037652351c54f1c45 | diff --git a/tests/conftest.py b/tests/conftest.py
index 60ad2ba..14898cd 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -33,13 +33,17 @@ def temp_dir():
@contextmanager
-def create_project(directory, metadata, setup_vcs=True): # noqa: FBT002
- project_dir = os.path.join(directory, 'my-app')
- os.mkdir(project_dir)
+def create_project(directory, metadata, setup_vcs=True, nested=False): # noqa: FBT002
+ root_dir = project_dir = os.path.join(directory, 'my-app')
+ os.mkdir(root_dir)
- gitignore_file = os.path.join(project_dir, '.gitignore')
+ gitignore_file = os.path.join(root_dir, '.gitignore')
write_file(gitignore_file, '/my_app/version.py')
+ if nested:
+ project_dir = os.path.join(root_dir, 'project')
+ os.mkdir(project_dir)
+
project_file = os.path.join(project_dir, 'pyproject.toml')
write_file(project_file, metadata)
@@ -55,6 +59,9 @@ def create_project(directory, metadata, setup_vcs=True): # noqa: FBT002
os.chdir(project_dir)
try:
if setup_vcs:
+ if nested:
+ os.chdir(root_dir)
+
git('init')
git('config', '--local', 'user.name', 'foo')
git('config', '--local', 'user.email', '[email protected]')
@@ -62,6 +69,9 @@ def create_project(directory, metadata, setup_vcs=True): # noqa: FBT002
git('commit', '-m', 'test')
git('tag', '1.2.3')
+ if nested:
+ os.chdir(project_dir)
+
yield project_dir
finally:
os.chdir(origin)
@@ -130,3 +140,25 @@ fallback-version = "7.8.9"
setup_vcs=False,
) as project:
yield project
+
+
[email protected]
+def new_project_root_elsewhere(temp_dir):
+ with create_project(
+ temp_dir,
+ """\
+[build-system]
+requires = ["hatchling", "hatch-vcs"]
+build-backend = "hatchling.build"
+
+[project]
+name = "my-app"
+dynamic = ["version"]
+
+[tool.hatch.version]
+source = "vcs"
+raw-options = { root = ".." }
+""",
+ nested=True,
+ ) as project:
+ yield project
diff --git a/tests/test_build.py b/tests/test_build.py
index 6b907ef..a3fdcb6 100644
--- a/tests/test_build.py
+++ b/tests/test_build.py
@@ -109,3 +109,34 @@ def test_fallback(new_project_fallback):
assert os.path.isfile(os.path.join(package_directory, 'foo.py'))
assert os.path.isfile(os.path.join(package_directory, 'bar.py'))
assert os.path.isfile(os.path.join(package_directory, 'baz.py'))
+
+
+def test_root(new_project_root_elsewhere):
+ build_project('-t', 'wheel')
+
+ build_dir = os.path.join(new_project_root_elsewhere, 'dist')
+ assert os.path.isdir(build_dir)
+
+ artifacts = os.listdir(build_dir)
+ assert len(artifacts) == 1
+ wheel_file = artifacts[0]
+
+ assert wheel_file == 'my_app-1.2.3-py2.py3-none-any.whl'
+
+ extraction_directory = os.path.join(os.path.dirname(new_project_root_elsewhere), '_archive')
+ os.mkdir(extraction_directory)
+
+ with zipfile.ZipFile(os.path.join(build_dir, wheel_file), 'r') as zip_archive:
+ zip_archive.extractall(extraction_directory)
+
+ metadata_directory = os.path.join(extraction_directory, 'my_app-1.2.3.dist-info')
+ assert os.path.isdir(metadata_directory)
+
+ package_directory = os.path.join(extraction_directory, 'my_app')
+ assert os.path.isdir(package_directory)
+ assert len(os.listdir(package_directory)) == 4
+
+ assert os.path.isfile(os.path.join(package_directory, '__init__.py'))
+ assert os.path.isfile(os.path.join(package_directory, 'foo.py'))
+ assert os.path.isfile(os.path.join(package_directory, 'bar.py'))
+ assert os.path.isfile(os.path.join(package_directory, 'baz.py'))
| setuptools-scm "root" parameter is ignored in raw-options
Consider this config in the pyproject.toml:
```toml
[tool.hatch.version]
raw-options = { root = ".." }
source = "vcs"
```
and such source tree:
```
.
├── .git
├── package1
| ...
│ └── pyproject.toml
├── package2
| ...
│ └── pyproject.toml
...
└── README.md
```
If I try to build a package with dynamic versioning then it will fail because it `setuptools-scm` is not able to find `.git` directory
```
LookupError: Error getting the version from source `vcs`: setuptools-scm was unable to detect version for /some/path/package1.
Make sure you're either building from a fully intact git repository or PyPI tarballs. Most other sources (such as GitHub's tarballs, a git checkout without the .git folder) don't contain the necessary metadata and will not work.
```
It happens due to this line https://github.com/ofek/hatch-vcs/blob/388c947133061a2056de9fe2f1102685a648f248/hatch_vcs/version_source.py#L56. I'm not sure what 's the intention of this but this prevents to work with projects where `pyproject.toml` is not located in the same directory with `.git`. | 0.0 | [
"tests/test_build.py::test_root"
] | [
"tests/test_build.py::test_basic",
"tests/test_build.py::test_fallback"
] | 2022-12-03 10:13:31+00:00 | 4,340 |
|
ofek__pypinfo-107 | diff --git a/pypinfo/core.py b/pypinfo/core.py
index d4de0cb..1075ea9 100644
--- a/pypinfo/core.py
+++ b/pypinfo/core.py
@@ -9,15 +9,8 @@ from google.cloud.bigquery.job import QueryJobConfig
from pypinfo.fields import AGGREGATES, Downloads
-FROM = """\
-FROM
- TABLE_DATE_RANGE(
- [the-psf:pypi.downloads],
- {},
- {}
- )
-"""
-DATE_ADD = 'DATE_ADD(CURRENT_TIMESTAMP(), {}, "day")'
+FROM = 'FROM `the-psf.pypi.file_downloads`'
+DATE_ADD = 'DATE_ADD(CURRENT_TIMESTAMP(), INTERVAL {} DAY)'
START_TIMESTAMP = 'TIMESTAMP("{} 00:00:00")'
END_TIMESTAMP = 'TIMESTAMP("{} 23:59:59")'
START_DATE = '-31'
@@ -27,7 +20,7 @@ DEFAULT_LIMIT = '10'
def create_config():
config = QueryJobConfig()
- config.use_legacy_sql = True
+ config.use_legacy_sql = False
return config
@@ -136,10 +129,11 @@ def build_query(
for field in fields:
query += f' {field.data} as {field.name},\n'
- query += FROM.format(start_date, end_date)
+ query += FROM
+ query += f'\nWHERE timestamp BETWEEN {start_date} AND {end_date}\n'
if where:
- query += f'WHERE\n {where}\n'
+ query += f' AND {where}\n'
else:
conditions = []
if project:
@@ -147,15 +141,20 @@ def build_query(
if pip:
conditions.append('details.installer.name = "pip"\n')
if conditions:
- query += 'WHERE\n ' + ' AND '.join(conditions)
+ query += ' AND '
+ query += ' AND '.join(conditions)
if len(fields) > 1:
gb = 'GROUP BY\n'
initial_length = len(gb)
+ non_aggregate_fields = []
for field in fields[:-1]:
if field not in AGGREGATES:
- gb += f' {field.name},\n'
+ non_aggregate_fields.append(field.name)
+ gb += ' '
+ gb += ', '.join(non_aggregate_fields)
+ gb += '\n'
if len(gb) > initial_length:
query += gb
diff --git a/pypinfo/fields.py b/pypinfo/fields.py
index 0e949fe..f779bd7 100644
--- a/pypinfo/fields.py
+++ b/pypinfo/fields.py
@@ -2,9 +2,9 @@ from collections import namedtuple
Field = namedtuple('Field', ('name', 'data'))
Downloads = Field('download_count', 'COUNT(*)')
-Date = Field('download_date', 'STRFTIME_UTC_USEC(timestamp, "%Y-%m-%d")')
-Month = Field('download_month', 'STRFTIME_UTC_USEC(timestamp, "%Y-%m")')
-Year = Field('download_year', 'STRFTIME_UTC_USEC(timestamp, "%Y")')
+Date = Field('download_date', 'FORMAT_TIMESTAMP("%Y-%m-%d", timestamp)')
+Month = Field('download_month', 'FORMAT_TIMESTAMP("%Y-%m", timestamp)')
+Year = Field('download_year', 'FORMAT_TIMESTAMP("%Y", timestamp)')
Country = Field('country', 'country_code')
Project = Field('project', 'file.project')
Version = Field('version', 'file.version')
| ofek/pypinfo | a5ce3683b82a551db42686f8512501df8f78642b | diff --git a/tests/test_core.py b/tests/test_core.py
index 6e1e28c..6965e5d 100644
--- a/tests/test_core.py
+++ b/tests/test_core.py
@@ -24,7 +24,7 @@ def test_create_config():
config = core.create_config()
# Assert
- assert config.use_legacy_sql
+ assert not config.use_legacy_sql
@pytest.mark.parametrize(
@@ -88,7 +88,7 @@ def test_format_date_negative_number():
date = core.format_date("-1", dummy_format)
# Assert
- assert date == 'DATE_ADD(CURRENT_TIMESTAMP(), -1, "day")'
+ assert date == 'DATE_ADD(CURRENT_TIMESTAMP(), INTERVAL -1 DAY)'
def test_format_date_yyy_mm_dd():
@@ -137,17 +137,12 @@ def test_build_query():
SELECT
REGEXP_EXTRACT(details.python, r"^([^\.]+\.[^\.]+)") as python_version,
COUNT(*) as download_count,
-FROM
- TABLE_DATE_RANGE(
- [the-psf:pypi.downloads],
- TIMESTAMP("2017-10-01 00:00:00"),
- TIMESTAMP("2017-10-31 23:59:59")
- )
-WHERE
- file.project = "pycodestyle"
+FROM `the-psf.pypi.file_downloads`
+WHERE timestamp BETWEEN TIMESTAMP("2017-10-01 00:00:00") AND TIMESTAMP("2017-10-31 23:59:59")
+ AND file.project = "pycodestyle"
AND details.installer.name = "pip"
GROUP BY
- python_version,
+ python_version
ORDER BY
download_count DESC
LIMIT 100
| Use clustered BigQuery tables for 95% improvements in querying costs
I create daily new tables that heavily improve the costs of going to BigQuery. `pypinfo` could use them:
- https://towardsdatascience.com/python-pypi-stats-in-bigquery-reclustered-d80e583e1bfe
(goes from 200GB queries to 10GB queries)
| 0.0 | [
"tests/test_core.py::test_format_date_negative_number",
"tests/test_core.py::test_create_config",
"tests/test_core.py::test_build_query"
] | [
"tests/test_core.py::test_validate_date_valid[2018-05-15]",
"tests/test_core.py::test_tabulate_markdown",
"tests/test_core.py::test_month_negative_integer",
"tests/test_core.py::test_validate_date_invalid[2018-19-39]",
"tests/test_core.py::test_validate_date_invalid[something",
"tests/test_core.py::test_tabulate_default",
"tests/test_core.py::test_normalize[Pillow-pillow]",
"tests/test_core.py::test_normalize[setuptools_scm-setuptools-scm]",
"tests/test_core.py::test_format_date_yyy_mm_dd",
"tests/test_core.py::test_normalize_dates_yyy_mm_dd_and_negative_integer",
"tests/test_core.py::test_validate_date_invalid[1]",
"tests/test_core.py::test_add_percentages",
"tests/test_core.py::test_normalize_dates_yyy_mm",
"tests/test_core.py::test_format_json",
"tests/test_core.py::test_normalize[pypinfo-pypinfo]",
"tests/test_core.py::test_validate_date_valid[-1]",
"tests/test_core.py::test_month_yyyy_mm",
"tests/test_core.py::test_add_download_total",
"tests/test_core.py::test_month_yyyy_mm_dd"
] | 2021-01-12 21:51:07+00:00 | 4,341 |
|
ofek__pypinfo-109 | diff --git a/pypinfo/core.py b/pypinfo/core.py
index 1075ea9..41bbd8c 100644
--- a/pypinfo/core.py
+++ b/pypinfo/core.py
@@ -10,7 +10,7 @@ from google.cloud.bigquery.job import QueryJobConfig
from pypinfo.fields import AGGREGATES, Downloads
FROM = 'FROM `the-psf.pypi.file_downloads`'
-DATE_ADD = 'DATE_ADD(CURRENT_TIMESTAMP(), INTERVAL {} DAY)'
+DATE_ADD = 'TIMESTAMP_ADD(CURRENT_TIMESTAMP(), INTERVAL {} DAY)'
START_TIMESTAMP = 'TIMESTAMP("{} 00:00:00")'
END_TIMESTAMP = 'TIMESTAMP("{} 23:59:59")'
START_DATE = '-31'
| ofek/pypinfo | 0007c10256804650b4787a14a32e38e8f9347bbc | diff --git a/tests/test_core.py b/tests/test_core.py
index 6965e5d..e873e91 100644
--- a/tests/test_core.py
+++ b/tests/test_core.py
@@ -88,7 +88,7 @@ def test_format_date_negative_number():
date = core.format_date("-1", dummy_format)
# Assert
- assert date == 'DATE_ADD(CURRENT_TIMESTAMP(), INTERVAL -1 DAY)'
+ assert date == 'TIMESTAMP_ADD(CURRENT_TIMESTAMP(), INTERVAL -1 DAY)'
def test_format_date_yyy_mm_dd():
| No matching signature for function DATE_ADD for argument types: TIMESTAMP, INTERVAL INT64 DATE_TIME_PART
Hi,
After installation following instructions given in the `README.md`, I tried a simplest call:
```bash
pypinfo requests
```
Unfortunately getting following exception:
```
...
File "/Users/christianr/.venv/sett/lib/python3.9/site-packages/pypinfo/cli.py", line 166, in pypinfo
query_rows = query_job.result(timeout=timeout // 1000)
File "/Users/christianr/.venv/sett/lib/python3.9/site-packages/google/cloud/bigquery/job/query.py", line 1160, in result
super(QueryJob, self).result(retry=retry, timeout=timeout)
File "/Users/christianr/.venv/sett/lib/python3.9/site-packages/google/cloud/bigquery/job/base.py", line 631, in result
return super(_AsyncJob, self).result(timeout=timeout, **kwargs)
File "/Users/christianr/.venv/sett/lib/python3.9/site-packages/google/api_core/future/polling.py", line 134, in result
raise self._exception
google.api_core.exceptions.BadRequest: 400 No matching signature for function DATE_ADD for argument types: TIMESTAMP, INTERVAL INT64 DATE_TIME_PART. Supported signature: DATE_ADD(DATE, INTERVAL INT64 DATE_TIME_PART) at [5:25]
(job ID: 947e6084-e5e6-4bb5-ae12-bb8faad8ec0b)
-----Query Job SQL Follows-----
| . | . | . | . | . | . | . | . | . | . | . | . |
1:SELECT
2: FORMAT_TIMESTAMP("%Y", timestamp) as download_year,
3: COUNT(*) as download_count,
4:FROM `the-psf.pypi.file_downloads`
5:WHERE timestamp BETWEEN DATE_ADD(CURRENT_TIMESTAMP(), INTERVAL -1826 DAY) AND DATE_ADD(CURRENT_TIMESTAMP(), INTERVAL -1 DAY)
6: AND file.project = "blist"
7: AND details.installer.name = "pip"
8:GROUP BY
9: download_year
10:ORDER BY
11: download_count DESC
12:LIMIT 10
| . | . | . | . | . | . | . | . | . | . | . | . |
```
Using the SQL query in the **BigQuery** SQL workspace pops up the same error message if I use the _public PyPI download statistics dataset_.
My environment:
```
pypinfo, version 18.0.0
Python 3.9.1
``` | 0.0 | [
"tests/test_core.py::test_format_date_negative_number"
] | [
"tests/test_core.py::test_tabulate_markdown",
"tests/test_core.py::test_normalize[Pillow-pillow]",
"tests/test_core.py::test_normalize[setuptools_scm-setuptools-scm]",
"tests/test_core.py::test_validate_date_valid[2018-05-15]",
"tests/test_core.py::test_build_query",
"tests/test_core.py::test_normalize_dates_yyy_mm_dd_and_negative_integer",
"tests/test_core.py::test_create_config",
"tests/test_core.py::test_month_yyyy_mm_dd",
"tests/test_core.py::test_month_negative_integer",
"tests/test_core.py::test_normalize_dates_yyy_mm",
"tests/test_core.py::test_add_download_total",
"tests/test_core.py::test_validate_date_valid[-1]",
"tests/test_core.py::test_validate_date_invalid[2018-19-39]",
"tests/test_core.py::test_month_yyyy_mm",
"tests/test_core.py::test_normalize[pypinfo-pypinfo]",
"tests/test_core.py::test_validate_date_invalid[something",
"tests/test_core.py::test_validate_date_invalid[1]",
"tests/test_core.py::test_add_percentages",
"tests/test_core.py::test_format_json",
"tests/test_core.py::test_format_date_yyy_mm_dd",
"tests/test_core.py::test_tabulate_default"
] | 2021-01-25 19:16:06+00:00 | 4,342 |
|
ogawa-ros__necstdb-27 | diff --git a/necstdb/necstdb.py b/necstdb/necstdb.py
index 05c1bb3..9715f1e 100644
--- a/necstdb/necstdb.py
+++ b/necstdb/necstdb.py
@@ -7,20 +7,20 @@ timestamp), various kinds of weather data (temperature + humidity + wind speed +
direction + ... + timestamp), etc.
"""
-
-from typing import Union, List, Tuple, Dict, Any
-import re
-import os
+import json
import mmap
-import struct
+import os
import pathlib
-import json
+import re
+import struct
import tarfile
+from typing import Any, Dict, List, Tuple, Union
import numpy
import pandas
from . import utils
+from .recover import recover
def duplicate_rename(path: pathlib.Path, _i: int = 0) -> pathlib.Path:
@@ -423,9 +423,12 @@ class table:
for col in cols:
size = struct.calcsize(col["format"])
+ if "x" in col["format"]: # Pad field
+ offset += col["size"]
+ continue
dat = struct.unpack(col["format"], data[offset : offset + size])
if len(dat) == 1:
- dat = dat[0]
+ (dat,) = dat
dict_[col["key"]] = dat
offset += col["size"]
@@ -448,18 +451,28 @@ class table:
formats = [col["format"] for col in cols]
def parse_dtype(format_character: str) -> str:
+ def str_format(length: Union[str, int], count: Union[str, int]):
+ count = count if int(count) > 1 else ""
+ return f"{count}S{length}"
+
format_character = re.sub(
r"^([\d+s]+)$",
- lambda m: f"{m.group(1).count('s')}S{m.group(1).split('s')[0]}",
+ lambda m: str_format(m.group(1).split("s")[0], m.group(1).count("s")),
format_character,
)
+
+ format_character = format_character.replace("x", "V")
return self.endian + format_character
np_formats = [parse_dtype(col["format"]) for col in cols]
keys = [col["key"] for col in cols]
offsets = utils.get_struct_indices(formats, self.endian)[:-1]
+
+ pad = ["x" in col["format"] for col in cols]
+ data_field = [k for k, p in zip(keys, pad) if not p]
+
dtype = numpy.dtype({"names": keys, "formats": np_formats, "offsets": offsets})
- return numpy.frombuffer(data, dtype=dtype)
+ return numpy.frombuffer(data, dtype=dtype)[data_field]
@property
def recovered(self) -> "table":
@@ -481,11 +494,7 @@ class table:
such as 1e-308)
"""
- self.endian = ""
- self.open(self._name, self._mode)
- for dat in self.header["data"]:
- dat["format"] = dat["format"].replace("i", "?")
- return self
+ return recover(self)
def opendb(path: os.PathLike, mode: str = "r") -> "necstdb":
diff --git a/necstdb/recover.py b/necstdb/recover.py
new file mode 100644
index 0000000..8cd2671
--- /dev/null
+++ b/necstdb/recover.py
@@ -0,0 +1,52 @@
+from typing import TYPE_CHECKING
+
+import numpy
+
+if TYPE_CHECKING:
+ from .necstdb import table
+
+
+def recover(t: "table") -> "table":
+ fmt = "".join([d["format"] for d in t.header["data"]])
+
+ if (t.endian == "<") and ("i" in fmt):
+ t.endian = ""
+ t.open(t._name, t._mode)
+ for dat in t.header["data"]:
+ dat["format"] = dat["format"].replace("i", "?")
+
+ if "s" in fmt:
+ modified_header_data = []
+ for dat in t.header["data"]:
+ if "s" not in dat["format"]:
+ modified_header_data.append(dat)
+ else:
+ dat_numpy = t.read(astype="sa")
+ this_field = dat_numpy[dat["key"]]
+ lengths = numpy.unique([len(d) for d in this_field])
+ if len(lengths) > 1: # Not uniform length
+ modified_header_data.append(dat)
+ else:
+ (length,) = lengths
+ specified = int(dat["format"].rstrip("s"))
+ if length == specified:
+ modified_header_data.append(dat)
+ else:
+ diff = specified - length
+ modified_header_data.append(
+ {
+ "key": dat["key"],
+ "format": f"{length}s",
+ "size": length,
+ }
+ )
+ modified_header_data.append(
+ {
+ "key": f"_{dat['key']}_pad",
+ "format": f"{diff}x",
+ "size": diff,
+ }
+ )
+ t.header["data"] = modified_header_data
+
+ return t
diff --git a/poetry.lock b/poetry.lock
index 147b715..6c0b1f9 100644
--- a/poetry.lock
+++ b/poetry.lock
@@ -23,10 +23,10 @@ optional = false
python-versions = ">=3.5"
[package.extras]
-dev = ["coverage[toml] (>=5.0.2)", "hypothesis", "pympler", "pytest (>=4.3.0)", "mypy (>=0.900,!=0.940)", "pytest-mypy-plugins", "zope-interface", "furo", "sphinx", "sphinx-notfound-page", "pre-commit", "cloudpickle"]
-docs = ["furo", "sphinx", "zope-interface", "sphinx-notfound-page"]
-tests = ["coverage[toml] (>=5.0.2)", "hypothesis", "pympler", "pytest (>=4.3.0)", "mypy (>=0.900,!=0.940)", "pytest-mypy-plugins", "zope-interface", "cloudpickle"]
-tests_no_zope = ["coverage[toml] (>=5.0.2)", "hypothesis", "pympler", "pytest (>=4.3.0)", "mypy (>=0.900,!=0.940)", "pytest-mypy-plugins", "cloudpickle"]
+dev = ["cloudpickle", "coverage[toml] (>=5.0.2)", "furo", "hypothesis", "mypy (>=0.900,!=0.940)", "pre-commit", "pympler", "pytest (>=4.3.0)", "pytest-mypy-plugins", "sphinx", "sphinx-notfound-page", "zope.interface"]
+docs = ["furo", "sphinx", "sphinx-notfound-page", "zope.interface"]
+tests = ["cloudpickle", "coverage[toml] (>=5.0.2)", "hypothesis", "mypy (>=0.900,!=0.940)", "pympler", "pytest (>=4.3.0)", "pytest-mypy-plugins", "zope.interface"]
+tests_no_zope = ["cloudpickle", "coverage[toml] (>=5.0.2)", "hypothesis", "mypy (>=0.900,!=0.940)", "pympler", "pytest (>=4.3.0)", "pytest-mypy-plugins"]
[[package]]
name = "black"
@@ -106,9 +106,9 @@ typing-extensions = {version = ">=3.6.4", markers = "python_version < \"3.8\""}
zipp = ">=0.5"
[package.extras]
-docs = ["sphinx", "jaraco.packaging (>=8.2)", "rst.linker (>=1.9)"]
+docs = ["jaraco.packaging (>=8.2)", "rst.linker (>=1.9)", "sphinx"]
perf = ["ipython"]
-testing = ["pytest (>=6)", "pytest-checkdocs (>=2.4)", "pytest-flake8", "pytest-cov", "pytest-enabler (>=1.0.1)", "packaging", "pep517", "pyfakefs", "flufl-flake8", "pytest-perf (>=0.9.2)", "pytest-black (>=0.3.7)", "pytest-mypy", "importlib-resources (>=1.3)"]
+testing = ["flufl.flake8", "importlib-resources (>=1.3)", "packaging", "pep517", "pyfakefs", "pytest (>=6)", "pytest-black (>=0.3.7)", "pytest-checkdocs (>=2.4)", "pytest-cov", "pytest-enabler (>=1.0.1)", "pytest-flake8", "pytest-mypy", "pytest-perf (>=0.9.2)"]
[[package]]
name = "iniconfig"
@@ -167,7 +167,7 @@ python-dateutil = ">=2.7.3"
pytz = ">=2017.2"
[package.extras]
-test = ["pytest (>=4.0.2)", "pytest-xdist", "hypothesis (>=3.58)"]
+test = ["hypothesis (>=3.58)", "pytest (>=4.0.2)", "pytest-xdist"]
[[package]]
name = "pathspec"
@@ -189,8 +189,8 @@ python-versions = ">=3.6"
importlib-metadata = {version = ">=0.12", markers = "python_version < \"3.8\""}
[package.extras]
-testing = ["pytest-benchmark", "pytest"]
-dev = ["tox", "pre-commit"]
+dev = ["pre-commit", "tox"]
+testing = ["pytest", "pytest-benchmark"]
[[package]]
name = "py"
@@ -317,8 +317,8 @@ optional = false
python-versions = ">=3.6"
[package.extras]
-docs = ["sphinx", "jaraco.packaging (>=8.2)", "rst.linker (>=1.9)"]
-testing = ["pytest (>=4.6)", "pytest-checkdocs (>=2.4)", "pytest-flake8", "pytest-cov", "pytest-enabler (>=1.0.1)", "jaraco-itertools", "func-timeout", "pytest-black (>=0.3.7)", "pytest-mypy"]
+docs = ["jaraco.packaging (>=8.2)", "rst.linker (>=1.9)", "sphinx"]
+testing = ["func-timeout", "jaraco.itertools", "pytest (>=4.6)", "pytest-black (>=0.3.7)", "pytest-checkdocs (>=2.4)", "pytest-cov", "pytest-enabler (>=1.0.1)", "pytest-flake8", "pytest-mypy"]
[metadata]
lock-version = "1.1"
| ogawa-ros/necstdb | fb254063d80c4f2a2c3047fe4a426e6de0ee6255 | diff --git a/tests/test_necstdb.py b/tests/test_necstdb.py
index bb5e9f6..7e70c58 100644
--- a/tests/test_necstdb.py
+++ b/tests/test_necstdb.py
@@ -53,10 +53,11 @@ DATA4_HEADER = {
{"key": "array", "format": "3d", "size": 24},
]
}
-DATA5 = ([[b"abc", b"def", b"ghi"]] for _ in range(55))
+DATA5 = ([[b"abc", b"def", b"ghi"], b"jkl"] for _ in range(55))
DATA5_HEADER = {
"data": [
{"key": "strArray", "format": "3s3s3s", "size": 9},
+ {"key": "strLenMismatch", "format": "5s", "size": 5},
]
}
@@ -66,14 +67,17 @@ EXPECTED_DATA1_TUPLE = (3, -16, -32, -64)
EXPECTED_DATA2_TUPLE = (3, 16, 32, 64)
EXPECTED_DATA3_TUPLE = (0.32, 3, b"byte", b"c")
EXPECTED_DATA4_TUPLE = (True, b"str", 3, TIME, TIME)
-EXPECTED_DATA5_TUPLE = (b"abc", b"def", b"ghi")
+EXPECTED_DATA5_TUPLE = (b"abc", b"def", b"ghi", b"jkl\x00\x00")
# DTypes (int8, int16, ...) are not preserved.
EXPECTED_DATA1_DICT = {"int8": 3, "int16": -16, "int32": -32, "int64": -64}
EXPECTED_DATA2_DICT = {"uint8": 3, "uint16": 16, "uint32": 32, "uint64": 64}
EXPECTED_DATA3_DICT = {"float32": 0.32, "float64": 3, "_byte": b"byte", "_char": b"c"}
EXPECTED_DATA4_DICT = {"bool": True, "string": b"str", "array": (3, TIME, TIME)}
-EXPECTED_DATA5_DICT = {"strArray": (b"abc", b"def", b"ghi")}
+EXPECTED_DATA5_DICT = {
+ "strArray": (b"abc", b"def", b"ghi"),
+ "strLenMismatch": b"jkl\x00\x00",
+}
# DTypes (int8, int16, ...) are not preserved.
EXPECTED_DATA1_DF = pd.DataFrame(
@@ -88,7 +92,9 @@ EXPECTED_DATA3_DF = pd.DataFrame(
EXPECTED_DATA4_DF = pd.DataFrame(
[(True, b"str", [3, TIME, TIME])], columns=["bool", "string", "array"]
)
-EXPECTED_DATA5_DF = pd.DataFrame([(["abc", "def", "ghi"],)], columns=["strArray"])
+EXPECTED_DATA5_DF = pd.DataFrame(
+ [(["abc", "def", "ghi"], "jkl\x00\x00")], columns=["strArray", "strLenMismatch"]
+)
EXPECTED_DATA1_ARRAY = np.array(
[(3, -16, -32, -64)],
@@ -107,8 +113,8 @@ EXPECTED_DATA4_ARRAY = np.array(
dtype=[("bool", "?"), ("string", "S3"), ("array", "3f8")],
)
EXPECTED_DATA5_ARRAY = np.array(
- [(["abc", "def", "ghi"],)],
- dtype=[("strArray", "3S3")],
+ [(("abc", "def", "ghi"), "jkl\x00\x00")],
+ dtype=[("strArray", "(3,)S3"), ("strLenMismatch", "S5")],
)
EXPECTED_DATA1_BYTE = b"\x03\xf0\xff\xe0\xff\xff\xff\xc0\xff\xff\xff\xff\xff\xff\xff"
@@ -118,7 +124,7 @@ EXPECTED_DATA4_BYTE = (
b"\x01str"
b"\x00\x00\x00\x00\x00\x00\x08@\xea!\x1b\xc3\x1eJ\xd8A\xea!\x1b\xc3\x1eJ\xd8A"
)
-EXPECTED_DATA5_BYTE = b"abcdefghi"
+EXPECTED_DATA5_BYTE = b"abcdefghijkl\x00\x00"
@pytest.fixture(scope="module")
@@ -249,13 +255,13 @@ class TestReadDatabase:
assert all(EXPECTED_DATA3_ARRAY == actual["data3"][3])
assert all(EXPECTED_DATA4_ARRAY == actual["data4"][3])
assert len(actual["data4"][3]["array"]) == 3
- assert all(EXPECTED_DATA5_ARRAY == actual["data5"][3])
+ assert EXPECTED_DATA5_ARRAY == actual["data5"][3]
assert len(actual["data5"][3]["strArray"]) == 3
def test_read_as_bytes(self, db_path):
db = necstdb.opendb(db_path)
actual = {name: db.open_table(name).read(astype="raw") for name in table_name}
- formats = ["<bhiq", "<BHIQ", "<fd4sc", "<?3s3d", "<3s3s3s"]
+ formats = ["<bhiq", "<BHIQ", "<fd4sc", "<?3s3d", "<3s3s3s5s"]
unpacked = {
k: tuple(struct.iter_unpack(fmt, v))
for fmt, (k, v) in zip(formats, actual.items())
@@ -395,7 +401,7 @@ class TestMethods:
("data2", 330, 22, 15, "<BHIQ"),
("data3", 594, 33, 17, "<fd4sc"),
("data4", 1364, 44, 28, "<?3s3d"),
- ("data5", 495, 55, 9, "<3s3s3s"),
+ ("data5", 495, 55, 14, "<3s3s3s5s"),
],
columns=[
"table name",
diff --git a/tests/test_necstdb_recover.py b/tests/test_necstdb_recover.py
index acaed8e..2cb853d 100644
--- a/tests/test_necstdb_recover.py
+++ b/tests/test_necstdb_recover.py
@@ -4,12 +4,19 @@ import pytest
import necstdb
-EXAMPLE_DATA_PATH = pathlib.Path(".") / "tests" / "example_data"
+
[email protected]
+def db_path(tmp_path_factory) -> pathlib.Path:
+ """Path to temporary database directory."""
+ return tmp_path_factory.mktemp("test_db")
class TestReadDatabase:
- def test_read_db(self):
- db = necstdb.opendb(EXAMPLE_DATA_PATH)
+
+ EXAMPLE_DATA_PATH = pathlib.Path(".") / "tests" / "example_data"
+
+ def test_read_db_with_invalid_format_specifier(self):
+ db = necstdb.opendb(self.EXAMPLE_DATA_PATH)
_ = db.open_table("data4").read(astype="raw")
with pytest.raises(ValueError):
_ = db.open_table("data4").read(astype="tuple")
@@ -29,3 +36,26 @@ class TestReadDatabase:
print(actual)
actual = db.open_table("data4").recovered.read(astype="array")
print(actual)
+
+ def test_ignore_trailing_pad_bytes(self, db_path):
+ header = {
+ "data": [
+ {"key": "data", "format": "5s", "size": 5},
+ {"key": "bool", "format": "?", "size": 1},
+ ]
+ }
+
+ db = necstdb.opendb(db_path, mode="w")
+ db.create_table("string_length_missepecified", header)
+ table = db.open_table("string_length_missepecified", mode="ab")
+
+ data = b"abc"
+ _ = table.append(data, True)
+ table.close() # Close table to flush the data
+
+ table = db.open_table("string_length_missepecified").recovered
+ assert table.read(astype="raw")[:5] == data + b"\x00\x00" # Won't be recovered
+ assert table.read(astype="tuple")[0][0] == data
+ assert table.read(astype="dict")[0]["data"] == data
+ assert table.read(astype="df")["data"].values[0] == data
+ assert table.read(astype="sa")["data"][0] == data
| Data type "|S12" does not unpacked when opening db specifying
Below works well
```python
>>>db = necstdb.opendb(data_path)
>>>obsmode = db.open_table("obsmode").read(astype="array")
```
However,
```python
>>>db = necstdb.opendb(data_path)
>>>obsmode = db.open_table("obsmode").read(astype="df")
>>>print(obsmode["obs_mode"])
b' \x00\x00'
```
pandas is very useful when manipulating time x 1-dimensional data
Could you please fix the issue?@KaoruNishikawa | 0.0 | [
"tests/test_necstdb_recover.py::TestReadDatabase::test_ignore_trailing_pad_bytes"
] | [
"tests/test_necstdb.py::TestWriteDatabase::test_create_table",
"tests/test_necstdb.py::TestWriteDatabase::test_write_table",
"tests/test_necstdb.py::TestWriteDatabase::test_write_file",
"tests/test_necstdb.py::TestReadDatabase::test_read_types",
"tests/test_necstdb.py::TestReadDatabase::test_read_as_tuple",
"tests/test_necstdb.py::TestReadDatabase::test_read_as_dict",
"tests/test_necstdb.py::TestReadDatabase::test_read_as_df",
"tests/test_necstdb.py::TestReadDatabase::test_read_as_array",
"tests/test_necstdb.py::TestReadDatabase::test_read_as_bytes",
"tests/test_necstdb.py::TestReadDatabase::test_read_file",
"tests/test_necstdb.py::TestPartialRead::test_partial_read_as_tuple",
"tests/test_necstdb.py::TestPartialRead::test_partial_read_as_dict",
"tests/test_necstdb.py::TestPartialRead::test_partial_read_as_df",
"tests/test_necstdb.py::TestPartialRead::test_partial_read_as_bytes",
"tests/test_necstdb.py::TestMethods::test_list_tables",
"tests/test_necstdb.py::TestMethods::test_checkout",
"tests/test_necstdb.py::TestMethods::test_get_info",
"tests/test_necstdb_recover.py::TestReadDatabase::test_read_db_with_invalid_format_specifier"
] | 2022-10-18 14:35:53+00:00 | 4,343 |
|
ohsu-comp-bio__py-tes-52 | diff --git a/tes/client.py b/tes/client.py
index d3f21a7..5539a34 100644
--- a/tes/client.py
+++ b/tes/client.py
@@ -193,14 +193,14 @@ class HTTPClient(object):
time.sleep(0.5)
def _request_params(
- self, data: Optional[str] = None,
- params: Optional[Dict] = None
+ self, data: Optional[str] = None, params: Optional[Dict] = None
) -> Dict[str, Any]:
kwargs: Dict[str, Any] = {}
kwargs['timeout'] = self.timeout
kwargs['headers'] = {}
kwargs['headers']['Content-type'] = 'application/json'
- kwargs['auth'] = (self.user, self.password)
+ if self.user is not None and self.password is not None:
+ kwargs['auth'] = (self.user, self.password)
if data:
kwargs['data'] = data
if params:
diff --git a/tes/models.py b/tes/models.py
index 8550291..09804cd 100644
--- a/tes/models.py
+++ b/tes/models.py
@@ -10,19 +10,15 @@ from datetime import datetime
from typing import Any, Dict, List, Optional, Tuple, Type, Union
-@attrs
+@attrs(repr=False)
class _ListOfValidator(object):
type: Type = attrib()
- def __call__(self, inst, attr, value):
- """
- We use a callable class to be able to change the ``__repr__``.
- """
+ def __call__(self, inst, attr, value) -> None:
if not all([isinstance(n, self.type) for n in value]):
raise TypeError(
- "'{attr.name}' must be a list of {self.type!r} (got {value!r} "
- "that is a list of {values[0].__class__!r}).",
- attr, self.type, value,
+ f"'{attr.name}' must be a list of {self.type!r} (got "
+ f"{value!r}", attr
)
def __repr__(self) -> str:
@@ -60,15 +56,15 @@ def strconv(value: Any) -> Any:
# since an int64 value is encoded as a string in json we need to handle
# conversion
def int64conv(value: Optional[str]) -> Optional[int]:
- if value is not None:
- return int(value)
- return value
+ if value is None:
+ return value
+ return int(value)
def timestampconv(value: Optional[str]) -> Optional[datetime]:
- if value is not None:
- return dateutil.parser.parse(value)
- return value
+ if value is None:
+ return value
+ return dateutil.parser.parse(value)
def datetime_json_handler(x: Any) -> str:
@@ -294,7 +290,7 @@ class Task(Base):
for e in self.executors:
if e.image is None:
errs.append("Executor image must be provided")
- if len(e.command) == 0:
+ if e.command is None or len(e.command) == 0:
errs.append("Executor command must be provided")
if e.stdin is not None:
if not os.path.isabs(e.stdin):
@@ -306,8 +302,8 @@ class Task(Base):
if not os.path.isabs(e.stderr):
errs.append("Executor stderr must be an absolute path")
if e.env is not None:
- for k, v in e.env:
- if not isinstance(k, str) and not isinstance(k, str):
+ for k, v in e.env.items():
+ if not isinstance(k, str) and not isinstance(v, str):
errs.append(
"Executor env keys and values must be StrType"
)
@@ -339,7 +335,7 @@ class Task(Base):
errs.append("Volume paths must be absolute")
if self.tags is not None:
- for k, v in self.tags:
+ for k, v in self.tags.items():
if not isinstance(k, str) and not isinstance(k, str):
errs.append(
"Tag keys and values must be StrType"
diff --git a/tes/utils.py b/tes/utils.py
index 199543b..8587d5f 100644
--- a/tes/utils.py
+++ b/tes/utils.py
@@ -27,14 +27,20 @@ class TimeoutError(Exception):
def unmarshal(j: Any, o: Type, convert_camel_case=True) -> Any:
+ m: Any = None
if isinstance(j, str):
- m = json.loads(j)
- elif isinstance(j, dict):
- m = j
+ try:
+ m = json.loads(j)
+ except json.decoder.JSONDecodeError:
+ pass
elif j is None:
return None
else:
- raise TypeError("j must be a str, a dict or None")
+ m = j
+
+ if not isinstance(m, dict):
+ raise TypeError("j must be a dictionary, a JSON string evaluation to "
+ "a dictionary, or None")
d: Dict[str, Any] = {}
if convert_camel_case:
@@ -77,16 +83,8 @@ def unmarshal(j: Any, o: Type, convert_camel_case=True) -> Any:
field = v
omap = fullOmap.get(o.__name__, {})
if k in omap:
- if isinstance(omap[k], tuple):
- try:
- obj = omap[k][0]
- field = _unmarshal(v, obj)
- except Exception:
- obj = omap[k][1]
- field = _unmarshal(v, obj)
- else:
- obj = omap[k]
- field = _unmarshal(v, obj)
+ obj = omap[k]
+ field = _unmarshal(v, obj)
r[k] = field
try:
| ohsu-comp-bio/py-tes | e67ab6ecb2c7c5113f35c7d8bc91ad4ad160c65f | diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
index e01138f..b273973 100644
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -29,7 +29,12 @@ jobs:
run: pip install .
- name: Lint with Flake8
- run: flake8 .
+ run: flake8 --max-line-length=120 .
- name: Run unit tests
- run: coverage run --source tes -m pytest -W ignore::DeprecationWarning
+ run: |
+ pytest \
+ --cov=tes/ \
+ --cov-branch \
+ --cov-report=term-missing \
+ --cov-fail-under=99
diff --git a/tests/__init__.py b/tests/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/tests/requirements.txt b/tests/requirements.txt
index 45208ca..8f67ab0 100644
--- a/tests/requirements.txt
+++ b/tests/requirements.txt
@@ -2,4 +2,5 @@ coverage>=6.5.0
coveralls>=3.3.1
flake8>=5.0.4
pytest>=7.2.1
+pytest-cov>=4.0.0
requests_mock>=1.10.0
diff --git a/tests/test_client.py b/tests/test_client.py
index 08b2448..52ade42 100644
--- a/tests/test_client.py
+++ b/tests/test_client.py
@@ -53,7 +53,7 @@ class TestHTTPClient(unittest.TestCase):
)
self.cli.create_task(self.task)
self.assertEqual(m.last_request.text, self.task.as_json())
- self.assertEqual(m.last_request.timeout, self.cli.timeout)
+ self.assertAlmostEqual(m.last_request.timeout, self.cli.timeout)
m.post(
"%s/ga4gh/tes/v1/tasks" % (self.mock_url),
@@ -62,6 +62,9 @@ class TestHTTPClient(unittest.TestCase):
with self.assertRaises(requests.HTTPError):
self.cli.create_task(self.task)
+ with self.assertRaises(TypeError):
+ self.cli.create_task('not_a_task_object') # type: ignore
+
def test_get_task(self):
with requests_mock.Mocker() as m:
m.get(
@@ -79,7 +82,7 @@ class TestHTTPClient(unittest.TestCase):
self.mock_url, self.mock_id
)
)
- self.assertEqual(m.last_request.timeout, self.cli.timeout)
+ self.assertAlmostEqual(m.last_request.timeout, self.cli.timeout)
m.get(
requests_mock.ANY,
@@ -102,7 +105,7 @@ class TestHTTPClient(unittest.TestCase):
m.last_request.url,
"%s/ga4gh/tes/v1/tasks?view=MINIMAL" % (self.mock_url)
)
- self.assertEqual(m.last_request.timeout, self.cli.timeout)
+ self.assertAlmostEqual(m.last_request.timeout, self.cli.timeout)
# empty response
m.get(
@@ -137,7 +140,7 @@ class TestHTTPClient(unittest.TestCase):
"%s/ga4gh/tes/v1/tasks/%s:cancel" % (
self.mock_url, self.mock_id)
)
- self.assertEqual(m.last_request.timeout, self.cli.timeout)
+ self.assertAlmostEqual(m.last_request.timeout, self.cli.timeout)
m.post(
"%s/ga4gh/tes/v1/tasks/%s:cancel" % (
@@ -167,7 +170,7 @@ class TestHTTPClient(unittest.TestCase):
m.last_request.url,
"%s/ga4gh/tes/v1/service-info" % (self.mock_url)
)
- self.assertEqual(m.last_request.timeout, self.cli.timeout)
+ self.assertAlmostEqual(m.last_request.timeout, self.cli.timeout)
m.get(
"%s/ga4gh/tes/v1/service-info" % (self.mock_url),
@@ -203,104 +206,124 @@ class TestHTTPClient(unittest.TestCase):
)
self.cli.wait(self.mock_id, timeout=2)
+ def test_request_params(self):
+
+ cli = HTTPClient(url="http://fakehost:8000", timeout=5)
+ vals = cli._request_params()
+ self.assertAlmostEqual(vals["timeout"], 5)
+ self.assertEqual(vals["headers"]["Content-type"], "application/json")
+ self.assertRaises(KeyError, lambda: vals["headers"]["Authorization"])
+ self.assertRaises(KeyError, lambda: vals["auth"])
+ self.assertRaises(KeyError, lambda: vals["data"])
+ self.assertRaises(KeyError, lambda: vals["params"])
+
+ cli = HTTPClient(url="http://fakehost:8000", user="user",
+ password="password", token="token")
+ vals = cli._request_params(data='{"json": "string"}',
+ params={"query_param": "value"})
+ self.assertAlmostEqual(vals["timeout"], 10)
+ self.assertEqual(vals["headers"]["Content-type"], "application/json")
+ self.assertEqual(vals["headers"]["Authorization"], "Bearer token")
+ self.assertEqual(vals["auth"], ("user", "password"))
+ self.assertEqual(vals["data"], '{"json": "string"}')
+ self.assertEqual(vals["params"], {"query_param": "value"})
+
+ def test_append_suffixes_to_url(self):
+ urls = ["http://example.com", "http://example.com/"]
+ urls_order = ["http://example1.com", "http://example2.com"]
+ suffixes = ["foo", "/foo", "foo/", "/foo/"]
+ no_suffixes = ["", "/", "//", "///"]
+ suffixes_order = ["1", "2"]
+
+ results = append_suffixes_to_url(urls=urls, suffixes=suffixes)
+ assert len(results) == len(urls) * len(suffixes)
+ assert all(url == 'http://example.com/foo' for url in results)
+
+ results = append_suffixes_to_url(urls=urls, suffixes=no_suffixes)
+ assert len(results) == len(urls) * len(no_suffixes)
+ assert all(url == 'http://example.com' for url in results)
+
+ results = append_suffixes_to_url(urls=urls_order, suffixes=suffixes_order)
+ assert len(results) == len(urls_order) * len(suffixes_order)
+ assert results[0] == 'http://example1.com/1'
+ assert results[1] == 'http://example1.com/2'
+ assert results[2] == 'http://example2.com/1'
+ assert results[3] == 'http://example2.com/2'
+
+ def test_send_request(self):
+ mock_url = "http://example.com"
+ mock_id = "mock_id"
+ mock_urls = append_suffixes_to_url([mock_url], ["/suffix", "/"])
+
+ # invalid method
+ with pytest.raises(ValueError):
+ send_request(paths=mock_urls, method="invalid")
+
+ # errors for all paths
+ with requests_mock.Mocker() as m:
+ m.get(requests_mock.ANY, exc=requests.exceptions.ConnectTimeout)
+ with pytest.raises(requests.HTTPError):
+ send_request(paths=mock_urls)
+
+ # error on first path, 200 on second
+ with requests_mock.Mocker() as m:
+ m.get(mock_urls[0], exc=requests.exceptions.ConnectTimeout)
+ m.get(mock_urls[1], status_code=200)
+ response = send_request(paths=mock_urls)
+ assert response.status_code == 200
+ assert m.last_request.url.rstrip('/') == f"{mock_url}"
+
+ # error on first path, 404 on second
+ with requests_mock.Mocker() as m:
+ m.get(mock_urls[0], exc=requests.exceptions.ConnectTimeout)
+ m.get(mock_urls[1], status_code=404)
+ with pytest.raises(requests.HTTPError):
+ send_request(paths=mock_urls)
+
+ # 404 on first path, error on second
+ with requests_mock.Mocker() as m:
+ m.get(mock_urls[0], status_code=404)
+ m.get(mock_urls[1], exc=requests.exceptions.ConnectTimeout)
+ with pytest.raises(requests.HTTPError):
+ send_request(paths=mock_urls)
+
+ # 404 on first path, 200 on second
+ with requests_mock.Mocker() as m:
+ m.get(mock_urls[0], status_code=404)
+ m.get(mock_urls[1], status_code=200)
+ response = send_request(paths=mock_urls)
+ assert response.status_code == 200
+ assert m.last_request.url.rstrip('/') == f"{mock_url}"
+
+ # POST 200
+ with requests_mock.Mocker() as m:
+ m.post(f"{mock_url}/suffix/foo/{mock_id}:bar", status_code=200)
+ paths = append_suffixes_to_url(mock_urls, ["/foo/{id}:bar"])
+ response = send_request(paths=paths, method="post", json={},
+ id=mock_id)
+ assert response.status_code == 200
+ assert m.last_request.url == f"{mock_url}/suffix/foo/{mock_id}:bar"
+
+ # GET 200
+ with requests_mock.Mocker() as m:
+ m.get(f"{mock_url}/suffix/foo/{mock_id}", status_code=200)
+ paths = append_suffixes_to_url(mock_urls, ["/foo/{id}"])
+ response = send_request(paths=paths, id=mock_id)
+ assert response.status_code == 200
+ assert m.last_request.url == f"{mock_url}/suffix/foo/{mock_id}"
+
+ # POST 404
+ with requests_mock.Mocker() as m:
+ m.post(requests_mock.ANY, status_code=404, json={})
+ paths = append_suffixes_to_url(mock_urls, ["/foo"])
+ with pytest.raises(requests.HTTPError):
+ send_request(paths=paths, method="post", json={})
+ assert m.last_request.url == f"{mock_url}/foo"
-def test_append_suffixes_to_url():
- urls = ["http://example.com", "http://example.com/"]
- urls_order = ["http://example1.com", "http://example2.com"]
- suffixes = ["foo", "/foo", "foo/", "/foo/"]
- no_suffixes = ["", "/", "//", "///"]
- suffixes_order = ["1", "2"]
-
- results = append_suffixes_to_url(urls=urls, suffixes=suffixes)
- assert len(results) == len(urls) * len(suffixes)
- assert all(url == 'http://example.com/foo' for url in results)
-
- results = append_suffixes_to_url(urls=urls, suffixes=no_suffixes)
- assert len(results) == len(urls) * len(no_suffixes)
- assert all(url == 'http://example.com' for url in results)
-
- results = append_suffixes_to_url(urls=urls_order, suffixes=suffixes_order)
- assert len(results) == len(urls_order) * len(suffixes_order)
- assert results[0] == 'http://example1.com/1'
- assert results[1] == 'http://example1.com/2'
- assert results[2] == 'http://example2.com/1'
- assert results[3] == 'http://example2.com/2'
-
-
-def test_send_request():
- mock_url = "http://example.com"
- mock_id = "mock_id"
- mock_urls = append_suffixes_to_url([mock_url], ["/suffix", "/"])
-
- # invalid method
- with pytest.raises(ValueError):
- send_request(paths=mock_urls, method="invalid")
-
- # errors for all paths
- with requests_mock.Mocker() as m:
- m.get(requests_mock.ANY, exc=requests.exceptions.ConnectTimeout)
- with pytest.raises(requests.HTTPError):
- send_request(paths=mock_urls)
-
- # error on first path, 200 on second
- with requests_mock.Mocker() as m:
- m.get(mock_urls[0], exc=requests.exceptions.ConnectTimeout)
- m.get(mock_urls[1], status_code=200)
- response = send_request(paths=mock_urls)
- assert response.status_code == 200
- assert m.last_request.url.rstrip('/') == f"{mock_url}"
-
- # error on first path, 404 on second
- with requests_mock.Mocker() as m:
- m.get(mock_urls[0], exc=requests.exceptions.ConnectTimeout)
- m.get(mock_urls[1], status_code=404)
- with pytest.raises(requests.HTTPError):
- send_request(paths=mock_urls)
-
- # 404 on first path, error on second
- with requests_mock.Mocker() as m:
- m.get(mock_urls[0], status_code=404)
- m.get(mock_urls[1], exc=requests.exceptions.ConnectTimeout)
- with pytest.raises(requests.HTTPError):
- send_request(paths=mock_urls)
-
- # 404 on first path, 200 on second
- with requests_mock.Mocker() as m:
- m.get(mock_urls[0], status_code=404)
- m.get(mock_urls[1], status_code=200)
- response = send_request(paths=mock_urls)
- assert response.status_code == 200
- assert m.last_request.url.rstrip('/') == f"{mock_url}"
-
- # POST 200
- with requests_mock.Mocker() as m:
- m.post(f"{mock_url}/suffix/foo/{mock_id}:bar", status_code=200)
- paths = append_suffixes_to_url(mock_urls, ["/foo/{id}:bar"])
- response = send_request(paths=paths, method="post", json={},
- id=mock_id)
- assert response.status_code == 200
- assert m.last_request.url == f"{mock_url}/suffix/foo/{mock_id}:bar"
-
- # GET 200
- with requests_mock.Mocker() as m:
- m.get(f"{mock_url}/suffix/foo/{mock_id}", status_code=200)
- paths = append_suffixes_to_url(mock_urls, ["/foo/{id}"])
- response = send_request(paths=paths, id=mock_id)
- assert response.status_code == 200
- assert m.last_request.url == f"{mock_url}/suffix/foo/{mock_id}"
-
- # POST 404
- with requests_mock.Mocker() as m:
- m.post(requests_mock.ANY, status_code=404, json={})
- paths = append_suffixes_to_url(mock_urls, ["/foo"])
- with pytest.raises(requests.HTTPError):
- send_request(paths=paths, method="post", json={})
- assert m.last_request.url == f"{mock_url}/foo"
-
- # GET 500
- with requests_mock.Mocker() as m:
- m.get(f"{mock_url}/suffix/foo", status_code=500)
- paths = append_suffixes_to_url(mock_urls, ["/foo"])
- with pytest.raises(requests.HTTPError):
- send_request(paths=paths)
- assert m.last_request.url == f"{mock_url}/suffix/foo"
+ # GET 500
+ with requests_mock.Mocker() as m:
+ m.get(f"{mock_url}/suffix/foo", status_code=500)
+ paths = append_suffixes_to_url(mock_urls, ["/foo"])
+ with pytest.raises(requests.HTTPError):
+ send_request(paths=paths)
+ assert m.last_request.url == f"{mock_url}/suffix/foo"
diff --git a/tests/test_models.py b/tests/test_models.py
index 2c8dd95..c1cebd7 100644
--- a/tests/test_models.py
+++ b/tests/test_models.py
@@ -1,67 +1,250 @@
import json
import unittest
-from tes.models import Task, Executor, Input, Output, strconv
+from copy import deepcopy
+from tes.models import (
+ Executor,
+ ExecutorLog,
+ Input,
+ Output,
+ OutputFileLog,
+ Resources,
+ Task,
+ TaskLog,
+ datetime_json_handler,
+ int64conv,
+ list_of,
+ strconv,
+ timestampconv,
+ _drop_none,
+)
-class TestModels(unittest.TestCase):
- task = Task(
- executors=[
- Executor(
- image="alpine",
- command=["echo", "hello"]
- )
- ]
- )
-
- expected = {
- "executors": [
- {
- "image": "alpine",
- "command": ["echo", "hello"]
- }
- ]
- }
- def test_strconv(self):
- self.assertTrue(strconv("foo"), u"foo")
- self.assertTrue(strconv(["foo", "bar"]), [u"foo", u"bar"])
- self.assertTrue(strconv(("foo", "bar")), (u"foo", u"bar"))
- self.assertTrue(strconv(1), 1)
+task_valid = Task(
+ executors=[
+ Executor(
+ image="alpine",
+ command=["echo", "hello"]
+ )
+ ]
+)
+
+
+datetm = "2018-01-01T00:00:00Z"
+task_valid_full = Task(
+ id="foo",
+ state="COMPLETE",
+ name="some_task",
+ description="some description",
+ resources=Resources(
+ cpu_cores=1,
+ ram_gb=2,
+ disk_gb=3,
+ preemptible=True,
+ zones=["us-east-1", "us-west-1"],
+ ),
+ executors=[
+ Executor(
+ image="alpine",
+ command=["echo", "hello"],
+ workdir="/abs/path",
+ stdin="/abs/path",
+ stdout="/abs/path",
+ stderr="/abs/path",
+ env={"VAR": "value"}
+ ),
+ Executor(
+ image="alpine",
+ command=["echo", "worls"]
+ )
+ ],
+ inputs=[
+ Input(
+ url="s3:/some/path",
+ path="/abs/path"
+ ),
+ Input(
+ content="foo",
+ path="/abs/path"
+ )
+ ],
+ outputs=[
+ Output(
+ url="s3:/some/path",
+ path="/abs/path"
+ )
+ ],
+ volumes=[],
+ tags={"key": "value", "key2": "value2"},
+ logs=[
+ TaskLog(
+ start_time=datetm, # type: ignore
+ end_time=datetm, # type: ignore
+ metadata={"key": "value", "key2": "value2"},
+ logs=[
+ ExecutorLog(
+ start_time=datetm, # type: ignore
+ end_time=datetm, # type: ignore
+ exit_code=0,
+ stdout="hello",
+ stderr="world"
+ )
+ ],
+ outputs=[
+ OutputFileLog(
+ url="s3:/some/path",
+ path="/abs/path",
+ size_bytes=int64conv(123) # type: ignore
+ )
+ ],
+ system_logs=[
+ "some system log message",
+ "some other system log message"
+ ]
+ )
+ ],
+ creation_time=datetm # type: ignore
+)
+task_invalid = Task(
+ executors=[
+ Executor( # type: ignore
+ image="alpine",
+ command=["echo", "hello"],
+ stdin="relative/path",
+ stdout="relative/path",
+ stderr="relative/path",
+ env={1: 2}
+ )
+ ],
+ inputs=[
+ Input(
+ url="s3:/some/path",
+ content="foo"
+ ),
+ Input(
+ path="relative/path"
+ )
+ ],
+ outputs=[
+ Output(),
+ Output(
+ url="s3:/some/path",
+ path="relative/path"
+ )
+ ],
+ volumes=['/abs/path', 'relative/path'],
+ tags={1: 2}
+)
+
+expected = {
+ "executors": [
+ {
+ "image": "alpine",
+ "command": ["echo", "hello"]
+ }
+ ]
+}
+
+
+class TestModels(unittest.TestCase):
+
+ def test_list_of(self):
+ validator = list_of(str)
+ self.assertEqual(list_of(str), validator)
+ self.assertEqual(
+ repr(validator),
+ "<instance_of validator for type <class 'str'>>"
+ )
with self.assertRaises(TypeError):
Input(
- url="s3:/some/path", path="/opt/foo", content=123
+ url="s3:/some/path",
+ path="/opt/foo",
+ content=123 # type: ignore
)
-
- def test_list_of(self):
with self.assertRaises(TypeError):
Task(
inputs=[
Input(
url="s3:/some/path", path="/opt/foo"
),
- "foo"
+ "foo" # type: ignore
]
)
+ def test_drop_none(self):
+ self.assertEqual(_drop_none({}), {})
+ self.assertEqual(_drop_none({"foo": None}), {})
+ self.assertEqual(_drop_none({"foo": 1}), {"foo": 1})
+ self.assertEqual(_drop_none({"foo": None, "bar": 1}), {"bar": 1})
+ self.assertEqual(_drop_none({"foo": [1, None, 2]}), {"foo": [1, 2]})
+ self.assertEqual(_drop_none({"foo": {"bar": None}}), {"foo": {}})
+ self.assertEqual(
+ _drop_none({"foo": {"bar": None}, "baz": 1}),
+ {"foo": {}, "baz": 1}
+ )
+
+ def test_strconv(self):
+ self.assertTrue(strconv("foo"), u"foo")
+ self.assertTrue(strconv(["foo", "bar"]), [u"foo", u"bar"])
+ self.assertTrue(strconv(("foo", "bar")), (u"foo", u"bar"))
+ self.assertTrue(strconv(1), 1)
+ self.assertTrue(strconv([1]), [1])
+
+ def test_int64conv(self):
+ self.assertEqual(int64conv("1"), 1)
+ self.assertEqual(int64conv("-1"), -1)
+ self.assertIsNone(int64conv(None))
+
+ def test_timestampconv(self):
+ tm = timestampconv("2018-02-01T00:00:00Z")
+ self.assertIsNotNone(tm)
+ assert tm is not None
+ self.assertAlmostEqual(tm.year, 2018)
+ self.assertAlmostEqual(tm.month, 2)
+ self.assertAlmostEqual(tm.day, 1)
+ self.assertAlmostEqual(tm.hour, 0)
+ self.assertAlmostEqual(tm.timestamp(), 1517443200.0)
+ self.assertIsNone(timestampconv(None))
+
+ def test_datetime_json_handler(self):
+ tm = timestampconv("2018-02-01T00:00:00Z")
+ tm_iso = '2018-02-01T00:00:00+00:00'
+ assert tm is not None
+ self.assertEqual(datetime_json_handler(tm), tm_iso)
+ with self.assertRaises(TypeError):
+ datetime_json_handler(None)
+ with self.assertRaises(TypeError):
+ datetime_json_handler("abc")
+ with self.assertRaises(TypeError):
+ datetime_json_handler(2001)
+ with self.assertRaises(TypeError):
+ datetime_json_handler(tm_iso)
+
def test_as_dict(self):
- self.assertEqual(self.task.as_dict(), self.expected)
+ task = deepcopy(task_valid)
+ self.assertEqual(task.as_dict(), expected)
+ with self.assertRaises(KeyError):
+ task.as_dict()['inputs']
+ self.assertIsNone(task.as_dict(drop_empty=False)['inputs'])
def test_as_json(self):
- self.assertEqual(self.task.as_json(), json.dumps(self.expected))
+ task = deepcopy(task_valid)
+ self.assertEqual(task.as_json(), json.dumps(expected))
def test_is_valid(self):
- self.assertTrue(self.task.is_valid()[0])
+ task = deepcopy(task_valid)
+ self.assertTrue(task.is_valid()[0])
- task2 = self.task
- task2.inputs = [Input(path="/opt/foo")]
- self.assertFalse(task2.is_valid()[0])
+ task = deepcopy(task_valid_full)
+ self.assertTrue(task.is_valid()[0])
- task3 = self.task
- task3.outputs = [
- Output(
- url="s3:/some/path", path="foo"
- )
- ]
- self.assertFalse(task3.is_valid()[0])
+ task = deepcopy(task_invalid)
+ task.executors[0].image = None # type: ignore
+ task.executors[0].command = None # type: ignore
+ self.assertFalse(task.is_valid()[0])
+
+ task = deepcopy(task_invalid)
+ task.executors = None
+ self.assertFalse(task.is_valid()[0])
diff --git a/tests/test_utils.py b/tests/test_utils.py
index c07dd09..b7fe5ed 100644
--- a/tests/test_utils.py
+++ b/tests/test_utils.py
@@ -5,7 +5,23 @@ import json
import unittest
from tes.utils import camel_to_snake, unmarshal, UnmarshalError
-from tes.models import Input, Task, CreateTaskResponse
+from tes.models import (
+ CancelTaskRequest,
+ CancelTaskResponse,
+ CreateTaskResponse,
+ Executor,
+ ExecutorLog,
+ GetTaskRequest,
+ Input,
+ ListTasksRequest,
+ ListTasksResponse,
+ Output,
+ OutputFileLog,
+ Resources,
+ ServiceInfo,
+ Task,
+ TaskLog,
+)
class TestUtils(unittest.TestCase):
@@ -19,7 +35,110 @@ class TestUtils(unittest.TestCase):
self.assertEqual(camel_to_snake(case3), "foo_bar")
def test_unmarshal(self):
- test_invalid_dict = {"adfasd": "bar"}
+
+ # test unmarshalling with no or minimal contents
+ try:
+ unmarshal(
+ CancelTaskRequest(id="foo").as_json(),
+ CancelTaskRequest
+ )
+ except Exception:
+ self.fail("Raised ExceptionType unexpectedly!")
+
+ try:
+ unmarshal(CancelTaskResponse().as_json(), CancelTaskResponse)
+ except Exception:
+ self.fail("Raised ExceptionType unexpectedly!")
+
+ try:
+ unmarshal(
+ CreateTaskResponse(id="foo").as_json(),
+ CreateTaskResponse
+ )
+ except Exception:
+ self.fail("Raised ExceptionType unexpectedly!")
+
+ try:
+ unmarshal(Executor(
+ image="alpine", command=["echo", "hello"]).as_json(),
+ Executor
+ )
+ except Exception:
+ self.fail("Raised ExceptionType unexpectedly!")
+
+ try:
+ unmarshal(ExecutorLog().as_json(), ExecutorLog)
+ except Exception:
+ self.fail("Raised ExceptionType unexpectedly!")
+
+ try:
+ unmarshal(
+ GetTaskRequest(id="foo", view="BASIC").as_json(),
+ GetTaskRequest
+ )
+ except Exception:
+ self.fail("Raised ExceptionType unexpectedly!")
+
+ try:
+ unmarshal(Input().as_json(), Input)
+ except Exception:
+ self.fail("Raised ExceptionType unexpectedly!")
+
+ try:
+ unmarshal(ListTasksRequest().as_json(), ListTasksRequest)
+ except Exception:
+ self.fail("Raised ExceptionType unexpectedly!")
+
+ try:
+ unmarshal(ListTasksResponse().as_json(), ListTasksResponse)
+ except Exception:
+ self.fail("Raised ExceptionType unexpectedly!")
+
+ try:
+ unmarshal(Output().as_json(), Output)
+ except Exception:
+ self.fail("Raised ExceptionType unexpectedly!")
+
+ try:
+ unmarshal(OutputFileLog().as_json(), OutputFileLog)
+ except Exception:
+ self.fail("Raised ExceptionType unexpectedly!")
+
+ try:
+ unmarshal(Resources().as_json(), Resources)
+ except Exception:
+ self.fail("Raised ExceptionType unexpectedly!")
+
+ try:
+ unmarshal(ServiceInfo().as_json(), ServiceInfo)
+ except Exception:
+ self.fail("Raised ExceptionType unexpectedly!")
+
+ try:
+ unmarshal(Task().as_json(), Task)
+ except Exception:
+ self.fail("Raised ExceptionType unexpectedly!")
+
+ try:
+ unmarshal(TaskLog().as_json(), TaskLog)
+ except Exception:
+ self.fail("Raised ExceptionType unexpectedly!")
+
+ # test special cases
+ self.assertIsNone(unmarshal(None, Input))
+ with self.assertRaises(TypeError):
+ unmarshal([], Input)
+ with self.assertRaises(TypeError):
+ unmarshal(1, Input)
+ with self.assertRaises(TypeError):
+ unmarshal(1.3, Input)
+ with self.assertRaises(TypeError):
+ unmarshal(True, Input)
+ with self.assertRaises(TypeError):
+ unmarshal('foo', Input)
+
+ # test with some interesting contents
+ test_invalid_dict = {"foo": "bar"}
test_invalid_str = json.dumps(test_invalid_dict)
with self.assertRaises(UnmarshalError):
unmarshal(test_invalid_dict, CreateTaskResponse)
@@ -33,7 +152,7 @@ class TestUtils(unittest.TestCase):
}
test_simple_str = json.dumps(test_simple_dict)
o1 = unmarshal(test_simple_dict, Input)
- o2 = unmarshal(test_simple_str, Input)
+ o2 = unmarshal(test_simple_str, Input, convert_camel_case=False)
self.assertTrue(isinstance(o1, Input))
self.assertTrue(isinstance(o2, Input))
self.assertEqual(o1, o2)
@@ -92,6 +211,13 @@ class TestUtils(unittest.TestCase):
]
}
],
+ "resources": {
+ "cpu_cores": 1,
+ "ram_gb": 2,
+ "disk_gb": 3,
+ "preemptible": True,
+ "zones": ["us-east-1", "us-west-1"]
+ },
"creation_time": "2017-10-09T17:00:00.0Z"
}
@@ -100,7 +226,7 @@ class TestUtils(unittest.TestCase):
o2 = unmarshal(test_complex_str, Task)
self.assertTrue(isinstance(o1, Task))
self.assertTrue(isinstance(o2, Task))
- self.assertEqual(o1, o2)
+ self.assertAlmostEqual(o1, o2)
expected = test_complex_dict.copy()
# handle expected conversions
@@ -122,7 +248,6 @@ class TestUtils(unittest.TestCase):
expected["creation_time"] = dateutil.parser.parse(
expected["creation_time"]
)
-
self.assertEqual(o1.as_dict(), expected)
def test_unmarshal_types(self):
| Increase unit test code coverage
According to the most recent code coverage report (on branch [`api-location`](https://github.com/ohsu-comp-bio/py-tes/tree/api-location) in PR #46), there is still a bit of untested code:
```console
Name Stmts Miss Cover Missing
-----------------------------------------------
tes/__init__.py 5 0 100%
tes/client.py 111 4 96% 133, 186-187, 211
tes/models.py 202 29 86% 29, 53, 65, 77, 87, 292, 296, 298, 300-301, 303-304, 306-307, 309-311, 320, 322, 324, 329, 331, 336-339, 342-344
tes/utils.py 57 11 81% 34-37, 44, 72, 81-86
-----------------------------------------------
TOTAL 375 44 88%
```
Increase code coverage by providing unit tests for the missing statements in:
- [ ] `tes/client.py`
- [ ] `tes/models.py`
- [ ] `tes/utils.py` | 0.0 | [
"tests/test_utils.py::TestUtils::test_unmarshal",
"tests/test_client.py::TestHTTPClient::test_request_params",
"tests/test_models.py::TestModels::test_is_valid",
"tests/test_models.py::TestModels::test_list_of"
] | [
"tests/test_utils.py::TestUtils::test_unmarshal_types",
"tests/test_utils.py::TestUtils::test_camel_to_snake",
"tests/test_client.py::TestHTTPClient::test_send_request",
"tests/test_client.py::TestHTTPClient::test_create_task",
"tests/test_client.py::TestHTTPClient::test_list_tasks",
"tests/test_client.py::TestHTTPClient::test_get_service_info",
"tests/test_client.py::TestHTTPClient::test_get_task",
"tests/test_client.py::TestHTTPClient::test_wait",
"tests/test_client.py::TestHTTPClient::test_cancel_task",
"tests/test_client.py::TestHTTPClient::test_cli",
"tests/test_client.py::TestHTTPClient::test_append_suffixes_to_url",
"tests/test_models.py::TestModels::test_int64conv",
"tests/test_models.py::TestModels::test_strconv",
"tests/test_models.py::TestModels::test_datetime_json_handler",
"tests/test_models.py::TestModels::test_timestampconv",
"tests/test_models.py::TestModels::test_as_dict",
"tests/test_models.py::TestModels::test_drop_none",
"tests/test_models.py::TestModels::test_as_json"
] | 2023-02-12 14:17:22+00:00 | 4,344 |
|
ojarva__python-sshpubkeys-43 | diff --git a/.isort.cfg b/.isort.cfg
index d82713f..d2f2d02 100644
--- a/.isort.cfg
+++ b/.isort.cfg
@@ -1,3 +1,3 @@
[settings]
line_length = 120
-
+not_skip = __init__.py
diff --git a/README.rst b/README.rst
index cc16fe0..1a9c97e 100644
--- a/README.rst
+++ b/README.rst
@@ -59,6 +59,23 @@ Usage:
print(ssh.options_raw) # None (string of optional options at the beginning of public key)
print(ssh.options) # None (options as a dictionary, parsed and validated)
+
+Parsing of `authorized_keys` files:
+
+::
+
+ from sshpubkeys import AuthorizedKeysFile
+
+ key_file = AuthorizedKeysFile("""ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIEGODBKRjsFB/1v3pDRGpA6xR+QpOJg9vat0brlbUNDD\n"""
+ """#This is a comment\n\n"""
+ """ecdsa-sha2-nistp521 AAAAE2VjZHNhLXNoYTItbmlzdHA1MjEAAAAIbmlzdHA1MjEAAACFBAF9QpvUneTvt8"""
+ """lu0ePSuzr7iLE9ZMPu2DFTmqh7BVn89IHuQ5dfg9pArxfHZWgu9lMdlOykVx0I6OXkE35A/mFqwwApyiPmiwno"""
+ """jmRnN//pApl6QQFINHzV/PGOSi599F1Y2tHQwcdb44CPOhkUmHtC9wKazSvw/ivbxNjcMzhhHsWGnA=="""
+ strict=True, disallow_options=True)
+ for key in key_file.keys:
+ print(key.key_type, key.bits, key.hash_512())
+
+
Options
-------
diff --git a/sshpubkeys/__init__.py b/sshpubkeys/__init__.py
index c361a53..2b7f5c5 100644
--- a/sshpubkeys/__init__.py
+++ b/sshpubkeys/__init__.py
@@ -1,2 +1,2 @@
-from .keys import * # pylint:disable=wildcard-import
from .exceptions import * # pylint:disable=wildcard-import
+from .keys import * # pylint:disable=wildcard-import
diff --git a/sshpubkeys/keys.py b/sshpubkeys/keys.py
index dad2009..df1a145 100644
--- a/sshpubkeys/keys.py
+++ b/sshpubkeys/keys.py
@@ -27,13 +27,36 @@ from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric.dsa import DSAParameterNumbers, DSAPublicNumbers
from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicNumbers
-from .exceptions import * # pylint:disable=wildcard-import,unused-wildcard-import
+from .exceptions import (InvalidKeyError, InvalidKeyLengthError, InvalidOptionNameError, InvalidOptionsError,
+ InvalidTypeError, MalformedDataError, MissingMandatoryOptionValueError, TooLongKeyError,
+ TooShortKeyError, UnknownOptionNameError)
-__all__ = ["SSHKey"]
+__all__ = ["AuthorizedKeysFile", "SSHKey"]
+
+
+class AuthorizedKeysFile(object): # pylint:disable=too-few-public-methods
+ """Represents a full authorized_keys file.
+
+ Comments and empty lines are ignored."""
+
+ def __init__(self, file_obj, **kwargs):
+ self.keys = []
+ self.parse(file_obj, **kwargs)
+
+ def parse(self, file_obj, **kwargs):
+ for line in file_obj:
+ line = line.strip()
+ if not line:
+ continue
+ if line.startswith("#"):
+ continue
+ ssh_key = SSHKey(line, **kwargs)
+ ssh_key.parse()
+ self.keys.append(ssh_key)
class SSHKey(object): # pylint:disable=too-many-instance-attributes
- """Presents a single SSH keypair.
+ """Represents a single SSH keypair.
ssh_key = SSHKey(key_data, strict=True)
ssh_key.parse()
@@ -110,6 +133,9 @@ class SSHKey(object): # pylint:disable=too-many-instance-attributes
except (InvalidKeyError, NotImplementedError):
pass
+ def __str__(self):
+ return "Key type: %s, bits: %s, options: %s" % (self.key_type, self.bits, self.options)
+
def reset(self):
"""Reset all data fields."""
for field in self.FIELDS:
| ojarva/python-sshpubkeys | 60c2299ac7669925f3d54b8f49b2b188a1092762 | diff --git a/tests/__init__.py b/tests/__init__.py
index 059b323..9e30401 100644
--- a/tests/__init__.py
+++ b/tests/__init__.py
@@ -4,13 +4,26 @@ New test is generated for each key so that running unittests gives out meaningfu
"""
+import sys
import unittest
-from sshpubkeys import SSHKey
+
+from sshpubkeys import AuthorizedKeysFile, InvalidOptionsError, SSHKey
+
+from .authorized_keys import items as list_of_authorized_keys
+from .invalid_authorized_keys import items as list_of_invalid_authorized_keys
+from .invalid_keys import keys as list_of_invalid_keys
+from .invalid_options import options as list_of_invalid_options
from .valid_keys import keys as list_of_valid_keys
from .valid_keys_rfc4716 import keys as list_of_valid_keys_rfc4716
-from .invalid_keys import keys as list_of_invalid_keys
from .valid_options import options as list_of_valid_options
-from .invalid_options import options as list_of_invalid_options
+
+if sys.version_info.major == 2:
+ from io import BytesIO as StringIO
+else:
+ from io import StringIO
+
+
+DEFAULT_KEY = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIEGODBKRjsFB/1v3pDRGpA6xR+QpOJg9vat0brlbUNDD"
class TestMisc(unittest.TestCase):
@@ -52,6 +65,32 @@ class TestOptions(unittest.TestCase):
ssh = SSHKey()
self.assertRaises(expected_error, ssh.parse_options, option)
+ def test_disallow_options(self):
+ ssh = SSHKey(disallow_options=True)
+ key = """command="dump /home",no-pty,no-port-forwarding """ + DEFAULT_KEY
+ self.assertRaises(InvalidOptionsError, ssh.parse, key)
+
+
+class TestAuthorizedKeys(unittest.TestCase):
+
+ def check_valid_file(self, file_str, valid_keys_count):
+ file_obj = StringIO(file_str)
+ key_file = AuthorizedKeysFile(file_obj)
+ for item in key_file.keys:
+ self.assertIsInstance(item, SSHKey)
+ self.assertEqual(len(key_file.keys), valid_keys_count)
+
+ def check_invalid_file(self, file_str, expected_error):
+ file_obj = StringIO(file_str)
+ self.assertRaises(expected_error, AuthorizedKeysFile, file_obj)
+
+ def test_disallow_options(self):
+ file_obj = StringIO("""command="dump /home",no-pty,no-port-forwarding """ + DEFAULT_KEY)
+ self.assertRaises(InvalidOptionsError, AuthorizedKeysFile, file_obj, disallow_options=True)
+ file_obj.seek(0)
+ key_file = AuthorizedKeysFile(file_obj)
+ self.assertEqual(len(key_file.keys), 1)
+
def loop_options(options):
""" Loop over list of options and dynamically create tests """
@@ -106,11 +145,29 @@ def loop_invalid(keyset, prefix):
setattr(TestKeys, "test_%s_mode_%s" % (prefix_tmp, mode), ch(pubkey, expected_error, **kwargs))
+def loop_authorized_keys(keyset):
+ def ch(file_str, valid_keys_count):
+ return lambda self: self.check_valid_file(file_str, valid_keys_count)
+ for i, items in enumerate(keyset):
+ prefix_tmp = "%s_%s" % (items[0], i)
+ setattr(TestAuthorizedKeys, "test_%s" % prefix_tmp, ch(items[1], items[2]))
+
+
+def loop_invalid_authorized_keys(keyset):
+ def ch(file_str, expected_error, **kwargs):
+ return lambda self: self.check_invalid_file(file_str, expected_error, **kwargs)
+ for i, items in enumerate(keyset):
+ prefix_tmp = "%s_%s" % (items[0], i)
+ setattr(TestAuthorizedKeys, "test_invalid_%s" % prefix_tmp, ch(items[1], items[2]))
+
+
loop_valid(list_of_valid_keys, "valid_key")
loop_valid(list_of_valid_keys_rfc4716, "valid_key_rfc4716")
loop_invalid(list_of_invalid_keys, "invalid_key")
loop_options(list_of_valid_options)
loop_invalid_options(list_of_invalid_options)
+loop_authorized_keys(list_of_authorized_keys)
+loop_invalid_authorized_keys(list_of_invalid_authorized_keys)
if __name__ == '__main__':
unittest.main()
diff --git a/tests/authorized_keys.py b/tests/authorized_keys.py
new file mode 100644
index 0000000..a213862
--- /dev/null
+++ b/tests/authorized_keys.py
@@ -0,0 +1,8 @@
+from .valid_keys import keys
+
+items = [
+ ["empty_file", "", 0],
+ ["single_key", keys[0][0], 1],
+ ["comment_only", "# Nothing else than a comment here", 0],
+ ["lines_with_spaces", " # Comments\n \n" + keys[0][0] + "\n#asdf", 1],
+]
diff --git a/tests/invalid_authorized_keys.py b/tests/invalid_authorized_keys.py
new file mode 100644
index 0000000..a681def
--- /dev/null
+++ b/tests/invalid_authorized_keys.py
@@ -0,0 +1,10 @@
+from sshpubkeys.exceptions import InvalidKeyError, MalformedDataError
+
+from .valid_keys import keys as valid_keys
+
+from.invalid_keys import keys as invalid_keys
+
+items = [
+ ["lines_with_spaces", " # Comments\n \n" + valid_keys[0][0] + "\nasdf", InvalidKeyError],
+ ["invalid_key", "# Comments\n" + invalid_keys[0][0], MalformedDataError],
+]
| Handle full parsing of authorized_keys file
Hi,
as by #21 would be wonderful to handle full parsing of authorized_keys files, including empty and commented-out lines.
I will try to manage in the future a PR, if it will not happens before.
Thanks,
Daniele | 0.0 | [
"tests/__init__.py::TestMisc::test_none_to_constructor",
"tests/__init__.py::TestKeys::test_invalid_key_512bit_ed25519_mode_loose",
"tests/__init__.py::TestKeys::test_invalid_key_512bit_ed25519_mode_strict",
"tests/__init__.py::TestKeys::test_invalid_key_broken_rsa_base64_mode_loose",
"tests/__init__.py::TestKeys::test_invalid_key_broken_rsa_base64_mode_strict",
"tests/__init__.py::TestKeys::test_invalid_key_dsa_2048_mode_strict",
"tests/__init__.py::TestKeys::test_invalid_key_empty_key_mode_loose",
"tests/__init__.py::TestKeys::test_invalid_key_empty_key_mode_strict",
"tests/__init__.py::TestKeys::test_invalid_key_invalid_ecdsa_key_mode_loose",
"tests/__init__.py::TestKeys::test_invalid_key_invalid_ecdsa_key_mode_strict",
"tests/__init__.py::TestKeys::test_invalid_key_invalid_nist_curve_mode_loose",
"tests/__init__.py::TestKeys::test_invalid_key_invalid_nist_curve_mode_strict",
"tests/__init__.py::TestKeys::test_invalid_key_invalid_q_for_dsa_mode_loose",
"tests/__init__.py::TestKeys::test_invalid_key_invalid_q_for_dsa_mode_strict",
"tests/__init__.py::TestKeys::test_invalid_key_key_type_mismatch_mode_loose",
"tests/__init__.py::TestKeys::test_invalid_key_key_type_mismatch_mode_strict",
"tests/__init__.py::TestKeys::test_invalid_key_missing_quote_mode_loose",
"tests/__init__.py::TestKeys::test_invalid_key_missing_quote_mode_strict",
"tests/__init__.py::TestKeys::test_invalid_key_missing_y_from_dsa_mode_loose",
"tests/__init__.py::TestKeys::test_invalid_key_missing_y_from_dsa_mode_strict",
"tests/__init__.py::TestKeys::test_invalid_key_no_content_mode_loose",
"tests/__init__.py::TestKeys::test_invalid_key_no_content_mode_strict",
"tests/__init__.py::TestKeys::test_invalid_key_not_implemented_key_type_mode_loose",
"tests/__init__.py::TestKeys::test_invalid_key_not_implemented_key_type_mode_strict",
"tests/__init__.py::TestKeys::test_invalid_key_rsa_771_mode_strict",
"tests/__init__.py::TestKeys::test_invalid_key_rsa_key_no_match_mode_loose",
"tests/__init__.py::TestKeys::test_invalid_key_rsa_key_no_match_mode_strict",
"tests/__init__.py::TestKeys::test_invalid_key_too_long_data_mode_loose",
"tests/__init__.py::TestKeys::test_invalid_key_too_long_data_mode_strict",
"tests/__init__.py::TestKeys::test_invalid_key_too_long_dsa_16384_mode_loose",
"tests/__init__.py::TestKeys::test_invalid_key_too_long_dsa_16384_mode_strict",
"tests/__init__.py::TestKeys::test_invalid_key_too_long_dsa_4096_mode_loose",
"tests/__init__.py::TestKeys::test_invalid_key_too_long_dsa_4096_mode_strict",
"tests/__init__.py::TestKeys::test_invalid_key_too_long_ed25519_mode_loose",
"tests/__init__.py::TestKeys::test_invalid_key_too_long_ed25519_mode_strict",
"tests/__init__.py::TestKeys::test_invalid_key_too_short_data_mode_loose",
"tests/__init__.py::TestKeys::test_invalid_key_too_short_data_mode_strict",
"tests/__init__.py::TestKeys::test_invalid_key_too_short_ed25519_mode_loose",
"tests/__init__.py::TestKeys::test_invalid_key_too_short_ed25519_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_dsa_2048_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_dsa_3072_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_dsa_basic_1_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_dsa_basic_1_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_dsa_basic_2_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_dsa_basic_2_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_ecdsa_sha2_nistp256_1_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_ecdsa_sha2_nistp256_1_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_ecdsa_sha2_nistp384_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_ecdsa_sha2_nistp384_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_ecdsa_sha2_nistp521_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_ecdsa_sha2_nistp521_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_ed25516_1_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_ed25516_1_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_ed25516_2_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_ed25516_2_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_ed25516_with_command_1_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_ed25516_with_command_1_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_ed25516_with_command_2_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_ed25516_with_command_2_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_ed25516_with_command_3_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_ed25516_with_command_3_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_dsa_basic_1_rfc4716_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_dsa_basic_1_rfc4716_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_dsa_basic_2_rfc4716_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_dsa_basic_2_rfc4716_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_1299_rfc4716_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_1299_rfc4716_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_1302_rfc4716_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_1302_rfc4716_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_1305_rfc4716_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_1305_rfc4716_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_1308_rfc4716_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_1308_rfc4716_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_1311_rfc4716_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_1311_rfc4716_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_1314_rfc4716_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_1314_rfc4716_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_1317_rfc4716_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_1317_rfc4716_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_1320_rfc4716_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_1320_rfc4716_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_1323_rfc4716_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_1323_rfc4716_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_1326_rfc4716_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_1326_rfc4716_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_1329_rfc4716_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_1329_rfc4716_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_1332_rfc4716_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_1332_rfc4716_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_1611_rfc4716_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_1611_rfc4716_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_16383_rfc4716_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_16383_rfc4716_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_16384_rfc4716_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_16384_rfc4716_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_2013_rfc4716_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_2013_rfc4716_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_2016_rfc4716_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_2016_rfc4716_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_2019_rfc4716_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_2019_rfc4716_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_2022_rfc4716_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_2022_rfc4716_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_2025_rfc4716_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_2025_rfc4716_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_2028_rfc4716_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_2028_rfc4716_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_2031_rfc4716_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_2031_rfc4716_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_2034_rfc4716_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_2034_rfc4716_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_2037_rfc4716_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_2037_rfc4716_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_2040_rfc4716_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_2040_rfc4716_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_2043_rfc4716_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_2043_rfc4716_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_2046_rfc4716_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_2046_rfc4716_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_768_rfc4716_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_771_rfc4716_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_780_rfc4716_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_783_rfc4716_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_786_rfc4716_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_789_rfc4716_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_792_rfc4716_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_804_rfc4716_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_807_rfc4716_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_810_rfc4716_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_rfc4716_valid_rsa_813_rfc4716_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_1299_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_1299_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_1302_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_1302_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_1305_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_1305_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_1308_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_1308_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_1311_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_1311_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_1314_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_1314_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_1317_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_1317_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_1320_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_1320_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_1323_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_1323_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_1326_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_1326_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_1329_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_1329_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_1332_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_1332_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_1611_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_1611_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_16383_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_16383_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_16384_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_16384_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_2013_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_2013_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_2016_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_2016_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_2019_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_2019_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_2022_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_2022_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_2025_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_2025_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_2028_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_2028_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_2031_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_2031_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_2034_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_2034_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_2037_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_2037_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_2040_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_2040_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_2043_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_2043_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_2046_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_2046_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_2046_with_options_1_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_2046_with_options_1_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_2046_with_options_2_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_2046_with_options_2_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_2046_with_options_3_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_2046_with_options_3_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_2046_with_options_4_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_2046_with_options_4_mode_strict",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_768_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_771_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_780_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_783_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_786_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_789_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_792_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_804_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_807_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_810_mode_loose",
"tests/__init__.py::TestKeys::test_valid_key_valid_rsa_813_mode_loose",
"tests/__init__.py::TestOptions::test_disallow_options",
"tests/__init__.py::TestOptions::test_empty_option_beginning_4",
"tests/__init__.py::TestOptions::test_empty_option_end_3",
"tests/__init__.py::TestOptions::test_empty_option_middle_5",
"tests/__init__.py::TestOptions::test_empty_options_0",
"tests/__init__.py::TestOptions::test_equals_in_quotes_3",
"tests/__init__.py::TestOptions::test_includes_space_0",
"tests/__init__.py::TestOptions::test_includes_space_before_comma_2",
"tests/__init__.py::TestOptions::test_includes_space_multiple_1",
"tests/__init__.py::TestOptions::test_invalid_characters_in_key_parenthesis_8",
"tests/__init__.py::TestOptions::test_invalid_characters_in_key_percent_7",
"tests/__init__.py::TestOptions::test_invalid_characters_in_key_space_9",
"tests/__init__.py::TestOptions::test_multiple_options_combined_5",
"tests/__init__.py::TestOptions::test_multiple_quoted_4",
"tests/__init__.py::TestOptions::test_parameter_missing_12",
"tests/__init__.py::TestOptions::test_single_basic_1",
"tests/__init__.py::TestOptions::test_single_quoted_2",
"tests/__init__.py::TestOptions::test_unbalanced_quotes_6",
"tests/__init__.py::TestOptions::test_unbalanced_quotes_complex_11",
"tests/__init__.py::TestOptions::test_unknown_option_name_10",
"tests/__init__.py::TestAuthorizedKeys::test_comment_only_2",
"tests/__init__.py::TestAuthorizedKeys::test_disallow_options",
"tests/__init__.py::TestAuthorizedKeys::test_empty_file_0",
"tests/__init__.py::TestAuthorizedKeys::test_invalid_invalid_key_1",
"tests/__init__.py::TestAuthorizedKeys::test_invalid_lines_with_spaces_0",
"tests/__init__.py::TestAuthorizedKeys::test_lines_with_spaces_3",
"tests/__init__.py::TestAuthorizedKeys::test_single_key_1"
] | [] | 2018-03-05 11:25:57+00:00 | 4,345 |
|
okigan__awscurl-139 | diff --git a/awscurl/awscurl.py b/awscurl/awscurl.py
index cf09318..3a99f5a 100755
--- a/awscurl/awscurl.py
+++ b/awscurl/awscurl.py
@@ -16,6 +16,7 @@ import configparser
import configargparse
import requests
from requests.structures import CaseInsensitiveDict
+from urllib.parse import quote
from .utils import sha256_hash, sha256_hash_for_binary_data, sign
@@ -315,11 +316,24 @@ def __normalize_query_string(query):
for s in query.split('&')
if len(s) > 0)
- normalized = '&'.join('%s=%s' % (p[0], p[1] if len(p) > 1 else '')
+ normalized = '&'.join('%s=%s' % (aws_url_encode(p[0]), aws_url_encode(p[1]) if len(p) > 1 else '')
for p in sorted(parameter_pairs))
return normalized
+def aws_url_encode(text):
+ """
+ URI-encode each parameter name and value according to the following rules:
+ - Do not URI-encode any of the unreserved characters that RFC 3986 defines: A-Z, a-z, 0-9, hyphen (-),
+ underscore (_), period (.), and tilde (~).
+ - Percent-encode all other characters with %XY, where X and Y are hexadecimal characters (0-9 and uppercase A-F).
+ For example, the space character must be encoded as %20 (not using '+', as some encoding schemes do) and
+ extended UTF-8 characters must be in the form %XY%ZA%BC.
+ - Double-encode any equals (=) characters in parameter values.
+ """
+ return quote(text, safe='~=').replace('=', '==')
+
+
def __now():
return datetime.datetime.utcnow()
| okigan/awscurl | 6d4b7bbc9a73bbf10a652bf917163a20bc88a061 | diff --git a/tests/stages_test.py b/tests/stages_test.py
index 1f42d11..26ac703 100644
--- a/tests/stages_test.py
+++ b/tests/stages_test.py
@@ -45,6 +45,33 @@ class TestStages(TestCase):
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855")
self.assertEqual(signed_headers, "host;x-amz-date")
+ def test_task_1_create_a_canonical_request_url_encode_querystring(self):
+ """
+ Test that canonical requests correctly sort and url encode querystring parameters.
+ """
+ canonical_request, payload_hash, signed_headers = task_1_create_a_canonical_request(
+ query="arg1=true&arg3=c,b,a&arg2=false&noEncoding=ABC-abc_1.23~tilde/slash",
+ headers="{'Content-Type': 'application/json', 'Accept': 'application/xml'}",
+ port=None,
+ host="my-gateway-id.execute-api.us-east-1.amazonaws.com",
+ amzdate="20190921T022008Z",
+ method="GET",
+ data="",
+ security_token=None,
+ data_binary=False,
+ canonical_uri="/stage/my-path")
+ self.assertEqual(canonical_request, "GET\n"
+ "/stage/my-path\n"
+ "arg1=true&arg2=false&arg3=c%2Cb%2Ca&noEncoding=ABC-abc_1.23~tilde%2Fslash\n"
+ "host:my-gateway-id.execute-api.us-east-1.amazonaws.com\n"
+ "x-amz-date:20190921T022008Z\n"
+ "\n"
+ "host;x-amz-date\n"
+ "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855")
+ self.assertEqual(payload_hash,
+ "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855")
+ self.assertEqual(signed_headers, "host;x-amz-date")
+
def test_task_2_create_the_string_to_sign(self):
"""
Test the next function that is creating a string in exactly the same way as AWS is on the
diff --git a/tests/unit_test.py b/tests/unit_test.py
index dd06bf1..38b96ae 100755
--- a/tests/unit_test.py
+++ b/tests/unit_test.py
@@ -2,14 +2,13 @@
# -*- coding: UTF-8 -*-
import datetime
-import logging
import sys
from unittest import TestCase
from mock import patch
-from awscurl.awscurl import make_request
+from awscurl.awscurl import aws_url_encode, make_request
from requests.exceptions import SSLError
from requests import Response
@@ -318,3 +317,13 @@ class TestRequestResponse(TestCase):
self.assertFalse(expected in str(r.text.encode('utf-8')))
pass
+
+class TestAwsUrlEncode(TestCase):
+ def test_aws_url_encode(self):
+ self.assertEqual(aws_url_encode(""), "")
+ self.assertEqual(aws_url_encode("AZaz09-_.~"), "AZaz09-_.~")
+ self.assertEqual(aws_url_encode(" /:@[`{"), "%20%2F%3A%40%5B%60%7B")
+ self.assertEqual(aws_url_encode("a=,=b"), "a==%2C==b")
+ self.assertEqual(aws_url_encode("\u0394-\u30a1"), "%CE%94-%E3%82%A1")
+
+ pass
| Commas in querystring are not URL encoded
I've been using awscurl to call API Gateway endpoints, and it has been working great for us up until now (thanks very much for making this!).
I recently started working on an endpoint that takes comma-delimited arrays, and found that the signature is not working properly in this case.
Example failure:
```
$ awscurl -v https://my-gateway-id.execute-api.us-east-1.amazonaws.com/live/my-path?arg=a,b,c
...
('\n'
'CANONICAL REQUEST = GET\n'
'/live/my-path\n'
'arg=a,b,c\n'
'host:my-gateway-id.execute-api.us-east-1.amazonaws.com\n'
'x-amz-date:20211202T033321Z\n'
'x-amz-security-token:IQoJb3JpZ2luX2VjEEsaCXVzLWVhc3QtMSJHMEUCIQC4m8wJYpB8Xch/XdJzdKHVbgT9refFSvzJ3CeRD9HYfQIgbWPPWfYZ6bYDupK/2SIbvkxruT8ssDn4Kl0qWcCxcF0qnAMIIxAAGgw3OTkyNDI4NjU0OTEiDALfa7r3/U7W1vFxMCr5AuxtcoYbB0iq58HexqEgxxe95yduKHkab03fDBNzwWl+ZG2ATBekfJLvi7Rhzr3U2uNckMXG32x3Nj/nirtwbqfecjqLj/7XfPhBNKgXzEuJ5bQ+oIUP3heXj5G8tJ/Yvwe0eRgghiLjarwzBzvMrA7u9o0jvIGTGHZqTMM0uUPkJrDWoGpWic73fvbe7GHG0j6Hcyy/agWmgLtG7NHh5GcAwdnZih8g9nzMOO5GL0wiu805NSo6xWc2BqnP/uyHQNRAxOc3Uxd+dYtqh6NosNvX3H5x8Gzj383hB3XDbsgZiRvvk+EMwlcZlsFMg+6Mg9abx516vpBgGaKsf5yoWhK4tnsvUnNsgF+2gwBjb93z6eKP7GdHyB3iirtetQcscwkFA6mt4cl1gz8FTNcfCN6BGPQhtUO+HXfpnOY8iapateIJnhjoibELSbcNYf9ql55Xm7bvOknGAJ6HCZvp3mpM/x/X7N6e+U0sdWtzVVFNt82cY/c3BknZML7UoI0GOqYB48W1RlChDe3KjQsHrKtTdgXBGdxU1IYbHdVSwzg9t3ZewwHEpVjfF77LQ0oSRD4ROuIC9cbAXXmr/QCPqpJpFaLtqFNlVCyLpAEygCLsXN+mxGQFj6laGmZR8nEVZrsnzZy1zhOEMOfhPZWQrULbaZeJ/ZtVWto3gnQ/Rl60H52jwf8ccU2EUijMLjlRgOH8MtAnS9WCbTKur07cxK4PXLVG21DTBw==\n'
'\n'
'host;x-amz-date;x-amz-security-token\n'
'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855')
...
{"message":"The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.\n\nThe Canonical String for this request should have been\n'GET\n/live/my-path\narg=a%2Cb%2Cc\nhost:my-gateway-id.execute-api.us-east-1.amazonaws.com\nx-amz-date:20211202T033321Z\nx-amz-security-token:IQoJb3JpZ2luX2VjEEsaCXVzLWVhc3QtMSJHMEUCIQC4m8wJYpB8Xch/XdJzdKHVbgT9refFSvzJ3CeRD9HYfQIgbWPPWfYZ6bYDupK/2SIbvkxruT8ssDn4Kl0qWcCxcF0qnAMIIxAAGgw3OTkyNDI4NjU0OTEiDALfa7r3/U7W1vFxMCr5AuxtcoYbB0iq58HexqEgxxe95yduKHkab03fDBNzwWl+ZG2ATBekfJLvi7Rhzr3U2uNckMXG32x3Nj/nirtwbqfecjqLj/7XfPhBNKgXzEuJ5bQ+oIUP3heXj5G8tJ/Yvwe0eRgghiLjarwzBzvMrA7u9o0jvIGTGHZqTMM0uUPkJrDWoGpWic73fvbe7GHG0j6Hcyy/agWmgLtG7NHh5GcAwdnZih8g9nzMOO5GL0wiu805NSo6xWc2BqnP/uyHQNRAxOc3Uxd+dYtqh6NosNvX3H5x8Gzj383hB3XDbsgZiRvvk+EMwlcZlsFMg+6Mg9abx516vpBgGaKsf5yoWhK4tnsvUnNsgF+2gwBjb93z6eKP7GdHyB3iirtetQcscwkFA6mt4cl1gz8FTNcfCN6BGPQhtUO+HXfpnOY8iapateIJnhjoibELSbcNYf9ql55Xm7bvOknGAJ6HCZvp3mpM/x/X7N6e+U0sdWtzVVFNt82cY/c3BknZML7UoI0GOqYB48W1RlChDe3KjQsHrKtTdgXBGdxU1IYbHdVSwzg9t3ZewwHEpVjfF77LQ0oSRD4ROuIC9cbAXXmr/QCPqpJpFaLtqFNlVCyLpAEygCLsXN+mxGQFj6laGmZR8nEVZrsnzZy1zhOEMOfhPZWQrULbaZeJ/ZtVWto3gnQ/Rl60H52jwf8ccU2EUijMLjlRgOH8MtAnS9WCbTKur07cxK4PXLVG21DTBw==\n\nhost;x-amz-date;x-amz-security-token\ne3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'\n\nThe String-to-Sign should have been\n'AWS4-HMAC-SHA256\n20211202T033321Z\n20211202/us-east-1/execute-api/aws4_request\n38b3266af08b8f9f119ffed742e0063da244001dbdf2331c42f4f1af695e3e64'\n"}
```
Reviewing [sigv4-create-canonical-request.html](https://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html), it says:
> Percent-encode all other characters with %XY, where X and Y are hexadecimal characters (0-9 and uppercase A-F). For example, the space character must be encoded as %20 (not using '+', as some encoding schemes do) and extended UTF-8 characters must be in the form %XY%ZA%BC.
In my case, I believe that means it should be sending `arg=a%2Cb%2Cc` instead of `arg=a,b,c`
Testing locally, the following patch appears to fix things for me, but I'm not sure how much fallout this might cause for other use cases:
```
diff --git a/awscurl/awscurl.py b/awscurl/awscurl.py
index cf09318..66a14c4 100755
--- a/awscurl/awscurl.py
+++ b/awscurl/awscurl.py
@@ -16,6 +16,7 @@ import configparser
import configargparse
import requests
from requests.structures import CaseInsensitiveDict
+from urllib.parse import urlencode
from .utils import sha256_hash, sha256_hash_for_binary_data, sign
@@ -315,9 +316,9 @@ def __normalize_query_string(query):
for s in query.split('&')
if len(s) > 0)
- normalized = '&'.join('%s=%s' % (p[0], p[1] if len(p) > 1 else '')
- for p in sorted(parameter_pairs))
- return normalized
+ normalized_pairs = [(p[0], p[1] if len(p) > 1 else '')
+ for p in [p for p in sorted(parameter_pairs)]]
+ return urlencode(normalized_pairs)
def __now():
```
| 0.0 | [
"tests/stages_test.py::TestStages::test_task_1_create_a_canonical_request",
"tests/stages_test.py::TestStages::test_task_4_build_auth_headers_for_the_request",
"tests/stages_test.py::TestStages::test_task_1_create_a_canonical_request_url_encode_querystring",
"tests/stages_test.py::TestStages::test_task_3_calculate_the_signature",
"tests/stages_test.py::TestStages::test_task_2_create_the_string_to_sign",
"tests/unit_test.py::TestMakeRequestWithBinaryData::test_make_request",
"tests/unit_test.py::TestMakeRequestWithToken::test_make_request",
"tests/unit_test.py::TestMakeRequest::test_make_request",
"tests/unit_test.py::TestAwsUrlEncode::test_aws_url_encode",
"tests/unit_test.py::TestMakeRequestVerifySSLPass::test_make_request",
"tests/unit_test.py::TestHostFromHeaderUsedInCanonicalHeader::test_make_request",
"tests/unit_test.py::TestMakeRequestVerifySSLRaises::test_make_request",
"tests/unit_test.py::TestRequestResponse::test_make_request",
"tests/unit_test.py::TestMakeRequestWithTokenAndBinaryData::test_make_request"
] | [] | 2021-12-03 18:29:48+00:00 | 4,346 |
|
okigan__awscurl-153 | diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml
index 92203b6..5557bcb 100644
--- a/.github/workflows/codeql-analysis.yml
+++ b/.github/workflows/codeql-analysis.yml
@@ -34,7 +34,7 @@ jobs:
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
- uses: github/codeql-action/init@v1
+ uses: github/codeql-action/init@v2
with:
languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file.
@@ -45,7 +45,7 @@ jobs:
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
- uses: github/codeql-action/autobuild@v1
+ uses: github/codeql-action/autobuild@v2
# ℹ️ Command-line programs to run using the OS shell.
# 📚 https://git.io/JvXDl
@@ -59,4 +59,4 @@ jobs:
# make release
- name: Perform CodeQL Analysis
- uses: github/codeql-action/analyze@v1
+ uses: github/codeql-action/analyze@v2
diff --git a/.github/workflows/pythonapp.yml b/.github/workflows/pythonapp.yml
index 33c8473..a5bd13d 100644
--- a/.github/workflows/pythonapp.yml
+++ b/.github/workflows/pythonapp.yml
@@ -6,8 +6,11 @@ jobs:
build:
strategy:
matrix:
- runs-on: [ubuntu-20.04, macOS-latest]
- python-version: [ '3.6', '3.8', '3.9']
+ runs-on: [ubuntu-20.04, ubuntu-latest, macOS-latest]
+ python-version: [ '3.6', '3.8', '3.9', '3.11']
+ exclude:
+ - runs-on: ubuntu-latest
+ python-version: '3.6'
fail-fast: false
runs-on: ${{ matrix.runs-on }}
@@ -37,8 +40,11 @@ jobs:
# flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics
# # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide
# flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics
+ - name: Check with pycodestyle
+ run: |
+ pycodestyle -v awscurl
- name: Test with pytest
run: |
- pytest -v --cov=awscurl --cov-fail-under=77 --cov-report html --cov-report annotate
+ pytest -v --cov=awscurl --cov-fail-under=77 --cov-report html
- name: Test with tox
run: tox -vv
diff --git a/.travis.yml b/.travis.yml
index d9438ae..8fc67bd 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,6 +1,5 @@
language: python
python:
- - "2.7"
- "3.6"
- "3.7"
- "3.8"
@@ -16,4 +15,4 @@ env:
# command to run tests
script:
- pycodestyle -v awscurl
- - pytest -v --cov=awscurl --cov-fail-under=77 --cov-report html --cov-report annotate
+ - pytest -v --cov=awscurl --cov-fail-under=77 --cov-report html
diff --git a/README.md b/README.md
index 929539c..bcbe579 100644
--- a/README.md
+++ b/README.md
@@ -1,7 +1,7 @@
# awscurl [](https://github.com/sponsors/okigan) [](https://www.paypal.com/donate/?business=UDN4FL55J34QC&amount=25) [](https://www.buymeacoffee.com/okigan)
[](https://pypi.python.org/pypi/awscurl)
-[](https://travis-ci.org/okigan/awscurl)
+[](https://github.com/okigan/awscurl)
[](https://hub.docker.com/r/okigan/awscurl)

diff --git a/awscurl/awscurl.py b/awscurl/awscurl.py
index c437d7a..0f1cebc 100755
--- a/awscurl/awscurl.py
+++ b/awscurl/awscurl.py
@@ -145,7 +145,7 @@ def make_request(method,
def remove_default_port(parsed_url):
- default_ports = { 'http': 80, 'https': 443 }
+ default_ports = {'http': 80, 'https': 443}
if any(parsed_url.scheme == scheme and parsed_url.port == port
for scheme, port in default_ports.items()):
host = parsed_url.hostname
@@ -359,7 +359,7 @@ def __send_request(uri, data, headers, method, verify, allow_redirects):
__log('\nBEGIN REQUEST++++++++++++++++++++++++++++++++++++')
__log('Request URL = ' + uri)
- if (verify == False):
+ if (verify is False):
import urllib3
urllib3.disable_warnings()
@@ -469,7 +469,7 @@ def inner_main(argv):
# https://github.com/boto/botocore/blob/c76553d3158b083d818f88c898d8f6d7918478fd/botocore/credentials.py#L260-262
parser.add_argument('--security_token', env_var='AWS_SECURITY_TOKEN')
parser.add_argument('--session_token', env_var='AWS_SESSION_TOKEN')
- parser.add_argument('-L', '--location', action='store_true', default=False,
+ parser.add_argument('-L', '--location', action='store_true', default=False,
help="Follow redirects")
parser.add_argument('uri')
@@ -531,12 +531,12 @@ def inner_main(argv):
elif IS_VERBOSE:
pprint.PrettyPrinter(stream=sys.stderr).pprint(response.headers)
pprint.PrettyPrinter(stream=sys.stderr).pprint('')
-
+
print(response.text)
- response.raise_for_status()
+ exit_code = 0 if response.ok else 1
- return 0
+ return exit_code
def main():
| okigan/awscurl | 27f949d3faa803f0bad5a4676513dd31d1f8c7b9 | diff --git a/tests/integration_test.py b/tests/integration_test.py
index d1aac31..092c2e6 100644
--- a/tests/integration_test.py
+++ b/tests/integration_test.py
@@ -21,7 +21,6 @@ print(f'sys.path2={sys.path}')
import pytest
from mock import patch
-from requests import HTTPError
from awscurl.awscurl import make_request, inner_main
@@ -123,5 +122,8 @@ class TestMakeRequestWithTokenAndNonEnglishData(TestCase):
class TestInnerMainMethod(TestCase):
maxDiff = None
- with pytest.raises(HTTPError):
- inner_main(['--verbose', '--service', 's3', 'https://awscurl-sample-bucket.s3.amazonaws.com'])
\ No newline at end of file
+ def test_exit_code(self, *args, **kwargs):
+ self.assertEqual(
+ inner_main(['--verbose', '--service', 's3', 'https://awscurl-sample-bucket.s3.amazonaws.com']),
+ 1
+ )
| raise_for_request should not be used for non-successful response
Hi there,
I'm wondering why you elected to use `response.raise_for_status()` after receiving the response - https://github.com/okigan/awscurl/blob/184d7735b57d5c71f75f52a85cc8c8909226b6d5/awscurl/awscurl.py#L537
Would it not make more sense to return an exit code that is either 0 for a successful request or non-zero for a non-successful request?
This would mean tools such as jq etc could still parse the response without the Python traceback interfering where a non-successful status code may still be anticipated.
Happy to open a PR if it makes sense. | 0.0 | [
"tests/integration_test.py::TestInnerMainMethod::test_exit_code"
] | [
"tests/integration_test.py::TestMakeRequestWithToken::test_make_request",
"tests/integration_test.py::TestMakeRequestWithTokenAndNonEnglishData::test_make_request",
"tests/integration_test.py::TestMakeRequestWithTokenAndEnglishData::test_make_request",
"tests/integration_test.py::TestMakeRequestWithTokenAndBinaryData::test_make_request"
] | 2023-04-23 10:17:27+00:00 | 4,347 |
|
omaciel__fauxfactory-103 | diff --git a/fauxfactory/factories/strings.py b/fauxfactory/factories/strings.py
index 5e38b52..67f6e50 100644
--- a/fauxfactory/factories/strings.py
+++ b/fauxfactory/factories/strings.py
@@ -68,28 +68,35 @@ def gen_string(str_type, length=None, validator=None, default=None, tries=10):
@check_len
@check_validation
-def gen_alpha(length=10):
+def gen_alpha(length=10, start=None, separator=''):
"""Return a random string made up of alpha characters.
:param int length: Length for random data.
+ :param str start: Random data start with.
+ :param char separator: Separator for start and random data.
:returns: A random string made up of alpha characters.
:rtype: str
"""
random.seed()
output_string = ''.join(
- random.choice(string.ascii_letters) for i in range(length)
+ random.choice(string.ascii_letters) for _ in range(length)
)
+ if start:
+ output_string = '{0}{1}{2}'.format(
+ start, separator, output_string)[0:length]
return output_string
@check_len
@check_validation
-def gen_alphanumeric(length=10):
+def gen_alphanumeric(length=10, start=None, separator=''):
"""Return a random string made up of alpha and numeric characters.
:param int length: Length for random data.
+ :param str start: Random data start with.
+ :param char separator: Separator for start and random data.
:returns: A random string made up of alpha and numeric characters.
:rtype: str
@@ -98,19 +105,24 @@ def gen_alphanumeric(length=10):
output_string = ''.join(
random.choice(
string.ascii_letters + string.digits
- ) for i in range(length))
+ ) for _ in range(length))
+ if start:
+ output_string = '{0}{1}{2}'.format(
+ start, separator, output_string)[0:length]
return output_string
@check_len
@check_validation
-def gen_cjk(length=10):
+def gen_cjk(length=10, start=None, separator=''):
"""Return a random string made up of CJK characters.
(Source: Wikipedia - CJK Unified Ideographs)
:param int length: Length for random data.
+ :param str start: Random data start with.
+ :param char separator: Separator for start and random data.
:returns: A random string made up of CJK characters.
:rtype: str
@@ -120,15 +132,22 @@ def gen_cjk(length=10):
# Generate codepoints, then convert the codepoints to a string. The
# valid range of CJK codepoints is 0x4E00 - 0x9FCC, inclusive.
codepoints = [random.randint(0x4E00, 0x9FCC) for _ in range(length)]
- return ''.join(chr(codepoint) for codepoint in codepoints)
+ output_string = ''.join(chr(codepoint) for codepoint in codepoints)
+
+ if start:
+ output_string = '{0}{1}{2}'.format(
+ start, separator, output_string)[0:length]
+ return output_string
@check_len
@check_validation
-def gen_cyrillic(length=10):
+def gen_cyrillic(length=10, start=None, separator=''):
"""Return a random string made up of Cyrillic characters.
:param int length: Length for random data.
+ :param str start: Random data start with.
+ :param char separator: Separator for start and random data.
:returns: A random string made up of Cyrillic characters.
:rtype: str
@@ -136,9 +155,14 @@ def gen_cyrillic(length=10):
random.seed()
# Generate codepoints, then convert the codepoints to a string. The
- # valid range of Cyrillic codepoints is 0x410 - 0x4ff, inclusive.
+ # valid range of Cyrillic codepoints is 0x0400 - 0x04FF, inclusive.
codepoints = [random.randint(0x0400, 0x04FF) for _ in range(length)]
- return ''.join(chr(codepoint) for codepoint in codepoints)
+ output_string = ''.join(chr(codepoint) for codepoint in codepoints)
+
+ if start:
+ output_string = '{0}{1}{2}'.format(
+ start, separator, output_string)[0:length]
+ return output_string
@check_len
@@ -236,12 +260,14 @@ def gen_iplum(words=None, paragraphs=None):
@check_len
@check_validation
-def gen_latin1(length=10):
+def gen_latin1(length=10, start=None, separator=''):
"""Return a random string made up of UTF-8 characters.
(Font: Wikipedia - Latin-1 Supplement Unicode Block)
:param int length: Length for random data.
+ :param str start: Random data start with.
+ :param char separator: Separator for start and random data.
:returns: A random string made up of ``Latin1`` characters.
:rtype: str
@@ -264,31 +290,45 @@ def gen_latin1(length=10):
chr(random.choice(output_array)) for _ in range(length)
)
+ if start:
+ output_string = '{0}{1}{2}'.format(
+ start, separator, output_string)[0:length]
return output_string
@check_len
@check_validation
-def gen_numeric_string(length=10):
+def gen_numeric_string(length=10, start=None, separator=''):
"""Return a random string made up of numbers.
:param int length: Length for random data.
+ :param str start: Random data start with.
+ :param char separator: Separator for start and random data.
:returns: A random string made up of numbers.
:rtype: str
"""
random.seed()
- return ''.join(random.choice(string.digits) for _ in range(length))
+ output_string = ''.join(
+ random.choice(string.digits) for _ in range(length)
+ )
+
+ if start:
+ output_string = '{0}{1}{2}'.format(
+ start, separator, output_string)[0:length]
+ return output_string
@check_len
@check_validation
-def gen_utf8(length=10, smp=True):
+def gen_utf8(length=10, smp=True, start=None, separator=''):
"""Return a random string made up of UTF-8 letters characters.
Follows `RFC 3629`_.
:param int length: Length for random data.
+ :param str start: Random data start with.
+ :param char separator: Separator for start and random data.
:param bool smp: Include Supplementary Multilingual Plane (SMP)
characters
:returns: A random string made up of ``UTF-8`` letters characters.
@@ -299,17 +339,33 @@ def gen_utf8(length=10, smp=True):
"""
UNICODE_LETTERS = [c for c in unicode_letters_generator(smp)]
random.seed()
- return ''.join([random.choice(UNICODE_LETTERS) for _ in range(length)])
+ output_string = ''.join(
+ [random.choice(UNICODE_LETTERS) for _ in range(length)]
+ )
+
+ if start:
+ output_string = '{0}{1}{2}'.format(
+ start, separator, output_string)[0:length]
+ return output_string
@check_len
@check_validation
-def gen_special(length=10):
+def gen_special(length=10, start=None, separator=''):
"""Return a random special characters string.
:param int length: Length for random data.
+ :param str start: Random data start with.
+ :param char separator: Separator for start and random data.
:returns: A random string made up of special characters.
:rtype: str
"""
random.seed()
- return ''.join(random.choice(string.punctuation) for _ in range(length))
+ output_string = ''.join(
+ random.choice(string.punctuation) for _ in range(length)
+ )
+
+ if start:
+ output_string = '{0}{1}{2}'.format(
+ start, separator, output_string)[0:length]
+ return output_string
| omaciel/fauxfactory | df28434be0baed3e68e9c26986ff67f78b66d5b0 | diff --git a/tests/test_strings.py b/tests/test_strings.py
index 7b977a3..2095fe4 100644
--- a/tests/test_strings.py
+++ b/tests/test_strings.py
@@ -1,6 +1,7 @@
"""Tests for all string generators."""
import string
import unicodedata
+from random import randint
import pytest
@@ -150,3 +151,14 @@ def test_special_string():
special_str = gen_special()
for char in special_str:
assert char in VALID_CHARS
+
+
[email protected]('fnc', GENERATORS[1:])
+def test_start_string(fnc):
+ """"String generated has start with specific keyword."""
+ start = fnc(randint(1, 5))
+ separator = fnc(1)
+ random_str = fnc(start=start, separator=separator)
+ assert start == random_str[0:len(start)]
+ assert separator == random_str[len(start)]
+ assert len(random_str) == 10
| [Proposal] some extra param to avoid string formatting
While using some string category method user like to matriculate string; they want string `start` with something. Its most common use-case; which, I observed while using `fauxfactory` in daily life. It will reduce lots of indirect string formatting.
```
def gen_alphanumeric(length=10, start=None):
pass
```
small example:
```
In [1]: from fauxfactory import gen_alpha, gen_alphanumeric
In [2]: gen_alpha(start="volume")
Out[2]: 'volume_DGDvJNxZmO'
In [3]: gen_alpha(3, start="og")
Out[3]: 'og_OpD'
In [4]: gen_alphanumeric(start="vol")
Out[4]: 'vol_DJBGf7Af2L'
In [5]: gen_alphanumeric(5, start="vol")
Out[5]: 'vol_3pmw0'
```
This is basic example. we can go for more enhancement, we can even take care of `string length`. | 0.0 | [
"tests/test_strings.py::test_start_string[gen_alpha]",
"tests/test_strings.py::test_start_string[gen_alphanumeric]",
"tests/test_strings.py::test_start_string[gen_cjk]",
"tests/test_strings.py::test_start_string[gen_cyrillic]",
"tests/test_strings.py::test_start_string[gen_latin1]",
"tests/test_strings.py::test_start_string[gen_numeric_string]",
"tests/test_strings.py::test_start_string[gen_utf8]",
"tests/test_strings.py::test_start_string[gen_special]"
] | [
"tests/test_strings.py::test_positive_string[gen_html]",
"tests/test_strings.py::test_positive_string[gen_alpha]",
"tests/test_strings.py::test_positive_string[gen_alphanumeric]",
"tests/test_strings.py::test_positive_string[gen_cjk]",
"tests/test_strings.py::test_positive_string[gen_cyrillic]",
"tests/test_strings.py::test_positive_string[gen_latin1]",
"tests/test_strings.py::test_positive_string[gen_numeric_string]",
"tests/test_strings.py::test_positive_string[gen_utf8]",
"tests/test_strings.py::test_positive_string[gen_special]",
"tests/test_strings.py::test_fixed_length_positional[gen_alpha]",
"tests/test_strings.py::test_fixed_length_positional[gen_alphanumeric]",
"tests/test_strings.py::test_fixed_length_positional[gen_cjk]",
"tests/test_strings.py::test_fixed_length_positional[gen_cyrillic]",
"tests/test_strings.py::test_fixed_length_positional[gen_latin1]",
"tests/test_strings.py::test_fixed_length_positional[gen_numeric_string]",
"tests/test_strings.py::test_fixed_length_positional[gen_utf8]",
"tests/test_strings.py::test_fixed_length_positional[gen_special]",
"tests/test_strings.py::test_fixed_length_keyword[gen_alpha]",
"tests/test_strings.py::test_fixed_length_keyword[gen_alphanumeric]",
"tests/test_strings.py::test_fixed_length_keyword[gen_cjk]",
"tests/test_strings.py::test_fixed_length_keyword[gen_cyrillic]",
"tests/test_strings.py::test_fixed_length_keyword[gen_latin1]",
"tests/test_strings.py::test_fixed_length_keyword[gen_numeric_string]",
"tests/test_strings.py::test_fixed_length_keyword[gen_utf8]",
"tests/test_strings.py::test_fixed_length_keyword[gen_special]",
"tests/test_strings.py::test_negative_length[gen_html]",
"tests/test_strings.py::test_negative_length[gen_alpha]",
"tests/test_strings.py::test_negative_length[gen_alphanumeric]",
"tests/test_strings.py::test_negative_length[gen_cjk]",
"tests/test_strings.py::test_negative_length[gen_cyrillic]",
"tests/test_strings.py::test_negative_length[gen_latin1]",
"tests/test_strings.py::test_negative_length[gen_numeric_string]",
"tests/test_strings.py::test_negative_length[gen_utf8]",
"tests/test_strings.py::test_negative_length[gen_special]",
"tests/test_strings.py::test_zero_length[gen_html]",
"tests/test_strings.py::test_zero_length[gen_alpha]",
"tests/test_strings.py::test_zero_length[gen_alphanumeric]",
"tests/test_strings.py::test_zero_length[gen_cjk]",
"tests/test_strings.py::test_zero_length[gen_cyrillic]",
"tests/test_strings.py::test_zero_length[gen_latin1]",
"tests/test_strings.py::test_zero_length[gen_numeric_string]",
"tests/test_strings.py::test_zero_length[gen_utf8]",
"tests/test_strings.py::test_zero_length[gen_special]",
"tests/test_strings.py::test_alpha_length[gen_html]",
"tests/test_strings.py::test_alpha_length[gen_alpha]",
"tests/test_strings.py::test_alpha_length[gen_alphanumeric]",
"tests/test_strings.py::test_alpha_length[gen_cjk]",
"tests/test_strings.py::test_alpha_length[gen_cyrillic]",
"tests/test_strings.py::test_alpha_length[gen_latin1]",
"tests/test_strings.py::test_alpha_length[gen_numeric_string]",
"tests/test_strings.py::test_alpha_length[gen_utf8]",
"tests/test_strings.py::test_alpha_length[gen_special]",
"tests/test_strings.py::test_alphanumeric_length[gen_html]",
"tests/test_strings.py::test_alphanumeric_length[gen_alpha]",
"tests/test_strings.py::test_alphanumeric_length[gen_alphanumeric]",
"tests/test_strings.py::test_alphanumeric_length[gen_cjk]",
"tests/test_strings.py::test_alphanumeric_length[gen_cyrillic]",
"tests/test_strings.py::test_alphanumeric_length[gen_latin1]",
"tests/test_strings.py::test_alphanumeric_length[gen_numeric_string]",
"tests/test_strings.py::test_alphanumeric_length[gen_utf8]",
"tests/test_strings.py::test_alphanumeric_length[gen_special]",
"tests/test_strings.py::test_empty_length[gen_html]",
"tests/test_strings.py::test_empty_length[gen_alpha]",
"tests/test_strings.py::test_empty_length[gen_alphanumeric]",
"tests/test_strings.py::test_empty_length[gen_cjk]",
"tests/test_strings.py::test_empty_length[gen_cyrillic]",
"tests/test_strings.py::test_empty_length[gen_latin1]",
"tests/test_strings.py::test_empty_length[gen_numeric_string]",
"tests/test_strings.py::test_empty_length[gen_utf8]",
"tests/test_strings.py::test_empty_length[gen_special]",
"tests/test_strings.py::test_space_length[gen_html]",
"tests/test_strings.py::test_space_length[gen_alpha]",
"tests/test_strings.py::test_space_length[gen_alphanumeric]",
"tests/test_strings.py::test_space_length[gen_cjk]",
"tests/test_strings.py::test_space_length[gen_cyrillic]",
"tests/test_strings.py::test_space_length[gen_latin1]",
"tests/test_strings.py::test_space_length[gen_numeric_string]",
"tests/test_strings.py::test_space_length[gen_utf8]",
"tests/test_strings.py::test_space_length[gen_special]",
"tests/test_strings.py::test_gen_string[html]",
"tests/test_strings.py::test_gen_string[alpha]",
"tests/test_strings.py::test_gen_string[alphanumeric]",
"tests/test_strings.py::test_gen_string[cjk]",
"tests/test_strings.py::test_gen_string[cyrillic]",
"tests/test_strings.py::test_gen_string[latin1]",
"tests/test_strings.py::test_gen_string[numeric]",
"tests/test_strings.py::test_gen_string[utf8]",
"tests/test_strings.py::test_gen_string[punctuation]",
"tests/test_strings.py::test_gen_string_fixed_length_positional[alpha]",
"tests/test_strings.py::test_gen_string_fixed_length_positional[alphanumeric]",
"tests/test_strings.py::test_gen_string_fixed_length_positional[cjk]",
"tests/test_strings.py::test_gen_string_fixed_length_positional[cyrillic]",
"tests/test_strings.py::test_gen_string_fixed_length_positional[latin1]",
"tests/test_strings.py::test_gen_string_fixed_length_positional[numeric]",
"tests/test_strings.py::test_gen_string_fixed_length_positional[utf8]",
"tests/test_strings.py::test_gen_string_fixed_length_positional[punctuation]",
"tests/test_strings.py::test_gen_string_fixed_length_keyword[alpha]",
"tests/test_strings.py::test_gen_string_fixed_length_keyword[alphanumeric]",
"tests/test_strings.py::test_gen_string_fixed_length_keyword[cjk]",
"tests/test_strings.py::test_gen_string_fixed_length_keyword[cyrillic]",
"tests/test_strings.py::test_gen_string_fixed_length_keyword[latin1]",
"tests/test_strings.py::test_gen_string_fixed_length_keyword[numeric]",
"tests/test_strings.py::test_gen_string_fixed_length_keyword[utf8]",
"tests/test_strings.py::test_gen_string_fixed_length_keyword[punctuation]",
"tests/test_strings.py::test_chars_in_letters_category",
"tests/test_strings.py::test_bmp_chars_only",
"tests/test_strings.py::test_invalid_string_type",
"tests/test_strings.py::test_special_string"
] | 2019-02-18 18:43:06+00:00 | 4,348 |
|
omaciel__fauxfactory-87 | diff --git a/fauxfactory/__init__.py b/fauxfactory/__init__.py
index a20be48..2d55c03 100644
--- a/fauxfactory/__init__.py
+++ b/fauxfactory/__init__.py
@@ -9,7 +9,6 @@ import sys
import unicodedata
import uuid
import warnings
-
from collections import Iterable
from functools import wraps
@@ -103,15 +102,67 @@ def _unicode_letters_generator():
UNICODE_LETTERS = [c for c in _unicode_letters_generator()]
+def _check_validation(fcn):
+ """Simple decorator to validate values generate by fcn accordingly to
+ parameters `validator`, `default` and `tries`
+
+ :param fcn: function to be enhanced
+ :return: decorated function
+ """
+
+ @wraps(fcn)
+ def validate(*args, **kwargs):
+ validator = kwargs.get('validator')
+ default = kwargs.get('default')
+ tries = kwargs.get('tries', 10)
+ if validator and default is None:
+ raise ValueError('If "validator" param is defined, "default" '
+ 'parameter must not be None')
+ if validator is None:
+ def validator_fcn(_):
+ return True
+ else:
+ validator_fcn = validator
+
+ if not callable(validator_fcn):
+ def regex_validator(value):
+ return re.match(validator, value)
+
+ validator_fcn = regex_validator
+
+ # Removing params related to validation but not fcn
+ for key in ('validator', 'default', 'tries'):
+ if key in kwargs:
+ kwargs.pop(key)
+
+ for _ in range(tries):
+ value = fcn(*args, **kwargs)
+ if validator_fcn(value):
+ return value
+
+ return default
+
+ return validate
+
+
# Public Functions ------------------------------------------------------------
-def gen_string(str_type, length=None):
+def gen_string(str_type, length=None, validator=None, default=None, tries=10):
"""A simple wrapper that calls other string generation methods.
:param str str_type: The type of string which should be generated.
:param int length: The length of the generated string. Must be 1 or
greater.
+ :param validator: Function or regex (str).
+ If a function it must receive one parameter and return True if value
+ can be used and False of another value need to be generated.
+ If str it will be used as regex to validate the generated value.
+ Default is None which will not validate the value.
+ :param tries: number of times validator must be called before returning
+ `default`. Default is 10.
+ :param default: If validator returns false a number of `tries` times, this
+ value is returned instead. Must be defined if validator is not None
:raises: ``ValueError`` if an invalid ``str_type`` is specified.
:returns: A string.
:rtype: str
@@ -146,10 +197,11 @@ def gen_string(str_type, length=None):
)
method = str_types_functions[str_type_lower]
if length is None:
- return method()
- return method(length)
+ return method(validator=validator, default=default, tries=tries)
+ return method(length, validator=validator, default=default, tries=tries)
+@_check_validation
def gen_alpha(length=10):
"""Returns a random string made up of alpha characters.
@@ -170,6 +222,7 @@ def gen_alpha(length=10):
return _make_unicode(output_string)
+@_check_validation
def gen_alphanumeric(length=10):
"""Returns a random string made up of alpha and numeric characters.
@@ -230,6 +283,7 @@ def gen_choice(choices):
return random.choice(choices)
+@_check_validation
def gen_cjk(length=10):
"""Returns a random string made up of CJK characters.
(Source: Wikipedia - CJK Unified Ideographs)
@@ -257,6 +311,7 @@ def gen_cjk(length=10):
return _make_unicode(output)
+@_check_validation
def gen_cyrillic(length=10):
"""Returns a random string made up of Cyrillic characters.
@@ -362,6 +417,7 @@ def gen_datetime(min_date=None, max_date=None):
return min_date + datetime.timedelta(seconds=seconds)
+@_check_validation
def gen_email(name=None, domain=None, tlds=None):
"""Generates a random email address.
@@ -488,6 +544,7 @@ def gen_iplum(words=None, paragraphs=None):
return _make_unicode(result.rstrip())
+@_check_validation
def gen_latin1(length=10):
"""Returns a random string made up of UTF-8 characters.
(Font: Wikipedia - Latin-1 Supplement Unicode Block)
@@ -542,6 +599,7 @@ def gen_negative_integer():
return gen_integer(max_value=max_value)
+@_check_validation
def gen_ipaddr(ip3=False, ipv6=False, prefix=()):
"""Generates a random IP address.
You can also specify an IP address prefix if you are interested in
@@ -599,6 +657,7 @@ def gen_ipaddr(ip3=False, ipv6=False, prefix=()):
return _make_unicode(ipaddr)
+@_check_validation
def gen_mac(delimiter=':', multicast=None, locally=None):
"""Generates a random MAC address.
@@ -647,6 +706,7 @@ def gen_mac(delimiter=':', multicast=None, locally=None):
return _make_unicode(mac)
+@_check_validation
def gen_netmask(min_cidr=1, max_cidr=31):
"""Generates a random valid netmask.
@@ -674,6 +734,7 @@ def gen_netmask(min_cidr=1, max_cidr=31):
return VALID_NETMASKS[random.randint(min_cidr, max_cidr)]
+@_check_validation
def gen_numeric_string(length=10):
"""Returns a random string made up of numbers.
@@ -723,6 +784,7 @@ def gen_time():
)
+@_check_validation
def gen_url(scheme=None, subdomain=None, tlds=None):
"""Generates a random URL address
@@ -765,6 +827,7 @@ def gen_url(scheme=None, subdomain=None, tlds=None):
return _make_unicode(url)
+@_check_validation
def gen_utf8(length=10):
"""Returns a random string made up of UTF-8 letters characters, as per
`RFC 3629`_.
@@ -783,6 +846,7 @@ def gen_utf8(length=10):
return u''.join([random.choice(UNICODE_LETTERS) for _ in range(length)])
+@_check_validation
def gen_uuid():
"""Generates a UUID string (universally unique identifiers).
@@ -796,6 +860,7 @@ def gen_uuid():
return output_uuid
+@_check_validation
def gen_html(length=10):
"""Returns a random string made up of html characters.
@@ -816,6 +881,7 @@ def gen_html(length=10):
return _make_unicode(output_string)
+@_check_validation
def gen_html_with_total_len(length=10):
"""Returns a random string made up of html characters.
This differ from fauxfactory.gen_html because length takes html tag chars
diff --git a/requirements-optional.txt b/requirements-optional.txt
index 7b50cdd..2c1ab56 100644
--- a/requirements-optional.txt
+++ b/requirements-optional.txt
@@ -3,3 +3,4 @@ coveralls
flake8
pylint
Sphinx
+mock
| omaciel/fauxfactory | 87611f293f9329ea024d93f5699c287f0725b5e5 | diff --git a/tests/test_check_validation.py b/tests/test_check_validation.py
new file mode 100644
index 0000000..8ba9460
--- /dev/null
+++ b/tests/test_check_validation.py
@@ -0,0 +1,69 @@
+# -*- coding: utf-8 -*-
+
+from sys import version_info
+
+from fauxfactory import _check_validation
+
+if version_info[0:2] == (2, 6):
+ import unittest2 as unittest
+else:
+ import unittest
+ if version_info[0] == 2:
+ from mock import Mock
+ else:
+ from unittest.mock import Mock
+
+
+@_check_validation
+def decorated_f():
+ return 'not a number'
+
+
+class CheckValidationTestCase(unittest.TestCase):
+ """_check_validation decorator tests"""
+
+ def test_no_validator_defined(self):
+ """Check result value of decorated function is returned when no
+ validator is provided
+ """
+ self.assertEqual('not a number', decorated_f())
+
+ def test_validator_defined_but_default_is_none(self):
+ """Check defining validator but not default raises an error"""
+ self.assertRaises(ValueError, decorated_f, validator=lambda _: True)
+
+ def test_regex(self):
+ """Check regex validation when validator is a string"""
+ self.assertEqual(
+ 'my default', decorated_f(validator=r'\d.*', default='my default'))
+ self.assertEqual(
+ 'not a number', decorated_f(validator=r'.*', default='my default'))
+
+ def test_callable(self):
+ """Check validation when validator is a callable"""
+ callable = Mock(return_value=False)
+
+ # Default of 10 unsuccessful tries
+ self.assertEqual(
+ 'my default',
+ decorated_f(validator=callable, default='my default')
+ )
+ callable.assert_called_with('not a number')
+ self.assertEqual(10, callable.call_count)
+
+ # 1 unsuccessful try
+ callable.reset_mock()
+ self.assertEqual(
+ 'my default',
+ decorated_f(validator=callable, default='my default', tries=1)
+ )
+ callable.assert_called_once_with('not a number')
+
+ # 1 successful try
+ callable.reset_mock()
+ callable.return_value = True
+ self.assertEqual(
+ 'not a number',
+ decorated_f(validator=callable, default='my default', tries=10)
+ )
+ callable.assert_called_once_with('not a number')
| add validator argument
Example: we want to generate names, but names cannot start with numbers.
```python
from fauxfactory import gen_string
name = gen_string(
'alpha',
validator=lambda x: not x.startswith(('1', '2', '3', '4', '5', '6', '7', '8', '9', '0')),
default='foobar',
tries=10
)
or simpler
name = gen_string(
'alpha',
validator=lambda x: not x[0].isdigit(),
default='foobar',
tries=10
)
```
So fauxfactory should accept `validator` which should return True, otherwise the value is `None` or `default`. If `tries` is set, then it retries to generate 10 times, if `tries` = `0` it tries to generate until validator is met!
BONUS: the validator must be callable or `re.Pattern` instance, so it checks for regex matching. | 0.0 | [
"tests/test_check_validation.py::CheckValidationTestCase::test_callable",
"tests/test_check_validation.py::CheckValidationTestCase::test_no_validator_defined",
"tests/test_check_validation.py::CheckValidationTestCase::test_regex",
"tests/test_check_validation.py::CheckValidationTestCase::test_validator_defined_but_default_is_none"
] | [] | 2017-03-15 13:14:22+00:00 | 4,349 |
|
omarryhan__aiogoogle-49 | diff --git a/aiogoogle/auth/utils.py b/aiogoogle/auth/utils.py
index bed0c05..aa291ae 100644
--- a/aiogoogle/auth/utils.py
+++ b/aiogoogle/auth/utils.py
@@ -3,6 +3,9 @@ __all__ = ["create_secret"]
import hashlib
import os
import datetime
+import sys
+
+from ..utils import _parse_isoformat
def create_secret(bytes_length=1024): # pragma: no cover
@@ -22,7 +25,11 @@ def _is_expired(expires_at):
if expires_at is None:
return True
if not isinstance(expires_at, datetime.datetime):
- expires_at = datetime.datetime.fromisoformat(expires_at)
+ # datetime.fromisoformat is 3.7+
+ if sys.version_info[1] <= 6:
+ expires_at = _parse_isoformat(expires_at)
+ else:
+ expires_at = datetime.fromisoformat(expires_at)
if datetime.datetime.utcnow() >= expires_at:
return True
else:
diff --git a/aiogoogle/utils.py b/aiogoogle/utils.py
index fe637f3..5f99587 100644
--- a/aiogoogle/utils.py
+++ b/aiogoogle/utils.py
@@ -1,5 +1,8 @@
__all__ = []
+import datetime
+import re
+
def _safe_getitem(dct, *keys):
for key in keys:
@@ -40,3 +43,59 @@ class _dict(dict): # pragma: no cover
def __delitem__(self, key): # pragma: no cover
super(_dict, self).__delitem__(key)
del self.__dict__[key]
+
+
+def _parse_time_components(tstr):
+ # supported format is HH[:MM[:SS[.fff[fff]]]]
+ if len(tstr) < 2:
+ raise ValueError("Invalid Isotime format")
+ hh = tstr[:2]
+ mm_ss = re.findall(r":(\d{2})", tstr)
+ ff = re.findall(r"\.(\d+)", tstr)
+ if ff and not len(ff[0]) in [3, 6]:
+ raise ValueError("Invalid Isotime format")
+ ff = ff[0] if ff else []
+
+ # ensure tstr was valid
+ if len(mm_ss) < 2 and ff:
+ raise ValueError("Invalid Isotime format")
+ parsed_str = hh + (":" + ":".join(mm_ss) if mm_ss else "") + \
+ ("." + ff if ff else "")
+ if parsed_str != tstr:
+ raise ValueError("Invalid Isotime format")
+ components = [int(hh)]
+ if mm_ss:
+ components.extend(int(t) for t in mm_ss)
+ if ff:
+ components.append(int(ff.ljust(6, "0")))
+ return components + [0] * (4 - len(components))
+
+
+def _parse_isoformat(dtstr):
+ # supported format is YYYY-mm-dd[THH[:MM[:SS[.fff[fff]]]]][+HH:MM[:SS[.ffffff]]]
+ dstr = dtstr[:10]
+ tstr = dtstr[11:]
+ try:
+ date = datetime.datetime.strptime(dstr, "%Y-%m-%d")
+ except ValueError as e:
+ raise ValueError("Invalid Isotime format") from e
+
+ if tstr:
+ # check for time zone
+ tz_pos = (tstr.find("-") + 1 or tstr.find("+") + 1)
+ if tz_pos > 0:
+ tzsign = -1 if tstr[tz_pos - 1] == "-" else 1
+ tz_comps = _parse_time_components(tstr[tz_pos:])
+ tz = tzsign * datetime.timedelta(
+ hours=tz_comps[0], minutes=tz_comps[1],
+ seconds=tz_comps[2], microseconds=tz_comps[3])
+ tstr = tstr[:tz_pos - 1]
+ else:
+ tz = datetime.timedelta(0)
+ time_comps = _parse_time_components(tstr)
+ date = date.replace(hour=time_comps[0], minute=time_comps[1],
+ second=time_comps[2], microsecond=time_comps[3])
+ date -= tz
+ elif len(dtstr) == 11:
+ raise ValueError("Invalid Isotime format")
+ return date
| omarryhan/aiogoogle | 8410dcf58716647f29cef2d3eeb548526d950d9f | diff --git a/tests/test_units/test_dateutil.py b/tests/test_units/test_dateutil.py
new file mode 100644
index 0000000..ebd91db
--- /dev/null
+++ b/tests/test_units/test_dateutil.py
@@ -0,0 +1,66 @@
+import pytest
+
+from datetime import datetime
+from aiogoogle.utils import _parse_isoformat
+
+
+def test_iso_parser1():
+ assert _parse_isoformat("2021-02-06") == datetime(2021, 2, 6)
+
+
+def test_iso_parser2():
+ assert _parse_isoformat("2021-02-06T14") == datetime(2021, 2, 6, 14)
+
+
+def test_iso_parser3():
+ assert _parse_isoformat("2021-02-06T14:52") == datetime(2021, 2, 6, 14, 52)
+
+
+def test_iso_parser4():
+ assert _parse_isoformat("2021-02-06T14:52:26") == \
+ datetime(2021, 2, 6, 14, 52, 26)
+
+
+def test_iso_parser5():
+ assert _parse_isoformat("2021-02-06T14:52:26.123") == \
+ datetime(2021, 2, 6, 14, 52, 26, 123000)
+
+
+def test_iso_parser6():
+ assert _parse_isoformat("2021-02-06T14:52:26.123456") == \
+ datetime(2021, 2, 6, 14, 52, 26, 123456)
+
+
+def test_iso_parser7():
+ assert _parse_isoformat("2021-02-06T14:52:26.123456+01:30") == \
+ datetime(2021, 2, 6, 13, 22, 26, 123456)
+
+
+def test_iso_parser8():
+ assert _parse_isoformat("2021-02-06T14:52:26.123456-01:00") == \
+ datetime(2021, 2, 6, 15, 52, 26, 123456)
+
+
+def test_iso_malformed1():
+ with pytest.raises(ValueError):
+ _parse_isoformat("2021-02T14:52")
+
+
+def test_iso_malformed2():
+ with pytest.raises(ValueError):
+ _parse_isoformat("2021-02-06T")
+
+
+def test_iso_malformed3():
+ with pytest.raises(ValueError):
+ _parse_isoformat("2021-02-06T14.123")
+
+
+def test_iso_malformed4():
+ with pytest.raises(ValueError):
+ _parse_isoformat("2021-02-06T14:52.123456")
+
+
+def test_iso_malformed5():
+ with pytest.raises(ValueError):
+ _parse_isoformat("2021-02-06T14:52:26.1234")
| Token expiry check broken in Python 3.6 and lower
I am not entirely sure if this is a bug or if there simply is no intention to support Python 3.6, but given I was able to `pip install` it into my Python 3.6.6 environment I suspect the former, so here we go:
[Line 25 of `auth.utils`](https://github.com/omarryhan/aiogoogle/blob/master/aiogoogle/auth/utils.py#L25) will not work for Python 3.6 and lower, as `.fromisoformat` was introduced to the `datetime` module in version 3.7. You'd need to use something like `.strptime(expires_at, '%Y-%m-%dT%H:%M:%S.%f')` instead for lower versions
I can submit a PR for this if it is deemed a bug indeed | 0.0 | [
"tests/test_units/test_dateutil.py::test_iso_parser1",
"tests/test_units/test_dateutil.py::test_iso_parser2",
"tests/test_units/test_dateutil.py::test_iso_parser3",
"tests/test_units/test_dateutil.py::test_iso_parser4",
"tests/test_units/test_dateutil.py::test_iso_parser5",
"tests/test_units/test_dateutil.py::test_iso_parser6",
"tests/test_units/test_dateutil.py::test_iso_parser7",
"tests/test_units/test_dateutil.py::test_iso_parser8",
"tests/test_units/test_dateutil.py::test_iso_malformed1",
"tests/test_units/test_dateutil.py::test_iso_malformed2",
"tests/test_units/test_dateutil.py::test_iso_malformed3",
"tests/test_units/test_dateutil.py::test_iso_malformed4",
"tests/test_units/test_dateutil.py::test_iso_malformed5"
] | [] | 2021-02-06 14:46:19+00:00 | 4,350 |
|
ome__ome-model-145 | diff --git a/.appveyor.yml b/.appveyor.yml
deleted file mode 100644
index 2f7748a0..00000000
--- a/.appveyor.yml
+++ /dev/null
@@ -1,39 +0,0 @@
-environment:
- AV_PROJECTS: 'c:\projects'
- AV_OME_M2: 'c:\projects\m2'
- AV_OME_PYTHON: 'c:\projects\python'
- AV_OME_SOURCE: 'c:\projects\source'
-
-# Note that only Oracle JDK is provided.
- matrix:
- - java: 10
- - java: 1.8
- - java: 1.7
-
-cache:
- - '%AV_OME_M2% -> appveyor.yml'
- - '%AV_OME_PYTHON% -> appveyor.yml'
-
-os: 'Visual Studio 2015'
-clone_folder: '%AV_OME_SOURCE%'
-clone_depth: 5
-platform: x64
-
-init:
- - git config --global core.autocrlf input
- - refreshenv
- - 'if [%java%] == [1.7] set "JAVA_HOME=C:\Program Files\Java\jdk1.7.0"'
- - 'if [%java%] == [1.8] set "JAVA_HOME=C:\Program Files\Java\jdk1.8.0"'
- - 'if [%java%] == [10] set "JAVA_HOME=C:\Program Files\Java\jdk10"'
- - PATH=%JAVA_HOME%\bin;%PATH%
- - 'set "MAVEN_OPTS=-Dmaven.repo.local=%AV_OME_M2%"'
- - 'if [%java%] == [1.7] set "MAVEN_OPTS=%MAVEN_OPTS% -Dhttps.protocols=TLSv1.2"'
-
-build_script:
- # Cached venv is available from this point.
- - 'if NOT EXIST "%AV_OME_PYTHON%\" set AV_OME_CREATE_VENV=true'
- - 'if [%AV_OME_CREATE_VENV%] == [true] C:\Python27-x64\python -m pip install virtualenv'
- - 'if [%AV_OME_CREATE_VENV%] == [true] C:\Python27-x64\python -m virtualenv %AV_OME_PYTHON%'
- - PATH=%AV_OME_PYTHON%;%AV_OME_PYTHON%\scripts;%PATH%
- - 'if [%AV_OME_CREATE_VENV%] == [true] python -m pip install sphinx'
- - mvn install
diff --git a/ome-xml/src/main/java/ome/xml/meta/MetadataConverter.java b/ome-xml/src/main/java/ome/xml/meta/MetadataConverter.java
index e76c1160..c787950a 100644
--- a/ome-xml/src/main/java/ome/xml/meta/MetadataConverter.java
+++ b/ome-xml/src/main/java/ome/xml/meta/MetadataConverter.java
@@ -2301,7 +2301,7 @@ public final class MetadataConverter {
int wellAnnotationRefCount = 0;
try {
- src.getWellAnnotationRefCount(i, q);
+ wellAnnotationRefCount = src.getWellAnnotationRefCount(i, q);
}
catch (NullPointerException e) { }
for (int a=0; a<wellAnnotationRefCount; a++) {
diff --git a/ome_model/experimental.py b/ome_model/experimental.py
index e5f4ecfd..aa9f8630 100644
--- a/ome_model/experimental.py
+++ b/ome_model/experimental.py
@@ -102,7 +102,7 @@ class Image(object):
def __init__(self,
name,
sizeX, sizeY, sizeZ, sizeC, sizeT,
- tiffs=[],
+ tiffs=None,
order="XYZTC",
type="uint16",
):
@@ -123,8 +123,9 @@ class Image(object):
'Planes': [],
}
Image.ID += 1
- for tiff in tiffs:
- self.add_tiff(tiff)
+ if tiffs:
+ for tiff in tiffs:
+ self.add_tiff(tiff)
def add_channel(self, name=None, color=None, samplesPerPixel=1):
self.data["Channels"].append(
@@ -223,12 +224,16 @@ def parse_tiff(tiff):
return (m.group("channel"), m.group("time"), m.group("slice"))
-def create_companion(plates=[], images=[], out=None):
+def create_companion(plates=None, images=None, out=None):
"""
Create a companion OME-XML for a given experiment.
Assumes 2D TIFFs
"""
root = ET.Element("OME", attrib=OME_ATTRIBUTES)
+ if not plates:
+ plates = []
+ if not images:
+ images = []
for plate in plates:
p = ET.SubElement(root, "Plate", attrib=plate.data['Plate'])
diff --git a/specification/src/main/resources/transforms/2008-09-to-2009-09.xsl b/specification/src/main/resources/transforms/2008-09-to-2009-09.xsl
index 53c1d1ab..8e6a5c52 100644
--- a/specification/src/main/resources/transforms/2008-09-to-2009-09.xsl
+++ b/specification/src/main/resources/transforms/2008-09-to-2009-09.xsl
@@ -154,6 +154,25 @@
</xsl:element>
</xsl:for-each>
+ <!-- Transform the CustomAttributes into XMLAnnotation -->
+ <xsl:if test="(count(//*[local-name() = 'StructuredAnnotations'])) = 0">
+ <xsl:if test="(count(//*[local-name() = 'CustomAttributes'])) > 0">
+ <xsl:element name="StructuredAnnotations" namespace="{$newSANS}">
+ <xsl:comment>Append Custom Attributes as XMLAnnotation</xsl:comment>
+ <xsl:for-each select="//*[local-name() = 'CustomAttributes']">
+ <xsl:if test="count(@*|node()) > 0">
+ <xsl:variable name="annotationIndex" select="position()" />
+ <xsl:element name="XMLAnnotation" namespace="{$newSANS}">
+ <xsl:attribute name="ID"><xsl:value-of select="concat('Annotation:CustomAttributes', $annotationIndex)"/></xsl:attribute>
+ <xsl:element name="Value" namespace="{$newSANS}">
+ <xsl:apply-templates select="@*|node()"/>
+ </xsl:element>
+ </xsl:element>
+ </xsl:if>
+ </xsl:for-each>
+ </xsl:element>
+ </xsl:if>
+ </xsl:if>
</OME>
</xsl:template>
@@ -181,6 +200,27 @@
</xsl:element>
</xsl:template>
+ <xsl:template match="SA:StructuredAnnotations">
+ <xsl:element name="{name()}" namespace="{$newSANS}">
+ <xsl:apply-templates select="@*|node()"/>
+ <!-- Transform the CustomAttributes into XMLAnnotation -->
+ <xsl:if test="(count(//*[local-name() = 'CustomAttributes'])) > 0">
+ <xsl:comment>Append Custom Attributes as XMLAnnotation</xsl:comment>
+ <xsl:for-each select="//*[local-name() = 'CustomAttributes']">
+ <xsl:if test="count(@*|node()) > 0">
+ <xsl:variable name="annotationIndex" select="position()" />
+ <xsl:element name="XMLAnnotation" namespace="{$newSANS}">
+ <xsl:attribute name="ID"><xsl:value-of select="concat('Annotation:CustomAttributes', $annotationIndex)"/></xsl:attribute>
+ <xsl:element name="Value" namespace="{$newSANS}">
+ <xsl:apply-templates select="@*|node()"/>
+ </xsl:element>
+ </xsl:element>
+ </xsl:if>
+ </xsl:for-each>
+ </xsl:if>
+ </xsl:element>
+ </xsl:template>
+
<xsl:template match="SA:List">
<xsl:apply-templates select="*"/>
</xsl:template>
@@ -849,18 +889,12 @@
</xsl:element>
</xsl:template>
- <!-- Transform the CustomAttributes into XMLAnnotation -->
+ <!-- Remove CustomAttributes -->
<xsl:template match="CA:CustomAttributes">
- <xsl:if test="count(@*|node()) > 0">
- <xsl:element name="StructuredAnnotations" namespace="{$newSANS}">
- <xsl:element name="XMLAnnotation" namespace="{$newSANS}">
- <xsl:attribute name="ID">Annotation:1</xsl:attribute>
- <xsl:element name="Value" namespace="{$newSANS}">
- <xsl:apply-templates select="@*|node()"/>
- </xsl:element>
- </xsl:element>
- </xsl:element>
- </xsl:if>
+ <xsl:variable name="caCount" select="count(preceding::CA:CustomAttributes | ancestor::CA:CustomAttributes) + 1"/>
+ <xsl:element name="SA:AnnotationRef" namespace="{$newSANS}">
+ <xsl:attribute name="ID"><xsl:value-of select="concat('Annotation:CustomAttributes', $caCount)"/></xsl:attribute>
+ </xsl:element>
</xsl:template>
<!--
@@ -886,8 +920,14 @@
<xsl:apply-templates
select="@* [not(name() = 'DefaultPixels' or name() = 'AcquiredPixels')]"/>
<xsl:for-each
- select="* [not(local-name(.) = 'Thumbnail' or local-name(.) = 'DisplayOptions' or local-name(.) = 'Region' or local-name(.) = 'CustomAttributes' or local-name(.) = 'LogicalChannel')]">
+ select="* [not(local-name(.) = 'Thumbnail' or local-name(.) = 'DisplayOptions' or local-name(.) = 'Region' or local-name(.) = 'LogicalChannel')]">
<xsl:choose>
+ <xsl:when test="local-name(.) ='CustomAttributes'">
+ <xsl:variable name="caCount" select="count(preceding::CA:CustomAttributes | ancestor::CA:CustomAttributes) + 1"/>
+ <xsl:element name="SA:AnnotationRef" namespace="{$newSANS}">
+ <xsl:attribute name="ID"><xsl:value-of select="concat('Annotation:CustomAttributes', $caCount)"/></xsl:attribute>
+ </xsl:element>
+ </xsl:when>
<xsl:when test="local-name(.) ='Description'">
<xsl:apply-templates select="current()"/>
</xsl:when>
| ome/ome-model | 38624e963f4dbde67992416d000d9eef26828f3b | diff --git a/test/unit/test_plate.py b/test/unit/test_plate.py
new file mode 100644
index 00000000..c7d09633
--- /dev/null
+++ b/test/unit/test_plate.py
@@ -0,0 +1,128 @@
+#! /usr/bin/env python
+# -*- coding: utf-8 -*-
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are met:
+#
+# 1. Redistributions of source code must retain the above copyright notice,
+# this list of conditions and the following disclaimer.
+# 2. Redistributions in binary form must reproduce the above copyright notice,
+# this list of conditions and the following disclaimer in the documentation
+# and/or other materials provided with the distribution.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
+# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+# POSSIBILITY OF SUCH DAMAGE.
+# #L%
+
+
+from ome_model.experimental import Plate, Image, create_companion
+import xml.etree.ElementTree as ElementTree
+
+NS = {'OME': 'http://www.openmicroscopy.org/Schemas/OME/2016-06'}
+ElementTree.register_namespace('OME', NS['OME'])
+
+
+class TestPlate(object):
+
+ def test_minimal_plate(self, tmpdir):
+ f = str(tmpdir.join('plate.companion.ome'))
+
+ p = Plate("test", 1, 1)
+ well = p.add_well(0, 0)
+ i = Image("test", 256, 512, 3, 4, 5)
+ well.add_wellsample(0, i)
+ create_companion(plates=[p], out=f)
+
+ root = ElementTree.parse(f).getroot()
+ plates = root.findall('OME:Plate', namespaces=NS)
+ assert len(plates) == 1
+ assert plates[0].attrib['Name'] == 'test'
+ wells = plates[0].findall('OME:Well', namespaces=NS)
+ assert len(wells) == 1
+ assert wells[0].attrib['Row'] == '0'
+ assert wells[0].attrib['Column'] == '0'
+ wellsamples = wells[0].findall('OME:WellSample', namespaces=NS)
+ assert len(wellsamples) == 1
+ imagerefs = wellsamples[0].findall('OME:ImageRef', namespaces=NS)
+ assert len(imagerefs) == 1
+ imageid = imagerefs[0].attrib['ID']
+ images = root.findall('OME:Image', namespaces=NS)
+ assert len(images) == 1
+ assert images[0].attrib['Name'] == 'test'
+ assert images[0].attrib['ID'] == imageid
+ pixels = images[0].findall('OME:Pixels', namespaces=NS)
+ assert len(pixels) == 1
+ assert pixels[0].attrib['SizeX'] == '256'
+ assert pixels[0].attrib['SizeY'] == '512'
+ assert pixels[0].attrib['SizeZ'] == '3'
+ assert pixels[0].attrib['SizeC'] == '4'
+ assert pixels[0].attrib['SizeT'] == '5'
+ assert pixels[0].attrib['DimensionOrder'] == 'XYZTC'
+ assert pixels[0].attrib['Type'] == 'uint16'
+ channels = pixels[0].findall('OME:Channel', namespaces=NS)
+ assert len(channels) == 0
+
+ def test_multiple_rows_columns_wellsamples(self, tmpdir):
+ f = str(tmpdir.join('plate.companion.ome'))
+
+ p = Plate("test", 4, 5)
+ for row in range(4):
+ for column in range(5):
+ well = p.add_well(row, column)
+ for field in range(6):
+ i = Image("test", 256, 512, 3, 4, 5)
+ well.add_wellsample(field, i)
+ create_companion(plates=[p], out=f)
+
+ root = ElementTree.parse(f).getroot()
+ plates = root.findall('OME:Plate', namespaces=NS)
+ assert len(plates) == 1
+ assert plates[0].attrib['Name'] == 'test'
+ wells = plates[0].findall('OME:Well', namespaces=NS)
+ assert len(wells) == 20
+ imageids = []
+ for i in range(20):
+ wellsamples = wells[i].findall('OME:WellSample', namespaces=NS)
+ assert len(wellsamples) == 6
+ for ws in wellsamples:
+ imagerefs = ws.findall('OME:ImageRef', namespaces=NS)
+ assert len(imagerefs) == 1
+ imageids.append(imagerefs[0].attrib['ID'])
+ assert len(imageids) == 120
+ images = root.findall('OME:Image', namespaces=NS)
+ assert len(images) == 120
+ assert [x.attrib['ID'] for x in images] == imageids
+
+ def test_multiple_plates_one_per_file(self, tmpdir):
+
+ files = [str(tmpdir.join('%s.companion.ome' % i)) for i in range(4)]
+ for i in range(4):
+ p = Plate("test %s" % i, 1, 1)
+ well = p.add_well(0, 0)
+ img = Image("test %s" % i, 256, 512, 3, 4, 5)
+ well.add_wellsample(0, img)
+ create_companion(plates=[p], out=files[i])
+
+ for i in range(4):
+ root = ElementTree.parse(files[i]).getroot()
+ plates = root.findall('OME:Plate', namespaces=NS)
+ assert len(plates) == 1
+ assert plates[0].attrib['Name'] == 'test %s' % i
+ wells = plates[0].findall('OME:Well', namespaces=NS)
+ assert len(wells) == 1
+ wellsamples = wells[0].findall('OME:WellSample', namespaces=NS)
+ assert len(wellsamples) == 1
+ imagerefs = wellsamples[0].findall('OME:ImageRef', namespaces=NS)
+ assert len(imagerefs) == 1
+ images = root.findall('OME:Image', namespaces=NS)
+ assert len(images) == 1
+ assert images[0].attrib['Name'] == 'test %s' % i
| OriginalMetadata from 2003-FC lost in transform process
Issue is a follow up to image.sc thread https://forum.image.sc/t/bio-formats-returns-all-metadata-except-ome-meta-data/52295/2
Using the sample file provided in the thread and correcting validation errors shows that the original metadata (stored in 2003-FC spec) gets lost when going through the transform update process. The particular transform the issue occurs with is
`2008-09-to-2009-09.xsl`
The data that gets lost is stored using the `OriginalMetadata` tag such as below (adding the CA namespace didn't resolve the issue):
```
<CustomAttributes>
<OriginalMetadata ID="OriginalMetadata:3" Name="Acquisition Parameters/Channel 2" Value="Fluorescence"/>
</CustomAttributes>
```
In the transform this should be handled by the following, transforming the metadata to an XMLAnnotation:
```
<xsl:template match="CA:*">
<xsl:element name="{name()}" namespace="{$newCANS}">
<xsl:apply-templates select="@*|node()"/>
</xsl:element>
</xsl:template>
<!-- Transform the CustomAttributes into XMLAnnotation -->
<xsl:template match="CA:CustomAttributes">
<xsl:if test="count(@*|node()) > 0">
<xsl:element name="StructuredAnnotations" namespace="{$newSANS}">
<xsl:element name="XMLAnnotation" namespace="{$newSANS}">
<xsl:attribute name="ID">Annotation:1</xsl:attribute>
<xsl:element name="Value" namespace="{$newSANS}">
<xsl:apply-templates select="@*|node()"/>
</xsl:element>
</xsl:element>
</xsl:element>
</xsl:if>
</xsl:template>
```
| 0.0 | [
"test/unit/test_plate.py::TestPlate::test_multiple_rows_columns_wellsamples",
"test/unit/test_plate.py::TestPlate::test_multiple_plates_one_per_file"
] | [
"test/unit/test_plate.py::TestPlate::test_minimal_plate"
] | 2021-05-24 13:29:37+00:00 | 4,351 |
|
omni-us__jsonargparse-132 | diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index e697442..b90bc59 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -10,6 +10,15 @@ only be introduced in major versions with advance notice in the **Deprecated**
section of releases.
+v4.6.0 (2022-04-??)
+-------------------
+
+Added
+^^^^^
+- Dump option to exclude entries whose value is the same as the default `#91
+ <https://github.com/omni-us/jsonargparse/issues/91>`__.
+
+
v4.5.0 (2022-03-29)
-------------------
diff --git a/jsonargparse/actions.py b/jsonargparse/actions.py
index 725c357..d6e6753 100644
--- a/jsonargparse/actions.py
+++ b/jsonargparse/actions.py
@@ -244,12 +244,12 @@ class _ActionPrintConfig(Action):
dest=dest,
default=default,
nargs=1,
- metavar='[={comments,skip_null}+]',
+ metavar='[={comments,skip_null,skip_default}+]',
help='Print configuration and exit.')
def __call__(self, parser, namespace, value, option_string=None):
kwargs = {'subparser': parser, 'key': None, 'skip_none': False, 'skip_check': True}
- valid_flags = {'': None, 'comments': 'yaml_comments', 'skip_null': 'skip_none'}
+ valid_flags = {'': None, 'comments': 'yaml_comments', 'skip_default': 'skip_default', 'skip_null': 'skip_none'}
if value is not None:
flags = value[0].split(',')
invalid_flags = [f for f in flags if f not in valid_flags]
diff --git a/jsonargparse/core.py b/jsonargparse/core.py
index 5e9e97c..46f3a30 100644
--- a/jsonargparse/core.py
+++ b/jsonargparse/core.py
@@ -17,7 +17,7 @@ from .jsonschema import ActionJsonSchema
from .loaders_dumpers import check_valid_dump_format, dump_using_format, get_loader_exceptions, loaders, load_value, load_value_context, yaml_load
from .namespace import is_meta_key, Namespace, split_key, split_key_leaf, strip_meta
from .signatures import is_pure_dataclass, SignatureArguments
-from .typehints import ActionTypeHint
+from .typehints import ActionTypeHint, is_class_object
from .actions import (
ActionParser,
ActionConfigFile,
@@ -658,6 +658,7 @@ class ArgumentParser(_ActionsContainer, argparse.ArgumentParser):
cfg: Namespace,
format: str = 'parser_mode',
skip_none: bool = True,
+ skip_default: bool = False,
skip_check: bool = False,
yaml_comments: bool = False,
) -> str:
@@ -667,6 +668,7 @@ class ArgumentParser(_ActionsContainer, argparse.ArgumentParser):
cfg: The configuration object to dump.
format: The output format: ``'yaml'``, ``'json'``, ``'json_indented'``, ``'parser_mode'`` or ones added via :func:`.set_dumper`.
skip_none: Whether to exclude entries whose value is None.
+ skip_default: Whether to exclude entries whose value is the same as the default.
skip_check: Whether to skip parser checking.
yaml_comments: Whether to add help content as comments. ``yaml_comments=True`` implies ``format='yaml'``.
@@ -686,28 +688,57 @@ class ArgumentParser(_ActionsContainer, argparse.ArgumentParser):
with load_value_context(self.parser_mode):
self.check_config(cfg)
- def cleanup_actions(cfg, actions, prefix=''):
- for action in filter_default_actions(actions):
- action_dest = prefix + action.dest
- if (action.help == argparse.SUPPRESS and not isinstance(action, _ActionConfigLoad)) or \
- isinstance(action, ActionConfigFile) or \
- (skip_none and action_dest in cfg and cfg[action_dest] is None):
- cfg.pop(action_dest, None)
- elif isinstance(action, _ActionSubCommands):
- cfg.pop(action_dest, None)
- for key, subparser in action.choices.items():
- cleanup_actions(cfg, subparser._actions, prefix=prefix+key+'.')
- elif isinstance(action, ActionTypeHint):
- value = cfg.get(action_dest)
- if value is not None:
- value = action.serialize(value, dump_kwargs={'skip_check': skip_check, 'skip_none': skip_none})
- cfg.update(value, action_dest)
-
with load_value_context(self.parser_mode):
- cleanup_actions(cfg, self._actions)
+ dump_kwargs = {'skip_check': skip_check, 'skip_none': skip_none}
+ self._dump_cleanup_actions(cfg, self._actions, dump_kwargs)
+
+ cfg = cfg.as_dict()
+
+ if skip_default:
+ self._dump_delete_default_entries(cfg, self.get_defaults().as_dict())
with formatter_context(self):
- return dump_using_format(self, cfg.as_dict(), 'yaml_comments' if yaml_comments else format)
+ return dump_using_format(self, cfg, 'yaml_comments' if yaml_comments else format)
+
+
+ def _dump_cleanup_actions(self, cfg, actions, dump_kwargs, prefix=''):
+ skip_none = dump_kwargs['skip_none']
+ for action in filter_default_actions(actions):
+ action_dest = prefix + action.dest
+ if (action.help == argparse.SUPPRESS and not isinstance(action, _ActionConfigLoad)) or \
+ isinstance(action, ActionConfigFile) or \
+ (skip_none and action_dest in cfg and cfg[action_dest] is None):
+ cfg.pop(action_dest, None)
+ elif isinstance(action, _ActionSubCommands):
+ cfg.pop(action_dest, None)
+ for key, subparser in action.choices.items():
+ self._dump_cleanup_actions(cfg, subparser._actions, dump_kwargs, prefix=prefix+key+'.')
+ elif isinstance(action, ActionTypeHint):
+ value = cfg.get(action_dest)
+ if value is not None:
+ value = action.serialize(value, dump_kwargs=dump_kwargs)
+ cfg.update(value, action_dest)
+
+
+ def _dump_delete_default_entries(self, subcfg, subdefaults):
+ for key in list(subcfg.keys()):
+ if key in subdefaults:
+ val = subcfg[key]
+ default = subdefaults[key]
+ class_object_val = None
+ if is_class_object(val):
+ if val['class_path'] != default.get('class_path'):
+ parser = ActionTypeHint.get_class_parser(val['class_path'])
+ default = {'init_args': parser.get_defaults().as_dict()}
+ class_object_val = val
+ val = val['init_args']
+ default = default.get('init_args')
+ if val == default:
+ del subcfg[key]
+ elif isinstance(val, dict) and isinstance(default, dict):
+ self._dump_delete_default_entries(val, default)
+ if class_object_val and class_object_val.get('init_args') == {}:
+ del class_object_val['init_args']
def save(
@@ -891,7 +922,7 @@ class ArgumentParser(_ActionsContainer, argparse.ArgumentParser):
cfg = Namespace()
for action in filter_default_actions(self._actions):
if action.default != argparse.SUPPRESS and action.dest != argparse.SUPPRESS:
- cfg[action.dest] = action.default
+ cfg[action.dest] = deepcopy(action.default)
self._logger.info('Loaded default values from parser.')
| omni-us/jsonargparse | d0830889df9a1ca89dd44761ecd4e44049e25b7b | diff --git a/jsonargparse_tests/core_tests.py b/jsonargparse_tests/core_tests.py
index 00aee2c..263a16b 100755
--- a/jsonargparse_tests/core_tests.py
+++ b/jsonargparse_tests/core_tests.py
@@ -660,6 +660,25 @@ class OutputTests(TempDirTestCase):
self.assertRaises(ValueError, lambda: parser.dump(cfg, format='invalid'))
+ def test_dump_skip_default(self):
+ parser = ArgumentParser()
+ parser.add_argument('--op1', default=123)
+ parser.add_argument('--op2', default='abc')
+ self.assertEqual(parser.dump(parser.get_defaults(), skip_default=True), '{}\n')
+ self.assertEqual(parser.dump(Namespace(op1=123, op2='xyz'), skip_default=True), 'op2: xyz\n')
+
+
+ def test_dump_skip_default_nested(self):
+ parser = ArgumentParser()
+ parser.add_argument('--g1.op1', type=int, default=123)
+ parser.add_argument('--g1.op2', type=str, default='abc')
+ parser.add_argument('--g2.op1', type=int, default=987)
+ parser.add_argument('--g2.op2', type=str, default='xyz')
+ self.assertEqual(parser.dump(parser.get_defaults(), skip_default=True), '{}\n')
+ self.assertEqual(parser.dump(parser.parse_args(['--g1.op1=0']), skip_default=True), 'g1:\n op1: 0\n')
+ self.assertEqual(parser.dump(parser.parse_args(['--g2.op2=pqr']), skip_default=True), 'g2:\n op2: pqr\n')
+
+
@unittest.skipIf(not dump_preserve_order_support,
'Dump preserve order only supported in python>=3.6 and CPython')
def test_dump_order(self):
diff --git a/jsonargparse_tests/signatures_tests.py b/jsonargparse_tests/signatures_tests.py
index 956d842..86650d7 100755
--- a/jsonargparse_tests/signatures_tests.py
+++ b/jsonargparse_tests/signatures_tests.py
@@ -1145,36 +1145,37 @@ class SignaturesTests(unittest.TestCase):
def test_link_arguments_subclass_missing_param_issue_129(self):
- class ClassA:
- def __init__(self, a1: int = 1):
- self.a1 = a1
+ with suppress_stderr():
+ class ClassA:
+ def __init__(self, a1: int = 1):
+ self.a1 = a1
- class ClassB:
- def __init__(self, b1: int = 2):
- self.b1 = b1
+ class ClassB:
+ def __init__(self, b1: int = 2):
+ self.b1 = b1
- with mock_module(ClassA, ClassB) as module, self.assertLogs(level='DEBUG') as log, suppress_stderr():
parser = ArgumentParser(error_handler=None, logger={'level': 'DEBUG'})
- parser.add_subclass_arguments(ClassA, 'a', default=lazy_instance(ClassA))
- parser.add_subclass_arguments(ClassB, 'b', default=lazy_instance(ClassB))
- parser.link_arguments('a.init_args.a2', 'b.init_args.b1', apply_on='parse')
- parser.link_arguments('a.init_args.a1', 'b.init_args.b2', apply_on='parse')
+ with mock_module(ClassA, ClassB) as module, self.assertLogs(level='DEBUG') as log:
+ parser.add_subclass_arguments(ClassA, 'a', default=lazy_instance(ClassA))
+ parser.add_subclass_arguments(ClassB, 'b', default=lazy_instance(ClassB))
+ parser.link_arguments('a.init_args.a2', 'b.init_args.b1', apply_on='parse')
+ parser.link_arguments('a.init_args.a1', 'b.init_args.b2', apply_on='parse')
- cfg = parser.parse_args([f'--a={module}.ClassA', f'--b={module}.ClassB'])
- self.assertTrue(any('a.init_args.a2 --> b.init_args.b1 ignored since source' in x for x in log.output))
- self.assertTrue(any('a.init_args.a1 --> b.init_args.b2 ignored since target' in x for x in log.output))
+ parser.parse_args([f'--a={module}.ClassA', f'--b={module}.ClassB'])
+ self.assertTrue(any('a.init_args.a2 --> b.init_args.b1 ignored since source' in x for x in log.output))
+ self.assertTrue(any('a.init_args.a1 --> b.init_args.b2 ignored since target' in x for x in log.output))
- with mock_module(ClassA, ClassB) as module, self.assertLogs(level='DEBUG') as log, suppress_stderr():
parser = ArgumentParser(error_handler=None, logger={'level': 'DEBUG'})
- parser.add_subclass_arguments(ClassA, 'a', default=lazy_instance(ClassA))
- parser.add_subclass_arguments(ClassB, 'b', default=lazy_instance(ClassB))
- parser.link_arguments('a.init_args.a2', 'b.init_args.b1', apply_on='instantiate')
- parser.link_arguments('a.init_args.a1', 'b.init_args.b2', apply_on='instantiate')
-
- cfg = parser.parse_args([f'--a={module}.ClassA', f'--b={module}.ClassB'])
- cfg_init = parser.instantiate_classes(cfg)
- self.assertTrue(any('a.init_args.a2 --> b.init_args.b1 ignored since source' in x for x in log.output))
- self.assertTrue(any('a.init_args.a1 --> b.init_args.b2 ignored since target' in x for x in log.output))
+ with mock_module(ClassA, ClassB) as module, self.assertLogs(level='DEBUG') as log:
+ parser.add_subclass_arguments(ClassA, 'a', default=lazy_instance(ClassA))
+ parser.add_subclass_arguments(ClassB, 'b', default=lazy_instance(ClassB))
+ parser.link_arguments('a.init_args.a2', 'b.init_args.b1', apply_on='instantiate')
+ parser.link_arguments('a.init_args.a1', 'b.init_args.b2', apply_on='instantiate')
+
+ cfg = parser.parse_args([f'--a={module}.ClassA', f'--b={module}.ClassB'])
+ parser.instantiate_classes(cfg)
+ self.assertTrue(any('a.init_args.a2 --> b.init_args.b1 ignored since source' in x for x in log.output))
+ self.assertTrue(any('a.init_args.a1 --> b.init_args.b2 ignored since target' in x for x in log.output))
def test_class_from_function(self):
diff --git a/jsonargparse_tests/typehints_tests.py b/jsonargparse_tests/typehints_tests.py
index 38a3f33..dbbd31c 100755
--- a/jsonargparse_tests/typehints_tests.py
+++ b/jsonargparse_tests/typehints_tests.py
@@ -503,6 +503,31 @@ class TypeHintsTests(unittest.TestCase):
self.assertRaises(ValueError, lambda: lazy_instance(MyClass, param='bad'))
+ def test_dump_skip_default(self):
+ class MyCalendar(Calendar):
+ def __init__(self, *args, param: str = '0', **kwargs):
+ super().__init__(*args, **kwargs)
+
+ with mock_module(MyCalendar) as module:
+ parser = ArgumentParser()
+ parser.add_argument('--g1.op1', default=123)
+ parser.add_argument('--g1.op2', default='abc')
+ parser.add_argument('--g2.op1', default=4.5)
+ parser.add_argument('--g2.op2', type=Calendar, default=lazy_instance(Calendar, firstweekday=2))
+
+ cfg = parser.get_defaults()
+ dump = parser.dump(cfg, skip_default=True)
+ self.assertEqual(dump, '{}\n')
+
+ cfg.g2.op2.class_path = f'{module}.MyCalendar'
+ dump = parser.dump(cfg, skip_default=True)
+ self.assertEqual(dump, 'g2:\n op2:\n class_path: jsonargparse_tests.MyCalendar\n init_args:\n firstweekday: 2\n')
+
+ cfg.g2.op2.init_args.firstweekday = 0
+ dump = parser.dump(cfg, skip_default=True)
+ self.assertEqual(dump, 'g2:\n op2:\n class_path: jsonargparse_tests.MyCalendar\n')
+
+
class TypeHintsTmpdirTests(TempDirTestCase):
def test_path(self):
| Support `--print_config skip_default`
Add support for `--print_config skip_default` so only the values different to the default are printed.
Two main benefits:
- Removes the manual work of removing the extra arguments from a config. However, this isn't recommended for reproducibility as it's useful to know exactly what was set.
- Improves backward compatibility. Often features are deprecated in a way that the default argument for a function is re-routed to the new implementation. Since the config saves all old defaults and passes them to the program, it is likely the program will fail when support for the old value is removed. | 0.0 | [
"jsonargparse_tests/core_tests.py::OutputTests::test_dump_skip_default",
"jsonargparse_tests/core_tests.py::OutputTests::test_dump_skip_default_nested",
"jsonargparse_tests/typehints_tests.py::TypeHintsTests::test_dump_skip_default"
] | [
"jsonargparse_tests/core_tests.py::ParsersTests::test_cfg_base",
"jsonargparse_tests/core_tests.py::ParsersTests::test_default_env",
"jsonargparse_tests/core_tests.py::ParsersTests::test_parse_args",
"jsonargparse_tests/core_tests.py::ParsersTests::test_parse_env",
"jsonargparse_tests/core_tests.py::ParsersTests::test_parse_object",
"jsonargparse_tests/core_tests.py::ParsersTests::test_parse_path",
"jsonargparse_tests/core_tests.py::ParsersTests::test_parse_string",
"jsonargparse_tests/core_tests.py::ParsersTests::test_precedence_of_sources",
"jsonargparse_tests/core_tests.py::ArgumentFeaturesTests::test_choices",
"jsonargparse_tests/core_tests.py::ArgumentFeaturesTests::test_nargs",
"jsonargparse_tests/core_tests.py::ArgumentFeaturesTests::test_positionals",
"jsonargparse_tests/core_tests.py::ArgumentFeaturesTests::test_required",
"jsonargparse_tests/core_tests.py::AdvancedFeaturesTests::test_link_arguments",
"jsonargparse_tests/core_tests.py::AdvancedFeaturesTests::test_optional_subcommand",
"jsonargparse_tests/core_tests.py::AdvancedFeaturesTests::test_subcommand_print_config_default_env_issue_126",
"jsonargparse_tests/core_tests.py::AdvancedFeaturesTests::test_subcommands",
"jsonargparse_tests/core_tests.py::AdvancedFeaturesTests::test_subsubcommands",
"jsonargparse_tests/core_tests.py::AdvancedFeaturesTests::test_subsubcommands_bad_order",
"jsonargparse_tests/core_tests.py::OutputTests::test_dump",
"jsonargparse_tests/core_tests.py::OutputTests::test_dump_formats",
"jsonargparse_tests/core_tests.py::OutputTests::test_dump_order",
"jsonargparse_tests/core_tests.py::OutputTests::test_dump_path_type",
"jsonargparse_tests/core_tests.py::OutputTests::test_dump_restricted_float_type",
"jsonargparse_tests/core_tests.py::OutputTests::test_dump_restricted_int_type",
"jsonargparse_tests/core_tests.py::OutputTests::test_dump_restricted_string_type",
"jsonargparse_tests/core_tests.py::OutputTests::test_print_config",
"jsonargparse_tests/core_tests.py::OutputTests::test_save",
"jsonargparse_tests/core_tests.py::OutputTests::test_save_failures",
"jsonargparse_tests/core_tests.py::OutputTests::test_save_path_content",
"jsonargparse_tests/core_tests.py::ConfigFilesTests::test_ActionConfigFile",
"jsonargparse_tests/core_tests.py::ConfigFilesTests::test_ActionConfigFile_failures",
"jsonargparse_tests/core_tests.py::ConfigFilesTests::test_default_config_files",
"jsonargparse_tests/core_tests.py::ConfigFilesTests::test_get_default_with_multiple_default_config_files",
"jsonargparse_tests/core_tests.py::OtherTests::test_capture_parser",
"jsonargparse_tests/core_tests.py::OtherTests::test_check_config_branch",
"jsonargparse_tests/core_tests.py::OtherTests::test_debug_usage_and_exit_error_handler",
"jsonargparse_tests/core_tests.py::OtherTests::test_error_handler_property",
"jsonargparse_tests/core_tests.py::OtherTests::test_invalid_parser_mode",
"jsonargparse_tests/core_tests.py::OtherTests::test_merge_config",
"jsonargparse_tests/core_tests.py::OtherTests::test_meta_key_failures",
"jsonargparse_tests/core_tests.py::OtherTests::test_named_groups",
"jsonargparse_tests/core_tests.py::OtherTests::test_parse_args_invalid_args",
"jsonargparse_tests/core_tests.py::OtherTests::test_parse_known_args",
"jsonargparse_tests/core_tests.py::OtherTests::test_pickle_parser",
"jsonargparse_tests/core_tests.py::OtherTests::test_set_get_defaults",
"jsonargparse_tests/core_tests.py::OtherTests::test_strip_unknown",
"jsonargparse_tests/core_tests.py::OtherTests::test_unrecognized_arguments",
"jsonargparse_tests/core_tests.py::OtherTests::test_usage_and_exit_error_handler",
"jsonargparse_tests/core_tests.py::OtherTests::test_version_print",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_add_class_arguments",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_add_class_from_function_arguments",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_add_class_implemented_with_new",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_add_function_arguments",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_add_method_arguments",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_add_method_arguments_parent_classes",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_add_subclass_arguments",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_add_subclass_arguments_tuple",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_add_subclass_discard_init_args",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_add_subclass_init_args_in_subcommand",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_add_subclass_init_args_without_class_path",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_basic_subtypes",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_class_from_function",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_dict_int_str_type",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_dict_type_nested_in_two_level_subclasses",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_fail_untyped_false",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_final_class",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_implicit_optional",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_instantiate_classes",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_instantiate_classes_subcommand",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_invalid_class_from_function",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_invalid_type",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_link_arguments",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_link_arguments_apply_on_instantiate",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_link_arguments_subclass_as_dict",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_link_arguments_subclass_missing_param_issue_129",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_link_arguments_subclasses",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_link_arguments_subclasses_with_instantiate_false",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_link_arguments_subcommand",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_logger_debug",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_not_required_group",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_optional_enum",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_print_config",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_print_config_subclass_required_param_issue_115",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_required_group",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_skip",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_skip_in_add_subclass_arguments",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_skip_within_subclass_type",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_subclass_help",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_type_any_serialize",
"jsonargparse_tests/signatures_tests.py::SignaturesConfigTests::test_add_class_arguments_with_config_not_found",
"jsonargparse_tests/signatures_tests.py::SignaturesConfigTests::test_add_function_arguments_config",
"jsonargparse_tests/signatures_tests.py::SignaturesConfigTests::test_add_subclass_arguments_with_config",
"jsonargparse_tests/signatures_tests.py::SignaturesConfigTests::test_add_subclass_arguments_with_multifile_save",
"jsonargparse_tests/signatures_tests.py::SignaturesConfigTests::test_config_within_config",
"jsonargparse_tests/signatures_tests.py::SignaturesConfigTests::test_parent_parser_default_config_files_lightning_issue_11622",
"jsonargparse_tests/signatures_tests.py::SignaturesConfigTests::test_subclass_required_param_with_default_config_files",
"jsonargparse_tests/signatures_tests.py::DataclassesTests::test_compose_dataclasses",
"jsonargparse_tests/signatures_tests.py::DataclassesTests::test_dataclass_add_argument_type",
"jsonargparse_tests/signatures_tests.py::DataclassesTests::test_dataclass_add_argument_type_some_required",
"jsonargparse_tests/signatures_tests.py::DataclassesTests::test_dataclass_field_default_factory",
"jsonargparse_tests/signatures_tests.py::DataclassesTests::test_dataclass_typehint",
"jsonargparse_tests/signatures_tests.py::DataclassesTests::test_dataclass_typehint_in_subclass",
"jsonargparse_tests/signatures_tests.py::DataclassesTests::test_instantiate_classes_dataclasses_lightning_issue_9207",
"jsonargparse_tests/typehints_tests.py::TypeHintsTests::test_Callable_with_class_path",
"jsonargparse_tests/typehints_tests.py::TypeHintsTests::test_Callable_with_function_path",
"jsonargparse_tests/typehints_tests.py::TypeHintsTests::test_Literal",
"jsonargparse_tests/typehints_tests.py::TypeHintsTests::test_add_argument_type_hint",
"jsonargparse_tests/typehints_tests.py::TypeHintsTests::test_bool",
"jsonargparse_tests/typehints_tests.py::TypeHintsTests::test_class_type",
"jsonargparse_tests/typehints_tests.py::TypeHintsTests::test_class_type_required_params",
"jsonargparse_tests/typehints_tests.py::TypeHintsTests::test_class_type_without_defaults",
"jsonargparse_tests/typehints_tests.py::TypeHintsTests::test_complex_number",
"jsonargparse_tests/typehints_tests.py::TypeHintsTests::test_dict",
"jsonargparse_tests/typehints_tests.py::TypeHintsTests::test_dict_union",
"jsonargparse_tests/typehints_tests.py::TypeHintsTests::test_enum",
"jsonargparse_tests/typehints_tests.py::TypeHintsTests::test_invalid_init_args_in_yaml",
"jsonargparse_tests/typehints_tests.py::TypeHintsTests::test_lazy_instance_invalid_kwargs",
"jsonargparse_tests/typehints_tests.py::TypeHintsTests::test_list",
"jsonargparse_tests/typehints_tests.py::TypeHintsTests::test_list_enum",
"jsonargparse_tests/typehints_tests.py::TypeHintsTests::test_list_tuple",
"jsonargparse_tests/typehints_tests.py::TypeHintsTests::test_list_union",
"jsonargparse_tests/typehints_tests.py::TypeHintsTests::test_nargs_questionmark",
"jsonargparse_tests/typehints_tests.py::TypeHintsTests::test_nested_tuples",
"jsonargparse_tests/typehints_tests.py::TypeHintsTests::test_no_str_strip",
"jsonargparse_tests/typehints_tests.py::TypeHintsTests::test_register_type",
"jsonargparse_tests/typehints_tests.py::TypeHintsTests::test_tuple",
"jsonargparse_tests/typehints_tests.py::TypeHintsTests::test_tuple_ellipsis",
"jsonargparse_tests/typehints_tests.py::TypeHintsTests::test_type_Any",
"jsonargparse_tests/typehints_tests.py::TypeHintsTests::test_type_hint_action_failure",
"jsonargparse_tests/typehints_tests.py::TypeHintsTests::test_typed_Callable_with_function_path",
"jsonargparse_tests/typehints_tests.py::TypeHintsTests::test_typehint_Type",
"jsonargparse_tests/typehints_tests.py::TypeHintsTests::test_typehint_non_parameterized_type",
"jsonargparse_tests/typehints_tests.py::TypeHintsTests::test_typehint_parametrized_type",
"jsonargparse_tests/typehints_tests.py::TypeHintsTests::test_typehint_serialize_enum",
"jsonargparse_tests/typehints_tests.py::TypeHintsTests::test_typehint_serialize_list",
"jsonargparse_tests/typehints_tests.py::TypeHintsTests::test_unsupported_type",
"jsonargparse_tests/typehints_tests.py::TypeHintsTests::test_uuid",
"jsonargparse_tests/typehints_tests.py::TypeHintsTmpdirTests::test_class_path_override_with_default_config_files",
"jsonargparse_tests/typehints_tests.py::TypeHintsTmpdirTests::test_class_type_with_default_config_files",
"jsonargparse_tests/typehints_tests.py::TypeHintsTmpdirTests::test_default_path_unregistered_type",
"jsonargparse_tests/typehints_tests.py::TypeHintsTmpdirTests::test_enable_path",
"jsonargparse_tests/typehints_tests.py::TypeHintsTmpdirTests::test_linking_deep_targets",
"jsonargparse_tests/typehints_tests.py::TypeHintsTmpdirTests::test_linking_deep_targets_mapping",
"jsonargparse_tests/typehints_tests.py::TypeHintsTmpdirTests::test_list_path",
"jsonargparse_tests/typehints_tests.py::TypeHintsTmpdirTests::test_mapping_class_typehint",
"jsonargparse_tests/typehints_tests.py::TypeHintsTmpdirTests::test_optional_path",
"jsonargparse_tests/typehints_tests.py::TypeHintsTmpdirTests::test_path",
"jsonargparse_tests/typehints_tests.py::TypeHintsTmpdirTests::test_subcommand_with_subclass_default_override_lightning_issue_10859",
"jsonargparse_tests/typehints_tests.py::OtherTests::test_is_optional"
] | 2022-03-15 08:05:01+00:00 | 4,352 |
|
omni-us__jsonargparse-176 | diff --git a/jsonargparse/typehints.py b/jsonargparse/typehints.py
index b163825..e4f1d2d 100644
--- a/jsonargparse/typehints.py
+++ b/jsonargparse/typehints.py
@@ -235,8 +235,12 @@ class ActionTypeHint(Action):
@staticmethod
- def is_callable_typehint(typehint):
+ def is_callable_typehint(typehint, all_subtypes=True):
typehint_origin = get_typehint_origin(typehint)
+ if typehint_origin == Union:
+ subtypes = [a for a in typehint.__args__ if a != NoneType]
+ test = all if all_subtypes else any
+ return test(ActionTypeHint.is_callable_typehint(s) for s in subtypes)
return typehint_origin in callable_origin_types or typehint in callable_origin_types
@@ -267,7 +271,7 @@ class ActionTypeHint(Action):
typehint = typehint_from_action(action)
if typehint and (
ActionTypeHint.is_subclass_typehint(typehint, all_subtypes=False) or
- ActionTypeHint.is_callable_typehint(typehint) or
+ ActionTypeHint.is_callable_typehint(typehint, all_subtypes=False) or
ActionTypeHint.is_mapping_typehint(typehint)
):
return action, arg_base, explicit_arg
| omni-us/jsonargparse | 04383f9d38d4096b7d149c8a4d2d57d21d521438 | diff --git a/jsonargparse_tests/test_typehints.py b/jsonargparse_tests/test_typehints.py
index af135f0..7d31c88 100755
--- a/jsonargparse_tests/test_typehints.py
+++ b/jsonargparse_tests/test_typehints.py
@@ -497,6 +497,24 @@ class TypeHintsTests(unittest.TestCase):
self.assertEqual(init.call(), 'Bob')
+ def test_union_callable_with_class_path_short_init_args(self):
+ class MyCallable:
+ def __init__(self, name: str):
+ self.name = name
+ def __call__(self):
+ return self.name
+
+ parser = ArgumentParser()
+ parser.add_argument('--call', type=Union[Callable, None])
+
+ with mock_module(MyCallable) as module:
+ cfg = parser.parse_args([f'--call={module}.MyCallable', '--call.name=Bob'])
+ self.assertEqual(cfg.call.class_path, f'{module}.MyCallable')
+ self.assertEqual(cfg.call.init_args, Namespace(name='Bob'))
+ init = parser.instantiate_classes(cfg)
+ self.assertEqual(init.call(), 'Bob')
+
+
def test_typed_Callable_with_function_path(self):
def my_func_1(p: int) -> str:
return str(p)
| Cannot override Callable init_args without passing the class_path
## 🐛 Bug report
Unlike the class argument, I cannot override `Callable` argument without passing the class_path even it is given previously.
### To reproduce
```python
from jsonargparse import CLI
from typing import Callable
def call():
print("Hi")
class Call:
def __init__(self, name: str):
self.name = name
def __call__(self):
print(f"Hi, {self.name}")
def fn(
callable: Callable = call,
):
callable()
if __name__ == "__main__":
CLI(fn)
```
```yaml
callable:
class_path: __main__.Call
init_args:
name: Alice
```
```console
python test.py --config test.yaml
Hi, Alice
python test.py --config test.yaml --callable.name Bob
usage: test.py [-h] [--config CONFIG] [--print_config [={comments,skip_null,skip_default}+]] [--callable CALLABLE]
test.py: error: Unrecognized arguments: --callable.name Bob
```
### Expected behavior
```console
python test.py --config test.yaml
Hi, Alice
python test.py --config test.yaml --callable.name Bob
Hi, Bob
```
### Environment
- jsonargparse version: 4.15.1
- Python version: 3.9
- How jsonargparse was installed: `pip install jsonargparse`
- OS (e.g., Linux): macOS & Linux
| 0.0 | [
"jsonargparse_tests/test_typehints.py::TypeHintsTests::test_union_callable_with_class_path_short_init_args"
] | [
"jsonargparse_tests/test_typehints.py::TypeHintsTests::test_Callable_with_class_path",
"jsonargparse_tests/test_typehints.py::TypeHintsTests::test_Callable_with_function_path",
"jsonargparse_tests/test_typehints.py::TypeHintsTests::test_Literal",
"jsonargparse_tests/test_typehints.py::TypeHintsTests::test_add_argument_type_hint",
"jsonargparse_tests/test_typehints.py::TypeHintsTests::test_bool",
"jsonargparse_tests/test_typehints.py::TypeHintsTests::test_callable_with_class_path_short_init_args",
"jsonargparse_tests/test_typehints.py::TypeHintsTests::test_class_type",
"jsonargparse_tests/test_typehints.py::TypeHintsTests::test_class_type_config_merge_init_args",
"jsonargparse_tests/test_typehints.py::TypeHintsTests::test_class_type_dict_default_nested_init_args",
"jsonargparse_tests/test_typehints.py::TypeHintsTests::test_class_type_in_union_with_str",
"jsonargparse_tests/test_typehints.py::TypeHintsTests::test_class_type_invalid_class_name_then_init_args",
"jsonargparse_tests/test_typehints.py::TypeHintsTests::test_class_type_required_params",
"jsonargparse_tests/test_typehints.py::TypeHintsTests::test_class_type_set_defaults_class_name",
"jsonargparse_tests/test_typehints.py::TypeHintsTests::test_class_type_subclass_given_by_name_issue_84",
"jsonargparse_tests/test_typehints.py::TypeHintsTests::test_class_type_subclass_in_union_help",
"jsonargparse_tests/test_typehints.py::TypeHintsTests::test_class_type_subclass_nested_help",
"jsonargparse_tests/test_typehints.py::TypeHintsTests::test_class_type_subclass_nested_init_args",
"jsonargparse_tests/test_typehints.py::TypeHintsTests::test_class_type_subclass_short_init_args",
"jsonargparse_tests/test_typehints.py::TypeHintsTests::test_class_type_unresolved_name_clash",
"jsonargparse_tests/test_typehints.py::TypeHintsTests::test_class_type_unresolved_parameters",
"jsonargparse_tests/test_typehints.py::TypeHintsTests::test_class_type_without_defaults",
"jsonargparse_tests/test_typehints.py::TypeHintsTests::test_complex_number",
"jsonargparse_tests/test_typehints.py::TypeHintsTests::test_dict",
"jsonargparse_tests/test_typehints.py::TypeHintsTests::test_dict_items",
"jsonargparse_tests/test_typehints.py::TypeHintsTests::test_dict_union",
"jsonargparse_tests/test_typehints.py::TypeHintsTests::test_dump_skip_default",
"jsonargparse_tests/test_typehints.py::TypeHintsTests::test_enum",
"jsonargparse_tests/test_typehints.py::TypeHintsTests::test_help_known_subclasses_class",
"jsonargparse_tests/test_typehints.py::TypeHintsTests::test_help_known_subclasses_type",
"jsonargparse_tests/test_typehints.py::TypeHintsTests::test_init_args_without_class_path",
"jsonargparse_tests/test_typehints.py::TypeHintsTests::test_invalid_init_args_in_yaml",
"jsonargparse_tests/test_typehints.py::TypeHintsTests::test_lazy_instance_invalid_kwargs",
"jsonargparse_tests/test_typehints.py::TypeHintsTests::test_list",
"jsonargparse_tests/test_typehints.py::TypeHintsTests::test_list_append",
"jsonargparse_tests/test_typehints.py::TypeHintsTests::test_list_append_config",
"jsonargparse_tests/test_typehints.py::TypeHintsTests::test_list_append_subclass_init_args",
"jsonargparse_tests/test_typehints.py::TypeHintsTests::test_list_append_subcommand_subclass",
"jsonargparse_tests/test_typehints.py::TypeHintsTests::test_list_enum",
"jsonargparse_tests/test_typehints.py::TypeHintsTests::test_list_str_positional",
"jsonargparse_tests/test_typehints.py::TypeHintsTests::test_list_tuple",
"jsonargparse_tests/test_typehints.py::TypeHintsTests::test_list_union",
"jsonargparse_tests/test_typehints.py::TypeHintsTests::test_nargs_questionmark",
"jsonargparse_tests/test_typehints.py::TypeHintsTests::test_nested_mapping_without_args",
"jsonargparse_tests/test_typehints.py::TypeHintsTests::test_nested_tuples",
"jsonargparse_tests/test_typehints.py::TypeHintsTests::test_no_str_strip",
"jsonargparse_tests/test_typehints.py::TypeHintsTests::test_register_type",
"jsonargparse_tests/test_typehints.py::TypeHintsTests::test_restricted_number_type",
"jsonargparse_tests/test_typehints.py::TypeHintsTests::test_str_not_timestamp_issue_135",
"jsonargparse_tests/test_typehints.py::TypeHintsTests::test_tuple",
"jsonargparse_tests/test_typehints.py::TypeHintsTests::test_tuple_ellipsis",
"jsonargparse_tests/test_typehints.py::TypeHintsTests::test_tuple_untyped",
"jsonargparse_tests/test_typehints.py::TypeHintsTests::test_type_Any",
"jsonargparse_tests/test_typehints.py::TypeHintsTests::test_type_hint_action_failure",
"jsonargparse_tests/test_typehints.py::TypeHintsTests::test_typed_Callable_with_function_path",
"jsonargparse_tests/test_typehints.py::TypeHintsTests::test_typehint_Type",
"jsonargparse_tests/test_typehints.py::TypeHintsTests::test_typehint_non_parameterized_type",
"jsonargparse_tests/test_typehints.py::TypeHintsTests::test_typehint_parametrized_type",
"jsonargparse_tests/test_typehints.py::TypeHintsTests::test_typehint_serialize_enum",
"jsonargparse_tests/test_typehints.py::TypeHintsTests::test_typehint_serialize_list",
"jsonargparse_tests/test_typehints.py::TypeHintsTests::test_union_partially_unsupported_type",
"jsonargparse_tests/test_typehints.py::TypeHintsTests::test_unsupported_type",
"jsonargparse_tests/test_typehints.py::TypeHintsTests::test_uuid",
"jsonargparse_tests/test_typehints.py::TypeHintsTmpdirTests::test_class_path_override_config_with_defaults",
"jsonargparse_tests/test_typehints.py::TypeHintsTmpdirTests::test_class_path_override_with_default_config_files",
"jsonargparse_tests/test_typehints.py::TypeHintsTmpdirTests::test_class_type_with_default_config_files",
"jsonargparse_tests/test_typehints.py::TypeHintsTmpdirTests::test_default_path_unregistered_type",
"jsonargparse_tests/test_typehints.py::TypeHintsTmpdirTests::test_enable_path",
"jsonargparse_tests/test_typehints.py::TypeHintsTmpdirTests::test_list_append_default_config_files",
"jsonargparse_tests/test_typehints.py::TypeHintsTmpdirTests::test_list_append_default_config_files_subcommand",
"jsonargparse_tests/test_typehints.py::TypeHintsTmpdirTests::test_list_path",
"jsonargparse_tests/test_typehints.py::TypeHintsTmpdirTests::test_mapping_class_typehint",
"jsonargparse_tests/test_typehints.py::TypeHintsTmpdirTests::test_optional_path",
"jsonargparse_tests/test_typehints.py::TypeHintsTmpdirTests::test_path",
"jsonargparse_tests/test_typehints.py::TypeHintsTmpdirTests::test_path_like_within_subclass",
"jsonargparse_tests/test_typehints.py::TypeHintsTmpdirTests::test_subcommand_with_subclass_default_override_lightning_issue_10859",
"jsonargparse_tests/test_typehints.py::OtherTests::test_is_optional"
] | 2022-10-14 13:24:13+00:00 | 4,353 |
|
omni-us__jsonargparse-197 | diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index 1d800e2..005aa34 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -21,6 +21,8 @@ Fixed
- ``parse_string`` raises ``AttributeError`` when given a simple string.
- Added missing ``return_parser`` deprecation warning when ``CLI`` has
subcommands.
+- Parsing fails for registered types that can't be cast to boolean `#196
+ <https://github.com/omni-us/jsonargparse/issues/196>`__.
Changed
^^^^^^^
diff --git a/jsonargparse/actions.py b/jsonargparse/actions.py
index c93b2df..e9ee140 100644
--- a/jsonargparse/actions.py
+++ b/jsonargparse/actions.py
@@ -480,7 +480,7 @@ class ActionParser:
"""Initializer for ActionParser instance.
Args:
- parser: A parser to parse the option with.
+ parser (Optional[ArgumentParser]): A parser to parse the option with.
Raises:
ValueError: If the parser parameter is invalid.
diff --git a/jsonargparse/core.py b/jsonargparse/core.py
index 57bf6d7..f700fdc 100644
--- a/jsonargparse/core.py
+++ b/jsonargparse/core.py
@@ -212,7 +212,7 @@ class ArgumentParser(ActionsContainer, ArgumentLinking, argparse.ArgumentParser)
self.groups = {}
self.required_args: Set[str] = set()
self.save_path_content: Set[str] = set()
- self.default_config_files = default_config_files
+ self.default_config_files = default_config_files # type: ignore
self.default_meta = default_meta
self.default_env = default_env
self.env_prefix = env_prefix
@@ -861,11 +861,11 @@ class ArgumentParser(ActionsContainer, ArgumentLinking, argparse.ArgumentParser)
## Methods related to defaults ##
- def set_defaults(self, *args, **kwargs) -> None:
+ def set_defaults(self, *args: Dict[str, Any], **kwargs: Any) -> None:
"""Sets default values from dictionary or keyword arguments.
Args:
- *args (dict): Dictionary defining the default values to set.
+ *args: Dictionary defining the default values to set.
**kwargs: Sets default values based on keyword arguments.
Raises:
@@ -938,7 +938,6 @@ class ArgumentParser(ActionsContainer, ArgumentLinking, argparse.ArgumentParser)
"""Returns a namespace with all default values.
Args:
- nested: Whether the namespace should be nested.
skip_check: Whether to skip check if configuration is valid.
Returns:
@@ -1314,7 +1313,7 @@ class ArgumentParser(ActionsContainer, ArgumentLinking, argparse.ArgumentParser)
## Properties ##
@property
- def error_handler(self):
+ def error_handler(self) -> Optional[Callable[['ArgumentParser', str], None]]:
"""Property for the error_handler function that is called when there are parsing errors.
:getter: Returns the current error_handler function.
@@ -1327,7 +1326,7 @@ class ArgumentParser(ActionsContainer, ArgumentLinking, argparse.ArgumentParser)
@error_handler.setter
- def error_handler(self, error_handler):
+ def error_handler(self, error_handler: Optional[Callable[['ArgumentParser', str], None]]):
if callable(error_handler) or error_handler is None:
self._error_handler = error_handler
else:
@@ -1335,7 +1334,7 @@ class ArgumentParser(ActionsContainer, ArgumentLinking, argparse.ArgumentParser)
@property
- def default_config_files(self):
+ def default_config_files(self) -> List[str]:
"""Default config file locations.
:getter: Returns the current default config file locations.
@@ -1348,7 +1347,7 @@ class ArgumentParser(ActionsContainer, ArgumentLinking, argparse.ArgumentParser)
@default_config_files.setter
- def default_config_files(self, default_config_files:Optional[List[str]]):
+ def default_config_files(self, default_config_files: Optional[List[str]]):
if default_config_files is None:
self._default_config_files = []
elif isinstance(default_config_files, list) and all(isinstance(x, str) for x in default_config_files):
diff --git a/jsonargparse/typehints.py b/jsonargparse/typehints.py
index 5c7a680..f3344ce 100644
--- a/jsonargparse/typehints.py
+++ b/jsonargparse/typehints.py
@@ -384,7 +384,7 @@ class ActionTypeHint(Action):
path_meta = val.pop('__path__', None) if isinstance(val, dict) else None
prev_val = cfg.get(self.dest) if cfg else None
- if not prev_val and not sub_defaults.get() and is_subclass_spec(self.default):
+ if prev_val is None and not sub_defaults.get() and is_subclass_spec(self.default):
prev_val = Namespace(class_path=self.default.class_path)
kwargs = {
diff --git a/jsonargparse/util.py b/jsonargparse/util.py
index e71042e..0f86ba8 100644
--- a/jsonargparse/util.py
+++ b/jsonargparse/util.py
@@ -586,12 +586,12 @@ class LoggerProperty:
def __init__(self, *args, logger: Union[bool, str, dict, logging.Logger] = False, **kwargs):
"""Initializer for LoggerProperty class."""
- self.logger = logger
+ self.logger = logger # type: ignore
super().__init__(*args, **kwargs)
@property
- def logger(self):
+ def logger(self) -> logging.Logger:
"""The logger property for the class.
:getter: Returns the current logger.
| omni-us/jsonargparse | fe55400e9564dbaf64219603ea1ce9de13a64ee5 | diff --git a/jsonargparse_tests/test_typing.py b/jsonargparse_tests/test_typing.py
index bbaf0dd..a800071 100755
--- a/jsonargparse_tests/test_typing.py
+++ b/jsonargparse_tests/test_typing.py
@@ -17,6 +17,7 @@ from jsonargparse.typing import (
path_type,
PositiveFloat,
PositiveInt,
+ register_type,
RegisteredType,
registered_types,
restricted_number_type,
@@ -254,5 +255,26 @@ class OtherTests(unittest.TestCase):
self.assertRaises(ValueError, lambda: timedelta_type.deserializer(delta_in))
+ def test_register_non_bool_cast_type(self):
+ class Elems:
+ def __init__(self, *elems):
+ self.elems = list(elems)
+ def __bool__(self):
+ raise RuntimeError('bool not supported')
+
+ self.assertRaises(RuntimeError, lambda: not Elems(1, 2))
+ register_type(Elems, lambda x: x.elems, lambda x: Elems(*x))
+
+ parser = ArgumentParser(error_handler=None)
+ parser.add_argument('--elems', type=Elems)
+ cfg = parser.parse_args(['--elems=[1, 2, 3]'])
+ self.assertIsInstance(cfg.elems, Elems)
+ self.assertEqual(cfg.elems.elems, [1, 2, 3])
+ dump = parser.dump(cfg, format='json')
+ self.assertEqual(dump, '{"elems":[1,2,3]}')
+
+ del registered_types[Elems]
+
+
if __name__ == '__main__':
unittest.main(verbosity=2)
| Support for conversion to `torch.Tensor`
## 🐛 Bug report
I am encountering a problem using the package with Lightning.
When trying to specify an `init_args` which expects a `torch.Tensor` (for example when specifying the weights of a loss function), an error occurs because torch module expects a tensor, not a list.
It should be possible to [register](https://jsonargparse.readthedocs.io/en/stable/index.html#registering-types) pytorch tensors using
```python
def serializer(x):
return x.tolist()
def deserializer(x):
return torch.tensor(x)
register_type(torch.Tensor, serializer, deserializer)
```
However, doing so results in an error:
```bash
main: error: Parser key "model": Problem with given class_path "MyModel":
- Configuration check failed :: Parser key "my_model": Value "Namespace(class_path='MySubModel', init_args=Namespace(..., loss=Namespace(class_path='torch.nn.CrossEntropyLoss', init_args=Namespace(weight=tensor([ 7.6200, 104.9100, 1.5600, 20.6500, 14.0500, 14.0600, 1.0000, 36.0700]), size_average=None, ignore_index=-100, reduce=None, reduction='mean', label_smoothing=0.0))))" does not validate against any of the types in typing.Optional[MySubModel]:
- Boolean value of Tensor with more than one value is ambiguous
...
```
Since a list is specified in the yaml and the namespace shows a `tensor([...])`, it looks like the deserializer is working correctly, but something is going wrong.
### Expected behavior
The list should be converted to a tensor without error.
### Environment
- jsonargparse 4.15.2
- Python 3.10.6
| 0.0 | [
"jsonargparse_tests/test_typing.py::OtherTests::test_register_non_bool_cast_type"
] | [
"jsonargparse_tests/test_typing.py::RestrictedNumberTests::test_ClosedUnitInterval",
"jsonargparse_tests/test_typing.py::RestrictedNumberTests::test_NonNegativeFloat",
"jsonargparse_tests/test_typing.py::RestrictedNumberTests::test_NonNegativeInt",
"jsonargparse_tests/test_typing.py::RestrictedNumberTests::test_OpenUnitInterval",
"jsonargparse_tests/test_typing.py::RestrictedNumberTests::test_PositiveFloat",
"jsonargparse_tests/test_typing.py::RestrictedNumberTests::test_PositiveInt",
"jsonargparse_tests/test_typing.py::RestrictedNumberTests::test_add_argument_type",
"jsonargparse_tests/test_typing.py::RestrictedNumberTests::test_already_registered",
"jsonargparse_tests/test_typing.py::RestrictedNumberTests::test_invalid_restricted_number_type",
"jsonargparse_tests/test_typing.py::RestrictedNumberTests::test_other_operators",
"jsonargparse_tests/test_typing.py::RestrictedStringTests::test_Email",
"jsonargparse_tests/test_typing.py::RestrictedStringTests::test_add_argument_type",
"jsonargparse_tests/test_typing.py::RestrictedStringTests::test_already_registered",
"jsonargparse_tests/test_typing.py::PathTypeTests::test_Path_fr",
"jsonargparse_tests/test_typing.py::PathTypeTests::test_already_registered",
"jsonargparse_tests/test_typing.py::PathTypeTests::test_path_like",
"jsonargparse_tests/test_typing.py::PathTypeTests::test_pathlib_path",
"jsonargparse_tests/test_typing.py::OtherTests::test_name_clash",
"jsonargparse_tests/test_typing.py::OtherTests::test_object_path_serializer_reimport_differs",
"jsonargparse_tests/test_typing.py::OtherTests::test_pickle_module_types",
"jsonargparse_tests/test_typing.py::OtherTests::test_serialize_class_method_path",
"jsonargparse_tests/test_typing.py::OtherTests::test_timedelta"
] | 2022-11-23 06:17:22+00:00 | 4,354 |
|
omni-us__jsonargparse-212 | diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index 23e37a4..5692d1a 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -28,6 +28,8 @@ Fixed
- List type with empty list default causes failure `PyLaia#48
<https://github.com/jpuigcerver/PyLaia/issues/48>`__.
- Pure dataclass instance default being considered as a subclass type.
+- Discard ``init_args`` after ``class_path`` change causes error `#205
+ <https://github.com/omni-us/jsonargparse/issues/205>`__.
v4.18.0 (2022-11-29)
diff --git a/jsonargparse/namespace.py b/jsonargparse/namespace.py
index cc62bc7..affd615 100644
--- a/jsonargparse/namespace.py
+++ b/jsonargparse/namespace.py
@@ -244,7 +244,7 @@ class Namespace(argparse.Namespace):
if isinstance(val, Namespace):
if branches:
yield key, val
- for subkey, subval in val.items():
+ for subkey, subval in val.items(branches):
yield key+'.'+del_clash_mark(subkey), subval
else:
yield key, val
diff --git a/jsonargparse/typehints.py b/jsonargparse/typehints.py
index 064c6d1..1edc7c8 100644
--- a/jsonargparse/typehints.py
+++ b/jsonargparse/typehints.py
@@ -295,8 +295,12 @@ class ActionTypeHint(Action):
@staticmethod
def discard_init_args_on_class_path_change(parser_or_action, prev_cfg, cfg):
+ if isinstance(prev_cfg, dict):
+ return
keys = list(prev_cfg.keys(branches=True))
- for key in keys:
+ num = 0
+ while num < len(keys):
+ key = keys[num]
prev_val = prev_cfg.get(key)
val = cfg.get(key)
if is_subclass_spec(prev_val) and is_subclass_spec(val):
@@ -305,6 +309,14 @@ class ActionTypeHint(Action):
action = _find_action(parser_or_action, key)
if isinstance(action, ActionTypeHint):
discard_init_args_on_class_path_change(action, prev_val, val)
+ prev_sub_cfg = prev_val.get('init_args')
+ if prev_sub_cfg:
+ sub_add_kwargs = getattr(action, 'sub_add_kwargs', {})
+ subparser = ActionTypeHint.get_class_parser(val['class_path'], sub_add_kwargs)
+ sub_cfg = val.get('init_args', Namespace())
+ ActionTypeHint.discard_init_args_on_class_path_change(subparser, prev_sub_cfg, sub_cfg)
+ keys = keys[:num+1] + [k for k in keys[num+1:] if not k.startswith(key+'.')]
+ num += 1
@staticmethod
| omni-us/jsonargparse | f37e6388a3fd85afd3ce8067b3495c1dee15956f | diff --git a/jsonargparse_tests/test_link_arguments.py b/jsonargparse_tests/test_link_arguments.py
index ca1d901..9a71eee 100755
--- a/jsonargparse_tests/test_link_arguments.py
+++ b/jsonargparse_tests/test_link_arguments.py
@@ -230,6 +230,9 @@ class LinkArgumentsTests(unittest.TestCase):
cfg = parser.parse_args(['--a='+json.dumps(a_value), '--c='+json.dumps(c_value)])
self.assertEqual(cfg.a.init_args.a1, c_value)
self.assertEqual(cfg.a.init_args.a2, c_value)
+ init = parser.instantiate_classes(cfg)
+ self.assertIsInstance(init.a, ClassA)
+ self.assertIsInstance(init.c, Calendar)
def test_link_arguments_on_parse_within_subcommand(self):
diff --git a/jsonargparse_tests/test_signatures.py b/jsonargparse_tests/test_signatures.py
index 49b7f71..c0364ab 100755
--- a/jsonargparse_tests/test_signatures.py
+++ b/jsonargparse_tests/test_signatures.py
@@ -9,6 +9,7 @@ from calendar import Calendar, January # type: ignore
from contextlib import redirect_stderr, redirect_stdout
from enum import Enum
from io import StringIO
+from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple, Union
import yaml
@@ -1309,6 +1310,59 @@ class SignaturesConfigTests(TempDirTestCase):
self.assertEqual(cfg.fit.model.foo, 123)
+ def test_config_nested_discard_init_args(self):
+ class Base:
+ def __init__(self, b: float = 0.5):
+ pass
+
+ class Sub1(Base):
+ def __init__(self, s1: str = 'x', **kwargs):
+ super().__init__(**kwargs)
+
+ class Sub2(Base):
+ def __init__(self, s2: int = 3, **kwargs):
+ super().__init__(**kwargs)
+
+ class Main:
+ def __init__(self, sub: Base = lazy_instance(Sub1)) -> None:
+ self.sub = sub
+
+ with mock_module(Base, Sub1, Sub2, Main) as module:
+ subconfig = {
+ 'sub': {
+ 'class_path': f'{module}.Sub2',
+ 'init_args': {'s2': 4},
+ }
+ }
+
+ for subtest in ['class', 'subclass']:
+ with self.subTest(subtest), warnings.catch_warnings(record=True) as w:
+ parser = ArgumentParser(error_handler=None)
+ parser.add_argument('--config', action=ActionConfigFile)
+
+ if subtest == 'class':
+ config = {'main': subconfig}
+ parser.add_class_arguments(Main, 'main')
+ else:
+ config = {
+ 'main': {
+ 'class_path': f'{module}.Main',
+ 'init_args': subconfig,
+ }
+ }
+ parser.add_subclass_arguments(Main, 'main')
+ parser.set_defaults(main=lazy_instance(Main))
+
+ config_path = Path('config.yaml')
+ config_path.write_text(yaml.safe_dump(config))
+
+ cfg = parser.parse_args([f'--config={config_path}'])
+ init = parser.instantiate_classes(cfg)
+ self.assertIsInstance(init.main, Main)
+ self.assertIsInstance(init.main.sub, Sub2)
+ self.assertIn("discarding init_args: {'s1': 'x'}", str(w[0].message))
+
+
@dataclasses.dataclass(frozen=True)
class MyDataClassA:
"""MyDataClassA description
| Discard `init_args` after `class_path` change causes error
## 🐛 Bug report
When composing configs, it appears that overwritten class paths do not properly drop the old `init_args` namespace, causing an error when the new class does not have the same `init_args`.
Here is the error message:
```bash
$ main fit --config config_1.yaml --config configs_2.yaml
/unix/atlastracking/svanstroud/miniconda3/envs/salt/lib/python3.10/site-packages/jsonargparse/typehints.py:909: UserWarning: Due to class_path change from 'models.GATv2Attention' to 'models.ScaledDotProductAttention', discarding init_args: {'num_heads': 8, 'head_dim': 16, 'activation': Namespace(class_path='torch.nn.SiLU')}.
warnings.warn(
usage: main [-h] [-c CONFIG] [--print_config[=flags]] {fit,validate,test,predict,tune} ...
main: error: Parser key "model": Problem with given class_path 'models.Tagger':
- Parser key "gnn": Does not validate against any of the Union subtypes
Subtypes: (<class 'torch.nn.modules.module.Module'>, <class 'NoneType'>)
Errors:
- Problem with given class_path 'models.Transformer':
- Parser key "attention": Problem with given class_path 'models.ScaledDotProductAttention':
- 'Configuration check failed :: No action for destination key "num_heads" to check its value.'
- Expected a <class 'NoneType'>
Given value type: <class 'jsonargparse.namespace.Namespace'>
Given value: Namespace(class_path='models.Transformer', init_args=Namespace(embd_dim=128, num_heads=8, num_layers=8, attention=Namespace(class_path='models.ScaledDotProductAttention', init_args=Namespace(num_heads=8, head_dim=16, activation=Namespace(class_path='torch.nn.SiLU'))), activation='SiLU', residual=True, norm_layer='LayerNorm', dropout=0.1, out_proj=False))
```
### To reproduce
<!--
Please include a code snippet that reproduces the bug and the output that
running it gives. The following snippet templates might help:
1. Using the CLI function
```python
import jsonargparse
# Here define one or more functions or classes
def func1(param1: int, ...):
...
# Run the CLI providing the components
jsonargparse.CLI([func1, ...], error_handler=None)
```
2. Manually constructing a parser
```python
import jsonargparse
parser = jsonargparse.ArgumentParser(error_handler=None)
# Here add to the parser only argument(s) relevant to the problem
# If a yaml config is required, it can be included in the same snippet as follows:
import yaml
parser.add_argument('--config', action=jsonargparse.ActionConfigFile)
config = yaml.safe_dump({
'key1': 'val1',
})
# Preferable that the command line arguments are given to the parse_args call
result = parser.parse_args([f'--config={config}', '--key2=val2', ...])
# If the problem is in the parsed result, print it to stdout
print(parser.dump(result))
# If the problem is in class instantiation
parser.instantiate_classes(result)
```
-->
### Expected behavior
The overwriting class should not be required to have the same `init_args` as the overwritten class.
It would also be nice to have an option to suppress the warning about overwritten args.
### Environment
<!-- Fill in the list below. -->
- jsonargparse 4.18.0
- Python 3.10.6
| 0.0 | [
"jsonargparse_tests/test_signatures.py::SignaturesConfigTests::test_config_nested_discard_init_args"
] | [
"jsonargparse_tests/test_link_arguments.py::LinkArgumentsTests::test_link_arguments_on_instantiate",
"jsonargparse_tests/test_link_arguments.py::LinkArgumentsTests::test_link_arguments_on_instantiate_multi_source",
"jsonargparse_tests/test_link_arguments.py::LinkArgumentsTests::test_link_arguments_on_instantiate_no_compute_no_target_instantiate",
"jsonargparse_tests/test_link_arguments.py::LinkArgumentsTests::test_link_arguments_on_instantiate_object_in_attribute",
"jsonargparse_tests/test_link_arguments.py::LinkArgumentsTests::test_link_arguments_on_parse_add_class_arguments",
"jsonargparse_tests/test_link_arguments.py::LinkArgumentsTests::test_link_arguments_on_parse_add_subclass_arguments",
"jsonargparse_tests/test_link_arguments.py::LinkArgumentsTests::test_link_arguments_on_parse_add_subclass_arguments_as_dict",
"jsonargparse_tests/test_link_arguments.py::LinkArgumentsTests::test_link_arguments_on_parse_add_subclass_arguments_with_instantiate_false",
"jsonargparse_tests/test_link_arguments.py::LinkArgumentsTests::test_link_arguments_on_parse_compute_fn_single_arguments",
"jsonargparse_tests/test_link_arguments.py::LinkArgumentsTests::test_link_arguments_on_parse_compute_fn_subclass_spec",
"jsonargparse_tests/test_link_arguments.py::LinkArgumentsTests::test_link_arguments_on_parse_entire_subclass",
"jsonargparse_tests/test_link_arguments.py::LinkArgumentsTests::test_link_arguments_on_parse_within_subcommand",
"jsonargparse_tests/test_link_arguments.py::LinkArgumentsTests::test_link_arguments_subclass_missing_param_issue_129",
"jsonargparse_tests/test_link_arguments.py::LinkArgumentsTempDirTests::test_linking_deep_targets",
"jsonargparse_tests/test_link_arguments.py::LinkArgumentsTempDirTests::test_linking_deep_targets_mapping",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_class_arguments",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_class_conditional_kwargs",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_class_from_function_arguments",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_class_implemented_with_new",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_class_required_args",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_class_without_args",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_class_without_valid_args",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_function_arguments",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_function_with_dict_int_keys_arg",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_method_arguments",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_method_arguments_parent_classes",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_subclass_arguments",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_subclass_arguments_tuple",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_subclass_discard_init_args",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_subclass_init_args_in_subcommand",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_subclass_init_args_without_class_path",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_subclass_merge_init_args_in_full_config",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_subclass_nested_discard_init_args",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_basic_subtypes",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_class_from_function",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_class_path_override_with_mixed_type",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_dict_int_str_type",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_dict_type_nested_in_two_level_subclasses",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_fail_untyped_false",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_final_class",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_implicit_optional",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_instantiate_classes",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_instantiate_classes_subcommand",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_invalid_class_from_function",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_invalid_type",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_logger_debug",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_not_required_group",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_optional_enum",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_print_config",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_print_config_subclass_required_param_issue_115",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_required_group",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_skip",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_skip_in_add_subclass_arguments",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_skip_within_subclass_type",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_subclass_help",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_type_any_serialize",
"jsonargparse_tests/test_signatures.py::SignaturesConfigTests::test_add_class_arguments_with_config_not_found",
"jsonargparse_tests/test_signatures.py::SignaturesConfigTests::test_add_function_arguments_config",
"jsonargparse_tests/test_signatures.py::SignaturesConfigTests::test_add_subclass_arguments_with_config",
"jsonargparse_tests/test_signatures.py::SignaturesConfigTests::test_add_subclass_arguments_with_multifile_save",
"jsonargparse_tests/test_signatures.py::SignaturesConfigTests::test_config_within_config",
"jsonargparse_tests/test_signatures.py::SignaturesConfigTests::test_parent_parser_default_config_files_lightning_issue_11622",
"jsonargparse_tests/test_signatures.py::SignaturesConfigTests::test_subclass_required_param_with_default_config_files",
"jsonargparse_tests/test_signatures.py::DataclassesTests::test_compose_dataclasses",
"jsonargparse_tests/test_signatures.py::DataclassesTests::test_dataclass_add_argument_type",
"jsonargparse_tests/test_signatures.py::DataclassesTests::test_dataclass_add_argument_type_some_required",
"jsonargparse_tests/test_signatures.py::DataclassesTests::test_dataclass_field_default_factory",
"jsonargparse_tests/test_signatures.py::DataclassesTests::test_dataclass_typehint",
"jsonargparse_tests/test_signatures.py::DataclassesTests::test_dataclass_typehint_in_subclass",
"jsonargparse_tests/test_signatures.py::DataclassesTests::test_instantiate_classes_dataclasses_lightning_issue_9207"
] | 2022-12-15 06:28:16+00:00 | 4,355 |
|
omni-us__jsonargparse-223 | diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index 6a9373a..688ae1c 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -43,6 +43,8 @@ Fixed
- ``fail_untyped=False`` not propagated to subclass ``--*.help`` actions.
- Issues reported by CodeQL.
- Incorrect value when ``Path`` is cast to ``str`` and ``rel_path`` was changed.
+- Argument links with target a subclass mixed with other types not working `#208
+ <https://github.com/omni-us/jsonargparse/issues/208>`__.
Changed
^^^^^^^
diff --git a/jsonargparse/link_arguments.py b/jsonargparse/link_arguments.py
index 0329aab..97030b3 100644
--- a/jsonargparse/link_arguments.py
+++ b/jsonargparse/link_arguments.py
@@ -135,7 +135,7 @@ class ActionLink(Action):
assert self.target[1] is not None
from .typehints import ActionTypeHint
- is_target_subclass = ActionTypeHint.is_subclass_typehint(self.target[1])
+ is_target_subclass = ActionTypeHint.is_subclass_typehint(self.target[1], all_subtypes=False)
valid_target_init_arg = is_target_subclass and target.startswith(self.target[1].dest+'.init_args.')
valid_target_leaf = self.target[1].dest == target
if not valid_target_leaf and is_target_subclass and not valid_target_init_arg:
@@ -321,7 +321,7 @@ class ActionLink(Action):
def set_target_value(action: 'ActionLink', value: Any, cfg: Namespace, logger) -> None:
target_key, target_action = action.target
from .typehints import ActionTypeHint
- if ActionTypeHint.is_subclass_typehint(target_action):
+ if ActionTypeHint.is_subclass_typehint(target_action, all_subtypes=False):
if target_key == target_action.dest: # type: ignore
target_action._check_type(value) # type: ignore
elif target_key not in cfg:
| omni-us/jsonargparse | 0d73a844ea6355dfddc49c145e25e7d4f22ffe83 | diff --git a/jsonargparse_tests/test_link_arguments.py b/jsonargparse_tests/test_link_arguments.py
index 1c69b25..eae5f32 100755
--- a/jsonargparse_tests/test_link_arguments.py
+++ b/jsonargparse_tests/test_link_arguments.py
@@ -183,6 +183,30 @@ class LinkArgumentsTests(unittest.TestCase):
parser.parse_args(['--a='+json.dumps(a_value), '--c=calendar.Calendar'])
+ def test_link_arguments_on_parse_mixed_subclass_target(self):
+ class Logger:
+ def __init__(self, save_dir: Optional[str] = None):
+ pass
+
+ class Trainer:
+ def __init__(
+ self,
+ save_dir: Optional[str] = None,
+ logger: Union[bool, Logger] = False,
+ ):
+ pass
+
+ with mock_module(Logger):
+ parser = ArgumentParser()
+ parser.add_class_arguments(Trainer, 'trainer')
+ parser.link_arguments('trainer.save_dir', 'trainer.logger.init_args.save_dir')
+ cfg = parser.parse_args([])
+ self.assertEqual(cfg.trainer, Namespace(logger=False, save_dir=None))
+ cfg = parser.parse_args(['--trainer.save_dir=logs', '--trainer.logger=Logger'])
+ self.assertEqual(cfg.trainer.save_dir, 'logs')
+ self.assertEqual(cfg.trainer.logger.init_args, Namespace(save_dir='logs'))
+
+
def test_link_arguments_on_parse_add_subclass_arguments_with_instantiate_false(self):
class ClassA:
def __init__(
| Link arguments "Target key must be for an individual argument"
<!-- If you like this project, please ⭐ star it https://github.com/omni-us/jsonargparse/ -->
## 🐛 Bug report
Certain argument links produce an error. For example, using a subclass of the `LightningCLI` that links the trainer `default_root_dir` to the logger `save_dir` arguments, the following error occurs.
```bash
Traceback (most recent call last):
...
File ".../clitest.py", line 8, in add_arguments_to_parser
parser.link_arguments("trainer.default_root_dir", "trainer.logger.init_args.save_dir")
File ".../lib/python3.10/site-packages/jsonargparse/link_arguments.py", line 379, in link_arguments
ActionLink(self, source, target, compute_fn, apply_on)
File ".../lib/python3.10/site-packages/jsonargparse/link_arguments.py", line 141, in __init__
raise ValueError(f'Target key "{target}" must be for an individual argument.')
ValueError: Target key "trainer.logger.init_args.save_dir" must be for an individual argument.
```
A link in the the other direction `save_dir` -> `default_root_dir` seems to work okay,
I suspect the issue may be to do with the fact that the target key exists within an optional `trainer.logger` class.
### To reproduce
```python
from pytorch_lightning.cli import LightningCLI
from pytorch_lightning.demos.boring_classes import BoringDataModule, DemoModel
class MyCLI(LightningCLI):
def add_arguments_to_parser(self, parser) -> None:
#parser.link_arguments("trainer.logger.init_args.save_dir", "trainer.default_root_dir") # works
parser.link_arguments("trainer.default_root_dir", "trainer.logger.init_args.save_dir") # error
def cli_main():
cli = MyCLI(DemoModel, BoringDataModule)
if __name__ == "__main__":
cli_main()
```
### Expected behavior
I'm opening an issue here as:
- It would be nice to allow the link to be ignored when the target is null (perhaps with an additional parameter to the `link_arguments` function e.g. `ignore_null_target`)
- In any case, the error message could be improved.
### Environment
<!-- Fill in the list below. -->
- jsonargparse 4.18.0
- Python 3.10.6 | 0.0 | [
"jsonargparse_tests/test_link_arguments.py::LinkArgumentsTests::test_link_arguments_on_parse_mixed_subclass_target"
] | [
"jsonargparse_tests/test_link_arguments.py::LinkArgumentsTests::test_link_arguments_on_instantiate",
"jsonargparse_tests/test_link_arguments.py::LinkArgumentsTests::test_link_arguments_on_instantiate_multi_source",
"jsonargparse_tests/test_link_arguments.py::LinkArgumentsTests::test_link_arguments_on_instantiate_no_compute_no_target_instantiate",
"jsonargparse_tests/test_link_arguments.py::LinkArgumentsTests::test_link_arguments_on_instantiate_object_in_attribute",
"jsonargparse_tests/test_link_arguments.py::LinkArgumentsTests::test_link_arguments_on_parse_add_class_arguments",
"jsonargparse_tests/test_link_arguments.py::LinkArgumentsTests::test_link_arguments_on_parse_add_subclass_arguments",
"jsonargparse_tests/test_link_arguments.py::LinkArgumentsTests::test_link_arguments_on_parse_add_subclass_arguments_as_dict",
"jsonargparse_tests/test_link_arguments.py::LinkArgumentsTests::test_link_arguments_on_parse_add_subclass_arguments_with_instantiate_false",
"jsonargparse_tests/test_link_arguments.py::LinkArgumentsTests::test_link_arguments_on_parse_compute_fn_single_arguments",
"jsonargparse_tests/test_link_arguments.py::LinkArgumentsTests::test_link_arguments_on_parse_compute_fn_subclass_spec",
"jsonargparse_tests/test_link_arguments.py::LinkArgumentsTests::test_link_arguments_on_parse_entire_subclass",
"jsonargparse_tests/test_link_arguments.py::LinkArgumentsTests::test_link_arguments_on_parse_within_subcommand",
"jsonargparse_tests/test_link_arguments.py::LinkArgumentsTests::test_link_arguments_previous_source_as_target_error",
"jsonargparse_tests/test_link_arguments.py::LinkArgumentsTests::test_link_arguments_previous_target_as_source_error",
"jsonargparse_tests/test_link_arguments.py::LinkArgumentsTests::test_link_arguments_subclass_missing_param_issue_129",
"jsonargparse_tests/test_link_arguments.py::LinkArgumentsTempDirTests::test_linking_deep_targets",
"jsonargparse_tests/test_link_arguments.py::LinkArgumentsTempDirTests::test_linking_deep_targets_mapping"
] | 2022-12-23 16:25:57+00:00 | 4,356 |
|
omni-us__jsonargparse-233 | diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index 0aef214..58bf380 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -15,6 +15,11 @@ paths are considered internals and can change in minor and patch releases.
v4.20.0 (2023-01-??)
--------------------
+Fixed
+^^^^^
+- ``add_subcommands`` fails when parser has required argument and default config
+ available `#232 <https://github.com/omni-us/jsonargparse/issues/232>`__.
+
Changed
^^^^^^^
- When parsing fails now ``argparse.ArgumentError`` is raised instead of
diff --git a/jsonargparse/core.py b/jsonargparse/core.py
index a951acb..3420ba4 100644
--- a/jsonargparse/core.py
+++ b/jsonargparse/core.py
@@ -670,7 +670,7 @@ class ArgumentParser(ParserDeprecations, ActionsContainer, ArgumentLinking, argp
"""
if 'description' not in kwargs:
kwargs['description'] = 'For more details of each subcommand, add it as an argument followed by --help.'
- with parser_context(parent_parser=self):
+ with parser_context(parent_parser=self, lenient_check=True):
subcommands: _ActionSubCommands = super().add_subparsers(dest=dest, **kwargs) # type: ignore
if required:
self.required_args.add(dest)
| omni-us/jsonargparse | 89f88de4d9b93700b755a3cedde401e312f461c6 | diff --git a/jsonargparse_tests/test_core.py b/jsonargparse_tests/test_core.py
index eb154e0..b76dfe1 100755
--- a/jsonargparse_tests/test_core.py
+++ b/jsonargparse_tests/test_core.py
@@ -2,6 +2,7 @@
import json
import os
+import pathlib
import pickle
import sys
import unittest
@@ -1012,6 +1013,19 @@ class ConfigFilesTests(TempDirTestCase):
self.assertIn('defaults_2.yaml', out.getvalue())
+ def test_required_arg_in_default_config_and_add_subcommands(self):
+ pathlib.Path('config.yaml').write_text('output: test\nprepare:\n media: test\n')
+ parser = ArgumentParser(default_config_files=['config.yaml'])
+ parser.add_argument('--output', required=True)
+ subcommands = parser.add_subcommands()
+ prepare = ArgumentParser()
+ prepare.add_argument('--media', required=True)
+ subcommands.add_subcommand('prepare', prepare)
+ cfg = parser.parse_args([])
+ self.assertEqual(str(cfg.__default_config__), 'config.yaml')
+ self.assertEqual(strip_meta(cfg), Namespace(output='test', prepare=Namespace(media='test'), subcommand='prepare'))
+
+
def test_ActionConfigFile(self):
os.mkdir(os.path.join(self.tmpdir, 'subdir'))
rel_yaml_file = os.path.join('subdir', 'config.yaml')
| Issue with Root Args and config file
## 🐛 Bug report
An error
`jsonargparse.util.ParserError: Problem in default config file "/home/main/Tools/.config/config.yaml" :: Configuration check failed :: No action for destination key "prepare.output" to check its value.
`
is raised when trying to parse args
### To reproduce
```
parser = ArgumentParser(default_config_files=[os.path.join('.config/config.yaml')])
parser.add_argument('-c','--config', action=ActionConfigFile,help="override config file")
parser.add_argument("-o","--output",help="Path to Dir",required=True)
prepare = ArgumentParser(description="Prepare file to be uploaded")
prepare.add_argument('-m','--media',help="Directory to retrive media files",required=True)
subcommands = parser.add_subcommands()
subcommands.add_subcommand('prepare',prepare, help="prepare mediafile for upload")
```
root argument must have required=True
root argument must also come before any group arguments.
Also Note: I have been able to fix this by setting root args to be the last argument
It strange because it also can parses correctly if I set required=False
### Expected behavior
Parse arguments
### Environment
- jsonargparse version 4.19.0
- Python version 3.8
- How jsonargparse was installed (e.g. `pip install jsonargparse):
- OS Linux
| 0.0 | [
"jsonargparse_tests/test_core.py::ConfigFilesTests::test_required_arg_in_default_config_and_add_subcommands"
] | [
"jsonargparse_tests/test_core.py::ParsersTests::test_cfg_base",
"jsonargparse_tests/test_core.py::ParsersTests::test_default_env",
"jsonargparse_tests/test_core.py::ParsersTests::test_env_prefix",
"jsonargparse_tests/test_core.py::ParsersTests::test_parse_args",
"jsonargparse_tests/test_core.py::ParsersTests::test_parse_env",
"jsonargparse_tests/test_core.py::ParsersTests::test_parse_object",
"jsonargparse_tests/test_core.py::ParsersTests::test_parse_path",
"jsonargparse_tests/test_core.py::ParsersTests::test_parse_string",
"jsonargparse_tests/test_core.py::ParsersTests::test_parse_string_not_dict",
"jsonargparse_tests/test_core.py::ParsersTests::test_parse_unexpected_kwargs",
"jsonargparse_tests/test_core.py::ParsersTests::test_precedence_of_sources",
"jsonargparse_tests/test_core.py::ArgumentFeaturesTests::test_choices",
"jsonargparse_tests/test_core.py::ArgumentFeaturesTests::test_nargs",
"jsonargparse_tests/test_core.py::ArgumentFeaturesTests::test_positionals",
"jsonargparse_tests/test_core.py::ArgumentFeaturesTests::test_required",
"jsonargparse_tests/test_core.py::AdvancedFeaturesTests::test_optional_subcommand",
"jsonargparse_tests/test_core.py::AdvancedFeaturesTests::test_subcommand_print_config_default_env_issue_126",
"jsonargparse_tests/test_core.py::AdvancedFeaturesTests::test_subcommand_without_options",
"jsonargparse_tests/test_core.py::AdvancedFeaturesTests::test_subcommands",
"jsonargparse_tests/test_core.py::AdvancedFeaturesTests::test_subsubcommands",
"jsonargparse_tests/test_core.py::AdvancedFeaturesTests::test_subsubcommands_bad_order",
"jsonargparse_tests/test_core.py::AdvancedFeaturesTests::test_urls",
"jsonargparse_tests/test_core.py::OutputTests::test_dump",
"jsonargparse_tests/test_core.py::OutputTests::test_dump_formats",
"jsonargparse_tests/test_core.py::OutputTests::test_dump_order",
"jsonargparse_tests/test_core.py::OutputTests::test_dump_path_type",
"jsonargparse_tests/test_core.py::OutputTests::test_dump_restricted_float_type",
"jsonargparse_tests/test_core.py::OutputTests::test_dump_restricted_int_type",
"jsonargparse_tests/test_core.py::OutputTests::test_dump_restricted_string_type",
"jsonargparse_tests/test_core.py::OutputTests::test_dump_skip_default",
"jsonargparse_tests/test_core.py::OutputTests::test_dump_skip_default_nested",
"jsonargparse_tests/test_core.py::OutputTests::test_print_config",
"jsonargparse_tests/test_core.py::OutputTests::test_save",
"jsonargparse_tests/test_core.py::OutputTests::test_save_failures",
"jsonargparse_tests/test_core.py::OutputTests::test_save_path_content",
"jsonargparse_tests/test_core.py::ConfigFilesTests::test_ActionConfigFile",
"jsonargparse_tests/test_core.py::ConfigFilesTests::test_ActionConfigFile_failures",
"jsonargparse_tests/test_core.py::ConfigFilesTests::test_default_config_files",
"jsonargparse_tests/test_core.py::ConfigFilesTests::test_get_default_with_multiple_default_config_files",
"jsonargparse_tests/test_core.py::OtherTests::test_add_multiple_config_arguments_error",
"jsonargparse_tests/test_core.py::OtherTests::test_capture_parser",
"jsonargparse_tests/test_core.py::OtherTests::test_check_config_branch",
"jsonargparse_tests/test_core.py::OtherTests::test_debug_environment_variable",
"jsonargparse_tests/test_core.py::OtherTests::test_exit_on_error",
"jsonargparse_tests/test_core.py::OtherTests::test_invalid_parser_mode",
"jsonargparse_tests/test_core.py::OtherTests::test_merge_config",
"jsonargparse_tests/test_core.py::OtherTests::test_meta_key_failures",
"jsonargparse_tests/test_core.py::OtherTests::test_named_groups",
"jsonargparse_tests/test_core.py::OtherTests::test_parse_args_invalid_args",
"jsonargparse_tests/test_core.py::OtherTests::test_parse_known_args",
"jsonargparse_tests/test_core.py::OtherTests::test_parse_known_args_without_caller_module",
"jsonargparse_tests/test_core.py::OtherTests::test_pickle_parser",
"jsonargparse_tests/test_core.py::OtherTests::test_set_defaults_config_argument_error",
"jsonargparse_tests/test_core.py::OtherTests::test_set_get_defaults",
"jsonargparse_tests/test_core.py::OtherTests::test_strip_unknown",
"jsonargparse_tests/test_core.py::OtherTests::test_unrecognized_arguments",
"jsonargparse_tests/test_core.py::OtherTests::test_version_print"
] | 2023-01-19 21:24:13+00:00 | 4,357 |
|
omni-us__jsonargparse-239 | diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index 58bf380..b5624a2 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -15,6 +15,11 @@ paths are considered internals and can change in minor and patch releases.
v4.20.0 (2023-01-??)
--------------------
+Added
+^^^^^
+- ``CLI`` support for callable class instances `#238
+ <https://github.com/omni-us/jsonargparse/issues/238>`__.
+
Fixed
^^^^^
- ``add_subcommands`` fails when parser has required argument and default config
diff --git a/jsonargparse/cli.py b/jsonargparse/cli.py
index 92fbeda..08dfd46 100644
--- a/jsonargparse/cli.py
+++ b/jsonargparse/cli.py
@@ -52,7 +52,10 @@ def CLI(
module = inspect.getmodule(caller).__name__ # type: ignore
components = [
v for v in caller.f_locals.values()
- if (inspect.isfunction(v) or inspect.isclass(v)) and inspect.getmodule(v).__name__ == module # type: ignore
+ if (
+ (inspect.isclass(v) or callable(v)) and
+ getattr(inspect.getmodule(v), '__name__', None) == module
+ )
]
if len(components) == 0:
raise ValueError('Either components argument must be given or there must be at least one '
@@ -61,6 +64,10 @@ def CLI(
elif not isinstance(components, list):
components = [components]
+ unexpected = [c for c in components if not (inspect.isclass(c) or callable(c))]
+ if unexpected:
+ raise ValueError(f'Unexpected components, not class or function: {unexpected}')
+
parser = parser_class(default_meta=False, **kwargs)
parser.add_argument('--config', action=ActionConfigFile, help=config_help)
@@ -108,11 +115,7 @@ def get_help_str(component, logger):
def _add_component_to_parser(component, parser, as_positional, fail_untyped, config_help):
kwargs = dict(as_positional=as_positional, fail_untyped=fail_untyped, sub_configs=True)
- if inspect.isfunction(component):
- added_args = parser.add_function_arguments(component, as_group=False, **kwargs)
- if not parser.description:
- parser.description = get_help_str(component, parser.logger)
- else:
+ if inspect.isclass(component):
added_args = parser.add_class_arguments(component, **kwargs)
subcommands = parser.add_subcommands(required=True)
for key in [k for k, v in inspect.getmembers(component) if callable(v) and k[0] != '_']:
@@ -124,12 +127,16 @@ def _add_component_to_parser(component, parser, as_positional, fail_untyped, con
if not added_subargs:
remove_actions(subparser, (ActionConfigFile, _ActionPrintConfig))
subcommands.add_subcommand(key, subparser, help=get_help_str(getattr(component, key), parser.logger))
+ else:
+ added_args = parser.add_function_arguments(component, as_group=False, **kwargs)
+ if not parser.description:
+ parser.description = get_help_str(component, parser.logger)
return added_args
def _run_component(component, cfg):
cfg.pop('config', None)
- if inspect.isfunction(component):
+ if not inspect.isclass(component):
return component(**cfg)
subcommand = cfg.pop('subcommand')
subcommand_cfg = cfg.pop(subcommand, {})
diff --git a/jsonargparse/typehints.py b/jsonargparse/typehints.py
index 76d4ad7..9c1f525 100644
--- a/jsonargparse/typehints.py
+++ b/jsonargparse/typehints.py
@@ -146,11 +146,7 @@ class ActionTypeHint(Action):
if sum(subtype_supported) < len(subtype_supported):
discard = {typehint.__args__[n] for n, s in enumerate(subtype_supported) if not s}
kwargs['logger'].debug(f'Discarding unsupported subtypes {discard} from {typehint}')
- orig_typehint = typehint # deepcopy does not copy ForwardRef
- typehint = deepcopy(orig_typehint)
- typehint.__args__ = tuple(
- orig_typehint.__args__[n] for n, s in enumerate(subtype_supported) if s
- )
+ typehint = Union[tuple(t for t, s in zip(typehint.__args__, subtype_supported) if s)] # type: ignore
self._typehint = typehint
self._enable_path = False if is_optional(typehint, Path) else enable_path
elif '_typehint' not in kwargs:
| omni-us/jsonargparse | fadff045095c6657af7b764c880eefbca5ea829c | diff --git a/jsonargparse_tests/base.py b/jsonargparse_tests/base.py
index dcf3afa..0123342 100644
--- a/jsonargparse_tests/base.py
+++ b/jsonargparse_tests/base.py
@@ -38,6 +38,8 @@ def mock_module(*args):
__module__ = 'jsonargparse_tests'
for component in args:
component.__module__ = __module__
+ if not hasattr(component, '__name__'):
+ component.__name__ = type(component).__name__.lower()
component.__qualname__ = component.__name__
if inspect.isclass(component):
methods = [k for k, v in inspect.getmembers(component) if callable(v) and k[0] != '_']
diff --git a/jsonargparse_tests/test_cli.py b/jsonargparse_tests/test_cli.py
index 93874ab..10daca8 100755
--- a/jsonargparse_tests/test_cli.py
+++ b/jsonargparse_tests/test_cli.py
@@ -2,6 +2,7 @@
import sys
import unittest
+import unittest.mock
from contextlib import redirect_stderr, redirect_stdout
from io import StringIO
from typing import Optional
@@ -16,6 +17,11 @@ from jsonargparse_tests.base import TempDirTestCase, mock_module
class CLITests(unittest.TestCase):
+ def test_unexpected(self):
+ with self.assertRaises(ValueError):
+ CLI(0)
+
+
def test_single_function_cli(self):
def function(a1: float):
return a1
@@ -36,6 +42,16 @@ class CLITests(unittest.TestCase):
self.assertIn('function CLITests.test_single_function_cli', out.getvalue())
+ def test_callable_instance(self):
+ class CallableClass:
+ def __call__(self, x: int):
+ return x
+
+ instance = CallableClass()
+ with mock_module(instance):
+ self.assertEqual(3, CLI(instance, as_positional=False, args=['--x=3']))
+
+
def test_multiple_functions_cli(self):
def cmd1(a1: int):
return a1
| CLI does not work with callable component?
<!-- If you like this project, please ⭐ star it https://github.com/omni-us/jsonargparse/ -->
## 🐛 Bug report
CLI currently breaks if I pass in a callable instance instead of a function. It would be nice not to break this abstraction.
### To reproduce
```python
from dataclasses import dataclass
from jsonargparse import CLI
@dataclass
class Foo:
def __call__(self, x: int):
return x
if __name__ == "__main__":
f = Foo()
CLI(f, as_positional=False)
```
```
❯ python test.py
Traceback (most recent call last):
File "/home/venky/dev/instant-science/name_generator/test.py", line 14, in <module>
CLI(f, as_positional=False)
File "/home/venky/dev/instant-science/name_generator/.venv/lib/python3.9/site-packages/jsonargparse/cli.py", line 69, in CLI
_add_component_to_parser(component, parser, as_positional, fail_untyped, config_help)
File "/home/venky/dev/instant-science/name_generator/.venv/lib/python3.9/site-packages/jsonargparse/cli.py", line 116, in _add_component_to_parser
added_args = parser.add_class_arguments(component, **kwargs)
File "/home/venky/dev/instant-science/name_generator/.venv/lib/python3.9/site-packages/jsonargparse/signatures.py", line 70, in add_class_arguments
raise ValueError(f'Expected "theclass" parameter to be a class type, got: {theclass}.')
ValueError: Expected "theclass" parameter to be a class type, got: Foo().
```
### Expected behavior
It should work similar to `def foo(x: int)`.
### Environment
- jsonargparse version (e.g., 4.8.0): 4.19
- Python version (e.g., 3.9): 3.9
- How jsonargparse was installed (e.g. `pip install jsonargparse[all]`): pip install jsonargparse[all]
- OS (e.g., Linux): linux
| 0.0 | [
"jsonargparse_tests/test_cli.py::CLITests::test_callable_instance"
] | [
"jsonargparse_tests/test_cli.py::CLITests::test_empty_context",
"jsonargparse_tests/test_cli.py::CLITests::test_function_and_class_cli",
"jsonargparse_tests/test_cli.py::CLITests::test_multiple_functions_cli",
"jsonargparse_tests/test_cli.py::CLITests::test_non_empty_context",
"jsonargparse_tests/test_cli.py::CLITests::test_single_class_cli",
"jsonargparse_tests/test_cli.py::CLITests::test_single_function_cli",
"jsonargparse_tests/test_cli.py::CLITests::test_unexpected",
"jsonargparse_tests/test_cli.py::CLITempDirTests::test_final_and_subclass_type_config_file",
"jsonargparse_tests/test_cli.py::CLITempDirTests::test_subclass_type_config_file"
] | 2023-02-09 20:47:40+00:00 | 4,358 |
|
omni-us__jsonargparse-242 | diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index b5624a2..c80d4ea 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -48,6 +48,7 @@ v4.19.0 (2022-12-27)
Added
^^^^^
+- ``add_dataclass_arguments`` now supports the ``fail_untyped`` parameter
- ``CLI`` now supports the ``fail_untyped`` and ``parser_class`` parameters.
- ``bytes`` and ``bytearray`` registered on first use and decodes from standard
Base64.
diff --git a/jsonargparse/signatures.py b/jsonargparse/signatures.py
index 1e3cf03..cd19e3f 100644
--- a/jsonargparse/signatures.py
+++ b/jsonargparse/signatures.py
@@ -312,6 +312,7 @@ class SignatureArguments(LoggerProperty):
kwargs['required'] = True
is_subclass_typehint = False
is_final_class_typehint = is_final_class(annotation)
+ is_pure_dataclass_typehint = is_pure_dataclass(annotation)
dest = (nested_key+'.' if nested_key else '') + name
args = [dest if is_required and as_positional else '--'+dest]
if param.origin:
@@ -326,7 +327,7 @@ class SignatureArguments(LoggerProperty):
if annotation in {str, int, float, bool} or \
is_subclass(annotation, (str, int, float)) or \
is_final_class_typehint or \
- is_pure_dataclass(annotation):
+ is_pure_dataclass_typehint:
kwargs['type'] = annotation
elif annotation != inspect_empty:
try:
@@ -353,7 +354,7 @@ class SignatureArguments(LoggerProperty):
'sub_configs': sub_configs,
'instantiate': instantiate,
}
- if is_final_class_typehint:
+ if is_final_class_typehint or is_pure_dataclass_typehint:
kwargs.update(sub_add_kwargs)
action = group.add_argument(*args, **kwargs)
action.sub_add_kwargs = sub_add_kwargs
@@ -370,6 +371,7 @@ class SignatureArguments(LoggerProperty):
nested_key: str,
default: Optional[Union[Type, dict]] = None,
as_group: bool = True,
+ fail_untyped: bool = True,
**kwargs
) -> List[str]:
"""Adds arguments from a dataclass based on its field types and docstrings.
@@ -379,6 +381,7 @@ class SignatureArguments(LoggerProperty):
nested_key: Key for nested namespace.
default: Value for defaults. Must be instance of or kwargs for theclass.
as_group: Whether arguments should be added to a new argument group.
+ fail_untyped: Whether to raise exception if a required parameter does not have a type.
Returns:
The list of arguments added.
@@ -413,6 +416,7 @@ class SignatureArguments(LoggerProperty):
nested_key,
params[field.name],
added_args,
+ fail_untyped=fail_untyped,
default=defaults.get(field.name, inspect_empty),
)
| omni-us/jsonargparse | dc5cdac8c4b1e029efaa2c273ea740e60fcacec7 | diff --git a/jsonargparse_tests/test_signatures.py b/jsonargparse_tests/test_signatures.py
index 6a4d3cb..35400a1 100755
--- a/jsonargparse_tests/test_signatures.py
+++ b/jsonargparse_tests/test_signatures.py
@@ -1571,6 +1571,32 @@ class DataclassesTests(unittest.TestCase):
self.assertEqual({'a': 1.2, 'b': 3.4}, cfg['a2'])
+ def test_dataclass_fail_untyped(self):
+
+ class MyClass:
+ def __init__(self, c1) -> None:
+ self.c1 = c1
+
+ @dataclasses.dataclass
+ class MyDataclass:
+ a1: MyClass
+ a2: str = "a2"
+ a3: str = "a3"
+
+ parser = ArgumentParser(exit_on_error=False)
+ parser.add_argument('--cfg', type=MyDataclass, fail_untyped=False)
+
+ with mock_module(MyDataclass, MyClass) as module:
+ class_path = f'"class_path": "{module}.MyClass"'
+ init_args = '"init_args": {"c1": 1}'
+ cfg = parser.parse_args(['--cfg.a1={'+class_path+', '+init_args+'}'])
+ cfg = parser.instantiate_classes(cfg)
+ self.assertIsInstance(cfg['cfg'], MyDataclass)
+ self.assertIsInstance(cfg['cfg'].a1, MyClass)
+ self.assertIsInstance(cfg['cfg'].a2, str)
+ self.assertIsInstance(cfg['cfg'].a3, str)
+
+
def test_compose_dataclasses(self):
@dataclasses.dataclass
| Update `fail_untyped` flag to work with dataclasses whose arguments are classese with untyped arguments.
## 🚀 Feature request
The `fail_untyped` works with classes and nested classes, but id does not work with dataclasses which have class arguments with untyped arguments in their `__init__`.
### Motivation
Dataclasses come handy when we build complex CLI frameworks as it organise the input fields without the need of typing `class_path` and `init_args`. The powerful feature here is to have objects as arguments that could be configured directly from the CLI. However, even though when these objects have arguments that are typed it works great, but the majority of open source doesn't, and thus limits use quite a bit.
Here is a snip it to reproduce and to make sense of the above, quite complex 😅, description:
```py3
# main.py
from dataclasses import dataclass
from jsonargparse import CLI
class Database:
def __init__(self, version) -> None: # <-- HERE version is untyped; for `version: str` works!
self._version = version
@dataclass
class MySQLConfig:
db: Database
host: str = "localhost"
port: int = 8080
def my_app(cfg: MySQLConfig) -> None:
print(f"{cfg.host}, {cfg.port}, {cfg.db._version}")
if __name__ == "__main__":
CLI(my_app, fail_untyped=False)
```
Command:
```sh
python3 main.py --cfg.host "localhost" --cfg.port 8080 --cfg.db Database --cfg.db.version "0.0.1"
````
mind that when changing `version` to `version: str`, it works as expected.
Thank you for you time and for maintaining this great library! | 0.0 | [
"jsonargparse_tests/test_signatures.py::DataclassesTests::test_dataclass_fail_untyped"
] | [
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_class_arguments",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_class_conditional_kwargs",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_class_from_function_arguments",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_class_implemented_with_new",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_class_required_args",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_class_without_args",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_class_without_valid_args",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_function_arguments",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_function_with_dict_int_keys_arg",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_method_arguments",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_method_arguments_parent_classes",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_subclass_arguments",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_subclass_arguments_tuple",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_subclass_discard_init_args",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_subclass_init_args_in_subcommand",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_subclass_init_args_without_class_path",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_subclass_merge_init_args_in_full_config",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_subclass_nested_discard_init_args",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_basic_subtypes",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_class_from_function",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_class_path_override_with_mixed_type",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_dict_int_str_type",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_dict_type_nested_in_two_level_subclasses",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_fail_untyped_false",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_fail_untyped_false_subclass_help",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_final_class",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_implicit_optional",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_instantiate_classes",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_instantiate_classes_subcommand",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_invalid_class_from_function",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_invalid_type",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_logger_debug",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_not_required_group",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_optional_enum",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_print_config",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_print_config_subclass_required_param_issue_115",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_required_group",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_skip",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_skip_in_add_subclass_arguments",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_skip_within_subclass_type",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_subclass_help",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_subclass_nested_error_message_indentation",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_type_any_serialize",
"jsonargparse_tests/test_signatures.py::SignaturesConfigTests::test_add_class_arguments_with_config_not_found",
"jsonargparse_tests/test_signatures.py::SignaturesConfigTests::test_add_function_arguments_config",
"jsonargparse_tests/test_signatures.py::SignaturesConfigTests::test_add_subclass_arguments_with_config",
"jsonargparse_tests/test_signatures.py::SignaturesConfigTests::test_add_subclass_arguments_with_multifile_save",
"jsonargparse_tests/test_signatures.py::SignaturesConfigTests::test_config_nested_discard_init_args",
"jsonargparse_tests/test_signatures.py::SignaturesConfigTests::test_config_within_config",
"jsonargparse_tests/test_signatures.py::SignaturesConfigTests::test_parent_parser_default_config_files_lightning_issue_11622",
"jsonargparse_tests/test_signatures.py::SignaturesConfigTests::test_subclass_required_param_with_default_config_files",
"jsonargparse_tests/test_signatures.py::DataclassesTests::test_compose_dataclasses",
"jsonargparse_tests/test_signatures.py::DataclassesTests::test_dataclass_add_argument_type",
"jsonargparse_tests/test_signatures.py::DataclassesTests::test_dataclass_add_argument_type_some_required",
"jsonargparse_tests/test_signatures.py::DataclassesTests::test_dataclass_field_default_factory",
"jsonargparse_tests/test_signatures.py::DataclassesTests::test_dataclass_typehint",
"jsonargparse_tests/test_signatures.py::DataclassesTests::test_dataclass_typehint_in_subclass",
"jsonargparse_tests/test_signatures.py::DataclassesTests::test_instantiate_classes_dataclasses_lightning_issue_9207"
] | 2023-02-15 18:29:43+00:00 | 4,359 |
|
omni-us__jsonargparse-248 | diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index 4faf1b4..1aafaf5 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -12,11 +12,14 @@ The semantic versioning only considers the public API as described in
paths are considered internals and can change in minor and patch releases.
-v4.20.1 (2023-02-??)
+v4.20.1 (2023-03-??)
--------------------
Fixed
^^^^^
+- Allow ``discard_init_args_on_class_path_change`` to handle more nested contexts `#247
+ <https://github.com/omni-us/jsonargparse/issues/247>`__.
+
- Dump not working for partial callable with return instance
`pytorch-lightning#15340 (comment)
<https://github.com/Lightning-AI/lightning/issues/15340#issuecomment-1439203008>`__.
diff --git a/jsonargparse/typehints.py b/jsonargparse/typehints.py
index fc11db1..7f67ae1 100644
--- a/jsonargparse/typehints.py
+++ b/jsonargparse/typehints.py
@@ -939,6 +939,7 @@ def discard_init_args_on_class_path_change(parser_or_action, prev_val, value):
sub_add_kwargs = getattr(parser_or_action, 'sub_add_kwargs', {})
parser = ActionTypeHint.get_class_parser(value['class_path'], sub_add_kwargs)
del_args = {}
+ prev_val = subclass_spec_as_namespace(prev_val)
for key, val in list(prev_val.init_args.__dict__.items()):
action = _find_action(parser, key)
if action:
| omni-us/jsonargparse | 14b484266115f79040b6a5c555e201daddf54f12 | diff --git a/jsonargparse_tests/test_signatures.py b/jsonargparse_tests/test_signatures.py
index 463be12..3c85032 100755
--- a/jsonargparse_tests/test_signatures.py
+++ b/jsonargparse_tests/test_signatures.py
@@ -1427,6 +1427,46 @@ class SignaturesConfigTests(TempDirTestCase):
self.assertIsInstance(init.main.sub, Sub2)
self.assertTrue(any("discarding init_args: {'s1': 'x'}" in o for o in log.output))
+ def test_config_nested_dict_discard_init_args(self):
+ class Base:
+ def __init__(self, b: float = 0.5):
+ pass
+
+ class Sub1(Base):
+ def __init__(self, s1: int = 3, **kwargs):
+ super().__init__(**kwargs)
+
+ class Sub2(Base):
+ def __init__(self, s2: int = 4, **kwargs):
+ super().__init__(**kwargs)
+
+ class Main:
+ def __init__(self, sub: Optional[Dict] = None) -> None:
+ self.sub = sub
+
+ configs, subconfigs, config_paths = {}, {}, {}
+ with mock_module(Base, Sub1, Sub2, Main) as module:
+ parser = ArgumentParser(exit_on_error=False, logger={'level': 'DEBUG'})
+ parser.add_argument('--config', action=ActionConfigFile)
+ parser.add_subclass_arguments(Main, 'main')
+ parser.set_defaults(main=lazy_instance(Main))
+ for c in [1, 2]:
+ subconfigs[c] = {
+ 'sub': {
+ 'class_path': f'{module}.Sub{c}',
+ 'init_args': {f's{c}': c},
+ }
+ }
+ configs[c] = {'main': {'class_path': f'{module}.Main','init_args': subconfigs[c],}}
+ config_paths[c] = Path(f'config{c}.yaml')
+ config_paths[c].write_text(yaml.safe_dump(configs[c]))
+
+ with self.assertLogs(logger=parser.logger, level='DEBUG') as log:
+ cfg = parser.parse_args([f'--config={config_paths[1]}', f'--config={config_paths[2]}'])
+ init = parser.instantiate_classes(cfg)
+ self.assertIsInstance(init.main, Main)
+ self.assertTrue(init.main.sub['init_args']['s2'], 2)
+ self.assertTrue(any("discarding init_args: {'s1': 1}" in o for o in log.output))
@dataclasses.dataclass(frozen=True)
class MyDataClassA:
| ``discard_init_args_on_class_path_change`` does not handle nested ``dict`` subclass specs in some contexts
## 🐛 Bug report
Firstly, thanks again for all your work maintaining this remarkably valuable package!
While a ``subclass_spec`` can be either a ``dict`` or ``Namespace``
https://github.com/omni-us/jsonargparse/blob/ac790ba09bcc920cab1acf712422152b931d337a/jsonargparse/typehints.py#L790-L795
when entering ``ActionTypeHint.discard_init_args_on_class_path_change``:
https://github.com/omni-us/jsonargparse/blob/ac790ba09bcc920cab1acf712422152b931d337a/jsonargparse/typehints.py#L295-L310
``jsonargparse.typehints.discard_init_args_on_class_path_change`` below currently assumes any previous value for a nested subclass will already have been cast as a ``Namespace``:
https://github.com/omni-us/jsonargparse/blob/ac790ba09bcc920cab1acf712422152b931d337a/jsonargparse/typehints.py#L934-L942
with ``L941`` resulting in:
```
argparse.ArgumentError: Parser key "some_class":
Problem with given class_path '__main__.CustomModule':
- 'dict' object has no attribute 'init_args'
```
Right now, nested generic ``dict`` configurations like the repro case I include below don't trigger the ``subclass_spec_as_namespace`` ``Namespace`` wrapping that ``jsonargparse.typehints.discard_init_args_on_class_path_change`` requires when removing overridden subclass spec configuration in this context.
With the below minor patch to ``jsonargparse.typehints.discard_init_args_on_class_path_change``, this use case can be accommodated (I haven't had a chance to run the full jsongarparse test suite but can't immediately think of any problem with this additional check/transformation):
```python
def discard_init_args_on_class_path_change(parser_or_action, prev_val, value):
if prev_val and 'init_args' in prev_val and prev_val['class_path'] != value['class_path']:
parser = parser_or_action
if isinstance(parser_or_action, ActionTypeHint):
sub_add_kwargs = getattr(parser_or_action, 'sub_add_kwargs', {})
parser = ActionTypeHint.get_class_parser(value['class_path'], sub_add_kwargs)
del_args = {}
if isinstance(prev_val, dict):
prev_val = subclass_spec_as_namespace(prev_val)
for key, val in list(prev_val.init_args.__dict__.items()):
action = _find_action(parser, key)
```
### To reproduce
```python
from typing import Any, Dict
import yaml
import lightning.pytorch as pl
from jsonargparse import ArgumentParser
override_config = yaml.safe_dump(
{
"class_path": "CustomModule",
"init_args": {
"some_custom_init": {
"class_path": "torch.optim.lr_scheduler.StepLR",
"init_args": {"step_size": 1, "gamma": 0.7},
}
}
}
)
default_config = yaml.safe_dump(
{
"class_path": "CustomModule",
"init_args": {
"some_custom_init": {
"class_path": "torch.optim.lr_scheduler.CosineAnnealingWarmRestarts",
"init_args": {"T_0": 1, "T_mult": 2, "eta_min": 1.0e-07}
}
}
}
)
class CustomModule(pl.LightningModule):
def __init__(self, some_custom_init: Dict[str, Any],):
super().__init__()
parser = ArgumentParser()
parser.add_argument("--some_class", type=pl.LightningModule)
result = parser.parse_args(["--some_class", default_config, "--some_class", override_config])
print(f"expected_result= {result}")
```
Current behavior:
```
argparse.ArgumentError: Parser key "some_class":
Problem with given class_path '__main__.CustomModule':
- 'dict' object has no attribute 'init_args'
```
Expected result, generated with additional handling discussed above:
```
expected_result= Namespace(some_class=Namespace(class_path='__main__.CustomModule', init_args=Namespace(some_custom_init={'class_path': 'torch.optim.lr_scheduler.StepLR', 'init_args': {'gamma': 0.7, 'step_size': 1}})))
```
### Environment
- jsonargparse version (e.g., 4.8.0): 4.20.0
- Python version (e.g., 3.9): 3.10
- How jsonargparse was installed (e.g. `pip install jsonargparse[all]`): pip install "jsonargparse[signatures]==4.20.0"
- OS (e.g., Linux): Ubuntu 20.04
| 0.0 | [
"jsonargparse_tests/test_signatures.py::SignaturesConfigTests::test_config_nested_dict_discard_init_args"
] | [
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_class_arguments",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_class_conditional_kwargs",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_class_from_function_arguments",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_class_implemented_with_new",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_class_required_args",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_class_without_args",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_class_without_valid_args",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_function_arguments",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_function_with_dict_int_keys_arg",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_method_arguments",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_method_arguments_parent_classes",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_subclass_arguments",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_subclass_arguments_tuple",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_subclass_discard_init_args",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_subclass_init_args_in_subcommand",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_subclass_init_args_without_class_path",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_subclass_merge_init_args_in_full_config",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_subclass_nested_discard_init_args",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_basic_subtypes",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_class_from_function",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_class_path_override_with_mixed_type",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_dict_int_str_type",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_dict_type_nested_in_two_level_subclasses",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_fail_untyped_false",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_fail_untyped_false_subclass_help",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_fail_untyped_true",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_final_class",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_implicit_optional",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_instantiate_classes",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_instantiate_classes_subcommand",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_invalid_class_from_function",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_invalid_type",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_logger_debug",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_not_required_group",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_optional_enum",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_print_config",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_print_config_subclass_required_param_issue_115",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_required_group",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_skip",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_skip_in_add_subclass_arguments",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_skip_within_subclass_type",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_subclass_help",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_subclass_nested_error_message_indentation",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_type_any_serialize",
"jsonargparse_tests/test_signatures.py::SignaturesConfigTests::test_add_class_arguments_with_config_not_found",
"jsonargparse_tests/test_signatures.py::SignaturesConfigTests::test_add_function_arguments_config",
"jsonargparse_tests/test_signatures.py::SignaturesConfigTests::test_add_subclass_arguments_with_config",
"jsonargparse_tests/test_signatures.py::SignaturesConfigTests::test_add_subclass_arguments_with_multifile_save",
"jsonargparse_tests/test_signatures.py::SignaturesConfigTests::test_config_nested_discard_init_args",
"jsonargparse_tests/test_signatures.py::SignaturesConfigTests::test_config_within_config",
"jsonargparse_tests/test_signatures.py::SignaturesConfigTests::test_parent_parser_default_config_files_lightning_issue_11622",
"jsonargparse_tests/test_signatures.py::SignaturesConfigTests::test_subclass_required_param_with_default_config_files",
"jsonargparse_tests/test_signatures.py::DataclassesTests::test_compose_dataclasses",
"jsonargparse_tests/test_signatures.py::DataclassesTests::test_dataclass_add_argument_type",
"jsonargparse_tests/test_signatures.py::DataclassesTests::test_dataclass_add_argument_type_some_required",
"jsonargparse_tests/test_signatures.py::DataclassesTests::test_dataclass_fail_untyped",
"jsonargparse_tests/test_signatures.py::DataclassesTests::test_dataclass_field_default_factory",
"jsonargparse_tests/test_signatures.py::DataclassesTests::test_dataclass_typehint",
"jsonargparse_tests/test_signatures.py::DataclassesTests::test_dataclass_typehint_in_subclass",
"jsonargparse_tests/test_signatures.py::DataclassesTests::test_instantiate_classes_dataclasses_lightning_issue_9207"
] | 2023-02-23 06:05:46+00:00 | 4,360 |
|
omni-us__jsonargparse-253 | diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index 1aafaf5..1b29009 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -17,12 +17,13 @@ v4.20.1 (2023-03-??)
Fixed
^^^^^
-- Allow ``discard_init_args_on_class_path_change`` to handle more nested contexts `#247
- <https://github.com/omni-us/jsonargparse/issues/247>`__.
-
- Dump not working for partial callable with return instance
`pytorch-lightning#15340 (comment)
<https://github.com/Lightning-AI/lightning/issues/15340#issuecomment-1439203008>`__.
+- Allow ``discard_init_args_on_class_path_change`` to handle more nested
+ contexts `#247 <https://github.com/omni-us/jsonargparse/issues/247>`__.
+- Failure with dataclasses that have field with ``init=False`` `#252
+ <https://github.com/omni-us/jsonargparse/issues/252>`__.
v4.20.0 (2023-02-20)
diff --git a/jsonargparse/signatures.py b/jsonargparse/signatures.py
index cc90a23..f8648e4 100644
--- a/jsonargparse/signatures.py
+++ b/jsonargparse/signatures.py
@@ -416,14 +416,15 @@ class SignatureArguments(LoggerProperty):
added_args: List[str] = []
params = {p.name: p for p in get_signature_parameters(theclass, None, logger=self.logger)}
for field in dataclasses.fields(theclass):
- self._add_signature_parameter(
- group,
- nested_key,
- params[field.name],
- added_args,
- fail_untyped=fail_untyped,
- default=defaults.get(field.name, inspect_empty),
- )
+ if field.name in params:
+ self._add_signature_parameter(
+ group,
+ nested_key,
+ params[field.name],
+ added_args,
+ fail_untyped=fail_untyped,
+ default=defaults.get(field.name, inspect_empty),
+ )
return added_args
| omni-us/jsonargparse | 1fce98951f6d41064a516719fd7940b3f00ee08b | diff --git a/jsonargparse_tests/test_signatures.py b/jsonargparse_tests/test_signatures.py
index 3c85032..3dce258 100755
--- a/jsonargparse_tests/test_signatures.py
+++ b/jsonargparse_tests/test_signatures.py
@@ -1615,6 +1615,19 @@ class DataclassesTests(unittest.TestCase):
self.assertRaises(ArgumentError, lambda: parser.parse_args([]))
+ def test_dataclass_field_init_false(self):
+
+ @dataclasses.dataclass
+ class DataInitFalse:
+ p1: str = '-'
+ p2: str = dataclasses.field(init=False)
+
+ parser = ArgumentParser(exit_on_error=False)
+ added = parser.add_dataclass_arguments(DataInitFalse, 'd')
+ self.assertEqual(added, ['d.p1'])
+ self.assertEqual(parser.get_defaults(), Namespace(d=Namespace(p1='-')))
+
+
def test_dataclass_field_default_factory(self):
@dataclasses.dataclass
| parser.add_dataclass_arguments doesn't support fields with init=False
<!-- If you like this project, please ⭐ star it https://github.com/omni-us/jsonargparse/ -->
## 🐛 Bug report
<!-- A clear and concise description of the bug. -->
If I have a dataclass with protected members (ex: _foo) in a dataclass, meaning I set the init param at False, I have a keyerror during
### To reproduce
<!--
Please include a code snippet that reproduces the bug and the output that
running it gives. The following snippet templates might help:
1. Using the CLI function
```python
import jsonargparse
# Here define one or more functions or classes
def func1(param1: int, ...):
...
# Run the CLI providing the components
jsonargparse.CLI([func1, ...], error_handler=None)
```
2. Manually constructing a parser
```python
import jsonargparse
parser = jsonargparse.ArgumentParser(error_handler=None)
# Here add to the parser only argument(s) relevant to the problem
# If a yaml config is required, it can be included in the same snippet as follows:
import yaml
parser.add_argument('--config', action=jsonargparse.ActionConfigFile)
config = yaml.safe_dump({
'key1': 'val1',
})
# Preferable that the command line arguments are given to the parse_args call
result = parser.parse_args([f'--config={config}', '--key2=val2', ...])
# If the problem is in the parsed result, print it to stdout
print(parser.dump(result))
# If the problem is in class instantiation
parser.instantiate_classes(result)
```
-->
if I have a main.py file like this:
```python
from dataclasses import dataclass, field
import jsonargparse
@dataclass
class Model:
param_1: str
_param_2: str = field(init=False)
if __name__ == '__main__':
for field in fields(Model):
print(f'field name: {field.name}, init: {field.init}')
parser: ArgumentParser = ArgumentParser(parser_mode='omegaconf')
parser.add_dataclass_arguments(theclass=Model, nested_key='model')
```
By running python main.py --model my_config.yaml
I'm having an error: KeyError: '_param_2' at line parser.add_dataclass_arguments(theclass=Model, nested_key='model').
It seems related to the [signatures.py, line 418 of add_dataclass_arguments()](https://github.com/omni-us/jsonargparse/blob/1fce98951f6d41064a516719fd7940b3f00ee08b/jsonargparse/signatures.py#L418) :
```python
for field in dataclasses.fields(theclass):
self._add_signature_parameter(
group,
nested_key,
params[field.name],
added_args,
fail_untyped=fail_untyped,
default=defaults.get(field.name, inspect_empty),
)
```
Would be nice to cast if a field has its init parameter set to True:
```python
for field in dataclasses.fields(theclass):
if field.init:
self._add_signature_parameter(
group,
nested_key,
params[field.name],
added_args,
fail_untyped=fail_untyped,
default=defaults.get(field.name, inspect_empty),
)
```
### Expected behavior
<!-- Describe how the behavior or output of the reproduction snippet should be. -->
add_dataclass_arguments should accept non initializabled parameters
### Environment
<!-- Fill in the list below. -->
- jsonargparse version ( 4.8.0):
- Python version (3.10):
- How jsonargparse was installed (`conda install jsonargparse`):
- OS (Linux, Ubuntu):
| 0.0 | [
"jsonargparse_tests/test_signatures.py::DataclassesTests::test_dataclass_field_init_false"
] | [
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_class_arguments",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_class_conditional_kwargs",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_class_from_function_arguments",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_class_implemented_with_new",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_class_required_args",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_class_without_args",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_class_without_valid_args",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_function_arguments",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_function_with_dict_int_keys_arg",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_method_arguments",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_method_arguments_parent_classes",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_subclass_arguments",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_subclass_arguments_tuple",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_subclass_discard_init_args",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_subclass_init_args_in_subcommand",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_subclass_init_args_without_class_path",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_subclass_merge_init_args_in_full_config",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_add_subclass_nested_discard_init_args",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_basic_subtypes",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_class_from_function",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_class_path_override_with_mixed_type",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_dict_int_str_type",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_dict_type_nested_in_two_level_subclasses",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_fail_untyped_false",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_fail_untyped_false_subclass_help",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_fail_untyped_true",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_final_class",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_implicit_optional",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_instantiate_classes",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_instantiate_classes_subcommand",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_invalid_class_from_function",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_invalid_type",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_logger_debug",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_not_required_group",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_optional_enum",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_print_config",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_print_config_subclass_required_param_issue_115",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_required_group",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_skip",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_skip_in_add_subclass_arguments",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_skip_within_subclass_type",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_subclass_help",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_subclass_nested_error_message_indentation",
"jsonargparse_tests/test_signatures.py::SignaturesTests::test_type_any_serialize",
"jsonargparse_tests/test_signatures.py::SignaturesConfigTests::test_add_class_arguments_with_config_not_found",
"jsonargparse_tests/test_signatures.py::SignaturesConfigTests::test_add_function_arguments_config",
"jsonargparse_tests/test_signatures.py::SignaturesConfigTests::test_add_subclass_arguments_with_config",
"jsonargparse_tests/test_signatures.py::SignaturesConfigTests::test_add_subclass_arguments_with_multifile_save",
"jsonargparse_tests/test_signatures.py::SignaturesConfigTests::test_config_nested_dict_discard_init_args",
"jsonargparse_tests/test_signatures.py::SignaturesConfigTests::test_config_nested_discard_init_args",
"jsonargparse_tests/test_signatures.py::SignaturesConfigTests::test_config_within_config",
"jsonargparse_tests/test_signatures.py::SignaturesConfigTests::test_parent_parser_default_config_files_lightning_issue_11622",
"jsonargparse_tests/test_signatures.py::SignaturesConfigTests::test_subclass_required_param_with_default_config_files",
"jsonargparse_tests/test_signatures.py::DataclassesTests::test_compose_dataclasses",
"jsonargparse_tests/test_signatures.py::DataclassesTests::test_dataclass_add_argument_type",
"jsonargparse_tests/test_signatures.py::DataclassesTests::test_dataclass_add_argument_type_some_required",
"jsonargparse_tests/test_signatures.py::DataclassesTests::test_dataclass_fail_untyped",
"jsonargparse_tests/test_signatures.py::DataclassesTests::test_dataclass_field_default_factory",
"jsonargparse_tests/test_signatures.py::DataclassesTests::test_dataclass_typehint",
"jsonargparse_tests/test_signatures.py::DataclassesTests::test_dataclass_typehint_in_subclass",
"jsonargparse_tests/test_signatures.py::DataclassesTests::test_instantiate_classes_dataclasses_lightning_issue_9207"
] | 2023-03-17 13:11:58+00:00 | 4,361 |
|
omni-us__jsonargparse-346 | diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index e44b33f..b07579f 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -19,6 +19,9 @@ Added
^^^^^
- New option in ``dump`` for including link targets.
- Support ``decimal.Decimal`` as a type.
+- ``CLI`` now accepts components as a dict, such that the keys define names of
+ the subcommands (`#334
+ <https://github.com/omni-us/jsonargparse/issues/334>`__).
v4.23.1 (2023-08-04)
diff --git a/README.rst b/README.rst
index c52569d..1a62605 100644
--- a/README.rst
+++ b/README.rst
@@ -235,6 +235,44 @@ is given to :func:`.CLI`, to execute a method of a class, two levels of
class and the second the name of the method, i.e. ``example.py class
[init_arguments] method [arguments]``.
+Arbitrary levels of sub-commands with custom names can be defined by providing a
+``dict``. For example:
+
+.. testcode::
+
+ class Raffle:
+ def __init__(self, prize: int):
+ self.prize = prize
+
+ def __call__(self, name: str):
+ return f"{name} won {self.prize}€!"
+
+ components = {
+ "weekday": {
+ "tier1": Raffle(prize=100),
+ "tier2": Raffle(prize=50),
+ },
+ "weekend": {
+ "tier1": Raffle(prize=300),
+ "tier2": Raffle(prize=75),
+ },
+ }
+
+ if __name__ == "__main__":
+ print(CLI(components))
+
+Then in a shell:
+
+.. code-block:: bash
+
+ $ python example.py weekend tier1 Lucky
+ Lucky won 300€!
+
+.. doctest:: :hide:
+
+ >>> CLI(components, args=["weekend", "tier1", "Lucky"])
+ 'Lucky won 300€!'
+
.. note::
The examples above are extremely simple, only defining parameters with
diff --git a/jsonargparse/_cli.py b/jsonargparse/_cli.py
index d832f77..f6b7eb2 100644
--- a/jsonargparse/_cli.py
+++ b/jsonargparse/_cli.py
@@ -6,14 +6,20 @@ from typing import Any, Callable, Dict, List, Optional, Type, Union
from ._actions import ActionConfigFile, _ActionPrintConfig, remove_actions
from ._core import ArgumentParser
from ._deprecated import deprecation_warning_cli_return_parser
+from ._namespace import Namespace, dict_to_namespace
from ._optionals import get_doc_short_description
from ._util import default_config_option_help
__all__ = ["CLI"]
+ComponentType = Union[Callable, Type]
+DictComponentsType = Dict[str, Union[ComponentType, "DictComponentsType"]]
+ComponentsType = Optional[Union[ComponentType, List[ComponentType], DictComponentsType]]
+
+
def CLI(
- components: Optional[Union[Callable, Type, List[Union[Callable, Type]]]] = None,
+ components: ComponentsType = None,
args: Optional[List[str]] = None,
config_help: str = default_config_option_help,
set_defaults: Optional[Dict[str, Any]] = None,
@@ -55,26 +61,31 @@ def CLI(
]
if len(components) == 0:
raise ValueError(
- "Either components argument must be given or there must be at least one "
+ "Either components parameter must be given or there must be at least one "
"function or class among the locals in the context where CLI is called."
)
- elif not isinstance(components, list):
- components = [components]
+ if isinstance(components, list) and len(components) == 1:
+ components = components[0]
- if len(components) == 0:
- raise ValueError("components argument not allowed to be an empty list")
+ elif not components:
+ raise ValueError("components parameter expected to be non-empty")
- unexpected = [c for c in components if not (inspect.isclass(c) or callable(c))]
+ if isinstance(components, list):
+ unexpected = [c for c in components if not (inspect.isclass(c) or callable(c))]
+ elif isinstance(components, dict):
+ ns = dict_to_namespace(components)
+ unexpected = [c for c in ns.values() if not (inspect.isclass(c) or callable(c))]
+ else:
+ unexpected = [c for c in [components] if not (inspect.isclass(c) or callable(c))]
if unexpected:
raise ValueError(f"Unexpected components, not class or function: {unexpected}")
parser = parser_class(default_meta=False, **kwargs)
parser.add_argument("--config", action=ActionConfigFile, help=config_help)
- if len(components) == 1:
- component = components[0]
- _add_component_to_parser(component, parser, as_positional, fail_untyped, config_help)
+ if not isinstance(components, (list, dict)):
+ _add_component_to_parser(components, parser, as_positional, fail_untyped, config_help)
if set_defaults is not None:
parser.set_defaults(set_defaults)
if return_parser:
@@ -82,18 +93,12 @@ def CLI(
return parser
cfg = parser.parse_args(args)
cfg_init = parser.instantiate_classes(cfg)
- return _run_component(component, cfg_init)
+ return _run_component(components, cfg_init)
- subcommands = parser.add_subcommands(required=True)
- comp_dict = {c.__name__: c for c in components}
- for name, component in comp_dict.items():
- description = get_help_str(component, parser.logger)
- subparser = parser_class(description=description)
- subparser.add_argument("--config", action=ActionConfigFile, help=config_help)
- subcommands.add_subcommand(name, subparser, help=get_help_str(component, parser.logger))
- added_args = _add_component_to_parser(component, subparser, as_positional, fail_untyped, config_help)
- if not added_args:
- remove_actions(subparser, (ActionConfigFile, _ActionPrintConfig))
+ elif isinstance(components, list):
+ components = {c.__name__: c for c in components}
+
+ _add_subcommands(components, parser, config_help, as_positional, fail_untyped)
if set_defaults is not None:
parser.set_defaults(set_defaults)
@@ -101,10 +106,17 @@ def CLI(
deprecation_warning_cli_return_parser()
return parser
cfg = parser.parse_args(args)
- cfg_init = parser.instantiate_classes(cfg)
- subcommand = cfg_init.pop("subcommand")
- component = comp_dict[subcommand]
- return _run_component(component, cfg_init.get(subcommand))
+ init = parser.instantiate_classes(cfg)
+ components_ns = dict_to_namespace(components)
+ subcommand = init.get("subcommand")
+ while isinstance(init.get(subcommand), Namespace) and isinstance(init[subcommand].get("subcommand"), str):
+ subsubcommand = subcommand + "." + init[subcommand].get("subcommand")
+ if subsubcommand in components_ns:
+ subcommand = subsubcommand
+ else:
+ break
+ component = components_ns[subcommand]
+ return _run_component(component, init.get(subcommand))
def get_help_str(component, logger):
@@ -114,6 +126,28 @@ def get_help_str(component, logger):
return help_str
+def _add_subcommands(
+ components,
+ parser: ArgumentParser,
+ config_help: str,
+ as_positional: bool,
+ fail_untyped: bool,
+) -> None:
+ subcommands = parser.add_subcommands(required=True)
+ for name, component in components.items():
+ description = get_help_str(component, parser.logger)
+ subparser = type(parser)(description=description)
+ subparser.add_argument("--config", action=ActionConfigFile, help=config_help)
+ if isinstance(component, dict):
+ subcommands.add_subcommand(name, subparser)
+ _add_subcommands(component, subparser, config_help, as_positional, fail_untyped)
+ else:
+ subcommands.add_subcommand(name, subparser, help=get_help_str(component, parser.logger))
+ added_args = _add_component_to_parser(component, subparser, as_positional, fail_untyped, config_help)
+ if not added_args:
+ remove_actions(subparser, (ActionConfigFile, _ActionPrintConfig))
+
+
def _add_component_to_parser(component, parser, as_positional, fail_untyped, config_help):
kwargs = dict(as_positional=as_positional, fail_untyped=fail_untyped, sub_configs=True)
if inspect.isclass(component):
| omni-us/jsonargparse | dcfd265ad12f43a09e9db25d552c8bdb6f9304f8 | diff --git a/jsonargparse_tests/test_cli.py b/jsonargparse_tests/test_cli.py
index 77abd84..c612aa2 100644
--- a/jsonargparse_tests/test_cli.py
+++ b/jsonargparse_tests/test_cli.py
@@ -28,7 +28,7 @@ def get_cli_stdout(*args, **kwargs) -> str:
# failure cases
[email protected]("components", [0, []])
[email protected]("components", [0, [], {"x": 0}])
def test_unexpected_components(components):
with pytest.raises(ValueError):
CLI(components)
@@ -344,6 +344,45 @@ def test_dataclass_without_methods_parser_groups():
assert parser.groups == {}
+# named components tests
+
+
+def test_named_components_shallow():
+ components = {"cmd1": single_function, "cmd2": callable_instance}
+ assert 3.4 == CLI(components, args=["cmd1", "3.4"])
+ assert 5 == CLI(components, as_positional=False, args=["cmd2", "--x=5"])
+
+
+def test_named_components_deep():
+ components = {
+ "lv1_a": {"lv2_x": single_function, "lv2_y": {"lv3_p": callable_instance}},
+ "lv1_b": {"lv2_z": {"lv3_q": Class1}},
+ }
+ kw = {"as_positional": False}
+ out = get_cli_stdout(components, args=["--help"], **kw)
+ assert " {lv1_a,lv1_b} ..." in out
+ out = get_cli_stdout(components, args=["lv1_a", "--help"], **kw)
+ assert " {lv2_x,lv2_y} ..." in out
+ out = get_cli_stdout(components, args=["lv1_a", "lv2_x", "--help"], **kw)
+ assert " --a1 A1" in out
+ out = get_cli_stdout(components, args=["lv1_a", "lv2_y", "--help"], **kw)
+ assert " {lv3_p} ..." in out
+ out = get_cli_stdout(components, args=["lv1_a", "lv2_y", "lv3_p", "--help"], **kw)
+ assert " --x X" in out
+ out = get_cli_stdout(components, args=["lv1_b", "--help"], **kw)
+ assert " {lv2_z} ..." in out
+ out = get_cli_stdout(components, args=["lv1_b", "lv2_z", "--help"], **kw)
+ assert " {lv3_q} ..." in out
+ out = get_cli_stdout(components, args=["lv1_b", "lv2_z", "lv3_q", "--help"], **kw)
+ assert " {method1} ..." in out
+ out = get_cli_stdout(components, args=["lv1_b", "lv2_z", "lv3_q", "method1", "--help"], **kw)
+ assert " --m1 M1" in out
+
+ assert 5.6 == CLI(components, args=["lv1_a", "lv2_x", "--a1=5.6"], **kw)
+ assert 7 == CLI(components, args=["lv1_a", "lv2_y", "lv3_p", "--x=7"], **kw)
+ assert ("w", 9) == CLI(components, args=["lv1_b", "lv2_z", "lv3_q", "--i1=w", "method1", "--m1=9"], **kw)
+
+
# config file tests
| Add multilevel subcommands support to `CLI`
<!-- If you like this project, please ⭐ star it https://github.com/omni-us/jsonargparse/ -->
## 🚀 Feature request
Currently `jsonargparse.CLI` can handle only one level of subcommands through classes. For example:
```Python
from jsonargparse import CLI
class mycli:
@staticmethod
def subcommand1(): ...
if __name__ == "__main__":
CLI(components=[mycli])
```
But there is no easy way to add more subcommands, since embedding a class in another one will cause an error.:
```Python
from jsonargparse import CLI
class mycli:
@staticmethod
def subcommand1(): ...
class subcommand2:
@staticmethod
def subsubcommand1(): ...
if __name__ == "__main__":
CLI(components=[mycli])
```
```Bash
ValueError: Invalid or unsupported input: class=<class '__main__.mycli'>, method_or_property=subcommand2
```
To add more subcommands, you need to use `jsonargparse.ArgumentParser` and implement all the logic manually.
### Motivation
It would be great to be able to create multilevel subcommands easily.
### Pitch
Add multilevel subcommands support to `jsonargparse.CLI`.
### Alternatives
<!-- Any alternative solutions or features you've considered, if any. -->
| 0.0 | [
"jsonargparse_tests/test_cli.py::test_named_components_shallow",
"jsonargparse_tests/test_cli.py::test_named_components_deep"
] | [
"jsonargparse_tests/test_cli.py::test_unexpected_components[0]",
"jsonargparse_tests/test_cli.py::test_unexpected_components[components1]",
"jsonargparse_tests/test_cli.py::test_unexpected_components[components2]",
"jsonargparse_tests/test_cli.py::test_single_function_return",
"jsonargparse_tests/test_cli.py::test_single_function_set_defaults",
"jsonargparse_tests/test_cli.py::test_single_function_help",
"jsonargparse_tests/test_cli.py::test_callable_instance",
"jsonargparse_tests/test_cli.py::test_multiple_functions_return",
"jsonargparse_tests/test_cli.py::test_multiple_functions_set_defaults",
"jsonargparse_tests/test_cli.py::test_multiple_functions_main_help",
"jsonargparse_tests/test_cli.py::test_multiple_functions_subcommand_help",
"jsonargparse_tests/test_cli.py::test_single_class_return",
"jsonargparse_tests/test_cli.py::test_single_class_missing_required_init",
"jsonargparse_tests/test_cli.py::test_single_class_invalid_method_parameter",
"jsonargparse_tests/test_cli.py::test_single_class_main_help",
"jsonargparse_tests/test_cli.py::test_single_class_subcommand_help",
"jsonargparse_tests/test_cli.py::test_single_class_print_config_after_subcommand",
"jsonargparse_tests/test_cli.py::test_single_class_print_config_before_subcommand",
"jsonargparse_tests/test_cli.py::test_function_and_class_return[5-args0]",
"jsonargparse_tests/test_cli.py::test_function_and_class_return[expected1-args1]",
"jsonargparse_tests/test_cli.py::test_function_and_class_return[expected2-args2]",
"jsonargparse_tests/test_cli.py::test_function_and_class_return[4-args3]",
"jsonargparse_tests/test_cli.py::test_function_and_class_return[expected4-args4]",
"jsonargparse_tests/test_cli.py::test_function_and_class_return[expected5-args5]",
"jsonargparse_tests/test_cli.py::test_function_and_class_return[expected6-args6]",
"jsonargparse_tests/test_cli.py::test_function_and_class_return[Cmd2.method3-args7]",
"jsonargparse_tests/test_cli.py::test_function_and_class_return[cmd3-args8]",
"jsonargparse_tests/test_cli.py::test_function_and_class_main_help",
"jsonargparse_tests/test_cli.py::test_function_and_class_subcommand_help",
"jsonargparse_tests/test_cli.py::test_function_and_class_subsubcommand_help",
"jsonargparse_tests/test_cli.py::test_function_and_class_print_config_after_subsubcommand",
"jsonargparse_tests/test_cli.py::test_function_and_class_print_config_in_between_subcommands",
"jsonargparse_tests/test_cli.py::test_function_and_class_print_config_before_subcommands",
"jsonargparse_tests/test_cli.py::test_function_and_class_method_without_parameters",
"jsonargparse_tests/test_cli.py::test_function_and_class_function_without_parameters",
"jsonargparse_tests/test_cli.py::test_automatic_components_empty_context",
"jsonargparse_tests/test_cli.py::test_automatic_components_context_function",
"jsonargparse_tests/test_cli.py::test_automatic_components_context_class",
"jsonargparse_tests/test_cli.py::test_dataclass_without_methods_response",
"jsonargparse_tests/test_cli.py::test_dataclass_without_methods_parser_groups",
"jsonargparse_tests/test_cli.py::test_subclass_type_config_file",
"jsonargparse_tests/test_cli.py::test_final_and_subclass_type_config_file"
] | 2023-08-09 03:48:59+00:00 | 4,362 |
|
omni-us__jsonargparse-363 | diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index 65d6bd7..73f7a38 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -19,6 +19,8 @@ Fixed
^^^^^
- Remove private ``linked_targets`` parameter from API Reference (`#317
<https://github.com/omni-us/jsonargparse/issues/317>`__).
+- Dataclass nested in list not setting defaults (`#357
+ <https://github.com/omni-us/jsonargparse/issues/357>`__)
v4.24.0 (2023-08-23)
diff --git a/jsonargparse/_typehints.py b/jsonargparse/_typehints.py
index 47f9bed..40b94a2 100644
--- a/jsonargparse/_typehints.py
+++ b/jsonargparse/_typehints.py
@@ -576,6 +576,7 @@ def adapt_typehints(
instantiate_classes=False,
prev_val=None,
append=False,
+ list_item=False,
enable_path=False,
sub_add_kwargs=None,
):
@@ -717,7 +718,7 @@ def adapt_typehints(
for n, v in enumerate(val):
if isinstance(prev_val, list) and len(prev_val) == len(val):
adapt_kwargs_n = {**adapt_kwargs, "prev_val": prev_val[n]}
- val[n] = adapt_typehints(v, subtypehints[0], **adapt_kwargs_n)
+ val[n] = adapt_typehints(v, subtypehints[0], list_item=True, **adapt_kwargs_n)
# Dict, Mapping
elif typehint_origin in mapping_origin_types:
@@ -802,7 +803,7 @@ def adapt_typehints(
if serialize:
val = load_value(parser.dump(val, **dump_kwargs.get()))
elif isinstance(val, (dict, Namespace)):
- val = parser.parse_object(val, defaults=sub_defaults.get())
+ val = parser.parse_object(val, defaults=sub_defaults.get() or list_item)
elif isinstance(val, NestedArg):
val = parser.parse_args([f"--{val.key}={val.val}"])
else:
| omni-us/jsonargparse | 323b4a50f4e1112b9fe2f126b0a1f0bd0896b8a7 | diff --git a/jsonargparse_tests/test_dataclass_like.py b/jsonargparse_tests/test_dataclass_like.py
index 2fe5092..50d55d6 100644
--- a/jsonargparse_tests/test_dataclass_like.py
+++ b/jsonargparse_tests/test_dataclass_like.py
@@ -98,6 +98,23 @@ def test_add_dataclass_arguments(parser, subtests):
parser.add_dataclass_arguments(MixedClass, "c")
[email protected]
+class NestedDefaultsA:
+ x: list = dataclasses.field(default_factory=list)
+ v: int = 1
+
+
[email protected]
+class NestedDefaultsB:
+ a: List[NestedDefaultsA]
+
+
+def test_add_dataclass_nested_defaults(parser):
+ parser.add_dataclass_arguments(NestedDefaultsB, "data")
+ cfg = parser.parse_args(["--data.a=[{}]"])
+ assert cfg.data == Namespace(a=[Namespace(x=[], v=1)])
+
+
class ClassDataAttributes:
def __init__(
self,
| `default` and `default_factory` do not work in nested list with parse_object
<!-- If you like this project, please ⭐ star it https://github.com/omni-us/jsonargparse/ -->
## 🐛 Bug report
<!-- A clear and concise description of the bug. -->
### To reproduce
```python
from dataclasses import dataclass, field
from jsonargparse import ArgumentParser
@dataclass
class A:
x: list = field(default_factory=list)
v: int = 1
@dataclass
class B:
a: list[A]
def main():
parser = ArgumentParser()
parser.add_dataclass_arguments(B, 'conf')
args = parser.parse_object({
'conf': {
'a': [{}]
}
})
print(args.conf)
if __name__ == '__main__':
main()
```
### Expected result
```
Namespace(a=[Namespace(v=1, x=[])])
```
### Actual result
```
Namespace(a=[Namespace()])
```
### Environment
<!-- Fill in the list below. -->
- jsonargparse version (e.g., 4.8.0): 4.23.1
- Python version (e.g., 3.9): 3.11.4
- How jsonargparse was installed: `pip install jsonargparse[all]`
- OS (e.g., Linux): Ubuntu 22.04
| 0.0 | [
"jsonargparse_tests/test_dataclass_like.py::test_add_dataclass_nested_defaults"
] | [
"jsonargparse_tests/test_dataclass_like.py::test_add_dataclass_arguments",
"jsonargparse_tests/test_dataclass_like.py::test_add_class_with_dataclass_attributes",
"jsonargparse_tests/test_dataclass_like.py::test_add_class_dataclass_typehint_in_subclass",
"jsonargparse_tests/test_dataclass_like.py::test_add_class_optional_without_default",
"jsonargparse_tests/test_dataclass_like.py::test_add_argument_dataclass_type",
"jsonargparse_tests/test_dataclass_like.py::test_add_argument_dataclass_type_required_attr",
"jsonargparse_tests/test_dataclass_like.py::test_dataclass_field_init_false",
"jsonargparse_tests/test_dataclass_like.py::test_dataclass_field_default_factory",
"jsonargparse_tests/test_dataclass_like.py::test_dataclass_fail_untyped_false",
"jsonargparse_tests/test_dataclass_like.py::test_compose_dataclasses",
"jsonargparse_tests/test_dataclass_like.py::test_instantiate_dataclass_within_classes",
"jsonargparse_tests/test_dataclass_like.py::test_optional_dataclass_type_all_fields",
"jsonargparse_tests/test_dataclass_like.py::test_optional_dataclass_type_single_field",
"jsonargparse_tests/test_dataclass_like.py::test_optional_dataclass_type_invalid_field",
"jsonargparse_tests/test_dataclass_like.py::test_optional_dataclass_type_instantiate",
"jsonargparse_tests/test_dataclass_like.py::test_optional_dataclass_type_dump",
"jsonargparse_tests/test_dataclass_like.py::test_optional_dataclass_type_missing_required_field",
"jsonargparse_tests/test_dataclass_like.py::test_optional_dataclass_type_null_value",
"jsonargparse_tests/test_dataclass_like.py::test_dataclass_optional_dict_attribute",
"jsonargparse_tests/test_dataclass_like.py::test_dataclass_in_union_type",
"jsonargparse_tests/test_dataclass_like.py::test_dataclass_in_list_type",
"jsonargparse_tests/test_dataclass_like.py::test_add_class_final",
"jsonargparse_tests/test_dataclass_like.py::TestPydantic::test_dataclass",
"jsonargparse_tests/test_dataclass_like.py::TestPydantic::test_basemodel",
"jsonargparse_tests/test_dataclass_like.py::TestPydantic::test_subclass",
"jsonargparse_tests/test_dataclass_like.py::TestPydantic::test_field_default_factory",
"jsonargparse_tests/test_dataclass_like.py::TestPydantic::test_field_description",
"jsonargparse_tests/test_dataclass_like.py::TestPydantic::test_pydantic_types",
"jsonargparse_tests/test_dataclass_like.py::TestAttrs::test_define",
"jsonargparse_tests/test_dataclass_like.py::TestAttrs::test_subclass",
"jsonargparse_tests/test_dataclass_like.py::TestAttrs::test_field_factory"
] | 2023-08-29 18:29:01+00:00 | 4,363 |
|
omni-us__jsonargparse-364 | diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index 73f7a38..db9cf3f 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -21,6 +21,9 @@ Fixed
<https://github.com/omni-us/jsonargparse/issues/317>`__).
- Dataclass nested in list not setting defaults (`#357
<https://github.com/omni-us/jsonargparse/issues/357>`__)
+- AST resolver ``kwargs.pop()`` with conflicting defaults not setting the
+ conditional default (`#362
+ <https://github.com/omni-us/jsonargparse/issues/362>`__).
v4.24.0 (2023-08-23)
diff --git a/DOCUMENTATION.rst b/DOCUMENTATION.rst
index 9d12594..f68a386 100644
--- a/DOCUMENTATION.rst
+++ b/DOCUMENTATION.rst
@@ -1693,11 +1693,11 @@ A special case which is supported but with caveats, is multiple calls that use
The resolved parameters that have the same type hint and default across all
calls are supported normally. When there is a discrepancy between the calls, the
-parameters behave differently and are shown in the help in special "Conditional
-arguments" sections. The main difference is that these arguments are not
-included in :py:meth:`.ArgumentParser.get_defaults` or the output of
-``--print_config``. This is necessary because the parser does not know which of
-the calls will be used at runtime, and adding them would cause
+parameters behave differently and are shown in the help with the default like
+``Conditional<ast-resolver> {DEFAULT_1, ...}``. The main difference is that
+these parameters are not included in :py:meth:`.ArgumentParser.get_defaults` or
+the output of ``--print_config``. This is necessary because the parser does not
+know which of the calls will be used at runtime, and adding them would cause
:py:meth:`.ArgumentParser.instantiate_classes` to fail due to unexpected keyword
arguments.
@@ -1747,6 +1747,10 @@ Without the stubs resolver, the
given to the ``a`` and ``b`` arguments, instead of ``float``. And this means
that the parser would not fail if given an invalid value, for instance a string.
+It is not possible to know the defaults of parameters discovered only because of
+the stubs. In these cases in the parser help the default is shown as
+``Unknown<stubs-resolver>`` and not included in
+:py:meth:`.ArgumentParser.get_defaults` or the output of ``--print_config``.
.. _sub-classes:
diff --git a/jsonargparse/_parameter_resolvers.py b/jsonargparse/_parameter_resolvers.py
index c59ebe2..85a7c4c 100644
--- a/jsonargparse/_parameter_resolvers.py
+++ b/jsonargparse/_parameter_resolvers.py
@@ -40,8 +40,7 @@ ParamList = List[ParamData]
parameter_attributes = [s[1:] for s in inspect.Parameter.__slots__] # type: ignore
kinds = inspect._ParameterKind
ast_assign_type: Tuple[Type[ast.AST], ...] = (ast.AnnAssign, ast.Assign)
-param_kwargs_get = "**.get()"
-param_kwargs_pop = "**.pop()"
+param_kwargs_pop_or_get = "**.pop|get():"
class SourceNotAvailable(Exception):
@@ -304,29 +303,6 @@ def add_stub_types(stubs: Optional[Dict[str, Any]], params: ParamList, component
ast_literals = {ast.dump(ast.parse(v, mode="eval").body): partial(ast.literal_eval, v) for v in ["{}", "[]"]}
-def get_kwargs_pop_or_get_parameter(node, component, parent, doc_params, log_debug):
- name = ast_get_constant_value(node.args[0])
- if ast_is_constant(node.args[1]):
- default = ast_get_constant_value(node.args[1])
- else:
- default = ast.dump(node.args[1])
- if default in ast_literals:
- default = ast_literals[default]()
- else:
- default = None
- log_debug(f"unsupported kwargs pop/get default: {ast_str(node)}")
- return ParamData(
- name=name,
- annotation=inspect._empty,
- default=default,
- kind=kinds.KEYWORD_ONLY,
- doc=doc_params.get(name),
- parent=parent,
- component=component,
- origin=param_kwargs_get if node.func.attr == "get" else param_kwargs_pop,
- )
-
-
def is_param_subclass_instance_default(param: ParamData) -> bool:
if is_dataclass_like(type(param.default)):
return False
@@ -368,31 +344,27 @@ def group_parameters(params_list: List[ParamList]) -> ParamList:
param.origin = None
return params_list[0]
grouped = []
- params_count = 0
- params_skip = set()
+ non_get_pop_count = 0
params_dict = defaultdict(lambda: [])
for params in params_list:
- if params[0].origin not in {param_kwargs_get, param_kwargs_pop}:
- params_count += 1
+ if not (params[0].origin or "").startswith(param_kwargs_pop_or_get): # type: ignore
+ non_get_pop_count += 1
for param in params:
- if param.name not in params_skip and param.kind != kinds.POSITIONAL_ONLY:
+ if param.kind != kinds.POSITIONAL_ONLY:
params_dict[param.name].append(param)
- if param.origin == param_kwargs_pop:
- params_skip.add(param.name)
for params in params_dict.values():
gparam = params[0]
types = unique(p.annotation for p in params if p.annotation is not inspect._empty)
defaults = unique(p.default for p in params if p.default is not inspect._empty)
- if len(params) >= params_count and len(types) <= 1 and len(defaults) <= 1:
+ if len(params) >= non_get_pop_count and len(types) <= 1 and len(defaults) <= 1:
gparam.origin = None
else:
gparam.parent = tuple(p.parent for p in params)
gparam.component = tuple(p.component for p in params)
gparam.origin = tuple(p.origin for p in params)
- gparam.default = ConditionalDefault(
- "ast-resolver",
- (p.default for p in params) if len(defaults) > 1 else defaults,
- )
+ if len(params) < non_get_pop_count:
+ defaults += ["NOT_ACCEPTED"]
+ gparam.default = ConditionalDefault("ast-resolver", defaults)
if len(types) > 1:
gparam.annotation = Union[tuple(types)] if types else inspect._empty
docs = [p.doc for p in params if p.doc]
@@ -644,6 +616,28 @@ class ParametersVisitor(LoggerProperty, ast.NodeVisitor):
default_nodes = [d for n, d in enumerate(default_nodes) if arg_nodes[n].arg in param_names]
return default_nodes
+ def get_kwargs_pop_or_get_parameter(self, node, component, parent, doc_params):
+ name = ast_get_constant_value(node.args[0])
+ if ast_is_constant(node.args[1]):
+ default = ast_get_constant_value(node.args[1])
+ else:
+ default = ast.dump(node.args[1])
+ if default in ast_literals:
+ default = ast_literals[default]()
+ else:
+ default = None
+ self.log_debug(f"unsupported kwargs pop/get default: {ast_str(node)}")
+ return ParamData(
+ name=name,
+ annotation=inspect._empty,
+ default=default,
+ kind=kinds.KEYWORD_ONLY,
+ doc=doc_params.get(name),
+ parent=parent,
+ component=component,
+ origin=param_kwargs_pop_or_get + self.get_node_origin(node),
+ )
+
def get_parameters_args_and_kwargs(self) -> Tuple[ParamList, ParamList]:
self.parse_source_tree()
args_name = getattr(self.component_node.args.vararg, "arg", None)
@@ -664,9 +658,7 @@ class ParametersVisitor(LoggerProperty, ast.NodeVisitor):
for node in [v for k, v in values_found if k == kwargs_name]:
if isinstance(node, ast.Call):
if ast_is_kwargs_pop_or_get(node, kwargs_value_dump):
- param = get_kwargs_pop_or_get_parameter(
- node, self.component, self.parent, self.doc_params, self.log_debug
- )
+ param = self.get_kwargs_pop_or_get_parameter(node, self.component, self.parent, self.doc_params)
params_list.append([param])
continue
kwarg = ast_get_call_kwarg_with_value(node, kwargs_value)
@@ -717,12 +709,15 @@ class ParametersVisitor(LoggerProperty, ast.NodeVisitor):
self.log_debug(f"did not find use of {self.self_name}.{attr_name} in members of {self.parent}")
return []
+ def get_node_origin(self, node) -> str:
+ return f"{get_parameter_origins(self.component, self.parent)}:{node.lineno}"
+
def add_node_origins(self, params: ParamList, node) -> None:
origin = None
for param in params:
if param.origin is None:
if not origin:
- origin = f"{get_parameter_origins(self.component, self.parent)}:{node.lineno}"
+ origin = self.get_node_origin(node)
param.origin = origin
def get_parameters_call_attr(self, attr_name: str, attr_value: ast.AST) -> Optional[ParamList]:
| omni-us/jsonargparse | cd165e9e0dd8bb497693568ea90c732cf74e12f4 | diff --git a/jsonargparse_tests/test_parameter_resolvers.py b/jsonargparse_tests/test_parameter_resolvers.py
index 0081fd5..03dcc3c 100644
--- a/jsonargparse_tests/test_parameter_resolvers.py
+++ b/jsonargparse_tests/test_parameter_resolvers.py
@@ -5,15 +5,15 @@ import inspect
import xml.dom
from calendar import Calendar
from random import shuffle
-from typing import Any, Callable, Dict, List
+from typing import Any, Callable, Dict, List, Union
from unittest.mock import patch
import pytest
from jsonargparse import Namespace, class_from_function
from jsonargparse._optionals import docstring_parser_support
+from jsonargparse._parameter_resolvers import ConditionalDefault, is_lambda
from jsonargparse._parameter_resolvers import get_signature_parameters as get_params
-from jsonargparse._parameter_resolvers import is_lambda
from jsonargparse_tests.conftest import capture_logs, source_unavailable
@@ -383,6 +383,21 @@ def function_pop_get_from_kwargs(kn1: int = 0, **kw):
kw.pop("pk1", "")
+def function_pop_get_conditional(p1: str, **kw):
+ """
+ Args:
+ p1: help for p1
+ p2: help for p2
+ p3: help for p3
+ """
+ kw.get("p3", "x")
+ if p1 == "a":
+ kw.pop("p2", None)
+ elif p1 == "b":
+ kw.pop("p2", 3)
+ kw.get("p3", "y")
+
+
def function_with_bug(**kws):
return does_not_exist(**kws) # noqa: F821
@@ -451,6 +466,7 @@ def assert_params(params, expected, origins={}):
assert expected == [p.name for p in params]
docs = [f"help for {p.name}" for p in params] if docstring_parser_support else [None] * len(params)
assert docs == [p.doc for p in params]
+ assert all(isinstance(params[n].default, ConditionalDefault) for n in origins.keys())
param_origins = {
n: [o.split(f"{__name__}.", 1)[1] for o in p.origin] for n, p in enumerate(params) if p.origin is not None
}
@@ -502,8 +518,9 @@ def test_get_params_class_with_kwargs_in_dict_attribute():
def test_get_params_class_kwargs_in_attr_method_conditioned_on_arg():
+ params = get_params(ClassG)
assert_params(
- get_params(ClassG),
+ params,
["func", "kmg1", "kmg2", "kmg3", "kmg4"],
{
2: ["ClassG._run:3", "ClassG._run:5"],
@@ -511,6 +528,10 @@ def test_get_params_class_kwargs_in_attr_method_conditioned_on_arg():
4: ["ClassG._run:5"],
},
)
+ assert params[2].annotation == Union[str, float]
+ assert str(params[2].default) == "Conditional<ast-resolver> {-, 2.3}"
+ assert str(params[3].default) == "Conditional<ast-resolver> {True, False}"
+ assert str(params[4].default) == "Conditional<ast-resolver> {4, NOT_ACCEPTED}"
with source_unavailable():
assert_params(get_params(ClassG), ["func"])
@@ -645,12 +666,31 @@ def test_get_params_function_call_classmethod():
def test_get_params_function_pop_get_from_kwargs(logger):
with capture_logs(logger) as logs:
params = get_params(function_pop_get_from_kwargs, logger=logger)
- assert_params(params, ["kn1", "k2", "kn2", "kn3", "kn4", "pk1"])
+ assert str(params[1].default) == "Conditional<ast-resolver> {2, 1}"
+ assert_params(
+ params,
+ ["kn1", "k2", "kn2", "kn3", "kn4", "pk1"],
+ {1: ["function_pop_get_from_kwargs:10", "function_pop_get_from_kwargs:15"]},
+ )
assert "unsupported kwargs pop/get default" in logs.getvalue()
with source_unavailable():
assert_params(get_params(function_pop_get_from_kwargs), ["kn1"])
+def test_get_params_function_pop_get_conditional():
+ params = get_params(function_pop_get_conditional)
+ assert str(params[1].default) == "Conditional<ast-resolver> {x, y}"
+ assert str(params[2].default) == "Conditional<ast-resolver> {None, 3}"
+ assert_params(
+ params,
+ ["p1", "p3", "p2"],
+ {
+ 1: ["function_pop_get_conditional:8", "function_pop_get_conditional:13"],
+ 2: ["function_pop_get_conditional:10", "function_pop_get_conditional:12"],
+ },
+ )
+
+
def test_get_params_function_module_class():
params = get_params(function_module_class)
assert ["firstweekday"] == [p.name for p in params]
diff --git a/jsonargparse_tests/test_signatures.py b/jsonargparse_tests/test_signatures.py
index 5f0e0b9..22567a7 100644
--- a/jsonargparse_tests/test_signatures.py
+++ b/jsonargparse_tests/test_signatures.py
@@ -298,7 +298,7 @@ def test_add_class_conditional_kwargs(parser):
"help for kmg1 (type: int, default: 1)",
"help for kmg2 (type: Union[str, float], default: Conditional<ast-resolver> {-, 2.3})",
"help for kmg3 (type: bool, default: Conditional<ast-resolver> {True, False})",
- "help for kmg4 (type: int, default: Conditional<ast-resolver> 4)",
+ "help for kmg4 (type: int, default: Conditional<ast-resolver> {4, NOT_ACCEPTED})",
]
for value in expected:
assert value in help_str
| Instantiation fails with TypeError only when fail_untyped=False
<!-- If you like this project, please ⭐ star it https://github.com/omni-us/jsonargparse/ -->
## 🐛 Bug report
I'm trying to instantiate a config class from Huggingface with CLI and it fails when `fail_untyped=False`. The fail_untyped is important because I'm doing this as part of a project that is written within the lightning framework, where we make heavy use of lightning cli, which sets fail_untyped to False and you can't change it. Most of our project is written internally by us and is not HuggingFace based, but we want to make use from time to time of some external models in the open source community (like for example HuggingFace).
I created an isolated example just with jsonargparse (see below). It only fails when `fail_untyped=False` . I stepped through the instantiation and I'm quite confused of what's happening. `num_labels` is not set, and through kwargs.pop("num_labels", 2) it should become 2, which is an int.
```
File "/opt/pyenv/versions/3.10.12/lib/python3.10/site-packages/transformers/configuration_utils.py", line 331, in __init__
self.num_labels = kwargs.pop("num_labels", 2)
File "/opt/pyenv/versions/3.10.12/lib/python3.10/site-packages/transformers/configuration_utils.py", line 256, in __setattr__
super().__setattr__(key, value)
File "/opt/pyenv/versions/3.10.12/lib/python3.10/site-packages/transformers/configuration_utils.py", line 420, in num_labels
self.id2label = {i: f"LABEL_{i}" for i in range(num_labels)}
TypeError: 'NoneType' object cannot be interpreted as an integer
```
As a side note I am planning to submit a PR soon to allow people to set fail_untyped in lightning https://github.com/Lightning-AI/lightning/issues/18285 .
### To reproduce
```python
from jsonargparse import CLI
from dataclasses import dataclass
from transformers.models.perceiver.configuration_perceiver import PerceiverConfig
@dataclass
class Test:
cfg: PerceiverConfig
print(CLI(Test, fail_untyped=False))
```
Config
```yaml
cfg:
class_path: transformers.models.perceiver.configuration_perceiver.PerceiverConfig
```
Command
```
python perceiver.py --config perceiver_config.yaml
```
### Expected behavior
No TypeError
### Environment
<!-- Fill in the list below. -->
- jsonargparse version: 4.23.1
- Python version: 3.10.12
- How jsonargparse was installed: `pip install jsonargparse[signatures,typing-extensions]==4.23.1`
- Huggingface transformers package: transformers==4.31.0
- OS: Ubuntu 22.04.2 LTS
| 0.0 | [
"jsonargparse_tests/test_parameter_resolvers.py::test_get_params_class_kwargs_in_attr_method_conditioned_on_arg",
"jsonargparse_tests/test_parameter_resolvers.py::test_get_params_function_pop_get_from_kwargs",
"jsonargparse_tests/test_parameter_resolvers.py::test_get_params_function_pop_get_conditional"
] | [
"jsonargparse_tests/test_parameter_resolvers.py::test_get_params_class_no_inheritance_unused_kwargs",
"jsonargparse_tests/test_parameter_resolvers.py::test_get_params_class_with_inheritance_hard_coded_kwargs",
"jsonargparse_tests/test_parameter_resolvers.py::test_get_params_class_with_inheritance_unused_args",
"jsonargparse_tests/test_parameter_resolvers.py::test_get_params_class_with_valueless_init_ann",
"jsonargparse_tests/test_parameter_resolvers.py::test_get_params_class_with_inheritance_parent_without_init",
"jsonargparse_tests/test_parameter_resolvers.py::test_get_params_class_with_kwargs_in_dict_attribute",
"jsonargparse_tests/test_parameter_resolvers.py::test_get_params_method_resolution_order",
"jsonargparse_tests/test_parameter_resolvers.py::test_get_params_nonimmediate_method_resolution_order",
"jsonargparse_tests/test_parameter_resolvers.py::test_get_params_kwargs_use_in_property",
"jsonargparse_tests/test_parameter_resolvers.py::test_get_params_class_from_function",
"jsonargparse_tests/test_parameter_resolvers.py::test_get_params_class_instance_defaults",
"jsonargparse_tests/test_parameter_resolvers.py::test_get_params_method_no_args_no_kwargs",
"jsonargparse_tests/test_parameter_resolvers.py::test_get_params_method_call_super_method",
"jsonargparse_tests/test_parameter_resolvers.py::test_get_params_staticmethod_call_function_return_class_c",
"jsonargparse_tests/test_parameter_resolvers.py::test_get_params_classmethod_make_class",
"jsonargparse_tests/test_parameter_resolvers.py::test_get_params_classmethod_instantiate_from_cls",
"jsonargparse_tests/test_parameter_resolvers.py::test_get_params_function_no_args_no_kwargs",
"jsonargparse_tests/test_parameter_resolvers.py::test_get_params_function_with_kwargs",
"jsonargparse_tests/test_parameter_resolvers.py::test_get_params_function_return_class_c",
"jsonargparse_tests/test_parameter_resolvers.py::test_get_params_function_call_classmethod",
"jsonargparse_tests/test_parameter_resolvers.py::test_get_params_function_module_class",
"jsonargparse_tests/test_parameter_resolvers.py::test_get_params_function_constant_boolean",
"jsonargparse_tests/test_parameter_resolvers.py::test_get_params_function_invalid_type",
"jsonargparse_tests/test_parameter_resolvers.py::test_conditional_calls_kwargs",
"jsonargparse_tests/test_parameter_resolvers.py::test_unsupported_component",
"jsonargparse_tests/test_parameter_resolvers.py::test_unsupported_type_of_assign",
"jsonargparse_tests/test_parameter_resolvers.py::test_unsupported_kwarg_as_keyword",
"jsonargparse_tests/test_parameter_resolvers.py::test_unsupported_super_with_arbitrary_params",
"jsonargparse_tests/test_parameter_resolvers.py::test_unsupported_self_attr_not_found_in_members",
"jsonargparse_tests/test_parameter_resolvers.py::test_unsupported_kwarg_attr_as_keyword",
"jsonargparse_tests/test_parameter_resolvers.py::test_get_params_non_existent_call",
"jsonargparse_tests/test_parameter_resolvers.py::test_get_params_failures",
"jsonargparse_tests/test_signatures.py::test_add_class_failure_not_a_class",
"jsonargparse_tests/test_signatures.py::test_add_class_failure_positional_without_type",
"jsonargparse_tests/test_signatures.py::test_add_class_without_nesting",
"jsonargparse_tests/test_signatures.py::test_add_class_nested_as_group_false",
"jsonargparse_tests/test_signatures.py::test_add_class_default_group_title",
"jsonargparse_tests/test_signatures.py::test_add_class_with_default",
"jsonargparse_tests/test_signatures.py::test_add_class_env_help",
"jsonargparse_tests/test_signatures.py::test_add_class_without_parameters",
"jsonargparse_tests/test_signatures.py::test_add_class_nested_with_and_without_parameters",
"jsonargparse_tests/test_signatures.py::test_add_class_without_valid_parameters",
"jsonargparse_tests/test_signatures.py::test_add_class_implemented_with_new",
"jsonargparse_tests/test_signatures.py::test_add_class_with_required_parameters",
"jsonargparse_tests/test_signatures.py::test_add_class_conditional_kwargs",
"jsonargparse_tests/test_signatures.py::test_add_class_skip_parameter_debug_logging",
"jsonargparse_tests/test_signatures.py::test_add_class_in_subcommand",
"jsonargparse_tests/test_signatures.py::test_add_class_group_config",
"jsonargparse_tests/test_signatures.py::test_add_class_group_config_not_found",
"jsonargparse_tests/test_signatures.py::test_add_class_custom_instantiator",
"jsonargparse_tests/test_signatures.py::test_add_method_failure_adding",
"jsonargparse_tests/test_signatures.py::test_add_method_normal_and_static",
"jsonargparse_tests/test_signatures.py::test_add_method_parent_classes",
"jsonargparse_tests/test_signatures.py::test_add_function_failure_not_callable",
"jsonargparse_tests/test_signatures.py::test_add_function_arguments",
"jsonargparse_tests/test_signatures.py::test_add_function_skip_names",
"jsonargparse_tests/test_signatures.py::test_add_function_skip_positional_and_name",
"jsonargparse_tests/test_signatures.py::test_add_function_skip_positionals_invalid",
"jsonargparse_tests/test_signatures.py::test_add_function_invalid_type",
"jsonargparse_tests/test_signatures.py::test_add_function_implicit_optional",
"jsonargparse_tests/test_signatures.py::test_add_function_fail_untyped_true_str_type",
"jsonargparse_tests/test_signatures.py::test_add_function_fail_untyped_true_untyped_params",
"jsonargparse_tests/test_signatures.py::test_add_function_fail_untyped_false",
"jsonargparse_tests/test_signatures.py::test_add_function_group_config",
"jsonargparse_tests/test_signatures.py::test_add_function_group_config_within_config"
] | 2023-08-30 04:58:16+00:00 | 4,364 |
|
omni-us__jsonargparse-370 | diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index 46cd745..eccf4d3 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -26,6 +26,9 @@ Fixed
<https://github.com/omni-us/jsonargparse/issues/362>`__).
- ``ActionJsonSchema`` not setting correctly defaults when schema uses
``oneOf``.
+- Recommended ``print_config`` steps not working when ``default_config_files``
+ used due to the config file initially being empty (`#367
+ <https://github.com/omni-us/jsonargparse/issues/367>`__).
v4.24.0 (2023-08-23)
diff --git a/jsonargparse/_core.py b/jsonargparse/_core.py
index 014f056..778613c 100644
--- a/jsonargparse/_core.py
+++ b/jsonargparse/_core.py
@@ -631,6 +631,8 @@ class ArgumentParser(ParserDeprecations, ActionsContainer, ArgumentLinking, argp
cfg_dict = load_value(cfg_str, path=cfg_path, ext_vars=ext_vars)
except get_loader_exceptions() as ex:
raise TypeError(f"Problems parsing config: {ex}") from ex
+ if cfg_dict is None:
+ return Namespace()
if not isinstance(cfg_dict, dict):
raise TypeError(f"Unexpected config: {cfg_str}")
return self._apply_actions(cfg_dict, prev_cfg=prev_cfg)
| omni-us/jsonargparse | 6ed515b78d281e10b0cdc4fa3e8ae006fa29ed66 | diff --git a/jsonargparse_tests/test_core.py b/jsonargparse_tests/test_core.py
index 950420b..efd4df2 100644
--- a/jsonargparse_tests/test_core.py
+++ b/jsonargparse_tests/test_core.py
@@ -698,6 +698,15 @@ def test_print_config_invalid_flag(print_parser):
ctx.match('Invalid option "invalid"')
[email protected](sys.version_info[:2] == (3, 6), reason="not supported in python 3.6")
+def test_print_config_empty_default_config_file(print_parser, tmp_cwd):
+ default_config_file = tmp_cwd / "defaults.yaml"
+ default_config_file.touch()
+ print_parser.default_config_files = [default_config_file]
+ out = get_parse_args_stdout(print_parser, ["--print_config"])
+ assert yaml.safe_load(out) == {"g1": {"v2": "2"}, "g2": {"v3": None}, "v1": 1}
+
+
def test_default_config_files(parser, subtests, tmp_cwd):
default_config_file = tmp_cwd / "defaults.yaml"
default_config_file.write_text("op1: from default config file\n")
| Unexpected config error when a default config file is empty
## 🐛 Bug report
If at least one `default_config_files` is set and this file is empty, a `TypeError: Unexpected config: ` is triggered on `parser.parse_args()`. Even if no argument is mandatory.
### To reproduce
```python
from jsonargparse import ArgumentParser
parser = ArgumentParser(default_config_files=['config.yaml'])
parser.add_argument("test", type=int, help="test", default=1)
cfg = parser.parse_args()
print(cfg.as_dict())
```
**no 'config.yaml' file**
```bash
python main.py
> {'test': 1}
```
Work as expected, no error
**empty 'config.yaml' file**
```bash
touch config.yaml
python main.py
> Unexpected config error:
```
**Not empty 'config.yaml' file**
Work as expected, no error
```bash
echo "test: 42" > config.yaml
python bug.py
> {'test': 42, '__default_config__': Path_fr(config.yaml, cwd=/Users/...)}
```
### Expected behavior
I expect to have the same behavior between no configuration file and empty configuration file.
In the case where every argument are optional I don't expect to have an error.
In my case I wanted to generate this default configuration file as suggest [in the document](https://jsonargparse.readthedocs.io/en/v4.24.0/#writing-configuration-files) with:
```bash
python example.py --print_config > config.yaml
````
But an empty file is created before to run the script. Which trigger the issue mentioned above.
### Environment
- jsonargparse version: 4.24.0
- Python version: 3.11.4
- How jsonargparse was installed: `pip install jsonargparse[signatures]~=4.24 docstring-parser~=0.15 PyYAML~=6.0 ruyaml~=0.91`
- OS: macOS 13.4.1
| 0.0 | [
"jsonargparse_tests/test_core.py::test_print_config_empty_default_config_file"
] | [
"jsonargparse_tests/test_core.py::test_parse_args_simple",
"jsonargparse_tests/test_core.py::test_parse_args_nested",
"jsonargparse_tests/test_core.py::test_parse_args_unrecognized_arguments",
"jsonargparse_tests/test_core.py::test_parse_args_invalid_args",
"jsonargparse_tests/test_core.py::test_parse_args_base_namespace",
"jsonargparse_tests/test_core.py::test_parse_args_unexpected_kwarg",
"jsonargparse_tests/test_core.py::test_parse_args_nargs_plus",
"jsonargparse_tests/test_core.py::test_parse_args_nargs_asterisk",
"jsonargparse_tests/test_core.py::test_parse_args_nargs_questionmark",
"jsonargparse_tests/test_core.py::test_parse_args_nargs_number",
"jsonargparse_tests/test_core.py::test_parse_args_positional_nargs_questionmark",
"jsonargparse_tests/test_core.py::test_parse_args_positional_nargs_plus",
"jsonargparse_tests/test_core.py::test_parse_args_positional_config",
"jsonargparse_tests/test_core.py::test_parse_args_choices",
"jsonargparse_tests/test_core.py::test_parse_object_simple",
"jsonargparse_tests/test_core.py::test_parse_object_nested",
"jsonargparse_tests/test_core.py::test_env_prefix_from_prog_with_dashes",
"jsonargparse_tests/test_core.py::test_parse_env_simple",
"jsonargparse_tests/test_core.py::test_parse_env_nested",
"jsonargparse_tests/test_core.py::test_parse_env_config",
"jsonargparse_tests/test_core.py::test_parse_env_positional_nargs_plus",
"jsonargparse_tests/test_core.py::test_default_env_property",
"jsonargparse_tests/test_core.py::test_default_env_override_true",
"jsonargparse_tests/test_core.py::test_default_env_override_false",
"jsonargparse_tests/test_core.py::test_env_prefix_true",
"jsonargparse_tests/test_core.py::test_env_prefix_false",
"jsonargparse_tests/test_core.py::test_env_properties_set_invalid",
"jsonargparse_tests/test_core.py::test_parse_string_simple",
"jsonargparse_tests/test_core.py::test_parse_string_simple_errors",
"jsonargparse_tests/test_core.py::test_parse_string_nested",
"jsonargparse_tests/test_core.py::test_parse_path_simple",
"jsonargparse_tests/test_core.py::test_parse_path_simple_errors",
"jsonargparse_tests/test_core.py::test_parse_path_defaults",
"jsonargparse_tests/test_core.py::test_precedence_of_sources",
"jsonargparse_tests/test_core.py::test_non_positional_required",
"jsonargparse_tests/test_core.py::test_dump_complete",
"jsonargparse_tests/test_core.py::test_dump_incomplete",
"jsonargparse_tests/test_core.py::test_dump_formats",
"jsonargparse_tests/test_core.py::test_dump_skip_default_simple",
"jsonargparse_tests/test_core.py::test_dump_skip_default_nested",
"jsonargparse_tests/test_core.py::test_dump_order",
"jsonargparse_tests/test_core.py::test_parse_args_url_config",
"jsonargparse_tests/test_core.py::test_save_multifile",
"jsonargparse_tests/test_core.py::test_save_overwrite",
"jsonargparse_tests/test_core.py::test_save_subconfig_overwrite",
"jsonargparse_tests/test_core.py::test_save_invalid_format",
"jsonargparse_tests/test_core.py::test_save_path_content",
"jsonargparse_tests/test_core.py::test_print_config_normal",
"jsonargparse_tests/test_core.py::test_print_config_skip_null",
"jsonargparse_tests/test_core.py::test_print_config_invalid_flag",
"jsonargparse_tests/test_core.py::test_default_config_files",
"jsonargparse_tests/test_core.py::test_default_config_file_help_message_no_existing",
"jsonargparse_tests/test_core.py::test_default_config_file_invalid_value",
"jsonargparse_tests/test_core.py::test_default_config_files_pattern",
"jsonargparse_tests/test_core.py::test_named_argument_groups",
"jsonargparse_tests/test_core.py::test_set_get_defaults_single",
"jsonargparse_tests/test_core.py::test_set_get_defaults_multiple",
"jsonargparse_tests/test_core.py::test_add_multiple_config_arguments_error",
"jsonargparse_tests/test_core.py::test_check_config_skip_none",
"jsonargparse_tests/test_core.py::test_check_config_branch",
"jsonargparse_tests/test_core.py::test_merge_config",
"jsonargparse_tests/test_core.py::test_strip_unknown",
"jsonargparse_tests/test_core.py::test_exit_on_error",
"jsonargparse_tests/test_core.py::test_version_print",
"jsonargparse_tests/test_core.py::test_debug_environment_variable",
"jsonargparse_tests/test_core.py::test_parse_known_args_not_implemented",
"jsonargparse_tests/test_core.py::test_parse_known_args_not_implemented_without_caller_module",
"jsonargparse_tests/test_core.py::test_default_meta_property",
"jsonargparse_tests/test_core.py::test_pickle_parser"
] | 2023-09-05 05:18:22+00:00 | 4,365 |
|
omni-us__jsonargparse-378 | diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index 3e4a477..7958e8f 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -15,6 +15,11 @@ paths are considered internals and can change in minor and patch releases.
v4.25.0 (2023-09-??)
--------------------
+Added
+^^^^^
+- Support for user-defined generic types (`#366
+ <https://github.com/omni-us/jsonargparse/issues/366>`__).
+
Fixed
^^^^^
- ``--print_config`` fails when parser has shallow links.
diff --git a/DOCUMENTATION.rst b/DOCUMENTATION.rst
index f68a386..46dc308 100644
--- a/DOCUMENTATION.rst
+++ b/DOCUMENTATION.rst
@@ -407,6 +407,9 @@ Some notes about this support are:
see :ref:`dataclass-like`. If a dataclass is mixed inheriting from a normal
class, it is considered a subclass type instead of a dataclass.
+- User-defined ``Generic`` types are supported. For more details see
+ :ref:`generic-types`.
+
- `Pydantic types <https://docs.pydantic.dev/usage/types/#pydantic-types>`__ are
supported. There might be edge cases which don't work as expected. Please
report any encountered issues.
@@ -876,6 +879,39 @@ structure.
number: 8
accepted: true
+.. _generic-types:
+
+Generic types
+-------------
+
+Classes that inherit from ``typing.Generic``, also known as `user-defined
+generic types
+<https://docs.python.org/3/library/typing.html#user-defined-generic-types>`__,
+are supported. Take for example a point in 2D:
+
+.. testsetup:: generic_types
+
+ parser = ArgumentParser()
+
+.. testcode:: generic_types
+
+ from typing import Generic, TypeVar
+
+ Number = TypeVar("Number", float, complex)
+
+ @dataclass
+ class Point2d(Generic[Number]):
+ x: Number = 0.0
+ y: Number = 0.0
+
+Parsing complex-valued points would be:
+
+.. doctest:: generic_types
+
+ >>> parser.add_argument("--point", type=Point2d[complex]) # doctest: +IGNORE_RESULT
+ >>> parser.parse_args(["--point.x=(1+2j)"]).point
+ Namespace(x=(1+2j), y=0.0)
+
.. _callable-type:
diff --git a/README.rst b/README.rst
index a06ac4b..c1c7aa2 100644
--- a/README.rst
+++ b/README.rst
@@ -63,9 +63,9 @@ high-quality code**. It encompasses numerous powerful features, some unique to
Other notable features include:
-- **Extensive type hint support:** nested types (union, tuple, etc.),
- containers (list, dict, etc.), restricted types (regex, numbers), paths, URLs,
- types from stubs (``*.pyi``), future annotations (PEP `563
+- **Extensive type hint support:** nested types (union, optional), containers
+ (list, dict, etc.), user-defined generics, restricted types (regex, numbers),
+ paths, URLs, types from stubs (``*.pyi``), future annotations (PEP `563
<https://peps.python.org/pep-0563/>`__), and backports (PEPs `604
<https://peps.python.org/pep-0604>`__/`585
<https://peps.python.org/pep-0585>`__).
diff --git a/jsonargparse/_common.py b/jsonargparse/_common.py
index 348f523..06053c9 100644
--- a/jsonargparse/_common.py
+++ b/jsonargparse/_common.py
@@ -3,7 +3,7 @@ import inspect
import sys
from contextlib import contextmanager
from contextvars import ContextVar
-from typing import Dict, Optional, Tuple, Type, TypeVar, Union
+from typing import Dict, Generic, Optional, Tuple, Type, TypeVar, Union, _GenericAlias # type: ignore
from ._namespace import Namespace
from ._type_checking import ArgumentParser
@@ -70,12 +70,22 @@ def is_final_class(cls) -> bool:
return getattr(cls, "__final__", False)
+def is_generic_class(cls) -> bool:
+ return isinstance(cls, _GenericAlias) and getattr(cls, "__module__", "") != "typing"
+
+
+def get_generic_origin(cls):
+ return cls.__origin__ if is_generic_class(cls) else cls
+
+
def is_dataclass_like(cls) -> bool:
+ if is_generic_class(cls):
+ return is_dataclass_like(cls.__origin__)
if not inspect.isclass(cls):
return False
if is_final_class(cls):
return True
- classes = [c for c in inspect.getmro(cls) if c != object]
+ classes = [c for c in inspect.getmro(cls) if c not in {object, Generic}]
all_dataclasses = all(dataclasses.is_dataclass(c) for c in classes)
from ._optionals import attrs_support, pydantic_support
diff --git a/jsonargparse/_parameter_resolvers.py b/jsonargparse/_parameter_resolvers.py
index a2df528..a53513b 100644
--- a/jsonargparse/_parameter_resolvers.py
+++ b/jsonargparse/_parameter_resolvers.py
@@ -11,7 +11,7 @@ from dataclasses import dataclass
from functools import partial
from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union
-from ._common import is_dataclass_like, is_subclass
+from ._common import get_generic_origin, is_dataclass_like, is_generic_class, is_subclass
from ._optionals import parse_docs
from ._postponed_annotations import evaluate_postponed_annotations
from ._stubs_resolver import get_stub_types
@@ -283,9 +283,28 @@ def get_signature_parameters_and_indexes(component, parent, logger):
)
evaluate_postponed_annotations(params, signature_source, parent, logger)
stubs = get_stub_types(params, signature_source, parent, logger)
+ replace_generic_type_vars(params, parent)
return params, args_idx, kwargs_idx, doc_params, stubs
+def replace_generic_type_vars(params: ParamList, parent) -> None:
+ if is_generic_class(parent) and parent.__args__ and getattr(parent.__origin__, "__parameters__", None):
+ type_vars = dict(zip(parent.__origin__.__parameters__, parent.__args__))
+
+ def replace_type_vars(annotation):
+ if annotation in type_vars:
+ return type_vars[annotation]
+ if getattr(annotation, "__args__", None):
+ origin = annotation.__origin__
+ if sys.version_info < (3, 10) and getattr(origin, "__module__", "") != "typing":
+ origin = getattr(__import__("typing"), origin.__name__.capitalize(), origin)
+ return origin[tuple(replace_type_vars(a) for a in annotation.__args__)]
+ return annotation
+
+ for param in params:
+ param.annotation = replace_type_vars(param.annotation)
+
+
def add_stub_types(stubs: Optional[Dict[str, Any]], params: ParamList, component) -> None:
if not stubs:
return
@@ -380,7 +399,7 @@ def group_parameters(params_list: List[ParamList]) -> ParamList:
def has_dunder_new_method(cls, attr_name):
- classes = inspect.getmro(cls)[1:]
+ classes = inspect.getmro(get_generic_origin(cls))[1:]
return (
attr_name == "__init__"
and cls.__new__ is not object.__new__
@@ -424,13 +443,13 @@ def get_component_and_parent(
if is_subclass(function_or_class, ClassFromFunctionBase) and method_or_property in {None, "__init__"}:
function_or_class = function_or_class.wrapped_function # type: ignore
method_or_property = None
- elif inspect.isclass(function_or_class) and method_or_property is None:
+ elif inspect.isclass(get_generic_origin(function_or_class)) and method_or_property is None:
method_or_property = "__init__"
elif method_or_property and not isinstance(method_or_property, str):
method_or_property = method_or_property.__name__
parent = component = None
if method_or_property:
- attr = inspect.getattr_static(function_or_class, method_or_property)
+ attr = inspect.getattr_static(get_generic_origin(function_or_class), method_or_property)
if is_staticmethod(attr):
component = getattr(function_or_class, method_or_property)
return component, parent, method_or_property
diff --git a/jsonargparse/_signatures.py b/jsonargparse/_signatures.py
index 6e6bd31..ba5731f 100644
--- a/jsonargparse/_signatures.py
+++ b/jsonargparse/_signatures.py
@@ -8,7 +8,7 @@ from contextlib import suppress
from typing import Any, Callable, List, Optional, Set, Tuple, Type, Union
from ._actions import _ActionConfigLoad
-from ._common import get_class_instantiator, is_dataclass_like, is_subclass
+from ._common import get_class_instantiator, get_generic_origin, is_dataclass_like, is_subclass
from ._optionals import get_doc_short_description, pydantic_support
from ._parameter_resolvers import (
ParamData,
@@ -72,7 +72,7 @@ class SignatureArguments(LoggerProperty):
ValueError: When not given a class.
ValueError: When there are required parameters without at least one valid type.
"""
- if not inspect.isclass(theclass):
+ if not inspect.isclass(get_generic_origin(theclass)):
raise ValueError(f'Expected "theclass" parameter to be a class type, got: {theclass}.')
if default and not (isinstance(default, LazyInitBaseClass) and isinstance(default, theclass)):
raise ValueError(f'Expected "default" parameter to be a lazy instance of the class, got: {default}.')
@@ -133,7 +133,7 @@ class SignatureArguments(LoggerProperty):
ValueError: When not given a class or the name of a method of the class.
ValueError: When there are required parameters without at least one valid type.
"""
- if not inspect.isclass(theclass):
+ if not inspect.isclass(get_generic_origin(theclass)):
raise ValueError('Expected "theclass" argument to be a class object.')
if not hasattr(theclass, themethod) or not callable(getattr(theclass, themethod)):
raise ValueError('Expected "themethod" argument to be a callable member of the class.')
diff --git a/jsonargparse/_util.py b/jsonargparse/_util.py
index 7d4c33a..e5b8eb9 100644
--- a/jsonargparse/_util.py
+++ b/jsonargparse/_util.py
@@ -30,7 +30,7 @@ from typing import (
get_type_hints,
)
-from ._common import ClassType, is_subclass, parser_capture, parser_context
+from ._common import ClassType, get_generic_origin, is_subclass, parser_capture, parser_context
from ._deprecated import PathDeprecations
from ._loaders_dumpers import json_dump, load_value
from ._optionals import (
@@ -215,6 +215,7 @@ def get_module_var_path(module_path: str, value: Any) -> Optional[str]:
def get_import_path(value: Any) -> Optional[str]:
"""Returns the shortest dot import path for the given object."""
path = None
+ value = get_generic_origin(value)
module_path = getattr(value, "__module__", None)
qualname = getattr(value, "__qualname__", "")
| omni-us/jsonargparse | 5da03814831aa00fb849887dccd38284eb76030e | diff --git a/jsonargparse_tests/test_dataclass_like.py b/jsonargparse_tests/test_dataclass_like.py
index 5cf262a..3c0622e 100644
--- a/jsonargparse_tests/test_dataclass_like.py
+++ b/jsonargparse_tests/test_dataclass_like.py
@@ -1,7 +1,7 @@
from __future__ import annotations
import dataclasses
-from typing import Any, Dict, List, Optional, Union
+from typing import Any, Dict, Generic, List, Optional, Tuple, TypeVar, Union
from unittest.mock import patch
import pytest
@@ -385,6 +385,40 @@ def test_dataclass_in_list_type(parser):
assert isinstance(init.list[1], Data)
+T = TypeVar("T", int, float)
+
+
[email protected]
+class GenericData(Generic[T]):
+ g1: T
+ g2: Tuple[T, T]
+ g3: Union[str, T]
+ g4: Dict[str, Union[T, bool]]
+
+
+def test_generic_dataclass(parser):
+ parser.add_argument("--data", type=GenericData[int])
+ help_str = get_parser_help(parser).lower()
+ assert "--data.g1 g1 (required, type: int)" in help_str
+ assert "--data.g2 [item,...] (required, type: tuple[int, int])" in help_str
+ assert "--data.g3 g3 (required, type: union[str, int])" in help_str
+ assert "--data.g4 g4 (required, type: dict[str, union[int, bool]])" in help_str
+
+
[email protected]
+class SpecificData:
+ y: GenericData[float]
+
+
+def test_nested_generic_dataclass(parser):
+ parser.add_dataclass_arguments(SpecificData, "x")
+ help_str = get_parser_help(parser).lower()
+ assert "--x.y.g1 g1 (required, type: float)" in help_str
+ assert "--x.y.g2 [item,...] (required, type: tuple[float, float])" in help_str
+ assert "--x.y.g3 g3 (required, type: union[str, float])" in help_str
+ assert "--x.y.g4 g4 (required, type: dict[str, union[float, bool]])" in help_str
+
+
# final classes tests
diff --git a/jsonargparse_tests/test_signatures.py b/jsonargparse_tests/test_signatures.py
index b251e96..f10ff1e 100644
--- a/jsonargparse_tests/test_signatures.py
+++ b/jsonargparse_tests/test_signatures.py
@@ -1,7 +1,7 @@
from __future__ import annotations
from pathlib import Path
-from typing import Any, Dict, List, Optional, Tuple, Union
+from typing import Any, Dict, Generic, List, Optional, Tuple, TypeVar, Union
from unittest.mock import patch
import pytest
@@ -391,6 +391,22 @@ def test_add_class_custom_instantiator(parser):
assert init.a.call == "custom"
+X = TypeVar("X")
+Y = TypeVar("Y")
+
+
+class WithGenerics(Generic[X, Y]):
+ def __init__(self, a: X, b: Y):
+ self.a = a
+ self.b = b
+
+
+def test_add_class_generics(parser):
+ parser.add_class_arguments(WithGenerics[int, complex], "p")
+ cfg = parser.parse_args(["--p.a=5", "--p.b=(6+7j)"])
+ assert cfg.p == Namespace(a=5, b=6 + 7j)
+
+
# add_method_arguments tests
| Support for generic dataclasses
## 🚀 Feature request
Add support for generic dataclasses in `ArgumentParser`.
### Motivation
I often use generic dataclasses as configuration objects in libraries code. When building a CLI application, I would like to reuse these configurations to build a specialized parser.
Currently if a generic dataclass is used as a subparser, the argument parsing complains that all parameters are not typed and crashes.
```python
from dataclasses import dataclass
from typing import Generic, TypeVar
from jsonargparse import ActionConfigFile, ArgumentParser
T = TypeVar("T")
# This is generic library code
@dataclass
class SubConfig(Generic[T]):
generic: T
a: int = 1
b: float = 2.0
# This is CLI-specific
@dataclass
class Config:
subconfig: SubConfig[int]
if __name__ == "__main__":
parser = ArgumentParser(print_config="--print-config")
parser.add_argument("--load", action=ActionConfigFile, help="Path to a YAML configuration")
parser.add_dataclass_arguments(Config, "config")
parser.parse_args()
```
```bash
$ python mre_jsonargparse.py --print-config
Traceback (most recent call last):
File "/Users/bilelomrani/Documents/ILLUIN.nosync/instructions-finetuning/mre_jsonargparse.py", line 24, in <module>
parser.add_dataclass_arguments(Config, "config")
File "/Users/bilelomrani/Documents/ILLUIN.nosync/instructions-finetuning/.venv/lib/python3.10/site-packages/jsonargparse/_signatures.py", line 435, in add_dataclass_arguments
self._add_signature_parameter(
File "/Users/bilelomrani/Documents/ILLUIN.nosync/instructions-finetuning/.venv/lib/python3.10/site-packages/jsonargparse/_signatures.py", line 381, in _add_signature_parameter
raise ValueError(
ValueError: With fail_untyped=True, all mandatory parameters must have a supported type. Parameter 'subconfig' from '__main__.Config.__init__' does not specify a type.
```
With `fail_untyped=False`, the printed config is empty.
### Pitch
Would be cool if `parser.add_dataclass_arguments` would work with generic dataclasses and would generate a specialized subparser (in the case of my example, adding an `int` validator to `config.subconfig.generic`).
| 0.0 | [
"jsonargparse_tests/test_dataclass_like.py::test_generic_dataclass",
"jsonargparse_tests/test_dataclass_like.py::test_nested_generic_dataclass",
"jsonargparse_tests/test_signatures.py::test_add_class_generics"
] | [
"jsonargparse_tests/test_dataclass_like.py::test_add_dataclass_arguments",
"jsonargparse_tests/test_dataclass_like.py::test_add_dataclass_nested_defaults",
"jsonargparse_tests/test_dataclass_like.py::test_add_class_with_dataclass_attributes",
"jsonargparse_tests/test_dataclass_like.py::test_add_class_dataclass_typehint_in_subclass",
"jsonargparse_tests/test_dataclass_like.py::test_add_class_optional_without_default",
"jsonargparse_tests/test_dataclass_like.py::test_add_argument_dataclass_type",
"jsonargparse_tests/test_dataclass_like.py::test_add_argument_dataclass_type_required_attr",
"jsonargparse_tests/test_dataclass_like.py::test_dataclass_field_init_false",
"jsonargparse_tests/test_dataclass_like.py::test_dataclass_field_default_factory",
"jsonargparse_tests/test_dataclass_like.py::test_dataclass_fail_untyped_false",
"jsonargparse_tests/test_dataclass_like.py::test_compose_dataclasses",
"jsonargparse_tests/test_dataclass_like.py::test_instantiate_dataclass_within_classes",
"jsonargparse_tests/test_dataclass_like.py::test_optional_dataclass_type_all_fields",
"jsonargparse_tests/test_dataclass_like.py::test_optional_dataclass_type_single_field",
"jsonargparse_tests/test_dataclass_like.py::test_optional_dataclass_type_invalid_field",
"jsonargparse_tests/test_dataclass_like.py::test_optional_dataclass_type_instantiate",
"jsonargparse_tests/test_dataclass_like.py::test_optional_dataclass_type_dump",
"jsonargparse_tests/test_dataclass_like.py::test_optional_dataclass_type_missing_required_field",
"jsonargparse_tests/test_dataclass_like.py::test_optional_dataclass_type_null_value",
"jsonargparse_tests/test_dataclass_like.py::test_dataclass_optional_dict_attribute",
"jsonargparse_tests/test_dataclass_like.py::test_dataclass_in_union_type",
"jsonargparse_tests/test_dataclass_like.py::test_dataclass_in_list_type",
"jsonargparse_tests/test_dataclass_like.py::test_add_class_final",
"jsonargparse_tests/test_dataclass_like.py::TestPydantic::test_dataclass",
"jsonargparse_tests/test_dataclass_like.py::TestPydantic::test_basemodel",
"jsonargparse_tests/test_dataclass_like.py::TestPydantic::test_subclass",
"jsonargparse_tests/test_dataclass_like.py::TestPydantic::test_field_default_factory",
"jsonargparse_tests/test_dataclass_like.py::TestPydantic::test_field_description",
"jsonargparse_tests/test_dataclass_like.py::TestPydantic::test_pydantic_types",
"jsonargparse_tests/test_dataclass_like.py::TestAttrs::test_define",
"jsonargparse_tests/test_dataclass_like.py::TestAttrs::test_subclass",
"jsonargparse_tests/test_dataclass_like.py::TestAttrs::test_field_factory",
"jsonargparse_tests/test_signatures.py::test_add_class_failure_not_a_class",
"jsonargparse_tests/test_signatures.py::test_add_class_failure_positional_without_type",
"jsonargparse_tests/test_signatures.py::test_add_class_without_nesting",
"jsonargparse_tests/test_signatures.py::test_add_class_nested_as_group_false",
"jsonargparse_tests/test_signatures.py::test_add_class_default_group_title",
"jsonargparse_tests/test_signatures.py::test_add_class_with_default",
"jsonargparse_tests/test_signatures.py::test_add_class_env_help",
"jsonargparse_tests/test_signatures.py::test_add_class_without_parameters",
"jsonargparse_tests/test_signatures.py::test_add_class_nested_with_and_without_parameters",
"jsonargparse_tests/test_signatures.py::test_add_class_without_valid_parameters",
"jsonargparse_tests/test_signatures.py::test_add_class_implemented_with_new",
"jsonargparse_tests/test_signatures.py::test_add_class_with_required_parameters",
"jsonargparse_tests/test_signatures.py::test_add_class_conditional_kwargs",
"jsonargparse_tests/test_signatures.py::test_add_class_skip_parameter_debug_logging",
"jsonargparse_tests/test_signatures.py::test_add_class_in_subcommand",
"jsonargparse_tests/test_signatures.py::test_add_class_group_config",
"jsonargparse_tests/test_signatures.py::test_add_class_group_config_not_found",
"jsonargparse_tests/test_signatures.py::test_add_class_custom_instantiator",
"jsonargparse_tests/test_signatures.py::test_add_method_failure_adding",
"jsonargparse_tests/test_signatures.py::test_add_method_normal_and_static",
"jsonargparse_tests/test_signatures.py::test_add_method_parent_classes",
"jsonargparse_tests/test_signatures.py::test_add_function_failure_not_callable",
"jsonargparse_tests/test_signatures.py::test_add_function_arguments",
"jsonargparse_tests/test_signatures.py::test_add_function_skip_names",
"jsonargparse_tests/test_signatures.py::test_add_function_skip_positional_and_name",
"jsonargparse_tests/test_signatures.py::test_add_function_skip_positionals_invalid",
"jsonargparse_tests/test_signatures.py::test_add_function_invalid_type",
"jsonargparse_tests/test_signatures.py::test_add_function_implicit_optional",
"jsonargparse_tests/test_signatures.py::test_add_function_fail_untyped_true_str_type",
"jsonargparse_tests/test_signatures.py::test_add_function_fail_untyped_true_untyped_params",
"jsonargparse_tests/test_signatures.py::test_add_function_fail_untyped_false",
"jsonargparse_tests/test_signatures.py::test_add_function_group_config",
"jsonargparse_tests/test_signatures.py::test_add_function_group_config_within_config"
] | 2023-09-12 05:17:41+00:00 | 4,366 |
|
omni-us__jsonargparse-380 | diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index 137d475..b3165af 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -19,6 +19,9 @@ Added
^^^^^
- Support for user-defined generic types (`#366
<https://github.com/omni-us/jsonargparse/issues/366>`__).
+- New function ``extend_base_type`` for easy creation and registering of custom
+ types that extend a base type (`#195
+ <https://github.com/omni-us/jsonargparse/issue/195>`__).
- Support for Python 3.12.
Fixed
@@ -38,6 +41,8 @@ Changed
- ``add_subclass_arguments`` now shows a better error message when an empty
tuple is given (`lightning#18546
<https://github.com/Lightning-AI/lightning/issues/18546>`__).
+- Document the requirements for creating and using custom types (`#195
+ <https://github.com/omni-us/jsonargparse/issue/195>`__).
- Removed support for python 3.6.
diff --git a/DOCUMENTATION.rst b/DOCUMENTATION.rst
index 46dc308..7363c17 100644
--- a/DOCUMENTATION.rst
+++ b/DOCUMENTATION.rst
@@ -331,6 +331,24 @@ Having a CLI function this could be easily implemented with
:func:`.CLI` is by using :func:`.capture_parser`.
+Functions as type
+-----------------
+
+Using a function as a type, like ``int_or_off`` below, is supported though
+discouraged. A basic requirement is that the function be idempotent, i.e.,
+applying the function two or more times should not modify the value. Instead of
+a function, it is recommended to implement a type, see :ref:`custom-types`.
+
+.. testcode::
+
+ # either int larger than zero or 'off' string
+ def int_or_off(x):
+ return x if x == "off" else int(x)
+
+
+ parser.add_argument("--int_or_off", type=int_or_off)
+
+
.. _type-hints:
Type hints
@@ -448,14 +466,6 @@ are:
parser.add_argument("--op2", type=from_0_to_10)
- # either int larger than zero or 'off' string
- def int_or_off(x):
- return x if x == "off" else PositiveInt(x)
-
-
- parser.add_argument("--op3", type=int_or_off)
-
-
.. _restricted-strings:
Restricted strings
@@ -1090,6 +1100,66 @@ requires to give both a serializer and a deserializer as seen below.
:func:`.register_type` then the sub-class option is no longer available.
+.. _custom-types:
+
+Creating custom types
+---------------------
+
+It is possible to create new types and use them for parsing. Even though types
+can be created for specific CLI behaviors, it is recommended to create them such
+that they make sense independent of parsing. This is so that they can be used as
+type hints in functions and classes in order to improve the code in a more
+general sense.
+
+There are a few ways for creating types, the most simple being to implement a
+class. When creating a type, take as reference how basic types work, e.g.
+``int``. Properties of basic types are:
+
+- Casting a string creates an instance of the type, if the value is valid, e.g.
+ ``int("1")``.
+- Casting a string raises a ``ValueError``, if the value is not valid, e.g.
+ ``int("a")``.
+- Casting an instance of the type to string gives back the string representation
+ of the value, e.g. ``str(1) == "1"``.
+- Types are idempotent, i.e. casting an instance of the type to the type gives
+ back the same value, e.g. ``int(1) == int(int(1))``.
+
+Once a type is created, it can be registered with :func:`.register_type`. If the
+type follows the properties above, then there is no need to provide more
+parameters, just do ``register_type(MyType)``.
+
+The :func:`.extend_base_type` function can be useful for creating and
+registering new types in a single call. For example, creating a type for even
+integers could be done as:
+
+.. testcode::
+
+ from jsonargparse.typing import extend_base_type
+
+ def is_even(type_class, value):
+ if int(value) % 2 != 0:
+ raise ValueError(f"{value} is not even")
+
+ EvenInt = extend_base_type("EvenInt", int, is_even)
+
+Then this type can be used in a parser as:
+
+.. doctest::
+
+ >>> parser = ArgumentParser()
+ >>> parser.add_argument("--even_int", type=EvenInt) # doctest: +IGNORE_RESULT
+ >>> parser.parse_args(["--even_int=2"])
+ Namespace(even_int=2)
+
+When using custom types as a type hint, defaults must be casted so that static
+type checkers don't complain. For example:
+
+.. testcode::
+
+ def fn(value: EvenInt = EvenInt(2)):
+ ...
+
+
.. _nested-namespaces:
Nested namespaces
diff --git a/jsonargparse/typing.py b/jsonargparse/typing.py
index 33e40a6..9bf65c0 100644
--- a/jsonargparse/typing.py
+++ b/jsonargparse/typing.py
@@ -15,6 +15,7 @@ __all__ = [
"final",
"is_final_class",
"register_type",
+ "extend_base_type",
"restricted_number_type",
"restricted_string_type",
"path_type",
@@ -49,14 +50,28 @@ registered_type_handlers: Dict[type, "RegisteredType"] = {}
registration_pending: Dict[str, Callable] = {}
-def create_type(
+def extend_base_type(
name: str,
base_type: type,
- check_value: Callable,
- register_key: Optional[Tuple] = None,
+ validation_fn: Callable,
docstring: Optional[str] = None,
extra_attrs: Optional[dict] = None,
+ register_key: Optional[Tuple] = None,
) -> type:
+ """Creates and registers an extension of base type.
+
+ Args:
+ name: How the new type will be called.
+ base_type: The type from which the created type is extended.
+ validation_fn: Function that validates the value on instantiation/casting. Gets two arguments: type_class and
+ value.
+ docstring: The __doc__ attribute value for the created type.
+ extra_attrs: Attributes set to the type class that the validation_fn can access.
+ register_key: Used to determine the uniqueness of registered types.
+
+ Raises:
+ ValueError: If the type has already been registered with a different name.
+ """
if register_key in registered_types:
registered_type = registered_types[register_key]
if registered_type.__name__ != name:
@@ -64,11 +79,12 @@ def create_type(
return registered_type
class TypeCore:
- _check_value = check_value
+ _validation_fn = validation_fn
+ _type = base_type
def __new__(cls, v):
- cls._check_value(cls, v)
- return super().__new__(cls, v)
+ cls._validation_fn(cls, v)
+ return super().__new__(cls, cls._type(v))
if extra_attrs is not None:
for key, value in extra_attrs.items():
@@ -133,7 +149,7 @@ def restricted_number_type(
"_type": base_type,
}
- def check_value(cls, v):
+ def validation_fn(cls, v):
if isinstance(v, bool):
raise ValueError(f"{v} not a number")
if cls._type == int and isinstance(v, float) and not float.is_integer(v):
@@ -143,10 +159,10 @@ def restricted_number_type(
if (cls._join == "and" and not all(check)) or (cls._join == "or" and not any(check)):
raise ValueError(f"{v} does not conform to restriction {cls._expression}")
- return create_type(
+ return extend_base_type(
name=name,
base_type=base_type,
- check_value=check_value,
+ validation_fn=validation_fn,
register_key=register_key,
docstring=docstring,
extra_attrs=extra_attrs,
@@ -178,14 +194,14 @@ def restricted_string_type(
"_type": str,
}
- def check_value(cls, v):
+ def validation_fn(cls, v):
if not cls._regex.match(v):
raise ValueError(f"{v} does not match regular expression {cls._regex.pattern}")
- return create_type(
+ return extend_base_type(
name=name,
base_type=str,
- check_value=check_value,
+ validation_fn=validation_fn,
register_key=(expression, str),
docstring=docstring,
extra_attrs=extra_attrs,
| omni-us/jsonargparse | 133c1586adf5523c024929702c838ba9e8ec3354 | diff --git a/jsonargparse_tests/test_typing.py b/jsonargparse_tests/test_typing.py
index f75096d..47c0b4b 100644
--- a/jsonargparse_tests/test_typing.py
+++ b/jsonargparse_tests/test_typing.py
@@ -20,6 +20,7 @@ from jsonargparse.typing import (
OpenUnitInterval,
PositiveFloat,
PositiveInt,
+ extend_base_type,
get_registered_type,
register_type,
register_type_on_first_use,
@@ -194,6 +195,17 @@ def test_type_function_parse(parser):
pytest.raises(ArgumentError, lambda: parser.parse_object({"multi_gt0_or_off": [1, 0]}))
+def test_extend_base_type(parser):
+ def is_even(t, v):
+ if int(v) % 2 != 0:
+ raise ValueError(f"{v} is not even")
+
+ EvenInt = extend_base_type("EvenInt", int, is_even)
+ parser.add_argument("--even_int", type=EvenInt)
+ assert 2 == parser.parse_args(["--even_int=2"]).even_int
+ pytest.raises(ArgumentError, lambda: parser.parse_args(["--even_int=3"]))
+
+
# restricted string tests
| Custom Types documentation
As a result of the changes that were made in jsonargparse for parsing types, some of the examples for argparse itself don't work completely.
This is an example from the argparse documentation on how to handle custom types
```
def hyphenated(string):
return '-'.join([word[:4] for word in string.casefold().split()])
parser = argparse.ArgumentParser()
_ = parser.add_argument('short_title', type=hyphenated)
parser.parse_args(['"The Tale of Two Cities"'])
```
This doesn't work completely in jsonargparse, because when printing the help screen it wants to print the type. The type part of the string just gets garbled into a reference to the memory location of the function.
Looking through the code there seem to be some complexities in getting a custom type implemented. Namely the use of the metaclass type, and some setup that the code wants implementing when calling the type constructor.
Saying that I notice that there was a function called create_type. It seems to provide all the abstractions required to make a custom_type.
It seems to strike a good balance between having control, and not being overly complicated. However, it currently is not documented.
This is an example of a test function
```
def interval2()-> Type:
def check_value(cls, v):
if v%5!=0:
raise ValueError(f'This is value is invalid')
return create_type("interval23",base_type=int,check_value=check_value,extra_attrs={"_type":int})
interval=interval2()
```
| 0.0 | [
"jsonargparse_tests/test_typing.py::test_public_api",
"jsonargparse_tests/test_typing.py::test_positive_int",
"jsonargparse_tests/test_typing.py::test_non_negative_int",
"jsonargparse_tests/test_typing.py::test_positive_float",
"jsonargparse_tests/test_typing.py::test_non_negative_float",
"jsonargparse_tests/test_typing.py::test_closed_unit_interval",
"jsonargparse_tests/test_typing.py::test_open_unit_interval",
"jsonargparse_tests/test_typing.py::test_restricted_number_invalid_type",
"jsonargparse_tests/test_typing.py::test_restricted_number_already_registered",
"jsonargparse_tests/test_typing.py::test_restricted_number_not_equal_operator",
"jsonargparse_tests/test_typing.py::test_restricted_number_operator_join",
"jsonargparse_tests/test_typing.py::test_non_negative_float_add_argument",
"jsonargparse_tests/test_typing.py::test_restricted_number_add_argument_optional",
"jsonargparse_tests/test_typing.py::test_restricted_number_add_argument_optional_nargs_plus",
"jsonargparse_tests/test_typing.py::test_restricted_number_positional_nargs_questionmark",
"jsonargparse_tests/test_typing.py::test_restricted_number_optional_union",
"jsonargparse_tests/test_typing.py::test_restricted_number_dump",
"jsonargparse_tests/test_typing.py::test_type_function_parse",
"jsonargparse_tests/test_typing.py::test_extend_base_type",
"jsonargparse_tests/test_typing.py::test_email",
"jsonargparse_tests/test_typing.py::test_optional_email_parse",
"jsonargparse_tests/test_typing.py::test_non_empty_string",
"jsonargparse_tests/test_typing.py::test_restricted_string_already_registered",
"jsonargparse_tests/test_typing.py::test_restricted_string_parse",
"jsonargparse_tests/test_typing.py::test_restricted_string_dump",
"jsonargparse_tests/test_typing.py::test_timedelta_deserializer[1:2:3-1:02:03]",
"jsonargparse_tests/test_typing.py::test_timedelta_deserializer[0:05:30-0:05:30]",
"jsonargparse_tests/test_typing.py::test_timedelta_deserializer[3",
"jsonargparse_tests/test_typing.py::test_timedelta_deserializer[345:0:0-14",
"jsonargparse_tests/test_typing.py::test_timedelta_deserializer_failure[not",
"jsonargparse_tests/test_typing.py::test_timedelta_deserializer_failure[1234]",
"jsonargparse_tests/test_typing.py::test_bytes[-]",
"jsonargparse_tests/test_typing.py::test_bytes[iVBORw0KGgo=-\\x89PNG\\r\\n\\x1a\\n]",
"jsonargparse_tests/test_typing.py::test_bytes[AAAAB3NzaC1yc2E=-\\x00\\x00\\x00\\x07ssh-rsa]",
"jsonargparse_tests/test_typing.py::test_bytearray[-]",
"jsonargparse_tests/test_typing.py::test_bytearray[iVBORw0KGgo=-\\x89PNG\\r\\n\\x1a\\n]",
"jsonargparse_tests/test_typing.py::test_bytearray[AAAAB3NzaC1yc2E=-\\x00\\x00\\x00\\x07ssh-rsa]",
"jsonargparse_tests/test_typing.py::test_range[range(5)-expected0-=]",
"jsonargparse_tests/test_typing.py::test_range[range(-2)-expected1-=]",
"jsonargparse_tests/test_typing.py::test_range[range(2,",
"jsonargparse_tests/test_typing.py::test_range[range(-6,",
"jsonargparse_tests/test_typing.py::test_range[range(1,",
"jsonargparse_tests/test_typing.py::test_range[range(-1,",
"jsonargparse_tests/test_typing.py::test_range[range(0,",
"jsonargparse_tests/test_typing.py::test_range_deserialize_failure",
"jsonargparse_tests/test_typing.py::test_pickle_module_type[PositiveInt]",
"jsonargparse_tests/test_typing.py::test_pickle_module_type[NonNegativeInt]",
"jsonargparse_tests/test_typing.py::test_pickle_module_type[PositiveFloat]",
"jsonargparse_tests/test_typing.py::test_pickle_module_type[NonNegativeFloat]",
"jsonargparse_tests/test_typing.py::test_pickle_module_type[ClosedUnitInterval]",
"jsonargparse_tests/test_typing.py::test_pickle_module_type[OpenUnitInterval]",
"jsonargparse_tests/test_typing.py::test_pickle_module_type[NotEmptyStr]",
"jsonargparse_tests/test_typing.py::test_pickle_module_type[Email]",
"jsonargparse_tests/test_typing.py::test_pickle_module_type[Path_fr]",
"jsonargparse_tests/test_typing.py::test_pickle_module_type[Path_fc]",
"jsonargparse_tests/test_typing.py::test_pickle_module_type[Path_dw]",
"jsonargparse_tests/test_typing.py::test_pickle_module_type[Path_dc]",
"jsonargparse_tests/test_typing.py::test_pickle_module_type[Path_drw]",
"jsonargparse_tests/test_typing.py::test_module_name_clash",
"jsonargparse_tests/test_typing.py::test_register_non_bool_cast_type",
"jsonargparse_tests/test_typing.py::test_register_type_datetime",
"jsonargparse_tests/test_typing.py::test_register_type_on_first_use",
"jsonargparse_tests/test_typing.py::test_decimal",
"jsonargparse_tests/test_typing.py::test_uuid"
] | [] | 2023-09-13 04:58:47+00:00 | 4,367 |
|
omni-us__jsonargparse-397 | diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index 81acd96..79e1c54 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -12,6 +12,15 @@ The semantic versioning only considers the public API as described in
paths are considered internals and can change in minor and patch releases.
+v4.25.1 (2023-10-??)
+--------------------
+
+Fixed
+^^^^^
+- Failures with subcommands and default_config_files when keys are repeated
+ (`#160 <https://github.com/omni-us/jsonargparse/issues/160>`__).
+
+
v4.25.0 (2023-09-25)
--------------------
diff --git a/jsonargparse/_core.py b/jsonargparse/_core.py
index 778613c..0914993 100644
--- a/jsonargparse/_core.py
+++ b/jsonargparse/_core.py
@@ -616,6 +616,7 @@ class ArgumentParser(ParserDeprecations, ActionsContainer, ArgumentLinking, argp
cfg_path: Union[str, os.PathLike] = "",
ext_vars: Optional[dict] = None,
prev_cfg: Optional[Namespace] = None,
+ key: Optional[str] = None,
) -> Namespace:
"""Loads a configuration string into a namespace.
@@ -633,6 +634,8 @@ class ArgumentParser(ParserDeprecations, ActionsContainer, ArgumentLinking, argp
raise TypeError(f"Problems parsing config: {ex}") from ex
if cfg_dict is None:
return Namespace()
+ if key and isinstance(cfg_dict, dict):
+ cfg_dict = cfg_dict.get(key, {})
if not isinstance(cfg_dict, dict):
raise TypeError(f"Unexpected config: {cfg_str}")
return self._apply_actions(cfg_dict, prev_cfg=prev_cfg)
@@ -954,9 +957,7 @@ class ArgumentParser(ParserDeprecations, ActionsContainer, ArgumentLinking, argp
default_config_files = self._get_default_config_files()
for key, default_config_file in default_config_files:
with change_to_path_dir(default_config_file), parser_context(parent_parser=self):
- cfg_file = self._load_config_parser_mode(default_config_file.get_content())
- if key is not None:
- cfg_file = cfg_file.get(key)
+ cfg_file = self._load_config_parser_mode(default_config_file.get_content(), key=key)
cfg = self.merge_config(cfg_file, cfg)
try:
with _ActionPrintConfig.skip_print_config():
| omni-us/jsonargparse | 863be75d91728f350cb7aa76b1ce139eecf225d7 | diff --git a/jsonargparse_tests/test_subcommands.py b/jsonargparse_tests/test_subcommands.py
index ae46995..a629eb3 100644
--- a/jsonargparse_tests/test_subcommands.py
+++ b/jsonargparse_tests/test_subcommands.py
@@ -212,6 +212,37 @@ def test_subcommand_print_config_default_env(subparser):
assert yaml.safe_load(out) == {"o": 1}
+def test_subcommand_default_config_repeated_keys(parser, subparser, tmp_cwd):
+ defaults = tmp_cwd / "defaults.json"
+ defaults.write_text('{"test":{"test":"value"}}')
+ parser.default_config_files = [defaults]
+ subparser.add_argument("--test")
+ subcommands = parser.add_subcommands()
+ subcommands.add_subcommand("test", subparser)
+
+ cfg = parser.parse_args([], with_meta=False)
+ assert cfg == Namespace(subcommand="test", test=Namespace(test="value"))
+ cfg = parser.parse_args(["test", "--test=x"], with_meta=False)
+ assert cfg == Namespace(subcommand="test", test=Namespace(test="x"))
+
+
+def test_subsubcommand_default_config_repeated_keys(parser, subparser, tmp_cwd):
+ defaults = tmp_cwd / "defaults.json"
+ defaults.write_text('{"test":{"test":{"test":"value"}}}')
+ parser.default_config_files = [defaults]
+ subsubparser = ArgumentParser()
+ subsubparser.add_argument("--test")
+ subcommands1 = parser.add_subcommands()
+ subcommands1.add_subcommand("test", subparser)
+ subcommands2 = subparser.add_subcommands()
+ subcommands2.add_subcommand("test", subsubparser)
+
+ cfg = parser.parse_args([], with_meta=False)
+ assert cfg.as_dict() == {"subcommand": "test", "test": {"subcommand": "test", "test": {"test": "value"}}}
+ cfg = parser.parse_args(["test", "test", "--test=x"], with_meta=False)
+ assert cfg.as_dict() == {"subcommand": "test", "test": {"subcommand": "test", "test": {"test": "x"}}}
+
+
def test_subcommand_required_arg_in_default_config(parser, subparser, tmp_cwd):
Path("config.yaml").write_text("output: test\nprepare:\n media: test\n")
parser.default_config_files = ["config.yaml"]
| Repeated Keys in Nested List
This was my first day trying out this module
I notice that repeated key names may lead to undesirable results. Even if they are separated by level
I have given out some examples I tested out. It really only causes issues for two of them
| 0.0 | [
"jsonargparse_tests/test_subcommands.py::test_subcommand_default_config_repeated_keys",
"jsonargparse_tests/test_subcommands.py::test_subsubcommand_default_config_repeated_keys"
] | [
"jsonargparse_tests/test_subcommands.py::test_add_subparsers_not_implemented",
"jsonargparse_tests/test_subcommands.py::test_add_parser_not_implemented",
"jsonargparse_tests/test_subcommands.py::test_subcommands_get_defaults",
"jsonargparse_tests/test_subcommands.py::test_subcommands_undefined_subcommand",
"jsonargparse_tests/test_subcommands.py::test_subcommands_not_given_when_few_subcommands",
"jsonargparse_tests/test_subcommands.py::test_subcommands_not_given_when_many_subcommands",
"jsonargparse_tests/test_subcommands.py::test_subcommands_missing_required_subargument",
"jsonargparse_tests/test_subcommands.py::test_subcommands_undefined_subargument",
"jsonargparse_tests/test_subcommands.py::test_subcommands_parse_args_basics",
"jsonargparse_tests/test_subcommands.py::test_main_subcommands_help",
"jsonargparse_tests/test_subcommands.py::test_subcommands_parse_args_alias",
"jsonargparse_tests/test_subcommands.py::test_subcommands_parse_args_config",
"jsonargparse_tests/test_subcommands.py::test_subcommands_parse_string_implicit_subcommand",
"jsonargparse_tests/test_subcommands.py::test_subcommands_parse_string_first_implicit_subcommand",
"jsonargparse_tests/test_subcommands.py::test_subcommands_parse_string_explicit_subcommand",
"jsonargparse_tests/test_subcommands.py::test_subcommands_parse_args_config_explicit_subcommand_arg",
"jsonargparse_tests/test_subcommands.py::test_subcommands_parse_args_environment",
"jsonargparse_tests/test_subcommands.py::test_subcommands_parse_env",
"jsonargparse_tests/test_subcommands.py::test_subcommands_help_default_env_true",
"jsonargparse_tests/test_subcommands.py::test_subcommand_required_false",
"jsonargparse_tests/test_subcommands.py::test_subcommand_without_options",
"jsonargparse_tests/test_subcommands.py::test_subcommand_print_config_default_env",
"jsonargparse_tests/test_subcommands.py::test_subcommand_required_arg_in_default_config",
"jsonargparse_tests/test_subcommands.py::test_subsubcommands_parse_args",
"jsonargparse_tests/test_subcommands.py::test_subsubcommands_wrong_add_order",
"jsonargparse_tests/test_subcommands.py::test_subcommands_custom_instantiator"
] | 2023-10-11 05:13:57+00:00 | 4,368 |
|
omni-us__jsonargparse-405 | diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index 2bfec93..6550d69 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -27,6 +27,8 @@ Fixed
- Failures with subcommands and default_config_files when keys are repeated
(`#160 <https://github.com/omni-us/jsonargparse/issues/160>`__).
- Key related errors printing messages within single quotes.
+- Choices not validated when value comes from config file (`#404
+ <https://github.com/omni-us/jsonargparse/issues/404>`__).
Changed
^^^^^^^
diff --git a/jsonargparse/_core.py b/jsonargparse/_core.py
index 1857bc3..d8056df 100644
--- a/jsonargparse/_core.py
+++ b/jsonargparse/_core.py
@@ -1330,11 +1330,12 @@ class ArgumentParser(ParserDeprecations, ActionsContainer, ArgumentLinking, argp
"""
if value is None and lenient_check.get():
return value
- if action.choices is not None and isinstance(action, _ActionSubCommands):
+ is_subcommand = isinstance(action, _ActionSubCommands)
+ if is_subcommand and action.choices:
leaf_key = split_key_leaf(key)[-1]
if leaf_key == action.dest:
return value
- subparser = action._name_parser_map[leaf_key]
+ subparser = action._name_parser_map[leaf_key] # type: ignore
subparser.check_config(value)
elif isinstance(action, _ActionConfigLoad):
if isinstance(value, str):
@@ -1351,6 +1352,8 @@ class ArgumentParser(ParserDeprecations, ActionsContainer, ArgumentLinking, argp
value[k] = action.type(v)
except (TypeError, ValueError) as ex:
raise TypeError(f'Parser key "{key}": {ex}') from ex
+ if not is_subcommand and action.choices and value not in action.choices:
+ raise TypeError(f'Parser key "{key}": {value!r} not among choices {action.choices}')
return value
## Properties ##
| omni-us/jsonargparse | 5fc835701e52e864c497806b92ce217f9eb56ed5 | diff --git a/jsonargparse_tests/test_core.py b/jsonargparse_tests/test_core.py
index 314b386..07cd4ac 100644
--- a/jsonargparse_tests/test_core.py
+++ b/jsonargparse_tests/test_core.py
@@ -139,13 +139,23 @@ def test_parse_args_positional_config(parser):
def test_parse_args_choices(parser):
parser.add_argument("--ch1", choices="ABC")
- parser.add_argument("--ch2", choices=["v1", "v2"])
+ parser.add_argument("--ch2", type=str, choices=["v1", "v2"])
cfg = parser.parse_args(["--ch1", "C", "--ch2", "v1"])
assert cfg.as_dict() == {"ch1": "C", "ch2": "v1"}
pytest.raises(ArgumentError, lambda: parser.parse_args(["--ch1", "D"]))
pytest.raises(ArgumentError, lambda: parser.parse_args(["--ch2", "v0"]))
+def test_parse_args_choices_config(parser):
+ parser.add_argument("--cfg", action=ActionConfigFile)
+ parser.add_argument("--ch1", choices="ABC")
+ parser.add_argument("--ch2", type=str, choices=["v1", "v2"])
+ assert parser.parse_args(["--cfg=ch1: B"]).ch1 == "B"
+ assert parser.parse_args(["--cfg=ch2: v2"]).ch2 == "v2"
+ pytest.raises(ArgumentError, lambda: parser.parse_args(["--cfg=ch1: D"]))
+ pytest.raises(ArgumentError, lambda: parser.parse_args(["--cfg=ch2: v0"]))
+
+
def test_parse_object_simple(parser):
parser.add_argument("--op", type=int)
assert parser.parse_object({"op": 1}) == Namespace(op=1)
| Failure to check choice matches for options when using a configuration yaml or json file.
<!-- If you like this project, please ⭐ star it https://github.com/omni-us/jsonargparse/ -->
## 🐛 Bug report
<!-- A clear and concise description of the bug. -->
Using a config file (yaml or json) skips the choice validation step for any other argument.
### To reproduce
```python
import jsonargparse
import yaml
parser = jsonargparse.ArgumentParser()
parser.add_argument('--arg1', type=str, choices=["choice1", "choice2"])
parser.add_argument("--config", action=jsonargparse.ActionConfigFile)
config = yaml.safe_dump(
{
"arg1": "i_wont_choose_from_choices",
}
)
result = parser.parse_args([f"--config={config}"])
print("Skips choice validation and wrong config is parsed:")
print(parser.dump(result))
print("\n----------The above one parses wrongly. The expected behaviour follows---------------------\n\n")
print("But pass the arg1 as a argument override and it immediately fails. As its supposed to - the tests make sure of this.")
result = parser.parse_args([f"--arg1=i_definitely_wont_choose_from_choices"])
print(parser.dump(result))
```
### Expected behavior
<!-- Describe how the behavior or output of the reproduction snippet should be. -->
The same script above shows the expected behavior as well. But what should happen is parser should throw an error stating that the given argument is not valid as it is not within the set of options given.
### Environment
<!-- Fill in the list below. -->
- jsonargparse version (e.g., 4.8.0): 4.25.0
- Python version (e.g., 3.9): 3.8.18
- How jsonargparse was installed (e.g. `pip install jsonargparse[all]`): as in example
- OS (e.g., Linux): Ubuntu 22.04 LTS
My initial suspicions are that this has to do with how config file arguments are parsed.
This line (calling a function from argparse which further down the line calls the choice validation function in argparse):
https://github.com/omni-us/jsonargparse/blob/5fc835701e52e864c497806b92ce217f9eb56ed5/jsonargparse/_core.py#L259
is on a high level responsible for choice validation. But, in the current code, the config argument parsing doesn't fill out the other fields before the validation work is handed over to argparse. So whatever arguments come from the config file are not at all choice checked. The current code does have choice checking but that is only for subcommands and not for '--arg' (not sure what to call them but the ones with dashes or just arguments). Hence, any choice arguments provided via a config file go under the radar and can potentially wreak havoc down the line.
| 0.0 | [
"jsonargparse_tests/test_core.py::test_parse_args_choices_config"
] | [
"jsonargparse_tests/test_core.py::test_parse_args_simple",
"jsonargparse_tests/test_core.py::test_parse_args_nested",
"jsonargparse_tests/test_core.py::test_parse_args_unrecognized_arguments",
"jsonargparse_tests/test_core.py::test_parse_args_from_sys_argv",
"jsonargparse_tests/test_core.py::test_parse_args_invalid_args",
"jsonargparse_tests/test_core.py::test_parse_args_base_namespace",
"jsonargparse_tests/test_core.py::test_parse_args_unexpected_kwarg",
"jsonargparse_tests/test_core.py::test_parse_args_nargs_plus",
"jsonargparse_tests/test_core.py::test_parse_args_nargs_asterisk",
"jsonargparse_tests/test_core.py::test_parse_args_nargs_questionmark",
"jsonargparse_tests/test_core.py::test_parse_args_nargs_number",
"jsonargparse_tests/test_core.py::test_parse_args_positional_nargs_questionmark",
"jsonargparse_tests/test_core.py::test_parse_args_positional_nargs_plus",
"jsonargparse_tests/test_core.py::test_parse_args_positional_config",
"jsonargparse_tests/test_core.py::test_parse_args_choices",
"jsonargparse_tests/test_core.py::test_parse_object_simple",
"jsonargparse_tests/test_core.py::test_parse_object_nested",
"jsonargparse_tests/test_core.py::test_env_prefix_from_prog_with_dashes",
"jsonargparse_tests/test_core.py::test_parse_env_simple",
"jsonargparse_tests/test_core.py::test_parse_env_nested",
"jsonargparse_tests/test_core.py::test_parse_env_config",
"jsonargparse_tests/test_core.py::test_parse_env_positional_nargs_plus",
"jsonargparse_tests/test_core.py::test_default_env_property",
"jsonargparse_tests/test_core.py::test_default_env_override_true",
"jsonargparse_tests/test_core.py::test_default_env_override_false",
"jsonargparse_tests/test_core.py::test_env_prefix_true",
"jsonargparse_tests/test_core.py::test_env_prefix_false",
"jsonargparse_tests/test_core.py::test_env_properties_set_invalid",
"jsonargparse_tests/test_core.py::test_parse_string_simple",
"jsonargparse_tests/test_core.py::test_parse_string_simple_errors",
"jsonargparse_tests/test_core.py::test_parse_string_nested",
"jsonargparse_tests/test_core.py::test_parse_path_simple",
"jsonargparse_tests/test_core.py::test_parse_path_simple_errors",
"jsonargparse_tests/test_core.py::test_parse_path_defaults",
"jsonargparse_tests/test_core.py::test_precedence_of_sources",
"jsonargparse_tests/test_core.py::test_non_positional_required",
"jsonargparse_tests/test_core.py::test_dump_complete",
"jsonargparse_tests/test_core.py::test_dump_incomplete",
"jsonargparse_tests/test_core.py::test_dump_formats",
"jsonargparse_tests/test_core.py::test_dump_skip_default_simple",
"jsonargparse_tests/test_core.py::test_dump_skip_default_nested",
"jsonargparse_tests/test_core.py::test_dump_order",
"jsonargparse_tests/test_core.py::test_parse_args_url_config",
"jsonargparse_tests/test_core.py::test_save_multifile",
"jsonargparse_tests/test_core.py::test_save_overwrite",
"jsonargparse_tests/test_core.py::test_save_subconfig_overwrite",
"jsonargparse_tests/test_core.py::test_save_invalid_format",
"jsonargparse_tests/test_core.py::test_save_path_content",
"jsonargparse_tests/test_core.py::test_print_config_normal",
"jsonargparse_tests/test_core.py::test_print_config_skip_null",
"jsonargparse_tests/test_core.py::test_print_config_invalid_flag",
"jsonargparse_tests/test_core.py::test_print_config_empty_default_config_file",
"jsonargparse_tests/test_core.py::test_default_config_files",
"jsonargparse_tests/test_core.py::test_default_config_file_help_message_no_existing",
"jsonargparse_tests/test_core.py::test_default_config_file_invalid_value",
"jsonargparse_tests/test_core.py::test_default_config_files_pattern",
"jsonargparse_tests/test_core.py::test_named_argument_groups",
"jsonargparse_tests/test_core.py::test_set_get_defaults_single",
"jsonargparse_tests/test_core.py::test_set_get_defaults_multiple",
"jsonargparse_tests/test_core.py::test_add_multiple_config_arguments_error",
"jsonargparse_tests/test_core.py::test_check_config_skip_none",
"jsonargparse_tests/test_core.py::test_check_config_branch",
"jsonargparse_tests/test_core.py::test_merge_config",
"jsonargparse_tests/test_core.py::test_strip_unknown",
"jsonargparse_tests/test_core.py::test_exit_on_error",
"jsonargparse_tests/test_core.py::test_version_print",
"jsonargparse_tests/test_core.py::test_debug_environment_variable",
"jsonargparse_tests/test_core.py::test_parse_known_args_not_implemented",
"jsonargparse_tests/test_core.py::test_parse_known_args_not_implemented_without_caller_module",
"jsonargparse_tests/test_core.py::test_default_meta_property",
"jsonargparse_tests/test_core.py::test_pickle_parser"
] | 2023-10-18 18:26:17+00:00 | 4,369 |
|
omni-us__jsonargparse-468 | diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index b6bc59b..99d9f6a 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -26,6 +26,8 @@ Fixed
produces an invalid string default.
- dataclass single parameter change incorrectly resetting previous values (`#464
<https://github.com/omni-us/jsonargparse/issues/464>`__).
+- Add function signature failing when conditionally calling different functions
+ (`#467 <https://github.com/omni-us/jsonargparse/issues/467>`__).
v4.27.5 (2024-02-12)
diff --git a/jsonargparse/_signatures.py b/jsonargparse/_signatures.py
index 0f83730..94ca7af 100644
--- a/jsonargparse/_signatures.py
+++ b/jsonargparse/_signatures.py
@@ -3,7 +3,7 @@
import dataclasses
import inspect
import re
-from argparse import SUPPRESS
+from argparse import SUPPRESS, ArgumentParser
from contextlib import suppress
from typing import Any, Callable, List, Optional, Set, Tuple, Type, Union
@@ -255,7 +255,7 @@ class SignatureArguments(LoggerProperty):
## Create group if requested ##
doc_group = get_doc_short_description(function_or_class, method_name, logger=self.logger)
component = getattr(function_or_class, method_name) if method_name else function_or_class
- group = self._create_group_if_requested(
+ container = self._create_group_if_requested(
component,
nested_key,
as_group,
@@ -268,7 +268,7 @@ class SignatureArguments(LoggerProperty):
added_args: List[str] = []
for param in params:
self._add_signature_parameter(
- group,
+ container,
nested_key,
param,
added_args,
@@ -283,7 +283,7 @@ class SignatureArguments(LoggerProperty):
def _add_signature_parameter(
self,
- group,
+ container,
nested_key: Optional[str],
param,
added_args: List[str],
@@ -339,11 +339,14 @@ class SignatureArguments(LoggerProperty):
dest = (nested_key + "." if nested_key else "") + name
args = [dest if is_required and as_positional else "--" + dest]
if param.origin:
+ parser = container
+ if not isinstance(container, ArgumentParser):
+ parser = getattr(container, "parser")
group_name = "; ".join(str(o) for o in param.origin)
- if group_name in group.parser.groups:
- group = group.parser.groups[group_name]
+ if group_name in parser.groups:
+ container = parser.groups[group_name]
else:
- group = group.parser.add_argument_group(
+ container = parser.add_argument_group(
f"Conditional arguments [origins: {group_name}]",
name=group_name,
)
@@ -372,7 +375,7 @@ class SignatureArguments(LoggerProperty):
args=args,
kwargs=kwargs,
enable_path=enable_path,
- container=group,
+ container=container,
logger=self.logger,
sub_add_kwargs=sub_add_kwargs,
)
@@ -387,7 +390,7 @@ class SignatureArguments(LoggerProperty):
if is_dataclass_like_typehint:
kwargs.update(sub_add_kwargs)
with ActionTypeHint.allow_default_instance_context():
- action = group.add_argument(*args, **kwargs)
+ action = container.add_argument(*args, **kwargs)
action.sub_add_kwargs = sub_add_kwargs
if is_subclass_typehint and len(subclass_skip) > 0:
action.sub_add_kwargs["skip"] = subclass_skip
| omni-us/jsonargparse | bca15889489e5f57ad89659da356ecaad4bf09c0 | diff --git a/jsonargparse_tests/test_cli.py b/jsonargparse_tests/test_cli.py
index 2590170..0bb933b 100644
--- a/jsonargparse_tests/test_cli.py
+++ b/jsonargparse_tests/test_cli.py
@@ -14,6 +14,7 @@ import yaml
from jsonargparse import CLI, capture_parser, lazy_instance
from jsonargparse._optionals import docstring_parser_support, ruyaml_support
+from jsonargparse._typehints import Literal
from jsonargparse.typing import final
from jsonargparse_tests.conftest import skip_if_docstring_parser_unavailable
@@ -120,6 +121,31 @@ def test_multiple_functions_subcommand_help():
assert "--a2 A2" in out
+def conditionalA(foo: int = 1):
+ return foo
+
+
+def conditionalB(bar: int = 2):
+ return bar
+
+
+def conditional_function(fn: "Literal['A', 'B']", *args, **kwargs):
+ if fn == "A":
+ return conditionalA(*args, **kwargs)
+ elif fn == "B":
+ return conditionalB(*args, **kwargs)
+ raise NotImplementedError(fn)
+
+
[email protected](condition=sys.version_info < (3, 9), reason="python>=3.9 is required")
[email protected](condition=not Literal, reason="Literal is required")
+def test_literal_conditional_function():
+ out = get_cli_stdout(conditional_function, args=["--help"])
+ assert "Conditional arguments" in out
+ assert "--foo FOO (type: int, default: Conditional<ast-resolver> {1, NOT_ACCEPTED})" in out
+ assert "--bar BAR (type: int, default: Conditional<ast-resolver> {2, NOT_ACCEPTED})" in out
+
+
# single class tests
| Dynamic selection of function given an argument fails with an `AttributeError`
## 🐛 Bug report
I am trying to setup a CLI system where I have a multitude of subcommands (only 1 in the repro code, `finetune`) and some of them take a `--method` argument that allows selecting a different function.
See https://github.com/Lightning-AI/litgpt/issues/996 for the real purpose of this.
### To reproduce
```python
from typing import Literal
def methodA(foo: int = 111):
print(locals())
def methodB(bar: int = 123):
print(locals())
def finetune(method: Literal["A", "B"], *args, **kwargs):
if method == "A":
return methodA(*args, **kwargs)
elif method == "B":
return methodB(*args, **kwargs)
raise NotImplementedError(method)
if __name__ == "__main__":
from jsonargparse import CLI
CLI(finetune)
```
```python
Traceback (most recent call last):
File "/home/carmocca/git/repro.py", line 19, in <module>
CLI(finetune)
File "/home/carmocca/git/nightly-venv/lib/python3.10/site-packages/jsonargparse/_cli.py", line 88, in CLI
_add_component_to_parser(components, parser, as_positional, fail_untyped, config_help)
File "/home/carmocca/git/nightly-venv/lib/python3.10/site-packages/jsonargparse/_cli.py", line 184, in _add_component_to_parser
added_args = parser.add_function_arguments(component, as_group=False, **kwargs)
File "/home/carmocca/git/nightly-venv/lib/python3.10/site-packages/jsonargparse/_signatures.py", line 190, in add_function_arguments
return self._add_signature_arguments(
File "/home/carmocca/git/nightly-venv/lib/python3.10/site-packages/jsonargparse/_signatures.py", line 270, in _add_signature_arguments
self._add_signature_parameter(
File "/home/carmocca/git/nightly-venv/lib/python3.10/site-packages/jsonargparse/_signatures.py", line 343, in _add_signature_parameter
if group_name in group.parser.groups:
AttributeError: 'ArgumentParser' object has no attribute 'parser'
```
### Expected behavior
The ideal behaviour would be that `python repro.py -h` only lists the method argument:
```python
positional arguments:
{A,B} (required, type: Literal['A', 'B'])
```
And then when one does `python repro.py --method B -h` then it also shows:
```python
options:
-h, --help Show this help message and exit.
--config CONFIG Path to a configuration file.
--print_config[=flags]
Print the configuration after applying all other arguments and exit. The optional flags customizes the output and are one or more keywords separated by comma. The supported flags are: comments, skip_default,
skip_null.
--bar BAR (type: int, default: 123)
```
I don't know if the AST is smart enough to parse the `*args, **kwargs` specific to the method selected.
I'm happy to try out a different way to support CLI behaviour like this, if there are better ways to approach this problem.
### Environment
- jsonargparse version (e.g., 4.8.0): 4.27.5
| 0.0 | [
"jsonargparse_tests/test_cli.py::test_literal_conditional_function"
] | [
"jsonargparse_tests/test_cli.py::test_unexpected_components[0]",
"jsonargparse_tests/test_cli.py::test_unexpected_components[components1]",
"jsonargparse_tests/test_cli.py::test_unexpected_components[components2]",
"jsonargparse_tests/test_cli.py::test_conflicting_subcommand_key",
"jsonargparse_tests/test_cli.py::test_single_function_return",
"jsonargparse_tests/test_cli.py::test_single_function_set_defaults",
"jsonargparse_tests/test_cli.py::test_single_function_help",
"jsonargparse_tests/test_cli.py::test_callable_instance",
"jsonargparse_tests/test_cli.py::test_multiple_functions_return",
"jsonargparse_tests/test_cli.py::test_multiple_functions_set_defaults",
"jsonargparse_tests/test_cli.py::test_multiple_functions_main_help",
"jsonargparse_tests/test_cli.py::test_multiple_functions_subcommand_help",
"jsonargparse_tests/test_cli.py::test_single_class_return",
"jsonargparse_tests/test_cli.py::test_single_class_missing_required_init",
"jsonargparse_tests/test_cli.py::test_single_class_invalid_method_parameter",
"jsonargparse_tests/test_cli.py::test_single_class_main_help",
"jsonargparse_tests/test_cli.py::test_single_class_subcommand_help",
"jsonargparse_tests/test_cli.py::test_single_class_print_config_after_subcommand",
"jsonargparse_tests/test_cli.py::test_single_class_print_config_before_subcommand",
"jsonargparse_tests/test_cli.py::test_method_with_config_parameter",
"jsonargparse_tests/test_cli.py::test_function_and_class_return[5-args0]",
"jsonargparse_tests/test_cli.py::test_function_and_class_return[expected1-args1]",
"jsonargparse_tests/test_cli.py::test_function_and_class_return[expected2-args2]",
"jsonargparse_tests/test_cli.py::test_function_and_class_return[4-args3]",
"jsonargparse_tests/test_cli.py::test_function_and_class_return[expected4-args4]",
"jsonargparse_tests/test_cli.py::test_function_and_class_return[expected5-args5]",
"jsonargparse_tests/test_cli.py::test_function_and_class_return[expected6-args6]",
"jsonargparse_tests/test_cli.py::test_function_and_class_return[Cmd2.method3-args7]",
"jsonargparse_tests/test_cli.py::test_function_and_class_return[cmd3-args8]",
"jsonargparse_tests/test_cli.py::test_function_and_class_main_help",
"jsonargparse_tests/test_cli.py::test_function_and_class_subcommand_help",
"jsonargparse_tests/test_cli.py::test_function_and_class_subsubcommand_help",
"jsonargparse_tests/test_cli.py::test_function_and_class_print_config_after_subsubcommand",
"jsonargparse_tests/test_cli.py::test_function_and_class_print_config_in_between_subcommands",
"jsonargparse_tests/test_cli.py::test_function_and_class_print_config_before_subcommands",
"jsonargparse_tests/test_cli.py::test_function_and_class_method_without_parameters",
"jsonargparse_tests/test_cli.py::test_function_and_class_function_without_parameters",
"jsonargparse_tests/test_cli.py::test_automatic_components_empty_context",
"jsonargparse_tests/test_cli.py::test_automatic_components_context_function",
"jsonargparse_tests/test_cli.py::test_automatic_components_context_class",
"jsonargparse_tests/test_cli.py::test_dataclass_without_methods_response",
"jsonargparse_tests/test_cli.py::test_dataclass_without_methods_parser_groups",
"jsonargparse_tests/test_cli.py::test_named_components_shallow",
"jsonargparse_tests/test_cli.py::test_named_components_deep",
"jsonargparse_tests/test_cli.py::test_subclass_type_config_file",
"jsonargparse_tests/test_cli.py::test_final_and_subclass_type_config_file"
] | 2024-03-11 21:48:12+00:00 | 4,370 |
|
omni-us__jsonargparse-471 | diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index 87a789b..b6bc59b 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -24,6 +24,8 @@ Fixed
<https://github.com/omni-us/jsonargparse/issues/465>`__).
- Optional callable that returns a class instance with a lambda default,
produces an invalid string default.
+- dataclass single parameter change incorrectly resetting previous values (`#464
+ <https://github.com/omni-us/jsonargparse/issues/464>`__).
v4.27.5 (2024-02-12)
diff --git a/jsonargparse/_typehints.py b/jsonargparse/_typehints.py
index eb6f050..67ec5eb 100644
--- a/jsonargparse/_typehints.py
+++ b/jsonargparse/_typehints.py
@@ -863,7 +863,8 @@ def adapt_typehints(
elif isinstance(val, (dict, Namespace)):
val = parser.parse_object(val, defaults=sub_defaults.get() or list_item)
elif isinstance(val, NestedArg):
- val = parser.parse_args([f"--{val.key}={val.val}"])
+ prev_val = prev_val if isinstance(prev_val, Namespace) else None
+ val = parser.parse_args([f"--{val.key}={val.val}"], namespace=prev_val)
else:
raise_unexpected_value(f"Type {typehint} expects a dict or Namespace", val)
| omni-us/jsonargparse | 14456c21ff7a11ba420f010d2b21bcfdb14977a2 | diff --git a/jsonargparse_tests/test_dataclass_like.py b/jsonargparse_tests/test_dataclass_like.py
index df8b431..0402eee 100644
--- a/jsonargparse_tests/test_dataclass_like.py
+++ b/jsonargparse_tests/test_dataclass_like.py
@@ -8,6 +8,7 @@ import pytest
import yaml
from jsonargparse import (
+ ActionConfigFile,
ArgumentError,
ArgumentParser,
Namespace,
@@ -359,6 +360,20 @@ def test_optional_dataclass_type_null_value():
assert cfg == parser_optional_data.instantiate_classes(cfg)
[email protected]
+class SingleParamChange:
+ p1: int = 0
+ p2: int = 0
+
+
+def test_optional_dataclass_single_param_change(parser):
+ parser.add_argument("--config", action=ActionConfigFile)
+ parser.add_argument("--data", type=Optional[SingleParamChange])
+ config = {"data": {"p1": 1}}
+ cfg = parser.parse_args([f"--config={config}", "--data.p2=2"])
+ assert cfg.data == Namespace(p1=1, p2=2)
+
+
@dataclasses.dataclass
class ModelConfig:
data: Optional[Dict[str, Any]] = None
| Overriding a config's argument makes everything else fall back to the base class
## 🐛 Bug report
### To reproduce
`repro.py`:
```python
from dataclasses import dataclass
from typing import Optional
@dataclass
class Thing:
foo: int = 1
bar: int = 2
def fn(thing: Optional[Thing] = None):
thing = Thing() if thing is None else thing
print(thing)
from jsonargparse import CLI
CLI(fn)
```
`repro.yaml`:
```yaml
thing:
foo: 123
bar: 321
```
`python repro.py --config repro.yaml --thing.foo 9`
### Expected behavior
The above prints
```python
Thing(foo=9, bar=2)
```
but I expected
```python
Thing(foo=9, bar=321)
```
### Context
A more real world example is that you have a `trainer_config.yaml` and you want to only modify the `--train.max_epochs` value without having everything else fall back to dataclass defaults
### Environment
Version 4.275
| 0.0 | [
"jsonargparse_tests/test_dataclass_like.py::test_optional_dataclass_single_param_change"
] | [
"jsonargparse_tests/test_dataclass_like.py::test_add_dataclass_arguments",
"jsonargparse_tests/test_dataclass_like.py::test_add_dataclass_nested_defaults",
"jsonargparse_tests/test_dataclass_like.py::test_add_class_with_dataclass_attributes",
"jsonargparse_tests/test_dataclass_like.py::test_add_class_dataclass_typehint_in_subclass",
"jsonargparse_tests/test_dataclass_like.py::test_add_class_optional_without_default",
"jsonargparse_tests/test_dataclass_like.py::test_add_argument_dataclass_type",
"jsonargparse_tests/test_dataclass_like.py::test_add_argument_dataclass_type_required_attr",
"jsonargparse_tests/test_dataclass_like.py::test_dataclass_field_init_false",
"jsonargparse_tests/test_dataclass_like.py::test_dataclass_field_default_factory",
"jsonargparse_tests/test_dataclass_like.py::test_dataclass_fail_untyped_false",
"jsonargparse_tests/test_dataclass_like.py::test_compose_dataclasses",
"jsonargparse_tests/test_dataclass_like.py::test_instantiate_dataclass_within_classes",
"jsonargparse_tests/test_dataclass_like.py::test_optional_dataclass_type_all_fields",
"jsonargparse_tests/test_dataclass_like.py::test_optional_dataclass_type_single_field",
"jsonargparse_tests/test_dataclass_like.py::test_optional_dataclass_type_invalid_field",
"jsonargparse_tests/test_dataclass_like.py::test_optional_dataclass_type_instantiate",
"jsonargparse_tests/test_dataclass_like.py::test_optional_dataclass_type_dump",
"jsonargparse_tests/test_dataclass_like.py::test_optional_dataclass_type_missing_required_field",
"jsonargparse_tests/test_dataclass_like.py::test_optional_dataclass_type_null_value",
"jsonargparse_tests/test_dataclass_like.py::test_dataclass_optional_dict_attribute",
"jsonargparse_tests/test_dataclass_like.py::test_dataclass_in_union_type",
"jsonargparse_tests/test_dataclass_like.py::test_dataclass_in_list_type",
"jsonargparse_tests/test_dataclass_like.py::test_generic_dataclass",
"jsonargparse_tests/test_dataclass_like.py::test_nested_generic_dataclass",
"jsonargparse_tests/test_dataclass_like.py::test_add_class_final",
"jsonargparse_tests/test_dataclass_like.py::TestPydantic::test_dataclass",
"jsonargparse_tests/test_dataclass_like.py::TestPydantic::test_basemodel",
"jsonargparse_tests/test_dataclass_like.py::TestPydantic::test_subclass",
"jsonargparse_tests/test_dataclass_like.py::TestPydantic::test_field_default_factory",
"jsonargparse_tests/test_dataclass_like.py::TestPydantic::test_field_description",
"jsonargparse_tests/test_dataclass_like.py::TestPydantic::test_annotated_field",
"jsonargparse_tests/test_dataclass_like.py::TestPydantic::test_pydantic_types[abc-a-none-constr(min_length=2,",
"jsonargparse_tests/test_dataclass_like.py::TestPydantic::test_pydantic_types[2-0-none-conint(ge=1)]",
"jsonargparse_tests/test_dataclass_like.py::TestPydantic::test_pydantic_types[-1.0-1.0-none-confloat(lt=0.0)]",
"jsonargparse_tests/test_dataclass_like.py::TestPydantic::test_pydantic_types[valid_value3-invalid_value3-none-conlist(int,",
"jsonargparse_tests/test_dataclass_like.py::TestPydantic::test_pydantic_types[valid_value4-invalid_value4-none-conlist(int,",
"jsonargparse_tests/test_dataclass_like.py::TestPydantic::test_pydantic_types[valid_value5-x-list-conset(int,",
"jsonargparse_tests/test_dataclass_like.py::TestPydantic::test_pydantic_types[http://abc.es/---str-HttpUrl]",
"jsonargparse_tests/test_dataclass_like.py::TestPydantic::test_pydantic_types[127.0.0.1-0-str-IPvAnyAddress]",
"jsonargparse_tests/test_dataclass_like.py::TestAttrs::test_define",
"jsonargparse_tests/test_dataclass_like.py::TestAttrs::test_subclass",
"jsonargparse_tests/test_dataclass_like.py::TestAttrs::test_field_factory"
] | 2024-03-13 09:00:29+00:00 | 4,371 |
|
omni-us__jsonargparse-56 | diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index 0457565..b668dce 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -17,6 +17,7 @@ Added
^^^^^
- Path support for fsspec file systems using the 's' mode flag.
- set_config_read_mode function that can enable fsspec for config reading.
+- Option for print_config and dump with help as yaml comments.
Deprecated
^^^^^^^^^^
diff --git a/README.rst b/README.rst
index 246b085..f9ddbf6 100644
--- a/README.rst
+++ b/README.rst
@@ -386,10 +386,12 @@ string respectively.
All parsers include a :code:`--print_config` option. This is useful particularly
for command line tools with a large set of options to create an initial config
-file including all default values. By default all entries are included, even the
-ones with :code:`null` values. If this argument is given as
-:code:`--print_config=skip_null`, then the entries with :code:`null` values will
-be excluded.
+file including all default values. If the `ruyaml
+<https://ruyaml.readthedocs.io>`__ package is installed, the config can be
+printed having the help descriptions content as yaml comments by using
+:code:`--print_config=comments`. Another option is
+:code:`--print_config=skip_null` which skips entries whose value is
+:code:`null`.
.. _environment-variables:
diff --git a/jsonargparse/actions.py b/jsonargparse/actions.py
index 3b9fea8..cd64248 100644
--- a/jsonargparse/actions.py
+++ b/jsonargparse/actions.py
@@ -8,7 +8,7 @@ import argparse
from typing import Callable, Tuple, Type, Union
from argparse import Namespace, Action, SUPPRESS, _HelpAction, _SubParsersAction
-from .optionals import get_config_read_mode, FilesCompleterMethod
+from .optionals import FilesCompleterMethod, get_config_read_mode, ruyaml_support
from .typing import path_type
from .util import (
yamlParserError,
@@ -177,15 +177,19 @@ class _ActionPrintConfig(Action):
dest=dest,
default=default,
nargs='?',
- metavar='skip_null',
+ metavar='comments,skip_null',
help='Print configuration and exit.')
def __call__(self, parser, namespace, value, option_string=None):
kwargs = {'subparser': parser, 'key': None, 'skip_none': False, 'skip_check': True}
+ valid_flags = {'': None, 'comments': 'yaml_comments', 'skip_null': 'skip_none'}
if value is not None:
- if value not in {'skip_null', ''}:
- raise ParserError('Invalid option "'+str(value)+'" for '+option_string)
- kwargs['skip_none'] = True
+ flags = value.split(',')
+ invalid_flags = [f for f in flags if f not in valid_flags]
+ if len(invalid_flags) > 0:
+ raise ParserError('Invalid option "'+str(invalid_flags[0])+'" for '+option_string)
+ for flag in [f for f in flags if f != '']:
+ kwargs[valid_flags[flag]] = True
while hasattr(parser, 'parent_parser'):
kwargs['key'] = parser.subcommand if kwargs['key'] is None else parser.subcommand+'.'+kwargs['key']
parser = parser.parent_parser
diff --git a/jsonargparse/core.py b/jsonargparse/core.py
index 7455908..2441425 100644
--- a/jsonargparse/core.py
+++ b/jsonargparse/core.py
@@ -708,6 +708,7 @@ class ArgumentParser(_ActionsContainer, argparse.ArgumentParser, LoggerProperty)
format: str = 'parser_mode',
skip_none: bool = True,
skip_check: bool = False,
+ yaml_comments: bool = False,
) -> str:
"""Generates a yaml or json string for the given configuration object.
@@ -716,6 +717,7 @@ class ArgumentParser(_ActionsContainer, argparse.ArgumentParser, LoggerProperty)
format: The output format: "yaml", "json", "json_indented" or "parser_mode".
skip_none: Whether to exclude entries whose value is None.
skip_check: Whether to skip parser checking.
+ yaml_comments: Whether to add help content as comments.
Returns:
The configuration in yaml or json format.
@@ -756,7 +758,11 @@ class ArgumentParser(_ActionsContainer, argparse.ArgumentParser, LoggerProperty)
if format == 'parser_mode':
format = 'yaml' if self.parser_mode == 'yaml' else 'json_indented'
if format == 'yaml':
- return yaml.safe_dump(cfg, **self.dump_yaml_kwargs) # type: ignore
+ dump = yaml.safe_dump(cfg, **self.dump_yaml_kwargs) # type: ignore
+ if yaml_comments:
+ formatter = self.formatter_class(self.prog)
+ dump = formatter.add_yaml_comments(dump) # type: ignore
+ return dump
elif format == 'json_indented':
return json.dumps(cfg, indent=2, **self.dump_json_kwargs)+'\n' # type: ignore
elif format == 'json':
diff --git a/jsonargparse/formatters.py b/jsonargparse/formatters.py
index 6d50412..2c686a8 100644
--- a/jsonargparse/formatters.py
+++ b/jsonargparse/formatters.py
@@ -1,9 +1,20 @@
"""Formatter classes."""
+import re
from argparse import _HelpAction, HelpFormatter, OPTIONAL, SUPPRESS, ZERO_OR_MORE
from enum import Enum
-
-from .actions import ActionConfigFile, ActionYesNo, _ActionLink
+from io import StringIO
+
+from .actions import (
+ ActionConfigFile,
+ ActionYesNo,
+ _ActionConfigLoad,
+ _ActionLink,
+ _ActionSubCommands,
+ _find_action,
+ filter_default_actions,
+)
+from .optionals import import_ruyaml
from .typehints import ActionTypeHint, type_to_str
from .util import _get_env_var, _get_key_value
@@ -94,3 +105,108 @@ class DefaultHelpFormatter(HelpFormatter):
def add_usage(self, usage, actions, groups, prefix=None):
actions = [a for a in actions if not isinstance(a, _ActionLink)]
super().add_usage(usage, actions, groups, prefix=prefix)
+
+
+ def add_yaml_comments(self, cfg: str) -> str:
+ """Adds help text as yaml comments."""
+ ruyaml = import_ruyaml('add_yaml_comments')
+ yaml = ruyaml.YAML()
+ cfg = yaml.load(cfg)
+
+ def get_subparsers(parser, prefix=''):
+ subparsers = {}
+ if parser._subparsers is not None:
+ for key, subparser in parser._subparsers._group_actions[0].choices.items():
+ full_key = (prefix+'.' if prefix else '')+key
+ subparsers[full_key] = subparser
+ subparsers.update(get_subparsers(subparser, prefix=full_key))
+ return subparsers
+
+ parsers = get_subparsers(self._parser) # type: ignore
+ parsers[None] = self._parser # type: ignore
+
+ group_titles = {}
+ for prefix, parser in parsers.items():
+ for group in parser._action_groups:
+ actions = filter_default_actions(group._group_actions)
+ actions = [a for a in actions if not isinstance(a, (_ActionConfigLoad, ActionConfigFile, _ActionSubCommands))]
+ keys = set(re.sub(r'\.?[^.]+$', '', a.dest) for a in actions)
+ if len(keys) == 1:
+ key = keys.pop()
+ full_key = (prefix+('.' if key else '') if prefix else '')+key
+ group_titles[full_key] = group.title
+
+ def set_comments(cfg, prefix='', depth=0):
+ for key in cfg.keys():
+ full_key = (prefix+'.' if prefix else '')+key
+ action = _find_action(self._parser, full_key, within_subcommands=True)
+ if isinstance(action, tuple):
+ action = action[0]
+ text = None
+ if full_key in group_titles and isinstance(cfg[key], dict):
+ text = group_titles[full_key]
+ elif action is not None and action.help not in {None, SUPPRESS}:
+ text = self._expand_help(action)
+ if isinstance(cfg[key], dict):
+ if text:
+ self.set_yaml_group_comment(text, cfg, key, depth)
+ set_comments(cfg[key], full_key, depth+1)
+ elif text:
+ self.set_yaml_argument_comment(text, cfg, key, depth)
+
+ if self._parser.description is not None: # type: ignore
+ self.set_yaml_start_comment(self._parser.description, cfg) # type: ignore
+ set_comments(cfg)
+ out = StringIO()
+ yaml.dump(cfg, out)
+ return out.getvalue()
+
+
+ def set_yaml_start_comment(
+ self,
+ text: str,
+ cfg: 'ruyaml.comments.CommentedMap', # type: ignore
+ ):
+ """Sets the start comment to a ruyaml object.
+
+ Args:
+ text: The content to use for the comment.
+ cfg: The ruyaml object.
+ """
+ cfg.yaml_set_start_comment(text)
+
+
+ def set_yaml_group_comment(
+ self,
+ text: str,
+ cfg: 'ruyaml.comments.CommentedMap', # type: ignore
+ key: str,
+ depth: int,
+ ):
+ """Sets the comment for a group to a ruyaml object.
+
+ Args:
+ text: The content to use for the comment.
+ cfg: The parent ruyaml object.
+ key: The key of the group.
+ depth: The nested level of the group.
+ """
+ cfg.yaml_set_comment_before_after_key(key, before='\n'+text, indent=2*depth)
+
+
+ def set_yaml_argument_comment(
+ self,
+ text: str,
+ cfg: 'ruyaml.comments.CommentedMap', # type: ignore
+ key: str,
+ depth: int,
+ ):
+ """Sets the comment for an argument to a ruyaml object.
+
+ Args:
+ text: The content to use for the comment.
+ cfg: The parent ruyaml object.
+ key: The key of the argument.
+ depth: The nested level of the argument.
+ """
+ cfg.yaml_set_comment_before_after_key(key, before='\n'+text, indent=2*depth)
diff --git a/jsonargparse/optionals.py b/jsonargparse/optionals.py
index 2859428..2088b15 100644
--- a/jsonargparse/optionals.py
+++ b/jsonargparse/optionals.py
@@ -21,6 +21,7 @@ _docstring_parser = find_spec('docstring_parser')
_argcomplete = find_spec('argcomplete')
_dataclasses = find_spec('dataclasses')
_fsspec = find_spec('fsspec')
+_ruyaml = find_spec('ruyaml')
jsonschema_support = False if _jsonschema is None else True
jsonnet_support = False if _jsonnet is None else True
@@ -29,6 +30,7 @@ docstring_parser_support = False if _docstring_parser is None else True
argcomplete_support = False if _argcomplete is None else True
dataclasses_support = False if _dataclasses is None else True
fsspec_support = False if _fsspec is None else True
+ruyaml_support = False if _ruyaml is None else True
_config_read_mode = 'fr'
@@ -116,6 +118,14 @@ def import_fsspec(importer):
raise ImportError('fsspec package is required by '+importer+' :: '+str(ex)) from ex
+def import_ruyaml(importer):
+ try:
+ import ruyaml
+ return ruyaml
+ except (ImportError, ModuleNotFound) as ex:
+ raise ImportError('ruyaml package is required by '+importer+' :: '+str(ex)) from ex
+
+
def set_config_read_mode(
urls_enabled: bool = False,
fsspec_enabled: bool = False,
diff --git a/setup.cfg b/setup.cfg
index 664f4d2..85c3251 100644
--- a/setup.cfg
+++ b/setup.cfg
@@ -14,6 +14,7 @@ all =
%(urls)s
%(fsspec)s
%(argcomplete)s
+ %(ruyaml)s
%(reconplogger)s
signatures =
docstring-parser>=0.7.3
@@ -28,6 +29,8 @@ fsspec =
fsspec>=0.8.4; python_version >= '3.6'
argcomplete =
argcomplete>=1.12.1
+ruyaml =
+ ruyaml>=0.20.0; python_version >= '3.6'
reconplogger =
reconplogger>=4.4.0
test =
@@ -115,6 +118,7 @@ extras =
urls
fsspec
argcomplete
+ ruyaml
changedir = jsonargparse_tests
commands = discover --pattern='*_tests.py'
deps = discover
| omni-us/jsonargparse | d0577d200ba3e37f04a9815d4a9736016d5e0016 | diff --git a/jsonargparse_tests/base.py b/jsonargparse_tests/base.py
index 5d21785..d763f12 100644
--- a/jsonargparse_tests/base.py
+++ b/jsonargparse_tests/base.py
@@ -14,6 +14,7 @@ from jsonargparse.optionals import (
dataclasses_support, import_dataclasses,
fsspec_support, import_fsspec,
get_config_read_mode,
+ ruyaml_support,
ModuleNotFound,
)
diff --git a/jsonargparse_tests/cli_tests.py b/jsonargparse_tests/cli_tests.py
index 5f048da..deed36e 100755
--- a/jsonargparse_tests/cli_tests.py
+++ b/jsonargparse_tests/cli_tests.py
@@ -150,6 +150,13 @@ class CLITests(unittest.TestCase):
CLI(components, args=['--print_config=', 'Cmd2', 'method2'])
self.assertEqual('Cmd2:\n i1: d\n method2:\n m2: 0\n', out.getvalue())
+ if docstring_parser_support and ruyaml_support:
+ out = StringIO()
+ with redirect_stdout(out), self.assertRaises(SystemExit):
+ CLI(components, args=['--print_config=comments', 'Cmd2', 'method2'])
+ self.assertIn('# Description of Cmd2', out.getvalue())
+ self.assertIn('# Description of method2', out.getvalue())
+
def test_empty_context(self):
def empty_context():
diff --git a/jsonargparse_tests/core_tests.py b/jsonargparse_tests/core_tests.py
index abd1104..9811d84 100755
--- a/jsonargparse_tests/core_tests.py
+++ b/jsonargparse_tests/core_tests.py
@@ -691,7 +691,7 @@ class OutputTests(TempDirTestCase):
def test_print_config(self):
- parser = ArgumentParser(error_handler=None)
+ parser = ArgumentParser(error_handler=None, description='cli tool')
parser.add_argument('--v0', help=SUPPRESS, default='0')
parser.add_argument('--v1', help='Option v1.', default=1)
parser.add_argument('--g1.v2', help='Option v2.', default='2')
@@ -709,12 +709,19 @@ class OutputTests(TempDirTestCase):
out = StringIO()
with redirect_stdout(out), self.assertRaises(SystemExit):
parser.parse_args(['--print_config=skip_null'])
-
outval = yaml.safe_load(out.getvalue())
self.assertEqual(outval, {'g1': {'v2': '2'}, 'v1': 1})
self.assertRaises(ParserError, lambda: parser.parse_args(['--print_config=bad']))
+ if docstring_parser_support and ruyaml_support:
+ out = StringIO()
+ with redirect_stdout(out), self.assertRaises(SystemExit):
+ parser.parse_args(['--print_config=comments'])
+ self.assertIn('# cli tool', out.getvalue())
+ self.assertIn('# Option v1. (default: 1)', out.getvalue())
+ self.assertIn('# Option v2. (default: 2)', out.getvalue())
+
class ConfigFilesTests(TempDirTestCase):
| [Feature request] Add arguments description as comments in print_config output
Hello and thank you for the great library !
### Feature request
The `--print_config` feature is useful but limited: this would be great if there was a way to print a config file in YAML format containing comments to describe the arguments. I'm aware that this kind of feature depends on the format used for the dump, because JSON does not support comments.
Suggestions are:
- add an optional argument to the `ArgumentParser.dump` method to allow printing comments (only for YAML files). This will need a modification of the way the YAML is dumped
- or add list of actions and groups to public API to allow custom implementation of this feature (as is, if I'm correct, there is no way to access Action objects except `parser._actions` which is not public)
### Example script
```python
import jsonargparse
parser = jsonargparse.ArgumentParser(parse_as_dict=True, description="Test print-config")
parser.add_argument("--argument1", default=1, help="Description argument 1")
parser.add_argument("--argument2", default='VAL2', help="Description argument 2")
group = parser.add_argument_group(title='Group title')
group.add_argument("--level.argument3", default=3, help="Description argument 3")
group.add_argument("--level.argument4", default=4, required=True, help="Description argument 4")
parser.parse_args()
```
### Current behaviour
Using the --print_config option produce this output:
```
argument1: 1
argument2: VAL2
level:
argument3: 3
argument4: 4
```
### Wanted behaviour
This would be great if I could produce this kind of output (using `--print-config` or `ArgumentParser.dump` method):
```
# optional arguments:
# ----------------------
# Description argument 1 (default: 1)
argument1: 1
# Description argument 2 (default: VAL2)
argument2: VAL2
# Group title
# ------------
level:
# Description argument 3 (default: 3)
argument3: 3
# Description argument 4 (required, default: 4)
argument4: 4
```
The file here should still be a valid YAML file. Comments used here could be the same as for the `--help` method (with types, default values, ...).
| 0.0 | [
"jsonargparse_tests/cli_tests.py::CLITests::test_empty_context",
"jsonargparse_tests/cli_tests.py::CLITests::test_function_and_class_cli",
"jsonargparse_tests/cli_tests.py::CLITests::test_multiple_functions_cli",
"jsonargparse_tests/cli_tests.py::CLITests::test_non_empty_context",
"jsonargparse_tests/cli_tests.py::CLITests::test_single_class_cli",
"jsonargparse_tests/cli_tests.py::CLITests::test_single_function_cli",
"jsonargparse_tests/core_tests.py::ParsersTests::test_cfg_base",
"jsonargparse_tests/core_tests.py::ParsersTests::test_default_env",
"jsonargparse_tests/core_tests.py::ParsersTests::test_parse_args",
"jsonargparse_tests/core_tests.py::ParsersTests::test_parse_as_dict",
"jsonargparse_tests/core_tests.py::ParsersTests::test_parse_env",
"jsonargparse_tests/core_tests.py::ParsersTests::test_parse_object",
"jsonargparse_tests/core_tests.py::ParsersTests::test_parse_path",
"jsonargparse_tests/core_tests.py::ParsersTests::test_parse_string",
"jsonargparse_tests/core_tests.py::ParsersTests::test_precedence_of_sources",
"jsonargparse_tests/core_tests.py::ArgumentFeaturesTests::test_choices",
"jsonargparse_tests/core_tests.py::ArgumentFeaturesTests::test_nargs",
"jsonargparse_tests/core_tests.py::ArgumentFeaturesTests::test_positionals",
"jsonargparse_tests/core_tests.py::ArgumentFeaturesTests::test_required",
"jsonargparse_tests/core_tests.py::AdvancedFeaturesTests::test_link_arguments",
"jsonargparse_tests/core_tests.py::AdvancedFeaturesTests::test_subcommands",
"jsonargparse_tests/core_tests.py::AdvancedFeaturesTests::test_subsubcommands",
"jsonargparse_tests/core_tests.py::AdvancedFeaturesTests::test_subsubcommands_bad_order",
"jsonargparse_tests/core_tests.py::OutputTests::test_dump",
"jsonargparse_tests/core_tests.py::OutputTests::test_dump_formats",
"jsonargparse_tests/core_tests.py::OutputTests::test_dump_order",
"jsonargparse_tests/core_tests.py::OutputTests::test_dump_path_type",
"jsonargparse_tests/core_tests.py::OutputTests::test_dump_restricted_float_type",
"jsonargparse_tests/core_tests.py::OutputTests::test_dump_restricted_int_type",
"jsonargparse_tests/core_tests.py::OutputTests::test_dump_restricted_string_type",
"jsonargparse_tests/core_tests.py::OutputTests::test_print_config",
"jsonargparse_tests/core_tests.py::OutputTests::test_save",
"jsonargparse_tests/core_tests.py::OutputTests::test_save_failures",
"jsonargparse_tests/core_tests.py::OutputTests::test_save_path_content",
"jsonargparse_tests/core_tests.py::ConfigFilesTests::test_ActionConfigFile",
"jsonargparse_tests/core_tests.py::ConfigFilesTests::test_ActionConfigFile_failures",
"jsonargparse_tests/core_tests.py::ConfigFilesTests::test_default_config_files",
"jsonargparse_tests/core_tests.py::OtherTests::test_check_config_branch",
"jsonargparse_tests/core_tests.py::OtherTests::test_error_handler_property",
"jsonargparse_tests/core_tests.py::OtherTests::test_invalid_parser_mode",
"jsonargparse_tests/core_tests.py::OtherTests::test_merge_config",
"jsonargparse_tests/core_tests.py::OtherTests::test_meta_key_failures",
"jsonargparse_tests/core_tests.py::OtherTests::test_named_groups",
"jsonargparse_tests/core_tests.py::OtherTests::test_parse_known_args",
"jsonargparse_tests/core_tests.py::OtherTests::test_set_get_defaults",
"jsonargparse_tests/core_tests.py::OtherTests::test_strip_unknown",
"jsonargparse_tests/core_tests.py::OtherTests::test_usage_and_exit_error_handler",
"jsonargparse_tests/core_tests.py::OtherTests::test_version_print"
] | [] | 2021-05-12 06:12:29+00:00 | 4,372 |
|
omni-us__jsonargparse-77 | diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index 5fae308..e58e0d9 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -17,6 +17,10 @@ Added
- Support for parsing ``Mapping`` and ``MutableMapping`` types.
- Support for parsing ``frozenset``, ``MutableSequence`` and ``MutableSet`` types.
+Changed
+^^^^^^^
+- Docstrings no longer supported for python 3.5.
+
v3.17.0 (2021-07-19)
--------------------
diff --git a/jsonargparse/typehints.py b/jsonargparse/typehints.py
index 8c2cf40..6008cb1 100644
--- a/jsonargparse/typehints.py
+++ b/jsonargparse/typehints.py
@@ -346,11 +346,11 @@ def adapt_typehints(val, typehint, serialize=False, instantiate_classes=False, s
elif typehint in {Type, type} or typehint_origin in {Type, type}:
if serialize:
val = object_path_serializer(val)
- elif not serialize and not isinstance(val, Type):
+ elif not serialize and not isinstance(val, type):
path = val
val = import_object(val)
- if (typehint in {Type, type} and not isinstance(val, (Type, type))) or \
- (typehint != Type and typehint_origin in {Type, type} and not _issubclass(val, subtypehints[0])):
+ if (typehint in {Type, type} and not isinstance(val, type)) or \
+ (typehint not in {Type, type} and not _issubclass(val, subtypehints[0])):
raise ValueError('Value "'+str(path)+'" is not a '+str(typehint)+'.')
# Union
diff --git a/setup.cfg b/setup.cfg
index d6aa6ce..4559f9b 100644
--- a/setup.cfg
+++ b/setup.cfg
@@ -18,7 +18,7 @@ all =
%(typing_extensions)s
%(reconplogger)s
signatures =
- docstring-parser>=0.7.3
+ docstring-parser>=0.7.3; python_version >= '3.6'
jsonschema =
jsonschema>=3.2.0
jsonnet =
| omni-us/jsonargparse | 989fea756cbeb8a9e30150d56b64520cc1bad0b9 | diff --git a/jsonargparse_tests/typehints_tests.py b/jsonargparse_tests/typehints_tests.py
index 4135798..4bd0b10 100755
--- a/jsonargparse_tests/typehints_tests.py
+++ b/jsonargparse_tests/typehints_tests.py
@@ -209,20 +209,39 @@ class TypeHintsTests(unittest.TestCase):
self.assertRaises(ParserError, lambda: parser.parse_args(['--false=true']))
- def test_type_Type(self):
+ def _test_typehint_non_parameterized_types(self, type):
parser = ArgumentParser(error_handler=None)
- ActionTypeHint.is_supported_typehint(Type, full=True)
- parser.add_argument('--type', type=Type)
- parser.add_argument('--cal', type=Type[Calendar])
+ ActionTypeHint.is_supported_typehint(type, full=True)
+ parser.add_argument('--type', type=type)
cfg = parser.parse_args(['--type=uuid.UUID'])
self.assertEqual(cfg.type, uuid.UUID)
self.assertEqual(parser.dump(cfg), 'type: uuid.UUID\n')
+
+
+ def _test_typehint_parameterized_types(self, type):
+ parser = ArgumentParser(error_handler=None)
+ ActionTypeHint.is_supported_typehint(type, full=True)
+ parser.add_argument('--cal', type=type[Calendar])
cfg = parser.parse_args(['--cal=calendar.Calendar'])
self.assertEqual(cfg.cal, Calendar)
self.assertEqual(parser.dump(cfg), 'cal: calendar.Calendar\n')
self.assertRaises(ParserError, lambda: parser.parse_args(['--cal=uuid.UUID']))
+ def test_typehint_Type(self):
+ self._test_typehint_non_parameterized_types(type=Type)
+ self._test_typehint_parameterized_types(type=Type)
+
+
+ def test_typehint_non_parameterized_type(self):
+ self._test_typehint_non_parameterized_types(type=type)
+
+
+ @unittest.skipIf(sys.version_info[:2] < (3, 9), '[] support for builtins introduced in python 3.9')
+ def test_typehint_parametrized_type(self):
+ self._test_typehint_parameterized_types(type=type)
+
+
def test_uuid(self):
id1 = uuid.uuid4()
id2 = uuid.uuid4()
| 'builtins.type' type hint is not parsed properly
### Setup to reproduce the issue:
Within module _**my_module**_:
_**a.py**_:
```
class A:
def __init__(self, a: int = 10):
self.a = a
```
_**b.py**_:
```
from jsonargparse import ArgumentParser
from my_module.a import A
class B:
def __init__(self, cls: type = A):
self.o = cls(10)
if __name__ == '__main__':
parser = ArgumentParser()
parser.add_class_arguments(B, 'B')
config = parser.parse_args()
init = parser.instantiate_classes(config)
```
Run command:
`python b.py --B.cls my_module.a.A`
### Current behavior:
Exits with:
```
usage: b.py [-h] [--B.cls CLS]
b.py: error: Parser key "B.cls": 'NoneType' object is not subscriptable
```
### Expected behavior
When using `typing.Type` type hint it works as expected and no errors are thrown. With `builtins.type` (as in example above) it works only when parametrized (`type[A]`). I think behavior with `builtins.type` and `typing.Type` should be consistent and example code should not crash.
Probably the issue goes deeper than this example and is caused by changes introduced in Python 3.9 [(Generic Alias Type)](https://docs.python.org/3/library/stdtypes.html#types-genericalias), but I have not experienced any problems with other types (e.g. `list`, `dict`, etc.) | 0.0 | [
"jsonargparse_tests/typehints_tests.py::TypeHintsTests::test_typehint_non_parameterized_type"
] | [
"jsonargparse_tests/typehints_tests.py::TypeHintsTests::test_Callable",
"jsonargparse_tests/typehints_tests.py::TypeHintsTests::test_Literal",
"jsonargparse_tests/typehints_tests.py::TypeHintsTests::test_add_argument_type_hint",
"jsonargparse_tests/typehints_tests.py::TypeHintsTests::test_bool",
"jsonargparse_tests/typehints_tests.py::TypeHintsTests::test_class_type",
"jsonargparse_tests/typehints_tests.py::TypeHintsTests::test_complex_number",
"jsonargparse_tests/typehints_tests.py::TypeHintsTests::test_dict",
"jsonargparse_tests/typehints_tests.py::TypeHintsTests::test_dict_union",
"jsonargparse_tests/typehints_tests.py::TypeHintsTests::test_list",
"jsonargparse_tests/typehints_tests.py::TypeHintsTests::test_list_enum",
"jsonargparse_tests/typehints_tests.py::TypeHintsTests::test_list_tuple",
"jsonargparse_tests/typehints_tests.py::TypeHintsTests::test_list_union",
"jsonargparse_tests/typehints_tests.py::TypeHintsTests::test_nargs_questionmark",
"jsonargparse_tests/typehints_tests.py::TypeHintsTests::test_nested_tuples",
"jsonargparse_tests/typehints_tests.py::TypeHintsTests::test_no_str_strip",
"jsonargparse_tests/typehints_tests.py::TypeHintsTests::test_register_type",
"jsonargparse_tests/typehints_tests.py::TypeHintsTests::test_tuple",
"jsonargparse_tests/typehints_tests.py::TypeHintsTests::test_tuple_ellipsis",
"jsonargparse_tests/typehints_tests.py::TypeHintsTests::test_type_Any",
"jsonargparse_tests/typehints_tests.py::TypeHintsTests::test_type_hint_action_failure",
"jsonargparse_tests/typehints_tests.py::TypeHintsTests::test_typehint_Type",
"jsonargparse_tests/typehints_tests.py::TypeHintsTests::test_typehint_parametrized_type",
"jsonargparse_tests/typehints_tests.py::TypeHintsTests::test_typehint_serialize_enum",
"jsonargparse_tests/typehints_tests.py::TypeHintsTests::test_typehint_serialize_list",
"jsonargparse_tests/typehints_tests.py::TypeHintsTests::test_unsupported_type",
"jsonargparse_tests/typehints_tests.py::TypeHintsTests::test_uuid",
"jsonargparse_tests/typehints_tests.py::TypeHintsTmpdirTests::test_class_type_with_default_config_files",
"jsonargparse_tests/typehints_tests.py::TypeHintsTmpdirTests::test_enable_path",
"jsonargparse_tests/typehints_tests.py::TypeHintsTmpdirTests::test_list_path",
"jsonargparse_tests/typehints_tests.py::TypeHintsTmpdirTests::test_optional_path",
"jsonargparse_tests/typehints_tests.py::TypeHintsTmpdirTests::test_path",
"jsonargparse_tests/typehints_tests.py::OtherTests::test_is_optional"
] | 2021-08-06 21:11:08+00:00 | 4,373 |
|
omni-us__jsonargparse-78 | diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index 5cfda88..3230abe 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -23,6 +23,7 @@ Fixed
- Don't ignore ``KeyError`` in call to instantiate_classes #81.
- Optional subcommands fail with a KeyError #68.
- Conflicting namespace for subclass key in subcommand.
+- ``instantiate_classes`` not working for subcommand keys #70.
Changed
^^^^^^^
diff --git a/jsonargparse/actions.py b/jsonargparse/actions.py
index ac3b78a..6cedc61 100644
--- a/jsonargparse/actions.py
+++ b/jsonargparse/actions.py
@@ -733,14 +733,10 @@ class _ActionSubCommands(_SubParsersAction):
@staticmethod
- def handle_subcommands(parser, cfg, env, defaults, prefix='', fail_no_subcommand=True):
- """Adds sub-command dest if missing and parses defaults and environment variables."""
+ def get_subcommand(parser, cfg_dict:dict, prefix:str='', fail_no_subcommand:bool=True):
+ """Returns the sub-command name and corresponding subparser."""
if parser._subparsers is None:
- return
-
- cfg_dict = cfg.__dict__ if isinstance(cfg, Namespace) else cfg
- cfg_keys = set(vars(_dict_to_flat_namespace(cfg)).keys())
- cfg_keys = cfg_keys.union(set(cfg_dict.keys()))
+ return None, None
# Get subcommands action
for action in parser._actions:
@@ -760,11 +756,27 @@ class _ActionSubCommands(_SubParsersAction):
cfg_dict[dest] = subcommand
if subcommand is None and not (fail_no_subcommand and action._required):
- return
+ return None, None
if action._required and subcommand not in action._name_parser_map:
raise KeyError('Sub-command "'+dest+'" is required but not given or its value is None.')
- subparser = action._name_parser_map[subcommand]
+ subparser = action._name_parser_map.get(subcommand)
+
+ return subcommand, subparser
+
+
+ @staticmethod
+ def handle_subcommands(parser, cfg, env, defaults, prefix='', fail_no_subcommand=True):
+ """Adds sub-command dest if missing and parses defaults and environment variables."""
+
+ cfg_dict = cfg.__dict__ if isinstance(cfg, Namespace) else cfg
+
+ subcommand, subparser = _ActionSubCommands.get_subcommand(parser, cfg_dict, prefix=prefix, fail_no_subcommand=fail_no_subcommand)
+ if subcommand is None:
+ return
+
+ cfg_keys = set(vars(_dict_to_flat_namespace(cfg)).keys())
+ cfg_keys = cfg_keys.union(set(cfg_dict.keys()))
# merge environment variable values and default values
subnamespace = None
diff --git a/jsonargparse/core.py b/jsonargparse/core.py
index 89d3790..b78ca77 100644
--- a/jsonargparse/core.py
+++ b/jsonargparse/core.py
@@ -1117,6 +1117,11 @@ class ArgumentParser(_ActionsContainer, argparse.ArgumentParser, LoggerProperty)
component.instantiate_class(component, cfg)
_ActionLink.apply_instantiation_links(self, cfg, component.dest)
+ cfg_dict = cfg.__dict__ if isinstance(cfg, Namespace) else cfg
+ subcommand, subparser = _ActionSubCommands.get_subcommand(self, cfg_dict, fail_no_subcommand=False)
+ if subcommand:
+ cfg[subcommand] = subparser.instantiate_classes(cfg[subcommand], instantiate_groups=instantiate_groups)
+
return cfg
| omni-us/jsonargparse | bdc7635685220fa7b108c06626ae1902bad84fc2 | diff --git a/jsonargparse_tests/signatures_tests.py b/jsonargparse_tests/signatures_tests.py
index e0506e9..966b7da 100755
--- a/jsonargparse_tests/signatures_tests.py
+++ b/jsonargparse_tests/signatures_tests.py
@@ -644,6 +644,24 @@ class SignaturesTests(unittest.TestCase):
self.assertIsInstance(cfg['e'], EmptyInitClass)
+ def test_instantiate_classes_subcommand(self):
+ class Foo:
+ def __init__(self, a: int = 1):
+ self.a = a
+
+ parser = ArgumentParser(parse_as_dict=True)
+ subcommands = parser.add_subcommands()
+ subparser = ArgumentParser()
+ key = "foo"
+ subparser.add_class_arguments(Foo, key)
+ subcommand = "cmd"
+ subcommands.add_subcommand(subcommand, subparser)
+
+ config = parser.parse_args([subcommand])
+ config_init = parser.instantiate_classes(config)
+ self.assertIsInstance(config_init[subcommand][key], Foo)
+
+
def test_implicit_optional(self):
def func(a1: int = None):
| Support for subcommands and `instantiate_classes`
I'm trying to use subcommands and `instantiate_classes` together.
Without subcommand, everything works properly:
```python
from jsonargparse import ArgumentParser
class Foo:
def __init__(self, a: int = 1):
...
parser = ArgumentParser(parse_as_dict=True)
key = "foo"
parser.add_class_arguments(Foo, key)
config = parser.parse_args()
print(config)
config_init = parser.instantiate_classes(config)
# the class should be instantiated
print(config_init)
assert isinstance(config_init[key], Foo)
```
```python
{'foo': {'a': 1}}
{'foo': <__main__.Foo object at 0x102fc90d0>}
```
However, with subcommand enabled, seems like `instantiate_classes` does not act recursively.
```python
from jsonargparse import ArgumentParser
class Foo:
def __init__(self, a: int = 1):
...
parser = ArgumentParser(parse_as_dict=True)
subcommands = parser.add_subcommands()
subparser = ArgumentParser()
key = "foo"
subparser.add_class_arguments(Foo, key)
subcommand = "cmd"
subcommands.add_subcommand(subcommand, subparser)
config = parser.parse_args([subcommand])
print(config)
# the class should be instantiated even if it is under a subcommand
config_init = parser.instantiate_classes(config)
print(config_init)
assert isinstance(config_init[subcommand][key], Foo)
```
```python
{'subcommand': 'cmd', 'cmd': {'foo': {'a': 1}}}
{'subcommand': 'cmd', 'cmd': {'foo': {'a': 1}}}
Traceback (most recent call last):
File "script.py", line 33, in <module>
assert isinstance(config_init[subcommand][key], Foo)
AssertionError
```
I would expect the second print to be
```python
{'subcommand': 'cmd', 'cmd': {'foo': <__main__.Foo object at 0x102fc90d0>}}
```
Not sure if this is a bug or a feature. Is this not a valid way to instantiate classes under subcommands?
If I try to do instead
```python
config_init = parser.instantiate_classes(config["subcommand"])
print(config_init)
```
I get:
```python
Traceback (most recent call last):
File "/Users/carlosmocholi/Library/Application Support/JetBrains/PyCharmCE2020.3/scratches/scratch_12.py", line 32, in <module>
config_init = parser.instantiate_classes(config["subcommand"])
File "/Users/carlosmocholi/.pyenv/versions/3.9.1/envs/lightning-3.9/lib/python3.9/site-packages/jsonargparse/core.py", line 1103, in instantiate_classes
cfg = strip_meta(cfg)
File "/Users/carlosmocholi/.pyenv/versions/3.9.1/envs/lightning-3.9/lib/python3.9/site-packages/jsonargparse/util.py", line 247, in strip_meta
cfg = namespace_to_dict(cfg)
File "/Users/carlosmocholi/.pyenv/versions/3.9.1/envs/lightning-3.9/lib/python3.9/site-packages/jsonargparse/util.py", line 233, in namespace_to_dict
return expand_namespace(cfg_ns)
File "/Users/carlosmocholi/.pyenv/versions/3.9.1/envs/lightning-3.9/lib/python3.9/site-packages/jsonargparse/util.py", line 224, in expand_namespace
cfg = dict(vars(cfg))
TypeError: vars() argument must have __dict__ attribute
``` | 0.0 | [
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_instantiate_classes_subcommand"
] | [
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_add_class_arguments",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_add_class_from_function_arguments",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_add_class_implemented_with_new",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_add_function_arguments",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_add_method_arguments",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_add_subclass_arguments",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_add_subclass_arguments_tuple",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_add_subclass_discard_init_args",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_basic_subtypes",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_fail_untyped_false",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_final_class",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_implicit_optional",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_instantiate_classes",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_invalid_type",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_link_arguments",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_link_arguments_apply_on_instantiate",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_link_arguments_subclasses",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_logger_debug",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_optional_enum",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_print_config",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_required_group",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_skip",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_skip_in_add_subclass_arguments",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_skip_within_subclass_type",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_type_any_serialize",
"jsonargparse_tests/signatures_tests.py::SignaturesConfigTests::test_add_function_arguments_config",
"jsonargparse_tests/signatures_tests.py::SignaturesConfigTests::test_add_subclass_arguments_with_config",
"jsonargparse_tests/signatures_tests.py::SignaturesConfigTests::test_config_within_config"
] | 2021-08-07 10:28:18+00:00 | 4,374 |
|
omni-us__jsonargparse-90 | diff --git a/jsonargparse/signatures.py b/jsonargparse/signatures.py
index ba936c6..d0e509a 100644
--- a/jsonargparse/signatures.py
+++ b/jsonargparse/signatures.py
@@ -2,7 +2,7 @@
import inspect
import re
-from argparse import Namespace
+from argparse import Namespace, SUPPRESS
from functools import wraps
from typing import Any, Callable, List, Optional, Set, Tuple, Type, Union
@@ -491,7 +491,7 @@ class SignatureArguments:
{},
added_args,
skip,
- default={},
+ default=SUPPRESS,
sub_configs=True,
instantiate=instantiate,
**kwargs
| omni-us/jsonargparse | dde80fb00f48e3a922001542c47f16c986df7fd2 | diff --git a/jsonargparse_tests/signatures_tests.py b/jsonargparse_tests/signatures_tests.py
index 87a55d4..757d37e 100755
--- a/jsonargparse_tests/signatures_tests.py
+++ b/jsonargparse_tests/signatures_tests.py
@@ -386,7 +386,9 @@ class SignaturesTests(unittest.TestCase):
parser = ArgumentParser(parse_as_dict=True, error_handler=None)
parser.add_subclass_arguments(calendar.Calendar, 'cal', required=False)
cfg = parser.parse_args([])
- self.assertEqual(cfg, {'cal': {}})
+ self.assertEqual(cfg, {})
+ cfg_init = parser.instantiate_classes(cfg)
+ self.assertEqual(cfg_init, {})
def test_invalid_type(self):
| Config check failed with `add_subclass_arguments(required=False)`
```python
from jsonargparse import ArgumentParser
class A:
...
class B:
...
parser = ArgumentParser()
parser.add_subclass_arguments((A, B), nested_key="foo", required=False)
args = parser.parse_args()
```
produces:
```
scratch_12.py: error: Configuration check failed :: Parser key "foo": Value {} does not validate against any of the types in typing.Union[__main__.A, __main__.B]:
- Type <class '__main__.A'> expects an str or a Dict with a class_path entry but got "{}"
- Type <class '__main__.B'> expects an str or a Dict with a class_path entry but got "{}"
```
My assumption was that by setting `required=False`, `--foo` does not need to be passed.
And `args` would be an empty dictionary. | 0.0 | [
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_not_required_group"
] | [
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_add_class_arguments",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_add_class_from_function_arguments",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_add_class_implemented_with_new",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_add_function_arguments",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_add_method_arguments",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_add_subclass_arguments",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_add_subclass_arguments_tuple",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_add_subclass_discard_init_args",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_basic_subtypes",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_fail_untyped_false",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_final_class",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_implicit_optional",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_instantiate_classes",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_instantiate_classes_subcommand",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_invalid_type",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_link_arguments",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_link_arguments_apply_on_instantiate",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_link_arguments_subclasses",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_link_arguments_subcommand",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_logger_debug",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_optional_enum",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_print_config",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_required_group",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_skip",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_skip_in_add_subclass_arguments",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_skip_within_subclass_type",
"jsonargparse_tests/signatures_tests.py::SignaturesTests::test_type_any_serialize",
"jsonargparse_tests/signatures_tests.py::SignaturesConfigTests::test_add_class_arguments_with_config_not_found",
"jsonargparse_tests/signatures_tests.py::SignaturesConfigTests::test_add_function_arguments_config",
"jsonargparse_tests/signatures_tests.py::SignaturesConfigTests::test_add_subclass_arguments_with_config",
"jsonargparse_tests/signatures_tests.py::SignaturesConfigTests::test_add_subclass_arguments_with_multifile_save",
"jsonargparse_tests/signatures_tests.py::SignaturesConfigTests::test_config_within_config"
] | 2021-09-15 18:32:39+00:00 | 4,375 |
|
omry__omegaconf-162 | diff --git a/docs/notebook/Tutorial.ipynb b/docs/notebook/Tutorial.ipynb
index b1d6a87..e038afe 100644
--- a/docs/notebook/Tutorial.ipynb
+++ b/docs/notebook/Tutorial.ipynb
@@ -131,11 +131,11 @@
"name": "stdout",
"output_type": "stream",
"text": [
+ "server:\n",
+ " port: 80\n",
"log:\n",
" file: ???\n",
" rotation: 3600\n",
- "server:\n",
- " port: 80\n",
"users:\n",
"- user1\n",
"- user2\n",
@@ -248,10 +248,10 @@
"name": "stdout",
"output_type": "stream",
"text": [
- "log:\n",
- " file: log2.txt\n",
"server:\n",
" port: 82\n",
+ "log:\n",
+ " file: log2.txt\n",
"\n"
]
}
@@ -285,11 +285,11 @@
"name": "stdout",
"output_type": "stream",
"text": [
+ "server:\n",
+ " port: 80\n",
"log:\n",
" file: ???\n",
" rotation: 3600\n",
- "server:\n",
- " port: 80\n",
"users:\n",
"- user1\n",
"- user2\n",
@@ -546,12 +546,12 @@
"name": "stdout",
"output_type": "stream",
"text": [
- "client:\n",
- " server_port: ${server.port}\n",
- " url: http://${server.host}:${server.port}/\n",
"server:\n",
" host: localhost\n",
" port: 80\n",
+ "client:\n",
+ " url: http://${server.host}:${server.port}/\n",
+ " server_port: ${server.port}\n",
"\n"
]
}
@@ -602,12 +602,12 @@
"name": "stdout",
"output_type": "stream",
"text": [
- "client:\n",
- " server_port: 80\n",
- " url: http://localhost:80/\n",
"server:\n",
" host: localhost\n",
" port: 80\n",
+ "client:\n",
+ " url: http://localhost:80/\n",
+ " server_port: 80\n",
"\n"
]
}
@@ -659,8 +659,8 @@
"output_type": "stream",
"text": [
"user:\n",
- " home: /home/${env:USER}\n",
" name: ${env:USER}\n",
+ " home: /home/${env:USER}\n",
"\n"
]
}
@@ -684,8 +684,8 @@
"output_type": "stream",
"text": [
"user:\n",
- " home: /home/omry\n",
" name: omry\n",
+ " home: /home/omry\n",
"\n"
]
}
@@ -817,13 +817,13 @@
"name": "stdout",
"output_type": "stream",
"text": [
- "log:\n",
- " file: log.txt\n",
"server:\n",
" port: 82\n",
"users:\n",
"- user1\n",
"- user2\n",
+ "log:\n",
+ " file: log.txt\n",
"\n"
]
}
@@ -859,7 +859,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
- "version": "3.7.5"
+ "version": "3.6.9"
},
"pycharm": {
"stem_cell": {
diff --git a/docs/source/structured_config.rst b/docs/source/structured_config.rst
index f62d46a..6fb03b1 100644
--- a/docs/source/structured_config.rst
+++ b/docs/source/structured_config.rst
@@ -67,11 +67,11 @@ fields during construction.
>>> conf3 = OmegaConf.create(SimpleTypes(num=20,
... height=Height.TALL))
>>> print(conf3.pretty())
- description: text
- height: Height.TALL
- is_awesome: true
num: 20
pi: 3.1415
+ is_awesome: true
+ height: Height.TALL
+ description: text
<BLANKLINE>
The resulting object is a regular OmegaConf object, except it will utilize the type information in the input class/object
@@ -177,13 +177,13 @@ Structured configs can be nested.
>>> conf : Group = OmegaConf.structured(Group)
>>> print(conf.pretty())
+ name: ???
admin:
- height: ???
name: ???
+ height: ???
manager:
- height: Height.TALL
name: manager
- name: ???
+ height: Height.TALL
<BLANKLINE>
OmegaConf will validate that assignment of nested objects is of the correct type:
diff --git a/docs/source/usage.rst b/docs/source/usage.rst
index 951c5e0..722f340 100644
--- a/docs/source/usage.rst
+++ b/docs/source/usage.rst
@@ -69,11 +69,11 @@ From a yaml file
>>> conf = OmegaConf.load('source/example.yaml')
>>> # Output is identical to the yaml file
>>> print(conf.pretty())
+ server:
+ port: 80
log:
file: ???
rotation: 3600
- server:
- port: 80
users:
- user1
- user2
@@ -131,10 +131,10 @@ To parse the content of sys.arg:
>>> sys.argv = ['your-program.py', 'server.port=82', 'log.file=log2.txt']
>>> conf = OmegaConf.from_cli()
>>> print(conf.pretty())
- log:
- file: log2.txt
server:
port: 82
+ log:
+ file: log2.txt
<BLANKLINE>
From structured config
@@ -154,8 +154,8 @@ See :doc:`structured_config` for more details, or keep reading for a minimal exa
>>> # For strict typing purposes, prefer OmegaConf.structured() when creating structured configs
>>> conf = OmegaConf.structured(MyConfig)
>>> print(conf.pretty())
- host: localhost
port: 80
+ host: localhost
<BLANKLINE>
You can use an object to initialize the config as well:
@@ -164,8 +164,8 @@ You can use an object to initialize the config as well:
>>> conf = OmegaConf.structured(MyConfig(port=443))
>>> print(conf.pretty())
- host: localhost
port: 443
+ host: localhost
<BLANKLINE>
OmegaConf objects constructed from Structured classes offers runtime type safety:
@@ -385,13 +385,13 @@ Note how the port changes to 82, and how the users lists are combined.
>>> # Merge with cli arguments
>>> conf.merge_with_cli()
>>> print(conf.pretty())
- log:
- file: log.txt
server:
port: 82
users:
- user1
- user2
+ log:
+ file: log.txt
<BLANKLINE>
Configuration flags
diff --git a/news/161.feature b/news/161.feature
new file mode 100644
index 0000000..504ecd1
--- /dev/null
+++ b/news/161.feature
@@ -0,0 +1,1 @@
+Container.pretty() now preserves insertion order by default. override with sort_keys=True
diff --git a/news/161.removal b/news/161.removal
new file mode 100644
index 0000000..738624c
--- /dev/null
+++ b/news/161.removal
@@ -0,0 +1,1 @@
+Container.pretty() behavior change: sorted keys -> unsorted keys by default. override with sort_keys=True.
\ No newline at end of file
diff --git a/omegaconf/base.py b/omegaconf/base.py
index 507fc6b..d409579 100644
--- a/omegaconf/base.py
+++ b/omegaconf/base.py
@@ -61,7 +61,7 @@ class Container(Node):
"""
@abstractmethod
- def pretty(self, resolve: bool = False) -> str:
+ def pretty(self, resolve: bool = False, sort_keys: bool = False) -> str:
... # pragma: no cover
@abstractmethod
diff --git a/omegaconf/basecontainer.py b/omegaconf/basecontainer.py
index 76584dc..b86a20f 100644
--- a/omegaconf/basecontainer.py
+++ b/omegaconf/basecontainer.py
@@ -272,18 +272,19 @@ class BaseContainer(Container, ABC):
return BaseContainer._to_content(self, resolve)
- def pretty(self, resolve: bool = False) -> str:
+ def pretty(self, resolve: bool = False, sort_keys: bool = False) -> str:
from omegaconf import OmegaConf
"""
returns a yaml dump of this config object.
:param resolve: if True, will return a string with the interpolations resolved, otherwise
interpolations are preserved
+ :param sort_keys: If True, will print dict keys in sorted order. default False.
:return: A string containing the yaml representation.
"""
container = OmegaConf.to_container(self, resolve=resolve, enum_to_str=True)
return yaml.dump( # type: ignore
- container, default_flow_style=False, allow_unicode=True
+ container, default_flow_style=False, allow_unicode=True, sort_keys=sort_keys
)
@staticmethod
| omry/omegaconf | 8e7989da4863c928cb5cdaa010422b99dfba47c6 | diff --git a/tests/examples/test_dataclass_example.py b/tests/examples/test_dataclass_example.py
index 2adcdbb..945d629 100644
--- a/tests/examples/test_dataclass_example.py
+++ b/tests/examples/test_dataclass_example.py
@@ -146,17 +146,15 @@ def test_nesting() -> None:
"manager": {"name": "manager", "height": Height.TALL},
}
- assert (
- conf.pretty()
- == """admin:
- height: ???
+ expected = """name: ???
+admin:
name: ???
+ height: ???
manager:
- height: Height.TALL
name: manager
-name: ???
+ height: Height.TALL
"""
- )
+ assert conf.pretty() == expected
# you can assign a different object of the same type
conf.admin = User(name="omry", height=Height.TALL)
diff --git a/tests/test_basic_ops_dict.py b/tests/test_basic_ops_dict.py
index 45cf3cb..24d1536 100644
--- a/tests/test_basic_ops_dict.py
+++ b/tests/test_basic_ops_dict.py
@@ -97,12 +97,20 @@ list:
assert OmegaConf.create(c.pretty()) == c
+def test_pretty_sort_keys() -> None:
+ c = OmegaConf.create({"b": 2, "a": 1})
+ # keys are not sorted by default
+ assert c.pretty() == "b: 2\na: 1\n"
+ c = OmegaConf.create({"b": 2, "a": 1})
+ assert c.pretty(sort_keys=True) == "a: 1\nb: 2\n"
+
+
def test_pretty_dict_unicode() -> None:
c = OmegaConf.create(dict(你好="世界", list=[1, 2]))
- expected = """list:
+ expected = """你好: 世界
+list:
- 1
- 2
-你好: 世界
"""
assert expected == c.pretty()
assert OmegaConf.create(c.pretty()) == c
| Do not sort keys by default in pretty(), and add sort_keys override. | 0.0 | [
"tests/examples/test_dataclass_example.py::test_nesting",
"tests/test_basic_ops_dict.py::test_pretty_sort_keys",
"tests/test_basic_ops_dict.py::test_pretty_dict_unicode"
] | [
"tests/examples/test_dataclass_example.py::test_simple_types_class",
"tests/examples/test_dataclass_example.py::test_static_typing",
"tests/examples/test_dataclass_example.py::test_simple_types_obj",
"tests/examples/test_dataclass_example.py::test_conversions",
"tests/examples/test_dataclass_example.py::test_modifiers",
"tests/examples/test_dataclass_example.py::test_typed_list_runtime_validation",
"tests/examples/test_dataclass_example.py::test_typed_dict_runtime_validation",
"tests/examples/test_dataclass_example.py::test_frozen",
"tests/examples/test_dataclass_example.py::test_enum_key",
"tests/examples/test_dataclass_example.py::test_dict_of_objects",
"tests/examples/test_dataclass_example.py::test_list_of_objects",
"tests/examples/test_dataclass_example.py::test_merge",
"tests/examples/test_dataclass_example.py::test_merge_example",
"tests/test_basic_ops_dict.py::test_setattr_deep_value",
"tests/test_basic_ops_dict.py::test_setattr_deep_from_empty",
"tests/test_basic_ops_dict.py::test_setattr_deep_map",
"tests/test_basic_ops_dict.py::test_getattr",
"tests/test_basic_ops_dict.py::test_getattr_dict",
"tests/test_basic_ops_dict.py::test_mandatory_value",
"tests/test_basic_ops_dict.py::test_nested_dict_mandatory_value",
"tests/test_basic_ops_dict.py::test_mandatory_with_default",
"tests/test_basic_ops_dict.py::test_subscript_get",
"tests/test_basic_ops_dict.py::test_subscript_set",
"tests/test_basic_ops_dict.py::test_pretty_dict",
"tests/test_basic_ops_dict.py::test_default_value",
"tests/test_basic_ops_dict.py::test_get_default_value",
"tests/test_basic_ops_dict.py::test_scientific_notation_float",
"tests/test_basic_ops_dict.py::test_dict_get_with_default",
"tests/test_basic_ops_dict.py::test_map_expansion",
"tests/test_basic_ops_dict.py::test_items",
"tests/test_basic_ops_dict.py::test_items2",
"tests/test_basic_ops_dict.py::test_items_with_interpolation",
"tests/test_basic_ops_dict.py::test_dict_keys",
"tests/test_basic_ops_dict.py::test_pickle_get_root",
"tests/test_basic_ops_dict.py::test_iterate_dictionary",
"tests/test_basic_ops_dict.py::test_dict_pop[cfg0-a-None-1-expectation0]",
"tests/test_basic_ops_dict.py::test_dict_pop[cfg1-not_found-default-default-expectation1]",
"tests/test_basic_ops_dict.py::test_dict_pop[cfg2-not_found-None-None-expectation2]",
"tests/test_basic_ops_dict.py::test_dict_pop[cfg3-a-None-2-expectation3]",
"tests/test_basic_ops_dict.py::test_dict_pop[cfg4-a-None-None-expectation4]",
"tests/test_basic_ops_dict.py::test_dict_pop[cfg5-a-None-None-expectation5]",
"tests/test_basic_ops_dict.py::test_dict_pop[cfg6-Enum1.FOO-None-bar-expectation6]",
"tests/test_basic_ops_dict.py::test_dict_pop[cfg7-Enum1.BAR-default-default-expectation7]",
"tests/test_basic_ops_dict.py::test_dict_pop[cfg8-Enum1.BAR-None-None-expectation8]",
"tests/test_basic_ops_dict.py::test_in_dict[conf0-a-True]",
"tests/test_basic_ops_dict.py::test_in_dict[conf1-b-True]",
"tests/test_basic_ops_dict.py::test_in_dict[conf2-c-False]",
"tests/test_basic_ops_dict.py::test_in_dict[conf3-b-True]",
"tests/test_basic_ops_dict.py::test_in_dict[conf4-b-False]",
"tests/test_basic_ops_dict.py::test_in_dict[conf5-c-False]",
"tests/test_basic_ops_dict.py::test_in_dict[conf6-b-False]",
"tests/test_basic_ops_dict.py::test_in_dict[conf7-a-True]",
"tests/test_basic_ops_dict.py::test_in_dict[conf8-b-True]",
"tests/test_basic_ops_dict.py::test_in_dict[conf9-b-True]",
"tests/test_basic_ops_dict.py::test_in_dict[conf10-Enum1.FOO-True]",
"tests/test_basic_ops_dict.py::test_get_root",
"tests/test_basic_ops_dict.py::test_get_root_of_merged",
"tests/test_basic_ops_dict.py::test_dict_config",
"tests/test_basic_ops_dict.py::test_dict_delitem",
"tests/test_basic_ops_dict.py::test_dict_len",
"tests/test_basic_ops_dict.py::test_dict_assign_illegal_value",
"tests/test_basic_ops_dict.py::test_dict_assign_illegal_value_nested",
"tests/test_basic_ops_dict.py::test_assign_dict_in_dict",
"tests/test_basic_ops_dict.py::test_to_container[src0]",
"tests/test_basic_ops_dict.py::test_to_container[src1]",
"tests/test_basic_ops_dict.py::test_to_container[src2]",
"tests/test_basic_ops_dict.py::test_pretty_without_resolve",
"tests/test_basic_ops_dict.py::test_pretty_with_resolve",
"tests/test_basic_ops_dict.py::test_instantiate_config_fails",
"tests/test_basic_ops_dict.py::test_dir",
"tests/test_basic_ops_dict.py::test_hash",
"tests/test_basic_ops_dict.py::test_get_with_default_from_struct_not_throwing",
"tests/test_basic_ops_dict.py::test_members",
"tests/test_basic_ops_dict.py::test_masked_copy[in_cfg0-mask_keys0-expected0]",
"tests/test_basic_ops_dict.py::test_masked_copy[in_cfg1-a-expected1]",
"tests/test_basic_ops_dict.py::test_masked_copy[in_cfg2-mask_keys2-expected2]",
"tests/test_basic_ops_dict.py::test_masked_copy[in_cfg3-b-expected3]",
"tests/test_basic_ops_dict.py::test_masked_copy[in_cfg4-mask_keys4-expected4]",
"tests/test_basic_ops_dict.py::test_masked_copy_is_deep",
"tests/test_basic_ops_dict.py::test_creation_with_invalid_key",
"tests/test_basic_ops_dict.py::test_set_with_invalid_key",
"tests/test_basic_ops_dict.py::test_get_with_invalid_key",
"tests/test_basic_ops_dict.py::test_hasattr",
"tests/test_basic_ops_dict.py::test_struct_mode_missing_key_getitem",
"tests/test_basic_ops_dict.py::test_struct_mode_missing_key_setitem"
] | 2020-03-08 04:38:48+00:00 | 4,376 |
|
omry__omegaconf-178 | diff --git a/news/174.bugfix b/news/174.bugfix
new file mode 100644
index 0000000..f581b33
--- /dev/null
+++ b/news/174.bugfix
@@ -0,0 +1,1 @@
+Fix AttributeError when accessing config in struct-mode with get() while providing None as default
diff --git a/omegaconf/basecontainer.py b/omegaconf/basecontainer.py
index 83b41ef..db52399 100644
--- a/omegaconf/basecontainer.py
+++ b/omegaconf/basecontainer.py
@@ -19,6 +19,8 @@ from ._utils import (
from .base import Container, ContainerMetadata, Node
from .errors import MissingMandatoryValue, ReadonlyConfigError, ValidationError
+DEFAULT_VALUE_MARKER: Any = object()
+
class BaseContainer(Container, ABC):
# static
@@ -42,7 +44,10 @@ class BaseContainer(Container, ABC):
OmegaConf.save(self, f)
def _resolve_with_default(
- self, key: Union[str, int, Enum], value: Any, default_value: Any = None
+ self,
+ key: Union[str, int, Enum],
+ value: Any,
+ default_value: Any = DEFAULT_VALUE_MARKER,
) -> Any:
"""returns the value with the specified key, like obj.key and obj['key']"""
@@ -51,7 +56,9 @@ class BaseContainer(Container, ABC):
value = _get_value(value)
- if default_value is not None and (value is None or is_mandatory_missing(value)):
+ if default_value is not DEFAULT_VALUE_MARKER and (
+ value is None or is_mandatory_missing(value)
+ ):
value = default_value
value = self._resolve_str_interpolation(
diff --git a/omegaconf/dictconfig.py b/omegaconf/dictconfig.py
index 2d64bc9..0143758 100644
--- a/omegaconf/dictconfig.py
+++ b/omegaconf/dictconfig.py
@@ -24,7 +24,7 @@ from ._utils import (
is_structured_config_frozen,
)
from .base import Container, ContainerMetadata, Node
-from .basecontainer import BaseContainer
+from .basecontainer import DEFAULT_VALUE_MARKER, BaseContainer
from .errors import (
KeyValidationError,
MissingMandatoryValue,
@@ -247,7 +247,7 @@ class DictConfig(BaseContainer, MutableMapping[str, Any]):
if key == "__members__":
raise AttributeError()
- return self.get(key=key, default_value=None)
+ return self.get(key=key)
def __getitem__(self, key: Union[str, Enum]) -> Any:
"""
@@ -256,11 +256,13 @@ class DictConfig(BaseContainer, MutableMapping[str, Any]):
:return:
"""
try:
- return self.get(key=key, default_value=None)
+ return self.get(key=key)
except AttributeError as e:
raise KeyError(str(e))
- def get(self, key: Union[str, Enum], default_value: Any = None) -> Any:
+ def get(
+ self, key: Union[str, Enum], default_value: Any = DEFAULT_VALUE_MARKER,
+ ) -> Any:
key = self._validate_and_normalize_key(key)
node = self.get_node_ex(key=key, default_value=default_value)
return self._resolve_with_default(
@@ -268,12 +270,12 @@ class DictConfig(BaseContainer, MutableMapping[str, Any]):
)
def get_node(self, key: Union[str, Enum]) -> Node:
- return self.get_node_ex(key)
+ return self.get_node_ex(key, default_value=DEFAULT_VALUE_MARKER)
def get_node_ex(
self,
key: Union[str, Enum],
- default_value: Any = None,
+ default_value: Any = DEFAULT_VALUE_MARKER,
validate_access: bool = True,
) -> Node:
value: Node = self.__dict__["_content"].get(key)
@@ -281,18 +283,18 @@ class DictConfig(BaseContainer, MutableMapping[str, Any]):
try:
self._validate_get(key)
except (KeyError, AttributeError):
- if default_value is not None:
+ if default_value != DEFAULT_VALUE_MARKER:
value = default_value
else:
raise
else:
- if default_value is not None:
+ if default_value is not DEFAULT_VALUE_MARKER:
value = default_value
return value
- __marker = object()
+ __pop_marker = object()
- def pop(self, key: Union[str, Enum], default: Any = __marker) -> Any:
+ def pop(self, key: Union[str, Enum], default: Any = __pop_marker) -> Any:
key = self._validate_and_normalize_key(key)
if self._get_flag("readonly"):
raise ReadonlyConfigError(self._get_full_key(key))
@@ -301,7 +303,7 @@ class DictConfig(BaseContainer, MutableMapping[str, Any]):
value=self.__dict__["_content"].pop(key, default),
default_value=default,
)
- if value is self.__marker:
+ if value is self.__pop_marker:
raise KeyError(key)
return value
@@ -328,7 +330,7 @@ class DictConfig(BaseContainer, MutableMapping[str, Any]):
return False
else:
try:
- self._resolve_with_default(key, node, None)
+ self._resolve_with_default(key=key, value=node)
return True
except UnsupportedInterpolationType:
# Value that has unsupported interpolation counts as existing.
| omry/omegaconf | 80ccd1cf2eb44307eaf67bcd704edb749235a81b | diff --git a/tests/test_basic_ops_dict.py b/tests/test_basic_ops_dict.py
index f8c7220..aa46b86 100644
--- a/tests/test_basic_ops_dict.py
+++ b/tests/test_basic_ops_dict.py
@@ -52,7 +52,7 @@ def test_getattr_dict() -> None:
def test_mandatory_value() -> None:
- c = OmegaConf.create(dict(a="???"))
+ c = OmegaConf.create({"a": "???"})
with pytest.raises(MissingMandatoryValue, match="a"):
c.a
@@ -270,8 +270,7 @@ def test_dict_pop(
)
def test_in_dict(conf: Any, key: str, expected: Any) -> None:
conf = OmegaConf.create(conf)
- ret = key in conf
- assert ret == expected
+ assert (key in conf) == expected
def test_get_root() -> None:
@@ -387,10 +386,11 @@ def test_hash() -> None:
assert hash(c1) != hash(c2)
-def test_get_with_default_from_struct_not_throwing() -> None:
- c = OmegaConf.create(dict(a=10, b=20))
[email protected]("default", ["default", 0, None]) # type: ignore
+def test_get_with_default_from_struct_not_throwing(default: Any) -> None:
+ c = OmegaConf.create({"a": 10, "b": 20})
OmegaConf.set_struct(c, True)
- assert c.get("z", "default") == "default"
+ assert c.get("z", default) == default
def test_members() -> None:
diff --git a/tests/test_struct.py b/tests/test_struct.py
index f8ec370..c6016d8 100644
--- a/tests/test_struct.py
+++ b/tests/test_struct.py
@@ -13,7 +13,7 @@ def test_struct_default() -> None:
def test_struct_set_on_dict() -> None:
- c = OmegaConf.create(dict(a=dict()))
+ c = OmegaConf.create({"a": {}})
OmegaConf.set_struct(c, True)
# Throwing when it hits foo, so exception key is a.foo and not a.foo.bar
with pytest.raises(AttributeError, match=re.escape("a.foo")):
| [bug] .get on ConfigNode with default None throws keyerror in struct mode
Minimal example:
```python
cfg = omegaconf.OmegaConf.create()
omegaconf.OmegaConf.set_struct(cfg, True)
a.get("d", None)
...
AttributeError: Accessing unknown key in a struct : d
```
Version: `2.0.0rc15` | 0.0 | [
"tests/test_basic_ops_dict.py::test_get_with_default_from_struct_not_throwing[None]"
] | [
"tests/test_basic_ops_dict.py::test_setattr_deep_value",
"tests/test_basic_ops_dict.py::test_setattr_deep_from_empty",
"tests/test_basic_ops_dict.py::test_setattr_deep_map",
"tests/test_basic_ops_dict.py::test_getattr",
"tests/test_basic_ops_dict.py::test_getattr_dict",
"tests/test_basic_ops_dict.py::test_mandatory_value",
"tests/test_basic_ops_dict.py::test_nested_dict_mandatory_value",
"tests/test_basic_ops_dict.py::test_mandatory_with_default",
"tests/test_basic_ops_dict.py::test_subscript_get",
"tests/test_basic_ops_dict.py::test_subscript_set",
"tests/test_basic_ops_dict.py::test_pretty_dict",
"tests/test_basic_ops_dict.py::test_pretty_sort_keys",
"tests/test_basic_ops_dict.py::test_pretty_dict_unicode",
"tests/test_basic_ops_dict.py::test_default_value",
"tests/test_basic_ops_dict.py::test_get_default_value",
"tests/test_basic_ops_dict.py::test_scientific_notation_float",
"tests/test_basic_ops_dict.py::test_dict_get_with_default",
"tests/test_basic_ops_dict.py::test_map_expansion",
"tests/test_basic_ops_dict.py::test_items",
"tests/test_basic_ops_dict.py::test_items2",
"tests/test_basic_ops_dict.py::test_items_with_interpolation",
"tests/test_basic_ops_dict.py::test_dict_keys",
"tests/test_basic_ops_dict.py::test_pickle_get_root",
"tests/test_basic_ops_dict.py::test_iterate_dictionary",
"tests/test_basic_ops_dict.py::test_dict_pop[cfg0-a-None-1-expectation0]",
"tests/test_basic_ops_dict.py::test_dict_pop[cfg1-not_found-default-default-expectation1]",
"tests/test_basic_ops_dict.py::test_dict_pop[cfg2-not_found-None-None-expectation2]",
"tests/test_basic_ops_dict.py::test_dict_pop[cfg3-a-None-2-expectation3]",
"tests/test_basic_ops_dict.py::test_dict_pop[cfg4-a-None-None-expectation4]",
"tests/test_basic_ops_dict.py::test_dict_pop[cfg5-a-None-None-expectation5]",
"tests/test_basic_ops_dict.py::test_dict_pop[cfg6-Enum1.FOO-None-bar-expectation6]",
"tests/test_basic_ops_dict.py::test_dict_pop[cfg7-Enum1.BAR-default-default-expectation7]",
"tests/test_basic_ops_dict.py::test_dict_pop[cfg8-Enum1.BAR-None-None-expectation8]",
"tests/test_basic_ops_dict.py::test_in_dict[conf0-a-True]",
"tests/test_basic_ops_dict.py::test_in_dict[conf1-b-True]",
"tests/test_basic_ops_dict.py::test_in_dict[conf2-c-False]",
"tests/test_basic_ops_dict.py::test_in_dict[conf3-b-True]",
"tests/test_basic_ops_dict.py::test_in_dict[conf4-b-False]",
"tests/test_basic_ops_dict.py::test_in_dict[conf5-c-False]",
"tests/test_basic_ops_dict.py::test_in_dict[conf6-b-False]",
"tests/test_basic_ops_dict.py::test_in_dict[conf7-a-True]",
"tests/test_basic_ops_dict.py::test_in_dict[conf8-b-True]",
"tests/test_basic_ops_dict.py::test_in_dict[conf9-b-True]",
"tests/test_basic_ops_dict.py::test_in_dict[conf10-Enum1.FOO-True]",
"tests/test_basic_ops_dict.py::test_get_root",
"tests/test_basic_ops_dict.py::test_get_root_of_merged",
"tests/test_basic_ops_dict.py::test_dict_config",
"tests/test_basic_ops_dict.py::test_dict_delitem",
"tests/test_basic_ops_dict.py::test_dict_len[d0-0]",
"tests/test_basic_ops_dict.py::test_dict_len[d1-2]",
"tests/test_basic_ops_dict.py::test_dict_assign_illegal_value",
"tests/test_basic_ops_dict.py::test_dict_assign_illegal_value_nested",
"tests/test_basic_ops_dict.py::test_assign_dict_in_dict",
"tests/test_basic_ops_dict.py::test_to_container[src0]",
"tests/test_basic_ops_dict.py::test_to_container[src1]",
"tests/test_basic_ops_dict.py::test_to_container[src2]",
"tests/test_basic_ops_dict.py::test_pretty_without_resolve",
"tests/test_basic_ops_dict.py::test_pretty_with_resolve",
"tests/test_basic_ops_dict.py::test_instantiate_config_fails",
"tests/test_basic_ops_dict.py::test_dir",
"tests/test_basic_ops_dict.py::test_hash",
"tests/test_basic_ops_dict.py::test_get_with_default_from_struct_not_throwing[default]",
"tests/test_basic_ops_dict.py::test_get_with_default_from_struct_not_throwing[0]",
"tests/test_basic_ops_dict.py::test_members",
"tests/test_basic_ops_dict.py::test_masked_copy[in_cfg0-mask_keys0-expected0]",
"tests/test_basic_ops_dict.py::test_masked_copy[in_cfg1-a-expected1]",
"tests/test_basic_ops_dict.py::test_masked_copy[in_cfg2-mask_keys2-expected2]",
"tests/test_basic_ops_dict.py::test_masked_copy[in_cfg3-b-expected3]",
"tests/test_basic_ops_dict.py::test_masked_copy[in_cfg4-mask_keys4-expected4]",
"tests/test_basic_ops_dict.py::test_masked_copy_is_deep",
"tests/test_basic_ops_dict.py::test_creation_with_invalid_key",
"tests/test_basic_ops_dict.py::test_set_with_invalid_key",
"tests/test_basic_ops_dict.py::test_get_with_invalid_key",
"tests/test_basic_ops_dict.py::test_hasattr",
"tests/test_basic_ops_dict.py::test_struct_mode_missing_key_getitem",
"tests/test_basic_ops_dict.py::test_struct_mode_missing_key_setitem",
"tests/test_basic_ops_dict.py::test_get_type",
"tests/test_basic_ops_dict.py::test_is_missing",
"tests/test_struct.py::test_struct_default",
"tests/test_struct.py::test_struct_set_on_dict",
"tests/test_struct.py::test_struct_set_on_nested_dict",
"tests/test_struct.py::test_merge_dotlist_into_struct",
"tests/test_struct.py::test_merge_config_with_struct[in_base0-in_merged0]",
"tests/test_struct.py::test_struct_contain_missing"
] | 2020-03-24 23:24:59+00:00 | 4,377 |
|
omry__omegaconf-205 | diff --git a/omegaconf/_utils.py b/omegaconf/_utils.py
index 1a5b762..5879d6d 100644
--- a/omegaconf/_utils.py
+++ b/omegaconf/_utils.py
@@ -477,19 +477,12 @@ def format_and_raise(
KEY_TYPE=f"{type(key).__name__}",
)
- full_backtrace = "OC_CAUSE" in os.environ and os.environ["OC_CAUSE"] == "1"
template = """$MSG
\tfull_key: $FULL_KEY
\treference_type=$REF_TYPE
\tobject_type=$OBJECT_TYPE
"""
- if not full_backtrace:
- template += """
-
-Set env OC_CAUSE=1 to include causing exception
- """
-
s = string.Template(template=template)
message = s.substitute(
@@ -515,6 +508,9 @@ Set env OC_CAUSE=1 to include causing exception
ex.ref_type = ref_type
ex.ref_type_str = ref_type_str
+ # Set the environment variable OC_CAUSE=1 to get a stacktrace that includes the
+ # causing exception.
+ full_backtrace = "OC_CAUSE" in os.environ and os.environ["OC_CAUSE"] == "1"
if full_backtrace:
ex.__cause__ = cause
else:
diff --git a/omegaconf/base.py b/omegaconf/base.py
index fd26d11..f1916d5 100644
--- a/omegaconf/base.py
+++ b/omegaconf/base.py
@@ -115,7 +115,7 @@ class Node(ABC):
key = self._key()
if value_kind == ValueKind.INTERPOLATION:
assert parent is not None
- v = parent._resolve_interpolation(
+ v = parent._resolve_simple_interpolation(
key=key,
inter_type=match.group(1),
inter_key=match.group(2),
@@ -125,7 +125,7 @@ class Node(ABC):
return v
elif value_kind == ValueKind.STR_INTERPOLATION:
assert parent is not None
- ret = parent._resolve_str_interpolation(
+ ret = parent._resolve_interpolation(
key=key,
value=self,
throw_on_missing=throw_on_missing,
@@ -279,7 +279,7 @@ class Container(Node):
)
if value is None:
return root, last_key, value
- value = root._resolve_str_interpolation(
+ value = root._resolve_interpolation(
key=last_key,
value=value,
throw_on_missing=False,
@@ -287,7 +287,7 @@ class Container(Node):
)
return root, last_key, value
- def _resolve_interpolation(
+ def _resolve_simple_interpolation(
self,
key: Any,
inter_type: str,
@@ -309,7 +309,8 @@ class Container(Node):
throw_on_resolution_failure=throw_on_resolution_failure,
)
- if parent is None or (value is None and last_key not in parent): # type: ignore
+ # if parent is None or (value is None and last_key not in parent): # type: ignore
+ if parent is None or value is None:
if throw_on_resolution_failure:
raise ConfigKeyError(
f"{inter_type} interpolation key '{inter_key}' not found"
@@ -341,7 +342,7 @@ class Container(Node):
else:
return None
- def _resolve_str_interpolation(
+ def _resolve_interpolation(
self,
key: Any,
value: "Node",
@@ -357,7 +358,7 @@ class Container(Node):
if value_kind == ValueKind.INTERPOLATION:
# simple interpolation, inherit type
match = match_list[0]
- return self._resolve_interpolation(
+ return self._resolve_simple_interpolation(
key=key,
inter_type=match.group(1),
inter_key=match.group(2),
@@ -371,7 +372,7 @@ class Container(Node):
new = ""
last_index = 0
for match in match_list:
- new_val = self._resolve_interpolation(
+ new_val = self._resolve_simple_interpolation(
key=key,
inter_type=match.group(1),
inter_key=match.group(2),
diff --git a/omegaconf/basecontainer.py b/omegaconf/basecontainer.py
index 47baea4..7acbdb9 100644
--- a/omegaconf/basecontainer.py
+++ b/omegaconf/basecontainer.py
@@ -56,7 +56,7 @@ class BaseContainer(Container, ABC):
if has_default and (value is None or is_mandatory_missing(value)):
return default_value
- resolved = self._resolve_str_interpolation(
+ resolved = self._resolve_interpolation(
key=key,
value=value,
throw_on_missing=not has_default,
@@ -179,9 +179,7 @@ class BaseContainer(Container, ABC):
return retdict
elif isinstance(conf, ListConfig):
retlist: List[Any] = []
- for index, item in enumerate(conf):
- if resolve:
- item = conf[index]
+ for index, item in enumerate(conf._iter_ex(resolve=resolve)):
item = convert(item)
if isinstance(item, Container):
item = BaseContainer._to_content(
diff --git a/omegaconf/listconfig.py b/omegaconf/listconfig.py
index cb21c94..7a57951 100644
--- a/omegaconf/listconfig.py
+++ b/omegaconf/listconfig.py
@@ -16,6 +16,7 @@ from typing import (
from ._utils import (
ValueKind,
+ _get_value,
format_and_raise,
get_list_element_type,
get_value_kind,
@@ -32,7 +33,6 @@ from .errors import (
ReadonlyConfigError,
ValidationError,
)
-from .nodes import ValueNode
class ListConfig(BaseContainer, MutableSequence[Any]):
@@ -388,6 +388,9 @@ class ListConfig(BaseContainer, MutableSequence[Any]):
return hash(str(self))
def __iter__(self) -> Iterator[Any]:
+ return self._iter_ex(resolve=True)
+
+ def _iter_ex(self, resolve: bool) -> Iterator[Any]:
try:
if self._is_none():
raise TypeError("Cannot iterate on ListConfig object representing None")
@@ -395,21 +398,24 @@ class ListConfig(BaseContainer, MutableSequence[Any]):
raise MissingMandatoryValue("Cannot iterate on a missing ListConfig")
class MyItems(Iterator[Any]):
- def __init__(self, lst: List[Any]) -> None:
+ def __init__(self, lst: ListConfig) -> None:
self.lst = lst
- self.iterator = iter(lst)
+ self.index = 0
def __next__(self) -> Any:
- return self.next()
-
- def next(self) -> Any:
- v = next(self.iterator)
- if isinstance(v, ValueNode):
- v = v._value()
+ if self.index == len(self.lst):
+ raise StopIteration()
+ if resolve:
+ v = self.lst[self.index]
+ else:
+ v = self.lst.__dict__["_content"][self.index]
+ if v is not None:
+ v = _get_value(v)
+ self.index = self.index + 1
return v
assert isinstance(self.__dict__["_content"], list)
- return MyItems(self.__dict__["_content"])
+ return MyItems(self)
except (ReadonlyConfigError, TypeError, MissingMandatoryValue) as e:
self._format_and_raise(key=None, value=None, cause=e)
assert False
@@ -453,8 +459,12 @@ class ListConfig(BaseContainer, MutableSequence[Any]):
if isinstance(value, ListConfig):
self.__dict__["_metadata"] = copy.deepcopy(value._metadata)
self.__dict__["_metadata"].flags = {}
- for item in value:
- self.append(item)
+ for item in value._iter_ex(resolve=False):
+ self.append(item)
+ self.__dict__["_metadata"].flags = copy.deepcopy(value._metadata.flags)
+ elif is_primitive_list(value):
+ for item in value:
+ self.append(item)
if isinstance(value, ListConfig):
self.__dict__["_metadata"].flags = value._metadata.flags
| omry/omegaconf | 4c5be9a3b99ad47a1492a2b3481498273ec3a6cd | diff --git a/tests/test_base_config.py b/tests/test_base_config.py
index 3b8ad4b..a0c6a0d 100644
--- a/tests/test_base_config.py
+++ b/tests/test_base_config.py
@@ -434,7 +434,7 @@ def test_not_implemented() -> None:
def test_resolve_str_interpolation(query: str, result: Any) -> None:
cfg = OmegaConf.create({"foo": 10, "bar": "${foo}"})
assert (
- cfg._resolve_str_interpolation(
+ cfg._resolve_interpolation(
key=None,
value=StringNode(value=query),
throw_on_missing=False,
diff --git a/tests/test_basic_ops_dict.py b/tests/test_basic_ops_dict.py
index b8ee516..8145d7b 100644
--- a/tests/test_basic_ops_dict.py
+++ b/tests/test_basic_ops_dict.py
@@ -237,13 +237,23 @@ def test_pickle_get_root() -> None:
def test_iterate_dictionary() -> None:
- c = OmegaConf.create(dict(a=1, b=2))
+ c = OmegaConf.create({"a": 1, "b": 2})
m2 = {}
for key in c:
m2[key] = c[key]
assert m2 == c
+def test_iterate_dict_with_interpolation() -> None:
+ c = OmegaConf.create({"a": "${b}", "b": 2})
+ expected = [("a", 2), ("b", 2)]
+ i = 0
+ for k, v in c.items():
+ assert k == expected[i][0]
+ assert v == expected[i][1]
+ i = i + 1
+
+
@pytest.mark.parametrize( # type: ignore
"cfg, key, default_, expected",
[
diff --git a/tests/test_basic_ops_list.py b/tests/test_basic_ops_list.py
index 1566ce3..5af36e3 100644
--- a/tests/test_basic_ops_list.py
+++ b/tests/test_basic_ops_list.py
@@ -6,6 +6,7 @@ import pytest
from omegaconf import AnyNode, ListConfig, OmegaConf
from omegaconf.errors import (
+ ConfigKeyError,
ConfigTypeError,
KeyValidationError,
MissingMandatoryValue,
@@ -57,11 +58,11 @@ def test_list_get_with_default() -> None:
@pytest.mark.parametrize( # type: ignore
- "input_, list_key",
+ "input_, expected, list_key",
[
- ([1, 2], None),
- (["${1}", 2], None),
- (
+ pytest.param([1, 2], [1, 2], None, id="simple"),
+ pytest.param(["${1}", 2], [2, 2], None, id="interpolation"),
+ pytest.param(
{
"defaults": [
{"optimizer": "adam"},
@@ -69,25 +70,36 @@ def test_list_get_with_default() -> None:
{"foo": "${defaults.0.optimizer}_${defaults.1.dataset}"},
]
},
+ [{"optimizer": "adam"}, {"dataset": "imagenet"}, {"foo": "adam_imagenet"}],
"defaults",
+ id="str_interpolation",
),
- ([1, 2, "${missing}"], None),
],
)
-def test_iterate_list(input_: Any, list_key: str) -> None:
+def test_iterate_list(input_: Any, expected: Any, list_key: str) -> None:
c = OmegaConf.create(input_)
if list_key is not None:
lst = c.get(list_key)
else:
lst = c
items = [x for x in lst]
- assert items == lst
+ assert items == expected
+
+
+def test_iterate_list_with_missing_interpolation() -> None:
+ c = OmegaConf.create([1, "${10}"])
+ itr = iter(c)
+ assert 1 == next(itr)
+ with pytest.raises(ConfigKeyError):
+ next(itr)
-def test_iterate_interpolated_list() -> None:
- cfg = OmegaConf.create({"inter": "${list}", "list": [1, 2, 3]})
- items = [x for x in cfg.inter]
- assert items == [1, 2, 3]
+def test_iterate_list_with_missing() -> None:
+ c = OmegaConf.create([1, "???"])
+ itr = iter(c)
+ assert 1 == next(itr)
+ with pytest.raises(MissingMandatoryValue):
+ next(itr)
def test_items_with_interpolation() -> None:
@@ -198,7 +210,8 @@ def test_list_append() -> None:
def test_pretty_without_resolve() -> None:
c = OmegaConf.create([100, "${0}"])
# without resolve, references are preserved
- c2 = OmegaConf.create(c.pretty(resolve=False))
+ yaml_str = c.pretty(resolve=False)
+ c2 = OmegaConf.create(yaml_str)
assert isinstance(c2, ListConfig)
c2[0] = 1000
assert c2[1] == 1000
| Variables not resolved when accessing through iterator
When accessing `ListConfig` through the iterator, the variables are not resolved. A similar issue is #21 regarding DictConfig.
config.yaml:
```
var1: 1
var2: 2
var3:
- ${var1}
- ${var2}
```
test.py:
```
import hydra
from omegaconf import DictConfig
@hydra.main('config.yaml')
def main(cfg: DictConfig) -> None:
print(cfg.var1)
print(cfg.var2)
print(cfg.var3)
print([x for x in cfg.var3])
print([cfg.var3[i] for i in range(len(cfg.var3))])
print(next(iter(cfg.var3)))
return
if __name__ == '__main__':
main()
```
Output:
```
$ python test.py
1
2
['${var1}', '${var2}']
['${var1}', '${var2}']
[1, 2]
${var1}
```
Hydra version: facebookresearch/hydra@b9df40a2
Omegaconf version: 4c5be9a | 0.0 | [
"tests/test_base_config.py::test_resolve_str_interpolation[a-a]",
"tests/test_base_config.py::test_resolve_str_interpolation[${foo}-10]",
"tests/test_base_config.py::test_resolve_str_interpolation[${bar}-10]",
"tests/test_base_config.py::test_resolve_str_interpolation[foo_${foo}-foo_10]",
"tests/test_base_config.py::test_resolve_str_interpolation[foo_${bar}-foo_10]",
"tests/test_basic_ops_list.py::test_iterate_list[interpolation]",
"tests/test_basic_ops_list.py::test_iterate_list_with_missing_interpolation",
"tests/test_basic_ops_list.py::test_iterate_list_with_missing"
] | [
"tests/test_base_config.py::test_set_value[input_0-foo-10-expected0]",
"tests/test_base_config.py::test_set_value[input_1-foo-value1-expected1]",
"tests/test_base_config.py::test_set_value[input_2-foo-value2-expected2]",
"tests/test_base_config.py::test_set_value[input_3-foo-value3-expected3]",
"tests/test_base_config.py::test_set_value[input_4-0-10-expected4]",
"tests/test_base_config.py::test_set_value[input_5-1-10-expected5]",
"tests/test_base_config.py::test_set_value[input_6-1-value6-expected6]",
"tests/test_base_config.py::test_set_value[input_7-1-value7-expected7]",
"tests/test_base_config.py::test_set_value[input_8-1-value8-expected8]",
"tests/test_base_config.py::test_set_value_validation_fail[input_0-foo-str]",
"tests/test_base_config.py::test_set_value_validation_fail[input_1-1-str]",
"tests/test_base_config.py::test_replace_value_node_type_with_another[input_0-foo-value0]",
"tests/test_base_config.py::test_replace_value_node_type_with_another[input_1-1-value1]",
"tests/test_base_config.py::test_to_container_returns_primitives[input_0]",
"tests/test_base_config.py::test_to_container_returns_primitives[input_1]",
"tests/test_base_config.py::test_to_container_returns_primitives[input_2]",
"tests/test_base_config.py::test_to_container_returns_primitives[input_3]",
"tests/test_base_config.py::test_to_container_returns_primitives[input_4]",
"tests/test_base_config.py::test_empty[input_0-True]",
"tests/test_base_config.py::test_empty[input_1-True]",
"tests/test_base_config.py::test_empty[input_2-False]",
"tests/test_base_config.py::test_empty[input_3-False]",
"tests/test_base_config.py::test_str[input_0-[]-str]",
"tests/test_base_config.py::test_str[input_0-[]-repr]",
"tests/test_base_config.py::test_str[input_1-{}-str]",
"tests/test_base_config.py::test_str[input_1-{}-repr]",
"tests/test_base_config.py::test_str[input_2-[1,",
"tests/test_base_config.py::test_str[input_3-[1,",
"tests/test_base_config.py::test_str[input_4-[1,",
"tests/test_base_config.py::test_str[input_5-{'b':",
"tests/test_base_config.py::test_str[input_6-{'b':",
"tests/test_base_config.py::test_str[StructuredWithMissing-{'num':",
"tests/test_base_config.py::test_flag_dict[readonly]",
"tests/test_base_config.py::test_flag_dict[struct]",
"tests/test_base_config.py::test_freeze_nested_dict[readonly]",
"tests/test_base_config.py::test_freeze_nested_dict[struct]",
"tests/test_base_config.py::TestDeepCopy::test_deepcopy[src0]",
"tests/test_base_config.py::TestDeepCopy::test_deepcopy[src1]",
"tests/test_base_config.py::TestDeepCopy::test_deepcopy[src2]",
"tests/test_base_config.py::TestDeepCopy::test_deepcopy[src3]",
"tests/test_base_config.py::TestDeepCopy::test_deepcopy[StructuredWithMissing]",
"tests/test_base_config.py::TestDeepCopy::test_deepcopy_readonly[src0]",
"tests/test_base_config.py::TestDeepCopy::test_deepcopy_readonly[src1]",
"tests/test_base_config.py::TestDeepCopy::test_deepcopy_readonly[src2]",
"tests/test_base_config.py::TestDeepCopy::test_deepcopy_readonly[src3]",
"tests/test_base_config.py::TestDeepCopy::test_deepcopy_readonly[StructuredWithMissing]",
"tests/test_base_config.py::TestDeepCopy::test_deepcopy_struct[src0]",
"tests/test_base_config.py::TestDeepCopy::test_deepcopy_struct[src1]",
"tests/test_base_config.py::TestDeepCopy::test_deepcopy_struct[src2]",
"tests/test_base_config.py::TestDeepCopy::test_deepcopy_struct[src3]",
"tests/test_base_config.py::TestDeepCopy::test_deepcopy_struct[StructuredWithMissing]",
"tests/test_base_config.py::test_deepcopy_after_del",
"tests/test_base_config.py::test_deepcopy_after_pop",
"tests/test_base_config.py::test_deepcopy_with_interpolation",
"tests/test_base_config.py::test_deepcopy_and_merge_and_flags",
"tests/test_base_config.py::test_deepcopy_preserves_container_type[cfg0]",
"tests/test_base_config.py::test_deepcopy_preserves_container_type[cfg1]",
"tests/test_base_config.py::test_flag_override[struct_setiitem]",
"tests/test_base_config.py::test_flag_override[struct_setattr]",
"tests/test_base_config.py::test_flag_override[readonly]",
"tests/test_base_config.py::test_read_write_override[src0-<lambda>-expectation0]",
"tests/test_base_config.py::test_read_write_override[src1-<lambda>-expectation1]",
"tests/test_base_config.py::test_tokenize_with_escapes[dog,cat-tokenized0]",
"tests/test_base_config.py::test_tokenize_with_escapes[dog\\\\,cat\\\\",
"tests/test_base_config.py::test_tokenize_with_escapes[dog,\\\\",
"tests/test_base_config.py::test_tokenize_with_escapes[\\\\",
"tests/test_base_config.py::test_tokenize_with_escapes[dog,",
"tests/test_base_config.py::test_tokenize_with_escapes[whitespace\\\\",
"tests/test_base_config.py::test_tokenize_with_escapes[None-tokenized8]",
"tests/test_base_config.py::test_tokenize_with_escapes[-tokenized9]",
"tests/test_base_config.py::test_tokenize_with_escapes[no",
"tests/test_base_config.py::test_struct_override[src0-<lambda>-expectation0]",
"tests/test_base_config.py::test_open_dict_restore[struct-open_dict]",
"tests/test_base_config.py::test_open_dict_restore[readonly-read_write]",
"tests/test_base_config.py::TestCopy::test_copy[src0-<lambda>0]",
"tests/test_base_config.py::TestCopy::test_copy[src0-<lambda>1]",
"tests/test_base_config.py::TestCopy::test_copy[src1-<lambda>0]",
"tests/test_base_config.py::TestCopy::test_copy[src1-<lambda>1]",
"tests/test_base_config.py::TestCopy::test_copy[src2-<lambda>0]",
"tests/test_base_config.py::TestCopy::test_copy[src2-<lambda>1]",
"tests/test_base_config.py::TestCopy::test_copy[src3-<lambda>0]",
"tests/test_base_config.py::TestCopy::test_copy[src3-<lambda>1]",
"tests/test_base_config.py::TestCopy::test_copy[src4-<lambda>0]",
"tests/test_base_config.py::TestCopy::test_copy[src4-<lambda>1]",
"tests/test_base_config.py::TestCopy::test_copy[src5-<lambda>0]",
"tests/test_base_config.py::TestCopy::test_copy[src5-<lambda>1]",
"tests/test_base_config.py::TestCopy::test_copy_with_interpolation[src0-2-0-<lambda>0]",
"tests/test_base_config.py::TestCopy::test_copy_with_interpolation[src0-2-0-<lambda>1]",
"tests/test_base_config.py::TestCopy::test_copy_with_interpolation[src1-b-a-<lambda>0]",
"tests/test_base_config.py::TestCopy::test_copy_with_interpolation[src1-b-a-<lambda>1]",
"tests/test_base_config.py::TestCopy::test_list_copy_is_shallow[<lambda>0]",
"tests/test_base_config.py::TestCopy::test_list_copy_is_shallow[<lambda>1]",
"tests/test_base_config.py::test_not_implemented",
"tests/test_base_config.py::test_omegaconf_create",
"tests/test_base_config.py::test_assign[parent0-0-value0-expected0]",
"tests/test_base_config.py::test_assign[parent1-0-value1-expected1]",
"tests/test_base_config.py::test_assign[parent2-0-value2-expected2]",
"tests/test_base_config.py::test_assign[parent3-foo-value3-expected3]",
"tests/test_base_config.py::test_assign[parent4-foo-value4-expected4]",
"tests/test_base_config.py::test_assign[parent5-foo-value5-expected5]",
"tests/test_base_config.py::test_get_node[cfg0-foo-bar]",
"tests/test_base_config.py::test_get_node[cfg1-foo-None]",
"tests/test_base_config.py::test_get_node[cfg2-foo-???]",
"tests/test_base_config.py::test_get_node[cfg3-1-20]",
"tests/test_base_config.py::test_get_node[cfg4-1-None]",
"tests/test_base_config.py::test_get_node[cfg5-1-???]",
"tests/test_basic_ops_dict.py::test_setattr_deep_value",
"tests/test_basic_ops_dict.py::test_setattr_deep_from_empty",
"tests/test_basic_ops_dict.py::test_setattr_deep_map",
"tests/test_basic_ops_dict.py::test_getattr",
"tests/test_basic_ops_dict.py::test_getattr_dict",
"tests/test_basic_ops_dict.py::test_mandatory_value",
"tests/test_basic_ops_dict.py::test_nested_dict_mandatory_value",
"tests/test_basic_ops_dict.py::test_mandatory_with_default",
"tests/test_basic_ops_dict.py::test_subscript_get",
"tests/test_basic_ops_dict.py::test_subscript_set",
"tests/test_basic_ops_dict.py::test_pretty_dict",
"tests/test_basic_ops_dict.py::test_pretty_sort_keys",
"tests/test_basic_ops_dict.py::test_pretty_dict_unicode",
"tests/test_basic_ops_dict.py::test_default_value",
"tests/test_basic_ops_dict.py::test_get_default_value",
"tests/test_basic_ops_dict.py::test_scientific_notation_float",
"tests/test_basic_ops_dict.py::test_dict_get_with_default[d0--missing]",
"tests/test_basic_ops_dict.py::test_dict_get_with_default[d1-hello-missing]",
"tests/test_basic_ops_dict.py::test_dict_get_with_default[d2--hello]",
"tests/test_basic_ops_dict.py::test_dict_get_with_default[d3--hello]",
"tests/test_basic_ops_dict.py::test_dict_get_with_default[d4--hello]",
"tests/test_basic_ops_dict.py::test_dict_get_with_default[d5--hello]",
"tests/test_basic_ops_dict.py::test_dict_get_with_default[d6--hello]",
"tests/test_basic_ops_dict.py::test_dict_get_with_default[d7--hello]",
"tests/test_basic_ops_dict.py::test_dict_get_with_default[d8--hello]",
"tests/test_basic_ops_dict.py::test_dict_get_with_default[d9--hello]",
"tests/test_basic_ops_dict.py::test_dict_get_with_default[d10--hello]",
"tests/test_basic_ops_dict.py::test_map_expansion",
"tests/test_basic_ops_dict.py::test_items",
"tests/test_basic_ops_dict.py::test_items2",
"tests/test_basic_ops_dict.py::test_items_with_interpolation",
"tests/test_basic_ops_dict.py::test_dict_keys",
"tests/test_basic_ops_dict.py::test_pickle_get_root",
"tests/test_basic_ops_dict.py::test_iterate_dictionary",
"tests/test_basic_ops_dict.py::test_iterate_dict_with_interpolation",
"tests/test_basic_ops_dict.py::test_dict_pop[cfg0-a-None-1]",
"tests/test_basic_ops_dict.py::test_dict_pop[cfg1-not_found-default-default]",
"tests/test_basic_ops_dict.py::test_dict_pop[cfg2-a-None-2]",
"tests/test_basic_ops_dict.py::test_dict_pop[cfg3-Enum1.FOO-None-bar]",
"tests/test_basic_ops_dict.py::test_dict_pop[cfg4-Enum1.BAR-default-default]",
"tests/test_basic_ops_dict.py::test_dict_pop_error[cfg0-not_found-expectation0]",
"tests/test_basic_ops_dict.py::test_dict_pop_error[cfg1-a-expectation1]",
"tests/test_basic_ops_dict.py::test_dict_pop_error[cfg2-a-expectation2]",
"tests/test_basic_ops_dict.py::test_dict_pop_error[cfg3-Enum1.BAR-expectation3]",
"tests/test_basic_ops_dict.py::test_in_dict[conf0-a-True]",
"tests/test_basic_ops_dict.py::test_in_dict[conf1-b-True]",
"tests/test_basic_ops_dict.py::test_in_dict[conf2-c-False]",
"tests/test_basic_ops_dict.py::test_in_dict[conf3-b-True]",
"tests/test_basic_ops_dict.py::test_in_dict[conf4-b-False]",
"tests/test_basic_ops_dict.py::test_in_dict[conf5-c-False]",
"tests/test_basic_ops_dict.py::test_in_dict[conf6-b-False]",
"tests/test_basic_ops_dict.py::test_in_dict[conf7-a-True]",
"tests/test_basic_ops_dict.py::test_in_dict[conf8-b-True]",
"tests/test_basic_ops_dict.py::test_in_dict[conf9-b-True]",
"tests/test_basic_ops_dict.py::test_in_dict[conf10-Enum1.FOO-True]",
"tests/test_basic_ops_dict.py::test_get_root",
"tests/test_basic_ops_dict.py::test_get_root_of_merged",
"tests/test_basic_ops_dict.py::test_dict_config",
"tests/test_basic_ops_dict.py::test_dict_delitem",
"tests/test_basic_ops_dict.py::test_dict_len[d0-0]",
"tests/test_basic_ops_dict.py::test_dict_len[d1-2]",
"tests/test_basic_ops_dict.py::test_dict_assign_illegal_value",
"tests/test_basic_ops_dict.py::test_dict_assign_illegal_value_nested",
"tests/test_basic_ops_dict.py::test_assign_dict_in_dict",
"tests/test_basic_ops_dict.py::test_to_container[src0]",
"tests/test_basic_ops_dict.py::test_to_container[src1]",
"tests/test_basic_ops_dict.py::test_to_container[src2]",
"tests/test_basic_ops_dict.py::test_pretty_without_resolve",
"tests/test_basic_ops_dict.py::test_pretty_with_resolve",
"tests/test_basic_ops_dict.py::test_instantiate_config_fails",
"tests/test_basic_ops_dict.py::test_dir[cfg0-None-expected0]",
"tests/test_basic_ops_dict.py::test_dir[cfg1-a-expected1]",
"tests/test_basic_ops_dict.py::test_dir[StructuredWithMissing-dict-expected2]",
"tests/test_basic_ops_dict.py::test_hash",
"tests/test_basic_ops_dict.py::test_get_with_default_from_struct_not_throwing[default]",
"tests/test_basic_ops_dict.py::test_get_with_default_from_struct_not_throwing[0]",
"tests/test_basic_ops_dict.py::test_get_with_default_from_struct_not_throwing[None]",
"tests/test_basic_ops_dict.py::test_members",
"tests/test_basic_ops_dict.py::test_masked_copy[in_cfg0-mask_keys0-expected0]",
"tests/test_basic_ops_dict.py::test_masked_copy[in_cfg1-a-expected1]",
"tests/test_basic_ops_dict.py::test_masked_copy[in_cfg2-mask_keys2-expected2]",
"tests/test_basic_ops_dict.py::test_masked_copy[in_cfg3-b-expected3]",
"tests/test_basic_ops_dict.py::test_masked_copy[in_cfg4-mask_keys4-expected4]",
"tests/test_basic_ops_dict.py::test_masked_copy_is_deep",
"tests/test_basic_ops_dict.py::test_creation_with_invalid_key",
"tests/test_basic_ops_dict.py::test_set_with_invalid_key",
"tests/test_basic_ops_dict.py::test_get_with_invalid_key",
"tests/test_basic_ops_dict.py::test_hasattr",
"tests/test_basic_ops_dict.py::test_struct_mode_missing_key_getitem",
"tests/test_basic_ops_dict.py::test_struct_mode_missing_key_setitem",
"tests/test_basic_ops_dict.py::test_get_type",
"tests/test_basic_ops_dict.py::test_get_ref_type",
"tests/test_basic_ops_dict.py::test_get_ref_type_with_conflict",
"tests/test_basic_ops_dict.py::test_is_missing",
"tests/test_basic_ops_dict.py::test_assign_to_reftype_none_or_any[None-None]",
"tests/test_basic_ops_dict.py::test_assign_to_reftype_none_or_any[None-ref_type1]",
"tests/test_basic_ops_dict.py::test_assign_to_reftype_none_or_any[assign1-None]",
"tests/test_basic_ops_dict.py::test_assign_to_reftype_none_or_any[assign1-ref_type1]",
"tests/test_basic_ops_dict.py::test_assign_to_reftype_none_or_any[assign2-None]",
"tests/test_basic_ops_dict.py::test_assign_to_reftype_none_or_any[assign2-ref_type1]",
"tests/test_basic_ops_dict.py::test_assign_to_reftype_none_or_any[assign3-None]",
"tests/test_basic_ops_dict.py::test_assign_to_reftype_none_or_any[assign3-ref_type1]",
"tests/test_basic_ops_dict.py::test_assign_to_reftype_plugin[Plugin-values0-None-does_not_raise]",
"tests/test_basic_ops_dict.py::test_assign_to_reftype_plugin[Plugin-values1-Plugin-does_not_raise]",
"tests/test_basic_ops_dict.py::test_assign_to_reftype_plugin[Plugin-values2-assign2-does_not_raise]",
"tests/test_basic_ops_dict.py::test_assign_to_reftype_plugin[Plugin-values3-ConcretePlugin-does_not_raise]",
"tests/test_basic_ops_dict.py::test_assign_to_reftype_plugin[Plugin-values4-assign4-does_not_raise]",
"tests/test_basic_ops_dict.py::test_assign_to_reftype_plugin[Plugin-values5-10-<lambda>]",
"tests/test_basic_ops_dict.py::test_assign_to_reftype_plugin[ConcretePlugin-values6-None-does_not_raise]",
"tests/test_basic_ops_dict.py::test_assign_to_reftype_plugin[ConcretePlugin-values7-Plugin-<lambda>]",
"tests/test_basic_ops_dict.py::test_assign_to_reftype_plugin[ConcretePlugin-values8-assign8-<lambda>]",
"tests/test_basic_ops_dict.py::test_assign_to_reftype_plugin[ConcretePlugin-values9-ConcretePlugin-does_not_raise]",
"tests/test_basic_ops_dict.py::test_assign_to_reftype_plugin[ConcretePlugin-values10-assign10-does_not_raise]",
"tests/test_basic_ops_list.py::test_list_value",
"tests/test_basic_ops_list.py::test_list_of_dicts",
"tests/test_basic_ops_list.py::test_pretty_list",
"tests/test_basic_ops_list.py::test_pretty_list_unicode",
"tests/test_basic_ops_list.py::test_list_get_with_default",
"tests/test_basic_ops_list.py::test_iterate_list[simple]",
"tests/test_basic_ops_list.py::test_iterate_list[str_interpolation]",
"tests/test_basic_ops_list.py::test_items_with_interpolation",
"tests/test_basic_ops_list.py::test_list_pop",
"tests/test_basic_ops_list.py::test_list_pop_on_unexpected_exception_not_modifying",
"tests/test_basic_ops_list.py::test_in_list",
"tests/test_basic_ops_list.py::test_list_config_with_list",
"tests/test_basic_ops_list.py::test_list_config_with_tuple",
"tests/test_basic_ops_list.py::test_items_on_list",
"tests/test_basic_ops_list.py::test_list_enumerate",
"tests/test_basic_ops_list.py::test_list_delitem",
"tests/test_basic_ops_list.py::test_list_len[lst0-2]",
"tests/test_basic_ops_list.py::test_list_len[lst1-0]",
"tests/test_basic_ops_list.py::test_list_len[lst2-0]",
"tests/test_basic_ops_list.py::test_nested_list_assign_illegal_value",
"tests/test_basic_ops_list.py::test_list_append",
"tests/test_basic_ops_list.py::test_pretty_without_resolve",
"tests/test_basic_ops_list.py::test_pretty_with_resolve",
"tests/test_basic_ops_list.py::test_list_index[index0-expected0]",
"tests/test_basic_ops_list.py::test_list_index[index1-expected1]",
"tests/test_basic_ops_list.py::test_list_index[-1-13]",
"tests/test_basic_ops_list.py::test_list_dir",
"tests/test_basic_ops_list.py::test_insert[input_0-1-100-expected0-AnyNode-None]",
"tests/test_basic_ops_list.py::test_insert[input_1-1-value1-expected1-IntegerNode-None]",
"tests/test_basic_ops_list.py::test_insert[input_2-1-foo-expected2-AnyNode-None]",
"tests/test_basic_ops_list.py::test_insert[input_3-1-value3-expected3-StringNode-None]",
"tests/test_basic_ops_list.py::test_insert[input_4-0-foo-None-None-ValidationError]",
"tests/test_basic_ops_list.py::test_insert_special_list[lst0-0-10-expectation0]",
"tests/test_basic_ops_list.py::test_insert_special_list[lst1-0-10-expectation1]",
"tests/test_basic_ops_list.py::test_extend[src0-append0-result0]",
"tests/test_basic_ops_list.py::test_extend[src1-append1-result1]",
"tests/test_basic_ops_list.py::test_extend[src2-append2-result2]",
"tests/test_basic_ops_list.py::test_remove[src0-10-result0-expectation0]",
"tests/test_basic_ops_list.py::test_remove[src1-oops-None-expectation1]",
"tests/test_basic_ops_list.py::test_remove[src2-remove2-result2-expectation2]",
"tests/test_basic_ops_list.py::test_remove[src3-2-result3-expectation3]",
"tests/test_basic_ops_list.py::test_clear[1-src0]",
"tests/test_basic_ops_list.py::test_clear[1-src1]",
"tests/test_basic_ops_list.py::test_clear[1-src2]",
"tests/test_basic_ops_list.py::test_clear[2-src0]",
"tests/test_basic_ops_list.py::test_clear[2-src1]",
"tests/test_basic_ops_list.py::test_clear[2-src2]",
"tests/test_basic_ops_list.py::test_index[src0-20--1-expectation0]",
"tests/test_basic_ops_list.py::test_index[src1-10-0-expectation1]",
"tests/test_basic_ops_list.py::test_index[src2-20-1-expectation2]",
"tests/test_basic_ops_list.py::test_index_with_range",
"tests/test_basic_ops_list.py::test_count[src0-10-0]",
"tests/test_basic_ops_list.py::test_count[src1-10-1]",
"tests/test_basic_ops_list.py::test_count[src2-10-2]",
"tests/test_basic_ops_list.py::test_count[src3-None-0]",
"tests/test_basic_ops_list.py::test_sort",
"tests/test_basic_ops_list.py::test_insert_throws_not_changing_list",
"tests/test_basic_ops_list.py::test_append_throws_not_changing_list",
"tests/test_basic_ops_list.py::test_hash",
"tests/test_basic_ops_list.py::TestListAdd::test_list_plus[in_list10-in_list20-in_expected0]",
"tests/test_basic_ops_list.py::TestListAdd::test_list_plus[in_list11-in_list21-in_expected1]",
"tests/test_basic_ops_list.py::TestListAdd::test_list_plus[in_list12-in_list22-in_expected2]",
"tests/test_basic_ops_list.py::TestListAdd::test_list_plus_eq[in_list10-in_list20-in_expected0]",
"tests/test_basic_ops_list.py::TestListAdd::test_list_plus_eq[in_list11-in_list21-in_expected1]",
"tests/test_basic_ops_list.py::TestListAdd::test_list_plus_eq[in_list12-in_list22-in_expected2]",
"tests/test_basic_ops_list.py::test_deep_add",
"tests/test_basic_ops_list.py::test_set_with_invalid_key",
"tests/test_basic_ops_list.py::test_getitem[lst0-0-1]",
"tests/test_basic_ops_list.py::test_getitem[lst1-0-TypeError]",
"tests/test_basic_ops_list.py::test_getitem[lst2-0-MissingMandatoryValue]",
"tests/test_basic_ops_list.py::test_get[lst0-0-1]",
"tests/test_basic_ops_list.py::test_get[lst1-foo-KeyValidationError]",
"tests/test_basic_ops_list.py::test_get[lst2-0-TypeError]",
"tests/test_basic_ops_list.py::test_get[lst3-0-MissingMandatoryValue]"
] | 2020-04-17 07:38:47+00:00 | 4,378 |
|
omry__omegaconf-218 | diff --git a/omegaconf/dictconfig.py b/omegaconf/dictconfig.py
index 82a1636..fbac511 100644
--- a/omegaconf/dictconfig.py
+++ b/omegaconf/dictconfig.py
@@ -362,7 +362,7 @@ class DictConfig(BaseContainer, MutableMapping[str, Any]):
if self._get_flag("readonly"):
raise ReadonlyConfigError("Cannot pop from read-only node")
- node = self._get_node(key=key)
+ node = self._get_node(key=key, validate_access=False)
if node is not None:
value = self._resolve_with_default(
key=key, value=node, default_value=default
| omry/omegaconf | 3c187e45be333af5535bff8f7b3a799e4caaa548 | diff --git a/tests/test_basic_ops_dict.py b/tests/test_basic_ops_dict.py
index 8145d7b..849d578 100644
--- a/tests/test_basic_ops_dict.py
+++ b/tests/test_basic_ops_dict.py
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
import re
import tempfile
-from typing import Any, Dict, List, Union
+from typing import Any, Dict, List, Optional, Union
import pytest
@@ -254,21 +254,56 @@ def test_iterate_dict_with_interpolation() -> None:
i = i + 1
[email protected]( # type: ignore
+ "struct",
+ [
+ pytest.param(None, id="struct_unspecified"),
+ pytest.param(False, id="struct_False"),
+ pytest.param(True, id="struct_True"),
+ ],
+)
@pytest.mark.parametrize( # type: ignore
"cfg, key, default_, expected",
[
- ({"a": 1, "b": 2}, "a", None, 1),
- ({"a": 1, "b": 2}, "not_found", "default", "default"),
+ pytest.param({"a": 1, "b": 2}, "a", "__NO_DEFAULT__", 1, id="no_default"),
+ pytest.param({"a": 1, "b": 2}, "not_found", None, None, id="none_default"),
+ pytest.param(
+ {"a": 1, "b": 2}, "not_found", "default", "default", id="with_default"
+ ),
# Interpolations
- ({"a": "${b}", "b": 2}, "a", None, 2),
+ pytest.param(
+ {"a": "${b}", "b": 2}, "a", "__NO_DEFAULT__", 2, id="interpolation"
+ ),
+ pytest.param(
+ {"a": "${b}"}, "a", "default", "default", id="interpolation_with_default"
+ ),
# enum key
- ({Enum1.FOO: "bar"}, Enum1.FOO, None, "bar"),
- ({Enum1.FOO: "bar"}, Enum1.BAR, "default", "default"),
+ pytest.param(
+ {Enum1.FOO: "bar"},
+ Enum1.FOO,
+ "__NO_DEFAULT__",
+ "bar",
+ id="enum_key_no_default",
+ ),
+ pytest.param(
+ {Enum1.FOO: "bar"}, Enum1.BAR, None, None, id="enum_key_with_none_default",
+ ),
+ pytest.param(
+ {Enum1.FOO: "bar"},
+ Enum1.BAR,
+ "default",
+ "default",
+ id="enum_key_with_default",
+ ),
],
)
-def test_dict_pop(cfg: Dict[Any, Any], key: Any, default_: Any, expected: Any) -> None:
+def test_dict_pop(
+ cfg: Dict[Any, Any], key: Any, default_: Any, expected: Any, struct: Optional[bool]
+) -> None:
c = OmegaConf.create(cfg)
- if default_ is not None:
+ OmegaConf.set_struct(c, struct)
+
+ if default_ != "__NO_DEFAULT__":
val = c.pop(key, default_)
else:
val = c.pop(key)
| [bug] .pop isn't behaving as standard dict in struct mode
```py
from omegaconf import OmegaConf
c = OmegaConf.create({"a": 1})
OmegaConf.set_struct(c, True)
c.get("b", 1) # Works fine returns 1
c.pop("b", 1) # Throws ConfigAttributeError
```
Expected:
`.pop` should return value 1
Actual:
Throws ConfigAttributeError
Version: 2.0.0.rc24
Used to work in rc16 | 0.0 | [
"tests/test_basic_ops_dict.py::test_dict_pop[none_default-struct_True]",
"tests/test_basic_ops_dict.py::test_dict_pop[with_default-struct_True]",
"tests/test_basic_ops_dict.py::test_dict_pop[enum_key_with_none_default-struct_True]",
"tests/test_basic_ops_dict.py::test_dict_pop[enum_key_with_default-struct_True]"
] | [
"tests/test_basic_ops_dict.py::test_setattr_deep_value",
"tests/test_basic_ops_dict.py::test_setattr_deep_from_empty",
"tests/test_basic_ops_dict.py::test_setattr_deep_map",
"tests/test_basic_ops_dict.py::test_getattr",
"tests/test_basic_ops_dict.py::test_getattr_dict",
"tests/test_basic_ops_dict.py::test_mandatory_value",
"tests/test_basic_ops_dict.py::test_nested_dict_mandatory_value",
"tests/test_basic_ops_dict.py::test_mandatory_with_default",
"tests/test_basic_ops_dict.py::test_subscript_get",
"tests/test_basic_ops_dict.py::test_subscript_set",
"tests/test_basic_ops_dict.py::test_pretty_dict",
"tests/test_basic_ops_dict.py::test_pretty_sort_keys",
"tests/test_basic_ops_dict.py::test_pretty_dict_unicode",
"tests/test_basic_ops_dict.py::test_default_value",
"tests/test_basic_ops_dict.py::test_get_default_value",
"tests/test_basic_ops_dict.py::test_scientific_notation_float",
"tests/test_basic_ops_dict.py::test_dict_get_with_default[d0--missing]",
"tests/test_basic_ops_dict.py::test_dict_get_with_default[d1-hello-missing]",
"tests/test_basic_ops_dict.py::test_dict_get_with_default[d2--hello]",
"tests/test_basic_ops_dict.py::test_dict_get_with_default[d3--hello]",
"tests/test_basic_ops_dict.py::test_dict_get_with_default[d4--hello]",
"tests/test_basic_ops_dict.py::test_dict_get_with_default[d5--hello]",
"tests/test_basic_ops_dict.py::test_dict_get_with_default[d6--hello]",
"tests/test_basic_ops_dict.py::test_dict_get_with_default[d7--hello]",
"tests/test_basic_ops_dict.py::test_dict_get_with_default[d8--hello]",
"tests/test_basic_ops_dict.py::test_dict_get_with_default[d9--hello]",
"tests/test_basic_ops_dict.py::test_dict_get_with_default[d10--hello]",
"tests/test_basic_ops_dict.py::test_map_expansion",
"tests/test_basic_ops_dict.py::test_items",
"tests/test_basic_ops_dict.py::test_items2",
"tests/test_basic_ops_dict.py::test_items_with_interpolation",
"tests/test_basic_ops_dict.py::test_dict_keys",
"tests/test_basic_ops_dict.py::test_pickle_get_root",
"tests/test_basic_ops_dict.py::test_iterate_dictionary",
"tests/test_basic_ops_dict.py::test_iterate_dict_with_interpolation",
"tests/test_basic_ops_dict.py::test_dict_pop[no_default-struct_unspecified]",
"tests/test_basic_ops_dict.py::test_dict_pop[no_default-struct_False]",
"tests/test_basic_ops_dict.py::test_dict_pop[no_default-struct_True]",
"tests/test_basic_ops_dict.py::test_dict_pop[none_default-struct_unspecified]",
"tests/test_basic_ops_dict.py::test_dict_pop[none_default-struct_False]",
"tests/test_basic_ops_dict.py::test_dict_pop[with_default-struct_unspecified]",
"tests/test_basic_ops_dict.py::test_dict_pop[with_default-struct_False]",
"tests/test_basic_ops_dict.py::test_dict_pop[interpolation-struct_unspecified]",
"tests/test_basic_ops_dict.py::test_dict_pop[interpolation-struct_False]",
"tests/test_basic_ops_dict.py::test_dict_pop[interpolation-struct_True]",
"tests/test_basic_ops_dict.py::test_dict_pop[interpolation_with_default-struct_unspecified]",
"tests/test_basic_ops_dict.py::test_dict_pop[interpolation_with_default-struct_False]",
"tests/test_basic_ops_dict.py::test_dict_pop[interpolation_with_default-struct_True]",
"tests/test_basic_ops_dict.py::test_dict_pop[enum_key_no_default-struct_unspecified]",
"tests/test_basic_ops_dict.py::test_dict_pop[enum_key_no_default-struct_False]",
"tests/test_basic_ops_dict.py::test_dict_pop[enum_key_no_default-struct_True]",
"tests/test_basic_ops_dict.py::test_dict_pop[enum_key_with_none_default-struct_unspecified]",
"tests/test_basic_ops_dict.py::test_dict_pop[enum_key_with_none_default-struct_False]",
"tests/test_basic_ops_dict.py::test_dict_pop[enum_key_with_default-struct_unspecified]",
"tests/test_basic_ops_dict.py::test_dict_pop[enum_key_with_default-struct_False]",
"tests/test_basic_ops_dict.py::test_dict_pop_error[cfg0-not_found-expectation0]",
"tests/test_basic_ops_dict.py::test_dict_pop_error[cfg1-a-expectation1]",
"tests/test_basic_ops_dict.py::test_dict_pop_error[cfg2-a-expectation2]",
"tests/test_basic_ops_dict.py::test_dict_pop_error[cfg3-Enum1.BAR-expectation3]",
"tests/test_basic_ops_dict.py::test_in_dict[conf0-a-True]",
"tests/test_basic_ops_dict.py::test_in_dict[conf1-b-True]",
"tests/test_basic_ops_dict.py::test_in_dict[conf2-c-False]",
"tests/test_basic_ops_dict.py::test_in_dict[conf3-b-True]",
"tests/test_basic_ops_dict.py::test_in_dict[conf4-b-False]",
"tests/test_basic_ops_dict.py::test_in_dict[conf5-c-False]",
"tests/test_basic_ops_dict.py::test_in_dict[conf6-b-False]",
"tests/test_basic_ops_dict.py::test_in_dict[conf7-a-True]",
"tests/test_basic_ops_dict.py::test_in_dict[conf8-b-True]",
"tests/test_basic_ops_dict.py::test_in_dict[conf9-b-True]",
"tests/test_basic_ops_dict.py::test_in_dict[conf10-Enum1.FOO-True]",
"tests/test_basic_ops_dict.py::test_get_root",
"tests/test_basic_ops_dict.py::test_get_root_of_merged",
"tests/test_basic_ops_dict.py::test_dict_config",
"tests/test_basic_ops_dict.py::test_dict_delitem",
"tests/test_basic_ops_dict.py::test_dict_len[d0-0]",
"tests/test_basic_ops_dict.py::test_dict_len[d1-2]",
"tests/test_basic_ops_dict.py::test_dict_assign_illegal_value",
"tests/test_basic_ops_dict.py::test_dict_assign_illegal_value_nested",
"tests/test_basic_ops_dict.py::test_assign_dict_in_dict",
"tests/test_basic_ops_dict.py::test_to_container[src0]",
"tests/test_basic_ops_dict.py::test_to_container[src1]",
"tests/test_basic_ops_dict.py::test_to_container[src2]",
"tests/test_basic_ops_dict.py::test_pretty_without_resolve",
"tests/test_basic_ops_dict.py::test_pretty_with_resolve",
"tests/test_basic_ops_dict.py::test_instantiate_config_fails",
"tests/test_basic_ops_dict.py::test_dir[cfg0-None-expected0]",
"tests/test_basic_ops_dict.py::test_dir[cfg1-a-expected1]",
"tests/test_basic_ops_dict.py::test_dir[StructuredWithMissing-dict-expected2]",
"tests/test_basic_ops_dict.py::test_hash",
"tests/test_basic_ops_dict.py::test_get_with_default_from_struct_not_throwing[default]",
"tests/test_basic_ops_dict.py::test_get_with_default_from_struct_not_throwing[0]",
"tests/test_basic_ops_dict.py::test_get_with_default_from_struct_not_throwing[None]",
"tests/test_basic_ops_dict.py::test_members",
"tests/test_basic_ops_dict.py::test_masked_copy[in_cfg0-mask_keys0-expected0]",
"tests/test_basic_ops_dict.py::test_masked_copy[in_cfg1-a-expected1]",
"tests/test_basic_ops_dict.py::test_masked_copy[in_cfg2-mask_keys2-expected2]",
"tests/test_basic_ops_dict.py::test_masked_copy[in_cfg3-b-expected3]",
"tests/test_basic_ops_dict.py::test_masked_copy[in_cfg4-mask_keys4-expected4]",
"tests/test_basic_ops_dict.py::test_masked_copy_is_deep",
"tests/test_basic_ops_dict.py::test_creation_with_invalid_key",
"tests/test_basic_ops_dict.py::test_set_with_invalid_key",
"tests/test_basic_ops_dict.py::test_get_with_invalid_key",
"tests/test_basic_ops_dict.py::test_hasattr",
"tests/test_basic_ops_dict.py::test_struct_mode_missing_key_getitem",
"tests/test_basic_ops_dict.py::test_struct_mode_missing_key_setitem",
"tests/test_basic_ops_dict.py::test_get_type",
"tests/test_basic_ops_dict.py::test_get_ref_type",
"tests/test_basic_ops_dict.py::test_get_ref_type_with_conflict",
"tests/test_basic_ops_dict.py::test_is_missing",
"tests/test_basic_ops_dict.py::test_assign_to_reftype_none_or_any[None-None]",
"tests/test_basic_ops_dict.py::test_assign_to_reftype_none_or_any[None-ref_type1]",
"tests/test_basic_ops_dict.py::test_assign_to_reftype_none_or_any[assign1-None]",
"tests/test_basic_ops_dict.py::test_assign_to_reftype_none_or_any[assign1-ref_type1]",
"tests/test_basic_ops_dict.py::test_assign_to_reftype_none_or_any[assign2-None]",
"tests/test_basic_ops_dict.py::test_assign_to_reftype_none_or_any[assign2-ref_type1]",
"tests/test_basic_ops_dict.py::test_assign_to_reftype_none_or_any[assign3-None]",
"tests/test_basic_ops_dict.py::test_assign_to_reftype_none_or_any[assign3-ref_type1]",
"tests/test_basic_ops_dict.py::test_assign_to_reftype_plugin[Plugin-values0-None-does_not_raise]",
"tests/test_basic_ops_dict.py::test_assign_to_reftype_plugin[Plugin-values1-Plugin-does_not_raise]",
"tests/test_basic_ops_dict.py::test_assign_to_reftype_plugin[Plugin-values2-assign2-does_not_raise]",
"tests/test_basic_ops_dict.py::test_assign_to_reftype_plugin[Plugin-values3-ConcretePlugin-does_not_raise]",
"tests/test_basic_ops_dict.py::test_assign_to_reftype_plugin[Plugin-values4-assign4-does_not_raise]",
"tests/test_basic_ops_dict.py::test_assign_to_reftype_plugin[Plugin-values5-10-<lambda>]",
"tests/test_basic_ops_dict.py::test_assign_to_reftype_plugin[ConcretePlugin-values6-None-does_not_raise]",
"tests/test_basic_ops_dict.py::test_assign_to_reftype_plugin[ConcretePlugin-values7-Plugin-<lambda>]",
"tests/test_basic_ops_dict.py::test_assign_to_reftype_plugin[ConcretePlugin-values8-assign8-<lambda>]",
"tests/test_basic_ops_dict.py::test_assign_to_reftype_plugin[ConcretePlugin-values9-ConcretePlugin-does_not_raise]",
"tests/test_basic_ops_dict.py::test_assign_to_reftype_plugin[ConcretePlugin-values10-assign10-does_not_raise]"
] | 2020-04-21 00:57:59+00:00 | 4,379 |
|
omry__omegaconf-220 | diff --git a/omegaconf/_utils.py b/omegaconf/_utils.py
index 8c7a6e4..126fca1 100644
--- a/omegaconf/_utils.py
+++ b/omegaconf/_utils.py
@@ -258,7 +258,7 @@ def get_value_kind(value: Any, return_match_list: bool = False) -> Any:
"""
key_prefix = r"\${(\w+:)?"
- legal_characters = r"([\w\.%_ \\,-]*?)}"
+ legal_characters = r"([\w\.%_ \\/:,-]*?)}"
match_list: Optional[List[Match[str]]] = None
def ret(
| omry/omegaconf | fd7846f9300f2e03b57d6dfe976367435b34ba73 | diff --git a/tests/test_interpolation.py b/tests/test_interpolation.py
index eb57d8d..6be772d 100644
--- a/tests/test_interpolation.py
+++ b/tests/test_interpolation.py
@@ -147,13 +147,20 @@ def test_env_interpolation_not_found() -> None:
c.path
-def test_env_default_interpolation_missing_env() -> None:
+def test_env_default_str_interpolation_missing_env() -> None:
if os.getenv("foobar") is not None:
del os.environ["foobar"]
c = OmegaConf.create({"path": "/test/${env:foobar,abc}"})
assert c.path == "/test/abc"
+def test_env_default_interpolation_missing_env_default_with_slash() -> None:
+ if os.getenv("foobar") is not None:
+ del os.environ["foobar"]
+ c = OmegaConf.create({"path": "${env:DATA_PATH,a/b}"})
+ assert c.path == "a/b"
+
+
def test_env_default_interpolation_env_exist() -> None:
os.environ["foobar"] = "1234"
c = OmegaConf.create({"path": "/test/${env:foobar,abc}"})
diff --git a/tests/test_utils.py b/tests/test_utils.py
index 74cb297..06ede88 100644
--- a/tests/test_utils.py
+++ b/tests/test_utils.py
@@ -202,6 +202,10 @@ class Dataclass:
("???", _utils.ValueKind.MANDATORY_MISSING),
("${foo.bar}", _utils.ValueKind.INTERPOLATION),
("ftp://${host}/path", _utils.ValueKind.STR_INTERPOLATION),
+ ("${func:foo}", _utils.ValueKind.INTERPOLATION),
+ ("${func:a/b}", _utils.ValueKind.INTERPOLATION),
+ ("${func:c:\\a\\b}", _utils.ValueKind.INTERPOLATION),
+ ("${func:c:\\a\\b}", _utils.ValueKind.INTERPOLATION),
],
)
def test_value_kind(value: Any, kind: _utils.ValueKind) -> None:
| [bug] Env Interpolation doesn't respect paths
```py
from omegaconf import OmegaConf
a = OmegaConf.create({"a": {"b": "${env:DATASET_CONFIG,configs/datasets}"}})
print(a.a.b) # prints '${env:DATASET_CONFIG,configs/datasets}'
```
Should print configs/datasets
Version: 2.0.0.rc24 | 0.0 | [
"tests/test_interpolation.py::test_env_interpolation_not_found",
"tests/test_interpolation.py::test_env_default_interpolation_missing_env_default_with_slash",
"tests/test_utils.py::test_value_kind[${func:c:\\\\a\\\\b}-ValueKind.INTERPOLATION0]",
"tests/test_utils.py::test_value_kind[${func:c:\\\\a\\\\b}-ValueKind.INTERPOLATION1]",
"tests/test_utils.py::test_value_kind[${func:a/b}-ValueKind.INTERPOLATION]"
] | [
"tests/test_interpolation.py::test_env_values_are_typed[10.0-10.0]",
"tests/test_interpolation.py::test_incremental_dict_with_interpolation",
"tests/test_interpolation.py::test_clear_resolvers",
"tests/test_interpolation.py::test_str_interpolation_3",
"tests/test_interpolation.py::test_register_resolver_1",
"tests/test_interpolation.py::test_register_resolver_twice_error",
"tests/test_interpolation.py::test_interpolations[cfg4-foo-bar]",
"tests/test_interpolation.py::test_supported_chars",
"tests/test_interpolation.py::test_env_values_are_typed[>1234->1234]",
"tests/test_interpolation.py::test_env_interpolation1",
"tests/test_interpolation.py::test_env_values_are_typed[true-True]",
"tests/test_interpolation.py::test_interpolation[input_2-a-expected2]",
"tests/test_interpolation.py::test_deep_str_interpolation_1",
"tests/test_interpolation.py::test_interpolations[cfg5-list.0-bar]",
"tests/test_interpolation.py::test_env_values_are_typed[10-10]",
"tests/test_interpolation.py::test_resolver_cache_2",
"tests/test_interpolation.py::test_interpolation[input_1-b.1-10]",
"tests/test_interpolation.py::test_interpolation_with_missing",
"tests/test_interpolation.py::test_deep_str_interpolation_2",
"tests/test_interpolation.py::test_interpolation[input_0-b-10]",
"tests/test_interpolation.py::test_env_default_interpolation_env_exist",
"tests/test_interpolation.py::test_env_values_are_typed[no-no]",
"tests/test_interpolation.py::test_env_values_are_typed[foo:",
"tests/test_interpolation.py::test_interpolation[input_5-a-foo-{'c':",
"tests/test_interpolation.py::test_interpolations[cfg0-b-10]",
"tests/test_interpolation.py::test_env_default_str_interpolation_missing_env",
"tests/test_interpolation.py::test_str_interpolation_key_error_1",
"tests/test_interpolation.py::test_env_values_are_typed[-10--10]",
"tests/test_interpolation.py::test_resolver_that_allows_a_list_of_arguments[<lambda>-escape_comma-${my_resolver:cat\\\\,",
"tests/test_interpolation.py::test_assign_to_interpolation",
"tests/test_interpolation.py::test_interpolations[cfg2-foo.0-10]",
"tests/test_interpolation.py::test_resolver_cache_1",
"tests/test_interpolation.py::test_complex_str_interpolation_is_always_str_1",
"tests/test_interpolation.py::test_env_values_are_typed[off-off]",
"tests/test_interpolation.py::test_str_interpolation_dict_1",
"tests/test_interpolation.py::test_clear_cache",
"tests/test_interpolation.py::test_unsupported_interpolation_type",
"tests/test_interpolation.py::test_interpolation[input_3-a-expected3]",
"tests/test_interpolation.py::test_resolver_that_allows_a_list_of_arguments[<lambda>-arg_list-${my_resolver:cat,",
"tests/test_interpolation.py::test_resolver_that_allows_a_list_of_arguments[<lambda>-zero_arg-${my_resolver:}-zero]",
"tests/test_interpolation.py::test_simple_str_interpolation_inherit_type",
"tests/test_interpolation.py::test_str_interpolation_key_error_2",
"tests/test_interpolation.py::test_interpolations[cfg3-bar-None]",
"tests/test_interpolation.py::test_env_values_are_typed[:1234-:1234]",
"tests/test_interpolation.py::test_env_values_are_typed[on-on]",
"tests/test_interpolation.py::test_interpolations[cfg1-c-10]",
"tests/test_interpolation.py::test_env_values_are_typed[yes-yes]",
"tests/test_interpolation.py::test_copy_cache",
"tests/test_interpolation.py::test_interpolation[input_4-a-foo-[1,",
"tests/test_interpolation.py::test_2_step_interpolation",
"tests/test_interpolation.py::test_env_values_are_typed[/1234-/1234]",
"tests/test_interpolation.py::test_env_values_are_typed[-10.0--10.0]",
"tests/test_interpolation.py::test_env_values_are_typed[false-False]",
"tests/test_interpolation.py::test_interpolation_in_list_key_error",
"tests/test_interpolation.py::test_merge_with_interpolation",
"tests/test_interpolation.py::test_str_interpolation_4",
"tests/test_interpolation.py::test_resolver_that_allows_a_list_of_arguments[<lambda>-escape_whitespace-${my_resolver:cat\\\\,",
"tests/test_utils.py::test_get_key_value_types[int-int-key_type3-None]",
"tests/test_utils.py::test_get_key_value_types[None-NoneType-int-KeyValidationError]",
"tests/test_utils.py::test_get_key_value_types[Color-Color-int-KeyValidationError]",
"tests/test_utils.py::test_maybe_wrap[int-Color.RED-ValidationError]",
"tests/test_utils.py::test_get_key_value_types[Color-Color-key_type3-None]",
"tests/test_utils.py::test_get_key_value_types[None-NoneType-None-KeyValidationError]",
"tests/test_utils.py::test_get_key_value_types[Color-Color-str-str]",
"tests/test_utils.py::test_is_primitive_type[DictConfig-False]",
"tests/test_utils.py::test_maybe_wrap[bool-0-None]",
"tests/test_utils.py::test_get_key_value_types[int-int-str-str]",
"tests/test_utils.py::test_type_str[DictConfig-DictConfig]",
"tests/test_utils.py::test_maybe_wrap[int-1-None]",
"tests/test_utils.py::test_maybe_wrap[bool-foo-ValidationError]",
"tests/test_utils.py::test_value_kind[False-ValueKind.VALUE]",
"tests/test_utils.py::test_maybe_wrap[Color-Color.RED-None1]",
"tests/test_utils.py::test_get_key_value_types[int-int-None-KeyValidationError]",
"tests/test_utils.py::test_valid_value_annotation_type[float-True]",
"tests/test_utils.py::test_is_primitive_type[str-True]",
"tests/test_utils.py::test_maybe_wrap[bool-on-None]",
"tests/test_utils.py::test_get_structured_config_data[test_cls_or_obj3-expectation3]",
"tests/test_utils.py::test_type_str[type_11-List[str]]",
"tests/test_utils.py::test_value_kind[???-ValueKind.MANDATORY_MISSING]",
"tests/test_utils.py::test_value_kind[${foo.bar}-ValueKind.INTERPOLATION]",
"tests/test_utils.py::test_get_structured_config_data[_TestAttrsClass-expectation2]",
"tests/test_utils.py::test_is_primitive_type[NoneType-True]",
"tests/test_utils.py::test_maybe_wrap[target_type4-Color.RED-None]",
"tests/test_utils.py::test_is_structured_config_frozen_with_invalid_obj",
"tests/test_utils.py::test_get_structured_config_data[invalid-expectation4]",
"tests/test_utils.py::test_maybe_wrap[bool-true-None]",
"tests/test_utils.py::test_maybe_wrap[Color-Color.RED-None0]",
"tests/test_utils.py::test_valid_value_annotation_type[int-True]",
"tests/test_utils.py::test_type_str[type_14-Union[str,",
"tests/test_utils.py::test_value_kind[Color.GREEN-ValueKind.VALUE]",
"tests/test_utils.py::test_get_key_value_types[None-NoneType-Color-Color]",
"tests/test_utils.py::test_is_primitive_type[ListConfig-False]",
"tests/test_utils.py::test_type_str[type_8-Dict[Color,",
"tests/test_utils.py::test_maybe_wrap[target_type2-1-None]",
"tests/test_utils.py::test_maybe_wrap[str-Color.RED-None]",
"tests/test_utils.py::test_is_primitive_type[bool-True]",
"tests/test_utils.py::test_get_key_value_types[str-str-Color-Color]",
"tests/test_utils.py::test_get_key_value_types[Color-Color-None-KeyValidationError]",
"tests/test_utils.py::test_maybe_wrap[str-True-None]",
"tests/test_utils.py::test_valid_value_annotation_type[_TestDataclass-True]",
"tests/test_utils.py::test_is_dataclass",
"tests/test_utils.py::test_value_kind[Dataclass-ValueKind.VALUE]",
"tests/test_utils.py::test_get_key_value_types[int-int-int-KeyValidationError]",
"tests/test_utils.py::test_value_kind[ftp://${host}/path-ValueKind.STR_INTERPOLATION]",
"tests/test_utils.py::test_maybe_wrap[float-Color.RED-ValidationError]",
"tests/test_utils.py::test_maybe_wrap[IllegalType-nope-ValidationError]",
"tests/test_utils.py::test_is_primitive_type[int-True]",
"tests/test_utils.py::test_value_kind[foo-ValueKind.VALUE]",
"tests/test_utils.py::test_valid_value_annotation_type[bool-True]",
"tests/test_utils.py::test_is_primitive_type[list-False]",
"tests/test_utils.py::test_get_key_value_types[value_type3-None-None-KeyValidationError]",
"tests/test_utils.py::test_maybe_wrap[Color-1.0-ValidationError]",
"tests/test_utils.py::test_maybe_wrap[bool-false-None]",
"tests/test_utils.py::test_get_key_value_types[None-NoneType-str-str]",
"tests/test_utils.py::test_maybe_wrap[Color-True-ValidationError]",
"tests/test_utils.py::test_type_str[ListConfig-ListConfig]",
"tests/test_utils.py::test_re_parent",
"tests/test_utils.py::test_maybe_wrap[int-1.0-ValidationError]",
"tests/test_utils.py::test_valid_value_annotation_type[_TestAttrsClass-True]",
"tests/test_utils.py::test_maybe_wrap[float-1-None]",
"tests/test_utils.py::test_maybe_wrap[Color-RED-None]",
"tests/test_utils.py::test_type_str[Color-Color]",
"tests/test_utils.py::test_maybe_wrap[str-foo-None]",
"tests/test_utils.py::test_maybe_wrap[target_type3-1.0-None]",
"tests/test_utils.py::test_valid_value_annotation_type[_TestUserClass-False]",
"tests/test_utils.py::test_value_kind[${func:foo}-ValueKind.INTERPOLATION]",
"tests/test_utils.py::test_maybe_wrap[Color-foo-ValidationError]",
"tests/test_utils.py::test_type_str[str-str]",
"tests/test_utils.py::test_maybe_wrap[Color-1-None]",
"tests/test_utils.py::test_maybe_wrap[bool-off-None]",
"tests/test_utils.py::test_is_attr_class",
"tests/test_utils.py::test_get_key_value_types[int-int-Color-Color]",
"tests/test_utils.py::test_get_key_value_types[value_type3-None-str-str]",
"tests/test_utils.py::test_is_primitive_type[dict-False]",
"tests/test_utils.py::test_valid_value_annotation_type[str-True]",
"tests/test_utils.py::test_type_str[type_13-List[Dict[str,",
"tests/test_utils.py::test_maybe_wrap[target_type0-foo-None]",
"tests/test_utils.py::test_maybe_wrap[str-1-None]",
"tests/test_utils.py::test_get_key_value_types[value_type3-None-Color-Color]",
"tests/test_utils.py::test_get_key_value_types[value_type3-None-key_type3-None]",
"tests/test_utils.py::test_get_key_value_types[str-str-int-KeyValidationError]",
"tests/test_utils.py::test_valid_value_annotation_type[_TestEnum-True]",
"tests/test_utils.py::test_maybe_wrap[target_type1-True-None]",
"tests/test_utils.py::test_type_str[type_9-Dict[str,",
"tests/test_utils.py::test_get_structured_config_data[test_cls_or_obj1-expectation1]",
"tests/test_utils.py::test_get_structured_config_data[_TestDataclass-expectation0]",
"tests/test_utils.py::test_maybe_wrap[str-1.0-None]",
"tests/test_utils.py::test_value_kind[True-ValueKind.VALUE]",
"tests/test_utils.py::test_get_key_value_types[None-NoneType-key_type3-None]",
"tests/test_utils.py::test_type_str[float-float]",
"tests/test_utils.py::test_maybe_wrap[int-True-ValidationError]",
"tests/test_utils.py::test_type_str[type_10-Dict[str,",
"tests/test_utils.py::test_is_primitive_type[Color-True]",
"tests/test_utils.py::test_maybe_wrap[bool-1-None]",
"tests/test_utils.py::test_get_key_value_types[str-str-key_type3-None]",
"tests/test_utils.py::test_type_str[type_12-List[Color]]",
"tests/test_utils.py::test_get_key_value_types[Color-Color-Color-Color]",
"tests/test_utils.py::test_maybe_wrap[float-True-ValidationError]",
"tests/test_utils.py::test_get_class",
"tests/test_utils.py::test_maybe_wrap[float-foo-ValidationError]",
"tests/test_utils.py::test_type_str[int-int]",
"tests/test_utils.py::test_type_str[bool-bool]",
"tests/test_utils.py::test_is_primitive_type[float-True]",
"tests/test_utils.py::test_maybe_wrap[bool-Color.RED-ValidationError]",
"tests/test_utils.py::test_value_kind[1.0-ValueKind.VALUE]",
"tests/test_utils.py::test_get_key_value_types[str-str-str-str]",
"tests/test_utils.py::test_type_str[type_7-Dict[str,",
"tests/test_utils.py::test_maybe_wrap[int-foo-ValidationError]",
"tests/test_utils.py::test_get_key_value_types[value_type3-None-int-KeyValidationError]",
"tests/test_utils.py::test_valid_value_annotation_type[type_4-True]",
"tests/test_utils.py::test_maybe_wrap[float-1.0-None]",
"tests/test_utils.py::test_maybe_wrap[bool-True-None]",
"tests/test_utils.py::test_get_key_value_types[str-str-None-KeyValidationError]",
"tests/test_utils.py::test_value_kind[1-ValueKind.VALUE]",
"tests/test_utils.py::test_maybe_wrap[bool-1.0-ValidationError]"
] | 2020-04-21 02:21:16+00:00 | 4,380 |
|
omry__omegaconf-247 | diff --git a/news/246.bugfix b/news/246.bugfix
new file mode 100644
index 0000000..0f57fd0
--- /dev/null
+++ b/news/246.bugfix
@@ -0,0 +1,1 @@
+Fixes merging of dict into a Dict[str, str]
\ No newline at end of file
diff --git a/omegaconf/basecontainer.py b/omegaconf/basecontainer.py
index eb22fe7..cafef05 100644
--- a/omegaconf/basecontainer.py
+++ b/omegaconf/basecontainer.py
@@ -239,31 +239,30 @@ class BaseContainer(Container, ABC):
dest._validate_set_merge_impl(key=None, value=src, is_assign=False)
for key, src_value in src.items_ex(resolve=False):
- dest_element_type = dest._metadata.element_type
- element_typed = dest_element_type not in (None, Any)
if OmegaConf.is_missing(dest, key):
if isinstance(src_value, DictConfig):
if OmegaConf.is_missing(dest, key):
dest[key] = src_value
dest_node = dest._get_node(key, validate_access=False)
- if dest_node is not None and dest_node._is_interpolation():
- target_node = dest_node._dereference_node(
- throw_on_resolution_failure=False
- )
- if isinstance(target_node, Container):
- dest[key] = target_node
- dest_node = dest._get_node(key)
+ if dest_node is not None:
+ if dest_node._is_interpolation():
+ target_node = dest_node._dereference_node(
+ throw_on_resolution_failure=False
+ )
+ if isinstance(target_node, Container):
+ dest[key] = target_node
+ dest_node = dest._get_node(key)
- if dest_node is not None or element_typed:
- if dest_node is None and element_typed:
- dest[key] = DictConfig(content=dest_element_type, parent=dest)
- dest_node = dest._get_node(key)
+ if is_structured_config(dest._metadata.element_type):
+ dest[key] = DictConfig(content=dest._metadata.element_type, parent=dest)
+ dest_node = dest._get_node(key)
+ if dest_node is not None:
if isinstance(dest_node, BaseContainer):
if isinstance(src_value, BaseContainer):
dest._validate_merge(key=key, value=src_value)
- dest_node.merge_with(src_value)
+ dest_node._merge_with(src_value)
else:
dest.__setitem__(key, src_value)
else:
@@ -284,43 +283,45 @@ class BaseContainer(Container, ABC):
def merge_with(
self,
*others: Union["BaseContainer", Dict[str, Any], List[Any], Tuple[Any], Any],
+ ) -> None:
+ try:
+ self._merge_with(*others)
+ except Exception as e:
+ self._format_and_raise(key=None, value=None, cause=e)
+
+ def _merge_with(
+ self,
+ *others: Union["BaseContainer", Dict[str, Any], List[Any], Tuple[Any], Any],
) -> None:
from .dictconfig import DictConfig
from .listconfig import ListConfig
from .omegaconf import OmegaConf
- try:
- """merge a list of other Config objects into this one, overriding as needed"""
- for other in others:
- if other is None:
- raise ValueError("Cannot merge with a None config")
- if is_primitive_container(other):
- assert isinstance(other, (list, dict))
- other = OmegaConf.create(other)
- elif is_structured_config(other):
- other = OmegaConf.structured(other)
- if isinstance(self, DictConfig) and isinstance(other, DictConfig):
- BaseContainer._map_merge(self, other)
- elif isinstance(self, ListConfig) and isinstance(other, ListConfig):
- if self._get_flag("readonly"):
- raise ReadonlyConfigError(self._get_full_key(""))
- if (
- self._is_none()
- or self._is_missing()
- or self._is_interpolation()
- ):
- self.__dict__["_content"] = []
- else:
- self.__dict__["_content"].clear()
- for item in other:
- self.append(item)
+ """merge a list of other Config objects into this one, overriding as needed"""
+ for other in others:
+ if other is None:
+ raise ValueError("Cannot merge with a None config")
+ if is_primitive_container(other):
+ assert isinstance(other, (list, dict))
+ other = OmegaConf.create(other)
+ elif is_structured_config(other):
+ other = OmegaConf.structured(other)
+ if isinstance(self, DictConfig) and isinstance(other, DictConfig):
+ BaseContainer._map_merge(self, other)
+ elif isinstance(self, ListConfig) and isinstance(other, ListConfig):
+ if self._get_flag("readonly"):
+ raise ReadonlyConfigError(self._get_full_key(""))
+ if self._is_none() or self._is_missing() or self._is_interpolation():
+ self.__dict__["_content"] = []
else:
- raise TypeError("Cannot merge DictConfig with ListConfig")
+ self.__dict__["_content"].clear()
+ for item in other:
+ self.append(item)
+ else:
+ raise TypeError("Cannot merge DictConfig with ListConfig")
- # recursively correct the parent hierarchy after the merge
- self._re_parent()
- except Exception as e:
- self._format_and_raise(key=None, value=None, cause=e)
+ # recursively correct the parent hierarchy after the merge
+ self._re_parent()
# noinspection PyProtectedMember
def _set_item_impl(self, key: Any, value: Any) -> None:
diff --git a/omegaconf/version.py b/omegaconf/version.py
index a723726..c24d79d 100644
--- a/omegaconf/version.py
+++ b/omegaconf/version.py
@@ -1,6 +1,6 @@
import sys # pragma: no cover
-__version__ = "2.0.0"
+__version__ = "2.0.1rc1"
msg = """OmegaConf 2.0 and above is compatible with Python 3.6 and newer.
You have the following options:
| omry/omegaconf | f736e72a96cee22f9fab0b562d561f2030b71a65 | diff --git a/tests/structured_conf/test_structured_config.py b/tests/structured_conf/test_structured_config.py
index 2e544de..73d446d 100644
--- a/tests/structured_conf/test_structured_config.py
+++ b/tests/structured_conf/test_structured_config.py
@@ -465,6 +465,12 @@ class TestConfigs:
with pytest.raises(ValidationError):
OmegaConf.merge(c1, c2)
+ def test_merge_into_Dict(self, class_type: str) -> None:
+ module: Any = import_module(class_type)
+ cfg = OmegaConf.structured(module.DictExamples)
+ res = OmegaConf.merge(cfg, {"strings": {"x": "abc"}})
+ assert res.strings == {"a": "foo", "b": "bar", "x": "abc"}
+
def test_typed_dict_key_error(self, class_type: str) -> None:
module: Any = import_module(class_type)
input_ = module.ErrorDictIntKey
@@ -532,11 +538,6 @@ class TestConfigs:
def test_dict_examples(self, class_type: str) -> None:
module: Any = import_module(class_type)
conf = OmegaConf.structured(module.DictExamples)
- # any: Dict = {"a": 1, "b": "foo"}
- # ints: Dict[str, int] = {"a": 10, "b": 20}
- # strings: Dict[str, str] = {"a": "foo", "b": "bar"}
- # booleans: Dict[str, bool] = {"a": True, "b": False}
- # colors: Dict[str, Color] = {"red": Color.RED, "green": "GREEN", "blue": 3}
def test_any(name: str) -> None:
conf[name].c = True
diff --git a/tests/test_merge.py b/tests/test_merge.py
index 5aea074..56f80fe 100644
--- a/tests/test_merge.py
+++ b/tests/test_merge.py
@@ -125,11 +125,16 @@ from . import (
[Users, {"name2user": {"joe": User(name="joe")}}],
{"name2user": {"joe": {"name": "joe", "age": MISSING}}},
),
- (
+ pytest.param(
[Users, {"name2user": {"joe": {"name": "joe"}}}],
{"name2user": {"joe": {"name": "joe", "age": MISSING}}},
+ id="users_merge_with_missing_age",
+ ),
+ pytest.param(
+ [ConfWithMissingDict, {"dict": {"foo": "bar"}}],
+ {"dict": {"foo": "bar"}},
+ id="conf_missing_dict",
),
- ([ConfWithMissingDict, {"dict": {"foo": "bar"}}], {"dict": {"foo": "bar"}}),
pytest.param(
[{}, ConfWithMissingDict],
{"dict": "???"},
| Error merging dict into a Dict[str, str]
```python
from dataclasses import dataclass, field
from typing import Dict
from omegaconf import OmegaConf
@dataclass
class JobConf:
env: Dict[str, str] = field(default_factory=dict)
cfg = OmegaConf.create({"job": JobConf})
res = OmegaConf.merge(cfg, {"job": {"env": {"abc": "ABC"}}})
assert res.job == {"env": {"abc": "ABC"}}
```
Results in:
```
AssertionError: Unsupported value type : <class 'str'>
full_key: job.env
reference_type=Dict[str, str]
object_type=dict
full_key: job
reference_type=Optional[JobConf]
object_type=JobConf
full_key:
reference_type=Optional[Dict[Any, Any]]
object_type=dict
``` | 0.0 | [
"tests/structured_conf/test_structured_config.py::TestConfigs::test_merge_into_Dict[tests.structured_conf.data.dataclasses]"
] | [
"tests/structured_conf/test_structured_config.py::TestConfigs::test_nested_config_is_none[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_nested_config[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_value_without_a_default[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_union_errors[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_config_with_list[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_assignment_to_nested_structured_config[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_assignment_to_structured_inside_dict_config[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_config_with_dict[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_structured_config_struct_behavior[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_field_with_default_value[BoolConfig-BoolConfigAssignments-init_dict0-tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_field_with_default_value[IntegersConfig-IntegersConfigAssignments-init_dict1-tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_field_with_default_value[FloatConfig-FloatConfigAssignments-init_dict2-tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_field_with_default_value[StringConfig-StringConfigAssignments-init_dict3-tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_field_with_default_value[EnumConfig-EnumConfigAssignments-init_dict4-tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_field_with_default_value[BoolConfig-BoolConfigAssignments-init_dict5-tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_field_with_default_value[IntegersConfig-IntegersConfigAssignments-init_dict6-tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_field_with_default_value[FloatConfig-FloatConfigAssignments-init_dict7-tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_field_with_default_value[StringConfig-StringConfigAssignments-init_dict8-tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_field_with_default_value[EnumConfig-EnumConfigAssignments-init_dict9-tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_field_with_default_value[AnyTypeConfig-AnyTypeConfigAssignments-init_dict10-tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_untyped[None-expected_init0-tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_untyped[input_init1-expected_init1-tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_untyped[None-expected_init2-tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_untyped[input_init3-expected_init3-tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_interpolation[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_optional[BoolOptional-tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_optional[IntegerOptional-tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_optional[FloatOptional-tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_optional[StringOptional-tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_optional[EnumOptional-tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_optional[StructuredOptional-tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_typed_list[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_typed_dict[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_merged_type1[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_merged_type2[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_merged_with_subclass[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_merge_with_subclass_into_missing[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_merged_with_nons_subclass[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_typed_dict_key_error[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_typed_dict_value_error[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_typed_list_value_error[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_list_examples[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_dict_examples[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_enum_key[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_dict_of_objects[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_list_of_objects[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_promote_api[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_promote_to_class[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_promote_to_object[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::test_dataclass_frozen",
"tests/structured_conf/test_structured_config.py::TestDictSubclass::test_str2str[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestDictSubclass::test_str2str_as_sub_node[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestDictSubclass::test_color2str[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestDictSubclass::test_color2color[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestDictSubclass::test_str2user[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestDictSubclass::test_str2str_with_field[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestDictSubclass::test_str2int_with_field_of_different_type[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestDictSubclass::TestErrors::test_usr2str[tests.structured_conf.data.dataclasses]",
"tests/test_merge.py::test_merge[inputs0-expected0]",
"tests/test_merge.py::test_merge[inputs1-expected1]",
"tests/test_merge.py::test_merge[inputs2-expected2]",
"tests/test_merge.py::test_merge[inputs3-expected3]",
"tests/test_merge.py::test_merge[inputs4-expected4]",
"tests/test_merge.py::test_merge[inputs5-expected5]",
"tests/test_merge.py::test_merge[inputs6-expected6]",
"tests/test_merge.py::test_merge[inputs7-expected7]",
"tests/test_merge.py::test_merge[inputs8-expected8]",
"tests/test_merge.py::test_merge[inputs9-expected9]",
"tests/test_merge.py::test_merge[inputs10-expected10]",
"tests/test_merge.py::test_merge[inputs11-expected11]",
"tests/test_merge.py::test_merge[inputs12-expected12]",
"tests/test_merge.py::test_merge[inputs13-expected13]",
"tests/test_merge.py::test_merge[inputs14-expected14]",
"tests/test_merge.py::test_merge[inter:updating_data]",
"tests/test_merge.py::test_merge[inter:value_inter_over_value_inter]",
"tests/test_merge.py::test_merge[inter:data_over_value_inter]",
"tests/test_merge.py::test_merge[inter:node_inter_over_value_inter]",
"tests/test_merge.py::test_merge[inter:inter_over_data]",
"tests/test_merge.py::test_merge[node_inter:node_update]",
"tests/test_merge.py::test_merge[node_inter:value_inter_over_node_inter]",
"tests/test_merge.py::test_merge[node_inter:data_over_node_inter]",
"tests/test_merge.py::test_merge[node_inter:node_inter_over_node_inter]",
"tests/test_merge.py::test_merge[inter:node_inter_over_data]",
"tests/test_merge.py::test_merge[inter:node_over_node_interpolation]",
"tests/test_merge.py::test_merge[inputs26-expected26]",
"tests/test_merge.py::test_merge[inputs27-expected27]",
"tests/test_merge.py::test_merge[inputs28-expected28]",
"tests/test_merge.py::test_merge[inputs29-expected29]",
"tests/test_merge.py::test_merge[inputs30-expected30]",
"tests/test_merge.py::test_merge[inputs31-expected31]",
"tests/test_merge.py::test_merge[inputs32-expected32]",
"tests/test_merge.py::test_merge[inputs33-expected33]",
"tests/test_merge.py::test_merge[inputs34-expected34]",
"tests/test_merge.py::test_merge[users_merge_with_missing_age]",
"tests/test_merge.py::test_merge[conf_missing_dict]",
"tests/test_merge.py::test_merge[merge_missing_dict_into_missing_dict]",
"tests/test_merge.py::test_merge[inputs38-expected38]",
"tests/test_merge.py::test_merge[inputs39-expected39]",
"tests/test_merge.py::test_merge[inputs40-ConcretePlugin]",
"tests/test_merge.py::test_merge[merge_into_missing_node]",
"tests/test_merge.py::test_merge[merge_into_missing_DictConfig]",
"tests/test_merge.py::test_merge[merge_into_missing_Dict[str,str]]",
"tests/test_merge.py::test_merge[merge_into_missing_ListConfig]",
"tests/test_merge.py::test_merge[merge_into_missing_List[str]]",
"tests/test_merge.py::test_merge_error_retains_type",
"tests/test_merge.py::test_primitive_dicts",
"tests/test_merge.py::test_merge_no_eq_verify[a_0-b_0-expected0]",
"tests/test_merge.py::test_merge_with_1",
"tests/test_merge.py::test_merge_with_2",
"tests/test_merge.py::test_3way_dict_merge",
"tests/test_merge.py::test_merge_list_list",
"tests/test_merge.py::test_merge_error[base0-merge0-TypeError]",
"tests/test_merge.py::test_merge_error[base1-merge1-TypeError]",
"tests/test_merge.py::test_merge_error[base2-None-ValueError]",
"tests/test_merge.py::test_merge_error[base3-None-ValueError]",
"tests/test_merge.py::test_with_readonly[c10-c20]",
"tests/test_merge.py::test_with_readonly[c11-c21]",
"tests/test_merge.py::test_into_readonly[c10-c20]",
"tests/test_merge.py::test_into_readonly[c11-c21]",
"tests/test_merge.py::test_parent_maintained"
] | 2020-05-05 01:20:03+00:00 | 4,381 |
|
omry__omegaconf-251 | diff --git a/news/252.bugix b/news/252.bugix
new file mode 100644
index 0000000..3aade21
--- /dev/null
+++ b/news/252.bugix
@@ -0,0 +1,1 @@
+Fix DictConfig created from another DictConfig drops node types
diff --git a/omegaconf/dictconfig.py b/omegaconf/dictconfig.py
index 5499a5b..aef92ee 100644
--- a/omegaconf/dictconfig.py
+++ b/omegaconf/dictconfig.py
@@ -552,7 +552,7 @@ class DictConfig(BaseContainer, MutableMapping[str, Any]):
self._metadata.object_type = get_type_of(value)
elif isinstance(value, DictConfig):
self._metadata.object_type = dict
- for k, v in value.items_ex(resolve=False):
+ for k, v in value.__dict__["_content"].items():
self.__setitem__(k, v)
self.__dict__["_metadata"] = copy.deepcopy(value._metadata)
| omry/omegaconf | 17bdd082345c24bb5c44492a0efda8f1e620b3f7 | diff --git a/tests/structured_conf/test_structured_config.py b/tests/structured_conf/test_structured_config.py
index 73d446d..25b9f73 100644
--- a/tests/structured_conf/test_structured_config.py
+++ b/tests/structured_conf/test_structured_config.py
@@ -800,3 +800,13 @@ class TestDictSubclass:
module: Any = import_module(class_type)
with pytest.raises(KeyValidationError):
OmegaConf.structured(module.DictSubclass.Error.User2Str())
+
+ def test_construct_from_another_retain_node_types(self, class_type: str) -> None:
+ module: Any = import_module(class_type)
+ cfg1 = OmegaConf.create(module.User(name="James Bond", age=7))
+ with pytest.raises(ValidationError):
+ cfg1.age = "not a number"
+
+ cfg2 = OmegaConf.create(cfg1)
+ with pytest.raises(ValidationError):
+ cfg2.age = "not a number"
| Creating a DictConfig from another drops node types
test:
```
@dataclass
class User:
name: str
age: int
cfg1 = OmegaConf.create(module.User(name="James Bond", age=7))
with pytest.raises(ValidationError):
cfg1.age = "not a number"
cfg2 = OmegaConf.create(cfg1)
with pytest.raises(ValidationError):
cfg2.age = "not a number"
``` | 0.0 | [
"tests/structured_conf/test_structured_config.py::TestDictSubclass::test_construct_from_another_retain_node_types[tests.structured_conf.data.dataclasses]"
] | [
"tests/structured_conf/test_structured_config.py::TestConfigs::test_nested_config_is_none[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_nested_config[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_value_without_a_default[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_union_errors[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_config_with_list[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_assignment_to_nested_structured_config[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_assignment_to_structured_inside_dict_config[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_config_with_dict[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_structured_config_struct_behavior[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_field_with_default_value[BoolConfig-BoolConfigAssignments-init_dict0-tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_field_with_default_value[IntegersConfig-IntegersConfigAssignments-init_dict1-tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_field_with_default_value[FloatConfig-FloatConfigAssignments-init_dict2-tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_field_with_default_value[StringConfig-StringConfigAssignments-init_dict3-tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_field_with_default_value[EnumConfig-EnumConfigAssignments-init_dict4-tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_field_with_default_value[BoolConfig-BoolConfigAssignments-init_dict5-tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_field_with_default_value[IntegersConfig-IntegersConfigAssignments-init_dict6-tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_field_with_default_value[FloatConfig-FloatConfigAssignments-init_dict7-tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_field_with_default_value[StringConfig-StringConfigAssignments-init_dict8-tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_field_with_default_value[EnumConfig-EnumConfigAssignments-init_dict9-tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_field_with_default_value[AnyTypeConfig-AnyTypeConfigAssignments-init_dict10-tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_untyped[None-expected_init0-tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_untyped[input_init1-expected_init1-tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_untyped[None-expected_init2-tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_untyped[input_init3-expected_init3-tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_interpolation[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_optional[BoolOptional-tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_optional[IntegerOptional-tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_optional[FloatOptional-tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_optional[StringOptional-tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_optional[EnumOptional-tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_optional[StructuredOptional-tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_typed_list[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_typed_dict[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_merged_type1[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_merged_type2[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_merged_with_subclass[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_merge_with_subclass_into_missing[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_merged_with_nons_subclass[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_merge_into_Dict[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_typed_dict_key_error[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_typed_dict_value_error[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_typed_list_value_error[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_list_examples[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_dict_examples[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_enum_key[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_dict_of_objects[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_list_of_objects[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_promote_api[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_promote_to_class[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestConfigs::test_promote_to_object[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::test_dataclass_frozen",
"tests/structured_conf/test_structured_config.py::TestDictSubclass::test_str2str[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestDictSubclass::test_str2str_as_sub_node[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestDictSubclass::test_color2str[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestDictSubclass::test_color2color[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestDictSubclass::test_str2user[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestDictSubclass::test_str2str_with_field[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestDictSubclass::test_str2int_with_field_of_different_type[tests.structured_conf.data.dataclasses]",
"tests/structured_conf/test_structured_config.py::TestDictSubclass::TestErrors::test_usr2str[tests.structured_conf.data.dataclasses]"
] | 2020-05-12 03:38:50+00:00 | 4,382 |
|
omry__omegaconf-27 | diff --git a/omegaconf/config.py b/omegaconf/config.py
index 25373d8..81461ff 100644
--- a/omegaconf/config.py
+++ b/omegaconf/config.py
@@ -39,10 +39,8 @@ def get_yaml_loader():
class Config(object):
def __init__(self):
- """
- Can't be instantiated
- """
- raise NotImplementedError
+ if type(self) == Config:
+ raise NotImplementedError
def save(self, f):
data = self.pretty()
@@ -138,7 +136,7 @@ class Config(object):
full_key = "{}".format(key)
else:
for parent_key, v in parent.items():
- if v == child:
+ if id(v) == id(child):
if isinstance(child, ListConfig):
full_key = "{}{}".format(parent_key, full_key)
else:
@@ -149,7 +147,7 @@ class Config(object):
full_key = "[{}]".format(key)
else:
for idx, v in enumerate(parent):
- if v == child:
+ if id(v) == id(child):
if isinstance(child, ListConfig):
full_key = "[{}]{}".format(idx, full_key)
else:
@@ -288,12 +286,10 @@ class Config(object):
assert isinstance(conf, Config)
if isinstance(conf, DictConfig):
ret = {}
- for key, value in conf.items():
+ for key, value in conf.items(resolve=resolve):
if isinstance(value, Config):
ret[key] = Config._to_content(value, resolve)
else:
- if resolve:
- value = conf[key]
ret[key] = value
return ret
elif isinstance(conf, ListConfig):
@@ -365,7 +361,7 @@ class Config(object):
# update parents of first level Config nodes to self
assert isinstance(node, (DictConfig, ListConfig))
if isinstance(node, DictConfig):
- for _key, value in node.items():
+ for _key, value in node.items(resolve=False):
if isinstance(value, Config):
value._set_parent(node)
re_parent(value)
@@ -445,11 +441,20 @@ class Config(object):
return isinstance(value, tuple(valid))
@staticmethod
- def _item_eq(v1, v2):
+ def _item_eq(c1, k1, c2, k2):
+ v1 = c1.content[k1]
+ v2 = c2.content[k2]
if isinstance(v1, BaseNode):
v1 = v1.value()
+ if isinstance(v1, str):
+ # noinspection PyProtectedMember
+ v1 = c1._resolve_single(v1)
if isinstance(v2, BaseNode):
v2 = v2.value()
+ if isinstance(v2, str):
+ # noinspection PyProtectedMember
+ v2 = c2._resolve_single(v2)
+
if isinstance(v1, Config) and isinstance(v2, Config):
if not Config._config_eq(v1, v2):
return False
@@ -457,22 +462,22 @@ class Config(object):
@staticmethod
def _list_eq(l1, l2):
- assert isinstance(l1, list)
- assert isinstance(l2, list)
+ from .listconfig import ListConfig
+ assert isinstance(l1, ListConfig)
+ assert isinstance(l2, ListConfig)
if len(l1) != len(l2):
return False
for i in range(len(l1)):
- v1 = l1[i]
- v2 = l2[i]
- if not Config._item_eq(v1, v2):
+ if not Config._item_eq(l1, i, l2, i):
return False
return True
@staticmethod
- def _dict_eq(d1, d2):
- assert isinstance(d1, dict)
- assert isinstance(d2, dict)
+ def _dict_conf_eq(d1, d2):
+ from .dictconfig import DictConfig
+ assert isinstance(d1, DictConfig)
+ assert isinstance(d2, DictConfig)
if len(d1) != len(d2):
return False
k1 = sorted(d1.keys())
@@ -480,9 +485,7 @@ class Config(object):
if k1 != k2:
return False
for k in k1:
- v1 = d1[k]
- v2 = d2[k]
- if not Config._item_eq(v1, v2):
+ if not Config._item_eq(d1, k, d2, k):
return False
return True
@@ -494,8 +497,8 @@ class Config(object):
assert isinstance(c1, Config)
assert isinstance(c2, Config)
if isinstance(c1, DictConfig) and isinstance(c2, DictConfig):
- return Config._dict_eq(c1.content, c2.content)
+ return DictConfig._dict_conf_eq(c1, c2)
if isinstance(c1, ListConfig) and isinstance(c2, ListConfig):
- return Config._list_eq(c1.content, c2.content)
+ return Config._list_eq(c1, c2)
# if type does not match objects are different
return False
diff --git a/omegaconf/dictconfig.py b/omegaconf/dictconfig.py
index a9ad915..cbf0fff 100644
--- a/omegaconf/dictconfig.py
+++ b/omegaconf/dictconfig.py
@@ -7,6 +7,7 @@ import copy
class DictConfig(Config):
def __init__(self, content, parent=None):
+ super(DictConfig, self).__init__()
assert isinstance(content, dict)
self.__dict__['frozen_flag'] = None
self.__dict__['content'] = {}
@@ -84,7 +85,7 @@ class DictConfig(Config):
def __iter__(self):
return iter(self.keys())
- def items(self):
+ def items(self, resolve=True):
class MyItems(object):
def __init__(self, m):
self.map = m
@@ -99,9 +100,12 @@ class DictConfig(Config):
def next(self):
k = next(self.iterator)
- v = self.map.content[k]
- if isinstance(v, BaseNode):
- v = v.value()
+ if resolve:
+ v = self.map.get(k)
+ else:
+ v = self.map.content[k]
+ if isinstance(v, BaseNode):
+ v = v.value()
kv = (k, v)
return kv
@@ -109,9 +113,9 @@ class DictConfig(Config):
def __eq__(self, other):
if isinstance(other, dict):
- return Config._dict_eq(self.content, other)
+ return Config._dict_conf_eq(self, DictConfig(other))
if isinstance(other, DictConfig):
- return Config._dict_eq(self.content, other.content)
+ return Config._dict_conf_eq(self, other)
return NotImplemented
def __ne__(self, other):
diff --git a/omegaconf/listconfig.py b/omegaconf/listconfig.py
index 3352fc4..c274f18 100644
--- a/omegaconf/listconfig.py
+++ b/omegaconf/listconfig.py
@@ -10,6 +10,7 @@ from .nodes import BaseNode, UntypedNode
class ListConfig(Config):
def __init__(self, content, parent=None):
+ super(ListConfig, self).__init__()
assert isinstance(content, (list, tuple))
self.__dict__['frozen_flag'] = None
self.__dict__['content'] = []
@@ -122,9 +123,9 @@ class ListConfig(Config):
def __eq__(self, other):
if isinstance(other, list):
- return Config._list_eq(self.content, other)
+ return Config._list_eq(self, ListConfig(other))
if isinstance(other, ListConfig):
- return Config._list_eq(self.content, other.content)
+ return Config._list_eq(self, other)
return NotImplemented
def __ne__(self, other):
| omry/omegaconf | 28182811dcb36ffa25c69839cb94660c140bece4 | diff --git a/tests/test_basic_ops_dict.py b/tests/test_basic_ops_dict.py
index b90985b..b08f3ce 100644
--- a/tests/test_basic_ops_dict.py
+++ b/tests/test_basic_ops_dict.py
@@ -6,7 +6,7 @@ import pytest
from omegaconf import OmegaConf, DictConfig, Config
from omegaconf import nodes
-from omegaconf.errors import MissingMandatoryValue, FrozenConfigError
+from omegaconf.errors import MissingMandatoryValue
from . import IllegalType
@@ -144,8 +144,27 @@ def test_map_expansion():
def test_items():
- c = OmegaConf.create('{a: 2, b: 10}')
- assert {'a': 2, 'b': 10}.items() == c.items()
+ c = OmegaConf.create(dict(a=2, b=10))
+ assert sorted([('a', 2), ('b', 10)]) == sorted(list(c.items()))
+
+
+def test_items2():
+ c = OmegaConf.create(dict(a=dict(v=1), b=dict(v=1)))
+ for k, v in c.items():
+ v.v = 2
+
+ assert c.a.v == 2
+ assert c.b.v == 2
+
+
+def test_items_with_interpolation():
+ c = OmegaConf.create(
+ dict(
+ a=2,
+ b='${a}'
+ )
+ )
+ assert list({'a': 2, 'b': 2}.items()) == list(c.items())
def test_dict_keys():
@@ -200,15 +219,6 @@ def test_iterate_dictionary():
assert m2 == c
-def test_items():
- c = OmegaConf.create(dict(a=dict(v=1), b=dict(v=1)))
- for k, v in c.items():
- v.v = 2
-
- assert c.a.v == 2
- assert c.b.v == 2
-
-
def test_dict_pop():
c = OmegaConf.create(dict(a=1, b=2))
assert c.pop('a') == 1
@@ -390,6 +400,22 @@ def test_dict_eq(input1, input2):
eq(c2, input2)
[email protected]('input1, input2', [
+ (dict(a=12, b='${a}'), dict(a=12, b=12)),
+])
+def test_dict_eq_with_interpolation(input1, input2):
+ c1 = OmegaConf.create(input1)
+ c2 = OmegaConf.create(input2)
+
+ def eq(a, b):
+ assert a == b
+ assert b == a
+ assert not a != b
+ assert not b != a
+
+ eq(c1, c2)
+
+
@pytest.mark.parametrize('input1, input2', [
(dict(), dict(a=10)),
({}, []),
@@ -424,7 +450,6 @@ def test_dict_not_eq_with_another_class():
assert OmegaConf.create() != "string"
-
def test_hash():
c1 = OmegaConf.create(dict(a=10))
c2 = OmegaConf.create(dict(a=10))
diff --git a/tests/test_basic_ops_list.py b/tests/test_basic_ops_list.py
index 0afeef0..930698c 100644
--- a/tests/test_basic_ops_list.py
+++ b/tests/test_basic_ops_list.py
@@ -62,6 +62,15 @@ def test_iterate_list():
assert items[1] == 2
+def test_items_with_interpolation():
+ c = OmegaConf.create([
+ 'foo',
+ '${0}'
+ ])
+
+ assert c == ['foo', 'foo']
+
+
def test_list_pop():
c = OmegaConf.create([1, 2, 3, 4])
assert c.pop(0) == 1
@@ -267,6 +276,22 @@ def test_list_eq(l1, l2):
eq(c2, l2)
[email protected]('l1,l2', [
+ ([10, '${0}'], [10, 10])
+])
+def test_list_eq_with_interpolation(l1, l2):
+ c1 = OmegaConf.create(l1)
+ c2 = OmegaConf.create(l2)
+
+ def eq(a, b):
+ assert a == b
+ assert b == a
+ assert not a != b
+ assert not b != a
+
+ eq(c1, c2)
+
+
@pytest.mark.parametrize('input1, input2', [
([], [10]),
([10], [11]),
| Iterating on DictConfig with items returns raw values that does not get resolved.
`family, name = next(iter(default.items()))` | 0.0 | [
"tests/test_basic_ops_dict.py::test_items_with_interpolation",
"tests/test_basic_ops_dict.py::test_dict_eq_with_interpolation[input10-input20]",
"tests/test_basic_ops_list.py::test_items_with_interpolation",
"tests/test_basic_ops_list.py::test_list_eq_with_interpolation[l10-l20]"
] | [
"tests/test_basic_ops_dict.py::test_setattr_value",
"tests/test_basic_ops_dict.py::test_setattr_deep_value",
"tests/test_basic_ops_dict.py::test_setattr_deep_from_empty",
"tests/test_basic_ops_dict.py::test_setattr_deep_map",
"tests/test_basic_ops_dict.py::test_getattr",
"tests/test_basic_ops_dict.py::test_getattr_dict",
"tests/test_basic_ops_dict.py::test_str",
"tests/test_basic_ops_dict.py::test_repr_dict",
"tests/test_basic_ops_dict.py::test_is_empty_dict",
"tests/test_basic_ops_dict.py::test_mandatory_value",
"tests/test_basic_ops_dict.py::test_nested_dict_mandatory_value",
"tests/test_basic_ops_dict.py::test_mandatory_with_default",
"tests/test_basic_ops_dict.py::test_subscript_get",
"tests/test_basic_ops_dict.py::test_subscript_set",
"tests/test_basic_ops_dict.py::test_pretty_dict",
"tests/test_basic_ops_dict.py::test_default_value",
"tests/test_basic_ops_dict.py::test_get_default_value",
"tests/test_basic_ops_dict.py::test_scientific_notation_float",
"tests/test_basic_ops_dict.py::test_dict_get_with_default",
"tests/test_basic_ops_dict.py::test_map_expansion",
"tests/test_basic_ops_dict.py::test_items",
"tests/test_basic_ops_dict.py::test_items2",
"tests/test_basic_ops_dict.py::test_dict_keys",
"tests/test_basic_ops_dict.py::test_pickle_get_root",
"tests/test_basic_ops_dict.py::test_iterate_dictionary",
"tests/test_basic_ops_dict.py::test_dict_pop",
"tests/test_basic_ops_dict.py::test_in_dict",
"tests/test_basic_ops_dict.py::test_get_root",
"tests/test_basic_ops_dict.py::test_get_root_of_merged",
"tests/test_basic_ops_dict.py::test_deepcopy",
"tests/test_basic_ops_dict.py::test_dict_config",
"tests/test_basic_ops_dict.py::test_dict_delitem",
"tests/test_basic_ops_dict.py::test_dict_len",
"tests/test_basic_ops_dict.py::test_dict_assign_illegal_value",
"tests/test_basic_ops_dict.py::test_dict_assign_illegal_value_nested",
"tests/test_basic_ops_dict.py::test_assign_dict_in_dict",
"tests/test_basic_ops_dict.py::test_to_container",
"tests/test_basic_ops_dict.py::test_pretty_without_resolve",
"tests/test_basic_ops_dict.py::test_pretty_with_resolve",
"tests/test_basic_ops_dict.py::test_instantiate_config_fails",
"tests/test_basic_ops_dict.py::test_dir",
"tests/test_basic_ops_dict.py::test_dict_eq[input10-input20]",
"tests/test_basic_ops_dict.py::test_dict_eq[input11-input21]",
"tests/test_basic_ops_dict.py::test_dict_eq[input12-input22]",
"tests/test_basic_ops_dict.py::test_dict_eq[input13-input23]",
"tests/test_basic_ops_dict.py::test_dict_eq[input14-input24]",
"tests/test_basic_ops_dict.py::test_dict_eq[input15-input25]",
"tests/test_basic_ops_dict.py::test_dict_eq[input16-input26]",
"tests/test_basic_ops_dict.py::test_dict_not_eq[input10-input20]",
"tests/test_basic_ops_dict.py::test_dict_not_eq[input11-input21]",
"tests/test_basic_ops_dict.py::test_dict_not_eq[input12-input22]",
"tests/test_basic_ops_dict.py::test_dict_not_eq[input13-input23]",
"tests/test_basic_ops_dict.py::test_dict_not_eq[input14-input24]",
"tests/test_basic_ops_dict.py::test_dict_not_eq[input15-input25]",
"tests/test_basic_ops_dict.py::test_dict_not_eq[input16-input26]",
"tests/test_basic_ops_dict.py::test_dict_not_eq[input17-input27]",
"tests/test_basic_ops_dict.py::test_dict_not_eq[input18-input28]",
"tests/test_basic_ops_dict.py::test_config_eq_mismatch_types",
"tests/test_basic_ops_dict.py::test_dict_not_eq_with_another_class",
"tests/test_basic_ops_dict.py::test_hash",
"tests/test_basic_ops_list.py::test_repr_list",
"tests/test_basic_ops_list.py::test_is_empty_list",
"tests/test_basic_ops_list.py::test_list_value",
"tests/test_basic_ops_list.py::test_list_of_dicts",
"tests/test_basic_ops_list.py::test_pretty_list",
"tests/test_basic_ops_list.py::test_list_get_with_default",
"tests/test_basic_ops_list.py::test_iterate_list",
"tests/test_basic_ops_list.py::test_list_pop",
"tests/test_basic_ops_list.py::test_in_list",
"tests/test_basic_ops_list.py::test_list_config_with_list",
"tests/test_basic_ops_list.py::test_list_config_with_tuple",
"tests/test_basic_ops_list.py::test_items_on_list",
"tests/test_basic_ops_list.py::test_list_enumerate",
"tests/test_basic_ops_list.py::test_list_delitem",
"tests/test_basic_ops_list.py::test_list_len",
"tests/test_basic_ops_list.py::test_assign_list_in_list",
"tests/test_basic_ops_list.py::test_assign_dict_in_list",
"tests/test_basic_ops_list.py::test_nested_list_assign_illegal_value",
"tests/test_basic_ops_list.py::test_assign_list_in_dict",
"tests/test_basic_ops_list.py::test_list_append",
"tests/test_basic_ops_list.py::test_to_container",
"tests/test_basic_ops_list.py::test_pretty_without_resolve",
"tests/test_basic_ops_list.py::test_pretty_with_resolve",
"tests/test_basic_ops_list.py::test_index_slice",
"tests/test_basic_ops_list.py::test_index_slice2",
"tests/test_basic_ops_list.py::test_negative_index",
"tests/test_basic_ops_list.py::test_list_dir",
"tests/test_basic_ops_list.py::test_getattr",
"tests/test_basic_ops_list.py::test_setitem",
"tests/test_basic_ops_list.py::test_insert",
"tests/test_basic_ops_list.py::test_sort",
"tests/test_basic_ops_list.py::test_list_eq[l10-l20]",
"tests/test_basic_ops_list.py::test_list_eq[l11-l21]",
"tests/test_basic_ops_list.py::test_list_eq[l12-l22]",
"tests/test_basic_ops_list.py::test_list_eq[l13-l23]",
"tests/test_basic_ops_list.py::test_list_eq[l14-l24]",
"tests/test_basic_ops_list.py::test_list_eq[l15-l25]",
"tests/test_basic_ops_list.py::test_list_eq[l16-l26]",
"tests/test_basic_ops_list.py::test_list_not_eq[input10-input20]",
"tests/test_basic_ops_list.py::test_list_not_eq[input11-input21]",
"tests/test_basic_ops_list.py::test_list_not_eq[input12-input22]",
"tests/test_basic_ops_list.py::test_list_not_eq[input13-input23]",
"tests/test_basic_ops_list.py::test_list_not_eq[input14-input24]",
"tests/test_basic_ops_list.py::test_list_not_eq[input15-input25]",
"tests/test_basic_ops_list.py::test_list_not_eq[input16-input26]",
"tests/test_basic_ops_list.py::test_insert_throws_not_changing_list",
"tests/test_basic_ops_list.py::test_append_throws_not_changing_list",
"tests/test_basic_ops_list.py::test_deepcopy",
"tests/test_basic_ops_list.py::test_hash"
] | 2019-07-31 07:59:19+00:00 | 4,383 |
|
omry__omegaconf-53 | diff --git a/omegaconf/config.py b/omegaconf/config.py
index 0a8995d..a1b3f14 100644
--- a/omegaconf/config.py
+++ b/omegaconf/config.py
@@ -83,6 +83,13 @@ class Config(object):
assert value is None or isinstance(value, bool)
self.__dict__['flags'][flag] = value
+ def _get_node_flag(self, flag):
+ """
+ :param flag: flag to inspect
+ :return: the state of the flag on this node.
+ """
+ return self.__dict__['flags'][flag]
+
def _get_flag(self, flag):
"""
Returns True if this config node flag is set
diff --git a/omegaconf/omegaconf.py b/omegaconf/omegaconf.py
index 03e908b..df3a92b 100644
--- a/omegaconf/omegaconf.py
+++ b/omegaconf/omegaconf.py
@@ -228,7 +228,8 @@ def flag_override(config, name, value):
# noinspection PyProtectedMember
@contextmanager
def read_write(config):
- prev_state = OmegaConf.is_readonly(config)
+ # noinspection PyProtectedMember
+ prev_state = config._get_node_flag("readonly")
try:
OmegaConf.set_readonly(config, False)
yield config
@@ -238,7 +239,8 @@ def read_write(config):
@contextmanager
def open_dict(config):
- prev_state = OmegaConf.is_struct(config)
+ # noinspection PyProtectedMember
+ prev_state = config._get_node_flag("struct")
try:
OmegaConf.set_struct(config, False)
yield config
| omry/omegaconf | db110e3b6effc337fb2dc11fe27b62f24b2f49c2 | diff --git a/tests/test_base_config.py b/tests/test_base_config.py
index 713ff52..b7112ed 100644
--- a/tests/test_base_config.py
+++ b/tests/test_base_config.py
@@ -275,3 +275,19 @@ def test_struct_override(src, func, expectation):
with does_not_raise():
with open_dict(c):
func(c)
+
+
[email protected]("flag_name,ctx", [("struct", open_dict), ("readonly", read_write)])
+def test_open_dict_restore(flag_name, ctx):
+ """
+ Tests that internal flags are restored properly when applying context on a child node
+ """
+ cfg = OmegaConf.create({"foo": {"bar": 10}})
+ cfg._set_flag(flag_name, True)
+ assert cfg._get_node_flag(flag_name)
+ assert not cfg.foo._get_node_flag(flag_name)
+ with ctx(cfg.foo):
+ cfg.foo.bar = 20
+ assert cfg._get_node_flag(flag_name)
+ assert not cfg.foo._get_node_flag(flag_name)
+
| open_dict change value to the inherited value
for a nested config:
```yaml
foo:
bar:
baz: 10
```
if foo is struct, and we do
```python
with open_dict(cfg.foo.bar):
bar.baz = 20
```
the struct flag of foo.bar would be changed to True. | 0.0 | [
"tests/test_base_config.py::test_open_dict_restore[struct-open_dict]",
"tests/test_base_config.py::test_open_dict_restore[readonly-read_write]"
] | [
"tests/test_base_config.py::test_set_value[input_0-foo-10-expected0]",
"tests/test_base_config.py::test_set_value[input_1-foo-value1-expected1]",
"tests/test_base_config.py::test_set_value[input_2-foo-value2-expected2]",
"tests/test_base_config.py::test_set_value[input_3-foo-value3-expected3]",
"tests/test_base_config.py::test_set_value[input_4-0-10-expected4]",
"tests/test_base_config.py::test_set_value[input_5-1-10-expected5]",
"tests/test_base_config.py::test_set_value[input_6-1-value6-expected6]",
"tests/test_base_config.py::test_set_value[input_7-1-value7-expected7]",
"tests/test_base_config.py::test_set_value[input_8-1-value8-expected8]",
"tests/test_base_config.py::test_set_value_validation_fail[input_0-foo-str]",
"tests/test_base_config.py::test_set_value_validation_fail[input_1-1-str]",
"tests/test_base_config.py::test_to_container_returns_primitives[input_0]",
"tests/test_base_config.py::test_to_container_returns_primitives[input_1]",
"tests/test_base_config.py::test_to_container_returns_primitives[input_2]",
"tests/test_base_config.py::test_to_container_returns_primitives[input_3]",
"tests/test_base_config.py::test_to_container_returns_primitives[input_4]",
"tests/test_base_config.py::test_empty[input_0-True]",
"tests/test_base_config.py::test_empty[input_1-True]",
"tests/test_base_config.py::test_empty[input_2-False]",
"tests/test_base_config.py::test_empty[input_3-False]",
"tests/test_base_config.py::test_repr[input_0]",
"tests/test_base_config.py::test_repr[input_1]",
"tests/test_base_config.py::test_repr[input_2]",
"tests/test_base_config.py::test_repr[input_3]",
"tests/test_base_config.py::test_repr[input_4]",
"tests/test_base_config.py::test_repr[input_5]",
"tests/test_base_config.py::test_repr[input_6]",
"tests/test_base_config.py::test_str[input_0]",
"tests/test_base_config.py::test_str[input_1]",
"tests/test_base_config.py::test_str[input_2]",
"tests/test_base_config.py::test_str[input_3]",
"tests/test_base_config.py::test_str[input_4]",
"tests/test_base_config.py::test_str[input_5]",
"tests/test_base_config.py::test_str[input_6]",
"tests/test_base_config.py::test_flag_dict[readonly]",
"tests/test_base_config.py::test_flag_dict[struct]",
"tests/test_base_config.py::test_freeze_nested_dict[readonly]",
"tests/test_base_config.py::test_freeze_nested_dict[struct]",
"tests/test_base_config.py::test_deepcopy[src0]",
"tests/test_base_config.py::test_deepcopy[src1]",
"tests/test_base_config.py::test_deepcopy[src2]",
"tests/test_base_config.py::test_deepcopy[src3]",
"tests/test_base_config.py::test_deepcopy_readonly[src0]",
"tests/test_base_config.py::test_deepcopy_readonly[src1]",
"tests/test_base_config.py::test_deepcopy_readonly[src2]",
"tests/test_base_config.py::test_deepcopy_readonly[src3]",
"tests/test_base_config.py::test_deepcopy_struct[src0]",
"tests/test_base_config.py::test_deepcopy_struct[src1]",
"tests/test_base_config.py::test_deepcopy_struct[src2]",
"tests/test_base_config.py::test_deepcopy_struct[src3]",
"tests/test_base_config.py::test_deepcopy_after_del",
"tests/test_base_config.py::test_deepcopy_with_interpolation",
"tests/test_base_config.py::test_deepcopy_and_merge_and_flags",
"tests/test_base_config.py::test_flag_override[src0-struct-False-<lambda>-expectation0]",
"tests/test_base_config.py::test_flag_override[src1-readonly-False-<lambda>-expectation1]",
"tests/test_base_config.py::test_read_write_override[src0-<lambda>-expectation0]",
"tests/test_base_config.py::test_read_write_override[src1-<lambda>-expectation1]",
"tests/test_base_config.py::test_tokenize_with_escapes[dog,cat-tokenized0]",
"tests/test_base_config.py::test_tokenize_with_escapes[dog\\\\,cat\\\\",
"tests/test_base_config.py::test_tokenize_with_escapes[dog,\\\\",
"tests/test_base_config.py::test_tokenize_with_escapes[\\\\",
"tests/test_base_config.py::test_tokenize_with_escapes[dog,",
"tests/test_base_config.py::test_tokenize_with_escapes[whitespace\\\\",
"tests/test_base_config.py::test_tokenize_with_escapes[None-tokenized8]",
"tests/test_base_config.py::test_tokenize_with_escapes[-tokenized9]",
"tests/test_base_config.py::test_tokenize_with_escapes[no",
"tests/test_base_config.py::test_struct_override[src0-<lambda>-expectation0]"
] | 2019-11-05 09:00:30+00:00 | 4,384 |
|
omry__omegaconf-57 | diff --git a/omegaconf/config.py b/omegaconf/config.py
index 6b53109..3c80734 100644
--- a/omegaconf/config.py
+++ b/omegaconf/config.py
@@ -244,12 +244,15 @@ class Config(object):
def merge_with_dotlist(self, dotlist):
for arg in dotlist:
- args = arg.split("=")
- key = args[0]
- value = None
- if len(args) > 1:
- # load with yaml to get correct automatic typing with the same rules as yaml parsing
- value = yaml.load(args[1], Loader=get_yaml_loader())
+ idx = arg.find("=")
+ if idx == -1:
+ key = arg
+ value = None
+ else:
+ key = arg[0:idx]
+ value = arg[idx + 1 :]
+ value = yaml.load(value, Loader=get_yaml_loader())
+
self.update(key, value)
def update(self, key, value=None):
| omry/omegaconf | db6f59569e541db940b8042e82b97b572138b031 | diff --git a/tests/test_update.py b/tests/test_update.py
index 0ade637..12fcacf 100644
--- a/tests/test_update.py
+++ b/tests/test_update.py
@@ -1,5 +1,6 @@
import sys
+import pytest
from pytest import raises
from omegaconf import MissingMandatoryValue
@@ -154,10 +155,18 @@ def test_update_list_make_dict():
assert c[1].b.b == "bb"
-def test_merge_with_dotlist():
- c = OmegaConf.create([1, 2, 3])
- c.merge_with_dotlist(["0=bar", "2.a=100"])
- assert c == ["bar", 2, dict(a=100)]
[email protected](
+ "cfg,overrides,expected",
+ [
+ ([1, 2, 3], ["0=bar", "2.a=100"], ["bar", 2, dict(a=100)]),
+ ({}, ["foo=bar", "bar=100"], {"foo": "bar", "bar": 100}),
+ ({}, ["foo=bar=10"], {"foo": "bar=10"}),
+ ],
+)
+def test_merge_with_dotlist(cfg, overrides, expected):
+ c = OmegaConf.create(cfg)
+ c.merge_with_dotlist(overrides)
+ assert c == expected
def test_merge_with_cli():
| Handle dotlist override with values containing =
See https://github.com/facebookresearch/hydra/issues/266 (Which is actually one bug in Hydra and one in OmegaConf). | 0.0 | [
"tests/test_update.py::test_merge_with_dotlist[cfg2-overrides2-expected2]"
] | [
"tests/test_update.py::test_update_map_value",
"tests/test_update.py::test_update_map_new_keyvalue",
"tests/test_update.py::test_update_map_to_value",
"tests/test_update.py::test_update_with_empty_map_value",
"tests/test_update.py::test_update_with_map_value",
"tests/test_update.py::test_update_deep_from_empty",
"tests/test_update.py::test_update_deep_with_map",
"tests/test_update.py::test_update_deep_with_value",
"tests/test_update.py::test_update_deep_with_map2",
"tests/test_update.py::test_update_deep_with_map_update",
"tests/test_update.py::test_list_value_update",
"tests/test_update.py::test_override_mandatory_value",
"tests/test_update.py::test_update_empty_to_value",
"tests/test_update.py::test_update_same_value",
"tests/test_update.py::test_update_value_to_map",
"tests/test_update.py::test_update_map_empty_to_map",
"tests/test_update.py::test_update_list",
"tests/test_update.py::test_update_nested_list",
"tests/test_update.py::test_update_list_make_dict",
"tests/test_update.py::test_merge_with_dotlist[cfg0-overrides0-expected0]",
"tests/test_update.py::test_merge_with_dotlist[cfg1-overrides1-expected1]",
"tests/test_update.py::test_merge_with_cli"
] | 2019-11-06 00:57:55+00:00 | 4,385 |
|
omry__omegaconf-64 | diff --git a/omegaconf/listconfig.py b/omegaconf/listconfig.py
index 6969aab..d2696b5 100644
--- a/omegaconf/listconfig.py
+++ b/omegaconf/listconfig.py
@@ -207,3 +207,10 @@ class ListConfig(Config):
return v
return MyItems(self.content)
+
+ def __add__(self, o):
+ # res is sharing this list's parent to allow interpolation to work as expected
+ res = ListConfig(parent=self.__dict__["parent"], content=[])
+ res.extend(self)
+ res.extend(o)
+ return res
| omry/omegaconf | 94d59d0090d4503540e92c1da19781fbe1995061 | diff --git a/tests/test_basic_ops_list.py b/tests/test_basic_ops_list.py
index a97aecb..d2e5a86 100644
--- a/tests/test_basic_ops_list.py
+++ b/tests/test_basic_ops_list.py
@@ -373,3 +373,27 @@ def test_hash():
assert hash(c1) == hash(c2)
c2[0] = 20
assert hash(c1) != hash(c2)
+
+
[email protected](
+ "list1, list2, expected",
+ [
+ ([], [], []),
+ ([1, 2], [3, 4], [1, 2, 3, 4]),
+ (["x", 2, "${0}"], [5, 6, 7], ["x", 2, "x", 5, 6, 7]),
+ ],
+)
+class TestListAdd:
+ def test_list_plus(self, list1, list2, expected):
+ list1 = OmegaConf.create(list1)
+ list2 = OmegaConf.create(list2)
+ expected = OmegaConf.create(expected)
+ ret = list1 + list2
+ assert ret == expected
+
+ def test_list_plus_eq(self, list1, list2, expected):
+ list1 = OmegaConf.create(list1)
+ list2 = OmegaConf.create(list2)
+ expected = OmegaConf.create(expected)
+ list1 += list2
+ assert list1 == expected
| consider implementing + operator for ListConfig | 0.0 | [
"tests/test_basic_ops_list.py::TestListAdd::test_list_plus[list10-list20-expected0]",
"tests/test_basic_ops_list.py::TestListAdd::test_list_plus[list11-list21-expected1]",
"tests/test_basic_ops_list.py::TestListAdd::test_list_plus[list12-list22-expected2]",
"tests/test_basic_ops_list.py::TestListAdd::test_list_plus_eq[list10-list20-expected0]",
"tests/test_basic_ops_list.py::TestListAdd::test_list_plus_eq[list11-list21-expected1]",
"tests/test_basic_ops_list.py::TestListAdd::test_list_plus_eq[list12-list22-expected2]"
] | [
"tests/test_basic_ops_list.py::test_list_value",
"tests/test_basic_ops_list.py::test_list_of_dicts",
"tests/test_basic_ops_list.py::test_pretty_list",
"tests/test_basic_ops_list.py::test_list_get_with_default",
"tests/test_basic_ops_list.py::test_iterate_list",
"tests/test_basic_ops_list.py::test_items_with_interpolation",
"tests/test_basic_ops_list.py::test_list_pop",
"tests/test_basic_ops_list.py::test_in_list",
"tests/test_basic_ops_list.py::test_list_config_with_list",
"tests/test_basic_ops_list.py::test_list_config_with_tuple",
"tests/test_basic_ops_list.py::test_items_on_list",
"tests/test_basic_ops_list.py::test_list_enumerate",
"tests/test_basic_ops_list.py::test_list_delitem",
"tests/test_basic_ops_list.py::test_list_len",
"tests/test_basic_ops_list.py::test_assign_list_in_list",
"tests/test_basic_ops_list.py::test_assign_dict_in_list",
"tests/test_basic_ops_list.py::test_nested_list_assign_illegal_value",
"tests/test_basic_ops_list.py::test_assign_list_in_dict",
"tests/test_basic_ops_list.py::test_list_append",
"tests/test_basic_ops_list.py::test_pretty_without_resolve",
"tests/test_basic_ops_list.py::test_pretty_with_resolve",
"tests/test_basic_ops_list.py::test_index_slice",
"tests/test_basic_ops_list.py::test_index_slice2",
"tests/test_basic_ops_list.py::test_negative_index",
"tests/test_basic_ops_list.py::test_list_dir",
"tests/test_basic_ops_list.py::test_getattr",
"tests/test_basic_ops_list.py::test_insert",
"tests/test_basic_ops_list.py::test_extend[src0-append0-result0]",
"tests/test_basic_ops_list.py::test_extend[src1-append1-result1]",
"tests/test_basic_ops_list.py::test_extend[src2-append2-result2]",
"tests/test_basic_ops_list.py::test_remove[src0-10-result0-expectation0]",
"tests/test_basic_ops_list.py::test_remove[src1-oops-None-expectation1]",
"tests/test_basic_ops_list.py::test_remove[src2-remove2-result2-expectation2]",
"tests/test_basic_ops_list.py::test_remove[src3-2-result3-expectation3]",
"tests/test_basic_ops_list.py::test_clear[1-src0]",
"tests/test_basic_ops_list.py::test_clear[1-src1]",
"tests/test_basic_ops_list.py::test_clear[1-src2]",
"tests/test_basic_ops_list.py::test_clear[2-src0]",
"tests/test_basic_ops_list.py::test_clear[2-src1]",
"tests/test_basic_ops_list.py::test_clear[2-src2]",
"tests/test_basic_ops_list.py::test_index[src0-20--1-expectation0]",
"tests/test_basic_ops_list.py::test_index[src1-10-0-expectation1]",
"tests/test_basic_ops_list.py::test_index[src2-20-1-expectation2]",
"tests/test_basic_ops_list.py::test_count[src0-10-0]",
"tests/test_basic_ops_list.py::test_count[src1-10-1]",
"tests/test_basic_ops_list.py::test_count[src2-10-2]",
"tests/test_basic_ops_list.py::test_count[src3-None-0]",
"tests/test_basic_ops_list.py::test_copy[src0]",
"tests/test_basic_ops_list.py::test_copy[src1]",
"tests/test_basic_ops_list.py::test_copy[src2]",
"tests/test_basic_ops_list.py::test_sort",
"tests/test_basic_ops_list.py::test_list_eq[l10-l20]",
"tests/test_basic_ops_list.py::test_list_eq[l11-l21]",
"tests/test_basic_ops_list.py::test_list_eq[l12-l22]",
"tests/test_basic_ops_list.py::test_list_eq[l13-l23]",
"tests/test_basic_ops_list.py::test_list_eq[l14-l24]",
"tests/test_basic_ops_list.py::test_list_eq[l15-l25]",
"tests/test_basic_ops_list.py::test_list_eq[l16-l26]",
"tests/test_basic_ops_list.py::test_list_eq_with_interpolation[l10-l20]",
"tests/test_basic_ops_list.py::test_list_not_eq[input10-input20]",
"tests/test_basic_ops_list.py::test_list_not_eq[input11-input21]",
"tests/test_basic_ops_list.py::test_list_not_eq[input12-input22]",
"tests/test_basic_ops_list.py::test_list_not_eq[input13-input23]",
"tests/test_basic_ops_list.py::test_list_not_eq[input14-input24]",
"tests/test_basic_ops_list.py::test_list_not_eq[input15-input25]",
"tests/test_basic_ops_list.py::test_list_not_eq[input16-input26]",
"tests/test_basic_ops_list.py::test_insert_throws_not_changing_list",
"tests/test_basic_ops_list.py::test_append_throws_not_changing_list",
"tests/test_basic_ops_list.py::test_hash"
] | 2019-11-07 08:08:41+00:00 | 4,386 |
|
omry__omegaconf-76 | diff --git a/news/40.bugfix b/news/40.bugfix
new file mode 100644
index 0000000..8163863
--- /dev/null
+++ b/news/40.bugfix
@@ -0,0 +1,1 @@
+Fix an error when expanding an empty dictionary in PyCharm debugger
diff --git a/omegaconf/dictconfig.py b/omegaconf/dictconfig.py
index 5b35776..9f81527 100644
--- a/omegaconf/dictconfig.py
+++ b/omegaconf/dictconfig.py
@@ -68,6 +68,10 @@ class DictConfig(Config):
:param key:
:return:
"""
+ # PyCharm is sometimes inspecting __members__. returning None or throwing is
+ # confusing it and it prints an error when inspecting this object.
+ if key == "__members__":
+ return {}
return self.get(key=key, default_value=None)
def __getitem__(self, key):
| omry/omegaconf | 6c581705d7baec14f8702ba5f02aa2e1803fc1b2 | diff --git a/tests/test_basic_ops_dict.py b/tests/test_basic_ops_dict.py
index 55af782..d968908 100644
--- a/tests/test_basic_ops_dict.py
+++ b/tests/test_basic_ops_dict.py
@@ -391,3 +391,9 @@ def test_get_with_default_from_struct_not_throwing():
c = OmegaConf.create(dict(a=10, b=20))
OmegaConf.set_struct(c, True)
assert c.get("z", "default") == "default"
+
+
+def test_members():
+ # Make sure accessing __members__ does not return None or throw.
+ c = OmegaConf.create({"foo": {}})
+ assert c.__members__ == {}
| Error expanding an DictConfig in pycharm debugger
OmegaConf.create(dict(foo={}))
expanding foo results in a stack trace in the debugger.
| 0.0 | [
"tests/test_basic_ops_dict.py::test_members"
] | [
"tests/test_basic_ops_dict.py::test_setattr_deep_value",
"tests/test_basic_ops_dict.py::test_setattr_deep_from_empty",
"tests/test_basic_ops_dict.py::test_setattr_deep_map",
"tests/test_basic_ops_dict.py::test_getattr",
"tests/test_basic_ops_dict.py::test_getattr_dict",
"tests/test_basic_ops_dict.py::test_mandatory_value",
"tests/test_basic_ops_dict.py::test_nested_dict_mandatory_value",
"tests/test_basic_ops_dict.py::test_mandatory_with_default",
"tests/test_basic_ops_dict.py::test_subscript_get",
"tests/test_basic_ops_dict.py::test_subscript_set",
"tests/test_basic_ops_dict.py::test_pretty_dict",
"tests/test_basic_ops_dict.py::test_default_value",
"tests/test_basic_ops_dict.py::test_get_default_value",
"tests/test_basic_ops_dict.py::test_scientific_notation_float",
"tests/test_basic_ops_dict.py::test_dict_get_with_default",
"tests/test_basic_ops_dict.py::test_map_expansion",
"tests/test_basic_ops_dict.py::test_items",
"tests/test_basic_ops_dict.py::test_items2",
"tests/test_basic_ops_dict.py::test_items_with_interpolation",
"tests/test_basic_ops_dict.py::test_dict_keys",
"tests/test_basic_ops_dict.py::test_pickle_get_root",
"tests/test_basic_ops_dict.py::test_iterate_dictionary",
"tests/test_basic_ops_dict.py::test_dict_pop",
"tests/test_basic_ops_dict.py::test_in_dict[conf0-a-True]",
"tests/test_basic_ops_dict.py::test_in_dict[conf1-b-True]",
"tests/test_basic_ops_dict.py::test_in_dict[conf2-c-False]",
"tests/test_basic_ops_dict.py::test_in_dict[conf3-b-True]",
"tests/test_basic_ops_dict.py::test_in_dict[conf4-b-False]",
"tests/test_basic_ops_dict.py::test_in_dict[conf5-c-False]",
"tests/test_basic_ops_dict.py::test_in_dict[conf6-b-False]",
"tests/test_basic_ops_dict.py::test_in_dict[conf7-a-True]",
"tests/test_basic_ops_dict.py::test_get_root",
"tests/test_basic_ops_dict.py::test_get_root_of_merged",
"tests/test_basic_ops_dict.py::test_dict_config",
"tests/test_basic_ops_dict.py::test_dict_delitem",
"tests/test_basic_ops_dict.py::test_dict_len",
"tests/test_basic_ops_dict.py::test_dict_assign_illegal_value",
"tests/test_basic_ops_dict.py::test_dict_assign_illegal_value_nested",
"tests/test_basic_ops_dict.py::test_assign_dict_in_dict",
"tests/test_basic_ops_dict.py::test_to_container",
"tests/test_basic_ops_dict.py::test_pretty_without_resolve",
"tests/test_basic_ops_dict.py::test_pretty_with_resolve",
"tests/test_basic_ops_dict.py::test_instantiate_config_fails",
"tests/test_basic_ops_dict.py::test_dir",
"tests/test_basic_ops_dict.py::test_dict_eq[input10-input20]",
"tests/test_basic_ops_dict.py::test_dict_eq[input11-input21]",
"tests/test_basic_ops_dict.py::test_dict_eq[input12-input22]",
"tests/test_basic_ops_dict.py::test_dict_eq[input13-input23]",
"tests/test_basic_ops_dict.py::test_dict_eq[input14-input24]",
"tests/test_basic_ops_dict.py::test_dict_eq[input15-input25]",
"tests/test_basic_ops_dict.py::test_dict_eq[input16-input26]",
"tests/test_basic_ops_dict.py::test_dict_eq[input17-input27]",
"tests/test_basic_ops_dict.py::test_dict_eq_with_interpolation[input10-input20]",
"tests/test_basic_ops_dict.py::test_dict_not_eq[input10-input20]",
"tests/test_basic_ops_dict.py::test_dict_not_eq[input11-input21]",
"tests/test_basic_ops_dict.py::test_dict_not_eq[input12-input22]",
"tests/test_basic_ops_dict.py::test_dict_not_eq[input13-input23]",
"tests/test_basic_ops_dict.py::test_dict_not_eq[input14-input24]",
"tests/test_basic_ops_dict.py::test_dict_not_eq[input15-input25]",
"tests/test_basic_ops_dict.py::test_dict_not_eq[input16-input26]",
"tests/test_basic_ops_dict.py::test_dict_not_eq[input17-input27]",
"tests/test_basic_ops_dict.py::test_dict_not_eq[input18-input28]",
"tests/test_basic_ops_dict.py::test_config_eq_mismatch_types",
"tests/test_basic_ops_dict.py::test_dict_not_eq_with_another_class",
"tests/test_basic_ops_dict.py::test_hash",
"tests/test_basic_ops_dict.py::test_get_with_default_from_struct_not_throwing"
] | 2019-11-09 22:57:28+00:00 | 4,387 |
|
omry__omegaconf-83 | diff --git a/omegaconf/dictconfig.py b/omegaconf/dictconfig.py
index 7c180f8..808a687 100644
--- a/omegaconf/dictconfig.py
+++ b/omegaconf/dictconfig.py
@@ -1,4 +1,5 @@
from .config import Config
+import copy
from .errors import (
ReadonlyConfigError,
MissingMandatoryValue,
@@ -21,6 +22,15 @@ class DictConfig(Config):
self._deepcopy_impl(res)
return res
+ def __copy__(self):
+ res = DictConfig({})
+ res.__dict__["content"] = copy.copy(self.__dict__["content"])
+ res.__dict__["parent"] = self.__dict__["parent"]
+ return res
+
+ def copy(self):
+ return copy.copy(self)
+
def __setitem__(self, key, value):
assert isinstance(key, str)
diff --git a/omegaconf/listconfig.py b/omegaconf/listconfig.py
index 993ba31..3d56753 100644
--- a/omegaconf/listconfig.py
+++ b/omegaconf/listconfig.py
@@ -121,7 +121,7 @@ class ListConfig(Config):
return c
def copy(self):
- return self[:]
+ return copy.copy(self)
if six.PY2:
| omry/omegaconf | 3c1859c62891924d5f95b266eb8d377b996df276 | diff --git a/tests/test_base_config.py b/tests/test_base_config.py
index a35f714..747b4e4 100644
--- a/tests/test_base_config.py
+++ b/tests/test_base_config.py
@@ -332,3 +332,45 @@ def test_open_dict_restore(flag_name, ctx):
cfg.foo.bar = 20
assert cfg._get_node_flag(flag_name)
assert not cfg.foo._get_node_flag(flag_name)
+
+
[email protected](
+ "copy_method", [lambda x: copy.copy(x), lambda x: x.copy()],
+)
+class TestCopy:
+ @pytest.mark.parametrize(
+ "src", [[], [1, 2], ["a", "b", "c"], {}, {"a": "b"}, {"a": {"b": []}}],
+ )
+ def test_copy(self, copy_method, src):
+ src = OmegaConf.create(src)
+ cp = copy_method(src)
+ assert id(src) != id(cp)
+ assert src == cp
+
+ @pytest.mark.parametrize(
+ "src,interpolating_key,interpolated_key",
+ [([1, 2, "${0}"], 2, 0), ({"a": 10, "b": "${a}"}, "b", "a")],
+ )
+ def test_copy_with_interpolation(
+ self, copy_method, src, interpolating_key, interpolated_key
+ ):
+ cfg = OmegaConf.create(src)
+ assert cfg[interpolated_key] == cfg[interpolating_key]
+ cp = copy_method(cfg)
+ assert id(cfg) != id(cp)
+ assert cp[interpolated_key] == cp[interpolating_key]
+ assert cfg[interpolated_key] == cp[interpolating_key]
+
+ # Interpolation is preserved in original
+ cfg[interpolated_key] = "XXX"
+ assert cfg[interpolated_key] == cfg[interpolating_key]
+
+ # Test interpolation is preserved in copy
+ cp[interpolated_key] = "XXX"
+ assert cp[interpolated_key] == cp[interpolating_key]
+
+ def test_list_copy_is_shallow(self, copy_method):
+ cfg = OmegaConf.create([[10, 20]])
+ cp = copy_method(cfg)
+ assert id(cfg) != id(cp)
+ assert id(cfg[0]) == id(cp[0])
diff --git a/tests/test_basic_ops_list.py b/tests/test_basic_ops_list.py
index 9060228..32ec4db 100644
--- a/tests/test_basic_ops_list.py
+++ b/tests/test_basic_ops_list.py
@@ -252,14 +252,6 @@ def test_count(src, item, count):
assert src.count(item) == count
[email protected]("src", [[], [1, 2], ["a", "b", "c"]])
-def test_copy(src):
- src = OmegaConf.create(src)
- cp = src.copy()
- assert id(src) != id(cp)
- assert src == cp
-
-
def test_sort():
c = OmegaConf.create(["bbb", "aa", "c"])
c.sort()
| OmegaConf object doesn't support a .copy method
A dict is supposed to have a .copy() method (https://docs.python.org/3/library/stdtypes.html#dict.copy). For an OmegaConf object to be compatible with a dict's API, it should also support the copy() method -
```
>>> from omegaconf import OmegaConf
>>> conf = OmegaConf.create({"a": 2, "b": [1,2,3]})
>>> conf
{'a': 2, 'b': [1, 2, 3]}
>>> conf.copy()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not callable
``` | 0.0 | [
"tests/test_base_config.py::TestCopy::test_copy[src4-<lambda>1]",
"tests/test_base_config.py::TestCopy::test_copy_with_interpolation[src0-2-0-<lambda>1]",
"tests/test_base_config.py::TestCopy::test_copy_with_interpolation[src1-b-a-<lambda>1]",
"tests/test_base_config.py::TestCopy::test_copy[src3-<lambda>1]",
"tests/test_base_config.py::TestCopy::test_copy[src5-<lambda>1]"
] | [
"tests/test_base_config.py::TestCopy::test_copy[src2-<lambda>0]",
"tests/test_base_config.py::TestCopy::test_copy[src1-<lambda>0]",
"tests/test_base_config.py::TestCopy::test_copy_with_interpolation[src1-b-a-<lambda>0]",
"tests/test_base_config.py::TestCopy::test_copy[src2-<lambda>1]",
"tests/test_base_config.py::TestCopy::test_copy[src0-<lambda>0]",
"tests/test_base_config.py::TestCopy::test_list_copy_is_shallow[<lambda>0]",
"tests/test_base_config.py::TestCopy::test_copy[src5-<lambda>0]",
"tests/test_base_config.py::TestCopy::test_copy[src3-<lambda>0]",
"tests/test_base_config.py::TestCopy::test_copy_with_interpolation[src0-2-0-<lambda>0]",
"tests/test_base_config.py::TestCopy::test_copy[src4-<lambda>0]",
"tests/test_base_config.py::TestCopy::test_copy[src0-<lambda>1]",
"tests/test_base_config.py::TestCopy::test_copy[src1-<lambda>1]",
"tests/test_base_config.py::TestCopy::test_list_copy_is_shallow[<lambda>1]",
"tests/test_base_config.py::test_tokenize_with_escapes[-tokenized9]",
"tests/test_base_config.py::test_str[input_6]",
"tests/test_base_config.py::test_repr[input_6]",
"tests/test_base_config.py::test_tokenize_with_escapes[whitespace\\\\",
"tests/test_base_config.py::test_set_value[input_1-foo-value1-expected1]",
"tests/test_base_config.py::test_deepcopy_struct[src0]",
"tests/test_base_config.py::test_repr[input_4]",
"tests/test_base_config.py::test_str[input_2]",
"tests/test_base_config.py::test_deepcopy_struct[src3]",
"tests/test_base_config.py::test_set_value[input_4-0-10-expected4]",
"tests/test_base_config.py::test_tokenize_with_escapes[None-tokenized8]",
"tests/test_base_config.py::test_set_value[input_0-foo-10-expected0]",
"tests/test_base_config.py::test_deepcopy[src2]",
"tests/test_base_config.py::test_tokenize_with_escapes[dog,",
"tests/test_base_config.py::test_tokenize_with_escapes[dog,cat-tokenized0]",
"tests/test_base_config.py::test_set_value[input_5-1-10-expected5]",
"tests/test_base_config.py::test_open_dict_restore[readonly-read_write]",
"tests/test_base_config.py::test_read_write_override[src1-<lambda>-expectation1]",
"tests/test_base_config.py::test_set_value_validation_fail[input_0-foo-str]",
"tests/test_base_config.py::test_deepcopy_after_del",
"tests/test_base_config.py::test_tokenize_with_escapes[dog\\\\,cat\\\\",
"tests/test_base_config.py::test_str[input_5]",
"tests/test_base_config.py::test_set_value[input_6-1-value6-expected6]",
"tests/test_base_config.py::test_repr[input_3]",
"tests/test_base_config.py::test_set_value[input_7-1-value7-expected7]",
"tests/test_base_config.py::test_flag_override[src0-struct-False-<lambda>-expectation0]",
"tests/test_base_config.py::test_to_container_returns_primitives[input_0]",
"tests/test_base_config.py::test_set_value[input_3-foo-value3-expected3]",
"tests/test_base_config.py::test_tokenize_with_escapes[\\\\",
"tests/test_base_config.py::test_deepcopy_struct[src1]",
"tests/test_base_config.py::test_deepcopy_with_interpolation",
"tests/test_base_config.py::test_set_value[input_8-1-value8-expected8]",
"tests/test_base_config.py::test_freeze_nested_dict[struct]",
"tests/test_base_config.py::test_tokenize_with_escapes[dog,\\\\",
"tests/test_base_config.py::test_empty[input_0-True]",
"tests/test_base_config.py::test_struct_override[src0-<lambda>-expectation0]",
"tests/test_base_config.py::test_str[input_4]",
"tests/test_base_config.py::test_str[input_1]",
"tests/test_base_config.py::test_deepcopy[src3]",
"tests/test_base_config.py::test_flag_override[src1-readonly-False-<lambda>-expectation1]",
"tests/test_base_config.py::test_freeze_nested_dict[readonly]",
"tests/test_base_config.py::test_to_container_returns_primitives[input_1]",
"tests/test_base_config.py::test_to_container_returns_primitives[input_2]",
"tests/test_base_config.py::test_flag_dict[struct]",
"tests/test_base_config.py::test_repr[input_1]",
"tests/test_base_config.py::test_deepcopy_readonly[src3]",
"tests/test_base_config.py::test_deepcopy_readonly[src0]",
"tests/test_base_config.py::test_repr[input_5]",
"tests/test_base_config.py::test_flag_dict[readonly]",
"tests/test_base_config.py::test_deepcopy_struct[src2]",
"tests/test_base_config.py::test_str[input_0]",
"tests/test_base_config.py::test_deepcopy[src0]",
"tests/test_base_config.py::test_str[input_3]",
"tests/test_base_config.py::test_deepcopy_and_merge_and_flags",
"tests/test_base_config.py::test_deepcopy_readonly[src2]",
"tests/test_base_config.py::test_tokenize_with_escapes[no",
"tests/test_base_config.py::test_repr[input_2]",
"tests/test_base_config.py::test_empty[input_3-False]",
"tests/test_base_config.py::test_repr[input_0]",
"tests/test_base_config.py::test_empty[input_2-False]",
"tests/test_base_config.py::test_empty[input_1-True]",
"tests/test_base_config.py::test_set_value_validation_fail[input_1-1-str]",
"tests/test_base_config.py::test_set_value[input_2-foo-value2-expected2]",
"tests/test_base_config.py::test_to_container_returns_primitives[input_3]",
"tests/test_base_config.py::test_open_dict_restore[struct-open_dict]",
"tests/test_base_config.py::test_to_container_returns_primitives[input_4]",
"tests/test_base_config.py::test_deepcopy_readonly[src1]",
"tests/test_base_config.py::test_read_write_override[src0-<lambda>-expectation0]",
"tests/test_base_config.py::test_deepcopy[src1]",
"tests/test_basic_ops_list.py::TestListAdd::test_list_plus[list10-list20-expected0]",
"tests/test_basic_ops_list.py::TestListAdd::test_list_plus_eq[list11-list21-expected1]",
"tests/test_basic_ops_list.py::TestListAdd::test_list_plus[list12-list22-expected2]",
"tests/test_basic_ops_list.py::TestListAdd::test_list_plus_eq[list10-list20-expected0]",
"tests/test_basic_ops_list.py::TestListAdd::test_list_plus_eq[list12-list22-expected2]",
"tests/test_basic_ops_list.py::TestListAdd::test_list_plus[list11-list21-expected1]",
"tests/test_basic_ops_list.py::test_insert_throws_not_changing_list",
"tests/test_basic_ops_list.py::test_index[src1-10-0-expectation1]",
"tests/test_basic_ops_list.py::test_pretty_list",
"tests/test_basic_ops_list.py::test_list_config_with_list",
"tests/test_basic_ops_list.py::test_list_not_eq[input12-input22]",
"tests/test_basic_ops_list.py::test_list_pop",
"tests/test_basic_ops_list.py::test_list_not_eq[input15-input25]",
"tests/test_basic_ops_list.py::test_list_config_with_tuple",
"tests/test_basic_ops_list.py::test_list_append",
"tests/test_basic_ops_list.py::test_list_eq[l14-l24]",
"tests/test_basic_ops_list.py::test_clear[2-src1]",
"tests/test_basic_ops_list.py::test_hash",
"tests/test_basic_ops_list.py::test_remove[src0-10-result0-expectation0]",
"tests/test_basic_ops_list.py::test_list_value",
"tests/test_basic_ops_list.py::test_clear[2-src0]",
"tests/test_basic_ops_list.py::test_clear[2-src2]",
"tests/test_basic_ops_list.py::test_assign[parent1-0-value1-expected1]",
"tests/test_basic_ops_list.py::test_extend[src1-append1-result1]",
"tests/test_basic_ops_list.py::test_list_eq[l12-l22]",
"tests/test_basic_ops_list.py::test_list_dir",
"tests/test_basic_ops_list.py::test_insert",
"tests/test_basic_ops_list.py::test_list_not_eq[input10-input20]",
"tests/test_basic_ops_list.py::test_list_delitem",
"tests/test_basic_ops_list.py::test_assign[parent2-foo-value2-expected2]",
"tests/test_basic_ops_list.py::test_items_with_interpolation",
"tests/test_basic_ops_list.py::test_assign[parent0-0-value0-expected0]",
"tests/test_basic_ops_list.py::test_list_eq[l10-l20]",
"tests/test_basic_ops_list.py::test_index_slice",
"tests/test_basic_ops_list.py::test_count[src3-None-0]",
"tests/test_basic_ops_list.py::test_list_len",
"tests/test_basic_ops_list.py::test_list_not_eq[input13-input23]",
"tests/test_basic_ops_list.py::test_list_eq_with_interpolation[l10-l20]",
"tests/test_basic_ops_list.py::test_list_get_with_default",
"tests/test_basic_ops_list.py::test_clear[1-src0]",
"tests/test_basic_ops_list.py::test_count[src1-10-1]",
"tests/test_basic_ops_list.py::test_clear[1-src2]",
"tests/test_basic_ops_list.py::test_extend[src0-append0-result0]",
"tests/test_basic_ops_list.py::test_pretty_without_resolve",
"tests/test_basic_ops_list.py::test_assign[parent3-foo-value3-expected3]",
"tests/test_basic_ops_list.py::test_list_eq[l16-l26]",
"tests/test_basic_ops_list.py::test_remove[src3-2-result3-expectation3]",
"tests/test_basic_ops_list.py::test_count[src2-10-2]",
"tests/test_basic_ops_list.py::test_list_of_dicts",
"tests/test_basic_ops_list.py::test_list_eq[l11-l21]",
"tests/test_basic_ops_list.py::test_list_enumerate",
"tests/test_basic_ops_list.py::test_index[src0-20--1-expectation0]",
"tests/test_basic_ops_list.py::test_index[src2-20-1-expectation2]",
"tests/test_basic_ops_list.py::test_count[src0-10-0]",
"tests/test_basic_ops_list.py::test_iterate_list",
"tests/test_basic_ops_list.py::test_index_slice2",
"tests/test_basic_ops_list.py::test_list_not_eq[input14-input24]",
"tests/test_basic_ops_list.py::test_negative_index",
"tests/test_basic_ops_list.py::test_list_not_eq[input11-input21]",
"tests/test_basic_ops_list.py::test_sort",
"tests/test_basic_ops_list.py::test_getattr",
"tests/test_basic_ops_list.py::test_list_eq[l13-l23]",
"tests/test_basic_ops_list.py::test_remove[src2-remove2-result2-expectation2]",
"tests/test_basic_ops_list.py::test_nested_list_assign_illegal_value",
"tests/test_basic_ops_list.py::test_pretty_with_resolve",
"tests/test_basic_ops_list.py::test_extend[src2-append2-result2]",
"tests/test_basic_ops_list.py::test_clear[1-src1]",
"tests/test_basic_ops_list.py::test_list_not_eq[input16-input26]",
"tests/test_basic_ops_list.py::test_remove[src1-oops-None-expectation1]",
"tests/test_basic_ops_list.py::test_list_eq[l15-l25]",
"tests/test_basic_ops_list.py::test_in_list",
"tests/test_basic_ops_list.py::test_items_on_list",
"tests/test_basic_ops_list.py::test_append_throws_not_changing_list"
] | 2019-11-14 08:12:49+00:00 | 4,388 |
|
omry__omegaconf-96 | diff --git a/news/95.bugfix b/news/95.bugfix
new file mode 100644
index 0000000..4a99b51
--- /dev/null
+++ b/news/95.bugfix
@@ -0,0 +1,1 @@
+Disable automatic conversion of date strings in yaml decoding
\ No newline at end of file
diff --git a/omegaconf/config.py b/omegaconf/config.py
index 0d76e38..8b21e27 100644
--- a/omegaconf/config.py
+++ b/omegaconf/config.py
@@ -39,6 +39,14 @@ def get_yaml_loader():
),
list(u"-+0123456789."),
)
+ loader.yaml_implicit_resolvers = {
+ key: [
+ (tag, regexp)
+ for tag, regexp in resolvers
+ if tag != u"tag:yaml.org,2002:timestamp"
+ ]
+ for key, resolvers in loader.yaml_implicit_resolvers.items()
+ }
return loader
| omry/omegaconf | 9f54f9ca971e899fbe522cf7e37af8e5f3c5f33b | diff --git a/tests/test_create.py b/tests/test_create.py
index 5d11d5d..668181d 100644
--- a/tests/test_create.py
+++ b/tests/test_create.py
@@ -50,7 +50,15 @@ def test_cli_passing():
@pytest.mark.parametrize(
- "input_, expected", [(["a=1", "b.c=2"], dict(a=1, b=dict(c=2)))]
+ "input_, expected",
+ [
+ # simple
+ (["a=1", "b.c=2"], dict(a=1, b=dict(c=2))),
+ # string
+ (["a=hello", "b=world"], dict(a="hello", b="world")),
+ # date-formatted string
+ (["my_date=2019-12-11"], dict(my_date="2019-12-11")),
+ ],
)
def test_dotlist(input_, expected):
c = OmegaConf.from_dotlist(input_)
| Disable automatic conversion of date strings in from_dotlist
### Issue
When instantiating OmegaConf from `from_dotlist`, yaml loader tries to convert date-formatted strings into `date` type, therefore raises error when validating the type of values.
```
OmegaConf.from_dotlist(["my_date=2019-11-11"])
>>>
.../site-packages/omegaconf/config.py in _prepare_value_to_add(self, key, value)
448 if not Config.is_primitive_type(value):
449 full_key = self.get_full_key(key)
--> 450 raise ValueError("key {}: {} is not a primitive type".format(full_key, type(value).__name__))
451
452 if self._get_flag('readonly'):
ValueError: key my_date: date is not a primitive type
```
This error also blocks the overriding of configuration values by using cli arguments in hydra.
### Potential workaround
Could be solved by removing implicit timestamp resolvers in default `yaml.SafeLoader`.
(Related stackoverflow: https://stackoverflow.com/questions/34667108/ignore-dates-and-times-while-parsing-yaml)
| 0.0 | [
"tests/test_create.py::test_dotlist[input_2-expected2]"
] | [
"tests/test_create.py::test_create_value[hello-expected0]",
"tests/test_create.py::test_create_value[hello:",
"tests/test_create.py::test_create_value[input_2-expected2]",
"tests/test_create.py::test_create_value[-expected3]",
"tests/test_create.py::test_create_value[input_4-expected4]",
"tests/test_create.py::test_create_value[input_5-expected5]",
"tests/test_create.py::test_create_value[input_6-expected6]",
"tests/test_create.py::test_create_value[input_7-expected7]",
"tests/test_create.py::test_create_value[input_8-expected8]",
"tests/test_create.py::test_create_from_cli",
"tests/test_create.py::test_cli_passing",
"tests/test_create.py::test_dotlist[input_0-expected0]",
"tests/test_create.py::test_dotlist[input_1-expected1]",
"tests/test_create.py::test_create_list_with_illegal_value_idx0",
"tests/test_create.py::test_create_list_with_illegal_value_idx1",
"tests/test_create.py::test_create_dict_with_illegal_value",
"tests/test_create.py::test_create_nested_dict_with_illegal_value",
"tests/test_create.py::test_create_from_oc"
] | 2019-12-11 02:10:17+00:00 | 4,389 |
|
onesuper__pandasticsearch-30 | diff --git a/pandasticsearch/dataframe.py b/pandasticsearch/dataframe.py
index 1f372db..1159dd6 100644
--- a/pandasticsearch/dataframe.py
+++ b/pandasticsearch/dataframe.py
@@ -138,7 +138,7 @@ class DataFrame(object):
raise TypeError('Column does not exist: [{0}]'.format(item))
return Column(item)
elif isinstance(item, BooleanFilter):
- self._filter = item.build()
+ self._filter = item
return self
else:
raise TypeError('Unsupported expr: [{0}]'.format(item))
@@ -434,10 +434,18 @@ class DataFrame(object):
sys.stdout.write('{0}\n'.format(self._index))
index = list(self._mapping.values())[0] # {'index': {}}
- for typ, properties in six.iteritems(index['mappings']):
- sys.stdout.write('|--{0}\n'.format(typ))
- for k, v in six.iteritems(properties['properties']):
- sys.stdout.write(' |--{0}: {1}\n'.format(k, v))
+ schema = self.resolve_schema(index['mappings']['properties'])
+ sys.stdout.write(schema)
+
+ def resolve_schema(self, json_prop, res_schema="", depth=1):
+ for field in json_prop:
+ if "properties" in json_prop[field]:
+ res_schema += f"{' '*depth}|--{field}:\n"
+ res_schema = self.resolve_schema(json_prop[field]["properties"],
+ res_schema, depth=depth+1)
+ else:
+ res_schema += f"{' ' * depth}|--{field}: {json_prop[field]}\n"
+ return res_schema
def _build_query(self):
query = dict()
@@ -488,16 +496,31 @@ class DataFrame(object):
@classmethod
def _get_cols(cls, mapping):
- cols = []
- index = list(mapping.values())[0] # {'index': {}}
- for _, properties in six.iteritems(index['mappings']):
- for k, _ in six.iteritems(properties['properties']):
- cols.append(k)
+ index = list(mapping.keys())[0]
+ cols = cls.get_mappings(mapping, index)
if len(cols) == 0:
raise Exception('0 columns found in mapping')
return cols
+ @classmethod
+ def resolve_mappings(cls, json_map):
+ prop = []
+ for field in json_map:
+ nested_props = []
+ if "properties" in json_map[field]:
+ nested_props = cls.resolve_mappings(json_map[field]["properties"])
+ if len(nested_props) == 0:
+ prop.append(field)
+ else:
+ for nested_prop in nested_props:
+ prop.append(f"{field}.{nested_prop}")
+ return prop
+
+ @classmethod
+ def get_mappings(cls, json_map, index_name):
+ return cls.resolve_mappings(json_map[index_name]["mappings"]["properties"])
+
@classmethod
def _get_doc_type(cls, mapping):
index = list(mapping.values())[0] # {'index': {}}
diff --git a/pandasticsearch/queries.py b/pandasticsearch/queries.py
index 15e5fc1..19b5c78 100644
--- a/pandasticsearch/queries.py
+++ b/pandasticsearch/queries.py
@@ -74,6 +74,18 @@ class Select(Query):
def __init__(self):
super(Select, self).__init__()
+ def resolve_fields(self, row):
+ fields = {}
+ for field in row:
+ nested_fields = {}
+ if isinstance(row[field], dict):
+ nested_fields = self.resolve_fields(row[field])
+ for n_field, val in nested_fields.items():
+ fields[f"{field}.{n_field}"] = val
+ else:
+ fields[field] = row[field]
+ return fields
+
def explain_result(self, result=None):
super(Select, self).explain_result(result)
rows = []
@@ -81,7 +93,8 @@ class Select(Query):
row = {}
for k in hit.keys():
if k == '_source':
- row.update(hit['_source'])
+ solved_fields = self.resolve_fields(hit['_source'])
+ row.update(solved_fields)
elif k.startswith('_'):
row[k] = hit[k]
rows.append(row)
| onesuper/pandasticsearch | 13b16ba9d5926438d11fc78b8f0271ec93d9d749 | diff --git a/tests/test_dataframe.py b/tests/test_dataframe.py
index f139d54..cc2cc8e 100644
--- a/tests/test_dataframe.py
+++ b/tests/test_dataframe.py
@@ -9,8 +9,30 @@ from pandasticsearch.operators import *
@patch('pandasticsearch.client.urllib.request.urlopen')
def create_df_from_es(mock_urlopen):
response = Mock()
- dic = {"index": {"mappings": {"doc_type": {"properties": {"a": {"type": "integer"},
- "b": {"type": "integer"}}}}}}
+ dic = {
+ "metricbeat-7.0.0-qa": {
+ "mappings": {
+ "_meta": {
+ "beat": "metricbeat",
+ "version": "7.0.0"
+ },
+ "date_detection": False,
+ "properties": {
+ "a": {
+ "type": "integer"
+ },
+ "b": {
+ "type": "integer"
+ },
+ "c": {"properties": {
+ "d": {"type": "keyword", "ignore_above": 1024},
+ "e": {"type": "keyword", "ignore_above": 1024}
+ }
+ }
+ }
+ }
+ }
+ }
response.read.return_value = json.dumps(dic).encode("utf-8")
mock_urlopen.return_value = response
return DataFrame.from_es(url="http://localhost:9200", index='xxx')
@@ -25,7 +47,7 @@ class TestDataFrame(unittest.TestCase):
expr = df['a'] > 2
self.assertTrue(isinstance(expr, BooleanFilter))
self.assertTrue(isinstance(df[expr], DataFrame))
- self.assertEqual(df[expr]._filter, {'range': {'a': {'gt': 2}}})
+ self.assertEqual(df[expr]._filter.build(), {'range': {'a': {'gt': 2}}})
def test_getattr(self):
df = create_df_from_es()
@@ -34,7 +56,7 @@ class TestDataFrame(unittest.TestCase):
def test_columns(self):
df = create_df_from_es()
- self.assertEqual(df.columns, ['a', 'b'])
+ self.assertEqual(df.columns, ['a', 'b', 'c.d', 'c.e'])
def test_init(self):
df = create_df_from_es()
| KeyError: properties in DataFrame.print_schema running against ES 7.x
Hi team,
I installed pandasticsearch version 0.5.1 using
```
pip install pandasticsearch[pandas]
```
and I tried to run this code
```
df = DataFrame.from_es(url='http://localhost:9200', index='my_index')
df.print_schema()
```
I get the following stacktrace
```
<ipython-input-9-cee54abe7265> in <module>
1 from pandasticsearch import DataFrame
----> 2 df = DataFrame.from_es(url='http://localhost:9200', index='my_index')
3 df.print_schema()
~/<redacted>/env/lib/python3.7/site-packages/pandasticsearch/dataframe.py in from_es(**kwargs)
122 endpoint = index + '/' + doc_type + '/_search'
123 return DataFrame(client=RestClient(url, endpoint, username, password, verify_ssl),
--> 124 mapping=mapping, index=index, doc_type=doc_type, compat=compat)
125
126 def __getattr__(self, name):
~/<redacted>/env/lib/python3.7/site-packages/pandasticsearch/dataframe.py in __init__(self, **kwargs)
40 self._index = list(self._mapping.keys())[0] if self._mapping else None
41 self._doc_type = DataFrame._get_doc_type(self._mapping) if self._mapping else None
---> 42 self._columns = sorted(DataFrame._get_cols(self._mapping)) if self._mapping else None
43 self._filter = kwargs.get('filter', None)
44 self._groupby = kwargs.get('groupby', None)
~/<redacted>env/lib/python3.7/site-packages/pandasticsearch/dataframe.py in _get_cols(cls, mapping)
492 index = list(mapping.values())[0] # {'index': {}}
493 for _, properties in six.iteritems(index['mappings']):
--> 494 for k, _ in six.iteritems(properties['properties']):
495 cols.append(k)
496
KeyError: 'properties'
```
It looks like this might have something to do with removing types, which is a breaking change between ES 6.x and 7.x. I can try to dig into this a bit later. | 0.0 | [
"tests/test_dataframe.py::TestDataFrame::test_columns",
"tests/test_dataframe.py::TestDataFrame::test_agg",
"tests/test_dataframe.py::TestDataFrame::test_getattr",
"tests/test_dataframe.py::TestDataFrame::test_groupby",
"tests/test_dataframe.py::TestDataFrame::test_complex",
"tests/test_dataframe.py::TestDataFrame::test_getitem",
"tests/test_dataframe.py::TestDataFrame::test_limit",
"tests/test_dataframe.py::TestDataFrame::test_init",
"tests/test_dataframe.py::TestDataFrame::test_complex_agg",
"tests/test_dataframe.py::TestDataFrame::test_sort",
"tests/test_dataframe.py::TestDataFrame::test_filter",
"tests/test_dataframe.py::TestDataFrame::test_select"
] | [] | 2019-05-23 14:19:15+00:00 | 4,390 |
|
onicagroup__runway-1245 | diff --git a/runway/cfngin/actions/diff.py b/runway/cfngin/actions/diff.py
index 0e68b2f9..8604e9d0 100644
--- a/runway/cfngin/actions/diff.py
+++ b/runway/cfngin/actions/diff.py
@@ -210,9 +210,14 @@ class Action(deploy.Action):
tags = deploy.build_stack_tags(stack)
+ try:
+ provider_stack = provider.get_stack(stack.fqn)
+ except exceptions.StackDoesNotExist:
+ provider_stack = None
+
try:
stack.resolve(self.context, provider)
- parameters = self.build_parameters(stack)
+ parameters = self.build_parameters(stack, provider_stack)
outputs = provider.get_stack_changes(
stack, self._template(stack.blueprint), parameters, tags
)
diff --git a/runway/cfngin/providers/aws/default.py b/runway/cfngin/providers/aws/default.py
index 97b620a0..ab9b259d 100644
--- a/runway/cfngin/providers/aws/default.py
+++ b/runway/cfngin/providers/aws/default.py
@@ -1503,8 +1503,10 @@ class Provider(BaseProvider):
# handling for orphaned changeset temp stacks
if self.get_stack_status(stack_details) == self.REVIEW_STATUS:
raise exceptions.StackDoesNotExist(stack.fqn)
- _old_template, old_params = self.get_stack_info(stack_details)
- old_template: Dict[str, Any] = parse_cloudformation_template(_old_template)
+ old_template_raw, old_params = self.get_stack_info(stack_details)
+ old_template: Dict[str, Any] = parse_cloudformation_template(
+ old_template_raw
+ )
change_type = "UPDATE"
except exceptions.StackDoesNotExist:
old_params: Dict[str, Union[List[str], str]] = {}
| onicagroup/runway | 2a41ab6982f8d0c927a0b256cf5c58e085fc5b0a | diff --git a/tests/unit/cfngin/actions/conftest.py b/tests/unit/cfngin/actions/conftest.py
new file mode 100644
index 00000000..56d46653
--- /dev/null
+++ b/tests/unit/cfngin/actions/conftest.py
@@ -0,0 +1,30 @@
+"""Pytest fixtures and plugins."""
+# pyright: basic
+from __future__ import annotations
+
+from datetime import datetime
+from typing import TYPE_CHECKING
+
+import pytest
+from mock import MagicMock
+
+from runway.cfngin.providers.aws.default import Provider
+
+if TYPE_CHECKING:
+ from mypy_boto3_cloudformation.type_defs import StackTypeDef
+ from pytest_mock import MockerFixture
+
+
[email protected](scope="function")
+def provider_get_stack(mocker: MockerFixture) -> MagicMock:
+ """Patches ``runway.cfngin.providers.aws.default.Provider.get_stack``."""
+ return_value: StackTypeDef = {
+ "CreationTime": datetime(2015, 1, 1),
+ "Description": "something",
+ "Outputs": [],
+ "Parameters": [],
+ "StackId": "123",
+ "StackName": "foo",
+ "StackStatus": "CREATE_COMPLETE",
+ }
+ return mocker.patch.object(Provider, "get_stack", return_value=return_value)
diff --git a/tests/unit/cfngin/actions/test_diff.py b/tests/unit/cfngin/actions/test_diff.py
index d5ce5a65..6d72501e 100644
--- a/tests/unit/cfngin/actions/test_diff.py
+++ b/tests/unit/cfngin/actions/test_diff.py
@@ -10,7 +10,7 @@ from typing import TYPE_CHECKING, Optional
import pytest
from botocore.exceptions import ClientError
-from mock import MagicMock, patch
+from mock import MagicMock, Mock, patch
from runway.cfngin.actions.diff import (
Action,
@@ -18,13 +18,15 @@ from runway.cfngin.actions.diff import (
diff_dictionaries,
diff_parameters,
)
+from runway.cfngin.exceptions import StackDoesNotExist
from runway.cfngin.providers.aws.default import Provider
from runway.cfngin.status import SkippedStatus
from ..factories import MockProviderBuilder, MockThreadingEvent
if TYPE_CHECKING:
- from pytest import LogCaptureFixture, MonkeyPatch
+ from pytest import LogCaptureFixture
+ from pytest_mock import MockerFixture
from ...factories import MockCFNginContext
@@ -82,11 +84,14 @@ class TestAction:
assert action.bucket_name == bucket_name
- def test_diff_stack_validationerror_template_too_large(
+ @pytest.mark.parametrize("stack_not_exist", [False, True])
+ def test__diff_stack_validationerror_template_too_large(
self,
caplog: LogCaptureFixture,
cfngin_context: MockCFNginContext,
- monkeypatch: MonkeyPatch,
+ mocker: MockerFixture,
+ provider_get_stack: MagicMock,
+ stack_not_exist: bool,
) -> None:
"""Test _diff_stack ValidationError - template too large."""
caplog.set_level(logging.ERROR)
@@ -94,8 +99,12 @@ class TestAction:
cfngin_context.add_stubber("cloudformation")
cfngin_context.config.cfngin_bucket = ""
expected = SkippedStatus("cfngin_bucket: existing bucket required")
- provider = Provider(cfngin_context.get_session()) # type: ignore
- mock_get_stack_changes = MagicMock(
+ mock_build_parameters = mocker.patch.object(
+ Action, "build_parameters", return_value=[]
+ )
+ mock_get_stack_changes = mocker.patch.object(
+ Provider,
+ "get_stack_changes",
side_effect=ClientError(
{
"Error": {
@@ -104,22 +113,29 @@ class TestAction:
}
},
"create_change_set",
- )
+ ),
+ )
+ provider = Provider(cfngin_context.get_session()) # type: ignore
+ stack = MagicMock(
+ blueprint=Mock(rendered="{}"),
+ fqn="test-stack",
+ locked=False,
+ region=cfngin_context.env.aws_region,
+ status=None,
)
- monkeypatch.setattr(provider, "get_stack_changes", mock_get_stack_changes)
- stack = MagicMock()
- stack.region = cfngin_context.env.aws_region
- stack.name = "test-stack"
- stack.fqn = "test-stack"
- stack.blueprint.rendered = "{}"
- stack.locked = False
- stack.status = None
+ stack.name = "stack"
+
+ if stack_not_exist:
+ provider_get_stack.side_effect = StackDoesNotExist("test-stack")
result = Action(
context=cfngin_context,
provider_builder=MockProviderBuilder(provider=provider),
cancel=MockThreadingEvent(), # type: ignore
)._diff_stack(stack)
+ mock_build_parameters.assert_called_once_with(
+ stack, None if stack_not_exist else provider_get_stack.return_value
+ )
mock_get_stack_changes.assert_called_once()
assert result == expected
| [BUG] runway incorrectly shows parameters to be removed in "plan"
### Bug Description
When running a cloudformation plan on an existing stack, the output states that parameters are to be removed:
```console
phil4079@L4CLYSQ2:~/runway-cloudformation-bug-test$ DEPLOY_ENVIRONMENT=common runway plan
[runway] could not find runway.variables.yml or runway.variables.yaml in the current directory; continuing without a variables file
[runway] deploy environment "common" is explicitly defined in the environment
[runway] if not correct, update the value or unset it to fall back to the name of the current git branch or parent directory
[runway]
[runway]
[runway] deployment_1:processing deployment (in progress)
[runway] deployment_1:processing regions sequentially...
[runway]
[runway] deployment_1.runway-cfn-test.cfn:processing module in us-east-1 (in progress)
[runway] found environment file: /home/phil4079/runway-cloudformation-bug-test/runway-cfn-test.cfn/common.env
[runway] stack-definition.yaml:plan (in progress)
[runway] diffing stacks: runway-cfn-test-stack
[runway] philcorp-dev-runway-cfn-test-stack changes:
Parameters Removed: InstanceType, SSHLocation, WebServerCount
Replacements:
- Modify EC2SRTA14Y5Q (AWS::EC2::SubnetRouteTableAssociation)
- Modify PublicSubnet (AWS::EC2::Subnet)
Changes:
- Modify ASGPolicy (AWS::AutoScaling::ScalingPolicy)
- Modify PublicElasticLoadBalancer (AWS::ElasticLoadBalancing::LoadBalancer)
- Modify WebServerFleet (AWS::AutoScaling::AutoScalingGroup)
Show full change set? [y/n] n
[runway] RawTemplateBlueprint.get_output_definitions is deprecated and will be removed in a future release
[runway] runway-cfn-test-stack:complete
[runway] stack-definition.yaml:plan (complete)
[runway] deployment_1.runway-cfn-test.cfn:processing module in us-east-1 (complete)
[runway] deployment_1:processing deployment (complete)
```
However, when running the same stack in deploy mode, these parameters are NOT listed for removal (which is the correct behavior):
```console
phil4079@L4CLYSQ2:~/runway-cloudformation-bug-test$ DEPLOY_ENVIRONMENT=common runway deploy
[runway] could not find runway.variables.yml or runway.variables.yaml in the current directory; continuing without a variables file
[runway] deploy environment "common" is explicitly defined in the environment
[runway] if not correct, update the value or unset it to fall back to the name of the current git branch or parent directory
[runway]
[runway]
[runway] deployment_1:processing deployment (in progress)
[runway] deployment_1:processing regions sequentially...
[runway]
[runway] deployment_1.runway-cfn-test.cfn:processing module in us-east-1 (in progress)
[runway] found environment file: /home/phil4079/runway-cloudformation-bug-test/runway-cfn-test.cfn/common.env
[runway] stack-definition.yaml:init (in progress)
[runway] cfngin_bucket cfngin-philcorp-dev-us-east-1 already exists
[runway] stack-definition.yaml:init (complete)
[runway] stack-definition.yaml:deploy (in progress)
[runway] philcorp-dev-runway-cfn-test-stack changes:
Replacements:
- Modify EC2SRTA14Y5Q (AWS::EC2::SubnetRouteTableAssociation)
- Modify PublicSubnet (AWS::EC2::Subnet)
Changes:
- Modify ASGPolicy (AWS::AutoScaling::ScalingPolicy)
- Modify PublicElasticLoadBalancer (AWS::ElasticLoadBalancing::LoadBalancer)
- Modify WebServerFleet (AWS::AutoScaling::AutoScalingGroup)
Execute the above changes? [y/n/v] n
[runway] runway-cfn-test-stack:skipped (canceled execution)
[runway] stack-definition.yaml:deploy (complete)
[runway] deployment_1.runway-cfn-test.cfn:processing module in us-east-1 (complete)
[runway] deployment_1:processing deployment (complete)
```
VIewing the change set in AWS console does not show any parameters to be removed (see attached).
[runway-cloudformation-bug-test-stack-20220128.txt](https://github.com/onicagroup/runway/files/7961947/runway-cloudformation-bug-test-stack-20220128.txt)
[runway-cloudformation-bug-test-change-set-20220128.txt](https://github.com/onicagroup/runway/files/7961967/runway-cloudformation-bug-test-change-set-20220128.txt)
### Expected Behavior
Both "plan" and "deploy" should not show any parameters being removed.
### Steps To Reproduce
Example project: ...
1. Deploy cloudformation stack with runway
2. Make a change to the stack
3. Perform a runway "plan" and "deploy" to see the output discrepancy
### Runway version
2.4.4
### Installation Type
pypi (pip, pipenv, poetry, etc)
### OS / Environment
- OS: Windows 10
- runway: 2.4.4
### Anything else?
_No response_ | 0.0 | [
"tests/unit/cfngin/actions/test_diff.py::TestAction::test__diff_stack_validationerror_template_too_large[False]",
"tests/unit/cfngin/actions/test_diff.py::TestAction::test__diff_stack_validationerror_template_too_large[True]"
] | [
"tests/unit/cfngin/actions/test_diff.py::TestDiffDictionary::test_diff_dictionaries",
"tests/unit/cfngin/actions/test_diff.py::TestDictValueFormat::test_format",
"tests/unit/cfngin/actions/test_diff.py::TestDictValueFormat::test_status",
"tests/unit/cfngin/actions/test_diff.py::TestAction::test_pre_run[test-bucket-False-True]",
"tests/unit/cfngin/actions/test_diff.py::TestAction::test_pre_run[None-True-False]",
"tests/unit/cfngin/actions/test_diff.py::TestAction::test_pre_run[None-False-True]",
"tests/unit/cfngin/actions/test_diff.py::TestAction::test_pre_run[test-bucket-True-False]",
"tests/unit/cfngin/actions/test_diff.py::TestDiffParameters::test_diff_parameters_no_changes"
] | 2022-02-01 16:57:35+00:00 | 4,391 |
|
onicagroup__runway-2013 | diff --git a/runway/core/components/_module_path.py b/runway/core/components/_module_path.py
index bdc471fc..60124812 100644
--- a/runway/core/components/_module_path.py
+++ b/runway/core/components/_module_path.py
@@ -37,7 +37,7 @@ class ModulePath:
ARGS_REGEX: ClassVar[str] = r"(\?)(?P<args>.*)$"
REMOTE_SOURCE_HANDLERS: ClassVar[Dict[str, Type[Source]]] = {"git": Git}
SOURCE_REGEX: ClassVar[str] = r"(?P<source>[a-z]+)(\:\:)"
- URI_REGEX: ClassVar[str] = r"(?P<uri>[a-z]+://[a-zA-Z0-9\./]+?(?=//|\?|$))"
+ URI_REGEX: ClassVar[str] = r"(?P<uri>[a-z]+://[a-zA-Z0-9\./-]+?(?=//|\?|$))"
def __init__(
self,
| onicagroup/runway | 956acd6bd9e25024189622122b70a2730a223653 | diff --git a/tests/unit/core/components/test_module_path.py b/tests/unit/core/components/test_module_path.py
index 2db1fe9e..a005666a 100644
--- a/tests/unit/core/components/test_module_path.py
+++ b/tests/unit/core/components/test_module_path.py
@@ -37,6 +37,15 @@ TypeDefTestDefinition = TypedDict(
)
TESTS: List[TypeDefTestDefinition] = [
+ {
+ "definition": "git::git://github.com/onicagroup/foo/foo-bar.git",
+ "expected": {
+ "location": "./",
+ "arguments": {},
+ "source": "git",
+ "uri": "git://github.com/onicagroup/foo/foo-bar.git",
+ },
+ },
{
"definition": "git::git://github.com/onicagroup/foo/bar.git",
"expected": {
| [BUG] git repo link not working in path attribute
### Bug Description
I am trying to source terraform module stored in github repo, but when I pass the git link of repo in the "path" attribute of modules section in runway.yml and execute runway plan, it returns error as follows:
$runway plan
return self.__git_ls_remote(self.__determine_git_ls_remote_ref())
File "/usr/lib/python3.9/site-packages/runway/sources/git.py", line 77, in __git_ls_remote
ls_remote_output = subprocess.check_output(cmd)
File "/usr/lib/python3.9/subprocess.py", line 424, in check_output
return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
File "/usr/lib/python3.9/subprocess.py", line 528, in run
raise CalledProcessError(retcode, process.args,
subprocess.CalledProcessError: Command '['git', 'ls-remote', '', 'HEAD']' returned non-zero exit status 128.
I am able to clone the repo manually with git clone command on the host machine where runway is installed, and ssh key is also added to github repo.
git ls-remote <repo_url> HEAD is also returning output without any error on manual execution on the terminal
I am assuming it has to do something with ssh authentication.
Can someone please address this asap as it is blocking critical operations in our project.
runway.yml:
deployments:
- name: test-deployment
modules:
- path: git::git://<githuborg>/terraform-google-bigquery.git
parameters:
dataset_id: "Testing-runway"
regions:
europe-west2
### Expected Behavior
runway plan should not return error
### Steps To Reproduce
Example project: ...
1. add git repo url to path attribute in runway.yml:
deployments:
- name: test-deployment
modules:
- path: git::git://<githuborg>/terraform-google-bigquery.git
parameters:
dataset_id: "Testing-runway"
regions:
europe-west2
2. $runway plan
...
### Runway version
2.6.8
### Installation Type
pypi (pip, pipenv, poetry, etc)
### OS / Environment
- OS: Red hat Linux
- terraform version: 1.5.2
### Anything else?
_No response_ | 0.0 | [
"tests/unit/core/components/test_module_path.py::TestModulePath::test_uri[test0]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_metadata[test0]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_location[test0]"
] | [
"tests/unit/core/components/test_module_path.py::TestModulePath::test_location[test9]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_metadata[test1]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_metadata[test5]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_arguments[test2]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_location[test6]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_metadata[test13]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_module_root[test6]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_arguments[test9]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_parse_obj_path",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_location[test11]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_arguments[test3]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_module_root[test4]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_source[test3]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_location[test4]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_source[test6]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_module_root[test8]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_uri[test11]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_location[test7]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_uri[test5]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_source[test11]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_uri[test7]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_location[test10]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_location[test8]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_metadata[test10]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_uri[test12]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_module_root[test1]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_module_root_not_implimented",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_metadata[test11]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_source[test14]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_arguments[test0]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_parse_obj_type_error",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_module_root[test5]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_module_root[test13]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_source[test7]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_module_root[test12]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_module_root[test7]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_metadata[test8]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_module_root[test3]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_source[test10]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_parse_obj_str",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_module_root[test11]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_source[test5]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_uri[test13]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_metadata[test4]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_source[test8]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_module_root[test14]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_location[test12]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_module_root[test10]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_source[test1]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_arguments[test12]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_location[test14]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_arguments[test1]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_arguments[test14]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_uri[test4]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_arguments[test7]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_metadata[test6]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_arguments[test11]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_uri[test9]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_source[test2]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_location[test1]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_arguments[test10]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_uri[test3]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_metadata[test2]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_module_root[test2]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_uri[test2]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_module_root[test9]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_arguments[test13]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_location[test13]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_metadata[test7]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_metadata[test12]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_module_root[test0]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_source[test9]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_arguments[test6]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_metadata[test9]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_location[test2]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_uri[test6]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_arguments[test5]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_arguments[test4]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_parse_obj_none",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_arguments[test8]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_source[test0]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_source[test4]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_uri[test1]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_location[test3]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_location[test5]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_uri[test8]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_source[test12]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_uri[test10]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_parse_obj_runway_config",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_metadata[test3]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_metadata[test14]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_uri[test14]",
"tests/unit/core/components/test_module_path.py::TestModulePath::test_source[test13]"
] | 2023-10-18 22:55:11+00:00 | 4,392 |
|
online-judge-tools__api-client-48 | diff --git a/README.md b/README.md
index 395adbc..1777a3f 100644
--- a/README.md
+++ b/README.md
@@ -37,6 +37,7 @@ $ pip3 install online-judge-api-client
| [Library Checker](https://judge.yosupo.jp/) | :heavy_check_mark: | :heavy_check_mark: | | | :white_check_mark: | |
| [PKU JudgeOnline](http://poj.org/) | :heavy_check_mark: | | | | :white_check_mark: | |
| [Sphere Online Judge](https://www.spoj.com/) | :heavy_check_mark: | | | | :white_check_mark: | |
+| [Topcoder](https://arena.topcoder.com/) | :white_check_mark: | | :white_check_mark: | | :white_check_mark: | |
| [Toph](https://toph.co/) | :heavy_check_mark: | | | | :white_check_mark: | :heavy_check_mark: |
| [yukicoder](https://yukicoder.me/) | :heavy_check_mark: | :heavy_check_mark: | | | :white_check_mark: | :heavy_check_mark: |
diff --git a/onlinejudge/service/__init__.py b/onlinejudge/service/__init__.py
index 68194bb..997be7d 100644
--- a/onlinejudge/service/__init__.py
+++ b/onlinejudge/service/__init__.py
@@ -12,5 +12,6 @@ import onlinejudge.service.kattis
import onlinejudge.service.library_checker
import onlinejudge.service.poj
import onlinejudge.service.spoj
+import onlinejudge.service.topcoder
import onlinejudge.service.toph
import onlinejudge.service.yukicoder
diff --git a/onlinejudge/service/topcoder.py b/onlinejudge/service/topcoder.py
new file mode 100644
index 0000000..1f3e683
--- /dev/null
+++ b/onlinejudge/service/topcoder.py
@@ -0,0 +1,209 @@
+"""
+the module for Topcoder (https://topcoder.com/)
+
+.. versionadded:: 10.1.0
+"""
+
+import urllib.parse
+from typing import *
+
+import bs4
+import requests
+
+import onlinejudge._implementation.logging as log
+import onlinejudge._implementation.utils as utils
+import onlinejudge.type
+from onlinejudge.type import SampleParseError, TestCase
+
+
+class TopcoderService(onlinejudge.type.Service):
+ def get_url(self) -> str:
+ return 'https://arena.topcoder.com/'
+
+ def get_name(self) -> str:
+ return 'Topcoder'
+
+ @classmethod
+ def from_url(cls, url: str) -> Optional['TopcoderService']:
+ # example: https://arena.topcoder.com/
+ # example: https://community.topcoder.com/stat?c=problem_statement&pm=10760
+ result = urllib.parse.urlparse(url)
+ if result.scheme in ('', 'http', 'https'):
+ if result.netloc in ('topcoder.com', 'arena.topcoder.com', 'community.topcoder.com'):
+ return cls()
+ return None
+
+
+# class _TopcoderData(onlinejudge.type.ProblemData):
+class _TopcoderData:
+ def __init__(self, *, definition: Dict[str, str], raw_sample_cases: List[Tuple[List[str], str]], sample_cases: List[TestCase]):
+ self.definition = definition
+ self.raw_sample_cases = sample_cases
+ self.sample_cases = sample_cases
+
+
+def _convert_to_greed(x: str) -> str:
+ # example: `{1, 0, 1, 1, 0}` -> `5 1 0 1 1 0`
+ # example: `"foo"` -> `foo`
+ # example: `2` -> `2`
+ # example: `{"aa", "bb", "cc"}` -> 3 aa bb cc
+ if x.startswith('{') and x.endswith('}'):
+ ys = x[1:-1].split(',')
+ return ' '.join([str(len(ys)), *map(lambda y: _convert_to_greed(y.strip()), ys)])
+ elif x.startswith('"') and x.endswith('"'):
+ return x[1:-1]
+ else:
+ return x
+
+
+class TopcoderProblem(onlinejudge.type.Problem):
+ """
+ :ivar problem_id: :py:class:`int`
+ """
+ def __init__(self, *, problem_id: int):
+ self.problem_id = problem_id
+
+ def _download_data(self, *, session: Optional[requests.Session] = None) -> _TopcoderData:
+ session = session or utils.get_default_session()
+
+ # download HTML
+ url = 'https://community.topcoder.com/stat?c=problem_statement&pm={}'.format(self.problem_id)
+ resp = utils.request('GET', url, session=session)
+
+ # parse HTML
+ soup = bs4.BeautifulSoup(resp.content.decode(resp.encoding), utils.html_parser)
+
+ problem_texts = soup.find_all('td', class_='problemText')
+ if len(problem_texts) != 1:
+ raise SampleParseError("""<td class="problemText"> is not found or not unique""")
+ problem_text = problem_texts[0]
+
+ # parse Definition section
+ # format:
+ # <tr>...<h3>Definition</h3>...<tr>
+ # <tr><td>...</td>
+ # <td><table>
+ # ...
+ # <tr><td>Class:</td><td>...</td></tr>
+ # <tr><td>Method:</td><td>...</td></tr>
+ # ...
+ # </table></td></tr>
+ log.debug('parse Definition section')
+ h3 = problem_text.find('h3', text='Definition')
+ if h3 is None:
+ raise SampleParseError("""<h3>Definition</h3> is not found""")
+ definition = {}
+ for text, key in {
+ 'Class:': 'class',
+ 'Method:': 'method',
+ 'Parameters:': 'parameters',
+ 'Returns:': 'returns',
+ 'Method signature:': 'method_signature',
+ }.items():
+ td = h3.parent.parent.next_sibling.find('td', class_='statText', text=text)
+ log.debug('%s', td.parent)
+ definition[key] = td.next_sibling.string
+
+ # parse Examples section
+ # format:
+ # <tr>...<h3>Examples</h3>...<tr>
+ # <tr><td>0)</td><td></td></tr>
+ # <tr><td></td>
+ # <td><table>
+ # ...
+ # <pre>{5, 8}</pre>
+ # <pre>"foo"</pre>
+ # <pre>3.5</pre>
+ # <pre>Returns: 40.0</pre>
+ # ...
+ # </table></td></tr>
+ # <tr><td>1)</td><td></td></tr>
+ # ...
+ log.debug('parse Examples section')
+ h3 = problem_text.find('h3', text='Examples')
+ if h3 is None:
+ raise SampleParseError("""<h3>Examples</h3> is not found""")
+
+ raw_sample_cases = [] # type: List[Tuple[List[str], str]]
+ cursor = h3.parent.parent
+ while True:
+ # read the header like "0)"
+ cursor = cursor.next_sibling
+ log.debug('%s', cursor)
+ if not cursor or cursor.name != 'tr':
+ break
+ if cursor.find('td').string != '{})'.format(len(raw_sample_cases)):
+ raise SampleParseError("""<td ...>){})</td> is expected, but not found""".format(len(raw_sample_cases)))
+
+ # collect <pre>s
+ cursor = cursor.next_sibling
+ log.debug('%s', cursor)
+ if not cursor or cursor.name != 'tr':
+ raise SampleParseError("""<tr>...</tr> is expected, but not found""")
+ input_items = []
+ for pre in cursor.find_all('pre'):
+ marker = 'Returns: '
+ if pre.string.startswith(marker):
+ output_item = pre.string[len(marker):]
+ break
+ else:
+ input_items.append(pre.string)
+ else:
+ raise SampleParseError("""<pre>Returns: ...</pre> is expected, but not found""")
+ raw_sample_cases.append((input_items, output_item))
+
+ # convert samples cases to the Greed format
+ sample_cases = []
+ for i, (input_items, output_item) in enumerate(raw_sample_cases):
+ sample_cases.append(TestCase(
+ 'example-{}'.format(i),
+ 'input',
+ ('\n'.join(map(_convert_to_greed, input_items)) + '\n').encode(),
+ 'output',
+ (_convert_to_greed(output_item) + '\n').encode(),
+ ))
+
+ return _TopcoderData(definition=definition, raw_sample_cases=raw_sample_cases, sample_cases=sample_cases)
+
+ def download_sample_cases(self, *, session: Optional[requests.Session] = None) -> List[TestCase]:
+ return self._download_data(session=session).sample_cases
+
+ def get_url(self) -> str:
+ return 'https://community.topcoder.com/stat?c=problem_statement&pm={}'.format(self.problem_id)
+
+ @classmethod
+ def from_url(cls, url: str) -> Optional['TopcoderProblem']:
+ # example: https://arena.topcoder.com/index.html#/u/practiceCode/14230/10838/10760/1/303803
+ # example: https://community.topcoder.com/stat?c=problem_statement&pm=10760
+ result = urllib.parse.urlparse(url)
+ if result.scheme in ('', 'http', 'https'):
+ if result.netloc == 'arena.topcoder.com' and utils.normpath(result.path) in ('/', '/index.html'):
+ dirs = utils.normpath(result.fragment).split('/')
+ if len(dirs) == 8 and dirs[0] == '' and dirs[1] == 'u' and dirs[2] == 'practiceCode':
+ try:
+ _ = int(dirs[3]) # round_id
+ _ = int(dirs[4]) # component_id
+ problem_id = int(dirs[5])
+ _ = int(dirs[6]) # division_id
+ _ = int(dirs[7]) # room_id
+ except ValueError:
+ pass
+ else:
+ return cls(problem_id=problem_id)
+ if result.netloc == 'community.topcoder.com' and utils.normpath(result.path) == '/stat':
+ query = urllib.parse.parse_qs(result.query)
+ if query.get('c') == ['problem_statement'] and len(query.get('pm', [])) == 1:
+ try:
+ problem_id = int(query['pm'][0])
+ except ValueError:
+ pass
+ else:
+ return cls(problem_id=problem_id)
+ return None
+
+ def get_service(self) -> TopcoderService:
+ return TopcoderService()
+
+
+onlinejudge.dispatch.services += [TopcoderService]
+onlinejudge.dispatch.problems += [TopcoderProblem]
diff --git a/onlinejudge_api/get_problem.py b/onlinejudge_api/get_problem.py
index 704da06..487e884 100644
--- a/onlinejudge_api/get_problem.py
+++ b/onlinejudge_api/get_problem.py
@@ -3,6 +3,7 @@ from typing import *
from onlinejudge.service.atcoder import AtCoderProblem
from onlinejudge.service.codeforces import CodeforcesProblem
+from onlinejudge.service.topcoder import TopcoderProblem
from onlinejudge.type import *
logger = getLogger()
@@ -340,6 +341,14 @@ def main(problem: Problem, *, is_system: bool, is_compatibility: bool, is_full:
"json": data.json.decode(),
}
+ elif isinstance(problem, TopcoderProblem):
+ definition = problem._download_data(session=session).definition
+ result["name"] = definition["class"]
+ if is_full:
+ result["raw"] = {
+ "definition": definition,
+ }
+
else:
result["context"] = {}
diff --git a/setup.cfg b/setup.cfg
index 515ab49..c56af2e 100644
--- a/setup.cfg
+++ b/setup.cfg
@@ -52,6 +52,7 @@ disable =
missing-class-docstring,
missing-function-docstring,
missing-module-docstring,
+ no-else-break,
no-else-return,
no-member,
no-self-use,
| online-judge-tools/api-client | 76e1e9549c4dcbd2e7cc2fbae9c2e5c4117fd91d | diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index 5a04071..297843c 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -1,6 +1,9 @@
name: test
-on: [pull_request]
+on:
+ pull_request:
+ schedule:
+ - cron: '30 18 * * MON' # At 03:30 on Tuesday in JST
jobs:
test:
diff --git a/tests/get_problem_topcoder.py b/tests/get_problem_topcoder.py
new file mode 100644
index 0000000..04d90cd
--- /dev/null
+++ b/tests/get_problem_topcoder.py
@@ -0,0 +1,66 @@
+import unittest
+
+from onlinejudge_api.main import main
+
+
+class GetProblemTopcoderTest(unittest.TestCase):
+ def test_10760(self):
+ # `double` is used and one of values is a scientific form `1.0E50`.
+ url = 'https://community.topcoder.com/stat?c=problem_statement&pm=10760'
+ expected = {
+ "status": "ok",
+ "messages": [],
+ "result": {
+ "url": "https://community.topcoder.com/stat?c=problem_statement&pm=10760",
+ "tests": [{
+ "input": "2 5 8\n",
+ "output": "40.0\n"
+ }, {
+ "input": "2 1.5 1.8\n",
+ "output": "3.3\n"
+ }, {
+ "input": "3 8.26 7.54 3.2567\n",
+ "output": "202.82857868\n"
+ }, {
+ "input": "4 1.5 1.7 1.6 1.5\n",
+ "output": "9.920000000000002\n"
+ }, {
+ "input": "50 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10\n",
+ "output": "1.0E50\n"
+ }],
+ "name": "Nisoku"
+ },
+ }
+ actual = main(['get-problem', url], debug=True)
+ self.assertEqual(expected, actual)
+
+ def test_11026(self):
+ # `String[]` is used.
+ # The type of the return value is a list.
+ url = 'https://community.topcoder.com/stat?c=problem_statement&pm=11026'
+ expected = {
+ "status": "ok",
+ "messages": [],
+ "result": {
+ "url": "https://community.topcoder.com/stat?c=problem_statement&pm=11026",
+ "tests": [{
+ "input": "1 00\n1 00\n1 58\n",
+ "output": "2 0.38461538461538464 0.6153846153846154\n"
+ }, {
+ "input": "2 00 00\n2 00 00\n2 21 11\n",
+ "output": "2 0.5888888888888889 0.4111111111111111\n"
+ }, {
+ "input": "3 0000 0000 0000\n3 2284 0966 9334\n3 1090 3942 4336\n",
+ "output": "\n{0.19685958571981937, 0.24397246802233483, 0.31496640865458775, 0.24420153760325805 }\n"
+ }, {
+ "input": "5 01010110 00011000 00001000 10001010 10111110\n5 22218214 32244284 68402430 18140323 29043145\n5 87688689 36101317 69474068 29337374 87255881\n",
+ "output": "\n{0.11930766223754977, 0.14033271060661345, 0.0652282589028571, 0.14448118133046356, 0.1981894622733832, 0.10743462836879789, 0.16411823601857622, 0.06090786026175882 }\n"
+ }, {
+ "input": "1 10\n1 00\n1 00\n",
+ "output": "2 1.0 0.0\n"
+ }],
+ "name": "RandomApple"
+ },
+ }
+ actual = main(['get-problem', url], debug=True)
+ self.assertEqual(expected, actual)
diff --git a/tests/service_topcoder.py b/tests/service_topcoder.py
new file mode 100644
index 0000000..66c82d9
--- /dev/null
+++ b/tests/service_topcoder.py
@@ -0,0 +1,18 @@
+import unittest
+
+from onlinejudge.service.topcoder import TopcoderProblem, TopcoderService
+
+
+class TopcoderSerivceTest(unittest.TestCase):
+ def test_from_url(self):
+ self.assertIsInstance(TopcoderService.from_url('https://topcoder.com/'), TopcoderService)
+ self.assertIsInstance(TopcoderService.from_url('https://arena.topcoder.com/'), TopcoderService)
+ self.assertIsInstance(TopcoderService.from_url('https://community.topcoder.com/'), TopcoderService)
+ self.assertIsNone(TopcoderService.from_url('https://atcoder.jp/'))
+
+
+class TopcoderProblemTest(unittest.TestCase):
+ def test_from_url(self):
+ self.assertEqual(TopcoderProblem.from_url('https://arena.topcoder.com/index.html#/u/practiceCode/14230/10838/10760/1/303803').problem_id, 10760)
+ self.assertEqual(TopcoderProblem.from_url('https://community.topcoder.com/stat?c=problem_statement&pm=10760').problem_id, 10760)
+ self.assertIsNone(TopcoderProblem.from_url('https://atcoder.jp/contests/abc141/tasks/abc141_b'))
| Run CI once a week even if no commits
api-client sometimes breaks even when we don't change anything. So we need to run CI even when we don't make any commits, using something like cron.
https://help.github.com/en/actions/reference/events-that-trigger-workflows#scheduled-events-schedule | 0.0 | [
"tests/get_problem_topcoder.py::GetProblemTopcoderTest::test_10760",
"tests/get_problem_topcoder.py::GetProblemTopcoderTest::test_11026",
"tests/service_topcoder.py::TopcoderSerivceTest::test_from_url",
"tests/service_topcoder.py::TopcoderProblemTest::test_from_url"
] | [] | 2020-05-19 19:27:42+00:00 | 4,393 |
|
online-judge-tools__api-client-56 | diff --git a/onlinejudge/_implementation/utils.py b/onlinejudge/_implementation/utils.py
index f0cbc18..eb25a74 100644
--- a/onlinejudge/_implementation/utils.py
+++ b/onlinejudge/_implementation/utils.py
@@ -46,11 +46,14 @@ def next_sibling_tag(tag: bs4.Tag) -> bs4.Tag:
return tag
-# remove all HTML tag without interpretation (except <br>)
-# remove all comment
-# using DFS(Depth First Search)
-# discussed in https://github.com/kmyk/online-judge-tools/issues/553
+# TODO: Why this returns bs4.NavigableString?
def parse_content(parent: Union[bs4.NavigableString, bs4.Tag, bs4.Comment]) -> bs4.NavigableString:
+ """parse_content convert a tag to a string with interpretting `<br>` and ignoring other tags.
+
+ .. seealso::
+ https://github.com/kmyk/online-judge-tools/issues/553
+ """
+
res = ''
if isinstance(parent, bs4.Comment):
pass
@@ -104,10 +107,21 @@ class FormSender:
def dos2unix(s: str) -> str:
+ """
+ .. deprecated:: 10.1.0
+ Use :func:`format_sample_case` instead.
+ """
+
return s.replace('\r\n', '\n')
-def textfile(s: str) -> str: # should have trailing newline
+def textfile(s: str) -> str:
+ """textfile convert a string s to the "text file" defined in POSIX
+
+ .. deprecated:: 10.1.0
+ Use :func:`format_sample_case` instead.
+ """
+
if s.endswith('\n'):
return s
elif '\r\n' in s:
@@ -116,6 +130,19 @@ def textfile(s: str) -> str: # should have trailing newline
return s + '\n'
+def format_sample_case(s: str) -> str:
+ """format_sample_case convert a string s to a good form as a sample case.
+
+ A good form means that, it use LR instead of CRLF, it has the trailing newline, and it has no superfluous whitespaces.
+ """
+
+ if not s.strip():
+ return ''
+ lines = s.strip().splitlines()
+ lines = [line.strip() + '\n' for line in lines]
+ return ''.join(lines)
+
+
def exec_command(command_str: str, *, stdin: 'Optional[IO[Any]]' = None, input: Optional[bytes] = None, timeout: Optional[float] = None, gnu_time: Optional[str] = None) -> Tuple[Dict[str, Any], subprocess.Popen]:
if input is not None:
assert stdin is None
diff --git a/onlinejudge/service/codeforces.py b/onlinejudge/service/codeforces.py
index 055b4c3..e61ee12 100644
--- a/onlinejudge/service/codeforces.py
+++ b/onlinejudge/service/codeforces.py
@@ -325,9 +325,8 @@ class CodeforcesProblem(onlinejudge.type.Problem):
title, pre = list(non_empty_children)
assert 'title' in title.attrs['class']
assert pre.name == 'pre'
- s = utils.parse_content(pre)
- s = s.lstrip()
- samples.add(s.encode(), title.string)
+ data = utils.format_sample_case(str(utils.parse_content(pre)))
+ samples.add(data.encode(), title.string)
return samples.get()
def get_available_languages(self, *, session: Optional[requests.Session] = None) -> List[Language]:
diff --git a/onlinejudge_api/login_service.py b/onlinejudge_api/login_service.py
index 58c5e5b..1e6bc77 100644
--- a/onlinejudge_api/login_service.py
+++ b/onlinejudge_api/login_service.py
@@ -25,7 +25,7 @@ def main(service: Service, *, username: Optional[str], password: Optional[str],
result = {} # type: Dict[str, Any]
if check_only:
- assert username is None
+ # We cannot check `assert username is None` because some environments defines $USERNAME and it is set here. See https://github.com/online-judge-tools/api-client/issues/53
assert password is None
result["loggedIn"] = service.is_logged_in(session=session)
else:
| online-judge-tools/api-client | 3d005ac622c160f34b7355e30380e5de2b02a38c | diff --git a/tests/get_problem_codeforces.py b/tests/get_problem_codeforces.py
index 8687392..33fde3e 100644
--- a/tests/get_problem_codeforces.py
+++ b/tests/get_problem_codeforces.py
@@ -5,25 +5,144 @@ from onlinejudge_api.main import main
class GetProblemCodeforcesTest(unittest.TestCase):
def test_problemset_700_b(self):
+ """This tests a problem in the problemset.
+ """
+
url = 'http://codeforces.com/problemset/problem/700/B'
- expected = {"status": "ok", "messages": [], "result": {"url": "https://codeforces.com/problemset/problem/700/B", "tests": [{"input": "7 2\n1 5 6 2\n1 3\n3 2\n4 5\n3 7\n4 3\n4 6\n", "output": "6\n"}, {"input": "9 3\n3 2 1 6 5 9\n8 9\n3 2\n2 7\n3 4\n7 6\n4 5\n2 1\n2 8\n", "output": "9\n"}], "context": {}}}
+ expected = {
+ "status": "ok",
+ "messages": [],
+ "result": {
+ "url": "https://codeforces.com/problemset/problem/700/B",
+ "tests": [{
+ "input": "7 2\n1 5 6 2\n1 3\n3 2\n4 5\n3 7\n4 3\n4 6\n",
+ "output": "6\n"
+ }, {
+ "input": "9 3\n3 2 1 6 5 9\n8 9\n3 2\n2 7\n3 4\n7 6\n4 5\n2 1\n2 8\n",
+ "output": "9\n"
+ }],
+ "context": {}
+ },
+ }
actual = main(['get-problem', url], debug=True)
self.assertEqual(expected, actual)
def test_contest_538_h(self):
+ """This tests a old problem.
+ """
+
url = 'http://codeforces.com/contest/538/problem/H'
- expected = {"status": "ok", "messages": [], "result": {"url": "https://codeforces.com/contest/538/problem/H", "tests": [{"input": "10 20\n3 0\n3 6\n4 9\n16 25\n", "output": "POSSIBLE\n4 16\n112\n"}, {"input": "1 10\n3 3\n0 10\n0 10\n0 10\n1 2\n1 3\n2 3\n", "output": "IMPOSSIBLE\n"}], "name": "Summer Dichotomy", "context": {"contest": {"name": "Codeforces Round #300", "url": "https://codeforces.com/contest/538"}, "alphabet": "H"}}}
+ expected = {
+ "status": "ok",
+ "messages": [],
+ "result": {
+ "url": "https://codeforces.com/contest/538/problem/H",
+ "tests": [{
+ "input": "10 20\n3 0\n3 6\n4 9\n16 25\n",
+ "output": "POSSIBLE\n4 16\n112\n"
+ }, {
+ "input": "1 10\n3 3\n0 10\n0 10\n0 10\n1 2\n1 3\n2 3\n",
+ "output": "IMPOSSIBLE\n"
+ }],
+ "name": "Summer Dichotomy",
+ "context": {
+ "contest": {
+ "name": "Codeforces Round #300",
+ "url": "https://codeforces.com/contest/538"
+ },
+ "alphabet": "H"
+ }
+ },
+ }
actual = main(['get-problem', url], debug=True)
self.assertEqual(expected, actual)
def test_gym_101020_a(self):
+ """This tests a problem in the gym.
+ """
+
url = 'http://codeforces.com/gym/101020/problem/A'
- expected = {"status": "ok", "messages": [], "result": {"url": "https://codeforces.com/gym/101020/problem/A", "tests": [{"input": "3\n5 4\n1 2\n33 33\n", "output": "20\n2\n1089\n"}], "name": "Jerry's Window", "context": {"contest": {"name": "2015 Syrian Private Universities Collegiate Programming Contest", "url": "https://codeforces.com/gym/101020"}, "alphabet": "A"}}}
+ expected = {
+ "status": "ok",
+ "messages": [],
+ "result": {
+ "url": "https://codeforces.com/gym/101020/problem/A",
+ "tests": [{
+ "input": "3\n5 4\n1 2\n33 33\n",
+ "output": "20\n2\n1089\n"
+ }],
+ "name": "Jerry's Window",
+ "context": {
+ "contest": {
+ "name": "2015 Syrian Private Universities Collegiate Programming Contest",
+ "url": "https://codeforces.com/gym/101020"
+ },
+ "alphabet": "A"
+ }
+ },
+ }
actual = main(['get-problem', url], debug=True)
self.assertEqual(expected, actual)
def test_contest_1080_a(self):
+ """Recent (Nov 2018) problems has leading spaces for sample cases. We should check that they are removed.
+
+ .. seealso::
+ https://github.com/online-judge-tools/oj/issues/198
+ """
+
url = 'https://codeforces.com/contest/1080/problem/A'
- expected = {"status": "ok", "messages": [], "result": {"url": "https://codeforces.com/contest/1080/problem/A", "tests": [{"input": "3 5\n", "output": "10\n"}, {"input": "15 6\n", "output": "38\n"}], "name": "Petya and Origami", "context": {"contest": {"name": "Codeforces Round #524 (Div. 2)", "url": "https://codeforces.com/contest/1080"}, "alphabet": "A"}}}
+ expected = {
+ "status": "ok",
+ "messages": [],
+ "result": {
+ "url": "https://codeforces.com/contest/1080/problem/A",
+ "tests": [{
+ "input": "3 5\n",
+ "output": "10\n"
+ }, {
+ "input": "15 6\n",
+ "output": "38\n"
+ }],
+ "name": "Petya and Origami",
+ "context": {
+ "contest": {
+ "name": "Codeforces Round #524 (Div. 2)",
+ "url": "https://codeforces.com/contest/1080"
+ },
+ "alphabet": "A"
+ }
+ },
+ }
+ actual = main(['get-problem', url], debug=True)
+ self.assertEqual(expected, actual)
+
+ def test_contest_1344_d(self):
+ """The sample output of this problem has superfluous whitespaces. We should check that they are removed.
+
+ .. seealso::
+ see https://github.com/online-judge-tools/api-client/issues/24
+ """
+
+ url = 'https://codeforces.com/contest/1334/problem/D'
+ expected = {
+ "status": "ok",
+ "messages": [],
+ "result": {
+ "url": "https://codeforces.com/contest/1334/problem/D",
+ "tests": [{
+ "input": "3\n2 1 3\n3 3 6\n99995 9998900031 9998900031\n",
+ "output": "1 2 1\n1 3 2 3\n1\n"
+ }],
+ "name": "Minimum Euler Cycle",
+ "context": {
+ "contest": {
+ "name": "Educational Codeforces Round 85 (Rated for Div. 2)",
+ "url": "https://codeforces.com/contest/1334"
+ },
+ "alphabet": "D"
+ }
+ },
+ }
actual = main(['get-problem', url], debug=True)
self.assertEqual(expected, actual)
| Remove trailing spaces from sample cases of Codeforces
example: https://codeforces.com/contest/1334/problem/D
``` console
$ oj --version
online-judge-tools 9.2.0
$ oj d -n https://codeforces.com/contest/1334/problem/D
[x] problem recognized: CodeforcesProblem.from_url('https://codeforces.com/contest/1334/problem/D'): https://codeforces.com/contest/1334/problem/D
[x] load cookie from: /home/user/.local/share/online-judge-tools/cookie.jar
[x] GET: https://codeforces.com/contest/1334/problem/D
[x] 200 OK
[x] save cookie to: /home/user/.local/share/online-judge-tools/cookie.jar
[*] sample 0
[x] input: sample-1
3
2 1 3
3 3 6
99995 9998900031 9998900031
[x] output: sample-1
1 2 1_(trailing spaces)
1 3 2 3_(trailing spaces)
1_(trailing spaces)
``` | 0.0 | [
"tests/get_problem_codeforces.py::GetProblemCodeforcesTest::test_contest_1344_d"
] | [
"tests/get_problem_codeforces.py::GetProblemCodeforcesTest::test_gym_101020_a",
"tests/get_problem_codeforces.py::GetProblemCodeforcesTest::test_problemset_700_b"
] | 2020-06-05 17:08:59+00:00 | 4,394 |
|
online-judge-tools__api-client-91 | diff --git a/onlinejudge/service/yukicoder.py b/onlinejudge/service/yukicoder.py
index 1cd8528..121ef5c 100644
--- a/onlinejudge/service/yukicoder.py
+++ b/onlinejudge/service/yukicoder.py
@@ -6,6 +6,7 @@ the module for yukicoder (https://yukicoder.me/)
:note: There is the official API https://petstore.swagger.io/?url=https://yukicoder.me/api/swagger.yaml
"""
+import json
import posixpath
import urllib.parse
from logging import getLogger
@@ -139,6 +140,79 @@ class YukicoderService(onlinejudge.type.Service):
star += '.5'
return star
+ _problems = None
+
+ @classmethod
+ def _get_problems(cls, *, session: Optional[requests.Session] = None) -> List[Dict[str, Any]]:
+ """`_get_problems` wraps the official API and caches the result.
+ """
+
+ session = session or utils.get_default_session()
+ if cls._problems is None:
+ url = 'https://yukicoder.me/api/v1/problems'
+ resp = utils.request('GET', url, session=session)
+ cls._problems = json.loads(resp.content.decode())
+ return cls._problems
+
+ _contests = None # type: Optional[List[Dict[str, Any]]]
+
+ @classmethod
+ def _get_contests(cls, *, session: Optional[requests.Session] = None) -> List[Dict[str, Any]]:
+ """`_get_contests` wraps the official API and caches the result.
+ """
+
+ session = session or utils.get_default_session()
+ if cls._contests is None:
+ cls._contests = []
+ for url in ('https://yukicoder.me/api/v1/contest/past', 'https://yukicoder.me/api/v1/contest/future'):
+ resp = utils.request('GET', url, session=session)
+ cls._contests.extend(json.loads(resp.content.decode()))
+ return cls._contests
+
+
+class YukicoderContest(onlinejudge.type.Contest):
+ """
+ :ivar contest_id: :py:class:`int`
+
+ .. versionadded:: 10.4.0
+ """
+ def __init__(self, *, contest_id: int):
+ self.contest_id = contest_id
+
+ def list_problems(self, *, session: Optional[requests.Session] = None) -> Sequence['YukicoderProblem']:
+ """
+ :raises RuntimeError:
+ """
+
+ session = session or utils.get_default_session()
+ for contest in YukicoderService._get_contests(session=session):
+ if contest['Id'] == self.contest_id:
+ table = {problem['ProblemId']: problem['No'] for problem in YukicoderService._get_problems(session=session)}
+ return [YukicoderProblem(problem_no=table[problem_id]) for problem_id in contest['ProblemIdList']]
+ raise RuntimeError('Failed to get the contest information from API: {}'.format(self.get_url()))
+
+ def get_url(self) -> str:
+ return 'https://yukicoder.me/contests/{}'.format(self.contest_id)
+
+ def get_service(self) -> Service:
+ return YukicoderService()
+
+ @classmethod
+ def from_url(cls, url: str) -> Optional['Contest']:
+ # example: https://yukicoder.me/contests/276
+ # example: http://yukicoder.me/contests/276/all
+ result = urllib.parse.urlparse(url)
+ dirs = utils.normpath(result.path).split('/')
+ if result.scheme in ('', 'http', 'https') and result.netloc == 'yukicoder.me':
+ if len(dirs) >= 3 and dirs[1] == 'contests':
+ try:
+ contest_id = int(dirs[2])
+ except ValueError:
+ pass
+ else:
+ return cls(contest_id=contest_id)
+ return None
+
class YukicoderProblem(onlinejudge.type.Problem):
def __init__(self, *, problem_no=None, problem_id=None):
@@ -281,4 +355,5 @@ class YukicoderProblem(onlinejudge.type.Problem):
onlinejudge.dispatch.services += [YukicoderService]
+onlinejudge.dispatch.contests += [YukicoderContest]
onlinejudge.dispatch.problems += [YukicoderProblem]
| online-judge-tools/api-client | fee573701c31fff192ceff2915902db084b244c0 | diff --git a/tests/service_yukicoder.py b/tests/service_yukicoder.py
index 6b1ec78..b46f5b8 100644
--- a/tests/service_yukicoder.py
+++ b/tests/service_yukicoder.py
@@ -3,7 +3,7 @@ import unittest
from tests.implementation_utils import get_handmade_sample_cases
-from onlinejudge.service.yukicoder import YukicoderProblem, YukicoderService
+from onlinejudge.service.yukicoder import YukicoderContest, YukicoderProblem, YukicoderService
from onlinejudge.type import *
@@ -122,6 +122,22 @@ class YukicoderProblemTest(unittest.TestCase):
])
+class YukicoderContestTest(unittest.TestCase):
+ def test_from_url(self):
+ self.assertEqual(YukicoderContest.from_url('https://yukicoder.me/contests/276').contest_id, 276)
+ self.assertEqual(YukicoderContest.from_url('http://yukicoder.me/contests/276/all').contest_id, 276)
+
+ def test_list_problems(self):
+ self.assertEqual(YukicoderContest.from_url('https://yukicoder.me/contests/276').list_problems(), [
+ YukicoderProblem(problem_no=1168),
+ YukicoderProblem(problem_no=1169),
+ YukicoderProblem(problem_no=1170),
+ YukicoderProblem(problem_no=1171),
+ YukicoderProblem(problem_no=1172),
+ YukicoderProblem(problem_no=1173),
+ ])
+
+
class YukicoderOfficialAPITest(unittest.TestCase):
def test_get_submissions(self):
data = YukicoderService().get_submissions(page=3, status='TLE')
| Support yukicoder.list_problems()
欲しい。順位表のリンクがあるから頑張れば取れるはず、、 | 0.0 | [
"tests/service_yukicoder.py::YukicoderProblemTest::test_donwload_sample_cases",
"tests/service_yukicoder.py::YukicoderProblemTest::test_donwload_sample_cases_issue_192",
"tests/service_yukicoder.py::YukicoderProblemTest::test_donwload_sample_cases_issue_355",
"tests/service_yukicoder.py::YukicoderProblemTest::test_from_url",
"tests/service_yukicoder.py::YukicoderContestTest::test_from_url",
"tests/service_yukicoder.py::YukicoderContestTest::test_list_problems",
"tests/service_yukicoder.py::YukicoderOfficialAPITest::test_get_submissions",
"tests/service_yukicoder.py::YukicoderProblemGetInputFormatTest::test_normal",
"tests/service_yukicoder.py::YukicoderProblemGetInputFormatTest::test_problem_without_input"
] | [] | 2020-08-15 14:53:17+00:00 | 4,395 |
|
online-judge-tools__oj-759 | diff --git a/onlinejudge_command/utils.py b/onlinejudge_command/utils.py
index de82639..02e867a 100644
--- a/onlinejudge_command/utils.py
+++ b/onlinejudge_command/utils.py
@@ -77,8 +77,13 @@ def exec_command(command_str: str, *, stdin: Optional[IO[Any]] = None, input: Op
try:
answer, _ = proc.communicate(input=input, timeout=timeout)
except subprocess.TimeoutExpired:
+ pass
+ finally:
if preexec_fn is not None:
- os.killpg(os.getpgid(proc.pid), signal.SIGTERM)
+ try:
+ os.killpg(os.getpgid(proc.pid), signal.SIGTERM)
+ except ProcessLookupError:
+ pass
else:
proc.terminate()
| online-judge-tools/oj | 99963a50f30b66ae6ddd6dde3e3fb235c62582e1 | diff --git a/tests/command_test.py b/tests/command_test.py
index f5d7b25..d10aa46 100644
--- a/tests/command_test.py
+++ b/tests/command_test.py
@@ -3,7 +3,9 @@ import os
import pathlib
import random
import shutil
+import signal
import sys
+import threading
import unittest
import tests.utils
@@ -1011,7 +1013,7 @@ class TestTest(unittest.TestCase):
)
@unittest.skipIf(os.name == 'nt', "procfs is required")
- def test_call_test_check_no_zombie(self):
+ def test_call_test_check_no_zombie_with_tle(self):
marker = 'zombie-%08x' % random.randrange(2**32)
data = self.snippet_call_test(
args=['-c', tests.utils.python_c("import time; time.sleep(100) # {}".format(marker)), '--tle', '1'],
@@ -1048,6 +1050,35 @@ class TestTest(unittest.TestCase):
with open(str(cmdline), 'rb') as fh:
self.assertNotIn(marker.encode(), fh.read())
+ @unittest.skipIf(os.name == 'nt', "procfs is required")
+ def test_call_test_check_no_zombie_with_keyboard_interrupt(self):
+ marker_for_callee = 'zombie-%08x' % random.randrange(2**32)
+ marker_for_caller = 'zombie-%08x' % random.randrange(2**32)
+ files = [
+ {
+ 'path': 'test/{}-1.in'.format(marker_for_caller),
+ 'data': 'foo\n'
+ },
+ ]
+
+ def send_keyboard_interrupt():
+ for cmdline in pathlib.Path('/proc').glob('*/cmdline'):
+ with open(str(cmdline), 'rb') as fh:
+ if marker_for_caller.encode() in fh.read():
+ pid = int(cmdline.parts[2])
+ print('sending Ctrl-C to', pid)
+ os.kill(pid, signal.SIGINT)
+
+ timer = threading.Timer(1.0, send_keyboard_interrupt)
+ timer.start()
+ result = tests.utils.run_in_sandbox(args=['-v', 'test', '-c', tests.utils.python_c("import time; time.sleep(10) # {}".format(marker_for_callee)), 'test/{}-1.in'.format(marker_for_caller)], files=files)
+ self.assertNotEqual(result['proc'].returncode, 0)
+
+ # check there are no processes whose command-line arguments contains the marker word
+ for cmdline in pathlib.Path('/proc').glob('*/cmdline'):
+ with open(str(cmdline), 'rb') as fh:
+ self.assertNotIn(marker_for_callee.encode(), fh.read())
+
@unittest.skipIf(os.name == 'nt', "memory checking is disabled and output is different with Linux")
class TestTestLog(unittest.TestCase):
| Zombie processes remains when terminate oj test with Ctrl-C | 0.0 | [
"tests/command_test.py::TestTest::test_call_test_check_no_zombie_with_keyboard_interrupt"
] | [
"tests/command_test.py::TestTest::test_call_expected_uses_crlf",
"tests/command_test.py::TestTest::test_call_non_unicode",
"tests/command_test.py::TestTest::test_call_output_uses_both_lf_and_crlf",
"tests/command_test.py::TestTest::test_call_output_uses_crlf",
"tests/command_test.py::TestTest::test_call_runtime_error",
"tests/command_test.py::TestTest::test_call_stderr",
"tests/command_test.py::TestTest::test_call_stderr_and_fail",
"tests/command_test.py::TestTest::test_call_test_check_no_zombie_with_tle",
"tests/command_test.py::TestTest::test_call_test_dir",
"tests/command_test.py::TestTest::test_call_test_float",
"tests/command_test.py::TestTest::test_call_test_format",
"tests/command_test.py::TestTest::test_call_test_format_hack",
"tests/command_test.py::TestTest::test_call_test_format_select",
"tests/command_test.py::TestTest::test_call_test_ignore_backup",
"tests/command_test.py::TestTest::test_call_test_in_parallel",
"tests/command_test.py::TestTest::test_call_test_multiline_all",
"tests/command_test.py::TestTest::test_call_test_multiline_line",
"tests/command_test.py::TestTest::test_call_test_norstrip",
"tests/command_test.py::TestTest::test_call_test_not_tle",
"tests/command_test.py::TestTest::test_call_test_re_glob_injection",
"tests/command_test.py::TestTest::test_call_test_select",
"tests/command_test.py::TestTest::test_call_test_shell",
"tests/command_test.py::TestTest::test_call_test_simple",
"tests/command_test.py::TestTest::test_call_test_special_judge",
"tests/command_test.py::TestTest::test_call_test_tle"
] | 2020-05-03 20:08:18+00:00 | 4,396 |
|
online-judge-tools__template-generator-56 | diff --git a/onlinejudge_template/generator/python.py b/onlinejudge_template/generator/python.py
index 88075ef..5fd6303 100644
--- a/onlinejudge_template/generator/python.py
+++ b/onlinejudge_template/generator/python.py
@@ -114,11 +114,11 @@ def _generate_input_dfs(node: FormatNode, *, declared: Set[VarName], initialized
elif type_ == VarType.Float:
return OtherNode(line=f"""{var} = 100.0 * random.random() # TODO: edit here""")
elif type_ == VarType.String:
- return OtherNode(line=f"""{var} = ''.join([random.choice('abcde') for range(random.randint(1, 100))]) # TODO: edit here""")
+ return OtherNode(line=f"""{var} = ''.join([random.choice('abcde') for _ in range(random.randint(1, 100))]) # TODO: edit here""")
elif type_ == VarType.Char:
return OtherNode(line=f"""{var} = random.choice('abcde') # TODO: edit here""")
else:
- return OtherNode(line=f"""{var} = None # TODO: edit here""")
+ return OtherNode(line=f"""{var} = random.randint(1, 10) # TODO: edit here""")
elif isinstance(node, NewlineNode):
return SentencesNode(sentences=[])
elif isinstance(node, SequenceNode):
diff --git a/setup.cfg b/setup.cfg
index ac26f88..ca5af62 100644
--- a/setup.cfg
+++ b/setup.cfg
@@ -14,9 +14,9 @@ classifiers =
[options.extras_require]
dev =
- isort == 5.4.1
+ isort == 5.5.2
mypy == 0.782
- pylint == 2.5.3
+ pylint == 2.6.0
yapf == 0.30.0
doc =
sphinx >= 2.4
| online-judge-tools/template-generator | f0230727fb9e67eb20d3f5c537d1747bb9fb90b3 | diff --git a/tests/command_template.py b/tests/command_template.py
index 28de86f..facea02 100644
--- a/tests/command_template.py
+++ b/tests/command_template.py
@@ -13,6 +13,7 @@ from onlinejudge_template.main import main
class TestOJTemplateCommand(unittest.TestCase):
"""TestOJTemplateCommand is a class for end-to-end tests about oj-template command.
+ The tests actually compile and execute the generated code and check them get AC on sample cases.
"""
def _helper(self, *, url: str, template: str, placeholder: str, code: str, compile: Callable[[pathlib.Path], List[str]], command: Callable[[pathlib.Path], str]):
with tempfile.TemporaryDirectory() as tmpdir_:
@@ -43,8 +44,8 @@ class TestOJTemplateCommand(unittest.TestCase):
y = str(b) * a
return int(min(x, y))
"""), ' ')
- compile = lambda tmpdir: [sys.executable, '--version']
- command = lambda tmpdir: ' '.join([sys.executable, str(tmpdir / 'main.py')])
+ compile = lambda tmpdir: [sys.executable, '--version'] # nop
+ command = lambda tmpdir: ' '.join([sys.executable, str(tmpdir / template)])
self._helper(url=url, template=template, placeholder=placeholder, code=code, compile=compile, command=command)
def test_main_cpp_aplusb(self) -> None:
@@ -54,6 +55,60 @@ class TestOJTemplateCommand(unittest.TestCase):
code = textwrap.indent(textwrap.dedent("""\
return A + B;
"""), ' ')
- compile = lambda tmpdir: ['g++', '-std=c++14', str(tmpdir / 'main.cpp'), '-o', str(tmpdir / 'a.out')]
+ compile = lambda tmpdir: ['g++', '-std=c++14', str(tmpdir / template), '-o', str(tmpdir / 'a.out')]
command = lambda tmpdir: str(tmpdir / 'a.out')
self._helper(url=url, template=template, placeholder=placeholder, code=code, compile=compile, command=command)
+
+
+class TestOJTemplateCommandGenerator(unittest.TestCase):
+ """TestOJTemplateCommandGenerator is a class for end-to-end tests about oj-template command.
+ The tests actually executes the generator and check the result with a validator.
+ """
+ def _helper(self, *, url: str, template: str, compile: Callable[[pathlib.Path], List[str]], command: Callable[[pathlib.Path], List[str]]):
+ with tempfile.TemporaryDirectory() as tmpdir_:
+ tmpdir = pathlib.Path(tmpdir_)
+ source_file = tmpdir / template
+
+ # generate
+ with open(source_file, 'w') as fh:
+ with contextlib.redirect_stdout(fh):
+ main(['-t', template, url])
+
+ # test
+ subprocess.check_call(compile(tmpdir), stdout=sys.stdout, stderr=sys.stderr)
+ return subprocess.check_output(command(tmpdir), stderr=sys.stderr)
+
+ def test_generate_py_arc088_b(self) -> None:
+ # arc088_b has a format with a binary string variable.
+ url = 'https://atcoder.jp/contests/arc088/tasks/arc088_b'
+ template = 'generate.py'
+ compile = lambda tmpdir: [sys.executable, '--version'] # nop
+ command = lambda tmpdir: [sys.executable, str(tmpdir / template)]
+
+ def validate(case: bytes) -> None:
+ lines = case.splitlines()
+ self.assertEqual(len(lines), 1)
+ s, = lines[0].split()
+ self.assertTrue(s.isalpha())
+
+ validate(self._helper(url=url, template=template, compile=compile, command=command))
+
+ def test_generate_py_arc089_b(self) -> None:
+ # arc089_b has a non-trivial format with char variables.
+ url = 'https://atcoder.jp/contests/arc089/tasks/arc089_b'
+ template = 'generate.py'
+ compile = lambda tmpdir: [sys.executable, '--version'] # nop
+ command = lambda tmpdir: [sys.executable, str(tmpdir / template)]
+
+ def validate(case: bytes) -> None:
+ lines = case.splitlines()
+ n, k = map(int, lines[0].split())
+ self.assertEqual(len(lines) - 1, n)
+ for line in lines[1:]:
+ x, y, c = line.split()
+ int(x)
+ int(y)
+ self.assertTrue(c.isalpha())
+ self.assertEqual(len(c), 1)
+
+ validate(self._helper(url=url, template=template, compile=compile, command=command))
| The default template `generate.py` has syntax error when string variables exsit in input
```shell
oj-template -t generate.py https://atcoder.jp/contests/abc166/tasks/abc166_a
```
の生成コードが syntax error となっているようです。文字列が入力に与えられる他の問題でも同様でした。僕が python に不慣れなため、具体的な間違いの内容は分かりませんでした。。 | 0.0 | [
"tests/command_template.py::TestOJTemplateCommandGenerator::test_generate_py_arc088_b"
] | [
"tests/command_template.py::TestOJTemplateCommand::test_main_py_abc152_b",
"tests/command_template.py::TestOJTemplateCommandGenerator::test_generate_py_arc089_b"
] | 2020-09-19 04:45:29+00:00 | 4,397 |
|
open-contracting__ocds-merge-22 | diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8c9d549..b732eb9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,10 @@
## 0.5.2
+### Changed
+
+* If there is more than one release, but the `date` field is missing or null, the `MissingDateKeyError` and `NullDateValueError` exceptions are raised, respestively, instead of the generic `KeyError` and `TypeError`.
+
### Fixed
* If a field's value is set to `null`, it is omitted from the compiled release.
diff --git a/ocdsmerge/merge.py b/ocdsmerge/merge.py
index 7f6c1ef..842cb66 100644
--- a/ocdsmerge/merge.py
+++ b/ocdsmerge/merge.py
@@ -31,6 +31,18 @@ class IdDict(OrderedDict):
self._identifier = identifier
+class OCDSMergeError(Exception):
+ """Base class for exceptions from within this package"""
+
+
+class MissingDateKeyError(OCDSMergeError):
+ """Raised when a release is missing a 'date' key"""
+
+
+class NullDateValueError(OCDSMergeError):
+ """Raised when a release has a null 'date' value"""
+
+
@lru_cache()
def get_tags():
"""
@@ -274,6 +286,20 @@ def process_flattened(flattened):
return processed
+def sorted_releases(releases):
+ """
+ Sorts a list of releases by date.
+ """
+ if len(releases) == 1:
+ return releases
+ try:
+ return sorted(releases, key=lambda release: release['date'])
+ except KeyError:
+ raise MissingDateKeyError
+ except TypeError:
+ raise NullDateValueError
+
+
def merge(releases, schema=None, merge_rules=None):
"""
Merges a list of releases into a compiledRelease.
@@ -282,11 +308,12 @@ def merge(releases, schema=None, merge_rules=None):
merge_rules = get_merge_rules(schema)
merged = OrderedDict({('tag',): ['compiled']})
- for release in sorted(releases, key=lambda release: release['date']):
+ for release in sorted_releases(releases):
release = release.copy()
- ocid = release['ocid']
- date = release['date']
+ # `ocid` and `date` are required fields, but the data can be invalid.
+ ocid = release.get('ocid')
+ date = release.get('date')
# Prior to OCDS 1.1.4, `tag` didn't set "omitWhenMerged": true.
release.pop('tag', None) # becomes ["compiled"]
@@ -313,15 +340,16 @@ def merge_versioned(releases, schema=None, merge_rules=None):
merge_rules = get_merge_rules(schema)
merged = OrderedDict()
- for release in sorted(releases, key=lambda release: release['date']):
+ for release in sorted_releases(releases):
release = release.copy()
# Don't version the OCID.
- ocid = release.pop('ocid')
+ ocid = release.pop('ocid', None)
merged[('ocid',)] = ocid
- releaseID = release['id']
- date = release['date']
+ # `id` and `date` are required fields, but the data can be invalid.
+ releaseID = release.get('id')
+ date = release.get('date')
# Prior to OCDS 1.1.4, `tag` didn't set "omitWhenMerged": true.
tag = release.pop('tag', None)
| open-contracting/ocds-merge | 09ef170b24f3fd13bdb1e33043d22de5f0448a9d | diff --git a/tests/test_merge.py b/tests/test_merge.py
index 1b25c32..7b4df8e 100644
--- a/tests/test_merge.py
+++ b/tests/test_merge.py
@@ -24,7 +24,8 @@ from jsonschema import FormatChecker
from jsonschema.validators import Draft4Validator as validator
from ocdsmerge import merge, merge_versioned, get_merge_rules
-from ocdsmerge.merge import get_tags, get_release_schema_url, flatten, process_flattened
+from ocdsmerge.merge import (get_tags, get_release_schema_url, flatten, process_flattened, MissingDateKeyError,
+ NullDateValueError)
tags = {
'1.0': '1__0__3',
@@ -64,6 +65,30 @@ def custom_warning_formatter(message, category, filename, lineno, line=None):
warnings.formatwarning = custom_warning_formatter
[email protected]('error, data', [(MissingDateKeyError, {}), (NullDateValueError, {'date': None})])
+def test_date_errors(error, data):
+ for method in (merge, merge_versioned):
+ with pytest.raises(error):
+ method([{'date': '2010-01-01'}, data])
+
+ release = deepcopy(data)
+ assert merge([release]) == {
+ 'id': 'None-None',
+ 'tag': ['compiled'],
+ }
+
+ release = deepcopy(data)
+ release['initiationType'] = 'tender'
+ assert merge_versioned([release]) == {
+ 'initiationType': [{
+ 'releaseID': None,
+ 'releaseDate': None,
+ 'releaseTag': None,
+ 'value': 'tender',
+ }],
+ }
+
+
@pytest.mark.parametrize('filename,schema', test_merge_argvalues)
def test_merge(filename, schema):
if filename.endswith('-compiled.json'):
| Crashs if no 'date' key in data.
https://github.com/open-contracting/ocds-merge/blob/master/ocdsmerge/merge.py#L316
We are currently seeing crashes in Kingfisher process where there is data with no 'date' key.
In fairness, I'm not sure what the merge library can actually do in this case 😄 ... but maybe we want to think about good ways to report this upwards. | 0.0 | [
"tests/test_merge.py::test_date_errors[MissingDateKeyError-data0]",
"tests/test_merge.py::test_date_errors[NullDateValueError-data1]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/null-compiled.json-None]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/empty-identifiermerge-array-compiled.json-None]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/simple-compiled.json-None]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/single-empty-wholelistmerge-array-compiled.json-None]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/fill-wholelistmerge-array-compiled.json-None]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/empty-object-compiled.json-None]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/unit-compiled.json-None]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/fill-object-compiled.json-None]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/lists-compiled.json-None]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/single-empty-object-compiled.json-None]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/string-list-compiled.json-None]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/single-empty-identifiermerge-array-compiled.json-None]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/mergeid-compiled.json-None]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/initial-null-compiled.json-None]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/contextual-compiled.json-None]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/fill-identifiermerge-array-compiled.json-None]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/empty-wholelistmerge-array-compiled.json-None]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/fill-wholelistmerge-array-versioned.json-None]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/single-empty-object-versioned.json-None]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/empty-identifiermerge-array-versioned.json-None]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/fill-object-versioned.json-None]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/single-empty-wholelistmerge-array-versioned.json-None]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/mergeid-versioned.json-None]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/null-versioned.json-None]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/empty-object-versioned.json-None]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/initial-null-versioned.json-None]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/unit-versioned.json-None]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/empty-wholelistmerge-array-versioned.json-None]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/simple-versioned.json-None]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/contextual-versioned.json-None]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/fill-identifiermerge-array-versioned.json-None]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/lists-versioned.json-None]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/single-empty-identifiermerge-array-versioned.json-None]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/string-list-versioned.json-None]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/null-compiled.json-http://standard.open-contracting.org/schema/1__1__2/release-schema.json]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/empty-identifiermerge-array-compiled.json-http://standard.open-contracting.org/schema/1__1__2/release-schema.json]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/simple-compiled.json-http://standard.open-contracting.org/schema/1__1__2/release-schema.json]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/single-empty-wholelistmerge-array-compiled.json-http://standard.open-contracting.org/schema/1__1__2/release-schema.json]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/fill-wholelistmerge-array-compiled.json-http://standard.open-contracting.org/schema/1__1__2/release-schema.json]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/empty-object-compiled.json-http://standard.open-contracting.org/schema/1__1__2/release-schema.json]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/unit-compiled.json-http://standard.open-contracting.org/schema/1__1__2/release-schema.json]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/fill-object-compiled.json-http://standard.open-contracting.org/schema/1__1__2/release-schema.json]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/lists-compiled.json-http://standard.open-contracting.org/schema/1__1__2/release-schema.json]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/single-empty-object-compiled.json-http://standard.open-contracting.org/schema/1__1__2/release-schema.json]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/string-list-compiled.json-http://standard.open-contracting.org/schema/1__1__2/release-schema.json]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/single-empty-identifiermerge-array-compiled.json-http://standard.open-contracting.org/schema/1__1__2/release-schema.json]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/mergeid-compiled.json-http://standard.open-contracting.org/schema/1__1__2/release-schema.json]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/initial-null-compiled.json-http://standard.open-contracting.org/schema/1__1__2/release-schema.json]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/contextual-compiled.json-http://standard.open-contracting.org/schema/1__1__2/release-schema.json]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/fill-identifiermerge-array-compiled.json-http://standard.open-contracting.org/schema/1__1__2/release-schema.json]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/empty-wholelistmerge-array-compiled.json-http://standard.open-contracting.org/schema/1__1__2/release-schema.json]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/fill-wholelistmerge-array-versioned.json-http://standard.open-contracting.org/schema/1__1__2/release-schema.json]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/single-empty-object-versioned.json-http://standard.open-contracting.org/schema/1__1__2/release-schema.json]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/empty-identifiermerge-array-versioned.json-http://standard.open-contracting.org/schema/1__1__2/release-schema.json]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/fill-object-versioned.json-http://standard.open-contracting.org/schema/1__1__2/release-schema.json]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/single-empty-wholelistmerge-array-versioned.json-http://standard.open-contracting.org/schema/1__1__2/release-schema.json]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/mergeid-versioned.json-http://standard.open-contracting.org/schema/1__1__2/release-schema.json]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/null-versioned.json-http://standard.open-contracting.org/schema/1__1__2/release-schema.json]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/empty-object-versioned.json-http://standard.open-contracting.org/schema/1__1__2/release-schema.json]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/initial-null-versioned.json-http://standard.open-contracting.org/schema/1__1__2/release-schema.json]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/unit-versioned.json-http://standard.open-contracting.org/schema/1__1__2/release-schema.json]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/empty-wholelistmerge-array-versioned.json-http://standard.open-contracting.org/schema/1__1__2/release-schema.json]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/simple-versioned.json-http://standard.open-contracting.org/schema/1__1__2/release-schema.json]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/contextual-versioned.json-http://standard.open-contracting.org/schema/1__1__2/release-schema.json]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/fill-identifiermerge-array-versioned.json-http://standard.open-contracting.org/schema/1__1__2/release-schema.json]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/lists-versioned.json-http://standard.open-contracting.org/schema/1__1__2/release-schema.json]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/single-empty-identifiermerge-array-versioned.json-http://standard.open-contracting.org/schema/1__1__2/release-schema.json]",
"tests/test_merge.py::test_merge[tests/fixtures/1.1/string-list-versioned.json-http://standard.open-contracting.org/schema/1__1__2/release-schema.json]",
"tests/test_merge.py::test_merge[tests/fixtures/1.0/suppliers-compiled.json-http://standard.open-contracting.org/schema/1__0__3/release-schema.json]",
"tests/test_merge.py::test_merge[tests/fixtures/1.0/suppliers-versioned.json-http://standard.open-contracting.org/schema/1__0__3/release-schema.json]",
"tests/test_merge.py::test_merge[tests/fixtures/schema/omit-when-merged-array-of-non-objects-compiled.json-schema70]",
"tests/test_merge.py::test_merge[tests/fixtures/schema/whole-list-merge-object-compiled.json-schema71]",
"tests/test_merge.py::test_merge[tests/fixtures/schema/deep-identifier-merge-compiled.json-schema72]",
"tests/test_merge.py::test_merge[tests/fixtures/schema/deep-whole-list-merge-compiled.json-schema73]",
"tests/test_merge.py::test_merge[tests/fixtures/schema/omit-when-merged-shadowed-compiled.json-schema74]",
"tests/test_merge.py::test_merge[tests/fixtures/schema/deep-omit-when-merged-compiled.json-schema75]",
"tests/test_merge.py::test_merge[tests/fixtures/schema/whole-list-merge-duplicate-id-compiled.json-schema76]",
"tests/test_merge.py::test_merge[tests/fixtures/schema/whole-list-merge-no-id-compiled.json-schema77]",
"tests/test_merge.py::test_merge[tests/fixtures/schema/identifier-merge-duplicate-id-compiled.json-schema78]",
"tests/test_merge.py::test_merge[tests/fixtures/schema/no-top-level-id-compiled.json-schema79]",
"tests/test_merge.py::test_merge[tests/fixtures/schema/identifier-merge-collision-compiled.json-schema80]",
"tests/test_merge.py::test_merge[tests/fixtures/schema/merge-property-is-false-compiled.json-schema81]",
"tests/test_merge.py::test_merge[tests/fixtures/schema/whole-list-merge-empty-compiled.json-schema82]",
"tests/test_merge.py::test_merge[tests/fixtures/schema/version-id-versioned.json-schema83]",
"tests/test_merge.py::test_merge_when_array_is_mixed[0-0]",
"tests/test_merge.py::test_merge_when_array_is_mixed[0-1]",
"tests/test_merge.py::test_merge_when_array_is_mixed[1-0]",
"tests/test_merge.py::test_merge_when_array_is_mixed[1-1]",
"tests/test_merge.py::test_merge_when_array_is_mixed_without_schema[0-0]",
"tests/test_merge.py::test_merge_when_array_is_mixed_without_schema[0-1]",
"tests/test_merge.py::test_merge_when_array_is_mixed_without_schema[1-0]",
"tests/test_merge.py::test_merge_when_array_is_mixed_without_schema[1-1]",
"tests/test_merge.py::test_get_tags",
"tests/test_merge.py::test_get_release_schema_url",
"tests/test_merge.py::test_get_merge_rules_1_1",
"tests/test_merge.py::test_get_merge_rules_1_0",
"tests/test_merge.py::test_flatten",
"tests/test_merge.py::test_process_flattened",
"tests/test_merge.py::test_valid[tests/fixtures/1.0/suppliers-compiled.json-schema0]",
"tests/test_merge.py::test_valid[tests/fixtures/1.0/suppliers.json-schema1]",
"tests/test_merge.py::test_valid[tests/fixtures/1.0/suppliers-versioned.json-schema2]",
"tests/test_merge.py::test_valid[tests/fixtures/1.1/fill-object.json-schema3]",
"tests/test_merge.py::test_valid[tests/fixtures/1.1/null-compiled.json-schema4]",
"tests/test_merge.py::test_valid[tests/fixtures/1.1/initial-null.json-schema5]",
"tests/test_merge.py::test_valid[tests/fixtures/1.1/empty-wholelistmerge-array.json-schema7]",
"tests/test_merge.py::test_valid[tests/fixtures/1.1/single-empty-identifiermerge-array.json-schema8]",
"tests/test_merge.py::test_valid[tests/fixtures/1.1/empty-identifiermerge-array-compiled.json-schema9]",
"tests/test_merge.py::test_valid[tests/fixtures/1.1/string-list.json-schema10]",
"tests/test_merge.py::test_valid[tests/fixtures/1.1/simple-compiled.json-schema11]",
"tests/test_merge.py::test_valid[tests/fixtures/1.1/mergeid.json-schema12]",
"tests/test_merge.py::test_valid[tests/fixtures/1.1/single-empty-wholelistmerge-array-compiled.json-schema13]",
"tests/test_merge.py::test_valid[tests/fixtures/1.1/single-empty-wholelistmerge-array.json-schema14]",
"tests/test_merge.py::test_valid[tests/fixtures/1.1/empty-object.json-schema15]",
"tests/test_merge.py::test_valid[tests/fixtures/1.1/fill-wholelistmerge-array-compiled.json-schema16]",
"tests/test_merge.py::test_valid[tests/fixtures/1.1/empty-object-compiled.json-schema17]",
"tests/test_merge.py::test_valid[tests/fixtures/1.1/unit-compiled.json-schema18]",
"tests/test_merge.py::test_valid[tests/fixtures/1.1/single-empty-object.json-schema19]",
"tests/test_merge.py::test_valid[tests/fixtures/1.1/empty-identifiermerge-array.json-schema20]",
"tests/test_merge.py::test_valid[tests/fixtures/1.1/fill-object-compiled.json-schema21]",
"tests/test_merge.py::test_valid[tests/fixtures/1.1/null.json-schema22]",
"tests/test_merge.py::test_valid[tests/fixtures/1.1/lists-compiled.json-schema23]",
"tests/test_merge.py::test_valid[tests/fixtures/1.1/fill-identifiermerge-array.json-schema24]",
"tests/test_merge.py::test_valid[tests/fixtures/1.1/single-empty-object-compiled.json-schema25]",
"tests/test_merge.py::test_valid[tests/fixtures/1.1/unit.json-schema26]",
"tests/test_merge.py::test_valid[tests/fixtures/1.1/lists.json-schema27]",
"tests/test_merge.py::test_valid[tests/fixtures/1.1/fill-wholelistmerge-array.json-schema28]",
"tests/test_merge.py::test_valid[tests/fixtures/1.1/string-list-compiled.json-schema29]",
"tests/test_merge.py::test_valid[tests/fixtures/1.1/single-empty-identifiermerge-array-compiled.json-schema30]",
"tests/test_merge.py::test_valid[tests/fixtures/1.1/simple.json-schema31]",
"tests/test_merge.py::test_valid[tests/fixtures/1.1/mergeid-compiled.json-schema32]",
"tests/test_merge.py::test_valid[tests/fixtures/1.1/initial-null-compiled.json-schema33]",
"tests/test_merge.py::test_valid[tests/fixtures/1.1/fill-identifiermerge-array-compiled.json-schema35]",
"tests/test_merge.py::test_valid[tests/fixtures/1.1/empty-wholelistmerge-array-compiled.json-schema36]",
"tests/test_merge.py::test_valid[tests/fixtures/1.1/fill-wholelistmerge-array-versioned.json-schema37]",
"tests/test_merge.py::test_valid[tests/fixtures/1.1/single-empty-object-versioned.json-schema38]",
"tests/test_merge.py::test_valid[tests/fixtures/1.1/empty-identifiermerge-array-versioned.json-schema39]",
"tests/test_merge.py::test_valid[tests/fixtures/1.1/fill-object-versioned.json-schema40]",
"tests/test_merge.py::test_valid[tests/fixtures/1.1/single-empty-wholelistmerge-array-versioned.json-schema41]",
"tests/test_merge.py::test_valid[tests/fixtures/1.1/mergeid-versioned.json-schema42]",
"tests/test_merge.py::test_valid[tests/fixtures/1.1/null-versioned.json-schema43]",
"tests/test_merge.py::test_valid[tests/fixtures/1.1/empty-object-versioned.json-schema44]",
"tests/test_merge.py::test_valid[tests/fixtures/1.1/initial-null-versioned.json-schema45]",
"tests/test_merge.py::test_valid[tests/fixtures/1.1/unit-versioned.json-schema46]",
"tests/test_merge.py::test_valid[tests/fixtures/1.1/empty-wholelistmerge-array-versioned.json-schema47]",
"tests/test_merge.py::test_valid[tests/fixtures/1.1/simple-versioned.json-schema48]",
"tests/test_merge.py::test_valid[tests/fixtures/1.1/fill-identifiermerge-array-versioned.json-schema50]",
"tests/test_merge.py::test_valid[tests/fixtures/1.1/lists-versioned.json-schema51]",
"tests/test_merge.py::test_valid[tests/fixtures/1.1/single-empty-identifiermerge-array-versioned.json-schema52]",
"tests/test_merge.py::test_valid[tests/fixtures/1.1/string-list-versioned.json-schema53]"
] | [] | 2019-04-30 15:47:32+00:00 | 4,398 |
|
open-dynaMIX__raiseorlaunch-44 | diff --git a/raiseorlaunch/raiseorlaunch.py b/raiseorlaunch/raiseorlaunch.py
index 9ac4338..e164d5d 100644
--- a/raiseorlaunch/raiseorlaunch.py
+++ b/raiseorlaunch/raiseorlaunch.py
@@ -144,8 +144,17 @@ class Raiseorlaunch(object):
Returns:
str: '<Con: class="{}" instance="{}" title="{}" id={}>'
"""
- return '<Con: class="{}" instance="{}" title="{}" id={}>'.format(
- window.window_class, window.window_instance, window.name, window.id
+
+ def quote(value):
+ if isinstance(value, str):
+ return '"{}"'.format(value)
+ return value
+
+ return "<Con: class={} instance={} title={} id={}>".format(
+ quote(window.window_class),
+ quote(window.window_instance),
+ quote(window.name),
+ window.id,
)
def _match_regex(self, regex, string_to_match):
@@ -177,7 +186,8 @@ class Raiseorlaunch(object):
(self.wm_instance, window.window_instance),
(self.wm_title, window.name),
]:
- if pattern and not self._match_regex(pattern, value):
+
+ if pattern and (not value or not self._match_regex(pattern, value)):
return False
logger.debug("Window match: {}".format(self._log_format_con(window)))
@@ -238,6 +248,14 @@ class Raiseorlaunch(object):
window_list = self._get_window_list()
found = []
for leave in window_list:
+ if (
+ leave.window_class
+ == leave.window_instance
+ == leave.window_title
+ is None
+ ):
+ logger.debug("Window without any properties found.")
+ continue
if self._compare_running(leave):
found.append(leave)
| open-dynaMIX/raiseorlaunch | 6f4364a598e0612ebe8bdb2516aeeb1080a3219b | diff --git a/tests/test_raiseorlaunch.py b/tests/test_raiseorlaunch.py
index a5c6c8e..34a1b36 100644
--- a/tests/test_raiseorlaunch.py
+++ b/tests/test_raiseorlaunch.py
@@ -76,8 +76,8 @@ def test__log_format_con(minimal_args, Con, mocker):
rol = Raiseorlaunch(**minimal_args)
assert (
- rol._log_format_con(Con())
- == '<Con: class="some_class" instance="some_instance" title="some_name" id=some_id>'
+ rol._log_format_con(Con(window_class=None))
+ == '<Con: class=None instance="some_instance" title="some_name" id=some_id>'
)
@@ -107,7 +107,8 @@ def test__match_regex(minimal_args, ignore_case, regex, string, success, mocker)
{"window_class": "Qutebrowser"},
True,
),
- ({"wm_class": "something"}, {"window_class": "Qutebrowser"}, False),
+ ({"wm_class": "foo"}, {"window_class": "Qutebrowser"}, False),
+ ({"wm_class": "foo"}, {"window_class": None}, False),
],
)
def test__compare_running(minimal_args, rol, Con, config, con_values, success):
@@ -125,8 +126,8 @@ def test__compare_running(minimal_args, rol, Con, config, con_values, success):
(
False,
None,
- 4,
- ["Home", "i3 - improved tiling wm - qutebrowser", "notes", "htop"],
+ 5,
+ ["Home", None, "i3 - improved tiling wm - qutebrowser", "notes", "htop"],
),
(True, None, 2, ["notes", "htop"]),
(False, "workspace_1", 2, ["i3 - improved tiling wm - qutebrowser", "htop"]),
@@ -219,7 +220,11 @@ def test_leave_fullscreen_on_workspace(workspace, exceptions, called, rol, mocke
)
def test__choose_if_multiple(target_workspace, multi, rol):
rol.target_workspace = target_workspace
- cons = [c for c in rol._get_window_list() if c.window_instance.startswith("test")]
+ cons = [
+ c
+ for c in rol._get_window_list()
+ if c.window_instance and c.window_instance.startswith("test")
+ ]
if not multi:
cons = [cons[0]]
con = rol._choose_if_multiple(cons)
@@ -242,7 +247,9 @@ def test__handle_running(
rol.cycle = cycle
rol.scratch = scratch
running = [
- c for c in rol._get_window_list() if c.window_instance.startswith("test")
+ c
+ for c in rol._get_window_list()
+ if c.window_instance and c.window_instance.startswith("test")
]
if not multi:
running = [running[0]]
diff --git a/tests/tree.py b/tests/tree.py
index 1d898c7..1682d10 100644
--- a/tests/tree.py
+++ b/tests/tree.py
@@ -325,7 +325,55 @@ tree = {
"sticky": False,
"floating": "auto_off",
"swallows": [],
- }
+ },
+ {
+ "id": 94083980242960,
+ "type": "con",
+ "orientation": "none",
+ "scratchpad_state": "none",
+ "percent": 0.5,
+ "urgent": False,
+ "focused": False,
+ "output": "eDP1",
+ "layout": "splith",
+ "workspace_layout": "default",
+ "last_split_layout": "splith",
+ "border": "normal",
+ "current_border_width": -1,
+ "rect": {
+ "x": 0,
+ "y": 50,
+ "width": 960,
+ "height": 1030,
+ },
+ "deco_rect": {
+ "x": 0,
+ "y": 0,
+ "width": 960,
+ "height": 24,
+ },
+ "window_rect": {
+ "x": 0,
+ "y": 0,
+ "width": 0,
+ "height": 0,
+ },
+ "geometry": {
+ "x": 0,
+ "y": 0,
+ "width": 0,
+ "height": 0,
+ },
+ "name": None,
+ "window": None,
+ "nodes": [],
+ "floating_nodes": [],
+ "focus": [],
+ "fullscreen_mode": 0,
+ "sticky": False,
+ "floating": "auto_off",
+ "swallows": [],
+ },
],
"floating_nodes": [],
"focus": [94271844826512, 94271844692688],
| crashes when Spotify is closed but not when Spotify is open
This syntax worked to raise Spotify if it was already running, but crashed instead of launching Spotify when it was not running. If I'm doing something invalid, it would be nice if it failed with a more helpful diagnostic message explaining what was invalid.
Thanks.
```
h> raiseorlaunch -r -c Spotify
expected string or bytes-like object
Traceback (most recent call last):
File "/usr/bin/raiseorlaunch", line 8, in <module>
sys.exit(main())
File "/usr/lib/python3.8/site-packages/raiseorlaunch/__main__.py", line 222, in main
rol.run()
File "/usr/lib/python3.8/site-packages/raiseorlaunch/raiseorlaunch.py", line 551, in run
self._handle_not_running()
File "/usr/lib/python3.8/site-packages/raiseorlaunch/raiseorlaunch.py", line 515, in _handle_not_running
self.i3.main(timeout=self.event_time_limit)
File "/usr/lib/python3.8/site-packages/i3ipc/connection.py", line 518, in main
raise loop_exception
File "/usr/lib/python3.8/site-packages/i3ipc/connection.py", line 497, in main
while not self._event_socket_poll():
File "/usr/lib/python3.8/site-packages/i3ipc/connection.py", line 477, in _event_socket_poll
raise e
File "/usr/lib/python3.8/site-packages/i3ipc/connection.py", line 474, in _event_socket_poll
self._pubsub.emit(event_name, event)
File "/usr/lib/python3.8/site-packages/i3ipc/_private/pubsub.py", line 28, in emit
s['handler'](self.conn, data)
File "/usr/lib/python3.8/site-packages/raiseorlaunch/raiseorlaunch.py", line 527, in _callback_new_window
if self._compare_running(window):
File "/usr/lib/python3.8/site-packages/raiseorlaunch/raiseorlaunch.py", line 180, in _compare_running
if pattern and not self._match_regex(pattern, value):
File "/usr/lib/python3.8/site-packages/raiseorlaunch/raiseorlaunch.py", line 163, in _match_regex
return True if re.match(*matchlist) else False
File "/usr/lib/python3.8/re.py", line 189, in match
return _compile(pattern, flags).match(string)
TypeError: expected string or bytes-like object
``` | 0.0 | [
"tests/test_raiseorlaunch.py::test__log_format_con",
"tests/test_raiseorlaunch.py::test__compare_running[config3-con_values3-False]",
"tests/test_raiseorlaunch.py::test__is_running[None-None-qutebrowser-None-None-True]",
"tests/test_raiseorlaunch.py::test__is_running[None-None-None-test-qutebrowser-None-True]",
"tests/test_raiseorlaunch.py::test__is_running[None-None-None-None-i3",
"tests/test_raiseorlaunch.py::test__is_running[None-None-non_existing_class-None-None-False]"
] | [
"tests/test_raiseorlaunch.py::test_init_success",
"tests/test_raiseorlaunch.py::test__check_args[args0-You",
"tests/test_raiseorlaunch.py::test__check_args[args1-You",
"tests/test_raiseorlaunch.py::test__check_args[args2-The",
"tests/test_raiseorlaunch.py::test__check_args[args3-Setting",
"tests/test_raiseorlaunch.py::test__check_args[args4-None]",
"tests/test_raiseorlaunch.py::test_check_positive[1-1.0_0]",
"tests/test_raiseorlaunch.py::test_check_positive[1.0-1.0_0]",
"tests/test_raiseorlaunch.py::test_check_positive[1-1.0_1]",
"tests/test_raiseorlaunch.py::test_check_positive[1.0-1.0_1]",
"tests/test_raiseorlaunch.py::test_check_positive[0-False0]",
"tests/test_raiseorlaunch.py::test_check_positive[-1-False0]",
"tests/test_raiseorlaunch.py::test_check_positive[0-False1]",
"tests/test_raiseorlaunch.py::test_check_positive[-1-False1]",
"tests/test_raiseorlaunch.py::test_check_positive[not",
"tests/test_raiseorlaunch.py::test__match_regex[qutebrowser-Qutebrowser-True-True]",
"tests/test_raiseorlaunch.py::test__match_regex[qutebrowser-qutebrowser-True-False]",
"tests/test_raiseorlaunch.py::test__match_regex[qutebrowser-Qutebrowser-False-False]",
"tests/test_raiseorlaunch.py::test__match_regex[^qutebrowser-something_qutebrowser-False-True]",
"tests/test_raiseorlaunch.py::test__match_regex[^qutebrowser$-qutebrowser_something-False-False]",
"tests/test_raiseorlaunch.py::test__compare_running[config0-con_values0-True]",
"tests/test_raiseorlaunch.py::test__compare_running[config1-con_values1-True]",
"tests/test_raiseorlaunch.py::test__compare_running[config2-con_values2-False]",
"tests/test_raiseorlaunch.py::test__get_window_list[False-None-5-names0]",
"tests/test_raiseorlaunch.py::test__get_window_list[True-None-2-names1]",
"tests/test_raiseorlaunch.py::test__get_window_list[False-workspace_1-2-names2]",
"tests/test_raiseorlaunch.py::test__get_window_list[False-not",
"tests/test_raiseorlaunch.py::test__find_marked_window[my_mark-None-True]",
"tests/test_raiseorlaunch.py::test__find_marked_window[my_mark-workspace_1-False]",
"tests/test_raiseorlaunch.py::test__find_marked_window[my_qb_mark-workspace_1-True]",
"tests/test_raiseorlaunch.py::test__find_marked_window[my_mark-not",
"tests/test_raiseorlaunch.py::test__find_marked_window[not",
"tests/test_raiseorlaunch.py::test__is_running[my_mark-None-None-None-None-True]",
"tests/test_raiseorlaunch.py::test__is_running[not",
"tests/test_raiseorlaunch.py::test_run_command",
"tests/test_raiseorlaunch.py::test_leave_fullscreen_on_workspace[workspace_1-None-True]",
"tests/test_raiseorlaunch.py::test_leave_fullscreen_on_workspace[workspace_1-exceptions1-False]",
"tests/test_raiseorlaunch.py::test_leave_fullscreen_on_workspace[not_a_workspace-None-False]",
"tests/test_raiseorlaunch.py::test__choose_if_multiple[workspace_1-True]",
"tests/test_raiseorlaunch.py::test__choose_if_multiple[workspace_1-False]",
"tests/test_raiseorlaunch.py::test__choose_if_multiple[not",
"tests/test_raiseorlaunch.py::test__choose_if_multiple[None-True]",
"tests/test_raiseorlaunch.py::test__choose_if_multiple[None-False]",
"tests/test_raiseorlaunch.py::test__handle_running[True-True-False-False-_handle_running_cycle]",
"tests/test_raiseorlaunch.py::test__handle_running[True-True-False-True-_handle_running_no_scratch]",
"tests/test_raiseorlaunch.py::test__handle_running[True-False-True-False-_handle_running_scratch]",
"tests/test_raiseorlaunch.py::test__handle_running[True-False-False-False-_handle_running_no_scratch]",
"tests/test_raiseorlaunch.py::test__handle_running_no_scratch[True-workspace_1-True-workspace",
"tests/test_raiseorlaunch.py::test__handle_running_no_scratch[True-workspace_2-False-None-False]",
"tests/test_raiseorlaunch.py::test__handle_running_no_scratch[False-workspace_2-True-focus-True]",
"tests/test_raiseorlaunch.py::test__handle_running_no_scratch[False-workspace_1-True-focus-True]",
"tests/test_raiseorlaunch.py::test__handle_running_scratch[True-notes-notes-scratchpad",
"tests/test_raiseorlaunch.py::test__handle_running_scratch[False-notes-notes-focus]",
"tests/test_raiseorlaunch.py::test__handle_running_scratch[False-notes-not_notes-scratchpad",
"tests/test_raiseorlaunch.py::test__handle_running_cycle[focused0-1]",
"tests/test_raiseorlaunch.py::test__handle_running_cycle[focused1-2]",
"tests/test_raiseorlaunch.py::test__handle_running_cycle[focused2-0]",
"tests/test_raiseorlaunch.py::test__handle_not_running[True-ws1-ws1-False-True]",
"tests/test_raiseorlaunch.py::test__handle_not_running[True-ws1-None-False-False]",
"tests/test_raiseorlaunch.py::test__handle_not_running[True-ws1-ws2-True-True]",
"tests/test_raiseorlaunch.py::test__handle_not_running[False-ws1-ws1-False-True]",
"tests/test_raiseorlaunch.py::test__handle_not_running[False-ws1-None-False-False]",
"tests/test_raiseorlaunch.py::test__handle_not_running[False-ws1-ws2-True-True]",
"tests/test_raiseorlaunch.py::test__callback_new_window[None-True-True-ws1-ws1-False-class1-class2]",
"tests/test_raiseorlaunch.py::test__callback_new_window[None-True-True-ws1-None-False-class1-class2]",
"tests/test_raiseorlaunch.py::test__callback_new_window[None-True-True-ws1-ws2-True-class1-class2]",
"tests/test_raiseorlaunch.py::test__callback_new_window[None-True-False-ws1-ws1-False-class1-class2]",
"tests/test_raiseorlaunch.py::test__callback_new_window[None-True-False-ws1-None-False-class1-class2]",
"tests/test_raiseorlaunch.py::test__callback_new_window[None-True-False-ws1-ws2-True-class1-class2]",
"tests/test_raiseorlaunch.py::test__callback_new_window[None-False-True-ws1-ws1-False-class1-class2]",
"tests/test_raiseorlaunch.py::test__callback_new_window[None-False-True-ws1-None-False-class1-class2]",
"tests/test_raiseorlaunch.py::test__callback_new_window[None-False-True-ws1-ws2-True-class1-class2]",
"tests/test_raiseorlaunch.py::test__callback_new_window[None-False-False-ws1-ws1-False-class1-class2]",
"tests/test_raiseorlaunch.py::test__callback_new_window[None-False-False-ws1-None-False-class1-class2]",
"tests/test_raiseorlaunch.py::test__callback_new_window[None-False-False-ws1-ws2-True-class1-class2]",
"tests/test_raiseorlaunch.py::test__callback_new_window[test_con_mark-True-True-ws1-ws1-False-class1-class2]",
"tests/test_raiseorlaunch.py::test__callback_new_window[test_con_mark-True-True-ws1-None-False-class1-class2]",
"tests/test_raiseorlaunch.py::test__callback_new_window[test_con_mark-True-True-ws1-ws2-True-class1-class2]",
"tests/test_raiseorlaunch.py::test__callback_new_window[test_con_mark-True-False-ws1-ws1-False-class1-class2]",
"tests/test_raiseorlaunch.py::test__callback_new_window[test_con_mark-True-False-ws1-None-False-class1-class2]",
"tests/test_raiseorlaunch.py::test__callback_new_window[test_con_mark-True-False-ws1-ws2-True-class1-class2]",
"tests/test_raiseorlaunch.py::test__callback_new_window[test_con_mark-False-True-ws1-ws1-False-class1-class2]",
"tests/test_raiseorlaunch.py::test__callback_new_window[test_con_mark-False-True-ws1-None-False-class1-class2]",
"tests/test_raiseorlaunch.py::test__callback_new_window[test_con_mark-False-True-ws1-ws2-True-class1-class2]",
"tests/test_raiseorlaunch.py::test__callback_new_window[test_con_mark-False-False-ws1-ws1-False-class1-class2]",
"tests/test_raiseorlaunch.py::test__callback_new_window[test_con_mark-False-False-ws1-None-False-class1-class2]",
"tests/test_raiseorlaunch.py::test__callback_new_window[test_con_mark-False-False-ws1-ws2-True-class1-class2]",
"tests/test_raiseorlaunch.py::test_run[True]",
"tests/test_raiseorlaunch.py::test_run[False]"
] | 2020-01-20 20:37:56+00:00 | 4,399 |
|
open-mmlab__mmengine-856 | diff --git a/mmengine/config/config.py b/mmengine/config/config.py
index 6a81797..18560ac 100644
--- a/mmengine/config/config.py
+++ b/mmengine/config/config.py
@@ -550,8 +550,8 @@ class Config:
Returns:
list: A list of base config.
"""
- file_format = filename.partition('.')[-1]
- if file_format == 'py':
+ file_format = osp.splitext(filename)[1]
+ if file_format == '.py':
Config._validate_py_syntax(filename)
with open(filename, encoding='utf-8') as f:
codes = ast.parse(f.read()).body
@@ -568,7 +568,7 @@ class Config:
base_files = eval(compile(base_code, '', mode='eval'))
else:
base_files = []
- elif file_format in ('yml', 'yaml', 'json'):
+ elif file_format in ('.yml', '.yaml', '.json'):
import mmengine
cfg_dict = mmengine.load(filename)
base_files = cfg_dict.get(BASE_KEY, [])
| open-mmlab/mmengine | 6af88783fb0c7556cfcdd09c7ad839f9572c3095 | diff --git a/tests/test_config/test_config.py b/tests/test_config/test_config.py
index 0714734..8420fe7 100644
--- a/tests/test_config/test_config.py
+++ b/tests/test_config/test_config.py
@@ -5,8 +5,10 @@ import os
import os.path as osp
import platform
import sys
+import tempfile
from importlib import import_module
from pathlib import Path
+from unittest.mock import patch
import pytest
@@ -715,6 +717,21 @@ class TestConfig:
cfg = Config._file2dict(cfg_file)[0]
assert cfg == dict(item1=dict(a=1))
+ # Simulate the case that the temporary directory includes `.`, etc.
+ # /tmp/test.axsgr12/. This patch is to check the issue
+ # https://github.com/open-mmlab/mmengine/issues/788 has been solved.
+ class PatchedTempDirectory(tempfile.TemporaryDirectory):
+
+ def __init__(self, *args, prefix='test.', **kwargs):
+ super().__init__(*args, prefix=prefix, **kwargs)
+
+ with patch('mmengine.config.config.tempfile.TemporaryDirectory',
+ PatchedTempDirectory):
+ cfg_file = osp.join(self.data_path,
+ 'config/py_config/test_py_modify_key.py')
+ cfg = Config._file2dict(cfg_file)[0]
+ assert cfg == dict(item1=dict(a=1))
+
def _merge_recursive_bases(self):
cfg_file = osp.join(self.data_path,
'config/py_config/test_merge_recursive_bases.py')
| [Bug] File format checking when more than one dot in the path
### Prerequisite
- [X] I have searched [Issues](https://github.com/open-mmlab/mmengine/issues) and [Discussions](https://github.com/open-mmlab/mmengine/discussions) but cannot get the expected help.
- [X] The bug has not been fixed in the latest version(https://github.com/open-mmlab/mmengine).
### Environment
OrderedDict([('sys.platform', 'linux'), ('Python', '3.8.15 (default, Nov 24 2022, 15:19:38) [GCC 11.2.0]'), ('CUDA available', True), ('numpy_random_seed', 2147483648), ('GPU 0,1,2,3', 'Tesla P100-SXM2-16GB'), ('CUDA_HOME', '/apps/cuda/11.6.2'), ('NVCC', 'Cuda compilation tools, release 11.6, V11.6.124'), ('GCC', 'gcc (SUSE Linux) 7.5.0'), ('PyTorch', '1.13.0'), ('PyTorch compiling details', 'PyTorch built with:\n - GCC 9.3\n - C++ Version: 201402\n - Intel(R) oneAPI Math Kernel Library Version 2021.4-Product Build 20210904 for Intel(R) 64 architecture applications\n - Intel(R) MKL-DNN v2.6.0 (Git Hash 52b5f107dd9cf10910aaa19cb47f3abf9b349815)\n - OpenMP 201511 (a.k.a. OpenMP 4.5)\n - LAPACK is enabled (usually provided by MKL)\n - NNPACK is enabled\n - CPU capability usage: AVX2\n - CUDA Runtime 11.6\n - NVCC architecture flags: -gencode;arch=compute_37,code=sm_37;-gencode;arch=compute_50,code=sm_50;-gencode;arch=compute_60,code=sm_60;-gencode;arch=compute_61,code=sm_61;-gencode;arch=compute_70,code=sm_70;-gencode;arch=compute_75,code=sm_75;-gencode;arch=compute_80,code=sm_80;-gencode;arch=compute_86,code=sm_86;-gencode;arch=compute_37,code=compute_37\n - CuDNN 8.3.2 (built against CUDA 11.5)\n - Magma 2.6.1\n - Build settings: BLAS_INFO=mkl, BUILD_TYPE=Release, CUDA_VERSION=11.6, CUDNN_VERSION=8.3.2, CXX_COMPILER=/opt/rh/devtoolset-9/root/usr/bin/c++, CXX_FLAGS= -fabi-version=11 -Wno-deprecated -fvisibility-inlines-hidden -DUSE_PTHREADPOOL -fopenmp -DNDEBUG -DUSE_KINETO -DUSE_FBGEMM -DUSE_QNNPACK -DUSE_PYTORCH_QNNPACK -DUSE_XNNPACK -DSYMBOLICATE_MOBILE_DEBUG_HANDLE -DEDGE_PROFILER_USE_KINETO -O2 -fPIC -Wno-narrowing -Wall -Wextra -Werror=return-type -Werror=non-virtual-dtor -Wno-missing-field-initializers -Wno-type-limits -Wno-array-bounds -Wno-unknown-pragmas -Wunused-local-typedefs -Wno-unused-parameter -Wno-unused-function -Wno-unused-result -Wno-strict-overflow -Wno-strict-aliasing -Wno-error=deprecated-declarations -Wno-stringop-overflow -Wno-psabi -Wno-error=pedantic -Wno-error=redundant-decls -Wno-error=old-style-cast -fdiagnostics-color=always -faligned-new -Wno-unused-but-set-variable -Wno-maybe-uninitialized -fno-math-errno -fno-trapping-math -Werror=format -Werror=cast-function-type -Wno-stringop-overflow, LAPACK_INFO=mkl, PERF_WITH_AVX=1, PERF_WITH_AVX2=1, PERF_WITH_AVX512=1, TORCH_VERSION=1.13.0, USE_CUDA=ON, USE_CUDNN=ON, USE_EXCEPTION_PTR=1, USE_GFLAGS=OFF, USE_GLOG=OFF, USE_MKL=ON, USE_MKLDNN=ON, USE_MPI=OFF, USE_NCCL=ON, USE_NNPACK=ON, USE_OPENMP=ON, USE_ROCM=OFF, \n'), ('TorchVision', '0.14.0'), ('OpenCV', '4.6.0'), ('MMEngine', '0.3.2')])
### Reproduces the problem - code sample
`python demo/image_demo.py demo/demo.jpg configs/yolo/yolov3_mobilenetv2_8xb24-320-300e_coco.py yolov3_mobilenetv2_320_300e_coco_20210719_215349-d18dff72.pth --device cpu --out-file result.jpg
`
### Reproduces the problem - command or script
`python demo/image_demo.py demo/demo.jpg configs/yolo/yolov3_mobilenetv2_8xb24-320-300e_coco.py yolov3_mobilenetv2_320_300e_coco_20210719_215349-d18dff72.pth --device cpu --out-file result.jpg`
### Reproduces the problem - error message
Traceback (most recent call last):
File "demo/image_demo.py", line 98, in <module>
main(args)
File "demo/image_demo.py", line 42, in main
model = init_detector(
File "/datasets/work/d61-visage-data/work/experiments/Yang/code/mmdetection/mmdet/apis/inference.py", line 47, in init_detector
config = Config.fromfile(config)
File "/scratch1/li309/miniconda3/envs/mmdet/lib/python3.8/site-packages/mmengine/config/config.py", line 172, in fromfile
cfg_dict, cfg_text = Config._file2dict(filename,
File "/scratch1/li309/miniconda3/envs/mmdet/lib/python3.8/site-packages/mmengine/config/config.py", line 401, in _file2dict
for base_cfg_path in Config._get_base_files(temp_config_file.name):
File "/scratch1/li309/miniconda3/envs/mmdet/lib/python3.8/site-packages/mmengine/config/config.py", line 576, in _get_base_files
raise TypeError('The config type should be py, json, yaml or '
TypeError: The config type should be py, json, yaml or yml, but got 43629/tmpm37bjlje/tmpl5h1hmu0.py
Exception ignored in: <function _TemporaryFileCloser.__del__ at 0x15553a649940>
Traceback (most recent call last):
File "/scratch1/li309/miniconda3/envs/mmdet/lib/python3.8/tempfile.py", line 440, in __del__
self.close()
File "/scratch1/li309/miniconda3/envs/mmdet/lib/python3.8/tempfile.py", line 436, in close
unlink(self.name)
FileNotFoundError: [Errno 2] No such file or directory: '/tmp/li309.43629/tmpm37bjlje/tmpl5h1hmu0.py'
### Additional information
Hi there,
I was running the demo script to test out mmdet framework on HPC. However, I got the issue above. When I tracked back the cause of the issue. I found out that the temp file written by mmengine cannot be detected when the temp file path has more than one dot. For example, on my HPC, my tmp file path is `/tmp/li309.43629/tmpm37bjlje/tmpl5h1hmu0.py`, the extracted file format becomes "43629/tmpm37bjlje/tmpl5h1hmu0.py" because the line 553 of the file mmengine/config/config.py uses partition() function, which only finds the first occurred dot. I fixed it by replacing it with split() function, so all "." are found and separated.
Please check if this is a bug that deserves to be fixed :) | 0.0 | [
"tests/test_config/test_config.py::TestConfig::test_file2dict"
] | [
"tests/test_config/test_config.py::TestConfig::test_init[py]",
"tests/test_config/test_config.py::TestConfig::test_init[json]",
"tests/test_config/test_config.py::TestConfig::test_init[yaml]",
"tests/test_config/test_config.py::TestConfig::test_fromfile",
"tests/test_config/test_config.py::TestConfig::test_fromstring[py]",
"tests/test_config/test_config.py::TestConfig::test_fromstring[json]",
"tests/test_config/test_config.py::TestConfig::test_fromstring[yaml]",
"tests/test_config/test_config.py::TestConfig::test_magic_methods",
"tests/test_config/test_config.py::TestConfig::test_merge_from_dict",
"tests/test_config/test_config.py::TestConfig::test_auto_argparser",
"tests/test_config/test_config.py::TestConfig::test_dict_to_config_dict",
"tests/test_config/test_config.py::TestConfig::test_repr",
"tests/test_config/test_config.py::TestConfig::test_dict_action",
"tests/test_config/test_config.py::TestConfig::test_validate_py_syntax",
"tests/test_config/test_config.py::TestConfig::test_substitute_predefined_vars",
"tests/test_config/test_config.py::TestConfig::test_pre_substitute_base_vars",
"tests/test_config/test_config.py::TestConfig::test_substitute_base_vars",
"tests/test_config/test_config.py::TestConfig::test_get_cfg_path_local",
"tests/test_config/test_config.py::TestConfig::test_deepcopy",
"tests/test_config/test_config.py::TestConfig::test_copy"
] | 2022-12-30 04:34:07+00:00 | 4,400 |
|
open-things__loggingex-14 | diff --git a/src/loggingex/context/__init__.py b/src/loggingex/context/__init__.py
index f722f47..23f0337 100644
--- a/src/loggingex/context/__init__.py
+++ b/src/loggingex/context/__init__.py
@@ -128,6 +128,21 @@ class ContextChange:
self.context_restore_token = context_restore_token
+ def __str__(self) -> str:
+ parts = [
+ "!" if self.context_restore_token else None,
+ "-*" if self.context_fresh else None,
+ ]
+ parts.extend("-%s" % n for n in sorted(self.context_remove))
+ upd = self.context_update
+ val = self.context_update.__getitem__
+ parts.extend("+%s=%r" % (n, val(n)) for n in sorted(upd.keys()))
+
+ return " ".join(x for x in parts if x)
+
+ def __repr__(self):
+ return "<ContextChange: %s>" % str(self)
+
@classmethod
def validate_context_variable_name(
cls, name: ContextVariableUnvalidatedName
| open-things/loggingex | 2c84f8745601d62666024edca3e74ebdcfbe685b | diff --git a/tests/loggingex/context/test_context_change.py b/tests/loggingex/context/test_context_change.py
index 98ab363..91bf5e4 100644
--- a/tests/loggingex/context/test_context_change.py
+++ b/tests/loggingex/context/test_context_change.py
@@ -1,4 +1,6 @@
-from pytest import mark, raises
+from itertools import product, starmap
+
+from pytest import fixture, mark, raises
from loggingex.context import (
ContextChange,
@@ -249,3 +251,55 @@ class ContextChangeAsDecoratorTests(InitializedContextBase):
return fib(n - 2) + fib(n - 1)
assert fib(3) == 3
+
+
+class SerializationTests:
+ VALUE_MAP = {
+ "locked": {False: None, True: "not a None"},
+ "fresh": {False: False, True: True},
+ "remove": {False: set(), True: ("b", "a")},
+ "update": {False: {}, True: {"y": 2.3, "x": 1, "z": "dummy"}},
+ }
+ STR_MAP = {
+ "locked": {False: None, True: "!"},
+ "fresh": {False: None, True: "-*"},
+ "remove": {False: None, True: "-a -b"},
+ "update": {False: None, True: "+x=1 +y=2.3 +z='dummy'"},
+ }
+
+ FIXTURES = product([False, True], repeat=4)
+ FIXTURE_IDS = starmap(
+ "{}__{}__{}__{}".format,
+ product(
+ ("unlocked", "locked"),
+ ("unfresh", "fresh"),
+ ("no_remove", "with_remove"),
+ ("no_update", "with_update"),
+ ),
+ )
+
+ @fixture(params=FIXTURES, ids=FIXTURE_IDS)
+ def context_change_and_expected_str(self, request):
+ locked, fresh, remove, update = request.param
+ change = ContextChange(
+ context_fresh=self.VALUE_MAP["fresh"][fresh],
+ context_remove=self.VALUE_MAP["remove"][remove],
+ context_update=self.VALUE_MAP["update"][update],
+ context_restore_token=self.VALUE_MAP["locked"][locked],
+ )
+ parts = [
+ self.STR_MAP["locked"][locked],
+ self.STR_MAP["fresh"][fresh],
+ self.STR_MAP["remove"][remove],
+ self.STR_MAP["update"][update],
+ ]
+ expected_str = " ".join(x for x in parts if x)
+ return change, expected_str
+
+ def test_str_context_change_test(self, context_change_and_expected_str):
+ change, expected = context_change_and_expected_str
+ assert str(change) == expected
+
+ def test_repr_context_change_test(self, context_change_and_expected_str):
+ change, expected = context_change_and_expected_str
+ assert repr(change) == "<ContextChange: %s>" % expected
| Implement __str__ and __repr__ for ContextChange
Currently `ContextChange` looks ugly in the debugger or when printed.
Implement `__str__` and `__repr__` methods to make it pretty and, most importantly, useful. | 0.0 | [
"tests/loggingex/context/test_context_change.py::SerializationTests::test_str_context_change_test[unlocked__unfresh__no_remove__no_update]",
"tests/loggingex/context/test_context_change.py::SerializationTests::test_str_context_change_test[unlocked__unfresh__no_remove__with_update]",
"tests/loggingex/context/test_context_change.py::SerializationTests::test_str_context_change_test[unlocked__unfresh__with_remove__no_update]",
"tests/loggingex/context/test_context_change.py::SerializationTests::test_str_context_change_test[unlocked__unfresh__with_remove__with_update]",
"tests/loggingex/context/test_context_change.py::SerializationTests::test_str_context_change_test[unlocked__fresh__no_remove__no_update]",
"tests/loggingex/context/test_context_change.py::SerializationTests::test_str_context_change_test[unlocked__fresh__no_remove__with_update]",
"tests/loggingex/context/test_context_change.py::SerializationTests::test_str_context_change_test[unlocked__fresh__with_remove__no_update]",
"tests/loggingex/context/test_context_change.py::SerializationTests::test_str_context_change_test[unlocked__fresh__with_remove__with_update]",
"tests/loggingex/context/test_context_change.py::SerializationTests::test_str_context_change_test[locked__unfresh__no_remove__no_update]",
"tests/loggingex/context/test_context_change.py::SerializationTests::test_str_context_change_test[locked__unfresh__no_remove__with_update]",
"tests/loggingex/context/test_context_change.py::SerializationTests::test_str_context_change_test[locked__unfresh__with_remove__no_update]",
"tests/loggingex/context/test_context_change.py::SerializationTests::test_str_context_change_test[locked__unfresh__with_remove__with_update]",
"tests/loggingex/context/test_context_change.py::SerializationTests::test_str_context_change_test[locked__fresh__no_remove__no_update]",
"tests/loggingex/context/test_context_change.py::SerializationTests::test_str_context_change_test[locked__fresh__no_remove__with_update]",
"tests/loggingex/context/test_context_change.py::SerializationTests::test_str_context_change_test[locked__fresh__with_remove__no_update]",
"tests/loggingex/context/test_context_change.py::SerializationTests::test_str_context_change_test[locked__fresh__with_remove__with_update]",
"tests/loggingex/context/test_context_change.py::SerializationTests::test_repr_context_change_test[unlocked__unfresh__no_remove__no_update]",
"tests/loggingex/context/test_context_change.py::SerializationTests::test_repr_context_change_test[unlocked__unfresh__no_remove__with_update]",
"tests/loggingex/context/test_context_change.py::SerializationTests::test_repr_context_change_test[unlocked__unfresh__with_remove__no_update]",
"tests/loggingex/context/test_context_change.py::SerializationTests::test_repr_context_change_test[unlocked__unfresh__with_remove__with_update]",
"tests/loggingex/context/test_context_change.py::SerializationTests::test_repr_context_change_test[unlocked__fresh__no_remove__no_update]",
"tests/loggingex/context/test_context_change.py::SerializationTests::test_repr_context_change_test[unlocked__fresh__no_remove__with_update]",
"tests/loggingex/context/test_context_change.py::SerializationTests::test_repr_context_change_test[unlocked__fresh__with_remove__no_update]",
"tests/loggingex/context/test_context_change.py::SerializationTests::test_repr_context_change_test[unlocked__fresh__with_remove__with_update]",
"tests/loggingex/context/test_context_change.py::SerializationTests::test_repr_context_change_test[locked__unfresh__no_remove__no_update]",
"tests/loggingex/context/test_context_change.py::SerializationTests::test_repr_context_change_test[locked__unfresh__no_remove__with_update]",
"tests/loggingex/context/test_context_change.py::SerializationTests::test_repr_context_change_test[locked__unfresh__with_remove__no_update]",
"tests/loggingex/context/test_context_change.py::SerializationTests::test_repr_context_change_test[locked__unfresh__with_remove__with_update]",
"tests/loggingex/context/test_context_change.py::SerializationTests::test_repr_context_change_test[locked__fresh__no_remove__no_update]",
"tests/loggingex/context/test_context_change.py::SerializationTests::test_repr_context_change_test[locked__fresh__no_remove__with_update]",
"tests/loggingex/context/test_context_change.py::SerializationTests::test_repr_context_change_test[locked__fresh__with_remove__no_update]",
"tests/loggingex/context/test_context_change.py::SerializationTests::test_repr_context_change_test[locked__fresh__with_remove__with_update]"
] | [
"tests/loggingex/context/test_context_change.py::test_default_constructor_initializes_context_changes",
"tests/loggingex/context/test_context_change.py::test_validate_context_variable_name_raises_when_not_a_string[None]",
"tests/loggingex/context/test_context_change.py::test_validate_context_variable_name_raises_when_not_a_string[1337]",
"tests/loggingex/context/test_context_change.py::test_validate_context_variable_name_raises_when_not_a_string[13.37]",
"tests/loggingex/context/test_context_change.py::test_validate_context_variable_name_raises_when_not_a_string[bytes]",
"tests/loggingex/context/test_context_change.py::test_validate_context_variable_name_raises_when_not_a_string[value4]",
"tests/loggingex/context/test_context_change.py::test_validate_context_variable_name_raises_when_not_a_string[value5]",
"tests/loggingex/context/test_context_change.py::test_validate_context_variable_name_raises_when_not_a_string[value6]",
"tests/loggingex/context/test_context_change.py::test_validate_context_variable_name_raises_when_not_a_string[value7]",
"tests/loggingex/context/test_context_change.py::test_validate_context_variable_name_raises_when_not_identifier[?]",
"tests/loggingex/context/test_context_change.py::test_validate_context_variable_name_raises_when_not_identifier[!]",
"tests/loggingex/context/test_context_change.py::test_validate_context_variable_name_raises_when_not_identifier[foo.bar]",
"tests/loggingex/context/test_context_change.py::test_validate_context_variable_name_raises_when_not_identifier[foo",
"tests/loggingex/context/test_context_change.py::test_validate_context_variable_name_raises_when_not_identifier[foo-bar]",
"tests/loggingex/context/test_context_change.py::test_validate_context_variable_name_passes_when_name_is_valid[foo]",
"tests/loggingex/context/test_context_change.py::test_validate_context_variable_name_passes_when_name_is_valid[foo_bar]",
"tests/loggingex/context/test_context_change.py::test_validate_context_variable_name_passes_when_name_is_valid[fooBar]",
"tests/loggingex/context/test_context_change.py::test_validate_context_variable_name_passes_when_name_is_valid[_foo]",
"tests/loggingex/context/test_context_change.py::test_validate_context_variable_name_passes_when_name_is_valid[bar_]",
"tests/loggingex/context/test_context_change.py::test_started_returns_false_when_token_is_not_assigned",
"tests/loggingex/context/test_context_change.py::test_started_returns_true_when_token_is_assigned",
"tests/loggingex/context/test_context_change.py::test_can_change_returns_true_when_token_is_not_assigned",
"tests/loggingex/context/test_context_change.py::test_can_change_returns_true_when_token_is_not_assigned_with_raise",
"tests/loggingex/context/test_context_change.py::test_can_change_raises_when_token_is_assigned_with_raise",
"tests/loggingex/context/test_context_change.py::test_fresh_changes_context_fresh[True]",
"tests/loggingex/context/test_context_change.py::test_fresh_changes_context_fresh[False]",
"tests/loggingex/context/test_context_change.py::test_fresh_raises_when_token_is_assigned",
"tests/loggingex/context/test_context_change.py::test_remove_updates_context_remove_set[None-update0-result0]",
"tests/loggingex/context/test_context_change.py::test_remove_updates_context_remove_set[init1-update1-result1]",
"tests/loggingex/context/test_context_change.py::test_remove_updates_context_remove_set[init2-update2-result2]",
"tests/loggingex/context/test_context_change.py::test_remove_raises_when_token_is_assigned",
"tests/loggingex/context/test_context_change.py::test_remove_raises_when_name_is_not_valid[None]",
"tests/loggingex/context/test_context_change.py::test_remove_raises_when_name_is_not_valid[1]",
"tests/loggingex/context/test_context_change.py::test_remove_raises_when_name_is_not_valid[foo-bar]",
"tests/loggingex/context/test_context_change.py::test_remove_raises_when_name_is_not_valid[with",
"tests/loggingex/context/test_context_change.py::test_update_extends_context_update_dict[None-update0-result0]",
"tests/loggingex/context/test_context_change.py::test_update_extends_context_update_dict[init1-update1-result1]",
"tests/loggingex/context/test_context_change.py::test_update_extends_context_update_dict[init2-update2-result2]",
"tests/loggingex/context/test_context_change.py::test_update_raises_when_token_is_assigned",
"tests/loggingex/context/test_context_change.py::test_update_raises_when_name_is_not_valid[foo-bar]",
"tests/loggingex/context/test_context_change.py::test_update_raises_when_name_is_not_valid[with",
"tests/loggingex/context/test_context_change.py::test_apply_returns_same_dict_when_no_changes",
"tests/loggingex/context/test_context_change.py::test_apply_removes_variables",
"tests/loggingex/context/test_context_change.py::test_apply_replaces_variables",
"tests/loggingex/context/test_context_change.py::test_apply_starts_fresh_when_fresh",
"tests/loggingex/context/test_context_change.py::test_apply_combines_removes_and_updates",
"tests/loggingex/context/test_context_change.py::StartAndStopTests::test_start_applies_context_change_and_saves_token",
"tests/loggingex/context/test_context_change.py::StartAndStopTests::test_start_raises_when_change_already_started",
"tests/loggingex/context/test_context_change.py::StartAndStopTests::test_stop_restores_context_and_clears_token",
"tests/loggingex/context/test_context_change.py::StartAndStopTests::test_stop_raises_when_change_was_not_started",
"tests/loggingex/context/test_context_change.py::ContextChangeAsContextManagerTests::test_can_be_used_as_context_manager",
"tests/loggingex/context/test_context_change.py::ContextChangeAsContextManagerTests::test_context_manager_does_not_swallow_exceptions",
"tests/loggingex/context/test_context_change.py::ContextChangeAsDecoratorTests::test_can_be_used_as_decorator",
"tests/loggingex/context/test_context_change.py::ContextChangeAsDecoratorTests::test_decorator_does_not_swallow_exceptions",
"tests/loggingex/context/test_context_change.py::ContextChangeAsDecoratorTests::test_decorator_works_with_recursive_functions"
] | 2019-04-11 15:30:07+00:00 | 4,401 |
|
opendatakosovo__cyrillic-transliteration-28 | diff --git a/cyrtranslit/__init__.py b/cyrtranslit/__init__.py
index 39eed72..34d47e6 100644
--- a/cyrtranslit/__init__.py
+++ b/cyrtranslit/__init__.py
@@ -99,6 +99,10 @@ def to_cyrillic(string_to_transliterate, lang_code='sr'):
if index != length_of_string_to_transliterate - 1:
c_plus_1 = string_to_transliterate[index + 1]
+ c_plus_2 = u''
+ if index + 2 <= length_of_string_to_transliterate - 1:
+ c_plus_2 = string_to_transliterate[index + 2]
+
if ((c == u'L' or c == u'l') and c_plus_1 == u'j') or \
((c == u'N' or c == u'n') and c_plus_1 == u'j') or \
((c == u'D' or c == u'd') and c_plus_1 == u'ž') or \
@@ -112,14 +116,19 @@ def to_cyrillic(string_to_transliterate, lang_code='sr'):
(c in u'Yy' and c_plus_1 in u'Aa') # Ya, ya
)) or \
(lang_code == 'ru' and (
- (c in u'Cc' and c_plus_1 in u'Hh') or # c, ch
- (c in u'Ee' and c_plus_1 in u'Hh') or # eh
+ (c in u'Cc' and c_plus_1 in u'HhKkZz') or # c, ch, ck, cz
+ (c in u'Tt' and c_plus_1 in u'Hh') or # th
+ (c in u'Ww' and c_plus_1 in u'Hh') or # wh
+ (c in u'Pp' and c_plus_1 in u'Hh') or # ph
+ (c in u'Ee' and c_plus_1 == u'\'') or # e'
+
(c == u'i' and c_plus_1 == u'y' and
string_to_transliterate[index + 2:index + 3] not in u'aou') or # iy[^AaOoUu]
- (c in u'Jj' and c_plus_1 in u'UuAaEe') or # j, ju, ja, je
+ (c in u'Jj' and c_plus_1 in u'UuAaEeIiOo') or # j, ju, ja, je, ji, jo
(c in u'Ss' and c_plus_1 in u'HhZz') or # s, sh, sz
- (c in u'Yy' and c_plus_1 in u'AaOoUu') or # y, ya, yo, yu
- (c in u'Zz' and c_plus_1 in u'Hh') # z, zh
+ (c in u'Yy' and c_plus_1 in u'AaOoUuEeIi\'') or # y, ya, yo, yu, ye, yi, y'
+ (c in u'Zz' and c_plus_1 in u'Hh') or # z, zh
+ (c == u'\'' and c_plus_1 == u'\'') # ''
)) or \
(lang_code == 'ua' and (
(c in u'Jj' and c_plus_1 in u'eau') or #je, ja, ju
@@ -134,7 +143,10 @@ def to_cyrillic(string_to_transliterate, lang_code='sr'):
if (lang_code == 'bg' and (c == 'sh' or c == 'Sh' or c == 'SH') and string_to_transliterate[index + 1] in u'Tt'):
index += 1
c += string_to_transliterate[index]
-
+ # Similarly in Russian, the letter "щ" шы represented by "shh".
+ if lang_code == 'ru' and index + 2 <= length_of_string_to_transliterate - 1 and (c == u'sh' or c == 'Sh' or c == 'SH') and string_to_transliterate[index + 1] in u'Hh': # shh
+ index += 1
+ c += string_to_transliterate[index]
# If character is in dictionary, it means it's a cyrillic so let's transliterate that character.
if c in transliteration_dict:
diff --git a/cyrtranslit/mapping.py b/cyrtranslit/mapping.py
index c77cfa8..c181fa0 100644
--- a/cyrtranslit/mapping.py
+++ b/cyrtranslit/mapping.py
@@ -84,7 +84,7 @@ MK_CYR_TO_LAT_DICT[u'ќ'] = u'ḱ'
# This dictionary is to transliterate from Macedonian latin to cyrillic.
MK_LAT_TO_CYR_DICT = {y: x for x, y in iter(MK_CYR_TO_LAT_DICT.items())}
-# This dictionary is to transliterate from Russian cyrillic to latin.
+# This dictionary is to transliterate from Russian cyrillic to latin (GOST_7.79-2000 System B).
RU_CYR_TO_LAT_DICT = {
u"А": u"A", u"а": u"a",
u"Б": u"B", u"б": u"b",
@@ -108,30 +108,43 @@ RU_CYR_TO_LAT_DICT = {
u"Т": u"T", u"т": u"t",
u"У": u"U", u"у": u"u",
u"Ф": u"F", u"ф": u"f",
- u"Х": u"H", u"х": u"h",
- u"Ц": u"C", u"ц": u"c",
+ u"Х": u"X", u"х": u"x",
+ u"Ц": u"CZ", u"ц": u"cz",
u"Ч": u"CH", u"ч": u"ch",
u"Ш": u"SH", u"ш": u"sh",
- u"Щ": u"SZ", u"щ": u"sz",
- u"Ъ": u"#", u"ъ": u"#",
- u"Ы": u"Y", u"ы": u"y",
+ u"Щ": u"SHH", u"щ": u"shh",
+ u"Ъ": u"''", u"ъ": u"''",
+ u"Ы": u"Y'", u"ы": u"y'",
u"Ь": u"'", u"ь": u"'",
- u"Э": u"EH", u"э": u"eh",
- u"Ю": u"JU", u"ю": u"ju",
- u"Я": u"JA", u"я": u"ja",
+ u"Э": u"E'", u"э": u"e'",
+ u"Ю": u"YU", u"ю": u"yu",
+ u"Я": u"YA", u"я": u"ya",
}
# This dictionary is to transliterate from Russian latin to cyrillic.
RU_LAT_TO_CYR_DICT = {y: x for x, y in RU_CYR_TO_LAT_DICT.items()}
RU_LAT_TO_CYR_DICT.update({
- u"X": u"Х", u"x": u"х",
- u"W": u"Щ", u"w": u"щ",
+ u"''": u"ъ",
u"'": u"ь",
- u"#": u"ъ",
+ u"C": u"К", u"c": u"к",
+ u"CK": u"К", u"Ck": u"К", u"ck": u"к",
+ u"JA": u"ЖА", u"Ja": u"Жа", u"ja": u"жа",
u"JE": u"ЖЕ", u"Je": u"Же", u"je": u"же",
- u"YU": u"Ю", u"Yu": u"Ю", u"yu": u"ю",
- u"YA": u"Я", u"Ya": u"Я", u"ya": u"я",
- u"iy": u"ый", # dobriy => добрый
+ u"JI": u"ЖИ", u"Ji": u"Жи", u"ji": u"жи",
+ u"JO": u"ЖО", u"Jo": u"Жо", u"jo": u"жо",
+ u"JU": u"ЖУ", u"Ju": u"Жу", u"ju": u"жу",
+ u"PH": u"Ф", u"Ph": u"Ф", u"ph": u"ф",
+ u"TH": u"З", u"Th": u"З", u"th": u"з",
+ u"W": u"В", u"w": u"в", u"Q": u"К", u"q": u"к",
+ u"WH": u"В", u"Wh": u"В", u"wh": u"в",
+ u"Y": u"И", u"y": u"и",
+ u"YA": u"Я", u"Ya": u"я", u"ya": u"я",
+ u"YE": u"Е", u"Ye": u"е", u"ye": u"е",
+ u"YI": u"И", u"Yi": u"и", u"yi": u"и",
+ u"YO": u"Ё", u"Yo": u"ё", u"yo": u"ё",
+ u"YU": u"Ю", u"Yu": u"ю", u"yu": u"ю",
+ u"Y'": u"ы", u"y'": u"ы",
+ u"iy": u"ый", u"ij": u"ый", # dobriy => добрый
})
# Transliterate from Tajik cyrillic to latin
@@ -140,6 +153,8 @@ TJ_CYR_TO_LAT_DICT = copy.deepcopy(RU_CYR_TO_LAT_DICT)
TJ_CYR_TO_LAT_DICT[u"Э"] = u"È"
TJ_CYR_TO_LAT_DICT[u"э"] = u"è"
TJ_CYR_TO_LAT_DICT[u"ъ"] = u"’"
+TJ_CYR_TO_LAT_DICT[u"Х"] = u"H"
+TJ_CYR_TO_LAT_DICT[u"х"] = u"h"
TJ_CYR_TO_LAT_DICT[u"Ч"] = u"Č"
TJ_CYR_TO_LAT_DICT[u"ч"] = u"č"
TJ_CYR_TO_LAT_DICT[u"Ж"] = u"Ž"
@@ -188,6 +203,8 @@ del BG_CYR_TO_LAT_DICT[u"э"]
# Some letters that are pronounced diferently
BG_CYR_TO_LAT_DICT[u"Й"] = u"Y"
BG_CYR_TO_LAT_DICT[u"й"] = u"y"
+BG_CYR_TO_LAT_DICT[u"Х"] = u"H"
+BG_CYR_TO_LAT_DICT[u"х"] = u"h"
BG_CYR_TO_LAT_DICT[u"Ц"] = u"TS"
BG_CYR_TO_LAT_DICT[u"ц"] = u"ts"
BG_CYR_TO_LAT_DICT[u"Щ"] = u"SHT"
@@ -228,6 +245,8 @@ UA_CYR_TO_LAT_DICT[u"И"] = u"Y"
UA_CYR_TO_LAT_DICT[u"и"] = u"y"
UA_CYR_TO_LAT_DICT[u"Х"] = u"X"
UA_CYR_TO_LAT_DICT[u"х"] = u"x"
+UA_CYR_TO_LAT_DICT[u"Ц"] = u"C"
+UA_CYR_TO_LAT_DICT[u"ц"] = u"c"
UA_CYR_TO_LAT_DICT[u"Ч"] = u"Č"
UA_CYR_TO_LAT_DICT[u"ч"] = u"č"
UA_CYR_TO_LAT_DICT[u"Ш"] = u"Š"
@@ -235,7 +254,9 @@ UA_CYR_TO_LAT_DICT[u"ш"] = u"š"
UA_CYR_TO_LAT_DICT[u"Щ"] = u"Šč"
UA_CYR_TO_LAT_DICT[u"щ"] = u"šč"
UA_CYR_TO_LAT_DICT[u"Ю"] = u"Ju"
+UA_CYR_TO_LAT_DICT[u"ю"] = u"ju"
UA_CYR_TO_LAT_DICT[u"Я"] = u"Ja"
+UA_CYR_TO_LAT_DICT[u"я"] = u"ja"
# Delete unused letters
del UA_CYR_TO_LAT_DICT[u"Ё"]
del UA_CYR_TO_LAT_DICT[u"ё"]
| opendatakosovo/cyrillic-transliteration | 308ec9fba59f96c5eb8cf74371db8a3c0a3a78d8 | diff --git a/tests.py b/tests.py
index 3e52db5..1a266a6 100644
--- a/tests.py
+++ b/tests.py
@@ -12,8 +12,8 @@ montenegrin_alphabet_latin = 'AaBbVvGgDdĐđEeŽžZzŹźIiJjKkLlLjljMmNnNjnjOo
macedonian_alphabet_cyrillic = 'АаБбВвГгДдЃѓЕеЖжЗзЅѕИиЈјКкЛлЉљМмНнЊњОоПпРрСсТтЌќУуФфХхЦцЧчЏџШш'
macedonian_alphabet_latin = 'AaBbVvGgDdǴǵEeŽžZzDzdzIiJjKkLlLjljMmNnNjnjOoPpRrSsTtḰḱUuFfHhCcČčDždžŠš'
-russian_alphabet_cyrillic = 'АаБбВвГгДдЕеЁёЖжЗзИиЙйКкЛлМмНнОоПпРрСсТтУуФфХхЦцЧчШшЩщЪъЫыЬьЭэЮюЯя'
-russian_alphabet_latin = 'AaBbVvGgDdEeYOyoZHzhZzIiJjKkLlMmNnOoPpRrSsTtUuFfHhCcCHchSHshSZsz##Yy\'\'EHehJUjuJAja'
+russian_alphabet_cyrillic = 'АаБбВвГгДдЕеЁёЖжЗзИиЙйКкЛлМмНнОоПпРрСсТтУуФфХхЦцЧчШшЩщЪъЫыьЭэЮюЯя'
+russian_alphabet_latin = 'AaBbVvGgDdEeYOyoZHzhZzIiJjKkLlMmNnOoPpRrSsTtUuFfXxCZczCHchSHshSHHshh\'\'\'\'Y\'y\'\'E\'e\'YUyuYAya'
tajik_alphabet_cyrillic = 'АаБбВвГгҒғДдЕеЁёЖжЗзИиӢӣЙйКкЛлМмНнОоПпРрСсТтУуӮӯФфХхҲҳЧчҶҷШшъЭэЮюЯя'
tajik_alphabet_latin = 'AaBbVvGgǦǧDdEeË뎞ZzIiĪīJjKkLlMmNnOoPpRrSsTtUuŪūFfHhḨḩČčÇ犚’ÈèÛûÂâ'
@@ -178,7 +178,7 @@ class TestRussianTransliteration(unittest.TestCase):
'''
transliterated_alphabet = cyrtranslit.to_cyrillic(russian_alphabet_latin, lang_code='ru')
- self.assertEqual(transliterated_alphabet, russian_alphabet_cyrillic.replace('Ъ', 'ъ').replace('Ь', 'ь'))
+ self.assertEqual(transliterated_alphabet, russian_alphabet_cyrillic.replace('Ъ', 'ъ').replace('Ь', 'ь').replace('Ы', 'ы'))
class TestTajikTransliteration(unittest.TestCase):
def test_alphabet_transliteration_cyrillic_to_latin(self):
| Cyrillic letter Ъ transliterate it to #.
This was raised in #12 by @097115. To reproduce this issue:
```bash
python cyrtranslit.py -l RU -i tests/ru.txt
``` | 0.0 | [
"tests.py::TestRussianTransliteration::test_alphabet_transliteration_cyrillic_to_latin",
"tests.py::TestRussianTransliteration::test_alphabet_transliteration_latin_to_cyrillic"
] | [
"tests.py::TestSerbianTransliterationFromCyrillicToLatin::test_alphabet_transliteration",
"tests.py::TestSerbianTransliterationFromCyrillicToLatin::test_latin_alphabet_characters",
"tests.py::TestSerbianTransliterationFromCyrillicToLatin::test_mix_characters",
"tests.py::TestSerbianTransliterationFromCyrillicToLatin::test_numerical_characters",
"tests.py::TestSerbianTransliterationFromCyrillicToLatin::test_special_characters",
"tests.py::TestSerbianTransliterationFromCyrillicToLatin::test_special_diacritic_characters",
"tests.py::TestSerbianTransliterationFromLatinToCyrillic::test_alphabet_transliteration",
"tests.py::TestSerbianTransliterationFromLatinToCyrillic::test_mix_characters",
"tests.py::TestSerbianTransliterationFromLatinToCyrillic::test_numerical_characters",
"tests.py::TestSerbianTransliterationFromLatinToCyrillic::test_special_characters",
"tests.py::TestSerbianTransliterationFromLatinToCyrillic::test_special_diacritic_characters",
"tests.py::TestMontenegrinTransliteration::test_alphabet_transliteration_cyrillic_to_latin",
"tests.py::TestMontenegrinTransliteration::test_alphabet_transliteration_latin_to_cyrillic",
"tests.py::TestMacedonianTransliteration::test_alphabet_transliteration_cyrillic_to_latin",
"tests.py::TestMacedonianTransliteration::test_alphabet_transliteration_latin_to_cyrillic",
"tests.py::TestTajikTransliteration::test_alphabet_transliteration_cyrillic_to_latin",
"tests.py::TestTajikTransliteration::test_alphabet_transliteration_latin_to_cyrillic",
"tests.py::TestUkrainianTransliteration::test_alphabet_transliteration_cyrillic_to_latin",
"tests.py::TestUkrainianTransliteration::test_alphabet_transliteration_latin_to_cyrillic",
"tests.py::TestUkrainianTransliteration::test_numerical_characters",
"tests.py::TestUkrainianTransliteration::test_special_diacritic_characters",
"tests.py::TestBulgarianTransliteration::test_alphabet_transliteration_cyrillic_to_latin",
"tests.py::TestBulgarianTransliteration::test_alphabet_transliteration_latin_to_cyrillic"
] | 2022-06-12 12:00:36+00:00 | 4,402 |
|
openelections__clarify-29 | diff --git a/HISTORY.rst b/HISTORY.rst
index 88cceee..0ca71c3 100644
--- a/HISTORY.rst
+++ b/HISTORY.rst
@@ -6,6 +6,12 @@ History
- Add optional party attibute to Choice objects.
+0.1.2 (2014-11-30)
+------------------
+
+- Fix `#13 <https://github.com/openelections/clarify/issues/13>`_.
+- Refactor parser code.
+
0.1.1 (2014-11-25)
------------------
diff --git a/clarify/parser.py b/clarify/parser.py
index a11dc91..01fef64 100644
--- a/clarify/parser.py
+++ b/clarify/parser.py
@@ -1,5 +1,6 @@
-import datetime
from collections import namedtuple
+import datetime
+import re
import dateutil.parser
from lxml import etree
@@ -45,7 +46,7 @@ class Parser(object):
self._result_jurisdictions = self._parse_result_jurisdictions(tree)
self._result_jurisdiction_lookup = {j.name: j for j in self._result_jurisdictions}
- self._contests = self._parse_contests(tree, self._result_jurisdiction_lookup)
+ self._contests = self._parse_contests(tree)
self._contest_lookup = {c.text: c for c in self._contests}
def _parse_timestamp(self, tree):
@@ -128,6 +129,29 @@ class Parser(object):
els = tree.xpath('/ElectionResult/VoterTurnout') + tree.xpath('/ElectionResult/ElectionVoterTurnout')
return els[0].values()
+ @classmethod
+ def _underscore_to_camel(cls, s):
+ """Convert a string separated by underscores to camelcase"""
+ matches = re.findall(r'(_.)', s)
+ converted = s
+ for m in matches:
+ converted = converted.replace(m, m.upper().lstrip('_'))
+ return converted
+
+ @classmethod
+ def _parse_result_jurisdiction(cls, el):
+ kwargs = {
+ 'level': el.tag.lower()
+ }
+ for f in RESULT_JURISDICTION_FIELDS:
+ if f == 'level':
+ continue
+ attr_name = cls._underscore_to_camel(f)
+ converter = RESULT_JURISDICTION_FIELD_CONVERTERS.get(f)
+ kwargs[f] = cls._get_attrib(el, attr_name, converter)
+
+ return ResultJurisdiction(**kwargs)
+
def _parse_result_jurisdictions(self, tree):
"""
Parse sub-jurisdictions for these results.
@@ -142,31 +166,9 @@ class Parser(object):
"""
result_jurisdictions = []
precinct_els = tree.xpath('/ElectionResult/VoterTurnout/Precincts/Precinct')
- for el in precinct_els:
- result_jurisdictions.append(ResultJurisdiction(
- name=el.attrib['name'],
- total_voters=int(el.attrib['totalVoters']),
- ballots_cast=int(el.attrib['ballotsCast']),
- voter_turnout=float(el.attrib['voterTurnout']),
- percent_reporting=float(el.attrib['percentReporting']),
- precincts_participating=None,
- precincts_reported=None,
- precincts_reporting_percent=None,
- level='precinct'
- ))
county_els = tree.xpath('/ElectionResult/ElectionVoterTurnout/Counties/County')
- for el in county_els:
- result_jurisdictions.append(ResultJurisdiction(
- name=el.attrib['name'],
- total_voters=int(el.attrib['totalVoters']),
- ballots_cast=int(el.attrib['ballotsCast']),
- voter_turnout=float(el.attrib['voterTurnout']),
- percent_reporting=None,
- precincts_participating=float(el.attrib['precinctsParticipating']),
- precincts_reported=float(el.attrib['precinctsReported']),
- precincts_reporting_percent=float(el.attrib['precinctsReportingPercent']),
- level='county'
- ))
+ for el in precinct_els + county_els:
+ result_jurisdictions.append(self._parse_result_jurisdiction(el))
return result_jurisdictions
@property
@@ -208,10 +210,33 @@ class Parser(object):
``ResultJurisdiction`` object whose ``name`` attribute matches
``name``.
+ Raises:
+ ``KeyError`` if a matching jurisdiction is not found.
+
"""
return self._result_jurisdiction_lookup[name]
- def _get_attrib(self, el, attr, fn=None):
+ def _get_or_create_result_jurisdiction(self, el):
+ try:
+ return self.get_result_jurisdiction(el.attrib['name'])
+ except KeyError:
+ # We don't yet know about this jurisdiction. In some rare
+ # cases, there is a mismatch between jurisdictions in the
+ # ``VoterTurnout`` element and the ``VoteType`` elements.
+ jurisdiction = self._parse_result_jurisdiction(el)
+ self.add_result_jurisdiction(jurisdiction)
+ return jurisdiction
+
+ def add_result_jurisdiction(self, jurisdiction):
+ """
+ Add a ResultJurisdiction object to the parser's list of known
+ Jurisdictions.
+ """
+ self._result_jurisdictions.append(jurisdiction)
+ self._result_jurisdiction_lookup[jurisdiction.name] = jurisdiction
+
+ @classmethod
+ def _get_attrib(cls, el, attr, fn=None):
"""
Get an attribute for an XML element
@@ -238,31 +263,30 @@ class Parser(object):
except KeyError:
return None
- def _parse_contests(self, tree, result_jurisdiction_lookup):
+ def _parse_contests(self, tree):
"""
Parse contests from these results
Args:
tree: ElementTree object representing the root of the parsed XML
document
- result_jurisdiction_lookup: Dictionary mapping jurisdiction names to
- ``ResultJurisdiction`` objects
Returns:
List of ``Contest`` objects
+ If a new jurisdiction is found when parsing the contests, it will be
+ added to the instance's list of result jurisdictions.
+
"""
contest_els = tree.xpath('/ElectionResult/Contest')
- return [self._parse_contest(el, result_jurisdiction_lookup) for el in contest_els]
+ return [self._parse_contest(el) for el in contest_els]
- def _parse_contest(self, contest_el, result_jurisdiction_lookup):
+ def _parse_contest(self, contest_el):
"""
Parse a single ``Contest`` element's attributes and results
Args:
contest_el: Element object for a ``Contest`` contest_element in the parsed XML.
- result_jurisdiction_lookup: Dictionary mapping jurisdiction names to
- ``ResultJurisdiction`` objects
Returns:
A ``Contest`` object with attributes parsed from the XML element.
@@ -280,15 +304,15 @@ class Parser(object):
counties_participating=self._get_attrib(contest_el, 'countiesParticipating', int)
)
- for r in self._parse_no_choice_results(contest_el, result_jurisdiction_lookup, contest):
+ for r in self._parse_no_choice_results(contest_el, contest):
contest.add_result(r)
- for c in self._parse_choices(contest_el, contest, result_jurisdiction_lookup):
+ for c in self._parse_choices(contest_el, contest):
contest.add_choice(c)
return contest
- def _parse_no_choice_results(self, contest_el, result_jurisdiction_lookup, contest):
+ def _parse_no_choice_results(self, contest_el, contest):
"""
Parse results not associated with a Choice.
@@ -297,8 +321,6 @@ class Parser(object):
Args:
contest_el: Element object for a single ``Contest`` element in the XML
document.
- result_jurisdiction_lookup: Dictionary mapping jurisdiction names to
- ``ResultJurisdiction`` objects
Returns:
A list of ``Result`` objects
@@ -319,45 +341,39 @@ class Parser(object):
# The subjurisdiction elements are either ``Precinct`` for county or
# city files or ``County`` for state files
for subjurisdiction_el in vt_el.xpath('./Precinct') + vt_el.xpath('./County'):
- if subjurisdiction_el.attrib['name'] in result_jurisdiction_lookup:
- subjurisdiction = result_jurisdiction_lookup[subjurisdiction_el.attrib['name']]
-
- results.append(Result(
- contest=contest,
- vote_type=vote_type,
- jurisdiction=subjurisdiction,
- votes=int(subjurisdiction_el.attrib['votes']),
- choice=None
- ))
+ subjurisdiction = self._get_or_create_result_jurisdiction(subjurisdiction_el)
+ results.append(Result(
+ contest=contest,
+ vote_type=vote_type,
+ jurisdiction=subjurisdiction,
+ votes=int(subjurisdiction_el.attrib['votes']),
+ choice=None
+ ))
return results
- def _parse_choices(self, contest_el, contest, result_jurisdiction_lookup):
+ def _parse_choices(self, contest_el, contest):
"""
Parse ``Choice`` elements for a ``Contest`` element.
Args:
contest_el: Element object for a ``Contest`` contest_element in the parsed XML
contest: ``Contest`` object corresponding to ``Contest`` element
- result_jurisdiction_lookup: Dictionary mapping jurisdiction names to
- ``ResultJurisdiction`` objects
Returns:
A list of ``Choice`` elements
"""
- return [self._parse_choice(c_el, contest, result_jurisdiction_lookup)
+ return [self._parse_choice(c_el, contest)
for c_el in contest_el.xpath('Choice')]
- def _parse_choice(self, contest_el, contest, result_jurisdiction_lookup):
+ def _parse_choice(self, contest_el, contest):
"""
Parse a single ``Choice`` element
Args:
contest_el: Element object for a ``Contest`` contest_element in the parsed XML
contest: ``Contest`` object corresponding to ``Contest`` element
- result_jurisdiction_lookup: Dictionary mapping jurisdiction names to
- ``ResultJurisdiction`` objects
Returns:
A ``Choice`` element
@@ -388,15 +404,16 @@ class Parser(object):
))
for subjurisdiction_el in vt_el.xpath('./Precinct') + vt_el.xpath('./County'):
- if subjurisdiction_el.attrib['name'] in result_jurisdiction_lookup:
- subjurisdiction = result_jurisdiction_lookup[subjurisdiction_el.attrib['name']]
- choice.add_result(Result(
- contest=contest,
- vote_type=vote_type,
- jurisdiction=subjurisdiction,
- votes=int(subjurisdiction_el.attrib['votes']),
- choice=choice
- ))
+ subjurisdiction = self.get_result_jurisdiction(subjurisdiction_el.attrib['name'])
+ subjurisdiction = self._get_or_create_result_jurisdiction(subjurisdiction_el)
+ choice.add_result(Result(
+ contest=contest,
+ vote_type=vote_type,
+ jurisdiction=subjurisdiction,
+ votes=int(subjurisdiction_el.attrib['votes']),
+ choice=choice
+ ))
+
return choice
@classmethod
@@ -441,7 +458,7 @@ class ResultAggregatorMixin(object):
self._results.append(result)
-RESULT_FIELDS = [
+RESULT_JURISDICTION_FIELDS = [
'name',
'total_voters',
'ballots_cast',
@@ -453,9 +470,19 @@ RESULT_FIELDS = [
'level',
]
+RESULT_JURISDICTION_FIELD_CONVERTERS = {
+ 'total_voters': int,
+ 'ballots_cast': int,
+ 'voter_turnout': float,
+ 'percent_reporting': float,
+ 'precincts_participating': float,
+ 'precincts_reported': float,
+ 'precincts_reporting_percent': float,
+}
+
class ResultJurisdiction(ResultAggregatorMixin,
- namedtuple('ResultJurisdictionBase', RESULT_FIELDS)):
+ namedtuple('ResultJurisdictionBase', RESULT_JURISDICTION_FIELDS)):
"""
A jurisdiction such as a county or precinct that has associated results
"""
| openelections/clarify | 3779c2f90cd49cfedf377730f6dd23d28b32e2a8 | diff --git a/tests/test_parser.py b/tests/test_parser.py
index 5c053ee..7a4b77b 100644
--- a/tests/test_parser.py
+++ b/tests/test_parser.py
@@ -1,7 +1,107 @@
import datetime
import unittest
-from clarify.parser import Parser
+import lxml.etree
+
+from clarify.parser import (Parser, ResultJurisdiction)
+
+
+class TestParser(unittest.TestCase):
+
+ def test__underscore_to_camel(self):
+ self.assertEqual(Parser._underscore_to_camel(""), "")
+ self.assertEqual(Parser._underscore_to_camel("test"), "test")
+ self.assertEqual(Parser._underscore_to_camel("test_again"), "testAgain")
+ self.assertEqual(Parser._underscore_to_camel("test_again_but_longer"), "testAgainButLonger")
+ self.assertEqual(Parser._underscore_to_camel("_test_again"), "TestAgain") # XXX: Is this what we expect?
+ self.assertEqual(Parser._underscore_to_camel("testing_123"), "testing123")
+ self.assertEqual(Parser._underscore_to_camel("testing_123_again"), "testing123Again")
+
+ def test__parse_result_jurisdiction(self):
+ tag_name = "County"
+ attributes = {
+ "name": "Arkansas",
+ "totalVoters": "10196",
+ "ballotsCast": "5137",
+ "voterTurnout": "50.38",
+ "percentReporting": "100.00",
+ "precinctsParticipating": "30",
+ "precinctsReported": "30",
+ "precinctsReportingPercent": "100.00",
+ }
+
+ result_jurisdiction_element = lxml.etree.Element(tag_name, attributes)
+
+ result_jurisdiction = Parser._parse_result_jurisdiction(result_jurisdiction_element)
+
+ self.assertIsInstance(result_jurisdiction, ResultJurisdiction)
+
+ self.assertTrue(hasattr(result_jurisdiction, "level"))
+ self.assertTrue(hasattr(result_jurisdiction, "name"))
+ self.assertTrue(hasattr(result_jurisdiction, "total_voters"))
+ self.assertTrue(hasattr(result_jurisdiction, "ballots_cast"))
+ self.assertTrue(hasattr(result_jurisdiction, "voter_turnout"))
+ self.assertTrue(hasattr(result_jurisdiction, "percent_reporting"))
+ self.assertTrue(hasattr(result_jurisdiction, "precincts_participating"))
+ self.assertTrue(hasattr(result_jurisdiction, "precincts_reported"))
+ self.assertTrue(hasattr(result_jurisdiction, "precincts_reporting_percent"))
+
+ self.assertEqual(result_jurisdiction.level, tag_name.lower())
+ self.assertEqual(result_jurisdiction.name, attributes["name"])
+ self.assertEqual(result_jurisdiction.total_voters, int(attributes["totalVoters"]))
+ self.assertEqual(result_jurisdiction.ballots_cast, int(attributes["ballotsCast"]))
+ self.assertEqual(result_jurisdiction.voter_turnout, float(attributes["voterTurnout"]))
+ self.assertEqual(result_jurisdiction.percent_reporting, float(attributes["percentReporting"]))
+ self.assertEqual(result_jurisdiction.precincts_participating, float(attributes["precinctsParticipating"]))
+ self.assertEqual(result_jurisdiction.precincts_reported, float(attributes["precinctsReported"]))
+ self.assertEqual(result_jurisdiction.precincts_reporting_percent, float(attributes["precinctsReportingPercent"]))
+
+ def test__get_or_create_result_jurisdiction(self):
+ result_jurisdiction_name = "Test"
+ result_jurisdiction_element = lxml.etree.Element("County", { "name": result_jurisdiction_name })
+ result_jurisdiction = Parser._parse_result_jurisdiction(result_jurisdiction_element)
+
+ parser = Parser()
+
+ self.assertEqual(parser._result_jurisdictions, [])
+ self.assertEqual(parser._result_jurisdiction_lookup, {})
+
+ # Test the "create" part.
+ parser._get_or_create_result_jurisdiction(result_jurisdiction_element)
+
+ self.assertEqual(parser._result_jurisdictions, [ result_jurisdiction ])
+ self.assertEqual(parser._result_jurisdiction_lookup, { result_jurisdiction_name: result_jurisdiction })
+
+ # Test the "get" part.
+ parser._get_or_create_result_jurisdiction(result_jurisdiction_element)
+
+ self.assertEqual(parser._result_jurisdictions, [ result_jurisdiction ])
+ self.assertEqual(parser._result_jurisdiction_lookup, { result_jurisdiction_name: result_jurisdiction })
+
+ def test_add_result_jurisdiction(self):
+ result_jurisdiction_name = "Test"
+ result_jurisdiction = ResultJurisdiction(
+ name=result_jurisdiction_name,
+ total_voters=0,
+ ballots_cast=0,
+ voter_turnout=100.0,
+ percent_reporting=100.0,
+ precincts_participating=0,
+ precincts_reported=0,
+ precincts_reporting_percent=100.0,
+ level="county",
+ )
+
+ parser = Parser()
+
+ self.assertEqual(parser._result_jurisdictions, [])
+ self.assertEqual(parser._result_jurisdiction_lookup, {})
+
+ parser.add_result_jurisdiction(result_jurisdiction)
+
+ self.assertEqual(parser._result_jurisdictions, [ result_jurisdiction ])
+ self.assertEqual(parser._result_jurisdiction_lookup, { result_jurisdiction_name: result_jurisdiction })
+
class TestPrecinctParser(unittest.TestCase):
def test_parse(self):
@@ -137,4 +237,3 @@ class TestCountyParser(unittest.TestCase):
self.assertEqual(contest_choice.key, "001")
self.assertEqual(contest_choice.party, "REP")
self.assertEqual(contest_choice.total_votes, 477734)
-
| Precinct lookup fails when precinct not in VoterTurnout element
We try to grab the lists of precincts from the VoterTurnout element and then look them up when setting the jurisdiction of vote objects. However, the precinct may not exist in the VoterTurnout entity, but may exist as a Precinct element under a VoteType element. This appears in the results file 20120522__ar__primary__van_buren__precinct.xml.
This happens in Parser._parse_contest() and results in a KeyError.
I've already fixed this in my working copy and am just creating this issue for reference. I'll push the change to GitHub and PyPI when I get home tonight.
| 0.0 | [
"tests/test_parser.py::TestParser::test__get_or_create_result_jurisdiction",
"tests/test_parser.py::TestParser::test__parse_result_jurisdiction",
"tests/test_parser.py::TestParser::test__underscore_to_camel",
"tests/test_parser.py::TestParser::test_add_result_jurisdiction"
] | [
"tests/test_parser.py::TestPrecinctParser::test_parse",
"tests/test_parser.py::TestCountyParser::test_parse"
] | 2018-09-09 03:08:45+00:00 | 4,403 |
|
openfoodfacts__openfoodfacts-python-17 | diff --git a/openfoodfacts/products.py b/openfoodfacts/products.py
index f3c88e5..9ea0327 100644
--- a/openfoodfacts/products.py
+++ b/openfoodfacts/products.py
@@ -31,8 +31,16 @@ def get_by_facets(query):
return utils.fetch('/'.join(path))['products']
-def search(query, pagination=20):
+def search(query, page=1, page_size=20, sort_by='unique_scans'):
"""
Perform a search using Open Food Facts search engine.
"""
- pass
+ path = "cgi/search.pl?search_terms={query}&json=1&" + \
+ "page={page}&page_size={page_size}&sort_by={sort_by}"
+ path = path.format(
+ query=query,
+ page=page,
+ page_size=page_size,
+ sort_by=sort_by
+ )
+ return utils.fetch(path, json_file=False)
diff --git a/openfoodfacts/utils.py b/openfoodfacts/utils.py
index 62689b4..4ae09d3 100644
--- a/openfoodfacts/utils.py
+++ b/openfoodfacts/utils.py
@@ -3,20 +3,35 @@ import requests
API_URL = "http://world.openfoodfacts.org/"
-def fetch(path):
+def fetch(path, json_file=True):
"""
Fetch data at a given path assuming that target match a json file and is
located on the OFF API.
"""
- response = requests.get("%s%s.json" % (API_URL, path))
+ if json_file:
+ path = "%s%s.json" % (API_URL, path)
+ else:
+ path = "%s%s" % (API_URL, path)
+
+ response = requests.get(path)
return response.json()
-def get_ocr_json_url_for_an_image(first_three_digits, second_three_digits, third_three_digits,fourth_three_digits, image_name):
+
+def get_ocr_json_url_for_an_image(first_three_digits,
+ second_three_digits,
+ third_three_digits,
+ fourth_three_digits,
+ image_name):
"""
- Get the URL of a JSON file given a barcode in 4 chunks of 3 digits and an image name (1, 2, 3, front_fr…)
+ Get the URL of a JSON file given a barcode in 4 chunks of 3 digits and an
+ image name (1, 2, 3, front_fr...).
"""
- try:
- image_ocr_json = "http://world.openfoodfacts.org/images/products/" + str(first_three_digits)+ "/" + str(second_three_digits)+ "/" + str(third_three_digits)+ "/" + str(fourth_three_digits)+ "/" + str(image_name) + ".json"
- return str(image_ocr_json)
- except IndexError:
- return None
+ url = "http://world.openfoodfacts.org/images/products/"
+ url += "%s/%s/%s/%s/%s.json" % (
+ first_three_digits,
+ second_three_digits,
+ third_three_digits,
+ fourth_three_digits,
+ image_name
+ )
+ return url
| openfoodfacts/openfoodfacts-python | bc1b70108866958c0bc50a2206c5796130fe6ced | diff --git a/tests/products_test.py b/tests/products_test.py
index 27496c3..c58a6d2 100644
--- a/tests/products_test.py
+++ b/tests/products_test.py
@@ -41,6 +41,23 @@ class TestProducts(unittest.TestCase):
{'trace': 'egg', 'country': 'france'})
self.assertEquals(res, ["omelet"])
+ def test_search(self):
+ with requests_mock.mock() as mock:
+ mock.get(
+ 'http://world.openfoodfacts.org/cgi/search.pl?' +
+ 'search_terms=kinder bueno&json=1&page=' +
+ '1&page_size=20&sort_by=unique_scans',
+ text='{"products":["kinder bueno"], "count": 1}')
+ res = openfoodfacts.products.search('kinder bueno')
+ self.assertEquals(res["products"], ["kinder bueno"])
+ mock.get(
+ 'http://world.openfoodfacts.org/cgi/search.pl?' +
+ 'search_terms=banania&json=1&page=' +
+ '2&page_size=10&sort_by=unique_scans',
+ text='{"products":["banania", "banania big"], "count": 2}')
+ res = openfoodfacts.products.search(
+ 'banania', page=2, page_size=10)
+ self.assertEquals(res["products"], ["banania", "banania big"])
if __name__ == '__main__':
unittest.main()
| Allow to perform a search
Ex: Get data from:
`http://world.openfoodfacts.org/cgi/search.pl?search_terms=banania&search_simple=1&action=process&json=1`
| 0.0 | [
"tests/products_test.py::TestProducts::test_get_by_country",
"tests/products_test.py::TestProducts::test_get_by_trace",
"tests/products_test.py::TestProducts::test_get_by_country_and_trace",
"tests/products_test.py::TestProducts::test_search",
"tests/products_test.py::TestProducts::test_get_product"
] | [] | 2016-11-13 15:23:51+00:00 | 4,404 |
|
openfoodfacts__openfoodfacts-python-191 | diff --git a/README.md b/README.md
index 0294826..181e6dc 100644
--- a/README.md
+++ b/README.md
@@ -112,4 +112,4 @@ Contributors:
Copyright 2016-2022 Open Food Facts
-The Open Food Facts Python SDK is licensed under the [MIT License](https://github.com/openfoodfacts/openfoodfacts-python/blob/develop/LICENSE).
\ No newline at end of file
+The Open Food Facts Python SDK is licensed under the [MIT License](https://github.com/openfoodfacts/openfoodfacts-python/blob/develop/LICENSE).
diff --git a/docs/usage.md b/docs/usage.md
index 39dfaca..c268e00 100644
--- a/docs/usage.md
+++ b/docs/usage.md
@@ -41,7 +41,7 @@ api.product.get(code)
*Perform text search*
```python
-results = api.product.text_search("mineral water")
+results = api.product.text_search("pizza")
```
*Create a new product or update an existing one*
diff --git a/openfoodfacts/api.py b/openfoodfacts/api.py
index cfcac1a..01bb049 100644
--- a/openfoodfacts/api.py
+++ b/openfoodfacts/api.py
@@ -197,7 +197,7 @@ class ProductResource:
params["sort_by"] = sort_by
return send_get_request(
- url=f"{self.base_url}/api/v2/search",
+ url=f"{self.base_url}/cgi/search.pl",
api_config=self.api_config,
params=params,
)
| openfoodfacts/openfoodfacts-python | 506f7a8b57918e0caff49747ded699d8176d599f | diff --git a/tests/test_api.py b/tests/test_api.py
index 5bf4917..d0d7698 100644
--- a/tests/test_api.py
+++ b/tests/test_api.py
@@ -86,7 +86,7 @@ class TestProducts(unittest.TestCase):
with requests_mock.mock() as mock:
response_data = {"products": ["kinder bueno"], "count": 1}
mock.get(
- "https://world.openfoodfacts.org/api/v2/search?"
+ "https://world.openfoodfacts.org/cgi/search.pl?"
+ "search_terms=kinder+bueno&json=1&page="
+ "1&page_size=20",
text=json.dumps(response_data),
@@ -95,7 +95,7 @@ class TestProducts(unittest.TestCase):
self.assertEqual(res["products"], ["kinder bueno"])
response_data = {"products": ["banania", "banania big"], "count": 2}
mock.get(
- "https://world.openfoodfacts.org/api/v2/search?"
+ "https://world.openfoodfacts.org/cgi/search.pl?"
+ "search_terms=banania&json=1&page="
+ "2&page_size=10&sort_by=unique_scans",
text=json.dumps(response_data),
| Problem with product search, something is certainly hardcoded
### What
The App always return the result for "eau mineral" (I guess it's for this because it's always starting with cristaline)
which is basically making the API useless
### Steps to reproduce the behavior:
import openfoodfacts
api = openfoodfacts.API(version="v2")
results = api.product.text_search("Tomate")
### Expected behavior
Return products data that are in link with Tomate and not "mineral water"
### Platform (Desktop, Mobile, Hunger Games)
- OS: MACOS
- Platform MacBook AIR
| 0.0 | [
"tests/test_api.py::TestProducts::test_text_search"
] | [
"tests/test_api.py::TestProducts::test_get_product",
"tests/test_api.py::TestProducts::test_get_product_with_fields",
"tests/test_api.py::TestProducts::test_get_product_missing",
"tests/test_api.py::TestProducts::test_get_product_invalid_code"
] | 2023-11-30 22:28:21+00:00 | 4,405 |
|
openfoodfacts__openfoodfacts-python-26 | diff --git a/README.md b/README.md
index 20ee03d..218f642 100644
--- a/README.md
+++ b/README.md
@@ -137,6 +137,8 @@ states = openfoodfacts.facets.get_states()
*Get all products for given facets.*
+Page access (pagination) is available through parameters.
+
```python
products = openfoodfacts.products.get_by_facets({
'trace': 'egg',
@@ -147,7 +149,7 @@ products = openfoodfacts.products.get_by_facets({
*Get all products for given additive.*
```python
-products = openfoodfacts.products.get_by_additive(additive)
+products = openfoodfacts.products.get_by_additive(additive, page=1)
```
*Get all products for given allergen.*
diff --git a/openfoodfacts/__init__.py b/openfoodfacts/__init__.py
index b9cef3b..6ad94e6 100644
--- a/openfoodfacts/__init__.py
+++ b/openfoodfacts/__init__.py
@@ -37,8 +37,8 @@ def add_by_facet_fetch_function(facet):
else:
facet = facet[:-1]
- def func(facet_id):
- return utils.fetch('%s/%s' % (facet, facet_id))['products']
+ def func(facet_id, page=1):
+ return utils.fetch('%s/%s/%s' % (facet, facet_id, page))['products']
func.__name__ = "get_by_%s" % facet
setattr(products, func.__name__, func)
diff --git a/openfoodfacts/products.py b/openfoodfacts/products.py
index 9ea0327..141d59e 100644
--- a/openfoodfacts/products.py
+++ b/openfoodfacts/products.py
@@ -12,7 +12,7 @@ def get_product(barcode):
return utils.fetch('api/v0/product/%s' % barcode)
-def get_by_facets(query):
+def get_by_facets(query, page=1):
"""
Return products for a set of facets.
"""
@@ -28,7 +28,7 @@ def get_by_facets(query):
path.append(key)
path.append(query[key])
- return utils.fetch('/'.join(path))['products']
+ return utils.fetch('%s/%s' % ('/'.join(path), page))['products']
def search(query, page=1, page_size=20, sort_by='unique_scans'):
| openfoodfacts/openfoodfacts-python | 0858f6688ca51c0064aa1891b342a441680bf5c9 | diff --git a/tests/facets_test.py b/tests/facets_test.py
index 51f1fe9..b54228a 100644
--- a/tests/facets_test.py
+++ b/tests/facets_test.py
@@ -1,7 +1,5 @@
import unittest
-import os
import openfoodfacts
-import requests
import requests_mock
@@ -9,14 +7,14 @@ class TestFacets(unittest.TestCase):
def test_get_traces(self):
with requests_mock.mock() as mock:
- mock.get('http://world.openfoodfacts.org/traces.json',
+ mock.get('https://world.openfoodfacts.org/traces.json',
text='{"tags":["egg"]}')
res = openfoodfacts.facets.get_traces()
self.assertEquals(res, ["egg"])
def test_get_additives(self):
with requests_mock.mock() as mock:
- mock.get('http://world.openfoodfacts.org/additives.json',
+ mock.get('https://world.openfoodfacts.org/additives.json',
text='{"tags":["additive"]}')
res = openfoodfacts.facets.get_additives()
self.assertEquals(res, ["additive"])
diff --git a/tests/products_test.py b/tests/products_test.py
index c58a6d2..a2c3ab9 100644
--- a/tests/products_test.py
+++ b/tests/products_test.py
@@ -10,21 +10,28 @@ class TestProducts(unittest.TestCase):
def test_get_product(self):
with requests_mock.mock() as mock:
mock.get(
- 'http://world.openfoodfacts.org/api/v0/product/1223435.json',
+ 'https://world.openfoodfacts.org/api/v0/product/1223435.json',
text='{"name":"product_test"}')
res = openfoodfacts.get_product('1223435')
self.assertEquals(res, {'name': 'product_test'})
def test_get_by_trace(self):
with requests_mock.mock() as mock:
- mock.get('http://world.openfoodfacts.org/trace/egg.json',
+ mock.get('https://world.openfoodfacts.org/trace/egg/1.json',
text='{"products":["omelet"]}')
res = openfoodfacts.products.get_by_trace('egg')
self.assertEquals(res, ["omelet"])
+ def test_get_by_trace_pagination(self):
+ with requests_mock.mock() as mock:
+ mock.get('https://world.openfoodfacts.org/trace/egg/2.json',
+ text='{"products":["omelet"]}')
+ res = openfoodfacts.products.get_by_trace('egg', 2)
+ self.assertEquals(res, ["omelet"])
+
def test_get_by_country(self):
with requests_mock.mock() as mock:
- mock.get('http://world.openfoodfacts.org/country/france.json',
+ mock.get('https://world.openfoodfacts.org/country/france/1.json',
text='{"products":["omelet"]}')
res = openfoodfacts.products.get_by_country('france')
self.assertEquals(res, ["omelet"])
@@ -35,7 +42,8 @@ class TestProducts(unittest.TestCase):
with requests_mock.mock() as mock:
mock.get(
- 'http://world.openfoodfacts.org/country/france/trace/egg.json',
+ 'https://world.openfoodfacts.org/country/'
+ 'france/trace/egg/1.json',
text='{"products":["omelet"]}')
res = openfoodfacts.products.get_by_facets(
{'trace': 'egg', 'country': 'france'})
@@ -44,14 +52,14 @@ class TestProducts(unittest.TestCase):
def test_search(self):
with requests_mock.mock() as mock:
mock.get(
- 'http://world.openfoodfacts.org/cgi/search.pl?' +
+ 'https://world.openfoodfacts.org/cgi/search.pl?' +
'search_terms=kinder bueno&json=1&page=' +
'1&page_size=20&sort_by=unique_scans',
text='{"products":["kinder bueno"], "count": 1}')
res = openfoodfacts.products.search('kinder bueno')
self.assertEquals(res["products"], ["kinder bueno"])
mock.get(
- 'http://world.openfoodfacts.org/cgi/search.pl?' +
+ 'https://world.openfoodfacts.org/cgi/search.pl?' +
'search_terms=banania&json=1&page=' +
'2&page_size=10&sort_by=unique_scans',
text='{"products":["banania", "banania big"], "count": 2}')
| Travis build failing
@frankrousseau : Travis notifications are now available on Slack, shortly after you commit. The build is currently broken (looks like an encoding issue)
writing manifest file 'openfoodfacts.egg-info/SOURCES.txt'
running build_ext
Traceback (most recent call last):
File "setup.py", line 63, in <module>
extras_require={
File "/opt/python/2.7.9/lib/python2.7/distutils/core.py", line 151, in setup
dist.run_commands()
File "/opt/python/2.7.9/lib/python2.7/distutils/dist.py", line 953, in run_commands
self.run_command(cmd)
File "/opt/python/2.7.9/lib/python2.7/distutils/dist.py", line 972, in run_command
cmd_obj.run()
File "/home/travis/virtualenv/python2.7.9/lib/python2.7/site-packages/setuptools/command/test.py", line 142, in run
self.with_project_on_sys_path(self.run_tests)
File "/home/travis/virtualenv/python2.7.9/lib/python2.7/site-packages/setuptools/command/test.py", line 122, in with_project_on_sys_path
func()
File "/home/travis/virtualenv/python2.7.9/lib/python2.7/site-packages/setuptools/command/test.py", line 163, in run_tests
testRunner=self._resolve_as_ep(self.test_runner),
File "/opt/python/2.7.9/lib/python2.7/unittest/main.py", line 94, in __init__
self.parseArgs(argv)
File "/opt/python/2.7.9/lib/python2.7/unittest/main.py", line 149, in parseArgs
self.createTests()
File "/opt/python/2.7.9/lib/python2.7/unittest/main.py", line 158, in createTests
self.module)
File "/opt/python/2.7.9/lib/python2.7/unittest/loader.py", line 130, in loadTestsFromNames
suites = [self.loadTestsFromName(name, module) for name in names]
File "/opt/python/2.7.9/lib/python2.7/unittest/loader.py", line 103, in loadTestsFromName
return self.loadTestsFromModule(obj)
File "/home/travis/virtualenv/python2.7.9/lib/python2.7/site-packages/setuptools/command/test.py", line 37, in loadTestsFromModule
tests.append(self.loadTestsFromName(submodule))
File "/opt/python/2.7.9/lib/python2.7/unittest/loader.py", line 91, in loadTestsFromName
module = __import__('.'.join(parts_copy))
File "/home/travis/build/openfoodfacts/openfoodfacts-python/tests/facets_test.py", line 3, in <module>
import openfoodfacts
File "/home/travis/build/openfoodfacts/openfoodfacts-python/openfoodfacts/__init__.py", line 4, in <module>
from . import utils
File "/home/travis/build/openfoodfacts/openfoodfacts-python/openfoodfacts/utils.py", line 21
SyntaxError: Non-ASCII character '\xe2' in file /home/travis/build/openfoodfacts/openfoodfacts-python/openfoodfacts/utils.py on line 22, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details
The command "python setup.py test" exited with 1.
0.11s$ pep8 openfoodfacts/*.py
openfoodfacts/utils.py:19:80: E501 line too long (127 characters)
openfoodfacts/utils.py:19:1: E302 expected 2 blank lines, found 1
openfoodfacts/utils.py:19:94: E231 missing whitespace after ','
openfoodfacts/utils.py:23:1: W191 indentation contains tabs
openfoodfacts/utils.py:23:1: E101 indentation contains mixed spaces and tabs
openfoodfacts/utils.py:23:2: E113 unexpected indentation
openfoodfacts/utils.py:24:95: E225 missing whitespace around operator
The command "pep8 openfoodfacts/*.py" exited with 1.
Done. Your build exited with 1. | 0.0 | [
"tests/products_test.py::TestProducts::test_get_by_trace",
"tests/products_test.py::TestProducts::test_get_by_country",
"tests/products_test.py::TestProducts::test_get_by_trace_pagination",
"tests/products_test.py::TestProducts::test_get_by_country_and_trace"
] | [
"tests/products_test.py::TestProducts::test_get_product",
"tests/products_test.py::TestProducts::test_search",
"tests/facets_test.py::TestFacets::test_get_additives",
"tests/facets_test.py::TestFacets::test_get_traces"
] | 2017-03-09 19:10:49+00:00 | 4,406 |
|
openlawlibrary__pygls-247 | diff --git a/pygls/lsp/types/basic_structures.py b/pygls/lsp/types/basic_structures.py
index 879c15b..2b28b59 100644
--- a/pygls/lsp/types/basic_structures.py
+++ b/pygls/lsp/types/basic_structures.py
@@ -54,6 +54,14 @@ class Model(BaseModel):
'from_': 'from'
}
+ def __init__(self, **data: Any) -> None:
+ super().__init__(**data)
+
+ # Serialize (.json()) fields that has default value which is not None
+ for name, field in self.__fields__.items():
+ if getattr(field, 'default', None) is not None:
+ self.__fields_set__.add(name)
+
class JsonRpcMessage(Model):
"""A base json rpc message defined by LSP."""
diff --git a/pygls/protocol.py b/pygls/protocol.py
index 7e03b7d..a5438cc 100644
--- a/pygls/protocol.py
+++ b/pygls/protocol.py
@@ -385,7 +385,7 @@ class JsonRPCProtocol(asyncio.Protocol):
return
try:
- body = data.json(by_alias=True, exclude_none=True, encoder=default_serializer)
+ body = data.json(by_alias=True, exclude_unset=True, encoder=default_serializer)
logger.info('Sending data: %s', body)
body = body.encode(self.CHARSET)
| openlawlibrary/pygls | 96bc69df9c963979ce76f386e83fa059093bc284 | diff --git a/tests/test_protocol.py b/tests/test_protocol.py
index 88e0a2d..5318b80 100644
--- a/tests/test_protocol.py
+++ b/tests/test_protocol.py
@@ -14,6 +14,7 @@
# See the License for the specific language governing permissions and #
# limitations under the License. #
############################################################################
+import io
import json
from concurrent.futures import Future
from functools import partial
@@ -25,8 +26,16 @@ import pytest
from pygls.exceptions import JsonRpcException, JsonRpcInvalidParams
from pygls.lsp import Model, get_method_params_type
-from pygls.lsp.types import ClientCapabilities, InitializeParams, InitializeResult
-from pygls.protocol import JsonRPCNotification, JsonRPCRequestMessage, JsonRPCResponseMessage
+from pygls.lsp.types import (
+ ClientCapabilities,
+ CompletionItem,
+ CompletionItemKind,
+ InitializeParams,
+ InitializeResult,
+ ProgressParams,
+ WorkDoneProgressBegin,
+)
+from pygls.protocol import JsonRPCNotification, JsonRPCProtocol, JsonRPCRequestMessage, JsonRPCResponseMessage
from pygls.protocol import deserialize_message as _deserialize_message
TEST_METHOD = 'test_method'
@@ -94,6 +103,47 @@ def test_deserialize_notification_message_bad_params_should_raise_error():
json.loads(params, object_hook=deserialize_message)
[email protected](
+ "params, expected",
+ [
+ (
+ ProgressParams(
+ token="id1",
+ value=WorkDoneProgressBegin(
+ title="Begin progress",
+ percentage=0,
+ )
+ ),
+ {
+ "jsonrpc": "2.0",
+ "method": "test/notification",
+ "params": {
+ "token": "id1",
+ "value": {
+ "kind": "begin",
+ "percentage": 0,
+ "title": "Begin progress"
+ }
+ }
+ }
+ ),
+ ]
+)
+def test_serialize_notification_message(params, expected):
+ """Ensure that we can serialize notification messages, retaining all expected fields."""
+
+ buffer = io.StringIO()
+
+ protocol = JsonRPCProtocol(None)
+ protocol._send_only_body = True
+ protocol.connection_made(buffer)
+
+ protocol.notify("test/notification", params=params)
+ actual = json.loads(buffer.getvalue())
+
+ assert actual == expected
+
+
def test_deserialize_response_message():
params = '''
{
@@ -110,7 +160,6 @@ def test_deserialize_response_message():
assert result.result == "1"
assert result.error is None
-
def test_deserialize_request_message_with_registered_type__should_return_instance():
params = '''
{
@@ -163,6 +212,51 @@ def test_deserialize_request_message_without_registered_type__should_return_name
assert result.params.field_b.inner_field == "test_inner"
[email protected](
+ "result, expected",
+ [
+ (None, {"jsonrpc": "2.0", "id": "1", "result": None}),
+ (
+ [
+ CompletionItem(label='example-one'),
+ CompletionItem(
+ label='example-two',
+ kind=CompletionItemKind.Class,
+ preselect=False,
+ deprecated=True
+ ),
+ ],
+ {
+ "jsonrpc": "2.0",
+ "id": "1",
+ "result": [
+ {"label": "example-one"},
+ {
+ "label": "example-two",
+ "kind": 7, # CompletionItemKind.Class
+ "preselect": False,
+ "deprecated": True
+ }
+ ]
+ }
+ ),
+ ]
+)
+def test_serialize_response_message(result, expected):
+ """Ensure that we can serialize response messages, retaining all expected fields."""
+
+ buffer = io.StringIO()
+
+ protocol = JsonRPCProtocol(None)
+ protocol._send_only_body = True
+ protocol.connection_made(buffer)
+
+ protocol._send_response("1", result=result)
+ actual = json.loads(buffer.getvalue())
+
+ assert actual == expected
+
+
def test_data_received_without_content_type_should_handle_message(client_server):
_, server = client_server
body = json.dumps({
@@ -278,4 +372,3 @@ def test_ignore_unknown_notification(client_server):
# Remove mock
server.lsp._execute_notification = fn
-
| `exclude_none = True` breaks `shutdown` requests
Unfortunately, it looks like #236 breaks [`shutdown`](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#shutdown) requests.
I have a [command](https://github.com/swyddfa/esbonio/blob/ea8311a2b79ab8ef74157e9d5b2635e6b7b6a9e9/code/src/lsp/client.ts#L256) in Esbonio's VSCode extension that restarts the language server which sends a `shutdown` request to the server resulting in the following error
```
Command 'Esbonio: Restart Language Server' resulted in an error
(The received response has neither a result or an error property.)
```
With VSCode's devtools open I can see the response received from the server and the `result` field is in fact missing.
```json
{
"jsonrpc": "2.0",
"id": 1
}
```
Changing `exclude_none` back to `exclude_unset` fixes this issue.
I'm not entirely sure what to suggest as a fix as while I didn't follow the discussion around #236 that closely I'm aware it was to resolve some other issues.
---
Edit: Actually it looks like this is an issue for any request where `"result": null` is a valid response which includes completions, goto definition and others | 0.0 | [
"tests/test_protocol.py::test_serialize_response_message[None-expected0]"
] | [
"tests/test_protocol.py::test_deserialize_notification_message_valid_params",
"tests/test_protocol.py::test_deserialize_notification_message_bad_params_should_raise_error",
"tests/test_protocol.py::test_serialize_notification_message[params0-expected0]",
"tests/test_protocol.py::test_deserialize_response_message",
"tests/test_protocol.py::test_deserialize_request_message_with_registered_type__should_return_instance",
"tests/test_protocol.py::test_deserialize_request_message_without_registered_type__should_return_namedtuple",
"tests/test_protocol.py::test_serialize_response_message[result1-expected1]",
"tests/test_protocol.py::test_data_received_without_content_type_should_handle_message",
"tests/test_protocol.py::test_data_received_content_type_first_should_handle_message",
"tests/test_protocol.py::test_data_received_single_message_should_handle_message",
"tests/test_protocol.py::test_data_received_partial_message_should_handle_message",
"tests/test_protocol.py::test_data_received_multi_message_should_handle_messages",
"tests/test_protocol.py::test_data_received_error_should_raise_jsonrpc_error",
"tests/test_protocol.py::test_initialize_should_return_server_capabilities",
"tests/test_protocol.py::test_ignore_unknown_notification"
] | 2022-07-04 19:00:18+00:00 | 4,407 |
|
openlawlibrary__pygls-252 | diff --git a/CHANGELOG.md b/CHANGELOG.md
index 148cefb..d26b9ce 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,6 +13,8 @@ and this project adheres to [Semantic Versioning][semver].
### Fixed
+- `Document` objects now expose a text document's `language_id`
+
## [0.12] - 04/07/2022
### Added
diff --git a/pygls/workspace.py b/pygls/workspace.py
index eb4b631..8e73625 100644
--- a/pygls/workspace.py
+++ b/pygls/workspace.py
@@ -20,7 +20,7 @@ import io
import logging
import os
import re
-from typing import List, Pattern
+from typing import List, Optional, Pattern
from pygls.lsp.types import (NumType, Position, Range, TextDocumentContentChangeEvent,
TextDocumentItem, TextDocumentSyncKind,
@@ -160,11 +160,19 @@ def range_to_utf16(lines: List[str], range: Range) -> Range:
class Document(object):
- def __init__(self, uri, source=None, version=None, local=True,
- sync_kind=TextDocumentSyncKind.INCREMENTAL):
+ def __init__(
+ self,
+ uri: str,
+ source: Optional[str] = None,
+ version: Optional[NumType] = None,
+ language_id: Optional[str] = None,
+ local: bool = True,
+ sync_kind: TextDocumentSyncKind = TextDocumentSyncKind.INCREMENTAL
+ ):
self.uri = uri
self.version = version
self.path = to_fs_path(uri)
+ self.language_id = language_id
self.filename = os.path.basename(self.path)
self._local = local
@@ -333,12 +341,20 @@ class Workspace(object):
for folder in workspace_folders:
self.add_folder(folder)
- def _create_document(self,
- doc_uri: str,
- source: str = None,
- version: NumType = None) -> Document:
- return Document(doc_uri, source=source, version=version,
- sync_kind=self._sync_kind)
+ def _create_document(
+ self,
+ doc_uri: str,
+ source: Optional[str] = None,
+ version: Optional[NumType] = None,
+ language_id: Optional[str] = None,
+ ) -> Document:
+ return Document(
+ doc_uri,
+ source=source,
+ version=version,
+ language_id=language_id,
+ sync_kind=self._sync_kind
+ )
def add_folder(self, folder: WorkspaceFolder):
self._folders[folder.uri] = folder
@@ -372,7 +388,8 @@ class Workspace(object):
self._docs[doc_uri] = self._create_document(
doc_uri,
source=text_document.text,
- version=text_document.version
+ version=text_document.version,
+ language_id=text_document.language_id,
)
def remove_document(self, doc_uri: str):
| openlawlibrary/pygls | e99a07e741e8aed9c146209daf2271adaf826c7a | diff --git a/tests/test_language_server.py b/tests/test_language_server.py
index 9f48760..98be7cb 100644
--- a/tests/test_language_server.py
+++ b/tests/test_language_server.py
@@ -84,6 +84,12 @@ def test_bf_text_document_did_open(client_server):
assert len(server.lsp.workspace.documents) == 1
+ document = server.workspace.get_document(__file__)
+ assert document.uri == __file__
+ assert document.version == 1
+ assert document.source == "test"
+ assert document.language_id == "python"
+
@pytest.mark.skipif(IS_PYODIDE, reason='threads are not available in pyodide.')
def test_command_async(client_server):
| Missing language_id in "class Document"
I need to get language_id to identify source's kind. And there are so many LS need this too, such as [efm](https://github.com/mattn/efm-langserver).
pygls declared "TextDocumentItem" with lanuage_id in "pygls/lsp/types/basic_structures.py", but never use /store language_id.
```python
document = ls.workspace.get_document(params.text_document.uri)
document.source # √
document.language_id # ×
``` | 0.0 | [
"tests/test_language_server.py::test_bf_text_document_did_open"
] | [
"tests/test_language_server.py::test_bf_initialize",
"tests/test_language_server.py::test_command_async",
"tests/test_language_server.py::test_command_sync",
"tests/test_language_server.py::test_command_thread",
"tests/test_language_server.py::test_allow_custom_protocol_derived_from_lsp",
"tests/test_language_server.py::test_forbid_custom_protocol_not_derived_from_lsp"
] | 2022-07-08 23:58:40+00:00 | 4,408 |
|
openlawlibrary__pygls-303 | diff --git a/CHANGELOG.md b/CHANGELOG.md
index d49b73c..363a4c0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,11 +13,12 @@ and this project adheres to [Semantic Versioning][semver].
- Fix progress example in json extension. ([#230])
- Fix `AttributeErrors` in `get_configuration_async`, `get_configuration_callback`, `get_configuration_threaded` commands in json extension. ([#307])
- Fix type annotations for `get_configuration_async` and `get_configuration` methods on `LanguageServer` and `LanguageServerProtocol` objects ([#307])
+ - Provide `version` param for publishing diagnostics ([#303])
[#230]: https://github.com/openlawlibrary/pygls/issues/230
+[#303]: https://github.com/openlawlibrary/pygls/issues/303
[#307]: https://github.com/openlawlibrary/pygls/issues/307
-
## [1.0.0] - 2/12/2022
### Changed
BREAKING CHANGE: Replaced `pydantic` with [`lsprotocol`](https://github.com/microsoft/lsprotocol)
diff --git a/pygls/protocol.py b/pygls/protocol.py
index 4f0d012..5b2fcef 100644
--- a/pygls/protocol.py
+++ b/pygls/protocol.py
@@ -835,10 +835,71 @@ class LanguageServerProtocol(JsonRPCProtocol, metaclass=LSPMeta):
self.notify(LOG_TRACE, params)
- def publish_diagnostics(self, doc_uri: str, diagnostics: List[Diagnostic]) -> None:
- """Sends diagnostic notification to the client."""
- self.notify(TEXT_DOCUMENT_PUBLISH_DIAGNOSTICS,
- PublishDiagnosticsParams(uri=doc_uri, diagnostics=diagnostics))
+ def _publish_diagnostics_deprecator(
+ self,
+ params_or_uri: Union[str, PublishDiagnosticsParams],
+ diagnostics: Optional[List[Diagnostic]],
+ version: Optional[int],
+ **kwargs
+ ) -> PublishDiagnosticsParams:
+ if isinstance(params_or_uri, str):
+ message = "DEPRECATION: "
+ "`publish_diagnostics("
+ "self, doc_uri: str, diagnostics: List[Diagnostic], version: Optional[int] = None)`"
+ "will be replaced with `publish_diagnostics(self, params: PublishDiagnosticsParams)`"
+ logging.warning(message)
+
+ params = self._construct_publish_diagnostic_type(
+ params_or_uri,
+ diagnostics,
+ version,
+ **kwargs
+ )
+ else:
+ params = params_or_uri
+ return params
+
+ def _construct_publish_diagnostic_type(
+ self,
+ uri: str,
+ diagnostics: Optional[List[Diagnostic]],
+ version: Optional[int],
+ **kwargs
+ ) -> PublishDiagnosticsParams:
+ if diagnostics is None:
+ diagnostics = []
+
+ args = {
+ **{
+ "uri": uri,
+ "diagnostics": diagnostics,
+ "version": version
+ },
+ **kwargs
+ }
+
+ params = PublishDiagnosticsParams(**args) # type:ignore
+ return params
+
+ def publish_diagnostics(
+ self,
+ params_or_uri: Union[str, PublishDiagnosticsParams],
+ diagnostics: Optional[List[Diagnostic]] = None,
+ version: Optional[int] = None,
+ **kwargs
+ ):
+ """
+ Sends diagnostic notification to the client.
+ Deprecation:
+ `uri`, `diagnostics` and `version` fields will be deprecated
+ """
+ params = self._publish_diagnostics_deprecator(
+ params_or_uri,
+ diagnostics,
+ version,
+ **kwargs
+ )
+ self.notify(TEXT_DOCUMENT_PUBLISH_DIAGNOSTICS, params)
def register_capability(self, params: RegistrationParams,
callback: Optional[Callable[[], None]] = None) -> Future:
diff --git a/pygls/server.py b/pygls/server.py
index 9fd48ab..4fd6953 100644
--- a/pygls/server.py
+++ b/pygls/server.py
@@ -408,9 +408,23 @@ class LanguageServer(Server):
"""Gets the object to manage client's progress bar."""
return self.lsp.progress
- def publish_diagnostics(self, doc_uri: str, diagnostics: List[Diagnostic]):
- """Sends diagnostic notification to the client."""
- self.lsp.publish_diagnostics(doc_uri, diagnostics)
+ def publish_diagnostics(
+ self,
+ uri: str,
+ diagnostics: Optional[List[Diagnostic]] = None,
+ version: Optional[int] = None,
+ **kwargs
+ ):
+ """
+ Sends diagnostic notification to the client.
+ """
+ params = self.lsp._construct_publish_diagnostic_type(
+ uri,
+ diagnostics,
+ version,
+ **kwargs
+ )
+ self.lsp.publish_diagnostics(params, **kwargs)
def register_capability(self, params: RegistrationParams,
callback: Optional[Callable[[], None]] = None) -> Future:
| openlawlibrary/pygls | feff213f7484d2f15ed70da3eb2128f01a987916 | diff --git a/tests/lsp/test_diagnostics.py b/tests/lsp/test_diagnostics.py
new file mode 100644
index 0000000..a4d438a
--- /dev/null
+++ b/tests/lsp/test_diagnostics.py
@@ -0,0 +1,95 @@
+############################################################################
+# Copyright(c) Open Law Library. All rights reserved. #
+# See ThirdPartyNotices.txt in the project root for additional notices. #
+# #
+# Licensed under the Apache License, Version 2.0 (the "License") #
+# you may not use this file except in compliance with the License. #
+# You may obtain a copy of the License at #
+# #
+# http: // www.apache.org/licenses/LICENSE-2.0 #
+# #
+# Unless required by applicable law or agreed to in writing, software #
+# distributed under the License is distributed on an "AS IS" BASIS, #
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #
+# See the License for the specific language governing permissions and #
+# limitations under the License. #
+############################################################################
+
+from typing import List
+
+import time
+from lsprotocol.types import (
+ TEXT_DOCUMENT_PUBLISH_DIAGNOSTICS,
+ PublishDiagnosticsParams,
+ Diagnostic,
+ Range,
+ Position,
+)
+from ..conftest import ClientServer
+
+
+class ConfiguredLS(ClientServer):
+ def __init__(self):
+ super().__init__()
+ self.client.notifications: List[PublishDiagnosticsParams] = []
+
+ @self.client.feature(TEXT_DOCUMENT_PUBLISH_DIAGNOSTICS)
+ def f1(params: PublishDiagnosticsParams):
+ self.client.notifications.append(params)
+
+
[email protected]()
+def test_diagnostics_notifications(client_server):
+ client, server = client_server
+ diagnostic = Diagnostic(
+ range=Range(
+ start=Position(line=0, character=0),
+ end=Position(line=1, character=1),
+ ),
+ message="test diagnostic",
+ )
+ server.lsp.publish_diagnostics(
+ PublishDiagnosticsParams(uri="", diagnostics=[diagnostic], version=1),
+ )
+ server.lsp.publish_diagnostics(
+ "",
+ diagnostics=[diagnostic],
+ version=1,
+ )
+
+ time.sleep(0.1)
+
+ assert len(client.notifications) == 2
+ expected = PublishDiagnosticsParams(
+ uri="",
+ diagnostics=[diagnostic],
+ version=1,
+ )
+ assert client.notifications[0] == expected
+
+
[email protected]()
+def test_diagnostics_notifications_deprecated(client_server):
+ client, server = client_server
+ diagnostic = Diagnostic(
+ range=Range(
+ start=Position(line=0, character=0),
+ end=Position(line=1, character=1),
+ ),
+ message="test diagnostic",
+ )
+ server.publish_diagnostics(
+ "",
+ diagnostics=[diagnostic],
+ version=1,
+ )
+
+ time.sleep(0.1)
+
+ assert len(client.notifications) == 1
+ expected = PublishDiagnosticsParams(
+ uri="",
+ diagnostics=[diagnostic],
+ version=1,
+ )
+ assert client.notifications[0] == expected
| Add an optional version parameter to LanguageServerProtocol publish_diagnostics
- The LSP v15 added an optional version parameter to the publishDiagnostics notification.
- PublishDiagnosticsParams includes version but,
- LanguageServerProtocol.publish_diagnostics is not using version
Please make version an optional parameter of LanguageServerProtocol.publish_diagnostics so that Lsp Servers can implement this feature. | 0.0 | [
"tests/lsp/test_diagnostics.py::test_diagnostics_notifications[ConfiguredLS]",
"tests/lsp/test_diagnostics.py::test_diagnostics_notifications_deprecated[ConfiguredLS]"
] | [] | 2022-12-14 13:18:10+00:00 | 4,409 |
|
openlawlibrary__pygls-304 | diff --git a/CHANGELOG.md b/CHANGELOG.md
index 95ed61e..a1a037d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -15,6 +15,7 @@ and this project adheres to [Semantic Versioning][semver].
### Changed
### Fixed
+[#304]: https://github.com/openlawlibrary/pygls/issues/304
- `pygls` no longer overrides the event loop for the current thread when given an explicit loop to use. ([#334])
- Fixed `MethodTypeNotRegisteredError` when registering a `TEXT_DOCUMENT_DID_SAVE` feature with options. ([#338])
diff --git a/pygls/workspace.py b/pygls/workspace.py
index bfd5aa5..dad7343 100644
--- a/pygls/workspace.py
+++ b/pygls/workspace.py
@@ -37,13 +37,17 @@ RE_START_WORD = re.compile('[A-Za-z_0-9]*$')
log = logging.getLogger(__name__)
+def is_char_beyond_multilingual_plane(char: str) -> bool:
+ return ord(char) > 0xFFFF
+
+
def utf16_unit_offset(chars: str):
"""Calculate the number of characters which need two utf-16 code units.
Arguments:
chars (str): The string to count occurrences of utf-16 code units for.
"""
- return sum(ord(ch) > 0xFFFF for ch in chars)
+ return sum(is_char_beyond_multilingual_plane(ch) for ch in chars)
def utf16_num_units(chars: str):
@@ -59,7 +63,7 @@ def position_from_utf16(lines: List[str], position: Position) -> Position:
"""Convert the position.character from utf-16 code units to utf-32.
A python application can't use the character member of `Position`
- directly as per specification it is represented as a zero-based line and
+ directly. As per specification it is represented as a zero-based line and
character offset based on a UTF-16 string representation.
All characters whose code point exceeds the Basic Multilingual Plane are
@@ -80,14 +84,44 @@ def position_from_utf16(lines: List[str], position: Position) -> Position:
Returns:
The position with `character` being converted to utf-32 code units.
"""
- try:
- return Position(
- line=position.line,
- character=position.character
- - utf16_unit_offset(lines[position.line][:position.character])
+ if len(lines) == 0:
+ return Position(0, 0)
+ if position.line >= len(lines):
+ return Position(len(lines) - 1, utf16_num_units(lines[-1]))
+
+ _line = lines[position.line]
+ _line = _line.replace('\r\n', '\n') # TODO: it's a bit of a hack
+ _utf16_len = utf16_num_units(_line)
+ _utf32_len = len(_line)
+
+ if _utf16_len == 0:
+ return Position(position.line, 0)
+
+ _utf16_end_of_line = utf16_num_units(_line)
+ if position.character > _utf16_end_of_line:
+ position.character = _utf16_end_of_line - 1
+
+ _utf16_index = 0
+ utf32_index = 0
+ while True:
+ _is_searching_queried_position = _utf16_index < position.character
+ _is_before_end_of_line = utf32_index < _utf32_len
+ _is_searching_for_position = (
+ _is_searching_queried_position and _is_before_end_of_line
)
- except IndexError:
- return Position(line=len(lines), character=0)
+ if not _is_searching_for_position:
+ break
+
+ _current_char = _line[utf32_index]
+ _is_double_width = is_char_beyond_multilingual_plane(_current_char)
+ if _is_double_width:
+ _utf16_index += 2
+ else:
+ _utf16_index += 1
+ utf32_index += 1
+
+ position = Position(line=position.line, character=utf32_index)
+ return position
def position_to_utf16(lines: List[str], position: Position) -> Position:
@@ -137,10 +171,11 @@ def range_from_utf16(lines: List[str], range: Range) -> Range:
Returns:
The range with `character` offsets being converted to utf-16 code units.
"""
- return Range(
+ range_new = Range(
start=position_from_utf16(lines, range.start),
end=position_from_utf16(lines, range.end)
)
+ return range_new
def range_to_utf16(lines: List[str], range: Range) -> Range:
@@ -280,7 +315,7 @@ class Document(object):
lines = self.lines
pos = position_from_utf16(lines, position)
row, col = pos.line, pos.character
- return col + sum(len(line) for line in lines[:row])
+ return col + sum(utf16_num_units(line) for line in lines[:row])
@property
def source(self) -> str:
| openlawlibrary/pygls | 6139c71bb5b050a9be49ddcfdee356b54cbd55e6 | diff --git a/tests/test_document.py b/tests/test_document.py
index 5c3c36b..8b21ac2 100644
--- a/tests/test_document.py
+++ b/tests/test_document.py
@@ -220,10 +220,11 @@ def test_range_from_utf16():
range = Range(
start=Position(line=0, character=3), end=Position(line=0, character=5)
)
- range_from_utf16(['x="😋"'], range)
- assert range == Range(
- start=Position(line=0, character=3), end=Position(line=0, character=5)
+ actual = range_from_utf16(['x="😋😋"'], range)
+ expected = Range(
+ start=Position(line=0, character=3), end=Position(line=0, character=4)
)
+ assert actual == expected
def test_range_to_utf16():
@@ -239,23 +240,40 @@ def test_range_to_utf16():
range = Range(
start=Position(line=0, character=3), end=Position(line=0, character=4)
)
- range_to_utf16(['x="😋"'], range)
- assert range == Range(
- start=Position(line=0, character=3), end=Position(line=0, character=4)
+ actual = range_to_utf16(['x="😋😋"'], range)
+ expected = Range(
+ start=Position(line=0, character=3), end=Position(line=0, character=5)
)
+ assert actual == expected
def test_offset_at_position(doc):
assert doc.offset_at_position(Position(line=0, character=8)) == 8
- assert doc.offset_at_position(Position(line=1, character=5)) == 14
+ assert doc.offset_at_position(Position(line=1, character=5)) == 12
assert doc.offset_at_position(Position(line=2, character=0)) == 13
assert doc.offset_at_position(Position(line=2, character=4)) == 17
assert doc.offset_at_position(Position(line=3, character=6)) == 27
- assert doc.offset_at_position(Position(line=3, character=7)) == 27
+ assert doc.offset_at_position(Position(line=3, character=7)) == 28
assert doc.offset_at_position(Position(line=3, character=8)) == 28
- assert doc.offset_at_position(Position(line=4, character=0)) == 39
- assert doc.offset_at_position(Position(line=5, character=0)) == 39
-
+ assert doc.offset_at_position(Position(line=4, character=0)) == 40
+ assert doc.offset_at_position(Position(line=5, character=0)) == 40
+
+def test_utf16_to_utf32_position_cast(doc):
+ lines = ['', '😋😋', '']
+ assert position_from_utf16(lines, Position(line=0, character=0)) == Position(line=0, character=0)
+ assert position_from_utf16(lines, Position(line=0, character=1)) == Position(line=0, character=0)
+ assert position_from_utf16(lines, Position(line=1, character=0)) == Position(line=1, character=0)
+ assert position_from_utf16(lines, Position(line=1, character=2)) == Position(line=1, character=1)
+ assert position_from_utf16(lines, Position(line=1, character=3)) == Position(line=1, character=2)
+ assert position_from_utf16(lines, Position(line=1, character=4)) == Position(line=1, character=2)
+ assert position_from_utf16(lines, Position(line=1, character=100)) == Position(line=1, character=2)
+ assert position_from_utf16(lines, Position(line=3, character=0)) == Position(line=2, character=0)
+ assert position_from_utf16(lines, Position(line=4, character=10)) == Position(line=2, character=0)
+
+def test_position_for_line_endings(doc):
+ lines = ['x\r\n', 'y\n']
+ assert position_from_utf16(lines, Position(line=0, character=10)) == Position(line=0, character=1)
+ assert position_from_utf16(lines, Position(line=1, character=10)) == Position(line=1, character=1)
def test_word_at_position(doc):
"""
| position_from_utf16 in workspace.py may return incorrect result.
The following code that mimics the way position_from_utf16 calculates the result, demonstrates the issue:
```python
def utf16_unit_offset(chars: str):
"""Calculate the number of characters which need two utf-16 code units.
Arguments:
chars (str): The string to count occurrences of utf-16 code units for.
"""
return sum(ord(ch) > 0xFFFF for ch in chars)
s = '😋😋'
def position_from_utf16(line, pos):
return pos - utf16_unit_offset(line[:pos])
print(position_from_utf16(s, 2))
```
The result is zero, but it should be one.
Although, this may not have a large real-world impact (you don't get many high-plane chars in python code), it would be nice to have a correct calculation.
| 0.0 | [
"tests/test_document.py::test_range_from_utf16",
"tests/test_document.py::test_offset_at_position",
"tests/test_document.py::test_utf16_to_utf32_position_cast",
"tests/test_document.py::test_position_for_line_endings"
] | [
"tests/test_document.py::test_document_empty_edit",
"tests/test_document.py::test_document_end_of_file_edit",
"tests/test_document.py::test_document_full_edit",
"tests/test_document.py::test_document_line_edit",
"tests/test_document.py::test_document_lines",
"tests/test_document.py::test_document_multiline_edit",
"tests/test_document.py::test_document_no_edit",
"tests/test_document.py::test_document_props",
"tests/test_document.py::test_document_source_unicode",
"tests/test_document.py::test_position_from_utf16",
"tests/test_document.py::test_position_to_utf16",
"tests/test_document.py::test_range_to_utf16",
"tests/test_document.py::test_word_at_position"
] | 2022-12-14 19:16:06+00:00 | 4,410 |
|
openlawlibrary__pygls-383 | diff --git a/pygls/workspace/__init__.py b/pygls/workspace/__init__.py
index afa2590..4880ef4 100644
--- a/pygls/workspace/__init__.py
+++ b/pygls/workspace/__init__.py
@@ -5,11 +5,11 @@ from lsprotocol import types
from .workspace import Workspace
from .text_document import TextDocument
-from .position import Position
+from .position_codec import PositionCodec
Workspace = Workspace
TextDocument = TextDocument
-Position = Position
+PositionCodec = PositionCodec
# For backwards compatibility
Document = TextDocument
@@ -17,65 +17,71 @@ Document = TextDocument
def utf16_unit_offset(chars: str):
warnings.warn(
- "'utf16_unit_offset' has been deprecated, use "
- "'Position.utf16_unit_offset' instead",
+ "'utf16_unit_offset' has been deprecated, instead use "
+ "'PositionCodec.utf16_unit_offset' via 'workspace.position_codec' "
+ "or 'text_document.position_codec'",
DeprecationWarning,
stacklevel=2,
)
- _position = Position()
- return _position.utf16_unit_offset(chars)
+ _codec = PositionCodec()
+ return _codec.utf16_unit_offset(chars)
def utf16_num_units(chars: str):
warnings.warn(
- "'utf16_num_units' has been deprecated, use "
- "'Position.client_num_units' instead",
+ "'utf16_num_units' has been deprecated, instead use "
+ "'PositionCodec.client_num_units' via 'workspace.position_codec' "
+ "or 'text_document.position_codec'",
DeprecationWarning,
stacklevel=2,
)
- _position = Position()
- return _position.client_num_units(chars)
+ _codec = PositionCodec()
+ return _codec.client_num_units(chars)
def position_from_utf16(lines: List[str], position: types.Position):
warnings.warn(
- "'position_from_utf16' has been deprecated, use "
- "'Position.position_from_client_units' instead",
+ "'position_from_utf16' has been deprecated, instead use "
+ "'PositionCodec.position_from_client_units' via "
+ "'workspace.position_codec' or 'text_document.position_codec'",
DeprecationWarning,
stacklevel=2,
)
- _position = Position()
- return _position.position_from_client_units(lines, position)
+ _codec = PositionCodec()
+ return _codec.position_from_client_units(lines, position)
def position_to_utf16(lines: List[str], position: types.Position):
warnings.warn(
- "'position_to_utf16' has been deprecated, use "
- "'Position.position_to_client_units' instead",
+ "'position_to_utf16' has been deprecated, instead use "
+ "'PositionCodec.position_to_client_units' via "
+ "'workspace.position_codec' or 'text_document.position_codec'",
DeprecationWarning,
stacklevel=2,
)
- _position = Position()
- return _position.position_to_client_units(lines, position)
+ _codec = PositionCodec()
+ return _codec.position_to_client_units(lines, position)
def range_from_utf16(lines: List[str], range: types.Range):
warnings.warn(
- "'range_from_utf16' has been deprecated, use "
- "'Position.range_from_client_units' instead",
+ "'range_from_utf16' has been deprecated, instead use "
+ "'PositionCodec.range_from_client_units' via "
+ "'workspace.position_codec' or 'text_document.position_codec'",
DeprecationWarning,
stacklevel=2,
)
- _position = Position()
- return _position.range_from_client_units(lines, range)
+ _codec = PositionCodec()
+ return _codec.range_from_client_units(lines, range)
def range_to_utf16(lines: List[str], range: types.Range):
warnings.warn(
- "'range_to_utf16' has been deprecated, use "
- "'Position.range_to_client_units' instead",
+ "'range_to_utf16' has been deprecated, instead use "
+ "'PositionCodec.range_to_client_units' via 'workspace.position_codec' "
+ "or 'text_document.position_codec'",
DeprecationWarning,
stacklevel=2,
)
- _position = Position()
- return _position.range_to_client_units(lines, range)
+ _codec = PositionCodec()
+ return _codec.range_to_client_units(lines, range)
diff --git a/pygls/workspace/position.py b/pygls/workspace/position_codec.py
similarity index 98%
rename from pygls/workspace/position.py
rename to pygls/workspace/position_codec.py
index 0f4616d..8189cfb 100644
--- a/pygls/workspace/position.py
+++ b/pygls/workspace/position_codec.py
@@ -25,7 +25,7 @@ from lsprotocol import types
log = logging.getLogger(__name__)
-class Position:
+class PositionCodec:
def __init__(
self,
encoding: Optional[
@@ -121,7 +121,9 @@ class Position:
break
_current_char = _line[utf32_index]
- _is_double_width = Position.is_char_beyond_multilingual_plane(_current_char)
+ _is_double_width = PositionCodec.is_char_beyond_multilingual_plane(
+ _current_char
+ )
if _is_double_width:
if self.encoding == types.PositionEncodingKind.Utf32:
_client_index += 1
diff --git a/pygls/workspace/text_document.py b/pygls/workspace/text_document.py
index 27b300a..d62c6aa 100644
--- a/pygls/workspace/text_document.py
+++ b/pygls/workspace/text_document.py
@@ -20,12 +20,12 @@ import io
import logging
import os
import re
-from typing import List, Optional, Pattern, Union
+from typing import List, Optional, Pattern
from lsprotocol import types
from pygls.uris import to_fs_path
-from .position import Position
+from .position_codec import PositionCodec
# TODO: this is not the best e.g. we capture numbers
RE_END_WORD = re.compile("^[A-Za-z_0-9]*")
@@ -43,9 +43,7 @@ class TextDocument(object):
language_id: Optional[str] = None,
local: bool = True,
sync_kind: types.TextDocumentSyncKind = types.TextDocumentSyncKind.Incremental,
- position_encoding: Optional[
- Union[types.PositionEncodingKind, str]
- ] = types.PositionEncodingKind.Utf16,
+ position_codec: Optional[PositionCodec] = None,
):
self.uri = uri
self.version = version
@@ -65,11 +63,15 @@ class TextDocument(object):
)
self._is_sync_kind_none = sync_kind == types.TextDocumentSyncKind.None_
- self.position = Position(encoding=position_encoding)
+ self._position_codec = position_codec if position_codec else PositionCodec()
def __str__(self):
return str(self.uri)
+ @property
+ def position_codec(self) -> PositionCodec:
+ return self._position_codec
+
def _apply_incremental_change(
self, change: types.TextDocumentContentChangeEvent_Type1
) -> None:
@@ -78,7 +80,7 @@ class TextDocument(object):
text = change.text
change_range = change.range
- range = self.position.range_from_client_units(lines, change_range)
+ range = self._position_codec.range_from_client_units(lines, change_range)
start_line = range.start.line
start_col = range.start.character
end_line = range.end.line
@@ -165,11 +167,13 @@ class TextDocument(object):
def offset_at_position(self, client_position: types.Position) -> int:
"""Return the character offset pointed at by the given client_position."""
lines = self.lines
- server_position = self.position.position_from_client_units(
+ server_position = self._position_codec.position_from_client_units(
lines, client_position
)
row, col = server_position.line, server_position.character
- return col + sum(self.position.client_num_units(line) for line in lines[:row])
+ return col + sum(
+ self._position_codec.client_num_units(line) for line in lines[:row]
+ )
@property
def source(self) -> str:
@@ -217,7 +221,7 @@ class TextDocument(object):
if client_position.line >= len(lines):
return ""
- server_position = self.position.position_from_client_units(
+ server_position = self._position_codec.position_from_client_units(
lines, client_position
)
row, col = server_position.line, server_position.character
diff --git a/pygls/workspace/workspace.py b/pygls/workspace/workspace.py
index 1ae2528..746c1ba 100644
--- a/pygls/workspace/workspace.py
+++ b/pygls/workspace/workspace.py
@@ -30,6 +30,7 @@ from lsprotocol.types import (
)
from pygls.uris import to_fs_path, uri_scheme
from pygls.workspace.text_document import TextDocument
+from pygls.workspace.position_codec import PositionCodec
logger = logging.getLogger(__name__)
@@ -60,11 +61,20 @@ class Workspace(object):
self._folders: Dict[str, WorkspaceFolder] = {}
self._docs: Dict[str, TextDocument] = {}
self._position_encoding = position_encoding
+ self._position_codec = PositionCodec(encoding=position_encoding)
if workspace_folders is not None:
for folder in workspace_folders:
self.add_folder(folder)
+ @property
+ def position_encoding(self) -> Optional[Union[PositionEncodingKind, str]]:
+ return self._position_encoding
+
+ @property
+ def position_codec(self) -> PositionCodec:
+ return self._position_codec
+
def _create_text_document(
self,
doc_uri: str,
@@ -78,7 +88,7 @@ class Workspace(object):
version=version,
language_id=language_id,
sync_kind=self._sync_kind,
- position_encoding=self._position_encoding,
+ position_codec=self._position_codec,
)
def add_folder(self, folder: WorkspaceFolder):
| openlawlibrary/pygls | fa00721e092aa87520e593ff4b73a9234ad97f71 | diff --git a/tests/test_document.py b/tests/test_document.py
index 859f508..f071a2f 100644
--- a/tests/test_document.py
+++ b/tests/test_document.py
@@ -19,7 +19,7 @@
import re
from lsprotocol import types
-from pygls.workspace import TextDocument, Position
+from pygls.workspace import TextDocument, PositionCodec
from .conftest import DOC, DOC_URI
@@ -174,71 +174,71 @@ def test_document_source_unicode():
def test_position_from_utf16():
- position = Position(encoding=types.PositionEncodingKind.Utf16)
- assert position.position_from_client_units(
+ codec = PositionCodec(encoding=types.PositionEncodingKind.Utf16)
+ assert codec.position_from_client_units(
['x="😋"'], types.Position(line=0, character=3)
) == types.Position(line=0, character=3)
- assert position.position_from_client_units(
+ assert codec.position_from_client_units(
['x="😋"'], types.Position(line=0, character=5)
) == types.Position(line=0, character=4)
def test_position_from_utf32():
- position = Position(encoding=types.PositionEncodingKind.Utf32)
- assert position.position_from_client_units(
+ codec = PositionCodec(encoding=types.PositionEncodingKind.Utf32)
+ assert codec.position_from_client_units(
['x="😋"'], types.Position(line=0, character=3)
) == types.Position(line=0, character=3)
- assert position.position_from_client_units(
+ assert codec.position_from_client_units(
['x="😋"'], types.Position(line=0, character=4)
) == types.Position(line=0, character=4)
def test_position_from_utf8():
- position = Position(encoding=types.PositionEncodingKind.Utf8)
- assert position.position_from_client_units(
+ codec = PositionCodec(encoding=types.PositionEncodingKind.Utf8)
+ assert codec.position_from_client_units(
['x="😋"'], types.Position(line=0, character=3)
) == types.Position(line=0, character=3)
- assert position.position_from_client_units(
+ assert codec.position_from_client_units(
['x="😋"'], types.Position(line=0, character=7)
) == types.Position(line=0, character=4)
def test_position_to_utf16():
- position = Position(encoding=types.PositionEncodingKind.Utf16)
- assert position.position_to_client_units(
+ codec = PositionCodec(encoding=types.PositionEncodingKind.Utf16)
+ assert codec.position_to_client_units(
['x="😋"'], types.Position(line=0, character=3)
) == types.Position(line=0, character=3)
- assert position.position_to_client_units(
+ assert codec.position_to_client_units(
['x="😋"'], types.Position(line=0, character=4)
) == types.Position(line=0, character=5)
def test_position_to_utf32():
- position = Position(encoding=types.PositionEncodingKind.Utf32)
- assert position.position_to_client_units(
+ codec = PositionCodec(encoding=types.PositionEncodingKind.Utf32)
+ assert codec.position_to_client_units(
['x="😋"'], types.Position(line=0, character=3)
) == types.Position(line=0, character=3)
- assert position.position_to_client_units(
+ assert codec.position_to_client_units(
['x="😋"'], types.Position(line=0, character=4)
) == types.Position(line=0, character=4)
def test_position_to_utf8():
- position = Position(encoding=types.PositionEncodingKind.Utf8)
- assert position.position_to_client_units(
+ codec = PositionCodec(encoding=types.PositionEncodingKind.Utf8)
+ assert codec.position_to_client_units(
['x="😋"'], types.Position(line=0, character=3)
) == types.Position(line=0, character=3)
- assert position.position_to_client_units(
+ assert codec.position_to_client_units(
['x="😋"'], types.Position(line=0, character=4)
) == types.Position(line=0, character=6)
def test_range_from_utf16():
- position = Position(encoding=types.PositionEncodingKind.Utf16)
- assert position.range_from_client_units(
+ codec = PositionCodec(encoding=types.PositionEncodingKind.Utf16)
+ assert codec.range_from_client_units(
['x="😋"'],
types.Range(
start=types.Position(line=0, character=3),
@@ -253,7 +253,7 @@ def test_range_from_utf16():
start=types.Position(line=0, character=3),
end=types.Position(line=0, character=5),
)
- actual = position.range_from_client_units(['x="😋😋"'], range)
+ actual = codec.range_from_client_units(['x="😋😋"'], range)
expected = types.Range(
start=types.Position(line=0, character=3),
end=types.Position(line=0, character=4),
@@ -262,8 +262,8 @@ def test_range_from_utf16():
def test_range_to_utf16():
- position = Position(encoding=types.PositionEncodingKind.Utf16)
- assert position.range_to_client_units(
+ codec = PositionCodec(encoding=types.PositionEncodingKind.Utf16)
+ assert codec.range_to_client_units(
['x="😋"'],
types.Range(
start=types.Position(line=0, character=3),
@@ -278,7 +278,7 @@ def test_range_to_utf16():
start=types.Position(line=0, character=3),
end=types.Position(line=0, character=4),
)
- actual = position.range_to_client_units(['x="😋😋"'], range)
+ actual = codec.range_to_client_units(['x="😋😋"'], range)
expected = types.Range(
start=types.Position(line=0, character=3),
end=types.Position(line=0, character=5),
@@ -300,56 +300,64 @@ def test_offset_at_position_utf16():
def test_offset_at_position_utf32():
- doc = TextDocument(DOC_URI, DOC, position_encoding=types.PositionEncodingKind.Utf32)
+ doc = TextDocument(
+ DOC_URI,
+ DOC,
+ position_codec=PositionCodec(encoding=types.PositionEncodingKind.Utf32),
+ )
assert doc.offset_at_position(types.Position(line=0, character=8)) == 8
assert doc.offset_at_position(types.Position(line=5, character=0)) == 39
def test_offset_at_position_utf8():
- doc = TextDocument(DOC_URI, DOC, position_encoding=types.PositionEncodingKind.Utf8)
+ doc = TextDocument(
+ DOC_URI,
+ DOC,
+ position_codec=PositionCodec(encoding=types.PositionEncodingKind.Utf8),
+ )
assert doc.offset_at_position(types.Position(line=0, character=8)) == 8
assert doc.offset_at_position(types.Position(line=5, character=0)) == 41
def test_utf16_to_utf32_position_cast():
- position = Position(encoding=types.PositionEncodingKind.Utf16)
+ codec = PositionCodec(encoding=types.PositionEncodingKind.Utf16)
lines = ["", "😋😋", ""]
- assert position.position_from_client_units(
+ assert codec.position_from_client_units(
lines, types.Position(line=0, character=0)
) == types.Position(line=0, character=0)
- assert position.position_from_client_units(
+ assert codec.position_from_client_units(
lines, types.Position(line=0, character=1)
) == types.Position(line=0, character=0)
- assert position.position_from_client_units(
+ assert codec.position_from_client_units(
lines, types.Position(line=1, character=0)
) == types.Position(line=1, character=0)
- assert position.position_from_client_units(
+ assert codec.position_from_client_units(
lines, types.Position(line=1, character=2)
) == types.Position(line=1, character=1)
- assert position.position_from_client_units(
+ assert codec.position_from_client_units(
lines, types.Position(line=1, character=3)
) == types.Position(line=1, character=2)
- assert position.position_from_client_units(
+ assert codec.position_from_client_units(
lines, types.Position(line=1, character=4)
) == types.Position(line=1, character=2)
- assert position.position_from_client_units(
+ assert codec.position_from_client_units(
lines, types.Position(line=1, character=100)
) == types.Position(line=1, character=2)
- assert position.position_from_client_units(
+ assert codec.position_from_client_units(
lines, types.Position(line=3, character=0)
) == types.Position(line=2, character=0)
- assert position.position_from_client_units(
+ assert codec.position_from_client_units(
lines, types.Position(line=4, character=10)
) == types.Position(line=2, character=0)
def test_position_for_line_endings():
- position = Position(encoding=types.PositionEncodingKind.Utf16)
+ codec = PositionCodec(encoding=types.PositionEncodingKind.Utf16)
lines = ["x\r\n", "y\n"]
- assert position.position_from_client_units(
+ assert codec.position_from_client_units(
lines, types.Position(line=0, character=10)
) == types.Position(line=0, character=1)
- assert position.position_from_client_units(
+ assert codec.position_from_client_units(
lines, types.Position(line=1, character=10)
) == types.Position(line=1, character=1)
| Poor experience with recent "Position" changes
I have just been bitten hard by recent changes and I'd like to offer a critique and suggest some improvements:
The problem that I hit is that up until now I have been using `utf16_num_units` to convert between python string indexes and client position units (I am doing operational-transform like processing on document changes, so need this low level capability). With recent updates, I get the following error:
```
DeprecationWarning: 'utf16_num_units' has been deprecated, use 'Position.client_num_units' instead
```
I think I understand the intent of the message, but here are some of the problems that I encountered:
- `Position` up until now has meant `lsprotocol.types.Position`. After a thorough search, I find `lsprotocol.types.Position` has no `client_num_units` method, nor has such a method been monkey patched into the class. So the deprecation message is confusing.
- Then I started looking at recent commits and discover that a second (!) `Position` class has been added: `pygls.workspace.position.Position`. Introducing a type name collision on such a fundamental domain entity seems crazy to me.
- To make matters even more confusing, `pygls.workspace.position.Position` does not actually model *positions* it models *encoding-specific position translation*, so a better name might be `PositionTranslator` or `PositionCodec`
- Now, the deprecation warning says "use `Position.client_num_units` instead" but `pygls.workspace.position.Position.client_num_units` is not a class method -- you can't use that function directly, you need to find an instance of it (where?). I guessed at `workspace.position` but it is not there. Later I found `text_document.position`
So, my suggestions are:
- Rename `pygls.workspace.position.Position` to `pygls.workspace.position_codec.PositionCodec` or maybe `PositionTranslator`
- store an instance of `PositionCodec` in the `Workspace` and `TextDocument` instances, so that `workspace.position_codec` and `text_document.position_codec` can be easily used. I would understand if you decided against adding the `workspace` field but really, there needs to be only a single codec for the entire workspace, it doesn't need to be instantiated on a per-text-document basis.
- Fix the DeprecationWarnings in a way that makes them accurate and helpful, for example:
```
DeprecationWarning: 'utf16_num_units' has been deprecated, use 'text_document.position_codec.client_num_units' instead
```
| 0.0 | [
"tests/test_document.py::test_document_empty_edit",
"tests/test_document.py::test_document_end_of_file_edit",
"tests/test_document.py::test_document_full_edit",
"tests/test_document.py::test_document_line_edit",
"tests/test_document.py::test_document_lines",
"tests/test_document.py::test_document_multiline_edit",
"tests/test_document.py::test_document_no_edit",
"tests/test_document.py::test_document_props",
"tests/test_document.py::test_document_source_unicode",
"tests/test_document.py::test_position_from_utf16",
"tests/test_document.py::test_position_from_utf32",
"tests/test_document.py::test_position_from_utf8",
"tests/test_document.py::test_position_to_utf16",
"tests/test_document.py::test_position_to_utf32",
"tests/test_document.py::test_position_to_utf8",
"tests/test_document.py::test_range_from_utf16",
"tests/test_document.py::test_range_to_utf16",
"tests/test_document.py::test_offset_at_position_utf16",
"tests/test_document.py::test_offset_at_position_utf32",
"tests/test_document.py::test_offset_at_position_utf8",
"tests/test_document.py::test_utf16_to_utf32_position_cast",
"tests/test_document.py::test_position_for_line_endings",
"tests/test_document.py::test_word_at_position"
] | [] | 2023-09-29 08:56:57+00:00 | 4,411 |
|
openmc-dev__openmc-2252 | diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 050c8e287..b7c548a37 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -34,9 +34,6 @@ jobs:
vectfit: [n]
include:
- - python-version: 3.6
- omp: n
- mpi: n
- python-version: 3.7
omp: n
mpi: n
diff --git a/docs/source/devguide/styleguide.rst b/docs/source/devguide/styleguide.rst
index 44d80915e..2a744b819 100644
--- a/docs/source/devguide/styleguide.rst
+++ b/docs/source/devguide/styleguide.rst
@@ -142,7 +142,7 @@ Style for Python code should follow PEP8_.
Docstrings for functions and methods should follow numpydoc_ style.
-Python code should work with Python 3.6+.
+Python code should work with Python 3.7+.
Use of third-party Python packages should be limited to numpy_, scipy_,
matplotlib_, pandas_, and h5py_. Use of other third-party packages must be
diff --git a/docs/source/usersguide/install.rst b/docs/source/usersguide/install.rst
index b57958814..74be9ba0b 100644
--- a/docs/source/usersguide/install.rst
+++ b/docs/source/usersguide/install.rst
@@ -511,7 +511,7 @@ to install the Python package in :ref:`"editable" mode <devguide_editable>`.
Prerequisites
-------------
-The Python API works with Python 3.6+. In addition to Python itself, the API
+The Python API works with Python 3.7+. In addition to Python itself, the API
relies on a number of third-party packages. All prerequisites can be installed
using Conda_ (recommended), pip_, or through the package manager in most Linux
distributions.
diff --git a/openmc/data/decay.py b/openmc/data/decay.py
index d7ededf33..801ef4410 100644
--- a/openmc/data/decay.py
+++ b/openmc/data/decay.py
@@ -1,10 +1,9 @@
from collections.abc import Iterable
from io import StringIO
from math import log
-from pathlib import Path
import re
+from typing import Optional
from warnings import warn
-from xml.etree import ElementTree as ET
import numpy as np
from uncertainties import ufloat, UFloat
@@ -579,7 +578,7 @@ class Decay(EqualityMixin):
_DECAY_PHOTON_ENERGY = {}
-def decay_photon_energy(nuclide: str) -> Univariate:
+def decay_photon_energy(nuclide: str) -> Optional[Univariate]:
"""Get photon energy distribution resulting from the decay of a nuclide
This function relies on data stored in a depletion chain. Before calling it
@@ -595,9 +594,10 @@ def decay_photon_energy(nuclide: str) -> Univariate:
Returns
-------
- openmc.stats.Univariate
- Distribution of energies in [eV] of photons emitted from decay. Note
- that the probabilities represent intensities, given as [decay/sec].
+ openmc.stats.Univariate or None
+ Distribution of energies in [eV] of photons emitted from decay, or None
+ if no photon source exists. Note that the probabilities represent
+ intensities, given as [decay/sec].
"""
if not _DECAY_PHOTON_ENERGY:
chain_file = openmc.config.get('chain_file')
diff --git a/openmc/material.py b/openmc/material.py
index 16b5a3048..e99eec52c 100644
--- a/openmc/material.py
+++ b/openmc/material.py
@@ -92,10 +92,11 @@ class Material(IDManagerMixin):
fissionable_mass : float
Mass of fissionable nuclides in the material in [g]. Requires that the
:attr:`volume` attribute is set.
- decay_photon_energy : openmc.stats.Univariate
+ decay_photon_energy : openmc.stats.Univariate or None
Energy distribution of photons emitted from decay of unstable nuclides
- within the material. The integral of this distribution is the total
- intensity of the photon source in [decay/sec].
+ within the material, or None if no photon source exists. The integral of
+ this distribution is the total intensity of the photon source in
+ [decay/sec].
.. versionadded:: 0.14.0
@@ -264,7 +265,7 @@ class Material(IDManagerMixin):
return density*self.volume
@property
- def decay_photon_energy(self) -> Univariate:
+ def decay_photon_energy(self) -> Optional[Univariate]:
atoms = self.get_nuclide_atoms()
dists = []
probs = []
@@ -273,7 +274,7 @@ class Material(IDManagerMixin):
if source_per_atom is not None:
dists.append(source_per_atom)
probs.append(num_atoms)
- return openmc.data.combine_distributions(dists, probs)
+ return openmc.data.combine_distributions(dists, probs) if dists else None
@classmethod
def from_hdf5(cls, group: h5py.Group):
diff --git a/openmc/mesh.py b/openmc/mesh.py
index a4c50a608..d4db5011b 100644
--- a/openmc/mesh.py
+++ b/openmc/mesh.py
@@ -514,7 +514,7 @@ class RegularMesh(StructuredMesh):
def from_domain(
cls,
domain,
- dimension=[100, 100, 100],
+ dimension=(10, 10, 10),
mesh_id=None,
name=''
):
@@ -1137,6 +1137,76 @@ class CylindricalMesh(StructuredMesh):
return mesh
+ @classmethod
+ def from_domain(
+ cls,
+ domain,
+ dimension=(10, 10, 10),
+ mesh_id=None,
+ phi_grid_bounds=(0.0, 2*pi),
+ name=''
+ ):
+ """Creates a regular CylindricalMesh from an existing openmc domain.
+
+ Parameters
+ ----------
+ domain : openmc.Cell or openmc.Region or openmc.Universe or openmc.Geometry
+ The object passed in will be used as a template for this mesh. The
+ bounding box of the property of the object passed will be used to
+ set the r_grid, z_grid ranges.
+ dimension : Iterable of int
+ The number of equally spaced mesh cells in each direction (r_grid,
+ phi_grid, z_grid)
+ mesh_id : int
+ Unique identifier for the mesh
+ phi_grid_bounds : numpy.ndarray
+ Mesh bounds points along the phi-axis in radians. The default value
+ is (0, 2π), i.e., the full phi range.
+ name : str
+ Name of the mesh
+
+ Returns
+ -------
+ openmc.RegularMesh
+ RegularMesh instance
+
+ """
+ cv.check_type(
+ "domain",
+ domain,
+ (openmc.Cell, openmc.Region, openmc.Universe, openmc.Geometry),
+ )
+
+ mesh = cls(mesh_id, name)
+
+ # loaded once to avoid reading h5m file repeatedly
+ cached_bb = domain.bounding_box
+ max_bounding_box_radius = max(
+ [
+ cached_bb[0][0],
+ cached_bb[0][1],
+ cached_bb[1][0],
+ cached_bb[1][1],
+ ]
+ )
+ mesh.r_grid = np.linspace(
+ 0,
+ max_bounding_box_radius,
+ num=dimension[0]+1
+ )
+ mesh.phi_grid = np.linspace(
+ phi_grid_bounds[0],
+ phi_grid_bounds[1],
+ num=dimension[1]+1
+ )
+ mesh.z_grid = np.linspace(
+ cached_bb[0][2],
+ cached_bb[1][2],
+ num=dimension[2]+1
+ )
+
+ return mesh
+
def to_xml_element(self):
"""Return XML representation of the mesh
diff --git a/setup.py b/setup.py
index 477f29dec..a4b77e68b 100755
--- a/setup.py
+++ b/setup.py
@@ -5,11 +5,7 @@ import sys
import numpy as np
from setuptools import setup, find_packages
-try:
- from Cython.Build import cythonize
- have_cython = True
-except ImportError:
- have_cython = False
+from Cython.Build import cythonize
# Determine shared library suffix
@@ -57,14 +53,14 @@ kwargs = {
'Topic :: Scientific/Engineering'
'Programming Language :: C++',
'Programming Language :: Python :: 3',
- 'Programming Language :: Python :: 3.6',
+ 'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
],
# Dependencies
- 'python_requires': '>=3.6',
+ 'python_requires': '>=3.7',
'install_requires': [
'numpy>=1.9', 'h5py', 'scipy', 'ipython', 'matplotlib',
'pandas', 'lxml', 'uncertainties'
@@ -76,13 +72,9 @@ kwargs = {
'test': ['pytest', 'pytest-cov', 'colorama'],
'vtk': ['vtk'],
},
+ # Cython is used to add resonance reconstruction and fast float_endf
+ 'ext_modules': cythonize('openmc/data/*.pyx'),
+ 'include_dirs': [np.get_include()]
}
-# If Cython is present, add resonance reconstruction and fast float_endf
-if have_cython:
- kwargs.update({
- 'ext_modules': cythonize('openmc/data/*.pyx'),
- 'include_dirs': [np.get_include()]
- })
-
setup(**kwargs)
| openmc-dev/openmc | 9a86c9c065e545a7ece086c34dc7dca38cfa9892 | diff --git a/tests/unit_tests/test_material.py b/tests/unit_tests/test_material.py
index 58df246dd..80935d68d 100644
--- a/tests/unit_tests/test_material.py
+++ b/tests/unit_tests/test_material.py
@@ -573,3 +573,9 @@ def test_decay_photon_energy():
assert src.integral() == pytest.approx(sum(
intensity(decay_photon_energy(nuc)) for nuc in m.get_nuclides()
))
+
+ # A material with no unstable nuclides should have no decay photon source
+ stable = openmc.Material()
+ stable.add_nuclide('Gd156', 1.0)
+ stable.volume = 1.0
+ assert stable.decay_photon_energy is None
diff --git a/tests/unit_tests/test_mesh_from_domain.py b/tests/unit_tests/test_mesh_from_domain.py
index ce27288ad..b4edae196 100644
--- a/tests/unit_tests/test_mesh_from_domain.py
+++ b/tests/unit_tests/test_mesh_from_domain.py
@@ -16,6 +16,22 @@ def test_reg_mesh_from_cell():
assert np.array_equal(mesh.upper_right, cell.bounding_box[1])
+def test_cylindrical_mesh_from_cell():
+ """Tests a CylindricalMesh can be made from a Cell and the specified
+ dimensions are propagated through. Cell is not centralized"""
+ cy_surface = openmc.ZCylinder(r=50)
+ z_surface_1 = openmc.ZPlane(z0=30)
+ z_surface_2 = openmc.ZPlane(z0=0)
+ cell = openmc.Cell(region=-cy_surface & -z_surface_1 & +z_surface_2)
+ mesh = openmc.CylindricalMesh.from_domain(cell, dimension=[2, 4, 3])
+
+ assert isinstance(mesh, openmc.CylindricalMesh)
+ assert np.array_equal(mesh.dimension, (2, 4, 3))
+ assert np.array_equal(mesh.r_grid, [0., 25., 50.])
+ assert np.array_equal(mesh.phi_grid, [0., 0.5*np.pi, np.pi, 1.5*np.pi, 2.*np.pi])
+ assert np.array_equal(mesh.z_grid, [0., 10., 20., 30.])
+
+
def test_reg_mesh_from_region():
"""Tests a RegularMesh can be made from a Region and the default dimensions
are propagated through. Region is not centralized"""
@@ -24,28 +40,48 @@ def test_reg_mesh_from_region():
mesh = openmc.RegularMesh.from_domain(region)
assert isinstance(mesh, openmc.RegularMesh)
- assert np.array_equal(mesh.dimension, (100, 100, 100)) # default values
+ assert np.array_equal(mesh.dimension, (10, 10, 10)) # default values
assert np.array_equal(mesh.lower_left, region.bounding_box[0])
assert np.array_equal(mesh.upper_right, region.bounding_box[1])
+def test_cylindrical_mesh_from_region():
+ """Tests a CylindricalMesh can be made from a Region and the specified
+ dimensions and phi_grid_bounds are propagated through. Cell is centralized"""
+ cy_surface = openmc.ZCylinder(r=6)
+ z_surface_1 = openmc.ZPlane(z0=30)
+ z_surface_2 = openmc.ZPlane(z0=-30)
+ cell = openmc.Cell(region=-cy_surface & -z_surface_1 & +z_surface_2)
+ mesh = openmc.CylindricalMesh.from_domain(
+ cell,
+ dimension=(6, 2, 3),
+ phi_grid_bounds=(0., np.pi)
+ )
+
+ assert isinstance(mesh, openmc.CylindricalMesh)
+ assert np.array_equal(mesh.dimension, (6, 2, 3))
+ assert np.array_equal(mesh.r_grid, [0., 1., 2., 3., 4., 5., 6.])
+ assert np.array_equal(mesh.phi_grid, [0., 0.5*np.pi, np.pi])
+ assert np.array_equal(mesh.z_grid, [-30., -10., 10., 30.])
+
+
def test_reg_mesh_from_universe():
- """Tests a RegularMesh can be made from a Universe and the default dimensions
- are propagated through. Universe is centralized"""
+ """Tests a RegularMesh can be made from a Universe and the default
+ dimensions are propagated through. Universe is centralized"""
surface = openmc.Sphere(r=42)
cell = openmc.Cell(region=-surface)
universe = openmc.Universe(cells=[cell])
mesh = openmc.RegularMesh.from_domain(universe)
assert isinstance(mesh, openmc.RegularMesh)
- assert np.array_equal(mesh.dimension, (100, 100, 100)) # default values
+ assert np.array_equal(mesh.dimension, (10, 10, 10)) # default values
assert np.array_equal(mesh.lower_left, universe.bounding_box[0])
assert np.array_equal(mesh.upper_right, universe.bounding_box[1])
def test_reg_mesh_from_geometry():
- """Tests a RegularMesh can be made from a Geometry and the default dimensions
- are propagated through. Geometry is centralized"""
+ """Tests a RegularMesh can be made from a Geometry and the default
+ dimensions are propagated through. Geometry is centralized"""
surface = openmc.Sphere(r=42)
cell = openmc.Cell(region=-surface)
universe = openmc.Universe(cells=[cell])
@@ -53,7 +89,7 @@ def test_reg_mesh_from_geometry():
mesh = openmc.RegularMesh.from_domain(geometry)
assert isinstance(mesh, openmc.RegularMesh)
- assert np.array_equal(mesh.dimension, (100, 100, 100)) # default values
+ assert np.array_equal(mesh.dimension, (10, 10, 10)) # default values
assert np.array_equal(mesh.lower_left, geometry.bounding_box[0])
assert np.array_equal(mesh.upper_right, geometry.bounding_box[1])
| Error when calling decay_photon_energy on stable isotope
When calling ```decay_photon_energy``` on a material which has no gamma decays the code raises an indexError
in this case ```dists``` is ```[]``` so ```dists[0]``` is not possible
Perhaps we should add some error handling for empty lists to ```combine_distributions```
Code to reproduce
```python
import openmc
openmc.config['chain_file']='chain-endf.xml'
a=openmc.Material()
a.add_nuclide('Li6',1)
a.volume=1
a.decay_photon_energy
```
error message
```
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/openmc/openmc/material.py", line 276, in decay_photon_energy
return openmc.data.combine_distributions(dists, probs)
File "/home/openmc/openmc/stats/univariate.py", line 1252, in combine_distributions
return dist_list[0]
IndexError: list index out of range
```
| 0.0 | [
"tests/unit_tests/test_mesh_from_domain.py::test_cylindrical_mesh_from_cell",
"tests/unit_tests/test_mesh_from_domain.py::test_reg_mesh_from_region",
"tests/unit_tests/test_mesh_from_domain.py::test_cylindrical_mesh_from_region",
"tests/unit_tests/test_mesh_from_domain.py::test_reg_mesh_from_universe",
"tests/unit_tests/test_mesh_from_domain.py::test_reg_mesh_from_geometry"
] | [
"tests/unit_tests/test_material.py::test_attributes",
"tests/unit_tests/test_material.py::test_add_nuclide",
"tests/unit_tests/test_material.py::test_add_components",
"tests/unit_tests/test_material.py::test_remove_nuclide",
"tests/unit_tests/test_material.py::test_remove_elements",
"tests/unit_tests/test_material.py::test_add_element",
"tests/unit_tests/test_material.py::test_elements_by_name",
"tests/unit_tests/test_material.py::test_add_elements_by_formula",
"tests/unit_tests/test_material.py::test_density",
"tests/unit_tests/test_material.py::test_salphabeta",
"tests/unit_tests/test_material.py::test_repr",
"tests/unit_tests/test_material.py::test_macroscopic",
"tests/unit_tests/test_material.py::test_paths",
"tests/unit_tests/test_material.py::test_isotropic",
"tests/unit_tests/test_material.py::test_get_nuclides",
"tests/unit_tests/test_material.py::test_get_nuclide_densities",
"tests/unit_tests/test_material.py::test_get_nuclide_atom_densities",
"tests/unit_tests/test_material.py::test_get_nuclide_atom_densities_specific",
"tests/unit_tests/test_material.py::test_get_nuclide_atoms",
"tests/unit_tests/test_material.py::test_mass",
"tests/unit_tests/test_material.py::test_materials",
"tests/unit_tests/test_material.py::test_borated_water",
"tests/unit_tests/test_material.py::test_from_xml",
"tests/unit_tests/test_material.py::test_mix_materials",
"tests/unit_tests/test_material.py::test_get_activity",
"tests/unit_tests/test_mesh_from_domain.py::test_reg_mesh_from_cell",
"tests/unit_tests/test_mesh_from_domain.py::test_error_from_unsupported_object"
] | 2022-10-05 19:29:41+00:00 | 4,412 |
|
openmc-dev__openmc-2713 | diff --git a/README.md b/README.md
index 561bf4e1a..6539ec3c7 100644
--- a/README.md
+++ b/README.md
@@ -1,7 +1,7 @@
# OpenMC Monte Carlo Particle Transport Code
[](https://docs.openmc.org/en/latest/license.html)
-[](https://github.com/openmc-dev/openmc/actions?query=workflow%3ACI)
+[](https://github.com/openmc-dev/openmc/actions/workflows/ci.yml)
[](https://coveralls.io/github/openmc-dev/openmc?branch=develop)
[](https://github.com/openmc-dev/openmc/actions?query=workflow%3Adockerhub-publish-develop-dagmc)
[](https://github.com/openmc-dev/openmc/actions?query=workflow%3Adockerhub-publish-develop)
diff --git a/docs/source/io_formats/settings.rst b/docs/source/io_formats/settings.rst
index 226e9084e..03abe9a3c 100644
--- a/docs/source/io_formats/settings.rst
+++ b/docs/source/io_formats/settings.rst
@@ -1068,8 +1068,14 @@ The ``<volume_calc>`` element indicates that a stochastic volume calculation
should be run at the beginning of the simulation. This element has the following
sub-elements/attributes:
- :cells:
- The unique IDs of cells for which the volume should be estimated.
+ :domain_type:
+ The type of each domain for the volume calculation ("cell", "material", or
+ "universe").
+
+ *Default*: None
+
+ :domain_ids:
+ The unique IDs of domains for which the volume should be estimated.
*Default*: None
@@ -1079,16 +1085,41 @@ sub-elements/attributes:
*Default*: None
:lower_left:
- The lower-left Cartesian coordinates of a bounding box that is used to
- sample points within.
+ The lower-left Cartesian coordinates of a bounding box that is used to
+ sample points within.
- *Default*: None
+ *Default*: None
:upper_right:
- The upper-right Cartesian coordinates of a bounding box that is used to
- sample points within.
+ The upper-right Cartesian coordinates of a bounding box that is used to
+ sample points within.
- *Default*: None
+ *Default*: None
+
+ :threshold:
+ Presence of a ``<threshold>`` sub-element indicates that the volume
+ calculation will be halted based on a threshold on the error. It has the
+ following sub-elements/attributes:
+
+ :type:
+ The type of the trigger. Accepted options are "variance", "std_dev",
+ and "rel_err".
+
+ :variance:
+ Variance of the mean, :math:`\sigma^2`
+
+ :std_dev:
+ Standard deviation of the mean, :math:`\sigma`
+
+ :rel_err:
+ Relative error of the mean, :math:`\frac{\sigma}{\mu}`
+
+ *Default*: None
+
+ :threshold:
+ The trigger's convergence criterion for the given type.
+
+ *Default*: None
----------------------------
``<weight_windows>`` Element
diff --git a/openmc/mesh.py b/openmc/mesh.py
index d683c8808..a655e7a89 100644
--- a/openmc/mesh.py
+++ b/openmc/mesh.py
@@ -1439,6 +1439,10 @@ class CylindricalMesh(StructuredMesh):
num=dimension[2]+1
)
origin = (cached_bb.center[0], cached_bb.center[1], z_grid[0])
+
+ # make z-grid relative to the origin
+ z_grid -= origin[2]
+
mesh = cls(
r_grid=r_grid,
z_grid=z_grid,
diff --git a/src/source.cpp b/src/source.cpp
index 817847b76..3251ca0d0 100644
--- a/src/source.cpp
+++ b/src/source.cpp
@@ -457,6 +457,11 @@ extern "C" int openmc_sample_external_source(
return OPENMC_E_INVALID_ARGUMENT;
}
+ if (model::external_sources.empty()) {
+ set_errmsg("No external sources have been defined.");
+ return OPENMC_E_OUT_OF_BOUNDS;
+ }
+
auto sites_array = static_cast<SourceSite*>(sites);
for (size_t i = 0; i < n; ++i) {
sites_array[i] = sample_external_source(seed);
| openmc-dev/openmc | 972dd73ae9db8fbacd398c5483aa6326665b2f0a | diff --git a/tests/unit_tests/test_mesh_from_domain.py b/tests/unit_tests/test_mesh_from_domain.py
index c75e8fd07..0cbe413e8 100644
--- a/tests/unit_tests/test_mesh_from_domain.py
+++ b/tests/unit_tests/test_mesh_from_domain.py
@@ -30,7 +30,7 @@ def test_cylindrical_mesh_from_cell():
assert np.array_equal(mesh.dimension, (2, 4, 3))
assert np.array_equal(mesh.r_grid, [0., 25., 50.])
assert np.array_equal(mesh.phi_grid, [0., 0.5*np.pi, np.pi, 1.5*np.pi, 2.*np.pi])
- assert np.array_equal(mesh.z_grid, [10., 20., 30., 40.])
+ assert np.array_equal(mesh.z_grid, [0., 10., 20., 30.])
assert np.array_equal(mesh.origin, [0., 0., 10.])
# Cell is not centralized on Z or X axis
@@ -83,7 +83,8 @@ def test_cylindrical_mesh_from_region():
assert np.array_equal(mesh.dimension, (6, 2, 3))
assert np.array_equal(mesh.r_grid, [0., 1., 2., 3., 4., 5., 6.])
assert np.array_equal(mesh.phi_grid, [0., 0.5*np.pi, np.pi])
- assert np.array_equal(mesh.z_grid, [-30., -10., 10., 30.])
+ assert np.array_equal(mesh.z_grid, [0.0, 20., 40., 60])
+ assert np.array_equal(mesh.origin, (0.0, 0.0, -30.))
def test_reg_mesh_from_universe():
| <volume_calc> settings.xml element file format outdated
<!--Describe the issue with the documentation and include a URL to the corresponding page-->
https://docs.openmc.org/en/latest/io_formats/settings.html#volume-calc-element
A few elements read by the C++ code are undocumented online:
- `domain_type`
- `threshold`
- `type`
- ~~cells~~ this is present but has been replaced by `domain_ids` | 0.0 | [
"tests/unit_tests/test_mesh_from_domain.py::test_cylindrical_mesh_from_cell",
"tests/unit_tests/test_mesh_from_domain.py::test_cylindrical_mesh_from_region"
] | [
"tests/unit_tests/test_mesh_from_domain.py::test_reg_mesh_from_cell",
"tests/unit_tests/test_mesh_from_domain.py::test_reg_mesh_from_region",
"tests/unit_tests/test_mesh_from_domain.py::test_reg_mesh_from_universe",
"tests/unit_tests/test_mesh_from_domain.py::test_reg_mesh_from_geometry",
"tests/unit_tests/test_mesh_from_domain.py::test_error_from_unsupported_object"
] | 2023-09-27 12:13:33+00:00 | 4,413 |
|
openmrslab__suspect-25 | diff --git a/suspect/processing/denoising.py b/suspect/processing/denoising.py
index fd49a14..f55b7ae 100644
--- a/suspect/processing/denoising.py
+++ b/suspect/processing/denoising.py
@@ -34,7 +34,7 @@ def sliding_window(input_signal, window_width):
window /= numpy.sum(window)
# pad the signal to cover half the window width on each side
padded_input = _pad(input_signal, len(input_signal) + window_width - 1)
- result = numpy.zeros(len(input_signal))
+ result = numpy.zeros_like(input_signal)
for i in range(len(input_signal)):
result[i] = numpy.dot(window, padded_input[i:(i + window_width)])
return result
@@ -62,7 +62,7 @@ def sift(input_signal, threshold):
def svd(input_signal, rank):
matrix_width = int(len(input_signal) / 2)
matrix_height = len(input_signal) - matrix_width + 1
- hankel_matrix = numpy.zeros((matrix_width, matrix_height))
+ hankel_matrix = numpy.zeros((matrix_width, matrix_height), input_signal.dtype)
for i in range(matrix_height):
hankel_matrix[:, i] = input_signal[i:(i + matrix_width)]
# perform the singular value decomposition
| openmrslab/suspect | 974ab0d0303778d7366cc458799dbd54dc34794a | diff --git a/tests/test_mrs/test_processing.py b/tests/test_mrs/test_processing.py
index 40ea9c3..9bf35ef 100644
--- a/tests/test_mrs/test_processing.py
+++ b/tests/test_mrs/test_processing.py
@@ -1,6 +1,9 @@
import suspect
import numpy
+import warnings
+
+warnings.filterwarnings('error')
def test_null_transform():
@@ -81,6 +84,24 @@ def test_gaussian_denoising():
numpy.testing.assert_almost_equal(data, denoised_data)
+def test_svd_dtype():
+ data = numpy.ones(128, dtype=complex)
+ denoised_data = suspect.processing.denoising.svd(data, 8)
+ assert data.dtype == denoised_data.dtype
+
+
+def test_sliding_window_dtype():
+ data = numpy.ones(128, dtype=complex)
+ denoised_data = suspect.processing.denoising.sliding_window(data, 30)
+ assert data.dtype == denoised_data.dtype
+
+
+def test_sliding_gaussian_dtype():
+ data = numpy.ones(128, dtype=complex)
+ denoised_data = suspect.processing.denoising.sliding_gaussian(data, 30)
+ assert data.dtype == denoised_data.dtype
+
+
def test_water_suppression():
data = suspect.io.load_twix("tests/test_data/siemens/twix_vb.dat")
channel_combined_data = data.inherit(numpy.average(data, axis=1))
| BUG: denoising methods cast complex to real
Several of the methods in suspect.processing.denoising return real results from complex inputs. | 0.0 | [
"tests/test_mrs/test_processing.py::test_sliding_window_dtype"
] | [
"tests/test_mrs/test_processing.py::test_null_transform",
"tests/test_mrs/test_processing.py::test_water_peak_alignment_misshape",
"tests/test_mrs/test_processing.py::test_water_peak_alignment",
"tests/test_mrs/test_processing.py::test_spectral_registration",
"tests/test_mrs/test_processing.py::test_compare_frequency_correction",
"tests/test_mrs/test_processing.py::test_frequency_transform",
"tests/test_mrs/test_processing.py::test_apodize",
"tests/test_mrs/test_processing.py::test_gaussian_denoising",
"tests/test_mrs/test_processing.py::test_svd_dtype",
"tests/test_mrs/test_processing.py::test_sliding_gaussian_dtype",
"tests/test_mrs/test_processing.py::test_water_suppression"
] | 2016-10-07 18:32:33+00:00 | 4,414 |
|
openmrslab__suspect-26 | diff --git a/suspect/io/__init__.py b/suspect/io/__init__.py
index c024146..040d217 100644
--- a/suspect/io/__init__.py
+++ b/suspect/io/__init__.py
@@ -2,4 +2,5 @@ from suspect.io.rda import load_rda
from suspect.io.twix import load_twix
from suspect.io.philips import load_sdat
from suspect.io.siemens import load_siemens_dicom
-from . import tarquin, lcmodel, felix
\ No newline at end of file
+from . import tarquin, lcmodel, felix
+from .dicom import load_dicom
diff --git a/suspect/io/_common.py b/suspect/io/_common.py
new file mode 100644
index 0000000..754da48
--- /dev/null
+++ b/suspect/io/_common.py
@@ -0,0 +1,29 @@
+import numpy as np
+
+
+def complex_array_from_iter(data_iter, length=-1, shape=None, chirality=1):
+ """
+ Converts an iterable over a series of real, imaginary pairs into
+ a numpy.ndarray of complex64.
+
+ Parameters
+ ----------
+ data_iter : iter
+ The iterator over the points
+ length : int
+ The number of complex points to read. The defaults is -1, which
+ means all data is read.
+ shape : array-like
+ Shape to convert the final array to. The array will be squeezed
+ after reshaping to remove any dimensions of length 1.
+
+ Returns
+ -------
+ out : ndarray
+ The output array
+ """
+ complex_iter = (complex(r, chirality * i) for r, i in zip(data_iter, data_iter))
+ complex_array = np.fromiter(complex_iter, "complex64", length)
+ if shape is not None:
+ complex_array = np.reshape(complex_array, shape).squeeze()
+ return complex_array
diff --git a/suspect/io/dicom.py b/suspect/io/dicom.py
new file mode 100644
index 0000000..e368428
--- /dev/null
+++ b/suspect/io/dicom.py
@@ -0,0 +1,48 @@
+from suspect import MRSData
+
+from ._common import complex_array_from_iter
+
+import pydicom.dicomio
+import pydicom.tag
+
+
+def load_dicom(filename):
+ """
+ Load a file in the DICOM Magnetic Resonance Spectroscopy format
+ (SOP 1.2.840.10008.5.1.4.1.1.4.2)
+
+ Parameters
+ ----------
+ filename : str
+ The name of the file to load
+
+ Returns
+ -------
+ MRSData
+ The loaded data from the file
+ """
+ dataset = pydicom.dicomio.read_file(filename)
+
+ sw = dataset[0x0018, 0x9052].value
+ dt = 1.0 / sw
+
+ f0 = dataset[0x0018, 0x9098].value
+
+ ppm0 = dataset[0x0018, 0x9053].value
+
+ rows = dataset[0x0028, 0x0010].value
+ cols = dataset[0x0028, 0x0011].value
+ frames = dataset[0x0028, 0x0008].value
+ num_second_spectral = dataset[0x0028, 0x9001].value
+ num_points = dataset[0x0028, 0x9002].value
+
+ data_shape = [frames, rows, cols, num_second_spectral, num_points]
+
+ # turn the data into a numpy array
+ data_iter = iter(dataset[0x5600, 0x0020])
+ data = complex_array_from_iter(data_iter, shape=data_shape, chirality=-1)
+
+ return MRSData(data,
+ dt,
+ f0,
+ ppm0=ppm0)
diff --git a/suspect/io/siemens.py b/suspect/io/siemens.py
index 65f3798..ad3763d 100644
--- a/suspect/io/siemens.py
+++ b/suspect/io/siemens.py
@@ -4,6 +4,7 @@ import numpy
import struct
from suspect import MRSData
+from ._common import complex_array_from_iter
CSA1 = 0
CSA2 = 1
@@ -143,14 +144,9 @@ def load_siemens_dicom(filename):
csa_data_bytes = dataset[0x7fe1, 0x0100 * data_index + 0x0010].value
# the data is stored as a list of 4 byte floats in (real, imaginary) pairs
data_floats = struct.unpack("<%df" % (len(csa_data_bytes) / 4), csa_data_bytes)
- # form an iterator which will provide the numbers one at a time, then an iterator which calls that iterator twice
- # each cycle to give a complex pair
- data_iter = iter(data_floats)
- complex_iter = (complex(r, i) for r, i in zip(data_iter, data_iter))
- # give this iterator to numpy to build the data array
- complex_data = numpy.fromiter(complex_iter, "complex128", int(len(csa_data_bytes) / 8))
- # reshape the array to structure of rows, columns and slices
- complex_data = numpy.reshape(complex_data, data_shape).squeeze()
+ complex_data = complex_array_from_iter(iter(data_floats),
+ length=len(data_floats) // 2,
+ shape=data_shape)
return MRSData(complex_data,
csa_header["RealDwellTime"] * 1e-9,
diff --git a/suspect/processing/denoising.py b/suspect/processing/denoising.py
index fd49a14..f55b7ae 100644
--- a/suspect/processing/denoising.py
+++ b/suspect/processing/denoising.py
@@ -34,7 +34,7 @@ def sliding_window(input_signal, window_width):
window /= numpy.sum(window)
# pad the signal to cover half the window width on each side
padded_input = _pad(input_signal, len(input_signal) + window_width - 1)
- result = numpy.zeros(len(input_signal))
+ result = numpy.zeros_like(input_signal)
for i in range(len(input_signal)):
result[i] = numpy.dot(window, padded_input[i:(i + window_width)])
return result
@@ -62,7 +62,7 @@ def sift(input_signal, threshold):
def svd(input_signal, rank):
matrix_width = int(len(input_signal) / 2)
matrix_height = len(input_signal) - matrix_width + 1
- hankel_matrix = numpy.zeros((matrix_width, matrix_height))
+ hankel_matrix = numpy.zeros((matrix_width, matrix_height), input_signal.dtype)
for i in range(matrix_height):
hankel_matrix[:, i] = input_signal[i:(i + matrix_width)]
# perform the singular value decomposition
diff --git a/suspect/processing/frequency_correction.py b/suspect/processing/frequency_correction.py
index 6ea3a89..6cd6e6c 100644
--- a/suspect/processing/frequency_correction.py
+++ b/suspect/processing/frequency_correction.py
@@ -29,10 +29,10 @@ def spectral_registration(data, target, initial_guess=(0.0, 0.0), frequency_rang
Parameters
----------
- data :
- target :
- initial_guess :
- frequency_range:
+ data : MRSData
+ target : MRSData
+ initial_guess : tuple
+ frequency_range :
Returns
-------
| openmrslab/suspect | 974ab0d0303778d7366cc458799dbd54dc34794a | diff --git a/tests/test_mrs/test_io.py b/tests/test_mrs/test_io.py
index d80a0a1..240855c 100644
--- a/tests/test_mrs/test_io.py
+++ b/tests/test_mrs/test_io.py
@@ -6,9 +6,25 @@ import builtins
from unittest.mock import patch
import os
+from suspect.io._common import complex_array_from_iter
+
import numpy
+def test_complex_from_iter():
+ float_list = [1.0, 0.0, 0.0, 1.0]
+ array = complex_array_from_iter(iter(float_list))
+ assert array.shape == (2,)
+ assert array[0] == 1
+ assert array[1] == 1j
+
+
+def test_shaped_complex_from_iter():
+ float_list = [1.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0]
+ array = complex_array_from_iter(iter(float_list), shape=[2, 2])
+ assert array.shape == (2, 2)
+
+
def test_write_dpt():
data = suspect.MRSData(numpy.zeros(1), 1e-3, 123.456)
mock = unittest.mock.mock_open()
diff --git a/tests/test_mrs/test_processing.py b/tests/test_mrs/test_processing.py
index 40ea9c3..9bf35ef 100644
--- a/tests/test_mrs/test_processing.py
+++ b/tests/test_mrs/test_processing.py
@@ -1,6 +1,9 @@
import suspect
import numpy
+import warnings
+
+warnings.filterwarnings('error')
def test_null_transform():
@@ -81,6 +84,24 @@ def test_gaussian_denoising():
numpy.testing.assert_almost_equal(data, denoised_data)
+def test_svd_dtype():
+ data = numpy.ones(128, dtype=complex)
+ denoised_data = suspect.processing.denoising.svd(data, 8)
+ assert data.dtype == denoised_data.dtype
+
+
+def test_sliding_window_dtype():
+ data = numpy.ones(128, dtype=complex)
+ denoised_data = suspect.processing.denoising.sliding_window(data, 30)
+ assert data.dtype == denoised_data.dtype
+
+
+def test_sliding_gaussian_dtype():
+ data = numpy.ones(128, dtype=complex)
+ denoised_data = suspect.processing.denoising.sliding_gaussian(data, 30)
+ assert data.dtype == denoised_data.dtype
+
+
def test_water_suppression():
data = suspect.io.load_twix("tests/test_data/siemens/twix_vb.dat")
channel_combined_data = data.inherit(numpy.average(data, axis=1))
| Support loading DICOM files
Support loading DICOM SOP 1.2.840.10008.5.1.4.1.1.4.2 files | 0.0 | [
"tests/test_mrs/test_io.py::test_complex_from_iter",
"tests/test_mrs/test_io.py::test_shaped_complex_from_iter",
"tests/test_mrs/test_io.py::test_write_dpt",
"tests/test_mrs/test_io.py::test_read_tarquin_results",
"tests/test_mrs/test_io.py::test_write_raw",
"tests/test_mrs/test_io.py::test_lcmodel_all_files",
"tests/test_mrs/test_io.py::test_lcmodel_read_coord",
"tests/test_mrs/test_io.py::test_lcmodel_read_liver_coord",
"tests/test_mrs/test_io.py::test_lcmodel_read_basis",
"tests/test_mrs/test_io.py::test_lcmodel_write_basis",
"tests/test_mrs/test_io.py::test_felix_save_mat",
"tests/test_mrs/test_processing.py::test_null_transform",
"tests/test_mrs/test_processing.py::test_water_peak_alignment_misshape",
"tests/test_mrs/test_processing.py::test_water_peak_alignment",
"tests/test_mrs/test_processing.py::test_spectral_registration",
"tests/test_mrs/test_processing.py::test_compare_frequency_correction",
"tests/test_mrs/test_processing.py::test_frequency_transform",
"tests/test_mrs/test_processing.py::test_apodize",
"tests/test_mrs/test_processing.py::test_gaussian_denoising",
"tests/test_mrs/test_processing.py::test_svd_dtype",
"tests/test_mrs/test_processing.py::test_sliding_window_dtype",
"tests/test_mrs/test_processing.py::test_sliding_gaussian_dtype",
"tests/test_mrs/test_processing.py::test_water_suppression"
] | [] | 2016-10-07 18:34:16+00:00 | 4,415 |
|
openmrslab__suspect-40 | diff --git a/suspect/processing/denoising.py b/suspect/processing/denoising.py
index f55b7ae..46dfc04 100644
--- a/suspect/processing/denoising.py
+++ b/suspect/processing/denoising.py
@@ -85,8 +85,8 @@ def svd(input_signal, rank):
def spline(input_signal, num_splines, spline_order):
# input signal has to be a multiple of num_splines
- padded_input_signal = _pad(input_signal, (numpy.ceil(len(input_signal) / float(num_splines))) * num_splines)
- stride = len(padded_input_signal) / num_splines
+ padded_input_signal = _pad(input_signal, int(numpy.ceil(len(input_signal) / float(num_splines))) * num_splines)
+ stride = len(padded_input_signal) // num_splines
import scipy.signal
# we construct the spline basis by building the first one, then the rest
# are identical copies offset by stride
@@ -95,11 +95,11 @@ def spline(input_signal, num_splines, spline_order):
spline_basis = numpy.zeros((num_splines + 1, len(padded_input_signal)), input_signal.dtype)
for i in range(num_splines + 1):
spline_basis[i, :] = numpy.roll(first_spline, i * stride)
- spline_basis[:(num_splines / 4), (len(padded_input_signal) / 2):] = 0.0
- spline_basis[(num_splines * 3 / 4):, :(len(padded_input_signal) / 2)] = 0.0
+ spline_basis[:(num_splines // 4), (len(padded_input_signal) // 2):] = 0.0
+ spline_basis[(num_splines * 3 // 4):, :(len(padded_input_signal) // 2)] = 0.0
coefficients = numpy.linalg.lstsq(spline_basis.T, padded_input_signal)
recon = numpy.dot(coefficients[0], spline_basis)
- start_offset = (len(padded_input_signal) - len(input_signal)) / 2.0
+ start_offset = (len(padded_input_signal) - len(input_signal)) // 2
return recon[start_offset:(start_offset + len(input_signal))]
@@ -108,9 +108,9 @@ def wavelet(input_signal, wavelet_shape, threshold):
# we have to pad the signal to make it a power of two
next_power_of_two = int(numpy.floor(numpy.log2(len(input_signal))) + 1)
padded_input_signal = _pad(input_signal, 2**next_power_of_two)
- wt_coeffs = pywt.wavedec(padded_input_signal, wavelet_shape, level=None, mode='per')
+ wt_coeffs = pywt.wavedec(padded_input_signal, wavelet_shape, level=None, mode='periodization')
denoised_coeffs = wt_coeffs[:]
denoised_coeffs[1:] = (pywt.threshold(i, value=threshold) for i in denoised_coeffs[1:])
- recon = pywt.waverec(denoised_coeffs, wavelet_shape, mode='per')
- start_offset = (len(padded_input_signal) - len(input_signal)) / 2.0
+ recon = pywt.waverec(denoised_coeffs, wavelet_shape, mode='periodization')
+ start_offset = (len(padded_input_signal) - len(input_signal)) // 2
return recon[start_offset:(start_offset + len(input_signal))]
| openmrslab/suspect | b03275c0dd645fd522cab182a2cfbe28dfc948ed | diff --git a/tests/test_mrs/test_processing/test_denoising.py b/tests/test_mrs/test_processing/test_denoising.py
new file mode 100644
index 0000000..2e45982
--- /dev/null
+++ b/tests/test_mrs/test_processing/test_denoising.py
@@ -0,0 +1,29 @@
+import suspect
+
+import numpy
+
+import warnings
+warnings.filterwarnings("ignore", message="numpy.dtype size changed")
+
+def test_spline():
+ # we need to check if this runs correctly when number of splines is not a
+ # factor of length of signal, so that padding is required.
+ # generate a sample signal
+ input_signal = numpy.random.randn(295) + 10
+ # denoise the signal with splines
+ output_signal = suspect.processing.denoising.spline(input_signal, 32, 2)
+ # main thing is that the test runs without errors, but we can also check
+ # for reduced std in the result
+ assert numpy.std(output_signal) < numpy.std(input_signal)
+
+
+def test_wavelet():
+ # this is to check if the code runs without throwing double -> integer
+ # conversion issues
+ # generate a sample signal
+ input_signal = numpy.random.randn(295) + 10
+ # denoise the signal with splines
+ output_signal = suspect.processing.denoising.wavelet(input_signal, "db8", 1e-2)
+ # main thing is that the test runs without errors, but we can also check
+ # for reduced std in the result
+ assert numpy.std(output_signal) < numpy.std(input_signal)
\ No newline at end of file
| Spline denoising fails on numpy 1.12
In numpy 1.12 spline denoising fails because it passes floating point values to _pad and roll instead of integer values. | 0.0 | [
"tests/test_mrs/test_processing/test_denoising.py::test_wavelet"
] | [] | 2017-01-13 12:14:36+00:00 | 4,416 |
|
openmrslab__suspect-77 | diff --git a/suspect/basis/__init__.py b/suspect/basis/__init__.py
index e0296f9..257e640 100644
--- a/suspect/basis/__init__.py
+++ b/suspect/basis/__init__.py
@@ -1,7 +1,9 @@
import numpy
+from ..mrsobjects import MRSData
-def gaussian(time_axis, frequency, phase, fwhm):
+def gaussian(time_axis, frequency, phase, fwhm, f0=123.0):
+ dt = time_axis[1] - time_axis[0]
oscillatory_term = numpy.exp(2j * numpy.pi * (frequency * time_axis) + 1j * phase)
damping = numpy.exp(-time_axis ** 2 / 4 * numpy.pi ** 2 / numpy.log(2) * fwhm ** 2)
fid = oscillatory_term * damping
@@ -13,10 +15,11 @@ def gaussian(time_axis, frequency, phase, fwhm):
# the chosen df does not affect the area, so we divide by df, which is
# equivalent to multiplying by dt * np, then the np terms cancel and we
# are left with the dt term (and a 2 because fid[0] = 0.5, not 1)
- return fid * (time_axis[1] - time_axis[0]) * 2.0
+ fid = fid * dt * 2.0
+ return MRSData(fid, dt, f0)
-def lorentzian(time_axis, frequency, phase, fwhm):
+def lorentzian(time_axis, frequency, phase, fwhm, f0=123.0):
oscillatory_term = numpy.exp(1j * (2 * numpy.pi * frequency * time_axis + phase))
damping = numpy.exp(-time_axis * numpy.pi * fwhm)
fid = oscillatory_term * damping
diff --git a/suspect/processing/__init__.py b/suspect/processing/__init__.py
index 4944019..68d8c93 100644
--- a/suspect/processing/__init__.py
+++ b/suspect/processing/__init__.py
@@ -1,2 +1,2 @@
-from . import frequency_correction, channel_combination, denoising, water_suppression
+from . import frequency_correction, channel_combination, denoising, water_suppression, phase
from suspect.processing._apodize import *
\ No newline at end of file
diff --git a/suspect/processing/phase.py b/suspect/processing/phase.py
new file mode 100644
index 0000000..acfe9dd
--- /dev/null
+++ b/suspect/processing/phase.py
@@ -0,0 +1,161 @@
+import lmfit
+import numpy as np
+
+
+def mag_real(data, *args, range_hz=None, range_ppm=None):
+ """
+ Estimates the zero and first order phase parameters which minimise the
+ difference between the real part of the spectrum and the magnitude. Note
+ that these are the phase correction terms, designed to be used directly
+ in the adjust_phase() function without negation.
+
+ Parameters
+ ----------
+ data: MRSBase
+ The data to be phased
+ range_hz: tuple (low, high)
+ The frequency range in Hertz over which to compare the spectra
+ range_ppm: tuple (low, high)
+ The frequency range in PPM over which to compare the spectra. range_hz
+ and range_ppm cannot both be defined.
+ Returns
+ -------
+ phi0 : float
+ The estimated zero order phase correction
+ phi1 : float
+ The estimated first order phase correction
+ """
+ if range_hz is not None and range_ppm is not None:
+ raise KeyError("Cannot specify both range_hz and range_ppm")
+
+ if range_hz is not None:
+ frequency_slice = data.slice_hz(*range_hz)
+ elif range_hz is not None:
+ frequency_slice = data.slice_ppm(*range_ppm)
+ else:
+ frequency_slice = slice(0, data.np)
+
+ def single_spectrum_version(spectrum):
+ def residual(pars):
+ par_vals = pars.valuesdict()
+ phased_data = spectrum.adjust_phase(par_vals['phi0'],)
+ #par_vals['phi1'])
+
+ diff = np.real(phased_data) - np.abs(spectrum)
+
+ return diff[frequency_slice]
+
+ params = lmfit.Parameters()
+ params.add('phi0', value=0, min=-np.pi, max=np.pi)
+ #params.add('phi1', value=0.0, min=-0.01, max=0.25)
+
+ result = lmfit.minimize(residual, params)
+ #return result.params['phi0'].value, result.params['phi1'].value
+ return result.params['phi0'].value, 0
+
+ return np.apply_along_axis(single_spectrum_version,
+ axis=-1,
+ arr=data.spectrum())
+
+
+def ernst(data):
+ """
+ Estimates the zero and first order phase using the ACME algorithm, which
+ minimises the integral of the imaginary part of the spectrum. Note that
+ these are the phase correction terms, designed to be used directly in the
+ adjust_phase() function without negation.
+
+ Parameters
+ ----------
+ data: MRSBase
+ The data to be phased
+ range_hz: tuple (low, high)
+ The frequency range in Hertz over which to compare the spectra
+ range_ppm: tuple (low, high)
+ The frequency range in PPM over which to compare the spectra. range_hz
+ and range_ppm cannot both be defined.
+ Returns
+ -------
+ phi0 : float
+ The estimated zero order phase correction
+ phi1 : float
+ The estimated first order phase correction
+ """
+ def residual(pars):
+ par_vals = pars.valuesdict()
+ phased_data = data.adjust_phase(par_vals['phi0'],
+ par_vals['phi1'])
+ return np.sum(phased_data.spectrum().imag)
+
+ params = lmfit.Parameters()
+ params.add('phi0', value=0, min=-np.pi, max=np.pi)
+ params.add('phi1', value=0.0, min=-0.005, max=0.1)
+
+ result = lmfit.minimize(residual, params, method='simplex')
+ return result.params['phi0'].value, result.params['phi1'].value
+
+
+def acme(data, *args, range_hz=None, range_ppm=None):
+ """
+ Estimates the zero and first order phase using the ACME algorithm, which
+ minimises the entropy of the real part of the spectrum. Note that these
+ are the phase correction terms, designed to be used directly in the
+ adjust_phase() function without negation.
+
+ Parameters
+ ----------
+ data: MRSBase
+ The data to be phased
+ range_hz: tuple (low, high)
+ The frequency range in Hertz over which to compare the spectra
+ range_ppm: tuple (low, high)
+ The frequency range in PPM over which to compare the spectra. range_hz
+ and range_ppm cannot both be defined.
+ Returns
+ -------
+ phi0 : float
+ The estimated zero order phase correction
+ phi1 : float
+ The estimated first order phase correction
+ """
+ if range_hz is not None and range_ppm is not None:
+ raise KeyError("Cannot specify both range_hz and range_ppm")
+
+ if range_hz is not None:
+ frequency_slice = data.slice_hz(*range_hz)
+ elif range_hz is not None:
+ frequency_slice = data.slice_ppm(*range_ppm)
+ else:
+ frequency_slice = slice(0, data.np)
+
+ def single_spectrum_version(spectrum):
+ def residual(pars):
+ par_vals = pars.valuesdict()
+ phased_data = spectrum.adjust_phase(par_vals['phi0'],
+ par_vals['phi1'])
+
+ r = phased_data.real[frequency_slice]
+ derivative = np.abs((r[1:] - r[:-1]))
+ derivative_norm = derivative / np.sum(derivative)
+
+ # make sure the entropy doesn't blow up by removing 0 values
+ derivative_norm[derivative_norm == 0] = 1
+
+ entropy = -np.sum(derivative_norm * np.log(derivative_norm))
+
+ # penalty function
+ p = np.sum(r[r < 0] ** 2)
+ gamma = 1000
+
+ return entropy + gamma * p
+
+ params = lmfit.Parameters()
+ params.add('phi0', value=0.0, min=-np.pi, max=np.pi)
+ params.add('phi1', value=0.0, min=-0.005, max=0.01)
+
+ result = lmfit.minimize(residual, params, method='simplex')
+ return result.params['phi0'].value, result.params['phi1'].value
+
+ return np.apply_along_axis(single_spectrum_version,
+ -1,
+ data.spectrum())
| openmrslab/suspect | 153f01f32f025eedfaefc655fb14621d087dd113 | diff --git a/tests/test_mrs/test_processing/test_phasing.py b/tests/test_mrs/test_processing/test_phasing.py
new file mode 100644
index 0000000..b7ae7da
--- /dev/null
+++ b/tests/test_mrs/test_processing/test_phasing.py
@@ -0,0 +1,61 @@
+import suspect
+import numpy as np
+
+
+def test_mag_real_zero():
+ time_axis = np.arange(0, 1.024, 2.5e-4)
+ sample_data = (6 * suspect.basis.gaussian(time_axis, 0, 0.0, 12)
+ + suspect.basis.gaussian(time_axis, 250, 0.0, 12)
+ + suspect.basis.gaussian(time_axis, 500, 0.0, 12))
+ sample_data = sample_data.adjust_phase(0.2, 0)
+ sample_data += np.random.rand(len(sample_data)) * 1e-6
+
+ phi0, phi1 = suspect.processing.phase.mag_real(sample_data)
+
+ np.testing.assert_allclose(phi0, -0.2, rtol=0.05)
+
+
+def test_acme_zero():
+ time_axis = np.arange(0, 1.024, 2.5e-4)
+ sample_data = (6 * suspect.basis.gaussian(time_axis, 0, 0.0, 12)
+ + suspect.basis.gaussian(time_axis, 50, 0.0, 12)
+ + suspect.basis.gaussian(time_axis, 200, 0.0, 12))
+ sample_data = sample_data.adjust_phase(0.2, 0)
+ sample_data += np.random.rand(len(sample_data)) * 1e-6
+
+ phi0, phi1 = suspect.processing.phase.acme(sample_data)
+
+ np.testing.assert_allclose(phi0, -0.2, rtol=0.05)
+
+
+def test_acme_first():
+ time_axis = np.arange(0, 1.024, 2.5e-4)
+ sample_data = (6 * suspect.basis.gaussian(time_axis, 0, 0.0, 6)
+ + suspect.basis.gaussian(time_axis, 150, 0.0, 6))
+ sample_data += np.random.rand(len(sample_data)) * 2e-6
+
+ in_0 = 0.5
+ in_1 = 0.001
+ sample_data = sample_data.adjust_phase(in_0, in_1)
+
+ out_0, out_1 = suspect.processing.phase.acme(sample_data)
+
+ np.testing.assert_allclose(in_0, -out_0, rtol=0.05)
+ np.testing.assert_allclose(in_1, -out_1, rtol=0.05)
+
+
+def test_acme_range_hz():
+ time_axis = np.arange(0, 1.024, 2.5e-4)
+ sample_data = (6 * suspect.basis.gaussian(time_axis, 0, 0.0, 12)
+ + suspect.basis.gaussian(time_axis, 50, 0.0, 12)
+ - suspect.basis.gaussian(time_axis, 200, 0.0, 12))
+ sample_data += np.random.rand(len(sample_data)) * 1e-7
+
+ in_0 = 0.2
+ in_1 = 0.001
+ sample_data = sample_data.adjust_phase(in_0, in_1)
+
+ out_0, out_1 = suspect.processing.phase.acme(sample_data, range_hz=(-1000, 75))
+
+ np.testing.assert_allclose(in_0, -out_0, rtol=0.05)
+ np.testing.assert_allclose(in_1, -out_1, rtol=0.05)
| ENH: auto-phasing
Add some algorithms for automatic phase estimation. Good first candidate is mag/real comparison, could also look at Ernst (minimise integral of imaginary component). | 0.0 | [
"tests/test_mrs/test_processing/test_phasing.py::test_mag_real_zero",
"tests/test_mrs/test_processing/test_phasing.py::test_acme_zero",
"tests/test_mrs/test_processing/test_phasing.py::test_acme_first",
"tests/test_mrs/test_processing/test_phasing.py::test_acme_range_hz"
] | [] | 2017-07-13 15:11:30+00:00 | 4,417 |
|
openqasm__oqpy-20 | diff --git a/oqpy/base.py b/oqpy/base.py
index 4a45796..43dece9 100644
--- a/oqpy/base.py
+++ b/oqpy/base.py
@@ -60,12 +60,29 @@ class OQPyExpression:
"""Helper method to produce a binary expression."""
return OQPyBinaryExpression(ast.BinaryOperator[op_name], first, second)
+ @staticmethod
+ def _to_unary(op_name: str, exp: AstConvertible) -> OQPyUnaryExpression:
+ """Helper method to produce a binary expression."""
+ return OQPyUnaryExpression(ast.UnaryOperator[op_name], exp)
+
+ def __pos__(self) -> OQPyExpression:
+ return self
+
+ def __neg__(self) -> OQPyUnaryExpression:
+ return self._to_unary("-", self)
+
def __add__(self, other: AstConvertible) -> OQPyBinaryExpression:
return self._to_binary("+", self, other)
def __radd__(self, other: AstConvertible) -> OQPyBinaryExpression:
return self._to_binary("+", other, self)
+ def __sub__(self, other: AstConvertible) -> OQPyBinaryExpression:
+ return self._to_binary("-", self, other)
+
+ def __rsub__(self, other: AstConvertible) -> OQPyBinaryExpression:
+ return self._to_binary("-", other, self)
+
def __mod__(self, other: AstConvertible) -> OQPyBinaryExpression:
return self._to_binary("%", self, other)
@@ -78,6 +95,18 @@ class OQPyExpression:
def __rmul__(self, other: AstConvertible) -> OQPyBinaryExpression:
return self._to_binary("*", other, self)
+ def __truediv__(self, other: AstConvertible) -> OQPyBinaryExpression:
+ return self._to_binary("/", self, other)
+
+ def __rtruediv__(self, other: AstConvertible) -> OQPyBinaryExpression:
+ return self._to_binary("/", other, self)
+
+ def __pow__(self, other: AstConvertible) -> OQPyBinaryExpression:
+ return self._to_binary("**", self, other)
+
+ def __rpow__(self, other: AstConvertible) -> OQPyBinaryExpression:
+ return self._to_binary("**", other, self)
+
def __eq__(self, other: AstConvertible) -> OQPyBinaryExpression: # type: ignore[override]
return self._to_binary("==", self, other)
@@ -132,6 +161,23 @@ class ExpressionConvertible(Protocol):
...
+class OQPyUnaryExpression(OQPyExpression):
+ """An expression consisting of one expression preceded by an operator."""
+
+ def __init__(self, op: ast.UnaryOperator, exp: AstConvertible):
+ super().__init__()
+ self.op = op
+ self.exp = exp
+ if isinstance(exp, OQPyExpression):
+ self.type = exp.type
+ else:
+ raise TypeError("exp is an expression")
+
+ def to_ast(self, program: Program) -> ast.UnaryExpression:
+ """Converts the OQpy expression into an ast node."""
+ return ast.UnaryExpression(self.op, to_ast(program, self.exp))
+
+
class OQPyBinaryExpression(OQPyExpression):
"""An expression consisting of two subexpressions joined by an operator."""
diff --git a/oqpy/classical_types.py b/oqpy/classical_types.py
index 630e336..7bc216f 100644
--- a/oqpy/classical_types.py
+++ b/oqpy/classical_types.py
@@ -38,6 +38,7 @@ if TYPE_CHECKING:
from oqpy.program import Program
__all__ = [
+ "pi",
"BoolVar",
"IntVar",
"UintVar",
@@ -53,6 +54,7 @@ __all__ = [
"stretch",
"bool_",
"bit_",
+ "bit",
"bit8",
"convert_range",
"int_",
@@ -78,24 +80,24 @@ __all__ = [
# subclasses of ``_ClassicalVar`` instead.
-def int_(size: int) -> ast.IntType:
+def int_(size: int | None = None) -> ast.IntType:
"""Create a sized signed integer type."""
- return ast.IntType(ast.IntegerLiteral(size))
+ return ast.IntType(ast.IntegerLiteral(size) if size is not None else None)
-def uint_(size: int) -> ast.UintType:
+def uint_(size: int | None = None) -> ast.UintType:
"""Create a sized unsigned integer type."""
- return ast.UintType(ast.IntegerLiteral(size))
+ return ast.UintType(ast.IntegerLiteral(size) if size is not None else None)
-def float_(size: int) -> ast.FloatType:
+def float_(size: int | None = None) -> ast.FloatType:
"""Create a sized floating-point type."""
- return ast.FloatType(ast.IntegerLiteral(size))
+ return ast.FloatType(ast.IntegerLiteral(size) if size is not None else None)
-def angle_(size: int) -> ast.AngleType:
+def angle_(size: int | None = None) -> ast.AngleType:
"""Create a sized angle type."""
- return ast.AngleType(ast.IntegerLiteral(size))
+ return ast.AngleType(ast.IntegerLiteral(size) if size is not None else None)
def complex_(size: int) -> ast.ComplexType:
@@ -107,14 +109,15 @@ def complex_(size: int) -> ast.ComplexType:
return ast.ComplexType(ast.FloatType(ast.IntegerLiteral(size // 2)))
-def bit_(size: int) -> ast.BitType:
+def bit_(size: int | None = None) -> ast.BitType:
"""Create a sized bit type."""
- return ast.BitType(ast.IntegerLiteral(size))
+ return ast.BitType(ast.IntegerLiteral(size) if size is not None else None)
duration = ast.DurationType()
stretch = ast.StretchType()
bool_ = ast.BoolType()
+bit = ast.BitType()
bit8 = bit_(8)
int32 = int_(32)
int64 = int_(64)
@@ -136,6 +139,22 @@ def convert_range(program: Program, item: Union[slice, range]) -> ast.RangeDefin
)
+class Identifier(OQPyExpression):
+ """Base class to specify constant symbols."""
+
+ name: str
+
+ def __init__(self, name: str) -> None:
+ self.type = None
+ self.name = name
+
+ def to_ast(self, program: Program) -> ast.Expression:
+ return ast.Identifier(name=self.name)
+
+
+pi = Identifier(name="pi")
+
+
class _ClassicalVar(Var, OQPyExpression):
"""Base type for variables with classical type.
diff --git a/oqpy/program.py b/oqpy/program.py
index 5e2e440..49c7d52 100644
--- a/oqpy/program.py
+++ b/oqpy/program.py
@@ -82,7 +82,9 @@ class Program:
def __init__(self, version: Optional[str] = "3.0") -> None:
self.stack: list[ProgramState] = [ProgramState()]
- self.defcals: dict[tuple[tuple[str, ...], str], ast.CalibrationDefinition] = {}
+ self.defcals: dict[
+ tuple[tuple[str, ...], str, tuple[str, ...]], ast.CalibrationDefinition
+ ] = {}
self.subroutines: dict[str, ast.SubroutineDefinition] = {}
self.externs: dict[str, ast.ExternDeclaration] = {}
self.declared_vars: dict[str, Var] = {}
@@ -196,13 +198,17 @@ class Program:
self.subroutines[name] = stmt
def _add_defcal(
- self, qubit_names: list[str], name: str, stmt: ast.CalibrationDefinition
+ self,
+ qubit_names: list[str],
+ name: str,
+ arguments: list[str],
+ stmt: ast.CalibrationDefinition,
) -> None:
"""Register a defcal defined in this program.
Defcals are added to the top of the program upon conversion to ast.
"""
- self.defcals[(tuple(qubit_names), name)] = stmt
+ self.defcals[(tuple(qubit_names), name, tuple(arguments))] = stmt
def _make_externs_statements(self, auto_encal: bool = False) -> list[ast.ExternDeclaration]:
"""Return a list of extern statements for inclusion at beginning of program.
diff --git a/oqpy/quantum_types.py b/oqpy/quantum_types.py
index 44c1a12..6ca4368 100644
--- a/oqpy/quantum_types.py
+++ b/oqpy/quantum_types.py
@@ -18,11 +18,13 @@
from __future__ import annotations
import contextlib
-from typing import TYPE_CHECKING, Iterator, Union
+from typing import TYPE_CHECKING, Iterator, Optional, Union
from openpulse import ast
+from openpulse.printer import dumps
-from oqpy.base import Var
+from oqpy.base import AstConvertible, Var, to_ast
+from oqpy.classical_types import _ClassicalVar
if TYPE_CHECKING:
from oqpy.program import Program
@@ -64,30 +66,57 @@ class QubitArray:
@contextlib.contextmanager
-def defcal(program: Program, qubits: Union[Qubit, list[Qubit]], name: str) -> Iterator[None]:
+def defcal(
+ program: Program,
+ qubits: Union[Qubit, list[Qubit]],
+ name: str,
+ arguments: Optional[list[AstConvertible]] = None,
+ return_type: Optional[ast.ClassicalType] = None,
+) -> Union[Iterator[None], Iterator[list[_ClassicalVar]], Iterator[_ClassicalVar]]:
"""Context manager for creating a defcal.
.. code-block:: python
- with defcal(program, q1, "X"):
+ with defcal(program, q1, "X", [AngleVar(name="theta"), oqpy.pi/2], oqpy.bit) as theta:
program.play(frame, waveform)
"""
- program._push()
- yield
- state = program._pop()
-
if isinstance(qubits, Qubit):
qubits = [qubits]
+ assert return_type is None or isinstance(return_type, ast.ClassicalType)
+
+ arguments_ast = []
+ variables = []
+ if arguments is not None:
+ for arg in arguments:
+ if isinstance(arg, _ClassicalVar):
+ arguments_ast.append(
+ ast.ClassicalArgument(type=arg.type, name=ast.Identifier(name=arg.name))
+ )
+ arg._needs_declaration = False
+ variables.append(arg)
+ else:
+ arguments_ast.append(to_ast(program, arg))
+
+ program._push()
+ if len(variables) > 1:
+ yield variables
+ elif len(variables) == 1:
+ yield variables[0]
+ else:
+ yield
+ state = program._pop()
stmt = ast.CalibrationDefinition(
ast.Identifier(name),
- [], # TODO (#52): support arguments
+ arguments_ast,
[ast.Identifier(q.name) for q in qubits],
- None, # TODO (#52): support return type,
+ return_type,
state.body,
)
program._add_statement(stmt)
- program._add_defcal([qubit.name for qubit in qubits], name, stmt)
+ program._add_defcal(
+ [qubit.name for qubit in qubits], name, [dumps(a) for a in arguments_ast], stmt
+ )
@contextlib.contextmanager
| openqasm/oqpy | 32cb438a101700af6c2b5c9be7d86d5ee2314ee6 | diff --git a/tests/test_directives.py b/tests/test_directives.py
index 24115ef..e10271e 100644
--- a/tests/test_directives.py
+++ b/tests/test_directives.py
@@ -22,6 +22,7 @@ import numpy as np
import pytest
from openpulse.printer import dumps
+import oqpy
from oqpy import *
from oqpy.base import expr_matches
from oqpy.quantum_types import PhysicalQubits
@@ -188,7 +189,10 @@ def test_binary_expressions():
i = IntVar(5, "i")
j = IntVar(2, "j")
prog.set(i, 2 * (i + j))
- prog.set(j, 2 % (2 + i) % 2)
+ prog.set(j, 2 % (2 - i) % 2)
+ prog.set(j, 1 + oqpy.pi)
+ prog.set(j, 1 / oqpy.pi**2 / 2 + 2**oqpy.pi)
+ prog.set(j, -oqpy.pi * oqpy.pi - i**j)
expected = textwrap.dedent(
"""
@@ -196,7 +200,10 @@ def test_binary_expressions():
int[32] i = 5;
int[32] j = 2;
i = 2 * (i + j);
- j = 2 % (2 + i) % 2;
+ j = 2 % (2 - i) % 2;
+ j = 1 + pi;
+ j = 1 / pi ** 2 / 2 + 2 ** pi;
+ j = -pi * pi - i ** j;
"""
).strip()
@@ -506,6 +513,154 @@ def test_set_shift_frequency():
assert prog.to_qasm() == expected
+def test_defcals():
+ prog = Program()
+ constant = declare_waveform_generator("constant", [("length", duration), ("iq", complex128)])
+
+ q_port = PortVar("q_port")
+ rx_port = PortVar("rx_port")
+ tx_port = PortVar("tx_port")
+ q_frame = FrameVar(q_port, 6.431e9, name="q_frame")
+ rx_frame = FrameVar(rx_port, 5.752e9, name="rx_frame")
+ tx_frame = FrameVar(tx_port, 5.752e9, name="tx_frame")
+
+ q1 = PhysicalQubits[1]
+ q2 = PhysicalQubits[2]
+
+ with defcal(prog, q2, "x"):
+ prog.play(q_frame, constant(1e-6, 0.1))
+
+ with defcal(prog, q2, "rx", [AngleVar(name="theta")]) as theta:
+ prog.increment(theta, 0.1)
+ prog.play(q_frame, constant(1e-6, 0.1))
+
+ with defcal(prog, q2, "rx", [pi / 3]):
+ prog.play(q_frame, constant(1e-6, 0.1))
+
+ with defcal(prog, [q1, q2], "xy", [AngleVar(name="theta"), +pi / 2]) as theta:
+ prog.increment(theta, 0.1)
+ prog.play(q_frame, constant(1e-6, 0.1))
+
+ with defcal(prog, [q1, q2], "xy", [AngleVar(name="theta"), FloatVar(name="phi"), 10]) as params:
+ theta, phi = params
+ prog.increment(theta, 0.1)
+ prog.increment(phi, 0.2)
+ prog.play(q_frame, constant(1e-6, 0.1))
+
+ with defcal(prog, q2, "readout", return_type=oqpy.bit):
+ prog.play(tx_frame, constant(2.4e-6, 0.2))
+ prog.capture(rx_frame, constant(2.4e-6, 1))
+
+ with pytest.raises(AssertionError):
+
+ with defcal(prog, q2, "readout", return_type=bool):
+ prog.play(tx_frame, constant(2.4e-6, 0.2))
+ prog.capture(rx_frame, constant(2.4e-6, 1))
+
+ expected = textwrap.dedent(
+ """
+ OPENQASM 3.0;
+ extern constant(duration, complex[float[64]]) -> waveform;
+ port rx_port;
+ port tx_port;
+ port q_port;
+ frame q_frame = newframe(q_port, 6431000000.0, 0);
+ frame tx_frame = newframe(tx_port, 5752000000.0, 0);
+ frame rx_frame = newframe(rx_port, 5752000000.0, 0);
+ defcal x $2 {
+ play(q_frame, constant(1000.0ns, 0.1));
+ }
+ defcal rx(angle[32] theta) $2 {
+ theta += 0.1;
+ play(q_frame, constant(1000.0ns, 0.1));
+ }
+ defcal rx(pi / 3) $2 {
+ play(q_frame, constant(1000.0ns, 0.1));
+ }
+ defcal xy(angle[32] theta, pi / 2) $1, $2 {
+ theta += 0.1;
+ play(q_frame, constant(1000.0ns, 0.1));
+ }
+ defcal xy(angle[32] theta, float[64] phi, 10) $1, $2 {
+ theta += 0.1;
+ phi += 0.2;
+ play(q_frame, constant(1000.0ns, 0.1));
+ }
+ defcal readout $2 -> bit {
+ play(tx_frame, constant(2400.0ns, 0.2));
+ capture(rx_frame, constant(2400.0ns, 1));
+ }
+ """
+ ).strip()
+ assert prog.to_qasm() == expected
+
+ expect_defcal_rx_theta = textwrap.dedent(
+ """
+ defcal rx(angle[32] theta) $2 {
+ theta += 0.1;
+ play(q_frame, constant(1000.0ns, 0.1));
+ }
+ """
+ ).strip()
+ assert (
+ dumps(prog.defcals[(("$2",), "rx", ("angle[32] theta",))], indent=" ").strip()
+ == expect_defcal_rx_theta
+ )
+ expect_defcal_rx_pio2 = textwrap.dedent(
+ """
+ defcal rx(pi / 3) $2 {
+ play(q_frame, constant(1000.0ns, 0.1));
+ }
+ """
+ ).strip()
+ assert (
+ dumps(prog.defcals[(("$2",), "rx", ("pi / 3",))], indent=" ").strip()
+ == expect_defcal_rx_pio2
+ )
+ expect_defcal_xy_theta_pio2 = textwrap.dedent(
+ """
+ defcal xy(angle[32] theta, pi / 2) $1, $2 {
+ theta += 0.1;
+ play(q_frame, constant(1000.0ns, 0.1));
+ }
+ """
+ ).strip()
+ assert (
+ dumps(
+ prog.defcals[(("$1", "$2"), "xy", ("angle[32] theta", "pi / 2"))], indent=" "
+ ).strip()
+ == expect_defcal_xy_theta_pio2
+ )
+ expect_defcal_xy_theta_phi = textwrap.dedent(
+ """
+ defcal xy(angle[32] theta, float[64] phi, 10) $1, $2 {
+ theta += 0.1;
+ phi += 0.2;
+ play(q_frame, constant(1000.0ns, 0.1));
+ }
+ """
+ ).strip()
+ assert (
+ dumps(
+ prog.defcals[(("$1", "$2"), "xy", ("angle[32] theta", "float[64] phi", "10"))],
+ indent=" ",
+ ).strip()
+ == expect_defcal_xy_theta_phi
+ )
+ expect_defcal_readout_q2 = textwrap.dedent(
+ """
+ defcal readout $2 -> bit {
+ play(tx_frame, constant(2400.0ns, 0.2));
+ capture(rx_frame, constant(2400.0ns, 1));
+ }
+ """
+ ).strip()
+ assert (
+ dumps(prog.defcals[(("$2",), "readout", ())], indent=" ").strip()
+ == expect_defcal_readout_q2
+ )
+
+
def test_ramsey_example():
prog = Program()
constant = declare_waveform_generator("constant", [("length", duration), ("iq", complex128)])
@@ -620,8 +775,11 @@ def test_ramsey_example():
).strip()
assert prog.to_qasm() == expected
- assert dumps(prog.defcals[(("$2",), "x90")], indent=" ").strip() == expect_defcal_x90_q2
- assert dumps(prog.defcals[(("$2",), "readout")], indent=" ").strip() == expect_defcal_readout_q2
+ assert dumps(prog.defcals[(("$2",), "x90", ())], indent=" ").strip() == expect_defcal_x90_q2
+ assert (
+ dumps(prog.defcals[(("$2",), "readout", ())], indent=" ").strip()
+ == expect_defcal_readout_q2
+ )
def test_rabi_example():
@@ -748,11 +906,11 @@ def test_program_add():
).strip()
assert (
- dumps(prog2.defcals[(("$1", "$2"), "two_qubit_gate")], indent=" ").strip()
+ dumps(prog2.defcals[(("$1", "$2"), "two_qubit_gate", ())], indent=" ").strip()
== expected_defcal_two_qubit_gate
)
assert (
- dumps(prog.defcals[(("$1", "$2"), "two_qubit_gate")], indent=" ").strip()
+ dumps(prog.defcals[(("$1", "$2"), "two_qubit_gate", ())], indent=" ").strip()
== expected_defcal_two_qubit_gate
)
| Support classical arguments and return types for defcals | 0.0 | [
"tests/test_directives.py::test_binary_expressions",
"tests/test_directives.py::test_defcals",
"tests/test_directives.py::test_ramsey_example",
"tests/test_directives.py::test_program_add"
] | [
"tests/test_directives.py::test_version_string",
"tests/test_directives.py::test_variable_declaration",
"tests/test_directives.py::test_complex_numbers_declaration",
"tests/test_directives.py::test_non_trivial_variable_declaration",
"tests/test_directives.py::test_variable_assignment",
"tests/test_directives.py::test_measure_reset",
"tests/test_directives.py::test_bare_if",
"tests/test_directives.py::test_if_else",
"tests/test_directives.py::test_for_in",
"tests/test_directives.py::test_while",
"tests/test_directives.py::test_create_frame",
"tests/test_directives.py::test_subroutine_with_return",
"tests/test_directives.py::test_box_and_timings",
"tests/test_directives.py::test_play_capture",
"tests/test_directives.py::test_set_shift_frequency",
"tests/test_directives.py::test_rabi_example",
"tests/test_directives.py::test_expression_convertible",
"tests/test_directives.py::test_waveform_extern_arg_passing",
"tests/test_directives.py::test_needs_declaration",
"tests/test_directives.py::test_discrete_waveform",
"tests/test_directives.py::test_var_and_expr_matches",
"tests/test_directives.py::test_program_tracks_frame_waveform_vars",
"tests/test_directives.py::test_make_duration",
"tests/test_directives.py::test_autoencal",
"tests/test_directives.py::test_ramsey_example_blog"
] | 2022-11-10 03:26:44+00:00 | 4,418 |
|
openshift__openshift-ansible-4543 | diff --git a/filter_plugins/openshift_version.py b/filter_plugins/openshift_version.py
new file mode 100644
index 000000000..1403e9dcc
--- /dev/null
+++ b/filter_plugins/openshift_version.py
@@ -0,0 +1,129 @@
+#!/usr/bin/python
+
+# -*- coding: utf-8 -*-
+# vim: expandtab:tabstop=4:shiftwidth=4
+"""
+Custom version comparison filters for use in openshift-ansible
+"""
+
+# pylint can't locate distutils.version within virtualenv
+# https://github.com/PyCQA/pylint/issues/73
+# pylint: disable=no-name-in-module, import-error
+from distutils.version import LooseVersion
+
+
+def legacy_gte_function_builder(name, versions):
+ """
+ Build and return a version comparison function.
+
+ Ex: name = 'oo_version_gte_3_1_or_1_1'
+ versions = {'enterprise': '3.1', 'origin': '1.1'}
+
+ returns oo_version_gte_3_1_or_1_1, a function which based on the
+ version and deployment type will return true if the provided
+ version is greater than or equal to the function's version
+ """
+ enterprise_version = versions['enterprise']
+ origin_version = versions['origin']
+
+ def _gte_function(version, deployment_type):
+ """
+ Dynamic function created by gte_function_builder.
+
+ Ex: version = '3.1'
+ deployment_type = 'openshift-enterprise'
+ returns True/False
+ """
+ version_gte = False
+ if 'enterprise' in deployment_type:
+ if str(version) >= LooseVersion(enterprise_version):
+ version_gte = True
+ elif 'origin' in deployment_type:
+ if str(version) >= LooseVersion(origin_version):
+ version_gte = True
+ return version_gte
+ _gte_function.__name__ = name
+ return _gte_function
+
+
+def gte_function_builder(name, gte_version):
+ """
+ Build and return a version comparison function.
+
+ Ex: name = 'oo_version_gte_3_6'
+ version = '3.6'
+
+ returns oo_version_gte_3_6, a function which based on the
+ version will return true if the provided version is greater
+ than or equal to the function's version
+ """
+ def _gte_function(version):
+ """
+ Dynamic function created by gte_function_builder.
+
+ Ex: version = '3.1'
+ returns True/False
+ """
+ version_gte = False
+ if str(version) >= LooseVersion(gte_version):
+ version_gte = True
+ return version_gte
+ _gte_function.__name__ = name
+ return _gte_function
+
+
+# pylint: disable=too-few-public-methods
+class FilterModule(object):
+ """
+ Filters for version checking.
+ """
+ # Each element of versions is composed of (major, minor_start, minor_end)
+ # Origin began versioning 3.x with 3.6, so begin 3.x with 3.6.
+ versions = [(3, 6, 10)]
+
+ def __init__(self):
+ """
+ Creates a new FilterModule for ose version checking.
+ """
+ self._filters = {}
+
+ # For each set of (major, minor, minor_iterations)
+ for major, minor_start, minor_end in self.versions:
+ # For each minor version in the range
+ for minor in range(minor_start, minor_end):
+ # Create the function name
+ func_name = 'oo_version_gte_{}_{}'.format(major, minor)
+ # Create the function with the builder
+ func = gte_function_builder(func_name, "{}.{}.0".format(major, minor))
+ # Add the function to the mapping
+ self._filters[func_name] = func
+
+ # Create filters with special versioning requirements.
+ # Treat all Origin 1.x as special case.
+ legacy_filters = [{'name': 'oo_version_gte_3_1_or_1_1',
+ 'versions': {'enterprise': '3.0.2.905',
+ 'origin': '1.1.0'}},
+ {'name': 'oo_version_gte_3_1_1_or_1_1_1',
+ 'versions': {'enterprise': '3.1.1',
+ 'origin': '1.1.1'}},
+ {'name': 'oo_version_gte_3_2_or_1_2',
+ 'versions': {'enterprise': '3.1.1.901',
+ 'origin': '1.2.0'}},
+ {'name': 'oo_version_gte_3_3_or_1_3',
+ 'versions': {'enterprise': '3.3.0',
+ 'origin': '1.3.0'}},
+ {'name': 'oo_version_gte_3_4_or_1_4',
+ 'versions': {'enterprise': '3.4.0',
+ 'origin': '1.4.0'}},
+ {'name': 'oo_version_gte_3_5_or_1_5',
+ 'versions': {'enterprise': '3.5.0',
+ 'origin': '1.5.0'}}]
+ for legacy_filter in legacy_filters:
+ self._filters[legacy_filter['name']] = legacy_gte_function_builder(legacy_filter['name'],
+ legacy_filter['versions'])
+
+ def filters(self):
+ """
+ Return the filters mapping.
+ """
+ return self._filters
| openshift/openshift-ansible | a23bf82b8f58b8e4d0ee57b16415b0a380d64d19 | diff --git a/test/openshift_version_tests.py b/test/openshift_version_tests.py
new file mode 100644
index 000000000..52e9a9888
--- /dev/null
+++ b/test/openshift_version_tests.py
@@ -0,0 +1,72 @@
+""" Tests for the openshift_version Ansible filter module. """
+# pylint: disable=missing-docstring,invalid-name
+
+import os
+import sys
+import unittest
+
+sys.path = [os.path.abspath(os.path.dirname(__file__) + "/../filter_plugins/")] + sys.path
+
+# pylint: disable=import-error
+import openshift_version # noqa: E402
+
+
+class OpenShiftVersionTests(unittest.TestCase):
+
+ openshift_version_filters = openshift_version.FilterModule()
+
+ # Static tests for legacy filters.
+ legacy_gte_tests = [{'name': 'oo_version_gte_3_1_or_1_1',
+ 'positive_enterprise_version': '3.2.0',
+ 'negative_enterprise_version': '3.0.0',
+ 'positive_origin_version': '1.2.0',
+ 'negative_origin_version': '1.0.0'},
+ {'name': 'oo_version_gte_3_1_1_or_1_1_1',
+ 'positive_enterprise_version': '3.2.0',
+ 'negative_enterprise_version': '3.1.0',
+ 'positive_origin_version': '1.2.0',
+ 'negative_origin_version': '1.1.0'},
+ {'name': 'oo_version_gte_3_2_or_1_2',
+ 'positive_enterprise_version': '3.3.0',
+ 'negative_enterprise_version': '3.1.0',
+ 'positive_origin_version': '1.3.0',
+ 'negative_origin_version': '1.1.0'},
+ {'name': 'oo_version_gte_3_3_or_1_3',
+ 'positive_enterprise_version': '3.4.0',
+ 'negative_enterprise_version': '3.2.0',
+ 'positive_origin_version': '1.4.0',
+ 'negative_origin_version': '1.2.0'},
+ {'name': 'oo_version_gte_3_4_or_1_4',
+ 'positive_enterprise_version': '3.5.0',
+ 'negative_enterprise_version': '3.3.0',
+ 'positive_origin_version': '1.5.0',
+ 'negative_origin_version': '1.3.0'},
+ {'name': 'oo_version_gte_3_5_or_1_5',
+ 'positive_enterprise_version': '3.6.0',
+ 'negative_enterprise_version': '3.4.0',
+ 'positive_origin_version': '1.6.0',
+ 'negative_origin_version': '1.4.0'}]
+
+ def test_legacy_gte_filters(self):
+ for test in self.legacy_gte_tests:
+ for deployment_type in ['enterprise', 'origin']:
+ # Test negative case per deployment_type
+ self.assertFalse(
+ self.openshift_version_filters._filters[test['name']](
+ test["negative_{}_version".format(deployment_type)], deployment_type))
+ # Test positive case per deployment_type
+ self.assertTrue(
+ self.openshift_version_filters._filters[test['name']](
+ test["positive_{}_version".format(deployment_type)], deployment_type))
+
+ def test_gte_filters(self):
+ for major, minor_start, minor_end in self.openshift_version_filters.versions:
+ for minor in range(minor_start, minor_end):
+ # Test positive case
+ self.assertTrue(
+ self.openshift_version_filters._filters["oo_version_gte_{}_{}".format(major, minor)](
+ "{}.{}".format(major, minor + 1)))
+ # Test negative case
+ self.assertFalse(
+ self.openshift_version_filters._filters["oo_version_gte_{}_{}".format(major, minor)](
+ "{}.{}".format(major, minor)))
| "template error while templating string: no filter named 'oo_version_gte_3_5_or_1_5'" when installing using release-1.5
When attempting to install using the `release-1.5` branch, I'm getting an error:
~~~
TASK [openshift_ca : Generate the loopback master client config] **********************************************************************************************
fatal: [openshift-master-2]: FAILED! => {"failed": true, "msg": "template error while templating string: no filter named 'oo_version_gte_3_5_or_1_5'. String: {{ hostvars[openshift_ca_host].openshift.common.client_binary
}} adm create-api-client-config\n {% for named_ca_certificate in openshift.master.named_certificates | default([]) | oo_collect('cafile') %}\n --certificate-authority {{ named_ca_certificate }}\n {% endfor %}\n --certificate-authority={{
openshift_ca_cert }}\n --client-dir={{ openshift_ca_config_dir }}\n --groups=system:masters,system:openshift-master\n --master={{ hostvars[openshift_ca_host].openshift.master.loopback_api_url }}\n --public-master={{ hostvars[openshift_ca_h
ost].openshift.master.loopback_api_url }}\n --signer-cert={{ openshift_ca_cert }}\n --signer-key={{ openshift_ca_key }}\n --signer-serial={{ openshift_ca_serial }}\n --user=system:openshift-master\n --basename=openshift-master\n {% if open
shift_version | oo_version_gte_3_5_or_1_5(openshift.common.deployment_type) | bool %}\n --expire-days={{ openshift_master_cert_expire_days }}\n {% endif %}"}
~~~
This seems to be because #4467 backported a change that used code from [filter_plugins/openshift_version.py](https://github.com/openshift/openshift-ansible/blob/402e8caa5bcbc22050bb4a4f189a802262ca725f/filter_plugins/openshift_version.py), which isn't in `release-1.5`. | 0.0 | [
"test/openshift_version_tests.py::OpenShiftVersionTests::test_gte_filters",
"test/openshift_version_tests.py::OpenShiftVersionTests::test_legacy_gte_filters"
] | [] | 2017-06-22 17:01:50+00:00 | 4,419 |
|
openshift__openshift-restclient-python-231 | diff --git a/.tito/packages/python-openshift b/.tito/packages/python-openshift
index f18cd6f..3f8c461 100644
--- a/.tito/packages/python-openshift
+++ b/.tito/packages/python-openshift
@@ -1,1 +1,1 @@
-0.6.2-12 ./
+0.8.0-1 ./
diff --git a/.tito/releasers.conf b/.tito/releasers.conf
index 2b4c815..f140a70 100644
--- a/.tito/releasers.conf
+++ b/.tito/releasers.conf
@@ -15,4 +15,4 @@ builder.test = 1
[asb-brew]
releaser = tito.release.DistGitReleaser
-branches = rhaos-3.11-asb-rhel-7
+branches = rhaos-4.0-asb-rhel-7
diff --git a/openshift/dynamic/client.py b/openshift/dynamic/client.py
index 5a51558..7bf55b5 100755
--- a/openshift/dynamic/client.py
+++ b/openshift/dynamic/client.py
@@ -517,10 +517,14 @@ class ResourceContainer(object):
on api_version, that resource will be returned.
"""
results = self.search(**kwargs)
+ # If there are multiple matches, prefer exact matches on api_version
if len(results) > 1 and kwargs.get('api_version'):
results = [
result for result in results if result.group_version == kwargs['api_version']
]
+ # If there are multiple matches, prefer non-List kinds
+ if len(results) > 1 and not all([isinstance(x, ResourceList) for x in results]):
+ results = [result for result in results if not isinstance(result, ResourceList)]
if len(results) == 1:
return results[0]
elif not results:
diff --git a/python-openshift.spec b/python-openshift.spec
index 221f5b6..12340a1 100644
--- a/python-openshift.spec
+++ b/python-openshift.spec
@@ -3,8 +3,8 @@
%global library openshift
Name: python-%{library}
-Version: 0.7.0
-Release: 12%{?dist}
+Version: 0.8.0
+Release: 1%{?dist}
Summary: Python client for the OpenShift API
License: MIT
URL: https://github.com/openshift/openshift-restclient-python
@@ -131,6 +131,28 @@ sed -i -e "s/extract_requirements('requirements.txt')/REQUIRES/g" setup.py
%endif # with_python3
%changelog
+* Tue Nov 06 2018 Jason Montleon <[email protected]> 0.8.0-1
+- Fix tag condition ([email protected])
+- Add watch to dynamic client (#221) ([email protected])
+- Pin flake8 ([email protected])
+- Do not decode response data in Python2 (#225)
+ ([email protected])
+- ResourceContainer does not contain delete method (#227)
+ ([email protected])
+- Add basic documentation for dynamic client verbs to README (#222)
+ ([email protected])
+- Add support for *List kinds (#213) ([email protected])
+- Add validate helper function (#199) ([email protected])
+- DynamicApiError: add a summary method (#211) ([email protected])
+- Allow less strict kubernetes version requirements (#207) ([email protected])
+- Add behavior-based tests for dynamic client (#208) ([email protected])
+- Provide 'append_hash' for ConfigMaps and Secrets (#196) ([email protected])
+- Allow creates on subresources properly (#201) ([email protected])
+- Rename async to async_req for compatibility with python3 and kubernetes 7
+ (#197) ([email protected])
+- Update kube_config to support concurrent clusters (#193)
+ ([email protected])
+
* Mon Aug 06 2018 David Zager <[email protected]> 0.6.2-12
- Fix decode issue (#192) ([email protected])
- b64encode expects bytes not string ([email protected])
| openshift/openshift-restclient-python | b52fc4a023fa662457723d245e82bfaa87842ccb | diff --git a/test/unit/test_resource_container.py b/test/unit/test_resource_container.py
new file mode 100644
index 0000000..5dd8657
--- /dev/null
+++ b/test/unit/test_resource_container.py
@@ -0,0 +1,82 @@
+import pytest
+
+from kubernetes.client import ApiClient
+
+from openshift.dynamic import DynamicClient, Resource, ResourceList
+
+
[email protected](scope='module')
+def mock_namespace():
+ return Resource(
+ api_version='v1',
+ kind='Namespace',
+ name='namespaces',
+ namespaced=False,
+ preferred=True,
+ prefix='api',
+ shorter_names=['ns'],
+ shortNames=['ns'],
+ singularName='namespace',
+ verbs=['create', 'delete', 'get', 'list', 'patch', 'update', 'watch']
+ )
+
+
[email protected](scope='module')
+def mock_namespace_list(mock_namespace):
+ return ResourceList(mock_namespace)
+
[email protected](scope='function', autouse=True)
+def setup_client_monkeypatch(monkeypatch, mock_namespace, mock_namespace_list):
+
+ def mock_load_server_info(self):
+ self.__version = {'kubernetes': 'mock-k8s-version'}
+
+ def mock_parse_api_groups(self):
+ return {
+ 'api': {
+ '': {
+ 'v1': {
+ 'Namespace': mock_namespace,
+ 'NamespaceList': mock_namespace_list
+ }
+ }
+ }
+ }
+
+ monkeypatch.setattr(DynamicClient, '_load_server_info', mock_load_server_info)
+ monkeypatch.setattr(DynamicClient, 'parse_api_groups', mock_parse_api_groups)
+
+
[email protected]()
+def client():
+ return DynamicClient(ApiClient())
+
+
[email protected](("attribute", "value"), [
+ ('name', 'namespaces'),
+ ('singular_name', 'namespace'),
+ ('short_names', ['ns'])
+])
+def test_search_returns_single_and_list(client, mock_namespace, mock_namespace_list, attribute, value):
+ resources = client.resources.search(**{'api_version':'v1', attribute: value})
+
+ assert len(resources) == 2
+ assert mock_namespace in resources
+ assert mock_namespace_list in resources
+
[email protected](("attribute", "value"), [
+ ('kind', 'Namespace'),
+ ('name', 'namespaces'),
+ ('singular_name', 'namespace'),
+ ('short_names', ['ns'])
+])
+def test_get_returns_only_single(client, mock_namespace, attribute, value):
+ resource = client.resources.get(**{'api_version':'v1', attribute: value})
+
+ assert resource == mock_namespace
+
+
+def test_get_namespace_list_kind(client, mock_namespace_list):
+ resource = client.resources.get(api_version='v1', kind='NamespaceList')
+
+ assert resource == mock_namespace_list
| openshift dynamic client is now case sensitive
Using `kind=namespace` (for example) used to work but no longer does
See https://github.com/ansible/ansible/issues/48137
This breaks backwards compatibility. | 0.0 | [
"test/unit/test_resource_container.py::test_get_returns_only_single[name-namespaces]",
"test/unit/test_resource_container.py::test_get_returns_only_single[singular_name-namespace]",
"test/unit/test_resource_container.py::test_get_returns_only_single[short_names-value3]"
] | [
"test/unit/test_resource_container.py::test_search_returns_single_and_list[name-namespaces]",
"test/unit/test_resource_container.py::test_search_returns_single_and_list[singular_name-namespace]",
"test/unit/test_resource_container.py::test_search_returns_single_and_list[short_names-value2]",
"test/unit/test_resource_container.py::test_get_returns_only_single[kind-Namespace]",
"test/unit/test_resource_container.py::test_get_namespace_list_kind"
] | 2018-11-06 15:16:03+00:00 | 4,420 |
|
openstack-charmers__zaza-36 | diff --git a/zaza/charm_lifecycle/prepare.py b/zaza/charm_lifecycle/prepare.py
index 0f0e436..00e6002 100644
--- a/zaza/charm_lifecycle/prepare.py
+++ b/zaza/charm_lifecycle/prepare.py
@@ -4,6 +4,22 @@ import subprocess
import sys
+MODEL_DEFAULTS = [
+ # Model defaults from charm-test-infra
+ # https://jujucharms.com/docs/2.1/models-config
+ '--config', 'agent-stream=proposed',
+ '--config', 'default-series=xenial',
+ '--config', 'image-stream=daily',
+ '--config', 'test-mode=true',
+ '--config', 'transmit-vendor-metrics=false',
+ # https://bugs.launchpad.net/juju/+bug/1685351
+ # enable-os-refresh-update: false
+ '--config', 'enable-os-upgrade=false',
+ '--config', 'automatically-retry-hooks=false',
+ '--config', 'use-default-secgroup=true',
+]
+
+
def add_model(model_name):
"""Add a model with the given name
@@ -11,7 +27,7 @@ def add_model(model_name):
:type bundle: str
"""
logging.info("Adding model {}".format(model_name))
- subprocess.check_call(['juju', 'add-model', model_name])
+ subprocess.check_call(['juju', 'add-model', model_name] + MODEL_DEFAULTS)
def prepare(model_name):
| openstack-charmers/zaza | fb5befcd3b2605c6894557a07414f17117e536df | diff --git a/unit_tests/test_zaza_charm_lifecycle_prepare.py b/unit_tests/test_zaza_charm_lifecycle_prepare.py
index 92ea511..510588b 100644
--- a/unit_tests/test_zaza_charm_lifecycle_prepare.py
+++ b/unit_tests/test_zaza_charm_lifecycle_prepare.py
@@ -8,7 +8,17 @@ class TestCharmLifecyclePrepare(ut_utils.BaseTestCase):
self.patch_object(lc_prepare.subprocess, 'check_call')
lc_prepare.add_model('newmodel')
self.check_call.assert_called_once_with(
- ['juju', 'add-model', 'newmodel'])
+ [
+ 'juju', 'add-model', 'newmodel',
+ '--config', 'agent-stream=proposed',
+ '--config', 'default-series=xenial',
+ '--config', 'image-stream=daily',
+ '--config', 'test-mode=true',
+ '--config', 'transmit-vendor-metrics=false',
+ '--config', 'enable-os-upgrade=false',
+ '--config', 'automatically-retry-hooks=false',
+ '--config', 'use-default-secgroup=true'
+ ])
def test_prepare(self):
self.patch_object(lc_prepare, 'add_model')
| models need to be in test mode and have hook retries disabled
Models which are created by Zaza should enable test mode, to prevent artificially ticking metrics in the charm store for charm usage.
The Zaza models should also disable retrying failed hooks, as we expect all charms to never enter a hook error state. The retry failed hooks feature is useful for users, but we do want to bail and fail if a charm ever enters an error state in a hook.
```
test-mode: true
transmit-vendor-metrics: false
automatically-retry-hooks: false
```
These, and other useful tuning from OSCI are here for example:
https://github.com/openstack-charmers/charm-test-infra/blob/master/juju-configs/model-default-serverstack.yaml
https://github.com/openstack-charmers/charm-test-infra/blob/master/juju-configs/controller-default.yaml
| 0.0 | [
"unit_tests/test_zaza_charm_lifecycle_prepare.py::TestCharmLifecyclePrepare::test_add_model"
] | [
"unit_tests/test_zaza_charm_lifecycle_prepare.py::TestCharmLifecyclePrepare::test_prepare",
"unit_tests/test_zaza_charm_lifecycle_prepare.py::TestCharmLifecyclePrepare::test_parser"
] | 2018-04-20 06:22:31+00:00 | 4,421 |
|
opsdroid__opsdroid-1660 | diff --git a/opsdroid/configuration/example_configuration.yaml b/opsdroid/configuration/example_configuration.yaml
index e73909f..c7e468d 100644
--- a/opsdroid/configuration/example_configuration.yaml
+++ b/opsdroid/configuration/example_configuration.yaml
@@ -37,6 +37,7 @@ welcome-message: true
## Configure the web server
# web:
# host: '127.0.0.1'
+# disable_web_index_handler_in_root: true
# port: 8080
# ssl:
# cert: /path/to/cert.pem
diff --git a/opsdroid/web.py b/opsdroid/web.py
index 1cb3cd3..00baa8a 100644
--- a/opsdroid/web.py
+++ b/opsdroid/web.py
@@ -34,8 +34,10 @@ class Web:
self.web_app = web.Application()
self.runner = web.AppRunner(self.web_app)
self.site = None
- self.web_app.router.add_get("/", self.web_index_handler)
- self.web_app.router.add_get("", self.web_index_handler)
+ if not self.config.get("disable_web_index_handler_in_root", False):
+ self.web_app.router.add_get("/", self.web_index_handler)
+ self.web_app.router.add_get("", self.web_index_handler)
+
self.web_app.router.add_get("/stats", self.web_stats_handler)
self.web_app.router.add_get("/stats/", self.web_stats_handler)
| opsdroid/opsdroid | e334a75243d27a5d2cb30db846a2c6ca427045d3 | diff --git a/opsdroid/tests/test_web.py b/opsdroid/tests/test_web.py
index b190dfb..4112d8a 100644
--- a/opsdroid/tests/test_web.py
+++ b/opsdroid/tests/test_web.py
@@ -38,6 +38,24 @@ async def test_web_get_host(opsdroid):
assert app.get_host == "127.0.0.1"
+async def test_web_disable_web_index_handler_in_root(opsdroid):
+ """Check disabling of web index handler in root."""
+ opsdroid.config["web"] = {"disable_web_index_handler_in_root": True}
+ app = web.Web(opsdroid)
+ canonicals = [resource.canonical for resource in app.web_app._router.resources()]
+ assert "/" not in canonicals
+
+ opsdroid.config["web"] = {"disable_web_index_handler_in_root": False}
+ app = web.Web(opsdroid)
+ canonicals = [resource.canonical for resource in app.web_app._router.resources()]
+ assert "/" in canonicals
+
+ opsdroid.config["web"] = {}
+ app = web.Web(opsdroid)
+ canonicals = [resource.canonical for resource in app.web_app._router.resources()]
+ assert "/" in canonicals
+
+
async def test_web_get_ssl(opsdroid):
"""Check the host getter."""
opsdroid.config["web"] = {}
| Add a config option to disable registering a route for /
In the web server by default a route is registered for the base / path. This should be configurable in case a user wants to register their own. | 0.0 | [
"opsdroid/tests/test_web.py::test_web_disable_web_index_handler_in_root"
] | [
"opsdroid/tests/test_web.py::test_web",
"opsdroid/tests/test_web.py::test_web_get_port",
"opsdroid/tests/test_web.py::test_web_get_host",
"opsdroid/tests/test_web.py::test_web_get_ssl",
"opsdroid/tests/test_web.py::test_web_build_response",
"opsdroid/tests/test_web.py::test_web_index_handler",
"opsdroid/tests/test_web.py::test_web_stats_handler",
"opsdroid/tests/test_web.py::test_web_start",
"opsdroid/tests/test_web.py::test_web_stop"
] | 2020-10-25 15:56:05+00:00 | 4,422 |
|
opsdroid__opsdroid-1888 | diff --git a/opsdroid/parsers/rasanlu.py b/opsdroid/parsers/rasanlu.py
index 2a896a5..07732a7 100644
--- a/opsdroid/parsers/rasanlu.py
+++ b/opsdroid/parsers/rasanlu.py
@@ -289,9 +289,18 @@ async def parse_rasanlu(opsdroid, skills, message, config):
if matcher["rasanlu_intent"] == result["intent"]["name"]:
message.rasanlu = result
for entity in result["entities"]:
- message.update_entity(
- entity["entity"], entity["value"], entity["confidence"]
- )
+ if "confidence_entity" in entity:
+ message.update_entity(
+ entity["entity"],
+ entity["value"],
+ entity["confidence_entity"],
+ )
+ elif "extractor" in entity:
+ message.update_entity(
+ entity["entity"],
+ entity["value"],
+ entity["extractor"],
+ )
matched_skills.append(
{
"score": confidence,
| opsdroid/opsdroid | 4ac4464910e1f67a67d6123aa366dde8beeb06f9 | diff --git a/tests/test_parser_rasanlu.py b/tests/test_parser_rasanlu.py
index 5af81bc..4b9053e 100644
--- a/tests/test_parser_rasanlu.py
+++ b/tests/test_parser_rasanlu.py
@@ -131,7 +131,7 @@ class TestParserRasaNLU(asynctest.TestCase):
"end": 32,
"entity": "state",
"extractor": "ner_crf",
- "confidence": 0.854,
+ "confidence_entity": 0.854,
"start": 25,
"value": "running",
}
@@ -175,7 +175,7 @@ class TestParserRasaNLU(asynctest.TestCase):
"value": "chinese",
"entity": "cuisine",
"extractor": "CRFEntityExtractor",
- "confidence": 0.854,
+ "confidence_entity": 0.854,
"processors": [],
}
],
@@ -190,6 +190,30 @@ class TestParserRasaNLU(asynctest.TestCase):
skill["message"].entities["cuisine"]["value"], "chinese"
)
+ with amock.patch.object(rasanlu, "call_rasanlu") as mocked_call_rasanlu:
+ mocked_call_rasanlu.return_value = {
+ "text": "show me chinese restaurants",
+ "intent": {"name": "restaurant_search", "confidence": 0.98343},
+ "entities": [
+ {
+ "start": 8,
+ "end": 15,
+ "value": "chinese",
+ "entity": "cuisine",
+ "extractor": "RegexEntityExtractor",
+ }
+ ],
+ }
+ [skill] = await rasanlu.parse_rasanlu(
+ opsdroid, opsdroid.skills, message, opsdroid.config["parsers"][0]
+ )
+
+ self.assertEqual(len(skill["message"].entities.keys()), 1)
+ self.assertTrue("cuisine" in skill["message"].entities.keys())
+ self.assertEqual(
+ skill["message"].entities["cuisine"]["value"], "chinese"
+ )
+
async def test_parse_rasanlu_raises(self):
with OpsDroid() as opsdroid:
opsdroid.config["parsers"] = [
@@ -215,7 +239,7 @@ class TestParserRasaNLU(asynctest.TestCase):
"end": 32,
"entity": "state",
"extractor": "ner_crf",
- "confidence": 0.854,
+ "confidence_entity": 0.854,
"start": 25,
"value": "running",
}
| KeyError: 'confidence'
<!-- Before you post an issue or if you are unsure about something join our matrix channel https://app.element.io/#/room/#opsdroid-general:matrix.org and ask away! We are more than happy to help you. -->
# Description
I am trying to build chatbot using opsdroid, matrix and rasanlu but I am not able to extract entities. getting following error: ```
entity["entity"], entity["value"], entity["confidence"]
KeyError: 'confidence'
```
## Expected Functionality
When user give message "Current price of GOOGLE" it should extract the entity [GOOG]
## Experienced Functionality
Getting `KeyEroor: 'confidence'`
## Versions
- **Opsdroid version:** v0.25.0
- **Python version:** 3.8.12
- **OS/Docker version:** 20.10.7
- **RASA version:** 2.8.1
## Configuration File
Please include your version of the configuration file below.
```
configuration.yaml
welcome-message: false
logging:
level: info
connectors:
matrix:
# Required
homeserver: $MATRIX_SERVER
mxid: $MATRIX_MXID
access_token: $MATRIX_TOKEN
device_name: "opsdroid"
enable_encryption: true
device_id: $DEVICE_ID # A unique string to use as an ID for a persistent opsdroid device
store_path: "/home/woyce-1-5/opsdroid/e2ee-keys" # Path to the directory where the matrix store will be saved
rooms:
main:
alias: $MATRIX_ROOM_MAIN
# Send messages as msgType: m.notice
send_m_notice: True
parsers:
rasanlu:
url: http://rasa:5005
#models-path: models
token: ###########
#min-score: 0.99999
min-score: 0.9999
skills:
fortune:
path: /skills/fortune
config:
mxid: $MATRIX_MXID
cmd_joke: '/home/opsdroid/.local/bin/fortune /skills/fortune/computers'
cmd_cookie: '/home/opsdroid/.local/bin/fortune /skills/fortune/cookies'
```
```
intents.yml
version: "2.0"
intents:
- greetings
- add
- bye
- tell_a_joke
- price:
use_entities:
- ticker
- add stock
entities:
- ticker
nlu:
- intent: greetings
examples: |
- Hii
- hi
- hey
- Hello
- Heya
- wassup
- intent: add
examples: |
- add stock AAPL for 9 days
- add stock MSFT 12 to monitor list
- add my stock GOOG 19
- add TSLA 14 days
- intent: Bye
examples: |
- Bye
- bie
- by
- see you
- see ya
- intent: tell_a_joke
examples: |
- Tell me a joke
- One more joke
- Do you know jokes
- Can you tell a joke
- Can you say something funny
- Would you entertain me
- What about a joke
- intent: this_is_funny
examples: |
- This is funny
- That's a funny one
- Hahaha
- That's a good one
- intent: price
examples: |
- current price of [TSLA]{"entity":"ticker"}
- tell me current price of [AMZN]{"entity":"ticker"}
- I want to know the current price of [NSRGY]{"entity":"ticker"}
- tell me about the current price of [AAPL]{"entity":"ticker"}```
## Additional Details
Any other details you wish to include such as screenshots, console messages, etc.
<!-- Love opsdroid? Please consider supporting our collective:
+👉 https://opencollective.com/opsdroid/donate -->

| 0.0 | [
"tests/test_parser_rasanlu.py::TestParserRasaNLU::test_parse_rasanlu",
"tests/test_parser_rasanlu.py::TestParserRasaNLU::test_parse_rasanlu_entities",
"tests/test_parser_rasanlu.py::TestParserRasaNLU::test_parse_rasanlu_raises"
] | [
"tests/test_parser_rasanlu.py::TestParserRasaNLU::test__build_status_url",
"tests/test_parser_rasanlu.py::TestParserRasaNLU::test__build_training_url",
"tests/test_parser_rasanlu.py::TestParserRasaNLU::test__get_all_intents",
"tests/test_parser_rasanlu.py::TestParserRasaNLU::test__get_all_intents_fails",
"tests/test_parser_rasanlu.py::TestParserRasaNLU::test__get_intents_fingerprint",
"tests/test_parser_rasanlu.py::TestParserRasaNLU::test__get_rasa_nlu_version",
"tests/test_parser_rasanlu.py::TestParserRasaNLU::test__init_model",
"tests/test_parser_rasanlu.py::TestParserRasaNLU::test__is_model_loaded",
"tests/test_parser_rasanlu.py::TestParserRasaNLU::test__load_model",
"tests/test_parser_rasanlu.py::TestParserRasaNLU::test_call_rasanlu",
"tests/test_parser_rasanlu.py::TestParserRasaNLU::test_call_rasanlu_bad_response",
"tests/test_parser_rasanlu.py::TestParserRasaNLU::test_call_rasanlu_raises",
"tests/test_parser_rasanlu.py::TestParserRasaNLU::test_has_compatible_version_rasanlu",
"tests/test_parser_rasanlu.py::TestParserRasaNLU::test_parse_rasanlu_failure",
"tests/test_parser_rasanlu.py::TestParserRasaNLU::test_parse_rasanlu_low_score",
"tests/test_parser_rasanlu.py::TestParserRasaNLU::test_parse_rasanlu_no_entity",
"tests/test_parser_rasanlu.py::TestParserRasaNLU::test_parse_rasanlu_no_intent",
"tests/test_parser_rasanlu.py::TestParserRasaNLU::test_parse_rasanlu_raise_ClientOSError",
"tests/test_parser_rasanlu.py::TestParserRasaNLU::test_train_rasanlu_fails",
"tests/test_parser_rasanlu.py::TestParserRasaNLU::test_train_rasanlu_succeeded"
] | 2022-02-11 08:53:21+00:00 | 4,423 |
|
orcasgit__python-nokia-28 | diff --git a/nokia/__init__.py b/nokia/__init__.py
index 007910a..9fcbf45 100644
--- a/nokia/__init__.py
+++ b/nokia/__init__.py
@@ -221,6 +221,10 @@ class NokiaApi(object):
r = self.request('sleep', 'get', params=kwargs, version='v2')
return NokiaSleep(r)
+ def get_sleep_summary(self, **kwargs):
+ r = self.request('sleep', 'getsummary', params=kwargs, version='v2')
+ return NokiaSleepSummary(r)
+
def subscribe(self, callback_url, comment, **kwargs):
params = {'callbackurl': callback_url, 'comment': comment}
params.update(kwargs)
@@ -319,3 +323,17 @@ class NokiaSleep(NokiaObject):
def __init__(self, data):
super(NokiaSleep, self).__init__(data)
self.series = [NokiaSleepSeries(series) for series in self.series]
+
+
+class NokiaSleepSummarySeries(NokiaObject):
+ def __init__(self, data):
+ _data = data
+ _data.update(_data.pop('data'))
+ super(NokiaSleepSummarySeries, self).__init__(_data)
+ self.timedelta = self.enddate - self.startdate
+
+
+class NokiaSleepSummary(NokiaObject):
+ def __init__(self, data):
+ super(NokiaSleepSummary, self).__init__(data)
+ self.series = [NokiaSleepSummarySeries(series) for series in self.series]
| orcasgit/python-nokia | fd4951da6bb51d2e2893339032207b96070c4c79 | diff --git a/tests/__init__.py b/tests/__init__.py
index 9a23d19..7824abd 100644
--- a/tests/__init__.py
+++ b/tests/__init__.py
@@ -9,6 +9,8 @@ from .test_nokia_measures import TestNokiaMeasures
from .test_nokia_object import TestNokiaObject
from .test_nokia_sleep import TestNokiaSleep
from .test_nokia_sleep_series import TestNokiaSleepSeries
+from .test_nokia_sleep_summary import TestNokiaSleepSummary
+from .test_nokia_sleep_summary_series import TestNokiaSleepSummarySeries
def all_tests():
@@ -22,4 +24,6 @@ def all_tests():
suite.addTest(unittest.makeSuite(TestNokiaObject))
suite.addTest(unittest.makeSuite(TestNokiaSleep))
suite.addTest(unittest.makeSuite(TestNokiaSleepSeries))
+ suite.addTest(unittest.makeSuite(TestNokiaSleepSummary))
+ suite.addTest(unittest.makeSuite(TestNokiaSleepSummarySeries))
return suite
diff --git a/tests/test_nokia_api.py b/tests/test_nokia_api.py
index a5b26f7..85848e4 100644
--- a/tests/test_nokia_api.py
+++ b/tests/test_nokia_api.py
@@ -11,7 +11,9 @@ from nokia import (
NokiaMeasureGroup,
NokiaMeasures,
NokiaSleep,
- NokiaSleepSeries
+ NokiaSleepSeries,
+ NokiaSleepSummary,
+ NokiaSleepSummarySeries,
)
try:
@@ -233,6 +235,70 @@ class TestNokiaApi(unittest.TestCase):
body['series'][0]['enddate'])
self.assertEqual(resp.series[1].state, 1)
+ def test_get_sleep_summary(self):
+ """
+ Check that get_sleep_summary fetches the appropriate URL, the response looks
+ correct, and the return value is a NokiaSleepSummary object with the
+ correct attributes
+ """
+ body = {
+ 'more': False,
+ 'series': [
+ {
+ 'data': {
+ 'deepsleepduration': 18660,
+ 'durationtosleep': 0,
+ 'durationtowakeup': 240,
+ 'lightsleepduration': 20220,
+ 'wakeupcount': 1,
+ 'wakeupduration': 720
+ },
+ 'date': '2018-10-30',
+ 'enddate': 1540897020,
+ 'id': 900363515,
+ 'model': 16,
+ 'modified': 1540897246,
+ 'startdate': 1540857420,
+ 'timezone': 'Europe/London'
+ },
+ {
+ 'data': {
+ 'deepsleepduration': 17040,
+ 'durationtosleep': 360,
+ 'durationtowakeup': 0,
+ 'lightsleepduration': 10860,
+ 'wakeupcount': 1,
+ 'wakeupduration': 540
+ },
+ 'date': '2018-10-31',
+ 'enddate': 1540973400,
+ 'id': 901269807,
+ 'model': 16,
+ 'modified': 1541020749,
+ 'startdate': 1540944960,
+ 'timezone': 'Europe/London'
+ }
+ ]
+ }
+ self.mock_request(body)
+ resp = self.api.get_sleep_summary()
+ Session.request.assert_called_once_with(
+ 'GET',
+ self._req_url('https://wbsapi.withings.net/v2/sleep'),
+ **self._req_kwargs({'action': 'getsummary'})
+ )
+ self.assertEqual(type(resp), NokiaSleepSummary)
+ self.assertEqual(type(resp.series), list)
+ self.assertEqual(len(resp.series), 2)
+ self.assertEqual(type(resp.series[0]), NokiaSleepSummarySeries)
+ self.assertEqual(resp.series[0].model, body['series'][0]['model'])
+ self.assertEqual(resp.series[0].startdate.timestamp,
+ body['series'][0]['startdate'])
+ self.assertEqual(resp.series[0].enddate.timestamp,
+ body['series'][0]['enddate'])
+ self.assertEqual(resp.series[0].deepsleepduration,
+ body['series'][0]['data']['deepsleepduration'])
+
def test_get_activities(self):
"""
Check that get_activities fetches the appropriate URL, the response
diff --git a/tests/test_nokia_sleep_summary.py b/tests/test_nokia_sleep_summary.py
new file mode 100644
index 0000000..40ea435
--- /dev/null
+++ b/tests/test_nokia_sleep_summary.py
@@ -0,0 +1,56 @@
+import time
+import unittest
+
+from nokia import NokiaSleepSummary, NokiaSleepSummarySeries
+
+
+class TestNokiaSleepSummary(unittest.TestCase):
+ def test_attributes(self):
+ data = {
+ 'more': False,
+ 'series': [
+ {
+ 'data': {
+ 'deepsleepduration': 18660,
+ 'durationtosleep': 0,
+ 'durationtowakeup': 240,
+ 'lightsleepduration': 20220,
+ 'wakeupcount': 1,
+ 'wakeupduration': 720
+ },
+ 'date': '2018-10-30',
+ 'enddate': 1540897020,
+ 'id': 900363515,
+ 'model': 16,
+ 'modified': 1540897246,
+ 'startdate': 1540857420,
+ 'timezone': 'Europe/London'
+ },
+ {
+ 'data': {
+ 'deepsleepduration': 17040,
+ 'durationtosleep': 360,
+ 'durationtowakeup': 0,
+ 'lightsleepduration': 10860,
+ 'wakeupcount': 1,
+ 'wakeupduration': 540
+ },
+ 'date': '2018-10-31',
+ 'enddate': 1540973400,
+ 'id': 901269807,
+ 'model': 16,
+ 'modified': 1541020749,
+ 'startdate': 1540944960,
+ 'timezone': 'Europe/London'
+ }
+ ]
+ }
+ sleep = NokiaSleepSummary(data)
+ self.assertEqual(sleep.series[0].model, data['series'][0]['model'])
+ self.assertEqual(type(sleep.series), list)
+ self.assertEqual(len(sleep.series), 2)
+ self.assertEqual(type(sleep.series[0]), NokiaSleepSummarySeries)
+ self.assertEqual(sleep.series[0].startdate.timestamp,
+ data['series'][0]['startdate'])
+ self.assertEqual(sleep.series[0].enddate.timestamp,
+ data['series'][0]['enddate'])
diff --git a/tests/test_nokia_sleep_summary_series.py b/tests/test_nokia_sleep_summary_series.py
new file mode 100644
index 0000000..83021cc
--- /dev/null
+++ b/tests/test_nokia_sleep_summary_series.py
@@ -0,0 +1,48 @@
+import time
+import unittest
+
+from datetime import timedelta
+from nokia import NokiaSleepSummarySeries
+
+
+class TestNokiaSleepSummarySeries(unittest.TestCase):
+ def test_attributes(self):
+ data = {
+ 'data': {
+ 'deepsleepduration': 18660,
+ 'durationtosleep': 0,
+ 'durationtowakeup': 240,
+ 'lightsleepduration': 20220,
+ 'wakeupcount': 1,
+ 'wakeupduration': 720,
+ },
+ 'date': '2018-10-30',
+ 'enddate': 1540897020,
+ 'id': 900363515,
+ 'model': 16,
+ 'modified': 1540897246,
+ 'startdate': 1540857420,
+ 'timezone': 'Europe/London',
+ }
+ flat_data = {
+ 'deepsleepduration': 18660,
+ 'durationtosleep': 0,
+ 'durationtowakeup': 240,
+ 'lightsleepduration': 20220,
+ 'wakeupcount': 1,
+ 'wakeupduration': 720,
+ 'date': '2018-10-30',
+ 'enddate': 1540897020,
+ 'id': 900363515,
+ 'model': 16,
+ 'modified': 1540897246,
+ 'startdate': 1540857420,
+ 'timezone': 'Europe/London',
+ }
+
+ series = NokiaSleepSummarySeries(data)
+ self.assertEqual(type(series), NokiaSleepSummarySeries)
+ self.assertEqual(series.startdate.timestamp, flat_data['startdate'])
+ self.assertEqual(series.data, flat_data)
+ self.assertEqual(series.enddate.timestamp, flat_data['enddate'])
+ self.assertEqual(series.timedelta, timedelta(seconds=39600))
| Add sleep summary API
We use this API in work, PR to follow. | 0.0 | [
"tests/__init__.py::TestNokiaActivity::test_attributes",
"tests/__init__.py::TestNokiaApi::test_attribute_defaults",
"tests/__init__.py::TestNokiaApi::test_attributes",
"tests/__init__.py::TestNokiaApi::test_get_activities",
"tests/__init__.py::TestNokiaApi::test_get_credentials",
"tests/__init__.py::TestNokiaApi::test_get_measures",
"tests/__init__.py::TestNokiaApi::test_get_measures_lastupdate_arrow",
"tests/__init__.py::TestNokiaApi::test_get_measures_lastupdate_date",
"tests/__init__.py::TestNokiaApi::test_get_measures_lastupdate_datetime",
"tests/__init__.py::TestNokiaApi::test_get_sleep",
"tests/__init__.py::TestNokiaApi::test_get_sleep_summary",
"tests/__init__.py::TestNokiaApi::test_get_user",
"tests/__init__.py::TestNokiaApi::test_is_subscribed",
"tests/__init__.py::TestNokiaApi::test_list_subscriptions",
"tests/__init__.py::TestNokiaApi::test_request",
"tests/__init__.py::TestNokiaApi::test_request_error",
"tests/__init__.py::TestNokiaApi::test_request_params",
"tests/__init__.py::TestNokiaApi::test_set_token",
"tests/__init__.py::TestNokiaApi::test_set_token_refresh_cb",
"tests/__init__.py::TestNokiaApi::test_subscribe",
"tests/__init__.py::TestNokiaApi::test_unsubscribe",
"tests/__init__.py::TestNokiaAuth::test_attributes",
"tests/__init__.py::TestNokiaAuth::test_get_authorize_url",
"tests/__init__.py::TestNokiaAuth::test_get_credentials",
"tests/__init__.py::TestNokiaAuth::test_migrate_from_oauth1",
"tests/__init__.py::TestNokiaCredentials::test_attribute_defaults",
"tests/__init__.py::TestNokiaCredentials::test_attributes",
"tests/__init__.py::TestNokiaMeasureGroup::test_attributes",
"tests/__init__.py::TestNokiaMeasureGroup::test_get_measure",
"tests/__init__.py::TestNokiaMeasureGroup::test_is_ambiguous",
"tests/__init__.py::TestNokiaMeasureGroup::test_is_measure",
"tests/__init__.py::TestNokiaMeasureGroup::test_is_target",
"tests/__init__.py::TestNokiaMeasureGroup::test_multigroup_types",
"tests/__init__.py::TestNokiaMeasureGroup::test_types",
"tests/__init__.py::TestNokiaMeasures::test_nokia_measures_init",
"tests/__init__.py::TestNokiaObject::test_attributes",
"tests/__init__.py::TestNokiaSleep::test_attributes",
"tests/__init__.py::TestNokiaSleepSeries::test_attributes",
"tests/__init__.py::TestNokiaSleepSummary::test_attributes",
"tests/__init__.py::TestNokiaSleepSummarySeries::test_attributes",
"tests/test_nokia_api.py::TestNokiaApi::test_attribute_defaults",
"tests/test_nokia_api.py::TestNokiaApi::test_attributes",
"tests/test_nokia_api.py::TestNokiaApi::test_get_activities",
"tests/test_nokia_api.py::TestNokiaApi::test_get_credentials",
"tests/test_nokia_api.py::TestNokiaApi::test_get_measures",
"tests/test_nokia_api.py::TestNokiaApi::test_get_measures_lastupdate_arrow",
"tests/test_nokia_api.py::TestNokiaApi::test_get_measures_lastupdate_date",
"tests/test_nokia_api.py::TestNokiaApi::test_get_measures_lastupdate_datetime",
"tests/test_nokia_api.py::TestNokiaApi::test_get_sleep",
"tests/test_nokia_api.py::TestNokiaApi::test_get_sleep_summary",
"tests/test_nokia_api.py::TestNokiaApi::test_get_user",
"tests/test_nokia_api.py::TestNokiaApi::test_is_subscribed",
"tests/test_nokia_api.py::TestNokiaApi::test_list_subscriptions",
"tests/test_nokia_api.py::TestNokiaApi::test_request",
"tests/test_nokia_api.py::TestNokiaApi::test_request_error",
"tests/test_nokia_api.py::TestNokiaApi::test_request_params",
"tests/test_nokia_api.py::TestNokiaApi::test_set_token",
"tests/test_nokia_api.py::TestNokiaApi::test_set_token_refresh_cb",
"tests/test_nokia_api.py::TestNokiaApi::test_subscribe",
"tests/test_nokia_api.py::TestNokiaApi::test_unsubscribe",
"tests/test_nokia_sleep_summary.py::TestNokiaSleepSummary::test_attributes",
"tests/test_nokia_sleep_summary_series.py::TestNokiaSleepSummarySeries::test_attributes"
] | [] | 2018-11-01 14:47:31+00:00 | 4,424 |
|
osantana__dicteval-13 | diff --git a/README.rst b/README.rst
index 2b11f85..a815a98 100644
--- a/README.rst
+++ b/README.rst
@@ -48,6 +48,17 @@ Functions
You can use the following builtin functions in your expressions:
+Function ``=any``
+'''''''''''''''''
+
+Returns ``True`` if any element of sequence is true.
+
+ >>> dicteval({"=any", [1, 2, 3]})
+ True
+ >>> dicteval({"=any", [0, 0]})
+ False
+
+
Function ``=eq``
''''''''''''''''
@@ -109,6 +120,16 @@ Returns a number with the product of arguments:
>>> dicteval({"=mul": [3, 5]})
15
+Function ``=all``
+'''''''''''''''''
+
+Return True if all elements of the iterable are true (or if the iterable is empty)
+
+ >>> dicteval({"=mul": (True, False)})
+ False
+ >>> dicteval({"=mul": (True, True)})
+ True
+
To Do
-----
diff --git a/dicteval/__init__.py b/dicteval/__init__.py
index 5978b4e..57602cc 100644
--- a/dicteval/__init__.py
+++ b/dicteval/__init__.py
@@ -16,6 +16,9 @@ class LanguageSpecification:
class BuiltinLanguage(LanguageSpecification):
+ def function_any(self, value, evaluator, context):
+ return any([evaluator(v, context) for v in value])
+
def function_eq(self, value, evaluator, context):
value = [evaluator(v, context) for v in value]
return not value or value.count(value[0]) == len(value)
@@ -35,6 +38,9 @@ class BuiltinLanguage(LanguageSpecification):
def function_mul(self, value, evaluator, context):
return functools.reduce(operator.mul, (evaluator(v, context) for v in value))
+ def function_all(self, value, evaluator, context):
+ return all(evaluator(v, context) for v in value)
+
class Evaluator:
def __init__(self, language_spec):
| osantana/dicteval | 5e1970132fd7a6ac55785648a89cf2e3e2131965 | diff --git a/tests/test_eval.py b/tests/test_eval.py
index 98ca542..b1bdadd 100644
--- a/tests/test_eval.py
+++ b/tests/test_eval.py
@@ -17,6 +17,9 @@ from dicteval.exceptions import FunctionNotFound
({"=sum": (3, 5)}, 8),
({"=sum": {"=": [3, 5]}}, 8),
({"=mul": (5, 3, 2, -1)}, -30),
+ ({"=all": (True, True, True)}, True),
+ ({"=all": (True, False, True)}, False),
+ ({"=all": (False, False, False)}, False),
])
def test_basic_eval(expression, result):
assert dicteval(expression) == result
@@ -36,6 +39,8 @@ def test_json_loads():
@pytest.mark.parametrize("fn,args,result", [
+ ("any", (1, 2, 3), True),
+ ("any", (0, 0), False),
("eq", (1, 1, 1, 1, 1), True),
("eq", (1, 1, 5, 1, 1), False),
("neq", (1, 1, 1, 1, 1), False),
@@ -45,6 +50,9 @@ def test_json_loads():
("not", False, True),
("sum", (1, 2), 3),
("mul", (2, 4), 8),
+ ("all", tuple(), True),
+ ("all", (True, True), True),
+ ("all", (True, False), False),
])
def test_buitin_language(fn, args, result, context):
language = BuiltinLanguage()
| Implement and document builtin function: =all
Equivalent to the Python's builtin. | 0.0 | [
"tests/test_eval.py::test_basic_eval[expression12-True]",
"tests/test_eval.py::test_basic_eval[expression13-False]",
"tests/test_eval.py::test_basic_eval[expression14-False]",
"tests/test_eval.py::test_buitin_language[any-args0-True]",
"tests/test_eval.py::test_buitin_language[any-args1-False]",
"tests/test_eval.py::test_buitin_language[all-args11-True]",
"tests/test_eval.py::test_buitin_language[all-args12-True]",
"tests/test_eval.py::test_buitin_language[all-args13-False]"
] | [
"tests/test_eval.py::test_basic_eval[3-3]",
"tests/test_eval.py::test_basic_eval[expression1-result1]",
"tests/test_eval.py::test_basic_eval[expression2-result2]",
"tests/test_eval.py::test_basic_eval[expression3-result3]",
"tests/test_eval.py::test_basic_eval[x-x]",
"tests/test_eval.py::test_basic_eval[expression5-3]",
"tests/test_eval.py::test_basic_eval[expression6-result6]",
"tests/test_eval.py::test_basic_eval[expression7-3]",
"tests/test_eval.py::test_basic_eval[expression8-8]",
"tests/test_eval.py::test_basic_eval[expression9-8]",
"tests/test_eval.py::test_basic_eval[expression10-8]",
"tests/test_eval.py::test_basic_eval[expression11--30]",
"tests/test_eval.py::test_context_eval",
"tests/test_eval.py::test_invalid_expression_object_with_no_result_key",
"tests/test_eval.py::test_json_loads",
"tests/test_eval.py::test_buitin_language[eq-args2-True]",
"tests/test_eval.py::test_buitin_language[eq-args3-False]",
"tests/test_eval.py::test_buitin_language[neq-args4-False]",
"tests/test_eval.py::test_buitin_language[neq-args5-True]",
"tests/test_eval.py::test_buitin_language[nop-4-4]",
"tests/test_eval.py::test_buitin_language[not-True-False]",
"tests/test_eval.py::test_buitin_language[not-False-True]",
"tests/test_eval.py::test_buitin_language[sum-args9-3]",
"tests/test_eval.py::test_buitin_language[mul-args10-8]",
"tests/test_eval.py::test_function_not_found_error"
] | 2018-10-02 03:15:00+00:00 | 4,425 |
|
osbuild__osbuild-107 | diff --git a/.travis.yml b/.travis.yml
index 7aac0cc3..0dd5c85c 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -21,8 +21,8 @@ jobs:
- name: pipeline-noop
before_install: sudo apt-get install -y systemd-container
script:
- - sudo env "PATH=$PATH" python3 -m osbuild --libdir . --output . samples/noop.json
- - sudo env "PATH=$PATH" python3 -m osbuild --libdir . --output . samples/noop.json
+ - sudo env "PATH=$PATH" python3 -m osbuild --libdir . samples/noop.json
+ - sudo env "PATH=$PATH" python3 -m osbuild --libdir . samples/noop.json
- name: f30-boot
before_install: sudo apt-get install -y systemd-container yum qemu-kvm
script: sudo env "PATH=$PATH" python3 -m test --case f30-boot --build-pipeline samples/build-from-yum.json
diff --git a/README.md b/README.md
index 4a7a390f..f2df5d28 100644
--- a/README.md
+++ b/README.md
@@ -70,7 +70,7 @@ The above pipeline has no base and produces a qcow2 image.
```
usage: python3 -m osbuild [-h] [--build-pipeline PIPELINE] [--store DIRECTORY]
- [-l DIRECTORY] -o DIRECTORY
+ [-l DIRECTORY]
PIPELINE
Build operating system images
@@ -87,11 +87,6 @@ optional arguments:
-l DIRECTORY, --libdir DIRECTORY
the directory containing stages, assemblers, and the
osbuild library
-
-required named arguments:
- -o DIRECTORY, --output DIRECTORY
- provide the empty DIRECTORY as output argument to the
- last stage
```
### Running example
@@ -99,7 +94,7 @@ required named arguments:
You can build basic qcow2 image of Fedora 30 by running a following command:
```
-sudo python3 -m osbuild -o output --libdir . samples/base-qcow2.json
+sudo python3 -m osbuild --libdir . samples/base-qcow2.json
```
- Root rights are required because osbuild heavily relies on creating
diff --git a/osbuild/__main__.py b/osbuild/__main__.py
index 8b3481b7..b929f863 100755
--- a/osbuild/__main__.py
+++ b/osbuild/__main__.py
@@ -21,9 +21,8 @@ def main():
help="the directory where intermediary os trees are stored")
parser.add_argument("-l", "--libdir", metavar="DIRECTORY", type=os.path.abspath,
help="the directory containing stages, assemblers, and the osbuild library")
- requiredNamed = parser.add_argument_group('required named arguments')
- requiredNamed.add_argument("-o", "--output", dest="output_dir", metavar="DIRECTORY", type=os.path.abspath,
- help="provide the empty DIRECTORY as output argument to the last stage", required=True)
+ parser.add_argument("--json", action="store_true",
+ help="output results in JSON format")
args = parser.parse_args()
with open(args.pipeline_path) as f:
@@ -35,16 +34,27 @@ def main():
pipeline.prepend_build_pipeline(build)
try:
- pipeline.run(args.output_dir, args.store, interactive=True, libdir=args.libdir)
+ pipeline.run(args.store, interactive=not args.json, libdir=args.libdir)
except KeyboardInterrupt:
print()
print(f"{RESET}{BOLD}{RED}Aborted{RESET}")
- sys.exit(130)
+ return 130
except (osbuild.StageFailed, osbuild.AssemblerFailed) as error:
print()
print(f"{RESET}{BOLD}{RED}{error.name} failed with code {error.returncode}{RESET}")
- sys.exit(1)
+ if args.json:
+ print(error.output)
+ return 1
+
+ if args.json:
+ json.dump({
+ "tree_id": pipeline.tree_id,
+ "output_id": pipeline.output_id,
+ }, sys.stdout)
+ sys.stdout.write("\n")
+
+ return 0
if __name__ == "__main__":
- main()
+ sys.exit(main())
diff --git a/osbuild/objectstore.py b/osbuild/objectstore.py
index ea726277..eaf73d53 100644
--- a/osbuild/objectstore.py
+++ b/osbuild/objectstore.py
@@ -13,6 +13,19 @@ __all__ = [
]
[email protected]
+def suppress_oserror(*errnos):
+ """A context manager that suppresses any OSError with an errno in `errnos`.
+
+ Like contextlib.suppress, but can differentiate between OSErrors.
+ """
+ try:
+ yield
+ except OSError as e:
+ if e.errno not in errnos:
+ raise e
+
+
class ObjectStore:
def __init__(self, store):
self.store = store
@@ -22,29 +35,35 @@ class ObjectStore:
os.makedirs(self.objects, exist_ok=True)
os.makedirs(self.refs, exist_ok=True)
- def has_tree(self, tree_id):
- if not tree_id:
+ def contains(self, object_id):
+ if not object_id:
return False
- return os.access(f"{self.refs}/{tree_id}", os.F_OK)
+ return os.access(f"{self.refs}/{object_id}", os.F_OK)
@contextlib.contextmanager
- def get_tree(self, tree_id):
+ def get(self, object_id):
with tempfile.TemporaryDirectory(dir=self.store) as tmp:
- if tree_id:
- subprocess.run(["mount", "-o", "bind,ro,mode=0755", f"{self.refs}/{tree_id}", tmp], check=True)
+ if object_id:
+ subprocess.run(["mount", "-o", "bind,ro,mode=0755", f"{self.refs}/{object_id}", tmp], check=True)
try:
yield tmp
finally:
subprocess.run(["umount", "--lazy", tmp], check=True)
else:
- # None was given as tree_id, just return an empty directory
+ # None was given as object_id, just return an empty directory
yield tmp
@contextlib.contextmanager
- def new_tree(self, tree_id, base_id=None):
+ def new(self, object_id, base_id=None):
+ """Creates a new directory for `object_id`.
+
+ This method must be used as a context manager. It returns a path to a
+ temporary directory and only commits it when the context completes
+ without raising an exception.
+ """
with tempfile.TemporaryDirectory(dir=self.store) as tmp:
# the tree that is yielded will be added to the content store
- # on success as tree_id
+ # on success as object_id
tree = f"{tmp}/tree"
link = f"{tmp}/link"
@@ -68,20 +87,18 @@ class ObjectStore:
finally:
os.close(fd)
# the tree is stored in the objects directory using its content
- # hash as its name, ideally a given tree_id (i.e., given config)
+ # hash as its name, ideally a given object_id (i.e., given config)
# will always produce the same content hash, but that is not
# guaranteed
output_tree = f"{self.objects}/{treesum_hash}"
- try:
+
+ # if a tree with the same treesum already exist, use that
+ with suppress_oserror(errno.ENOTEMPTY):
os.rename(tree, output_tree)
- except OSError as e:
- if e.errno == errno.ENOTEMPTY:
- pass # tree with the same content hash already exist, use that
- else:
- raise
- # symlink the tree_id (config hash) in the refs directory to the treesum
- # (content hash) in the objects directory. If a symlink by that name
- # alreday exists, atomically replace it, but leave the backing object
- # in place (it may be in use).
+
+ # symlink the object_id (config hash) in the refs directory to the
+ # treesum (content hash) in the objects directory. If a symlink by
+ # that name alreday exists, atomically replace it, but leave the
+ # backing object in place (it may be in use).
os.symlink(f"../objects/{treesum_hash}", link)
- os.replace(link, f"{self.refs}/{tree_id}")
+ os.replace(link, f"{self.refs}/{object_id}")
diff --git a/osbuild/pipeline.py b/osbuild/pipeline.py
index 13057bab..ee6a4a4a 100644
--- a/osbuild/pipeline.py
+++ b/osbuild/pipeline.py
@@ -38,16 +38,20 @@ def print_header(title, options):
class Stage:
def __init__(self, name, build, base, options):
- m = hashlib.sha256()
- m.update(json.dumps(name, sort_keys=True).encode())
- m.update(json.dumps(build, sort_keys=True).encode())
- m.update(json.dumps(base, sort_keys=True).encode())
- m.update(json.dumps(options, sort_keys=True).encode())
-
- self.id = m.hexdigest()
self.name = name
+ self.build = build
+ self.base = base
self.options = options
+ @property
+ def id(self):
+ m = hashlib.sha256()
+ m.update(json.dumps(self.name, sort_keys=True).encode())
+ m.update(json.dumps(self.build, sort_keys=True).encode())
+ m.update(json.dumps(self.base, sort_keys=True).encode())
+ m.update(json.dumps(self.options, sort_keys=True).encode())
+ return m.hexdigest()
+
def description(self):
description = {}
description["name"] = self.name
@@ -78,18 +82,25 @@ class Stage:
if check and r.returncode != 0:
raise StageFailed(self.name, r.returncode, r.stdout)
- return {
- "name": self.name,
- "returncode": r.returncode,
- "output": r.stdout
- }
+ return r.returncode == 0
class Assembler:
- def __init__(self, name, options):
+ def __init__(self, name, build, base, options):
self.name = name
+ self.build = build
+ self.base = base
self.options = options
+ @property
+ def id(self):
+ m = hashlib.sha256()
+ m.update(json.dumps(self.name, sort_keys=True).encode())
+ m.update(json.dumps(self.build, sort_keys=True).encode())
+ m.update(json.dumps(self.base, sort_keys=True).encode())
+ m.update(json.dumps(self.options, sort_keys=True).encode())
+ return m.hexdigest()
+
def description(self):
description = {}
description["name"] = self.name
@@ -100,7 +111,7 @@ class Assembler:
def run(self, tree, build_tree, output_dir=None, interactive=False, check=True, libdir=None):
with buildroot.BuildRoot(build_tree) as build_root:
if interactive:
- print_header(f"Assembling: {self.name}", self.options)
+ print_header(f"Assembler {self.name}: {self.id}", self.options)
args = {
"tree": "/run/osbuild/tree",
@@ -127,11 +138,7 @@ class Assembler:
if check and r.returncode != 0:
raise AssemblerFailed(self.name, r.returncode, r.stdout)
- return {
- "name": self.name,
- "returncode": r.returncode,
- "output": r.stdout
- }
+ return r.returncode == 0
class Pipeline:
@@ -140,16 +147,24 @@ class Pipeline:
self.stages = []
self.assembler = None
- def get_id(self):
+ @property
+ def tree_id(self):
return self.stages[-1].id if self.stages else None
+ @property
+ def output_id(self):
+ return self.assembler.id if self.assembler else None
+
def add_stage(self, name, options=None):
- build = self.build.get_id() if self.build else None
- stage = Stage(name, build, self.get_id(), options or {})
+ build = self.build.tree_id if self.build else None
+ stage = Stage(name, build, self.tree_id, options or {})
self.stages.append(stage)
+ if self.assembler:
+ self.assembler.base = stage.id
def set_assembler(self, name, options=None):
- self.assembler = Assembler(name, options or {})
+ build = self.build.tree_id if self.build else None
+ self.assembler = Assembler(name, build, self.tree_id, options or {})
def prepend_build_pipeline(self, build):
pipeline = self
@@ -170,7 +185,7 @@ class Pipeline:
@contextlib.contextmanager
def get_buildtree(self, object_store):
if self.build:
- with object_store.get_tree(self.build.get_id()) as tree:
+ with object_store.get(self.build.tree_id) as tree:
yield tree
else:
with tempfile.TemporaryDirectory(dir=object_store.store) as tmp:
@@ -180,28 +195,22 @@ class Pipeline:
finally:
subprocess.run(["umount", "--lazy", tmp], check=True)
- def run(self, output_dir, store, interactive=False, check=True, libdir=None):
+ def run(self, store, interactive=False, check=True, libdir=None):
os.makedirs("/run/osbuild", exist_ok=True)
object_store = objectstore.ObjectStore(store)
- results = {
- "stages": []
- }
if self.build:
- r = self.build.run(None, store, interactive, check, libdir)
- results["build"] = r
- if r["returncode"] != 0:
- results["returncode"] = r["returncode"]
- return results
+ if not self.build.run(store, interactive, check, libdir):
+ return False
with self.get_buildtree(object_store) as build_tree:
if self.stages:
- if not object_store.has_tree(self.get_id()):
+ if not object_store.contains(self.tree_id):
# Find the last stage that already exists in the object store, and use
# that as the base.
base = None
base_idx = -1
for i in reversed(range(len(self.stages))):
- if object_store.has_tree(self.stages[i].id):
+ if object_store.contains(self.stages[i].id):
base = self.stages[i].id
base_idx = i
break
@@ -210,33 +219,27 @@ class Pipeline:
# is nondeterministic which of them will end up referenced by the tree_id
# in the content store. However, we guarantee that all tree_id's and all
# generated trees remain valid.
- with object_store.new_tree(self.get_id(), base_id=base) as tree:
+ with object_store.new(self.tree_id, base_id=base) as tree:
for stage in self.stages[base_idx + 1:]:
- r = stage.run(tree,
- build_tree,
- interactive=interactive,
- check=check,
- libdir=libdir)
- results["stages"].append(r)
- if r["returncode"] != 0:
- results["returncode"] = r["returncode"]
- return results
-
- if self.assembler:
- with object_store.get_tree(self.get_id()) as tree:
- r = self.assembler.run(tree,
- build_tree,
- output_dir=output_dir,
- interactive=interactive,
- check=check,
- libdir=libdir)
- results["assembler"] = r
- if r["returncode"] != 0:
- results["returncode"] = r["returncode"]
- return results
-
- results["returncode"] = 0
- return results
+ if not stage.run(tree,
+ build_tree,
+ interactive=interactive,
+ check=check,
+ libdir=libdir):
+ return False
+
+ if self.assembler and not object_store.contains(self.output_id):
+ with object_store.get(self.tree_id) as tree, \
+ object_store.new(self.output_id) as output_dir:
+ if not self.assembler.run(tree,
+ build_tree,
+ output_dir=output_dir,
+ interactive=interactive,
+ check=check,
+ libdir=libdir):
+ return False
+
+ return True
def load(description):
| osbuild/osbuild | 56a25adf7f02060f86735be1c6e1652be916493b | diff --git a/test/__main__.py b/test/__main__.py
index 1df003a3..4e14ca62 100644
--- a/test/__main__.py
+++ b/test/__main__.py
@@ -43,7 +43,6 @@ if __name__ == '__main__':
args = parser.parse_args()
logging.info(f"Using {OBJECTS} for objects storage.")
- logging.info(f"Using {OUTPUT_DIR} for output images storage.")
logging.info(f"Using {OSBUILD} for building images.")
f30_boot = IntegrationTestCase(
diff --git a/test/integration_tests/build.py b/test/integration_tests/build.py
index f8802086..38084dc4 100644
--- a/test/integration_tests/build.py
+++ b/test/integration_tests/build.py
@@ -1,3 +1,4 @@
+import json
import logging
import subprocess
import sys
@@ -5,8 +6,8 @@ import sys
from .config import *
-def run_osbuild(pipeline: str, build_pipeline: str, check=True):
- cmd = OSBUILD + ["--store", OBJECTS, "-o", OUTPUT_DIR, pipeline]
+def run_osbuild(pipeline: str, build_pipeline: str):
+ cmd = OSBUILD + ["--json", "--store", OBJECTS, pipeline]
if build_pipeline:
cmd += ["--build-pipeline", build_pipeline]
logging.info(f"Running osbuild: {cmd}")
@@ -17,10 +18,10 @@ def run_osbuild(pipeline: str, build_pipeline: str, check=True):
print(osbuild.stderr.decode())
print(f"{BOLD}STDOUT{RESET}")
print(osbuild.stdout.decode())
- if check:
- sys.exit(1)
+ sys.exit(1)
- return osbuild.returncode
+ result = json.loads(osbuild.stdout.decode())
+ return result["tree_id"], result.get("output_id")
def build_testing_image(pipeline_full_path, build_pipeline_full_path):
diff --git a/test/integration_tests/config.py b/test/integration_tests/config.py
index 9f57ee9c..b956e500 100644
--- a/test/integration_tests/config.py
+++ b/test/integration_tests/config.py
@@ -7,5 +7,4 @@ RESET = "\033[0m"
BOLD = "\033[1m"
RED = "\033[31m"
OBJECTS = os.environ.get("OBJECTS", ".osbuild-test")
-OUTPUT_DIR = os.environ.get("OUTPUT_DIR", "output-test")
OSBUILD = os.environ.get("OSBUILD", "python3 -m osbuild --libdir .").split(' ')
diff --git a/test/integration_tests/run.py b/test/integration_tests/run.py
index 7b04e469..0a87a762 100644
--- a/test/integration_tests/run.py
+++ b/test/integration_tests/run.py
@@ -11,7 +11,7 @@ def run_image(file_name: str):
silence = ["-nographic", "-monitor", "none", "-serial", "none"]
serial = ["-chardev", "stdio,id=stdio", "-device", "virtio-serial", "-device", "virtserialport,chardev=stdio"]
cmd = ["qemu-system-x86_64", "-m", "1024", "-snapshot"] + \
- acceleration + silence + serial + [f"{OUTPUT_DIR}/{file_name}"]
+ acceleration + silence + serial + [file_name]
logging.info(f"Booting image: {cmd}")
return subprocess.run(cmd, capture_output=True, timeout=EXPECTED_TIME_TO_BOOT, encoding="utf-8", check=True)
@@ -19,7 +19,7 @@ def run_image(file_name: str):
@contextlib.contextmanager
def extract_image(file_name: str):
extract_dir = tempfile.mkdtemp(prefix="osbuild-")
- archive = path.join(os.getcwd(), OUTPUT_DIR, file_name)
+ archive = path.join(os.getcwd(), file_name)
subprocess.run(["tar", "xf", archive], cwd=extract_dir, check=True)
try:
yield extract_dir
diff --git a/test/integration_tests/test_case.py b/test/integration_tests/test_case.py
index e6f03970..37907c55 100644
--- a/test/integration_tests/test_case.py
+++ b/test/integration_tests/test_case.py
@@ -5,6 +5,7 @@ from typing import List, Callable, Any
from . import evaluate_test, rel_path
from .build import run_osbuild
from .run import run_image, extract_image
+from test.integration_tests.config import *
class IntegrationTestType(Enum):
@@ -22,18 +23,18 @@ class IntegrationTestCase:
type: IntegrationTestType
def run(self):
- run_osbuild(rel_path(f"pipelines/{self.pipeline}"), self.build_pipeline)
+ tree_id, output_id = run_osbuild(rel_path(f"pipelines/{self.pipeline}"), self.build_pipeline)
if self.type == IntegrationTestType.BOOT_WITH_QEMU:
- self.run_and_test()
+ self.run_and_test(output_id)
else:
- self.extract_and_test()
+ self.extract_and_test(output_id)
- def run_and_test(self):
- r = run_image(self.output_image)
+ def run_and_test(self, output_id):
+ r = run_image(f"{OBJECTS}/refs/{output_id}/{self.output_image}")
for test in self.test_cases:
evaluate_test(test, r.stdout)
- def extract_and_test(self):
- with extract_image(self.output_image) as fstree:
+ def extract_and_test(self, output_id):
+ with extract_image(f"{OBJECTS}/refs/{output_id}/{self.output_image}") as fstree:
for test in self.test_cases:
evaluate_test(lambda: test(fstree), name=test.__name__)
diff --git a/test/test_osbuild.py b/test/test_osbuild.py
index 63d2024c..b7c89abd 100644
--- a/test/test_osbuild.py
+++ b/test/test_osbuild.py
@@ -35,9 +35,9 @@ class TestDescriptions(unittest.TestCase):
name = "org.osbuild.test"
options = { "one": 1 }
cases = [
- (osbuild.Assembler(name, {}), {"name": name}),
- (osbuild.Assembler(name, None), {"name": name}),
- (osbuild.Assembler(name, options), {"name": name, "options": options}),
+ (osbuild.Assembler(name, None, None, {}), {"name": name}),
+ (osbuild.Assembler(name, None, None, None), {"name": name}),
+ (osbuild.Assembler(name, None, None, options), {"name": name, "options": options}),
]
for assembler, description in cases:
with self.subTest(description):
| Proposal: cache assembler output
osbuild caches trees, but not output from assemblers. This is inconsistent, because trees are cached, but outputs are not. People (or programs like Composer) that use osbuild need to manage where they store the outputs themselves, using `--output`. That argument is a bit awkward to use, because one (technically) needs to clear it between every run of osbuild, or pass a new one named after the pipeline.
osbuild can manage this for them by storing all output in `.osbuild/output`, which contains directories named after the pipline's hash, similar to `.osbuild/objects`.
This lets us remove the `--output` argument. To make the last output easier to find, let's print the full path after the assembler is finished running. | 0.0 | [
"test/test_osbuild.py::TestDescriptions::test_assembler"
] | [
"test/test_osbuild.py::TestDescriptions::test_canonical",
"test/test_osbuild.py::TestDescriptions::test_pipeline",
"test/test_osbuild.py::TestDescriptions::test_stage"
] | 2019-09-25 17:27:52+00:00 | 4,426 |
|
osbuild__osbuild-1648 | diff --git a/stages/org.osbuild.users b/stages/org.osbuild.users
index 88a40f0b..c4e82eb9 100755
--- a/stages/org.osbuild.users
+++ b/stages/org.osbuild.users
@@ -70,6 +70,10 @@ SCHEMA = """
"items": {
"type": "string"
}
+ },
+ "expiredate": {
+ "description": "The date on which the user account will be disabled. This date is represented as a number of days since January 1st, 1970.",
+ "type": "integer"
}
}
}
@@ -89,7 +93,17 @@ def getpwnam(root, name):
return None
-def useradd(root, name, uid=None, gid=None, groups=None, description=None, home=None, shell=None, password=None):
+def useradd(
+ root,
+ name,
+ uid=None,
+ gid=None,
+ groups=None,
+ description=None,
+ home=None,
+ shell=None,
+ password=None,
+ expiredate=None):
arguments = []
if uid is not None:
arguments += ["--uid", str(uid), "-o"]
@@ -108,11 +122,13 @@ def useradd(root, name, uid=None, gid=None, groups=None, description=None, home=
arguments += ["--shell", shell]
if password is not None:
arguments += ["--password", password]
+ if expiredate is not None:
+ arguments += ["--expiredate", str(expiredate)]
subprocess.run(["chroot", root, "useradd", *arguments, name], check=True)
-def usermod(root, name, gid=None, groups=None, description=None, home=None, shell=None, password=None):
+def usermod(root, name, gid=None, groups=None, description=None, home=None, shell=None, password=None, expiredate=None):
arguments = []
if gid is not None:
arguments += ["--gid", gid]
@@ -126,6 +142,8 @@ def usermod(root, name, gid=None, groups=None, description=None, home=None, shel
arguments += ["--shell", shell]
if password is not None:
arguments += ["--password", password]
+ if expiredate is not None:
+ arguments += ["--expiredate", str(expiredate)]
if arguments:
subprocess.run(["chroot", root, "usermod", *arguments, name], check=True)
@@ -168,6 +186,7 @@ def main(tree, options):
home = user_options.get("home")
shell = user_options.get("shell")
password = user_options.get("password")
+ expiredate = user_options.get("expiredate")
passwd = getpwnam(tree, name)
if passwd is not None:
@@ -175,13 +194,13 @@ def main(tree, options):
if uid is not None and passwd[2] != str(uid):
print(f"Error: can't set uid of existing user '{name}'")
return 1
- usermod(tree, name, gid, groups, description, home, shell, password)
+ usermod(tree, name, gid, groups, description, home, shell, password, expiredate)
# ensure the home directory exists, see module doc string for details
_, _, _, _, _, home, _ = getpwnam(tree, name)
ensure_homedir(tree, name, home)
else:
- useradd(tree, name, uid, gid, groups, description, home, shell, password)
+ useradd(tree, name, uid, gid, groups, description, home, shell, password, expiredate)
# following maintains backwards compatibility for handling a single ssh key
key = user_options.get("key") # Public SSH key
| osbuild/osbuild | 8b601d146b3d86682777c18f5c781ee0d9c84221 | diff --git a/stages/test/test_users.py b/stages/test/test_users.py
new file mode 100644
index 00000000..1bc06ccd
--- /dev/null
+++ b/stages/test/test_users.py
@@ -0,0 +1,34 @@
+#!/usr/bin/python3
+
+from unittest.mock import patch
+
+import pytest
+
+from osbuild.testutil import make_fake_tree
+
+STAGE_NAME = "org.osbuild.users"
+
+
[email protected]("user_opts,expected_args", [
+ ({}, []),
+ ({"expiredate": 12345}, ["--expiredate", "12345"]),
+])
+@patch("subprocess.run")
+def test_users_happy(mocked_run, tmp_path, stage_module, user_opts, expected_args):
+ make_fake_tree(tmp_path, {
+ "/etc/passwd": "",
+ })
+
+ options = {
+ "users": {
+ "foo": {},
+ }
+ }
+ options["users"]["foo"].update(user_opts)
+
+ stage_module.main(tmp_path, options)
+
+ assert len(mocked_run.call_args_list) == 1
+ args, kwargs = mocked_run.call_args_list[0]
+ assert args[0] == ["chroot", tmp_path, "useradd"] + expected_args + ["foo"]
+ assert kwargs.get("check")
| Set password expiry for users
I would like to add a user to my final image, but require that that user change their password on first login. In general you can achieve this with `passwd --expire <user>` or `useradd --expiredate`/`usermod --expiredate` or `chage --expiredate`. The expire date is stored in `/etc/shadow` but I don't know how to specifically drop that file. I think this makes sense to happen as part of the `org.osbuild.users` stage. Eventually I want to be able to control this from an osbuild-composer blueprint, but I know that is not part of this repo. | 0.0 | [
"stages/test/test_users.py::test_users_happy[user_opts1-expected_args1]"
] | [
"stages/test/test_users.py::test_users_happy[user_opts0-expected_args0]"
] | 2024-03-06 18:16:57+00:00 | 4,427 |
|
osrf__rocker-23 | diff --git a/src/rocker/cli.py b/src/rocker/cli.py
index f422ef0..5b59ed7 100755
--- a/src/rocker/cli.py
+++ b/src/rocker/cli.py
@@ -18,11 +18,10 @@ import argparse
import os
import sys
-
-import docker
-
from .core import DockerImageGenerator
from .core import list_plugins
+from .core import pull_image
+
def main():
@@ -51,18 +50,8 @@ def main():
base_image = args.image
if args.pull:
- try:
- docker_client = docker.APIClient()
- except AttributeError:
- # docker-py pre 2.0
- docker_client = docker.Client()
- try:
- print("Pulling image %s" % base_image)
- for line in docker_client.pull(base_image, stream=True):
- print(line)
- except docker.errors.APIError as ex:
- print('Pull of %s failed: %s' % (base_image, ex))
- pass
+ pull_image(base_image)
+
dig = DockerImageGenerator(active_extensions, args_dict, base_image)
exit_code = dig.build(**vars(args))
if exit_code != 0:
diff --git a/src/rocker/core.py b/src/rocker/core.py
index 895c6ed..06e836e 100755
--- a/src/rocker/core.py
+++ b/src/rocker/core.py
@@ -29,6 +29,15 @@ import docker
import pexpect
+def get_docker_client():
+ """Simple helper function for pre 2.0 imports"""
+ try:
+ docker_client = docker.APIClient()
+ except AttributeError:
+ # docker-py pre 2.0
+ docker_client = docker.Client()
+ return docker_client
+
class DockerImageGenerator(object):
def __init__(self, active_extensions, cliargs, base_image):
self.built = False
@@ -59,11 +68,7 @@ class DockerImageGenerator(object):
arguments['tag'] = self.image_name
print("Building docker file with arguments: ", arguments)
try:
- try:
- docker_client = docker.APIClient()
- except AttributeError:
- # docker-py pre 2.0
- docker_client = docker.Client()
+ docker_client = get_docker_client()
success_detected = False
for line in docker_client.build(**arguments):
output = line.get('stream', '').rstrip()
@@ -159,3 +164,15 @@ def list_plugins(extension_point='rocker.extensions'):
plugin_names = list(unordered_plugins.keys())
plugin_names.sort()
return OrderedDict([(k, unordered_plugins[k]) for k in plugin_names])
+
+
+def pull_image(image_name):
+ docker_client = get_docker_client()
+ try:
+ print("Pulling image %s" % image_name)
+ for line in docker_client.pull(image_name, stream=True):
+ print(line)
+ return True
+ except docker.errors.APIError as ex:
+ print('Pull of %s failed: %s' % (image_name, ex))
+ return False
| osrf/rocker | 1ab01acbf203c3f134ce5d00992367484e8c47fd | diff --git a/test/test_core.py b/test/test_core.py
index 9c7a5b7..0fdfe8c 100644
--- a/test/test_core.py
+++ b/test/test_core.py
@@ -15,10 +15,14 @@
# specific language governing permissions and limitations
# under the License.
+import docker
import unittest
+from itertools import chain
from rocker.cli import DockerImageGenerator, list_plugins
+from rocker.core import pull_image
+from rocker.core import get_docker_client
class RockerCoreTest(unittest.TestCase):
@@ -29,3 +33,18 @@ class RockerCoreTest(unittest.TestCase):
self.assertTrue('pulse' in plugin_names )
self.assertTrue('user' in plugin_names )
self.assertTrue('home' in plugin_names )
+
+ def test_pull_image(self):
+ TEST_IMAGE='alpine:latest'
+ docker_client = get_docker_client()
+
+ l = docker_client.images()
+ tags = set(chain.from_iterable([i['RepoTags'] for i in l if i['RepoTags']]))
+ print(tags)
+ if TEST_IMAGE in tags:
+ docker_client.remove_image(TEST_IMAGE)
+ print('removed image %s' % TEST_IMAGE)
+ self.assertTrue(pull_image(TEST_IMAGE))
+
+ def test_failed_pull_image(self):
+ self.assertFalse(pull_image("osrf/ros:does_not_exist"))
| extract pull functionality into library
it's currently only available in the cli interface. It could easily be a free function for easier reuse. | 0.0 | [
"test/test_core.py::RockerCoreTest::test_list_plugins"
] | [] | 2019-01-31 01:00:44+00:00 | 4,428 |
|
osrf__rocker-242 | diff --git a/src/rocker/cli.py b/src/rocker/cli.py
index 7d78641..2840c8b 100644
--- a/src/rocker/cli.py
+++ b/src/rocker/cli.py
@@ -20,6 +20,7 @@ from .core import DockerImageGenerator
from .core import get_rocker_version
from .core import RockerExtensionManager
from .core import DependencyMissing
+from .core import ExtensionError
from .os_detector import detect_os
@@ -54,9 +55,11 @@ def main():
args_dict['mode'] = OPERATIONS_DRY_RUN
print('DEPRECATION Warning: --noexecute is deprecated for --mode dry-run please switch your usage by December 2020')
- active_extensions = extension_manager.get_active_extensions(args_dict)
- # Force user to end if present otherwise it will break other extensions
- active_extensions.sort(key=lambda e:e.get_name().startswith('user'))
+ try:
+ active_extensions = extension_manager.get_active_extensions(args_dict)
+ except ExtensionError as e:
+ print(f"ERROR! {str(e)}")
+ return 1
print("Active extensions %s" % [e.get_name() for e in active_extensions])
base_image = args.image
diff --git a/src/rocker/core.py b/src/rocker/core.py
index 2f1a535..7c23d9f 100644
--- a/src/rocker/core.py
+++ b/src/rocker/core.py
@@ -32,6 +32,7 @@ import fcntl
import signal
import struct
import termios
+import typing
SYS_STDOUT = sys.stdout
@@ -45,6 +46,10 @@ class DependencyMissing(RuntimeError):
pass
+class ExtensionError(RuntimeError):
+ pass
+
+
class RockerExtension(object):
"""The base class for Rocker extension points"""
@@ -58,6 +63,22 @@ class RockerExtension(object):
necessary resources are available, like hardware."""
pass
+ def invoke_after(self, cliargs) -> typing.Set[str]:
+ """
+ This extension should be loaded after the extensions in the returned
+ set. These extensions are not required to be present, but if they are,
+ they will be loaded before this extension.
+ """
+ return set()
+
+ def required(self, cliargs) -> typing.Set[str]:
+ """
+ Ensures the specified extensions are present and combined with
+ this extension. If the required extension should be loaded before
+ this extension, it should also be added to the `invoke_after` set.
+ """
+ return set()
+
def get_preamble(self, cliargs):
return ''
@@ -106,13 +127,70 @@ class RockerExtensionManager:
parser.add_argument('--extension-blacklist', nargs='*',
default=[],
help='Prevent any of these extensions from being loaded.')
+ parser.add_argument('--strict-extension-selection', action='store_true',
+ help='When enabled, causes an error if required extensions are not explicitly '
+ 'called out on the command line. Otherwise, the required extensions will '
+ 'automatically be loaded if available.')
def get_active_extensions(self, cli_args):
- active_extensions = [e() for e in self.available_plugins.values() if e.check_args_for_activation(cli_args) and e.get_name() not in cli_args['extension_blacklist']]
- active_extensions.sort(key=lambda e:e.get_name().startswith('user'))
- return active_extensions
+ """
+ Checks for missing dependencies (specified by each extension's
+ required() method) and additionally sorts them.
+ """
+ def sort_extensions(extensions, cli_args):
+
+ def topological_sort(source: typing.Dict[str, typing.Set[str]]) -> typing.List[str]:
+ """Perform a topological sort on names and dependencies and returns the sorted list of names."""
+ names = set(source.keys())
+ # prune optional dependencies if they are not present (at this point the required check has already occurred)
+ pending = [(name, dependencies.intersection(names)) for name, dependencies in source.items()]
+ emitted = []
+ while pending:
+ next_pending = []
+ next_emitted = []
+ for entry in pending:
+ name, deps = entry
+ deps.difference_update(emitted) # remove dependencies already emitted
+ if deps: # still has dependencies? recheck during next pass
+ next_pending.append(entry)
+ else: # no more dependencies? time to emit
+ yield name
+ next_emitted.append(name) # remember what was emitted for difference_update()
+ if not next_emitted:
+ raise ExtensionError("Cyclic dependancy detected: %r" % (next_pending,))
+ pending = next_pending
+ emitted = next_emitted
+
+ extension_graph = {name: cls.invoke_after(cli_args) for name, cls in sorted(extensions.items())}
+ active_extension_list = [extensions[name] for name in topological_sort(extension_graph)]
+ return active_extension_list
+
+ active_extensions = {}
+ find_reqs = set([name for name, cls in self.available_plugins.items() if cls.check_args_for_activation(cli_args)])
+ while find_reqs:
+ name = find_reqs.pop()
+
+ if name in self.available_plugins.keys():
+ if name not in cli_args['extension_blacklist']:
+ ext = self.available_plugins[name]()
+ active_extensions[name] = ext
+ else:
+ raise ExtensionError(f"Extension '{name}' is blacklisted.")
+ else:
+ raise ExtensionError(f"Extension '{name}' not found. Is it installed?")
+
+ # add additional reqs for processing not already known about
+ known_reqs = set(active_extensions.keys()).union(find_reqs)
+ missing_reqs = ext.required(cli_args).difference(known_reqs)
+ if missing_reqs:
+ if cli_args['strict_extension_selection']:
+ raise ExtensionError(f"Extension '{name}' is missing required extension(s) {list(missing_reqs)}")
+ else:
+ print(f"Adding implicilty required extension(s) {list(missing_reqs)} required by extension '{name}'")
+ find_reqs = find_reqs.union(missing_reqs)
+ return sort_extensions(active_extensions, cli_args)
def get_docker_client():
"""Simple helper function for pre 2.0 imports"""
@@ -254,7 +332,6 @@ class DockerImageGenerator(object):
print("No tty detected for stdin forcing non-interactive")
return operating_mode
-
def generate_docker_cmd(self, command='', **kwargs):
docker_args = ''
| osrf/rocker | 2b8d5abb18c829d22f290679b739dc53765198ad | diff --git a/test/test_core.py b/test/test_core.py
index f57e659..f7b12dc 100644
--- a/test/test_core.py
+++ b/test/test_core.py
@@ -26,7 +26,9 @@ from rocker.core import DockerImageGenerator
from rocker.core import list_plugins
from rocker.core import get_docker_client
from rocker.core import get_rocker_version
+from rocker.core import RockerExtension
from rocker.core import RockerExtensionManager
+from rocker.core import ExtensionError
class RockerCoreTest(unittest.TestCase):
@@ -128,9 +130,82 @@ class RockerCoreTest(unittest.TestCase):
self.assertIn('non-interactive', help_str)
self.assertIn('--extension-blacklist', help_str)
- active_extensions = active_extensions = extension_manager.get_active_extensions({'user': True, 'ssh': True, 'extension_blacklist': ['ssh']})
- self.assertEqual(len(active_extensions), 1)
- self.assertEqual(active_extensions[0].get_name(), 'user')
+ self.assertRaises(ExtensionError,
+ extension_manager.get_active_extensions,
+ {'user': True, 'ssh': True, 'extension_blacklist': ['ssh']})
+
+ def test_strict_required_extensions(self):
+ class Foo(RockerExtension):
+ @classmethod
+ def get_name(cls):
+ return 'foo'
+
+ class Bar(RockerExtension):
+ @classmethod
+ def get_name(cls):
+ return 'bar'
+
+ def required(self, cli_args):
+ return {'foo'}
+
+ extension_manager = RockerExtensionManager()
+ extension_manager.available_plugins = {'foo': Foo, 'bar': Bar}
+
+ correct_extensions_args = {'strict_extension_selection': True, 'bar': True, 'foo': True, 'extension_blacklist': []}
+ extension_manager.get_active_extensions(correct_extensions_args)
+
+ incorrect_extensions_args = {'strict_extension_selection': True, 'bar': True, 'extension_blacklist': []}
+ self.assertRaises(ExtensionError,
+ extension_manager.get_active_extensions, incorrect_extensions_args)
+
+ def test_implicit_required_extensions(self):
+ class Foo(RockerExtension):
+ @classmethod
+ def get_name(cls):
+ return 'foo'
+
+ class Bar(RockerExtension):
+ @classmethod
+ def get_name(cls):
+ return 'bar'
+
+ def required(self, cli_args):
+ return {'foo'}
+
+ extension_manager = RockerExtensionManager()
+ extension_manager.available_plugins = {'foo': Foo, 'bar': Bar}
+
+ implicit_extensions_args = {'strict_extension_selection': False, 'bar': True, 'extension_blacklist': []}
+ active_extensions = extension_manager.get_active_extensions(implicit_extensions_args)
+ self.assertEqual(len(active_extensions), 2)
+ # required extensions are not ordered, just check to make sure they are both present
+ if active_extensions[0].get_name() == 'foo':
+ self.assertEqual(active_extensions[1].get_name(), 'bar')
+ else:
+ self.assertEqual(active_extensions[0].get_name(), 'bar')
+ self.assertEqual(active_extensions[1].get_name(), 'foo')
+
+ def test_extension_sorting(self):
+ class Foo(RockerExtension):
+ @classmethod
+ def get_name(cls):
+ return 'foo'
+
+ class Bar(RockerExtension):
+ @classmethod
+ def get_name(cls):
+ return 'bar'
+
+ def invoke_after(self, cli_args):
+ return {'foo', 'absent_extension'}
+
+ extension_manager = RockerExtensionManager()
+ extension_manager.available_plugins = {'foo': Foo, 'bar': Bar}
+
+ args = {'bar': True, 'foo': True, 'extension_blacklist': []}
+ active_extensions = extension_manager.get_active_extensions(args)
+ self.assertEqual(active_extensions[0].get_name(), 'foo')
+ self.assertEqual(active_extensions[1].get_name(), 'bar')
def test_docker_cmd_interactive(self):
dig = DockerImageGenerator([], {}, 'ubuntu:bionic')
@@ -148,7 +223,6 @@ class RockerCoreTest(unittest.TestCase):
self.assertNotIn('-it', dig.generate_docker_cmd(mode='non-interactive'))
-
def test_docker_cmd_nocleanup(self):
dig = DockerImageGenerator([], {}, 'ubuntu:bionic')
| Add the ability for extensions to have requirements on other extension
For example the nvidia extension will need the x11 extension to be useful.
Also the home extension should require the user extension for permissions.
There' s a question of ordering, required before or not. And for each sequential element aka snippets.
Preamble elements are named so order independent, and arguments are order independent as far as I know as long as they're escaped properly.
This will resolve this todo: https://github.com/osrf/rocker/blob/cea068015fd7e1026d3887c103a71d86557b5dbb/test/test_nvidia.py#L134 | 0.0 | [
"test/test_core.py::RockerCoreTest::test_docker_cmd_interactive",
"test/test_core.py::RockerCoreTest::test_docker_cmd_nocleanup",
"test/test_core.py::RockerCoreTest::test_extension_sorting",
"test/test_core.py::RockerCoreTest::test_get_rocker_version",
"test/test_core.py::RockerCoreTest::test_implicit_required_extensions",
"test/test_core.py::RockerCoreTest::test_list_plugins",
"test/test_core.py::RockerCoreTest::test_strict_required_extensions"
] | [] | 2023-09-21 19:28:41+00:00 | 4,429 |
|
osrf__rocker-83 | diff --git a/src/rocker/extensions.py b/src/rocker/extensions.py
index a7894af..9d32843 100644
--- a/src/rocker/extensions.py
+++ b/src/rocker/extensions.py
@@ -215,9 +215,15 @@ class Environment(RockerExtension):
def get_docker_args(self, cli_args):
args = ['']
- envs = [ x for sublist in cli_args['env'] for x in sublist]
- for env in envs:
- args.append('-e {0}'.format(quote(env)))
+ if cli_args.get('env'):
+ envs = [ x for sublist in cli_args['env'] for x in sublist]
+ for env in envs:
+ args.append('-e {0}'.format(quote(env)))
+
+ if cli_args.get('env_file'):
+ env_files = [ x for sublist in cli_args['env_file'] for x in sublist]
+ for env_file in env_files:
+ args.append('--env-file {0}'.format(quote(env_file)))
return ' '.join(args)
@@ -229,3 +235,13 @@ class Environment(RockerExtension):
nargs='+',
action='append',
help='set environment variables')
+ parser.add_argument('--env-file',
+ type=str,
+ nargs=1,
+ action='append',
+ help='set environment variable via env-file')
+
+ @classmethod
+ def check_args_for_activation(cls, cli_args):
+ """ Returns true if the arguments indicate that this extension should be activated otherwise false."""
+ return True if cli_args.get('env') or cli_args.get('env_file') else False
diff --git a/src/rocker/nvidia_extension.py b/src/rocker/nvidia_extension.py
index 32c31ff..e27a707 100644
--- a/src/rocker/nvidia_extension.py
+++ b/src/rocker/nvidia_extension.py
@@ -82,8 +82,8 @@ class Nvidia(RockerExtension):
def __init__(self):
self._env_subs = None
self.name = Nvidia.get_name()
- self.supported_distros = ['Ubuntu']
- self.supported_versions = ['16.04', '18.04']
+ self.supported_distros = ['Ubuntu', 'Debian GNU/Linux']
+ self.supported_versions = ['16.04', '18.04', '20.04', '10']
def get_environment_subs(self, cliargs={}):
@@ -105,7 +105,7 @@ class Nvidia(RockerExtension):
sys.exit(1)
self._env_subs['image_distro_version'] = ver
if self._env_subs['image_distro_version'] not in self.supported_versions:
- print("WARNING distro version %s not in supported list by Nvidia supported versions" % self._env_subs['image_distro_version'], self.supported_versions)
+ print("WARNING distro %s version %s not in supported list by Nvidia supported versions" % (dist, ver), self.supported_versions)
sys.exit(1)
# TODO(tfoote) add a standard mechanism for checking preconditions and disabling plugins
diff --git a/src/rocker/templates/nvidia_preamble.Dockerfile.em b/src/rocker/templates/nvidia_preamble.Dockerfile.em
index f6fb0af..1bab533 100644
--- a/src/rocker/templates/nvidia_preamble.Dockerfile.em
+++ b/src/rocker/templates/nvidia_preamble.Dockerfile.em
@@ -1,2 +1,3 @@
# Ubuntu 16.04 with nvidia-docker2 beta opengl support
-FROM nvidia/opengl:1.0-glvnd-devel-@(image_distro_id.lower())@(image_distro_version) as glvnd
+@{suffix = '16.04' if image_distro_version == '16.04' else '18.04'}@
+FROM nvidia/opengl:1.0-glvnd-devel-ubuntu@(suffix) as glvnd
diff --git a/src/rocker/templates/nvidia_snippet.Dockerfile.em b/src/rocker/templates/nvidia_snippet.Dockerfile.em
index 1cda845..69e9a09 100644
--- a/src/rocker/templates/nvidia_snippet.Dockerfile.em
+++ b/src/rocker/templates/nvidia_snippet.Dockerfile.em
@@ -10,7 +10,7 @@ RUN ( echo '/usr/local/lib/x86_64-linux-gnu' >> /etc/ld.so.conf.d/glvnd.conf &&
ENV LD_LIBRARY_PATH /usr/local/lib/x86_64-linux-gnu:/usr/local/lib/i386-linux-gnu${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}}
COPY --from=glvnd /usr/local/share/glvnd/egl_vendor.d/10_nvidia.json /usr/local/share/glvnd/egl_vendor.d/10_nvidia.json
-@[else if image_distro_version == '18.04']@
+@[else]@
RUN apt-get update && apt-get install -y --no-install-recommends \
libglvnd0 \
libgl1 \
| osrf/rocker | 413d25a7e578d4eab410eda99042cabb8dc8026b | diff --git a/test/test_extension.py b/test/test_extension.py
index 5000c32..9d61593 100644
--- a/test/test_extension.py
+++ b/test/test_extension.py
@@ -289,3 +289,17 @@ class EnvExtensionTest(unittest.TestCase):
self.assertEqual(p.get_snippet(mock_cliargs), '')
self.assertEqual(p.get_preamble(mock_cliargs), '')
self.assertEqual(p.get_docker_args(mock_cliargs), ' -e ENVVARNAME=envvar_value -e ENV2=val2 -e ENV3=val3')
+
+ def test_env_file_extension(self):
+ plugins = list_plugins()
+ env_plugin = plugins['env']
+ self.assertEqual(env_plugin.get_name(), 'env')
+
+ p = env_plugin()
+ self.assertTrue(plugin_load_parser_correctly(env_plugin))
+
+ mock_cliargs = {'env_file': [['foo'], ['bar']]}
+
+ self.assertEqual(p.get_snippet(mock_cliargs), '')
+ self.assertEqual(p.get_preamble(mock_cliargs), '')
+ self.assertEqual(p.get_docker_args(mock_cliargs), ' --env-file foo --env-file bar')
diff --git a/test/test_nvidia.py b/test/test_nvidia.py
index b183fe6..01bf2d4 100644
--- a/test/test_nvidia.py
+++ b/test/test_nvidia.py
@@ -36,9 +36,9 @@ class X11Test(unittest.TestCase):
def setUpClass(self):
client = get_docker_client()
self.dockerfile_tags = []
- for distro_version in ['xenial', 'bionic']:
+ for distro, distro_version in [('ubuntu', 'xenial'), ('ubuntu', 'bionic'), ('ubuntu', 'focal'), ('debian', 'buster')]:
dockerfile = """
-FROM ubuntu:%(distro_version)s
+FROM %(distro)s:%(distro_version)s
RUN apt-get update && apt-get install x11-utils -y && apt-get clean
@@ -204,7 +204,7 @@ CMD glmark2 --validate
self.assertEqual(cm.exception.code, 1)
# unsupported os
- mock_cliargs = {'base_image': 'debian'}
+ mock_cliargs = {'base_image': 'fedora'}
with self.assertRaises(SystemExit) as cm:
p.get_environment_subs(mock_cliargs)
self.assertEqual(cm.exception.code, 1)
| Ubuntu 20.04 support for `--nvidia`
Currently testing some stuff with ROS2 Foxy on Ubutu 20.04. Looks like `--nvidia` isn't supported yet:
```
WARNING distro version 20.04 not in supported list by Nvidia supported versions ['16.04', '18.04']
```
Related: https://gitlab.com/nvidia/container-images/opengl/-/issues/7 | 0.0 | [
"test/test_extension.py::EnvExtensionTest::test_env_file_extension"
] | [
"test/test_extension.py::ExtensionsTest::test_name_to_argument",
"test/test_extension.py::DevicesExtensionTest::test_devices_extension",
"test/test_extension.py::HomeExtensionTest::test_home_extension",
"test/test_extension.py::PulseExtensionTest::test_pulse_extension",
"test/test_extension.py::DevHelpersExtensionTest::test_pulse_extension",
"test/test_extension.py::EnvExtensionTest::test_env_extension"
] | 2020-05-08 00:20:12+00:00 | 4,430 |
Subsets and Splits