instance_id
stringlengths 10
57
| base_commit
stringlengths 40
40
| created_at
stringdate 2014-04-30 14:58:36
2025-04-30 20:14:11
| environment_setup_commit
stringlengths 40
40
| hints_text
stringlengths 0
273k
| patch
stringlengths 251
7.06M
| problem_statement
stringlengths 11
52.5k
| repo
stringlengths 7
53
| test_patch
stringlengths 231
997k
| meta
dict | version
stringclasses 851
values | install_config
dict | requirements
stringlengths 93
34.2k
⌀ | environment
stringlengths 760
20.5k
⌀ | FAIL_TO_PASS
listlengths 1
9.39k
| FAIL_TO_FAIL
listlengths 0
2.69k
| PASS_TO_PASS
listlengths 0
7.87k
| PASS_TO_FAIL
listlengths 0
192
| license_name
stringclasses 55
values | __index_level_0__
int64 0
21.4k
| before_filepaths
listlengths 1
105
| after_filepaths
listlengths 1
105
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
sendgrid__sendgrid-python-454 | 718ff6a1f91f7696b25c4ffd5b1dff9892e76f54 | 2017-10-27 15:41:53 | e270db212f25ad8ca4cc48aa17dc30b48cb3758a | diff --git a/sendgrid/helpers/mail/mail.py b/sendgrid/helpers/mail/mail.py
index 116afb4..7d131f4 100644
--- a/sendgrid/helpers/mail/mail.py
+++ b/sendgrid/helpers/mail/mail.py
@@ -293,7 +293,14 @@ class Mail(object):
:type content: Content
"""
- self._contents.append(content)
+ if self._contents is None:
+ self._contents = []
+
+ # Text content should be before HTML content
+ if content._type == "text/plain":
+ self._contents.insert(0, content)
+ else:
+ self._contents.append(content)
@property
def attachments(self):
| text/plain must precede text/html content
#### Issue Summary
Requests to send mail with both plain text and HTML content fail if the HTML content is specified first.
#### Code
```
sg = sendgrid.SendGridAPIClient(apikey=sendgrid_key)
mail = Mail()
from_email = Email("[email protected]")
to_email = Email("[email protected]")
subject = "Sending with SendGrid is Fun"
per = Personalization()
mail.from_email = from_email
mail.subject = subject
html_content = Content("text/html", "<html><body>some text here</body></html>")
plain_content = Content("text/plain", "and easy to do anywhere, even with Python")
### Add plain content first
mail.add_content(plain_content)
### Add HTML content next
mail.add_content(html_content)
per.add_to(to_email)
mail.add_personalization(per)
response = sg.client.mail.send.post(request_body=mail.get())
```
#### Steps to Reproduce
1. The above code works properly, but if you reverse the order of the add_content lines, http-client throws a BadRequestsError
#### Expected Result
The library should sort content into the order that the API expects. (I'm not clear why the order should matter to the API—perhaps this should be fixed there instead.)
#### Technical details:
* sendgrid-python Version: master (latest commit: [b12728a53d4c997832c56289c7559f22acf1ff90])
* Python Version: 2.7.13 | sendgrid/sendgrid-python | diff --git a/test/test_mail.py b/test/test_mail.py
index 8b88f5b..0941fa7 100644
--- a/test/test_mail.py
+++ b/test/test_mail.py
@@ -68,6 +68,39 @@ class UnitTests(unittest.TestCase):
self.assertTrue(isinstance(str(mail), str))
+ def test_helloEmailAdditionalContent(self):
+ """Tests bug found in Issue-451 with Content ordering causing a crash"""
+
+ self.maxDiff = None
+
+ """Minimum required to send an email"""
+ mail = Mail()
+
+ mail.from_email = Email("[email protected]")
+
+ mail.subject = "Hello World from the SendGrid Python Library"
+
+ personalization = Personalization()
+ personalization.add_to(Email("[email protected]"))
+ mail.add_personalization(personalization)
+
+ mail.add_content(Content("text/html", "<html><body>some text here</body></html>"))
+ mail.add_content(Content("text/plain", "some text here"))
+
+ self.assertEqual(
+ json.dumps(
+ mail.get(),
+ sort_keys=True),
+ '{"content": [{"type": "text/plain", "value": "some text here"}, '
+ '{"type": "text/html", '
+ '"value": "<html><body>some text here</body></html>"}], '
+ '"from": {"email": "[email protected]"}, "personalizations": '
+ '[{"to": [{"email": "[email protected]"}]}], '
+ '"subject": "Hello World from the SendGrid Python Library"}'
+ )
+
+ self.assertTrue(isinstance(str(mail), str))
+
def test_kitchenSink(self):
self.maxDiff = None
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_git_commit_hash"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 1,
"test_score": 0
},
"num_modified_files": 1
} | 5.3 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest"
],
"pre_install": null,
"python": "3.6",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs==22.2.0
certifi==2021.5.30
dataclasses==0.8
Flask==0.10.1
importlib-metadata==4.8.3
iniconfig==1.1.1
itsdangerous==2.0.1
Jinja2==3.0.3
MarkupSafe==2.0.1
packaging==21.3
pluggy==1.0.0
py==1.11.0
pyparsing==3.1.4
pytest==7.0.1
python-http-client==3.3.7
PyYAML==3.11
-e git+https://github.com/sendgrid/sendgrid-python.git@718ff6a1f91f7696b25c4ffd5b1dff9892e76f54#egg=sendgrid
six==1.10.0
tomli==1.2.3
typing_extensions==4.1.1
Werkzeug==2.0.3
zipp==3.6.0
| name: sendgrid-python
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- attrs==22.2.0
- dataclasses==0.8
- flask==0.10.1
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- itsdangerous==2.0.1
- jinja2==3.0.3
- markupsafe==2.0.1
- packaging==21.3
- pluggy==1.0.0
- py==1.11.0
- pyparsing==3.1.4
- pytest==7.0.1
- python-http-client==3.3.7
- pyyaml==3.11
- six==1.10.0
- tomli==1.2.3
- typing-extensions==4.1.1
- werkzeug==2.0.3
- zipp==3.6.0
prefix: /opt/conda/envs/sendgrid-python
| [
"test/test_mail.py::UnitTests::test_helloEmailAdditionalContent"
]
| []
| [
"test/test_mail.py::UnitTests::test_asm_display_group_limit",
"test/test_mail.py::UnitTests::test_disable_tracking",
"test/test_mail.py::UnitTests::test_helloEmail",
"test/test_mail.py::UnitTests::test_kitchenSink",
"test/test_mail.py::UnitTests::test_unicode_values_in_substitutions_helper"
]
| []
| MIT License | 1,812 | [
"sendgrid/helpers/mail/mail.py"
]
| [
"sendgrid/helpers/mail/mail.py"
]
|
|
mkdocs__mkdocs-1330 | fd0428543225f6fe5795b294235b12c540092aad | 2017-10-27 16:01:40 | 27f06517db4d8b73b162f2a2af65826ddcc8db54 | diff --git a/docs/about/release-notes.md b/docs/about/release-notes.md
index 22e2d900..64dc8a9b 100644
--- a/docs/about/release-notes.md
+++ b/docs/about/release-notes.md
@@ -23,6 +23,7 @@ The current and past members of the MkDocs team.
## Development Version
+* Bugfix: Support `repo_url` with missing ending slash. (#1321).
* Bugfix: Add length support to `mkdocs.toc.TableOfContext` (#1325).
* Bugfix: Add some theme specific settings to the search plugin for third party
themes (#1316).
diff --git a/mkdocs/config/config_options.py b/mkdocs/config/config_options.py
index 230a49e8..01fbd5ab 100644
--- a/mkdocs/config/config_options.py
+++ b/mkdocs/config/config_options.py
@@ -276,7 +276,7 @@ class RepoURL(URL):
if edit_uri:
if not edit_uri.startswith(('?', '#')) \
and not config['repo_url'].endswith('/'):
- edit_uri = '/' + edit_uri
+ config['repo_url'] += '/'
if not edit_uri.endswith('/'):
edit_uri += '/'
| Broken 'Edit on GitHub' link
We recently updated to 0.17.0 and it seems to have broken our 'Edit on GitHub' link, you can see this in action [here](https://opensciencegrid.github.io/docs/). The link given is https://github.com/edit/master/docs/index.md when it should be https://github.com/opensciencegrid/docs/edit/master/docs/index.md. [repo_url](https://github.com/opensciencegrid/docs/blob/master/mkdocs.yml#L3) appears to be set properly. | mkdocs/mkdocs | diff --git a/mkdocs/tests/config/config_options_tests.py b/mkdocs/tests/config/config_options_tests.py
index 7bdb49a0..87394fe5 100644
--- a/mkdocs/tests/config/config_options_tests.py
+++ b/mkdocs/tests/config/config_options_tests.py
@@ -196,7 +196,7 @@ class RepoURLTest(unittest.TestCase):
option = config_options.RepoURL()
config = {'repo_url': "https://github.com/mkdocs/mkdocs"}
option.post_validation(config, 'repo_url')
- self.assertEqual(config['edit_uri'], '/edit/master/docs/')
+ self.assertEqual(config['edit_uri'], 'edit/master/docs/')
def test_edit_uri_bitbucket(self):
@@ -218,7 +218,7 @@ class RepoURLTest(unittest.TestCase):
config = {'repo_url': "https://github.com/mkdocs/mkdocs",
'repo_name': 'mkdocs'}
option.post_validation(config, 'repo_url')
- self.assertEqual(config.get('edit_uri'), '/edit/master/docs/')
+ self.assertEqual(config.get('edit_uri'), 'edit/master/docs/')
class DirTest(unittest.TestCase):
diff --git a/mkdocs/tests/nav_tests.py b/mkdocs/tests/nav_tests.py
index 98fa515e..d8648b1c 100644
--- a/mkdocs/tests/nav_tests.py
+++ b/mkdocs/tests/nav_tests.py
@@ -466,9 +466,6 @@ class SiteNavigationTests(unittest.TestCase):
self.assertEqual(str(site_navigation).strip(), expected)
def test_edit_uri(self):
- """
- Ensure that set_edit_url creates well formed URLs for edit_uri
- """
pages = [
'index.md',
@@ -500,6 +497,47 @@ class SiteNavigationTests(unittest.TestCase):
for idx, page in enumerate(site_navigation.walk_pages()):
self.assertEqual(page.edit_url, expected_results[idx])
+ def test_edit_uri_sub_dir(self):
+
+ pages = [
+ 'index.md',
+ 'internal.md',
+ 'sub/internal.md',
+ 'sub1/sub2/internal.md',
+ ]
+
+ # Basic test
+ repo_url = 'http://example.com/foo/'
+ edit_uri = 'edit/master/docs/'
+
+ site_navigation = nav.SiteNavigation(load_config(
+ pages=pages,
+ repo_url=repo_url,
+ edit_uri=edit_uri,
+ site_dir='site',
+ site_url='',
+ use_directory_urls=True
+ ))
+
+ expected_results = (
+ repo_url + edit_uri + pages[0],
+ repo_url + edit_uri + pages[1],
+ repo_url + edit_uri + pages[2],
+ repo_url + edit_uri + pages[3],
+ )
+
+ for idx, page in enumerate(site_navigation.walk_pages()):
+ self.assertEqual(page.edit_url, expected_results[idx])
+
+ def test_edit_uri_missing_slash(self):
+
+ pages = [
+ 'index.md',
+ 'internal.md',
+ 'sub/internal.md',
+ 'sub1/sub2/internal.md',
+ ]
+
# Ensure the '/' is added to the repo_url and edit_uri
repo_url = 'http://example.com'
edit_uri = 'edit/master/docs'
@@ -513,9 +551,57 @@ class SiteNavigationTests(unittest.TestCase):
use_directory_urls=True
))
+ expected_results = (
+ repo_url + '/' + edit_uri + '/' + pages[0],
+ repo_url + '/' + edit_uri + '/' + pages[1],
+ repo_url + '/' + edit_uri + '/' + pages[2],
+ repo_url + '/' + edit_uri + '/' + pages[3],
+ )
+
for idx, page in enumerate(site_navigation.walk_pages()):
self.assertEqual(page.edit_url, expected_results[idx])
+ def test_edit_uri_sub_dir_missing_slash(self):
+
+ pages = [
+ 'index.md',
+ 'internal.md',
+ 'sub/internal.md',
+ 'sub1/sub2/internal.md',
+ ]
+
+ # Basic test
+ repo_url = 'http://example.com/foo'
+ edit_uri = 'edit/master/docs'
+
+ site_navigation = nav.SiteNavigation(load_config(
+ pages=pages,
+ repo_url=repo_url,
+ edit_uri=edit_uri,
+ site_dir='site',
+ site_url='',
+ use_directory_urls=True
+ ))
+
+ expected_results = (
+ repo_url + '/' + edit_uri + '/' + pages[0],
+ repo_url + '/' + edit_uri + '/' + pages[1],
+ repo_url + '/' + edit_uri + '/' + pages[2],
+ repo_url + '/' + edit_uri + '/' + pages[3],
+ )
+
+ for idx, page in enumerate(site_navigation.walk_pages()):
+ self.assertEqual(page.edit_url, expected_results[idx])
+
+ def test_edit_uri_query_string(self):
+
+ pages = [
+ 'index.md',
+ 'internal.md',
+ 'sub/internal.md',
+ 'sub1/sub2/internal.md',
+ ]
+
# Ensure query strings are supported
repo_url = 'http://example.com'
edit_uri = '?query=edit/master/docs/'
@@ -539,6 +625,15 @@ class SiteNavigationTests(unittest.TestCase):
for idx, page in enumerate(site_navigation.walk_pages()):
self.assertEqual(page.edit_url, expected_results[idx])
+ def test_edit_uri_fragment(self):
+
+ pages = [
+ 'index.md',
+ 'internal.md',
+ 'sub/internal.md',
+ 'sub1/sub2/internal.md',
+ ]
+
# Ensure fragment strings are supported
repo_url = 'http://example.com'
edit_uri = '#fragment/edit/master/docs/'
@@ -563,9 +658,6 @@ class SiteNavigationTests(unittest.TestCase):
self.assertEqual(page.edit_url, expected_results[idx])
def test_edit_uri_windows(self):
- """
- Ensure that set_edit_url creates well formed URLs for edit_uri with a windows path
- """
pages = [
'index.md',
@@ -597,6 +689,47 @@ class SiteNavigationTests(unittest.TestCase):
for idx, page in enumerate(site_navigation.walk_pages()):
self.assertEqual(page.edit_url, expected_results[idx])
+ def test_edit_uri_sub_dir_windows(self):
+
+ pages = [
+ 'index.md',
+ 'internal.md',
+ 'sub\\internal.md',
+ 'sub1\\sub2\\internal.md',
+ ]
+
+ # Basic test
+ repo_url = 'http://example.com/foo/'
+ edit_uri = 'edit/master/docs/'
+
+ site_navigation = nav.SiteNavigation(load_config(
+ pages=pages,
+ repo_url=repo_url,
+ edit_uri=edit_uri,
+ site_dir='site',
+ site_url='',
+ use_directory_urls=True
+ ))
+
+ expected_results = (
+ repo_url + edit_uri + pages[0],
+ repo_url + edit_uri + pages[1],
+ repo_url + edit_uri + pages[2].replace('\\', '/'),
+ repo_url + edit_uri + pages[3].replace('\\', '/'),
+ )
+
+ for idx, page in enumerate(site_navigation.walk_pages()):
+ self.assertEqual(page.edit_url, expected_results[idx])
+
+ def test_edit_uri_missing_slash_windows(self):
+
+ pages = [
+ 'index.md',
+ 'internal.md',
+ 'sub\\internal.md',
+ 'sub1\\sub2\\internal.md',
+ ]
+
# Ensure the '/' is added to the repo_url and edit_uri
repo_url = 'http://example.com'
edit_uri = 'edit/master/docs'
@@ -610,9 +743,57 @@ class SiteNavigationTests(unittest.TestCase):
use_directory_urls=True
))
+ expected_results = (
+ repo_url + '/' + edit_uri + '/' + pages[0],
+ repo_url + '/' + edit_uri + '/' + pages[1],
+ repo_url + '/' + edit_uri + '/' + pages[2].replace('\\', '/'),
+ repo_url + '/' + edit_uri + '/' + pages[3].replace('\\', '/'),
+ )
+
for idx, page in enumerate(site_navigation.walk_pages()):
self.assertEqual(page.edit_url, expected_results[idx])
+ def test_edit_uri_sub_dir_missing_slash_windows(self):
+
+ pages = [
+ 'index.md',
+ 'internal.md',
+ 'sub\\internal.md',
+ 'sub1\\sub2\\internal.md',
+ ]
+
+ # Ensure the '/' is added to the repo_url and edit_uri
+ repo_url = 'http://example.com/foo'
+ edit_uri = 'edit/master/docs'
+
+ site_navigation = nav.SiteNavigation(load_config(
+ pages=pages,
+ repo_url=repo_url,
+ edit_uri=edit_uri,
+ site_dir='site',
+ site_url='',
+ use_directory_urls=True
+ ))
+
+ expected_results = (
+ repo_url + '/' + edit_uri + '/' + pages[0],
+ repo_url + '/' + edit_uri + '/' + pages[1],
+ repo_url + '/' + edit_uri + '/' + pages[2].replace('\\', '/'),
+ repo_url + '/' + edit_uri + '/' + pages[3].replace('\\', '/'),
+ )
+
+ for idx, page in enumerate(site_navigation.walk_pages()):
+ self.assertEqual(page.edit_url, expected_results[idx])
+
+ def test_edit_uri_query_string_windows(self):
+
+ pages = [
+ 'index.md',
+ 'internal.md',
+ 'sub\\internal.md',
+ 'sub1\\sub2\\internal.md',
+ ]
+
# Ensure query strings are supported
repo_url = 'http://example.com'
edit_uri = '?query=edit/master/docs/'
@@ -636,6 +817,15 @@ class SiteNavigationTests(unittest.TestCase):
for idx, page in enumerate(site_navigation.walk_pages()):
self.assertEqual(page.edit_url, expected_results[idx])
+ def test_edit_uri_fragment_windows(self):
+
+ pages = [
+ 'index.md',
+ 'internal.md',
+ 'sub\\internal.md',
+ 'sub1\\sub2\\internal.md',
+ ]
+
# Ensure fragment strings are supported
repo_url = 'http://example.com'
edit_uri = '#fragment/edit/master/docs/'
| {
"commit_name": "merge_commit",
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 0,
"test_score": 2
},
"num_modified_files": 2
} | 0.17 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-mock",
"mock"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": [
"requirements/project.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | click==8.1.8
exceptiongroup==1.2.2
importlib_metadata==8.6.1
iniconfig==2.1.0
Jinja2==3.1.6
livereload==2.7.1
Markdown==3.7
MarkupSafe==3.0.2
-e git+https://github.com/mkdocs/mkdocs.git@fd0428543225f6fe5795b294235b12c540092aad#egg=mkdocs
mock==5.2.0
packaging==24.2
pluggy==1.5.0
pytest==8.3.5
pytest-mock==3.14.0
PyYAML==6.0.2
tomli==2.2.1
tornado==6.4.2
zipp==3.21.0
| name: mkdocs
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- click==8.1.8
- exceptiongroup==1.2.2
- importlib-metadata==8.6.1
- iniconfig==2.1.0
- jinja2==3.1.6
- livereload==2.7.1
- markdown==3.7
- markupsafe==3.0.2
- mock==5.2.0
- packaging==24.2
- pluggy==1.5.0
- pytest==8.3.5
- pytest-mock==3.14.0
- pyyaml==6.0.2
- tomli==2.2.1
- tornado==6.4.2
- zipp==3.21.0
prefix: /opt/conda/envs/mkdocs
| [
"mkdocs/tests/config/config_options_tests.py::RepoURLTest::test_edit_uri_github",
"mkdocs/tests/config/config_options_tests.py::RepoURLTest::test_repo_name_custom_and_empty_edit_uri"
]
| [
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_ancestors",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_base_url",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_edit_uri",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_edit_uri_fragment",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_edit_uri_fragment_windows",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_edit_uri_missing_slash",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_edit_uri_missing_slash_windows",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_edit_uri_query_string",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_edit_uri_query_string_windows",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_edit_uri_sub_dir",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_edit_uri_sub_dir_missing_slash",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_edit_uri_sub_dir_missing_slash_windows",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_edit_uri_sub_dir_windows",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_edit_uri_windows",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_empty_toc_item",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_force_abs_urls",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_force_abs_urls_with_base",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_generate_site_navigation",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_generate_site_navigation_windows",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_indented_toc",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_nested_ungrouped",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_nested_ungrouped_no_titles",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_nested_ungrouped_no_titles_windows",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_nesting",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_pages_config",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_relative_md_links_have_slash",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_simple_toc",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_walk_empty_toc",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_walk_indented_toc",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_walk_simple_toc"
]
| [
"mkdocs/tests/config/config_options_tests.py::OptionallyRequiredTest::test_default",
"mkdocs/tests/config/config_options_tests.py::OptionallyRequiredTest::test_empty",
"mkdocs/tests/config/config_options_tests.py::OptionallyRequiredTest::test_replace_default",
"mkdocs/tests/config/config_options_tests.py::OptionallyRequiredTest::test_required",
"mkdocs/tests/config/config_options_tests.py::OptionallyRequiredTest::test_required_no_default",
"mkdocs/tests/config/config_options_tests.py::TypeTest::test_length",
"mkdocs/tests/config/config_options_tests.py::TypeTest::test_multiple_types",
"mkdocs/tests/config/config_options_tests.py::TypeTest::test_single_type",
"mkdocs/tests/config/config_options_tests.py::IpAddressTest::test_default_address",
"mkdocs/tests/config/config_options_tests.py::IpAddressTest::test_invalid_address_format",
"mkdocs/tests/config/config_options_tests.py::IpAddressTest::test_invalid_address_missing_port",
"mkdocs/tests/config/config_options_tests.py::IpAddressTest::test_invalid_address_port",
"mkdocs/tests/config/config_options_tests.py::IpAddressTest::test_invalid_address_type",
"mkdocs/tests/config/config_options_tests.py::IpAddressTest::test_named_address",
"mkdocs/tests/config/config_options_tests.py::IpAddressTest::test_valid_IPv6_address",
"mkdocs/tests/config/config_options_tests.py::IpAddressTest::test_valid_address",
"mkdocs/tests/config/config_options_tests.py::URLTest::test_invalid",
"mkdocs/tests/config/config_options_tests.py::URLTest::test_invalid_url",
"mkdocs/tests/config/config_options_tests.py::URLTest::test_valid_url",
"mkdocs/tests/config/config_options_tests.py::RepoURLTest::test_edit_uri_bitbucket",
"mkdocs/tests/config/config_options_tests.py::RepoURLTest::test_edit_uri_custom",
"mkdocs/tests/config/config_options_tests.py::RepoURLTest::test_repo_name_bitbucket",
"mkdocs/tests/config/config_options_tests.py::RepoURLTest::test_repo_name_custom",
"mkdocs/tests/config/config_options_tests.py::RepoURLTest::test_repo_name_github",
"mkdocs/tests/config/config_options_tests.py::DirTest::test_doc_dir_is_config_dir",
"mkdocs/tests/config/config_options_tests.py::DirTest::test_file",
"mkdocs/tests/config/config_options_tests.py::DirTest::test_incorrect_type_attribute_error",
"mkdocs/tests/config/config_options_tests.py::DirTest::test_incorrect_type_type_error",
"mkdocs/tests/config/config_options_tests.py::DirTest::test_missing_dir",
"mkdocs/tests/config/config_options_tests.py::DirTest::test_missing_dir_but_required",
"mkdocs/tests/config/config_options_tests.py::DirTest::test_valid_dir",
"mkdocs/tests/config/config_options_tests.py::SiteDirTest::test_common_prefix",
"mkdocs/tests/config/config_options_tests.py::SiteDirTest::test_doc_dir_in_site_dir",
"mkdocs/tests/config/config_options_tests.py::SiteDirTest::test_site_dir_in_docs_dir",
"mkdocs/tests/config/config_options_tests.py::ThemeTest::test_theme_as_complex_config",
"mkdocs/tests/config/config_options_tests.py::ThemeTest::test_theme_as_simple_config",
"mkdocs/tests/config/config_options_tests.py::ThemeTest::test_theme_as_string",
"mkdocs/tests/config/config_options_tests.py::ThemeTest::test_theme_config_missing_name",
"mkdocs/tests/config/config_options_tests.py::ThemeTest::test_theme_default",
"mkdocs/tests/config/config_options_tests.py::ThemeTest::test_theme_invalid_type",
"mkdocs/tests/config/config_options_tests.py::ThemeTest::test_theme_name_is_none",
"mkdocs/tests/config/config_options_tests.py::ThemeTest::test_uninstalled_theme_as_config",
"mkdocs/tests/config/config_options_tests.py::ThemeTest::test_uninstalled_theme_as_string",
"mkdocs/tests/config/config_options_tests.py::PagesTest::test_invalid_config",
"mkdocs/tests/config/config_options_tests.py::PagesTest::test_invalid_type",
"mkdocs/tests/config/config_options_tests.py::PagesTest::test_old_format",
"mkdocs/tests/config/config_options_tests.py::PagesTest::test_provided_dict",
"mkdocs/tests/config/config_options_tests.py::PagesTest::test_provided_empty",
"mkdocs/tests/config/config_options_tests.py::PrivateTest::test_defined",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_builtins",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_builtins_config",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_configkey",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_duplicates",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_invalid_config_item",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_invalid_config_option",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_invalid_dict_item",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_list_dicts",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_mixed_list",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_none",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_not_list",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_simple_list",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_invalid_pages_config"
]
| []
| BSD 2-Clause "Simplified" License | 1,813 | [
"docs/about/release-notes.md",
"mkdocs/config/config_options.py"
]
| [
"docs/about/release-notes.md",
"mkdocs/config/config_options.py"
]
|
|
great-expectations__great_expectations-107 | e4f42b80d95cff33339681464a72d833c692dd65 | 2017-10-27 16:05:27 | c5ba7058a8afc99b7b9ce523d3cb183961a321a3 | diff --git a/great_expectations/dataset/base.py b/great_expectations/dataset/base.py
index 14acf8ecf..47c943cba 100644
--- a/great_expectations/dataset/base.py
+++ b/great_expectations/dataset/base.py
@@ -6,6 +6,7 @@ import traceback
import pandas as pd
import numpy as np
+from collections import defaultdict
from .util import DotDict, ensure_json_serializable
@@ -106,6 +107,12 @@ class DataSet(object):
else:
raise(err)
+ #Add a "success" object to the config
+ if output_format == "BOOLEAN_ONLY":
+ expectation_config["success_on_last_run"] = return_obj
+ else:
+ expectation_config["success_on_last_run"] = return_obj["success"]
+
#Append the expectation to the config.
self.append_expectation(expectation_config)
@@ -187,22 +194,111 @@ class DataSet(object):
self.default_expectation_args[argument] = value
- def get_expectations_config(self):
- return self._expectations_config
-
- def save_expectations_config(self, filepath=None):
+ def get_expectations_config(self,
+ discard_failed_expectations=True,
+ discard_output_format_kwargs=True,
+ discard_include_configs_kwargs=True,
+ discard_catch_exceptions_kwargs=True,
+ suppress_warnings=False
+ ):
+ config = dict(self._expectations_config)
+ config = copy.deepcopy(config)
+ expectations = config["expectations"]
+
+ discards = defaultdict(int)
+
+ if discard_failed_expectations:
+ new_expectations = []
+
+ for expectation in expectations:
+ #Note: This is conservative logic.
+ #Instead of retaining expectations IFF success==True, it discard expectations IFF success==False.
+ #In cases where expectation["success"] is missing or None, expectations are *retained*.
+ #Such a case could occur if expectations were loaded from a config file and never run.
+ if "success_on_last_run" in expectation and expectation["success_on_last_run"] == False:
+ discards["failed_expectations"] += 1
+ else:
+ new_expectations.append(expectation)
+
+ expectations = new_expectations
+
+ for expectation in expectations:
+ if "success_on_last_run" in expectation:
+ del expectation["success_on_last_run"]
+
+ if discard_output_format_kwargs:
+ if "output_format" in expectation["kwargs"]:
+ del expectation["kwargs"]["output_format"]
+ discards["output_format"] += 1
+
+ if discard_include_configs_kwargs:
+ if "include_configs" in expectation["kwargs"]:
+ del expectation["kwargs"]["include_configs"]
+ discards["include_configs"] += 1
+
+ if discard_catch_exceptions_kwargs:
+ if "catch_exceptions" in expectation["kwargs"]:
+ del expectation["kwargs"]["catch_exceptions"]
+ discards["catch_exceptions"] += 1
+
+
+ if not suppress_warnings:
+ """
+WARNING: get_expectations_config discarded
+ 12 failing expectations
+ 44 output_format kwargs
+ 0 include_config kwargs
+ 1 catch_exceptions kwargs
+If you wish to change this behavior, please set discard_failed_expectations, discard_output_format_kwargs, discard_include_configs_kwargs, and discard_catch_exceptions_kwargs appropirately.
+ """
+ if any([discard_failed_expectations, discard_output_format_kwargs, discard_include_configs_kwargs, discard_catch_exceptions_kwargs]):
+ print ("WARNING: get_expectations_config discarded")
+ if discard_failed_expectations:
+ print ("\t%d failing expectations" % discards["failed_expectations"])
+ if discard_output_format_kwargs:
+ print ("\t%d output_format kwargs" % discards["output_format"])
+ if discard_include_configs_kwargs:
+ print ("\t%d include_configs kwargs" % discards["include_configs"])
+ if discard_catch_exceptions_kwargs:
+ print ("\t%d catch_exceptions kwargs" % discards["catch_exceptions"])
+ print ("If you wish to change this behavior, please set discard_failed_expectations, discard_output_format_kwargs, discard_include_configs_kwargs, and discard_catch_exceptions_kwargs appropirately.")
+
+ config["expectations"] = expectations
+ return config
+
+ def save_expectations_config(
+ self,
+ filepath=None,
+ discard_failed_expectations=True,
+ discard_output_format_kwargs=True,
+ discard_include_configs_kwargs=True,
+ discard_catch_exceptions_kwargs=True,
+ suppress_warnings=False
+ ):
if filepath==None:
- #!!! Fetch the proper filepath from the project config
+ #FIXME: Fetch the proper filepath from the project config
pass
- expectation_config_str = json.dumps(self.get_expectations_config(), indent=2)
+ expectations_config = self.get_expectations_config(
+ discard_failed_expectations,
+ discard_output_format_kwargs,
+ discard_include_configs_kwargs,
+ discard_catch_exceptions_kwargs,
+ suppress_warnings
+ )
+ expectation_config_str = json.dumps(expectations_config, indent=2)
open(filepath, 'w').write(expectation_config_str)
def validate(self, expectations_config=None, catch_exceptions=True, output_format=None, include_config=None, only_return_failures=False):
results = []
if expectations_config is None:
- expectations_config = self.get_expectations_config()
+ expectations_config = self.get_expectations_config(
+ discard_failed_expectations=False,
+ discard_output_format_kwargs=False,
+ discard_include_configs_kwargs=False,
+ discard_catch_exceptions_kwargs=False,
+ )
for expectation in expectations_config['expectations']:
expectation_method = getattr(self, expectation['expectation_type'])
diff --git a/great_expectations/dataset/util.py b/great_expectations/dataset/util.py
index b8556219a..8bb9200b2 100644
--- a/great_expectations/dataset/util.py
+++ b/great_expectations/dataset/util.py
@@ -3,18 +3,26 @@
import numpy as np
from scipy import stats
import pandas as pd
+import copy
from functools import wraps
class DotDict(dict):
"""dot.notation access to dictionary attributes"""
+
def __getattr__(self, attr):
return self.get(attr)
+
__setattr__= dict.__setitem__
__delattr__= dict.__delitem__
+
def __dir__(self):
return self.keys()
+ #Cargo-cultishly copied from: https://github.com/spindlelabs/pyes/commit/d2076b385c38d6d00cebfe0df7b0d1ba8df934bc
+ def __deepcopy__(self, memo):
+ return DotDict([(copy.deepcopy(k, memo), copy.deepcopy(v, memo)) for k, v in self.items()])
+
class DocInherit(object):
"""
| Proposal: define a clear pattern for default output_format and catch_exceptions parameters
The default value of those parameters changes based on context according to the documentation, and that is currently implemented by ```None``` triggering the default value. Document that or agree it's clear. | great-expectations/great_expectations | diff --git a/tests/test_cli.py b/tests/test_cli.py
index 8d5f1057c..503c1d11a 100644
--- a/tests/test_cli.py
+++ b/tests/test_cli.py
@@ -49,6 +49,9 @@ class TestCLI(unittest.TestCase):
result = get_system_command_result(command_str)["output"]
json_result = json.loads(result)
except ValueError as ve:
+ print ("=== Result ==================================================")
+ print (result)
+ print ("=== Error ===================================================")
print(ve)
json_result = {}
diff --git a/tests/test_dataset.py b/tests/test_dataset.py
index 50e96e1ef..3e059955c 100644
--- a/tests/test_dataset.py
+++ b/tests/test_dataset.py
@@ -1,3 +1,7 @@
+import json
+import tempfile
+import shutil
+
import pandas as pd
import great_expectations as ge
@@ -33,6 +37,7 @@ class TestDataset(unittest.TestCase):
}
)
+ self.maxDiff = None
self.assertEqual(
D.get_expectations_config(),
{
@@ -81,6 +86,219 @@ class TestDataset(unittest.TestCase):
}
)
+ def test_get_and_save_expectation_config(self):
+ directory_name = tempfile.mkdtemp()
+
+ df = ge.dataset.PandasDataSet({
+ 'x' : [1,2,4],
+ 'y' : [1,2,5],
+ 'z' : ['hello', 'jello', 'mello'],
+ })
+ df.expect_column_values_to_be_in_set('x', [1,2,4])
+ df.expect_column_values_to_be_in_set('y', [1,2,4])
+ df.expect_column_values_to_match_regex('z', 'ello')
+
+ ### First test set ###
+
+ output_config = {
+ "expectations": [
+ {
+ "expectation_type": "expect_column_to_exist",
+ "kwargs": {
+ "column": "x"
+ }
+ },
+ {
+ "expectation_type": "expect_column_to_exist",
+ "kwargs": {
+ "column": "y"
+ }
+ },
+ {
+ "expectation_type": "expect_column_to_exist",
+ "kwargs": {
+ "column": "z"
+ }
+ },
+ {
+ "expectation_type": "expect_column_values_to_be_in_set",
+ "kwargs": {
+ "column": "x",
+ "values_set": [
+ 1,
+ 2,
+ 4
+ ]
+ }
+ },
+ {
+ "expectation_type": "expect_column_values_to_match_regex",
+ "kwargs": {
+ "column": "z",
+ "regex": "ello"
+ }
+ }
+ ],
+ "dataset_name": None
+ }
+
+ self.assertEqual(
+ df.get_expectations_config(),
+ output_config,
+ )
+
+ df.save_expectations_config(directory_name+'/temp1.json')
+ temp_file = open(directory_name+'/temp1.json')
+ self.assertEqual(
+ json.load(temp_file),
+ output_config,
+ )
+ temp_file.close()
+
+ ### Second test set ###
+
+ output_config = {
+ "expectations": [
+ {
+ "expectation_type": "expect_column_to_exist",
+ "kwargs": {
+ "column": "x"
+ }
+ },
+ {
+ "expectation_type": "expect_column_to_exist",
+ "kwargs": {
+ "column": "y"
+ }
+ },
+ {
+ "expectation_type": "expect_column_to_exist",
+ "kwargs": {
+ "column": "z"
+ }
+ },
+ {
+ "expectation_type": "expect_column_values_to_be_in_set",
+ "kwargs": {
+ "column": "x",
+ "values_set": [
+ 1,
+ 2,
+ 4
+ ]
+ }
+ },
+ {
+ "expectation_type": "expect_column_values_to_be_in_set",
+ "kwargs": {
+ "column": "y",
+ "values_set": [
+ 1,
+ 2,
+ 4
+ ]
+ }
+ },
+ {
+ "expectation_type": "expect_column_values_to_match_regex",
+ "kwargs": {
+ "column": "z",
+ "regex": "ello"
+ }
+ }
+ ],
+ "dataset_name": None
+ }
+
+ self.assertEqual(
+ df.get_expectations_config(
+ discard_failed_expectations=False
+ ),
+ output_config
+ )
+
+ df.save_expectations_config(
+ directory_name+'/temp2.json',
+ discard_failed_expectations=False
+ )
+ temp_file = open(directory_name+'/temp2.json')
+ self.assertEqual(
+ json.load(temp_file),
+ output_config,
+ )
+ temp_file.close()
+
+ ### Third test set ###
+
+ output_config = {
+ "expectations": [
+ {
+ "expectation_type": "expect_column_to_exist",
+ "kwargs": {
+ "column": "x"
+ }
+ },
+ {
+ "expectation_type": "expect_column_to_exist",
+ "kwargs": {
+ "column": "y"
+ }
+ },
+ {
+ "expectation_type": "expect_column_to_exist",
+ "kwargs": {
+ "column": "z"
+ }
+ },
+ {
+ "expectation_type": "expect_column_values_to_be_in_set",
+ "kwargs": {
+ "column": "x",
+ "values_set": [
+ 1,
+ 2,
+ 4
+ ],
+ "output_format": "BASIC"
+ }
+ },
+ {
+ "expectation_type": "expect_column_values_to_match_regex",
+ "kwargs": {
+ "column": "z",
+ "regex": "ello",
+ "output_format": "BASIC"
+ }
+ }
+ ],
+ "dataset_name": None
+ }
+
+ self.assertEqual(
+ df.get_expectations_config(
+ discard_output_format_kwargs=False,
+ discard_include_configs_kwargs=False,
+ discard_catch_exceptions_kwargs=False,
+ ),
+ output_config
+ )
+
+ df.save_expectations_config(
+ directory_name+'/temp3.json',
+ discard_output_format_kwargs=False,
+ discard_include_configs_kwargs=False,
+ discard_catch_exceptions_kwargs=False,
+ )
+ temp_file = open(directory_name+'/temp3.json')
+ self.assertEqual(
+ json.load(temp_file),
+ output_config,
+ )
+ temp_file.close()
+
+ # Clean up the output directory
+ shutil.rmtree(directory_name)
+
def test_format_column_map_output(self):
df = ge.dataset.PandasDataSet({
"x" : list("abcdefghijklmnopqrstuvwxyz")
@@ -228,6 +446,5 @@ class TestDataset(unittest.TestCase):
(False, 0.0)
)
-
if __name__ == "__main__":
unittest.main()
diff --git a/tests/test_great_expectations.py b/tests/test_great_expectations.py
index b5fbf1076..9295d469a 100644
--- a/tests/test_great_expectations.py
+++ b/tests/test_great_expectations.py
@@ -107,9 +107,12 @@ class TestValidation(unittest.TestCase):
expected_results
)
+
+ validation_results = my_df.validate(only_return_failures=True)
+ # print json.dumps(validation_results, indent=2)
assertDeepAlmostEqual(
self,
- my_df.validate(only_return_failures=True),
+ validation_results,
{"results": [{"exception_traceback": None, "expectation_type": "expect_column_values_to_be_in_set", "success": False, "exception_list": ["*"], "raised_exception": False, "kwargs": {"column": "PClass", "output_format": "COMPLETE", "values_set": ["1st", "2nd", "3rd"]}, "exception_index_list": [456]}]}
)
diff --git a/tests/test_pandas_dataset.py b/tests/test_pandas_dataset.py
index 2f92e50e2..2ce8a7673 100644
--- a/tests/test_pandas_dataset.py
+++ b/tests/test_pandas_dataset.py
@@ -1,7 +1,5 @@
import unittest
import json
-import hashlib
-import datetime
import numpy as np
import great_expectations as ge
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 1,
"test_score": 3
},
"num_modified_files": 2
} | 0.2 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest pytest-cov pytest-xdist pytest-mock pytest-asyncio"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.6",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | argh==0.27.2
attrs==22.2.0
certifi==2021.5.30
coverage==6.2
execnet==1.9.0
-e git+https://github.com/great-expectations/great_expectations.git@e4f42b80d95cff33339681464a72d833c692dd65#egg=great_expectations
importlib-metadata==4.8.3
iniconfig==1.1.1
jsonschema==3.2.0
numpy==1.19.5
packaging==21.3
pandas==1.1.5
pluggy==1.0.0
py==1.11.0
pyparsing==3.1.4
pyrsistent==0.18.0
pytest==7.0.1
pytest-asyncio==0.16.0
pytest-cov==4.0.0
pytest-mock==3.6.1
pytest-xdist==3.0.2
python-dateutil==2.9.0.post0
pytz==2025.2
scipy==1.5.4
six==1.17.0
tomli==1.2.3
typing_extensions==4.1.1
zipp==3.6.0
| name: great_expectations
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- argh==0.27.2
- attrs==22.2.0
- coverage==6.2
- execnet==1.9.0
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- jsonschema==3.2.0
- numpy==1.19.5
- packaging==21.3
- pandas==1.1.5
- pluggy==1.0.0
- py==1.11.0
- pyparsing==3.1.4
- pyrsistent==0.18.0
- pytest==7.0.1
- pytest-asyncio==0.16.0
- pytest-cov==4.0.0
- pytest-mock==3.6.1
- pytest-xdist==3.0.2
- python-dateutil==2.9.0.post0
- pytz==2025.2
- scipy==1.5.4
- six==1.17.0
- tomli==1.2.3
- typing-extensions==4.1.1
- zipp==3.6.0
prefix: /opt/conda/envs/great_expectations
| [
"tests/test_dataset.py::TestDataset::test_get_and_save_expectation_config"
]
| [
"tests/test_pandas_dataset.py::TestPandasDataset::test_expect_column_mean_to_be_between"
]
| [
"tests/test_cli.py::TestCLI::test_cli_arguments",
"tests/test_dataset.py::TestDataset::test_calc_map_expectation_success",
"tests/test_dataset.py::TestDataset::test_dataset",
"tests/test_dataset.py::TestDataset::test_format_column_map_output",
"tests/test_dataset.py::TestDataset::test_set_default_expectation_argument",
"tests/test_great_expectations.py::TestCustomClass::test_custom_class",
"tests/test_great_expectations.py::TestValidation::test_validate",
"tests/test_great_expectations.py::TestRepeatedAppendExpectation::test_validate",
"tests/test_pandas_dataset.py::TestPandasDataset::test_expect_column_most_common_value_to_be",
"tests/test_pandas_dataset.py::TestPandasDataset::test_expect_column_most_common_value_to_be_in_set",
"tests/test_pandas_dataset.py::TestPandasDataset::test_expect_column_proportion_of_unique_values_to_be_between",
"tests/test_pandas_dataset.py::TestPandasDataset::test_expect_column_stdev_to_be_between",
"tests/test_pandas_dataset.py::TestPandasDataset::test_expect_column_unique_value_count_to_be_between",
"tests/test_pandas_dataset.py::TestPandasDataset::test_expect_column_value_lengths_to_be_between",
"tests/test_pandas_dataset.py::TestPandasDataset::test_expect_column_values_to_be_between",
"tests/test_pandas_dataset.py::TestPandasDataset::test_expect_column_values_to_be_dateutil_parseable",
"tests/test_pandas_dataset.py::TestPandasDataset::test_expect_column_values_to_be_in_set",
"tests/test_pandas_dataset.py::TestPandasDataset::test_expect_column_values_to_be_in_type_list",
"tests/test_pandas_dataset.py::TestPandasDataset::test_expect_column_values_to_be_json_parseable",
"tests/test_pandas_dataset.py::TestPandasDataset::test_expect_column_values_to_be_null",
"tests/test_pandas_dataset.py::TestPandasDataset::test_expect_column_values_to_be_of_type",
"tests/test_pandas_dataset.py::TestPandasDataset::test_expect_column_values_to_be_unique",
"tests/test_pandas_dataset.py::TestPandasDataset::test_expect_column_values_to_match_json_schema",
"tests/test_pandas_dataset.py::TestPandasDataset::test_expect_column_values_to_match_regex",
"tests/test_pandas_dataset.py::TestPandasDataset::test_expect_column_values_to_match_regex_list",
"tests/test_pandas_dataset.py::TestPandasDataset::test_expect_column_values_to_match_strftime_format",
"tests/test_pandas_dataset.py::TestPandasDataset::test_expect_column_values_to_not_be_in_set",
"tests/test_pandas_dataset.py::TestPandasDataset::test_expect_column_values_to_not_be_null",
"tests/test_pandas_dataset.py::TestPandasDataset::test_expect_column_values_to_not_match_regex",
"tests/test_pandas_dataset.py::TestPandasDataset::test_expect_table_row_count_to_be_between",
"tests/test_pandas_dataset.py::TestPandasDataset::test_expect_table_row_count_to_equal",
"tests/test_pandas_dataset.py::TestPandasDataset::test_expectation_decorator_summary_mode",
"tests/test_pandas_dataset.py::TestPandasDataset::test_positional_arguments"
]
| []
| Apache License 2.0 | 1,814 | [
"great_expectations/dataset/base.py",
"great_expectations/dataset/util.py"
]
| [
"great_expectations/dataset/base.py",
"great_expectations/dataset/util.py"
]
|
|
zopefoundation__zope.server-7 | 4f54c909b0df4040732766080503535d80454410 | 2017-10-27 20:19:08 | 96b0b61756a9e9b29133f5d4be9ee3347b5fdd6a | diff --git a/.coveragerc b/.coveragerc
index b468a15..b34de8c 100644
--- a/.coveragerc
+++ b/.coveragerc
@@ -1,13 +1,5 @@
[run]
source = zope.server
-# https://github.com/zopefoundation/zope.server/issues/4
-omit =
- src/zope/server/logger/filelogger.py
- src/zope/server/logger/m_syslog.py
- src/zope/server/logger/rotatingfilelogger.py
- src/zope/server/logger/socketlogger.py
- src/zope/server/logger/sysloglogger.py
- src/zope/server/logger/taillogger.py
[report]
precision = 2
diff --git a/CHANGES.rst b/CHANGES.rst
index 3824c08..90d6e59 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -21,6 +21,14 @@
- Achieve and maintain 100% test coverage.
+- Remove all the custom logging implementations in
+ ``zope.server.logging`` and change the ``CommonAccessLogger`` and
+ ``CommonFTPActivityLogger`` to only work with Python standard
+ library loggers. The standard library supports all the logging
+ functions this package used to expose. It can be easily configured
+ with ZConfig. See `issue 4
+ <https://github.com/zopefoundation/zope.server/issues/4>`_.
+
3.9.0 (2013-03-13)
==================
diff --git a/src/zope/server/http/commonaccesslogger.py b/src/zope/server/http/commonaccesslogger.py
index 7499302..6f48303 100644
--- a/src/zope/server/http/commonaccesslogger.py
+++ b/src/zope/server/http/commonaccesslogger.py
@@ -19,22 +19,28 @@ import time
from zope.server.http.http_date import monthname
from zope.server.logger.pythonlogger import PythonLogger
from zope.server.logger.resolvinglogger import ResolvingLogger
-from zope.server.logger.unresolvinglogger import UnresolvingLogger
class CommonAccessLogger(object):
"""Outputs accesses in common HTTP log format.
"""
- def __init__(self, logger_object=None, resolver=None):
- if logger_object is None:
- # logger_object is an IMessageLogger
- logger_object = PythonLogger('accesslog')
+ def __init__(self, logger_object='accesslog', resolver=None):
+ """
- # self.output is an IRequestLogger
+ :keyword logger_object: Either a Python :class:`logging.Logger`
+ object, or a string giving the name of a Python logger to find.
+
+ .. versionchanged:: 4.0.0
+ Remove support for arbitrary ``IMessageLogger`` objects in
+ *logger_object*. Logging is now always directed through the
+ Python standard logging library.
+ """
+ self.output = PythonLogger(logger_object)
+
+ # self.output is an IRequestLogger, which PythonLogger implements
+ # as unresolving.
if resolver is not None:
- self.output = ResolvingLogger(resolver, logger_object)
- else:
- self.output = UnresolvingLogger(logger_object)
+ self.output = ResolvingLogger(resolver, self.output)
@classmethod
def compute_timezone_for_log(cls, tz):
diff --git a/src/zope/server/logger/filelogger.py b/src/zope/server/logger/filelogger.py
deleted file mode 100644
index 7c76aac..0000000
--- a/src/zope/server/logger/filelogger.py
+++ /dev/null
@@ -1,67 +0,0 @@
-##############################################################################
-#
-# Copyright (c) 2001, 2002 Zope Foundation and Contributors.
-# All Rights Reserved.
-#
-# This software is subject to the provisions of the Zope Public License,
-# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
-# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
-# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
-# FOR A PARTICULAR PURPOSE.
-#
-##############################################################################
-"""File Logger
-"""
-
-from zope.server.interfaces.logger import IMessageLogger
-from zope.interface import implementer
-
-@implementer(IMessageLogger)
-class FileLogger(object):
- """Simple File Logger
- """
-
- def __init__(self, file, flush=1, mode='a'):
- """pass this either a path or a file object."""
- if not hasattr(file, 'read'):
- if (file == '-'):
- import sys
- self.file = sys.stdout
- else:
- self.file = open(file, mode)
- else:
- self.file = file
- self.do_flush = flush
-
- def __repr__(self):
- return '<file logger: %s>' % self.file
-
- def write(self, data):
- self.file.write(data)
- self.maybe_flush()
-
- def writeline(self, line):
- self.file.writeline(line)
- self.maybe_flush()
-
- def writelines(self, lines):
- self.file.writelines(lines)
- self.maybe_flush()
-
- def maybe_flush(self):
- if self.do_flush:
- self.file.flush()
-
- def flush(self):
- self.file.flush()
-
- def softspace(self, *args):
- pass
-
- def logMessage(self, message):
- 'See IMessageLogger'
- if message[-1] not in ('\r', '\n'):
- self.write(message + '\n')
- else:
- self.write(message)
diff --git a/src/zope/server/logger/m_syslog.py b/src/zope/server/logger/m_syslog.py
deleted file mode 100644
index 92c8a36..0000000
--- a/src/zope/server/logger/m_syslog.py
+++ /dev/null
@@ -1,177 +0,0 @@
-# -*- Mode: Python; tab-width: 4 -*-
-
-# ======================================================================
-# Copyright 1997 by Sam Rushing
-#
-# All Rights Reserved
-#
-# Permission to use, copy, modify, and distribute this software and
-# its documentation for any purpose and without fee is hereby
-# granted, provided that the above copyright notice appear in all
-# copies and that both that copyright notice and this permission
-# notice appear in supporting documentation, and that the name of Sam
-# Rushing not be used in advertising or publicity pertaining to
-# distribution of the software without specific, written prior
-# permission.
-#
-# SAM RUSHING DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
-# INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN
-# NO EVENT SHALL SAM RUSHING BE LIABLE FOR ANY SPECIAL, INDIRECT OR
-# CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
-# OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
-# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
-# CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
-# ======================================================================
-
-"""socket interface to unix syslog.
-On Unix, there are usually two ways of getting to syslog: via a
-local unix-domain socket, or via the TCP service.
-
-Usually "/dev/log" is the unix domain socket. This may be different
-for other systems.
-
->>> my_client = syslog_client ('/dev/log')
-
-Otherwise, just use the UDP version, port 514.
-
->>> my_client = syslog_client (('my_log_host', 514))
-
-On win32, you will have to use the UDP version. Note that
-you can use this to log to other hosts (and indeed, multiple
-hosts).
-
-This module is not a drop-in replacement for the python
-<syslog> extension module - the interface is different.
-
-Usage:
-
->>> c = syslog_client()
->>> c = syslog_client ('/strange/non_standard_log_location')
->>> c = syslog_client (('other_host.com', 514))
->>> c.log ('testing', facility='local0', priority='debug')
-
-"""
-
-# TODO: support named-pipe syslog.
-# [see ftp://sunsite.unc.edu/pub/Linux/system/Daemons/syslog-fifo.tar.z]
-
-# from <linux/sys/syslog.h>:
-# ===========================================================================
-# priorities/facilities are encoded into a single 32-bit quantity, where the
-# bottom 3 bits are the priority (0-7) and the top 28 bits are the facility
-# (0-big number). Both the priorities and the facilities map roughly
-# one-to-one to strings in the syslogd(8) source code. This mapping is
-# included in this file.
-#
-# priorities (these are ordered)
-
-LOG_EMERG = 0 # system is unusable
-LOG_ALERT = 1 # action must be taken immediately
-LOG_CRIT = 2 # critical conditions
-LOG_ERR = 3 # error conditions
-LOG_WARNING = 4 # warning conditions
-LOG_NOTICE = 5 # normal but significant condition
-LOG_INFO = 6 # informational
-LOG_DEBUG = 7 # debug-level messages
-
-# facility codes
-LOG_KERN = 0 # kernel messages
-LOG_USER = 1 # random user-level messages
-LOG_MAIL = 2 # mail system
-LOG_DAEMON = 3 # system daemons
-LOG_AUTH = 4 # security/authorization messages
-LOG_SYSLOG = 5 # messages generated internally by syslogd
-LOG_LPR = 6 # line printer subsystem
-LOG_NEWS = 7 # network news subsystem
-LOG_UUCP = 8 # UUCP subsystem
-LOG_CRON = 9 # clock daemon
-LOG_AUTHPRIV = 10 # security/authorization messages (private)
-
-# other codes through 15 reserved for system use
-LOG_LOCAL0 = 16 # reserved for local use
-LOG_LOCAL1 = 17 # reserved for local use
-LOG_LOCAL2 = 18 # reserved for local use
-LOG_LOCAL3 = 19 # reserved for local use
-LOG_LOCAL4 = 20 # reserved for local use
-LOG_LOCAL5 = 21 # reserved for local use
-LOG_LOCAL6 = 22 # reserved for local use
-LOG_LOCAL7 = 23 # reserved for local use
-
-priority_names = {
- "alert": LOG_ALERT,
- "crit": LOG_CRIT,
- "debug": LOG_DEBUG,
- "emerg": LOG_EMERG,
- "err": LOG_ERR,
- "error": LOG_ERR, # DEPRECATED
- "info": LOG_INFO,
- "notice": LOG_NOTICE,
- "panic": LOG_EMERG, # DEPRECATED
- "warn": LOG_WARNING, # DEPRECATED
- "warning": LOG_WARNING,
- }
-
-facility_names = {
- "auth": LOG_AUTH,
- "authpriv": LOG_AUTHPRIV,
- "cron": LOG_CRON,
- "daemon": LOG_DAEMON,
- "kern": LOG_KERN,
- "lpr": LOG_LPR,
- "mail": LOG_MAIL,
- "news": LOG_NEWS,
- "security": LOG_AUTH, # DEPRECATED
- "syslog": LOG_SYSLOG,
- "user": LOG_USER,
- "uucp": LOG_UUCP,
- "local0": LOG_LOCAL0,
- "local1": LOG_LOCAL1,
- "local2": LOG_LOCAL2,
- "local3": LOG_LOCAL3,
- "local4": LOG_LOCAL4,
- "local5": LOG_LOCAL5,
- "local6": LOG_LOCAL6,
- "local7": LOG_LOCAL7,
- }
-
-import socket
-
-class syslog_client(object):
-
- def __init__(self, address='/dev/log'):
- self.address = address
- if type(address) == type(''):
- try: # APUE 13.4.2 specifes /dev/log as datagram socket
- self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
- self.socket.connect(address)
- except: # older linux may create as stream socket
- self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
- self.socket.connect(address)
- self.unix = 1
- else:
- self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
- self.unix = 0
-
-
- log_format_string = '<%d>%s\000'
-
- def log(self, message, facility=LOG_USER, priority=LOG_INFO):
- message = self.log_format_string % (
- self.encode_priority(facility, priority),
- message
- )
- if self.unix:
- self.socket.send(message)
- else:
- self.socket.sendto(message, self.address)
-
- def encode_priority(self, facility, priority):
- if type(facility) == type(''):
- facility = facility_names[facility]
- if type(priority) == type(''):
- priority = priority_names[priority]
- return (facility<<3) | priority
-
- def close(self):
- if self.unix:
- self.socket.close()
diff --git a/src/zope/server/logger/pythonlogger.py b/src/zope/server/logger/pythonlogger.py
index 3874e1e..e06e667 100644
--- a/src/zope/server/logger/pythonlogger.py
+++ b/src/zope/server/logger/pythonlogger.py
@@ -16,22 +16,35 @@
import logging
from zope.server.interfaces.logger import IMessageLogger
+from zope.server.interfaces.logger import IRequestLogger
from zope.interface import implementer
-@implementer(IMessageLogger)
+@implementer(IMessageLogger, IRequestLogger)
class PythonLogger(object):
"""Proxy for Python's logging module"""
def __init__(self, name=None, level=logging.INFO):
+ """
+ :keyword str name: The name of a logger to use,
+ or the logger itself.
+ """
+ name = getattr(name, 'name', name)
self.name = name
self.level = level
self.logger = logging.getLogger(name)
def __repr__(self):
return '<python logger: %s %s>' % (self.name,
- logging.getLevelName(self.level))
+ logging.getLevelName(self.level))
def logMessage(self, message):
"""See IMessageLogger"""
self.logger.log(self.level, message.rstrip())
+
+ def logRequest(self, ip, message):
+ """
+ Log request is implemented to call :meth:`logMessage` without
+ attempting any resolution.
+ """
+ self.logMessage('%s%s' % (ip, message))
diff --git a/src/zope/server/logger/rotatingfilelogger.py b/src/zope/server/logger/rotatingfilelogger.py
deleted file mode 100644
index d09547f..0000000
--- a/src/zope/server/logger/rotatingfilelogger.py
+++ /dev/null
@@ -1,91 +0,0 @@
-##############################################################################
-#
-# Copyright (c) 2001, 2002 Zope Foundation and Contributors.
-# All Rights Reserved.
-#
-# This software is subject to the provisions of the Zope Public License,
-# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
-# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
-# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
-# FOR A PARTICULAR PURPOSE.
-#
-##############################################################################
-"""Rotating File Logger
-
-Rotates a log file in time intervals.
-"""
-import time
-import os
-import stat
-
-from zope.server.logger.filelogger import FileLogger
-
-class RotatingFileLogger(FileLogger):
- """ If freq is non-None we back up 'daily', 'weekly', or
- 'monthly'. Else if maxsize is non-None we back up whenever
- the log gets to big. If both are None we never back up.
-
- Like a FileLogger, but it must be attached to a filename.
- When the log gets too full, or a certain time has passed, it
- backs up the log and starts a new one. Note that backing up
- the log is done via 'mv' because anything else (cp, gzip)
- would take time, during which medusa would do nothing else.
- """
-
- def __init__(self, file, freq=None, maxsize=None, flush=1, mode='a'):
- self.filename = file
- self.mode = mode
- self.file = open(file, mode)
- self.freq = freq
- self.maxsize = maxsize
- self.rotate_when = self.next_backup(self.freq)
- self.do_flush = flush
-
- def __repr__(self):
- return '<rotating-file logger: %s>' % self.file
-
- # We back up at midnight every 1) day, 2) monday, or 3) 1st of month
- def next_backup(self, freq):
- (yr, mo, day, hr, min, sec, wd, jday, dst) = \
- time.localtime(time.time())
- if freq == 'daily':
- return time.mktime((yr,mo,day+1, 0,0,0, 0,0,-1))
- elif freq == 'weekly':
- # wd(monday)==0
- return time.mktime((yr,mo,day-wd+7, 0,0,0, 0,0,-1))
- elif freq == 'monthly':
- return time.mktime((yr,mo+1,1, 0,0,0, 0,0,-1))
- else:
- return None # not a date-based backup
-
- def maybe_flush(self): # rotate first if necessary
- self.maybe_rotate()
- if self.do_flush: # from file_logger()
- self.file.flush()
-
- def maybe_rotate(self):
- if self.freq and time.time() > self.rotate_when:
- self.rotate()
- self.rotate_when = self.next_backup(self.freq)
- elif self.maxsize: # rotate when we get too big
- try:
- if os.stat(self.filename)[stat.ST_SIZE] > self.maxsize:
- self.rotate()
- except os.error: # file not found, probably
- self.rotate() # will create a new file
-
- def rotate(self):
- yr, mo, day, hr, min, sec, wd, jday, dst = time.localtime(time.time())
- try:
- self.file.close()
- newname = '%s.ends%04d%02d%02d' % (self.filename, yr, mo, day)
- try:
- open(newname, "r").close() # check if file exists
- newname = newname + "-%02d%02d%02d" % (hr, min, sec)
- except IOError: # concatenation of YEAR MO DY is unique
- pass
- os.rename(self.filename, newname)
- self.file = open(self.filename, self.mode)
- except IOError:
- pass
diff --git a/src/zope/server/logger/socketlogger.py b/src/zope/server/logger/socketlogger.py
deleted file mode 100644
index 43de5c4..0000000
--- a/src/zope/server/logger/socketlogger.py
+++ /dev/null
@@ -1,45 +0,0 @@
-##############################################################################
-#
-# Copyright (c) 2001, 2002 Zope Foundation and Contributors.
-# All Rights Reserved.
-#
-# This software is subject to the provisions of the Zope Public License,
-# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
-# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
-# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
-# FOR A PARTICULAR PURPOSE.
-#
-##############################################################################
-"""Socket Logger
-
-Sends logging messages to a socket.
-"""
-import asynchat
-import socket
-
-from zope.server.interfaces.logger import IMessageLogger
-from zope.interface import implementer
-
-@implementer(IMessageLogger)
-class SocketLogger(asynchat.async_chat):
- """Log to a stream socket, asynchronously."""
-
- def __init__(self, address):
- if type(address) == type(''):
- self.create_socket(socket.AF_UNIX, socket.SOCK_STREAM)
- else:
- self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
-
- self.connect(address)
- self.address = address
-
- def __repr__(self):
- return '<socket logger: address=%s>' % (self.address)
-
- def logMessage(self, message):
- 'See IMessageLogger'
- if message[-2:] != '\r\n':
- self.socket.push(message + '\r\n')
- else:
- self.socket.push(message)
diff --git a/src/zope/server/logger/sysloglogger.py b/src/zope/server/logger/sysloglogger.py
deleted file mode 100644
index 56b0b55..0000000
--- a/src/zope/server/logger/sysloglogger.py
+++ /dev/null
@@ -1,57 +0,0 @@
-##############################################################################
-#
-# Copyright (c) 2001, 2002 Zope Foundation and Contributors.
-# All Rights Reserved.
-#
-# This software is subject to the provisions of the Zope Public License,
-# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
-# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
-# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
-# FOR A PARTICULAR PURPOSE.
-#
-##############################################################################
-"""Syslog Logger
-
-Writes log messages to syslog.
-"""
-
-import os
-from zope.server.logger import m_syslog
-
-from zope.server.interfaces.logger import IMessageLogger
-from zope.interface import implementer
-
-
-@implementer(IMessageLogger)
-class SyslogLogger(m_syslog.syslog_client):
- """syslog is a line-oriented log protocol - this class would be
- appropriate for FTP or HTTP logs, but not for dumping stderr
- to.
-
- TODO: a simple safety wrapper that will ensure that the line
- sent to syslog is reasonable.
-
- TODO: async version of syslog_client: now, log entries use
- blocking send()
- """
-
- svc_name = 'zope'
- pid_str = str(os.getpid())
-
- def __init__ (self, address, facility='user'):
- m_syslog.syslog_client.__init__ (self, address)
- self.facility = m_syslog.facility_names[facility]
- self.address=address
-
- def __repr__ (self):
- return '<syslog logger address=%s>' % (repr(self.address))
-
- def logMessage(self, message):
- 'See IMessageLogger'
- m_syslog.syslog_client.log (
- self,
- '%s[%s]: %s' % (self.svc_name, self.pid_str, message),
- facility=self.facility,
- priority=m_syslog.LOG_INFO
- )
diff --git a/src/zope/server/logger/taillogger.py b/src/zope/server/logger/taillogger.py
deleted file mode 100644
index a4199c1..0000000
--- a/src/zope/server/logger/taillogger.py
+++ /dev/null
@@ -1,39 +0,0 @@
-##############################################################################
-#
-# Copyright (c) 2001, 2002 Zope Foundation and Contributors.
-# All Rights Reserved.
-#
-# This software is subject to the provisions of the Zope Public License,
-# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
-# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
-# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
-# FOR A PARTICULAR PURPOSE.
-#
-##############################################################################
-"""Tail Logger
-"""
-from zope.server.interfaces.logger import IMessageLogger
-from zope.interface import implementer
-
-@implementer(IMessageLogger)
-class TailLogger(object):
- """Keep track of the last <size> log messages"""
-
- def __init__(self, logger, size=500):
- self.size = size
- self.logger = logger
- self.messages = []
-
- def logMessage(self, message):
- 'See IMessageLogger'
- self.messages.append(strip_eol(message))
- if len(self.messages) > self.size:
- del self.messages[0]
- self.logger.logMessage(message)
-
-
-def strip_eol(line):
- while line and line[-1] in '\r\n':
- line = line[:-1]
- return line
diff --git a/src/zope/server/logger/unresolvinglogger.py b/src/zope/server/logger/unresolvinglogger.py
deleted file mode 100644
index 91a6c7b..0000000
--- a/src/zope/server/logger/unresolvinglogger.py
+++ /dev/null
@@ -1,28 +0,0 @@
-##############################################################################
-#
-# Copyright (c) 2001, 2002 Zope Foundation and Contributors.
-# All Rights Reserved.
-#
-# This software is subject to the provisions of the Zope Public License,
-# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
-# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
-# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
-# FOR A PARTICULAR PURPOSE.
-#
-##############################################################################
-"""Unresolving Logger
-"""
-from zope.server.interfaces.logger import IRequestLogger
-from zope.interface import implementer
-
-@implementer(IRequestLogger)
-class UnresolvingLogger(object):
- """Just in case you don't want to resolve"""
-
- def __init__(self, logger):
- self.logger = logger
-
- def logRequest(self, ip, message):
- 'See IRequestLogger'
- self.logger.logMessage('%s%s' % (ip, message))
| Does this package still need its own implementation of Rotating/Socket/SysLog handlers?
It includes them, but it doesn't use them. They are completely untested.
They have been mostly untouched since they were moved here. They appear to date back to Python 2.4 or earlier (surviving log message: "remove support for Python 2.4 and 2.5"). 2.3 is when the standard library logging module was introduced. As of 2.7, the stdlib has analogues to all of these handlers. ZConfig can configure them. The default in `CommonAccessLogger` is to redirect logging to the Python stdlib logging package, and `zope.app.server.wsgi` uses that default. `zope.app.server` also includes ZConfig directives for configuring the Python logger this winds up using. If the other handlers are used, I'm not finding where.
I'm working on test coverage for this package, and I'd prefer not to have to write entire test suites for these things if they're not used. Ideally we'd be able to drop all of them, and perhaps simplify CommonAccessLogger to directly use the stdlib package instead of redirecting through this module's PythonLogger (with some layers to account for un/resolving of addresses). Somewhat less ideally we would be able to implement them on top of the functionality that the stdlib provides. | zopefoundation/zope.server | diff --git a/src/zope/server/ftp/tests/test_logger.py b/src/zope/server/ftp/tests/test_logger.py
index 6b676bc..561f2d7 100644
--- a/src/zope/server/ftp/tests/test_logger.py
+++ b/src/zope/server/ftp/tests/test_logger.py
@@ -8,6 +8,8 @@ import unittest
from zope.server.ftp import logger
+from zope.testing import loggingsupport
+
class TestCommonFTPActivityLogger(unittest.TestCase):
def test_log(self):
@@ -18,15 +20,12 @@ class TestCommonFTPActivityLogger(unittest.TestCase):
addr = ('localhost',)
m_name = 'head'
- msgs = []
- class Output(object):
- def logMessage(self, msg):
- msgs.append(msg)
+ handler = loggingsupport.InstalledHandler("accesslog")
+ self.addCleanup(handler.uninstall)
- output = Output()
- cal = logger.CommonFTPActivityLogger(output)
+ cal = logger.CommonFTPActivityLogger()
cal.log(Task)
- self.assertEqual(1, len(msgs))
- self.assertIn('localhost', msgs[0])
- self.assertIn('user', msgs[0])
+ self.assertEqual(1, len(handler.records))
+ self.assertIn('localhost', str(handler))
+ self.assertIn('user', str(handler))
diff --git a/src/zope/server/http/tests/test_commonaccesslogger.py b/src/zope/server/http/tests/test_commonaccesslogger.py
index c9e8489..8846733 100644
--- a/src/zope/server/http/tests/test_commonaccesslogger.py
+++ b/src/zope/server/http/tests/test_commonaccesslogger.py
@@ -27,16 +27,13 @@ class CommonAccessLogger(_CommonAccessLogger):
class TestCommonAccessLogger(unittest.TestCase):
def test_default_constructor(self):
-
- from zope.server.logger.unresolvinglogger import UnresolvingLogger
from zope.server.logger.pythonlogger import PythonLogger
logger = CommonAccessLogger()
# CommonHitLogger is registered as an argumentless factory via
# ZCML, so the defaults should be sensible
- self.assertIsInstance(logger.output, UnresolvingLogger)
- self.assertIsInstance(logger.output.logger, PythonLogger)
+ self.assertIsInstance(logger.output, PythonLogger)
self.assertEqual(logger.output.logger.name, 'accesslog')
- self.assertEqual(logger.output.logger.level, logging.INFO)
+ self.assertEqual(logger.output.level, logging.INFO)
def test_compute_timezone_for_log_negative(self):
tz = -3600
@@ -77,11 +74,9 @@ class TestCommonAccessLogger(unittest.TestCase):
def test_log_request(self):
import time
-
- class Output(object):
- msgs = ()
- def logMessage(self, msg):
- self.msgs += (msg,)
+ from zope.testing import loggingsupport
+ handler = loggingsupport.InstalledHandler("accesslog")
+ self.addCleanup(handler.uninstall)
class Resolver(object):
def resolve_ptr(self, ip, then):
@@ -105,14 +100,14 @@ class TestCommonAccessLogger(unittest.TestCase):
time.altzone = -3600
time.time = t
try:
- output = Output()
- cal = CommonAccessLogger(output, Resolver())
+ cal = CommonAccessLogger(resolver=Resolver())
cal.log(Task())
finally:
time.daylight = orig_dl
time.altzone = orig_az
time.time = orig_t
+ self.assertEqual(1, len(handler.records))
self.assertEqual(
- 'host - anonymous [29/Nov/1973:21:33:09 +0100] "GET / HTTP/1.0" 200 OK 10 "" ""\n',
- output.msgs[0])
+ 'host - anonymous [29/Nov/1973:21:33:09 +0100] "GET / HTTP/1.0" 200 OK 10 "" ""',
+ handler.records[0].getMessage())
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_removed_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 2,
"test_score": 3
},
"num_modified_files": 4
} | 3.9 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[test]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"zope-testrunner",
"pytest"
],
"pre_install": null,
"python": "3.6",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work
certifi==2021.5.30
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work
multipart==1.1.0
packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work
Paste==3.10.1
pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pytest==6.2.4
python-gettext==4.1
pytz==2025.2
six==1.17.0
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
zope.browser==2.4
zope.component==5.1.0
zope.configuration==4.4.1
zope.contenttype==4.6
zope.deprecation==4.4.0
zope.event==4.6
zope.exceptions==4.6
zope.hookable==5.4
zope.i18n==4.9.0
zope.i18nmessageid==5.1.1
zope.interface==5.5.2
zope.location==4.3
zope.proxy==4.6.1
zope.publisher==6.1.0
zope.schema==6.2.1
zope.security==5.8
-e git+https://github.com/zopefoundation/zope.server.git@4f54c909b0df4040732766080503535d80454410#egg=zope.server
zope.testing==5.0.1
zope.testrunner==5.6
| name: zope.server
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=21.4.0=pyhd3eb1b0_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- importlib-metadata=4.8.1=py36h06a4308_0
- importlib_metadata=4.8.1=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- more-itertools=8.12.0=pyhd3eb1b0_0
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=21.3=pyhd3eb1b0_0
- pip=21.2.2=py36h06a4308_0
- pluggy=0.13.1=py36h06a4308_0
- py=1.11.0=pyhd3eb1b0_0
- pyparsing=3.0.4=pyhd3eb1b0_0
- pytest=6.2.4=py36h06a4308_2
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- toml=0.10.2=pyhd3eb1b0_0
- typing_extensions=4.1.1=pyh06a4308_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zipp=3.6.0=pyhd3eb1b0_0
- zlib=1.2.13=h5eee18b_1
- pip:
- multipart==1.1.0
- paste==3.10.1
- python-gettext==4.1
- pytz==2025.2
- six==1.17.0
- zope-browser==2.4
- zope-component==5.1.0
- zope-configuration==4.4.1
- zope-contenttype==4.6
- zope-deprecation==4.4.0
- zope-event==4.6
- zope-exceptions==4.6
- zope-hookable==5.4
- zope-i18n==4.9.0
- zope-i18nmessageid==5.1.1
- zope-interface==5.5.2
- zope-location==4.3
- zope-proxy==4.6.1
- zope-publisher==6.1.0
- zope-schema==6.2.1
- zope-security==5.8
- zope-testing==5.0.1
- zope-testrunner==5.6
prefix: /opt/conda/envs/zope.server
| [
"src/zope/server/http/tests/test_commonaccesslogger.py::TestCommonAccessLogger::test_default_constructor"
]
| []
| [
"src/zope/server/ftp/tests/test_logger.py::TestCommonFTPActivityLogger::test_log",
"src/zope/server/http/tests/test_commonaccesslogger.py::TestCommonAccessLogger::test_compute_timezone_for_log_negative",
"src/zope/server/http/tests/test_commonaccesslogger.py::TestCommonAccessLogger::test_compute_timezone_for_log_positive",
"src/zope/server/http/tests/test_commonaccesslogger.py::TestCommonAccessLogger::test_log_date_string_daylight",
"src/zope/server/http/tests/test_commonaccesslogger.py::TestCommonAccessLogger::test_log_date_string_non_daylight",
"src/zope/server/http/tests/test_commonaccesslogger.py::TestCommonAccessLogger::test_log_request"
]
| []
| Zope Public License 2.1 | 1,815 | [
"src/zope/server/logger/pythonlogger.py",
"src/zope/server/logger/m_syslog.py",
"src/zope/server/logger/filelogger.py",
"src/zope/server/logger/rotatingfilelogger.py",
"src/zope/server/logger/socketlogger.py",
"src/zope/server/http/commonaccesslogger.py",
"src/zope/server/logger/taillogger.py",
"src/zope/server/logger/unresolvinglogger.py",
".coveragerc",
"CHANGES.rst",
"src/zope/server/logger/sysloglogger.py"
]
| [
"src/zope/server/logger/pythonlogger.py",
"src/zope/server/logger/m_syslog.py",
"src/zope/server/logger/filelogger.py",
"src/zope/server/logger/rotatingfilelogger.py",
"src/zope/server/logger/socketlogger.py",
"src/zope/server/http/commonaccesslogger.py",
"src/zope/server/logger/taillogger.py",
"src/zope/server/logger/unresolvinglogger.py",
".coveragerc",
"CHANGES.rst",
"src/zope/server/logger/sysloglogger.py"
]
|
|
MechanicalSoup__MechanicalSoup-152 | 0d147eb88b3bffb4853b841b418924cbb569c4ea | 2017-10-28 08:53:48 | 0d147eb88b3bffb4853b841b418924cbb569c4ea | moy: Looks good to me. 0-based index shouldn't be a problem for programmers. | diff --git a/docs/ChangeLog.rst b/docs/ChangeLog.rst
index 1fd119d..cbaa569 100644
--- a/docs/ChangeLog.rst
+++ b/docs/ChangeLog.rst
@@ -23,7 +23,9 @@ Main changes:
* We now have a documentation: https://mechanicalsoup.readthedocs.io/
* ``StatefulBrowser.select_form`` can now be called without argument,
- and defaults to ``"form"`` in this case.
+ and defaults to ``"form"`` in this case. It also has a new argument,
+ ``nr`` (defaults to 0), which can be used to specify the index of
+ the form to select if multiple forms match the selection criteria.
* We now use requirement files. You can install the dependencies of
Mechanicalsoup with e.g.::
diff --git a/mechanicalsoup/stateful_browser.py b/mechanicalsoup/stateful_browser.py
index 8d27bbc..5baf098 100644
--- a/mechanicalsoup/stateful_browser.py
+++ b/mechanicalsoup/stateful_browser.py
@@ -147,31 +147,32 @@ class StatefulBrowser(Browser):
"""
return self.open(self.absolute_url(url), *args, **kwargs)
- def select_form(self, selector="form", *args, **kwargs):
+ def select_form(self, selector="form", nr=0):
"""Select a form in the current page.
+ :param selector: CSS selector to identify the form to select.
+ If not specified, ``selector`` defaults to "form", which is
+ useful if, e.g., there is only one form on the page.
+ For ``selector`` syntax, see the `.select() method in BeautifulSoup
+ <https://www.crummy.com/software/BeautifulSoup/bs4/doc/#css-selectors>`__.
+ :param nr: A zero-based index specifying which form among those that
+ match ``selector`` will be selected. Useful when one or more forms
+ have the same attributes as the form you want to select, and its
+ position on the page is the only way to uniquely identify it.
+ Default is the first matching form (``nr=0``).
+
:return: The selected form as a soup object. It can also be
retrieved later with :func:`get_current_form`.
-
- Arguments are the same as the select() method for a soup
- object. ``selector`` is a string containing a CSS selector.
-
- If the ``selector`` argument is not given, it defaults
- to "form", so one can
- call :func:`~mechanicalsoup.Browser.select_form()` to select
- the form if there is only one form in the page.
-
- See also: `.select() method in BeautifulSoup
- <https://www.crummy.com/software/BeautifulSoup/bs4/doc/#css-selectors>`__
"""
- found_forms = self.__current_page.select(selector, *args, **kwargs)
- if len(found_forms) < 1:
+ # nr is a 0-based index for consistency with mechanize
+ found_forms = self.__current_page.select(selector, limit=nr + 1)
+ if len(found_forms) != nr + 1:
if self.__debug:
- print('select_form failed for', *args)
+ print('select_form failed for', selector)
self.launch_browser()
raise LinkNotFoundError()
- self.__current_form = Form(found_forms[0])
+ self.__current_form = Form(found_forms[-1])
return self.__current_form
def submit_selected(self, btnName=None, *args, **kwargs):
| Implement nr option?
In MechanicalSoup, almost all of our methods that find some element return or operate on the first one that is found (`Form.choose_submit` appears to be the recently-modified exception). If, for example, you have a page with two `<form>...</form>` with no unique attributes, then you cannot select the second form with `StatefulBrowser.select_form`.
This problem is solved in Mechanize by giving these methods an `nr=1` argument, which selects the _nr_-th match, and the first by default. We could certainly add this to many of the methods and retain the current default behavior entirely. I think this alone would be a worthwhile enhancement.
One related (but perhaps separate) issue is the lack of feedback when you omit the `nr` option and get an element that you don't expect, likely resulting in an indecipherable error, or worse, silently incorrect behavior. In my ideal world, you'd specify `nr` when you know you want the _nr_-th match, and if `nr` is omitted you demand that there is only one match. This seems like the safest option, but may be too draconian. Perhaps it would be suitable for a "debug" or "strict" mode? | MechanicalSoup/MechanicalSoup | diff --git a/tests/test_stateful_browser.py b/tests/test_stateful_browser.py
index 58eb88d..19febf0 100644
--- a/tests/test_stateful_browser.py
+++ b/tests/test_stateful_browser.py
@@ -326,5 +326,20 @@ def test_with():
assert browser.session is None
+def test_select_form_nr():
+ """Test the nr option of select_form."""
+ forms = """<form id="a"></form><form id="b"></form><form id="c"></form>"""
+ with mechanicalsoup.StatefulBrowser() as browser:
+ browser.open_fake_page(forms)
+ form = browser.select_form()
+ assert form.form['id'] == "a"
+ form = browser.select_form(nr=1)
+ assert form.form['id'] == "b"
+ form = browser.select_form(nr=2)
+ assert form.form['id'] == "c"
+ with pytest.raises(mechanicalsoup.LinkNotFoundError):
+ browser.select_form(nr=3)
+
+
if __name__ == '__main__':
pytest.main(sys.argv)
| {
"commit_name": "merge_commit",
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 1,
"test_score": 2
},
"num_modified_files": 2
} | 0.8 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-cov",
"pytest-flake8",
"pytest-mock",
"requests_mock"
],
"pre_install": null,
"python": "3.6",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs==22.2.0
beautifulsoup4==4.12.3
certifi==2021.5.30
charset-normalizer==2.0.12
coverage==6.2
flake8==5.0.4
idna==3.10
importlib-metadata==4.2.0
iniconfig==1.1.1
lxml==5.3.1
mccabe==0.7.0
-e git+https://github.com/MechanicalSoup/MechanicalSoup.git@0d147eb88b3bffb4853b841b418924cbb569c4ea#egg=MechanicalSoup
packaging==21.3
pluggy==1.0.0
py==1.11.0
pycodestyle==2.9.1
pyflakes==2.5.0
pyparsing==3.1.4
pytest==7.0.1
pytest-cov==4.0.0
pytest-flake8==1.1.1
pytest-mock==3.6.1
requests==2.27.1
requests-mock==1.12.1
six==1.17.0
soupsieve==2.3.2.post1
tomli==1.2.3
typing_extensions==4.1.1
urllib3==1.26.20
zipp==3.6.0
| name: MechanicalSoup
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- attrs==22.2.0
- beautifulsoup4==4.12.3
- charset-normalizer==2.0.12
- coverage==6.2
- flake8==5.0.4
- idna==3.10
- importlib-metadata==4.2.0
- iniconfig==1.1.1
- lxml==5.3.1
- mccabe==0.7.0
- packaging==21.3
- pluggy==1.0.0
- py==1.11.0
- pycodestyle==2.9.1
- pyflakes==2.5.0
- pyparsing==3.1.4
- pytest==7.0.1
- pytest-cov==4.0.0
- pytest-flake8==1.1.1
- pytest-mock==3.6.1
- requests==2.27.1
- requests-mock==1.12.1
- six==1.17.0
- soupsieve==2.3.2.post1
- tomli==1.2.3
- typing-extensions==4.1.1
- urllib3==1.26.20
- zipp==3.6.0
prefix: /opt/conda/envs/MechanicalSoup
| [
"tests/test_stateful_browser.py::test_select_form_nr"
]
| [
"tests/test_stateful_browser.py::flake-8::FLAKE8",
"tests/test_stateful_browser.py::test_submit_online",
"tests/test_stateful_browser.py::test_form_noaction"
]
| [
"tests/test_stateful_browser.py::test_request_forward",
"tests/test_stateful_browser.py::test_no_404",
"tests/test_stateful_browser.py::test_404",
"tests/test_stateful_browser.py::test_user_agent",
"tests/test_stateful_browser.py::test_open_relative",
"tests/test_stateful_browser.py::test_links",
"tests/test_stateful_browser.py::test_submit_btnName[input]",
"tests/test_stateful_browser.py::test_submit_btnName[button]",
"tests/test_stateful_browser.py::test_get_set_debug",
"tests/test_stateful_browser.py::test_list_links",
"tests/test_stateful_browser.py::test_launch_browser",
"tests/test_stateful_browser.py::test_find_link",
"tests/test_stateful_browser.py::test_verbose",
"tests/test_stateful_browser.py::test_new_control",
"tests/test_stateful_browser.py::test_form_noname",
"tests/test_stateful_browser.py::test_form_multiple",
"tests/test_stateful_browser.py::test_with"
]
| []
| MIT License | 1,816 | [
"docs/ChangeLog.rst",
"mechanicalsoup/stateful_browser.py"
]
| [
"docs/ChangeLog.rst",
"mechanicalsoup/stateful_browser.py"
]
|
sendgrid__sendgrid-python-476 | a403813a9f4e95f8695b9a4a547dfbcedccc8671 | 2017-10-28 16:10:30 | e270db212f25ad8ca4cc48aa17dc30b48cb3758a | diff --git a/sendgrid/helpers/inbound/send.py b/sendgrid/helpers/inbound/send.py
index d786f67..9cbb5aa 100644
--- a/sendgrid/helpers/inbound/send.py
+++ b/sendgrid/helpers/inbound/send.py
@@ -26,17 +26,16 @@ class Send(object):
"Content-Type": "multipart/form-data; boundary=xYzZY"
}
client = Client(host=self.url, request_headers=headers)
- f = open(payload_filepath, 'r')
- data = f.read()
- return client.post(request_body=data)
+ with open(payload_filepath, 'r') as f:
+ data = f.read()
+ return client.post(request_body=data)
@property
def url(self):
"""URL to send to."""
return self._url
-
-if __name__ == '__main__':
+def main():
config = Config()
parser = argparse.ArgumentParser(description='Test data and optional host.')
parser.add_argument('data',
@@ -52,3 +51,6 @@ if __name__ == '__main__':
print(response.status_code)
print(response.headers)
print(response.body)
+
+if __name__ == '__main__':
+ main()
\ No newline at end of file
diff --git a/tox.ini b/tox.ini
index d3e8924..9336a97 100644
--- a/tox.ini
+++ b/tox.ini
@@ -19,12 +19,14 @@ commands = coverage erase
coverage run {envbindir}/unit2 discover -v []
coverage report
deps = unittest2
+ mock
{[testenv]deps}
basepython = python2.6
[testenv:py27]
commands = {[testenv]commands}
deps = {[testenv]deps}
+ mock
basepython = python2.7
[testenv:py34]
| Add tests for Send.py
#### Issue Summary
CodeCov is showing that we're missing some testing on send.py.
[Please see their page and add some tests](https://codecov.io/gh/sendgrid/sendgrid-python/compare/db608f74fbbb4b1d4d71c644da9614de6ed900e3...86abbc199800fefe9114cab7535d28a8114cca78/src/sendgrid/helpers/inbound/send.py) | sendgrid/sendgrid-python | diff --git a/test/test_send.py b/test/test_send.py
new file mode 100644
index 0000000..16d496b
--- /dev/null
+++ b/test/test_send.py
@@ -0,0 +1,42 @@
+import argparse
+from sendgrid.helpers.inbound import send
+
+try:
+ import unittest2 as unittest
+except ImportError:
+ import unittest
+
+try:
+ import unittest.mock as mock
+except ImportError:
+ import mock
+
+
+class UnitTests(unittest.TestCase):
+ def setUp(self):
+ self.client_mock = mock.patch('sendgrid.helpers.inbound.send.Client')
+ self.open_mock = mock.patch('sendgrid.helpers.inbound.send.open',
+ mock.mock_open(), create=True)
+ self.client_mock.start()
+ self.open_mock.start()
+
+ def tearDown(self):
+ self.client_mock.stop()
+ self.open_mock.stop()
+
+ def test_send(self):
+
+ fake_url = 'https://fake_url'
+ x = send.Send(fake_url)
+ x.test_payload(fake_url)
+
+ send.Client.assert_called_once_with(host=fake_url, request_headers={'User-Agent': 'SendGrid-Test',
+ 'Content-Type': 'multipart/form-data; boundary=xYzZY'})
+
+ def test_main_call(self):
+ fake_url = 'https://fake_url'
+
+ with mock.patch('argparse.ArgumentParser.parse_args', return_value=argparse.Namespace(host=fake_url, data='test_file.txt')):
+ send.main()
+ send.Client.assert_called_once_with(host=fake_url, request_headers={'User-Agent': 'SendGrid-Test',
+ 'Content-Type': 'multipart/form-data; boundary=xYzZY'})
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks",
"has_git_commit_hash",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 2,
"test_score": 0
},
"num_modified_files": 2
} | 5.3 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"tox",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.6",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs==22.2.0
certifi==2021.5.30
dataclasses==0.8
distlib==0.3.9
filelock==3.4.1
Flask==0.10.1
importlib-metadata==4.8.3
importlib-resources==5.4.0
iniconfig==1.1.1
itsdangerous==2.0.1
Jinja2==3.0.3
MarkupSafe==2.0.1
packaging==21.3
platformdirs==2.4.0
pluggy==1.0.0
py==1.11.0
pyparsing==3.1.4
pytest==7.0.1
python-http-client==3.3.7
PyYAML==3.11
-e git+https://github.com/sendgrid/sendgrid-python.git@a403813a9f4e95f8695b9a4a547dfbcedccc8671#egg=sendgrid
six==1.17.0
toml==0.10.2
tomli==1.2.3
tox==3.28.0
typing_extensions==4.1.1
virtualenv==20.17.1
Werkzeug==2.0.3
zipp==3.6.0
| name: sendgrid-python
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- attrs==22.2.0
- dataclasses==0.8
- distlib==0.3.9
- filelock==3.4.1
- flask==0.10.1
- importlib-metadata==4.8.3
- importlib-resources==5.4.0
- iniconfig==1.1.1
- itsdangerous==2.0.1
- jinja2==3.0.3
- markupsafe==2.0.1
- packaging==21.3
- platformdirs==2.4.0
- pluggy==1.0.0
- py==1.11.0
- pyparsing==3.1.4
- pytest==7.0.1
- python-http-client==3.3.7
- pyyaml==3.11
- six==1.17.0
- toml==0.10.2
- tomli==1.2.3
- tox==3.28.0
- typing-extensions==4.1.1
- virtualenv==20.17.1
- werkzeug==2.0.3
- zipp==3.6.0
prefix: /opt/conda/envs/sendgrid-python
| [
"test/test_send.py::UnitTests::test_main_call"
]
| []
| [
"test/test_send.py::UnitTests::test_send"
]
| []
| MIT License | 1,817 | [
"sendgrid/helpers/inbound/send.py",
"tox.ini"
]
| [
"sendgrid/helpers/inbound/send.py",
"tox.ini"
]
|
|
ahawker__ulid-63 | ee7977eef6df2c85dda59f7be117722e0718ff05 | 2017-10-28 22:19:31 | 64db8e687fcb5faaf68c92dc5d8adef2b4b1bddd | diff --git a/ulid/base32.py b/ulid/base32.py
index f7377b6..b63ba7a 100644
--- a/ulid/base32.py
+++ b/ulid/base32.py
@@ -248,14 +248,7 @@ def decode_ulid(value: str) -> bytes:
:raises ValueError: when value is not 26 characters
:raises ValueError: when value cannot be encoded in ASCII
"""
- length = len(value)
- if length != 26:
- raise ValueError('Expects 26 characters for timestamp + randomness; got {}'.format(length))
-
- try:
- encoded = value.encode('ascii')
- except UnicodeEncodeError as ex:
- raise ValueError('Expects value that can be encoded in ASCII charset: {}'.format(ex))
+ encoded = str_to_bytes(value, 26)
decoding = DECODING
@@ -296,14 +289,7 @@ def decode_timestamp(timestamp: str) -> bytes:
:raises ValueError: when value is not 10 characters
:raises ValueError: when value cannot be encoded in ASCII
"""
- length = len(timestamp)
- if length != 10:
- raise ValueError('Expects 10 characters for timestamp; got {}'.format(length))
-
- try:
- encoded = timestamp.encode('ascii')
- except UnicodeEncodeError as ex:
- raise ValueError('Expects timestamp that can be encoded in ASCII charset: {}'.format(ex))
+ encoded = str_to_bytes(timestamp, 10)
decoding = DECODING
@@ -334,14 +320,7 @@ def decode_randomness(randomness: str) -> bytes:
:raises ValueError: when value is not 16 characters
:raises ValueError: when value cannot be encoded in ASCII
"""
- length = len(randomness)
- if length != 16:
- raise ValueError('Expects 16 characters for randomness; got {}'.format(length))
-
- try:
- encoded = randomness.encode('ascii')
- except UnicodeEncodeError as ex:
- raise ValueError('Expects randomness that can be encoded in ASCII charset: {}'.format(ex))
+ encoded = str_to_bytes(randomness, 16)
decoding = DECODING
@@ -357,3 +336,34 @@ def decode_randomness(randomness: str) -> bytes:
((decoding[encoded[12]] << 7) | (decoding[encoded[13]] << 2) | (decoding[encoded[14]] >> 3)) & 0xFF,
((decoding[encoded[14]] << 5) | (decoding[encoded[15]])) & 0xFF
))
+
+
+def str_to_bytes(value: str, expected_length: int) -> bytes:
+ """
+ Convert the given string to bytes and validate it is within the Base32 character set.
+
+ :param value: String to convert to bytes
+ :type value: :class:`~str`
+ :param expected_length: Expected length of the input string
+ :type expected_length: :class:`~int`
+ :return: Value converted to bytes.
+ :rtype: :class:`~bytes`
+ """
+ length = len(value)
+ if length != expected_length:
+ raise ValueError('Expects {} characters for decoding; got {}'.format(expected_length, length))
+
+ try:
+ encoded = value.encode('ascii')
+ except UnicodeEncodeError as ex:
+ raise ValueError('Expects value that can be encoded in ASCII charset: {}'.format(ex))
+
+ decoding = DECODING
+
+ # Confirm all bytes are valid Base32 decode characters.
+ # Note: ASCII encoding handles the out of range checking for us.
+ for byte in encoded:
+ if decoding[byte] > 31:
+ raise ValueError('Non-base32 character found: "{}"'.format(chr(byte)))
+
+ return encoded
| Properly handle invalid base32 characters
As of today, it is possible to input non-base32 characters, `uU` for example, into any of the `api` calls.
Doing this will cause the library to fail silently and perform an incorrect `base32` decode on the string.
The API should provide a feedback mechanism that informs the caller of the bad input. The implementation of that feedback is still TBD (separate API call vs. exception vs. ??).
**Considerations:**
* Performance of this computation for every decode call?
* Double-penality for callers that have already made this guarantee?
* Separate API call to validate? Is there use-cases for this outside of normal hot path?
| ahawker/ulid | diff --git a/tests/conftest.py b/tests/conftest.py
index 5e78e67..48e4ec1 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -13,7 +13,9 @@ import random
from ulid import base32
+ASCII_ALPHABET = ''.join(chr(d) for d in range(0, 128))
EXTENDED_ASCII_ALPHABET = ''.join(chr(d) for d in range(128, 256))
+ASCII_NON_BASE_32_ALPHABET = ''.join(set(ASCII_ALPHABET).difference(set(base32.ENCODING)))
@pytest.fixture(scope='session')
@@ -126,6 +128,14 @@ def invalid_bytes_48_80_128(request):
return random_bytes(request.param, not_in=[6, 10, 16])
[email protected](scope='function', params=[10, 16, 26])
+def valid_str_valid_length(request):
+ """
+ Fixture that yields :class:`~str` instances that are 10, 16, and 26 characters.
+ """
+ return random_str(request.param)
+
+
@pytest.fixture(scope='function')
def valid_str_26():
"""
@@ -182,6 +192,42 @@ def invalid_str_10_16_26(request):
return random_str(request.param, not_in=[10, 16, 26])
[email protected](scope='function', params=[10, 16, 26])
+def ascii_non_base32_str_valid_length(request):
+ """
+ Fixture that yields a :class:`~str` instance that is valid length for a ULID part but contains
+ any standard ASCII characters that are not in the Base 32 alphabet.
+ """
+ return random_str(request.param, alphabet=ASCII_NON_BASE_32_ALPHABET)
+
+
[email protected](scope='function')
+def ascii_non_base32_str_26():
+ """
+ Fixture that yields a :class:`~str` instance that is 26 characters, the length of an entire ULID but
+ contains extended ASCII characters.
+ """
+ return random_str(26, alphabet=ASCII_NON_BASE_32_ALPHABET)
+
+
[email protected](scope='function')
+def ascii_non_base32_str_10():
+ """
+ Fixture that yields a :class:`~str` instance that is 10 characters, the length of a ULID timestamp value but
+ contains extended ASCII characters.
+ """
+ return random_str(10, alphabet=ASCII_NON_BASE_32_ALPHABET)
+
+
[email protected](scope='function')
+def ascii_non_base32_str_16():
+ """
+ Fixture that yields a :class:`~str` instance that is 16 characters, the length of a ULID randomness value but
+ contains extended ASCII characters.
+ """
+ return random_str(16, alphabet=ASCII_NON_BASE_32_ALPHABET)
+
+
@pytest.fixture(scope='function', params=[10, 16, 26])
def extended_ascii_str_valid_length(request):
"""
diff --git a/tests/test_base32.py b/tests/test_base32.py
index a922802..42cdf1f 100644
--- a/tests/test_base32.py
+++ b/tests/test_base32.py
@@ -9,6 +9,9 @@ import pytest
from ulid import base32
+NON_BASE_32_EXP = r'^Non-base32 character found'
+
+
@pytest.fixture(scope='session')
def decoding_alphabet():
"""
@@ -115,7 +118,7 @@ def test_encode_randomness_raises_on_bytes_length_mismatch(invalid_bytes_80):
def test_decode_handles_ulid_and_returns_16_bytes(valid_str_26):
"""
- Assert that :func:`~ulid.base32.decode` decodes a valid 26 character string into a :class:`~bytes`
+ Assert that :func:`~ulid.base32.decode` decodes a valid 26 character string into a :class:`~bytes`
instance that is 128 bit.
"""
decoded = base32.decode(valid_str_26)
@@ -125,7 +128,7 @@ def test_decode_handles_ulid_and_returns_16_bytes(valid_str_26):
def test_decode_handles_timestamp_and_returns_6_bytes(valid_str_10):
"""
- Assert that :func:`~ulid.base32.decode` decodes a valid 10 character string into a :class:`~bytes`
+ Assert that :func:`~ulid.base32.decode` decodes a valid 10 character string into a :class:`~bytes`
instance that is 48 bit.
"""
decoded = base32.decode(valid_str_10)
@@ -135,7 +138,7 @@ def test_decode_handles_timestamp_and_returns_6_bytes(valid_str_10):
def test_decode_handles_randomness_and_returns_10_bytes(valid_str_16):
"""
- Assert that :func:`~ulid.base32.decode` decodes a valid 16 character string into a :class:`~bytes`
+ Assert that :func:`~ulid.base32.decode` decodes a valid 16 character string into a :class:`~bytes`
instance that is 80 bit.
"""
decoded = base32.decode(valid_str_16)
@@ -161,9 +164,19 @@ def test_decode_raises_on_extended_ascii_str(extended_ascii_str_valid_length):
base32.decode(extended_ascii_str_valid_length)
+def test_decode_raises_on_non_base32_decode_char(ascii_non_base32_str_valid_length):
+ """
+ Assert that :func:`~ulid.base32.decode_ulid` raises a :class:`~ValueError` when given a :class:`~str`
+ instance that includes ASCII characters not part of the Base 32 decoding character set.
+ """
+ with pytest.raises(ValueError) as ex:
+ base32.decode(ascii_non_base32_str_valid_length)
+ ex.match(NON_BASE_32_EXP)
+
+
def test_decode_ulid_returns_16_bytes(valid_str_26):
"""
- Assert that :func:`~ulid.base32.decode_ulid` decodes a valid 26 character string into a :class:`~bytes`
+ Assert that :func:`~ulid.base32.decode_ulid` decodes a valid 26 character string into a :class:`~bytes`
instance that is 128 bit.
"""
decoded = base32.decode_ulid(valid_str_26)
@@ -189,9 +202,19 @@ def test_decode_ulid_raises_on_non_ascii_str(extended_ascii_str_26):
base32.decode_ulid(extended_ascii_str_26)
+def test_decode_ulid_raises_on_non_base32_decode_char(ascii_non_base32_str_26):
+ """
+ Assert that :func:`~ulid.base32.decode_ulid` raises a :class:`~ValueError` when given a :class:`~str`
+ instance that includes ASCII characters not part of the Base 32 decoding character set.
+ """
+ with pytest.raises(ValueError) as ex:
+ base32.decode_ulid(ascii_non_base32_str_26)
+ ex.match(NON_BASE_32_EXP)
+
+
def test_decode_timestamp_returns_6_bytes(valid_str_10):
"""
- Assert that :func:`~ulid.base32.decode_timestamp` decodes a valid 10 character string into a :class:`~bytes`
+ Assert that :func:`~ulid.base32.decode_timestamp` decodes a valid 10 character string into a :class:`~bytes`
instance that is 48 bit.
"""
decoded = base32.decode_timestamp(valid_str_10)
@@ -217,9 +240,19 @@ def test_decode_timestamp_raises_on_non_ascii_str(extended_ascii_str_10):
base32.decode_timestamp(extended_ascii_str_10)
+def test_decode_timestamp_raises_on_non_base32_decode_char(ascii_non_base32_str_10):
+ """
+ Assert that :func:`~ulid.base32.decode_timestamp` raises a :class:`~ValueError` when given a :class:`~str`
+ instance that includes ASCII characters not part of the Base 32 decoding character set.
+ """
+ with pytest.raises(ValueError) as ex:
+ base32.decode_timestamp(ascii_non_base32_str_10)
+ ex.match(NON_BASE_32_EXP)
+
+
def test_decode_randomness_returns_10_bytes(valid_str_16):
"""
- Assert that :func:`~ulid.base32.decode_randomness` decodes a valid 16 character string into a :class:`~bytes`
+ Assert that :func:`~ulid.base32.decode_randomness` decodes a valid 16 character string into a :class:`~bytes`
instance that is 80 bit.
"""
decoded = base32.decode_randomness(valid_str_16)
@@ -245,6 +278,16 @@ def test_decode_randomness_raises_on_non_ascii_str(extended_ascii_str_16):
base32.decode_randomness(extended_ascii_str_16)
+def test_decode_randomness_raises_on_non_base32_decode_char(ascii_non_base32_str_16):
+ """
+ Assert that :func:`~ulid.base32.decode_randomness` raises a :class:`~ValueError` when given a :class:`~str`
+ instance that includes ASCII characters not part of the Base 32 decoding character set.
+ """
+ with pytest.raises(ValueError) as ex:
+ base32.decode_randomness(ascii_non_base32_str_16)
+ ex.match(NON_BASE_32_EXP)
+
+
def test_decode_table_has_value_for_entire_decoding_alphabet(decoding_alphabet):
"""
Assert that :attr:`~ulid.base32.DECODING` stores a valid value mapping for all characters that
@@ -252,3 +295,41 @@ def test_decode_table_has_value_for_entire_decoding_alphabet(decoding_alphabet):
"""
for char in decoding_alphabet:
assert base32.DECODING[ord(char)] != 0xFF, 'Character "{}" decoded improperly'.format(char)
+
+
+def test_str_to_bytes_returns_expected_bytes(valid_str_valid_length):
+ """
+ Assert that :func:`~ulid.base32.str_to_bytes` decodes a valid string that is 10, 16, or 26 characters long
+ into a :class:`~bytes` instance.
+ """
+ decoded = base32.str_to_bytes(valid_str_valid_length, len(valid_str_valid_length))
+ assert isinstance(decoded, bytes)
+ assert len(decoded) == len(valid_str_valid_length)
+
+
+def test_str_to_bytes_raises_on_unexpected_length(invalid_str_26):
+ """
+ Assert that :func:`~ulid.base32.str_to_bytes` raises a :class:`~ValueError` when given a :class:`~str`
+ instance that does not match the expected length.
+ """
+ with pytest.raises(ValueError):
+ base32.str_to_bytes(invalid_str_26, 26)
+
+
+def test_str_to_bytes_raises_on_extended_ascii_str(extended_ascii_str_valid_length):
+ """
+ Assert that :func:`~ulid.base32.str_to_bytes` raises a :class:`~ValueError` when given a :class:`~str`
+ instance that includes extended ascii characters.
+ """
+ with pytest.raises(ValueError):
+ base32.str_to_bytes(extended_ascii_str_valid_length, len(extended_ascii_str_valid_length))
+
+
+def test_str_to_bytes_raises_on_non_base32_decode_char(ascii_non_base32_str_valid_length):
+ """
+ Assert that :func:`~ulid.base32.str_to_bytes` raises a :class:`~ValueError` when given a :class:`~str`
+ instance that includes ASCII characters not part of the Base 32 decoding character set.
+ """
+ with pytest.raises(ValueError) as ex:
+ base32.str_to_bytes(ascii_non_base32_str_valid_length, len(ascii_non_base32_str_valid_length))
+ ex.match(NON_BASE_32_EXP)
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 2,
"test_score": 2
},
"num_modified_files": 1
} | 0.0 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-cov",
"pytest-xdist",
"pytest-mock",
"pytest-asyncio"
],
"pre_install": null,
"python": "3.6",
"reqs_path": [
"requirements/base.txt",
"requirements/dev.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | astroid==2.3.0
attrs==22.2.0
bandit==1.4.0
bumpversion==0.5.3
certifi==2021.5.30
charset-normalizer==2.0.12
click==8.0.4
coverage==6.2
dparse==0.6.3
execnet==1.9.0
gitdb==4.0.9
GitPython==3.1.18
idna==3.10
importlib-metadata==4.8.3
iniconfig==1.1.1
isort==5.10.1
lazy-object-proxy==1.7.1
mccabe==0.7.0
mypy==0.540
packaging==21.3
pbr==6.1.1
pluggy==1.0.0
py==1.11.0
pylint==1.7.4
pyparsing==3.1.4
pytest==7.0.1
pytest-asyncio==0.16.0
pytest-cov==4.0.0
pytest-mock==3.6.1
pytest-xdist==3.0.2
PyYAML==6.0.1
requests==2.27.1
safety==1.6.1
six==1.17.0
smmap==5.0.0
stevedore==3.5.2
tomli==1.2.3
typed-ast==1.1.2
typing_extensions==4.1.1
-e git+https://github.com/ahawker/ulid.git@ee7977eef6df2c85dda59f7be117722e0718ff05#egg=ulid_py
urllib3==1.26.20
wrapt==1.16.0
zipp==3.6.0
| name: ulid
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- astroid==2.3.0
- attrs==22.2.0
- bandit==1.4.0
- bumpversion==0.5.3
- charset-normalizer==2.0.12
- click==8.0.4
- coverage==6.2
- dparse==0.6.3
- execnet==1.9.0
- gitdb==4.0.9
- gitpython==3.1.18
- idna==3.10
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- isort==5.10.1
- lazy-object-proxy==1.7.1
- mccabe==0.7.0
- mypy==0.540
- packaging==21.3
- pbr==6.1.1
- pluggy==1.0.0
- py==1.11.0
- pylint==1.7.4
- pyparsing==3.1.4
- pytest==7.0.1
- pytest-asyncio==0.16.0
- pytest-cov==4.0.0
- pytest-mock==3.6.1
- pytest-xdist==3.0.2
- pyyaml==6.0.1
- requests==2.27.1
- safety==1.6.1
- six==1.17.0
- smmap==5.0.0
- stevedore==3.5.2
- tomli==1.2.3
- typed-ast==1.1.2
- typing-extensions==4.1.1
- urllib3==1.26.20
- wrapt==1.16.0
- zipp==3.6.0
prefix: /opt/conda/envs/ulid
| [
"tests/test_base32.py::test_decode_raises_on_non_base32_decode_char[10]",
"tests/test_base32.py::test_decode_raises_on_non_base32_decode_char[16]",
"tests/test_base32.py::test_decode_raises_on_non_base32_decode_char[26]",
"tests/test_base32.py::test_decode_ulid_raises_on_non_base32_decode_char",
"tests/test_base32.py::test_decode_timestamp_raises_on_non_base32_decode_char",
"tests/test_base32.py::test_decode_randomness_raises_on_non_base32_decode_char",
"tests/test_base32.py::test_str_to_bytes_returns_expected_bytes[10]",
"tests/test_base32.py::test_str_to_bytes_returns_expected_bytes[16]",
"tests/test_base32.py::test_str_to_bytes_returns_expected_bytes[26]",
"tests/test_base32.py::test_str_to_bytes_raises_on_unexpected_length[0]",
"tests/test_base32.py::test_str_to_bytes_raises_on_unexpected_length[1]",
"tests/test_base32.py::test_str_to_bytes_raises_on_unexpected_length[2]",
"tests/test_base32.py::test_str_to_bytes_raises_on_unexpected_length[3]",
"tests/test_base32.py::test_str_to_bytes_raises_on_unexpected_length[4]",
"tests/test_base32.py::test_str_to_bytes_raises_on_unexpected_length[5]",
"tests/test_base32.py::test_str_to_bytes_raises_on_unexpected_length[6]",
"tests/test_base32.py::test_str_to_bytes_raises_on_unexpected_length[7]",
"tests/test_base32.py::test_str_to_bytes_raises_on_unexpected_length[8]",
"tests/test_base32.py::test_str_to_bytes_raises_on_unexpected_length[9]",
"tests/test_base32.py::test_str_to_bytes_raises_on_unexpected_length[10]",
"tests/test_base32.py::test_str_to_bytes_raises_on_unexpected_length[11]",
"tests/test_base32.py::test_str_to_bytes_raises_on_unexpected_length[12]",
"tests/test_base32.py::test_str_to_bytes_raises_on_unexpected_length[13]",
"tests/test_base32.py::test_str_to_bytes_raises_on_unexpected_length[14]",
"tests/test_base32.py::test_str_to_bytes_raises_on_unexpected_length[15]",
"tests/test_base32.py::test_str_to_bytes_raises_on_unexpected_length[16]",
"tests/test_base32.py::test_str_to_bytes_raises_on_unexpected_length[17]",
"tests/test_base32.py::test_str_to_bytes_raises_on_unexpected_length[18]",
"tests/test_base32.py::test_str_to_bytes_raises_on_unexpected_length[19]",
"tests/test_base32.py::test_str_to_bytes_raises_on_unexpected_length[20]",
"tests/test_base32.py::test_str_to_bytes_raises_on_unexpected_length[21]",
"tests/test_base32.py::test_str_to_bytes_raises_on_unexpected_length[22]",
"tests/test_base32.py::test_str_to_bytes_raises_on_unexpected_length[23]",
"tests/test_base32.py::test_str_to_bytes_raises_on_unexpected_length[24]",
"tests/test_base32.py::test_str_to_bytes_raises_on_unexpected_length[25]",
"tests/test_base32.py::test_str_to_bytes_raises_on_unexpected_length[26]",
"tests/test_base32.py::test_str_to_bytes_raises_on_unexpected_length[27]",
"tests/test_base32.py::test_str_to_bytes_raises_on_unexpected_length[28]",
"tests/test_base32.py::test_str_to_bytes_raises_on_unexpected_length[29]",
"tests/test_base32.py::test_str_to_bytes_raises_on_unexpected_length[30]",
"tests/test_base32.py::test_str_to_bytes_raises_on_unexpected_length[31]",
"tests/test_base32.py::test_str_to_bytes_raises_on_extended_ascii_str[10]",
"tests/test_base32.py::test_str_to_bytes_raises_on_extended_ascii_str[16]",
"tests/test_base32.py::test_str_to_bytes_raises_on_extended_ascii_str[26]",
"tests/test_base32.py::test_str_to_bytes_raises_on_non_base32_decode_char[10]",
"tests/test_base32.py::test_str_to_bytes_raises_on_non_base32_decode_char[16]",
"tests/test_base32.py::test_str_to_bytes_raises_on_non_base32_decode_char[26]"
]
| []
| [
"tests/test_base32.py::test_encode_handles_ulid_and_returns_26_char_string",
"tests/test_base32.py::test_encode_handles_timestamp_and_returns_10_char_string",
"tests/test_base32.py::test_encode_handles_randomness_and_returns_16_char_string",
"tests/test_base32.py::test_encode_raises_on_bytes_length_mismatch[0]",
"tests/test_base32.py::test_encode_raises_on_bytes_length_mismatch[1]",
"tests/test_base32.py::test_encode_raises_on_bytes_length_mismatch[2]",
"tests/test_base32.py::test_encode_raises_on_bytes_length_mismatch[3]",
"tests/test_base32.py::test_encode_raises_on_bytes_length_mismatch[4]",
"tests/test_base32.py::test_encode_raises_on_bytes_length_mismatch[5]",
"tests/test_base32.py::test_encode_raises_on_bytes_length_mismatch[6]",
"tests/test_base32.py::test_encode_raises_on_bytes_length_mismatch[7]",
"tests/test_base32.py::test_encode_raises_on_bytes_length_mismatch[8]",
"tests/test_base32.py::test_encode_raises_on_bytes_length_mismatch[9]",
"tests/test_base32.py::test_encode_raises_on_bytes_length_mismatch[10]",
"tests/test_base32.py::test_encode_raises_on_bytes_length_mismatch[11]",
"tests/test_base32.py::test_encode_raises_on_bytes_length_mismatch[12]",
"tests/test_base32.py::test_encode_raises_on_bytes_length_mismatch[13]",
"tests/test_base32.py::test_encode_raises_on_bytes_length_mismatch[14]",
"tests/test_base32.py::test_encode_raises_on_bytes_length_mismatch[15]",
"tests/test_base32.py::test_encode_raises_on_bytes_length_mismatch[16]",
"tests/test_base32.py::test_encode_raises_on_bytes_length_mismatch[17]",
"tests/test_base32.py::test_encode_raises_on_bytes_length_mismatch[18]",
"tests/test_base32.py::test_encode_raises_on_bytes_length_mismatch[19]",
"tests/test_base32.py::test_encode_raises_on_bytes_length_mismatch[20]",
"tests/test_base32.py::test_encode_raises_on_bytes_length_mismatch[21]",
"tests/test_base32.py::test_encode_raises_on_bytes_length_mismatch[22]",
"tests/test_base32.py::test_encode_raises_on_bytes_length_mismatch[23]",
"tests/test_base32.py::test_encode_raises_on_bytes_length_mismatch[24]",
"tests/test_base32.py::test_encode_raises_on_bytes_length_mismatch[25]",
"tests/test_base32.py::test_encode_raises_on_bytes_length_mismatch[26]",
"tests/test_base32.py::test_encode_raises_on_bytes_length_mismatch[27]",
"tests/test_base32.py::test_encode_raises_on_bytes_length_mismatch[28]",
"tests/test_base32.py::test_encode_raises_on_bytes_length_mismatch[29]",
"tests/test_base32.py::test_encode_raises_on_bytes_length_mismatch[30]",
"tests/test_base32.py::test_encode_raises_on_bytes_length_mismatch[31]",
"tests/test_base32.py::test_encode_ulid_returns_26_char_string",
"tests/test_base32.py::test_encode_ulid_raises_on_bytes_length_mismatch[0]",
"tests/test_base32.py::test_encode_ulid_raises_on_bytes_length_mismatch[1]",
"tests/test_base32.py::test_encode_ulid_raises_on_bytes_length_mismatch[2]",
"tests/test_base32.py::test_encode_ulid_raises_on_bytes_length_mismatch[3]",
"tests/test_base32.py::test_encode_ulid_raises_on_bytes_length_mismatch[4]",
"tests/test_base32.py::test_encode_ulid_raises_on_bytes_length_mismatch[5]",
"tests/test_base32.py::test_encode_ulid_raises_on_bytes_length_mismatch[6]",
"tests/test_base32.py::test_encode_ulid_raises_on_bytes_length_mismatch[7]",
"tests/test_base32.py::test_encode_ulid_raises_on_bytes_length_mismatch[8]",
"tests/test_base32.py::test_encode_ulid_raises_on_bytes_length_mismatch[9]",
"tests/test_base32.py::test_encode_ulid_raises_on_bytes_length_mismatch[10]",
"tests/test_base32.py::test_encode_ulid_raises_on_bytes_length_mismatch[11]",
"tests/test_base32.py::test_encode_ulid_raises_on_bytes_length_mismatch[12]",
"tests/test_base32.py::test_encode_ulid_raises_on_bytes_length_mismatch[13]",
"tests/test_base32.py::test_encode_ulid_raises_on_bytes_length_mismatch[14]",
"tests/test_base32.py::test_encode_ulid_raises_on_bytes_length_mismatch[15]",
"tests/test_base32.py::test_encode_ulid_raises_on_bytes_length_mismatch[16]",
"tests/test_base32.py::test_encode_ulid_raises_on_bytes_length_mismatch[17]",
"tests/test_base32.py::test_encode_ulid_raises_on_bytes_length_mismatch[18]",
"tests/test_base32.py::test_encode_ulid_raises_on_bytes_length_mismatch[19]",
"tests/test_base32.py::test_encode_ulid_raises_on_bytes_length_mismatch[20]",
"tests/test_base32.py::test_encode_ulid_raises_on_bytes_length_mismatch[21]",
"tests/test_base32.py::test_encode_ulid_raises_on_bytes_length_mismatch[22]",
"tests/test_base32.py::test_encode_ulid_raises_on_bytes_length_mismatch[23]",
"tests/test_base32.py::test_encode_ulid_raises_on_bytes_length_mismatch[24]",
"tests/test_base32.py::test_encode_ulid_raises_on_bytes_length_mismatch[25]",
"tests/test_base32.py::test_encode_ulid_raises_on_bytes_length_mismatch[26]",
"tests/test_base32.py::test_encode_ulid_raises_on_bytes_length_mismatch[27]",
"tests/test_base32.py::test_encode_ulid_raises_on_bytes_length_mismatch[28]",
"tests/test_base32.py::test_encode_ulid_raises_on_bytes_length_mismatch[29]",
"tests/test_base32.py::test_encode_ulid_raises_on_bytes_length_mismatch[30]",
"tests/test_base32.py::test_encode_ulid_raises_on_bytes_length_mismatch[31]",
"tests/test_base32.py::test_encode_timestamp_returns_10_char_string",
"tests/test_base32.py::test_encode_timestamp_raises_on_bytes_length_mismatch[0]",
"tests/test_base32.py::test_encode_timestamp_raises_on_bytes_length_mismatch[1]",
"tests/test_base32.py::test_encode_timestamp_raises_on_bytes_length_mismatch[2]",
"tests/test_base32.py::test_encode_timestamp_raises_on_bytes_length_mismatch[3]",
"tests/test_base32.py::test_encode_timestamp_raises_on_bytes_length_mismatch[4]",
"tests/test_base32.py::test_encode_timestamp_raises_on_bytes_length_mismatch[5]",
"tests/test_base32.py::test_encode_timestamp_raises_on_bytes_length_mismatch[6]",
"tests/test_base32.py::test_encode_timestamp_raises_on_bytes_length_mismatch[7]",
"tests/test_base32.py::test_encode_timestamp_raises_on_bytes_length_mismatch[8]",
"tests/test_base32.py::test_encode_timestamp_raises_on_bytes_length_mismatch[9]",
"tests/test_base32.py::test_encode_timestamp_raises_on_bytes_length_mismatch[10]",
"tests/test_base32.py::test_encode_timestamp_raises_on_bytes_length_mismatch[11]",
"tests/test_base32.py::test_encode_timestamp_raises_on_bytes_length_mismatch[12]",
"tests/test_base32.py::test_encode_timestamp_raises_on_bytes_length_mismatch[13]",
"tests/test_base32.py::test_encode_timestamp_raises_on_bytes_length_mismatch[14]",
"tests/test_base32.py::test_encode_timestamp_raises_on_bytes_length_mismatch[15]",
"tests/test_base32.py::test_encode_timestamp_raises_on_bytes_length_mismatch[16]",
"tests/test_base32.py::test_encode_timestamp_raises_on_bytes_length_mismatch[17]",
"tests/test_base32.py::test_encode_timestamp_raises_on_bytes_length_mismatch[18]",
"tests/test_base32.py::test_encode_timestamp_raises_on_bytes_length_mismatch[19]",
"tests/test_base32.py::test_encode_timestamp_raises_on_bytes_length_mismatch[20]",
"tests/test_base32.py::test_encode_timestamp_raises_on_bytes_length_mismatch[21]",
"tests/test_base32.py::test_encode_timestamp_raises_on_bytes_length_mismatch[22]",
"tests/test_base32.py::test_encode_timestamp_raises_on_bytes_length_mismatch[23]",
"tests/test_base32.py::test_encode_timestamp_raises_on_bytes_length_mismatch[24]",
"tests/test_base32.py::test_encode_timestamp_raises_on_bytes_length_mismatch[25]",
"tests/test_base32.py::test_encode_timestamp_raises_on_bytes_length_mismatch[26]",
"tests/test_base32.py::test_encode_timestamp_raises_on_bytes_length_mismatch[27]",
"tests/test_base32.py::test_encode_timestamp_raises_on_bytes_length_mismatch[28]",
"tests/test_base32.py::test_encode_timestamp_raises_on_bytes_length_mismatch[29]",
"tests/test_base32.py::test_encode_timestamp_raises_on_bytes_length_mismatch[30]",
"tests/test_base32.py::test_encode_timestamp_raises_on_bytes_length_mismatch[31]",
"tests/test_base32.py::test_encode_randomness_returns_16_char_string",
"tests/test_base32.py::test_encode_randomness_raises_on_bytes_length_mismatch[0]",
"tests/test_base32.py::test_encode_randomness_raises_on_bytes_length_mismatch[1]",
"tests/test_base32.py::test_encode_randomness_raises_on_bytes_length_mismatch[2]",
"tests/test_base32.py::test_encode_randomness_raises_on_bytes_length_mismatch[3]",
"tests/test_base32.py::test_encode_randomness_raises_on_bytes_length_mismatch[4]",
"tests/test_base32.py::test_encode_randomness_raises_on_bytes_length_mismatch[5]",
"tests/test_base32.py::test_encode_randomness_raises_on_bytes_length_mismatch[6]",
"tests/test_base32.py::test_encode_randomness_raises_on_bytes_length_mismatch[7]",
"tests/test_base32.py::test_encode_randomness_raises_on_bytes_length_mismatch[8]",
"tests/test_base32.py::test_encode_randomness_raises_on_bytes_length_mismatch[9]",
"tests/test_base32.py::test_encode_randomness_raises_on_bytes_length_mismatch[10]",
"tests/test_base32.py::test_encode_randomness_raises_on_bytes_length_mismatch[11]",
"tests/test_base32.py::test_encode_randomness_raises_on_bytes_length_mismatch[12]",
"tests/test_base32.py::test_encode_randomness_raises_on_bytes_length_mismatch[13]",
"tests/test_base32.py::test_encode_randomness_raises_on_bytes_length_mismatch[14]",
"tests/test_base32.py::test_encode_randomness_raises_on_bytes_length_mismatch[15]",
"tests/test_base32.py::test_encode_randomness_raises_on_bytes_length_mismatch[16]",
"tests/test_base32.py::test_encode_randomness_raises_on_bytes_length_mismatch[17]",
"tests/test_base32.py::test_encode_randomness_raises_on_bytes_length_mismatch[18]",
"tests/test_base32.py::test_encode_randomness_raises_on_bytes_length_mismatch[19]",
"tests/test_base32.py::test_encode_randomness_raises_on_bytes_length_mismatch[20]",
"tests/test_base32.py::test_encode_randomness_raises_on_bytes_length_mismatch[21]",
"tests/test_base32.py::test_encode_randomness_raises_on_bytes_length_mismatch[22]",
"tests/test_base32.py::test_encode_randomness_raises_on_bytes_length_mismatch[23]",
"tests/test_base32.py::test_encode_randomness_raises_on_bytes_length_mismatch[24]",
"tests/test_base32.py::test_encode_randomness_raises_on_bytes_length_mismatch[25]",
"tests/test_base32.py::test_encode_randomness_raises_on_bytes_length_mismatch[26]",
"tests/test_base32.py::test_encode_randomness_raises_on_bytes_length_mismatch[27]",
"tests/test_base32.py::test_encode_randomness_raises_on_bytes_length_mismatch[28]",
"tests/test_base32.py::test_encode_randomness_raises_on_bytes_length_mismatch[29]",
"tests/test_base32.py::test_encode_randomness_raises_on_bytes_length_mismatch[30]",
"tests/test_base32.py::test_encode_randomness_raises_on_bytes_length_mismatch[31]",
"tests/test_base32.py::test_decode_handles_ulid_and_returns_16_bytes",
"tests/test_base32.py::test_decode_handles_timestamp_and_returns_6_bytes",
"tests/test_base32.py::test_decode_handles_randomness_and_returns_10_bytes",
"tests/test_base32.py::test_decode_raises_on_str_length_mismatch[0]",
"tests/test_base32.py::test_decode_raises_on_str_length_mismatch[1]",
"tests/test_base32.py::test_decode_raises_on_str_length_mismatch[2]",
"tests/test_base32.py::test_decode_raises_on_str_length_mismatch[3]",
"tests/test_base32.py::test_decode_raises_on_str_length_mismatch[4]",
"tests/test_base32.py::test_decode_raises_on_str_length_mismatch[5]",
"tests/test_base32.py::test_decode_raises_on_str_length_mismatch[6]",
"tests/test_base32.py::test_decode_raises_on_str_length_mismatch[7]",
"tests/test_base32.py::test_decode_raises_on_str_length_mismatch[8]",
"tests/test_base32.py::test_decode_raises_on_str_length_mismatch[9]",
"tests/test_base32.py::test_decode_raises_on_str_length_mismatch[10]",
"tests/test_base32.py::test_decode_raises_on_str_length_mismatch[11]",
"tests/test_base32.py::test_decode_raises_on_str_length_mismatch[12]",
"tests/test_base32.py::test_decode_raises_on_str_length_mismatch[13]",
"tests/test_base32.py::test_decode_raises_on_str_length_mismatch[14]",
"tests/test_base32.py::test_decode_raises_on_str_length_mismatch[15]",
"tests/test_base32.py::test_decode_raises_on_str_length_mismatch[16]",
"tests/test_base32.py::test_decode_raises_on_str_length_mismatch[17]",
"tests/test_base32.py::test_decode_raises_on_str_length_mismatch[18]",
"tests/test_base32.py::test_decode_raises_on_str_length_mismatch[19]",
"tests/test_base32.py::test_decode_raises_on_str_length_mismatch[20]",
"tests/test_base32.py::test_decode_raises_on_str_length_mismatch[21]",
"tests/test_base32.py::test_decode_raises_on_str_length_mismatch[22]",
"tests/test_base32.py::test_decode_raises_on_str_length_mismatch[23]",
"tests/test_base32.py::test_decode_raises_on_str_length_mismatch[24]",
"tests/test_base32.py::test_decode_raises_on_str_length_mismatch[25]",
"tests/test_base32.py::test_decode_raises_on_str_length_mismatch[26]",
"tests/test_base32.py::test_decode_raises_on_str_length_mismatch[27]",
"tests/test_base32.py::test_decode_raises_on_str_length_mismatch[28]",
"tests/test_base32.py::test_decode_raises_on_str_length_mismatch[29]",
"tests/test_base32.py::test_decode_raises_on_str_length_mismatch[30]",
"tests/test_base32.py::test_decode_raises_on_str_length_mismatch[31]",
"tests/test_base32.py::test_decode_raises_on_extended_ascii_str[10]",
"tests/test_base32.py::test_decode_raises_on_extended_ascii_str[16]",
"tests/test_base32.py::test_decode_raises_on_extended_ascii_str[26]",
"tests/test_base32.py::test_decode_ulid_returns_16_bytes",
"tests/test_base32.py::test_decode_ulid_raises_on_str_length_mismatch[0]",
"tests/test_base32.py::test_decode_ulid_raises_on_str_length_mismatch[1]",
"tests/test_base32.py::test_decode_ulid_raises_on_str_length_mismatch[2]",
"tests/test_base32.py::test_decode_ulid_raises_on_str_length_mismatch[3]",
"tests/test_base32.py::test_decode_ulid_raises_on_str_length_mismatch[4]",
"tests/test_base32.py::test_decode_ulid_raises_on_str_length_mismatch[5]",
"tests/test_base32.py::test_decode_ulid_raises_on_str_length_mismatch[6]",
"tests/test_base32.py::test_decode_ulid_raises_on_str_length_mismatch[7]",
"tests/test_base32.py::test_decode_ulid_raises_on_str_length_mismatch[8]",
"tests/test_base32.py::test_decode_ulid_raises_on_str_length_mismatch[9]",
"tests/test_base32.py::test_decode_ulid_raises_on_str_length_mismatch[10]",
"tests/test_base32.py::test_decode_ulid_raises_on_str_length_mismatch[11]",
"tests/test_base32.py::test_decode_ulid_raises_on_str_length_mismatch[12]",
"tests/test_base32.py::test_decode_ulid_raises_on_str_length_mismatch[13]",
"tests/test_base32.py::test_decode_ulid_raises_on_str_length_mismatch[14]",
"tests/test_base32.py::test_decode_ulid_raises_on_str_length_mismatch[15]",
"tests/test_base32.py::test_decode_ulid_raises_on_str_length_mismatch[16]",
"tests/test_base32.py::test_decode_ulid_raises_on_str_length_mismatch[17]",
"tests/test_base32.py::test_decode_ulid_raises_on_str_length_mismatch[18]",
"tests/test_base32.py::test_decode_ulid_raises_on_str_length_mismatch[19]",
"tests/test_base32.py::test_decode_ulid_raises_on_str_length_mismatch[20]",
"tests/test_base32.py::test_decode_ulid_raises_on_str_length_mismatch[21]",
"tests/test_base32.py::test_decode_ulid_raises_on_str_length_mismatch[22]",
"tests/test_base32.py::test_decode_ulid_raises_on_str_length_mismatch[23]",
"tests/test_base32.py::test_decode_ulid_raises_on_str_length_mismatch[24]",
"tests/test_base32.py::test_decode_ulid_raises_on_str_length_mismatch[25]",
"tests/test_base32.py::test_decode_ulid_raises_on_str_length_mismatch[26]",
"tests/test_base32.py::test_decode_ulid_raises_on_str_length_mismatch[27]",
"tests/test_base32.py::test_decode_ulid_raises_on_str_length_mismatch[28]",
"tests/test_base32.py::test_decode_ulid_raises_on_str_length_mismatch[29]",
"tests/test_base32.py::test_decode_ulid_raises_on_str_length_mismatch[30]",
"tests/test_base32.py::test_decode_ulid_raises_on_str_length_mismatch[31]",
"tests/test_base32.py::test_decode_ulid_raises_on_non_ascii_str",
"tests/test_base32.py::test_decode_timestamp_returns_6_bytes",
"tests/test_base32.py::test_decode_timestamp_raises_on_str_length_mismatch[0]",
"tests/test_base32.py::test_decode_timestamp_raises_on_str_length_mismatch[1]",
"tests/test_base32.py::test_decode_timestamp_raises_on_str_length_mismatch[2]",
"tests/test_base32.py::test_decode_timestamp_raises_on_str_length_mismatch[3]",
"tests/test_base32.py::test_decode_timestamp_raises_on_str_length_mismatch[4]",
"tests/test_base32.py::test_decode_timestamp_raises_on_str_length_mismatch[5]",
"tests/test_base32.py::test_decode_timestamp_raises_on_str_length_mismatch[6]",
"tests/test_base32.py::test_decode_timestamp_raises_on_str_length_mismatch[7]",
"tests/test_base32.py::test_decode_timestamp_raises_on_str_length_mismatch[8]",
"tests/test_base32.py::test_decode_timestamp_raises_on_str_length_mismatch[9]",
"tests/test_base32.py::test_decode_timestamp_raises_on_str_length_mismatch[10]",
"tests/test_base32.py::test_decode_timestamp_raises_on_str_length_mismatch[11]",
"tests/test_base32.py::test_decode_timestamp_raises_on_str_length_mismatch[12]",
"tests/test_base32.py::test_decode_timestamp_raises_on_str_length_mismatch[13]",
"tests/test_base32.py::test_decode_timestamp_raises_on_str_length_mismatch[14]",
"tests/test_base32.py::test_decode_timestamp_raises_on_str_length_mismatch[15]",
"tests/test_base32.py::test_decode_timestamp_raises_on_str_length_mismatch[16]",
"tests/test_base32.py::test_decode_timestamp_raises_on_str_length_mismatch[17]",
"tests/test_base32.py::test_decode_timestamp_raises_on_str_length_mismatch[18]",
"tests/test_base32.py::test_decode_timestamp_raises_on_str_length_mismatch[19]",
"tests/test_base32.py::test_decode_timestamp_raises_on_str_length_mismatch[20]",
"tests/test_base32.py::test_decode_timestamp_raises_on_str_length_mismatch[21]",
"tests/test_base32.py::test_decode_timestamp_raises_on_str_length_mismatch[22]",
"tests/test_base32.py::test_decode_timestamp_raises_on_str_length_mismatch[23]",
"tests/test_base32.py::test_decode_timestamp_raises_on_str_length_mismatch[24]",
"tests/test_base32.py::test_decode_timestamp_raises_on_str_length_mismatch[25]",
"tests/test_base32.py::test_decode_timestamp_raises_on_str_length_mismatch[26]",
"tests/test_base32.py::test_decode_timestamp_raises_on_str_length_mismatch[27]",
"tests/test_base32.py::test_decode_timestamp_raises_on_str_length_mismatch[28]",
"tests/test_base32.py::test_decode_timestamp_raises_on_str_length_mismatch[29]",
"tests/test_base32.py::test_decode_timestamp_raises_on_str_length_mismatch[30]",
"tests/test_base32.py::test_decode_timestamp_raises_on_str_length_mismatch[31]",
"tests/test_base32.py::test_decode_timestamp_raises_on_non_ascii_str",
"tests/test_base32.py::test_decode_randomness_returns_10_bytes",
"tests/test_base32.py::test_decode_randomness_raises_on_str_length_mismatch[0]",
"tests/test_base32.py::test_decode_randomness_raises_on_str_length_mismatch[1]",
"tests/test_base32.py::test_decode_randomness_raises_on_str_length_mismatch[2]",
"tests/test_base32.py::test_decode_randomness_raises_on_str_length_mismatch[3]",
"tests/test_base32.py::test_decode_randomness_raises_on_str_length_mismatch[4]",
"tests/test_base32.py::test_decode_randomness_raises_on_str_length_mismatch[5]",
"tests/test_base32.py::test_decode_randomness_raises_on_str_length_mismatch[6]",
"tests/test_base32.py::test_decode_randomness_raises_on_str_length_mismatch[7]",
"tests/test_base32.py::test_decode_randomness_raises_on_str_length_mismatch[8]",
"tests/test_base32.py::test_decode_randomness_raises_on_str_length_mismatch[9]",
"tests/test_base32.py::test_decode_randomness_raises_on_str_length_mismatch[10]",
"tests/test_base32.py::test_decode_randomness_raises_on_str_length_mismatch[11]",
"tests/test_base32.py::test_decode_randomness_raises_on_str_length_mismatch[12]",
"tests/test_base32.py::test_decode_randomness_raises_on_str_length_mismatch[13]",
"tests/test_base32.py::test_decode_randomness_raises_on_str_length_mismatch[14]",
"tests/test_base32.py::test_decode_randomness_raises_on_str_length_mismatch[15]",
"tests/test_base32.py::test_decode_randomness_raises_on_str_length_mismatch[16]",
"tests/test_base32.py::test_decode_randomness_raises_on_str_length_mismatch[17]",
"tests/test_base32.py::test_decode_randomness_raises_on_str_length_mismatch[18]",
"tests/test_base32.py::test_decode_randomness_raises_on_str_length_mismatch[19]",
"tests/test_base32.py::test_decode_randomness_raises_on_str_length_mismatch[20]",
"tests/test_base32.py::test_decode_randomness_raises_on_str_length_mismatch[21]",
"tests/test_base32.py::test_decode_randomness_raises_on_str_length_mismatch[22]",
"tests/test_base32.py::test_decode_randomness_raises_on_str_length_mismatch[23]",
"tests/test_base32.py::test_decode_randomness_raises_on_str_length_mismatch[24]",
"tests/test_base32.py::test_decode_randomness_raises_on_str_length_mismatch[25]",
"tests/test_base32.py::test_decode_randomness_raises_on_str_length_mismatch[26]",
"tests/test_base32.py::test_decode_randomness_raises_on_str_length_mismatch[27]",
"tests/test_base32.py::test_decode_randomness_raises_on_str_length_mismatch[28]",
"tests/test_base32.py::test_decode_randomness_raises_on_str_length_mismatch[29]",
"tests/test_base32.py::test_decode_randomness_raises_on_str_length_mismatch[30]",
"tests/test_base32.py::test_decode_randomness_raises_on_str_length_mismatch[31]",
"tests/test_base32.py::test_decode_randomness_raises_on_non_ascii_str",
"tests/test_base32.py::test_decode_table_has_value_for_entire_decoding_alphabet"
]
| []
| Apache License 2.0 | 1,818 | [
"ulid/base32.py"
]
| [
"ulid/base32.py"
]
|
|
levlaz__circleci.py-28 | 873f151b4c378dec7333c68f9f5e5279e0899532 | 2017-10-29 01:37:16 | 80caa75bab504d47482e21053d65130a03d8742a | diff --git a/circleci/api.py b/circleci/api.py
index cf8a7ab..84ea9c6 100644
--- a/circleci/api.py
+++ b/circleci/api.py
@@ -259,7 +259,7 @@ class Api():
resp = self._request('GET', endpoint)
return resp
- def retry_build(self, username, project, build_num, vcs_type='github'):
+ def retry_build(self, username, project, build_num, ssh=False, vcs_type='github'):
"""Retries the build.
Args:
@@ -269,6 +269,8 @@ class Api():
case sensitive repo name
build_num (str):
build number
+ ssh: retry a build with SSH enabled
+ defaults to False
vcs_type (str):
defaults to github
on circleci.com you can also pass in bitbucket
@@ -276,12 +278,20 @@ class Api():
Endpoint:
POST: /project/:vcs-type/:username/:project/:build_num/retry
"""
- endpoint = 'project/{0}/{1}/{2}/{3}/retry'.format(
- vcs_type,
- username,
- project,
- build_num
- )
+ if ssh:
+ endpoint = 'project/{0}/{1}/{2}/{3}/ssh'.format(
+ vcs_type,
+ username,
+ project,
+ build_num
+ )
+ else:
+ endpoint = 'project/{0}/{1}/{2}/{3}/retry'.format(
+ vcs_type,
+ username,
+ project,
+ build_num
+ )
resp = self._request('POST', endpoint)
return resp
| Update retry method to include retry with SSH
We have retry, and we also have retry without cache via the Experimental API. We should also include an option to retry with SSH as [described here](https://circleci.com/docs/api/v1-reference/#retry-build) | levlaz/circleci.py | diff --git a/tests/circle/test_api.py b/tests/circle/test_api.py
index 347223b..33c0ee0 100644
--- a/tests/circle/test_api.py
+++ b/tests/circle/test_api.py
@@ -92,6 +92,11 @@ class TestCircleCIApi(unittest.TestCase):
self.assertEqual(resp['reponame'], 'MOCK+testing')
+ # with SSH
+ resp = json.loads(self.c.retry_build('ccie-tester', 'testing', '1', ssh=True))
+
+ self.assertEqual(resp['reponame'], 'MOCK+testing')
+
def test_cancel_build(self):
self.loadMock('mock_cancel_build_response')
resp = json.loads(self.c.cancel_build('ccie-tester', 'testing', '11'))
@@ -194,6 +199,12 @@ class TestCircleCIApi(unittest.TestCase):
self.assertEqual(resp[0]['path'],'circleci-docs/index.html')
+ resp = json.loads(self.c.get_latest_artifact('levlaz', 'circleci-sandbox', 'master'))
+ self.assertEqual(resp[0]['path'],'circleci-docs/index.html')
+
+ with self.assertRaises(InvalidFilterError):
+ self.c.get_latest_artifact('levlaz', 'circleci-sandbox', 'master', 'invalid')
+
# def test_helper(self):
# resp = self.c.get_latest_artifact('circleci', 'circleci-docs')
# print(resp)
diff --git a/tests/circle/test_error.py b/tests/circle/test_error.py
index bab58d1..c907ad2 100644
--- a/tests/circle/test_error.py
+++ b/tests/circle/test_error.py
@@ -11,7 +11,7 @@ class TestCircleCIError(unittest.TestCase):
self.key = BadKeyError('fake')
self.verb = BadVerbError('fake')
self.filter = InvalidFilterError('fake', 'status')
-
+ self.afilter = InvalidFilterError('fake', 'artifacts')
def test_error_implements_str(self):
self.assertTrue(self.base.__str__ is not object.__str__)
@@ -26,5 +26,6 @@ class TestCircleCIError(unittest.TestCase):
self.assertIn('deploy-key', self.key.message)
def test_filter_message(self):
- print(self.filter)
- self.assertIn('running', self.filter.message)
\ No newline at end of file
+ self.assertIn('running', self.filter.message)
+
+ self.assertIn('completed', self.afilter.message)
\ No newline at end of file
| {
"commit_name": "merge_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 2,
"test_score": 3
},
"num_modified_files": 1
} | 1.1 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"pytest"
],
"pre_install": null,
"python": "3.9",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | certifi==2025.1.31
chardet==3.0.4
-e git+https://github.com/levlaz/circleci.py.git@873f151b4c378dec7333c68f9f5e5279e0899532#egg=circleci
exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work
idna==2.6
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
packaging @ file:///croot/packaging_1734472117206/work
pluggy @ file:///croot/pluggy_1733169602837/work
pytest @ file:///croot/pytest_1738938843180/work
requests==2.18.4
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
urllib3==1.22
| name: circleci.py
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- exceptiongroup=1.2.0=py39h06a4308_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- packaging=24.2=py39h06a4308_0
- pip=25.0=py39h06a4308_0
- pluggy=1.5.0=py39h06a4308_0
- pytest=8.3.4=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tomli=2.0.1=py39h06a4308_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- certifi==2025.1.31
- chardet==3.0.4
- idna==2.6
- requests==2.18.4
- urllib3==1.22
prefix: /opt/conda/envs/circleci.py
| [
"tests/circle/test_api.py::TestCircleCIApi::test_retry_build"
]
| []
| [
"tests/circle/test_api.py::TestCircleCIApi::test_add_envvar",
"tests/circle/test_api.py::TestCircleCIApi::test_add_ssh_user",
"tests/circle/test_api.py::TestCircleCIApi::test_bad_verb",
"tests/circle/test_api.py::TestCircleCIApi::test_cancel_build",
"tests/circle/test_api.py::TestCircleCIApi::test_clear_cache",
"tests/circle/test_api.py::TestCircleCIApi::test_create_checkout_key",
"tests/circle/test_api.py::TestCircleCIApi::test_delete_checkout_key",
"tests/circle/test_api.py::TestCircleCIApi::test_delete_envvar",
"tests/circle/test_api.py::TestCircleCIApi::test_follow_project",
"tests/circle/test_api.py::TestCircleCIApi::test_get_artifacts",
"tests/circle/test_api.py::TestCircleCIApi::test_get_build_info",
"tests/circle/test_api.py::TestCircleCIApi::test_get_checkout_key",
"tests/circle/test_api.py::TestCircleCIApi::test_get_envvar",
"tests/circle/test_api.py::TestCircleCIApi::test_get_latest_artifact",
"tests/circle/test_api.py::TestCircleCIApi::test_get_project_build_summary",
"tests/circle/test_api.py::TestCircleCIApi::test_get_projects",
"tests/circle/test_api.py::TestCircleCIApi::test_get_recent_builds",
"tests/circle/test_api.py::TestCircleCIApi::test_get_test_metadata",
"tests/circle/test_api.py::TestCircleCIApi::test_get_user_info",
"tests/circle/test_api.py::TestCircleCIApi::test_list_checkout_keys",
"tests/circle/test_api.py::TestCircleCIApi::test_list_envvars",
"tests/circle/test_api.py::TestCircleCIApi::test_trigger_build",
"tests/circle/test_error.py::TestCircleCIError::test_error_implements_str",
"tests/circle/test_error.py::TestCircleCIError::test_filter_message",
"tests/circle/test_error.py::TestCircleCIError::test_key_message",
"tests/circle/test_error.py::TestCircleCIError::test_verb_message"
]
| []
| MIT License | 1,819 | [
"circleci/api.py"
]
| [
"circleci/api.py"
]
|
|
VictorPelaez__coral-reef-optimization-algorithm-43 | 9939a280c87090b7ae575a23670f49a265ad017a | 2017-10-29 08:56:15 | 9939a280c87090b7ae575a23670f49a265ad017a | diff --git a/cro/cro.py b/cro/cro.py
index 44c17ae..ebc560b 100644
--- a/cro/cro.py
+++ b/cro/cro.py
@@ -20,6 +20,7 @@ class CRO(object):
self.Pd = Pd
self.fitness_coral = fitness_coral
self.opt = opt
+ self.opt_multiplier = -1 if opt == "max" else 1
self.L = L
self.ke = ke
self.seed = seed
@@ -83,7 +84,7 @@ class CRO(object):
coral_fitness = self.fitness_coral(coral)
REEF_fitness.append(coral_fitness)
- return np.array(REEF_fitness)
+ return self.opt_multiplier*np.array(REEF_fitness)
def broadcastspawning(self, REEF, REEFpob):
"""
@@ -197,7 +198,6 @@ class CRO(object):
- REEFfitness: new reef fitness
"""
k = self.k
- opt = self.opt
np.random.seed(seed=self.seed)
Nlarvae = larvae.shape[0]
@@ -222,10 +222,7 @@ class CRO(object):
REEFfitness[reef_index] = larva_fitness
REEF[reef_index] = 1
else: # occupied coral
- if opt == "max":
- fitness_comparison = larva_fitness > REEFfitness[reef_indices]
- else:
- fitness_comparison = larva_fitness < REEFfitness[reef_indices]
+ fitness_comparison = larva_fitness < REEFfitness[reef_indices]
if np.any(fitness_comparison):
reef_index = reef_indices[np.where(fitness_comparison)[0][0]]
@@ -243,7 +240,6 @@ class CRO(object):
- pob: reef population
- fitness: reef fitness
- Fa: fraction of corals to be duplicated
- - opt: type of optimization ('max' or 'min')
Output:
- Alarvae: created larvae,
- Afitness: larvae's fitness
@@ -255,8 +251,7 @@ class CRO(object):
N = pob.shape[0]
NA = int(np.round(Fa*N))
- if self.opt=='max': ind = np.argsort(-fitness);
- else: ind = np.argsort(fitness)
+ ind = np.argsort(fitness)
fitness = fitness[ind]
Alarvae = pob[ind[0:NA], :]
@@ -284,10 +279,8 @@ class CRO(object):
Pd = self.Pd
np.random.seed(seed = self.seed)
- if (self.opt=='max'):
- ind = np.argsort(REEFfitness)
- else:
- ind = np.argsort(-REEFfitness)
+ # Sort by worse fitness (hence the minus sign)
+ ind = np.argsort(-REEFfitness)
sortind = ind[:int(np.round(Fd*REEFpob.shape[0]))]
p = np.random.rand(len(sortind))
@@ -390,13 +383,10 @@ class CRO(object):
Bestfitness = []
Meanfitness = []
- if opt=='max':
- if verbose: print('Reef initialization:', np.max(REEFfitness))
- Bestfitness.append(np.max(REEFfitness))
- else:
- if verbose: print('Reef initialization:', np.min(REEFfitness))
- Bestfitness.append(np.min(REEFfitness))
- Meanfitness.append(np.mean(REEFfitness))
+ Bestfitness.append(self.opt_multiplier*np.min(REEFfitness))
+ Meanfitness.append(self.opt_multiplier*np.mean(REEFfitness))
+ if verbose:
+ print('Reef initialization:', self.opt_multiplier*np.min(REEFfitness))
for n in range(Ngen):
@@ -420,23 +410,18 @@ class CRO(object):
(REEF, REEFpob, REEFfitness) = self.depredation(REEF, REEFpob, REEFfitness)
(REEF, REEFpob, REEFfitness) = self.extremedepredation(REEF, REEFpob, REEFfitness, int(np.round(self.ke*N*M)))
- if opt=='max': Bestfitness.append(np.max(REEFfitness))
- else: Bestfitness.append(np.min(REEFfitness))
- Meanfitness.append(np.mean(REEFfitness))
+ Bestfitness.append(self.opt_multiplier*np.min(REEFfitness))
+ Meanfitness.append(self.opt_multiplier*np.mean(REEFfitness))
- if (n%10==0) & (n!=Ngen):
- if (opt=='max') & (verbose): print('Best-fitness:', np.max(REEFfitness), '\n', str(n/Ngen*100) + '% completado \n' );
- if (opt=='min') & (verbose): print('Best-fitness:', np.min(REEFfitness), '\n', str(n/Ngen*100) + '% completado \n' );
+ if all([n%10 == 0, n != Ngen, verbose]):
+ print('Best-fitness:', self.opt_multiplier*np.min(REEFfitness), '\n', str(n/Ngen*100) + '% completado \n' );
- if opt=='max':
- if verbose: print('Best-fitness:', np.max(REEFfitness), '\n', str(100) + '% completado \n' )
- ind_best = np.where(REEFfitness == np.max(REEFfitness))[0][0]
- else:
- if verbose: print('Best-fitness:', np.min(REEFfitness), '\n', str(100) + '% completado \n' )
- ind_best = np.where(REEFfitness == np.min(REEFfitness))[0][0]
+ if verbose:
+ print('Best-fitness:', self.opt_multiplier*np.min(REEFfitness), '\n', str(100) + '% completado \n' )
+ ind_best = np.where(REEFfitness == np.min(REEFfitness))[0][0]
self.plot_results(Bestfitness, Meanfitness)
print('Best coral: ', REEFpob[ind_best, :])
- print('Best solution:', REEFfitness[ind_best])
+ print('Best solution:', self.opt_multiplier*REEFfitness[ind_best])
return (REEF, REEFpob, REEFfitness, ind_best, Bestfitness, Meanfitness)
| create a opt_multiplier (-1 or 1) with opt argument
One of the main point suggested in Issue #22.
Using opt argument, create a self.opt_multiplier (1, -1)
It looks an improvement in 2 functions:
- budding()
```
if self.opt=='max': ind = np.argsort(-fitness);
else: ind = np.argsort(fitness)
```
- depredation()
```
if (self.opt=='max'):
ind = np.argsort(REEFfitness)
else:
ind = np.argsort(-REEFfitness)
```
@apastors Did your proposal cover anything else? regards | VictorPelaez/coral-reef-optimization-algorithm | diff --git a/cro/tests.py b/cro/tests.py
index abd19cf..9bde3df 100644
--- a/cro/tests.py
+++ b/cro/tests.py
@@ -91,14 +91,14 @@ def test_larvaesettling_nonemptyreef():
[1,0,1,1]])
REEF = np.array([0,1,1,1])
- REEFfitness = np.array([0,1,2,11])
+ REEFfitness = -np.array([0,1,2,11])
larvae = np.array([[1,0,0,0],
[0,1,1,0],
[0,1,0,0],
[1,0,0,1]])
- larvaefitness = np.array([8,6,4,9])
+ larvaefitness = -np.array([8,6,4,9])
N, L = REEFpob.shape
M = 1
@@ -126,7 +126,7 @@ def test_larvaesettling_nonemptyreef():
[1,0,0,1],
[0,0,1,0],
[1,0,1,1]])
- REEFfitness_exp = np.array([8,9,2,11])
+ REEFfitness_exp = -np.array([8,9,2,11])
np.testing.assert_almost_equal(REEF_res, np.array([1,1,1,1]))
np.testing.assert_almost_equal(REEFpob_res, REEFpob_exp)
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_issue_reference",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 2,
"test_score": 3
},
"num_modified_files": 1
} | unknown | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | -e git+https://github.com/VictorPelaez/coral-reef-optimization-algorithm.git@9939a280c87090b7ae575a23670f49a265ad017a#egg=cro
exceptiongroup==1.2.2
iniconfig==2.1.0
joblib==1.4.2
numpy==2.0.2
packaging==24.2
pandas==2.2.3
pluggy==1.5.0
pytest==8.3.5
python-dateutil==2.9.0.post0
pytz==2025.2
scikit-learn==1.6.1
scipy==1.13.1
six==1.17.0
threadpoolctl==3.6.0
tomli==2.2.1
tzdata==2025.2
| name: coral-reef-optimization-algorithm
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- exceptiongroup==1.2.2
- iniconfig==2.1.0
- joblib==1.4.2
- numpy==2.0.2
- packaging==24.2
- pandas==2.2.3
- pluggy==1.5.0
- pytest==8.3.5
- python-dateutil==2.9.0.post0
- pytz==2025.2
- scikit-learn==1.6.1
- scipy==1.13.1
- six==1.17.0
- threadpoolctl==3.6.0
- tomli==2.2.1
- tzdata==2025.2
prefix: /opt/conda/envs/coral-reef-optimization-algorithm
| [
"cro/tests.py::test_larvaesettling_nonemptyreef"
]
| []
| [
"cro/tests.py::test_croCreation",
"cro/tests.py::test_croInit",
"cro/tests.py::test_reefinitializationDisc",
"cro/tests.py::test_larvaesettling_emptyreef"
]
| []
| MIT License | 1,820 | [
"cro/cro.py"
]
| [
"cro/cro.py"
]
|
|
borgbackup__borg-3234 | 4a58310433f21857fc124eed4bafde2956bac46a | 2017-10-29 13:19:08 | a439fa3e720c8bb2a82496768ffcce282fb7f7b7 | codecov-io: # [Codecov](https://codecov.io/gh/borgbackup/borg/pull/3234?src=pr&el=h1) Report
> Merging [#3234](https://codecov.io/gh/borgbackup/borg/pull/3234?src=pr&el=desc) into [master](https://codecov.io/gh/borgbackup/borg/commit/2b79aade368140026562a7b515f02952ddc3474e?src=pr&el=desc) will **decrease** coverage by `0.14%`.
> The diff coverage is `80%`.
[](https://codecov.io/gh/borgbackup/borg/pull/3234?src=pr&el=tree)
```diff
@@ Coverage Diff @@
## master #3234 +/- ##
=========================================
- Coverage 85.94% 85.8% -0.15%
=========================================
Files 36 36
Lines 8981 8991 +10
Branches 1490 1491 +1
=========================================
- Hits 7719 7715 -4
- Misses 848 860 +12
- Partials 414 416 +2
```
| [Impacted Files](https://codecov.io/gh/borgbackup/borg/pull/3234?src=pr&el=tree) | Coverage Δ | |
|---|---|---|
| [src/borg/archiver.py](https://codecov.io/gh/borgbackup/borg/pull/3234?src=pr&el=tree#diff-c3JjL2JvcmcvYXJjaGl2ZXIucHk=) | `86.11% <100%> (-0.42%)` | :arrow_down: |
| [src/borg/archive.py](https://codecov.io/gh/borgbackup/borg/pull/3234?src=pr&el=tree#diff-c3JjL2JvcmcvYXJjaGl2ZS5weQ==) | `83.76% <77.77%> (+0.1%)` | :arrow_up: |
| [src/borg/helpers/misc.py](https://codecov.io/gh/borgbackup/borg/pull/3234?src=pr&el=tree#diff-c3JjL2JvcmcvaGVscGVycy9taXNjLnB5) | `81.73% <0%> (-6.09%)` | :arrow_down: |
------
[Continue to review full report at Codecov](https://codecov.io/gh/borgbackup/borg/pull/3234?src=pr&el=continue).
> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
> `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
> Powered by [Codecov](https://codecov.io/gh/borgbackup/borg/pull/3234?src=pr&el=footer). Last update [2b79aad...46f1513](https://codecov.io/gh/borgbackup/borg/pull/3234?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).
enkore: Wasn't this observed in 1.1, which does this differently?
ThomasWaldmann: IIRC I tried to reproduce in master and found it broken. Maybe it has other reasons in 1.1, that could be.
ThomasWaldmann: output of fixed code:
```
(borg-env) tw@tux:~/w/borg$ borg init -e none repo
(borg-env) tw@tux:~/w/borg$ borg create --stats repo::arch src
------------------------------------------------------------------------------
Archive name: arch
Archive fingerprint: 2225d8d8fc2424e179a8c311ff950c936a429c4e598389552212e6777b6b0e7b
Time (start): Thu, 2017-11-02 17:39:43
Time (end): Thu, 2017-11-02 17:39:45
Duration: 2.13 seconds
Number of files: 471
Utilization of max. archive size: 0%
------------------------------------------------------------------------------
Original size Compressed size Deduplicated size
This archive: 146.66 MB 39.29 MB 36.87 MB
All archives: 146.66 MB 39.29 MB 36.87 MB
Unique chunks Total chunks
Chunk index: 499 508
------------------------------------------------------------------------------
(borg-env) tw@tux:~/w/borg$ borg create --stats repo::arch2 src
------------------------------------------------------------------------------
Archive name: arch2
Archive fingerprint: 9b75b27a7e31d8afdf9b05c402bdc9ff80fea5f9d56e54a9a3282ce33aa5d4b0
Time (start): Thu, 2017-11-02 17:40:22
Time (end): Thu, 2017-11-02 17:40:22
Duration: 0.09 seconds
Number of files: 471
Utilization of max. archive size: 0%
------------------------------------------------------------------------------
Original size Compressed size Deduplicated size
This archive: 146.66 MB 39.29 MB 41.75 kB
All archives: 293.33 MB 78.58 MB 36.91 MB
Unique chunks Total chunks
Chunk index: 501 1016
------------------------------------------------------------------------------
```
ThomasWaldmann: output of master code:
```
(borg-env) tw@tux:~/w/borg$ borg init -e none repo
(borg-env) tw@tux:~/w/borg$ borg create --stats repo::arch src
------------------------------------------------------------------------------
Archive name: arch
Archive fingerprint: 7adea46884c14504608ef2f4cbb54f6e5a8a0607b5d1b4d2e84cabcc2867cf13
Time (start): Thu, 2017-11-02 17:43:44
Time (end): Thu, 2017-11-02 17:43:46
Duration: 2.50 seconds
Number of files: 0
Utilization of max. archive size: 0%
------------------------------------------------------------------------------
Original size Compressed size Deduplicated size
This archive: 106.12 kB 41.73 kB 41.73 kB
All archives: 146.66 MB 39.29 MB 36.87 MB
Unique chunks Total chunks
Chunk index: 499 508
------------------------------------------------------------------------------
(borg-env) tw@tux:~/w/borg$ borg create --stats repo::arch2 src
------------------------------------------------------------------------------
Archive name: arch2
Archive fingerprint: efbfeb5728b5d8f287320b3567b5ae13d2723ea228a7360131a2fb10ed2e36f0
Time (start): Thu, 2017-11-02 17:44:00
Time (end): Thu, 2017-11-02 17:44:00
Duration: 0.09 seconds
Number of files: 0
Utilization of max. archive size: 0%
------------------------------------------------------------------------------
Original size Compressed size Deduplicated size
This archive: 106.12 kB 41.73 kB 41.73 kB
All archives: 293.33 MB 78.58 MB 36.91 MB
Unique chunks Total chunks
Chunk index: 501 1016
------------------------------------------------------------------------------
```
"Number of files" and "This Archive" stats obviously broken.
| diff --git a/src/borg/archive.py b/src/borg/archive.py
index e04731e8..a8fbba91 100644
--- a/src/borg/archive.py
+++ b/src/borg/archive.py
@@ -65,6 +65,16 @@ def update(self, size, csize, unique):
if unique:
self.usize += csize
+ def __add__(self, other):
+ if not isinstance(other, Statistics):
+ raise TypeError('can only add Statistics objects')
+ stats = Statistics(self.output_json)
+ stats.osize = self.osize + other.osize
+ stats.csize = self.csize + other.csize
+ stats.usize = self.usize + other.usize
+ stats.nfiles = self.nfiles + other.nfiles
+ return stats
+
summary = "{label:15} {stats.osize_fmt:>20s} {stats.csize_fmt:>20s} {stats.usize_fmt:>20s}"
def __str__(self):
diff --git a/src/borg/archiver.py b/src/borg/archiver.py
index d678bb28..03f66137 100644
--- a/src/borg/archiver.py
+++ b/src/borg/archiver.py
@@ -49,7 +49,7 @@
from .helpers import BaseFormatter, ItemFormatter, ArchiveFormatter
from .helpers import format_timedelta, format_file_size, parse_file_size, format_archive
from .helpers import safe_encode, remove_surrogates, bin_to_hex, prepare_dump_dict
-from .helpers import interval, prune_within, prune_split, PRUNING_PATTERNS
+from .helpers import interval, prune_within, prune_split
from .helpers import timestamp
from .helpers import get_cache_dir
from .helpers import Manifest, AI_HUMAN_SORT_KEYS
@@ -482,6 +482,7 @@ def create_inner(archive, cache, fso):
if args.progress:
archive.stats.show_progress(final=True)
args.stats |= args.json
+ archive.stats += fso.stats
if args.stats:
if args.json:
json_print(basic_json_data(manifest, cache=cache, extra={
@@ -1333,48 +1334,45 @@ def do_prune(self, args, repository, manifest, key):
# that is newer than a successfully completed backup - and killing the successful backup.
archives = [arch for arch in archives_checkpoints if arch not in checkpoints]
keep = []
- # collect the rule responsible for the keeping of each archive in this dict
- # keys are archive ids, values are a tuple
- # (<rulename>, <how many archives were kept by this rule so far >)
- kept_because = {}
-
- # find archives which need to be kept because of the keep-within rule
if args.within:
- keep += prune_within(archives, args.within, kept_because)
-
- # find archives which need to be kept because of the various time period rules
- for rule in PRUNING_PATTERNS.keys():
- num = getattr(args, rule, None)
- if num is not None:
- keep += prune_split(archives, rule, num, kept_because)
-
+ keep += prune_within(archives, args.within)
+ if args.secondly:
+ keep += prune_split(archives, '%Y-%m-%d %H:%M:%S', args.secondly, keep)
+ if args.minutely:
+ keep += prune_split(archives, '%Y-%m-%d %H:%M', args.minutely, keep)
+ if args.hourly:
+ keep += prune_split(archives, '%Y-%m-%d %H', args.hourly, keep)
+ if args.daily:
+ keep += prune_split(archives, '%Y-%m-%d', args.daily, keep)
+ if args.weekly:
+ keep += prune_split(archives, '%G-%V', args.weekly, keep)
+ if args.monthly:
+ keep += prune_split(archives, '%Y-%m', args.monthly, keep)
+ if args.yearly:
+ keep += prune_split(archives, '%Y', args.yearly, keep)
to_delete = (set(archives) | checkpoints) - (set(keep) | set(keep_checkpoints))
stats = Statistics()
with Cache(repository, key, manifest, do_files=False, lock_wait=self.lock_wait) as cache:
list_logger = logging.getLogger('borg.output.list')
- # set up counters for the progress display
- to_delete_len = len(to_delete)
- archives_deleted = 0
+ if args.output_list:
+ # set up counters for the progress display
+ to_delete_len = len(to_delete)
+ archives_deleted = 0
for archive in archives_checkpoints:
if archive in to_delete:
if args.dry_run:
- log_message = 'Would prune:'
+ if args.output_list:
+ list_logger.info('Would prune: %s' % format_archive(archive))
else:
- archives_deleted += 1
- log_message = 'Pruning archive (%d/%d):' % (archives_deleted, to_delete_len)
+ if args.output_list:
+ archives_deleted += 1
+ list_logger.info('Pruning archive: %s (%d/%d)' % (format_archive(archive),
+ archives_deleted, to_delete_len))
Archive(repository, key, manifest, archive.name, cache,
progress=args.progress).delete(stats, forced=args.forced)
else:
- if is_checkpoint(archive.name):
- log_message = 'Keeping checkpoint archive:'
- else:
- log_message = 'Keeping archive (rule: {rule} #{num}):'.format(
- rule=kept_because[archive.id][0], num=kept_because[archive.id][1]
- )
- if args.output_list:
- list_logger.info("{message:<40} {archive}".format(
- message=log_message, archive=format_archive(archive)
- ))
+ if args.output_list:
+ list_logger.info('Keeping archive: %s' % format_archive(archive))
if to_delete and not args.dry_run:
manifest.write()
repository.commit(save_space=args.save_space)
diff --git a/src/borg/helpers/misc.py b/src/borg/helpers/misc.py
index b0fbb203..e33b46f0 100644
--- a/src/borg/helpers/misc.py
+++ b/src/borg/helpers/misc.py
@@ -4,7 +4,7 @@
import os.path
import platform
import sys
-from collections import deque, OrderedDict
+from collections import deque
from datetime import datetime, timezone, timedelta
from itertools import islice
from operator import attrgetter
@@ -17,44 +17,22 @@
from .. import chunker
-def prune_within(archives, hours, kept_because):
+def prune_within(archives, hours):
target = datetime.now(timezone.utc) - timedelta(seconds=hours * 3600)
- kept_counter = 0
- result = []
- for a in archives:
- if a.ts > target:
- kept_counter += 1
- kept_because[a.id] = ("within", kept_counter)
- result.append(a)
- return result
-
-
-PRUNING_PATTERNS = OrderedDict([
- ("secondly", '%Y-%m-%d %H:%M:%S'),
- ("minutely", '%Y-%m-%d %H:%M'),
- ("hourly", '%Y-%m-%d %H'),
- ("daily", '%Y-%m-%d'),
- ("weekly", '%G-%V'),
- ("monthly", '%Y-%m'),
- ("yearly", '%Y'),
-])
-
-
-def prune_split(archives, rule, n, kept_because=None):
+ return [a for a in archives if a.ts > target]
+
+
+def prune_split(archives, pattern, n, skip=[]):
last = None
keep = []
- pattern = PRUNING_PATTERNS[rule]
- if kept_because is None:
- kept_because = {}
if n == 0:
return keep
for a in sorted(archives, key=attrgetter('ts'), reverse=True):
period = to_localtime(a.ts).strftime(pattern)
if period != last:
last = period
- if a.id not in kept_because:
+ if a not in skip:
keep.append(a)
- kept_because[a.id] = (rule, len(keep))
if len(keep) == n:
break
return keep
| wrong original size in borg create
Hello,
[borg 1.1.1 python 3.4.5 CentOs 6]
I tried 2 times with same command but different files ( oracle dump ) and both times I had
an original size reported twice bigger than the real one.
The file is 109 GB.
I tried even with smaller files but the problem did not appear.
```
# borg create -p --stats /opt/mnt/test.borg::test2 ads_orcl_daily_dmp_5
------------------------------------------------------------------------------
Archive name: test2
Archive fingerprint: ba34d3cb846d521388a14ea5cf1b9a8addb114de386a042738b99fac01e48a42
Time (start): Thu, 2017-10-26 12:33:18
Time (end): Thu, 2017-10-26 13:33:38
Duration: 1 hours 20.12 seconds
Number of files: 1
Utilization of max. archive size: 0%
------------------------------------------------------------------------------
Original size Compressed size Deduplicated size
This archive: 232.90 GB 205.06 GB 102.53 GB
All archives: 232.90 GB 205.06 GB 102.53 GB
Unique chunks Total chunks
Chunk index: 44512 89022
------------------------------------------------------------------------------
```
giuseppe
| borgbackup/borg | diff --git a/src/borg/testsuite/archiver.py b/src/borg/testsuite/archiver.py
index 29fc50f7..c3a66632 100644
--- a/src/borg/testsuite/archiver.py
+++ b/src/borg/testsuite/archiver.py
@@ -6,7 +6,6 @@
import os
import pstats
import random
-import re
import shutil
import socket
import stat
@@ -1732,11 +1731,12 @@ def test_prune_repository(self):
self.cmd('create', self.repository_location + '::test3.checkpoint.1', src_dir)
self.cmd('create', self.repository_location + '::test4.checkpoint', src_dir)
output = self.cmd('prune', '--list', '--dry-run', self.repository_location, '--keep-daily=2')
- assert re.search(r'Would prune:\s+test1', output)
+ self.assert_in('Keeping archive: test2', output)
+ self.assert_in('Would prune: test1', output)
# must keep the latest non-checkpoint archive:
- assert re.search(r'Keeping archive \(rule: daily #1\):\s+test2', output)
+ self.assert_in('Keeping archive: test2', output)
# must keep the latest checkpoint archive:
- assert re.search(r'Keeping checkpoint archive:\s+test4.checkpoint', output)
+ self.assert_in('Keeping archive: test4.checkpoint', output)
output = self.cmd('list', self.repository_location)
self.assert_in('test1', output)
self.assert_in('test2', output)
@@ -1766,8 +1766,8 @@ def test_prune_repository_save_space(self):
self.cmd('create', self.repository_location + '::test1', src_dir)
self.cmd('create', self.repository_location + '::test2', src_dir)
output = self.cmd('prune', '--list', '--stats', '--dry-run', self.repository_location, '--keep-daily=2')
- assert re.search(r'Keeping archive \(rule: daily #1\):\s+test2', output)
- assert re.search(r'Would prune:\s+test1', output)
+ self.assert_in('Keeping archive: test2', output)
+ self.assert_in('Would prune: test1', output)
self.assert_in('Deleted data:', output)
output = self.cmd('list', self.repository_location)
self.assert_in('test1', output)
@@ -1784,8 +1784,8 @@ def test_prune_repository_prefix(self):
self.cmd('create', self.repository_location + '::bar-2015-08-12-10:00', src_dir)
self.cmd('create', self.repository_location + '::bar-2015-08-12-20:00', src_dir)
output = self.cmd('prune', '--list', '--dry-run', self.repository_location, '--keep-daily=2', '--prefix=foo-')
- assert re.search(r'Keeping archive \(rule: daily #1\):\s+foo-2015-08-12-20:00', output)
- assert re.search(r'Would prune:\s+foo-2015-08-12-10:00', output)
+ self.assert_in('Keeping archive: foo-2015-08-12-20:00', output)
+ self.assert_in('Would prune: foo-2015-08-12-10:00', output)
output = self.cmd('list', self.repository_location)
self.assert_in('foo-2015-08-12-10:00', output)
self.assert_in('foo-2015-08-12-20:00', output)
@@ -1805,8 +1805,8 @@ def test_prune_repository_glob(self):
self.cmd('create', self.repository_location + '::2015-08-12-10:00-bar', src_dir)
self.cmd('create', self.repository_location + '::2015-08-12-20:00-bar', src_dir)
output = self.cmd('prune', '--list', '--dry-run', self.repository_location, '--keep-daily=2', '--glob-archives=2015-*-foo')
- assert re.search(r'Keeping archive \(rule: daily #1\):\s+2015-08-12-20:00-foo', output)
- assert re.search(r'Would prune:\s+2015-08-12-10:00-foo', output)
+ self.assert_in('Keeping archive: 2015-08-12-20:00-foo', output)
+ self.assert_in('Would prune: 2015-08-12-10:00-foo', output)
output = self.cmd('list', self.repository_location)
self.assert_in('2015-08-12-10:00-foo', output)
self.assert_in('2015-08-12-20:00-foo', output)
diff --git a/src/borg/testsuite/helpers.py b/src/borg/testsuite/helpers.py
index 8d191974..15c029f5 100644
--- a/src/borg/testsuite/helpers.py
+++ b/src/borg/testsuite/helpers.py
@@ -1,10 +1,11 @@
import hashlib
+import io
import os
import shutil
import sys
from argparse import ArgumentTypeError
from datetime import datetime, timezone, timedelta
-from time import sleep
+from time import mktime, strptime, sleep
import pytest
@@ -332,56 +333,40 @@ def test(self):
class MockArchive:
- def __init__(self, ts, id):
+ def __init__(self, ts):
self.ts = ts
- self.id = id
def __repr__(self):
- return "{0}: {1}".format(self.id, self.ts.isoformat())
-
-
[email protected](
- "rule,num_to_keep,expected_ids", [
- ("yearly", 3, (13, 2, 1)),
- ("monthly", 3, (13, 8, 4)),
- ("weekly", 2, (13, 8)),
- ("daily", 3, (13, 8, 7)),
- ("hourly", 3, (13, 10, 8)),
- ("minutely", 3, (13, 10, 9)),
- ("secondly", 4, (13, 12, 11, 10)),
- ("daily", 0, []),
- ]
-)
-def test_prune_split(rule, num_to_keep, expected_ids):
- def subset(lst, ids):
- return {i for i in lst if i.id in ids}
-
- archives = [
- # years apart
- MockArchive(datetime(2015, 1, 1, 10, 0, 0, tzinfo=timezone.utc), 1),
- MockArchive(datetime(2016, 1, 1, 10, 0, 0, tzinfo=timezone.utc), 2),
- MockArchive(datetime(2017, 1, 1, 10, 0, 0, tzinfo=timezone.utc), 3),
- # months apart
- MockArchive(datetime(2017, 2, 1, 10, 0, 0, tzinfo=timezone.utc), 4),
- MockArchive(datetime(2017, 3, 1, 10, 0, 0, tzinfo=timezone.utc), 5),
- # days apart
- MockArchive(datetime(2017, 3, 2, 10, 0, 0, tzinfo=timezone.utc), 6),
- MockArchive(datetime(2017, 3, 3, 10, 0, 0, tzinfo=timezone.utc), 7),
- MockArchive(datetime(2017, 3, 4, 10, 0, 0, tzinfo=timezone.utc), 8),
- # minutes apart
- MockArchive(datetime(2017, 10, 1, 9, 45, 0, tzinfo=timezone.utc), 9),
- MockArchive(datetime(2017, 10, 1, 9, 55, 0, tzinfo=timezone.utc), 10),
- # seconds apart
- MockArchive(datetime(2017, 10, 1, 10, 0, 1, tzinfo=timezone.utc), 11),
- MockArchive(datetime(2017, 10, 1, 10, 0, 3, tzinfo=timezone.utc), 12),
- MockArchive(datetime(2017, 10, 1, 10, 0, 5, tzinfo=timezone.utc), 13),
- ]
- kept_because = {}
- keep = prune_split(archives, rule, num_to_keep, kept_because)
-
- assert set(keep) == subset(archives, expected_ids)
- for item in keep:
- assert kept_because[item.id][0] == rule
+ return repr(self.ts)
+
+
+class PruneSplitTestCase(BaseTestCase):
+
+ def test(self):
+
+ def local_to_UTC(month, day):
+ """Convert noon on the month and day in 2013 to UTC."""
+ seconds = mktime(strptime('2013-%02d-%02d 12:00' % (month, day), '%Y-%m-%d %H:%M'))
+ return datetime.fromtimestamp(seconds, tz=timezone.utc)
+
+ def subset(lst, indices):
+ return {lst[i] for i in indices}
+
+ def dotest(test_archives, n, skip, indices):
+ for ta in test_archives, reversed(test_archives):
+ self.assert_equal(set(prune_split(ta, '%Y-%m', n, skip)),
+ subset(test_archives, indices))
+
+ test_pairs = [(1, 1), (2, 1), (2, 28), (3, 1), (3, 2), (3, 31), (5, 1)]
+ test_dates = [local_to_UTC(month, day) for month, day in test_pairs]
+ test_archives = [MockArchive(date) for date in test_dates]
+
+ dotest(test_archives, 3, [], [6, 5, 2])
+ dotest(test_archives, -1, [], [6, 5, 2, 0])
+ dotest(test_archives, 3, [test_archives[6]], [5, 2, 0])
+ dotest(test_archives, 3, [test_archives[5]], [6, 2, 0])
+ dotest(test_archives, 3, [test_archives[4]], [6, 5, 2])
+ dotest(test_archives, 0, [], [])
class IntervalTestCase(BaseTestCase):
@@ -425,19 +410,14 @@ def subset(lst, indices):
def dotest(test_archives, within, indices):
for ta in test_archives, reversed(test_archives):
- kept_because = {}
- keep = prune_within(ta, interval(within), kept_because)
- self.assert_equal(set(keep),
+ self.assert_equal(set(prune_within(ta, interval(within))),
subset(test_archives, indices))
- assert all("within" == kept_because[a.id][0] for a in keep)
# 1 minute, 1.5 hours, 2.5 hours, 3.5 hours, 25 hours, 49 hours
test_offsets = [60, 90*60, 150*60, 210*60, 25*60*60, 49*60*60]
now = datetime.now(timezone.utc)
test_dates = [now - timedelta(seconds=s) for s in test_offsets]
- test_archives = [
- MockArchive(date, i) for i, date in enumerate(test_dates)
- ]
+ test_archives = [MockArchive(date) for date in test_dates]
dotest(test_archives, '1H', [0])
dotest(test_archives, '2H', [0, 1])
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 2,
"test_score": 3
},
"num_modified_files": 3
} | 1.1 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest pytest-cov pytest-xdist pytest-mock pytest-asyncio",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc libssl-dev libacl1-dev liblz4-dev libzstd-dev pkg-config build-essential"
],
"python": "3.9",
"reqs_path": [
"requirements.d/development.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | -e git+https://github.com/borgbackup/borg.git@4a58310433f21857fc124eed4bafde2956bac46a#egg=borgbackup
cachetools==5.5.2
chardet==5.2.0
colorama==0.4.6
coverage==7.8.0
Cython==3.0.12
distlib==0.3.9
exceptiongroup==1.2.2
execnet==2.1.1
filelock==3.18.0
iniconfig==2.1.0
msgpack-python==0.5.6
packaging==24.2
platformdirs==4.3.7
pluggy==1.5.0
py-cpuinfo==9.0.0
pyproject-api==1.9.0
pytest==8.3.5
pytest-asyncio==0.26.0
pytest-benchmark==5.1.0
pytest-cov==6.0.0
pytest-mock==3.14.0
pytest-xdist==3.6.1
pyzmq==26.3.0
setuptools-scm==8.2.0
tomli==2.2.1
tox==4.25.0
typing_extensions==4.13.0
virtualenv==20.29.3
| name: borg
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- cachetools==5.5.2
- chardet==5.2.0
- colorama==0.4.6
- coverage==7.8.0
- cython==3.0.12
- distlib==0.3.9
- exceptiongroup==1.2.2
- execnet==2.1.1
- filelock==3.18.0
- iniconfig==2.1.0
- msgpack-python==0.5.6
- packaging==24.2
- platformdirs==4.3.7
- pluggy==1.5.0
- py-cpuinfo==9.0.0
- pyproject-api==1.9.0
- pytest==8.3.5
- pytest-asyncio==0.26.0
- pytest-benchmark==5.1.0
- pytest-cov==6.0.0
- pytest-mock==3.14.0
- pytest-xdist==3.6.1
- pyzmq==26.3.0
- setuptools-scm==8.2.0
- tomli==2.2.1
- tox==4.25.0
- typing-extensions==4.13.0
- virtualenv==20.29.3
prefix: /opt/conda/envs/borg
| [
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_prune_repository",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_prune_repository_glob",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_prune_repository_prefix",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_prune_repository_save_space",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_prune_repository",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_prune_repository_glob",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_prune_repository_prefix",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_prune_repository_save_space",
"src/borg/testsuite/helpers.py::PruneSplitTestCase::test",
"src/borg/testsuite/helpers.py::PruneWithinTestCase::test_prune_within"
]
| [
"src/borg/testsuite/archiver.py::test_return_codes[python]",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_common_options",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_auto_compressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_auto_uncompressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_lz4_compressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_lzma_compressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_none_compressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_none_uncompressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_zlib_compressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_corrupted_repository",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_json",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_no_cache_sync",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_stdin",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_debug_dump_archive",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_debug_dump_manifest",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_debug_info",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_debug_refcount_obj",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_delete_multiple",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_detect_attic_repo",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_info_json",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_list_json",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_list_repository_format",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_list_size",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_log_json",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_rechunkify",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_recompress",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_target",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_check_usage",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_corrupted_manifest",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_manifest_rebuild_corrupted_chunk",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_missing_file_chunk",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_missing_manifest",
"src/borg/testsuite/archiver.py::ManifestAuthenticationTest::test_disable",
"src/borg/testsuite/archiver.py::ManifestAuthenticationTest::test_disable2",
"src/borg/testsuite/archiver.py::ManifestAuthenticationTest::test_not_required",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_common_options",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_auto_compressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_auto_uncompressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_lz4_compressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_lz4_uncompressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_lzma_compressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_lzma_uncompressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_none_compressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_none_uncompressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_zlib_compressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_zlib_uncompressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_json",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_no_cache_sync",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_stdin",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_debug_dump_archive",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_debug_dump_manifest",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_debug_info",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_debug_refcount_obj",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_delete_force",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_delete_multiple",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_detect_attic_repo",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_info_json",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_init_nested_repositories",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_list_json",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_list_repository_format",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_list_size",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_rechunkify",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_recompress",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_target",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_remote_repo_restrict_to_path",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_remote_repo_restrict_to_repository",
"src/borg/testsuite/archiver.py::ArchiverCorruptionTestCase::test_cache_chunks",
"src/borg/testsuite/archiver.py::ArchiverCorruptionTestCase::test_cache_files",
"src/borg/testsuite/archiver.py::ArchiverCorruptionTestCase::test_chunks_archive",
"src/borg/testsuite/archiver.py::ArchiverCorruptionTestCase::test_old_version_interfered",
"src/borg/testsuite/archiver.py::DiffArchiverTestCase::test_sort_option",
"src/borg/testsuite/helpers.py::test_is_slow_msgpack"
]
| [
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_aes_counter_uniqueness_keyfile",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_aes_counter_uniqueness_passphrase",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_atime",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_bad_filters",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_basic_functionality",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_benchmark_crud",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_break_lock",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_change_passphrase",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_check_cache",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_comment",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_lz4_uncompressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_lzma_uncompressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_zlib_uncompressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_dry_run",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_pattern",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_pattern_exclude_folder_but_recurse",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_pattern_exclude_folder_no_recurse",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_pattern_file",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_pattern_intermediate_folders_first",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_pattern_root",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_read_special_broken_symlink",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_topical",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_without_root",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_debug_dump_archive_items",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_debug_dump_repo_objs",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_debug_profile",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_debug_put_get_delete_obj",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_delete",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_delete_double_force",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_delete_force",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_delete_repo",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_exclude_caches",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_exclude_keep_tagged",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_exclude_keep_tagged_deprecation",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_exclude_normalization",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_exclude_tagged",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_export_tar",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_export_tar_gz",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_export_tar_strip_components",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_export_tar_strip_components_links",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_extract_hardlinks",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_extract_include_exclude",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_extract_include_exclude_regex",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_extract_include_exclude_regex_from_file",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_extract_list_output",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_extract_pattern_opt",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_extract_progress",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_extract_with_pattern",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_file_status",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_file_status_cs_cache_mode",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_file_status_excluded",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_file_status_ms_cache_mode",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_file_status_rc_cache_mode",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_help",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_info",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_init_interrupt",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_init_nested_repositories",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_init_requires_encryption_option",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_key_export_keyfile",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_key_export_paperkey",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_key_export_qr",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_key_export_repokey",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_key_import_errors",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_key_import_paperkey",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_list_chunk_counts",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_list_format",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_list_hash",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_list_json_args",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_list_prefix",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_overwrite",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_path_normalization",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_progress_off",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_progress_on",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_basic",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_dry_run",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_exclude_caches",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_exclude_keep_tagged",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_exclude_tagged",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_list_output",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_skips_nothing_to_do",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_subtree_hardlinks",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_target_rc",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_rename",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_repeated_files",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_repository_move",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_repository_swap_detection",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_repository_swap_detection2",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_repository_swap_detection2_no_cache",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_repository_swap_detection_no_cache",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_repository_swap_detection_repokey_blank_passphrase",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_security_dir_compat",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_sparse_file",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_strip_components",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_strip_components_links",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_symlink_extract",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_umask",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unix_socket",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unknown_feature_on_cache_sync",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unknown_feature_on_change_passphrase",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unknown_feature_on_create",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unknown_feature_on_delete",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unknown_feature_on_read",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unknown_feature_on_rename",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unknown_mandatory_feature_in_cache",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unknown_unencrypted",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unusual_filenames",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_usage",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_with_lock",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_attic013_acl_bug",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_empty_repository",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_extra_chunks",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_manifest_rebuild_duplicate_archive",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_missing_archive_item_chunk",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_missing_archive_metadata",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_verify_data",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_verify_data_unencrypted",
"src/borg/testsuite/archiver.py::ManifestAuthenticationTest::test_fresh_init_tam_required",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_aes_counter_uniqueness_keyfile",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_aes_counter_uniqueness_passphrase",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_atime",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_bad_filters",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_basic_functionality",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_benchmark_crud",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_break_lock",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_change_passphrase",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_check_cache",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_comment",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_corrupted_repository",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_dry_run",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_pattern",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_pattern_exclude_folder_but_recurse",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_pattern_exclude_folder_no_recurse",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_pattern_file",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_pattern_intermediate_folders_first",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_pattern_root",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_read_special_broken_symlink",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_topical",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_without_root",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_debug_dump_archive_items",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_debug_dump_repo_objs",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_debug_profile",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_delete",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_delete_double_force",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_delete_repo",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_exclude_caches",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_exclude_keep_tagged",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_exclude_keep_tagged_deprecation",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_exclude_normalization",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_exclude_tagged",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_export_tar",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_export_tar_gz",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_export_tar_strip_components",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_export_tar_strip_components_links",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_extract_hardlinks",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_extract_include_exclude",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_extract_include_exclude_regex",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_extract_include_exclude_regex_from_file",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_extract_list_output",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_extract_pattern_opt",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_extract_progress",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_extract_with_pattern",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_file_status",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_file_status_cs_cache_mode",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_file_status_excluded",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_file_status_ms_cache_mode",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_file_status_rc_cache_mode",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_help",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_info",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_init_interrupt",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_init_requires_encryption_option",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_key_export_keyfile",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_key_export_paperkey",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_key_export_qr",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_key_export_repokey",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_key_import_errors",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_key_import_paperkey",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_list_chunk_counts",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_list_format",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_list_hash",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_list_json_args",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_list_prefix",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_log_json",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_overwrite",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_path_normalization",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_progress_off",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_progress_on",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_basic",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_dry_run",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_exclude_caches",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_exclude_keep_tagged",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_exclude_tagged",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_list_output",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_skips_nothing_to_do",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_subtree_hardlinks",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_target_rc",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_rename",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_repeated_files",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_repository_move",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_repository_swap_detection",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_repository_swap_detection2",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_repository_swap_detection2_no_cache",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_repository_swap_detection_no_cache",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_repository_swap_detection_repokey_blank_passphrase",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_security_dir_compat",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_sparse_file",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_strip_components",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_strip_components_doesnt_leak",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_strip_components_links",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_symlink_extract",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_umask",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unix_socket",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unknown_feature_on_cache_sync",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unknown_feature_on_change_passphrase",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unknown_feature_on_create",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unknown_feature_on_delete",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unknown_feature_on_read",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unknown_feature_on_rename",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unknown_mandatory_feature_in_cache",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unknown_unencrypted",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unusual_filenames",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_usage",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_with_lock",
"src/borg/testsuite/archiver.py::DiffArchiverTestCase::test_basic_functionality",
"src/borg/testsuite/archiver.py::test_get_args",
"src/borg/testsuite/archiver.py::test_chunk_content_equal",
"src/borg/testsuite/archiver.py::TestBuildFilter::test_basic",
"src/borg/testsuite/archiver.py::TestBuildFilter::test_empty",
"src/borg/testsuite/archiver.py::TestBuildFilter::test_strip_components",
"src/borg/testsuite/archiver.py::TestCommonOptions::test_simple",
"src/borg/testsuite/archiver.py::TestCommonOptions::test_flag_position_independence[-p-progress-True-before]",
"src/borg/testsuite/archiver.py::TestCommonOptions::test_flag_position_independence[-p-progress-True-after]",
"src/borg/testsuite/archiver.py::TestCommonOptions::test_flag_position_independence[-p-progress-True-both]",
"src/borg/testsuite/archiver.py::TestCommonOptions::test_flag_position_independence[--lock-wait=3-lock_wait-3-before]",
"src/borg/testsuite/archiver.py::TestCommonOptions::test_flag_position_independence[--lock-wait=3-lock_wait-3-after]",
"src/borg/testsuite/archiver.py::TestCommonOptions::test_flag_position_independence[--lock-wait=3-lock_wait-3-both]",
"src/borg/testsuite/archiver.py::test_parse_storage_quota",
"src/borg/testsuite/archiver.py::test_help_formatting[benchmark",
"src/borg/testsuite/archiver.py::test_help_formatting[benchmark-parser1]",
"src/borg/testsuite/archiver.py::test_help_formatting[break-lock-parser2]",
"src/borg/testsuite/archiver.py::test_help_formatting[change-passphrase-parser3]",
"src/borg/testsuite/archiver.py::test_help_formatting[check-parser4]",
"src/borg/testsuite/archiver.py::test_help_formatting[create-parser5]",
"src/borg/testsuite/archiver.py::test_help_formatting[debug",
"src/borg/testsuite/archiver.py::test_help_formatting[debug-parser16]",
"src/borg/testsuite/archiver.py::test_help_formatting[delete-parser17]",
"src/borg/testsuite/archiver.py::test_help_formatting[diff-parser18]",
"src/borg/testsuite/archiver.py::test_help_formatting[export-tar-parser19]",
"src/borg/testsuite/archiver.py::test_help_formatting[extract-parser20]",
"src/borg/testsuite/archiver.py::test_help_formatting[help-parser21]",
"src/borg/testsuite/archiver.py::test_help_formatting[info-parser22]",
"src/borg/testsuite/archiver.py::test_help_formatting[init-parser23]",
"src/borg/testsuite/archiver.py::test_help_formatting[key",
"src/borg/testsuite/archiver.py::test_help_formatting[key-parser28]",
"src/borg/testsuite/archiver.py::test_help_formatting[list-parser29]",
"src/borg/testsuite/archiver.py::test_help_formatting[mount-parser30]",
"src/borg/testsuite/archiver.py::test_help_formatting[prune-parser31]",
"src/borg/testsuite/archiver.py::test_help_formatting[recreate-parser32]",
"src/borg/testsuite/archiver.py::test_help_formatting[rename-parser33]",
"src/borg/testsuite/archiver.py::test_help_formatting[serve-parser34]",
"src/borg/testsuite/archiver.py::test_help_formatting[umount-parser35]",
"src/borg/testsuite/archiver.py::test_help_formatting[upgrade-parser36]",
"src/borg/testsuite/archiver.py::test_help_formatting[with-lock-parser37]",
"src/borg/testsuite/archiver.py::test_help_formatting_helptexts[patterns-\\nFile",
"src/borg/testsuite/archiver.py::test_help_formatting_helptexts[placeholders-\\nRepository",
"src/borg/testsuite/archiver.py::test_help_formatting_helptexts[compression-\\nIt",
"src/borg/testsuite/helpers.py::BigIntTestCase::test_bigint",
"src/borg/testsuite/helpers.py::test_bin_to_hex",
"src/borg/testsuite/helpers.py::TestLocationWithoutEnv::test_ssh",
"src/borg/testsuite/helpers.py::TestLocationWithoutEnv::test_file",
"src/borg/testsuite/helpers.py::TestLocationWithoutEnv::test_scp",
"src/borg/testsuite/helpers.py::TestLocationWithoutEnv::test_smb",
"src/borg/testsuite/helpers.py::TestLocationWithoutEnv::test_folder",
"src/borg/testsuite/helpers.py::TestLocationWithoutEnv::test_long_path",
"src/borg/testsuite/helpers.py::TestLocationWithoutEnv::test_abspath",
"src/borg/testsuite/helpers.py::TestLocationWithoutEnv::test_relpath",
"src/borg/testsuite/helpers.py::TestLocationWithoutEnv::test_with_colons",
"src/borg/testsuite/helpers.py::TestLocationWithoutEnv::test_user_parsing",
"src/borg/testsuite/helpers.py::TestLocationWithoutEnv::test_underspecified",
"src/borg/testsuite/helpers.py::TestLocationWithoutEnv::test_no_slashes",
"src/borg/testsuite/helpers.py::TestLocationWithoutEnv::test_canonical_path",
"src/borg/testsuite/helpers.py::TestLocationWithoutEnv::test_format_path",
"src/borg/testsuite/helpers.py::TestLocationWithoutEnv::test_bad_syntax",
"src/borg/testsuite/helpers.py::TestLocationWithEnv::test_ssh",
"src/borg/testsuite/helpers.py::TestLocationWithEnv::test_file",
"src/borg/testsuite/helpers.py::TestLocationWithEnv::test_scp",
"src/borg/testsuite/helpers.py::TestLocationWithEnv::test_folder",
"src/borg/testsuite/helpers.py::TestLocationWithEnv::test_abspath",
"src/borg/testsuite/helpers.py::TestLocationWithEnv::test_relpath",
"src/borg/testsuite/helpers.py::TestLocationWithEnv::test_with_colons",
"src/borg/testsuite/helpers.py::TestLocationWithEnv::test_no_slashes",
"src/borg/testsuite/helpers.py::FormatTimedeltaTestCase::test",
"src/borg/testsuite/helpers.py::test_chunkerparams",
"src/borg/testsuite/helpers.py::MakePathSafeTestCase::test",
"src/borg/testsuite/helpers.py::IntervalTestCase::test_interval",
"src/borg/testsuite/helpers.py::IntervalTestCase::test_interval_number",
"src/borg/testsuite/helpers.py::IntervalTestCase::test_interval_time_unit",
"src/borg/testsuite/helpers.py::StableDictTestCase::test",
"src/borg/testsuite/helpers.py::TestParseTimestamp::test",
"src/borg/testsuite/helpers.py::test_get_config_dir",
"src/borg/testsuite/helpers.py::test_get_cache_dir",
"src/borg/testsuite/helpers.py::test_get_keys_dir",
"src/borg/testsuite/helpers.py::test_get_security_dir",
"src/borg/testsuite/helpers.py::test_file_size",
"src/borg/testsuite/helpers.py::test_file_size_precision",
"src/borg/testsuite/helpers.py::test_file_size_sign",
"src/borg/testsuite/helpers.py::test_parse_file_size[1-1]",
"src/borg/testsuite/helpers.py::test_parse_file_size[20-20]",
"src/borg/testsuite/helpers.py::test_parse_file_size[5K-5000]",
"src/borg/testsuite/helpers.py::test_parse_file_size[1.75M-1750000]",
"src/borg/testsuite/helpers.py::test_parse_file_size[1e+9-1000000000.0]",
"src/borg/testsuite/helpers.py::test_parse_file_size[-1T--1000000000000.0]",
"src/borg/testsuite/helpers.py::test_parse_file_size_invalid[]",
"src/borg/testsuite/helpers.py::test_parse_file_size_invalid[5",
"src/borg/testsuite/helpers.py::test_parse_file_size_invalid[4E]",
"src/borg/testsuite/helpers.py::test_parse_file_size_invalid[2229",
"src/borg/testsuite/helpers.py::test_parse_file_size_invalid[1B]",
"src/borg/testsuite/helpers.py::TestBuffer::test_type",
"src/borg/testsuite/helpers.py::TestBuffer::test_len",
"src/borg/testsuite/helpers.py::TestBuffer::test_resize",
"src/borg/testsuite/helpers.py::TestBuffer::test_limit",
"src/borg/testsuite/helpers.py::TestBuffer::test_get",
"src/borg/testsuite/helpers.py::test_yes_input",
"src/borg/testsuite/helpers.py::test_yes_input_defaults",
"src/borg/testsuite/helpers.py::test_yes_input_custom",
"src/borg/testsuite/helpers.py::test_yes_env",
"src/borg/testsuite/helpers.py::test_yes_env_default",
"src/borg/testsuite/helpers.py::test_yes_defaults",
"src/borg/testsuite/helpers.py::test_yes_retry",
"src/borg/testsuite/helpers.py::test_yes_no_retry",
"src/borg/testsuite/helpers.py::test_yes_output",
"src/borg/testsuite/helpers.py::test_yes_env_output",
"src/borg/testsuite/helpers.py::test_progress_percentage_sameline",
"src/borg/testsuite/helpers.py::test_progress_percentage_step",
"src/borg/testsuite/helpers.py::test_progress_percentage_quiet",
"src/borg/testsuite/helpers.py::test_progress_endless",
"src/borg/testsuite/helpers.py::test_progress_endless_step",
"src/borg/testsuite/helpers.py::test_partial_format",
"src/borg/testsuite/helpers.py::test_chunk_file_wrapper",
"src/borg/testsuite/helpers.py::test_chunkit",
"src/borg/testsuite/helpers.py::test_clean_lines",
"src/borg/testsuite/helpers.py::test_format_line",
"src/borg/testsuite/helpers.py::test_format_line_erroneous",
"src/borg/testsuite/helpers.py::test_replace_placeholders",
"src/borg/testsuite/helpers.py::test_swidth_slice",
"src/borg/testsuite/helpers.py::test_swidth_slice_mixed_characters",
"src/borg/testsuite/helpers.py::test_safe_timestamps",
"src/borg/testsuite/helpers.py::TestPopenWithErrorHandling::test_simple",
"src/borg/testsuite/helpers.py::TestPopenWithErrorHandling::test_not_found",
"src/borg/testsuite/helpers.py::TestPopenWithErrorHandling::test_bad_syntax[mismatched",
"src/borg/testsuite/helpers.py::TestPopenWithErrorHandling::test_bad_syntax[foo",
"src/borg/testsuite/helpers.py::TestPopenWithErrorHandling::test_bad_syntax[]",
"src/borg/testsuite/helpers.py::TestPopenWithErrorHandling::test_shell",
"src/borg/testsuite/helpers.py::test_dash_open"
]
| []
| BSD License | 1,821 | [
"src/borg/archive.py",
"src/borg/helpers/misc.py",
"src/borg/archiver.py"
]
| [
"src/borg/archive.py",
"src/borg/helpers/misc.py",
"src/borg/archiver.py"
]
|
cwacek__python-jsonschema-objects-95 | ba178ce7680e14e4ac367a6fab5ea3655396668f | 2017-10-29 22:24:51 | ba178ce7680e14e4ac367a6fab5ea3655396668f | diff --git a/python_jsonschema_objects/classbuilder.py b/python_jsonschema_objects/classbuilder.py
index 4ba6006..ed55b99 100644
--- a/python_jsonschema_objects/classbuilder.py
+++ b/python_jsonschema_objects/classbuilder.py
@@ -39,6 +39,7 @@ class ProtocolBase(collections.MutableMapping):
"""
__propinfo__ = {}
__required__ = set()
+ __has_default__ = set()
__object_attr_list__ = set(["_properties", "_extended_properties"])
def as_dict(self):
@@ -158,6 +159,13 @@ class ProtocolBase(collections.MutableMapping):
[None for x in
six.moves.xrange(len(self.__prop_names__))]))
+ # To support defaults, we have to actually execute the constructors
+ # but only for the ones that have defaults set.
+ for name in self.__has_default__:
+ if name not in props:
+ logger.debug(util.lazy_format("Initializing '{0}' ", name))
+ setattr(self, name, None)
+
for prop in props:
try:
logger.debug(util.lazy_format("Setting value for '{0}' to {1}", prop, props[prop]))
@@ -166,10 +174,9 @@ class ProtocolBase(collections.MutableMapping):
import sys
raise six.reraise(type(e), type(e)(str(e) + " \nwhile setting '{0}' in {1}".format(
prop, self.__class__.__name__)), sys.exc_info()[2])
+
if getattr(self, '__strict__', None):
self.validate()
- #if len(props) > 0:
- # self.validate()
def __setattr__(self, name, val):
if name in self.__object_attr_list__:
@@ -277,7 +284,10 @@ class ProtocolBase(collections.MutableMapping):
def MakeLiteral(name, typ, value, **properties):
properties.update({'type': typ})
klass = type(str(name), tuple((LiteralValue,)), {
- '__propinfo__': {'__literal__': properties}
+ '__propinfo__': {
+ '__literal__': properties,
+ '__default__': properties.get('default')
+ }
})
return klass(value)
@@ -328,6 +338,9 @@ class LiteralValue(object):
else:
self._value = value
+ if self._value is None and self.default() is not None:
+ self._value = self.default()
+
self.validate()
def as_dict(self):
@@ -336,6 +349,10 @@ class LiteralValue(object):
def for_json(self):
return self._value
+ @classmethod
+ def default(cls):
+ return cls.__propinfo__.get('__default__')
+
@classmethod
def propinfo(cls, propname):
if propname not in cls.__propinfo__:
@@ -516,7 +533,9 @@ class ClassBuilder(object):
"""
cls = type(str(nm), tuple((LiteralValue,)), {
- '__propinfo__': { '__literal__': clsdata}
+ '__propinfo__': {
+ '__literal__': clsdata,
+ '__default__': clsdata.get('default')}
})
return cls
@@ -525,6 +544,7 @@ class ClassBuilder(object):
logger.debug(util.lazy_format("Building object {0}", nm))
props = {}
+ defaults = set()
properties = {}
for p in parents:
@@ -541,6 +561,9 @@ class ClassBuilder(object):
name_translation[prop] = prop.replace('@', '')
prop = name_translation[prop]
+ if detail.get('default', None) is not None:
+ defaults.add(prop)
+
if detail.get('type', None) == 'object':
uri = "{0}/{1}_{2}".format(nm,
prop, "<anonymous>")
@@ -673,6 +696,7 @@ class ClassBuilder(object):
.format(nm, invalid_requires))
props['__required__'] = required
+ props['__has_default__'] = defaults
if required and kw.get("strict"):
props['__strict__'] = True
cls = type(str(nm.split('/')[-1]), tuple(parents), props)
@@ -765,7 +789,10 @@ def make_property(prop, info, desc=""):
elif getattr(info['type'], 'isLiteralClass', False) is True:
if not isinstance(val, info['type']):
validator = info['type'](val)
- validator.validate()
+ validator.validate()
+ if validator._value is not None:
+ # This allows setting of default Literal values
+ val = validator
elif util.safe_issubclass(info['type'], ProtocolBase):
if not isinstance(val, info['type']):
| Feature request: implement default values
Would it be possible for the auto-generated class to implement any default values as specified in the JSON schema? Right now if I have a property defined as:
```
"sample-boolean": {
"description": "A sample boolean",
"type": "boolean",
"default": false
}
```
and I instantiate an object of the generated class using obj = MyClass.from_json('{}') (or any JSON that does not include "sample-boolean") then obj.sample-boolean will be None instead of false.
Implementing the defaults would be a useful feature, I think. | cwacek/python-jsonschema-objects | diff --git a/test/test_pytest.py b/test/test_pytest.py
index 4e52b6f..70dea0e 100644
--- a/test/test_pytest.py
+++ b/test/test_pytest.py
@@ -493,3 +493,27 @@ def test_boolean_in_child_object():
ns = builder.build_classes()
ns.Test(data={"my_bool": True})
+
+
+
[email protected]('default', [
+ '{"type": "boolean", "default": false}',
+ '{"type": "string", "default": "Hello"}',
+ '{"type": "integer", "default": 500}'
+])
+def test_default_values(default):
+ default = json.loads(default)
+ schema = {
+ "$schema": "http://json-schema.org/schema#",
+ "id": "test",
+ "type": "object",
+ "properties": {
+ "sample": default
+ }
+ }
+
+ builder = pjs.ObjectBuilder(schema)
+ ns = builder.build_classes()
+
+ x = ns.Test()
+ assert x.sample == default['default']
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 1,
"test_score": 0
},
"num_modified_files": 1
} | 0.2 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"coverage",
"pytest",
"nose",
"rednose",
"pyandoc",
"pandoc",
"sphinx",
"sphinx-autobuild",
"recommonmark"
],
"pre_install": null,
"python": "3.5",
"reqs_path": [
"requirements.txt",
"development.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | alabaster==0.7.13
attrs==22.2.0
Babel==2.11.0
certifi==2021.5.30
charset-normalizer==2.0.12
colorama==0.4.5
commonmark==0.9.1
coverage==6.2
docutils==0.18.1
idna==3.10
imagesize==1.4.1
importlib-metadata==4.8.3
inflection==0.2.0
iniconfig==1.1.1
Jinja2==3.0.3
jsonschema==2.6.0
livereload==2.6.3
Markdown==2.4
MarkupSafe==2.0.1
nose==1.3.0
packaging==21.3
pandoc==2.4
pandocfilters==1.5.1
pluggy==1.0.0
plumbum==1.8.3
ply==3.11
py==1.11.0
pyandoc==0.2.0
Pygments==2.14.0
pyparsing==3.1.4
pyrsistent==0.18.0
pytest==7.0.1
-e git+https://github.com/cwacek/python-jsonschema-objects.git@ba178ce7680e14e4ac367a6fab5ea3655396668f#egg=python_jsonschema_objects
python-termstyle==0.1.10
pytz==2025.2
recommonmark==0.7.1
rednose==0.4.1
requests==2.27.1
six==1.17.0
snowballstemmer==2.2.0
Sphinx==5.3.0
sphinx-autobuild==2021.3.14
sphinxcontrib-applehelp==1.0.2
sphinxcontrib-devhelp==1.0.2
sphinxcontrib-htmlhelp==2.0.0
sphinxcontrib-jsmath==1.0.1
sphinxcontrib-qthelp==1.0.3
sphinxcontrib-serializinghtml==1.1.5
tomli==1.2.3
tornado==6.1
typing_extensions==4.1.1
urllib3==1.26.20
zipp==3.6.0
| name: python-jsonschema-objects
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- alabaster==0.7.13
- attrs==22.2.0
- babel==2.11.0
- charset-normalizer==2.0.12
- colorama==0.4.5
- commonmark==0.9.1
- coverage==6.2
- docutils==0.18.1
- idna==3.10
- imagesize==1.4.1
- importlib-metadata==4.8.3
- inflection==0.2.0
- iniconfig==1.1.1
- jinja2==3.0.3
- jsonschema==2.6.0
- livereload==2.6.3
- markdown==2.4
- markupsafe==2.0.1
- nose==1.3.0
- packaging==21.3
- pandoc==2.4
- pandocfilters==1.5.1
- pluggy==1.0.0
- plumbum==1.8.3
- ply==3.11
- py==1.11.0
- pyandoc==0.2.0
- pygments==2.14.0
- pyparsing==3.1.4
- pyrsistent==0.18.0
- pytest==7.0.1
- python-termstyle==0.1.10
- pytz==2025.2
- recommonmark==0.7.1
- rednose==0.4.1
- requests==2.27.1
- six==1.17.0
- snowballstemmer==2.2.0
- sphinx==5.3.0
- sphinx-autobuild==2021.3.14
- sphinxcontrib-applehelp==1.0.2
- sphinxcontrib-devhelp==1.0.2
- sphinxcontrib-htmlhelp==2.0.0
- sphinxcontrib-jsmath==1.0.1
- sphinxcontrib-qthelp==1.0.3
- sphinxcontrib-serializinghtml==1.1.5
- tomli==1.2.3
- tornado==6.1
- typing-extensions==4.1.1
- urllib3==1.26.20
- zipp==3.6.0
prefix: /opt/conda/envs/python-jsonschema-objects
| [
"test/test_pytest.py::test_default_values[{\"type\":"
]
| []
| [
"test/test_pytest.py::test_schema_validation",
"test/test_pytest.py::test_regression_9",
"test/test_pytest.py::test_build_classes_is_idempotent",
"test/test_pytest.py::test_underscore_properties",
"test/test_pytest.py::test_array_regressions",
"test/test_pytest.py::test_arrays_can_have_reffed_items_of_mixed_type",
"test/test_pytest.py::test_regression_39",
"test/test_pytest.py::test_loads_markdown_schema_extraction",
"test/test_pytest.py::test_object_builder_loads_memory_references",
"test/test_pytest.py::test_object_builder_reads_all_definitions",
"test/test_pytest.py::test_oneOf_validates_against_any_valid[{\"MyData\":",
"test/test_pytest.py::test_oneOf_fails_against_non_matching",
"test/test_pytest.py::test_oneOfBare_validates_against_any_valid[{\"MyAddress\":",
"test/test_pytest.py::test_oneOfBare_validates_against_any_valid[{\"firstName\":",
"test/test_pytest.py::test_oneOfBare_fails_against_non_matching",
"test/test_pytest.py::test_additional_props_allowed_by_default",
"test/test_pytest.py::test_additional_props_permitted_explicitly",
"test/test_pytest.py::test_still_raises_when_accessing_undefined_attrs",
"test/test_pytest.py::test_permits_deletion_of_additional_properties",
"test/test_pytest.py::test_additional_props_disallowed_explicitly",
"test/test_pytest.py::test_objects_can_be_empty",
"test/test_pytest.py::test_object_equality_should_compare_data",
"test/test_pytest.py::test_object_allows_attributes_in_oncstructor",
"test/test_pytest.py::test_object_validates_on_json_decode",
"test/test_pytest.py::test_object_validates_enumerations",
"test/test_pytest.py::test_validation_of_mixed_type_enums",
"test/test_pytest.py::test_objects_allow_non_required_attrs_to_be_missing",
"test/test_pytest.py::test_objects_require_required_attrs_on_validate",
"test/test_pytest.py::test_attribute_access_via_dict",
"test/test_pytest.py::test_attribute_set_via_dict",
"test/test_pytest.py::test_numeric_attribute_validation",
"test/test_pytest.py::test_objects_validate_prior_to_serializing",
"test/test_pytest.py::test_serializing_removes_null_objects",
"test/test_pytest.py::test_lists_get_serialized_correctly",
"test/test_pytest.py::test_dictionary_transformation[pdict0]",
"test/test_pytest.py::test_dictionary_transformation[pdict1]",
"test/test_pytest.py::test_strict_mode",
"test/test_pytest.py::test_boolean_in_child_object"
]
| []
| MIT License | 1,823 | [
"python_jsonschema_objects/classbuilder.py"
]
| [
"python_jsonschema_objects/classbuilder.py"
]
|
|
Azure__msrestazure-for-python-55 | 005f5a4320385930ba82d4c0e13ce90506884b27 | 2017-10-30 22:28:54 | 0f372b60f9add4c245c323e24acca038936e472f | diff --git a/msrestazure/azure_exceptions.py b/msrestazure/azure_exceptions.py
index bb85333..5b4792c 100644
--- a/msrestazure/azure_exceptions.py
+++ b/msrestazure/azure_exceptions.py
@@ -30,6 +30,15 @@ from msrest.exceptions import ClientException
from msrest.serialization import Deserializer
from msrest.exceptions import DeserializationError
+class CloudErrorRoot(object):
+ """Just match the "error" key at the root of a OdataV4 JSON.
+ """
+ _validation = {}
+ _attribute_map = {
+ 'error': {'key': 'error', 'type': 'CloudErrorData'},
+ }
+ def __init__(self, error):
+ self.error = error
class CloudErrorData(object):
"""Cloud Error Data object, deserialized from error data returned
@@ -47,7 +56,7 @@ class CloudErrorData(object):
def __init__(self, *args, **kwargs):
self.error = kwargs.get('error')
- self._message = kwargs.get('message')
+ self.message = kwargs.get('message')
self.request_id = None
self.error_time = None
self.target = kwargs.get('target')
@@ -122,7 +131,10 @@ class CloudError(ClientException):
"""
def __init__(self, response, error=None, *args, **kwargs):
- self.deserializer = Deserializer({'CloudErrorData': CloudErrorData})
+ self.deserializer = Deserializer({
+ 'CloudErrorRoot': CloudErrorRoot,
+ 'CloudErrorData': CloudErrorData
+ })
self.error = None
self.message = None
self.response = response
@@ -149,13 +161,7 @@ class CloudError(ClientException):
def _build_error_data(self, response):
try:
- data = response.json()
- except ValueError:
- data = response
- else:
- data = data.get('error', data)
- try:
- self.error = self.deserializer(CloudErrorData(), data)
+ self.error = self.deserializer('CloudErrorRoot', response).error
except DeserializationError:
self.error = None
else:
@@ -178,7 +184,10 @@ class CloudError(ClientException):
except ValueError:
message = "none"
else:
- message = data.get("message", self._get_state(data))
+ try:
+ message = data.get("message", self._get_state(data))
+ except AttributeError: # data is not a dict, but is a requests.Response parsable as JSON
+ message = str(response.text)
try:
response.raise_for_status()
except RequestException as err:
| CloudError parsing should be resilient if input type is string
In so (messy) scenario, we don't receive a dict (from a JSON), but a string. We should be robust to that and print the while string as the error message:
```python
msrest.http_logger : b'"{\\"error\\":{\\"code\\":\\"ResourceGroupNotFound\\",\\"message\\":\\"Resource group \'res_grp\' could not be found.\\"}}"'
'str' object has no attribute 'get'
Traceback (most recent call last):
File "C:\Users\lmazuel\Git\AzureCli\lib\site-packages\azure\cli\main.py", line 36, in main
cmd_result = APPLICATION.execute(args)
File "C:\Users\lmazuel\Git\AzureCli\lib\site-packages\azure\cli\core\application.py", line 212, in execute
result = expanded_arg.func(params)
File "C:\Users\lmazuel\Git\AzureCli\lib\site-packages\azure\cli\core\commands\__init__.py", line 377, in __call__
return self.handler(*args, **kwargs)
File "C:\Users\lmazuel\Git\AzureCli\lib\site-packages\azure\cli\core\commands\__init__.py", line 620, in _execute_command
reraise(*sys.exc_info())
File "C:\Users\lmazuel\Git\AzureCli\lib\site-packages\six.py", line 693, in reraise
raise value
File "C:\Users\lmazuel\Git\AzureCli\lib\site-packages\azure\cli\core\commands\__init__.py", line 614, in _execute_command
return list(result)
File "C:\Users\lmazuel\Git\AzureCli\lib\site-packages\msrest\paging.py", line 109, in __next__
self.advance_page()
File "C:\Users\lmazuel\Git\AzureCli\lib\site-packages\msrest\paging.py", line 95, in advance_page
self._response = self._get_next(self.next_link)
File "C:\Users\lmazuel\Git\AzureCli\lib\site-packages\azure\mgmt\compute\v2017_03_30\operations\disks_operations.py", line 441, in internal_paging
exp = CloudError(response)
File "C:\Users\lmazuel\Git\AzureCli\lib\site-packages\msrestazure\azure_exceptions.py", line 136, in __init__
self._build_error_data(response)
File "C:\Users\lmazuel\Git\AzureCli\lib\site-packages\msrestazure\azure_exceptions.py", line 156, in _build_error_data
data = data.get('error', data)
AttributeError: 'str' object has no attribute 'get'
``` | Azure/msrestazure-for-python | diff --git a/tests/test_exceptions.py b/tests/test_exceptions.py
index 2506a9c..45a4770 100644
--- a/tests/test_exceptions.py
+++ b/tests/test_exceptions.py
@@ -125,20 +125,6 @@ class TestCloudException(unittest.TestCase):
response.headers = {"content-type": "application/json; charset=utf8"}
response.reason = 'BadRequest'
- message = {
- 'code': '500',
- 'message': {'value': 'Bad Request\nRequest:34875\nTime:1999-12-31T23:59:59-23:59'},
- 'values': {'invalid_attribute':'data'}
- }
-
- response.text = json.dumps(message)
- response.json = lambda: json.loads(response.text)
-
- error = CloudError(response)
- self.assertEqual(error.message, 'Bad Request')
- self.assertEqual(error.status_code, 400)
- self.assertIsInstance(error.error, CloudErrorData)
-
message = { 'error': {
'code': '500',
'message': {'value': 'Bad Request\nRequest:34875\nTime:1999-12-31T23:59:59-23:59'},
@@ -146,6 +132,7 @@ class TestCloudException(unittest.TestCase):
}}
response.text = json.dumps(message)
+ response.json = lambda: json.loads(response.text)
error = CloudError(response)
self.assertEqual(error.message, 'Bad Request')
self.assertEqual(error.status_code, 400)
@@ -175,9 +162,9 @@ class TestCloudException(unittest.TestCase):
response.text = '{\r\n "odata.metadata":"https://account.region.batch.azure.com/$metadata#Microsoft.Azure.Batch.Protocol.Entities.Container.errors/@Element","code":"InvalidHeaderValue","message":{\r\n "lang":"en-US","value":"The value for one of the HTTP headers is not in the correct format.\\nRequestId:5f4c1f05-603a-4495-8e80-01f776310bbd\\nTime:2016-01-04T22:12:33.9245931Z"\r\n },"values":[\r\n {\r\n "key":"HeaderName","value":"Content-Type"\r\n },{\r\n "key":"HeaderValue","value":"application/json; odata=minimalmetadata; charset=utf-8"\r\n }\r\n ]\r\n}'
error = CloudError(response)
- self.assertIsInstance(error.error, CloudErrorData)
+ self.assertIn("The value for one of the HTTP headers is not in the correct format", error.message)
- response.text = '{"code":"Conflict","message":"The maximum number of Free ServerFarms allowed in a Subscription is 10.","target":null,"details":[{"message":"The maximum number of Free ServerFarms allowed in a Subscription is 10."},{"code":"Conflict"},{"errorentity":{"code":"Conflict","message":"The maximum number of Free ServerFarms allowed in a Subscription is 10.","extendedCode":"59301","messageTemplate":"The maximum number of {0} ServerFarms allowed in a Subscription is {1}.","parameters":["Free","10"],"innerErrors":null}}],"innererror":null}'
+ response.text = '{"error":{"code":"Conflict","message":"The maximum number of Free ServerFarms allowed in a Subscription is 10.","target":null,"details":[{"message":"The maximum number of Free ServerFarms allowed in a Subscription is 10."},{"code":"Conflict"},{"errorentity":{"code":"Conflict","message":"The maximum number of Free ServerFarms allowed in a Subscription is 10.","extendedCode":"59301","messageTemplate":"The maximum number of {0} ServerFarms allowed in a Subscription is {1}.","parameters":["Free","10"],"innerErrors":null}}],"innererror":null}}'
error = CloudError(response)
self.assertIsInstance(error.error, CloudErrorData)
self.assertEqual(error.error.error, "Conflict")
@@ -199,6 +186,11 @@ class TestCloudException(unittest.TestCase):
self.assertIsInstance(error.error, CloudErrorData)
self.assertEqual(error.error.error, "BadArgument")
+ # See https://github.com/Azure/msrestazure-for-python/issues/54
+ response.text = '"{\\"error\\": {\\"code\\": \\"ResourceGroupNotFound\\", \\"message\\": \\"Resource group \'res_grp\' could not be found.\\"}}"'
+ error = CloudError(response)
+ self.assertIn(response.text, error.message)
+
if __name__ == '__main__':
unittest.main()
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 0,
"test_score": 2
},
"num_modified_files": 1
} | 0.4 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"httpretty",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | adal==0.4.7
backports.tarfile==1.2.0
certifi==2025.1.31
cffi==1.17.1
charset-normalizer==3.4.1
cryptography==44.0.2
exceptiongroup==1.2.2
httpretty==1.1.4
idna==3.10
importlib_metadata==8.6.1
iniconfig==2.1.0
isodate==0.7.2
jaraco.classes==3.4.0
jaraco.context==6.0.1
jaraco.functools==4.1.0
jeepney==0.9.0
keyring==25.6.0
more-itertools==10.6.0
msrest==0.4.29
-e git+https://github.com/Azure/msrestazure-for-python.git@005f5a4320385930ba82d4c0e13ce90506884b27#egg=msrestazure
oauthlib==3.2.2
packaging==24.2
pluggy==1.5.0
pycparser==2.22
PyJWT==2.10.1
pytest==8.3.5
python-dateutil==2.9.0.post0
requests==2.32.3
requests-oauthlib==2.0.0
SecretStorage==3.3.3
six==1.17.0
tomli==2.2.1
urllib3==2.3.0
zipp==3.21.0
| name: msrestazure-for-python
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- adal==0.4.7
- backports-tarfile==1.2.0
- certifi==2025.1.31
- cffi==1.17.1
- charset-normalizer==3.4.1
- cryptography==44.0.2
- exceptiongroup==1.2.2
- httpretty==1.1.4
- idna==3.10
- importlib-metadata==8.6.1
- iniconfig==2.1.0
- isodate==0.7.2
- jaraco-classes==3.4.0
- jaraco-context==6.0.1
- jaraco-functools==4.1.0
- jeepney==0.9.0
- keyring==25.6.0
- more-itertools==10.6.0
- msrest==0.4.29
- oauthlib==3.2.2
- packaging==24.2
- pluggy==1.5.0
- pycparser==2.22
- pyjwt==2.10.1
- pytest==8.3.5
- python-dateutil==2.9.0.post0
- requests==2.32.3
- requests-oauthlib==2.0.0
- secretstorage==3.3.3
- six==1.17.0
- tomli==2.2.1
- urllib3==2.3.0
- zipp==3.21.0
prefix: /opt/conda/envs/msrestazure-for-python
| [
"tests/test_exceptions.py::TestCloudException::test_cloud_error"
]
| []
| [
"tests/test_exceptions.py::TestCloudException::test_cloud_exception"
]
| []
| MIT License | 1,825 | [
"msrestazure/azure_exceptions.py"
]
| [
"msrestazure/azure_exceptions.py"
]
|
|
quantumlib__OpenFermion-95 | e51fe9c381fe29c04a83d63c6d708d4af2bb7a63 | 2017-10-31 01:07:26 | e51fe9c381fe29c04a83d63c6d708d4af2bb7a63 | diff --git a/src/openfermion/ops/_quadratic_hamiltonian.py b/src/openfermion/ops/_quadratic_hamiltonian.py
index 15cc467..fdd42be 100644
--- a/src/openfermion/ops/_quadratic_hamiltonian.py
+++ b/src/openfermion/ops/_quadratic_hamiltonian.py
@@ -17,7 +17,7 @@ from __future__ import absolute_import
import numpy
from openfermion.config import EQ_TOLERANCE
-from openfermion.ops import PolynomialTensor
+from openfermion.ops import FermionOperator, PolynomialTensor
class QuadraticHamiltonianError(Exception):
@@ -67,15 +67,17 @@ class QuadraticHamiltonian(PolynomialTensor):
hermitian_part -
chemical_potential * numpy.eye(n_qubits))
- # Initialize antisymmetric part
if antisymmetric_part is None:
- antisymmetric_part = numpy.zeros((n_qubits, n_qubits), complex)
+ super(QuadraticHamiltonian, self).__init__(
+ {(): constant,
+ (1, 0): combined_hermitian_part})
+ else:
+ super(QuadraticHamiltonian, self).__init__(
+ {(): constant,
+ (1, 0): combined_hermitian_part,
+ (1, 1): .5 * antisymmetric_part,
+ (0, 0): -.5 * antisymmetric_part.conj()})
- super(QuadraticHamiltonian, self).__init__(
- {(): constant,
- (1, 0): combined_hermitian_part,
- (1, 1): .5 * antisymmetric_part,
- (0, 0): -.5 * antisymmetric_part.conj()})
self.chemical_potential = chemical_potential
def combined_hermitian_part(self):
@@ -92,9 +94,100 @@ class QuadraticHamiltonian(PolynomialTensor):
def antisymmetric_part(self):
"""Return the antisymmetric part."""
- return 2. * self.n_body_tensors[1, 1].copy()
+ if (1, 1) in self.n_body_tensors:
+ return 2. * self.n_body_tensors[1, 1].copy()
+ else:
+ return numpy.zeros((self.n_qubits, self.n_qubits), complex)
def conserves_particle_number(self):
"""Return whether this Hamiltonian conserves particle number."""
discrepancy = numpy.max(numpy.abs(self.antisymmetric_part()))
return discrepancy < EQ_TOLERANCE
+
+ def majorana_form(self):
+ """Return the Majorana represention of the Hamiltonian.
+
+ Any quadratic Hamiltonian can be written in the form
+
+ constant + i / 2 \sum_{j, k} A_{jk} s_j s_k.
+
+ where the s_i are normalized Majorana fermion operators:
+
+ s_j = i / sqrt(2) (a^\dagger_j - a_j)
+ s_{j + n_qubits} = 1 / sqrt(2) (a^\dagger_j + a_j)
+
+ and A is a (2 * n_qubits) x (2 * n_qubits) real antisymmetric matrix.
+ This function returns the matrix A and the constant.
+ """
+ hermitian_part = self.combined_hermitian_part()
+ antisymmetric_part = self.antisymmetric_part()
+
+ # Compute the Majorana matrix using block matrix manipulations
+ majorana_matrix = numpy.zeros((2 * self.n_qubits, 2 * self.n_qubits))
+ # Set upper left block
+ majorana_matrix[:self.n_qubits, :self.n_qubits] = numpy.real(-.5j * (
+ hermitian_part - hermitian_part.conj() +
+ antisymmetric_part - antisymmetric_part.conj()))
+ # Set upper right block
+ majorana_matrix[:self.n_qubits, self.n_qubits:] = numpy.real(.5 * (
+ hermitian_part + hermitian_part.conj() -
+ antisymmetric_part - antisymmetric_part.conj()))
+ # Set lower left block
+ majorana_matrix[self.n_qubits:, :self.n_qubits] = numpy.real(-.5 * (
+ hermitian_part + hermitian_part.conj() +
+ antisymmetric_part + antisymmetric_part.conj()))
+ # Set lower right block
+ majorana_matrix[self.n_qubits:, self.n_qubits:] = numpy.real(-.5j * (
+ hermitian_part - hermitian_part.conj() -
+ antisymmetric_part + antisymmetric_part.conj()))
+
+ # Compute the constant
+ majorana_constant = (.5 * numpy.real(numpy.trace(hermitian_part)) +
+ self.n_body_tensors[()])
+
+ return majorana_matrix, majorana_constant
+
+
+def majorana_operator(term=None, coefficient=1.):
+ """Initialize a Majorana operator.
+
+ Args:
+ term(tuple): The first element of the tuple indicates the mode
+ on which the Majorana operator acts, starting from zero.
+ The second element of the tuple is an integer, either 1 or 0,
+ indicating which type of Majorana operator it is:
+ type 1: 1 / sqrt(2) (a^\dagger_j + a_j)
+ type 0: i / sqrt(2) (a^\dagger_j - a_j)
+ where the a^\dagger_j and a_j are the usual fermionic ladder
+ operators.
+ Default will result in the zero operator.
+ coefficient(complex or float, optional): The coefficient of the term.
+ Default value is 1.0.
+
+ Returns:
+ FermionOperator
+ """
+ if not isinstance(coefficient, (int, float, complex)):
+ raise ValueError('Coefficient must be scalar.')
+
+ if term is None:
+ # Return zero operator
+ return FermionOperator()
+ elif isinstance(term, tuple):
+ mode, operator_type = term
+ if operator_type == 1:
+ majorana_op = FermionOperator(
+ ((mode, 1),), coefficient / numpy.sqrt(2.))
+ majorana_op += FermionOperator(
+ ((mode, 0),), coefficient / numpy.sqrt(2.))
+ elif operator_type == 0:
+ majorana_op = FermionOperator(
+ ((mode, 1),), 1.j * coefficient / numpy.sqrt(2.))
+ majorana_op -= FermionOperator(
+ ((mode, 0),), 1.j * coefficient / numpy.sqrt(2.))
+ else:
+ raise ValueError('Operator specified incorrectly.')
+ return majorana_op
+ # Invalid input.
+ else:
+ raise ValueError('Operator specified incorrectly.')
diff --git a/src/openfermion/utils/__init__.py b/src/openfermion/utils/__init__.py
index 9d5bb20..d75656f 100644
--- a/src/openfermion/utils/__init__.py
+++ b/src/openfermion/utils/__init__.py
@@ -20,8 +20,9 @@ from ._operator_utils import (commutator, count_qubits,
get_file_path, inverse_fourier_transform,
is_identity, load_operator, save_operator)
-from ._slater_determinants import (givens_decomposition,
- fermionic_gaussian_decomposition)
+from ._slater_determinants import (fermionic_gaussian_decomposition,
+ givens_decomposition,
+ ground_state_preparation_circuit)
from ._sparse_tools import (expectation,
expectation_computational_basis_state,
diff --git a/src/openfermion/utils/_slater_determinants.py b/src/openfermion/utils/_slater_determinants.py
index 5ebecd6..b3ae971 100644
--- a/src/openfermion/utils/_slater_determinants.py
+++ b/src/openfermion/utils/_slater_determinants.py
@@ -18,6 +18,63 @@ import numpy
from scipy.linalg import schur
from openfermion.config import EQ_TOLERANCE
+from openfermion.ops import QuadraticHamiltonian
+
+
+def ground_state_preparation_circuit(quadratic_hamiltonian):
+ """Obtain a description of a circuit which prepares the ground state
+ of a quadratic Hamiltonian.
+
+ Args:
+ quadratic_hamiltonian(QuadraticHamiltonian):
+ The Hamiltonian whose ground state is desired.
+
+ Returns:
+ circuit_description(list[tuple]):
+ A list of operations describing the circuit. Each operation
+ is a tuple of objects describing elementary operations that
+ can be performed in parallel. Each elementary operation
+ is either the string 'pht', indicating a particle-hole
+ transformation on the last fermionic mode, or a tuple of
+ the form (i, j, theta, phi), indicating a Givens rotation
+ of qubits i and j by angles theta and phi.
+ """
+ if not isinstance(quadratic_hamiltonian, QuadraticHamiltonian):
+ raise ValueError('Input must be an instance of QuadraticHamiltonian.')
+
+ if quadratic_hamiltonian.conserves_particle_number():
+ # The Hamiltonian conserves particle number, so we don't need
+ # to use the most general procedure.
+ hermitian_matrix = quadratic_hamiltonian.combined_hermitian_part()
+ # Get the unitary rows which represent the ground state
+ # Slater determinant
+ energies, diagonalizing_unitary = numpy.linalg.eigh(
+ hermitian_matrix)
+ num_negative_energies = numpy.count_nonzero(
+ energies < -EQ_TOLERANCE)
+ slater_determinant_matrix = diagonalizing_unitary.T[
+ :num_negative_energies]
+ # Get the circuit description
+ left_unitary, decomposition, diagonal = givens_decomposition(
+ slater_determinant_matrix)
+ circuit_description = decomposition
+ else:
+ # The Hamiltonian does not conserve particle number, so we
+ # need to use the most general procedure.
+ majorana_matrix, majorana_constant = (
+ quadratic_hamiltonian.majorana_form())
+ # Get the unitary rows which represent the ground state
+ # Slater determinant
+ diagonalizing_unitary = diagonalizing_fermionic_unitary(
+ majorana_matrix)
+ slater_determinant_matrix = diagonalizing_unitary[
+ quadratic_hamiltonian.n_qubits:]
+ # Get the circuit description
+ left_unitary, decomposition, diagonal = (
+ fermionic_gaussian_decomposition(
+ slater_determinant_matrix))
+ circuit_description = decomposition
+ return circuit_description
def fermionic_gaussian_decomposition(unitary_rows):
@@ -49,7 +106,7 @@ def fermionic_gaussian_decomposition(unitary_rows):
something like [('pht', ), (G_1, ), ('pht', G_2), ... ].
The objects within a tuple are either the string 'pht', which indicates
a particle-hole transformation on the last fermionic mode, or a tuple
- of the form (i, j, theta, phi), which indicates a Givens roation
+ of the form (i, j, theta, phi), which indicates a Givens rotation
of rows i and j by angles theta and phi.
Args:
@@ -148,109 +205,6 @@ def fermionic_gaussian_decomposition(unitary_rows):
return left_unitary, decomposition, diagonal
-def diagonalizing_fermionic_unitary(antisymmetric_matrix):
- """Compute the unitary that diagonalizes a quadratic Hamiltonian.
-
- The input matrix represents a quadratic Hamiltonian in the Majorana basis.
- The output matrix is a unitary that represents a transformation (mixing)
- of the fermionic ladder operators. We use the convention that the
- creation operators are listed before the annihilation operators.
- The returned unitary has additional structure which ensures
- that the transformed ladder operators also satisfy the fermionic
- anticommutation relations.
-
- Args:
- antisymmetric_matrix(ndarray): A (2 * n_qubits) x (2 * n_qubits)
- antisymmetric matrix representing a quadratic Hamiltonian in the
- Majorana basis.
- Returns:
- diagonalizing_unitary(ndarray): A (2 * n_qubits) x (2 * n_qubits)
- unitary matrix representing a transformation of the fermionic
- ladder operators.
- """
- m, n = antisymmetric_matrix.shape
- n_qubits = n // 2
-
- # Get the orthogonal transformation that puts antisymmetric_matrix
- # into canonical form
- canonical, orthogonal = antisymmetric_canonical_form(antisymmetric_matrix)
-
- # Create the matrix that converts between fermionic ladder and
- # Majorana bases
- normalized_identity = numpy.eye(n_qubits, dtype=complex) / numpy.sqrt(2.)
- majorana_basis_change = numpy.eye(
- 2 * n_qubits, dtype=complex) / numpy.sqrt(2.)
- majorana_basis_change[n_qubits:, n_qubits:] *= -1.j
- majorana_basis_change[:n_qubits, n_qubits:] = normalized_identity
- majorana_basis_change[n_qubits:, :n_qubits] = 1.j * normalized_identity
-
- # Compute the unitary and return
- diagonalizing_unitary = majorana_basis_change.T.conj().dot(
- orthogonal.dot(majorana_basis_change))
-
- return diagonalizing_unitary
-
-
-def antisymmetric_canonical_form(antisymmetric_matrix):
- """Compute the canonical form of an antisymmetric matrix.
-
- The input is a real, antisymmetric n x n matrix A, where n is even.
- Its canonical form is::
-
- A = R^T C R
-
- where R is a real, orthogonal matrix and C has the form::
-
- [ 0 D ]
- [ -D 0 ]
-
- where D is a diagonal matrix with nonnegative entries.
-
- Args:
- antisymmetric_matrix(ndarray): An antisymmetric matrix with even
- dimension.
-
- Returns:
- canonical(ndarray): The canonical form C of antisymmetric_matrix
- orthogonal(ndarray): The orthogonal transformation R.
- """
- m, n = antisymmetric_matrix.shape
-
- if m != n or n % 2 != 0:
- raise ValueError('The input matrix must be square with even '
- 'dimension.')
-
- # Check that input matrix is antisymmetric
- matrix_plus_transpose = antisymmetric_matrix + antisymmetric_matrix.T
- maxval = numpy.max(numpy.abs(matrix_plus_transpose))
- if maxval > EQ_TOLERANCE:
- raise ValueError('The input matrix must be antisymmetric.')
-
- # Compute Schur decomposition
- canonical, orthogonal = schur(antisymmetric_matrix, output='real')
-
- # The returned form is block diagonal; we need to permute rows and columns
- # to put it into the form we want
- num_blocks = n // 2
- for i in range(1, num_blocks, 2):
- swap_rows(canonical, i, num_blocks + i - 1)
- swap_columns(canonical, i, num_blocks + i - 1)
- swap_columns(orthogonal, i, num_blocks + i - 1)
- if num_blocks % 2 != 0:
- swap_rows(canonical, num_blocks - 1, num_blocks + i)
- swap_columns(canonical, num_blocks - 1, num_blocks + i)
- swap_columns(orthogonal, num_blocks - 1, num_blocks + i)
-
- # Now we permute so that the upper right block is non-negative
- for i in range(num_blocks):
- if canonical[i, num_blocks + i] < -EQ_TOLERANCE:
- swap_rows(canonical, i, num_blocks + i)
- swap_columns(canonical, i, num_blocks + i)
- swap_columns(orthogonal, i, num_blocks + i)
-
- return canonical, orthogonal.T
-
-
def givens_decomposition(unitary_rows):
"""Decompose a matrix into a sequence of Givens rotations.
@@ -379,6 +333,109 @@ def givens_decomposition(unitary_rows):
return left_unitary, givens_rotations, diagonal
+def diagonalizing_fermionic_unitary(antisymmetric_matrix):
+ """Compute the unitary that diagonalizes a quadratic Hamiltonian.
+
+ The input matrix represents a quadratic Hamiltonian in the Majorana basis.
+ The output matrix is a unitary that represents a transformation (mixing)
+ of the fermionic ladder operators. We use the convention that the
+ creation operators are listed before the annihilation operators.
+ The returned unitary has additional structure which ensures
+ that the transformed ladder operators also satisfy the fermionic
+ anticommutation relations.
+
+ Args:
+ antisymmetric_matrix(ndarray): A (2 * n_qubits) x (2 * n_qubits)
+ antisymmetric matrix representing a quadratic Hamiltonian in the
+ Majorana basis.
+ Returns:
+ diagonalizing_unitary(ndarray): A (2 * n_qubits) x (2 * n_qubits)
+ unitary matrix representing a transformation of the fermionic
+ ladder operators.
+ """
+ m, n = antisymmetric_matrix.shape
+ n_qubits = n // 2
+
+ # Get the orthogonal transformation that puts antisymmetric_matrix
+ # into canonical form
+ canonical, orthogonal = antisymmetric_canonical_form(antisymmetric_matrix)
+
+ # Create the matrix that converts between fermionic ladder and
+ # Majorana bases
+ normalized_identity = numpy.eye(n_qubits, dtype=complex) / numpy.sqrt(2.)
+ majorana_basis_change = numpy.eye(
+ 2 * n_qubits, dtype=complex) / numpy.sqrt(2.)
+ majorana_basis_change[n_qubits:, n_qubits:] *= -1.j
+ majorana_basis_change[:n_qubits, n_qubits:] = normalized_identity
+ majorana_basis_change[n_qubits:, :n_qubits] = 1.j * normalized_identity
+
+ # Compute the unitary and return
+ diagonalizing_unitary = majorana_basis_change.T.conj().dot(
+ orthogonal.dot(majorana_basis_change))
+
+ return diagonalizing_unitary
+
+
+def antisymmetric_canonical_form(antisymmetric_matrix):
+ """Compute the canonical form of an antisymmetric matrix.
+
+ The input is a real, antisymmetric n x n matrix A, where n is even.
+ Its canonical form is::
+
+ A = R^T C R
+
+ where R is a real, orthogonal matrix and C has the form::
+
+ [ 0 D ]
+ [ -D 0 ]
+
+ where D is a diagonal matrix with nonnegative entries.
+
+ Args:
+ antisymmetric_matrix(ndarray): An antisymmetric matrix with even
+ dimension.
+
+ Returns:
+ canonical(ndarray): The canonical form C of antisymmetric_matrix
+ orthogonal(ndarray): The orthogonal transformation R.
+ """
+ m, n = antisymmetric_matrix.shape
+
+ if m != n or n % 2 != 0:
+ raise ValueError('The input matrix must be square with even '
+ 'dimension.')
+
+ # Check that input matrix is antisymmetric
+ matrix_plus_transpose = antisymmetric_matrix + antisymmetric_matrix.T
+ maxval = numpy.max(numpy.abs(matrix_plus_transpose))
+ if maxval > EQ_TOLERANCE:
+ raise ValueError('The input matrix must be antisymmetric.')
+
+ # Compute Schur decomposition
+ canonical, orthogonal = schur(antisymmetric_matrix, output='real')
+
+ # The returned form is block diagonal; we need to permute rows and columns
+ # to put it into the form we want
+ num_blocks = n // 2
+ for i in range(1, num_blocks, 2):
+ swap_rows(canonical, i, num_blocks + i - 1)
+ swap_columns(canonical, i, num_blocks + i - 1)
+ swap_columns(orthogonal, i, num_blocks + i - 1)
+ if num_blocks % 2 != 0:
+ swap_rows(canonical, num_blocks - 1, num_blocks + i)
+ swap_columns(canonical, num_blocks - 1, num_blocks + i)
+ swap_columns(orthogonal, num_blocks - 1, num_blocks + i)
+
+ # Now we permute so that the upper right block is non-negative
+ for i in range(num_blocks):
+ if canonical[i, num_blocks + i] < -EQ_TOLERANCE:
+ swap_rows(canonical, i, num_blocks + i)
+ swap_columns(canonical, i, num_blocks + i)
+ swap_columns(orthogonal, i, num_blocks + i)
+
+ return canonical, orthogonal.T
+
+
def givens_matrix_elements(a, b):
"""Compute the matrix elements of the Givens rotation that zeroes out one
of two row entries.
| Circular dependency when importing from utils in ops
I'm working on the file `ops/_quadratic_hamiltonian.py`. In there, I add the line
```from openfermion.utils._slater_determinants import swap_columns, swap_rows```
This causes the tests in the `hamiltonians` folder to fail; i.e., when I run `pytest hamiltonians/`, I get
```
________________ ERROR collecting src/openfermion/hamiltonians/_chemical_series_test.py ________________
ImportError while importing test module '/home/kjs/Projects/OpenFermion/src/openfermion/hamiltonians/_chemical_series_test.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
hamiltonians/__init__.py:13: in <module>
from ._chemical_series import (make_atomic_ring,
hamiltonians/_chemical_series.py:18: in <module>
from openfermion.hamiltonians._molecular_data import (MolecularData,
hamiltonians/_molecular_data.py:21: in <module>
from openfermion.ops import InteractionOperator, InteractionRDM
ops/__init__.py:23: in <module>
from ._quadratic_hamiltonian import QuadraticHamiltonian
ops/_quadratic_hamiltonian.py:22: in <module>
from openfermion.utils._slater_determinants import swap_columns, swap_rows
utils/__init__.py:39: in <module>
from ._trotter_error import error_bound, error_operator
utils/_trotter_error.py:20: in <module>
from openfermion.hamiltonians import MolecularData
E ImportError: cannot import name 'MolecularData'
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Interrupted: 1 errors during collection !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
```
It seems that there is a circular dependency
MolecularData -> ops -> utils -> MolecularData
and any file in the `ops` folder which imports anything from `utils` will cause this error. What is the best way to deal with it? | quantumlib/OpenFermion | diff --git a/src/openfermion/ops/_quadratic_hamiltonian_test.py b/src/openfermion/ops/_quadratic_hamiltonian_test.py
index e852031..321f925 100644
--- a/src/openfermion/ops/_quadratic_hamiltonian_test.py
+++ b/src/openfermion/ops/_quadratic_hamiltonian_test.py
@@ -16,20 +16,29 @@ from __future__ import absolute_import
import numpy
import unittest
-from openfermion.ops import QuadraticHamiltonian
+from openfermion.config import EQ_TOLERANCE
+from openfermion.ops import (FermionOperator,
+ QuadraticHamiltonian,
+ normal_ordered)
+from openfermion.ops._quadratic_hamiltonian import majorana_operator
+from openfermion.transforms import get_fermion_operator
class QuadraticHamiltoniansTest(unittest.TestCase):
def setUp(self):
self.n_qubits = 5
- self.constant = 1.
+ self.constant = 1.7
self.chemical_potential = 2.
# Obtain random Hermitian and antisymmetric matrices
- rand_mat = numpy.random.randn(self.n_qubits, self.n_qubits)
+ rand_mat_A = numpy.random.randn(self.n_qubits, self.n_qubits)
+ rand_mat_B = numpy.random.randn(self.n_qubits, self.n_qubits)
+ rand_mat = rand_mat_A + 1.j * rand_mat_B
self.hermitian_mat = rand_mat + rand_mat.T.conj()
- rand_mat = numpy.random.randn(self.n_qubits, self.n_qubits)
+ rand_mat_A = numpy.random.randn(self.n_qubits, self.n_qubits)
+ rand_mat_B = numpy.random.randn(self.n_qubits, self.n_qubits)
+ rand_mat = rand_mat_A + 1.j * rand_mat_B
self.antisymmetric_mat = rand_mat - rand_mat.T
self.combined_hermitian = (
@@ -82,3 +91,43 @@ class QuadraticHamiltoniansTest(unittest.TestCase):
"""Test checking whether Hamiltonian conserves particle number."""
self.assertTrue(self.quad_ham_pc.conserves_particle_number())
self.assertFalse(self.quad_ham_npc.conserves_particle_number())
+
+ def test_majorana_form(self):
+ """Test getting the Majorana form."""
+ majorana_matrix, majorana_constant = self.quad_ham_npc.majorana_form()
+ # Convert the Majorana form to a FermionOperator
+ majorana_op = FermionOperator((), majorana_constant)
+ for i in range(2 * self.n_qubits):
+ if i < self.n_qubits:
+ left_op = majorana_operator((i, 1))
+ else:
+ left_op = majorana_operator((i - self.n_qubits, 0))
+ for j in range(2 * self.n_qubits):
+ if j < self.n_qubits:
+ right_op = majorana_operator((j, 1), majorana_matrix[i, j])
+ else:
+ right_op = majorana_operator((j - self.n_qubits, 0),
+ majorana_matrix[i, j])
+ majorana_op += .5j * left_op * right_op
+ # Get FermionOperator for original Hamiltonian
+ fermion_operator = normal_ordered(
+ get_fermion_operator(self.quad_ham_npc))
+ self.assertTrue(
+ normal_ordered(majorana_op).isclose(fermion_operator))
+
+
+class MajoranaOperatorTest(unittest.TestCase):
+
+ def test_none_term(self):
+ majorana_op = majorana_operator()
+ self.assertTrue(majorana_operator().isclose(FermionOperator()))
+
+ def test_bad_coefficient(self):
+ with self.assertRaises(ValueError):
+ majorana_op = majorana_operator((1, 1), 'a')
+
+ def test_bad_term(self):
+ with self.assertRaises(ValueError):
+ majorana_op = majorana_operator((2, 2))
+ with self.assertRaises(ValueError):
+ majorana_op = majorana_operator('a')
diff --git a/src/openfermion/utils/_slater_determinants_test.py b/src/openfermion/utils/_slater_determinants_test.py
index d0c838c..da94ad1 100644
--- a/src/openfermion/utils/_slater_determinants_test.py
+++ b/src/openfermion/utils/_slater_determinants_test.py
@@ -18,8 +18,10 @@ import unittest
from scipy.linalg import qr
from openfermion.config import EQ_TOLERANCE
+from openfermion.ops import QuadraticHamiltonian
from openfermion.utils import (fermionic_gaussian_decomposition,
- givens_decomposition)
+ givens_decomposition,
+ ground_state_preparation_circuit)
from openfermion.utils._slater_determinants import (
antisymmetric_canonical_form,
diagonalizing_fermionic_unitary,
@@ -28,6 +30,46 @@ from openfermion.utils._slater_determinants import (
swap_rows)
+class GroundStatePreparationCircuitTest(unittest.TestCase):
+
+ def setUp(self):
+ self.n_qubits = 5
+ self.constant = 1.7
+ self.chemical_potential = 2.
+
+ # Obtain random Hermitian and antisymmetric matrices
+ rand_mat_A = numpy.random.randn(self.n_qubits, self.n_qubits)
+ rand_mat_B = numpy.random.randn(self.n_qubits, self.n_qubits)
+ rand_mat = rand_mat_A + 1.j * rand_mat_B
+ self.hermitian_mat = rand_mat + rand_mat.T.conj()
+ rand_mat_A = numpy.random.randn(self.n_qubits, self.n_qubits)
+ rand_mat_B = numpy.random.randn(self.n_qubits, self.n_qubits)
+ rand_mat = rand_mat_A + 1.j * rand_mat_B
+ self.antisymmetric_mat = rand_mat - rand_mat.T
+
+ self.combined_hermitian = (
+ self.hermitian_mat -
+ self.chemical_potential * numpy.eye(self.n_qubits))
+
+ # Initialize a particle-number-conserving Hamiltonian
+ self.quad_ham_pc = QuadraticHamiltonian(
+ self.constant, self.hermitian_mat)
+
+ # Initialize a non-particle-number-conserving Hamiltonian
+ self.quad_ham_npc = QuadraticHamiltonian(
+ self.constant, self.hermitian_mat, self.antisymmetric_mat,
+ self.chemical_potential)
+
+ def test_no_error(self):
+ """Test that the procedure runs without error."""
+ # Test a particle-number-conserving Hamiltonian
+ circuit_description = (
+ ground_state_preparation_circuit(self.quad_ham_pc))
+ # Test a non-particle-number-conserving Hamiltonian
+ circuit_description = (
+ ground_state_preparation_circuit(self.quad_ham_npc))
+
+
class GivensDecompositionTest(unittest.TestCase):
def test_bad_dimensions(self):
| {
"commit_name": "merge_commit",
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 2,
"test_score": 3
},
"num_modified_files": 3
} | 0.1 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-cov",
"coveralls",
"sphinx",
"sphinx_rtd_theme"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc g++"
],
"python": "3.9",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | alabaster==0.7.16
anyio==4.9.0
argon2-cffi==23.1.0
argon2-cffi-bindings==21.2.0
arrow==1.3.0
asttokens==3.0.0
async-lru==2.0.5
attrs==25.3.0
babel==2.17.0
beautifulsoup4==4.13.3
bleach==6.2.0
certifi==2025.1.31
cffi==1.17.1
charset-normalizer==3.4.1
comm==0.2.2
contourpy==1.3.0
coverage==7.8.0
coveralls==4.0.1
cvxopt==1.3.2
cycler==0.12.1
debugpy==1.8.13
decorator==5.2.1
defusedxml==0.7.1
docopt==0.6.2
docutils==0.21.2
exceptiongroup==1.2.2
executing==2.2.0
fastjsonschema==2.21.1
fonttools==4.56.0
fqdn==1.5.1
future==1.0.0
h11==0.14.0
h5py==3.13.0
httpcore==1.0.7
httpx==0.28.1
idna==3.10
imagesize==1.4.1
importlib_metadata==8.6.1
importlib_resources==6.5.2
iniconfig==2.1.0
ipykernel==6.29.5
ipython==8.18.1
ipywidgets==8.1.5
isoduration==20.11.0
jedi==0.19.2
Jinja2==3.1.6
json5==0.10.0
jsonpointer==3.0.0
jsonschema==4.23.0
jsonschema-specifications==2024.10.1
jupyter==1.1.1
jupyter-console==6.6.3
jupyter-events==0.12.0
jupyter-lsp==2.2.5
jupyter_client==8.6.3
jupyter_core==5.7.2
jupyter_server==2.15.0
jupyter_server_terminals==0.5.3
jupyterlab==4.3.6
jupyterlab_pygments==0.3.0
jupyterlab_server==2.27.3
jupyterlab_widgets==3.0.13
kiwisolver==1.4.7
MarkupSafe==3.0.2
matplotlib==3.9.4
matplotlib-inline==0.1.7
mistune==3.1.3
nbclient==0.10.2
nbconvert==7.16.6
nbformat==5.10.4
nest-asyncio==1.6.0
networkx==3.2.1
notebook==7.3.3
notebook_shim==0.2.4
numpy==2.0.2
-e git+https://github.com/quantumlib/OpenFermion.git@e51fe9c381fe29c04a83d63c6d708d4af2bb7a63#egg=openfermion
overrides==7.7.0
packaging==24.2
pandocfilters==1.5.1
parso==0.8.4
pexpect==4.9.0
pillow==11.1.0
platformdirs==4.3.7
pluggy==1.5.0
prometheus_client==0.21.1
prompt_toolkit==3.0.50
psutil==7.0.0
ptyprocess==0.7.0
pure_eval==0.2.3
pycparser==2.22
Pygments==2.19.1
pyparsing==3.2.3
pytest==8.3.5
pytest-cov==6.0.0
python-dateutil==2.9.0.post0
python-json-logger==3.3.0
PyYAML==6.0.2
pyzmq==26.3.0
referencing==0.36.2
requests==2.32.3
rfc3339-validator==0.1.4
rfc3986-validator==0.1.1
rpds-py==0.24.0
scipy==1.13.1
Send2Trash==1.8.3
six==1.17.0
sniffio==1.3.1
snowballstemmer==2.2.0
soupsieve==2.6
Sphinx==7.4.7
sphinx-rtd-theme==3.0.2
sphinxcontrib-applehelp==2.0.0
sphinxcontrib-devhelp==2.0.0
sphinxcontrib-htmlhelp==2.1.0
sphinxcontrib-jquery==4.1
sphinxcontrib-jsmath==1.0.1
sphinxcontrib-qthelp==2.0.0
sphinxcontrib-serializinghtml==2.0.0
stack-data==0.6.3
terminado==0.18.1
tinycss2==1.4.0
tomli==2.2.1
tornado==6.4.2
traitlets==5.14.3
types-python-dateutil==2.9.0.20241206
typing_extensions==4.13.0
uri-template==1.3.0
urllib3==2.3.0
wcwidth==0.2.13
webcolors==24.11.1
webencodings==0.5.1
websocket-client==1.8.0
widgetsnbextension==4.0.13
zipp==3.21.0
| name: OpenFermion
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- alabaster==0.7.16
- anyio==4.9.0
- argon2-cffi==23.1.0
- argon2-cffi-bindings==21.2.0
- arrow==1.3.0
- asttokens==3.0.0
- async-lru==2.0.5
- attrs==25.3.0
- babel==2.17.0
- beautifulsoup4==4.13.3
- bleach==6.2.0
- certifi==2025.1.31
- cffi==1.17.1
- charset-normalizer==3.4.1
- comm==0.2.2
- contourpy==1.3.0
- coverage==7.8.0
- coveralls==4.0.1
- cvxopt==1.3.2
- cycler==0.12.1
- debugpy==1.8.13
- decorator==5.2.1
- defusedxml==0.7.1
- docopt==0.6.2
- docutils==0.21.2
- exceptiongroup==1.2.2
- executing==2.2.0
- fastjsonschema==2.21.1
- fonttools==4.56.0
- fqdn==1.5.1
- future==1.0.0
- h11==0.14.0
- h5py==3.13.0
- httpcore==1.0.7
- httpx==0.28.1
- idna==3.10
- imagesize==1.4.1
- importlib-metadata==8.6.1
- importlib-resources==6.5.2
- iniconfig==2.1.0
- ipykernel==6.29.5
- ipython==8.18.1
- ipywidgets==8.1.5
- isoduration==20.11.0
- jedi==0.19.2
- jinja2==3.1.6
- json5==0.10.0
- jsonpointer==3.0.0
- jsonschema==4.23.0
- jsonschema-specifications==2024.10.1
- jupyter==1.1.1
- jupyter-client==8.6.3
- jupyter-console==6.6.3
- jupyter-core==5.7.2
- jupyter-events==0.12.0
- jupyter-lsp==2.2.5
- jupyter-server==2.15.0
- jupyter-server-terminals==0.5.3
- jupyterlab==4.3.6
- jupyterlab-pygments==0.3.0
- jupyterlab-server==2.27.3
- jupyterlab-widgets==3.0.13
- kiwisolver==1.4.7
- markupsafe==3.0.2
- matplotlib==3.9.4
- matplotlib-inline==0.1.7
- mistune==3.1.3
- nbclient==0.10.2
- nbconvert==7.16.6
- nbformat==5.10.4
- nest-asyncio==1.6.0
- networkx==3.2.1
- notebook==7.3.3
- notebook-shim==0.2.4
- numpy==2.0.2
- overrides==7.7.0
- packaging==24.2
- pandocfilters==1.5.1
- parso==0.8.4
- pexpect==4.9.0
- pillow==11.1.0
- platformdirs==4.3.7
- pluggy==1.5.0
- prometheus-client==0.21.1
- prompt-toolkit==3.0.50
- psutil==7.0.0
- ptyprocess==0.7.0
- pure-eval==0.2.3
- pycparser==2.22
- pygments==2.19.1
- pyparsing==3.2.3
- pytest==8.3.5
- pytest-cov==6.0.0
- python-dateutil==2.9.0.post0
- python-json-logger==3.3.0
- pyyaml==6.0.2
- pyzmq==26.3.0
- referencing==0.36.2
- requests==2.32.3
- rfc3339-validator==0.1.4
- rfc3986-validator==0.1.1
- rpds-py==0.24.0
- scipy==1.13.1
- send2trash==1.8.3
- six==1.17.0
- sniffio==1.3.1
- snowballstemmer==2.2.0
- soupsieve==2.6
- sphinx==7.4.7
- sphinx-rtd-theme==3.0.2
- sphinxcontrib-applehelp==2.0.0
- sphinxcontrib-devhelp==2.0.0
- sphinxcontrib-htmlhelp==2.1.0
- sphinxcontrib-jquery==4.1
- sphinxcontrib-jsmath==1.0.1
- sphinxcontrib-qthelp==2.0.0
- sphinxcontrib-serializinghtml==2.0.0
- stack-data==0.6.3
- terminado==0.18.1
- tinycss2==1.4.0
- tomli==2.2.1
- tornado==6.4.2
- traitlets==5.14.3
- types-python-dateutil==2.9.0.20241206
- typing-extensions==4.13.0
- uri-template==1.3.0
- urllib3==2.3.0
- wcwidth==0.2.13
- webcolors==24.11.1
- webencodings==0.5.1
- websocket-client==1.8.0
- widgetsnbextension==4.0.13
- zipp==3.21.0
prefix: /opt/conda/envs/OpenFermion
| [
"src/openfermion/ops/_quadratic_hamiltonian_test.py::QuadraticHamiltoniansTest::test_antisymmetric_part",
"src/openfermion/ops/_quadratic_hamiltonian_test.py::QuadraticHamiltoniansTest::test_combined_hermitian_part",
"src/openfermion/ops/_quadratic_hamiltonian_test.py::QuadraticHamiltoniansTest::test_conserves_particle_number",
"src/openfermion/ops/_quadratic_hamiltonian_test.py::QuadraticHamiltoniansTest::test_hermitian_part",
"src/openfermion/ops/_quadratic_hamiltonian_test.py::QuadraticHamiltoniansTest::test_majorana_form",
"src/openfermion/ops/_quadratic_hamiltonian_test.py::MajoranaOperatorTest::test_bad_coefficient",
"src/openfermion/ops/_quadratic_hamiltonian_test.py::MajoranaOperatorTest::test_bad_term",
"src/openfermion/ops/_quadratic_hamiltonian_test.py::MajoranaOperatorTest::test_none_term",
"src/openfermion/utils/_slater_determinants_test.py::GroundStatePreparationCircuitTest::test_no_error",
"src/openfermion/utils/_slater_determinants_test.py::GivensDecompositionTest::test_3_by_3",
"src/openfermion/utils/_slater_determinants_test.py::GivensDecompositionTest::test_3_by_4",
"src/openfermion/utils/_slater_determinants_test.py::GivensDecompositionTest::test_3_by_5",
"src/openfermion/utils/_slater_determinants_test.py::GivensDecompositionTest::test_3_by_6",
"src/openfermion/utils/_slater_determinants_test.py::GivensDecompositionTest::test_3_by_7",
"src/openfermion/utils/_slater_determinants_test.py::GivensDecompositionTest::test_3_by_8",
"src/openfermion/utils/_slater_determinants_test.py::GivensDecompositionTest::test_3_by_9",
"src/openfermion/utils/_slater_determinants_test.py::GivensDecompositionTest::test_4_by_5",
"src/openfermion/utils/_slater_determinants_test.py::GivensDecompositionTest::test_4_by_9",
"src/openfermion/utils/_slater_determinants_test.py::GivensDecompositionTest::test_antidiagonal",
"src/openfermion/utils/_slater_determinants_test.py::GivensDecompositionTest::test_bad_dimensions",
"src/openfermion/utils/_slater_determinants_test.py::GivensDecompositionTest::test_identity",
"src/openfermion/utils/_slater_determinants_test.py::FermionicGaussianDecompositionTest::test_bad_constraints",
"src/openfermion/utils/_slater_determinants_test.py::FermionicGaussianDecompositionTest::test_bad_dimensions",
"src/openfermion/utils/_slater_determinants_test.py::FermionicGaussianDecompositionTest::test_n_equals_3",
"src/openfermion/utils/_slater_determinants_test.py::FermionicGaussianDecompositionTest::test_n_equals_4",
"src/openfermion/utils/_slater_determinants_test.py::FermionicGaussianDecompositionTest::test_n_equals_5",
"src/openfermion/utils/_slater_determinants_test.py::FermionicGaussianDecompositionTest::test_n_equals_6",
"src/openfermion/utils/_slater_determinants_test.py::FermionicGaussianDecompositionTest::test_n_equals_7",
"src/openfermion/utils/_slater_determinants_test.py::FermionicGaussianDecompositionTest::test_n_equals_8",
"src/openfermion/utils/_slater_determinants_test.py::FermionicGaussianDecompositionTest::test_n_equals_9",
"src/openfermion/utils/_slater_determinants_test.py::DiagonalizingFermionicUnitaryTest::test_bad_dimensions",
"src/openfermion/utils/_slater_determinants_test.py::DiagonalizingFermionicUnitaryTest::test_n_equals_3",
"src/openfermion/utils/_slater_determinants_test.py::DiagonalizingFermionicUnitaryTest::test_not_antisymmetric",
"src/openfermion/utils/_slater_determinants_test.py::AntisymmetricCanonicalFormTest::test_canonical",
"src/openfermion/utils/_slater_determinants_test.py::AntisymmetricCanonicalFormTest::test_equality"
]
| []
| []
| []
| Apache License 2.0 | 1,826 | [
"src/openfermion/ops/_quadratic_hamiltonian.py",
"src/openfermion/utils/__init__.py",
"src/openfermion/utils/_slater_determinants.py"
]
| [
"src/openfermion/ops/_quadratic_hamiltonian.py",
"src/openfermion/utils/__init__.py",
"src/openfermion/utils/_slater_determinants.py"
]
|
|
alecthomas__voluptuous-307 | 48d1ea8f0f07478e50da38935d7e452f80d8501b | 2017-10-31 05:06:40 | b99459ffb6c9932abae3c6882c634a108a34f6ab | diff --git a/voluptuous/schema_builder.py b/voluptuous/schema_builder.py
index 429ab32..2c430a5 100644
--- a/voluptuous/schema_builder.py
+++ b/voluptuous/schema_builder.py
@@ -875,10 +875,11 @@ class VirtualPathComponent(str):
class Marker(object):
"""Mark nodes for special treatment."""
- def __init__(self, schema_, msg=None):
+ def __init__(self, schema_, msg=None, description=None):
self.schema = schema_
self._schema = Schema(schema_)
self.msg = msg
+ self.description = description
def __call__(self, v):
try:
@@ -930,8 +931,9 @@ class Optional(Marker):
{'key2': 'value'}
"""
- def __init__(self, schema, msg=None, default=UNDEFINED):
- super(Optional, self).__init__(schema, msg=msg)
+ def __init__(self, schema, msg=None, default=UNDEFINED, description=None):
+ super(Optional, self).__init__(schema, msg=msg,
+ description=description)
self.default = default_factory(default)
@@ -971,8 +973,9 @@ class Exclusive(Optional):
... 'social': {'social_network': 'barfoo', 'token': 'tEMp'}})
"""
- def __init__(self, schema, group_of_exclusion, msg=None):
- super(Exclusive, self).__init__(schema, msg=msg)
+ def __init__(self, schema, group_of_exclusion, msg=None, description=None):
+ super(Exclusive, self).__init__(schema, msg=msg,
+ description=description)
self.group_of_exclusion = group_of_exclusion
@@ -1038,8 +1041,9 @@ class Required(Marker):
{'key': []}
"""
- def __init__(self, schema, msg=None, default=UNDEFINED):
- super(Required, self).__init__(schema, msg=msg)
+ def __init__(self, schema, msg=None, default=UNDEFINED, description=None):
+ super(Required, self).__init__(schema, msg=msg,
+ description=description)
self.default = default_factory(default)
| RFC: Add description attribute to Required/Optional
So I'm not sure if this should be even a thing in voluptuous, but since more users of this lib might be interested I thought I'll bring it up.
We use voluptuous in [Home Assistant](https://github.com/home-assistant/home-assistant) and it's awesome. For some of the things that we have voluptuous validate, we would like to generate a schema of what is allowed.
To this end I started an experiment a while ago called [voluptuous form](https://github.com/balloob/voluptuous_form). I'm looking into reviving this effort but there is one missing piece of the puzzle: description of the fields.
Would description be something that would make sense to add to Voluptuous?
Potential syntax:
```python
import voluptuous as vol
SCHEMA = vol.Schema({
vol.Required('name', description='The name of the user.'): str,
vol.Required('age', description='The age of the user.'): int,
})
``` | alecthomas/voluptuous | diff --git a/voluptuous/tests/tests.py b/voluptuous/tests/tests.py
index 8b82f98..48cbfd0 100644
--- a/voluptuous/tests/tests.py
+++ b/voluptuous/tests/tests.py
@@ -6,7 +6,7 @@ import sys
from nose.tools import assert_equal, assert_raises, assert_true
from voluptuous import (
- Schema, Required, Optional, Extra, Invalid, In, Remove, Literal,
+ Schema, Required, Exclusive, Optional, Extra, Invalid, In, Remove, Literal,
Url, MultipleInvalid, LiteralInvalid, TypeInvalid, NotIn, Match, Email,
Replace, Range, Coerce, All, Any, Length, FqdnUrl, ALLOW_EXTRA, PREVENT_EXTRA,
validate, ExactSequence, Equal, Unordered, Number, Maybe, Datetime, Date,
@@ -915,3 +915,17 @@ def test_PathExists():
schema = Schema(PathExists())
assert_raises(MultipleInvalid, schema, 3)
schema(os.path.abspath(__file__))
+
+
+def test_description():
+ marker = Marker(Schema(str), description='Hello')
+ assert marker.description == 'Hello'
+
+ optional = Optional('key', description='Hello')
+ assert optional.description == 'Hello'
+
+ exclusive = Exclusive('alpha', 'angles', description='Hello')
+ assert exclusive.description == 'Hello'
+
+ required = Required('key', description='Hello')
+ assert required.description == 'Hello'
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_hyperlinks",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 1,
"test_score": 0
},
"num_modified_files": 1
} | 0.10 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"nose",
"pytest"
],
"pre_install": null,
"python": "3.6",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work
certifi==2021.5.30
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work
nose==1.3.7
packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work
pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pytest==6.2.4
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
-e git+https://github.com/alecthomas/voluptuous.git@48d1ea8f0f07478e50da38935d7e452f80d8501b#egg=voluptuous
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
| name: voluptuous
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=21.4.0=pyhd3eb1b0_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- importlib-metadata=4.8.1=py36h06a4308_0
- importlib_metadata=4.8.1=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- more-itertools=8.12.0=pyhd3eb1b0_0
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=21.3=pyhd3eb1b0_0
- pip=21.2.2=py36h06a4308_0
- pluggy=0.13.1=py36h06a4308_0
- py=1.11.0=pyhd3eb1b0_0
- pyparsing=3.0.4=pyhd3eb1b0_0
- pytest=6.2.4=py36h06a4308_2
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- toml=0.10.2=pyhd3eb1b0_0
- typing_extensions=4.1.1=pyh06a4308_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zipp=3.6.0=pyhd3eb1b0_0
- zlib=1.2.13=h5eee18b_1
- pip:
- nose==1.3.7
prefix: /opt/conda/envs/voluptuous
| [
"voluptuous/tests/tests.py::test_description"
]
| []
| [
"voluptuous/tests/tests.py::test_exact_sequence",
"voluptuous/tests/tests.py::test_required",
"voluptuous/tests/tests.py::test_extra_with_required",
"voluptuous/tests/tests.py::test_iterate_candidates",
"voluptuous/tests/tests.py::test_in",
"voluptuous/tests/tests.py::test_not_in",
"voluptuous/tests/tests.py::test_contains",
"voluptuous/tests/tests.py::test_remove",
"voluptuous/tests/tests.py::test_extra_empty_errors",
"voluptuous/tests/tests.py::test_literal",
"voluptuous/tests/tests.py::test_class",
"voluptuous/tests/tests.py::test_email_validation",
"voluptuous/tests/tests.py::test_email_validation_with_none",
"voluptuous/tests/tests.py::test_email_validation_with_empty_string",
"voluptuous/tests/tests.py::test_email_validation_without_host",
"voluptuous/tests/tests.py::test_fqdn_url_validation",
"voluptuous/tests/tests.py::test_fqdn_url_without_domain_name",
"voluptuous/tests/tests.py::test_fqdnurl_validation_with_none",
"voluptuous/tests/tests.py::test_fqdnurl_validation_with_empty_string",
"voluptuous/tests/tests.py::test_fqdnurl_validation_without_host",
"voluptuous/tests/tests.py::test_url_validation",
"voluptuous/tests/tests.py::test_url_validation_with_none",
"voluptuous/tests/tests.py::test_url_validation_with_empty_string",
"voluptuous/tests/tests.py::test_url_validation_without_host",
"voluptuous/tests/tests.py::test_copy_dict_undefined",
"voluptuous/tests/tests.py::test_sorting",
"voluptuous/tests/tests.py::test_schema_extend",
"voluptuous/tests/tests.py::test_schema_extend_overrides",
"voluptuous/tests/tests.py::test_schema_extend_key_swap",
"voluptuous/tests/tests.py::test_subschema_extension",
"voluptuous/tests/tests.py::test_repr",
"voluptuous/tests/tests.py::test_list_validation_messages",
"voluptuous/tests/tests.py::test_nested_multiple_validation_errors",
"voluptuous/tests/tests.py::test_humanize_error",
"voluptuous/tests/tests.py::test_fix_157",
"voluptuous/tests/tests.py::test_range_exlcudes_nan",
"voluptuous/tests/tests.py::test_equal",
"voluptuous/tests/tests.py::test_unordered",
"voluptuous/tests/tests.py::test_maybe",
"voluptuous/tests/tests.py::test_empty_list_as_exact",
"voluptuous/tests/tests.py::test_empty_dict_as_exact",
"voluptuous/tests/tests.py::test_schema_decorator_match_with_args",
"voluptuous/tests/tests.py::test_schema_decorator_unmatch_with_args",
"voluptuous/tests/tests.py::test_schema_decorator_match_with_kwargs",
"voluptuous/tests/tests.py::test_schema_decorator_unmatch_with_kwargs",
"voluptuous/tests/tests.py::test_schema_decorator_match_return_with_args",
"voluptuous/tests/tests.py::test_schema_decorator_unmatch_return_with_args",
"voluptuous/tests/tests.py::test_schema_decorator_match_return_with_kwargs",
"voluptuous/tests/tests.py::test_schema_decorator_unmatch_return_with_kwargs",
"voluptuous/tests/tests.py::test_schema_decorator_return_only_match",
"voluptuous/tests/tests.py::test_schema_decorator_return_only_unmatch",
"voluptuous/tests/tests.py::test_schema_decorator_partial_match_called_with_args",
"voluptuous/tests/tests.py::test_schema_decorator_partial_unmatch_called_with_args",
"voluptuous/tests/tests.py::test_schema_decorator_partial_match_called_with_kwargs",
"voluptuous/tests/tests.py::test_schema_decorator_partial_unmatch_called_with_kwargs",
"voluptuous/tests/tests.py::test_unicode_as_key",
"voluptuous/tests/tests.py::test_number_validation_with_string",
"voluptuous/tests/tests.py::test_number_validation_with_invalid_precision_invalid_scale",
"voluptuous/tests/tests.py::test_number_validation_with_valid_precision_scale_yield_decimal_true",
"voluptuous/tests/tests.py::test_number_when_precision_scale_none_yield_decimal_true",
"voluptuous/tests/tests.py::test_number_when_precision_none_n_valid_scale_case1_yield_decimal_true",
"voluptuous/tests/tests.py::test_number_when_precision_none_n_valid_scale_case2_yield_decimal_true",
"voluptuous/tests/tests.py::test_number_when_precision_none_n_invalid_scale_yield_decimal_true",
"voluptuous/tests/tests.py::test_number_when_valid_precision_n_scale_none_yield_decimal_true",
"voluptuous/tests/tests.py::test_number_when_invalid_precision_n_scale_none_yield_decimal_true",
"voluptuous/tests/tests.py::test_number_validation_with_valid_precision_scale_yield_decimal_false",
"voluptuous/tests/tests.py::test_named_tuples_validate_as_tuples",
"voluptuous/tests/tests.py::test_datetime",
"voluptuous/tests/tests.py::test_date",
"voluptuous/tests/tests.py::test_ordered_dict",
"voluptuous/tests/tests.py::test_marker_hashable",
"voluptuous/tests/tests.py::test_validation_performance",
"voluptuous/tests/tests.py::test_IsDir",
"voluptuous/tests/tests.py::test_IsFile",
"voluptuous/tests/tests.py::test_PathExists"
]
| []
| BSD 3-Clause "New" or "Revised" License | 1,827 | [
"voluptuous/schema_builder.py"
]
| [
"voluptuous/schema_builder.py"
]
|
|
OpenMined__PySyft-391 | f1f230c45e29abce37f83a2ed4606c8a6512d3fa | 2017-10-31 09:08:36 | 06ce023225dd613d8fb14ab2046135b93ab22376 | codecov[bot]: # [Codecov](https://codecov.io/gh/OpenMined/PySyft/pull/391?src=pr&el=h1) Report
> Merging [#391](https://codecov.io/gh/OpenMined/PySyft/pull/391?src=pr&el=desc) into [master](https://codecov.io/gh/OpenMined/PySyft/commit/f1f230c45e29abce37f83a2ed4606c8a6512d3fa?src=pr&el=desc) will **increase** coverage by `<.01%`.
> The diff coverage is `n/a`.
[](https://codecov.io/gh/OpenMined/PySyft/pull/391?src=pr&el=tree)
```diff
@@ Coverage Diff @@
## master #391 +/- ##
==========================================
+ Coverage 99.52% 99.52% +<.01%
==========================================
Files 4 4
Lines 1682 1695 +13
==========================================
+ Hits 1674 1687 +13
Misses 8 8
```
| [Impacted Files](https://codecov.io/gh/OpenMined/PySyft/pull/391?src=pr&el=tree) | Coverage Δ | |
|---|---|---|
| [PySyft/tests/test\_tensor.py](https://codecov.io/gh/OpenMined/PySyft/pull/391?src=pr&el=tree#diff-UHlTeWZ0L3Rlc3RzL3Rlc3RfdGVuc29yLnB5) | `99.35% <0%> (ø)` | :arrow_up: |
------
[Continue to review full report at Codecov](https://codecov.io/gh/OpenMined/PySyft/pull/391?src=pr&el=continue).
> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
> `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
> Powered by [Codecov](https://codecov.io/gh/OpenMined/PySyft/pull/391?src=pr&el=footer). Last update [f1f230c...f714e87](https://codecov.io/gh/OpenMined/PySyft/pull/391?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).
bharathgs: looks like few test are missing.
divyanshj16: Earlier I confused `split_size` variable to be the number of splits. But In the new commit, I changed this!
Actually, split size is chunk size.
If there is an array [0,1,2,3,4,5,6,7,8,9] then if `split_size` is 3 then the array will get divided into subarrays of size 3 and last one with size one as [[0,1,2],[3,4,5],[6,7,8],[9]].
In my earlier implementation the above array would have divided into 3 subarrays [[0,1,2,3],[4,5,6,7],[8,9]]. This has been resolved by this last commit.
bharathgs: your code does not produce the results that you mention in the comment above.
also, please try out the code before a PR.
divyanshj16: I'll do the changes! I did not understand your second point, `2. in place version of this function is not necessary, however, a split method is(in tensor module)`
bharathgs: change `split_` -> `split`
divyanshj16: There is already a `split` method in `tensor.py` at line 3041 and `SplitTests` are also there in `test_tensor.py` at line 977. Its tests are not exhaustive. Also, they are not implemented as PyTorch's implementation.
This was the reason I had to name my test class as `SplitTests2` and my function as `split_`.
My functions are working good in accordance with the PyTorch's implementation. See the image below.

I'll add tests in test_math for the split function and will create a PR!
Should I remove the earlier implementation(i.e implementation on the specified lines)?
bharathgs: ahh, now I see, I missed that. yes remove the earlier implementation
divyanshj16: Naming conventions are not specific as `axis`(numpy's) and `dim`(pytorch's) are interchangeably used in the whole code. What should I use?
divyanshj16: I have used `axis` for naming the axis of the tensor. However, we should raise an issue to make it consistent. | diff --git a/syft/math.py b/syft/math.py
index e880c85ed9..4d395a6a0d 100644
--- a/syft/math.py
+++ b/syft/math.py
@@ -968,3 +968,43 @@ def zeros(dim):
Output Tensor
"""
return TensorBase(np.zeros(dim))
+
+
+def split(tensor, split_size, axis=0):
+ """
+ Splits the tensor into multiple equally sized chunks (if possible).
+
+ Last chunk will be smaller if the tensor size along a given axis
+ is not divisible by `split_size`.
+
+ Returns a list of the split tensors
+
+ Parameters
+ ----------
+ tensor: TensorBase
+ array to be divided into sub-arrays.
+
+ split_size: int
+ size of single chunk
+
+ axis: int, optional
+ The axis along which to split, default is 0.
+
+ Returns
+ -------
+ list: list of divided arrays
+ """
+ if axis < 0:
+ axis += len(tensor.shape())
+
+ length_along_axis = tensor.shape()[axis]
+
+ # calculate number of splits!
+ num_splits = (length_along_axis + split_size - 1) // split_size
+
+ # make array to pass to numpy array_split function
+ split_according = [split_size * i for i in range(1, num_splits)]
+
+ list_ = np.array_split(tensor.data, split_according, axis)
+
+ return list(map(lambda x: TensorBase(x), list_))
diff --git a/syft/tensor.py b/syft/tensor.py
index f774b294e1..89f23c3b05 100644
--- a/syft/tensor.py
+++ b/syft/tensor.py
@@ -3038,29 +3038,6 @@ class TensorBase(object):
else:
return self.data.shape
- def split(self, split_size, dim=0):
- """
- Returns tuple of tensors of equally sized tensor/chunks (if possible)
-
- Parameters
- ----------
- split_size:
-
- dim:
-
- Returns
- -------
- Tuple of Tensors
- """
- if self.encrypted:
- return NotImplemented
- splits = np.array_split(self.data, split_size, axis=0)
- tensors = list()
- for s in splits:
- tensors.append(TensorBase(s))
- tensors_tuple = tuple(tensors)
- return tensors_tuple
-
def stride(self, dim=None):
"""
Returns the jump necessary to go from one element to the next one in the specified dimension dim.
@@ -3601,3 +3578,30 @@ class TensorBase(object):
self.data.fill(0)
return self
+
+ def split(self, split_size, axis=0):
+ """
+ Splits the tensor into multiple equally sized chunks (if possible).
+
+ Last chunk will be smaller if the tensor size along a given axis
+ is not divisible by `split_size`.
+
+ Returns a list of the split tensors
+
+ Parameters
+ ----------
+
+ split_size: int
+ size of single chunk
+
+ axis: int, optional
+ The axis along which to split, default is 0.
+
+ Returns
+ -------
+ list: list of divided arrays
+ """
+ if self.encrypted:
+ return NotImplemented
+
+ return syft.math.split(self, split_size, axis)
| Implement Default split Functionality for Base Tensor Type.
<!-- Please make sure that you review this: https://github.com/OpenMined/Docs/blob/master/contributing/guidelines.md -->
<!-- If you are looking to file a bug make sure to look at the .github/BUG_ISSUE_TEMPLATE.md -->
#### User story:
As a Data Scientist using Syft's Base Tensor type, I want to leverage a default method for computing operations on a Tensor of arbitrary type. For this ticket to be complete `split` should return a new tensor. For a reference on the operation these perform check out [PyTorch's](http://pytorch.org/docs/master/torch.html#torch.split) documentation.
<!-- Provide a detailed explaination about the proposed feature, you can draw inspiration from something like this:
https://github.com/OpenMined/PySyft/issues/227 or https://github.com/OpenMined/PySyft/issues/12 -->
#### Acceptance Criteria:
<!-- Provide an outline af all the things that needs to be addressed in order to close this Issue,
be as descriptive as possible -->
- [x] If the Base Tensor type's attribute "encrypted" is set to True, it should return a NotImplemented error.
- [ ] corresponding unit tests demonstrating the correct operation on the Base Tensor type implemented over int and float Tensors.
- [ ] inline documentation as described over [here](https://github.com/OpenMined/PySyft/blob/85bc68e81a2f4bfc0f0bf6c4252b88d6d7b54004/syft/math.py#L5).
<!-- Thanks for your contributions! -->
| OpenMined/PySyft | diff --git a/tests/test_math.py b/tests/test_math.py
index 83b590f47b..09aad0a9f7 100644
--- a/tests/test_math.py
+++ b/tests/test_math.py
@@ -427,3 +427,17 @@ class MultinomialTests(unittest.TestCase):
t2 = syft.math.multinomial(t1, len(t1))
self.assertTupleEqual((len(t1),), t2.shape())
self.assertTrue(np.all(t2.data >= 0) and np.all(t2.data <= len(t1)))
+
+
+class SplitTests(unittest.TestCase):
+ def test_split(self):
+ t = TensorBase(np.random.rand(7, 4))
+ split_size = 3
+ axis = 0
+ target_shapes = [(3, 4), (3, 4), (1, 4)]
+ splits = syft.math.split(t, split_size, axis)
+ start = 0
+ for target_shape, split in zip(target_shapes, splits):
+ self.assertTrue(syft.equal(split.shape(), target_shape))
+ self.assertTrue(syft.equal(t.narrow(axis, start, target_shape[axis]), split))
+ start += target_shape[axis]
diff --git a/tests/test_tensor.py b/tests/test_tensor.py
index c34b4cebc6..3c9052c3bf 100644
--- a/tests/test_tensor.py
+++ b/tests/test_tensor.py
@@ -974,13 +974,6 @@ class CumprodTest(unittest.TestCase):
self.assertTrue(np.equal(t1.cumprod_(dim=1), t3).all())
-class SplitTests(unittest.TestCase):
- def test_split(self):
- t1 = TensorBase(np.arange(8.0))
- t2 = t1.split(4)
- self.assertTrue(np.array_equal(t2, tuple((np.array([0., 1.]), np.array([2., 3.]), np.array([4., 5.]), np.array([6., 7.])))))
-
-
class SqueezeTests(unittest.TestCase):
def test_squeeze(self):
t1 = TensorBase(np.zeros((2, 1, 2, 1, 2)))
@@ -1628,6 +1621,20 @@ class UnfoldTest(unittest.TestCase):
t1_unfolded_actual_2))
+class SplitTests(unittest.TestCase):
+ def test_split(self):
+ t = TensorBase(np.random.rand(10, 5))
+ split_size = 3
+ axis = 0
+ target_shapes = [(3, 5), (3, 5), (3, 5), (1, 5)]
+ splits = t.split(split_size, axis)
+ start = 0
+ for target_shape, split in zip(target_shapes, splits):
+ self.assertTrue(syft.equal(split.shape(), target_shape))
+ self.assertTrue(syft.equal(t.narrow(axis, start, target_shape[axis]), split))
+ start += target_shape[axis]
+
+
if __name__ == "__main__":
unittest.main()
| {
"commit_name": "merge_commit",
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 1,
"test_score": 1
},
"num_modified_files": 2
} | PySyft/hydrogen | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"flake8"
],
"pre_install": [
"apt-get update",
"apt-get install -y musl-dev g++ libgmp3-dev libmpfr-dev ca-certificates libmpc-dev"
],
"python": "3.6",
"reqs_path": [
"requirements.txt",
"dev-requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | anyio==3.6.2
argon2-cffi==21.3.0
argon2-cffi-bindings==21.2.0
args==0.1.0
async-generator==1.10
attrs==22.2.0
Babel==2.11.0
backcall==0.2.0
bleach==4.1.0
certifi==2021.5.30
cffi==1.15.1
charset-normalizer==2.0.12
clint==0.5.1
comm==0.1.4
contextvars==2.4
coverage==6.2
dataclasses==0.8
decorator==5.1.1
defusedxml==0.7.1
entrypoints==0.4
flake8==5.0.4
idna==3.10
immutables==0.19
importlib-metadata==4.2.0
iniconfig==1.1.1
ipykernel==5.5.6
ipython==7.16.3
ipython-genutils==0.2.0
ipywidgets==7.8.5
jedi==0.17.2
Jinja2==3.0.3
joblib==1.1.1
json5==0.9.16
jsonschema==3.2.0
jupyter==1.1.1
jupyter-client==7.1.2
jupyter-console==6.4.3
jupyter-core==4.9.2
jupyter-server==1.13.1
jupyterlab==3.2.9
jupyterlab-pygments==0.1.2
jupyterlab-server==2.10.3
jupyterlab_widgets==1.1.11
line-profiler==4.1.3
MarkupSafe==2.0.1
mccabe==0.7.0
mistune==0.8.4
nbclassic==0.3.5
nbclient==0.5.9
nbconvert==6.0.7
nbformat==5.1.3
nest-asyncio==1.6.0
notebook==6.4.10
numpy==1.19.5
packaging==21.3
pandocfilters==1.5.1
parso==0.7.1
pexpect==4.9.0
phe==1.5.0
pickleshare==0.7.5
pluggy==1.0.0
prometheus-client==0.17.1
prompt-toolkit==3.0.36
ptyprocess==0.7.0
py==1.11.0
pycodestyle==2.9.1
pycparser==2.21
pyflakes==2.5.0
Pygments==2.14.0
pyparsing==3.1.4
pyRserve==1.0.4
pyrsistent==0.18.0
pytest==7.0.1
pytest-flake8==1.1.1
python-dateutil==2.9.0.post0
pytz==2025.2
pyzmq==25.1.2
requests==2.27.1
scikit-learn==0.24.2
scipy==1.5.4
Send2Trash==1.8.3
six==1.17.0
sklearn==0.0
sniffio==1.2.0
-e git+https://github.com/OpenMined/PySyft.git@f1f230c45e29abce37f83a2ed4606c8a6512d3fa#egg=syft
terminado==0.12.1
testpath==0.6.0
threadpoolctl==3.1.0
tomli==1.2.3
tornado==6.1
traitlets==4.3.3
typing_extensions==4.1.1
urllib3==1.26.20
wcwidth==0.2.13
webencodings==0.5.1
websocket-client==1.3.1
widgetsnbextension==3.6.10
zipp==3.6.0
| name: PySyft
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- anyio==3.6.2
- argon2-cffi==21.3.0
- argon2-cffi-bindings==21.2.0
- args==0.1.0
- async-generator==1.10
- attrs==22.2.0
- babel==2.11.0
- backcall==0.2.0
- bleach==4.1.0
- cffi==1.15.1
- charset-normalizer==2.0.12
- clint==0.5.1
- comm==0.1.4
- contextvars==2.4
- coverage==6.2
- dataclasses==0.8
- decorator==5.1.1
- defusedxml==0.7.1
- entrypoints==0.4
- flake8==5.0.4
- idna==3.10
- immutables==0.19
- importlib-metadata==4.2.0
- iniconfig==1.1.1
- ipykernel==5.5.6
- ipython==7.16.3
- ipython-genutils==0.2.0
- ipywidgets==7.8.5
- jedi==0.17.2
- jinja2==3.0.3
- joblib==1.1.1
- json5==0.9.16
- jsonschema==3.2.0
- jupyter==1.1.1
- jupyter-client==7.1.2
- jupyter-console==6.4.3
- jupyter-core==4.9.2
- jupyter-server==1.13.1
- jupyterlab==3.2.9
- jupyterlab-pygments==0.1.2
- jupyterlab-server==2.10.3
- jupyterlab-widgets==1.1.11
- line-profiler==4.1.3
- markupsafe==2.0.1
- mccabe==0.7.0
- mistune==0.8.4
- nbclassic==0.3.5
- nbclient==0.5.9
- nbconvert==6.0.7
- nbformat==5.1.3
- nest-asyncio==1.6.0
- notebook==6.4.10
- numpy==1.19.5
- packaging==21.3
- pandocfilters==1.5.1
- parso==0.7.1
- pexpect==4.9.0
- phe==1.5.0
- pickleshare==0.7.5
- pluggy==1.0.0
- prometheus-client==0.17.1
- prompt-toolkit==3.0.36
- ptyprocess==0.7.0
- py==1.11.0
- pycodestyle==2.9.1
- pycparser==2.21
- pyflakes==2.5.0
- pygments==2.14.0
- pyparsing==3.1.4
- pyrserve==1.0.4
- pyrsistent==0.18.0
- pytest==7.0.1
- pytest-flake8==1.1.1
- python-dateutil==2.9.0.post0
- pytz==2025.2
- pyzmq==25.1.2
- requests==2.27.1
- scikit-learn==0.24.2
- scipy==1.5.4
- send2trash==1.8.3
- six==1.17.0
- sklearn==0.0
- sniffio==1.2.0
- terminado==0.12.1
- testpath==0.6.0
- threadpoolctl==3.1.0
- tomli==1.2.3
- tornado==6.1
- traitlets==4.3.3
- typing-extensions==4.1.1
- urllib3==1.26.20
- wcwidth==0.2.13
- webencodings==0.5.1
- websocket-client==1.3.1
- widgetsnbextension==3.6.10
- zipp==3.6.0
prefix: /opt/conda/envs/PySyft
| [
"tests/test_math.py::SplitTests::test_split",
"tests/test_tensor.py::SplitTests::test_split"
]
| []
| [
"tests/test_math.py::ConvenienceTests::test_ones",
"tests/test_math.py::ConvenienceTests::test_rand",
"tests/test_math.py::ConvenienceTests::test_zeros",
"tests/test_math.py::DotTests::test_dot_float",
"tests/test_math.py::DotTests::test_dot_int",
"tests/test_math.py::DiagTests::test_one_dim_tensor_below_diag",
"tests/test_math.py::DiagTests::test_one_dim_tensor_main_diag",
"tests/test_math.py::DiagTests::test_one_dim_tensor_upper_diag",
"tests/test_math.py::DiagTests::test_two_dim_tensor_below_diag",
"tests/test_math.py::DiagTests::test_two_dim_tensor_main_diag",
"tests/test_math.py::DiagTests::test_two_dim_tensor_upper_diag",
"tests/test_math.py::CeilTests::test_ceil",
"tests/test_math.py::FloorTests::test_floor",
"tests/test_math.py::SinTests::test_sin",
"tests/test_math.py::SinhTests::test_sinh",
"tests/test_math.py::CosTests::test_cos",
"tests/test_math.py::CoshTests::test_cosh",
"tests/test_math.py::TanTests::test_tan",
"tests/test_math.py::TanhTests::test_tanh",
"tests/test_math.py::CumsumTests::test_cumsum",
"tests/test_math.py::CumprodTests::test_cumprod",
"tests/test_math.py::SigmoidTests::test_sigmoid",
"tests/test_math.py::MatmulTests::test_matmul_1d_float",
"tests/test_math.py::MatmulTests::test_matmul_1d_int",
"tests/test_math.py::MatmulTests::test_matmul_2d_float",
"tests/test_math.py::MatmulTests::test_matmul_2d_identity",
"tests/test_math.py::MatmulTests::test_matmul_2d_int",
"tests/test_math.py::AddmmTests::test_addmm_1d",
"tests/test_math.py::AddmmTests::test_addmm_2d",
"tests/test_math.py::AddcmulTests::test_addcmul_1d",
"tests/test_math.py::AddcmulTests::test_addcmul_2d",
"tests/test_math.py::AddcdivTests::test_addcdiv_1d",
"tests/test_math.py::AddcdivTests::test_addcdiv_2d",
"tests/test_math.py::AddmvTests::test_addmv",
"tests/test_math.py::BmmTests::test_bmm",
"tests/test_math.py::BmmTests::test_bmm_for_correct_size_output",
"tests/test_math.py::AddbmmTests::test_addbmm",
"tests/test_math.py::BaddbmmTests::test_baddbmm",
"tests/test_math.py::TransposeTests::test_transpose",
"tests/test_math.py::UnsqueezeTests::test_unsqueeze",
"tests/test_math.py::MmTests::test_mm_1d",
"tests/test_math.py::MmTests::test_mm_2d",
"tests/test_math.py::MmTests::test_mm_3d",
"tests/test_math.py::FmodTests::test_fmod_number",
"tests/test_math.py::FmodTests::test_fmod_tensor",
"tests/test_math.py::LerpTests::test_lerp",
"tests/test_math.py::NumelTests::test_numel_float",
"tests/test_math.py::NumelTests::test_numel_int",
"tests/test_math.py::RenormTests::test_3d_tensor_renorm",
"tests/test_math.py::RenormTests::test_float_renorm",
"tests/test_math.py::RenormTests::test_int_renorm",
"tests/test_math.py::MultinomialTests::test_multinomial",
"tests/test_tensor.py::DimTests::test_as_view",
"tests/test_tensor.py::DimTests::test_dim_one",
"tests/test_tensor.py::DimTests::test_resize",
"tests/test_tensor.py::DimTests::test_resize_as",
"tests/test_tensor.py::DimTests::test_view",
"tests/test_tensor.py::DiagTests::test_one_dim_tensor_below_diag",
"tests/test_tensor.py::DiagTests::test_one_dim_tensor_main_diag",
"tests/test_tensor.py::DiagTests::test_one_dim_tensor_upper_diag",
"tests/test_tensor.py::DiagTests::test_two_dim_tensor_below_diag",
"tests/test_tensor.py::DiagTests::test_two_dim_tensor_main_diag",
"tests/test_tensor.py::DiagTests::test_two_dim_tensor_upper_diag",
"tests/test_tensor.py::AddTests::test_inplace",
"tests/test_tensor.py::AddTests::test_scalar",
"tests/test_tensor.py::AddTests::test_simple",
"tests/test_tensor.py::CeilTests::test_ceil",
"tests/test_tensor.py::CeilTests::test_ceil_",
"tests/test_tensor.py::ZeroTests::test_zero",
"tests/test_tensor.py::FloorTests::test_floor",
"tests/test_tensor.py::SubTests::test_inplace",
"tests/test_tensor.py::SubTests::test_scalar",
"tests/test_tensor.py::SubTests::test_simple",
"tests/test_tensor.py::MaxTests::test_axis",
"tests/test_tensor.py::MaxTests::test_no_dim",
"tests/test_tensor.py::MultTests::test_inplace",
"tests/test_tensor.py::MultTests::test_scalar",
"tests/test_tensor.py::MultTests::test_simple",
"tests/test_tensor.py::DivTests::test_inplace",
"tests/test_tensor.py::DivTests::test_scalar",
"tests/test_tensor.py::DivTests::test_simple",
"tests/test_tensor.py::AbsTests::test_abs",
"tests/test_tensor.py::AbsTests::test_abs_",
"tests/test_tensor.py::ShapeTests::test_shape",
"tests/test_tensor.py::SqrtTests::test_sqrt",
"tests/test_tensor.py::SqrtTests::test_sqrt_",
"tests/test_tensor.py::SumTests::test_dim_is_not_none_int",
"tests/test_tensor.py::SumTests::test_dim_none_int",
"tests/test_tensor.py::EqualTests::test_equal",
"tests/test_tensor.py::EqualTests::test_equal_operation",
"tests/test_tensor.py::EqualTests::test_inequality_operation",
"tests/test_tensor.py::EqualTests::test_not_equal",
"tests/test_tensor.py::EqualTests::test_shape_inequality_operation",
"tests/test_tensor.py::EqualTests::test_shape_not_equal",
"tests/test_tensor.py::SigmoidTests::test_sigmoid",
"tests/test_tensor.py::AddmmTests::test_addmm_1d",
"tests/test_tensor.py::AddmmTests::test_addmm_1d_",
"tests/test_tensor.py::AddmmTests::test_addmm_2d",
"tests/test_tensor.py::AddmmTests::test_addmm_2d_",
"tests/test_tensor.py::AddcmulTests::test_addcmul_1d",
"tests/test_tensor.py::AddcmulTests::test_addcmul_1d_",
"tests/test_tensor.py::AddcmulTests::test_addcmul_2d",
"tests/test_tensor.py::AddcmulTests::test_addcmul_2d_",
"tests/test_tensor.py::AddcdivTests::test_addcdiv_1d",
"tests/test_tensor.py::AddcdivTests::test_addcdiv_1d_",
"tests/test_tensor.py::AddcdivTests::test_addcdiv_2d",
"tests/test_tensor.py::AddcdivTests::test_addcdiv_2d_",
"tests/test_tensor.py::AddmvTests::test_addmv",
"tests/test_tensor.py::AddmvTests::test_addmv_",
"tests/test_tensor.py::BmmTests::test_bmm",
"tests/test_tensor.py::BmmTests::test_bmm_size",
"tests/test_tensor.py::AddbmmTests::test_addbmm",
"tests/test_tensor.py::AddbmmTests::test_addbmm_",
"tests/test_tensor.py::BaddbmmTests::test_baddbmm",
"tests/test_tensor.py::BaddbmmTests::test_baddbmm_",
"tests/test_tensor.py::TransposeTests::test_t",
"tests/test_tensor.py::TransposeTests::test_transpose",
"tests/test_tensor.py::TransposeTests::test_transpose_",
"tests/test_tensor.py::UnsqueezeTests::test_unsqueeze",
"tests/test_tensor.py::UnsqueezeTests::test_unsqueeze_",
"tests/test_tensor.py::ExpTests::test_exp",
"tests/test_tensor.py::ExpTests::test_exp_",
"tests/test_tensor.py::FracTests::test_frac",
"tests/test_tensor.py::FracTests::test_frac_",
"tests/test_tensor.py::RsqrtTests::test_rsqrt",
"tests/test_tensor.py::RsqrtTests::test_rsqrt_",
"tests/test_tensor.py::SignTests::test_sign",
"tests/test_tensor.py::SignTests::test_sign_",
"tests/test_tensor.py::NumpyTests::test_numpy",
"tests/test_tensor.py::ReciprocalTests::test_reciprocal",
"tests/test_tensor.py::ReciprocalTests::test_reciprocal_",
"tests/test_tensor.py::LogTests::test_log",
"tests/test_tensor.py::LogTests::test_log_",
"tests/test_tensor.py::LogTests::test_log_1p",
"tests/test_tensor.py::LogTests::test_log_1p_",
"tests/test_tensor.py::ClampTests::test_clamp_float",
"tests/test_tensor.py::ClampTests::test_clamp_float_in_place",
"tests/test_tensor.py::ClampTests::test_clamp_int",
"tests/test_tensor.py::ClampTests::test_clamp_int_in_place",
"tests/test_tensor.py::CloneTests::test_clone",
"tests/test_tensor.py::ChunkTests::test_chunk",
"tests/test_tensor.py::ChunkTests::test_chunk_same_size",
"tests/test_tensor.py::GtTests::test_gt__in_place_with_number",
"tests/test_tensor.py::GtTests::test_gt__in_place_with_tensor",
"tests/test_tensor.py::GtTests::test_gt_with_encrypted",
"tests/test_tensor.py::GtTests::test_gt_with_number",
"tests/test_tensor.py::GtTests::test_gt_with_tensor",
"tests/test_tensor.py::GeTests::test_ge__in_place_with_number",
"tests/test_tensor.py::GeTests::test_ge__in_place_with_tensor",
"tests/test_tensor.py::GeTests::test_ge_with_encrypted",
"tests/test_tensor.py::GeTests::test_ge_with_number",
"tests/test_tensor.py::GeTests::test_ge_with_tensor",
"tests/test_tensor.py::LtTests::test_lt__in_place_with_number",
"tests/test_tensor.py::LtTests::test_lt__in_place_with_tensor",
"tests/test_tensor.py::LtTests::test_lt_with_encrypted",
"tests/test_tensor.py::LtTests::test_lt_with_number",
"tests/test_tensor.py::LtTests::test_lt_with_tensor",
"tests/test_tensor.py::LeTests::test_le__in_place_with_number",
"tests/test_tensor.py::LeTests::test_le__in_place_with_tensor",
"tests/test_tensor.py::LeTests::test_le_with_encrypted",
"tests/test_tensor.py::LeTests::test_le_with_number",
"tests/test_tensor.py::LeTests::test_le_with_tensor",
"tests/test_tensor.py::BernoulliTests::test_bernoulli",
"tests/test_tensor.py::BernoulliTests::test_bernoulli_",
"tests/test_tensor.py::MultinomialTests::test_multinomial",
"tests/test_tensor.py::CauchyTests::test_cauchy_",
"tests/test_tensor.py::UniformTests::test_uniform",
"tests/test_tensor.py::UniformTests::test_uniform_",
"tests/test_tensor.py::GeometricTests::test_geometric_",
"tests/test_tensor.py::NormalTests::test_normal",
"tests/test_tensor.py::NormalTests::test_normal_",
"tests/test_tensor.py::FillTests::test_fill_",
"tests/test_tensor.py::TopkTests::test_topK",
"tests/test_tensor.py::TolistTests::test_to_list",
"tests/test_tensor.py::TraceTests::test_trace",
"tests/test_tensor.py::RoundTests::test_round",
"tests/test_tensor.py::RoundTests::test_round_",
"tests/test_tensor.py::RepeatTests::test_repeat",
"tests/test_tensor.py::PowTests::test_pow",
"tests/test_tensor.py::PowTests::test_pow_",
"tests/test_tensor.py::NegTests::test_neg",
"tests/test_tensor.py::NegTests::test_neg_",
"tests/test_tensor.py::SinTests::test_sin",
"tests/test_tensor.py::SinhTests::test_sinh",
"tests/test_tensor.py::CosTests::test_cos",
"tests/test_tensor.py::CoshTests::test_cosh",
"tests/test_tensor.py::TanTests::test_tan",
"tests/test_tensor.py::TanhTests::test_tanh_",
"tests/test_tensor.py::ProdTests::test_prod",
"tests/test_tensor.py::RandomTests::test_random_",
"tests/test_tensor.py::NonzeroTests::test_non_zero",
"tests/test_tensor.py::CumprodTest::test_cumprod",
"tests/test_tensor.py::CumprodTest::test_cumprod_",
"tests/test_tensor.py::SqueezeTests::test_squeeze",
"tests/test_tensor.py::ExpandAsTests::test_expand_as",
"tests/test_tensor.py::MeanTests::test_mean",
"tests/test_tensor.py::NotEqualTests::test_ne",
"tests/test_tensor.py::NotEqualTests::test_ne_",
"tests/test_tensor.py::IndexTests::test_index",
"tests/test_tensor.py::IndexTests::test_index_add_",
"tests/test_tensor.py::IndexTests::test_index_copy_",
"tests/test_tensor.py::IndexTests::test_index_fill_",
"tests/test_tensor.py::IndexTests::test_index_select",
"tests/test_tensor.py::IndexTests::test_index_slice_notation",
"tests/test_tensor.py::IndexTests::test_indexing",
"tests/test_tensor.py::GatherTests::test_gather_numerical_1",
"tests/test_tensor.py::GatherTests::test_gather_numerical_2",
"tests/test_tensor.py::ScatterTests::test_scatter_dim_out_Of_range",
"tests/test_tensor.py::ScatterTests::test_scatter_index_out_of_range",
"tests/test_tensor.py::ScatterTests::test_scatter_index_src_dimension_mismatch",
"tests/test_tensor.py::ScatterTests::test_scatter_index_type",
"tests/test_tensor.py::ScatterTests::test_scatter_numerical_0",
"tests/test_tensor.py::ScatterTests::test_scatter_numerical_1",
"tests/test_tensor.py::ScatterTests::test_scatter_numerical_2",
"tests/test_tensor.py::ScatterTests::test_scatter_numerical_3",
"tests/test_tensor.py::ScatterTests::test_scatter_numerical_4",
"tests/test_tensor.py::ScatterTests::test_scatter_numerical_5",
"tests/test_tensor.py::ScatterTests::test_scatter_numerical_6",
"tests/test_tensor.py::RemainderTests::test_remainder_",
"tests/test_tensor.py::RemainderTests::test_remainder_broadcasting",
"tests/test_tensor.py::MvTests::test_mv",
"tests/test_tensor.py::MvTests::test_mv_tensor",
"tests/test_tensor.py::NarrowTests::test_narrow_float",
"tests/test_tensor.py::NarrowTests::test_narrow_int",
"tests/test_tensor.py::MaskedScatterTests::test_masked_scatter_1",
"tests/test_tensor.py::MaskedScatterTests::test_masked_scatter_braodcasting_1",
"tests/test_tensor.py::MaskedScatterTests::test_masked_scatter_braodcasting_2",
"tests/test_tensor.py::MaskedFillTests::test_masked_fill_",
"tests/test_tensor.py::MaskedFillTests::test_masked_fill_broadcasting",
"tests/test_tensor.py::MaskedSelectTests::test_masked_select",
"tests/test_tensor.py::MaskedSelectTests::test_masked_select_broadcasting_1",
"tests/test_tensor.py::MaskedSelectTests::test_masked_select_broadcasting_2",
"tests/test_tensor.py::MaskedSelectTests::test_tensor_base_masked_select",
"tests/test_tensor.py::EqTests::test_eq_in_place_with_number",
"tests/test_tensor.py::EqTests::test_eq_in_place_with_tensor",
"tests/test_tensor.py::EqTests::test_eq_with_number",
"tests/test_tensor.py::EqTests::test_eq_with_tensor",
"tests/test_tensor.py::MmTests::test_mm_1d",
"tests/test_tensor.py::MmTests::test_mm_2d",
"tests/test_tensor.py::MmTests::test_mm_3d",
"tests/test_tensor.py::NewTensorTests::test_encrypted_error",
"tests/test_tensor.py::NewTensorTests::test_return_new_float_tensor",
"tests/test_tensor.py::NewTensorTests::test_return_new_int_tensor",
"tests/test_tensor.py::HalfTests::test_half_1",
"tests/test_tensor.py::HalfTests::test_half_2",
"tests/test_tensor.py::FmodTests::test_fmod_number",
"tests/test_tensor.py::FmodTests::test_fmod_tensor",
"tests/test_tensor.py::FmodTestsBis::test_fmod_number",
"tests/test_tensor.py::FmodTestsBis::test_fmod_tensor",
"tests/test_tensor.py::NumelTests::test_numel_2d",
"tests/test_tensor.py::NumelTests::test_numel_3d",
"tests/test_tensor.py::NumelTests::test_numel_encrypted",
"tests/test_tensor.py::NumelTests::test_numel_float",
"tests/test_tensor.py::NumelTests::test_numel_int",
"tests/test_tensor.py::NumelTests::test_numel_str",
"tests/test_tensor.py::NelementTests::test_nelement_2d",
"tests/test_tensor.py::NelementTests::test_nelement_3d",
"tests/test_tensor.py::NelementTests::test_nelement_encrypted",
"tests/test_tensor.py::NelementTests::test_nelement_float",
"tests/test_tensor.py::NelementTests::test_nelement_int",
"tests/test_tensor.py::NelementTests::test_nelement_str",
"tests/test_tensor.py::SizeTests::test_size_2d",
"tests/test_tensor.py::SizeTests::test_size_3d",
"tests/test_tensor.py::SizeTests::test_size_float",
"tests/test_tensor.py::SizeTests::test_size_int",
"tests/test_tensor.py::SizeTests::test_size_str",
"tests/test_tensor.py::LerpTests::test_lerp",
"tests/test_tensor.py::LerpTests::test_lerp_",
"tests/test_tensor.py::ModeTests::testMode_axis_None",
"tests/test_tensor.py::ModeTests::testMode_axis_col",
"tests/test_tensor.py::ModeTests::testMode_axis_row",
"tests/test_tensor.py::RenormTests::testRenorm",
"tests/test_tensor.py::RenormTests::testRenorm_",
"tests/test_tensor.py::StrideTests::test_stride",
"tests/test_tensor.py::UnfoldTest::test_unfold_big",
"tests/test_tensor.py::UnfoldTest::test_unfold_small"
]
| []
| Apache License 2.0 | 1,828 | [
"syft/tensor.py",
"syft/math.py"
]
| [
"syft/tensor.py",
"syft/math.py"
]
|
EdinburghGenomics__EGCG-Core-64 | 5be3adbce57f2efd3afc6d15f59bb288ce0c1b50 | 2017-10-31 13:35:10 | 5be3adbce57f2efd3afc6d15f59bb288ce0c1b50 | diff --git a/CHANGELOG.md b/CHANGELOG.md
index f304aea..260484f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,10 +1,10 @@
Changelog for EGCG-Core
===========================
-0.8 (unreleased)
+0.7.4 (unreleased)
----------------
-- Nothing changed yet.
+- Bugfix in archive management.
0.7.3 (2017-09-01)
diff --git a/egcg_core/archive_management.py b/egcg_core/archive_management.py
index 58c5eb9..c5f5f2c 100644
--- a/egcg_core/archive_management.py
+++ b/egcg_core/archive_management.py
@@ -95,7 +95,7 @@ def register_for_archiving(file_path, strict=False):
raise ArchivingError('Registering %s for archiving to tape failed' % file_path)
# Registering for archive can sometime take time so give it a second
sleep(1)
- return register_for_archiving(filter, strict=True)
+ return register_for_archiving(file_path, strict=True)
return True
| Broken recursion in archive_management
In archive_management.register_for_archiving, the recursion is called with the built-in function `filter`, which can only be a typo. | EdinburghGenomics/EGCG-Core | diff --git a/tests/test_archive_management.py b/tests/test_archive_management.py
index 5d45646..0506957 100644
--- a/tests/test_archive_management.py
+++ b/tests/test_archive_management.py
@@ -80,6 +80,16 @@ class TestArchiveManagement(TestEGCG):
assert get_stdout.call_count == 3
assert get_stdout.call_args_list[1][0] == ('lfs hsm_archive testfile',)
+ with patch('egcg_core.archive_management._get_stdout',
+ side_effect=[
+ 'testfile: (0x00000001)', '', 'testfile: (0x00000001)',
+ 'testfile: (0x00000001)', '', 'testfile: (0x00000001)',
+ ]) as get_stdout:
+ self.assertRaises(ArchivingError, register_for_archiving, 'testfile', False)
+ assert get_stdout.call_count == 6
+ assert get_stdout.call_args_list[1][0] == ('lfs hsm_archive testfile',)
+ assert get_stdout.call_args_list[4][0] == ('lfs hsm_archive testfile',)
+
def test_recall_from_tape(self):
with patch('egcg_core.archive_management._get_stdout',
side_effect=[
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 0,
"test_score": 0
},
"num_modified_files": 2
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-cov"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.6",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | asana==0.6.5
attrs==22.2.0
cached-property==1.5.2
certifi==2021.5.30
coverage==6.2
-e git+https://github.com/EdinburghGenomics/EGCG-Core.git@5be3adbce57f2efd3afc6d15f59bb288ce0c1b50#egg=EGCG_Core
importlib-metadata==4.8.3
iniconfig==1.1.1
Jinja2==2.8
MarkupSafe==2.0.1
oauthlib==3.2.2
packaging==21.3
pluggy==1.0.0
py==1.11.0
pyclarity-lims==0.4.8
pyparsing==3.1.4
pytest==7.0.1
pytest-cov==4.0.0
PyYAML==6.0.1
requests==2.14.2
requests-oauthlib==0.6.2
six==1.10.0
tomli==1.2.3
typing_extensions==4.1.1
zipp==3.6.0
| name: EGCG-Core
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- asana==0.6.5
- attrs==22.2.0
- cached-property==1.5.2
- coverage==6.2
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- jinja2==2.8
- markupsafe==2.0.1
- oauthlib==3.2.2
- packaging==21.3
- pluggy==1.0.0
- py==1.11.0
- pyclarity-lims==0.4.8
- pyparsing==3.1.4
- pytest==7.0.1
- pytest-cov==4.0.0
- pyyaml==6.0.1
- requests==2.14.2
- requests-oauthlib==0.6.2
- six==1.10.0
- tomli==1.2.3
- typing-extensions==4.1.1
- zipp==3.6.0
prefix: /opt/conda/envs/EGCG-Core
| [
"tests/test_archive_management.py::TestArchiveManagement::test_register_for_archiving"
]
| []
| [
"tests/test_archive_management.py::TestArchiveManagement::test_archive_directory",
"tests/test_archive_management.py::TestArchiveManagement::test_archive_states",
"tests/test_archive_management.py::TestArchiveManagement::test_recall_from_tape",
"tests/test_archive_management.py::TestArchiveManagement::test_release_file_from_lustre"
]
| []
| MIT License | 1,829 | [
"egcg_core/archive_management.py",
"CHANGELOG.md"
]
| [
"egcg_core/archive_management.py",
"CHANGELOG.md"
]
|
|
pika__pika-888 | 7022aa9f4acb769672a1f13abaf36bd6c4d28674 | 2017-10-31 18:54:27 | 7b6d7983db021ae4b84d08ea9cee4b8f960ada43 | diff --git a/pika/data.py b/pika/data.py
index fe35e37..da6ab63 100644
--- a/pika/data.py
+++ b/pika/data.py
@@ -2,6 +2,8 @@
import struct
import decimal
import calendar
+import warnings
+
from datetime import datetime
from pika import exceptions
@@ -119,8 +121,16 @@ def encode_value(pieces, value):
pieces.append(struct.pack('>cq', b'l', value))
return 9
elif isinstance(value, int):
- pieces.append(struct.pack('>ci', b'I', value))
- return 5
+ with warnings.catch_warnings():
+ warnings.filterwarnings('error')
+ try:
+ p = struct.pack('>ci', b'I', value)
+ pieces.append(p)
+ return 5
+ except (struct.error, DeprecationWarning):
+ p = struct.pack('>cq', b'l', long(value))
+ pieces.append(p)
+ return 9
elif isinstance(value, decimal.Decimal):
value = value.normalize()
if value.as_tuple().exponent < 0:
| Python int type does not fit into struct 'i' format
https://github.com/pika/pika/blob/master/pika/data.py#L118-L123
I'm getting a "struct.error: 'i' format requires -2147483648 <= number <= 2147483647" where my value is 2592000000. That value fits into a Python int, which is `long` and on our platform is 64-bit wide, while struct 'i' format is defined as strictly 32-bit. I can work around that by explicitly casting to `long`, but it is a bug in pika nonetheless. | pika/pika | diff --git a/tests/unit/data_tests.py b/tests/unit/data_tests.py
index f14decc..eccb0ef 100644
--- a/tests/unit/data_tests.py
+++ b/tests/unit/data_tests.py
@@ -24,14 +24,15 @@ from pika.compat import long
class DataTests(unittest.TestCase):
FIELD_TBL_ENCODED = (
- b'\x00\x00\x00\xbb'
+ b'\x00\x00\x00\xcb'
b'\x05arrayA\x00\x00\x00\x0fI\x00\x00\x00\x01I\x00\x00\x00\x02I\x00\x00\x00\x03'
b'\x07boolvalt\x01'
b'\x07decimalD\x02\x00\x00\x01:'
b'\x0bdecimal_tooD\x00\x00\x00\x00d'
b'\x07dictvalF\x00\x00\x00\x0c\x03fooS\x00\x00\x00\x03bar'
b'\x06intvalI\x00\x00\x00\x01'
- b'\x07longvall\x00\x00\x00\x006e&U'
+ b'\x06bigint\x6c\x00\x00\x00\x00\x9a\x7e\xc8\x00'
+ b'\x07longval\x6c\x00\x00\x00\x00\x36\x65\x26\x55'
b'\x04nullV'
b'\x06strvalS\x00\x00\x00\x04Test'
b'\x0ctimestampvalT\x00\x00\x00\x00Ec)\x92'
@@ -44,7 +45,8 @@ class DataTests(unittest.TestCase):
('decimal', decimal.Decimal('3.14')),
('decimal_too', decimal.Decimal('100')),
('dictval', {'foo': 'bar'}),
- ('intval', 1) ,
+ ('intval', 1),
+ ('bigint', 2592000000),
('longval', long(912598613)),
('null', None),
('strval', 'Test'),
@@ -60,7 +62,7 @@ class DataTests(unittest.TestCase):
def test_encode_table_bytes(self):
result = []
byte_count = data.encode_table(result, self.FIELD_TBL_VALUE)
- self.assertEqual(byte_count, 191)
+ self.assertEqual(byte_count, 207)
def test_decode_table(self):
value, byte_count = data.decode_table(self.FIELD_TBL_ENCODED, 0)
@@ -68,7 +70,7 @@ class DataTests(unittest.TestCase):
def test_decode_table_bytes(self):
value, byte_count = data.decode_table(self.FIELD_TBL_ENCODED, 0)
- self.assertEqual(byte_count, 191)
+ self.assertEqual(byte_count, 207)
def test_encode_raises(self):
self.assertRaises(exceptions.UnsupportedAMQPFieldException,
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 2,
"test_score": 0
},
"num_modified_files": 1
} | 0.11 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest"
],
"pre_install": null,
"python": "3.6",
"reqs_path": [
"test-requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs==22.2.0
certifi==2021.5.30
charset-normalizer==2.0.12
codecov==2.1.13
coverage==6.2
idna==3.10
importlib-metadata==4.8.3
iniconfig==1.1.1
mock==5.2.0
nose==1.3.7
packaging==21.3
-e git+https://github.com/pika/pika.git@7022aa9f4acb769672a1f13abaf36bd6c4d28674#egg=pika
pluggy==1.0.0
py==1.11.0
pyparsing==3.1.4
pytest==7.0.1
requests==2.27.1
tomli==1.2.3
tornado==6.1
Twisted==15.3.0
typing_extensions==4.1.1
urllib3==1.26.20
zipp==3.6.0
zope.interface==5.5.2
| name: pika
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- attrs==22.2.0
- charset-normalizer==2.0.12
- codecov==2.1.13
- coverage==6.2
- idna==3.10
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- mock==5.2.0
- nose==1.3.7
- packaging==21.3
- pluggy==1.0.0
- py==1.11.0
- pyparsing==3.1.4
- pytest==7.0.1
- requests==2.27.1
- tomli==1.2.3
- tornado==6.1
- twisted==15.3.0
- typing-extensions==4.1.1
- urllib3==1.26.20
- zipp==3.6.0
- zope-interface==5.5.2
prefix: /opt/conda/envs/pika
| [
"tests/unit/data_tests.py::DataTests::test_encode_table",
"tests/unit/data_tests.py::DataTests::test_encode_table_bytes"
]
| []
| [
"tests/unit/data_tests.py::DataTests::test_decode_raises",
"tests/unit/data_tests.py::DataTests::test_decode_table",
"tests/unit/data_tests.py::DataTests::test_decode_table_bytes",
"tests/unit/data_tests.py::DataTests::test_encode_raises"
]
| []
| BSD 3-Clause "New" or "Revised" License | 1,831 | [
"pika/data.py"
]
| [
"pika/data.py"
]
|
|
numpy__numpydoc-136 | 2f075a613b7066493d05fb28d9851cdd7acd8f2a | 2017-11-01 09:34:47 | 8c1e85c746d1c95b9433b2ae97057b7f447c83d1 | diff --git a/README.rst b/README.rst
index 7174840..3d680a5 100644
--- a/README.rst
+++ b/README.rst
@@ -11,16 +11,16 @@
numpydoc -- Numpy's Sphinx extensions
=====================================
-Numpy's documentation uses several custom extensions to Sphinx. These
-are shipped in this ``numpydoc`` package, in case you want to make use
-of them in third-party projects.
+This package provides the ``numpydoc`` Sphinx extension for handling
+docstrings formatted according to the `NumPy documentation format
+<https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt>`__.
+The extension also adds the code description directives
+``np:function``, ``np-c:function``, etc.
-The ``numpydoc`` extension provides support for the Numpy docstring format in
-Sphinx, and adds the code description directives ``np:function``,
-``np-c:function``, etc. that support the Numpy docstring syntax.
+For usage information, please refer to the `documentation
+<https://numpydoc.readthedocs.io/>`_.
-See `numpydoc docstring guide <https://numpydoc.readthedocs.io/en/latest/format.html>`_
-for how to write docs that use this extension, and the `user guide <https://numpydoc.readthedocs.io>`_
-
-Numpydoc inserts a hook into Sphinx's autodoc that converts docstrings
-following the Numpy/Scipy format to a form palatable to Sphinx.
+The `numpydoc docstring guide
+<https://numpydoc.readthedocs.io/en/latest/format.html>`_ explains how
+to write docs formatted for this extension, and the `user guide
+<https://numpydoc.readthedocs.io>`_ explains how to use it with Sphinx.
diff --git a/doc/example.py b/doc/example.py
index 425c892..c55d64d 100644
--- a/doc/example.py
+++ b/doc/example.py
@@ -62,6 +62,7 @@ def foo(var1, var2, long_var_name='hi'):
Explanation of return value named `describe`.
out : type
Explanation of `out`.
+ type_without_description
Other Parameters
----------------
diff --git a/doc/format.rst b/doc/format.rst
index d67ddbc..814f301 100644
--- a/doc/format.rst
+++ b/doc/format.rst
@@ -387,6 +387,12 @@ The sections of a function's docstring are:
should not be required to understand it. References are numbered, starting
from one, in the order in which they are cited.
+ .. warning:: **References will break tables**
+
+ Where references like [1] appear in a tables within a numpydoc
+ docstring, the table markup will be broken by numpydoc processing. See
+ `numpydoc issue #130 <https://github.com/numpy/numpydoc/issues/130>`_
+
14. **Examples**
An optional section for examples, using the `doctest
@@ -443,6 +449,13 @@ The sections of a function's docstring are:
``import matplotlib.pyplot as plt``. All other imports, including the
demonstrated function, must be explicit.
+ When matplotlib is imported in the example, the Example code will be
+ wrapped in `matplotlib's Sphinx `plot` directive
+ <http://matplotlib.org/sampledoc/extensions.html>`_. When matplotlib is
+ not explicitly imported, `.. plot::` can be used directly if
+ `matplotlib.sphinxext.plot_directive` is loaded as a Sphinx extension in
+ ``conf.py``.
+
Documenting classes
-------------------
diff --git a/doc/install.rst b/doc/install.rst
index ea19389..260b4ee 100644
--- a/doc/install.rst
+++ b/doc/install.rst
@@ -9,8 +9,8 @@ The extension is available from:
* `numpydoc on GitHub <https://github.com/numpy/numpydoc/>`_
'numpydoc' should be added to the ``extensions`` option in your Sphinx
-``conf.py``.
-
+``conf.py``. (Note that `sphinx.ext.autosummary` will automatically be loaded
+as well.)
Sphinx config options
=====================
@@ -38,6 +38,10 @@ numpydoc_citation_re : str
should be mangled to avoid conflicts due to
duplication across the documentation. Defaults
to ``[\w-]+``.
+numpydoc_use_blockquotes : bool
+ Until version 0.8, parameter definitions were shown as blockquotes, rather
+ than in a definition list. If your styling requires blockquotes, switch
+ this config option to True. This option will be removed in version 0.10.
numpydoc_edit_link : bool
.. deprecated:: edit your HTML template instead
diff --git a/numpydoc/__init__.py b/numpydoc/__init__.py
index 5d64ad7..30dba8f 100644
--- a/numpydoc/__init__.py
+++ b/numpydoc/__init__.py
@@ -2,4 +2,7 @@ from __future__ import division, absolute_import, print_function
__version__ = '0.8.0.dev0'
-from .numpydoc import setup
+
+def setup(app, *args, **kwargs):
+ from .numpydoc import setup
+ return setup(app, *args, **kwargs)
diff --git a/numpydoc/docscrape.py b/numpydoc/docscrape.py
index b1bab1d..6ca6292 100644
--- a/numpydoc/docscrape.py
+++ b/numpydoc/docscrape.py
@@ -13,6 +13,15 @@ import copy
import sys
+def strip_blank_lines(l):
+ "Remove leading and trailing blank lines from a list of lines"
+ while l and not l[0].strip():
+ del l[0]
+ while l and not l[-1].strip():
+ del l[-1]
+ return l
+
+
class Reader(object):
"""A line-based string reader.
@@ -214,6 +223,7 @@ class NumpyDocString(collections.Mapping):
desc = r.read_to_next_unindented_line()
desc = dedent_lines(desc)
+ desc = strip_blank_lines(desc)
params.append((arg_name, arg_type, desc))
@@ -404,7 +414,8 @@ class NumpyDocString(collections.Mapping):
out += ['%s : %s' % (param, param_type)]
else:
out += [param]
- out += self._str_indent(desc)
+ if desc and ''.join(desc).strip():
+ out += self._str_indent(desc)
out += ['']
return out
diff --git a/numpydoc/docscrape_sphinx.py b/numpydoc/docscrape_sphinx.py
index d2bc923..087ddaf 100644
--- a/numpydoc/docscrape_sphinx.py
+++ b/numpydoc/docscrape_sphinx.py
@@ -31,6 +31,7 @@ class SphinxDocString(NumpyDocString):
def load_config(self, config):
self.use_plots = config.get('use_plots', False)
+ self.use_blockquotes = config.get('use_blockquotes', False)
self.class_members_toctree = config.get('class_members_toctree', True)
self.template = config.get('template', None)
if self.template is None:
@@ -66,19 +67,28 @@ class SphinxDocString(NumpyDocString):
return self['Extended Summary'] + ['']
def _str_returns(self, name='Returns'):
+ if self.use_blockquotes:
+ typed_fmt = '**%s** : %s'
+ untyped_fmt = '**%s**'
+ else:
+ typed_fmt = '%s : %s'
+ untyped_fmt = '%s'
+
out = []
if self[name]:
out += self._str_field_list(name)
out += ['']
for param, param_type, desc in self[name]:
if param_type:
- out += self._str_indent(['**%s** : %s' % (param.strip(),
- param_type)])
+ out += self._str_indent([typed_fmt % (param.strip(),
+ param_type)])
else:
- out += self._str_indent([param.strip()])
- if desc:
+ out += self._str_indent([untyped_fmt % param.strip()])
+ if desc and self.use_blockquotes:
out += ['']
- out += self._str_indent(desc, 8)
+ elif not desc:
+ desc = ['..']
+ out += self._str_indent(desc, 8)
out += ['']
return out
@@ -117,7 +127,7 @@ class SphinxDocString(NumpyDocString):
relies on Sphinx's plugin mechanism.
"""
param = param.strip()
- display_param = '**%s**' % param
+ display_param = ('**%s**' if self.use_blockquotes else '%s') % param
if not fake_autosummary:
return display_param, desc
@@ -191,9 +201,12 @@ class SphinxDocString(NumpyDocString):
param_type)])
else:
out += self._str_indent([display_param])
- if desc:
- out += [''] # produces a blockquote, rather than a dt/dd
- out += self._str_indent(desc, 8)
+ if desc and self.use_blockquotes:
+ out += ['']
+ elif not desc:
+ # empty definition
+ desc = ['..']
+ out += self._str_indent(desc, 8)
out += ['']
return out
@@ -262,7 +275,6 @@ class SphinxDocString(NumpyDocString):
out = []
if self[name]:
out += self._str_header(name)
- out += ['']
content = textwrap.dedent("\n".join(self[name])).split("\n")
out += content
out += ['']
@@ -281,6 +293,7 @@ class SphinxDocString(NumpyDocString):
if self['Warnings']:
out = ['.. warning::', '']
out += self._str_indent(self['Warnings'])
+ out += ['']
return out
def _str_index(self):
@@ -297,6 +310,7 @@ class SphinxDocString(NumpyDocString):
out += [' single: %s' % (', '.join(references))]
else:
out += [' %s: %s' % (section, ','.join(references))]
+ out += ['']
return out
def _str_references(self):
diff --git a/numpydoc/numpydoc.py b/numpydoc/numpydoc.py
index c14fb0e..2b259af 100644
--- a/numpydoc/numpydoc.py
+++ b/numpydoc/numpydoc.py
@@ -21,14 +21,19 @@ from __future__ import division, absolute_import, print_function
import sys
import re
import pydoc
-import sphinx
import inspect
import collections
+import hashlib
+
+from docutils.nodes import citation, Text
+import sphinx
+from sphinx.addnodes import pending_xref, desc_content
if sphinx.__version__ < '1.0.1':
raise RuntimeError("Sphinx 1.0.1 or newer is required")
from .docscrape_sphinx import get_doc_object, SphinxDocString
+from . import __version__
if sys.version_info[0] >= 3:
sixu = lambda s: s
@@ -36,9 +41,12 @@ else:
sixu = lambda s: unicode(s, 'unicode_escape')
-def rename_references(app, what, name, obj, options, lines,
- reference_offset=[0]):
- # replace reference numbers so that there are no duplicates
+HASH_LEN = 12
+
+
+def rename_references(app, what, name, obj, options, lines):
+ # decorate reference numbers so that there are no duplicates
+ # these are later undecorated in the doctree, in relabel_references
references = set()
for line in lines:
line = line.strip()
@@ -48,19 +56,51 @@ def rename_references(app, what, name, obj, options, lines,
references.add(m.group(1))
if references:
- for r in references:
- if r.isdigit():
- new_r = sixu("R%d") % (reference_offset[0] + int(r))
- else:
- new_r = sixu("%s%d") % (r, reference_offset[0])
+ # we use a hash to mangle the reference name to avoid invalid names
+ sha = hashlib.sha256()
+ sha.update(name.encode('utf8'))
+ prefix = 'R' + sha.hexdigest()[:HASH_LEN]
+ for r in references:
+ new_r = prefix + '-' + r
for i, line in enumerate(lines):
lines[i] = lines[i].replace(sixu('[%s]_') % r,
sixu('[%s]_') % new_r)
lines[i] = lines[i].replace(sixu('.. [%s]') % r,
sixu('.. [%s]') % new_r)
- reference_offset[0] += len(references)
+
+def _ascend(node, cls):
+ while node and not isinstance(node, cls):
+ node = node.parent
+ return node
+
+
+def relabel_references(app, doc):
+ # Change 'hash-ref' to 'ref' in label text
+ for citation_node in doc.traverse(citation):
+ if _ascend(citation_node, desc_content) is None:
+ # no desc node in ancestry -> not in a docstring
+ # XXX: should we also somehow check it's in a References section?
+ continue
+ label_node = citation_node[0]
+ prefix, _, new_label = label_node[0].astext().partition('-')
+ assert len(prefix) == HASH_LEN + 1
+ new_text = Text(new_label)
+ label_node.replace(label_node[0], new_text)
+
+ for id in citation_node['backrefs']:
+ ref = doc.ids[id]
+ ref_text = ref[0]
+
+ # Sphinx has created pending_xref nodes with [reftext] text.
+ def matching_pending_xref(node):
+ return (isinstance(node, pending_xref) and
+ node[0].astext() == '[%s]' % ref_text)
+
+ for xref_node in ref.parent.traverse(matching_pending_xref):
+ xref_node.replace(xref_node[0], Text('[%s]' % new_text))
+ ref.replace(ref_text, new_text.copy())
DEDUPLICATION_TAG = ' !! processed by numpydoc !!'
@@ -71,6 +111,7 @@ def mangle_docstrings(app, what, name, obj, options, lines):
return
cfg = {'use_plots': app.config.numpydoc_use_plots,
+ 'use_blockquotes': app.config.numpydoc_use_blockquotes,
'show_class_members': app.config.numpydoc_show_class_members,
'show_inherited_class_members':
app.config.numpydoc_show_inherited_class_members,
@@ -137,8 +178,10 @@ def setup(app, get_doc_object_=get_doc_object):
app.connect('autodoc-process-docstring', mangle_docstrings)
app.connect('autodoc-process-signature', mangle_signature)
+ app.connect('doctree-read', relabel_references)
app.add_config_value('numpydoc_edit_link', None, False)
app.add_config_value('numpydoc_use_plots', None, False)
+ app.add_config_value('numpydoc_use_blockquotes', None, False)
app.add_config_value('numpydoc_show_class_members', True, True)
app.add_config_value('numpydoc_show_inherited_class_members', True, True)
app.add_config_value('numpydoc_class_members_toctree', True, True)
@@ -148,7 +191,10 @@ def setup(app, get_doc_object_=get_doc_object):
app.add_domain(NumpyPythonDomain)
app.add_domain(NumpyCDomain)
- metadata = {'parallel_read_safe': True}
+ app.setup_extension('sphinx.ext.autosummary')
+
+ metadata = {'version': __version__,
+ 'parallel_read_safe': True}
return metadata
# ------------------------------------------------------------------------------
diff --git a/setup.py b/setup.py
index a2dc46a..ea42ecd 100644
--- a/setup.py
+++ b/setup.py
@@ -3,18 +3,15 @@ from __future__ import division, print_function
import sys
import os
+import setuptools # may monkeypatch distutils in some versions. # noqa
from distutils.command.sdist import sdist
-import setuptools
from distutils.core import setup
+from numpydoc import __version__ as version
+
if sys.version_info[:2] < (2, 7) or (3, 0) <= sys.version_info[0:2] < (3, 4):
raise RuntimeError("Python version 2.7 or >= 3.4 required.")
-with open('numpydoc/__init__.py') as fid:
- for line in fid:
- if line.startswith('__version__'):
- version = line.strip().split()[-1][1:-1]
- break
def read(fname):
"""Utility function to get README.rst into long_description.
| BUG: Reference de-duplication isn't parallel-safe
Currently Numpydoc is marked as a parallel-safe sphinx plugin, but the renaming of duplicate references in ``rename_references`` is not parallel-safe because ``reference_offset`` will be [0] in each process at the start of the function call.
I'm running into conflicts when building the Astropy docs:
```
/Users/tom/Dropbox/Code/Astropy/astropy/astropy/stats/biweight.py:docstring of astropy.stats.biweight_midcorrelation:70: WARNING: duplicate citation R11, other instance in /Users/tom/Dropbox/Code/Astropy/astropy/docs/modeling/index.rst
/Users/tom/Dropbox/Code/Astropy/astropy/astropy/stats/biweight.py:docstring of astropy.stats.biweight_midcovariance:138: WARNING: duplicate citation R33, other instance in /Users/tom/Dropbox/Code/Astropy/astropy/docs/api/astropy.coordinates.BaseCoordinateFrame.rst
/Users/tom/Dropbox/Code/Astropy/astropy/astropy/stats/biweight.py:docstring of astropy.stats.biweight_midvariance:101: WARNING: duplicate citation R56, other instance in /Users/tom/Dropbox/Code/Astropy/astropy/docs/api/astropy.coordinates.EarthLocation.rst
/Users/tom/Dropbox/Code/Astropy/astropy/astropy/stats/biweight.py:docstring of astropy.stats.biweight_midvariance:103: WARNING: duplicate citation R66, other instance in /Users/tom/Dropbox/Code/Astropy/astropy/docs/api/astropy.coordinates.EarthLocation.rst
/Users/tom/Dropbox/Code/Astropy/astropy/astropy/stats/bayesian_blocks.py:docstring of astropy.stats.FitnessFunc:7: WARNING: Unknown target name: "scargle2012".
/Users/tom/Dropbox/Code/Astropy/astropy/astropy/stats/bayesian_blocks.py:docstring of astropy.stats.FitnessFunc:26: WARNING: Unknown target name: "scargle2012".
docstring of astropy.stats.LombScargle.false_alarm_probability:62: WARNING: duplicate citation R1313, other instance in /Users/tom/Dropbox/Code/Astropy/astropy/docs/api/astropy.coordinates.SkyCoord.rst
/Users/tom/Dropbox/Code/Astropy/astropy/astropy/modeling/polynomial.py:docstring of astropy.modeling.polynomial.SIP:55: WARNING: duplicate citation R11, other instance in /Users/tom/Dropbox/Code/Astropy/astropy/docs/api/astropy.stats.biweight_midcorrelation.rst
/Users/tom/Dropbox/Code/Astropy/astropy/astropy/modeling/functional_models.py:docstring of astropy.modeling.functional_models.AiryDisk2D:91: WARNING: duplicate citation R11, other instance in /Users/tom/Dropbox/Code/Astropy/astropy/docs/api/astropy.stats.biweight_midcorrelation.rst
/Users/tom/Dropbox/Code/Astropy/astropy/astropy/modeling/functional_models.py:docstring of astropy.modeling.functional_models.Gaussian2D:133: WARNING: duplicate citation R33, other instance in /Users/tom/Dropbox/Code/Astropy/astropy/docs/api/astropy.stats.biweight_midcovariance.rst
/Users/tom/Dropbox/Code/Astropy/astropy/astropy/modeling/optimizers.py:docstring of astropy.modeling.optimizers.SLSQP:19: WARNING: duplicate citation R99, other instance in /Users/tom/Dropbox/Code/Astropy/astropy/docs/api/astropy.coordinates.Galactic.rst
/Users/tom/Dropbox/Code/Astropy/astropy/astropy/modeling/optimizers.py:docstring of astropy.modeling.optimizers.Simplex:18: WARNING: duplicate citation R1111, other instance in /Users/tom/Dropbox/Code/Astropy/astropy/docs/api/astropy.stats.LombScargle.rst
``` | numpy/numpydoc | diff --git a/numpydoc/tests/test_docscrape.py b/numpydoc/tests/test_docscrape.py
index 81f914e..2fb4eb5 100644
--- a/numpydoc/tests/test_docscrape.py
+++ b/numpydoc/tests/test_docscrape.py
@@ -1,6 +1,7 @@
# -*- encoding:utf-8 -*-
from __future__ import division, absolute_import, print_function
+import re
import sys
import textwrap
import warnings
@@ -55,7 +56,7 @@ doc_txt = '''\
-------
out : ndarray
The drawn samples, arranged according to `shape`. If the
- shape given is (m,n,...), then the shape of `out` is is
+ shape given is (m,n,...), then the shape of `out` is
(m,n,...,N).
In other words, each entry ``out[i,j,...,:]`` is an N-dimensional
@@ -63,6 +64,7 @@ doc_txt = '''\
list of str
This is not a real return value. It exists to test
anonymous return values.
+ no_description
Other Parameters
----------------
@@ -171,7 +173,7 @@ def test_parameters():
arg, arg_type, desc = doc['Parameters'][1]
assert_equal(arg_type, '(N, N) ndarray')
assert desc[0].startswith('Covariance matrix')
- assert doc['Parameters'][0][-1][-2] == ' (1+2+3)/3'
+ assert doc['Parameters'][0][-1][-1] == ' (1+2+3)/3'
def test_other_parameters():
@@ -183,7 +185,7 @@ def test_other_parameters():
def test_returns():
- assert_equal(len(doc['Returns']), 2)
+ assert_equal(len(doc['Returns']), 3)
arg, arg_type, desc = doc['Returns'][0]
assert_equal(arg, 'out')
assert_equal(arg_type, 'ndarray')
@@ -196,6 +198,11 @@ def test_returns():
assert desc[0].startswith('This is not a real')
assert desc[-1].endswith('anonymous return values.')
+ arg, arg_type, desc = doc['Returns'][2]
+ assert_equal(arg, 'no_description')
+ assert_equal(arg_type, '')
+ assert not ''.join(desc).strip()
+
def test_yields():
section = doc_yields['Yields']
@@ -316,11 +323,19 @@ def test_index():
assert_equal(len(doc['index']['refguide']), 2)
-def non_blank_line_by_line_compare(a, b):
+def _strip_blank_lines(s):
+ "Remove leading, trailing and multiple blank lines"
+ s = re.sub(r'^\s*\n', '', s)
+ s = re.sub(r'\n\s*$', '', s)
+ s = re.sub(r'\n\s*\n', r'\n\n', s)
+ return s
+
+
+def line_by_line_compare(a, b):
a = textwrap.dedent(a)
b = textwrap.dedent(b)
- a = [l.rstrip() for l in a.split('\n') if l.strip()]
- b = [l.rstrip() for l in b.split('\n') if l.strip()]
+ a = [l.rstrip() for l in _strip_blank_lines(a).split('\n')]
+ b = [l.rstrip() for l in _strip_blank_lines(b).split('\n')]
assert_list_equal(a, b)
@@ -328,7 +343,7 @@ def test_str():
# doc_txt has the order of Notes and See Also sections flipped.
# This should be handled automatically, and so, one thing this test does
# is to make sure that See Also precedes Notes in the output.
- non_blank_line_by_line_compare(str(doc),
+ line_by_line_compare(str(doc),
"""numpy.multivariate_normal(mean, cov, shape=None, spam=None)
Draw values from a multivariate normal distribution with specified
@@ -345,7 +360,6 @@ mean : (N,) ndarray
.. math::
(1+2+3)/3
-
cov : (N, N) ndarray
Covariance matrix of the distribution.
shape : tuple of ints
@@ -357,7 +371,7 @@ Returns
-------
out : ndarray
The drawn samples, arranged according to `shape`. If the
- shape given is (m,n,...), then the shape of `out` is is
+ shape given is (m,n,...), then the shape of `out` is
(m,n,...,N).
In other words, each entry ``out[i,j,...,:]`` is an N-dimensional
@@ -365,6 +379,7 @@ out : ndarray
list of str
This is not a real return value. It exists to test
anonymous return values.
+no_description
Other Parameters
----------------
@@ -387,6 +402,7 @@ Certain warnings apply.
See Also
--------
+
`some`_, `other`_, `funcs`_
`otherfunc`_
@@ -438,7 +454,7 @@ standard deviation:
def test_yield_str():
- non_blank_line_by_line_compare(str(doc_yields),
+ line_by_line_compare(str(doc_yields),
"""Test generator
Yields
@@ -455,7 +471,7 @@ int
def test_sphinx_str():
sphinx_doc = SphinxDocString(doc_txt)
- non_blank_line_by_line_compare(str(sphinx_doc),
+ line_by_line_compare(str(sphinx_doc),
"""
.. index:: random
single: random;distributions, random;gauss
@@ -468,56 +484,51 @@ of the one-dimensional normal distribution to higher dimensions.
:Parameters:
- **mean** : (N,) ndarray
-
+ mean : (N,) ndarray
Mean of the N-dimensional distribution.
.. math::
(1+2+3)/3
- **cov** : (N, N) ndarray
-
+ cov : (N, N) ndarray
Covariance matrix of the distribution.
- **shape** : tuple of ints
-
+ shape : tuple of ints
Given a shape of, for example, (m,n,k), m*n*k samples are
generated, and packed in an m-by-n-by-k arrangement. Because
each sample is N-dimensional, the output shape is (m,n,k,N).
:Returns:
- **out** : ndarray
-
+ out : ndarray
The drawn samples, arranged according to `shape`. If the
- shape given is (m,n,...), then the shape of `out` is is
+ shape given is (m,n,...), then the shape of `out` is
(m,n,...,N).
In other words, each entry ``out[i,j,...,:]`` is an N-dimensional
value drawn from the distribution.
list of str
-
This is not a real return value. It exists to test
anonymous return values.
-:Other Parameters:
+ no_description
+ ..
- **spam** : parrot
+:Other Parameters:
+ spam : parrot
A parrot off its mortal coil.
:Raises:
- **RuntimeError**
-
+ RuntimeError
Some error
:Warns:
- **RuntimeWarning**
-
+ RuntimeWarning
Some warning
.. warning::
@@ -580,21 +591,18 @@ standard deviation:
def test_sphinx_yields_str():
sphinx_doc = SphinxDocString(doc_yields_txt)
- non_blank_line_by_line_compare(str(sphinx_doc),
+ line_by_line_compare(str(sphinx_doc),
"""Test generator
:Yields:
- **a** : int
-
+ a : int
The number of apples.
- **b** : int
-
+ b : int
The number of bananas.
int
-
The number of unknowns.
""")
@@ -855,6 +863,46 @@ def test_plot_examples():
assert str(doc).count('plot::') == 1, str(doc)
+def test_use_blockquotes():
+ cfg = dict(use_blockquotes=True)
+ doc = SphinxDocString("""
+ Parameters
+ ----------
+ abc : def
+ ghi
+ jkl
+ mno
+
+ Returns
+ -------
+ ABC : DEF
+ GHI
+ JKL
+ MNO
+ """, config=cfg)
+ line_by_line_compare(str(doc), '''
+ :Parameters:
+
+ **abc** : def
+
+ ghi
+
+ **jkl**
+
+ mno
+
+ :Returns:
+
+ **ABC** : DEF
+
+ GHI
+
+ **JKL**
+
+ MNO
+ ''')
+
+
def test_class_members():
class Dummy(object):
@@ -960,6 +1008,7 @@ class_doc_txt = """
f : callable ``f(t, y, *f_args)``
Aaa.
jac : callable ``jac(t, y, *jac_args)``
+
Bbb.
Attributes
@@ -994,7 +1043,7 @@ class_doc_txt = """
def test_class_members_doc():
doc = ClassDoc(None, class_doc_txt)
- non_blank_line_by_line_compare(str(doc),
+ line_by_line_compare(str(doc),
"""
Foo
@@ -1030,9 +1079,7 @@ def test_class_members_doc():
Methods
-------
a
-
b
-
c
.. index::
@@ -1076,18 +1123,16 @@ def test_class_members_doc_sphinx():
return None
doc = SphinxClassDoc(Foo, class_doc_txt)
- non_blank_line_by_line_compare(str(doc),
+ line_by_line_compare(str(doc),
"""
Foo
:Parameters:
- **f** : callable ``f(t, y, *f_args)``
-
+ f : callable ``f(t, y, *f_args)``
Aaa.
- **jac** : callable ``jac(t, y, *jac_args)``
-
+ jac : callable ``jac(t, y, *jac_args)``
Bbb.
.. rubric:: Examples
@@ -1096,22 +1141,30 @@ def test_class_members_doc_sphinx():
:Attributes:
- **t** : float
+ t : float
Current time.
- **y** : ndarray
+
+ y : ndarray
Current variable values.
* hello
* world
+
:obj:`an_attribute <an_attribute>` : float
Test attribute
- **no_docstring** : str
+
+ no_docstring : str
But a description
- **no_docstring2** : str
+
+ no_docstring2 : str
+ ..
+
:obj:`multiline_sentence <multiline_sentence>`
This is a sentence.
+
:obj:`midword_period <midword_period>`
The sentence for numpy.org.
+
:obj:`no_period <no_period>`
This does not have a period
@@ -1128,22 +1181,19 @@ def test_class_members_doc_sphinx():
def test_templated_sections():
doc = SphinxClassDoc(None, class_doc_txt,
- config={'template': jinja2.Template('{{examples}}{{parameters}}')})
- non_blank_line_by_line_compare(str(doc),
+ config={'template': jinja2.Template('{{examples}}\n{{parameters}}')})
+ line_by_line_compare(str(doc),
"""
.. rubric:: Examples
For usage examples, see `ode`.
-
:Parameters:
- **f** : callable ``f(t, y, *f_args)``
-
+ f : callable ``f(t, y, *f_args)``
Aaa.
- **jac** : callable ``jac(t, y, *jac_args)``
-
+ jac : callable ``jac(t, y, *jac_args)``
Bbb.
""")
| {
"commit_name": "merge_commit",
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 1,
"test_score": 3
},
"num_modified_files": 9
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"sphinx>=1.2.3",
"Jinja2>=2.3",
"nose",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc texlive texlive-latex-extra latexmk"
],
"python": "3.6",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | alabaster==0.7.13
attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work
Babel==2.11.0
certifi==2021.5.30
charset-normalizer==2.0.12
docutils==0.18.1
idna==3.10
imagesize==1.4.1
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
Jinja2==3.0.3
MarkupSafe==2.0.1
more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work
nose==1.3.7
-e git+https://github.com/numpy/numpydoc.git@2f075a613b7066493d05fb28d9851cdd7acd8f2a#egg=numpydoc
packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work
pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
Pygments==2.14.0
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pytest==6.2.4
pytz==2025.2
requests==2.27.1
snowballstemmer==2.2.0
Sphinx==5.3.0
sphinxcontrib-applehelp==1.0.2
sphinxcontrib-devhelp==1.0.2
sphinxcontrib-htmlhelp==2.0.0
sphinxcontrib-jsmath==1.0.1
sphinxcontrib-qthelp==1.0.3
sphinxcontrib-serializinghtml==1.1.5
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
urllib3==1.26.20
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
| name: numpydoc
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=21.4.0=pyhd3eb1b0_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- importlib-metadata=4.8.1=py36h06a4308_0
- importlib_metadata=4.8.1=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- more-itertools=8.12.0=pyhd3eb1b0_0
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=21.3=pyhd3eb1b0_0
- pip=21.2.2=py36h06a4308_0
- pluggy=0.13.1=py36h06a4308_0
- py=1.11.0=pyhd3eb1b0_0
- pyparsing=3.0.4=pyhd3eb1b0_0
- pytest=6.2.4=py36h06a4308_2
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- toml=0.10.2=pyhd3eb1b0_0
- typing_extensions=4.1.1=pyh06a4308_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zipp=3.6.0=pyhd3eb1b0_0
- zlib=1.2.13=h5eee18b_1
- pip:
- alabaster==0.7.13
- babel==2.11.0
- charset-normalizer==2.0.12
- docutils==0.18.1
- idna==3.10
- imagesize==1.4.1
- jinja2==3.0.3
- markupsafe==2.0.1
- nose==1.3.7
- pygments==2.14.0
- pytz==2025.2
- requests==2.27.1
- snowballstemmer==2.2.0
- sphinx==5.3.0
- sphinxcontrib-applehelp==1.0.2
- sphinxcontrib-devhelp==1.0.2
- sphinxcontrib-htmlhelp==2.0.0
- sphinxcontrib-jsmath==1.0.1
- sphinxcontrib-qthelp==1.0.3
- sphinxcontrib-serializinghtml==1.1.5
- urllib3==1.26.20
prefix: /opt/conda/envs/numpydoc
| [
"numpydoc/tests/test_docscrape.py::test_parameters",
"numpydoc/tests/test_docscrape.py::test_str",
"numpydoc/tests/test_docscrape.py::test_sphinx_str",
"numpydoc/tests/test_docscrape.py::test_sphinx_yields_str",
"numpydoc/tests/test_docscrape.py::test_use_blockquotes",
"numpydoc/tests/test_docscrape.py::test_class_members_doc",
"numpydoc/tests/test_docscrape.py::test_class_members_doc_sphinx",
"numpydoc/tests/test_docscrape.py::test_templated_sections"
]
| []
| [
"numpydoc/tests/test_docscrape.py::test_signature",
"numpydoc/tests/test_docscrape.py::test_summary",
"numpydoc/tests/test_docscrape.py::test_extended_summary",
"numpydoc/tests/test_docscrape.py::test_other_parameters",
"numpydoc/tests/test_docscrape.py::test_returns",
"numpydoc/tests/test_docscrape.py::test_yields",
"numpydoc/tests/test_docscrape.py::test_returnyield",
"numpydoc/tests/test_docscrape.py::test_section_twice",
"numpydoc/tests/test_docscrape.py::test_notes",
"numpydoc/tests/test_docscrape.py::test_references",
"numpydoc/tests/test_docscrape.py::test_examples",
"numpydoc/tests/test_docscrape.py::test_index",
"numpydoc/tests/test_docscrape.py::test_yield_str",
"numpydoc/tests/test_docscrape.py::test_parameters_without_extended_description",
"numpydoc/tests/test_docscrape.py::test_escape_stars",
"numpydoc/tests/test_docscrape.py::test_empty_extended_summary",
"numpydoc/tests/test_docscrape.py::test_raises",
"numpydoc/tests/test_docscrape.py::test_warns",
"numpydoc/tests/test_docscrape.py::test_see_also",
"numpydoc/tests/test_docscrape.py::test_see_also_parse_error",
"numpydoc/tests/test_docscrape.py::test_see_also_print",
"numpydoc/tests/test_docscrape.py::test_unknown_section",
"numpydoc/tests/test_docscrape.py::test_empty_first_line",
"numpydoc/tests/test_docscrape.py::test_no_summary",
"numpydoc/tests/test_docscrape.py::test_unicode",
"numpydoc/tests/test_docscrape.py::test_plot_examples",
"numpydoc/tests/test_docscrape.py::test_class_members",
"numpydoc/tests/test_docscrape.py::test_duplicate_signature"
]
| []
| BSD License | 1,833 | [
"README.rst",
"numpydoc/docscrape.py",
"setup.py",
"numpydoc/docscrape_sphinx.py",
"doc/example.py",
"numpydoc/__init__.py",
"doc/format.rst",
"numpydoc/numpydoc.py",
"doc/install.rst"
]
| [
"README.rst",
"numpydoc/docscrape.py",
"setup.py",
"numpydoc/docscrape_sphinx.py",
"doc/example.py",
"numpydoc/__init__.py",
"doc/format.rst",
"numpydoc/numpydoc.py",
"doc/install.rst"
]
|
|
streamlink__streamlink-1302 | 160e34a4f35d201984dbf519254c8b8d15e95340 | 2017-11-01 12:08:26 | e71336f3729148c64b26511b2b41b22fa6d249c9 | diff --git a/docs/ext_argparse.py b/docs/ext_argparse.py
index 06b8cae8..e95b9ab4 100644
--- a/docs/ext_argparse.py
+++ b/docs/ext_argparse.py
@@ -17,10 +17,10 @@ from collections import namedtuple
from textwrap import dedent
from docutils import nodes
-from docutils.parsers.rst import Directive
from docutils.parsers.rst.directives import unchanged
from docutils.statemachine import ViewList
from sphinx.util.nodes import nested_parse_with_titles
+from sphinx.util.compat import Directive
_ArgumentParser = argparse.ArgumentParser
diff --git a/docs/plugin_matrix.rst b/docs/plugin_matrix.rst
index db98da77..44fe7537 100644
--- a/docs/plugin_matrix.rst
+++ b/docs/plugin_matrix.rst
@@ -81,7 +81,8 @@ dogan - teve2.com.tr Yes Yes VOD is supported for teve2
- dreamtv.com.tr
- cnnturk.com
- dreamturk.com.tr
-dogus - ntvspor.net Yes No
+dogus - startv.com.tr Yes No
+ - ntvspor.net
- kralmuzik.com.tr
- ntv.com.tr
- eurostartv.com.tr
@@ -187,7 +188,6 @@ srgssr - srf.ch Yes No Streams are geo-restricted
- rsi.ch
- rtr.ch
ssh101 ssh101.com Yes No
-startv startv.com.tr Yes No
streamable streamable.com - Yes
streamboat streamboat.tv Yes No
streamingvi... [1]_ streamingvid... [2]_ Yes -- RTMP streams requires rtmpdump with
diff --git a/src/streamlink/plugins/canlitv.py b/src/streamlink/plugins/canlitv.py
index 7c56102a..64c73fa3 100644
--- a/src/streamlink/plugins/canlitv.py
+++ b/src/streamlink/plugins/canlitv.py
@@ -5,14 +5,14 @@ from streamlink.plugin.api import http
from streamlink.plugin.api import useragents
from streamlink.stream import HLSStream
-EMBED_URL_1 = "http://www.canlitv.plus/kanallar.php?kanal={0}"
+EMBED_URL_1 = "http://www.canlitv.life/kanallar.php?kanal={0}"
EMBED_URL_2 = "http://www.ecanlitvizle.net/embed.php?kanal={0}"
_m3u8_re = re.compile(r"""file\s*:\s*['"](?P<url>[^"']+)['"]""")
_url_re = re.compile(r"""http(s)?://(?:www\.)?(?P<domain>
- canlitv\.(com|plus)
+ canlitv\.(com|life)
|
- canlitvlive\.(io|co|live|site)
+ canlitvlive\.(co|live)
|
ecanlitvizle\.net
)
@@ -35,7 +35,7 @@ class Canlitv(Plugin):
"User-Agent": useragents.FIREFOX
}
- if domain == "canlitv.plus":
+ if domain == "canlitv.life":
res = http.get(EMBED_URL_1.format(channel), headers=headers)
elif domain == "ecanlitvizle.net":
res = http.get(EMBED_URL_2.format(channel), headers=headers)
@@ -47,9 +47,6 @@ class Canlitv(Plugin):
if url_match:
hls_url = url_match.group("url")
- if domain in ("canlitvlive.live", "canlitvlive.site"):
- hls_url = "http:" + hls_url
-
self.logger.debug("Found URL: {0}".format(hls_url))
try:
diff --git a/src/streamlink/plugins/cinergroup.py b/src/streamlink/plugins/cinergroup.py
index 32625ca4..0e588f0a 100644
--- a/src/streamlink/plugins/cinergroup.py
+++ b/src/streamlink/plugins/cinergroup.py
@@ -16,7 +16,7 @@ class CinerGroup(Plugin):
"""
url_re = re.compile(r"""https?://(?:www.)?
(?:
- showtv.com.tr/canli-yayin(/showtv)?|
+ showtv.com.tr/canli-yayin/showtv|
haberturk.com/canliyayin|
showmax.com.tr/canliyayin|
showturk.com.tr/canli-yayin/showturk|
diff --git a/src/streamlink/plugins/dogan.py b/src/streamlink/plugins/dogan.py
index 90c70ea2..9732e984 100644
--- a/src/streamlink/plugins/dogan.py
+++ b/src/streamlink/plugins/dogan.py
@@ -24,7 +24,7 @@ class Dogan(Plugin):
""", re.VERBOSE)
playerctrl_re = re.compile(r'''<div[^>]*?ng-controller=(?P<quote>["'])(?:Live)?PlayerCtrl(?P=quote).*?>''', re.DOTALL)
data_id_re = re.compile(r'''data-id=(?P<quote>["'])(?P<id>\w+)(?P=quote)''')
- content_id_re = re.compile(r'"content(?:I|i)d", "(\w+)"')
+ content_id_re = re.compile(r'"contentId", "(\w+)"')
content_api = "/actions/content/media/{id}"
new_content_api = "/action/media/{id}"
content_api_schema = validate.Schema({
@@ -32,7 +32,7 @@ class Dogan(Plugin):
"Media": {
"Link": {
"DefaultServiceUrl": validate.url(),
- validate.optional("ServiceUrl"): validate.any(validate.url(), ""),
+ validate.optional("ServiceUrl"): validate.url(),
"SecurePath": validate.text,
}
}
@@ -44,11 +44,6 @@ class Dogan(Plugin):
def _get_content_id(self):
res = http.get(self.url)
- # find the contentId
- content_id_m = self.content_id_re.search(res.text)
- if content_id_m:
- return content_id_m.group(1)
-
# find the PlayerCtrl div
player_ctrl_m = self.playerctrl_re.search(res.text)
if player_ctrl_m:
@@ -58,6 +53,10 @@ class Dogan(Plugin):
if content_id_m:
return content_id_m.group("id")
+ # use the fall back regex
+ content_id_m = self.content_id_re.search(res.text)
+ return content_id_m and content_id_m.group(1)
+
def _get_hls_url(self, content_id):
# make the api url relative to the current domain
if "cnnturk" in self.url or "teve2.com.tr" in self.url:
diff --git a/src/streamlink/plugins/dogus.py b/src/streamlink/plugins/dogus.py
index 4e1f17e1..4d58d33b 100644
--- a/src/streamlink/plugins/dogus.py
+++ b/src/streamlink/plugins/dogus.py
@@ -1,18 +1,23 @@
+from __future__ import print_function
+
import re
from streamlink.plugin import Plugin
from streamlink.plugin.api import http
+from streamlink.plugin.api import validate
+from streamlink.stream import HDSStream
from streamlink.stream import HLSStream
from streamlink.utils import update_scheme
class Dogus(Plugin):
"""
- Support for live streams from Dogus sites include ntv, ntvspor, and kralmuzik
+ Support for live streams from Dogus sites include startv, ntv, ntvspor, and kralmuzik
"""
url_re = re.compile(r"""https?://(?:www.)?
(?:
+ startv.com.tr/canli-yayin|
ntv.com.tr/canli-yayin/ntv|
ntvspor.net/canli-yayin|
kralmuzik.com.tr/tv/kral-tv|
@@ -21,27 +26,61 @@ class Dogus(Plugin):
)/?""", re.VERBOSE)
mobile_url_re = re.compile(r"""(?P<q>["'])(?P<url>(https?:)?//[^'"]*?/live/hls/[^'"]*?\?token=)
(?P<token>[^'"]*?)(?P=q)""", re.VERBOSE)
+ desktop_url_re = re.compile(r"""(?P<q>["'])(?P<url>(https?:)?//[^'"]*?/live/hds/[^'"]*?\?token=)
+ (?P<token>[^'"]*?)(?P=q)""", re.VERBOSE)
token_re = re.compile(r"""token=(?P<q>["'])(?P<token>[^'"]*?)(?P=q)""")
+ hds_schema = validate.Schema(validate.all(
+ {
+ "success": True,
+ "xtra": {
+ "url": validate.url(),
+ "use_akamai": bool
+ }
+ },
+ validate.get("xtra")
+ ))
+ SWF_URL = "http://dygassets.akamaized.net/player2/plugins/flowplayer/flowplayer.httpstreaming-3.2.11.swf"
+
@classmethod
def can_handle_url(cls, url):
return cls.url_re.match(url) is not None
+ def _get_star_streams(self, desktop_url, mobile_url, token=""):
+ if token:
+ self.logger.debug("Opening stream with token: {}", token)
+
+ if mobile_url:
+ for _, s in HLSStream.parse_variant_playlist(self.session,
+ mobile_url + token,
+ headers={"Referer": self.url}).items():
+ yield "live", s
+ if desktop_url:
+ # get the HDS stream URL
+ res = http.get(desktop_url + token)
+ stream_data = http.json(res, schema=self.hds_schema)
+ for _, s in HDSStream.parse_manifest(self.session,
+ stream_data["url"],
+ pvswf=self.SWF_URL,
+ is_akamai=stream_data["use_akamai"],
+ headers={"Referer": self.url}).items():
+ yield "live", s
+
def _get_streams(self):
res = http.get(self.url)
mobile_url_m = self.mobile_url_re.search(res.text)
+ desktop_url_m = self.desktop_url_re.search(res.text)
- mobile_url = mobile_url_m and update_scheme(self.url, mobile_url_m.group("url"))
+ desktop_url = desktop_url_m and update_scheme(self.url, desktop_url_m.group("url"))
+ mobile_url = mobile_url_m and update_scheme(self.url, mobile_url_m.group("url"))
- token = mobile_url_m and mobile_url_m.group("token")
+ token = (desktop_url_m and desktop_url_m.group("token")) or (mobile_url_m and mobile_url_m.group("token"))
if not token:
# if no token is in the url, try to find it else where in the page
token_m = self.token_re.search(res.text)
token = token_m and token_m.group("token")
- return HLSStream.parse_variant_playlist(self.session, mobile_url + token,
- headers={"Referer": self.url})
-
+ return self._get_star_streams(desktop_url, mobile_url, token=token)
__plugin__ = Dogus
diff --git a/src/streamlink/plugins/huya.py b/src/streamlink/plugins/huya.py
index 65aa5cda..8c45ac97 100644
--- a/src/streamlink/plugins/huya.py
+++ b/src/streamlink/plugins/huya.py
@@ -10,7 +10,7 @@ from streamlink.plugin.api import useragents
HUYA_URL = "http://m.huya.com/%s"
_url_re = re.compile(r'http(s)?://(www\.)?huya.com/(?P<channel>[^/]+)', re.VERBOSE)
-_hls_re = re.compile(r'^\s*<video\s+id="html5player-video"\s+src="(?P<url>[^"]+)"', re.MULTILINE)
+_hls_re = re.compile(r'^\s*<source\s+src="(?P<url>[^"]+)"/>', re.MULTILINE)
_hls_schema = validate.Schema(
validate.all(
diff --git a/src/streamlink/plugins/liveme.py b/src/streamlink/plugins/liveme.py
index f7a83b88..b96a52bc 100644
--- a/src/streamlink/plugins/liveme.py
+++ b/src/streamlink/plugins/liveme.py
@@ -1,4 +1,4 @@
-import random
+from __future__ import print_function
import re
from streamlink.plugin import Plugin
@@ -11,7 +11,7 @@ from streamlink.stream import HTTPStream
class LiveMe(Plugin):
url_re = re.compile(r"https?://(www.)?liveme\.com/live\.html\?videoid=(\d+)")
- api_url = "https://live.ksmobile.net/live/queryinfo"
+ api_url = "http://live.ksmobile.net/live/queryinfo?userid=1&videoid={id}"
api_schema = validate.Schema(validate.all({
"status": "200",
"data": {
@@ -26,9 +26,6 @@ class LiveMe(Plugin):
def can_handle_url(cls, url):
return cls.url_re.match(url) is not None
- def _random_t(self, t):
- return "".join(random.choice("ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678") for _ in range(t))
-
def _make_stream(self, url):
if url and url.endswith("flv"):
return HTTPStream(self.session, url)
@@ -40,16 +37,8 @@ class LiveMe(Plugin):
video_id = url_params.get("videoid")
if video_id:
- vali = '{0}l{1}m{2}'.format(self._random_t(4), self._random_t(4), self._random_t(5))
- data = {
- 'userid': 1,
- 'videoid': video_id,
- 'area': '',
- 'h5': 1,
- 'vali': vali
- }
- self.logger.debug("Found Video ID: {0}".format(video_id))
- res = http.post(self.api_url, data=data)
+ self.logger.debug("Found Video ID: {}", video_id)
+ res = http.get(self.api_url.format(id=video_id))
data = http.json(res, schema=self.api_schema)
hls = self._make_stream(data["video_info"]["hlsvideosource"])
video = self._make_stream(data["video_info"]["videosource"])
diff --git a/src/streamlink/plugins/pandatv.py b/src/streamlink/plugins/pandatv.py
index ab8de87d..324b1e76 100644
--- a/src/streamlink/plugins/pandatv.py
+++ b/src/streamlink/plugins/pandatv.py
@@ -1,27 +1,24 @@
+"""Plugin for panda.tv by Fat Deer"""
+
import re
import types
import time
import json
-from streamlink.compat import quote
from streamlink.plugin import Plugin
from streamlink.plugin.api import http, validate
from streamlink.stream import HTTPStream
-ROOM_API = "https://www.panda.tv/api_room_v3?token=&hostid={0}&roomid={1}&roomkey={2}&_={3}¶m={4}&time={5}&sign={6}"
-ROOM_API_V2 = "https://www.panda.tv/api_room_v2?roomid={0}&_={1}"
-SD_URL_PATTERN = "https://pl{0}.live.panda.tv/live_panda/{1}.flv?sign={2}&ts={3}&rid={4}"
-HD_URL_PATTERN = "https://pl{0}.live.panda.tv/live_panda/{1}_mid.flv?sign={2}&ts={3}&rid={4}"
-OD_URL_PATTERN = "https://pl{0}.live.panda.tv/live_panda/{1}_small.flv?sign={2}&ts={3}&rid={4}"
+ROOM_API = "http://www.panda.tv/api_room_v3?roomid={0}&roomkey={1}&_={2}"
+ROOM_API_V2 = "http://www.panda.tv/api_room_v2?roomid={0}&_={1}"
+SD_URL_PATTERN = "http://pl{0}.live.panda.tv/live_panda/{1}.flv?sign={2}&ts={3}&rid={4}"
+HD_URL_PATTERN = "http://pl{0}.live.panda.tv/live_panda/{1}_mid.flv?sign={2}&ts={3}&rid={4}"
+OD_URL_PATTERN = "http://pl{0}.live.panda.tv/live_panda/{1}_small.flv?sign={2}&ts={3}&rid={4}"
_url_re = re.compile(r"http(s)?://(\w+.)?panda.tv/(?P<channel>[^/&?]+)")
_room_id_re = re.compile(r'data-room-id="(\d+)"')
_status_re = re.compile(r'"status"\s*:\s*"(\d+)"\s*,\s*"display_type"')
_room_key_re = re.compile(r'"room_key"\s*:\s*"(.+?)"')
-_hostid_re = re.compile(r'\\"hostid\\"\s*:\s*\\"(.+?)\\"')
-_param_re = re.compile(r'"param"\s*:\s*"(.+?)"\s*,\s*"time"')
-_time_re = re.compile(r'"time"\s*:\s*(\d+)')
-_sign_re = re.compile(r'"sign"\s*:\s*"(.+?)"')
_sd_re = re.compile(r'"SD"\s*:\s*"(\d+)"')
_hd_re = re.compile(r'"HD"\s*:\s*"(\d+)"')
_od_re = re.compile(r'"OD"\s*:\s*"(\d+)"')
@@ -47,7 +44,7 @@ _room_schema = validate.Schema(
class Pandatv(Plugin):
@classmethod
- def can_handle_url(cls, url):
+ def can_handle_url(self, url):
return _url_re.match(url)
def _get_streams(self):
@@ -67,10 +64,6 @@ class Pandatv(Plugin):
try:
status = _status_re.search(res.text).group(1)
room_key = _room_key_re.search(res.text).group(1)
- hostid = _hostid_re.search(res.text).group(1)
- param = _param_re.search(res.text).group(1)
- tt = _time_re.search(res.text).group(1)
- sign = _sign_re.search(res.text).group(1)
sd = _sd_re.search(res.text).group(1)
hd = _hd_re.search(res.text).group(1)
od = _od_re.search(res.text).group(1)
@@ -83,9 +76,7 @@ class Pandatv(Plugin):
return
ts = int(time.time())
- param = param.replace("\\", "")
- param = quote(param)
- url = ROOM_API.format(hostid, channel, room_key, ts, param, tt, sign)
+ url = ROOM_API.format(channel, room_key, ts)
room = http.get(url)
data = http.json(room, schema=_room_schema)
if not isinstance(data, dict):
@@ -104,24 +95,17 @@ class Pandatv(Plugin):
self.logger.info("Please Check PandaTV Room API")
return
+ plflag0 = plflag.split('_')[1]
+ if plflag0 != '3':
+ plflag1 = '4'
+ else:
+ plflag1 = '3'
+
plflag_list = json.loads(plflag_list)
- backup = plflag_list["backup"]
rid = plflag_list["auth"]["rid"]
sign = plflag_list["auth"]["sign"]
ts = plflag_list["auth"]["time"]
- backup.append(plflag)
- plflag0 = backup
- plflag0 = [i.split('_')[1] for i in plflag0]
-
- # let wangsu cdn priority, flag can see here in "H5PLAYER_CDN_LINES":
- # https://www.panda.tv/cmstatic/global-config.js
- lines = ["3", "4"]
- try:
- plflag1 = [i for i in plflag0 if i in lines][0]
- except IndexError:
- plflag1 = plflag0[0]
-
if sd == '1':
streams['ehq'] = HTTPStream(self.session, SD_URL_PATTERN.format(plflag1, room_key, sign, ts, rid))
diff --git a/src/streamlink/plugins/startv.py b/src/streamlink/plugins/startv.py
deleted file mode 100644
index b136c6b0..00000000
--- a/src/streamlink/plugins/startv.py
+++ /dev/null
@@ -1,28 +0,0 @@
-from __future__ import print_function
-import re
-
-from streamlink import streams
-from streamlink.plugin import Plugin
-from streamlink.plugin.api import http
-from streamlink.plugin.api import validate
-
-
-class StarTV(Plugin):
- url_re = re.compile(r"https?://(?:www\.)?startv.com.tr/canli-yayin")
- iframe_re = re.compile(r'frame .*?src="(https://www.youtube.com/[^"]+)"')
-
- @classmethod
- def can_handle_url(cls, url):
- return cls.url_re.match(url) is not None
-
- def _get_streams(self):
- res = http.get(self.url)
- m = self.iframe_re.search(res.text)
-
- yt_url = m and m.group(1)
- if yt_url:
- self.logger.debug("Deferring to YouTube plugin with URL: {0}".format(yt_url))
- return streams(yt_url)
-
-
-__plugin__ = StarTV
diff --git a/src/streamlink/plugins/telefe.py b/src/streamlink/plugins/telefe.py
index 93d9165b..fd19b63a 100644
--- a/src/streamlink/plugins/telefe.py
+++ b/src/streamlink/plugins/telefe.py
@@ -45,4 +45,4 @@ class Telefe(Plugin):
if video_url_found_http:
yield "http", HTTPStream(self.session, video_url_found_http)
-__plugin__ = Telefe
+__plugin__ = Telefe
\ No newline at end of file
diff --git a/src/streamlink/plugins/turkuvaz.py b/src/streamlink/plugins/turkuvaz.py
index 3d54adfd..8a14ebbe 100644
--- a/src/streamlink/plugins/turkuvaz.py
+++ b/src/streamlink/plugins/turkuvaz.py
@@ -2,7 +2,6 @@ import random
import re
from streamlink.plugin import Plugin
from streamlink.plugin.api import http
-from streamlink.plugin.api import useragents
from streamlink.plugin.api import validate
from streamlink.stream import HLSStream
@@ -13,10 +12,10 @@ class Turkuvaz(Plugin):
"""
_url_re = re.compile(r"""https?://(?:www.)?
- (?:(atvavrupa).tv|
- (atv|a2tv|ahaber|aspor|minikago|minikacocuk|anews).com.tr)
- /webtv/(live-broadcast|canli-yayin)""",
- re.VERBOSE)
+ (?:
+ (atv|a2tv|ahaber|aspor|minikago|minikacocuk).com.tr/webtv/canli-yayin|
+ (atvavrupa).tv/webtv/videoizle/atv_avrupa/canli_yayin
+ )""", re.VERBOSE)
_hls_url = "http://trkvz-live.ercdn.net/{channel}/{channel}.m3u8"
_token_url = "http://videotoken.tmgrup.com.tr/webtv/secure"
_token_schema = validate.Schema(validate.all(
@@ -37,19 +36,15 @@ class Turkuvaz(Plugin):
# remap the domain to channel
channel = {"atv": "atvhd",
"ahaber": "ahaberhd",
- "aspor": "asporhd",
- "anews": "anewshd",
- "minikacocuk": "minikagococuk"}.get(domain, domain)
+ "aspor": "asporhd"}.get(domain, domain)
+
hls_url = self._hls_url.format(channel=channel)
# get the secure HLS URL
res = http.get(self._token_url,
- params="url={0}".format(hls_url),
- headers={"Referer": self.url,
- "User-Agent": useragents.CHROME})
-
+ params={"url": hls_url},
+ headers={"Referer": self.url})
secure_hls_url = http.json(res, schema=self._token_schema)
- self.logger.debug("Found HLS URL: {0}".format(secure_hls_url))
return HLSStream.parse_variant_playlist(self.session, secure_hls_url)
diff --git a/src/streamlink/plugins/tvcatchup.py b/src/streamlink/plugins/tvcatchup.py
index 25018fdf..ca6a60d2 100644
--- a/src/streamlink/plugins/tvcatchup.py
+++ b/src/streamlink/plugins/tvcatchup.py
@@ -6,7 +6,7 @@ from streamlink.stream import HLSStream
USER_AGENT = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"
_url_re = re.compile(r"http://(?:www\.)?tvcatchup.com/watch/\w+")
-_stream_re = re.compile(r'''(?P<q>["'])(?P<stream_url>https?://.*m3u8\?.*clientKey=.*?)(?P=q)''')
+_stream_re = re.compile(r'''source.*?(?P<q>["'])(?P<stream_url>https?://.*m3u8\?.*clientKey=.*?)(?P=q)''')
class TVCatchup(Plugin):
diff --git a/src/streamlink/plugins/webcast_india_gov.py b/src/streamlink/plugins/webcast_india_gov.py
index 40b988cf..4069fb09 100644
--- a/src/streamlink/plugins/webcast_india_gov.py
+++ b/src/streamlink/plugins/webcast_india_gov.py
@@ -26,4 +26,4 @@ class WebcastIndiaGov(Plugin):
except:
self.logger.error("The requested channel is unavailable.")
-__plugin__ = WebcastIndiaGov
+__plugin__ = WebcastIndiaGov
\ No newline at end of file
diff --git a/src/streamlink/plugins/zattoo.py b/src/streamlink/plugins/zattoo.py
index 37e6e2bd..966500eb 100644
--- a/src/streamlink/plugins/zattoo.py
+++ b/src/streamlink/plugins/zattoo.py
@@ -57,7 +57,7 @@ class Zattoo(Plugin):
self._session_attributes = Cache(filename='plugin-cache.json', key_prefix='zattoo:attributes')
self._authed = self._session_attributes.get('beaker.session.id') and self._session_attributes.get('pzuid') and self._session_attributes.get('power_guide_hash')
self._uuid = self._session_attributes.get('uuid')
- self._expires = self._session_attributes.get('expires', 946684800)
+ self._expires = self._session_attributes.get('expires')
self.base_url = 'https://{0}'.format(Zattoo._url_re.match(url).group('base_url'))
self.headers = {
| tvcatchup plugin broken
tvcatchup.com/watch/dave
they encoded their source with base64
```
function b64DecodeUnicode(str) {
// Going backwards: from bytestream, to percent-encoding, to original string.
return decodeURIComponent(atob(str).split('').map(function(c) {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
}
var a7b5b2a9d1f72b8d2202fc725e95a9b58 = "aHR0cHM6Ly9zMTQ3LmNkbi50dmNhdGNodXAuY29tL3BzaGlmdF9zZXNzX2VjMGNkNTBhODM1ODkvZGF2ZV9hZHAubTN1OD9jbGllbnRLZXk9MTk5MzhiODkxYTRmN2UzZjZlNTNjMWU1ZTFmZjhhYmMtTVRVd056QTJNRE0wT0E9PSZkZXZpY2U9d2ViJmNoYW5uZWxpZD0yMCZjaGFubmVsPTIwJmVhPVRXOTZhV3hzWVM4MUxqQWdLRmRw";
jwplayer('playerrpKPIEPXXyLT').setup({
file: b64DecodeUnicode(a7b5b2a9d1f72b8d2202fc725e95a9b58),
width: '100%',
//height: '480',
aspectratio: '16:9',
autostart: 'true',
stretching: 'exactfit',
cast: {}
});
``` | streamlink/streamlink | diff --git a/tests/test_plugin_canlitv.py b/tests/test_plugin_canlitv.py
index 58041011..0c5c69c4 100644
--- a/tests/test_plugin_canlitv.py
+++ b/tests/test_plugin_canlitv.py
@@ -20,22 +20,13 @@ class TestPluginCanlitv(unittest.TestCase):
def test_can_handle_url(self):
# should match
- self.assertTrue(Canlitv.can_handle_url("http://www.canlitv.plus/channel"))
self.assertTrue(Canlitv.can_handle_url("http://www.canlitv.com/channel"))
+ self.assertTrue(Canlitv.can_handle_url("http://www.canlitv.life/channel"))
self.assertTrue(Canlitv.can_handle_url("http://www.canlitvlive.co/izle/channel.html"))
self.assertTrue(Canlitv.can_handle_url("http://www.canlitvlive.live/izle/channel.html"))
- self.assertTrue(Canlitv.can_handle_url("http://www.canlitvlive.io/izle/channel.html"))
- self.assertTrue(Canlitv.can_handle_url("http://www.canlitvlive.site/izle/channel.html"))
self.assertTrue(Canlitv.can_handle_url("http://www.ecanlitvizle.net/channel/"))
self.assertTrue(Canlitv.can_handle_url("http://www.ecanlitvizle.net/onizleme.php?kanal=channel"))
self.assertTrue(Canlitv.can_handle_url("http://www.ecanlitvizle.net/tv.php?kanal=channel"))
# shouldn't match
self.assertFalse(Canlitv.can_handle_url("http://www.canlitv.com"))
- self.assertFalse(Canlitv.can_handle_url("http://www.canlitv.plus"))
self.assertFalse(Canlitv.can_handle_url("http://www.ecanlitvizle.net"))
- self.assertFalse(Canlitv.can_handle_url("http://www.canlitvlive.co"))
- self.assertFalse(Canlitv.can_handle_url("http://www.canlitvlive.live"))
- self.assertFalse(Canlitv.can_handle_url("http://www.canlitvlive.io"))
- self.assertFalse(Canlitv.can_handle_url("http://www.canlitvlive.site"))
- self.assertFalse(Canlitv.can_handle_url("http://www.ecanlitvizle.net"))
-
diff --git a/tests/test_plugin_eltrecetv.py b/tests/test_plugin_eltrecetv.py
index 83485bca..7c016d6a 100644
--- a/tests/test_plugin_eltrecetv.py
+++ b/tests/test_plugin_eltrecetv.py
@@ -12,4 +12,4 @@ class TestPluginElTreceTV(unittest.TestCase):
# shouldn't match
self.assertFalse(ElTreceTV.can_handle_url("http://eltrecetv.com.ar/"))
- self.assertFalse(ElTreceTV.can_handle_url("https://www.youtube.com/c/eltrece"))
+ self.assertFalse(ElTreceTV.can_handle_url("https://www.youtube.com/c/eltrece"))
\ No newline at end of file
diff --git a/tests/test_plugin_telefe.py b/tests/test_plugin_telefe.py
index 5d1d8492..d8ae58dc 100644
--- a/tests/test_plugin_telefe.py
+++ b/tests/test_plugin_telefe.py
@@ -13,4 +13,4 @@ class TestPluginTelefe(unittest.TestCase):
# shouldn't match
self.assertFalse(Telefe.can_handle_url("http://telefe.com/"))
self.assertFalse(Telefe.can_handle_url("http://www.telefeinternacional.com.ar/"))
- self.assertFalse(Telefe.can_handle_url("http://marketing.telefe.com/"))
+ self.assertFalse(Telefe.can_handle_url("http://marketing.telefe.com/"))
\ No newline at end of file
diff --git a/tests/test_webcast_india_gov.py b/tests/test_webcast_india_gov.py
index 3cc4b500..1790c127 100644
--- a/tests/test_webcast_india_gov.py
+++ b/tests/test_webcast_india_gov.py
@@ -13,4 +13,4 @@ class TestPluginWebcastIndiaGov(unittest.TestCase):
# shouldn't match
self.assertFalse(WebcastIndiaGov.can_handle_url("http://meity.gov.in/"))
self.assertFalse(WebcastIndiaGov.can_handle_url("http://www.nic.in/"))
- self.assertFalse(WebcastIndiaGov.can_handle_url("http://digitalindiaawards.gov.in/"))
+ self.assertFalse(WebcastIndiaGov.can_handle_url("http://digitalindiaawards.gov.in/"))
\ No newline at end of file
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_removed_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 2,
"test_score": 3
},
"num_modified_files": 14
} | 0.8 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-cov"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": [
"dev-requirements.txt",
"docs-requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | alabaster==0.7.16
babel==2.17.0
certifi==2025.1.31
charset-normalizer==3.4.1
codecov==2.1.13
coverage==7.8.0
distlib==0.3.9
docutils==0.21.2
exceptiongroup==1.2.2
idna==3.10
imagesize==1.4.1
iniconfig==2.1.0
iso-639==0.4.5
iso3166==2.1.1
Jinja2==3.1.6
MarkupSafe==3.0.2
mock==5.2.0
packaging==24.2
pluggy==1.5.0
pycryptodome==3.22.0
Pygments==2.19.1
pynsist==2.8
PySocks==1.7.1
pytest==8.3.5
pytest-cov==6.0.0
requests==2.32.3
requests_download==0.1.2
six==1.17.0
snowballstemmer==2.2.0
Sphinx==1.6.7
sphinxcontrib-serializinghtml==2.0.0
sphinxcontrib-websupport==1.2.4
-e git+https://github.com/streamlink/streamlink.git@160e34a4f35d201984dbf519254c8b8d15e95340#egg=streamlink
tomli==2.2.1
urllib3==2.3.0
websocket-client==1.8.0
yarg==0.1.10
| name: streamlink
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- alabaster==0.7.16
- babel==2.17.0
- certifi==2025.1.31
- charset-normalizer==3.4.1
- codecov==2.1.13
- coverage==7.8.0
- distlib==0.3.9
- docutils==0.21.2
- exceptiongroup==1.2.2
- idna==3.10
- imagesize==1.4.1
- iniconfig==2.1.0
- iso-639==0.4.5
- iso3166==2.1.1
- jinja2==3.1.6
- markupsafe==3.0.2
- mock==5.2.0
- packaging==24.2
- pluggy==1.5.0
- pycryptodome==3.22.0
- pygments==2.19.1
- pynsist==2.8
- pysocks==1.7.1
- pytest==8.3.5
- pytest-cov==6.0.0
- requests==2.32.3
- requests-download==0.1.2
- six==1.17.0
- snowballstemmer==2.2.0
- sphinx==1.6.7
- sphinxcontrib-serializinghtml==2.0.0
- sphinxcontrib-websupport==1.2.4
- tomli==2.2.1
- urllib3==2.3.0
- websocket-client==1.8.0
- yarg==0.1.10
prefix: /opt/conda/envs/streamlink
| [
"tests/test_plugin_canlitv.py::TestPluginCanlitv::test_can_handle_url"
]
| []
| [
"tests/test_plugin_canlitv.py::TestPluginCanlitv::test_m3u8_re",
"tests/test_plugin_eltrecetv.py::TestPluginElTreceTV::test_can_handle_url",
"tests/test_plugin_telefe.py::TestPluginTelefe::test_can_handle_url",
"tests/test_webcast_india_gov.py::TestPluginWebcastIndiaGov::test_can_handle_url"
]
| []
| BSD 2-Clause "Simplified" License | 1,834 | [
"src/streamlink/plugins/telefe.py",
"src/streamlink/plugins/pandatv.py",
"docs/plugin_matrix.rst",
"src/streamlink/plugins/liveme.py",
"src/streamlink/plugins/canlitv.py",
"src/streamlink/plugins/dogan.py",
"src/streamlink/plugins/turkuvaz.py",
"src/streamlink/plugins/startv.py",
"src/streamlink/plugins/tvcatchup.py",
"src/streamlink/plugins/dogus.py",
"src/streamlink/plugins/cinergroup.py",
"src/streamlink/plugins/webcast_india_gov.py",
"src/streamlink/plugins/zattoo.py",
"docs/ext_argparse.py",
"src/streamlink/plugins/huya.py"
]
| [
"src/streamlink/plugins/telefe.py",
"src/streamlink/plugins/pandatv.py",
"docs/plugin_matrix.rst",
"src/streamlink/plugins/liveme.py",
"src/streamlink/plugins/canlitv.py",
"src/streamlink/plugins/dogan.py",
"src/streamlink/plugins/turkuvaz.py",
"src/streamlink/plugins/startv.py",
"src/streamlink/plugins/tvcatchup.py",
"src/streamlink/plugins/dogus.py",
"src/streamlink/plugins/cinergroup.py",
"src/streamlink/plugins/webcast_india_gov.py",
"src/streamlink/plugins/zattoo.py",
"docs/ext_argparse.py",
"src/streamlink/plugins/huya.py"
]
|
|
oasis-open__cti-python-stix2-97 | 07a5d3a98ea49f4c343d26f04810bf305c052c8a | 2017-11-01 16:53:30 | ef6dade6f6773edd14aa16a2e4566e50bf74cbb4 | diff --git a/stix2/sources/memory.py b/stix2/sources/memory.py
index 2d1705d..4d3943b 100644
--- a/stix2/sources/memory.py
+++ b/stix2/sources/memory.py
@@ -164,7 +164,7 @@ class MemorySink(DataSink):
if not os.path.exists(os.path.dirname(file_path)):
os.makedirs(os.path.dirname(file_path))
with open(file_path, "w") as f:
- f.write(str(Bundle(self._data.values(), allow_custom=allow_custom)))
+ f.write(str(Bundle(list(self._data.values()), allow_custom=allow_custom)))
save_to_file.__doc__ = MemoryStore.save_to_file.__doc__
| Add tests for Memory Data Stores, Sources, Sinks
From #58 | oasis-open/cti-python-stix2 | diff --git a/stix2/test/test_memory.py b/stix2/test/test_memory.py
index 0603bf7..7a00029 100644
--- a/stix2/test/test_memory.py
+++ b/stix2/test/test_memory.py
@@ -1,3 +1,6 @@
+import os
+import shutil
+
import pytest
from stix2 import (Bundle, Campaign, CustomObject, Filter, MemorySource,
@@ -166,6 +169,22 @@ def test_memory_store_query_multiple_filters(mem_store):
assert len(resp) == 1
+def test_memory_store_save_load_file(mem_store):
+ filename = 'memory_test/mem_store.json'
+ mem_store.save_to_file(filename)
+ contents = open(os.path.abspath(filename)).read()
+
+ assert '"id": "indicator--d81f86b9-975b-bc0b-775e-810c5ad45a4f",' in contents
+ assert '"id": "indicator--d81f86b8-975b-bc0b-775e-810c5ad45a4f",' in contents
+
+ mem_store2 = MemoryStore()
+ mem_store2.load_from_file(filename)
+ assert mem_store2.get("indicator--d81f86b8-975b-bc0b-775e-810c5ad45a4f")
+ assert mem_store2.get("indicator--d81f86b9-975b-bc0b-775e-810c5ad45a4f")
+
+ shutil.rmtree(os.path.dirname(filename))
+
+
def test_memory_store_add_stix_object_str(mem_store):
# add stix object string
camp_id = "campaign--111111b6-1112-4fb0-111b-b111107ca70a"
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_issue_reference"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 2,
"test_score": 0
},
"num_modified_files": 1
} | 0.3 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-cov",
"coverage"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.6",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | alabaster==0.7.13
antlr4-python3-runtime==4.9.3
async-generator==1.10
attrs==22.2.0
Babel==2.11.0
bleach==4.1.0
bump2version==1.0.1
bumpversion==0.6.0
certifi==2021.5.30
cfgv==3.3.1
charset-normalizer==2.0.12
coverage==6.2
decorator==5.1.1
defusedxml==0.7.1
distlib==0.3.9
docutils==0.18.1
entrypoints==0.4
filelock==3.4.1
identify==2.4.4
idna==3.10
imagesize==1.4.1
importlib-metadata==4.8.3
importlib-resources==5.2.3
iniconfig==1.1.1
ipython-genutils==0.2.0
Jinja2==3.0.3
jsonschema==3.2.0
jupyter-client==7.1.2
jupyter-core==4.9.2
jupyterlab-pygments==0.1.2
MarkupSafe==2.0.1
mistune==0.8.4
nbclient==0.5.9
nbconvert==6.0.7
nbformat==5.1.3
nbsphinx==0.8.8
nest-asyncio==1.6.0
nodeenv==1.6.0
packaging==21.3
pandocfilters==1.5.1
platformdirs==2.4.0
pluggy==1.0.0
pre-commit==2.17.0
py==1.11.0
Pygments==2.14.0
pyparsing==3.1.4
pyrsistent==0.18.0
pytest==7.0.1
pytest-cov==4.0.0
python-dateutil==2.9.0.post0
pytz==2025.2
PyYAML==6.0.1
pyzmq==25.1.2
requests==2.27.1
simplejson==3.20.1
six==1.17.0
snowballstemmer==2.2.0
Sphinx==5.3.0
sphinx-prompt==1.5.0
sphinxcontrib-applehelp==1.0.2
sphinxcontrib-devhelp==1.0.2
sphinxcontrib-htmlhelp==2.0.0
sphinxcontrib-jsmath==1.0.1
sphinxcontrib-qthelp==1.0.3
sphinxcontrib-serializinghtml==1.1.5
-e git+https://github.com/oasis-open/cti-python-stix2.git@07a5d3a98ea49f4c343d26f04810bf305c052c8a#egg=stix2
stix2-patterns==2.0.0
taxii2-client==2.3.0
testpath==0.6.0
toml==0.10.2
tomli==1.2.3
tornado==6.1
tox==3.28.0
traitlets==4.3.3
typing_extensions==4.1.1
urllib3==1.26.20
virtualenv==20.16.2
webencodings==0.5.1
zipp==3.6.0
| name: cti-python-stix2
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- alabaster==0.7.13
- antlr4-python3-runtime==4.9.3
- async-generator==1.10
- attrs==22.2.0
- babel==2.11.0
- bleach==4.1.0
- bump2version==1.0.1
- bumpversion==0.6.0
- cfgv==3.3.1
- charset-normalizer==2.0.12
- coverage==6.2
- decorator==5.1.1
- defusedxml==0.7.1
- distlib==0.3.9
- docutils==0.18.1
- entrypoints==0.4
- filelock==3.4.1
- identify==2.4.4
- idna==3.10
- imagesize==1.4.1
- importlib-metadata==4.8.3
- importlib-resources==5.2.3
- iniconfig==1.1.1
- ipython-genutils==0.2.0
- jinja2==3.0.3
- jsonschema==3.2.0
- jupyter-client==7.1.2
- jupyter-core==4.9.2
- jupyterlab-pygments==0.1.2
- markupsafe==2.0.1
- mistune==0.8.4
- nbclient==0.5.9
- nbconvert==6.0.7
- nbformat==5.1.3
- nbsphinx==0.8.8
- nest-asyncio==1.6.0
- nodeenv==1.6.0
- packaging==21.3
- pandocfilters==1.5.1
- platformdirs==2.4.0
- pluggy==1.0.0
- pre-commit==2.17.0
- py==1.11.0
- pygments==2.14.0
- pyparsing==3.1.4
- pyrsistent==0.18.0
- pytest==7.0.1
- pytest-cov==4.0.0
- python-dateutil==2.9.0.post0
- pytz==2025.2
- pyyaml==6.0.1
- pyzmq==25.1.2
- requests==2.27.1
- simplejson==3.20.1
- six==1.17.0
- snowballstemmer==2.2.0
- sphinx==5.3.0
- sphinx-prompt==1.5.0
- sphinxcontrib-applehelp==1.0.2
- sphinxcontrib-devhelp==1.0.2
- sphinxcontrib-htmlhelp==2.0.0
- sphinxcontrib-jsmath==1.0.1
- sphinxcontrib-qthelp==1.0.3
- sphinxcontrib-serializinghtml==1.1.5
- stix2-patterns==2.0.0
- taxii2-client==2.3.0
- testpath==0.6.0
- toml==0.10.2
- tomli==1.2.3
- tornado==6.1
- tox==3.28.0
- traitlets==4.3.3
- typing-extensions==4.1.1
- urllib3==1.26.20
- virtualenv==20.16.2
- webencodings==0.5.1
- zipp==3.6.0
prefix: /opt/conda/envs/cti-python-stix2
| [
"stix2/test/test_memory.py::test_memory_store_save_load_file"
]
| []
| [
"stix2/test/test_memory.py::test_memory_source_get",
"stix2/test/test_memory.py::test_memory_source_get_nonexistant_object",
"stix2/test/test_memory.py::test_memory_store_all_versions",
"stix2/test/test_memory.py::test_memory_store_query",
"stix2/test/test_memory.py::test_memory_store_query_single_filter",
"stix2/test/test_memory.py::test_memory_store_query_empty_query",
"stix2/test/test_memory.py::test_memory_store_query_multiple_filters",
"stix2/test/test_memory.py::test_memory_store_add_stix_object_str",
"stix2/test/test_memory.py::test_memory_store_add_stix_bundle_str",
"stix2/test/test_memory.py::test_memory_store_add_invalid_object",
"stix2/test/test_memory.py::test_memory_store_object_with_custom_property",
"stix2/test/test_memory.py::test_memory_store_object_with_custom_property_in_bundle",
"stix2/test/test_memory.py::test_memory_store_custom_object"
]
| []
| BSD 3-Clause "New" or "Revised" License | 1,835 | [
"stix2/sources/memory.py"
]
| [
"stix2/sources/memory.py"
]
|
|
Unidata__siphon-166 | bd0a6e36c8390d9bb9b072e0a1a95ca4f44ee1d5 | 2017-11-01 19:47:00 | f2e5e13fc49bea29492e6dbf64b2d5110ce72c2b | jrleeman: Should be ready to go @dopplershift - looks like the code coverage again isn't related. | diff --git a/environment.yml b/environment.yml
index b6005bf3..7265b1d7 100755
--- a/environment.yml
+++ b/environment.yml
@@ -13,6 +13,7 @@ dependencies:
- sphinx-gallery
- doc8
- pytest
+ - pytest-catchlog
- pytest-cov
- pytest-flake8
- pytest-runner
diff --git a/siphon/catalog.py b/siphon/catalog.py
index 9fa9f37a..2ef9eb4f 100644
--- a/siphon/catalog.py
+++ b/siphon/catalog.py
@@ -133,6 +133,8 @@ class DatasetCollection(IndexableMapping):
"""Return a string representation of the collection."""
return str(list(self))
+ __repr__ = __str__
+
class TDSCatalog(object):
"""
@@ -237,6 +239,10 @@ class TDSCatalog(object):
self._process_datasets()
+ def __str__(self):
+ """Return a string representation of the catalog name."""
+ return str(self.catalog_name)
+
def _process_dataset(self, element):
catalog_url = ''
if 'urlPath' in element.attrib:
@@ -277,6 +283,8 @@ class TDSCatalog(object):
return TDSCatalog(latest_cat).datasets[0]
raise AttributeError('"latest" not available for this catalog')
+ __repr__ = __str__
+
class CatalogRef(object):
"""
@@ -312,6 +320,10 @@ class CatalogRef(object):
href = element_node.attrib['{http://www.w3.org/1999/xlink}href']
self.href = urljoin(base_url, href)
+ def __str__(self):
+ """Return a string representation of the catalog reference."""
+ return str(self.title)
+
def follow(self):
"""Follow the catalog reference and return a new :class:`TDSCatalog`.
@@ -323,6 +335,8 @@ class CatalogRef(object):
"""
return TDSCatalog(self.href)
+ __repr__ = __str__
+
class Dataset(object):
"""
@@ -371,6 +385,10 @@ class Dataset(object):
log.warning('Must pass along the catalog URL to resolve '
'the latest.xml dataset!')
+ def __str__(self):
+ """Return a string representation of the dataset."""
+ return str(self.name)
+
def resolve_url(self, catalog_url):
"""Resolve the url of the dataset when reading latest.xml.
@@ -576,6 +594,8 @@ class Dataset(object):
except KeyError:
raise ValueError(service + ' is not available for this dataset')
+ __repr__ = __str__
+
class SimpleService(object):
"""Hold information about an access service enabled on a dataset.
| Improve catalog dataset string representation
Currently if we look at the catalog of GOES-16 data:
```python
from datetime import datetime
from siphon.catalog import TDSCatalog
date = datetime.utcnow()
channel = 8
region = 'Mesoscale-2'
cat = TDSCatalog('http://thredds-test.unidata.ucar.edu/thredds/catalog/satellite/goes16/GOES16/'
'{}/Channel{:02d}/{:%Y%m%d}/catalog.xml'.format(region, channel, date))
```
and display the most recent datasets:
```python
list(cat.datasets)[-5:]
```
We get a nice representation:
```
['GOES16_Mesoscale-2_20170920_085559_6.19_2km_16.6N_62.2W.nc4',
'GOES16_Mesoscale-2_20170920_085659_6.19_2km_16.6N_62.2W.nc4',
'GOES16_Mesoscale-2_20170920_085759_6.19_2km_16.6N_62.2W.nc4',
'GOES16_Mesoscale-2_20170920_085859_6.19_2km_16.6N_62.2W.nc4',
'GOES16_Mesoscale-2_20170920_085959_6.19_2km_37.5N_86.3W.nc4']
```
It'd be nice to get that for just printing `cat.datasets[-5:]` as currently we get:
```
[<siphon.catalog.Dataset at 0x116996358>,
<siphon.catalog.Dataset at 0x1169963c8>,
<siphon.catalog.Dataset at 0x116996470>,
<siphon.catalog.Dataset at 0x116996630>,
<siphon.catalog.Dataset at 0x1169964e0>]
``` | Unidata/siphon | diff --git a/siphon/tests/test_catalog.py b/siphon/tests/test_catalog.py
index 9b5497a2..0d850299 100644
--- a/siphon/tests/test_catalog.py
+++ b/siphon/tests/test_catalog.py
@@ -26,6 +26,14 @@ def test_basic():
assert 'Forecast Model Data' in cat.catalog_refs
[email protected]_cassette('thredds-test-toplevel-catalog')
+def test_catalog_representation():
+ """Test string representation of the catalog object."""
+ url = 'http://thredds-test.unidata.ucar.edu/thredds/catalog.xml'
+ cat = TDSCatalog(url)
+ assert str(cat) == 'Unidata THREDDS Data Server'
+
+
@recorder.use_cassette('thredds-test-latest-gfs-0p5')
def test_access():
"""Test catalog parsing of access methods."""
@@ -147,6 +155,16 @@ def test_datasets_str():
"'Latest Collection for NAM CONUS 20km']")
[email protected]_cassette('top_level_20km_rap_catalog')
+def test_datasets_sliced_str():
+ """Test that datasets are printed as expected when sliced."""
+ url = ('http://thredds.ucar.edu/thredds/catalog/grib/NCEP/NAM/'
+ 'CONUS_20km/noaaport/catalog.xml')
+ cat = TDSCatalog(url)
+ assert str(cat.datasets[-2:]) == ('[Best NAM CONUS 20km Time Series, '
+ 'Latest Collection for NAM CONUS 20km]')
+
+
@recorder.use_cassette('top_level_20km_rap_catalog')
def test_datasets_nearest_time():
"""Test getting dataset by time using filenames."""
@@ -266,3 +284,11 @@ def test_tds50_catalogref_follow():
"""Test following a catalog ref url on TDS 5."""
cat = TDSCatalog('http://thredds-test.unidata.ucar.edu/thredds/catalog.xml')
assert len(cat.catalog_refs[0].follow().catalog_refs) == 59
+
+
[email protected]_cassette('top_level_cat')
+def test_catalog_ref_str():
+ """Test that catalog references are properly represented as strings."""
+ url = 'http://thredds.ucar.edu/thredds/catalog.xml'
+ cat = TDSCatalog(url)
+ assert str(cat.catalog_refs[0]) == 'Forecast Model Data'
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 0,
"test_score": 0
},
"num_modified_files": 2
} | 0.6 | {
"env_vars": null,
"env_yml_path": [
"environment.yml"
],
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "environment.yml",
"pip_packages": [
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y libhdf5-serial-dev libnetcdf-dev"
],
"python": "3.6",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | alabaster @ file:///home/conda/feedstock_root/build_artifacts/alabaster_1673645646525/work
argon2-cffi @ file:///home/conda/feedstock_root/build_artifacts/argon2-cffi_1633990451307/work
async_generator @ file:///home/conda/feedstock_root/build_artifacts/async_generator_1722652753231/work
attrs @ file:///home/conda/feedstock_root/build_artifacts/attrs_1671632566681/work
Babel @ file:///home/conda/feedstock_root/build_artifacts/babel_1667688356751/work
backcall @ file:///home/conda/feedstock_root/build_artifacts/backcall_1592338393461/work
backports.functools-lru-cache @ file:///home/conda/feedstock_root/build_artifacts/backports.functools_lru_cache_1702571698061/work
beautifulsoup4 @ file:///home/conda/feedstock_root/build_artifacts/beautifulsoup4_1705564648255/work
bleach @ file:///home/conda/feedstock_root/build_artifacts/bleach_1696630167146/work
brotlipy==0.7.0
Cartopy @ file:///home/conda/feedstock_root/build_artifacts/cartopy_1630680837223/work
certifi==2021.5.30
cffi @ file:///home/conda/feedstock_root/build_artifacts/cffi_1631636256886/work
cftime @ file:///home/conda/feedstock_root/build_artifacts/cftime_1632539733990/work
charset-normalizer @ file:///home/conda/feedstock_root/build_artifacts/charset-normalizer_1661170624537/work
colorama @ file:///home/conda/feedstock_root/build_artifacts/colorama_1655412516417/work
coverage @ file:///home/conda/feedstock_root/build_artifacts/coverage_1633450575846/work
cryptography @ file:///home/conda/feedstock_root/build_artifacts/cryptography_1634230300355/work
cycler @ file:///home/conda/feedstock_root/build_artifacts/cycler_1635519461629/work
decorator @ file:///home/conda/feedstock_root/build_artifacts/decorator_1641555617451/work
defusedxml @ file:///home/conda/feedstock_root/build_artifacts/defusedxml_1615232257335/work
doc8 @ file:///home/conda/feedstock_root/build_artifacts/doc8_1652824562281/work
docutils @ file:///home/conda/feedstock_root/build_artifacts/docutils_1618676244774/work
entrypoints @ file:///home/conda/feedstock_root/build_artifacts/entrypoints_1643888246732/work
flake8 @ file:///home/conda/feedstock_root/build_artifacts/flake8_1659645013175/work
flake8-builtins @ file:///home/conda/feedstock_root/build_artifacts/flake8-builtins_1589815207697/work
flake8-comprehensions @ file:///home/conda/feedstock_root/build_artifacts/flake8-comprehensions_1641851052064/work
flake8-copyright @ file:///home/conda/feedstock_root/build_artifacts/flake8-copyright_1676003148518/work
flake8-docstrings @ file:///home/conda/feedstock_root/build_artifacts/flake8-docstrings_1616176909510/work
flake8-import-order @ file:///home/conda/feedstock_root/build_artifacts/flake8-import-order_1669670271290/work
flake8-mutable==1.2.0
flake8-pep3101==1.3.0
flake8-polyfill==1.0.2
flake8-print @ file:///home/conda/feedstock_root/build_artifacts/flake8-print_1606721773021/work
flake8-quotes @ file:///home/conda/feedstock_root/build_artifacts/flake8-quotes_1707605925191/work
idna @ file:///home/conda/feedstock_root/build_artifacts/idna_1726459485162/work
imagesize @ file:///home/conda/feedstock_root/build_artifacts/imagesize_1656939531508/work
importlib-metadata @ file:///home/conda/feedstock_root/build_artifacts/importlib-metadata_1630267465156/work
importlib-resources==5.4.0
iniconfig @ file:///home/conda/feedstock_root/build_artifacts/iniconfig_1603384189793/work
ipykernel @ file:///home/conda/feedstock_root/build_artifacts/ipykernel_1620912934572/work/dist/ipykernel-5.5.5-py3-none-any.whl
ipyparallel==8.2.1
ipython @ file:///home/conda/feedstock_root/build_artifacts/ipython_1609697613279/work
ipython_genutils @ file:///home/conda/feedstock_root/build_artifacts/ipython_genutils_1716278396992/work
ipywidgets @ file:///home/conda/feedstock_root/build_artifacts/ipywidgets_1679421482533/work
jedi @ file:///home/conda/feedstock_root/build_artifacts/jedi_1605054537831/work
Jinja2 @ file:///home/conda/feedstock_root/build_artifacts/jinja2_1636510082894/work
jsonschema @ file:///home/conda/feedstock_root/build_artifacts/jsonschema_1634752161479/work
jupyter @ file:///home/conda/feedstock_root/build_artifacts/jupyter_1696255489086/work
jupyter-client @ file:///home/conda/feedstock_root/build_artifacts/jupyter_client_1642858610849/work
jupyter-console @ file:///home/conda/feedstock_root/build_artifacts/jupyter_console_1676328545892/work
jupyter-core @ file:///home/conda/feedstock_root/build_artifacts/jupyter_core_1631852698933/work
jupyterlab-pygments @ file:///home/conda/feedstock_root/build_artifacts/jupyterlab_pygments_1601375948261/work
jupyterlab-widgets @ file:///home/conda/feedstock_root/build_artifacts/jupyterlab_widgets_1655961217661/work
kiwisolver @ file:///home/conda/feedstock_root/build_artifacts/kiwisolver_1610099771815/work
MarkupSafe @ file:///home/conda/feedstock_root/build_artifacts/markupsafe_1621455668064/work
matplotlib @ file:///home/conda/feedstock_root/build_artifacts/matplotlib-suite_1611858699142/work
mccabe @ file:///home/conda/feedstock_root/build_artifacts/mccabe_1643049622439/work
mistune @ file:///home/conda/feedstock_root/build_artifacts/mistune_1673904152039/work
more-itertools @ file:///home/conda/feedstock_root/build_artifacts/more-itertools_1690211628840/work
multidict @ file:///home/conda/feedstock_root/build_artifacts/multidict_1633329770033/work
nbclient @ file:///home/conda/feedstock_root/build_artifacts/nbclient_1637327213451/work
nbconvert @ file:///home/conda/feedstock_root/build_artifacts/nbconvert_1605401832871/work
nbformat @ file:///home/conda/feedstock_root/build_artifacts/nbformat_1617383142101/work
nest_asyncio @ file:///home/conda/feedstock_root/build_artifacts/nest-asyncio_1705850609492/work
netCDF4 @ file:///home/conda/feedstock_root/build_artifacts/netcdf4_1633096406418/work
nose==1.3.7
notebook @ file:///home/conda/feedstock_root/build_artifacts/notebook_1616419146127/work
numpy @ file:///home/conda/feedstock_root/build_artifacts/numpy_1626681920064/work
olefile @ file:///home/conda/feedstock_root/build_artifacts/olefile_1602866521163/work
packaging @ file:///home/conda/feedstock_root/build_artifacts/packaging_1637239678211/work
pandas==1.1.5
pandocfilters @ file:///home/conda/feedstock_root/build_artifacts/pandocfilters_1631603243851/work
parso @ file:///home/conda/feedstock_root/build_artifacts/parso_1595548966091/work
pbr @ file:///home/conda/feedstock_root/build_artifacts/pbr_1724777609752/work
pep8-naming @ file:///home/conda/feedstock_root/build_artifacts/pep8-naming_1628397497711/work
pexpect @ file:///home/conda/feedstock_root/build_artifacts/pexpect_1667297516076/work
pickleshare @ file:///home/conda/feedstock_root/build_artifacts/pickleshare_1602536217715/work
Pillow @ file:///home/conda/feedstock_root/build_artifacts/pillow_1630696616009/work
pluggy @ file:///home/conda/feedstock_root/build_artifacts/pluggy_1631522669284/work
prometheus-client @ file:///home/conda/feedstock_root/build_artifacts/prometheus_client_1689032443210/work
prompt-toolkit @ file:///home/conda/feedstock_root/build_artifacts/prompt-toolkit_1670414775770/work
protobuf==3.18.0
psutil==7.0.0
ptyprocess @ file:///home/conda/feedstock_root/build_artifacts/ptyprocess_1609419310487/work/dist/ptyprocess-0.7.0-py2.py3-none-any.whl
py @ file:///home/conda/feedstock_root/build_artifacts/py_1636301881863/work
pycodestyle @ file:///home/conda/feedstock_root/build_artifacts/pycodestyle_1659638152915/work
pycparser @ file:///home/conda/feedstock_root/build_artifacts/pycparser_1636257122734/work
pydocstyle @ file:///home/conda/feedstock_root/build_artifacts/pydocstyle_1672787369895/work
pyflakes @ file:///home/conda/feedstock_root/build_artifacts/pyflakes_1659210156976/work
Pygments @ file:///home/conda/feedstock_root/build_artifacts/pygments_1672682006896/work
pyOpenSSL @ file:///home/conda/feedstock_root/build_artifacts/pyopenssl_1663846997386/work
pyparsing @ file:///home/conda/feedstock_root/build_artifacts/pyparsing_1724616129934/work
PyQt5==5.12.3
PyQt5_sip==4.19.18
PyQtChart==5.12
PyQtWebEngine==5.12.1
pyrsistent @ file:///home/conda/feedstock_root/build_artifacts/pyrsistent_1610146795286/work
pyshp @ file:///home/conda/feedstock_root/build_artifacts/pyshp_1659002966020/work
PySocks @ file:///home/conda/feedstock_root/build_artifacts/pysocks_1610291458349/work
pytest==6.2.5
pytest-cov @ file:///home/conda/feedstock_root/build_artifacts/pytest-cov_1664412836798/work
pytest-flake8 @ file:///home/conda/feedstock_root/build_artifacts/pytest-flake8_1646767752166/work
pytest-runner @ file:///home/conda/feedstock_root/build_artifacts/pytest-runner_1646127837850/work
python-dateutil @ file:///home/conda/feedstock_root/build_artifacts/python-dateutil_1626286286081/work
pytz @ file:///home/conda/feedstock_root/build_artifacts/pytz_1693930252784/work
PyYAML==5.4.1
pyzmq @ file:///home/conda/feedstock_root/build_artifacts/pyzmq_1631793305981/work
qtconsole @ file:///home/conda/feedstock_root/build_artifacts/qtconsole-base_1640876679830/work
QtPy @ file:///home/conda/feedstock_root/build_artifacts/qtpy_1643828301492/work
requests @ file:///home/conda/feedstock_root/build_artifacts/requests_1656534056640/work
restructuredtext-lint @ file:///home/conda/feedstock_root/build_artifacts/restructuredtext_lint_1645724685739/work
scipy @ file:///home/conda/feedstock_root/build_artifacts/scipy_1629411471490/work
Send2Trash @ file:///home/conda/feedstock_root/build_artifacts/send2trash_1682601222253/work
Shapely @ file:///home/conda/feedstock_root/build_artifacts/shapely_1628205367507/work
-e git+https://github.com/Unidata/siphon.git@bd0a6e36c8390d9bb9b072e0a1a95ca4f44ee1d5#egg=siphon
six @ file:///home/conda/feedstock_root/build_artifacts/six_1620240208055/work
snowballstemmer @ file:///home/conda/feedstock_root/build_artifacts/snowballstemmer_1637143057757/work
soupsieve @ file:///home/conda/feedstock_root/build_artifacts/soupsieve_1658207591808/work
Sphinx @ file:///home/conda/feedstock_root/build_artifacts/sphinx_1658872348413/work
sphinx-gallery @ file:///home/conda/feedstock_root/build_artifacts/sphinx-gallery_1700542355088/work
sphinxcontrib-applehelp @ file:///home/conda/feedstock_root/build_artifacts/sphinxcontrib-applehelp_1674487779667/work
sphinxcontrib-devhelp==1.0.2
sphinxcontrib-htmlhelp @ file:///home/conda/feedstock_root/build_artifacts/sphinxcontrib-htmlhelp_1675256494457/work
sphinxcontrib-jsmath @ file:///home/conda/feedstock_root/build_artifacts/sphinxcontrib-jsmath_1691604704163/work
sphinxcontrib-qthelp==1.0.3
sphinxcontrib-serializinghtml @ file:///home/conda/feedstock_root/build_artifacts/sphinxcontrib-serializinghtml_1649380998999/work
stevedore @ file:///home/conda/feedstock_root/build_artifacts/stevedore_1629395095970/work
terminado @ file:///home/conda/feedstock_root/build_artifacts/terminado_1631128154882/work
testpath @ file:///home/conda/feedstock_root/build_artifacts/testpath_1645693042223/work
toml @ file:///home/conda/feedstock_root/build_artifacts/toml_1604308577558/work
tomli @ file:///home/conda/feedstock_root/build_artifacts/tomli_1635181214134/work
tornado @ file:///home/conda/feedstock_root/build_artifacts/tornado_1610094701020/work
tqdm==4.64.1
traitlets @ file:///home/conda/feedstock_root/build_artifacts/traitlets_1631041982274/work
typing_extensions @ file:///home/conda/feedstock_root/build_artifacts/typing_extensions_1644850595256/work
urllib3 @ file:///home/conda/feedstock_root/build_artifacts/urllib3_1678635778344/work
vcrpy @ file:///home/conda/feedstock_root/build_artifacts/vcrpy_1602284745577/work
wcwidth @ file:///home/conda/feedstock_root/build_artifacts/wcwidth_1699959196938/work
webencodings @ file:///home/conda/feedstock_root/build_artifacts/webencodings_1694681268211/work
widgetsnbextension @ file:///home/conda/feedstock_root/build_artifacts/widgetsnbextension_1655939017940/work
wrapt @ file:///home/conda/feedstock_root/build_artifacts/wrapt_1633440474617/work
xarray @ file:///home/conda/feedstock_root/build_artifacts/xarray_1621474818012/work
yarl @ file:///home/conda/feedstock_root/build_artifacts/yarl_1625232870338/work
zipp @ file:///home/conda/feedstock_root/build_artifacts/zipp_1633302054558/work
| name: siphon
channels:
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=conda_forge
- _openmp_mutex=4.5=2_gnu
- alabaster=0.7.13=pyhd8ed1ab_0
- alsa-lib=1.2.7.2=h166bdaf_0
- argon2-cffi=21.1.0=py36h8f6f2f9_0
- async_generator=1.10=pyhd8ed1ab_1
- attrs=22.2.0=pyh71513ae_0
- babel=2.11.0=pyhd8ed1ab_0
- backcall=0.2.0=pyh9f0ad1d_0
- backports=1.0=pyhd8ed1ab_4
- backports.functools_lru_cache=2.0.0=pyhd8ed1ab_0
- beautifulsoup4=4.12.3=pyha770c72_0
- bleach=6.1.0=pyhd8ed1ab_0
- brotlipy=0.7.0=py36h8f6f2f9_1001
- bzip2=1.0.8=h4bc722e_7
- c-ares=1.34.4=hb9d3cd8_0
- ca-certificates=2025.1.31=hbcca054_0
- cartopy=0.19.0.post1=py36hbcbf2fa_1
- certifi=2021.5.30=py36h5fab9bb_0
- cffi=1.14.6=py36hd8eec40_1
- cftime=1.5.1=py36he33b4a0_0
- charset-normalizer=2.1.1=pyhd8ed1ab_0
- colorama=0.4.5=pyhd8ed1ab_0
- coverage=6.0=py36h8f6f2f9_1
- cryptography=35.0.0=py36hb60f036_0
- curl=7.87.0=h6312ad2_0
- cycler=0.11.0=pyhd8ed1ab_0
- dbus=1.13.6=h5008d03_3
- decorator=5.1.1=pyhd8ed1ab_0
- defusedxml=0.7.1=pyhd8ed1ab_0
- doc8=0.11.2=pyhd8ed1ab_0
- docutils=0.17.1=py36h5fab9bb_0
- entrypoints=0.4=pyhd8ed1ab_0
- expat=2.6.4=h5888daf_0
- flake8=5.0.4=pyhd8ed1ab_0
- flake8-builtins=1.5.3=pyh9f0ad1d_0
- flake8-comprehensions=3.8.0=pyhd8ed1ab_0
- flake8-copyright=0.2.4=pyhd8ed1ab_0
- flake8-docstrings=1.6.0=pyhd8ed1ab_0
- flake8-import-order=0.18.2=pyhd8ed1ab_0
- flake8-mutable=1.2.0=py_1
- flake8-pep3101=1.3.0=py_0
- flake8-polyfill=1.0.2=py_0
- flake8-print=4.0.0=pyhd8ed1ab_0
- flake8-quotes=3.4.0=pyhd8ed1ab_0
- font-ttf-dejavu-sans-mono=2.37=hab24e00_0
- font-ttf-inconsolata=3.000=h77eed37_0
- font-ttf-source-code-pro=2.038=h77eed37_0
- font-ttf-ubuntu=0.83=h77eed37_3
- fontconfig=2.14.2=h14ed4e7_0
- fonts-conda-ecosystem=1=0
- fonts-conda-forge=1=0
- freetype=2.12.1=h267a509_2
- geos=3.9.1=h9c3ff4c_2
- gettext=0.23.1=h5888daf_0
- gettext-tools=0.23.1=h5888daf_0
- glib=2.80.2=hf974151_0
- glib-tools=2.80.2=hb6ce0ca_0
- gst-plugins-base=1.20.3=h57caac4_2
- gstreamer=1.20.3=hd4edc92_2
- hdf4=4.2.15=h9772cbc_5
- hdf5=1.12.1=nompi_h2386368_104
- icu=69.1=h9c3ff4c_0
- idna=3.10=pyhd8ed1ab_0
- imagesize=1.4.1=pyhd8ed1ab_0
- importlib-metadata=4.8.1=py36h5fab9bb_0
- importlib_metadata=4.8.1=hd8ed1ab_1
- iniconfig=1.1.1=pyh9f0ad1d_0
- ipykernel=5.5.5=py36hcb3619a_0
- ipython=7.16.1=py36he448a4c_2
- ipython_genutils=0.2.0=pyhd8ed1ab_1
- ipywidgets=7.7.4=pyhd8ed1ab_0
- jedi=0.17.2=py36h5fab9bb_1
- jinja2=3.0.3=pyhd8ed1ab_0
- jpeg=9e=h0b41bf4_3
- jsonschema=4.1.2=pyhd8ed1ab_0
- jupyter=1.0.0=pyhd8ed1ab_10
- jupyter_client=7.1.2=pyhd8ed1ab_0
- jupyter_console=6.5.1=pyhd8ed1ab_0
- jupyter_core=4.8.1=py36h5fab9bb_0
- jupyterlab_pygments=0.1.2=pyh9f0ad1d_0
- jupyterlab_widgets=1.1.1=pyhd8ed1ab_0
- keyutils=1.6.1=h166bdaf_0
- kiwisolver=1.3.1=py36h605e78d_1
- krb5=1.20.1=hf9c8cef_0
- lcms2=2.12=hddcbb42_0
- ld_impl_linux-64=2.43=h712a8e2_4
- lerc=3.0=h9c3ff4c_0
- libasprintf=0.23.1=h8e693c7_0
- libasprintf-devel=0.23.1=h8e693c7_0
- libblas=3.9.0=20_linux64_openblas
- libcblas=3.9.0=20_linux64_openblas
- libclang=13.0.1=default_hb5137d0_10
- libcurl=7.87.0=h6312ad2_0
- libdeflate=1.10=h7f98852_0
- libedit=3.1.20250104=pl5321h7949ede_0
- libev=4.33=hd590300_2
- libevent=2.1.10=h9b69904_4
- libexpat=2.6.4=h5888daf_0
- libffi=3.4.6=h2dba641_0
- libgcc=14.2.0=h767d61c_2
- libgcc-ng=14.2.0=h69a702a_2
- libgettextpo=0.23.1=h5888daf_0
- libgettextpo-devel=0.23.1=h5888daf_0
- libgfortran=14.2.0=h69a702a_2
- libgfortran-ng=14.2.0=h69a702a_2
- libgfortran5=14.2.0=hf1ad2bd_2
- libglib=2.80.2=hf974151_0
- libgomp=14.2.0=h767d61c_2
- libiconv=1.18=h4ce23a2_1
- liblapack=3.9.0=20_linux64_openblas
- libllvm13=13.0.1=hf817b99_2
- liblzma=5.6.4=hb9d3cd8_0
- liblzma-devel=5.6.4=hb9d3cd8_0
- libnetcdf=4.8.1=nompi_h329d8a1_102
- libnghttp2=1.51.0=hdcd2b5c_0
- libnsl=2.0.1=hd590300_0
- libogg=1.3.5=h4ab18f5_0
- libopenblas=0.3.25=pthreads_h413a1c8_0
- libopus=1.3.1=h7f98852_1
- libpng=1.6.43=h2797004_0
- libpq=14.5=h2baec63_5
- libprotobuf=3.18.0=h780b84a_1
- libsodium=1.0.18=h36c2ea0_1
- libsqlite=3.46.0=hde9e2c9_0
- libssh2=1.10.0=haa6b8db_3
- libstdcxx=14.2.0=h8f9b012_2
- libstdcxx-ng=14.2.0=h4852527_2
- libtiff=4.3.0=h0fcbabc_4
- libuuid=2.38.1=h0b41bf4_0
- libvorbis=1.3.7=h9c3ff4c_0
- libwebp-base=1.5.0=h851e524_0
- libxcb=1.13=h7f98852_1004
- libxkbcommon=1.0.3=he3ba5ed_0
- libxml2=2.9.14=haae042b_4
- libzip=1.9.2=hc869a4a_1
- libzlib=1.2.13=h4ab18f5_6
- markupsafe=2.0.1=py36h8f6f2f9_0
- matplotlib=3.3.4=py36h5fab9bb_0
- matplotlib-base=3.3.4=py36hd391965_0
- mccabe=0.7.0=pyhd8ed1ab_0
- mistune=0.8.4=pyh1a96a4e_1006
- more-itertools=10.0.0=pyhd8ed1ab_0
- multidict=5.2.0=py36h8f6f2f9_0
- mysql-common=8.0.32=h14678bc_0
- mysql-libs=8.0.32=h54cf53e_0
- nbclient=0.5.9=pyhd8ed1ab_0
- nbconvert=6.0.7=py36h5fab9bb_3
- nbformat=5.1.3=pyhd8ed1ab_0
- ncurses=6.5=h2d0b736_3
- nest-asyncio=1.6.0=pyhd8ed1ab_0
- netcdf4=1.5.7=nompi_py36h775750b_103
- notebook=6.3.0=py36h5fab9bb_0
- nspr=4.36=h5888daf_0
- nss=3.100=hca3bf56_0
- numpy=1.19.5=py36hfc0c790_2
- olefile=0.46=pyh9f0ad1d_1
- openjpeg=2.5.0=h7d73246_0
- openssl=1.1.1w=hd590300_0
- packaging=21.3=pyhd8ed1ab_0
- pandas=1.1.5=py36h284efc9_0
- pandoc=2.19.2=h32600fe_2
- pandocfilters=1.5.0=pyhd8ed1ab_0
- parso=0.7.1=pyh9f0ad1d_0
- pbr=6.1.0=pyhd8ed1ab_0
- pcre2=10.43=hcad00b1_0
- pep8-naming=0.12.1=pyhd8ed1ab_0
- pexpect=4.8.0=pyh1a96a4e_2
- pickleshare=0.7.5=py_1003
- pillow=8.3.2=py36h676a545_0
- pip=21.3.1=pyhd8ed1ab_0
- pluggy=1.0.0=py36h5fab9bb_1
- proj=7.2.0=h277dcde_2
- prometheus_client=0.17.1=pyhd8ed1ab_0
- prompt-toolkit=3.0.36=pyha770c72_0
- prompt_toolkit=3.0.36=hd8ed1ab_0
- protobuf=3.18.0=py36hc4f0c31_0
- pthread-stubs=0.4=hb9d3cd8_1002
- ptyprocess=0.7.0=pyhd3deb0d_0
- py=1.11.0=pyh6c4a22f_0
- pycodestyle=2.9.1=pyhd8ed1ab_0
- pycparser=2.21=pyhd8ed1ab_0
- pydocstyle=6.2.0=pyhd8ed1ab_0
- pyflakes=2.5.0=pyhd8ed1ab_0
- pygments=2.14.0=pyhd8ed1ab_0
- pyopenssl=22.0.0=pyhd8ed1ab_1
- pyparsing=3.1.4=pyhd8ed1ab_0
- pyqt=5.12.3=py36h5fab9bb_7
- pyqt-impl=5.12.3=py36h7ec31b9_7
- pyqt5-sip=4.19.18=py36hc4f0c31_7
- pyqtchart=5.12=py36h7ec31b9_7
- pyqtwebengine=5.12.1=py36h7ec31b9_7
- pyrsistent=0.17.3=py36h8f6f2f9_2
- pyshp=2.3.1=pyhd8ed1ab_0
- pysocks=1.7.1=py36h5fab9bb_3
- pytest=6.2.5=py36h5fab9bb_0
- pytest-cov=4.0.0=pyhd8ed1ab_0
- pytest-flake8=1.1.0=pyhd8ed1ab_0
- pytest-runner=5.3.2=pyhd8ed1ab_0
- python=3.6.15=hb7a2778_0_cpython
- python-dateutil=2.8.2=pyhd8ed1ab_0
- python_abi=3.6=2_cp36m
- pytz=2023.3.post1=pyhd8ed1ab_0
- pyyaml=5.4.1=py36h8f6f2f9_1
- pyzmq=22.3.0=py36h7068817_0
- qt=5.12.9=h1304e3e_6
- qtconsole-base=5.2.2=pyhd8ed1ab_1
- qtpy=2.0.1=pyhd8ed1ab_0
- readline=8.2=h8c095d6_2
- requests=2.28.1=pyhd8ed1ab_0
- restructuredtext_lint=1.4.0=pyhd8ed1ab_0
- scipy=1.5.3=py36h81d768a_1
- send2trash=1.8.2=pyh41d4057_0
- setuptools=58.0.4=py36h5fab9bb_2
- shapely=1.7.1=py36hff28ebb_5
- six=1.16.0=pyh6c4a22f_0
- snowballstemmer=2.2.0=pyhd8ed1ab_0
- soupsieve=2.3.2.post1=pyhd8ed1ab_0
- sphinx=5.1.1=pyh6c4a22f_0
- sphinx-gallery=0.15.0=pyhd8ed1ab_0
- sphinxcontrib-applehelp=1.0.4=pyhd8ed1ab_0
- sphinxcontrib-devhelp=1.0.2=py_0
- sphinxcontrib-htmlhelp=2.0.1=pyhd8ed1ab_0
- sphinxcontrib-jsmath=1.0.1=pyhd8ed1ab_0
- sphinxcontrib-qthelp=1.0.3=py_0
- sphinxcontrib-serializinghtml=1.1.5=pyhd8ed1ab_2
- sqlite=3.46.0=h6d4b2fc_0
- stevedore=3.4.0=py36h5fab9bb_0
- terminado=0.12.1=py36h5fab9bb_0
- testpath=0.6.0=pyhd8ed1ab_0
- tk=8.6.13=noxft_h4845f30_101
- toml=0.10.2=pyhd8ed1ab_0
- tomli=1.2.2=pyhd8ed1ab_0
- tornado=6.1=py36h8f6f2f9_1
- traitlets=4.3.3=pyhd8ed1ab_2
- typing-extensions=4.1.1=hd8ed1ab_0
- typing_extensions=4.1.1=pyha770c72_0
- urllib3=1.26.15=pyhd8ed1ab_0
- vcrpy=4.1.1=py_0
- wcwidth=0.2.10=pyhd8ed1ab_0
- webencodings=0.5.1=pyhd8ed1ab_2
- wheel=0.37.1=pyhd8ed1ab_0
- widgetsnbextension=3.6.1=pyha770c72_0
- wrapt=1.13.1=py36h8f6f2f9_0
- xarray=0.18.2=pyhd8ed1ab_0
- xorg-libxau=1.0.12=hb9d3cd8_0
- xorg-libxdmcp=1.1.5=hb9d3cd8_0
- xz=5.6.4=hbcc6ac9_0
- xz-gpl-tools=5.6.4=hbcc6ac9_0
- xz-tools=5.6.4=hb9d3cd8_0
- yaml=0.2.5=h7f98852_2
- yarl=1.6.3=py36h8f6f2f9_2
- zeromq=4.3.5=h59595ed_1
- zipp=3.6.0=pyhd8ed1ab_0
- zlib=1.2.13=h4ab18f5_6
- zstd=1.5.6=ha6fb4c9_0
- pip:
- importlib-resources==5.4.0
- ipyparallel==8.2.1
- nose==1.3.7
- psutil==7.0.0
- tqdm==4.64.1
prefix: /opt/conda/envs/siphon
| [
"siphon/tests/test_catalog.py::test_catalog_representation",
"siphon/tests/test_catalog.py::test_datasets_sliced_str",
"siphon/tests/test_catalog.py::test_catalog_ref_str"
]
| []
| [
"siphon/tests/test_catalog.py::test_basic",
"siphon/tests/test_catalog.py::test_access",
"siphon/tests/test_catalog.py::test_virtual_access",
"siphon/tests/test_catalog.py::test_get_latest",
"siphon/tests/test_catalog.py::test_latest_attribute",
"siphon/tests/test_catalog.py::test_tds_top_catalog",
"siphon/tests/test_catalog.py::test_simple_radar_cat",
"siphon/tests/test_catalog.py::test_simple_point_feature_collection_xml",
"siphon/tests/test_catalog.py::test_html_link",
"siphon/tests/test_catalog.py::test_catalog_follow",
"siphon/tests/test_catalog.py::test_datasets_order",
"siphon/tests/test_catalog.py::test_datasets_get_by_index",
"siphon/tests/test_catalog.py::test_datasets_str",
"siphon/tests/test_catalog.py::test_datasets_nearest_time",
"siphon/tests/test_catalog.py::test_datasets_nearest_time_raises",
"siphon/tests/test_catalog.py::test_datasets_time_range",
"siphon/tests/test_catalog.py::test_datasets_time_range_raises",
"siphon/tests/test_catalog.py::test_catalog_ref_order",
"siphon/tests/test_catalog.py::test_non_standard_context_path",
"siphon/tests/test_catalog.py::test_access_elements",
"siphon/tests/test_catalog.py::test_simple_service_within_compound",
"siphon/tests/test_catalog.py::test_ramadda_catalog",
"siphon/tests/test_catalog.py::test_ramadda_access_urls",
"siphon/tests/test_catalog.py::test_tds50_catalogref_follow"
]
| []
| BSD 3-Clause "New" or "Revised" License | 1,836 | [
"environment.yml",
"siphon/catalog.py"
]
| [
"environment.yml",
"siphon/catalog.py"
]
|
google__mobly-361 | 5958f83fc5f297c91a63bf8c8bd579144d002a06 | 2017-11-01 20:56:35 | 7e5e62af4ab4537bf619f0ee403c05f004c5baf0 | diff --git a/README.md b/README.md
index e914afe..7d22e5f 100644
--- a/README.md
+++ b/README.md
@@ -58,6 +58,9 @@ restrictions.
## Tutorials
To get started with some simple tests, see the [Mobly tutorial](docs/tutorial.md).
+To get started running single-device Android instrumentation tests with Mobly,
+see the [instrumentation runner tutorial](docs/instrumentation_tutorial.md).
+
## Mobly Snippet
The Mobly Snippet projects let users better control Android devices.
diff --git a/docs/conf.py b/docs/conf.py
index 2e12371..044c857 100644
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -79,7 +79,11 @@ language = 'en'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
-exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store', 'tutorial.md']
+exclude_patterns = ['_build',
+ 'Thumbs.db',
+ '.DS_Store',
+ 'tutorial.md',
+ 'instrumentation_tutorial.md']
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
diff --git a/docs/instrumentation_tutorial.md b/docs/instrumentation_tutorial.md
new file mode 100644
index 0000000..ff3d258
--- /dev/null
+++ b/docs/instrumentation_tutorial.md
@@ -0,0 +1,190 @@
+# Running Android instrumentation tests with Mobly
+
+This tutorial shows how to write and execute Mobly tests for running Android
+instrumentation tests. For more details about instrumentation tests, please refer to
+https://developer.android.com/studio/test/index.html.
+
+## Setup Requirements
+
+* A computer with at least 1 USB ports.
+* Mobly package and its system dependencies installed on the computer.
+* One Android device that is compatible with your instrumentatation and
+ application apks.
+* Your instrumentation and applications apks for installing.
+* A working adb setup. To check, connect one Android device to the computer
+ and make sure it has "USB debugging" enabled. Make sure the device shows up
+ in the list printed by `adb devices`.
+
+## Example Name Substitutions
+
+Here are the names that we use in this tutorial, substitute these names with
+your actual apk package and file names when using your real files:
+
+* The application apk : `application.apk`
+* The instrumentation apk : `instrumentation_test.apk`
+* The instrumentation test package : `com.example.package.test`
+
+## Example 1: Running Instrumentation Tests
+
+Assuming your apks are already installed on devices. You can just subclass the
+instrumentation test class and run against your package.
+
+You will need a configuration file for Mobly to find your devices.
+
+***sample_config.yml***
+
+```yaml
+TestBeds:
+ - Name: BasicTestBed
+ Controllers:
+ AndroidDevice: '*'
+```
+
+***instrumentation_test.py***
+
+```python
+from mobly import base_instrumentation_test
+from mobly import test_runner
+from mobly.controllers import android_device
+
+class InstrumentationTest(base_instrumentation_test.BaseInstrumentationTestClass):
+ def setup_class(self):
+ self.dut = self.register_controller(android_device)[0]
+
+ def test_instrumentation(self):
+ self.run_instrumentation_test(self.dut, 'com.example.package.test')
+
+
+if __name__ == '__main__':
+ test_runner.main()
+```
+
+*To execute:*
+
+```
+$ python instrumentation_test.py -c sample_config.yml
+```
+
+*Expect*:
+
+The output from normally running your instrumentation tests along with a summary
+of the test results.
+
+## Example 2: Specifying Instrumentation Options
+
+If your instrumentation tests use instrumentation options for controlling
+behaviour, then you can put these options into your configuration file and then
+fetch them when you run your instrumentatation tests.
+
+***sample_config.yml***
+
+```yaml
+TestBeds:
+ - Name: BasicTestBed
+ Controllers:
+ AndroidDevice: '*'
+ TestParams:
+ instrumentation_option_annotation: android.support.test.filters.LargeTest
+ instrumentation_option_nonAnnotation: android.support.test.filters.SmallTest
+```
+
+***instrumentation_test.py***
+
+```python
+from mobly import base_instrumentation_test
+from mobly import test_runner
+from mobly.controllers import android_device
+
+class InstrumentationTest(base_instrumentation_test.BaseInstrumentationTestClass):
+ def setup_class(self):
+ self.dut = self.register_controller(android_device)[0]
+ self.options = self.parse_instrumentation_options(self.user_params)
+
+ def test_instrumentation(self):
+ self.run_instrumentation_test(self.dut, 'com.example.package.test',
+ options=self.options)
+
+
+if __name__ == '__main__':
+ test_runner.main()
+```
+
+*To execute:*
+
+```
+$ python instrumentation_test.py -c sample_config.yml
+```
+
+*Expect*:
+
+The output of your *LargeTest* instrumentation tests with no *SmallTest*
+instrumentation test being run.
+
+## Example 3 Using a Custom Runner
+
+If you have a custom runner that you use for instrumentation tests, then you can
+specify it in the *run_instrumentation_test* method call. Replace
+`com.example.package.test.CustomRunner` with the fully quailied package name of
+your real instrumentation runner.
+
+```python
+def test_instrumentation(self):
+ self.run_instrumentation_test(self.dut, 'com.example.package.test',
+ runner='com.example.package.test.CustomRunner')
+```
+
+## Example 4: Multiple Instrumentation Runs
+
+If you have multiple devices that you want to run instrumentation tests
+against, then you can simply call the *run_instrumentation_test* method
+multiple times. If you need to distinguish between runs, then you can specify
+a prefix.
+
+***sample_config.yml***
+
+```yaml
+TestBeds:
+ - Name: TwoDeviceTestBed
+ Controllers:
+ AndroidDevice:
+ - serial: xyz
+ label: dut
+ - serial: abc
+ label: dut
+```
+
+***instrumentation_test.py***
+
+```python
+from mobly import base_instrumentation_test
+from mobly import test_runner
+from mobly.controllers import android_device
+
+class InstrumentationTest(base_instrumentation_test.BaseInstrumentationTestClass):
+ def setup_class(self):
+ self.ads = self.register_controller(android_device)
+ # Get all of the dut devices to run instrumentation tests against.
+ self.duts = android_device.get_devices(self.ads, label='dut')
+
+ def test_instrumentation(self):
+ # Iterate over the dut devices with a corresponding index.
+ for index, dut in zip(range(len(self.duts)), self.duts):
+ # Specify a prefix to help disambiguate the runs.
+ self.run_instrumentation_test(dut, 'com.example.package.tests',
+ prefix='test_run_%s' % index)
+
+
+if __name__ == '__main__':
+ test_runner.main()
+```
+
+*To execute:*
+
+```
+$ python instrumentation_test.py -c sample_config.yml
+```
+
+*Expect*:
+
+The output from both instrumentation runs along with an aggregated summary of
+the results from both runs.
diff --git a/mobly/controllers/android_device_lib/adb.py b/mobly/controllers/android_device_lib/adb.py
index 045f43e..4162caa 100644
--- a/mobly/controllers/android_device_lib/adb.py
+++ b/mobly/controllers/android_device_lib/adb.py
@@ -27,6 +27,9 @@ ADB = 'adb'
# do with port forwarding must happen under this lock.
ADB_PORT_LOCK = threading.Lock()
+# Qualified class name of the default instrumentation test runner.
+DEFAULT_INSTRUMENTATION_RUNNER = 'com.android.common.support.test.runner.AndroidJUnitRunner'
+
class AdbError(Exception):
"""Raised when there is an error in adb operations."""
@@ -129,7 +132,7 @@ class AdbProxy(object):
raise AdbTimeoutError('Timed out Adb cmd "%s". timeout: %s' %
(args, timeout))
elif timeout and timeout < 0:
- raise AdbTimeoutError("Timeout is a negative value: %s" % timeout)
+ raise AdbTimeoutError('Timeout is a negative value: %s' % timeout)
(out, err) = proc.communicate()
ret = proc.returncode
@@ -178,6 +181,48 @@ class AdbProxy(object):
with ADB_PORT_LOCK:
return self._exec_adb_cmd('forward', args, shell, timeout=None)
+ def instrument(self, package, options=None, runner=None):
+ """Runs an instrumentation command on the device.
+
+ This is a convenience wrapper to avoid parameter formatting.
+
+ Example:
+ device.instrument(
+ 'com.my.package.test',
+ options = {
+ 'class': 'com.my.package.test.TestSuite',
+ },
+ )
+
+ Args:
+ package: string, the package of the instrumentation tests.
+ options: dict, the instrumentation options including the test
+ class.
+ runner: string, the test runner name, which defaults to
+ DEFAULT_INSTRUMENTATION_RUNNER.
+
+ Returns:
+ The output of instrumentation command.
+ """
+ if runner is None:
+ runner = DEFAULT_INSTRUMENTATION_RUNNER
+ if options is None:
+ options = {}
+
+ options_list = []
+ for option_key, option_value in options.items():
+ options_list.append('-e %s %s' % (option_key, option_value))
+ options_string = ' '.join(options_list)
+
+ instrumentation_command = 'am instrument -r -w %s %s/%s' % (
+ options_string,
+ package,
+ runner,
+ )
+ logging.info('AndroidDevice|%s: Executing adb shell %s', self.serial,
+ instrumentation_command)
+ return self.shell(instrumentation_command)
+
def __getattr__(self, name):
def adb_call(args=None, shell=False, timeout=None):
"""Wrapper for an ADB command.
diff --git a/mobly/controllers/android_device_lib/snippet_client.py b/mobly/controllers/android_device_lib/snippet_client.py
index 6395b66..5db99ec 100644
--- a/mobly/controllers/android_device_lib/snippet_client.py
+++ b/mobly/controllers/android_device_lib/snippet_client.py
@@ -144,9 +144,10 @@ class SnippetClient(jsonrpc_client_base.JsonRpcClientBase):
self.connect()
except:
# Failed to connect to app, something went wrong.
- raise jsonrpc_client_base.AppRestoreConnectionError(self._ad
- ('Failed to restore app connection for %s at host port %s, '
- 'device port %s'), self.package, self.host_port,
+ raise jsonrpc_client_base.AppRestoreConnectionError(
+ self._ad(
+ 'Failed to restore app connection for %s at host port %s, '
+ 'device port %s'), self.package, self.host_port,
self.device_port)
# Because the previous connection was lost, update self._proc
@@ -167,7 +168,8 @@ class SnippetClient(jsonrpc_client_base.JsonRpcClientBase):
utils.stop_standing_subprocess(self._proc)
out = self._adb.shell(_STOP_CMD % self.package).decode('utf-8')
if 'OK (0 tests)' not in out:
- raise errors.DeviceError(self._ad,
+ raise errors.DeviceError(
+ self._ad,
'Failed to stop existing apk. Unexpected output: %s' % out)
finally:
# Always clean up the adb port
@@ -176,7 +178,7 @@ class SnippetClient(jsonrpc_client_base.JsonRpcClientBase):
def _start_event_client(self):
"""Overrides superclass."""
- event_client = SnippetClient(package=self.package, ad=self)
+ event_client = SnippetClient(package=self.package, ad=self._ad)
event_client.host_port = self.host_port
event_client.device_port = self.device_port
event_client.connect(self.uid,
@@ -204,7 +206,8 @@ class SnippetClient(jsonrpc_client_base.JsonRpcClientBase):
(self.package,
_INSTRUMENTATION_RUNNER_PACKAGE), out)
if not matched_out:
- raise jsonrpc_client_base.AppStartError(self._ad,
+ raise jsonrpc_client_base.AppStartError(
+ self._ad,
'%s is installed, but it is not instrumented.' % self.package)
match = re.search('^instrumentation:(.*)\/(.*) \(target=(.*)\)$',
matched_out[0])
@@ -214,8 +217,8 @@ class SnippetClient(jsonrpc_client_base.JsonRpcClientBase):
if target_name != self.package:
out = self._adb.shell('pm list package')
if not utils.grep('^package:%s$' % target_name, out):
- raise jsonrpc_client_base.AppStartError(self._ad,
- 'Instrumentation target %s is not installed.' %
+ raise jsonrpc_client_base.AppStartError(
+ self._ad, 'Instrumentation target %s is not installed.' %
target_name)
def _do_start_app(self, launch_cmd):
@@ -241,8 +244,8 @@ class SnippetClient(jsonrpc_client_base.JsonRpcClientBase):
while True:
line = self._proc.stdout.readline().decode('utf-8')
if not line:
- raise jsonrpc_client_base.AppStartError(self._ad,
- 'Unexpected EOF waiting for app to start')
+ raise jsonrpc_client_base.AppStartError(
+ self._ad, 'Unexpected EOF waiting for app to start')
# readline() uses an empty string to mark EOF, and a single newline
# to mark regular empty lines in the output. Don't move the strip()
# call above the truthiness check, or this method will start
| Wrong msg in snippet client's exception
Expected device id, but got snippet client `repr` in an error msg.
```
File "mobly/controllers/android_device_lib/callback_handler.py", line 94, in waitAndGet
self._id, event_name, timeout_ms)
File "mobly/controllers/android_device_lib/jsonrpc_client_base.py", line 295, in rpc_call
return self._rpc(name, *args)
File "mobly/controllers/android_device_lib/jsonrpc_client_base.py", line 274, in _rpc
ProtocolError.NO_RESPONSE_FROM_SERVER)
ProtocolError: <mobly.controllers.android_device_lib.snippet_client.SnippetClient object at 0x20c4490> No response from server.
``` | google/mobly | diff --git a/mobly/base_instrumentation_test.py b/mobly/base_instrumentation_test.py
new file mode 100644
index 0000000..902fa68
--- /dev/null
+++ b/mobly/base_instrumentation_test.py
@@ -0,0 +1,936 @@
+# Copyright 2017 Google Inc.
+#
+# 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.
+
+import logging
+
+from collections import defaultdict
+from enum import Enum
+from mobly import base_test
+from mobly import records
+from mobly import signals
+
+
+class _InstrumentationStructurePrefixes(object):
+ """Class containing prefixes that structure insturmentation output.
+
+ Android instrumentation generally follows the following format:
+
+ .. code-block:: none
+
+ INSTRUMENTATION_STATUS: ...
+ ...
+ INSTRUMENTATION_STATUS: ...
+ INSTRUMENTATION_STATUS_CODE: ...
+ INSTRUMENTATION_STATUS: ...
+ ...
+ INSTRUMENTATION_STATUS: ...
+ INSTRUMENTATION_STATUS_CODE: ...
+ ...
+ INSTRUMENTATION_RESULT: ...
+ ...
+ INSTRUMENTATION_RESULT: ...
+ ...
+ INSTRUMENTATION_CODE: ...
+
+ This means that these prefixes can be used to guide parsing
+ the output of the instrumentation command into the different
+ instrumetnation test methods.
+
+ Refer to the following Android Framework package for more details:
+
+ .. code-block:: none
+
+ com.android.commands.am.AM
+
+ """
+
+ STATUS = 'INSTRUMENTATION_STATUS:'
+ STATUS_CODE = 'INSTRUMENTATION_STATUS_CODE:'
+ RESULT = 'INSTRUMENTATION_RESULT:'
+ CODE = 'INSTRUMENTATION_CODE:'
+ FAILED = 'INSTRUMENTATION_FAILED:'
+
+
+class _InstrumentationKnownStatusKeys(object):
+ """Commonly used keys used in instrumentation output for listing
+ instrumentation test method result properties.
+
+ An instrumenation status line usually contains a key-value pair such as
+ the following:
+
+ .. code-block:: none
+
+ INSTRUMENTATION_STATUS: <key>=<value>
+
+ Some of these key-value pairs are very common and represent test case
+ properties. This mapping is used to handle each of the corresponding
+ key-value pairs different than less important key-value pairs.
+
+ Refer to the following Android Framework packages for more details:
+
+ .. code-block:: none
+
+ android.app.Instrumentation
+ android.support.test.internal.runner.listener.InstrumentationResultPrinter
+
+ """
+
+ CLASS = 'class'
+ ERROR = 'Error'
+ STACK = 'stack'
+ TEST = 'test'
+ STREAM = 'stream'
+
+
+class _InstrumentationStatusCodes(object):
+ """A mapping of instrumentation status codes to test method results.
+
+ When instrumentation runs, at various points ouput is created in a serias
+ of blocks that terminate as follows:
+
+ .. code-block:: none
+
+ INSTRUMENTATION_STATUS_CODE: 1
+
+ These blocks typically have several status keys in them, and they indicate
+ the progression of a particular instrumentation test method. When the
+ corresponding instrumentation test method finishes, there is generally a
+ line which includes a status code that gives thes the test result.
+
+ The UNKNOWN status code is not an actual status code and is only used to
+ represent that a status code has not yet been read for an instrumentation
+ block.
+
+ Refer to the following Android Framework package for more details:
+
+ .. code-block:: none
+
+ android.support.test.internal.runner.listener.InstrumentationResultPrinter
+
+ """
+
+ UNKNOWN = None
+ OK = '0'
+ START = '1'
+ IN_PROGRESS = '2'
+ ERROR = '-1'
+ FAILURE = '-2'
+ IGNORED = '-3'
+ ASSUMPTION_FAILURE = '-4'
+
+
+class _InstrumentationStatusCodeCategories(object):
+ """A mapping of instrumentation test method results to categories.
+
+ Aside from the TIMING category, these categories roughly map to Mobly
+ signals and are used for determining how a particular instrumentation test
+ method gets recorded.
+ """
+
+ TIMING = [
+ _InstrumentationStatusCodes.START,
+ _InstrumentationStatusCodes.IN_PROGRESS,
+ ]
+ PASS = [
+ _InstrumentationStatusCodes.OK,
+ ]
+ FAIL = [
+ _InstrumentationStatusCodes.ERROR,
+ _InstrumentationStatusCodes.FAILURE,
+ ]
+ SKIPPED = [
+ _InstrumentationStatusCodes.IGNORED,
+ _InstrumentationStatusCodes.ASSUMPTION_FAILURE,
+ ]
+
+
+class _InstrumentationKnownResultKeys(object):
+ """Commonly used keys for outputting instrumentation errors.
+
+ When instrumentation finishes running all of the instrumentation test
+ methods, a result line will appear as follows:
+
+ .. code-block:: none
+
+ INSTRUMENTATION_RESULT:
+
+ If something wrong happened during the instrumentation run such as an
+ application under test crash, the the line will appear similarly as thus:
+
+ .. code-block:: none
+
+ INSTRUMENTATION_RESULT: shortMsg=Process crashed.
+
+ Since these keys indicate that something wrong has happened to the
+ instrumentation run, they should be checked for explicitly.
+
+ Refer to the following documentation page for more information:
+
+ .. code-block:: none
+
+ https://developer.android.com/reference/android/app/ActivityManager.ProcessErrorStateInfo.html
+
+ """
+
+ LONGMSG = 'longMsg'
+ SHORTMSG = 'shortMsg'
+
+
+class _InstrumentationResultSignals(object):
+ """Instrumenttion result block strings for signalling run completion.
+
+ The final section of the instrumentation output generally follows this
+ format:
+
+ .. code-block:: none
+
+ INSTRUMENTATION_RESULT: stream=
+ ...
+ INSTRUMENTATION_CODE -1
+
+ Inside of the ellipsed section, one of these signaling strings should be
+ present. If they are not present, this usually means that the
+ instrumentation run has failed in someway such as a crash. Because the
+ final instrumentation block simply summarizes information, simply roughly
+ checking for a particilar string should be sufficient to check to a proper
+ run completion as the contents of the instrumentation result block don't
+ really matter.
+
+ Refer to the following JUnit package for more details:
+
+ .. code-block:: none
+
+ junit.textui.ResultPrinter
+
+ """
+
+ FAIL = 'FAILURES!!!'
+ PASS = 'OK ('
+
+
+class _InstrumentationBlockStates(Enum):
+ """States used for determing what the parser is currently parsing.
+
+ The parse always starts and ends a block in the UKNOWN state, which is
+ used to indicate that either a method or a result block (matching the
+ METHOD and RESULT states respectively) are valid follow ups, which means
+ that parser should be checking for a structure prefix that indicates which
+ of those two states it should transition to. If the parser is in the
+ METHOD state, then the parser will be parsing input into test methods.
+ Otherwise, the parse can simply concatenate all the input to check for
+ some final run completion signals.
+ """
+
+ UNKNOWN = 0
+ METHOD = 1
+ RESULT = 2
+
+
+class _InstrumentationBlock(object):
+ """Container class for parsed instrumentation output for instrumentation
+ test methods.
+
+ Instrumentation test methods typically follow the follwoing format:
+
+ .. code-block:: none
+
+ INSTRUMENTATION_STATUS: <key>=<value>
+ ...
+ INSTRUMENTATION_STATUS: <key>=<value>
+ INSTRUMENTATION_STATUS_CODE: <status code #>
+
+ The main issue with parsing this however is that the key-value pairs can
+ span multiple lines such as this:
+
+ .. code-block:: none
+
+ INSTRUMENTATION_STATUS: stream=
+ Error in ...
+ ...
+
+ Or, such as this:
+
+ .. code-block:: none
+
+ INSTRUMENTATION_STATUS: stack=...
+ ...
+
+ Because these keys are poentially very long, constant string contatention
+ is potentially inefficent. Instead, this class builds up a buffer to store
+ the raw ouput until it is processed into an actual test result by the
+ _InstrumentationBlockFormatter class.
+
+ Additionally, this class also serves to store the parser state, which
+ means that the BaseInstrumentationTestClass does not need to keep any
+ potentially volatile instrumentation related state, so multiple
+ instrumentation runs should have completely separate parsing states.
+
+ This class is also used for storing result blocks although very little
+ needs to be done for those.
+
+ Attributes:
+ current_key: string, the current key that is being parsed, default to
+ _InstrumentationKnownStatusKeys.STREAM.
+ error_message: string, an error message indicating that something
+ unexpected happened during a instrumentatoin test method.
+ known_keys: dict, well known keys that are handled uniquely.
+ prefix: string, a prefix to add to the class name of the
+ instrumentation test methods.
+ previous_instrumentation_block: _InstrumentationBlock, the last parsed
+ instrumentation block.
+ state: _InstrumentationBlockStates, the current state of the parser.
+ status_code: string, the state code for an instrumentation method
+ block.
+ unknown_keys: dict, arbitrary keys that are handled generically.
+ """
+
+ def __init__(self,
+ state=_InstrumentationBlockStates.UNKNOWN,
+ prefix=None,
+ previous_instrumentation_block=None):
+ self.state = state
+ self.prefix = prefix
+ self.previous_instrumentation_block = previous_instrumentation_block
+
+ self._empty = True
+ self.error_message = ''
+ self.status_code = _InstrumentationStatusCodes.UNKNOWN
+
+ self.current_key = _InstrumentationKnownStatusKeys.STREAM
+ self.known_keys = {
+ _InstrumentationKnownStatusKeys.STREAM: [],
+ _InstrumentationKnownStatusKeys.CLASS: [],
+ _InstrumentationKnownStatusKeys.ERROR: [],
+ _InstrumentationKnownStatusKeys.STACK: [],
+ _InstrumentationKnownStatusKeys.TEST: [],
+ _InstrumentationKnownResultKeys.LONGMSG: [],
+ _InstrumentationKnownResultKeys.SHORTMSG: [],
+ }
+ self.unknown_keys = defaultdict(list)
+
+ @property
+ def is_empty(self):
+ """Deteremines whether or not anything has been parsed with this
+ instrumentation block.
+
+ Returns:
+ A boolean indicating whether or not the this instrumentation block
+ has parsed and contains any output.
+ """
+ return self._empty
+
+ def set_error_message(self, error_message):
+ """Sets an error message on an instrumentation block.
+
+ This method is used exclusively to indicate that a test method failed
+ to complete, which is usually cause by a crash of some sort such that
+ the test method is marked as error instead of ignored.
+
+ Args:
+ error_message: string, an error message to be added to the
+ TestResultRecord to explain that something wrong happened.
+ """
+ self._empty = False
+ self.error_message = error_message
+
+ def _remove_structure_prefix(self, prefix, line):
+ """Helper function for removing the structure prefix for parsing.
+
+ Args:
+ prefix: string, a _InstrumentationStructurePrefixes to remove from
+ the raw output.
+ line: string, the raw line from the instrumentation output.
+
+ Returns:
+ A string containing a key value pair descripting some property
+ of the current instrumentation test method.
+ """
+ return line[len(prefix):].strip()
+
+ def set_status_code(self, status_code_line):
+ """Sets the status code for the instrumentation test method, used in
+ determining the test result.
+
+ Args:
+ status_code_line: string, the raw instrumentation output line that
+ contains the status code of the instrumentation block.
+ """
+ self._empty = False
+ self.status_code = self._remove_structure_prefix(
+ _InstrumentationStructurePrefixes.STATUS_CODE,
+ status_code_line,
+ )
+
+ def set_key(self, structure_prefix, key_line):
+ """Sets the current key for the instrumentation block.
+
+ For unknown keys, the key is added to the value list in order to
+ better contextualize the value in the output.
+
+ Args:
+ structure_prefix: string, the structure prefix that was matched
+ and that needs to be removed.
+ key_line: string, the raw instrumentation ouput line that contains
+ the key-value pair.
+ """
+ self._empty = False
+ key_value = self._remove_structure_prefix(
+ structure_prefix,
+ key_line,
+ )
+ if '=' in key_value:
+ (key, value) = key_value.split('=')
+ self.current_key = key
+ if key in self.known_keys:
+ self.known_keys[key].append(value)
+ else:
+ self.unknown_keys[key].append(key_value)
+
+ def add_value(self, line):
+ """Adds unstructured or multi-line value output to the current parsed
+ instrumentation block for outputting later.
+
+ Usually, this will add extra lines to the value list for the current
+ key-value pair. However, sometimes, such as when instrumentation
+ failed to start, output does not follow the structured prefix format.
+ In this case, adding all of the output is still useful so that a user
+ can debug the issue.
+
+ Args:
+ line: string, the raw instrumentation line to append to the value
+ list.
+ """
+ self._empty = False
+ if self.current_key in self.known_keys:
+ self.known_keys[self.current_key].append(line)
+ else:
+ self.unknown_keys[self.current_key].append(line)
+
+ def transition_state(self, new_state):
+ """Transitions or sets the current instrumentation block to the new
+ parser state.
+
+ Args:
+ new_state: _InstrumentationBlockStates, the state that the parser
+ should transition to.
+
+ Returns:
+ A new instrumentation block set to the new state, representing
+ the start of parsing a new instrumentation test method.
+ Alternatively, if the current instrumentation block represents the
+ start of parsing a new instrumentation block (state UKNOWN), then
+ this returns the current instrumentation block set to the now
+ known parsing state.
+ """
+ if self.state == _InstrumentationBlockStates.UNKNOWN:
+ self.state = new_state
+ return self
+ else:
+ return _InstrumentationBlock(
+ state=new_state,
+ prefix=self.prefix,
+ previous_instrumentation_block=self,
+ )
+
+
+class _InstrumentationBlockFormatter(object):
+ """Takes an instrumentation block and converts it into a Mobly test
+ result.
+ """
+
+ DEFAULT_INSTRUMENTATION_METHOD_NAME = 'instrumentation_method'
+
+ def __init__(self, instrumentation_block):
+ self._prefix = instrumentation_block.prefix
+ self._status_code = instrumentation_block.status_code
+ self._error_message = instrumentation_block.error_message
+ self._known_keys = {}
+ self._unknown_keys = {}
+ for key, value in instrumentation_block.known_keys.items():
+ self._known_keys[key] = '\n'.join(
+ instrumentation_block.known_keys[key])
+ for key, value in instrumentation_block.unknown_keys.items():
+ self._unknown_keys[key] = '\n'.join(
+ instrumentation_block.unknown_keys[key])
+
+ def _get_name(self):
+ """Gets the method name of the test method for the instrumentation
+ method block.
+
+ Returns:
+ A string containing the name of the instrumentation test method's
+ test or a default name if no name was parsed.
+ """
+ if self._known_keys[_InstrumentationKnownStatusKeys.TEST]:
+ return self._known_keys[_InstrumentationKnownStatusKeys.TEST]
+ else:
+ return self.DEFAULT_INSTRUMENTATION_METHOD_NAME
+
+ def _get_class(self):
+ """Gets the class name of the test method for the instrumentation
+ method block.
+
+ Returns:
+ A string containing the class name of the instrumentation test
+ method's test or empty string if no name was parsed. If a prefix
+ was specified, then the prefix will be prepended to the class
+ name.
+ """
+ class_parts = [
+ self._prefix,
+ self._known_keys[_InstrumentationKnownStatusKeys.CLASS]
+ ]
+ return '.'.join(filter(None, class_parts))
+
+ def _get_full_name(self):
+ """Gets the qualified name of the test method corresponding to the
+ instrumentation block.
+
+ Returns:
+ A string containing the fully qualified name of the
+ instrumentation test method. If parts are missing, then degrades
+ steadily.
+ """
+ full_name_parts = [self._get_class(), self._get_name()]
+ return '#'.join(filter(None, full_name_parts))
+
+ def _get_details(self):
+ """Gets the ouput for the detail section of the TestResultRecord.
+
+ Returns:
+ A string to set for a TestResultRecord's details.
+ """
+ detail_parts = [self._get_full_name(), self._error_message]
+ return '\n'.join(filter(None, detail_parts))
+
+ def _get_extras(self):
+ """Gets the output for the extras section of the TestResultRecord.
+
+ Returns:
+ A string to set for a TestResultRecord's extras.
+ """
+ # Add empty line to start key-value pairs on a new line.
+ extra_parts = ['']
+
+ for value in self._unknown_keys.values():
+ extra_parts.append(value)
+
+ extra_parts.append(
+ self._known_keys[_InstrumentationKnownStatusKeys.STREAM])
+ extra_parts.append(
+ self._known_keys[_InstrumentationKnownResultKeys.SHORTMSG])
+ extra_parts.append(
+ self._known_keys[_InstrumentationKnownResultKeys.LONGMSG])
+ extra_parts.append(
+ self._known_keys[_InstrumentationKnownStatusKeys.ERROR])
+
+ if self._known_keys[
+ _InstrumentationKnownStatusKeys.STACK] not in self._known_keys[
+ _InstrumentationKnownStatusKeys.STREAM]:
+ extra_parts.append(
+ self._known_keys[_InstrumentationKnownStatusKeys.STACK])
+
+ return '\n'.join(filter(None, extra_parts))
+
+ def _is_failed(self):
+ """Determines if the test corresponding to the instrumentation block
+ failed.
+
+ This method can not be used to tell if a test method passed and
+ should not be used for such a purpose.
+
+ Returns:
+ A boolean indicating if the test method failed.
+ """
+ if self._status_code in _InstrumentationStatusCodeCategories.FAIL:
+ return True
+ elif (self._known_keys[_InstrumentationKnownStatusKeys.STACK]
+ and self._status_code !=
+ _InstrumentationStatusCodes.ASSUMPTION_FAILURE):
+ return True
+ elif self._known_keys[_InstrumentationKnownStatusKeys.ERROR]:
+ return True
+ elif self._known_keys[_InstrumentationKnownResultKeys.SHORTMSG]:
+ return True
+ elif self._known_keys[_InstrumentationKnownResultKeys.LONGMSG]:
+ return True
+ else:
+ return False
+
+ def create_test_record(self, mobly_test_class):
+ """Creates a TestResultRecord for the instrumentation block.
+
+ Args:
+ mobly_test_class: string, the name of the Mobly test case
+ executing the instrumentation run.
+
+ Returns:
+ A TestResultRecord with an appropriate signals exception
+ representing the instrumentation test method's result status.
+ """
+ details = self._get_details()
+ extras = self._get_extras()
+
+ tr_record = records.TestResultRecord(
+ t_name=self._get_full_name(),
+ t_class=mobly_test_class,
+ )
+ if self._is_failed():
+ tr_record.test_fail(
+ e=signals.TestFailure(details=details, extras=extras))
+ elif self._status_code in _InstrumentationStatusCodeCategories.SKIPPED:
+ tr_record.test_skip(
+ e=signals.TestSkip(details=details, extras=extras))
+ elif self._status_code in _InstrumentationStatusCodeCategories.PASS:
+ tr_record.test_pass(
+ e=signals.TestPass(details=details, extras=extras))
+ elif self._status_code in _InstrumentationStatusCodeCategories.TIMING:
+ if self._error_message:
+ tr_record.test_error(
+ e=signals.TestError(details=details, extras=extras))
+ else:
+ tr_record = None
+ else:
+ tr_record.test_error(
+ e=signals.TestError(details=details, extras=extras))
+ if self._known_keys[_InstrumentationKnownStatusKeys.STACK]:
+ tr_record.termination_signal.stacktrace = self._known_keys[
+ _InstrumentationKnownStatusKeys.STACK]
+ return tr_record
+
+ def has_completed_result_block_format(self, error_message):
+ """Checks the instrumentation result block for a signal indicating
+ normal completion.
+
+ Args:
+ error_message: string, the error message to give if the
+ instrumentation run did not complete successfully.-
+
+ Returns:
+ A boolean indicating whether or not the instrumentation run passed
+ or failed overall.
+
+ Raises:
+ signals.TestError: Error raised if the instrumentation run did not
+ complete because of a crash or some other issue.
+ """
+ extras = self._get_extras()
+ if _InstrumentationResultSignals.PASS in extras:
+ return True
+ elif _InstrumentationResultSignals.FAIL in extras:
+ return False
+ else:
+ raise signals.TestError(details=error_message, extras=extras)
+
+
+class BaseInstrumentationTestClass(base_test.BaseTestClass):
+ """Base class for all instrumentation test claseses to inherit from.
+
+ This class extends the BaseTestClass to add functionality to run and parse
+ the output of instrumentation runs.
+
+ Attributes:
+ DEFAULT_INSTRUMENTATION_OPTION_PREFIX: string, the default prefix for
+ instrumentation params contained within user params.
+ DEFAULT_INSTRUMENTATION_ERROR_MESSAGE: string, the default error
+ message to set if something has prevented something in the
+ instrumentation test run from completing properly.
+ """
+
+ DEFAULT_INSTRUMENTATION_OPTION_PREFIX = 'instrumentation_option_'
+ DEFAULT_INSTRUMENTATION_ERROR_MESSAGE = ('instrumentation run exited '
+ 'unexpectedly')
+
+ def _previous_block_never_completed(self, current_block, previous_block,
+ new_state):
+ """Checks if the previous instrumentation method block completed.
+
+ Args:
+ current_block: _InstrumentationBlock, the current instrumentation
+ block to check for being a different instrumentation test
+ method.
+ previous_block: _InstrumentationBlock, rhe previous
+ instrumentation block to check for an incomplete status.
+ new_state: _InstrumentationBlockStates, the next state for the
+ parser, used to check for the instrumentation run ending
+ with an incomplete test.
+
+ Returns:
+ A boolean indicating whether the previous instrumentation block
+ completed executing.
+ """
+ if previous_block:
+ previously_timing_block = (
+ previous_block.status_code in
+ _InstrumentationStatusCodeCategories.TIMING)
+ currently_new_block = (
+ current_block.status_code == _InstrumentationStatusCodes.START
+ or new_state == _InstrumentationBlockStates.RESULT)
+ return all([previously_timing_block, currently_new_block])
+ else:
+ return False
+
+ def _create_formatters(self, instrumentation_block, new_state):
+ """Creates the _InstrumentationBlockFormatters for outputting the
+ instrumentation method block that have finished parsing.
+
+ Args:
+ instrumentation_block: _InstrumentationBlock, the current
+ instrumentation method block to create formatters based upon.
+ new_state: _InstrumentationBlockState, the next state that the
+ parser will transition to.
+
+ Returns:
+ A list of the formatters tha need to create and add
+ TestResultRecords to the test results.
+ """
+ formatters = []
+ if self._previous_block_never_completed(
+ current_block=instrumentation_block,
+ previous_block=instrumentation_block.
+ previous_instrumentation_block,
+ new_state=new_state):
+ instrumentation_block.previous_instrumentation_block.set_error_message(
+ self.DEFAULT_INSTRUMENTATION_ERROR_MESSAGE)
+ formatters.append(
+ _InstrumentationBlockFormatter(
+ instrumentation_block.previous_instrumentation_block))
+
+ if not instrumentation_block.is_empty:
+ formatters.append(
+ _InstrumentationBlockFormatter(instrumentation_block))
+ return formatters
+
+ def _transition_instrumentation_block(
+ self,
+ instrumentation_block,
+ new_state=_InstrumentationBlockStates.UNKNOWN):
+ """Transitions and finishes the current instrumentation block.
+
+ Args:
+ instrumentation_block: _InstrumentationBlock, the current
+ instrumentation block to finish.
+ new_state: _InstrumentationBlockState, the next state for the
+ parser to transition to.
+
+ Returns:
+ The new instrumentation block to use for storing parsed
+ instrumentation ouput.
+ """
+ formatters = self._create_formatters(instrumentation_block, new_state)
+ for formatter in formatters:
+ test_record = formatter.create_test_record(self.TAG)
+ if test_record:
+ self.results.add_record(test_record)
+ self.summary_writer.dump(test_record.to_dict(),
+ records.TestSummaryEntryType.RECORD)
+ return instrumentation_block.transition_state(new_state=new_state)
+
+ def _parse_method_block_line(self, instrumentation_block, line):
+ """Parses the instrumnetation method block's line.
+
+ Args:
+ instrumentation_block: _InstrumentationBlock, the current
+ instrumentation method block.
+ line: string, the raw instrumentation output line to parse.
+
+ Returns:
+ The next instrumentation block, which should be used to continue
+ parsing instrumentation output.
+ """
+ if line.startswith(_InstrumentationStructurePrefixes.STATUS):
+ instrumentation_block.set_key(
+ _InstrumentationStructurePrefixes.STATUS, line)
+ return instrumentation_block
+ elif line.startswith(_InstrumentationStructurePrefixes.STATUS_CODE):
+ instrumentation_block.set_status_code(line)
+ return self._transition_instrumentation_block(
+ instrumentation_block)
+ elif line.startswith(_InstrumentationStructurePrefixes.RESULT):
+ # Unexpected transition from method block -> result block
+ instrumentation_block.set_key(
+ _InstrumentationStructurePrefixes.RESULT, line)
+ return self._parse_result_line(
+ self._transition_instrumentation_block(
+ instrumentation_block,
+ new_state=_InstrumentationBlockStates.RESULT,
+ ),
+ line,
+ )
+ else:
+ instrumentation_block.add_value(line)
+ return instrumentation_block
+
+ def _parse_result_block_line(self, instrumentation_block, line):
+ """Parses the instrumentation result block's line.
+
+ Args:
+ instrumentation_block: _InstrumentationBlock, the instrumentation
+ result block for the instrumentation run.
+ line: string, the raw instrumentation output to add to the
+ instrumenation result block's _InstrumentationResultBlocki
+ object.
+
+ Returns:
+ The instrumentation result block for the instrumentation run.
+ """
+ instrumentation_block.add_value(line)
+ return instrumentation_block
+
+ def _parse_unknown_block_line(self, instrumentation_block, line):
+ """Parses a line from the instrumentation output from the UNKNOWN
+ parser state.
+
+ Args:
+ instrumentation_block: _InstrumentationBlock, the current
+ instrumenation block, where the correct categorization it noti
+ yet known.
+ line: string, the raw instrumenation output line to be used to
+ deteremine the correct categorization.
+
+ Returns:
+ The next instrumentation block to continue parsing with. Usually,
+ this is the same instrumentation block but with the state
+ transitioned appropriately.
+ """
+ if line.startswith(_InstrumentationStructurePrefixes.STATUS):
+ return self._parse_method_block_line(
+ self._transition_instrumentation_block(
+ instrumentation_block,
+ new_state=_InstrumentationBlockStates.METHOD,
+ ),
+ line,
+ )
+ elif (line.startswith(_InstrumentationStructurePrefixes.RESULT)
+ or _InstrumentationStructurePrefixes.FAILED in line):
+ return self._parse_result_block_line(
+ self._transition_instrumentation_block(
+ instrumentation_block,
+ new_state=_InstrumentationBlockStates.RESULT,
+ ),
+ line,
+ )
+ else:
+ # This would only really execute if instrumentation failed to start.
+ instrumentation_block.add_value(line)
+ return instrumentation_block
+
+ def _parse_line(self, instrumentation_block, line):
+ """Parses an arbitary line from the instrumentation output based upon
+ the current parser state.
+
+ Args:
+ instrumentation_block: _InstrumentationBlock, an instrumentation
+ block with any of the possible parser states.
+ line: string, the raw instrumentation output line to parse
+ appropriately.
+
+ Returns:
+ The next instrumenation block to continue parsing with.
+ """
+ if instrumentation_block.state == _InstrumentationBlockStates.METHOD:
+ return self._parse_method_block_line(instrumentation_block, line)
+ elif instrumentation_block.state == _InstrumentationBlockStates.RESULT:
+ return self._parse_result_block_line(instrumentation_block, line)
+ else:
+ return self._parse_unknown_block_line(instrumentation_block, line)
+
+ def _finish_parsing(self, instrumentation_block):
+ """Finishes parsing the instrumentation result block for the final
+ instrumentation run status.
+
+ Args:
+ instrumentation_block: _InstrumentationBlock, the instrumentation
+ result block for the instrumenation run. Potentially, thisi
+ could actually be method block if the instrumentation outputi
+ is malformed.
+
+ Returns:
+ A boolean indicating whether the instrumentation run completed
+ with all the tests passing.
+
+ Raises:
+ signals.TestError: Error raised if the instrumentation failed to
+ complete with either a pass or fail status.
+ """
+ formatter = _InstrumentationBlockFormatter(instrumentation_block)
+ return formatter.has_completed_result_block_format(
+ self.DEFAULT_INSTRUMENTATION_ERROR_MESSAGE)
+
+ def parse_instrumentation_options(self, parameters=None):
+ """Returns the options for the instrumentation test from user_params.
+
+ By default, this method assume that the correct instrumentation options
+ all start with DEFAULT_INSTRUMENTATION_OPTION_PREFIX.
+
+ Args:
+ parameters: dict, the key value pairs representing an assortment
+ of parameters including instrumentation options. Usually,
+ this argument will be from self.user_params.
+
+ Returns:
+ A dictionary of options/parameters for the instrumentation tst.
+ """
+ if parameters is None:
+ return {}
+
+ filtered_parameters = {}
+ for parameter_key, parameter_value in parameters.items():
+ if parameter_key.startswith(
+ self.DEFAULT_INSTRUMENTATION_OPTION_PREFIX):
+ option_key = parameter_key[len(
+ self.DEFAULT_INSTRUMENTATION_OPTION_PREFIX):]
+ filtered_parameters[option_key] = parameter_value
+ return filtered_parameters
+
+ def run_instrumentation_test(self,
+ device,
+ package,
+ options=None,
+ prefix=None,
+ runner=None):
+ """Runs instrumentation tests on a device and creates test records.
+
+ Args:
+ device: AndroidDevice, the device to run instrumentation tests on.
+ package: string, the package name of the instrumentation tests.
+ options: dict, Instrumentation options for the instrumentation
+ tests.
+ prefix: string, an optional prefix for parser output for
+ distinguishing between instrumentation test runs.
+ runner: string, the runner to use for the instrumentation package,
+ default to DEFAULT_INSTRUMENTATION_RUNNER.
+
+ Returns:
+ A boolean indicating whether or not all the instrumentation test
+ methods passed.
+
+ Raises:
+ TestError if the instrumentation run crashed or if parsing the
+ output failed.
+ """
+ instrumentation_output = device.adb.instrument(
+ package=package,
+ options=options,
+ runner=runner,
+ )
+ logging.info('Outputting instrumentation test log...')
+ logging.info(instrumentation_output)
+
+ # TODO(winterfrosts): Implement online output generation and parsing.
+ instrumentation_block = _InstrumentationBlock(prefix=prefix)
+ for line in instrumentation_output.splitlines():
+ instrumentation_block = self._parse_line(instrumentation_block,
+ line)
+ return self._finish_parsing(instrumentation_block)
diff --git a/mobly/test_runner.py b/mobly/test_runner.py
index 4cebda7..cf70258 100644
--- a/mobly/test_runner.py
+++ b/mobly/test_runner.py
@@ -124,7 +124,7 @@ def main(argv=None):
def _find_test_class():
"""Finds the test class in a test script.
- Walk through module memebers and find the subclass of BaseTestClass. Only
+ Walk through module members and find the subclass of BaseTestClass. Only
one subclass is allowed in a test script.
Returns:
@@ -392,7 +392,8 @@ class TestRunner(object):
Raises:
ControllerError:
* The controller module has already been registered.
- * The actual number of objects instantiated is less than the `min_number`.
+ * The actual number of objects instantiated is less than the
+ * `min_number`.
* `required` is True and no corresponding config can be found.
* Any other error occurred in the registration process.
diff --git a/tests/mobly/base_instrumentation_test_test.py b/tests/mobly/base_instrumentation_test_test.py
new file mode 100755
index 0000000..32a5343
--- /dev/null
+++ b/tests/mobly/base_instrumentation_test_test.py
@@ -0,0 +1,991 @@
+# Copyright 2017 Google Inc.
+#
+# 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.
+
+import os
+import mock
+import shutil
+import tempfile
+
+from future.tests.base import unittest
+
+from mobly.base_instrumentation_test import BaseInstrumentationTestClass
+from mobly import config_parser
+from mobly import signals
+
+# A mock test package for instrumentation.
+MOCK_TEST_PACKAGE = 'com.my.package.test'
+# A random prefix to test that prefixes are added properly.
+MOCK_PREFIX = 'my_prefix'
+# A mock name for the instrumentation test subclass.
+MOCK_INSTRUMENTATION_TEST_CLASS_NAME = 'MockInstrumentationTest'
+
+
+class MockInstrumentationTest(BaseInstrumentationTestClass):
+ def __init__(self, tmp_dir, user_params={}):
+ mock_test_run_configs = config_parser.TestRunConfig()
+ mock_test_run_configs.summary_writer = mock.Mock()
+ mock_test_run_configs.log_path = tmp_dir
+ mock_test_run_configs.user_params = user_params
+ mock_test_run_configs.reporter = mock.MagicMock()
+ super(MockInstrumentationTest, self).__init__(mock_test_run_configs)
+
+ def run_mock_instrumentation_test(self, instrumentation_output, prefix):
+ mock_device = mock.Mock()
+ mock_device.adb = mock.Mock()
+ mock_device.adb.instrument = mock.MagicMock(
+ return_value=instrumentation_output)
+ return self.run_instrumentation_test(
+ mock_device, MOCK_TEST_PACKAGE, prefix=prefix)
+
+
+class InstrumentationResult(object):
+ def __init__(self):
+ self.error = None
+ self.completed_and_passed = False
+ self.executed = []
+ self.skipped = []
+
+
+class BaseInstrumentationTestTest(unittest.TestCase):
+ def setUp(self):
+ self.tmp_dir = tempfile.mkdtemp()
+
+ def tearDown(self):
+ shutil.rmtree(self.tmp_dir)
+
+ def assert_parse_instrumentation_options(self, user_params,
+ expected_instrumentation_options):
+ mit = MockInstrumentationTest(self.tmp_dir, user_params)
+ instrumentation_options = mit.parse_instrumentation_options(
+ mit.user_params)
+ self.assertEqual(instrumentation_options,
+ expected_instrumentation_options)
+
+ def test_parse_instrumentation_options_with_no_user_params(self):
+ self.assert_parse_instrumentation_options({}, {})
+
+ def test_parse_instrumentation_options_with_no_instrumentation_params(
+ self):
+ self.assert_parse_instrumentation_options(
+ {
+ 'param1': 'val1',
+ 'param2': 'val2',
+ },
+ {},
+ )
+
+ def test_parse_instrumentation_options_with_only_instrumentation_params(
+ self):
+ self.assert_parse_instrumentation_options(
+ {
+ 'instrumentation_option_key1': 'value1',
+ 'instrumentation_option_key2': 'value2',
+ },
+ {'key1': 'value1',
+ 'key2': 'value2'},
+ )
+
+ def test_parse_instrumentation_options_with_mixed_user_params(self):
+ self.assert_parse_instrumentation_options(
+ {
+ 'param1': 'val1',
+ 'param2': 'val2',
+ 'instrumentation_option_key1': 'value1',
+ 'instrumentation_option_key2': 'value2',
+ },
+ {'key1': 'value1',
+ 'key2': 'value2'},
+ )
+
+ def run_instrumentation_test(self, instrumentation_output, prefix=None):
+ mit = MockInstrumentationTest(self.tmp_dir)
+ result = InstrumentationResult()
+ try:
+ result.completed_and_passed = mit.run_mock_instrumentation_test(
+ instrumentation_output, prefix=prefix)
+ except signals.TestError as e:
+ result.error = e
+ result.executed = mit.results.executed
+ result.skipped = mit.results.skipped
+ return result
+
+ def assert_equal_test(self, actual_test, expected_test):
+ (expected_test_name, expected_signal) = expected_test
+ self.assertEqual(actual_test.test_class,
+ MOCK_INSTRUMENTATION_TEST_CLASS_NAME)
+ self.assertEqual(actual_test.test_name, expected_test_name)
+ self.assertIsInstance(actual_test.termination_signal.exception,
+ expected_signal)
+
+ def assert_run_instrumentation_test(self,
+ instrumentation_output,
+ expected_executed=[],
+ expected_skipped=[],
+ expected_completed_and_passed=False,
+ expected_has_error=False,
+ prefix=None):
+ result = self.run_instrumentation_test(
+ instrumentation_output, prefix=prefix)
+ if expected_has_error:
+ self.assertIsInstance(result.error, signals.TestError)
+ else:
+ self.assertIsNone(result.error)
+ self.assertEquals(result.completed_and_passed,
+ expected_completed_and_passed)
+ self.assertEqual(len(result.executed), len(expected_executed))
+ for actual_test, expected_test in zip(result.executed,
+ expected_executed):
+ self.assert_equal_test(actual_test, expected_test)
+ self.assertEqual(len(result.skipped), len(expected_skipped))
+ for actual_test, expected_test in zip(result.skipped,
+ expected_skipped):
+ self.assert_equal_test(actual_test, expected_test)
+
+ def test_run_instrumentation_test_with_invalid_syntax(self):
+ instrumentation_output = """\
+usage: am [subcommand] [options]
+usage: am start [-D] [-N] [-W] [-P <FILE>] [--start-profiler <FILE>]
+ [--sampling INTERVAL] [-R COUNT] [-S]
+
+am start: start an Activity. Options are:
+ -D: enable debugging
+
+am startservice: start a Service. Options are:
+ --user <USER_ID> | current: Specify which user to run as; if not
+ specified then run as the current user.
+
+am task lock: bring <TASK_ID> to the front and don't allow other tasks to run.
+
+<INTENT> specifications include these flags and arguments:
+ [-a <ACTION>] [-d <DATA_URI>] [-t <MIME_TYPE>]
+ [-c <CATEGORY> [-c <CATEGORY>] ...]
+
+Error: Bad component name: /
+"""
+ self.assert_run_instrumentation_test(
+ instrumentation_output, expected_has_error=True)
+
+ def test_run_instrumentation_test_with_no_output(self):
+ instrumentation_output = """\
+"""
+ self.assert_run_instrumentation_test(
+ instrumentation_output, expected_has_error=True)
+
+ def test_run_instrumentation_test_with_missing_test_package(self):
+ instrumentation_output = """\
+android.util.AndroidException: INSTRUMENTATION_FAILED: com.my.package.test/com.my.package.test.runner.MyRunner
+ at com.android.commands.am.Am.runInstrument(Am.java:897)
+ at com.android.commands.am.Am.onRun(Am.java:405)
+ at com.android.internal.os.BaseCommand.run(BaseCommand.java:51)
+ at com.android.commands.am.Am.main(Am.java:124)
+ at com.android.internal.os.RuntimeInit.nativeFinishInit(Native Method)
+ at com.android.internal.os.RuntimeInit.main(RuntimeInit.java:262)
+INSTRUMENTATION_STATUS: id=ActivityManagerService
+INSTRUMENTATION_STATUS: Error=Unable to find instrumentation info for: ComponentInfo{com.my.package.test/com.my.package.test.runner.MyRunner}
+INSTRUMENTATION_STATUS_CODE: -1"""
+ self.assert_run_instrumentation_test(
+ instrumentation_output, expected_has_error=True)
+
+ def test_run_instrumentation_test_with_missing_runner(self):
+ instrumentation_output = """\
+android.util.AndroidException: INSTRUMENTATION_FAILED: com.my.package.test/com.my.package.test.runner
+INSTRUMENTATION_STATUS: id=ActivityManagerService
+INSTRUMENTATION_STATUS: Error=Unable to find instrumentation info for: ComponentInfo{com.my.package.test/com.my.package.test.runner}
+INSTRUMENTATION_STATUS_CODE: -1
+ at com.android.commands.am.Am.runInstrument(Am.java:897)
+ at com.android.commands.am.Am.onRun(Am.java:405)
+ at com.android.internal.os.BaseCommand.run(BaseCommand.java:51)
+ at com.android.commands.am.Am.main(Am.java:124)
+ at com.android.internal.os.RuntimeInit.nativeFinishInit(Native Method)
+ at com.android.internal.os.RuntimeInit.main(RuntimeInit.java:262)"""
+ self.assert_run_instrumentation_test(
+ instrumentation_output, expected_has_error=True)
+
+ def test_run_instrumentation_test_with_no_tests(self):
+ instrumentation_output = """\
+INSTRUMENTATION_RESULT: stream=
+
+Time: 0.001
+
+OK (0 tests)
+
+
+INSTRUMENTATION_CODE: -1
+"""
+ self.assert_run_instrumentation_test(
+ instrumentation_output, expected_completed_and_passed=True)
+
+ def test_run_instrumentation_test_with_passing_test(self):
+ instrumentation_output = """\
+INSTRUMENTATION_STATUS: numtests=1
+INSTRUMENTATION_STATUS: stream=
+com.my.package.test.BasicTest:
+INSTRUMENTATION_STATUS: id=AndroidJUnitRunner
+INSTRUMENTATION_STATUS: test=basicTest
+INSTRUMENTATION_STATUS: class=com.my.package.test.BasicTest
+INSTRUMENTATION_STATUS: current=1
+INSTRUMENTATION_STATUS_CODE: 1
+INSTRUMENTATION_STATUS: numtests=1
+INSTRUMENTATION_STATUS: stream=.
+INSTRUMENTATION_STATUS: id=AndroidJUnitRunner
+INSTRUMENTATION_STATUS: test=basicTest
+INSTRUMENTATION_STATUS: class=com.my.package.test.BasicTest
+INSTRUMENTATION_STATUS: current=1
+INSTRUMENTATION_STATUS_CODE: 0
+INSTRUMENTATION_RESULT: stream=
+
+Time: 0.214
+
+OK (1 test)
+
+
+INSTRUMENTATION_CODE: -1
+"""
+ expected_executed = [
+ ('com.my.package.test.BasicTest#basicTest', signals.TestPass),
+ ]
+ self.assert_run_instrumentation_test(
+ instrumentation_output,
+ expected_executed=expected_executed,
+ expected_completed_and_passed=True)
+
+ def test_run_instrumentation_test_with_prefix_test(self):
+ instrumentation_output = """\
+INSTRUMENTATION_STATUS: numtests=1
+INSTRUMENTATION_STATUS: stream=
+com.my.package.test.BasicTest:
+INSTRUMENTATION_STATUS: id=AndroidJUnitRunner
+INSTRUMENTATION_STATUS: test=basicTest
+INSTRUMENTATION_STATUS: class=com.my.package.test.BasicTest
+INSTRUMENTATION_STATUS: current=1
+INSTRUMENTATION_STATUS_CODE: 1
+INSTRUMENTATION_STATUS: numtests=1
+INSTRUMENTATION_STATUS: stream=.
+INSTRUMENTATION_STATUS: id=AndroidJUnitRunner
+INSTRUMENTATION_STATUS: test=basicTest
+INSTRUMENTATION_STATUS: class=com.my.package.test.BasicTest
+INSTRUMENTATION_STATUS: current=1
+INSTRUMENTATION_STATUS_CODE: 0
+INSTRUMENTATION_RESULT: stream=
+
+Time: 0.214
+
+OK (1 test)
+
+
+INSTRUMENTATION_CODE: -1
+"""
+ expected_executed = [
+ ('%s.com.my.package.test.BasicTest#basicTest' % MOCK_PREFIX,
+ signals.TestPass),
+ ]
+ self.assert_run_instrumentation_test(
+ instrumentation_output,
+ expected_executed=expected_executed,
+ expected_completed_and_passed=True,
+ prefix=MOCK_PREFIX)
+
+ def test_run_instrumentation_test_with_failing_test(self):
+ instrumentation_output = """\
+INSTRUMENTATION_STATUS: class=com.my.package.test.BasicTest
+INSTRUMENTATION_STATUS: current=1
+INSTRUMENTATION_STATUS: id=AndroidJUnitRunner
+INSTRUMENTATION_STATUS: numtests=1
+INSTRUMENTATION_STATUS: stream=
+com.my.package.test.BasicTest:
+INSTRUMENTATION_STATUS: test=failingTest
+INSTRUMENTATION_STATUS_CODE: 1
+INSTRUMENTATION_STATUS: class=com.my.package.test.BasicTest
+INSTRUMENTATION_STATUS: current=1
+INSTRUMENTATION_STATUS: id=AndroidJUnitRunner
+INSTRUMENTATION_STATUS: numtests=1
+INSTRUMENTATION_STATUS: stack=java.lang.UnsupportedOperationException: dummy failing test
+ at com.my.package.test.BasicTest.failingTest(BasicTest.java:38)
+ at java.lang.reflect.Method.invoke(Native Method)
+ at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:57)
+ at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
+ at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:59)
+ at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
+ at android.support.test.internal.runner.junit4.statement.RunBefores.evaluate(RunBefores.java:80)
+ at android.support.test.internal.runner.junit4.statement.RunAfters.evaluate(RunAfters.java:61)
+ at android.support.test.rule.ActivityTestRule$ActivityStatement.evaluate(ActivityTestRule.java:433)
+ at com.my.package.test.BaseTest$3.evaluate(BaseTest.java:96)
+ at com.my.package.test.BaseTest$4.evaluate(BaseTest.java:109)
+ at com.my.package.test.BaseTest$2.evaluate(BaseTest.java:77)
+ at org.junit.rules.TestWatcher$1.evaluate(TestWatcher.java:55)
+ at org.junit.rules.TestWatcher$1.evaluate(TestWatcher.java:55)
+ at org.junit.rules.RunRules.evaluate(RunRules.java:20)
+ at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:81)
+ at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:327)
+ at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:84)
+ at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
+ at org.junit.runners.ParentRunner$3.run(ParentRunner.java:292)
+ at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:73)
+ at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:290)
+ at org.junit.runners.ParentRunner.access$000(ParentRunner.java:60)
+ at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:270)
+ at org.junit.runners.ParentRunner.run(ParentRunner.java:370)
+ at android.support.test.runner.AndroidJUnit4.run(AndroidJUnit4.java:99)
+ at org.junit.runners.Suite.runChild(Suite.java:128)
+ at org.junit.runners.Suite.runChild(Suite.java:27)
+ at org.junit.runners.ParentRunner$3.run(ParentRunner.java:292)
+ at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:73)
+ at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:290)
+ at org.junit.runners.ParentRunner.access$000(ParentRunner.java:60)
+ at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:270)
+ at org.junit.runners.ParentRunner.run(ParentRunner.java:370)
+ at org.junit.runners.Suite.runChild(Suite.java:128)
+ at org.junit.runners.Suite.runChild(Suite.java:27)
+ at org.junit.runners.ParentRunner$3.run(ParentRunner.java:292)
+ at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:73)
+ at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:290)
+ at org.junit.runners.ParentRunner.access$000(ParentRunner.java:60)
+ at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:270)
+ at org.junit.runners.ParentRunner.run(ParentRunner.java:370)
+ at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
+ at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
+ at android.support.test.internal.runner.TestExecutor.execute(TestExecutor.java:56)
+ at com.my.package.test.BaseRunner.runTests(BaseRunner.java:344)
+ at com.my.package.test.BaseRunner.onStart(BaseRunner.java:330)
+ at com.my.package.test.runner.MyRunner.onStart(MyRunner.java:253)
+ at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:2074)
+
+INSTRUMENTATION_STATUS: stream=
+Error in failingTest(com.my.package.test.BasicTest):
+java.lang.UnsupportedOperationException: dummy failing test
+ at com.my.package.test.BasicTest.failingTest(BasicTest.java:38)
+ at java.lang.reflect.Method.invoke(Native Method)
+ at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:57)
+ at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
+ at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:59)
+ at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
+ at android.support.test.internal.runner.junit4.statement.RunBefores.evaluate(RunBefores.java:80)
+ at android.support.test.internal.runner.junit4.statement.RunAfters.evaluate(RunAfters.java:61)
+ at android.support.test.rule.ActivityTestRule$ActivityStatement.evaluate(ActivityTestRule.java:433)
+ at com.my.package.test.BaseTest$3.evaluate(BaseTest.java:96)
+ at com.my.package.test.BaseTest$4.evaluate(BaseTest.java:109)
+ at com.my.package.test.BaseTest$2.evaluate(BaseTest.java:77)
+ at org.junit.rules.TestWatcher$1.evaluate(TestWatcher.java:55)
+ at org.junit.rules.TestWatcher$1.evaluate(TestWatcher.java:55)
+ at org.junit.rules.RunRules.evaluate(RunRules.java:20)
+ at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:81)
+ at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:327)
+ at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:84)
+ at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
+ at org.junit.runners.ParentRunner$3.run(ParentRunner.java:292)
+ at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:73)
+ at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:290)
+ at org.junit.runners.ParentRunner.access$000(ParentRunner.java:60)
+ at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:270)
+ at org.junit.runners.ParentRunner.run(ParentRunner.java:370)
+ at android.support.test.runner.AndroidJUnit4.run(AndroidJUnit4.java:99)
+ at org.junit.runners.Suite.runChild(Suite.java:128)
+ at org.junit.runners.Suite.runChild(Suite.java:27)
+ at org.junit.runners.ParentRunner$3.run(ParentRunner.java:292)
+ at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:73)
+ at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:290)
+ at org.junit.runners.ParentRunner.access$000(ParentRunner.java:60)
+ at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:270)
+ at org.junit.runners.ParentRunner.run(ParentRunner.java:370)
+ at org.junit.runners.Suite.runChild(Suite.java:128)
+ at org.junit.runners.Suite.runChild(Suite.java:27)
+ at org.junit.runners.ParentRunner$3.run(ParentRunner.java:292)
+ at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:73)
+ at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:290)
+ at org.junit.runners.ParentRunner.access$000(ParentRunner.java:60)
+ at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:270)
+ at org.junit.runners.ParentRunner.run(ParentRunner.java:370)
+ at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
+ at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
+ at android.support.test.internal.runner.TestExecutor.execute(TestExecutor.java:56)
+ at com.my.package.test.BaseRunner.runTests(BaseRunner.java:344)
+ at com.my.package.test.BaseRunner.onStart(BaseRunner.java:330)
+ at com.my.package.test.runner.MyRunner.onStart(MyRunner.java:253)
+ at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:2074)
+
+INSTRUMENTATION_STATUS: test=failingTest
+INSTRUMENTATION_STATUS_CODE: -2
+INSTRUMENTATION_RESULT: stream=
+
+Time: 1.92
+There was 1 failure:
+1) failingTest(com.my.package.test.BasicTest)
+java.lang.UnsupportedOperationException: dummy failing test
+ at com.my.package.test.BasicTest.failingTest(BasicTest.java:38)
+ at java.lang.reflect.Method.invoke(Native Method)
+ at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:57)
+ at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
+ at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:59)
+ at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
+ at android.support.test.internal.runner.junit4.statement.RunBefores.evaluate(RunBefores.java:80)
+ at android.support.test.internal.runner.junit4.statement.RunAfters.evaluate(RunAfters.java:61)
+ at android.support.test.rule.ActivityTestRule$ActivityStatement.evaluate(ActivityTestRule.java:433)
+ at com.my.package.test.BaseTest$3.evaluate(BaseTest.java:96)
+ at com.my.package.test.BaseTest$4.evaluate(BaseTest.java:109)
+ at com.my.package.test.BaseTest$2.evaluate(BaseTest.java:77)
+ at org.junit.rules.TestWatcher$1.evaluate(TestWatcher.java:55)
+ at org.junit.rules.TestWatcher$1.evaluate(TestWatcher.java:55)
+ at org.junit.rules.RunRules.evaluate(RunRules.java:20)
+ at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:81)
+ at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:327)
+ at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:84)
+ at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
+ at org.junit.runners.ParentRunner$3.run(ParentRunner.java:292)
+ at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:73)
+ at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:290)
+ at org.junit.runners.ParentRunner.access$000(ParentRunner.java:60)
+ at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:270)
+ at org.junit.runners.ParentRunner.run(ParentRunner.java:370)
+ at android.support.test.runner.AndroidJUnit4.run(AndroidJUnit4.java:99)
+ at org.junit.runners.Suite.runChild(Suite.java:128)
+ at org.junit.runners.Suite.runChild(Suite.java:27)
+ at org.junit.runners.ParentRunner$3.run(ParentRunner.java:292)
+ at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:73)
+ at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:290)
+ at org.junit.runners.ParentRunner.access$000(ParentRunner.java:60)
+ at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:270)
+ at org.junit.runners.ParentRunner.run(ParentRunner.java:370)
+ at org.junit.runners.Suite.runChild(Suite.java:128)
+ at org.junit.runners.Suite.runChild(Suite.java:27)
+ at org.junit.runners.ParentRunner$3.run(ParentRunner.java:292)
+ at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:73)
+ at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:290)
+ at org.junit.runners.ParentRunner.access$000(ParentRunner.java:60)
+ at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:270)
+ at org.junit.runners.ParentRunner.run(ParentRunner.java:370)
+ at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
+ at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
+ at android.support.test.internal.runner.TestExecutor.execute(TestExecutor.java:56)
+ at com.my.package.test.BaseRunner.runTests(BaseRunner.java:344)
+ at com.my.package.test.BaseRunner.onStart(BaseRunner.java:330)
+ at com.my.package.test.runner.MyRunner.onStart(MyRunner.java:253)
+ at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:2074)
+
+FAILURES!!!
+Tests run: 1, Failures: 1
+
+
+INSTRUMENTATION_CODE: -1"""
+ expected_executed = [
+ ('com.my.package.test.BasicTest#failingTest', signals.TestFailure),
+ ]
+ self.assert_run_instrumentation_test(
+ instrumentation_output, expected_executed=expected_executed)
+
+ def test_run_instrumentation_test_with_assumption_failure_test(self):
+ instrumentation_output = """\
+INSTRUMENTATION_STATUS: class=com.my.package.test.BasicTest
+INSTRUMENTATION_STATUS: current=1
+INSTRUMENTATION_STATUS: id=AndroidJUnitRunner
+INSTRUMENTATION_STATUS: numtests=1
+INSTRUMENTATION_STATUS: stream=
+com.my.package.test.BasicTest:
+INSTRUMENTATION_STATUS: test=assumptionFailureTest
+INSTRUMENTATION_STATUS_CODE: 1
+INSTRUMENTATION_STATUS: class=com.my.package.test.BasicTest
+INSTRUMENTATION_STATUS: current=1
+INSTRUMENTATION_STATUS: id=AndroidJUnitRunner
+INSTRUMENTATION_STATUS: numtests=1
+INSTRUMENTATION_STATUS: stack=org.junit.AssumptionViolatedException: Assumption failure reason
+ at org.junit.Assume.assumeTrue(Assume.java:59)
+ at org.junit.Assume.assumeFalse(Assume.java:66)
+ at com.my.package.test.BasicTest.assumptionFailureTest(BasicTest.java:63)
+ at java.lang.reflect.Method.invoke(Native Method)
+ at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:57)
+ at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
+ at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:59)
+ at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
+ at android.support.test.internal.runner.junit4.statement.RunBefores.evaluate(RunBefores.java:80)
+ at android.support.test.internal.runner.junit4.statement.RunAfters.evaluate(RunAfters.java:61)
+ at android.support.test.rule.ActivityTestRule$ActivityStatement.evaluate(ActivityTestRule.java:433)
+ at com.my.package.test.MyBaseTest$3.evaluate(MyBaseTest.java:96)
+ at com.my.package.test.MyBaseTest$4.evaluate(MyBaseTest.java:109)
+ at com.my.package.test.MyBaseTest$2.evaluate(MyBaseTest.java:77)
+ at org.junit.rules.TestWatcher$1.evaluate(TestWatcher.java:55)
+ at org.junit.rules.TestWatcher$1.evaluate(TestWatcher.java:55)
+ at org.junit.rules.RunRules.evaluate(RunRules.java:20)
+ at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:81)
+ at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:327)
+ at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:84)
+ at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
+ at org.junit.runners.ParentRunner$3.run(ParentRunner.java:292)
+ at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:73)
+ at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:290)
+ at org.junit.runners.ParentRunner.access$000(ParentRunner.java:60)
+ at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:270)
+ at org.junit.runners.ParentRunner.run(ParentRunner.java:370)
+ at android.support.test.runner.AndroidJUnit4.run(AndroidJUnit4.java:99)
+ at org.junit.runners.Suite.runChild(Suite.java:128)
+ at org.junit.runners.Suite.runChild(Suite.java:27)
+ at org.junit.runners.ParentRunner$3.run(ParentRunner.java:292)
+ at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:73)
+ at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:290)
+ at org.junit.runners.ParentRunner.access$000(ParentRunner.java:60)
+ at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:270)
+ at org.junit.runners.ParentRunner.run(ParentRunner.java:370)
+ at org.junit.runners.Suite.runChild(Suite.java:128)
+ at org.junit.runners.Suite.runChild(Suite.java:27)
+ at org.junit.runners.ParentRunner$3.run(ParentRunner.java:292)
+ at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:73)
+ at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:290)
+ at org.junit.runners.ParentRunner.access$000(ParentRunner.java:60)
+ at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:270)
+ at org.junit.runners.ParentRunner.run(ParentRunner.java:370)
+ at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
+ at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
+ at android.support.test.internal.runner.TestExecutor.execute(TestExecutor.java:56)
+ at com.my.package.test.runner.BaseRunner.runTests(BaseRunner.java:344)
+ at com.my.package.test.runner.BaseRunner.onStart(BaseRunner.java:330)
+ at com.my.package.test.runner.BaseRunner.onStart(BaseRunner.java:253)
+ at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:2074)
+
+INSTRUMENTATION_STATUS: stream=
+com.my.package.test.BasicTest:
+INSTRUMENTATION_STATUS: test=assumptionFailureTest
+INSTRUMENTATION_STATUS_CODE: -4
+INSTRUMENTATION_RESULT: stream=
+
+Time: 3.139
+
+OK (1 test)
+
+
+INSTRUMENTATION_CODE: -1"""
+ expected_skipped = [
+ ('com.my.package.test.BasicTest#assumptionFailureTest',
+ signals.TestSkip),
+ ]
+ self.assert_run_instrumentation_test(
+ instrumentation_output,
+ expected_skipped=expected_skipped,
+ expected_completed_and_passed=True)
+
+ def test_run_instrumentation_test_with_ignored_test(self):
+ instrumentation_output = """\
+INSTRUMENTATION_STATUS: class=com.my.package.test.BasicTest
+INSTRUMENTATION_STATUS: current=1
+INSTRUMENTATION_STATUS: id=AndroidJUnitRunner
+INSTRUMENTATION_STATUS: numtests=1
+INSTRUMENTATION_STATUS: stream=
+com.my.package.test.BasicTest:
+INSTRUMENTATION_STATUS: test=ignoredTest
+INSTRUMENTATION_STATUS_CODE: 1
+INSTRUMENTATION_STATUS: class=com.my.package.test.BasicTest
+INSTRUMENTATION_STATUS: current=1
+INSTRUMENTATION_STATUS: id=AndroidJUnitRunner
+INSTRUMENTATION_STATUS: numtests=1
+INSTRUMENTATION_STATUS: stream=
+com.my.package.test.BasicTest:
+INSTRUMENTATION_STATUS: test=ignoredTest
+INSTRUMENTATION_STATUS_CODE: -3
+INSTRUMENTATION_RESULT: stream=
+
+Time: 0.007
+
+OK (0 tests)
+
+
+INSTRUMENTATION_CODE: -1"""
+ expected_skipped = [
+ ('com.my.package.test.BasicTest#ignoredTest', signals.TestSkip),
+ ]
+ self.assert_run_instrumentation_test(
+ instrumentation_output,
+ expected_skipped=expected_skipped,
+ expected_completed_and_passed=True)
+
+ def test_run_instrumentation_test_with_crashed_test(self):
+ instrumentation_output = """\
+INSTRUMENTATION_STATUS: class=com.my.package.test.BasicTest
+INSTRUMENTATION_STATUS: current=1
+INSTRUMENTATION_STATUS: id=AndroidJUnitRunner
+INSTRUMENTATION_STATUS: numtests=1
+INSTRUMENTATION_STATUS: stream=
+com.my.package.test.BasicTest:
+INSTRUMENTATION_STATUS: test=crashTest
+INSTRUMENTATION_STATUS_CODE: 1
+INSTRUMENTATION_RESULT: shortMsg=Process crashed.
+INSTRUMENTATION_CODE: 0"""
+ expected_executed = [
+ ('com.my.package.test.BasicTest#crashTest', signals.TestError),
+ ]
+ self.assert_run_instrumentation_test(
+ instrumentation_output,
+ expected_executed=expected_executed,
+ expected_has_error=True)
+
+ def test_run_instrumentation_test_with_crashing_test(self):
+ instrumentation_output = """\
+INSTRUMENTATION_STATUS: class=com.my.package.test.BasicTest
+INSTRUMENTATION_STATUS: current=1
+INSTRUMENTATION_STATUS: id=AndroidJUnitRunner
+INSTRUMENTATION_STATUS: numtests=2
+INSTRUMENTATION_STATUS: stream=
+com.my.package.test.BasicTest:
+INSTRUMENTATION_STATUS: test=crashAndRecover1Test
+INSTRUMENTATION_STATUS_CODE: 1
+INSTRUMENTATION_STATUS: class=com.my.package.test.BasicTest
+INSTRUMENTATION_STATUS: current=2
+INSTRUMENTATION_STATUS: id=AndroidJUnitRunner
+INSTRUMENTATION_STATUS: numtests=2
+INSTRUMENTATION_STATUS: stream=
+com.my.package.test.BasicTest:
+INSTRUMENTATION_STATUS: test=crashAndRecover2Test
+INSTRUMENTATION_STATUS_CODE: 1
+INSTRUMENTATION_RESULT: stream=
+
+Time: 6.342
+
+OK (2 tests)
+
+
+INSTRUMENTATION_CODE: -1"""
+ expected_executed = [
+ ('com.my.package.test.BasicTest#crashAndRecover1Test',
+ signals.TestError),
+ ('com.my.package.test.BasicTest#crashAndRecover2Test',
+ signals.TestError),
+ ]
+ self.assert_run_instrumentation_test(
+ instrumentation_output,
+ expected_executed=expected_executed,
+ expected_completed_and_passed=True)
+
+ def test_run_instrumentation_test_with_runner_setup_crash(self):
+ instrumentation_output = """\
+INSTRUMENTATION_RESULT: shortMsg=Process crashed.
+INSTRUMENTATION_CODE: 0"""
+ self.assert_run_instrumentation_test(
+ instrumentation_output, expected_has_error=True)
+
+ def test_run_instrumentation_test_with_runner_teardown_crash(self):
+ instrumentation_output = """\
+INSTRUMENTATION_STATUS: numtests=1
+INSTRUMENTATION_STATUS: stream=
+com.my.package.test.BasicTest:
+INSTRUMENTATION_STATUS: id=AndroidJUnitRunner
+INSTRUMENTATION_STATUS: test=basicTest
+INSTRUMENTATION_STATUS: class=com.my.package.test.BasicTest
+INSTRUMENTATION_STATUS: current=1
+INSTRUMENTATION_STATUS_CODE: 1
+INSTRUMENTATION_STATUS: numtests=1
+INSTRUMENTATION_STATUS: stream=.
+INSTRUMENTATION_STATUS: id=AndroidJUnitRunner
+INSTRUMENTATION_STATUS: test=basicTest
+INSTRUMENTATION_STATUS: class=com.my.package.test.BasicTest
+INSTRUMENTATION_STATUS: current=1
+INSTRUMENTATION_STATUS_CODE: 0
+INSTRUMENTATION_RESULT: shortMsg=Process crashed.
+INSTRUMENTATION_CODE: 0
+"""
+ expected_executed = [
+ ('com.my.package.test.BasicTest#basicTest', signals.TestPass),
+ ]
+ self.assert_run_instrumentation_test(
+ instrumentation_output,
+ expected_executed=expected_executed,
+ expected_has_error=True)
+
+ def test_run_instrumentation_test_with_multiple_tests(self):
+ instrumentation_output = """\
+INSTRUMENTATION_STATUS: class=com.my.package.test.BasicTest
+INSTRUMENTATION_STATUS: current=1
+INSTRUMENTATION_STATUS: id=AndroidJUnitRunner
+INSTRUMENTATION_STATUS: numtests=4
+INSTRUMENTATION_STATUS: stream=
+com.my.package.test.BasicTest:
+INSTRUMENTATION_STATUS: test=failingTest
+INSTRUMENTATION_STATUS_CODE: 1
+INSTRUMENTATION_STATUS: class=com.my.package.test.BasicTest
+INSTRUMENTATION_STATUS: current=1
+INSTRUMENTATION_STATUS: id=AndroidJUnitRunner
+INSTRUMENTATION_STATUS: numtests=4
+INSTRUMENTATION_STATUS: stack=java.lang.UnsupportedOperationException: dummy failing test
+ at com.my.package.test.BasicTest.failingTest(BasicTest.java:40)
+ at java.lang.reflect.Method.invoke(Native Method)
+ at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:57)
+ at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
+ at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:59)
+ at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
+ at android.support.test.internal.runner.junit4.statement.RunBefores.evaluate(RunBefores.java:80)
+ at android.support.test.internal.runner.junit4.statement.RunAfters.evaluate(RunAfters.java:61)
+ at android.support.test.rule.ActivityTestRule$ActivityStatement.evaluate(ActivityTestRule.java:433)
+ at com.my.package.test.BaseTest$3.evaluate(BaseTest.java:96)
+ at com.my.package.test.BaseTest$4.evaluate(BaseTest.java:109)
+ at com.my.package.test.BaseTest$2.evaluate(BaseTest.java:77)
+ at org.junit.rules.TestWatcher$1.evaluate(TestWatcher.java:55)
+ at org.junit.rules.TestWatcher$1.evaluate(TestWatcher.java:55)
+ at org.junit.rules.RunRules.evaluate(RunRules.java:20)
+ at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:81)
+ at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:327)
+ at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:84)
+ at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
+ at org.junit.runners.ParentRunner$3.run(ParentRunner.java:292)
+ at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:73)
+ at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:290)
+ at org.junit.runners.ParentRunner.access$000(ParentRunner.java:60)
+ at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:270)
+ at org.junit.runners.ParentRunner.run(ParentRunner.java:370)
+ at android.support.test.runner.AndroidJUnit4.run(AndroidJUnit4.java:99)
+ at org.junit.runners.Suite.runChild(Suite.java:128)
+ at org.junit.runners.Suite.runChild(Suite.java:27)
+ at org.junit.runners.ParentRunner$3.run(ParentRunner.java:292)
+ at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:73)
+ at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:290)
+ at org.junit.runners.ParentRunner.access$000(ParentRunner.java:60)
+ at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:270)
+ at org.junit.runners.ParentRunner.run(ParentRunner.java:370)
+ at org.junit.runners.Suite.runChild(Suite.java:128)
+ at org.junit.runners.Suite.runChild(Suite.java:27)
+ at org.junit.runners.ParentRunner$3.run(ParentRunner.java:292)
+ at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:73)
+ at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:290)
+ at org.junit.runners.ParentRunner.access$000(ParentRunner.java:60)
+ at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:270)
+ at org.junit.runners.ParentRunner.run(ParentRunner.java:370)
+ at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
+ at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
+ at android.support.test.internal.runner.TestExecutor.execute(TestExecutor.java:56)
+ at com.my.package.test.BaseRunner.runTests(BaseRunner.java:344)
+ at com.my.package.test.BaseRunner.onStart(BaseRunner.java:330)
+ at com.my.package.test.runner.MyRunner.onStart(MyRunner.java:253)
+ at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:2074)
+
+INSTRUMENTATION_STATUS: stream=
+Error in failingTest(com.my.package.test.BasicTest):
+java.lang.UnsupportedOperationException: dummy failing test
+ at com.my.package.test.BasicTest.failingTest(BasicTest.java:40)
+ at java.lang.reflect.Method.invoke(Native Method)
+ at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:57)
+ at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
+ at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:59)
+ at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
+ at android.support.test.internal.runner.junit4.statement.RunBefores.evaluate(RunBefores.java:80)
+ at android.support.test.internal.runner.junit4.statement.RunAfters.evaluate(RunAfters.java:61)
+ at android.support.test.rule.ActivityTestRule$ActivityStatement.evaluate(ActivityTestRule.java:433)
+ at com.my.package.test.BaseTest$3.evaluate(BaseTest.java:96)
+ at com.my.package.test.BaseTest$4.evaluate(BaseTest.java:109)
+ at com.my.package.test.BaseTest$2.evaluate(BaseTest.java:77)
+ at org.junit.rules.TestWatcher$1.evaluate(TestWatcher.java:55)
+ at org.junit.rules.TestWatcher$1.evaluate(TestWatcher.java:55)
+ at org.junit.rules.RunRules.evaluate(RunRules.java:20)
+ at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:81)
+ at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:327)
+ at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:84)
+ at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
+ at org.junit.runners.ParentRunner$3.run(ParentRunner.java:292)
+ at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:73)
+ at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:290)
+ at org.junit.runners.ParentRunner.access$000(ParentRunner.java:60)
+ at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:270)
+ at org.junit.runners.ParentRunner.run(ParentRunner.java:370)
+ at android.support.test.runner.AndroidJUnit4.run(AndroidJUnit4.java:99)
+ at org.junit.runners.Suite.runChild(Suite.java:128)
+ at org.junit.runners.Suite.runChild(Suite.java:27)
+ at org.junit.runners.ParentRunner$3.run(ParentRunner.java:292)
+ at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:73)
+ at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:290)
+ at org.junit.runners.ParentRunner.access$000(ParentRunner.java:60)
+ at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:270)
+ at org.junit.runners.ParentRunner.run(ParentRunner.java:370)
+ at org.junit.runners.Suite.runChild(Suite.java:128)
+ at org.junit.runners.Suite.runChild(Suite.java:27)
+ at org.junit.runners.ParentRunner$3.run(ParentRunner.java:292)
+ at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:73)
+ at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:290)
+ at org.junit.runners.ParentRunner.access$000(ParentRunner.java:60)
+ at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:270)
+ at org.junit.runners.ParentRunner.run(ParentRunner.java:370)
+ at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
+ at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
+ at android.support.test.internal.runner.TestExecutor.execute(TestExecutor.java:56)
+ at com.my.package.test.BaseRunner.runTests(BaseRunner.java:344)
+ at com.my.package.test.BaseRunner.onStart(BaseRunner.java:330)
+ at com.my.package.test.runner.MyRunner.onStart(MyRunner.java:253)
+ at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:2074)
+
+INSTRUMENTATION_STATUS: test=failingTest
+INSTRUMENTATION_STATUS_CODE: -2
+INSTRUMENTATION_STATUS: class=com.my.package.test.BasicTest
+INSTRUMENTATION_STATUS: current=2
+INSTRUMENTATION_STATUS: id=AndroidJUnitRunner
+INSTRUMENTATION_STATUS: numtests=4
+INSTRUMENTATION_STATUS: stream=
+INSTRUMENTATION_STATUS: test=assumptionFailureTest
+INSTRUMENTATION_STATUS_CODE: 1
+INSTRUMENTATION_STATUS: class=com.my.package.test.BasicTest
+INSTRUMENTATION_STATUS: current=2
+INSTRUMENTATION_STATUS: id=AndroidJUnitRunner
+INSTRUMENTATION_STATUS: numtests=4
+INSTRUMENTATION_STATUS: stack=org.junit.AssumptionViolatedException: Assumption failure reason
+ at org.junit.Assume.assumeTrue(Assume.java:59)
+ at com.my.package.test.BasicTest.assumptionFailureTest(BasicTest.java:61)
+ at java.lang.reflect.Method.invoke(Native Method)
+ at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:57)
+ at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
+ at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:59)
+ at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
+ at android.support.test.internal.runner.junit4.statement.RunBefores.evaluate(RunBefores.java:80)
+ at android.support.test.internal.runner.junit4.statement.RunAfters.evaluate(RunAfters.java:61)
+ at android.support.test.rule.ActivityTestRule$ActivityStatement.evaluate(ActivityTestRule.java:433)
+ at com.my.package.test.BaseTest$3.evaluate(BaseTest.java:96)
+ at com.my.package.test.BaseTest$4.evaluate(BaseTest.java:109)
+ at com.my.package.test.BaseTest$2.evaluate(BaseTest.java:77)
+ at org.junit.rules.TestWatcher$1.evaluate(TestWatcher.java:55)
+ at org.junit.rules.TestWatcher$1.evaluate(TestWatcher.java:55)
+ at org.junit.rules.RunRules.evaluate(RunRules.java:20)
+ at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:81)
+ at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:327)
+ at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:84)
+ at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
+ at org.junit.runners.ParentRunner$3.run(ParentRunner.java:292)
+ at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:73)
+ at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:290)
+ at org.junit.runners.ParentRunner.access$000(ParentRunner.java:60)
+ at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:270)
+ at org.junit.runners.ParentRunner.run(ParentRunner.java:370)
+ at android.support.test.runner.AndroidJUnit4.run(AndroidJUnit4.java:99)
+ at org.junit.runners.Suite.runChild(Suite.java:128)
+ at org.junit.runners.Suite.runChild(Suite.java:27)
+ at org.junit.runners.ParentRunner$3.run(ParentRunner.java:292)
+ at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:73)
+ at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:290)
+ at org.junit.runners.ParentRunner.access$000(ParentRunner.java:60)
+ at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:270)
+ at org.junit.runners.ParentRunner.run(ParentRunner.java:370)
+ at org.junit.runners.Suite.runChild(Suite.java:128)
+ at org.junit.runners.Suite.runChild(Suite.java:27)
+ at org.junit.runners.ParentRunner$3.run(ParentRunner.java:292)
+ at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:73)
+ at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:290)
+ at org.junit.runners.ParentRunner.access$000(ParentRunner.java:60)
+ at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:270)
+ at org.junit.runners.ParentRunner.run(ParentRunner.java:370)
+ at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
+ at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
+ at android.support.test.internal.runner.TestExecutor.execute(TestExecutor.java:56)
+ at com.my.package.test.BaseRunner.runTests(BaseRunner.java:344)
+ at com.my.package.test.BaseRunner.onStart(BaseRunner.java:330)
+ at com.my.package.test.runner.MyRunner.onStart(MyRunner.java:253)
+ at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:2074)
+
+INSTRUMENTATION_STATUS: stream=
+INSTRUMENTATION_STATUS: test=assumptionFailureTest
+INSTRUMENTATION_STATUS_CODE: -4
+INSTRUMENTATION_STATUS: class=com.my.package.test.BasicTest
+INSTRUMENTATION_STATUS: current=3
+INSTRUMENTATION_STATUS: id=AndroidJUnitRunner
+INSTRUMENTATION_STATUS: numtests=4
+INSTRUMENTATION_STATUS: stream=
+INSTRUMENTATION_STATUS: test=ignoredTest
+INSTRUMENTATION_STATUS_CODE: 1
+INSTRUMENTATION_STATUS: class=com.my.package.test.BasicTest
+INSTRUMENTATION_STATUS: current=3
+INSTRUMENTATION_STATUS: id=AndroidJUnitRunner
+INSTRUMENTATION_STATUS: numtests=4
+INSTRUMENTATION_STATUS: stream=
+INSTRUMENTATION_STATUS: test=ignoredTest
+INSTRUMENTATION_STATUS_CODE: -3
+INSTRUMENTATION_STATUS: class=com.my.package.test.BasicTest
+INSTRUMENTATION_STATUS: current=4
+INSTRUMENTATION_STATUS: id=AndroidJUnitRunner
+INSTRUMENTATION_STATUS: numtests=4
+INSTRUMENTATION_STATUS: stream=
+INSTRUMENTATION_STATUS: test=passingTest
+INSTRUMENTATION_STATUS_CODE: 1
+INSTRUMENTATION_STATUS: class=com.my.package.test.BasicTest
+INSTRUMENTATION_STATUS: current=4
+INSTRUMENTATION_STATUS: id=AndroidJUnitRunner
+INSTRUMENTATION_STATUS: numtests=4
+INSTRUMENTATION_STATUS: stream=.
+INSTRUMENTATION_STATUS: test=passingTest
+INSTRUMENTATION_STATUS_CODE: 0
+INSTRUMENTATION_RESULT: stream=
+
+Time: 4.131
+There was 1 failure:
+1) failingTest(com.my.package.test.BasicTest)
+java.lang.UnsupportedOperationException: dummy failing test
+ at com.my.package.test.BasicTest.failingTest(BasicTest.java:40)
+ at java.lang.reflect.Method.invoke(Native Method)
+ at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:57)
+ at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
+ at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:59)
+ at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
+ at android.support.test.internal.runner.junit4.statement.RunBefores.evaluate(RunBefores.java:80)
+ at android.support.test.internal.runner.junit4.statement.RunAfters.evaluate(RunAfters.java:61)
+ at android.support.test.rule.ActivityTestRule$ActivityStatement.evaluate(ActivityTestRule.java:433)
+ at com.my.package.test.BaseTest$3.evaluate(BaseTest.java:96)
+ at com.my.package.test.BaseTest$4.evaluate(BaseTest.java:109)
+ at com.my.package.test.BaseTest$2.evaluate(BaseTest.java:77)
+ at org.junit.rules.TestWatcher$1.evaluate(TestWatcher.java:55)
+ at org.junit.rules.TestWatcher$1.evaluate(TestWatcher.java:55)
+ at org.junit.rules.RunRules.evaluate(RunRules.java:20)
+ at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:81)
+ at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:327)
+ at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:84)
+ at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
+ at org.junit.runners.ParentRunner$3.run(ParentRunner.java:292)
+ at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:73)
+ at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:290)
+ at org.junit.runners.ParentRunner.access$000(ParentRunner.java:60)
+ at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:270)
+ at org.junit.runners.ParentRunner.run(ParentRunner.java:370)
+ at android.support.test.runner.AndroidJUnit4.run(AndroidJUnit4.java:99)
+ at org.junit.runners.Suite.runChild(Suite.java:128)
+ at org.junit.runners.Suite.runChild(Suite.java:27)
+ at org.junit.runners.ParentRunner$3.run(ParentRunner.java:292)
+ at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:73)
+ at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:290)
+ at org.junit.runners.ParentRunner.access$000(ParentRunner.java:60)
+ at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:270)
+ at org.junit.runners.ParentRunner.run(ParentRunner.java:370)
+ at org.junit.runners.Suite.runChild(Suite.java:128)
+ at org.junit.runners.Suite.runChild(Suite.java:27)
+ at org.junit.runners.ParentRunner$3.run(ParentRunner.java:292)
+ at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:73)
+ at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:290)
+ at org.junit.runners.ParentRunner.access$000(ParentRunner.java:60)
+ at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:270)
+ at org.junit.runners.ParentRunner.run(ParentRunner.java:370)
+ at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
+ at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
+ at android.support.test.internal.runner.TestExecutor.execute(TestExecutor.java:56)
+ at com.my.package.test.BaseRunner.runTests(BaseRunner.java:344)
+ at com.my.package.test.BaseRunner.onStart(BaseRunner.java:330)
+ at com.my.package.test.runner.MyRunner.onStart(MyRunner.java:253)
+ at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:2074)
+
+FAILURES!!!
+Tests run: 3, Failures: 1
+
+
+INSTRUMENTATION_CODE: -1"""
+ expected_executed = [
+ ('com.my.package.test.BasicTest#failingTest', signals.TestFailure),
+ ('com.my.package.test.BasicTest#passingTest', signals.TestPass),
+ ]
+ expected_skipped = [
+ ('com.my.package.test.BasicTest#assumptionFailureTest',
+ signals.TestSkip),
+ ('com.my.package.test.BasicTest#ignoredTest', signals.TestSkip),
+ ]
+ self.assert_run_instrumentation_test(
+ instrumentation_output,
+ expected_executed=expected_executed,
+ expected_skipped=expected_skipped)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tests/mobly/controllers/android_device_lib/adb_test.py b/tests/mobly/controllers/android_device_lib/adb_test.py
index 5c5f6a8..382ed01 100755
--- a/tests/mobly/controllers/android_device_lib/adb_test.py
+++ b/tests/mobly/controllers/android_device_lib/adb_test.py
@@ -14,10 +14,32 @@
import mock
+from collections import OrderedDict
from future.tests.base import unittest
from mobly.controllers.android_device_lib import adb
+# Mock parameters for instrumentation.
+MOCK_INSTRUMENTATION_PACKAGE = 'com.my.instrumentation.tests'
+MOCK_INSTRUMENTATION_RUNNER = 'com.my.instrumentation.runner'
+MOCK_INSTRUMENTATION_OPTIONS = OrderedDict([
+ ('option1', 'value1'),
+ ('option2', 'value2'),
+])
+# Mock android instrumentation commands.
+MOCK_BASIC_INSTRUMENTATION_COMMAND = ('am instrument -r -w com.my'
+ '.instrumentation.tests/com.android'
+ '.common.support.test.runner'
+ '.AndroidJUnitRunner')
+MOCK_RUNNER_INSTRUMENTATION_COMMAND = ('am instrument -r -w com.my'
+ '.instrumentation.tests/com.my'
+ '.instrumentation.runner')
+MOCK_OPTIONS_INSTRUMENTATION_COMMAND = ('am instrument -r -w -e option1 value1'
+ ' -e option2 value2 com.my'
+ '.instrumentation.tests/com.android'
+ '.common.support.test.runner'
+ '.AndroidJUnitRunner')
+
class AdbTest(unittest.TestCase):
"""Unit tests for mobly.controllers.android_device_lib.adb.
@@ -31,8 +53,8 @@ class AdbTest(unittest.TestCase):
# the created process object in adb._exec_cmd()
mock_psutil_process.return_value = mock.Mock()
- mock_proc.communicate = mock.Mock(return_value=("out".encode('utf-8'),
- "err".encode('utf-8')))
+ mock_proc.communicate = mock.Mock(
+ return_value=('out'.encode('utf-8'), 'err'.encode('utf-8')))
mock_proc.returncode = 0
return (mock_psutil_process, mock_popen)
@@ -43,8 +65,8 @@ class AdbTest(unittest.TestCase):
self._mock_process(mock_psutil_process, mock_Popen)
reply = adb.AdbProxy()._exec_cmd(
- ["fake_cmd"], shell=False, timeout=None)
- self.assertEqual("out", reply.decode('utf-8'))
+ ['fake_cmd'], shell=False, timeout=None)
+ self.assertEqual('out', reply.decode('utf-8'))
@mock.patch('mobly.controllers.android_device_lib.adb.subprocess.Popen')
@mock.patch('mobly.controllers.android_device_lib.adb.psutil.Process')
@@ -54,8 +76,8 @@ class AdbTest(unittest.TestCase):
mock_popen.return_value.returncode = 1
with self.assertRaisesRegex(adb.AdbError,
- "Error executing adb cmd .*"):
- adb.AdbProxy()._exec_cmd(["fake_cmd"], shell=False, timeout=None)
+ 'Error executing adb cmd .*'):
+ adb.AdbProxy()._exec_cmd(['fake_cmd'], shell=False, timeout=None)
@mock.patch('mobly.controllers.android_device_lib.adb.subprocess.Popen')
@mock.patch('mobly.controllers.android_device_lib.adb.psutil.Process')
@@ -63,8 +85,8 @@ class AdbTest(unittest.TestCase):
mock_popen):
self._mock_process(mock_psutil_process, mock_popen)
- reply = adb.AdbProxy()._exec_cmd(["fake_cmd"], shell=False, timeout=1)
- self.assertEqual("out", reply.decode('utf-8'))
+ reply = adb.AdbProxy()._exec_cmd(['fake_cmd'], shell=False, timeout=1)
+ self.assertEqual('out', reply.decode('utf-8'))
@mock.patch('mobly.controllers.android_device_lib.adb.subprocess.Popen')
@mock.patch('mobly.controllers.android_device_lib.adb.psutil.Process')
@@ -76,8 +98,8 @@ class AdbTest(unittest.TestCase):
adb.psutil.TimeoutExpired('Timed out'))
with self.assertRaisesRegex(adb.AdbTimeoutError,
- "Timed out Adb cmd .*"):
- adb.AdbProxy()._exec_cmd(["fake_cmd"], shell=False, timeout=0.1)
+ 'Timed out Adb cmd .*'):
+ adb.AdbProxy()._exec_cmd(['fake_cmd'], shell=False, timeout=0.1)
@mock.patch('mobly.controllers.android_device_lib.adb.subprocess.Popen')
@mock.patch('mobly.controllers.android_device_lib.adb.psutil.Process')
@@ -85,8 +107,8 @@ class AdbTest(unittest.TestCase):
mock_popen):
self._mock_process(mock_psutil_process, mock_popen)
with self.assertRaisesRegex(adb.AdbError,
- "Timeout is a negative value: .*"):
- adb.AdbProxy()._exec_cmd(["fake_cmd"], shell=False, timeout=-1)
+ 'Timeout is a negative value: .*'):
+ adb.AdbProxy()._exec_cmd(['fake_cmd'], shell=False, timeout=-1)
def test_exec_adb_cmd(self):
with mock.patch.object(adb.AdbProxy, '_exec_cmd') as mock_exec_cmd:
@@ -110,6 +132,43 @@ class AdbTest(unittest.TestCase):
mock_exec_cmd.assert_called_once_with(
'"adb" -s "12345" shell arg1 arg2', shell=True, timeout=None)
+ def test_instrument_without_parameters(self):
+ """Verifies the AndroidDevice object's instrument command is correct in
+ the basic case.
+ """
+ with mock.patch.object(adb.AdbProxy, '_exec_cmd') as mock_exec_cmd:
+ adb.AdbProxy().instrument(MOCK_INSTRUMENTATION_PACKAGE)
+ mock_exec_cmd.assert_called_once_with(
+ ['adb', 'shell', MOCK_BASIC_INSTRUMENTATION_COMMAND],
+ shell=False,
+ timeout=None)
+
+ def test_instrument_with_runner(self):
+ """Verifies the AndroidDevice object's instrument command is correct
+ with a runner specified.
+ """
+ with mock.patch.object(adb.AdbProxy, '_exec_cmd') as mock_exec_cmd:
+ adb.AdbProxy().instrument(
+ MOCK_INSTRUMENTATION_PACKAGE,
+ runner=MOCK_INSTRUMENTATION_RUNNER)
+ mock_exec_cmd.assert_called_once_with(
+ ['adb', 'shell', MOCK_RUNNER_INSTRUMENTATION_COMMAND],
+ shell=False,
+ timeout=None)
+
+ def test_instrument_with_options(self):
+ """Verifies the AndroidDevice object's instrument command is correct
+ with options.
+ """
+ with mock.patch.object(adb.AdbProxy, '_exec_cmd') as mock_exec_cmd:
+ adb.AdbProxy().instrument(
+ MOCK_INSTRUMENTATION_PACKAGE,
+ options=MOCK_INSTRUMENTATION_OPTIONS)
+ mock_exec_cmd.assert_called_once_with(
+ ['adb', 'shell', MOCK_OPTIONS_INSTRUMENTATION_COMMAND],
+ shell=False,
+ timeout=None)
+
-if __name__ == "__main__":
+if __name__ == '__main__':
unittest.main()
diff --git a/tests/mobly/controllers/android_device_test.py b/tests/mobly/controllers/android_device_test.py
index 4031d3f..33dd23c 100755
--- a/tests/mobly/controllers/android_device_test.py
+++ b/tests/mobly/controllers/android_device_test.py
@@ -17,6 +17,7 @@ import mock
import os
import shutil
import tempfile
+
from future.tests.base import unittest
from mobly.controllers import android_device
| {
"commit_name": "merge_commit",
"failed_lite_validators": [
"has_added_files",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 3,
"issue_text_score": 0,
"test_score": 1
},
"num_modified_files": 4
} | 1.6 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"pytest",
"pytest-cov",
"pytest-xdist",
"pytest-mock",
"pytest-asyncio"
],
"pre_install": [
"apt-get update",
"apt-get install -y adb"
],
"python": "3.9",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | coverage==7.8.0
exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work
execnet==2.1.1
future==1.0.0
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
-e git+https://github.com/google/mobly.git@5958f83fc5f297c91a63bf8c8bd579144d002a06#egg=mobly
mock==1.0.1
packaging @ file:///croot/packaging_1734472117206/work
pluggy @ file:///croot/pluggy_1733169602837/work
portpicker==1.6.0
psutil==7.0.0
pytest @ file:///croot/pytest_1738938843180/work
pytest-asyncio==0.26.0
pytest-cov==6.0.0
pytest-mock==3.14.0
pytest-xdist==3.6.1
pytz==2025.2
PyYAML==6.0.2
timeout-decorator==0.5.0
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
typing_extensions==4.13.0
| name: mobly
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- exceptiongroup=1.2.0=py39h06a4308_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- packaging=24.2=py39h06a4308_0
- pip=25.0=py39h06a4308_0
- pluggy=1.5.0=py39h06a4308_0
- pytest=8.3.4=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tomli=2.0.1=py39h06a4308_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- coverage==7.8.0
- execnet==2.1.1
- future==1.0.0
- mock==1.0.1
- portpicker==1.6.0
- psutil==7.0.0
- pytest-asyncio==0.26.0
- pytest-cov==6.0.0
- pytest-mock==3.14.0
- pytest-xdist==3.6.1
- pytz==2025.2
- pyyaml==6.0.2
- timeout-decorator==0.5.0
- typing-extensions==4.13.0
prefix: /opt/conda/envs/mobly
| [
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_instrument_with_options",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_instrument_with_runner",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_instrument_without_parameters"
]
| []
| [
"tests/mobly/base_instrumentation_test_test.py::BaseInstrumentationTestTest::test_parse_instrumentation_options_with_mixed_user_params",
"tests/mobly/base_instrumentation_test_test.py::BaseInstrumentationTestTest::test_parse_instrumentation_options_with_no_instrumentation_params",
"tests/mobly/base_instrumentation_test_test.py::BaseInstrumentationTestTest::test_parse_instrumentation_options_with_no_user_params",
"tests/mobly/base_instrumentation_test_test.py::BaseInstrumentationTestTest::test_parse_instrumentation_options_with_only_instrumentation_params",
"tests/mobly/base_instrumentation_test_test.py::BaseInstrumentationTestTest::test_run_instrumentation_test_with_assumption_failure_test",
"tests/mobly/base_instrumentation_test_test.py::BaseInstrumentationTestTest::test_run_instrumentation_test_with_crashed_test",
"tests/mobly/base_instrumentation_test_test.py::BaseInstrumentationTestTest::test_run_instrumentation_test_with_crashing_test",
"tests/mobly/base_instrumentation_test_test.py::BaseInstrumentationTestTest::test_run_instrumentation_test_with_failing_test",
"tests/mobly/base_instrumentation_test_test.py::BaseInstrumentationTestTest::test_run_instrumentation_test_with_ignored_test",
"tests/mobly/base_instrumentation_test_test.py::BaseInstrumentationTestTest::test_run_instrumentation_test_with_invalid_syntax",
"tests/mobly/base_instrumentation_test_test.py::BaseInstrumentationTestTest::test_run_instrumentation_test_with_missing_runner",
"tests/mobly/base_instrumentation_test_test.py::BaseInstrumentationTestTest::test_run_instrumentation_test_with_missing_test_package",
"tests/mobly/base_instrumentation_test_test.py::BaseInstrumentationTestTest::test_run_instrumentation_test_with_multiple_tests",
"tests/mobly/base_instrumentation_test_test.py::BaseInstrumentationTestTest::test_run_instrumentation_test_with_no_output",
"tests/mobly/base_instrumentation_test_test.py::BaseInstrumentationTestTest::test_run_instrumentation_test_with_no_tests",
"tests/mobly/base_instrumentation_test_test.py::BaseInstrumentationTestTest::test_run_instrumentation_test_with_passing_test",
"tests/mobly/base_instrumentation_test_test.py::BaseInstrumentationTestTest::test_run_instrumentation_test_with_prefix_test",
"tests/mobly/base_instrumentation_test_test.py::BaseInstrumentationTestTest::test_run_instrumentation_test_with_runner_setup_crash",
"tests/mobly/base_instrumentation_test_test.py::BaseInstrumentationTestTest::test_run_instrumentation_test_with_runner_teardown_crash",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_exec_adb_cmd",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_exec_adb_cmd_with_shell_true",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_exec_cmd_error_no_timeout",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_exec_cmd_no_timeout_success",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_exec_cmd_timed_out",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_exec_cmd_with_negative_timeout_value",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_exec_cmd_with_timeout_success",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_build_info",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_cat_adb_log",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_debug_tag",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_instantiation",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_load_snippet",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_load_snippet_dup_attribute_name",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_load_snippet_dup_package",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_load_snippet_dup_snippet_name",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_snippet_cleanup",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_take_bug_report",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_take_bug_report_fail",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_take_bug_report_fallback",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_take_bug_report_with_destination",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_take_logcat",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_take_logcat_with_user_param",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_create_with_dict_list",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_create_with_empty_config",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_create_with_no_valid_config",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_create_with_not_list_config",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_create_with_pickup_all",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_create_with_string_list",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_create_with_usb_id",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_get_device_no_match",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_get_device_success_with_serial",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_get_device_success_with_serial_and_extra_field",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_get_device_too_many_matches",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_get_devices_no_match",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_get_devices_success_with_extra_field",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_start_services_on_ads"
]
| []
| Apache License 2.0 | 1,837 | [
"docs/conf.py",
"mobly/controllers/android_device_lib/snippet_client.py",
"mobly/controllers/android_device_lib/adb.py",
"README.md",
"docs/instrumentation_tutorial.md"
]
| [
"docs/conf.py",
"mobly/controllers/android_device_lib/snippet_client.py",
"mobly/controllers/android_device_lib/adb.py",
"README.md",
"docs/instrumentation_tutorial.md"
]
|
|
openmrslab__suspect-93 | 758a6d0d41dd61617d6957ae400a7b0c366b477b | 2017-11-02 10:32:05 | 820e897294d90e08c4b91be7289e4ee9ebc6d009 | coveralls:
[](https://coveralls.io/builds/14003998)
Coverage increased (+0.05%) to 81.017% when pulling **b2195c51696b5c0198e491351886561d1d687103 on 90_image_resample** into **758a6d0d41dd61617d6957ae400a7b0c366b477b on master**.
| diff --git a/suspect/base.py b/suspect/base.py
index 6952aa2..8be873b 100644
--- a/suspect/base.py
+++ b/suspect/base.py
@@ -122,12 +122,12 @@ class ImageBase(np.ndarray):
@property
@requires_transform
def row_vector(self):
- return self.transform[:3, 1] / np.linalg.norm(self.transform[:3, 1])
+ return self.transform[:3, 0] / np.linalg.norm(self.transform[:3, 0])
@property
@requires_transform
def col_vector(self):
- return self.transform[:3, 0] / np.linalg.norm(self.transform[:3, 0])
+ return self.transform[:3, 1] / np.linalg.norm(self.transform[:3, 1])
@requires_transform
def _closest_axis(self, target_axis):
@@ -264,12 +264,13 @@ class ImageBase(np.ndarray):
+ JJ[..., np.newaxis] * col_vector \
+ KK[..., np.newaxis] * slice_vector + centre
+ image_coords = self.from_scanner(space_coords).reshape(*space_coords.shape)[..., ::-1].astype(np.int)
resampled = scipy.interpolate.interpn([np.arange(dim) for dim in self.shape],
self,
- self.from_scanner(space_coords)[..., ::-1],
+ image_coords,
method=method,
bounds_error=False,
- fill_value=0)
+ fill_value=0).squeeze()
transform = _transforms.transformation_matrix(row_vector,
col_vector,
| BUG: resampling of image volumes doesn't work properly for single slices
When transforming coordinates the arrays are squeezed which can remove singlet spatial dimensions, leading to issues in interpreting the coordinate arrays. | openmrslab/suspect | diff --git a/tests/test_mrs/test_base.py b/tests/test_mrs/test_base.py
index 72a8d6d..d5e437a 100644
--- a/tests/test_mrs/test_base.py
+++ b/tests/test_mrs/test_base.py
@@ -55,8 +55,8 @@ def test_find_axes():
[1, 1, 1])
base = suspect.base.ImageBase(np.zeros(1), transform=transform)
np.testing.assert_equal(base.axial_vector, base.slice_vector)
- np.testing.assert_equal(base.coronal_vector, base.row_vector)
- np.testing.assert_equal(base.sagittal_vector, base.col_vector)
+ np.testing.assert_equal(base.coronal_vector, base.col_vector)
+ np.testing.assert_equal(base.sagittal_vector, base.row_vector)
def test_find_axes_reversed():
@@ -66,8 +66,8 @@ def test_find_axes_reversed():
[1, 1, 1])
base = suspect.base.ImageBase(np.zeros(1), transform=transform)
np.testing.assert_equal(base.axial_vector, base.slice_vector)
- np.testing.assert_equal(base.coronal_vector, -base.row_vector)
- np.testing.assert_equal(base.sagittal_vector, -base.col_vector)
+ np.testing.assert_equal(base.coronal_vector, -base.col_vector)
+ np.testing.assert_equal(base.sagittal_vector, -base.row_vector)
def test_centre():
diff --git a/tests/test_mrs/test_image.py b/tests/test_mrs/test_image.py
index d1a760c..128bd97 100644
--- a/tests/test_mrs/test_image.py
+++ b/tests/test_mrs/test_image.py
@@ -32,3 +32,13 @@ def test_nifti_io():
nifti_volume = suspect.image.load_nifti("tests/test_data/tmp/nifti.nii")
np.testing.assert_equal(dicom_volume, nifti_volume)
np.testing.assert_allclose(dicom_volume.transform, nifti_volume.transform)
+
+
+def test_resample_single_slice():
+ source_volume = suspect.base.ImageBase(np.random.random((20, 20, 20)), transform=np.eye(4))
+ slc = source_volume.resample(source_volume.row_vector,
+ source_volume.col_vector,
+ [1, 20, 10],
+ centre=(5, 10, 0))
+ assert slc.shape == (20, 10)
+ np.testing.assert_equal(source_volume[0, :, :10], slc)
| {
"commit_name": "merge_commit",
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 1,
"test_score": 0
},
"num_modified_files": 1
} | 0.3 | {
"env_vars": null,
"env_yml_path": [],
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-cov"
],
"pre_install": [],
"python": "3.5",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | alabaster==0.7.13
asteval==0.9.26
async-generator==1.10
attrs==22.2.0
Babel==2.11.0
backcall==0.2.0
bleach==4.1.0
certifi==2021.5.30
charset-normalizer==2.0.12
coverage==6.2
decorator==5.1.1
defusedxml==0.7.1
docutils==0.18.1
entrypoints==0.4
future==1.0.0
idna==3.10
imagesize==1.4.1
importlib-metadata==4.8.3
iniconfig==1.1.1
ipykernel==5.5.6
ipython==7.16.3
ipython-genutils==0.2.0
jedi==0.17.2
Jinja2==3.0.3
jsonschema==3.2.0
jupyter-client==7.1.2
jupyter-core==4.9.2
jupyterlab-pygments==0.1.2
lmfit==1.0.3
MarkupSafe==2.0.1
mistune==0.8.4
nbclient==0.5.9
nbconvert==6.0.7
nbformat==5.1.3
nbsphinx==0.8.8
nest-asyncio==1.6.0
nibabel==3.2.2
numpy==1.19.5
packaging==21.3
pandocfilters==1.5.1
parse==1.20.2
Parsley==1.3
parso==0.7.1
pexpect==4.9.0
pickleshare==0.7.5
pluggy==1.0.0
prompt-toolkit==3.0.36
ptyprocess==0.7.0
py==1.11.0
pydicom==2.3.1
Pygments==2.14.0
pyparsing==3.1.4
pyrsistent==0.18.0
pytest==7.0.1
pytest-cov==4.0.0
python-dateutil==2.9.0.post0
pytz==2025.2
PyWavelets==1.1.1
pyzmq==25.1.2
requests==2.27.1
scipy==1.5.4
six==1.17.0
snowballstemmer==2.2.0
Sphinx==5.3.0
sphinxcontrib-applehelp==1.0.2
sphinxcontrib-devhelp==1.0.2
sphinxcontrib-htmlhelp==2.0.0
sphinxcontrib-jsmath==1.0.1
sphinxcontrib-qthelp==1.0.3
sphinxcontrib-serializinghtml==1.1.5
-e git+https://github.com/openmrslab/suspect.git@758a6d0d41dd61617d6957ae400a7b0c366b477b#egg=suspect
testpath==0.6.0
tomli==1.2.3
tornado==6.1
traitlets==4.3.3
typing_extensions==4.1.1
uncertainties==3.1.7
urllib3==1.26.20
wcwidth==0.2.13
webencodings==0.5.1
zipp==3.6.0
| name: suspect
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- alabaster==0.7.13
- asteval==0.9.26
- async-generator==1.10
- attrs==22.2.0
- babel==2.11.0
- backcall==0.2.0
- bleach==4.1.0
- charset-normalizer==2.0.12
- coverage==6.2
- decorator==5.1.1
- defusedxml==0.7.1
- docutils==0.18.1
- entrypoints==0.4
- future==1.0.0
- idna==3.10
- imagesize==1.4.1
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- ipykernel==5.5.6
- ipython==7.16.3
- ipython-genutils==0.2.0
- jedi==0.17.2
- jinja2==3.0.3
- jsonschema==3.2.0
- jupyter-client==7.1.2
- jupyter-core==4.9.2
- jupyterlab-pygments==0.1.2
- lmfit==1.0.3
- markupsafe==2.0.1
- mistune==0.8.4
- nbclient==0.5.9
- nbconvert==6.0.7
- nbformat==5.1.3
- nbsphinx==0.8.8
- nest-asyncio==1.6.0
- nibabel==3.2.2
- numpy==1.19.5
- packaging==21.3
- pandocfilters==1.5.1
- parse==1.20.2
- parsley==1.3
- parso==0.7.1
- pexpect==4.9.0
- pickleshare==0.7.5
- pluggy==1.0.0
- prompt-toolkit==3.0.36
- ptyprocess==0.7.0
- py==1.11.0
- pydicom==2.3.1
- pygments==2.14.0
- pyparsing==3.1.4
- pyrsistent==0.18.0
- pytest==7.0.1
- pytest-cov==4.0.0
- python-dateutil==2.9.0.post0
- pytz==2025.2
- pywavelets==1.1.1
- pyzmq==25.1.2
- requests==2.27.1
- scipy==1.5.4
- six==1.17.0
- snowballstemmer==2.2.0
- sphinx==5.3.0
- sphinxcontrib-applehelp==1.0.2
- sphinxcontrib-devhelp==1.0.2
- sphinxcontrib-htmlhelp==2.0.0
- sphinxcontrib-jsmath==1.0.1
- sphinxcontrib-qthelp==1.0.3
- sphinxcontrib-serializinghtml==1.1.5
- testpath==0.6.0
- tomli==1.2.3
- tornado==6.1
- traitlets==4.3.3
- typing-extensions==4.1.1
- uncertainties==3.1.7
- urllib3==1.26.20
- wcwidth==0.2.13
- webencodings==0.5.1
- zipp==3.6.0
prefix: /opt/conda/envs/suspect
| [
"tests/test_mrs/test_base.py::test_find_axes",
"tests/test_mrs/test_base.py::test_find_axes_reversed",
"tests/test_mrs/test_image.py::test_resample_single_slice"
]
| []
| [
"tests/test_mrs/test_base.py::test_create_base",
"tests/test_mrs/test_base.py::test_base_transform",
"tests/test_mrs/test_base.py::test_transforms_fail",
"tests/test_mrs/test_base.py::test_centre",
"tests/test_mrs/test_base.py::test_resample",
"tests/test_mrs/test_image.py::test_simple_mask",
"tests/test_mrs/test_image.py::test_nifti_io"
]
| []
| MIT License | 1,838 | [
"suspect/base.py"
]
| [
"suspect/base.py"
]
|
borgbackup__borg-3246 | 4a58310433f21857fc124eed4bafde2956bac46a | 2017-11-02 15:07:23 | a439fa3e720c8bb2a82496768ffcce282fb7f7b7 | diff --git a/src/borg/archiver.py b/src/borg/archiver.py
index d678bb28..b09490bf 100644
--- a/src/borg/archiver.py
+++ b/src/borg/archiver.py
@@ -49,7 +49,7 @@
from .helpers import BaseFormatter, ItemFormatter, ArchiveFormatter
from .helpers import format_timedelta, format_file_size, parse_file_size, format_archive
from .helpers import safe_encode, remove_surrogates, bin_to_hex, prepare_dump_dict
-from .helpers import interval, prune_within, prune_split, PRUNING_PATTERNS
+from .helpers import interval, prune_within, prune_split
from .helpers import timestamp
from .helpers import get_cache_dir
from .helpers import Manifest, AI_HUMAN_SORT_KEYS
@@ -1333,48 +1333,45 @@ def do_prune(self, args, repository, manifest, key):
# that is newer than a successfully completed backup - and killing the successful backup.
archives = [arch for arch in archives_checkpoints if arch not in checkpoints]
keep = []
- # collect the rule responsible for the keeping of each archive in this dict
- # keys are archive ids, values are a tuple
- # (<rulename>, <how many archives were kept by this rule so far >)
- kept_because = {}
-
- # find archives which need to be kept because of the keep-within rule
if args.within:
- keep += prune_within(archives, args.within, kept_because)
-
- # find archives which need to be kept because of the various time period rules
- for rule in PRUNING_PATTERNS.keys():
- num = getattr(args, rule, None)
- if num is not None:
- keep += prune_split(archives, rule, num, kept_because)
-
+ keep += prune_within(archives, args.within)
+ if args.secondly:
+ keep += prune_split(archives, '%Y-%m-%d %H:%M:%S', args.secondly, keep)
+ if args.minutely:
+ keep += prune_split(archives, '%Y-%m-%d %H:%M', args.minutely, keep)
+ if args.hourly:
+ keep += prune_split(archives, '%Y-%m-%d %H', args.hourly, keep)
+ if args.daily:
+ keep += prune_split(archives, '%Y-%m-%d', args.daily, keep)
+ if args.weekly:
+ keep += prune_split(archives, '%G-%V', args.weekly, keep)
+ if args.monthly:
+ keep += prune_split(archives, '%Y-%m', args.monthly, keep)
+ if args.yearly:
+ keep += prune_split(archives, '%Y', args.yearly, keep)
to_delete = (set(archives) | checkpoints) - (set(keep) | set(keep_checkpoints))
stats = Statistics()
with Cache(repository, key, manifest, do_files=False, lock_wait=self.lock_wait) as cache:
list_logger = logging.getLogger('borg.output.list')
- # set up counters for the progress display
- to_delete_len = len(to_delete)
- archives_deleted = 0
+ if args.output_list:
+ # set up counters for the progress display
+ to_delete_len = len(to_delete)
+ archives_deleted = 0
for archive in archives_checkpoints:
if archive in to_delete:
if args.dry_run:
- log_message = 'Would prune:'
+ if args.output_list:
+ list_logger.info('Would prune: %s' % format_archive(archive))
else:
- archives_deleted += 1
- log_message = 'Pruning archive (%d/%d):' % (archives_deleted, to_delete_len)
+ if args.output_list:
+ archives_deleted += 1
+ list_logger.info('Pruning archive: %s (%d/%d)' % (format_archive(archive),
+ archives_deleted, to_delete_len))
Archive(repository, key, manifest, archive.name, cache,
progress=args.progress).delete(stats, forced=args.forced)
else:
- if is_checkpoint(archive.name):
- log_message = 'Keeping checkpoint archive:'
- else:
- log_message = 'Keeping archive (rule: {rule} #{num}):'.format(
- rule=kept_because[archive.id][0], num=kept_because[archive.id][1]
- )
- if args.output_list:
- list_logger.info("{message:<40} {archive}".format(
- message=log_message, archive=format_archive(archive)
- ))
+ if args.output_list:
+ list_logger.info('Keeping archive: %s' % format_archive(archive))
if to_delete and not args.dry_run:
manifest.write()
repository.commit(save_space=args.save_space)
diff --git a/src/borg/helpers/misc.py b/src/borg/helpers/misc.py
index b0fbb203..e33b46f0 100644
--- a/src/borg/helpers/misc.py
+++ b/src/borg/helpers/misc.py
@@ -4,7 +4,7 @@
import os.path
import platform
import sys
-from collections import deque, OrderedDict
+from collections import deque
from datetime import datetime, timezone, timedelta
from itertools import islice
from operator import attrgetter
@@ -17,44 +17,22 @@
from .. import chunker
-def prune_within(archives, hours, kept_because):
+def prune_within(archives, hours):
target = datetime.now(timezone.utc) - timedelta(seconds=hours * 3600)
- kept_counter = 0
- result = []
- for a in archives:
- if a.ts > target:
- kept_counter += 1
- kept_because[a.id] = ("within", kept_counter)
- result.append(a)
- return result
-
-
-PRUNING_PATTERNS = OrderedDict([
- ("secondly", '%Y-%m-%d %H:%M:%S'),
- ("minutely", '%Y-%m-%d %H:%M'),
- ("hourly", '%Y-%m-%d %H'),
- ("daily", '%Y-%m-%d'),
- ("weekly", '%G-%V'),
- ("monthly", '%Y-%m'),
- ("yearly", '%Y'),
-])
-
-
-def prune_split(archives, rule, n, kept_because=None):
+ return [a for a in archives if a.ts > target]
+
+
+def prune_split(archives, pattern, n, skip=[]):
last = None
keep = []
- pattern = PRUNING_PATTERNS[rule]
- if kept_because is None:
- kept_because = {}
if n == 0:
return keep
for a in sorted(archives, key=attrgetter('ts'), reverse=True):
period = to_localtime(a.ts).strftime(pattern)
if period != last:
last = period
- if a.id not in kept_because:
+ if a not in skip:
keep.append(a)
- kept_because[a.id] = (rule, len(keep))
if len(keep) == n:
break
return keep
diff --git a/src/borg/remote.py b/src/borg/remote.py
index d3c5e542..81067881 100644
--- a/src/borg/remote.py
+++ b/src/borg/remote.py
@@ -596,7 +596,7 @@ def do_open():
# emit this msg in the same way as the 'Remote: ...' lines that show the remote TypeError
sys.stderr.write(msg)
self.server_version = parse_version('1.0.6')
- compatMap['open'] = ('path', 'create', 'lock_wait', 'lock', ),
+ compatMap['open'] = ('path', 'create', 'lock_wait', 'lock', )
# try again with corrected version and compatMap
do_open()
except Exception:
| Borg 1.1.x failing to handle exceptions for servers < 1.0.7
When `borg list server:repo` is run on version 1.0.11:
```
Remote: Borg 0.29.0: exception in RPC call:
Remote: Traceback (most recent call last):
Remote: File "/usr/home/username/borgbackup-0.29.0/borg/remote.py", line 96, in serve
Remote: TypeError: open() takes from 2 to 5 positional arguments but 7 were given
Remote: Platform: FreeBSD servername.net 10.3-RELEASE FreeBSD 10.3-RELEASE #0: Wed Aug 30 20:40:07 CEST 2017 [email protected]:/usr/src/sys/amd64/compile/servername_10.3 amd64
Remote: Python: CPython 3.4.3
Remote:
Please note:
If you see a TypeError complaining about the number of positional arguments
given to open(), you can ignore it if it comes from a borg version < 1.0.7.
This TypeError is a cosmetic side effect of the compatibility code borg
clients >= 1.0.7 have to support older borg servers.
This problem will go away as soon as the server has been upgraded to 1.0.7+.
backup-2017-10-21T20:49:41.602262 Sat, 2017-10-21 20:49:49
backup-2017-10-23T10:44:59.177504 Mon, 2017-10-23 10:45:06
```
The same command run on version 1.1.1
```
Remote: Borg 0.29.0: exception in RPC call:
Remote: Traceback (most recent call last):
Remote: File "/usr/home/username/borgbackup-0.29.0/borg/remote.py", line 96, in serve
Remote: TypeError: open() takes from 2 to 5 positional arguments but 7 were given
Remote: Platform: FreeBSD servername.net 10.3-RELEASE FreeBSD 10.3-RELEASE #0: Wed Aug 30 20:40:07 CEST 2017 [email protected]:/usr/src/sys/amd64/compile/servername_10.3 amd64
Remote: Python: CPython 3.4.3
Remote:
Please note:
If you see a TypeError complaining about the number of positional arguments
given to open(), you can ignore it if it comes from a borg version < 1.0.7.
This TypeError is a cosmetic side effect of the compatibility code borg
clients >= 1.0.7 have to support older borg servers.
This problem will go away as soon as the server has been upgraded to 1.0.7+.
Local Exception
Traceback (most recent call last):
File "/usr/lib/python3.6/site-packages/borg/remote.py", line 591, in __init__
do_open()
File "/usr/lib/python3.6/site-packages/borg/remote.py", line 584, in do_open
lock=lock, exclusive=exclusive, append_only=append_only)
File "/usr/lib/python3.6/site-packages/borg/remote.py", line 476, in do_rpc
return self.call(f.__name__, named, **extra)
File "/usr/lib/python3.6/site-packages/borg/remote.py", line 707, in call
for resp in self.call_many(cmd, [args], **kw):
File "/usr/lib/python3.6/site-packages/borg/remote.py", line 773, in call_many
handle_error(unpacked)
File "/usr/lib/python3.6/site-packages/borg/remote.py", line 757, in handle_error
raise self.RPCError(unpacked)
borg.remote.RemoteRepository.RPCError: {b'i': 2, b'exception_class': b'TypeError'}
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/lib/python3.6/site-packages/borg/archiver.py", line 4049, in main
exit_code = archiver.run(args)
File "/usr/lib/python3.6/site-packages/borg/archiver.py", line 3977, in run
return set_ec(func(args))
File "/usr/lib/python3.6/site-packages/borg/archiver.py", line 130, in wrapper
lock_wait=self.lock_wait, lock=lock, append_only=append_only, args=args)
File "/usr/lib/python3.6/site-packages/borg/remote.py", line 608, in __init__
do_open()
File "/usr/lib/python3.6/site-packages/borg/remote.py", line 584, in do_open
lock=lock, exclusive=exclusive, append_only=append_only)
File "/usr/lib/python3.6/site-packages/borg/remote.py", line 476, in do_rpc
return self.call(f.__name__, named, **extra)
File "/usr/lib/python3.6/site-packages/borg/remote.py", line 707, in call
for resp in self.call_many(cmd, [args], **kw):
File "/usr/lib/python3.6/site-packages/borg/remote.py", line 867, in call_many
self.to_send = msgpack.packb((1, self.msgid, cmd, self.named_to_positional(cmd, args)))
File "/usr/lib/python3.6/site-packages/borg/remote.py", line 704, in named_to_positional
return [kwargs[name] for name in compatMap[method]]
File "/usr/lib/python3.6/site-packages/borg/remote.py", line 704, in <listcomp>
return [kwargs[name] for name in compatMap[method]]
KeyError: ('path', 'create', 'lock_wait', 'lock')
Platform: Linux mycomputer 4.13.8-1-ARCH #1 SMP PREEMPT Wed Oct 18 11:49:44 CEST 2017 x86_64
Linux: arch
Borg: 1.1.1 Python: CPython 3.6.3
PID: 23092 CWD: /root
sys.argv: ['/usr/bin/borg', 'list', 'server:repo']
SSH_ORIGINAL_COMMAND: None
```
I have also tested on 1.1.0. It seems all the 1.1.x branches have this issue.
Note: I'm connecting to the remote repo over SSH. In `~/.ssh/config` there is an entry called "server" that defines the HostName, User, and IdentityFile for the remote borg server. | borgbackup/borg | diff --git a/src/borg/testsuite/archiver.py b/src/borg/testsuite/archiver.py
index 29fc50f7..c3a66632 100644
--- a/src/borg/testsuite/archiver.py
+++ b/src/borg/testsuite/archiver.py
@@ -6,7 +6,6 @@
import os
import pstats
import random
-import re
import shutil
import socket
import stat
@@ -1732,11 +1731,12 @@ def test_prune_repository(self):
self.cmd('create', self.repository_location + '::test3.checkpoint.1', src_dir)
self.cmd('create', self.repository_location + '::test4.checkpoint', src_dir)
output = self.cmd('prune', '--list', '--dry-run', self.repository_location, '--keep-daily=2')
- assert re.search(r'Would prune:\s+test1', output)
+ self.assert_in('Keeping archive: test2', output)
+ self.assert_in('Would prune: test1', output)
# must keep the latest non-checkpoint archive:
- assert re.search(r'Keeping archive \(rule: daily #1\):\s+test2', output)
+ self.assert_in('Keeping archive: test2', output)
# must keep the latest checkpoint archive:
- assert re.search(r'Keeping checkpoint archive:\s+test4.checkpoint', output)
+ self.assert_in('Keeping archive: test4.checkpoint', output)
output = self.cmd('list', self.repository_location)
self.assert_in('test1', output)
self.assert_in('test2', output)
@@ -1766,8 +1766,8 @@ def test_prune_repository_save_space(self):
self.cmd('create', self.repository_location + '::test1', src_dir)
self.cmd('create', self.repository_location + '::test2', src_dir)
output = self.cmd('prune', '--list', '--stats', '--dry-run', self.repository_location, '--keep-daily=2')
- assert re.search(r'Keeping archive \(rule: daily #1\):\s+test2', output)
- assert re.search(r'Would prune:\s+test1', output)
+ self.assert_in('Keeping archive: test2', output)
+ self.assert_in('Would prune: test1', output)
self.assert_in('Deleted data:', output)
output = self.cmd('list', self.repository_location)
self.assert_in('test1', output)
@@ -1784,8 +1784,8 @@ def test_prune_repository_prefix(self):
self.cmd('create', self.repository_location + '::bar-2015-08-12-10:00', src_dir)
self.cmd('create', self.repository_location + '::bar-2015-08-12-20:00', src_dir)
output = self.cmd('prune', '--list', '--dry-run', self.repository_location, '--keep-daily=2', '--prefix=foo-')
- assert re.search(r'Keeping archive \(rule: daily #1\):\s+foo-2015-08-12-20:00', output)
- assert re.search(r'Would prune:\s+foo-2015-08-12-10:00', output)
+ self.assert_in('Keeping archive: foo-2015-08-12-20:00', output)
+ self.assert_in('Would prune: foo-2015-08-12-10:00', output)
output = self.cmd('list', self.repository_location)
self.assert_in('foo-2015-08-12-10:00', output)
self.assert_in('foo-2015-08-12-20:00', output)
@@ -1805,8 +1805,8 @@ def test_prune_repository_glob(self):
self.cmd('create', self.repository_location + '::2015-08-12-10:00-bar', src_dir)
self.cmd('create', self.repository_location + '::2015-08-12-20:00-bar', src_dir)
output = self.cmd('prune', '--list', '--dry-run', self.repository_location, '--keep-daily=2', '--glob-archives=2015-*-foo')
- assert re.search(r'Keeping archive \(rule: daily #1\):\s+2015-08-12-20:00-foo', output)
- assert re.search(r'Would prune:\s+2015-08-12-10:00-foo', output)
+ self.assert_in('Keeping archive: 2015-08-12-20:00-foo', output)
+ self.assert_in('Would prune: 2015-08-12-10:00-foo', output)
output = self.cmd('list', self.repository_location)
self.assert_in('2015-08-12-10:00-foo', output)
self.assert_in('2015-08-12-20:00-foo', output)
diff --git a/src/borg/testsuite/helpers.py b/src/borg/testsuite/helpers.py
index 8d191974..15c029f5 100644
--- a/src/borg/testsuite/helpers.py
+++ b/src/borg/testsuite/helpers.py
@@ -1,10 +1,11 @@
import hashlib
+import io
import os
import shutil
import sys
from argparse import ArgumentTypeError
from datetime import datetime, timezone, timedelta
-from time import sleep
+from time import mktime, strptime, sleep
import pytest
@@ -332,56 +333,40 @@ def test(self):
class MockArchive:
- def __init__(self, ts, id):
+ def __init__(self, ts):
self.ts = ts
- self.id = id
def __repr__(self):
- return "{0}: {1}".format(self.id, self.ts.isoformat())
-
-
[email protected](
- "rule,num_to_keep,expected_ids", [
- ("yearly", 3, (13, 2, 1)),
- ("monthly", 3, (13, 8, 4)),
- ("weekly", 2, (13, 8)),
- ("daily", 3, (13, 8, 7)),
- ("hourly", 3, (13, 10, 8)),
- ("minutely", 3, (13, 10, 9)),
- ("secondly", 4, (13, 12, 11, 10)),
- ("daily", 0, []),
- ]
-)
-def test_prune_split(rule, num_to_keep, expected_ids):
- def subset(lst, ids):
- return {i for i in lst if i.id in ids}
-
- archives = [
- # years apart
- MockArchive(datetime(2015, 1, 1, 10, 0, 0, tzinfo=timezone.utc), 1),
- MockArchive(datetime(2016, 1, 1, 10, 0, 0, tzinfo=timezone.utc), 2),
- MockArchive(datetime(2017, 1, 1, 10, 0, 0, tzinfo=timezone.utc), 3),
- # months apart
- MockArchive(datetime(2017, 2, 1, 10, 0, 0, tzinfo=timezone.utc), 4),
- MockArchive(datetime(2017, 3, 1, 10, 0, 0, tzinfo=timezone.utc), 5),
- # days apart
- MockArchive(datetime(2017, 3, 2, 10, 0, 0, tzinfo=timezone.utc), 6),
- MockArchive(datetime(2017, 3, 3, 10, 0, 0, tzinfo=timezone.utc), 7),
- MockArchive(datetime(2017, 3, 4, 10, 0, 0, tzinfo=timezone.utc), 8),
- # minutes apart
- MockArchive(datetime(2017, 10, 1, 9, 45, 0, tzinfo=timezone.utc), 9),
- MockArchive(datetime(2017, 10, 1, 9, 55, 0, tzinfo=timezone.utc), 10),
- # seconds apart
- MockArchive(datetime(2017, 10, 1, 10, 0, 1, tzinfo=timezone.utc), 11),
- MockArchive(datetime(2017, 10, 1, 10, 0, 3, tzinfo=timezone.utc), 12),
- MockArchive(datetime(2017, 10, 1, 10, 0, 5, tzinfo=timezone.utc), 13),
- ]
- kept_because = {}
- keep = prune_split(archives, rule, num_to_keep, kept_because)
-
- assert set(keep) == subset(archives, expected_ids)
- for item in keep:
- assert kept_because[item.id][0] == rule
+ return repr(self.ts)
+
+
+class PruneSplitTestCase(BaseTestCase):
+
+ def test(self):
+
+ def local_to_UTC(month, day):
+ """Convert noon on the month and day in 2013 to UTC."""
+ seconds = mktime(strptime('2013-%02d-%02d 12:00' % (month, day), '%Y-%m-%d %H:%M'))
+ return datetime.fromtimestamp(seconds, tz=timezone.utc)
+
+ def subset(lst, indices):
+ return {lst[i] for i in indices}
+
+ def dotest(test_archives, n, skip, indices):
+ for ta in test_archives, reversed(test_archives):
+ self.assert_equal(set(prune_split(ta, '%Y-%m', n, skip)),
+ subset(test_archives, indices))
+
+ test_pairs = [(1, 1), (2, 1), (2, 28), (3, 1), (3, 2), (3, 31), (5, 1)]
+ test_dates = [local_to_UTC(month, day) for month, day in test_pairs]
+ test_archives = [MockArchive(date) for date in test_dates]
+
+ dotest(test_archives, 3, [], [6, 5, 2])
+ dotest(test_archives, -1, [], [6, 5, 2, 0])
+ dotest(test_archives, 3, [test_archives[6]], [5, 2, 0])
+ dotest(test_archives, 3, [test_archives[5]], [6, 2, 0])
+ dotest(test_archives, 3, [test_archives[4]], [6, 5, 2])
+ dotest(test_archives, 0, [], [])
class IntervalTestCase(BaseTestCase):
@@ -425,19 +410,14 @@ def subset(lst, indices):
def dotest(test_archives, within, indices):
for ta in test_archives, reversed(test_archives):
- kept_because = {}
- keep = prune_within(ta, interval(within), kept_because)
- self.assert_equal(set(keep),
+ self.assert_equal(set(prune_within(ta, interval(within))),
subset(test_archives, indices))
- assert all("within" == kept_because[a.id][0] for a in keep)
# 1 minute, 1.5 hours, 2.5 hours, 3.5 hours, 25 hours, 49 hours
test_offsets = [60, 90*60, 150*60, 210*60, 25*60*60, 49*60*60]
now = datetime.now(timezone.utc)
test_dates = [now - timedelta(seconds=s) for s in test_offsets]
- test_archives = [
- MockArchive(date, i) for i, date in enumerate(test_dates)
- ]
+ test_archives = [MockArchive(date) for date in test_dates]
dotest(test_archives, '1H', [0])
dotest(test_archives, '2H', [0, 1])
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_issue_reference",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 1,
"test_score": 1
},
"num_modified_files": 3
} | 1.1 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest pytest-cov pytest-xdist pytest-mock pytest-asyncio",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc libssl-dev libacl1-dev liblz4-dev libzstd-dev pkg-config build-essential"
],
"python": "3.9",
"reqs_path": [
"requirements.d/development.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | -e git+https://github.com/borgbackup/borg.git@4a58310433f21857fc124eed4bafde2956bac46a#egg=borgbackup
cachetools==5.5.2
chardet==5.2.0
colorama==0.4.6
coverage==7.8.0
Cython==3.0.12
distlib==0.3.9
exceptiongroup==1.2.2
execnet==2.1.1
filelock==3.18.0
iniconfig==2.1.0
msgpack-python==0.5.6
packaging==24.2
platformdirs==4.3.7
pluggy==1.5.0
py-cpuinfo==9.0.0
pyproject-api==1.9.0
pytest==8.3.5
pytest-asyncio==0.26.0
pytest-benchmark==5.1.0
pytest-cov==6.0.0
pytest-mock==3.14.0
pytest-xdist==3.6.1
pyzmq==26.3.0
setuptools-scm==8.2.0
tomli==2.2.1
tox==4.25.0
typing_extensions==4.13.0
virtualenv==20.29.3
| name: borg
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- cachetools==5.5.2
- chardet==5.2.0
- colorama==0.4.6
- coverage==7.8.0
- cython==3.0.12
- distlib==0.3.9
- exceptiongroup==1.2.2
- execnet==2.1.1
- filelock==3.18.0
- iniconfig==2.1.0
- msgpack-python==0.5.6
- packaging==24.2
- platformdirs==4.3.7
- pluggy==1.5.0
- py-cpuinfo==9.0.0
- pyproject-api==1.9.0
- pytest==8.3.5
- pytest-asyncio==0.26.0
- pytest-benchmark==5.1.0
- pytest-cov==6.0.0
- pytest-mock==3.14.0
- pytest-xdist==3.6.1
- pyzmq==26.3.0
- setuptools-scm==8.2.0
- tomli==2.2.1
- tox==4.25.0
- typing-extensions==4.13.0
- virtualenv==20.29.3
prefix: /opt/conda/envs/borg
| [
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_prune_repository",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_prune_repository_glob",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_prune_repository_prefix",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_prune_repository_save_space",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_prune_repository",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_prune_repository_glob",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_prune_repository_prefix",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_prune_repository_save_space",
"src/borg/testsuite/helpers.py::PruneSplitTestCase::test",
"src/borg/testsuite/helpers.py::PruneWithinTestCase::test_prune_within"
]
| [
"src/borg/testsuite/archiver.py::test_return_codes[python]",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_common_options",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_auto_compressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_auto_uncompressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_lz4_compressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_lzma_compressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_none_compressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_none_uncompressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_zlib_compressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_corrupted_repository",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_json",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_no_cache_sync",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_stdin",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_debug_dump_archive",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_debug_dump_manifest",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_debug_info",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_debug_refcount_obj",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_delete_multiple",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_detect_attic_repo",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_info_json",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_list_json",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_list_repository_format",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_list_size",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_log_json",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_rechunkify",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_recompress",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_target",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_check_usage",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_corrupted_manifest",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_manifest_rebuild_corrupted_chunk",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_missing_file_chunk",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_missing_manifest",
"src/borg/testsuite/archiver.py::ManifestAuthenticationTest::test_disable",
"src/borg/testsuite/archiver.py::ManifestAuthenticationTest::test_disable2",
"src/borg/testsuite/archiver.py::ManifestAuthenticationTest::test_not_required",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_common_options",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_auto_compressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_auto_uncompressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_lz4_compressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_lz4_uncompressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_lzma_compressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_lzma_uncompressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_none_compressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_none_uncompressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_zlib_compressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_zlib_uncompressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_json",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_no_cache_sync",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_stdin",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_debug_dump_archive",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_debug_dump_manifest",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_debug_info",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_debug_refcount_obj",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_delete_force",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_delete_multiple",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_detect_attic_repo",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_info_json",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_init_nested_repositories",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_list_json",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_list_repository_format",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_list_size",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_rechunkify",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_recompress",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_target",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_remote_repo_restrict_to_path",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_remote_repo_restrict_to_repository",
"src/borg/testsuite/archiver.py::ArchiverCorruptionTestCase::test_cache_chunks",
"src/borg/testsuite/archiver.py::ArchiverCorruptionTestCase::test_cache_files",
"src/borg/testsuite/archiver.py::ArchiverCorruptionTestCase::test_chunks_archive",
"src/borg/testsuite/archiver.py::ArchiverCorruptionTestCase::test_old_version_interfered",
"src/borg/testsuite/archiver.py::DiffArchiverTestCase::test_sort_option",
"src/borg/testsuite/helpers.py::test_is_slow_msgpack"
]
| [
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_aes_counter_uniqueness_keyfile",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_aes_counter_uniqueness_passphrase",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_atime",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_bad_filters",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_basic_functionality",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_benchmark_crud",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_break_lock",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_change_passphrase",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_check_cache",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_comment",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_lz4_uncompressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_lzma_uncompressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_zlib_uncompressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_dry_run",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_pattern",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_pattern_exclude_folder_but_recurse",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_pattern_exclude_folder_no_recurse",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_pattern_file",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_pattern_intermediate_folders_first",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_pattern_root",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_read_special_broken_symlink",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_topical",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_without_root",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_debug_dump_archive_items",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_debug_dump_repo_objs",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_debug_profile",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_debug_put_get_delete_obj",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_delete",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_delete_double_force",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_delete_force",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_delete_repo",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_exclude_caches",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_exclude_keep_tagged",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_exclude_keep_tagged_deprecation",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_exclude_normalization",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_exclude_tagged",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_export_tar",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_export_tar_gz",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_export_tar_strip_components",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_export_tar_strip_components_links",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_extract_hardlinks",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_extract_include_exclude",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_extract_include_exclude_regex",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_extract_include_exclude_regex_from_file",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_extract_list_output",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_extract_pattern_opt",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_extract_progress",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_extract_with_pattern",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_file_status",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_file_status_cs_cache_mode",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_file_status_excluded",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_file_status_ms_cache_mode",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_file_status_rc_cache_mode",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_help",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_info",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_init_interrupt",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_init_nested_repositories",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_init_requires_encryption_option",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_key_export_keyfile",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_key_export_paperkey",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_key_export_qr",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_key_export_repokey",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_key_import_errors",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_key_import_paperkey",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_list_chunk_counts",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_list_format",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_list_hash",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_list_json_args",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_list_prefix",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_overwrite",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_path_normalization",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_progress_off",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_progress_on",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_basic",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_dry_run",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_exclude_caches",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_exclude_keep_tagged",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_exclude_tagged",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_list_output",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_skips_nothing_to_do",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_subtree_hardlinks",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_target_rc",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_rename",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_repeated_files",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_repository_move",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_repository_swap_detection",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_repository_swap_detection2",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_repository_swap_detection2_no_cache",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_repository_swap_detection_no_cache",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_repository_swap_detection_repokey_blank_passphrase",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_security_dir_compat",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_sparse_file",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_strip_components",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_strip_components_links",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_symlink_extract",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_umask",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unix_socket",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unknown_feature_on_cache_sync",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unknown_feature_on_change_passphrase",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unknown_feature_on_create",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unknown_feature_on_delete",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unknown_feature_on_read",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unknown_feature_on_rename",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unknown_mandatory_feature_in_cache",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unknown_unencrypted",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unusual_filenames",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_usage",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_with_lock",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_attic013_acl_bug",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_empty_repository",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_extra_chunks",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_manifest_rebuild_duplicate_archive",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_missing_archive_item_chunk",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_missing_archive_metadata",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_verify_data",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_verify_data_unencrypted",
"src/borg/testsuite/archiver.py::ManifestAuthenticationTest::test_fresh_init_tam_required",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_aes_counter_uniqueness_keyfile",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_aes_counter_uniqueness_passphrase",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_atime",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_bad_filters",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_basic_functionality",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_benchmark_crud",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_break_lock",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_change_passphrase",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_check_cache",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_comment",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_corrupted_repository",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_dry_run",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_pattern",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_pattern_exclude_folder_but_recurse",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_pattern_exclude_folder_no_recurse",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_pattern_file",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_pattern_intermediate_folders_first",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_pattern_root",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_read_special_broken_symlink",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_topical",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_without_root",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_debug_dump_archive_items",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_debug_dump_repo_objs",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_debug_profile",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_delete",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_delete_double_force",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_delete_repo",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_exclude_caches",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_exclude_keep_tagged",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_exclude_keep_tagged_deprecation",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_exclude_normalization",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_exclude_tagged",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_export_tar",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_export_tar_gz",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_export_tar_strip_components",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_export_tar_strip_components_links",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_extract_hardlinks",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_extract_include_exclude",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_extract_include_exclude_regex",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_extract_include_exclude_regex_from_file",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_extract_list_output",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_extract_pattern_opt",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_extract_progress",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_extract_with_pattern",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_file_status",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_file_status_cs_cache_mode",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_file_status_excluded",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_file_status_ms_cache_mode",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_file_status_rc_cache_mode",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_help",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_info",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_init_interrupt",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_init_requires_encryption_option",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_key_export_keyfile",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_key_export_paperkey",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_key_export_qr",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_key_export_repokey",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_key_import_errors",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_key_import_paperkey",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_list_chunk_counts",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_list_format",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_list_hash",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_list_json_args",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_list_prefix",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_log_json",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_overwrite",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_path_normalization",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_progress_off",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_progress_on",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_basic",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_dry_run",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_exclude_caches",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_exclude_keep_tagged",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_exclude_tagged",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_list_output",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_skips_nothing_to_do",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_subtree_hardlinks",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_target_rc",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_rename",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_repeated_files",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_repository_move",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_repository_swap_detection",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_repository_swap_detection2",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_repository_swap_detection2_no_cache",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_repository_swap_detection_no_cache",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_repository_swap_detection_repokey_blank_passphrase",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_security_dir_compat",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_sparse_file",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_strip_components",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_strip_components_doesnt_leak",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_strip_components_links",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_symlink_extract",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_umask",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unix_socket",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unknown_feature_on_cache_sync",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unknown_feature_on_change_passphrase",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unknown_feature_on_create",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unknown_feature_on_delete",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unknown_feature_on_read",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unknown_feature_on_rename",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unknown_mandatory_feature_in_cache",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unknown_unencrypted",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unusual_filenames",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_usage",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_with_lock",
"src/borg/testsuite/archiver.py::DiffArchiverTestCase::test_basic_functionality",
"src/borg/testsuite/archiver.py::test_get_args",
"src/borg/testsuite/archiver.py::test_chunk_content_equal",
"src/borg/testsuite/archiver.py::TestBuildFilter::test_basic",
"src/borg/testsuite/archiver.py::TestBuildFilter::test_empty",
"src/borg/testsuite/archiver.py::TestBuildFilter::test_strip_components",
"src/borg/testsuite/archiver.py::TestCommonOptions::test_simple",
"src/borg/testsuite/archiver.py::TestCommonOptions::test_flag_position_independence[-p-progress-True-before]",
"src/borg/testsuite/archiver.py::TestCommonOptions::test_flag_position_independence[-p-progress-True-after]",
"src/borg/testsuite/archiver.py::TestCommonOptions::test_flag_position_independence[-p-progress-True-both]",
"src/borg/testsuite/archiver.py::TestCommonOptions::test_flag_position_independence[--lock-wait=3-lock_wait-3-before]",
"src/borg/testsuite/archiver.py::TestCommonOptions::test_flag_position_independence[--lock-wait=3-lock_wait-3-after]",
"src/borg/testsuite/archiver.py::TestCommonOptions::test_flag_position_independence[--lock-wait=3-lock_wait-3-both]",
"src/borg/testsuite/archiver.py::test_parse_storage_quota",
"src/borg/testsuite/archiver.py::test_help_formatting[benchmark",
"src/borg/testsuite/archiver.py::test_help_formatting[benchmark-parser1]",
"src/borg/testsuite/archiver.py::test_help_formatting[break-lock-parser2]",
"src/borg/testsuite/archiver.py::test_help_formatting[change-passphrase-parser3]",
"src/borg/testsuite/archiver.py::test_help_formatting[check-parser4]",
"src/borg/testsuite/archiver.py::test_help_formatting[create-parser5]",
"src/borg/testsuite/archiver.py::test_help_formatting[debug",
"src/borg/testsuite/archiver.py::test_help_formatting[debug-parser16]",
"src/borg/testsuite/archiver.py::test_help_formatting[delete-parser17]",
"src/borg/testsuite/archiver.py::test_help_formatting[diff-parser18]",
"src/borg/testsuite/archiver.py::test_help_formatting[export-tar-parser19]",
"src/borg/testsuite/archiver.py::test_help_formatting[extract-parser20]",
"src/borg/testsuite/archiver.py::test_help_formatting[help-parser21]",
"src/borg/testsuite/archiver.py::test_help_formatting[info-parser22]",
"src/borg/testsuite/archiver.py::test_help_formatting[init-parser23]",
"src/borg/testsuite/archiver.py::test_help_formatting[key",
"src/borg/testsuite/archiver.py::test_help_formatting[key-parser28]",
"src/borg/testsuite/archiver.py::test_help_formatting[list-parser29]",
"src/borg/testsuite/archiver.py::test_help_formatting[mount-parser30]",
"src/borg/testsuite/archiver.py::test_help_formatting[prune-parser31]",
"src/borg/testsuite/archiver.py::test_help_formatting[recreate-parser32]",
"src/borg/testsuite/archiver.py::test_help_formatting[rename-parser33]",
"src/borg/testsuite/archiver.py::test_help_formatting[serve-parser34]",
"src/borg/testsuite/archiver.py::test_help_formatting[umount-parser35]",
"src/borg/testsuite/archiver.py::test_help_formatting[upgrade-parser36]",
"src/borg/testsuite/archiver.py::test_help_formatting[with-lock-parser37]",
"src/borg/testsuite/archiver.py::test_help_formatting_helptexts[patterns-\\nFile",
"src/borg/testsuite/archiver.py::test_help_formatting_helptexts[placeholders-\\nRepository",
"src/borg/testsuite/archiver.py::test_help_formatting_helptexts[compression-\\nIt",
"src/borg/testsuite/helpers.py::BigIntTestCase::test_bigint",
"src/borg/testsuite/helpers.py::test_bin_to_hex",
"src/borg/testsuite/helpers.py::TestLocationWithoutEnv::test_ssh",
"src/borg/testsuite/helpers.py::TestLocationWithoutEnv::test_file",
"src/borg/testsuite/helpers.py::TestLocationWithoutEnv::test_scp",
"src/borg/testsuite/helpers.py::TestLocationWithoutEnv::test_smb",
"src/borg/testsuite/helpers.py::TestLocationWithoutEnv::test_folder",
"src/borg/testsuite/helpers.py::TestLocationWithoutEnv::test_long_path",
"src/borg/testsuite/helpers.py::TestLocationWithoutEnv::test_abspath",
"src/borg/testsuite/helpers.py::TestLocationWithoutEnv::test_relpath",
"src/borg/testsuite/helpers.py::TestLocationWithoutEnv::test_with_colons",
"src/borg/testsuite/helpers.py::TestLocationWithoutEnv::test_user_parsing",
"src/borg/testsuite/helpers.py::TestLocationWithoutEnv::test_underspecified",
"src/borg/testsuite/helpers.py::TestLocationWithoutEnv::test_no_slashes",
"src/borg/testsuite/helpers.py::TestLocationWithoutEnv::test_canonical_path",
"src/borg/testsuite/helpers.py::TestLocationWithoutEnv::test_format_path",
"src/borg/testsuite/helpers.py::TestLocationWithoutEnv::test_bad_syntax",
"src/borg/testsuite/helpers.py::TestLocationWithEnv::test_ssh",
"src/borg/testsuite/helpers.py::TestLocationWithEnv::test_file",
"src/borg/testsuite/helpers.py::TestLocationWithEnv::test_scp",
"src/borg/testsuite/helpers.py::TestLocationWithEnv::test_folder",
"src/borg/testsuite/helpers.py::TestLocationWithEnv::test_abspath",
"src/borg/testsuite/helpers.py::TestLocationWithEnv::test_relpath",
"src/borg/testsuite/helpers.py::TestLocationWithEnv::test_with_colons",
"src/borg/testsuite/helpers.py::TestLocationWithEnv::test_no_slashes",
"src/borg/testsuite/helpers.py::FormatTimedeltaTestCase::test",
"src/borg/testsuite/helpers.py::test_chunkerparams",
"src/borg/testsuite/helpers.py::MakePathSafeTestCase::test",
"src/borg/testsuite/helpers.py::IntervalTestCase::test_interval",
"src/borg/testsuite/helpers.py::IntervalTestCase::test_interval_number",
"src/borg/testsuite/helpers.py::IntervalTestCase::test_interval_time_unit",
"src/borg/testsuite/helpers.py::StableDictTestCase::test",
"src/borg/testsuite/helpers.py::TestParseTimestamp::test",
"src/borg/testsuite/helpers.py::test_get_config_dir",
"src/borg/testsuite/helpers.py::test_get_cache_dir",
"src/borg/testsuite/helpers.py::test_get_keys_dir",
"src/borg/testsuite/helpers.py::test_get_security_dir",
"src/borg/testsuite/helpers.py::test_file_size",
"src/borg/testsuite/helpers.py::test_file_size_precision",
"src/borg/testsuite/helpers.py::test_file_size_sign",
"src/borg/testsuite/helpers.py::test_parse_file_size[1-1]",
"src/borg/testsuite/helpers.py::test_parse_file_size[20-20]",
"src/borg/testsuite/helpers.py::test_parse_file_size[5K-5000]",
"src/borg/testsuite/helpers.py::test_parse_file_size[1.75M-1750000]",
"src/borg/testsuite/helpers.py::test_parse_file_size[1e+9-1000000000.0]",
"src/borg/testsuite/helpers.py::test_parse_file_size[-1T--1000000000000.0]",
"src/borg/testsuite/helpers.py::test_parse_file_size_invalid[]",
"src/borg/testsuite/helpers.py::test_parse_file_size_invalid[5",
"src/borg/testsuite/helpers.py::test_parse_file_size_invalid[4E]",
"src/borg/testsuite/helpers.py::test_parse_file_size_invalid[2229",
"src/borg/testsuite/helpers.py::test_parse_file_size_invalid[1B]",
"src/borg/testsuite/helpers.py::TestBuffer::test_type",
"src/borg/testsuite/helpers.py::TestBuffer::test_len",
"src/borg/testsuite/helpers.py::TestBuffer::test_resize",
"src/borg/testsuite/helpers.py::TestBuffer::test_limit",
"src/borg/testsuite/helpers.py::TestBuffer::test_get",
"src/borg/testsuite/helpers.py::test_yes_input",
"src/borg/testsuite/helpers.py::test_yes_input_defaults",
"src/borg/testsuite/helpers.py::test_yes_input_custom",
"src/borg/testsuite/helpers.py::test_yes_env",
"src/borg/testsuite/helpers.py::test_yes_env_default",
"src/borg/testsuite/helpers.py::test_yes_defaults",
"src/borg/testsuite/helpers.py::test_yes_retry",
"src/borg/testsuite/helpers.py::test_yes_no_retry",
"src/borg/testsuite/helpers.py::test_yes_output",
"src/borg/testsuite/helpers.py::test_yes_env_output",
"src/borg/testsuite/helpers.py::test_progress_percentage_sameline",
"src/borg/testsuite/helpers.py::test_progress_percentage_step",
"src/borg/testsuite/helpers.py::test_progress_percentage_quiet",
"src/borg/testsuite/helpers.py::test_progress_endless",
"src/borg/testsuite/helpers.py::test_progress_endless_step",
"src/borg/testsuite/helpers.py::test_partial_format",
"src/borg/testsuite/helpers.py::test_chunk_file_wrapper",
"src/borg/testsuite/helpers.py::test_chunkit",
"src/borg/testsuite/helpers.py::test_clean_lines",
"src/borg/testsuite/helpers.py::test_format_line",
"src/borg/testsuite/helpers.py::test_format_line_erroneous",
"src/borg/testsuite/helpers.py::test_replace_placeholders",
"src/borg/testsuite/helpers.py::test_swidth_slice",
"src/borg/testsuite/helpers.py::test_swidth_slice_mixed_characters",
"src/borg/testsuite/helpers.py::test_safe_timestamps",
"src/borg/testsuite/helpers.py::TestPopenWithErrorHandling::test_simple",
"src/borg/testsuite/helpers.py::TestPopenWithErrorHandling::test_not_found",
"src/borg/testsuite/helpers.py::TestPopenWithErrorHandling::test_bad_syntax[mismatched",
"src/borg/testsuite/helpers.py::TestPopenWithErrorHandling::test_bad_syntax[foo",
"src/borg/testsuite/helpers.py::TestPopenWithErrorHandling::test_bad_syntax[]",
"src/borg/testsuite/helpers.py::TestPopenWithErrorHandling::test_shell",
"src/borg/testsuite/helpers.py::test_dash_open"
]
| []
| BSD License | 1,839 | [
"src/borg/helpers/misc.py",
"src/borg/remote.py",
"src/borg/archiver.py"
]
| [
"src/borg/helpers/misc.py",
"src/borg/remote.py",
"src/borg/archiver.py"
]
|
|
OpenMined__PySyft-392 | 34af4f778c2b2f1a16a5a8aa505c37b7d9b18009 | 2017-11-02 19:06:29 | 06ce023225dd613d8fb14ab2046135b93ab22376 | codecov[bot]: # [Codecov](https://codecov.io/gh/OpenMined/PySyft/pull/392?src=pr&el=h1) Report
> Merging [#392](https://codecov.io/gh/OpenMined/PySyft/pull/392?src=pr&el=desc) into [master](https://codecov.io/gh/OpenMined/PySyft/commit/34af4f778c2b2f1a16a5a8aa505c37b7d9b18009?src=pr&el=desc) will **increase** coverage by `<.01%`.
> The diff coverage is `n/a`.
[](https://codecov.io/gh/OpenMined/PySyft/pull/392?src=pr&el=tree)
```diff
@@ Coverage Diff @@
## master #392 +/- ##
==========================================
+ Coverage 99.52% 99.53% +<.01%
==========================================
Files 4 4
Lines 1701 1725 +24
==========================================
+ Hits 1693 1717 +24
Misses 8 8
```
| [Impacted Files](https://codecov.io/gh/OpenMined/PySyft/pull/392?src=pr&el=tree) | Coverage Δ | |
|---|---|---|
| [PySyft/tests/test\_math.py](https://codecov.io/gh/OpenMined/PySyft/pull/392?src=pr&el=tree#diff-UHlTeWZ0L3Rlc3RzL3Rlc3RfbWF0aC5weQ==) | `100% <0%> (ø)` | :arrow_up: |
| [PySyft/tests/test\_tensor.py](https://codecov.io/gh/OpenMined/PySyft/pull/392?src=pr&el=tree#diff-UHlTeWZ0L3Rlc3RzL3Rlc3RfdGVuc29yLnB5) | `99.35% <0%> (ø)` | :arrow_up: |
------
[Continue to review full report at Codecov](https://codecov.io/gh/OpenMined/PySyft/pull/392?src=pr&el=continue).
> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
> `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
> Powered by [Codecov](https://codecov.io/gh/OpenMined/PySyft/pull/392?src=pr&el=footer). Last update [34af4f7...8e876e2](https://codecov.io/gh/OpenMined/PySyft/pull/392?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).
bharathgs: Also, update the *__init__.py* as well. | diff --git a/syft/__init__.py b/syft/__init__.py
index 43b3fa7b10..cada8b5181 100644
--- a/syft/__init__.py
+++ b/syft/__init__.py
@@ -7,7 +7,8 @@ from syft import nonlin
from syft.tensor import equal, TensorBase
from syft.math import cumprod, cumsum, ceil, dot, matmul, addmm, addcmul
from syft.math import addcdiv, addmv, bmm, addbmm, baddbmm, transpose
-from syft.math import unsqueeze, zeros, ones, rand, randn, mm, fmod, diag, lerp, renorm, numel
+from syft.math import unsqueeze, zeros, ones, rand, randn, mm, fmod, diag
+from syft.math import lerp, renorm, numel, cross
s = str(he)
s += str(nn)
@@ -26,3 +27,4 @@ s += str(fmod)
s += str(lerp)
s += str(numel)
s += str(renorm)
+s += str(cross)
diff --git a/syft/math.py b/syft/math.py
index 4d395a6a0d..207942c75b 100644
--- a/syft/math.py
+++ b/syft/math.py
@@ -20,7 +20,7 @@ __all__ = [
'cumprod', 'cumsum', 'ceil', 'dot', 'floor', 'matmul', 'addmm', 'addcmul',
'addcdiv', 'addmv', 'bmm', 'addbmm', 'baddbmm', 'sigmoid', 'unsqueeze',
'sin', 'sinh', 'cos', 'cosh', 'tan', 'tanh', 'zeros', 'ones', 'rand',
- 'randn', 'mm', 'fmod', 'diag', 'lerp', 'renorm', 'numel'
+ 'randn', 'mm', 'fmod', 'diag', 'lerp', 'renorm', 'numel', 'cross'
]
@@ -1008,3 +1008,49 @@ def split(tensor, split_size, axis=0):
list_ = np.array_split(tensor.data, split_according, axis)
return list(map(lambda x: TensorBase(x), list_))
+
+
+def cross(input, other, dim=-1):
+ """
+ Computes cross products between two tensors in the given dimension
+ The two vectors must have the same size, and the size of the dim
+ dimension should be 3.
+
+ Parameters
+ ----------
+
+ input: TensorBase
+ the first input tensor
+
+ other: TensorBase
+ the second input tensor
+
+ dim: int, optional
+ the dimension to take the cross-product in. Default is -1
+
+ Returns
+ -------
+ TensorBase: The result Tensor
+ """
+ input = _ensure_tensorbase(input)
+ other = _ensure_tensorbase(other)
+
+ if input.encrypted or other.encrypted:
+ return NotImplemented
+
+ # Verify that the shapes of both vectors are same
+ if input.shape() != other.shape():
+ raise ValueError('inconsistent dimensions {} and {}'.format(
+ input.shape(), other.shape()))
+
+ # verify that the given dim is valid
+ if dim < -len(input.shape()) or dim >= len(input.shape()):
+ raise ValueError('invalid dim. Should be between {} and {}'.format(
+ -len(input.shape()), len(input.shape()) - 1))
+
+ # verify that the size of dimension dim is 3
+ if input.shape()[dim] != 3:
+ raise ValueError('size of dimension {}(dim) is {}. Should be 3'.format(
+ dim, input.shape()[-1]))
+
+ return TensorBase(np.cross(input, other, axis=dim))
diff --git a/syft/tensor.py b/syft/tensor.py
index 89f23c3b05..f5dadf7f7d 100644
--- a/syft/tensor.py
+++ b/syft/tensor.py
@@ -3605,3 +3605,24 @@ class TensorBase(object):
return NotImplemented
return syft.math.split(self, split_size, axis)
+
+ def cross(self, tensor, dim=-1):
+ """
+ Computes cross products between two tensors in the given dimension
+ The two vectors must have the same size, and the size of the dim
+ dimension should be 3.
+
+ Parameters
+ ----------
+
+ tensor: TensorBase
+ the second input tensor
+
+ dim: int, optional
+ the dimension to take the cross-product in. Default is -1
+
+ Returns
+ -------
+ TensorBase: The result Tensor
+ """
+ return syft.math.cross(self, tensor, dim)
| Implement Default cross Functionality for Base Tensor Type.
<!-- Please make sure that you review this: https://github.com/OpenMined/Docs/blob/master/contributing/guidelines.md -->
<!-- If you are looking to file a bug make sure to look at the .github/BUG_ISSUE_TEMPLATE.md -->
#### User story:
As a Data Scientist using Syft's Base Tensor type, I want to leverage a default method for computing operations on a Tensor of arbitrary type. For this ticket to be complete `cross` should return a new tensor. For a reference on the operation these perform check out [PyTorch's](http://pytorch.org/docs/master/torch.html#torch.cross) documentation.
<!-- Provide a detailed explaination about the proposed feature, you can draw inspiration from something like this:
https://github.com/OpenMined/PySyft/issues/227 or https://github.com/OpenMined/PySyft/issues/12 -->
#### Acceptance Criteria:
<!-- Provide an outline af all the things that needs to be addressed in order to close this Issue,
be as descriptive as possible -->
- [ ] If the Base Tensor type's attribute "encrypted" is set to True, it should return a NotImplemented error.
- [ ] corresponding unit tests demonstrating the correct operation on the Base Tensor type implemented over int and float Tensors.
- [ ] inline documentation as described over [here](https://github.com/OpenMined/PySyft/blob/85bc68e81a2f4bfc0f0bf6c4252b88d6d7b54004/syft/math.py#L5).
<!-- Thanks for your contributions! -->
| OpenMined/PySyft | diff --git a/tests/test_math.py b/tests/test_math.py
index 09aad0a9f7..c90a0c3cb9 100644
--- a/tests/test_math.py
+++ b/tests/test_math.py
@@ -441,3 +441,31 @@ class SplitTests(unittest.TestCase):
self.assertTrue(syft.equal(split.shape(), target_shape))
self.assertTrue(syft.equal(t.narrow(axis, start, target_shape[axis]), split))
start += target_shape[axis]
+
+
+class CrossTests(unittest.TestCase):
+ def setUp(self):
+ self.a = np.eye(2, 3)
+ self.b = np.ones((2, 3))
+
+ def test_cross(self):
+ a = TensorBase(self.a)
+ b = TensorBase(self.b)
+
+ # Verify that the expected result is retuned
+ expected_result = np.array([0, -1, 1, 1, 0, -1]).reshape(2, 3)
+ self.assertTrue(np.array_equal(a.cross(b), expected_result))
+
+ # Verify that ValueError is thrown when dimension is out of bounds
+ self.assertRaises(ValueError, a.cross, b, 5)
+
+ # Verify that ValueError is thrown when size dimension dim != 3
+ self.assertRaises(ValueError, a.cross, b, 0)
+
+ # Verify that ValueError is thrown when dimensions don't match
+ a = TensorBase(self.a.reshape(3, 2))
+ self.assertRaises(ValueError, a.cross, b)
+
+ # Verify that NotImplemented is returned if Tensor is encrypted
+ a = TensorBase(self.a, True)
+ self.assertEqual(a.cross(b), NotImplemented)
diff --git a/tests/test_tensor.py b/tests/test_tensor.py
index 3c9052c3bf..9d7143a875 100644
--- a/tests/test_tensor.py
+++ b/tests/test_tensor.py
@@ -1635,6 +1635,20 @@ class SplitTests(unittest.TestCase):
start += target_shape[axis]
+class CrossTests(unittest.TestCase):
+ def setUp(self):
+ self.a = np.eye(2, 3)
+ self.b = np.ones((2, 3))
+
+ def test_cross(self):
+ a = TensorBase(self.a)
+ b = TensorBase(self.b)
+ expected_result = np.array([0, -1, 1, 1, 0, -1]).reshape(2, 3)
+
+ # Verify that the expected result is retuned
+ self.assertTrue(np.array_equal(a.cross(b), expected_result))
+
+
if __name__ == "__main__":
unittest.main()
| {
"commit_name": "merge_commit",
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 1,
"test_score": 0
},
"num_modified_files": 3
} | PySyft/hydrogen | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"line_profiler",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y musl-dev g++ libgmp3-dev libmpfr-dev ca-certificates"
],
"python": "3.9",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | exceptiongroup==1.2.2
iniconfig==2.1.0
line_profiler==4.2.0
numpy==1.26.4
packaging==24.2
phe==1.5.0
pluggy==1.5.0
pyRserve==1.0.4
pytest==8.3.5
scipy==1.13.1
-e git+https://github.com/OpenMined/PySyft.git@34af4f778c2b2f1a16a5a8aa505c37b7d9b18009#egg=syft
tomli==2.2.1
| name: PySyft
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- exceptiongroup==1.2.2
- iniconfig==2.1.0
- line-profiler==4.2.0
- numpy==1.26.4
- packaging==24.2
- phe==1.5.0
- pluggy==1.5.0
- pyrserve==1.0.4
- pytest==8.3.5
- scipy==1.13.1
- tomli==2.2.1
prefix: /opt/conda/envs/PySyft
| [
"tests/test_math.py::CrossTests::test_cross",
"tests/test_tensor.py::CrossTests::test_cross"
]
| [
"tests/test_tensor.py::ScatterTests::test_scatter_numerical_0",
"tests/test_tensor.py::ScatterTests::test_scatter_numerical_1",
"tests/test_tensor.py::ScatterTests::test_scatter_numerical_2",
"tests/test_tensor.py::ScatterTests::test_scatter_numerical_3",
"tests/test_tensor.py::ScatterTests::test_scatter_numerical_4",
"tests/test_tensor.py::ScatterTests::test_scatter_numerical_5",
"tests/test_tensor.py::ScatterTests::test_scatter_numerical_6",
"tests/test_tensor.py::UnfoldTest::test_unfold_big",
"tests/test_tensor.py::UnfoldTest::test_unfold_small"
]
| [
"tests/test_math.py::ConvenienceTests::test_ones",
"tests/test_math.py::ConvenienceTests::test_rand",
"tests/test_math.py::ConvenienceTests::test_zeros",
"tests/test_math.py::DotTests::test_dot_float",
"tests/test_math.py::DotTests::test_dot_int",
"tests/test_math.py::DiagTests::test_one_dim_tensor_below_diag",
"tests/test_math.py::DiagTests::test_one_dim_tensor_main_diag",
"tests/test_math.py::DiagTests::test_one_dim_tensor_upper_diag",
"tests/test_math.py::DiagTests::test_two_dim_tensor_below_diag",
"tests/test_math.py::DiagTests::test_two_dim_tensor_main_diag",
"tests/test_math.py::DiagTests::test_two_dim_tensor_upper_diag",
"tests/test_math.py::CeilTests::test_ceil",
"tests/test_math.py::FloorTests::test_floor",
"tests/test_math.py::SinTests::test_sin",
"tests/test_math.py::SinhTests::test_sinh",
"tests/test_math.py::CosTests::test_cos",
"tests/test_math.py::CoshTests::test_cosh",
"tests/test_math.py::TanTests::test_tan",
"tests/test_math.py::TanhTests::test_tanh",
"tests/test_math.py::CumsumTests::test_cumsum",
"tests/test_math.py::CumprodTests::test_cumprod",
"tests/test_math.py::SigmoidTests::test_sigmoid",
"tests/test_math.py::MatmulTests::test_matmul_1d_float",
"tests/test_math.py::MatmulTests::test_matmul_1d_int",
"tests/test_math.py::MatmulTests::test_matmul_2d_float",
"tests/test_math.py::MatmulTests::test_matmul_2d_identity",
"tests/test_math.py::MatmulTests::test_matmul_2d_int",
"tests/test_math.py::AddmmTests::test_addmm_1d",
"tests/test_math.py::AddmmTests::test_addmm_2d",
"tests/test_math.py::AddcmulTests::test_addcmul_1d",
"tests/test_math.py::AddcmulTests::test_addcmul_2d",
"tests/test_math.py::AddcdivTests::test_addcdiv_1d",
"tests/test_math.py::AddcdivTests::test_addcdiv_2d",
"tests/test_math.py::AddmvTests::test_addmv",
"tests/test_math.py::BmmTests::test_bmm",
"tests/test_math.py::BmmTests::test_bmm_for_correct_size_output",
"tests/test_math.py::AddbmmTests::test_addbmm",
"tests/test_math.py::BaddbmmTests::test_baddbmm",
"tests/test_math.py::TransposeTests::test_transpose",
"tests/test_math.py::UnsqueezeTests::test_unsqueeze",
"tests/test_math.py::MmTests::test_mm_1d",
"tests/test_math.py::MmTests::test_mm_2d",
"tests/test_math.py::MmTests::test_mm_3d",
"tests/test_math.py::FmodTests::test_fmod_number",
"tests/test_math.py::FmodTests::test_fmod_tensor",
"tests/test_math.py::LerpTests::test_lerp",
"tests/test_math.py::NumelTests::test_numel_float",
"tests/test_math.py::NumelTests::test_numel_int",
"tests/test_math.py::RenormTests::test_3d_tensor_renorm",
"tests/test_math.py::RenormTests::test_float_renorm",
"tests/test_math.py::RenormTests::test_int_renorm",
"tests/test_math.py::MultinomialTests::test_multinomial",
"tests/test_math.py::SplitTests::test_split",
"tests/test_tensor.py::DimTests::test_as_view",
"tests/test_tensor.py::DimTests::test_dim_one",
"tests/test_tensor.py::DimTests::test_resize",
"tests/test_tensor.py::DimTests::test_resize_as",
"tests/test_tensor.py::DimTests::test_view",
"tests/test_tensor.py::DiagTests::test_one_dim_tensor_below_diag",
"tests/test_tensor.py::DiagTests::test_one_dim_tensor_main_diag",
"tests/test_tensor.py::DiagTests::test_one_dim_tensor_upper_diag",
"tests/test_tensor.py::DiagTests::test_two_dim_tensor_below_diag",
"tests/test_tensor.py::DiagTests::test_two_dim_tensor_main_diag",
"tests/test_tensor.py::DiagTests::test_two_dim_tensor_upper_diag",
"tests/test_tensor.py::AddTests::test_inplace",
"tests/test_tensor.py::AddTests::test_scalar",
"tests/test_tensor.py::AddTests::test_simple",
"tests/test_tensor.py::CeilTests::test_ceil",
"tests/test_tensor.py::CeilTests::test_ceil_",
"tests/test_tensor.py::ZeroTests::test_zero",
"tests/test_tensor.py::FloorTests::test_floor",
"tests/test_tensor.py::SubTests::test_inplace",
"tests/test_tensor.py::SubTests::test_scalar",
"tests/test_tensor.py::SubTests::test_simple",
"tests/test_tensor.py::MaxTests::test_axis",
"tests/test_tensor.py::MaxTests::test_no_dim",
"tests/test_tensor.py::MultTests::test_inplace",
"tests/test_tensor.py::MultTests::test_scalar",
"tests/test_tensor.py::MultTests::test_simple",
"tests/test_tensor.py::DivTests::test_inplace",
"tests/test_tensor.py::DivTests::test_scalar",
"tests/test_tensor.py::DivTests::test_simple",
"tests/test_tensor.py::AbsTests::test_abs",
"tests/test_tensor.py::AbsTests::test_abs_",
"tests/test_tensor.py::ShapeTests::test_shape",
"tests/test_tensor.py::SqrtTests::test_sqrt",
"tests/test_tensor.py::SqrtTests::test_sqrt_",
"tests/test_tensor.py::SumTests::test_dim_is_not_none_int",
"tests/test_tensor.py::SumTests::test_dim_none_int",
"tests/test_tensor.py::EqualTests::test_equal",
"tests/test_tensor.py::EqualTests::test_equal_operation",
"tests/test_tensor.py::EqualTests::test_inequality_operation",
"tests/test_tensor.py::EqualTests::test_not_equal",
"tests/test_tensor.py::EqualTests::test_shape_inequality_operation",
"tests/test_tensor.py::EqualTests::test_shape_not_equal",
"tests/test_tensor.py::SigmoidTests::test_sigmoid",
"tests/test_tensor.py::AddmmTests::test_addmm_1d",
"tests/test_tensor.py::AddmmTests::test_addmm_1d_",
"tests/test_tensor.py::AddmmTests::test_addmm_2d",
"tests/test_tensor.py::AddmmTests::test_addmm_2d_",
"tests/test_tensor.py::AddcmulTests::test_addcmul_1d",
"tests/test_tensor.py::AddcmulTests::test_addcmul_1d_",
"tests/test_tensor.py::AddcmulTests::test_addcmul_2d",
"tests/test_tensor.py::AddcmulTests::test_addcmul_2d_",
"tests/test_tensor.py::AddcdivTests::test_addcdiv_1d",
"tests/test_tensor.py::AddcdivTests::test_addcdiv_1d_",
"tests/test_tensor.py::AddcdivTests::test_addcdiv_2d",
"tests/test_tensor.py::AddcdivTests::test_addcdiv_2d_",
"tests/test_tensor.py::AddmvTests::test_addmv",
"tests/test_tensor.py::AddmvTests::test_addmv_",
"tests/test_tensor.py::BmmTests::test_bmm",
"tests/test_tensor.py::BmmTests::test_bmm_size",
"tests/test_tensor.py::AddbmmTests::test_addbmm",
"tests/test_tensor.py::AddbmmTests::test_addbmm_",
"tests/test_tensor.py::BaddbmmTests::test_baddbmm",
"tests/test_tensor.py::BaddbmmTests::test_baddbmm_",
"tests/test_tensor.py::TransposeTests::test_t",
"tests/test_tensor.py::TransposeTests::test_transpose",
"tests/test_tensor.py::TransposeTests::test_transpose_",
"tests/test_tensor.py::UnsqueezeTests::test_unsqueeze",
"tests/test_tensor.py::UnsqueezeTests::test_unsqueeze_",
"tests/test_tensor.py::ExpTests::test_exp",
"tests/test_tensor.py::ExpTests::test_exp_",
"tests/test_tensor.py::FracTests::test_frac",
"tests/test_tensor.py::FracTests::test_frac_",
"tests/test_tensor.py::RsqrtTests::test_rsqrt",
"tests/test_tensor.py::RsqrtTests::test_rsqrt_",
"tests/test_tensor.py::SignTests::test_sign",
"tests/test_tensor.py::SignTests::test_sign_",
"tests/test_tensor.py::NumpyTests::test_numpy",
"tests/test_tensor.py::ReciprocalTests::test_reciprocal",
"tests/test_tensor.py::ReciprocalTests::test_reciprocal_",
"tests/test_tensor.py::LogTests::test_log",
"tests/test_tensor.py::LogTests::test_log_",
"tests/test_tensor.py::LogTests::test_log_1p",
"tests/test_tensor.py::LogTests::test_log_1p_",
"tests/test_tensor.py::ClampTests::test_clamp_float",
"tests/test_tensor.py::ClampTests::test_clamp_float_in_place",
"tests/test_tensor.py::ClampTests::test_clamp_int",
"tests/test_tensor.py::ClampTests::test_clamp_int_in_place",
"tests/test_tensor.py::CloneTests::test_clone",
"tests/test_tensor.py::ChunkTests::test_chunk",
"tests/test_tensor.py::ChunkTests::test_chunk_same_size",
"tests/test_tensor.py::GtTests::test_gt__in_place_with_number",
"tests/test_tensor.py::GtTests::test_gt__in_place_with_tensor",
"tests/test_tensor.py::GtTests::test_gt_with_encrypted",
"tests/test_tensor.py::GtTests::test_gt_with_number",
"tests/test_tensor.py::GtTests::test_gt_with_tensor",
"tests/test_tensor.py::GeTests::test_ge__in_place_with_number",
"tests/test_tensor.py::GeTests::test_ge__in_place_with_tensor",
"tests/test_tensor.py::GeTests::test_ge_with_encrypted",
"tests/test_tensor.py::GeTests::test_ge_with_number",
"tests/test_tensor.py::GeTests::test_ge_with_tensor",
"tests/test_tensor.py::LtTests::test_lt__in_place_with_number",
"tests/test_tensor.py::LtTests::test_lt__in_place_with_tensor",
"tests/test_tensor.py::LtTests::test_lt_with_encrypted",
"tests/test_tensor.py::LtTests::test_lt_with_number",
"tests/test_tensor.py::LtTests::test_lt_with_tensor",
"tests/test_tensor.py::LeTests::test_le__in_place_with_number",
"tests/test_tensor.py::LeTests::test_le__in_place_with_tensor",
"tests/test_tensor.py::LeTests::test_le_with_encrypted",
"tests/test_tensor.py::LeTests::test_le_with_number",
"tests/test_tensor.py::LeTests::test_le_with_tensor",
"tests/test_tensor.py::BernoulliTests::test_bernoulli",
"tests/test_tensor.py::BernoulliTests::test_bernoulli_",
"tests/test_tensor.py::MultinomialTests::test_multinomial",
"tests/test_tensor.py::CauchyTests::test_cauchy_",
"tests/test_tensor.py::UniformTests::test_uniform",
"tests/test_tensor.py::UniformTests::test_uniform_",
"tests/test_tensor.py::GeometricTests::test_geometric_",
"tests/test_tensor.py::NormalTests::test_normal",
"tests/test_tensor.py::NormalTests::test_normal_",
"tests/test_tensor.py::FillTests::test_fill_",
"tests/test_tensor.py::TopkTests::test_topK",
"tests/test_tensor.py::TolistTests::test_to_list",
"tests/test_tensor.py::TraceTests::test_trace",
"tests/test_tensor.py::RoundTests::test_round",
"tests/test_tensor.py::RoundTests::test_round_",
"tests/test_tensor.py::RepeatTests::test_repeat",
"tests/test_tensor.py::PowTests::test_pow",
"tests/test_tensor.py::PowTests::test_pow_",
"tests/test_tensor.py::NegTests::test_neg",
"tests/test_tensor.py::NegTests::test_neg_",
"tests/test_tensor.py::SinTests::test_sin",
"tests/test_tensor.py::SinhTests::test_sinh",
"tests/test_tensor.py::CosTests::test_cos",
"tests/test_tensor.py::CoshTests::test_cosh",
"tests/test_tensor.py::TanTests::test_tan",
"tests/test_tensor.py::TanhTests::test_tanh_",
"tests/test_tensor.py::ProdTests::test_prod",
"tests/test_tensor.py::RandomTests::test_random_",
"tests/test_tensor.py::NonzeroTests::test_non_zero",
"tests/test_tensor.py::CumprodTest::test_cumprod",
"tests/test_tensor.py::CumprodTest::test_cumprod_",
"tests/test_tensor.py::SqueezeTests::test_squeeze",
"tests/test_tensor.py::ExpandAsTests::test_expand_as",
"tests/test_tensor.py::MeanTests::test_mean",
"tests/test_tensor.py::NotEqualTests::test_ne",
"tests/test_tensor.py::NotEqualTests::test_ne_",
"tests/test_tensor.py::IndexTests::test_index",
"tests/test_tensor.py::IndexTests::test_index_add_",
"tests/test_tensor.py::IndexTests::test_index_copy_",
"tests/test_tensor.py::IndexTests::test_index_fill_",
"tests/test_tensor.py::IndexTests::test_index_select",
"tests/test_tensor.py::IndexTests::test_index_slice_notation",
"tests/test_tensor.py::IndexTests::test_indexing",
"tests/test_tensor.py::GatherTests::test_gather_numerical_1",
"tests/test_tensor.py::GatherTests::test_gather_numerical_2",
"tests/test_tensor.py::ScatterTests::test_scatter_dim_out_Of_range",
"tests/test_tensor.py::ScatterTests::test_scatter_index_out_of_range",
"tests/test_tensor.py::ScatterTests::test_scatter_index_src_dimension_mismatch",
"tests/test_tensor.py::ScatterTests::test_scatter_index_type",
"tests/test_tensor.py::RemainderTests::test_remainder_",
"tests/test_tensor.py::RemainderTests::test_remainder_broadcasting",
"tests/test_tensor.py::MvTests::test_mv",
"tests/test_tensor.py::MvTests::test_mv_tensor",
"tests/test_tensor.py::NarrowTests::test_narrow_float",
"tests/test_tensor.py::NarrowTests::test_narrow_int",
"tests/test_tensor.py::MaskedScatterTests::test_masked_scatter_1",
"tests/test_tensor.py::MaskedScatterTests::test_masked_scatter_braodcasting_1",
"tests/test_tensor.py::MaskedScatterTests::test_masked_scatter_braodcasting_2",
"tests/test_tensor.py::MaskedFillTests::test_masked_fill_",
"tests/test_tensor.py::MaskedFillTests::test_masked_fill_broadcasting",
"tests/test_tensor.py::MaskedSelectTests::test_masked_select",
"tests/test_tensor.py::MaskedSelectTests::test_masked_select_broadcasting_1",
"tests/test_tensor.py::MaskedSelectTests::test_masked_select_broadcasting_2",
"tests/test_tensor.py::MaskedSelectTests::test_tensor_base_masked_select",
"tests/test_tensor.py::EqTests::test_eq_in_place_with_number",
"tests/test_tensor.py::EqTests::test_eq_in_place_with_tensor",
"tests/test_tensor.py::EqTests::test_eq_with_number",
"tests/test_tensor.py::EqTests::test_eq_with_tensor",
"tests/test_tensor.py::MmTests::test_mm_1d",
"tests/test_tensor.py::MmTests::test_mm_2d",
"tests/test_tensor.py::MmTests::test_mm_3d",
"tests/test_tensor.py::NewTensorTests::test_encrypted_error",
"tests/test_tensor.py::NewTensorTests::test_return_new_float_tensor",
"tests/test_tensor.py::NewTensorTests::test_return_new_int_tensor",
"tests/test_tensor.py::HalfTests::test_half_1",
"tests/test_tensor.py::HalfTests::test_half_2",
"tests/test_tensor.py::FmodTests::test_fmod_number",
"tests/test_tensor.py::FmodTests::test_fmod_tensor",
"tests/test_tensor.py::FmodTestsBis::test_fmod_number",
"tests/test_tensor.py::FmodTestsBis::test_fmod_tensor",
"tests/test_tensor.py::NumelTests::test_numel_2d",
"tests/test_tensor.py::NumelTests::test_numel_3d",
"tests/test_tensor.py::NumelTests::test_numel_encrypted",
"tests/test_tensor.py::NumelTests::test_numel_float",
"tests/test_tensor.py::NumelTests::test_numel_int",
"tests/test_tensor.py::NumelTests::test_numel_str",
"tests/test_tensor.py::NelementTests::test_nelement_2d",
"tests/test_tensor.py::NelementTests::test_nelement_3d",
"tests/test_tensor.py::NelementTests::test_nelement_encrypted",
"tests/test_tensor.py::NelementTests::test_nelement_float",
"tests/test_tensor.py::NelementTests::test_nelement_int",
"tests/test_tensor.py::NelementTests::test_nelement_str",
"tests/test_tensor.py::SizeTests::test_size_2d",
"tests/test_tensor.py::SizeTests::test_size_3d",
"tests/test_tensor.py::SizeTests::test_size_float",
"tests/test_tensor.py::SizeTests::test_size_int",
"tests/test_tensor.py::SizeTests::test_size_str",
"tests/test_tensor.py::LerpTests::test_lerp",
"tests/test_tensor.py::LerpTests::test_lerp_",
"tests/test_tensor.py::ModeTests::testMode_axis_None",
"tests/test_tensor.py::ModeTests::testMode_axis_col",
"tests/test_tensor.py::ModeTests::testMode_axis_row",
"tests/test_tensor.py::RenormTests::testRenorm",
"tests/test_tensor.py::RenormTests::testRenorm_",
"tests/test_tensor.py::StrideTests::test_stride",
"tests/test_tensor.py::SplitTests::test_split"
]
| []
| Apache License 2.0 | 1,840 | [
"syft/tensor.py",
"syft/__init__.py",
"syft/math.py"
]
| [
"syft/tensor.py",
"syft/__init__.py",
"syft/math.py"
]
|
minio__minio-py-591 | 41240393e679226942d2300f281602468b20c7b2 | 2017-11-02 22:09:58 | 41240393e679226942d2300f281602468b20c7b2 | poornas: @vadmeste, appveyor and travis are both failing.
vadmeste: Fixed @poornas | diff --git a/minio/api.py b/minio/api.py
index cb7e207..3c29b3a 100644
--- a/minio/api.py
+++ b/minio/api.py
@@ -1605,7 +1605,12 @@ class Minio(object):
is_non_empty_string(object_name)
is_non_empty_string(upload_id)
- data = xml_marshal_complete_multipart_upload(uploaded_parts)
+ # Order uploaded parts as required by S3 specification
+ ordered_parts = []
+ for part in sorted(uploaded_parts.keys()):
+ ordered_parts.append(uploaded_parts[part])
+
+ data = xml_marshal_complete_multipart_upload(ordered_parts)
sha256_hex = get_sha256_hexdigest(data)
md5_base64 = get_md5_base64digest(data)
diff --git a/minio/xml_marshal.py b/minio/xml_marshal.py
index e450d6b..9c62aa0 100644
--- a/minio/xml_marshal.py
+++ b/minio/xml_marshal.py
@@ -51,17 +51,17 @@ def xml_marshal_complete_multipart_upload(uploaded_parts):
"""
Marshal's complete multipart upload request based on *uploaded_parts*.
- :param uploaded_parts: List of all uploaded parts ordered in the
- way they were uploaded.
+ :param uploaded_parts: List of all uploaded parts, ordered by part number.
:return: Marshalled XML data.
"""
root = s3_xml.Element('CompleteMultipartUpload', {'xmlns': _S3_NAMESPACE})
- for part_number in uploaded_parts.keys():
+ for uploaded_part in uploaded_parts:
+ part_number = uploaded_part.part_number
part = s3_xml.SubElement(root, 'Part')
part_num = s3_xml.SubElement(part, 'PartNumber')
part_num.text = str(part_number)
etag = s3_xml.SubElement(part, 'ETag')
- etag.text = '"' + uploaded_parts[part_number].etag + '"'
+ etag.text = '"' + uploaded_part.etag + '"'
data = io.BytesIO()
s3_xml.ElementTree(root).write(data, encoding=None,
xml_declaration=False)
| Part order error with fput_object
When trying to upload a 200MB file to minio server with minio-py I'm getting an error.
minio-py version 2.2.5
minio server RELEASE.2017-09-29T19-16-56Z
```
File "/usr/local/lib/python3.6/dist-packages/minio/api.py", line 561, in fput_object
content_type, metadata)
File "/usr/local/lib/python3.6/dist-packages/minio/api.py", line 767, in put_object
data, length, metadata=metadata)
File "/usr/local/lib/python3.6/dist-packages/minio/api.py", line 1561, in _stream_put_object
metadata=metadata)
File "/usr/local/lib/python3.6/dist-packages/minio/api.py", line 1632, in _complete_multipart_upload
content_sha256=sha256_hex)
File "/usr/local/lib/python3.6/dist-packages/minio/api.py", line 1781, in _url_open
object_name).get_exception()
minio.error.InvalidPartOrder: InvalidPartOrder: message: The list of parts was not in ascending order.Parts list must specified in order by part number.
```
Maybe related to this commit?
https://github.com/minio/minio-py/pull/563 | minio/minio-py | diff --git a/tests/unit/generate_xml_test.py b/tests/unit/generate_xml_test.py
index 18706b9..bdd1dfd 100644
--- a/tests/unit/generate_xml_test.py
+++ b/tests/unit/generate_xml_test.py
@@ -33,17 +33,16 @@ class GenerateRequestTest(TestCase):
b'<Part><PartNumber>2</PartNumber><ETag>"0c78aef83f66abc1fa1e8477f296d394"</ETag>' \
b'</Part><Part><PartNumber>3</PartNumber><ETag>"acbd18db4cc2f85cedef654fccc4a4d8"' \
b'</ETag></Part></CompleteMultipartUpload>'
- etags = {}
- etags = {
- 1: UploadPart('bucket', 'object', 'upload_id', 1,
+ etags = [
+ UploadPart('bucket', 'object', 'upload_id', 1,
'a54357aff0632cce46d942af68356b38',
None, 0),
- 2: UploadPart('bucket', 'object', 'upload_id', 2,
+ UploadPart('bucket', 'object', 'upload_id', 2,
'0c78aef83f66abc1fa1e8477f296d394',
None, 0),
- 3: UploadPart('bucket', 'object', 'upload_id', 3,
+ UploadPart('bucket', 'object', 'upload_id', 3,
'acbd18db4cc2f85cedef654fccc4a4d8',
None, 0),
- }
+ ]
actual_string = xml_marshal_complete_multipart_upload(etags)
eq_(expected_string, actual_string)
| {
"commit_name": "merge_commit",
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 1,
"test_score": 0
},
"num_modified_files": 2
} | 2.2 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"nose",
"mock",
"pytest"
],
"pre_install": null,
"python": "3.5",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work
certifi==2021.5.30
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
-e git+https://github.com/minio/minio-py.git@41240393e679226942d2300f281602468b20c7b2#egg=minio
mock==5.2.0
more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work
nose==1.3.7
packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work
pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pytest==6.2.4
pytz==2025.2
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
urllib3==1.26.20
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
| name: minio-py
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=21.4.0=pyhd3eb1b0_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- importlib-metadata=4.8.1=py36h06a4308_0
- importlib_metadata=4.8.1=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- more-itertools=8.12.0=pyhd3eb1b0_0
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=21.3=pyhd3eb1b0_0
- pip=21.2.2=py36h06a4308_0
- pluggy=0.13.1=py36h06a4308_0
- py=1.11.0=pyhd3eb1b0_0
- pyparsing=3.0.4=pyhd3eb1b0_0
- pytest=6.2.4=py36h06a4308_2
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- toml=0.10.2=pyhd3eb1b0_0
- typing_extensions=4.1.1=pyh06a4308_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zipp=3.6.0=pyhd3eb1b0_0
- zlib=1.2.13=h5eee18b_1
- pip:
- mock==5.2.0
- nose==1.3.7
- pytz==2025.2
- urllib3==1.26.20
prefix: /opt/conda/envs/minio-py
| [
"tests/unit/generate_xml_test.py::GenerateRequestTest::test_generate_complete_multipart_upload"
]
| []
| [
"tests/unit/generate_xml_test.py::GenerateRequestTest::test_generate_bucket_constraint"
]
| []
| Apache License 2.0 | 1,841 | [
"minio/xml_marshal.py",
"minio/api.py"
]
| [
"minio/xml_marshal.py",
"minio/api.py"
]
|
JohannesBuchner__imagehash-64 | 43481e54c33983a4b14202214e718ec16692ccd7 | 2017-11-02 22:15:05 | 43481e54c33983a4b14202214e718ec16692ccd7 | coveralls:
[](https://coveralls.io/builds/14016469)
Coverage decreased (-7.1%) to 75.0% when pulling **c8dd2664ca2af3880395cec34c19cac2521e0e6b on djunzu:fix__binary_array_to_hex** into **43481e54c33983a4b14202214e718ec16692ccd7 on JohannesBuchner:master**.
coveralls:
[](https://coveralls.io/builds/14016469)
Coverage decreased (-7.1%) to 75.0% when pulling **c8dd2664ca2af3880395cec34c19cac2521e0e6b on djunzu:fix__binary_array_to_hex** into **43481e54c33983a4b14202214e718ec16692ccd7 on JohannesBuchner:master**.
coveralls:
[](https://coveralls.io/builds/14016804)
Coverage decreased (-7.1%) to 75.0% when pulling **0e96b2c0f9afdb9302b958f3a7219a2b116fe2dd on djunzu:fix__binary_array_to_hex** into **43481e54c33983a4b14202214e718ec16692ccd7 on JohannesBuchner:master**.
coveralls:
[](https://coveralls.io/builds/14016804)
Coverage decreased (-7.1%) to 75.0% when pulling **0e96b2c0f9afdb9302b958f3a7219a2b116fe2dd on djunzu:fix__binary_array_to_hex** into **43481e54c33983a4b14202214e718ec16692ccd7 on JohannesBuchner:master**.
JohannesBuchner: That looks very good already, thank you!
What does the .python-version file do?
Could you also include the problematic cases you pointed out in #51 with Lenna.png (hash_size=6, hash_size=2) as new unit tests? You can use the imagehash.png in imagehash/tests/data/, which is not copyrighted.
Could you also include one or two unit tests for the old implementation, just to make sure we don't break it in the future (coverage decreased, I guess because of this).
I had been flirting earlier on with the idea of using hypothesis for testing (e.g. generating new images of various sizes, making hash of some size, generating string, make a hash out of this again). Not necessary to do this here, but might be an idea.
Do you think it would make sense to include bitarray (mentioned in #51) as a dependency?
coveralls:
[](https://coveralls.io/builds/14017134)
Coverage decreased (-7.1%) to 75.0% when pulling **49ee130b1b8923a3929150c86b27b9f85cb0fd7c on djunzu:fix__binary_array_to_hex** into **43481e54c33983a4b14202214e718ec16692ccd7 on JohannesBuchner:master**.
JohannesBuchner: That looks very good already, thank you!
What does the .python-version file do?
Could you also include the problematic cases you pointed out in #51 with Lenna.png (hash_size=6, hash_size=2) as new unit tests? You can use the imagehash.png in imagehash/tests/data/, which is not copyrighted.
Could you also include one or two unit tests for the old implementation, just to make sure we don't break it in the future (coverage decreased, I guess because of this).
I had been flirting earlier on with the idea of using hypothesis for testing (e.g. generating new images of various sizes, making hash of some size, generating string, make a hash out of this again). Not necessary to do this here, but might be an idea.
Do you think it would make sense to include bitarray (mentioned in #51) as a dependency? Or binascii.hexlify/unhexlify? Or binhex.binhex/hexbin?
djunzu: > What does the .python-version file do?
I use [pyenv](https://github.com/pyenv/pyenv) to run different Python versions and it uses this file. It should not be committed, my fault. I will add it to .gitignore
> Could you also include the problematic cases you pointed out in #51 with Lenna.png (hash_size=6, hash_size=2) as new unit tests?
It is already there. (See my comments in "files changed".)
> Could you also include one or two unit tests for the old implementation, just to make sure we don't break it in the future (coverage decreased, I guess because of this).
OK.
> Do you think it would make sense to include bitarray (mentioned in #51) as a dependency? Or binascii.hexlify/unhexlify? Or binhex.binhex/hexbin?
My opinion on this is that the fewer dependencies the better. Everything already works without it.
| diff --git a/.gitignore b/.gitignore
index 93135d8..378b372 100644
--- a/.gitignore
+++ b/.gitignore
@@ -6,4 +6,5 @@ build
dist
ImageHash.egg-info/
.eggs
-.DS_Store
\ No newline at end of file
+.DS_Store
+.python-version
diff --git a/imagehash/__init__.py b/imagehash/__init__.py
index 0dc69b8..5da7efd 100644
--- a/imagehash/__init__.py
+++ b/imagehash/__init__.py
@@ -41,24 +41,14 @@ import os.path
__version__ = open(os.path.join(os.path.abspath(
os.path.dirname(__file__)), 'VERSION')).read().strip()
+
def _binary_array_to_hex(arr):
"""
internal function to make a hex string out of a binary array.
-
- binary array might be created from comparison - for example, in
- average hash, each pixel in the image is compared with the average pixel value.
- If the pixel's value is less than the average it gets a 0 and if it's more it gets a 1.
- Then we treat this like a string of bits and convert it to hexadecimal.
"""
- h = 0
- s = []
- for i, v in enumerate(arr.flatten()):
- if v:
- h += 2**(i % 8)
- if (i % 8) == 7:
- s.append(hex(h)[2:].rjust(2, '0'))
- h = 0
- return "".join(s)
+ bit_string = ''.join(str(b) for b in 1 * arr.flatten())
+ width = int(numpy.ceil(len(bit_string)/4))
+ return '{:0>{width}x}'.format(int(bit_string, 2), width=width)
class ImageHash(object):
@@ -96,10 +86,29 @@ class ImageHash(object):
return sum([2**(i % 8) for i, v in enumerate(self.hash.flatten()) if v])
-def hex_to_hash(hexstr, hash_size=8):
+def hex_to_hash(hexstr):
"""
Convert a stored hash (hex, as retrieved from str(Imagehash))
back to a Imagehash object.
+
+ Notes:
+ 1. This algorithm assumes all hashes are bidimensional arrays
+ with dimensions hash_size * hash_size.
+ 2. This algorithm does not work for hash_size < 2.
+ """
+ hash_size = int(numpy.sqrt(len(hexstr)*4))
+ binary_array = '{:0>{width}b}'.format(int(hexstr, 16), width = hash_size * hash_size)
+ bit_rows = [binary_array[i:i+hash_size] for i in range(0, len(binary_array), hash_size)]
+ hash_array = numpy.array([[bool(int(d)) for d in row] for row in bit_rows])
+ return ImageHash(hash_array)
+
+def old_hex_to_hash(hexstr, hash_size=8):
+ """
+ Convert a stored hash (hex, as retrieved from str(Imagehash))
+ back to a Imagehash object. This method should be used for
+ hashes generated by ImageHash up to version 3.7. For hashes
+ generated by newer versions of ImageHash, hex_to_hash should
+ be used instead.
"""
l = []
count = hash_size * (hash_size // 4)
@@ -123,8 +132,8 @@ def average_hash(image, hash_size=8):
@image must be a PIL instance.
"""
- if hash_size < 0:
- raise ValueError("Hash size must be positive")
+ if hash_size < 2:
+ raise ValueError("Hash size must be greater than or equal to 2")
# reduce size and complexity, then covert to grayscale
image = image.convert("L").resize((hash_size, hash_size), Image.ANTIALIAS)
@@ -147,8 +156,8 @@ def phash(image, hash_size=8, highfreq_factor=4):
@image must be a PIL instance.
"""
- if hash_size < 0:
- raise ValueError("Hash size must be positive")
+ if hash_size < 2:
+ raise ValueError("Hash size must be greater than or equal to 2")
import scipy.fftpack
img_size = hash_size * highfreq_factor
@@ -191,8 +200,8 @@ def dhash(image, hash_size=8):
@image must be a PIL instance.
"""
# resize(w, h), but numpy.array((h, w))
- if hash_size < 0:
- raise ValueError("Hash size must be positive")
+ if hash_size < 2:
+ raise ValueError("Hash size must be greater than or equal to 2")
image = image.convert("L").resize((hash_size + 1, hash_size), Image.ANTIALIAS)
pixels = numpy.asarray(image)
| _binary_array_to_hex gives wrong value
Correct me if I am wrong, but `_binary_array_to_hex` gives wrong values.
```python
Python 2.7.13 (default, Feb 16 2017, 19:11:00)
[GCC 5.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from PIL import Image
>>> import imagehash
>>> img = Image.open('sample_image.png')
>>> ph = imagehash.phash(img)
>>> bool_array = ph.hash.flatten()
>>> bool_array
array([ True, False, False, True, True, True, True, False, False,
False, True, True, True, True, False, False, True, True,
False, False, False, False, False, True, True, True, True,
True, False, False, False, False, True, True, True, True,
False, False, False, False, True, True, False, False, False,
False, True, True, True, True, True, False, False, True,
True, True, True, True, False, False, False, False, False, False], dtype=bool)
>>> bit_array = 1*bool_array
>>> bit_array
array([1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0,
1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0,
1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0])
>>> bit_string = ''.join(str(b) for b in bit_array)
>>> bit_string
'1001111000111100110000011111000011110000110000111110011111000000'
>>> int(bit_string, 2)
11402201597170935744L
>>> hex(int(bit_string, 2))
'0x9e3cc1f0f0c3e7c0L' # This is the expected hex value for the given bit array (phash)
>>> str(ph)
'793c830f0fc3e703' # and here is the actual value.
```
If I made no mistake, let me know and I will submit a PR.
| JohannesBuchner/imagehash | diff --git a/imagehash/tests/__init__.py b/imagehash/tests/__init__.py
index 13ab8f0..6f2f0a8 100644
--- a/imagehash/tests/__init__.py
+++ b/imagehash/tests/__init__.py
@@ -41,24 +41,27 @@ class TestImageHash(unittest.TestCase):
distance))
self.assertTrue(distance > 10, emsg)
- def check_hash_length(self, func, image, sizes):
+ def check_hash_length(self, func, image, sizes=range(2,21)):
for hash_size in sizes:
image_hash = func(image, hash_size=hash_size)
emsg = 'hash_size={} is not respected'.format(hash_size)
self.assertEqual(image_hash.hash.size, hash_size**2, emsg)
- def check_hash_stored(self, func, image):
- image_hash = func(image)
- other_hash = imagehash.hex_to_hash(str(image_hash))
- emsg = 'stringified hash {} != original hash {}'.format(other_hash,
- image_hash)
- self.assertEqual(image_hash, other_hash, emsg)
- distance = image_hash - other_hash
- emsg = ('unexpected hamming distance {}: original hash {} '
- '- stringified hash {}'.format(distance, image_hash,
- other_hash))
- self.assertEqual(distance, 0, emsg)
+ def check_hash_stored(self, func, image, sizes=range(2,21)):
+ for hash_size in sizes:
+ image_hash = func(image, hash_size)
+ other_hash = imagehash.hex_to_hash(str(image_hash))
+ emsg = 'stringified hash {} != original hash {}'.format(other_hash,
+ image_hash)
+ self.assertEqual(image_hash, other_hash, emsg)
+ distance = image_hash - other_hash
+ emsg = ('unexpected hamming distance {}: original hash {} '
+ '- stringified hash {}'.format(distance, image_hash,
+ other_hash))
+ self.assertEqual(distance, 0, emsg)
+
+ def check_hash_size(self, func, image, sizes=range(-1,2)):
+ for hash_size in sizes:
+ with self.assertRaises(ValueError):
+ func(image, hash_size)
- def check_hash_size(self, func, image, size):
- with self.assertRaises(ValueError):
- func(image, -1)
diff --git a/imagehash/tests/test_average_hash.py b/imagehash/tests/test_average_hash.py
index bf26323..5664e28 100644
--- a/imagehash/tests/test_average_hash.py
+++ b/imagehash/tests/test_average_hash.py
@@ -16,13 +16,13 @@ class Test(tests.TestImageHash):
self.check_hash_algorithm(self.func, self.image)
def test_average_hash_length(self):
- self.check_hash_length(self.func, self.image, [8, 20])
+ self.check_hash_length(self.func, self.image)
def test_average_hash_stored(self):
self.check_hash_stored(self.func, self.image)
def test_average_hash_size(self):
- self.check_hash_size(self.func, self.image, -1)
+ self.check_hash_size(self.func, self.image)
diff --git a/imagehash/tests/test_dhash.py b/imagehash/tests/test_dhash.py
index 60179db..60ea960 100644
--- a/imagehash/tests/test_dhash.py
+++ b/imagehash/tests/test_dhash.py
@@ -16,13 +16,13 @@ class Test(tests.TestImageHash):
self.check_hash_algorithm(self.func, self.image)
def test_dhash_length(self):
- self.check_hash_length(self.func, self.image, [8, 20])
+ self.check_hash_length(self.func, self.image)
def test_dhash_stored(self):
self.check_hash_stored(self.func, self.image)
def test_dhash_size(self):
- self.check_hash_size(self.func, self.image, -1)
+ self.check_hash_size(self.func, self.image)
if __name__ == '__main__':
unittest.main()
diff --git a/imagehash/tests/test_hex_conversions.py b/imagehash/tests/test_hex_conversions.py
new file mode 100644
index 0000000..1708f6f
--- /dev/null
+++ b/imagehash/tests/test_hex_conversions.py
@@ -0,0 +1,99 @@
+import unittest
+import numpy as np
+import imagehash
+
+
+# Each row is a test case where the first value is a bit sequence and
+# the second value is the expected hexadecimal representation for it.
+binary_to_hexadecimal_values = [
+ ['1', '1'],
+ ['11', '3'],
+ ['111', '7'],
+ ['1111', 'f'],
+ ['10000', '10'],
+ ['110000', '30'],
+ ['1110000', '70'],
+ ['11110000', 'f0'],
+ ['00001', '01'],
+ ['000011', '03'],
+ ['0000111', '07'],
+ ['00001111', '0f'],
+ ['10000001', '81'],
+ ['00000000000000001', '00001'],
+ ['000000000000000011', '00003'],
+ ['0000000000000000111', '00007'],
+ ['00000000000000001111', '0000f'],
+ ['11110000111100001111', 'f0f0f'],
+ ['00001111000011110000', '0f0f0'],
+ ['11110000000100100011010001010110011110001001101010111100110111101111', 'f0123456789abcdef'],
+ ['1001111000111100110000011111000011110000110000111110011111000000', '9e3cc1f0f0c3e7c0'],
+ ['1000111100001111000011110000111100001111000010110000101101111010', '8f0f0f0f0f0b0b7a'],
+]
+
+# Each row is a test case where the first value is a hexadecimal sequence
+# and the second value is the expected binary representation for it.
+hexadecimal_to_binary_values = [
+ ['1', '0001'],
+ ['2', '0010'],
+ ['3', '0011'],
+ ['a', '1010'],
+ ['f', '1111'],
+ ['101', '100000001'],
+ ['1b1', '110110001'],
+ ['0b1', '010110001'],
+ ['f0f0', '1111000011110000'],
+ ['0f0f', '0000111100001111'],
+ ['000c', '0000000000001100'],
+ ['100000d', '1000000000000000000001101'],
+ ['000000d', '0000000000000000000001101'],
+ ['000000001', '000000000000000000000000000000000001'],
+ ['800000001', '100000000000000000000000000000000001'],
+ ['0000000000001', '0000000000000000000000000000000000000000000000001'],
+ ['1000000000001', '1000000000000000000000000000000000000000000000001'],
+ ['0000000000000001', '0000000000000000000000000000000000000000000000000000000000000001'],
+ ['8000000000000001', '1000000000000000000000000000000000000000000000000000000000000001'],
+]
+
+# Each row is a test case where the first value is a hexadecimal
+# sequence and the second value is the expected bool array for it.
+hexadecimal_to_bool_array = [
+ ['9e3cc1f0f0c3e7c0', np.array([ [True, False, False, True, True, True, True, False],
+ [False, False, True, True, True, True, False, False],
+ [True, True, False, False, False, False, False, True],
+ [True, True, True, True, False, False, False, False],
+ [True, True, True, True, False, False, False, False],
+ [True, True, False, False, False, False, True, True],
+ [True, True, True, False, False, True, True, True],
+ [True, True, False, False, False, False, False, False]]) ],
+]
+
+class TestHexConversions(unittest.TestCase):
+
+ def setUp(self):
+ self.to_hex = imagehash._binary_array_to_hex
+ self.from_hex = imagehash.hex_to_hash
+
+ def test_binary_array_to_hex_input(self):
+ for case in hexadecimal_to_bool_array:
+ self.assertEqual(case[0], self.to_hex(case[1]))
+
+ def test_hex_to_hash_output(self):
+ for case in hexadecimal_to_bool_array:
+ self.assertTrue(np.array_equal(case[1], self.from_hex(case[0]).hash))
+
+ def test_conversion_to_hex(self):
+ for case in binary_to_hexadecimal_values:
+ expected = case[1]
+ bit_array = np.array([int(d) for d in case[0]])
+ result = self.to_hex(bit_array)
+ self.assertEqual(expected, result)
+
+ def test_conversion_from_hex(self):
+ for case in hexadecimal_to_binary_values:
+ expected = case[1]
+ result = ''.join(str(b) for b in 1 * self.from_hex(case[0]).hash.flatten())
+ self.assertEqual(expected, result)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/imagehash/tests/test_old_hex_conversions.py b/imagehash/tests/test_old_hex_conversions.py
new file mode 100644
index 0000000..42d82e8
--- /dev/null
+++ b/imagehash/tests/test_old_hex_conversions.py
@@ -0,0 +1,30 @@
+import unittest
+import numpy as np
+import imagehash
+
+
+# Each row is a test case where the first value is a hexadecimal
+# sequence and the second value is the expected bool array for it.
+old_hexadecimal_to_bool_array = [
+ ['ffeb89818193ffff', np.array([ [True, True, True, True, True, True, True, True],
+ [True, True, False, True, False, True, True, True],
+ [True, False, False, True, False, False, False, True],
+ [True, False, False, False, False, False, False, True],
+ [True, False, False, False, False, False, False, True],
+ [True, True, False, False, True, False, False, True],
+ [True, True, True, True, True, True, True, True],
+ [True, True, True, True, True, True, True, True]]) ],
+]
+
+class TestOldHexConversions(unittest.TestCase):
+
+ def setUp(self):
+ self.from_hex = imagehash.old_hex_to_hash
+
+ def test_hex_to_hash_output(self):
+ for case in old_hexadecimal_to_bool_array:
+ self.assertTrue(np.array_equal(case[1], self.from_hex(case[0]).hash))
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/imagehash/tests/test_phash.py b/imagehash/tests/test_phash.py
index 9061753..3fc5f13 100644
--- a/imagehash/tests/test_phash.py
+++ b/imagehash/tests/test_phash.py
@@ -16,13 +16,13 @@ class Test(tests.TestImageHash):
self.check_hash_algorithm(self.func, self.image)
def test_phash_length(self):
- self.check_hash_length(self.func, self.image, [8, 20])
+ self.check_hash_length(self.func, self.image)
def test_phash_stored(self):
self.check_hash_stored(self.func, self.image)
def test_phash_size(self):
- self.check_hash_size(self.func, self.image, -1)
+ self.check_hash_size(self.func, self.image)
if __name__ == '__main__':
unittest.main()
diff --git a/imagehash/tests/test_whash.py b/imagehash/tests/test_whash.py
index 3134ef9..0c518f1 100644
--- a/imagehash/tests/test_whash.py
+++ b/imagehash/tests/test_whash.py
@@ -5,6 +5,23 @@ import six
import unittest
import imagehash
+import imagehash.tests as tests
+
+
+class TestBasic(tests.TestImageHash):
+
+ def setUp(self):
+ self.image = self.get_data_image()
+ self.func = imagehash.whash
+
+ def test_whash(self):
+ self.check_hash_algorithm(self.func, self.image)
+
+ def test_whash_length(self):
+ self.check_hash_length(self.func, self.image, sizes=[2,4,8,16,32,64])
+
+ def test_whash_stored(self):
+ self.check_hash_stored(self.func, self.image, sizes=[2,4,8,16,32,64])
class Test(unittest.TestCase):
@@ -57,5 +74,6 @@ class Test(unittest.TestCase):
with six.assertRaisesRegex(self, AssertionError, emsg):
imagehash.whash(self.image, image_scale=image_scale+1)
+
if __name__ == '__main__':
unittest.main()
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_media",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 0,
"test_score": 1
},
"num_modified_files": 2
} | 3.1 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest"
],
"pre_install": null,
"python": "3.9",
"reqs_path": [
"conda-requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | exceptiongroup==1.2.2
-e git+https://github.com/JohannesBuchner/imagehash.git@43481e54c33983a4b14202214e718ec16692ccd7#egg=ImageHash
iniconfig==2.1.0
numpy==2.0.2
packaging==24.2
pillow==11.1.0
pluggy==1.5.0
pytest==8.3.5
PyWavelets==1.6.0
scipy==1.13.1
six==1.17.0
tomli==2.2.1
| name: imagehash
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- exceptiongroup==1.2.2
- iniconfig==2.1.0
- numpy==2.0.2
- packaging==24.2
- pillow==11.1.0
- pluggy==1.5.0
- pytest==8.3.5
- pywavelets==1.6.0
- scipy==1.13.1
- six==1.17.0
- tomli==2.2.1
prefix: /opt/conda/envs/imagehash
| [
"imagehash/tests/test_average_hash.py::Test::test_average_hash_size",
"imagehash/tests/test_dhash.py::Test::test_dhash_size",
"imagehash/tests/test_hex_conversions.py::TestHexConversions::test_binary_array_to_hex_input",
"imagehash/tests/test_hex_conversions.py::TestHexConversions::test_conversion_from_hex",
"imagehash/tests/test_hex_conversions.py::TestHexConversions::test_conversion_to_hex",
"imagehash/tests/test_hex_conversions.py::TestHexConversions::test_hex_to_hash_output",
"imagehash/tests/test_old_hex_conversions.py::TestOldHexConversions::test_hex_to_hash_output",
"imagehash/tests/test_phash.py::Test::test_phash_size"
]
| [
"imagehash/tests/test_average_hash.py::Test::test_average_hash",
"imagehash/tests/test_average_hash.py::Test::test_average_hash_length",
"imagehash/tests/test_average_hash.py::Test::test_average_hash_stored",
"imagehash/tests/test_dhash.py::Test::test_dhash",
"imagehash/tests/test_dhash.py::Test::test_dhash_length",
"imagehash/tests/test_dhash.py::Test::test_dhash_stored",
"imagehash/tests/test_phash.py::Test::test_phash",
"imagehash/tests/test_phash.py::Test::test_phash_length",
"imagehash/tests/test_phash.py::Test::test_phash_stored",
"imagehash/tests/test_whash.py::TestBasic::test_whash",
"imagehash/tests/test_whash.py::TestBasic::test_whash_length",
"imagehash/tests/test_whash.py::TestBasic::test_whash_stored",
"imagehash/tests/test_whash.py::Test::test_custom_hash_size_and_scale",
"imagehash/tests/test_whash.py::Test::test_hash_size_2power",
"imagehash/tests/test_whash.py::Test::test_hash_size_for_small_images"
]
| [
"imagehash/tests/test_whash.py::Test::test_hash_size_is_less_than_image_scale",
"imagehash/tests/test_whash.py::Test::test_hash_size_more_than_scale",
"imagehash/tests/test_whash.py::Test::test_hash_size_not_2power",
"imagehash/tests/test_whash.py::Test::test_image_scale_not_2power"
]
| []
| BSD 2-Clause "Simplified" License | 1,842 | [
".gitignore",
"imagehash/__init__.py"
]
| [
".gitignore",
"imagehash/__init__.py"
]
|
laughingman7743__BigQuery-DatasetManager-3 | 555792046ce2e7664229a54cce1f3a6bb516980a | 2017-11-03 05:20:26 | 1e930adbfb1714670ad04717401b36b59bf12558 | diff --git a/README.rst b/README.rst
index 3559c85..a4799df 100644
--- a/README.rst
+++ b/README.rst
@@ -44,7 +44,7 @@ The resource representation of the dataset is described in `YAML format`_.
description: null
default_table_expiration_ms: null
location: US
- access_grants:
+ access_entries:
- role: OWNER
entity_type: specialGroup
entity_id: projectOwners
@@ -62,48 +62,48 @@ The resource representation of the dataset is described in `YAML format`_.
See `the official documentation of BigQuery Datasets`_ for details of key names.
-+---------------+-------------+-----------+---------+----------------------------------------------------------+
-| Key name | Value | Description |
-+===============+=============+===========+=========+==========================================================+
-| name | str | The name of the dataset. |
-+---------------+-------------+-----------+---------+----------------------------------------------------------+
-| friendly_name | str | Title of the dataset. |
-+---------------+-------------+-----------+---------+----------------------------------------------------------+
-| description | str | Description of the dataset. |
-+---------------+-------------+-----------+---------+----------------------------------------------------------+
-| default_table_expiration_ms | int | Default expiration time for tables in the dataset. |
-+---------------+-------------+-----------+---------+----------------------------------------------------------+
-| location | str | Location in which the dataset is hosted. |
-+---------------+-------------+-----------+---------+----------------------------------------------------------+
-| access_grants | seq | Roles granted to entities for this dataset. |
-+---------------+-------------+-----------+---------+----------------------------------------------------------+
-| access_grants | role | str | Role granted to the entity. One of |
-| | | | |
-| | | | * ``OWNER`` |
-| | | | * ``WRITER`` |
-| | | | * ``READER`` |
-| | | | |
-| | | | May also be ``None`` if the ``entity_type`` is ``view``. |
-+ +-------------+-----------+---------+----------------------------------------------------------+
-| | entity_type | str | Type of entity being granted the role. One of |
-| | | | |
-| | | | * ``userByEmail`` |
-| | | | * ``groupByEmail`` |
-| | | | * ``domain`` |
-| | | | * ``specialGroup`` |
-| | | | * ``view`` |
-+ +-------------+-----------+---------+----------------------------------------------------------+
-| | entity_id | | str/map | ID of entity being granted the role. |
-+ + +-----------+---------+----------------------------------------------------------+
-| | | datasetId | str | The ID of the dataset containing this table. |
-| | | | | (Specified when ``entity_type`` is ``view``.) |
-+ + +-----------+---------+----------------------------------------------------------+
-| | | projectId | str | The ID of the project containing this table. |
-| | | | | (Specified when ``entity_type`` is ``view``.) |
-+ + +-----------+---------+----------------------------------------------------------+
-| | | tableId | str | The ID of the table. |
-| | | | | (Specified when ``entity_type`` is ``view``.) |
-+---------------+-------------+-----------+---------+----------------------------------------------------------+
++----------------+-------------+-----------+---------+----------------------------------------------------------+
+| Key name | Value | Description |
++================+=============+===========+=========+==========================================================+
+| name | str | The name of the dataset. |
++----------------+-------------+-----------+---------+----------------------------------------------------------+
+| friendly_name | str | Title of the dataset. |
++----------------+-------------+-----------+---------+----------------------------------------------------------+
+| description | str | Description of the dataset. |
++----------------+-------------+-----------+---------+----------------------------------------------------------+
+| default_table_expiration_ms | int | Default expiration time for tables in the dataset. |
++----------------+-------------+-----------+---------+----------------------------------------------------------+
+| location | str | Location in which the dataset is hosted. |
++----------------+-------------+-----------+---------+----------------------------------------------------------+
+| access_entries | seq | Represent grant of an access role to an entity. |
++----------------+-------------+-----------+---------+----------------------------------------------------------+
+| access_entries | role | str | Role granted to the entity. One of |
+| | | | |
+| | | | * ``OWNER`` |
+| | | | * ``WRITER`` |
+| | | | * ``READER`` |
+| | | | |
+| | | | May also be ``None`` if the ``entity_type`` is ``view``. |
++ +-------------+-----------+---------+----------------------------------------------------------+
+| | entity_type | str | Type of entity being granted the role. One of |
+| | | | |
+| | | | * ``userByEmail`` |
+| | | | * ``groupByEmail`` |
+| | | | * ``domain`` |
+| | | | * ``specialGroup`` |
+| | | | * ``view`` |
++ +-------------+-----------+---------+----------------------------------------------------------+
+| | entity_id | | str/map | ID of entity being granted the role. |
++ + +-----------+---------+----------------------------------------------------------+
+| | | datasetId | str | The ID of the dataset containing this table. |
+| | | | | (Specified when ``entity_type`` is ``view``.) |
++ + +-----------+---------+----------------------------------------------------------+
+| | | projectId | str | The ID of the project containing this table. |
+| | | | | (Specified when ``entity_type`` is ``view``.) |
++ + +-----------+---------+----------------------------------------------------------+
+| | | tableId | str | The ID of the table. |
+| | | | | (Specified when ``entity_type`` is ``view``.) |
++----------------+-------------+-----------+---------+----------------------------------------------------------+
.. _`the official documentation of BigQuery Datasets`: https://cloud.google.com/bigquery/docs/reference/rest/v2/datasets
diff --git a/bqdm/cli.py b/bqdm/cli.py
index 9f2a945..5405243 100755
--- a/bqdm/cli.py
+++ b/bqdm/cli.py
@@ -12,7 +12,7 @@ from past.types import unicode
import bqdm.message as msg
from bqdm import CONTEXT_SETTINGS
from bqdm.action import DatasetAction
-from bqdm.model import BigQueryDataset, BigQueryAccessGrant
+from bqdm.model import BigQueryDataset, BigQueryAccessEntry
from bqdm.util import list_local_datasets, ordered_dict_constructor, str_representer
@@ -24,7 +24,7 @@ _logger.setLevel(logging.INFO)
yaml.add_representer(str, str_representer)
yaml.add_representer(unicode, str_representer)
yaml.add_representer(BigQueryDataset, BigQueryDataset.represent)
-yaml.add_representer(BigQueryAccessGrant, BigQueryAccessGrant.represent)
+yaml.add_representer(BigQueryAccessEntry, BigQueryAccessEntry.represent)
yaml.add_constructor('tag:yaml.org,2002:map', ordered_dict_constructor)
diff --git a/bqdm/model.py b/bqdm/model.py
index c835def..c93266d 100644
--- a/bqdm/model.py
+++ b/bqdm/model.py
@@ -3,51 +3,51 @@ from __future__ import absolute_import
from collections import OrderedDict
from future.utils import iteritems
-from google.cloud.bigquery.dataset import Dataset, AccessGrant
+from google.cloud.bigquery.dataset import Dataset, AccessEntry
class BigQueryDataset(object):
def __init__(self, name, friendly_name, description,
- default_table_expiration_ms, location, access_grants):
+ default_table_expiration_ms, location, access_entries):
self.name = name
self.friendly_name = friendly_name
self.description = description
self.default_table_expiration_ms = default_table_expiration_ms
self.location = location
- self.access_grants = access_grants
+ self.access_entries = access_entries
@staticmethod
def from_dict(value):
- access_grants = value.get('access_grants', None)
- if access_grants:
- access_grants = [BigQueryAccessGrant.from_dict(a) for a in access_grants]
+ access_entries = value.get('access_entries', None)
+ if access_entries:
+ access_entries = [BigQueryAccessEntry.from_dict(a) for a in access_entries]
return BigQueryDataset(value.get('name', None),
value.get('friendly_name', None),
value.get('description', None),
value.get('default_table_expiration_ms', None),
value.get('location', None),
- access_grants)
+ access_entries)
@staticmethod
def from_dataset(value):
value.reload()
- access_grants = value.access_grants
- if access_grants:
- access_grants = [BigQueryAccessGrant.from_access_grant(a) for a in access_grants]
+ access_entries = value.access_entries
+ if access_entries:
+ access_entries = [BigQueryAccessEntry.from_access_entry(a) for a in access_entries]
return BigQueryDataset(value.name,
value.friendly_name,
value.description,
value.default_table_expiration_ms,
value.location,
- access_grants)
+ access_entries)
@staticmethod
def to_dataset(client, value):
- access_grants = value.access_grants
- if access_grants:
- access_grants = tuple([BigQueryAccessGrant.to_access_grant(a) for a in access_grants])
- dataset = Dataset(value.name, client, access_grants)
+ access_entries = value.access_entries
+ if access_entries:
+ access_entries = tuple([BigQueryAccessEntry.to_access_entry(a) for a in access_entries])
+ dataset = Dataset(value.name, client, access_entries)
dataset.friendly_name = value.friendly_name
dataset.description = value.description
dataset.default_table_expiration_ms = value.default_table_expiration_ms
@@ -64,7 +64,7 @@ class BigQueryDataset(object):
('description', value.description),
('default_table_expiration_ms', value.default_table_expiration_ms),
('location', value.location),
- ('access_grants', value.access_grants),
+ ('access_entries', value.access_entries),
)
)
@@ -74,8 +74,8 @@ class BigQueryDataset(object):
self.description,
self.default_table_expiration_ms,
self.location,
- frozenset(self.access_grants) if self.access_grants is not None
- else self.access_grants,)
+ frozenset(self.access_entries) if self.access_entries is not None
+ else self.access_entries,)
def __eq__(self, other):
if not isinstance(other, BigQueryDataset):
@@ -92,7 +92,7 @@ class BigQueryDataset(object):
return 'BigQueryDataset{0}'.format(self._key())
-class BigQueryAccessGrant(object):
+class BigQueryAccessEntry(object):
def __init__(self, role, entity_type, entity_id):
self.role = role
@@ -101,21 +101,21 @@ class BigQueryAccessGrant(object):
@staticmethod
def from_dict(value):
- return BigQueryAccessGrant(
+ return BigQueryAccessEntry(
value.get('role', None),
value.get('entity_type', None),
value.get('entity_id', None),)
@staticmethod
- def from_access_grant(value):
- return BigQueryAccessGrant(
+ def from_access_entry(value):
+ return BigQueryAccessEntry(
value.role,
value.entity_type,
value.entity_id,)
@staticmethod
- def to_access_grant(value):
- return AccessGrant(value.role, value.entity_type, value.entity_id)
+ def to_access_entry(value):
+ return AccessEntry(value.role, value.entity_type, value.entity_id)
@staticmethod
def represent(dumper, value):
@@ -135,7 +135,7 @@ class BigQueryAccessGrant(object):
if isinstance(self.entity_id, (dict, OrderedDict,)) else self.entity_id,)
def __eq__(self, other):
- if not isinstance(other, BigQueryAccessGrant):
+ if not isinstance(other, BigQueryAccessEntry):
return NotImplemented
return self._key() == other._key()
@@ -146,4 +146,4 @@ class BigQueryAccessGrant(object):
return hash(self._key())
def __repr__(self):
- return 'BigQueryAccessGrant{0}'.format(self._key())
+ return 'BigQueryAccessEntry{0}'.format(self._key())
diff --git a/setup.py b/setup.py
index 6808225..742814f 100755
--- a/setup.py
+++ b/setup.py
@@ -30,7 +30,7 @@ setup(
'future',
'click>=6.0',
'PyYAML>=3.12',
- 'google-cloud-bigquery>=0.27.0',
+ 'google-cloud-bigquery==0.28.0',
],
tests_require=[
'pytest',
| Migrating to Python Client Library v0.28
https://github.com/GoogleCloudPlatform/google-cloud-python/releases/tag/bigquery-0.28.0 | laughingman7743/BigQuery-DatasetManager | diff --git a/tests/__init__.py b/tests/__init__.py
index 688a9d5..95bd52a 100644
--- a/tests/__init__.py
+++ b/tests/__init__.py
@@ -2,10 +2,10 @@
import yaml
from bqdm.util import ordered_dict_constructor, str_representer
-from bqdm.model import BigQueryDataset, BigQueryAccessGrant
+from bqdm.model import BigQueryDataset, BigQueryAccessEntry
yaml.add_representer(str, str_representer)
yaml.add_representer(BigQueryDataset, BigQueryDataset.represent)
-yaml.add_representer(BigQueryAccessGrant, BigQueryAccessGrant.represent)
+yaml.add_representer(BigQueryAccessEntry, BigQueryAccessEntry.represent)
yaml.add_constructor('tag:yaml.org,2002:map', ordered_dict_constructor)
diff --git a/tests/test_action.py b/tests/test_action.py
index ad52c1b..16b2cd9 100644
--- a/tests/test_action.py
+++ b/tests/test_action.py
@@ -2,7 +2,7 @@
import unittest
from bqdm.action import DatasetAction
-from bqdm.model import BigQueryDataset, BigQueryAccessGrant
+from bqdm.model import BigQueryDataset, BigQueryAccessEntry
class TestAction(unittest.TestCase):
@@ -75,7 +75,7 @@ class TestAction(unittest.TestCase):
24 * 30 * 60 * 1000,
'US',
[
- BigQueryAccessGrant(
+ BigQueryAccessEntry(
None,
'view',
{
@@ -149,7 +149,7 @@ class TestAction(unittest.TestCase):
24 * 30 * 60 * 1000,
'US',
[
- BigQueryAccessGrant(
+ BigQueryAccessEntry(
None,
'view',
{
@@ -223,7 +223,7 @@ class TestAction(unittest.TestCase):
24 * 30 * 60 * 1000,
'US',
[
- BigQueryAccessGrant(
+ BigQueryAccessEntry(
None,
'view',
{
diff --git a/tests/test_model.py b/tests/test_model.py
index 653d826..032c42b 100644
--- a/tests/test_model.py
+++ b/tests/test_model.py
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
import unittest
-from bqdm.model import BigQueryDataset, BigQueryAccessGrant
+from bqdm.model import BigQueryDataset, BigQueryAccessEntry
class TestModel(unittest.TestCase):
@@ -44,18 +44,18 @@ class TestModel(unittest.TestCase):
self.assertNotEqual(dataset1, dataset4)
self.assertNotEqual(dataset3, dataset4)
- def test_eq_dataset_with_access_grant(self):
- access_grant1 = BigQueryAccessGrant(
+ def test_eq_dataset_with_access_entry(self):
+ access_entry1 = BigQueryAccessEntry(
'OWNER',
'specialGroup',
'projectOwners'
)
- access_grant2 = BigQueryAccessGrant(
+ access_entry2 = BigQueryAccessEntry(
'OWNER',
'specialGroup',
'projectOwners'
)
- access_grant3 = BigQueryAccessGrant(
+ access_entry3 = BigQueryAccessEntry(
None,
'view',
{
@@ -65,69 +65,69 @@ class TestModel(unittest.TestCase):
}
)
- dataset_with_access_grant1 = BigQueryDataset(
+ dataset_with_access_entry1 = BigQueryDataset(
'test',
'test_friendly_name',
'test_description',
24 * 30 * 60 * 1000,
'US',
- [access_grant1]
+ [access_entry1]
)
- dataset_with_access_grant2 = BigQueryDataset(
+ dataset_with_access_entry2 = BigQueryDataset(
'test',
'test_friendly_name',
'test_description',
24 * 30 * 60 * 1000,
'US',
- [access_grant2]
+ [access_entry2]
)
- dataset_with_access_grant3 = BigQueryDataset(
+ dataset_with_access_entry3 = BigQueryDataset(
'test',
'test_friendly_name',
'test_description',
24 * 30 * 60 * 1000,
'US',
- [access_grant3]
+ [access_entry3]
)
- dataset_with_access_grant4 = BigQueryDataset(
+ dataset_with_access_entry4 = BigQueryDataset(
'foo',
'bar',
'test_description',
24 * 30 * 60 * 1000,
'US',
- [access_grant1]
+ [access_entry1]
)
- dataset_with_access_grant5 = BigQueryDataset(
+ dataset_with_access_entry5 = BigQueryDataset(
'foo',
'bar',
'test_description',
24 * 30 * 60 * 1000,
'US',
- [access_grant1, access_grant3]
+ [access_entry1, access_entry3]
)
- dataset_with_access_grant6 = BigQueryDataset(
+ dataset_with_access_entry6 = BigQueryDataset(
'foo',
'bar',
'test_description',
24 * 30 * 60 * 1000,
'US',
- [access_grant3, access_grant1]
+ [access_entry3, access_entry1]
)
- dataset_with_access_grant7 = BigQueryDataset(
+ dataset_with_access_entry7 = BigQueryDataset(
'foo',
'bar',
'test_description',
24 * 30 * 60 * 1000,
'US',
- [access_grant1, access_grant2]
+ [access_entry1, access_entry2]
)
- self.assertEqual(dataset_with_access_grant1, dataset_with_access_grant2)
- self.assertNotEqual(dataset_with_access_grant1, dataset_with_access_grant3)
- self.assertNotEqual(dataset_with_access_grant1, dataset_with_access_grant4)
- self.assertNotEqual(dataset_with_access_grant3, dataset_with_access_grant4)
- self.assertEqual(dataset_with_access_grant5, dataset_with_access_grant6)
- self.assertEqual(dataset_with_access_grant4, dataset_with_access_grant7)
- self.assertNotEqual(dataset_with_access_grant6, dataset_with_access_grant7)
+ self.assertEqual(dataset_with_access_entry1, dataset_with_access_entry2)
+ self.assertNotEqual(dataset_with_access_entry1, dataset_with_access_entry3)
+ self.assertNotEqual(dataset_with_access_entry1, dataset_with_access_entry4)
+ self.assertNotEqual(dataset_with_access_entry3, dataset_with_access_entry4)
+ self.assertEqual(dataset_with_access_entry5, dataset_with_access_entry6)
+ self.assertEqual(dataset_with_access_entry4, dataset_with_access_entry7)
+ self.assertNotEqual(dataset_with_access_entry6, dataset_with_access_entry7)
def test_dataset_from_dict(self):
dataset = BigQueryDataset(
@@ -144,7 +144,7 @@ class TestModel(unittest.TestCase):
'description': 'test_description',
'default_table_expiration_ms': 24 * 30 * 60 * 1000,
'location': 'US',
- 'access_grants': None
+ 'access_entris': None
})
dataset_from_dict2 = BigQueryDataset.from_dict({
'name': 'test',
@@ -152,7 +152,7 @@ class TestModel(unittest.TestCase):
'description': 'test_description',
'default_table_expiration_ms': None,
'location': 'US',
- 'access_grants': None
+ 'access_entries': None
})
dataset_from_dict3 = BigQueryDataset.from_dict({
'name': 'foo',
@@ -160,19 +160,19 @@ class TestModel(unittest.TestCase):
'description': 'test_description',
'default_table_expiration_ms': None,
'location': 'US',
- 'access_grants': None
+ 'access_entries': None
})
self.assertEqual(dataset, dataset_from_dict1)
self.assertNotEqual(dataset, dataset_from_dict2)
self.assertNotEqual(dataset, dataset_from_dict3)
- def test_dataset_from_dict_with_access_grant(self):
- access_grant1 = BigQueryAccessGrant(
+ def test_dataset_from_dict_with_access_entry(self):
+ access_entry1 = BigQueryAccessEntry(
'OWNER',
'specialGroup',
'projectOwners'
)
- access_grant2 = BigQueryAccessGrant(
+ access_entry2 = BigQueryAccessEntry(
None,
'view',
{
@@ -182,45 +182,45 @@ class TestModel(unittest.TestCase):
}
)
- dataset_with_access_grant1 = BigQueryDataset(
+ dataset_with_access_entry1 = BigQueryDataset(
'test',
'test_friendly_name',
'test_description',
24 * 30 * 60 * 1000,
'US',
- [access_grant1]
+ [access_entry1]
)
- dataset_with_access_grant2 = BigQueryDataset(
+ dataset_with_access_entry2 = BigQueryDataset(
'test',
'test_friendly_name',
'test_description',
24 * 30 * 60 * 1000,
'US',
- [access_grant2]
+ [access_entry2]
)
- dataset_with_access_grant3 = BigQueryDataset(
+ dataset_with_access_entry3 = BigQueryDataset(
'test',
'test_friendly_name',
'test_description',
24 * 30 * 60 * 1000,
'US',
- [access_grant1, access_grant2]
+ [access_entry1, access_entry2]
)
- dataset_with_access_grant4 = BigQueryDataset(
+ dataset_with_access_entry4 = BigQueryDataset(
'test',
'test_friendly_name',
'test_description',
24 * 30 * 60 * 1000,
'US',
- [access_grant1, access_grant1]
+ [access_entry1, access_entry1]
)
- dataset_with_access_grant_from_dict1 = BigQueryDataset.from_dict({
+ dataset_with_access_entry_from_dict1 = BigQueryDataset.from_dict({
'name': 'test',
'friendly_name': 'test_friendly_name',
'description': 'test_description',
'default_table_expiration_ms': 24 * 30 * 60 * 1000,
'location': 'US',
- 'access_grants': [
+ 'access_entries': [
{
'role': 'OWNER',
'entity_type': 'specialGroup',
@@ -228,13 +228,13 @@ class TestModel(unittest.TestCase):
}
]
})
- dataset_with_access_grant_from_dict2 = BigQueryDataset.from_dict({
+ dataset_with_access_entry_from_dict2 = BigQueryDataset.from_dict({
'name': 'test',
'friendly_name': 'test_friendly_name',
'description': 'test_description',
'default_table_expiration_ms': 24 * 30 * 60 * 1000,
'location': 'US',
- 'access_grants': [
+ 'access_entries': [
{
'role': None,
'entity_type': 'view',
@@ -246,13 +246,13 @@ class TestModel(unittest.TestCase):
}
]
})
- dataset_with_access_grant_from_dict3 = BigQueryDataset.from_dict({
+ dataset_with_access_entry_from_dict3 = BigQueryDataset.from_dict({
'name': 'test',
'friendly_name': 'test_friendly_name',
'description': 'test_description',
'default_table_expiration_ms': 24 * 30 * 60 * 1000,
'location': 'US',
- 'access_grants': [
+ 'access_entries': [
{
'role': 'OWNER',
'entity_type': 'specialGroup',
@@ -269,13 +269,13 @@ class TestModel(unittest.TestCase):
}
]
})
- dataset_with_access_grant_from_dict4 = BigQueryDataset.from_dict({
+ dataset_with_access_entry_from_dict4 = BigQueryDataset.from_dict({
'name': 'test',
'friendly_name': 'test_friendly_name',
'description': 'test_description',
'default_table_expiration_ms': 24 * 30 * 60 * 1000,
'location': 'US',
- 'access_grants': [
+ 'access_entries': [
{
'role': 'OWNER',
'entity_type': 'specialGroup',
@@ -288,15 +288,15 @@ class TestModel(unittest.TestCase):
}
]
})
- self.assertEqual(dataset_with_access_grant1, dataset_with_access_grant_from_dict1)
- self.assertNotEqual(dataset_with_access_grant1, dataset_with_access_grant_from_dict2)
- self.assertNotEqual(dataset_with_access_grant1, dataset_with_access_grant_from_dict3)
- self.assertEqual(dataset_with_access_grant2, dataset_with_access_grant_from_dict2)
- self.assertNotEqual(dataset_with_access_grant2, dataset_with_access_grant_from_dict1)
- self.assertNotEqual(dataset_with_access_grant2, dataset_with_access_grant_from_dict3)
- self.assertEqual(dataset_with_access_grant3, dataset_with_access_grant_from_dict3)
- self.assertNotEqual(dataset_with_access_grant3, dataset_with_access_grant_from_dict1)
- self.assertNotEqual(dataset_with_access_grant3, dataset_with_access_grant_from_dict2)
- self.assertEqual(dataset_with_access_grant4, dataset_with_access_grant_from_dict4)
- self.assertEqual(dataset_with_access_grant1, dataset_with_access_grant_from_dict4)
- self.assertEqual(dataset_with_access_grant4, dataset_with_access_grant_from_dict1)
+ self.assertEqual(dataset_with_access_entry1, dataset_with_access_entry_from_dict1)
+ self.assertNotEqual(dataset_with_access_entry1, dataset_with_access_entry_from_dict2)
+ self.assertNotEqual(dataset_with_access_entry1, dataset_with_access_entry_from_dict3)
+ self.assertEqual(dataset_with_access_entry2, dataset_with_access_entry_from_dict2)
+ self.assertNotEqual(dataset_with_access_entry2, dataset_with_access_entry_from_dict1)
+ self.assertNotEqual(dataset_with_access_entry2, dataset_with_access_entry_from_dict3)
+ self.assertEqual(dataset_with_access_entry3, dataset_with_access_entry_from_dict3)
+ self.assertNotEqual(dataset_with_access_entry3, dataset_with_access_entry_from_dict1)
+ self.assertNotEqual(dataset_with_access_entry3, dataset_with_access_entry_from_dict2)
+ self.assertEqual(dataset_with_access_entry4, dataset_with_access_entry_from_dict4)
+ self.assertEqual(dataset_with_access_entry1, dataset_with_access_entry_from_dict4)
+ self.assertEqual(dataset_with_access_entry4, dataset_with_access_entry_from_dict1)
diff --git a/tests/test_util.py b/tests/test_util.py
index 618d9b0..c609b81 100644
--- a/tests/test_util.py
+++ b/tests/test_util.py
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
import unittest
-from bqdm.model import BigQueryDataset, BigQueryAccessGrant
+from bqdm.model import BigQueryDataset, BigQueryAccessEntry
from bqdm.util import dump_dataset
@@ -22,11 +22,11 @@ friendly_name: test_friendly_name
description: test_description
default_table_expiration_ms: 43200000
location: US
-access_grants: null
+access_entries: null
"""
self.assertEqual(actual_dump_data1, expected_dump_data1)
- access_grant2 = BigQueryAccessGrant(
+ access_entry2 = BigQueryAccessEntry(
'OWNER',
'specialGroup',
'projectOwners'
@@ -37,7 +37,7 @@ access_grants: null
'test_description',
24 * 30 * 60 * 1000,
'US',
- [access_grant2]
+ [access_entry2]
)
actual_dump_data2 = dump_dataset(dataset2)
expected_dump_data2 = """name: test2
@@ -45,14 +45,14 @@ friendly_name: test_friendly_name
description: test_description
default_table_expiration_ms: 43200000
location: US
-access_grants:
+access_entries:
- role: OWNER
entity_type: specialGroup
entity_id: projectOwners
"""
self.assertEqual(actual_dump_data2, expected_dump_data2)
- access_grant3 = BigQueryAccessGrant(
+ access_entry3 = BigQueryAccessEntry(
None,
'view',
{
@@ -67,7 +67,7 @@ access_grants:
'test_description',
24 * 30 * 60 * 1000,
'US',
- [access_grant3]
+ [access_entry3]
)
actual_dump_data3 = dump_dataset(dataset3)
expected_dump_data3 = """name: test3
@@ -75,7 +75,7 @@ friendly_name: test_friendly_name
description: test_description
default_table_expiration_ms: 43200000
location: US
-access_grants:
+access_entries:
- role: null
entity_type: view
entity_id:
@@ -91,7 +91,7 @@ access_grants:
'test_description',
24 * 30 * 60 * 1000,
'US',
- [access_grant2, access_grant3]
+ [access_entry2, access_entry3]
)
actual_dump_data4 = dump_dataset(dataset4)
expected_dump_data4 = """name: test4
@@ -99,7 +99,7 @@ friendly_name: test_friendly_name
description: test_description
default_table_expiration_ms: 43200000
location: US
-access_grants:
+access_entries:
- role: OWNER
entity_type: specialGroup
entity_id: projectOwners
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 3,
"test_score": 2
},
"num_modified_files": 4
} | 0.0 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-cov",
"pytest-flake8",
"pytest-catchlog"
],
"pre_install": null,
"python": "3.6",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs==22.2.0
-e git+https://github.com/laughingman7743/BigQuery-DatasetManager.git@555792046ce2e7664229a54cce1f3a6bb516980a#egg=BigQuery_DatasetManager
cachetools==4.2.4
certifi==2021.5.30
charset-normalizer==2.0.12
click==8.0.4
coverage==6.2
flake8==5.0.4
future==1.0.0
google-api-core==2.8.2
google-auth==2.22.0
google-cloud-bigquery==3.2.0
google-cloud-bigquery-storage==2.13.2
google-cloud-core==2.3.1
google-crc32c==1.3.0
google-resumable-media==2.3.3
googleapis-common-protos==1.56.3
grpcio==1.48.2
grpcio-status==1.48.2
idna==3.10
importlib-metadata==4.2.0
iniconfig==1.1.1
mccabe==0.7.0
numpy==1.19.5
packaging==21.3
pluggy==1.0.0
proto-plus==1.23.0
protobuf==3.19.6
py==1.11.0
pyarrow==6.0.1
pyasn1==0.5.1
pyasn1-modules==0.3.0
pycodestyle==2.9.1
pyflakes==2.5.0
pyparsing==3.1.4
pytest==7.0.1
pytest-catchlog==1.2.2
pytest-cov==4.0.0
pytest-flake8==1.1.1
python-dateutil==2.9.0.post0
PyYAML==6.0.1
requests==2.27.1
rsa==4.9
six==1.17.0
tomli==1.2.3
typing_extensions==4.1.1
urllib3==1.26.20
zipp==3.6.0
| name: BigQuery-DatasetManager
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- attrs==22.2.0
- cachetools==4.2.4
- charset-normalizer==2.0.12
- click==8.0.4
- coverage==6.2
- flake8==5.0.4
- future==1.0.0
- google-api-core==2.8.2
- google-auth==2.22.0
- google-cloud-bigquery==3.2.0
- google-cloud-bigquery-storage==2.13.2
- google-cloud-core==2.3.1
- google-crc32c==1.3.0
- google-resumable-media==2.3.3
- googleapis-common-protos==1.56.3
- grpcio==1.48.2
- grpcio-status==1.48.2
- idna==3.10
- importlib-metadata==4.2.0
- iniconfig==1.1.1
- mccabe==0.7.0
- numpy==1.19.5
- packaging==21.3
- pluggy==1.0.0
- proto-plus==1.23.0
- protobuf==3.19.6
- py==1.11.0
- pyarrow==6.0.1
- pyasn1==0.5.1
- pyasn1-modules==0.3.0
- pycodestyle==2.9.1
- pyflakes==2.5.0
- pyparsing==3.1.4
- pytest==7.0.1
- pytest-catchlog==1.2.2
- pytest-cov==4.0.0
- pytest-flake8==1.1.1
- python-dateutil==2.9.0.post0
- pyyaml==6.0.1
- requests==2.27.1
- rsa==4.9
- six==1.17.0
- tomli==1.2.3
- typing-extensions==4.1.1
- urllib3==1.26.20
- zipp==3.6.0
prefix: /opt/conda/envs/BigQuery-DatasetManager
| [
"tests/test_action.py::TestAction::test_get_add_datasets",
"tests/test_action.py::TestAction::test_get_change_datasets",
"tests/test_action.py::TestAction::test_get_destroy_datasets",
"tests/test_action.py::TestAction::test_get_intersection_datasets",
"tests/test_model.py::TestModel::test_dataset_from_dict",
"tests/test_model.py::TestModel::test_dataset_from_dict_with_access_entry",
"tests/test_model.py::TestModel::test_eq_dataset",
"tests/test_model.py::TestModel::test_eq_dataset_with_access_entry",
"tests/test_util.py::TestUtil::test_dump_dataset"
]
| []
| []
| []
| MIT License | 1,844 | [
"README.rst",
"bqdm/cli.py",
"setup.py",
"bqdm/model.py"
]
| [
"README.rst",
"bqdm/cli.py",
"setup.py",
"bqdm/model.py"
]
|
|
laughingman7743__BigQuery-DatasetManager-6 | 60e6ebe169f5e1be06b98cf878fee11702cf2ec7 | 2017-11-03 06:26:48 | 1e930adbfb1714670ad04717401b36b59bf12558 | codecov-io: # [Codecov](https://codecov.io/gh/laughingman7743/BigQuery-DatasetManager/pull/6?src=pr&el=h1) Report
> :exclamation: No coverage uploaded for pull request base (`master@60e6ebe`). [Click here to learn what that means](https://docs.codecov.io/docs/error-reference#section-missing-base-commit).
> The diff coverage is `40%`.
[](https://codecov.io/gh/laughingman7743/BigQuery-DatasetManager/pull/6?src=pr&el=tree)
```diff
@@ Coverage Diff @@
## master #6 +/- ##
=========================================
Coverage ? 31.14%
=========================================
Files ? 6
Lines ? 350
Branches ? 0
=========================================
Hits ? 109
Misses ? 241
Partials ? 0
```
| [Impacted Files](https://codecov.io/gh/laughingman7743/BigQuery-DatasetManager/pull/6?src=pr&el=tree) | Coverage Δ | |
|---|---|---|
| [bqdm/cli.py](https://codecov.io/gh/laughingman7743/BigQuery-DatasetManager/pull/6?src=pr&el=tree#diff-YnFkbS9jbGkucHk=) | `0% <0%> (ø)` | |
| [bqdm/model.py](https://codecov.io/gh/laughingman7743/BigQuery-DatasetManager/pull/6?src=pr&el=tree#diff-YnFkbS9tb2RlbC5weQ==) | `70.83% <44.44%> (ø)` | |
------
[Continue to review full report at Codecov](https://codecov.io/gh/laughingman7743/BigQuery-DatasetManager/pull/6?src=pr&el=continue).
> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
> `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
> Powered by [Codecov](https://codecov.io/gh/laughingman7743/BigQuery-DatasetManager/pull/6?src=pr&el=footer). Last update [60e6ebe...2f8d007](https://codecov.io/gh/laughingman7743/BigQuery-DatasetManager/pull/6?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).
| diff --git a/README.rst b/README.rst
index 3559c85..ef9cbc1 100644
--- a/README.rst
+++ b/README.rst
@@ -44,7 +44,7 @@ The resource representation of the dataset is described in `YAML format`_.
description: null
default_table_expiration_ms: null
location: US
- access_grants:
+ access_entries:
- role: OWNER
entity_type: specialGroup
entity_id: projectOwners
@@ -62,48 +62,48 @@ The resource representation of the dataset is described in `YAML format`_.
See `the official documentation of BigQuery Datasets`_ for details of key names.
-+---------------+-------------+-----------+---------+----------------------------------------------------------+
-| Key name | Value | Description |
-+===============+=============+===========+=========+==========================================================+
-| name | str | The name of the dataset. |
-+---------------+-------------+-----------+---------+----------------------------------------------------------+
-| friendly_name | str | Title of the dataset. |
-+---------------+-------------+-----------+---------+----------------------------------------------------------+
-| description | str | Description of the dataset. |
-+---------------+-------------+-----------+---------+----------------------------------------------------------+
-| default_table_expiration_ms | int | Default expiration time for tables in the dataset. |
-+---------------+-------------+-----------+---------+----------------------------------------------------------+
-| location | str | Location in which the dataset is hosted. |
-+---------------+-------------+-----------+---------+----------------------------------------------------------+
-| access_grants | seq | Roles granted to entities for this dataset. |
-+---------------+-------------+-----------+---------+----------------------------------------------------------+
-| access_grants | role | str | Role granted to the entity. One of |
-| | | | |
-| | | | * ``OWNER`` |
-| | | | * ``WRITER`` |
-| | | | * ``READER`` |
-| | | | |
-| | | | May also be ``None`` if the ``entity_type`` is ``view``. |
-+ +-------------+-----------+---------+----------------------------------------------------------+
-| | entity_type | str | Type of entity being granted the role. One of |
-| | | | |
-| | | | * ``userByEmail`` |
-| | | | * ``groupByEmail`` |
-| | | | * ``domain`` |
-| | | | * ``specialGroup`` |
-| | | | * ``view`` |
-+ +-------------+-----------+---------+----------------------------------------------------------+
-| | entity_id | | str/map | ID of entity being granted the role. |
-+ + +-----------+---------+----------------------------------------------------------+
-| | | datasetId | str | The ID of the dataset containing this table. |
-| | | | | (Specified when ``entity_type`` is ``view``.) |
-+ + +-----------+---------+----------------------------------------------------------+
-| | | projectId | str | The ID of the project containing this table. |
-| | | | | (Specified when ``entity_type`` is ``view``.) |
-+ + +-----------+---------+----------------------------------------------------------+
-| | | tableId | str | The ID of the table. |
-| | | | | (Specified when ``entity_type`` is ``view``.) |
-+---------------+-------------+-----------+---------+----------------------------------------------------------+
++----------------+-------------+-----------+---------+----------------------------------------------------------+
+| Key name | Value | Description |
++================+=============+===========+=========+==========================================================+
+| dataset_id | str | Dataset ID. |
++----------------+-------------+-----------+---------+----------------------------------------------------------+
+| friendly_name | str | Title of the dataset. |
++----------------+-------------+-----------+---------+----------------------------------------------------------+
+| description | str | Description of the dataset. |
++----------------+-------------+-----------+---------+----------------------------------------------------------+
+| default_table_expiration_ms | int | Default expiration time for tables in the dataset. |
++----------------+-------------+-----------+---------+----------------------------------------------------------+
+| location | str | Location in which the dataset is hosted. |
++----------------+-------------+-----------+---------+----------------------------------------------------------+
+| access_entries | seq | Represent grant of an access role to an entity. |
++----------------+-------------+-----------+---------+----------------------------------------------------------+
+| access_entries | role | str | Role granted to the entity. One of |
+| | | | |
+| | | | * ``OWNER`` |
+| | | | * ``WRITER`` |
+| | | | * ``READER`` |
+| | | | |
+| | | | May also be ``None`` if the ``entity_type`` is ``view``. |
++ +-------------+-----------+---------+----------------------------------------------------------+
+| | entity_type | str | Type of entity being granted the role. One of |
+| | | | |
+| | | | * ``userByEmail`` |
+| | | | * ``groupByEmail`` |
+| | | | * ``domain`` |
+| | | | * ``specialGroup`` |
+| | | | * ``view`` |
++ +-------------+-----------+---------+----------------------------------------------------------+
+| | entity_id | | str/map | ID of entity being granted the role. |
++ + +-----------+---------+----------------------------------------------------------+
+| | | datasetId | str | The ID of the dataset containing this table. |
+| | | | | (Specified when ``entity_type`` is ``view``.) |
++ + +-----------+---------+----------------------------------------------------------+
+| | | projectId | str | The ID of the project containing this table. |
+| | | | | (Specified when ``entity_type`` is ``view``.) |
++ + +-----------+---------+----------------------------------------------------------+
+| | | tableId | str | The ID of the table. |
+| | | | | (Specified when ``entity_type`` is ``view``.) |
++----------------+-------------+-----------+---------+----------------------------------------------------------+
.. _`the official documentation of BigQuery Datasets`: https://cloud.google.com/bigquery/docs/reference/rest/v2/datasets
diff --git a/bqdm/action.py b/bqdm/action.py
index 5f3b686..0aa750a 100644
--- a/bqdm/action.py
+++ b/bqdm/action.py
@@ -25,8 +25,8 @@ class DatasetAction(object):
@staticmethod
def get_add_datasets(source, target):
- names = set(t.name for t in target) - set(s.name for s in source)
- results = [t for t in target if t.name in names]
+ dataset_ids = set(t.dataset_id for t in target) - set(s.dataset_id for s in source)
+ results = [t for t in target if t.dataset_id in dataset_ids]
return len(results), tuple(results)
@staticmethod
@@ -37,21 +37,21 @@ class DatasetAction(object):
@staticmethod
def get_destroy_datasets(source, target):
- names = set(s.name for s in source) - set(t.name for t in target)
- results = [s for s in source if s.name in names]
+ dataset_ids = set(s.dataset_id for s in source) - set(t.dataset_id for t in target)
+ results = [s for s in source if s.dataset_id in dataset_ids]
return len(results), tuple(results)
@staticmethod
def get_intersection_datasets(source, target):
- names = set(s.name for s in source) & set(t.name for t in target)
- results = [s for s in source if s.name in names]
+ dataset_ids = set(s.dataset_id for s in source) & set(t.dataset_id for t in target)
+ results = [s for s in source if s.dataset_id in dataset_ids]
return len(results), tuple(results)
def list_datasets(self):
datasets = []
for dataset in self.client.list_datasets():
click.echo('Load: ' + dataset.path)
- datasets.append(BigQueryDataset.from_dataset(dataset))
+ datasets.append(BigQueryDataset.from_dataset(self.client, dataset.dataset_id))
click.echo('------------------------------------------------------------------------')
click.echo()
return datasets
@@ -60,13 +60,11 @@ class DatasetAction(object):
if not os.path.exists(output_dir):
os.makedirs(output_dir)
- datasets = self.client.list_datasets()
- for dataset in datasets:
- dataset.reload()
+ for dataset in self.client.list_datasets():
click.echo('Export: {0}'.format(dataset.path))
- data = dump_dataset(BigQueryDataset.from_dataset(dataset))
+ data = dump_dataset(BigQueryDataset.from_dataset(self.client, dataset.dataset_id))
_logger.debug(data)
- with codecs.open(os.path.join(output_dir, '{0}.yml'.format(dataset.name)),
+ with codecs.open(os.path.join(output_dir, '{0}.yml'.format(dataset.dataset_id)),
'wb', 'utf-8') as f:
f.write(data)
@@ -74,7 +72,7 @@ class DatasetAction(object):
count, datasets = self.get_add_datasets(source, target)
_logger.debug('Add datasets: {0}'.format(datasets))
for dataset in datasets:
- click.secho(' + {0}'.format(dataset.name), fg='green')
+ click.secho(' + {0}'.format(dataset.dataset_id), fg='green')
for line in dump_dataset(dataset).splitlines():
click.echo(' {0}'.format(line))
click.echo()
@@ -96,8 +94,8 @@ class DatasetAction(object):
count, datasets = self.get_change_datasets(source, target)
_logger.debug('Change datasets: {0}'.format(datasets))
for dataset in datasets:
- click.secho(' ~ {0}'.format(dataset.name), fg='yellow')
- old_dataset = next((o for o in source if o.name == dataset.name), None)
+ click.secho(' ~ {0}'.format(dataset.dataset_id), fg='yellow')
+ old_dataset = next((o for o in source if o.dataset_id == dataset.dataset_id), None)
for d in ndiff(old_dataset, dataset):
click.echo(' {0}'.format(d))
click.echo()
@@ -108,7 +106,7 @@ class DatasetAction(object):
_logger.debug('Change datasets: {0}'.format(datasets))
for dataset in datasets:
converted = BigQueryDataset.to_dataset(self.client, dataset)
- old_dataset = next((o for o in source if o.name == dataset.name), None)
+ old_dataset = next((o for o in source if o.dataset_id == dataset.dataset_id), None)
diff = ndiff(old_dataset, dataset)
click.secho(' Changing... {0}'.format(converted.path), fg='yellow')
for d in diff:
@@ -121,7 +119,7 @@ class DatasetAction(object):
count, datasets = self.get_destroy_datasets(source, target)
_logger.debug('Destroy datasets: {0}'.format(datasets))
for dataset in datasets:
- click.secho(' - {0}'.format(dataset.name), fg='red')
+ click.secho(' - {0}'.format(dataset.dataset_id), fg='red')
click.echo()
return count
@@ -139,7 +137,7 @@ class DatasetAction(object):
count, datasets = self.get_intersection_datasets(target, source)
_logger.debug('Destroy datasets: {0}'.format(datasets))
for dataset in datasets:
- click.secho(' - {0}'.format(dataset.name), fg='red')
+ click.secho(' - {0}'.format(dataset.dataset_id), fg='red')
click.echo()
return count
@@ -148,7 +146,7 @@ class DatasetAction(object):
_logger.debug('Destroy datasets: {0}'.format(datasets))
for dataset in datasets:
converted = BigQueryDataset.to_dataset(self.client, dataset)
- click.secho(' Destroying... {0}'.format(dataset.name), fg='red')
+ click.secho(' Destroying... {0}'.format(dataset.dataset_id), fg='red')
converted.delete()
click.echo()
return count
diff --git a/bqdm/cli.py b/bqdm/cli.py
index 9f2a945..5405243 100755
--- a/bqdm/cli.py
+++ b/bqdm/cli.py
@@ -12,7 +12,7 @@ from past.types import unicode
import bqdm.message as msg
from bqdm import CONTEXT_SETTINGS
from bqdm.action import DatasetAction
-from bqdm.model import BigQueryDataset, BigQueryAccessGrant
+from bqdm.model import BigQueryDataset, BigQueryAccessEntry
from bqdm.util import list_local_datasets, ordered_dict_constructor, str_representer
@@ -24,7 +24,7 @@ _logger.setLevel(logging.INFO)
yaml.add_representer(str, str_representer)
yaml.add_representer(unicode, str_representer)
yaml.add_representer(BigQueryDataset, BigQueryDataset.represent)
-yaml.add_representer(BigQueryAccessGrant, BigQueryAccessGrant.represent)
+yaml.add_representer(BigQueryAccessEntry, BigQueryAccessEntry.represent)
yaml.add_constructor('tag:yaml.org,2002:map', ordered_dict_constructor)
diff --git a/bqdm/model.py b/bqdm/model.py
index c835def..0bb4351 100644
--- a/bqdm/model.py
+++ b/bqdm/model.py
@@ -3,55 +3,58 @@ from __future__ import absolute_import
from collections import OrderedDict
from future.utils import iteritems
-from google.cloud.bigquery.dataset import Dataset, AccessGrant
+from google.cloud.bigquery.dataset import AccessEntry
class BigQueryDataset(object):
- def __init__(self, name, friendly_name, description,
- default_table_expiration_ms, location, access_grants):
- self.name = name
+ def __init__(self, dataset_id, friendly_name, description,
+ default_table_expiration_ms, location, access_entries):
+ self.dataset_id = dataset_id
self.friendly_name = friendly_name
self.description = description
self.default_table_expiration_ms = default_table_expiration_ms
self.location = location
- self.access_grants = access_grants
+ self.access_entries = access_entries
@staticmethod
def from_dict(value):
- access_grants = value.get('access_grants', None)
- if access_grants:
- access_grants = [BigQueryAccessGrant.from_dict(a) for a in access_grants]
- return BigQueryDataset(value.get('name', None),
+ access_entries = value.get('access_entries', None)
+ if access_entries:
+ access_entries = [BigQueryAccessEntry.from_dict(a) for a in access_entries]
+ return BigQueryDataset(value.get('dataset_id', None),
value.get('friendly_name', None),
value.get('description', None),
value.get('default_table_expiration_ms', None),
value.get('location', None),
- access_grants)
+ access_entries)
@staticmethod
- def from_dataset(value):
- value.reload()
- access_grants = value.access_grants
- if access_grants:
- access_grants = [BigQueryAccessGrant.from_access_grant(a) for a in access_grants]
- return BigQueryDataset(value.name,
- value.friendly_name,
- value.description,
- value.default_table_expiration_ms,
- value.location,
- access_grants)
+ def from_dataset(client, dataset_id):
+ dataset_ref = client.dataset(dataset_id)
+ dataset = client.get_dataset(dataset_ref)
+ access_entries = dataset.access_entries
+ if access_entries:
+ access_entries = [BigQueryAccessEntry.from_access_entry(a) for a in access_entries]
+ return BigQueryDataset(dataset.dataset_id,
+ dataset.friendly_name,
+ dataset.description,
+ dataset.default_table_expiration_ms,
+ dataset.location,
+ access_entries)
@staticmethod
def to_dataset(client, value):
- access_grants = value.access_grants
- if access_grants:
- access_grants = tuple([BigQueryAccessGrant.to_access_grant(a) for a in access_grants])
- dataset = Dataset(value.name, client, access_grants)
+ access_entries = value.access_entries
+ if access_entries:
+ access_entries = tuple([BigQueryAccessEntry.to_access_entry(a) for a in access_entries])
+ dataset_ref = client.dataset(value.dataset_id)
+ dataset = client.get_dataset(dataset_ref)
dataset.friendly_name = value.friendly_name
dataset.description = value.description
dataset.default_table_expiration_ms = value.default_table_expiration_ms
dataset.location = value.location
+ dataset.access_entries = access_entries
return dataset
@staticmethod
@@ -59,23 +62,23 @@ class BigQueryDataset(object):
return dumper.represent_mapping(
'tag:yaml.org,2002:map',
(
- ('name', value.name),
+ ('dataset_id', value.dataset_id),
('friendly_name', value.friendly_name),
('description', value.description),
('default_table_expiration_ms', value.default_table_expiration_ms),
('location', value.location),
- ('access_grants', value.access_grants),
+ ('access_entries', value.access_entries),
)
)
def _key(self):
- return (self.name,
+ return (self.dataset_id,
self.friendly_name,
self.description,
self.default_table_expiration_ms,
self.location,
- frozenset(self.access_grants) if self.access_grants is not None
- else self.access_grants,)
+ frozenset(self.access_entries) if self.access_entries is not None
+ else self.access_entries,)
def __eq__(self, other):
if not isinstance(other, BigQueryDataset):
@@ -92,7 +95,7 @@ class BigQueryDataset(object):
return 'BigQueryDataset{0}'.format(self._key())
-class BigQueryAccessGrant(object):
+class BigQueryAccessEntry(object):
def __init__(self, role, entity_type, entity_id):
self.role = role
@@ -101,21 +104,21 @@ class BigQueryAccessGrant(object):
@staticmethod
def from_dict(value):
- return BigQueryAccessGrant(
+ return BigQueryAccessEntry(
value.get('role', None),
value.get('entity_type', None),
value.get('entity_id', None),)
@staticmethod
- def from_access_grant(value):
- return BigQueryAccessGrant(
+ def from_access_entry(value):
+ return BigQueryAccessEntry(
value.role,
value.entity_type,
value.entity_id,)
@staticmethod
- def to_access_grant(value):
- return AccessGrant(value.role, value.entity_type, value.entity_id)
+ def to_access_entry(value):
+ return AccessEntry(value.role, value.entity_type, value.entity_id)
@staticmethod
def represent(dumper, value):
@@ -135,7 +138,7 @@ class BigQueryAccessGrant(object):
if isinstance(self.entity_id, (dict, OrderedDict,)) else self.entity_id,)
def __eq__(self, other):
- if not isinstance(other, BigQueryAccessGrant):
+ if not isinstance(other, BigQueryAccessEntry):
return NotImplemented
return self._key() == other._key()
@@ -146,4 +149,4 @@ class BigQueryAccessGrant(object):
return hash(self._key())
def __repr__(self):
- return 'BigQueryAccessGrant{0}'.format(self._key())
+ return 'BigQueryAccessEntry{0}'.format(self._key())
diff --git a/setup.py b/setup.py
index 6808225..742814f 100755
--- a/setup.py
+++ b/setup.py
@@ -30,7 +30,7 @@ setup(
'future',
'click>=6.0',
'PyYAML>=3.12',
- 'google-cloud-bigquery>=0.27.0',
+ 'google-cloud-bigquery==0.28.0',
],
tests_require=[
'pytest',
| Migrating to Python Client Library v0.28
https://github.com/GoogleCloudPlatform/google-cloud-python/releases/tag/bigquery-0.28.0 | laughingman7743/BigQuery-DatasetManager | diff --git a/tests/__init__.py b/tests/__init__.py
index 688a9d5..95bd52a 100644
--- a/tests/__init__.py
+++ b/tests/__init__.py
@@ -2,10 +2,10 @@
import yaml
from bqdm.util import ordered_dict_constructor, str_representer
-from bqdm.model import BigQueryDataset, BigQueryAccessGrant
+from bqdm.model import BigQueryDataset, BigQueryAccessEntry
yaml.add_representer(str, str_representer)
yaml.add_representer(BigQueryDataset, BigQueryDataset.represent)
-yaml.add_representer(BigQueryAccessGrant, BigQueryAccessGrant.represent)
+yaml.add_representer(BigQueryAccessEntry, BigQueryAccessEntry.represent)
yaml.add_constructor('tag:yaml.org,2002:map', ordered_dict_constructor)
diff --git a/tests/test_action.py b/tests/test_action.py
index ad52c1b..16b2cd9 100644
--- a/tests/test_action.py
+++ b/tests/test_action.py
@@ -2,7 +2,7 @@
import unittest
from bqdm.action import DatasetAction
-from bqdm.model import BigQueryDataset, BigQueryAccessGrant
+from bqdm.model import BigQueryDataset, BigQueryAccessEntry
class TestAction(unittest.TestCase):
@@ -75,7 +75,7 @@ class TestAction(unittest.TestCase):
24 * 30 * 60 * 1000,
'US',
[
- BigQueryAccessGrant(
+ BigQueryAccessEntry(
None,
'view',
{
@@ -149,7 +149,7 @@ class TestAction(unittest.TestCase):
24 * 30 * 60 * 1000,
'US',
[
- BigQueryAccessGrant(
+ BigQueryAccessEntry(
None,
'view',
{
@@ -223,7 +223,7 @@ class TestAction(unittest.TestCase):
24 * 30 * 60 * 1000,
'US',
[
- BigQueryAccessGrant(
+ BigQueryAccessEntry(
None,
'view',
{
diff --git a/tests/test_model.py b/tests/test_model.py
index 653d826..16dbe16 100644
--- a/tests/test_model.py
+++ b/tests/test_model.py
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
import unittest
-from bqdm.model import BigQueryDataset, BigQueryAccessGrant
+from bqdm.model import BigQueryDataset, BigQueryAccessEntry
class TestModel(unittest.TestCase):
@@ -44,18 +44,18 @@ class TestModel(unittest.TestCase):
self.assertNotEqual(dataset1, dataset4)
self.assertNotEqual(dataset3, dataset4)
- def test_eq_dataset_with_access_grant(self):
- access_grant1 = BigQueryAccessGrant(
+ def test_eq_dataset_with_access_entry(self):
+ access_entry1 = BigQueryAccessEntry(
'OWNER',
'specialGroup',
'projectOwners'
)
- access_grant2 = BigQueryAccessGrant(
+ access_entry2 = BigQueryAccessEntry(
'OWNER',
'specialGroup',
'projectOwners'
)
- access_grant3 = BigQueryAccessGrant(
+ access_entry3 = BigQueryAccessEntry(
None,
'view',
{
@@ -65,69 +65,69 @@ class TestModel(unittest.TestCase):
}
)
- dataset_with_access_grant1 = BigQueryDataset(
+ dataset_with_access_entry1 = BigQueryDataset(
'test',
'test_friendly_name',
'test_description',
24 * 30 * 60 * 1000,
'US',
- [access_grant1]
+ [access_entry1]
)
- dataset_with_access_grant2 = BigQueryDataset(
+ dataset_with_access_entry2 = BigQueryDataset(
'test',
'test_friendly_name',
'test_description',
24 * 30 * 60 * 1000,
'US',
- [access_grant2]
+ [access_entry2]
)
- dataset_with_access_grant3 = BigQueryDataset(
+ dataset_with_access_entry3 = BigQueryDataset(
'test',
'test_friendly_name',
'test_description',
24 * 30 * 60 * 1000,
'US',
- [access_grant3]
+ [access_entry3]
)
- dataset_with_access_grant4 = BigQueryDataset(
+ dataset_with_access_entry4 = BigQueryDataset(
'foo',
'bar',
'test_description',
24 * 30 * 60 * 1000,
'US',
- [access_grant1]
+ [access_entry1]
)
- dataset_with_access_grant5 = BigQueryDataset(
+ dataset_with_access_entry5 = BigQueryDataset(
'foo',
'bar',
'test_description',
24 * 30 * 60 * 1000,
'US',
- [access_grant1, access_grant3]
+ [access_entry1, access_entry3]
)
- dataset_with_access_grant6 = BigQueryDataset(
+ dataset_with_access_entry6 = BigQueryDataset(
'foo',
'bar',
'test_description',
24 * 30 * 60 * 1000,
'US',
- [access_grant3, access_grant1]
+ [access_entry3, access_entry1]
)
- dataset_with_access_grant7 = BigQueryDataset(
+ dataset_with_access_entry7 = BigQueryDataset(
'foo',
'bar',
'test_description',
24 * 30 * 60 * 1000,
'US',
- [access_grant1, access_grant2]
+ [access_entry1, access_entry2]
)
- self.assertEqual(dataset_with_access_grant1, dataset_with_access_grant2)
- self.assertNotEqual(dataset_with_access_grant1, dataset_with_access_grant3)
- self.assertNotEqual(dataset_with_access_grant1, dataset_with_access_grant4)
- self.assertNotEqual(dataset_with_access_grant3, dataset_with_access_grant4)
- self.assertEqual(dataset_with_access_grant5, dataset_with_access_grant6)
- self.assertEqual(dataset_with_access_grant4, dataset_with_access_grant7)
- self.assertNotEqual(dataset_with_access_grant6, dataset_with_access_grant7)
+ self.assertEqual(dataset_with_access_entry1, dataset_with_access_entry2)
+ self.assertNotEqual(dataset_with_access_entry1, dataset_with_access_entry3)
+ self.assertNotEqual(dataset_with_access_entry1, dataset_with_access_entry4)
+ self.assertNotEqual(dataset_with_access_entry3, dataset_with_access_entry4)
+ self.assertEqual(dataset_with_access_entry5, dataset_with_access_entry6)
+ self.assertEqual(dataset_with_access_entry4, dataset_with_access_entry7)
+ self.assertNotEqual(dataset_with_access_entry6, dataset_with_access_entry7)
def test_dataset_from_dict(self):
dataset = BigQueryDataset(
@@ -139,40 +139,40 @@ class TestModel(unittest.TestCase):
None
)
dataset_from_dict1 = BigQueryDataset.from_dict({
- 'name': 'test',
+ 'dataset_id': 'test',
'friendly_name': 'test_friendly_name',
'description': 'test_description',
'default_table_expiration_ms': 24 * 30 * 60 * 1000,
'location': 'US',
- 'access_grants': None
+ 'access_entris': None
})
dataset_from_dict2 = BigQueryDataset.from_dict({
- 'name': 'test',
+ 'dataset_id': 'test',
'friendly_name': 'test_friendly_name',
'description': 'test_description',
'default_table_expiration_ms': None,
'location': 'US',
- 'access_grants': None
+ 'access_entries': None
})
dataset_from_dict3 = BigQueryDataset.from_dict({
- 'name': 'foo',
+ 'dataset_id': 'foo',
'friendly_name': 'bar',
'description': 'test_description',
'default_table_expiration_ms': None,
'location': 'US',
- 'access_grants': None
+ 'access_entries': None
})
self.assertEqual(dataset, dataset_from_dict1)
self.assertNotEqual(dataset, dataset_from_dict2)
self.assertNotEqual(dataset, dataset_from_dict3)
- def test_dataset_from_dict_with_access_grant(self):
- access_grant1 = BigQueryAccessGrant(
+ def test_dataset_from_dict_with_access_entry(self):
+ access_entry1 = BigQueryAccessEntry(
'OWNER',
'specialGroup',
'projectOwners'
)
- access_grant2 = BigQueryAccessGrant(
+ access_entry2 = BigQueryAccessEntry(
None,
'view',
{
@@ -182,45 +182,45 @@ class TestModel(unittest.TestCase):
}
)
- dataset_with_access_grant1 = BigQueryDataset(
+ dataset_with_access_entry1 = BigQueryDataset(
'test',
'test_friendly_name',
'test_description',
24 * 30 * 60 * 1000,
'US',
- [access_grant1]
+ [access_entry1]
)
- dataset_with_access_grant2 = BigQueryDataset(
+ dataset_with_access_entry2 = BigQueryDataset(
'test',
'test_friendly_name',
'test_description',
24 * 30 * 60 * 1000,
'US',
- [access_grant2]
+ [access_entry2]
)
- dataset_with_access_grant3 = BigQueryDataset(
+ dataset_with_access_entry3 = BigQueryDataset(
'test',
'test_friendly_name',
'test_description',
24 * 30 * 60 * 1000,
'US',
- [access_grant1, access_grant2]
+ [access_entry1, access_entry2]
)
- dataset_with_access_grant4 = BigQueryDataset(
+ dataset_with_access_entry4 = BigQueryDataset(
'test',
'test_friendly_name',
'test_description',
24 * 30 * 60 * 1000,
'US',
- [access_grant1, access_grant1]
+ [access_entry1, access_entry1]
)
- dataset_with_access_grant_from_dict1 = BigQueryDataset.from_dict({
- 'name': 'test',
+ dataset_with_access_entry_from_dict1 = BigQueryDataset.from_dict({
+ 'dataset_id': 'test',
'friendly_name': 'test_friendly_name',
'description': 'test_description',
'default_table_expiration_ms': 24 * 30 * 60 * 1000,
'location': 'US',
- 'access_grants': [
+ 'access_entries': [
{
'role': 'OWNER',
'entity_type': 'specialGroup',
@@ -228,13 +228,13 @@ class TestModel(unittest.TestCase):
}
]
})
- dataset_with_access_grant_from_dict2 = BigQueryDataset.from_dict({
- 'name': 'test',
+ dataset_with_access_entry_from_dict2 = BigQueryDataset.from_dict({
+ 'dataset_id': 'test',
'friendly_name': 'test_friendly_name',
'description': 'test_description',
'default_table_expiration_ms': 24 * 30 * 60 * 1000,
'location': 'US',
- 'access_grants': [
+ 'access_entries': [
{
'role': None,
'entity_type': 'view',
@@ -246,13 +246,13 @@ class TestModel(unittest.TestCase):
}
]
})
- dataset_with_access_grant_from_dict3 = BigQueryDataset.from_dict({
- 'name': 'test',
+ dataset_with_access_entry_from_dict3 = BigQueryDataset.from_dict({
+ 'dataset_id': 'test',
'friendly_name': 'test_friendly_name',
'description': 'test_description',
'default_table_expiration_ms': 24 * 30 * 60 * 1000,
'location': 'US',
- 'access_grants': [
+ 'access_entries': [
{
'role': 'OWNER',
'entity_type': 'specialGroup',
@@ -269,13 +269,13 @@ class TestModel(unittest.TestCase):
}
]
})
- dataset_with_access_grant_from_dict4 = BigQueryDataset.from_dict({
- 'name': 'test',
+ dataset_with_access_entry_from_dict4 = BigQueryDataset.from_dict({
+ 'dataset_id': 'test',
'friendly_name': 'test_friendly_name',
'description': 'test_description',
'default_table_expiration_ms': 24 * 30 * 60 * 1000,
'location': 'US',
- 'access_grants': [
+ 'access_entries': [
{
'role': 'OWNER',
'entity_type': 'specialGroup',
@@ -288,15 +288,15 @@ class TestModel(unittest.TestCase):
}
]
})
- self.assertEqual(dataset_with_access_grant1, dataset_with_access_grant_from_dict1)
- self.assertNotEqual(dataset_with_access_grant1, dataset_with_access_grant_from_dict2)
- self.assertNotEqual(dataset_with_access_grant1, dataset_with_access_grant_from_dict3)
- self.assertEqual(dataset_with_access_grant2, dataset_with_access_grant_from_dict2)
- self.assertNotEqual(dataset_with_access_grant2, dataset_with_access_grant_from_dict1)
- self.assertNotEqual(dataset_with_access_grant2, dataset_with_access_grant_from_dict3)
- self.assertEqual(dataset_with_access_grant3, dataset_with_access_grant_from_dict3)
- self.assertNotEqual(dataset_with_access_grant3, dataset_with_access_grant_from_dict1)
- self.assertNotEqual(dataset_with_access_grant3, dataset_with_access_grant_from_dict2)
- self.assertEqual(dataset_with_access_grant4, dataset_with_access_grant_from_dict4)
- self.assertEqual(dataset_with_access_grant1, dataset_with_access_grant_from_dict4)
- self.assertEqual(dataset_with_access_grant4, dataset_with_access_grant_from_dict1)
+ self.assertEqual(dataset_with_access_entry1, dataset_with_access_entry_from_dict1)
+ self.assertNotEqual(dataset_with_access_entry1, dataset_with_access_entry_from_dict2)
+ self.assertNotEqual(dataset_with_access_entry1, dataset_with_access_entry_from_dict3)
+ self.assertEqual(dataset_with_access_entry2, dataset_with_access_entry_from_dict2)
+ self.assertNotEqual(dataset_with_access_entry2, dataset_with_access_entry_from_dict1)
+ self.assertNotEqual(dataset_with_access_entry2, dataset_with_access_entry_from_dict3)
+ self.assertEqual(dataset_with_access_entry3, dataset_with_access_entry_from_dict3)
+ self.assertNotEqual(dataset_with_access_entry3, dataset_with_access_entry_from_dict1)
+ self.assertNotEqual(dataset_with_access_entry3, dataset_with_access_entry_from_dict2)
+ self.assertEqual(dataset_with_access_entry4, dataset_with_access_entry_from_dict4)
+ self.assertEqual(dataset_with_access_entry1, dataset_with_access_entry_from_dict4)
+ self.assertEqual(dataset_with_access_entry4, dataset_with_access_entry_from_dict1)
diff --git a/tests/test_util.py b/tests/test_util.py
index 618d9b0..a122afc 100644
--- a/tests/test_util.py
+++ b/tests/test_util.py
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
import unittest
-from bqdm.model import BigQueryDataset, BigQueryAccessGrant
+from bqdm.model import BigQueryDataset, BigQueryAccessEntry
from bqdm.util import dump_dataset
@@ -17,16 +17,16 @@ class TestUtil(unittest.TestCase):
None
)
actual_dump_data1 = dump_dataset(dataset1)
- expected_dump_data1 = """name: test1
+ expected_dump_data1 = """dataset_id: test1
friendly_name: test_friendly_name
description: test_description
default_table_expiration_ms: 43200000
location: US
-access_grants: null
+access_entries: null
"""
self.assertEqual(actual_dump_data1, expected_dump_data1)
- access_grant2 = BigQueryAccessGrant(
+ access_entry2 = BigQueryAccessEntry(
'OWNER',
'specialGroup',
'projectOwners'
@@ -37,22 +37,22 @@ access_grants: null
'test_description',
24 * 30 * 60 * 1000,
'US',
- [access_grant2]
+ [access_entry2]
)
actual_dump_data2 = dump_dataset(dataset2)
- expected_dump_data2 = """name: test2
+ expected_dump_data2 = """dataset_id: test2
friendly_name: test_friendly_name
description: test_description
default_table_expiration_ms: 43200000
location: US
-access_grants:
+access_entries:
- role: OWNER
entity_type: specialGroup
entity_id: projectOwners
"""
self.assertEqual(actual_dump_data2, expected_dump_data2)
- access_grant3 = BigQueryAccessGrant(
+ access_entry3 = BigQueryAccessEntry(
None,
'view',
{
@@ -67,15 +67,15 @@ access_grants:
'test_description',
24 * 30 * 60 * 1000,
'US',
- [access_grant3]
+ [access_entry3]
)
actual_dump_data3 = dump_dataset(dataset3)
- expected_dump_data3 = """name: test3
+ expected_dump_data3 = """dataset_id: test3
friendly_name: test_friendly_name
description: test_description
default_table_expiration_ms: 43200000
location: US
-access_grants:
+access_entries:
- role: null
entity_type: view
entity_id:
@@ -91,15 +91,15 @@ access_grants:
'test_description',
24 * 30 * 60 * 1000,
'US',
- [access_grant2, access_grant3]
+ [access_entry2, access_entry3]
)
actual_dump_data4 = dump_dataset(dataset4)
- expected_dump_data4 = """name: test4
+ expected_dump_data4 = """dataset_id: test4
friendly_name: test_friendly_name
description: test_description
default_table_expiration_ms: 43200000
location: US
-access_grants:
+access_entries:
- role: OWNER
entity_type: specialGroup
entity_id: projectOwners
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 3,
"test_score": 2
},
"num_modified_files": 5
} | 0.0 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-cov",
"pytest-flake8",
"pytest-catchlog"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.6",
"reqs_path": null,
"test_cmd": "py.test --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs==22.2.0
-e git+https://github.com/laughingman7743/BigQuery-DatasetManager.git@60e6ebe169f5e1be06b98cf878fee11702cf2ec7#egg=BigQuery_DatasetManager
cachetools==4.2.4
certifi==2021.5.30
charset-normalizer==2.0.12
click==8.0.4
coverage==6.2
flake8==5.0.4
future==1.0.0
google-api-core==2.8.2
google-auth==2.22.0
google-cloud-bigquery==3.2.0
google-cloud-bigquery-storage==2.13.2
google-cloud-core==2.3.1
google-crc32c==1.3.0
google-resumable-media==2.3.3
googleapis-common-protos==1.56.3
grpcio==1.48.2
grpcio-status==1.48.2
idna==3.10
importlib-metadata==4.2.0
iniconfig==1.1.1
mccabe==0.7.0
numpy==1.19.5
packaging==21.3
pluggy==1.0.0
proto-plus==1.23.0
protobuf==3.19.6
py==1.11.0
pyarrow==6.0.1
pyasn1==0.5.1
pyasn1-modules==0.3.0
pycodestyle==2.9.1
pyflakes==2.5.0
pyparsing==3.1.4
pytest==7.0.1
pytest-catchlog==1.2.2
pytest-cov==4.0.0
pytest-flake8==1.1.1
python-dateutil==2.9.0.post0
PyYAML==6.0.1
requests==2.27.1
rsa==4.9
six==1.17.0
tomli==1.2.3
typing_extensions==4.1.1
urllib3==1.26.20
zipp==3.6.0
| name: BigQuery-DatasetManager
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- attrs==22.2.0
- cachetools==4.2.4
- charset-normalizer==2.0.12
- click==8.0.4
- coverage==6.2
- flake8==5.0.4
- future==1.0.0
- google-api-core==2.8.2
- google-auth==2.22.0
- google-cloud-bigquery==3.2.0
- google-cloud-bigquery-storage==2.13.2
- google-cloud-core==2.3.1
- google-crc32c==1.3.0
- google-resumable-media==2.3.3
- googleapis-common-protos==1.56.3
- grpcio==1.48.2
- grpcio-status==1.48.2
- idna==3.10
- importlib-metadata==4.2.0
- iniconfig==1.1.1
- mccabe==0.7.0
- numpy==1.19.5
- packaging==21.3
- pluggy==1.0.0
- proto-plus==1.23.0
- protobuf==3.19.6
- py==1.11.0
- pyarrow==6.0.1
- pyasn1==0.5.1
- pyasn1-modules==0.3.0
- pycodestyle==2.9.1
- pyflakes==2.5.0
- pyparsing==3.1.4
- pytest==7.0.1
- pytest-catchlog==1.2.2
- pytest-cov==4.0.0
- pytest-flake8==1.1.1
- python-dateutil==2.9.0.post0
- pyyaml==6.0.1
- requests==2.27.1
- rsa==4.9
- six==1.17.0
- tomli==1.2.3
- typing-extensions==4.1.1
- urllib3==1.26.20
- zipp==3.6.0
prefix: /opt/conda/envs/BigQuery-DatasetManager
| [
"tests/test_action.py::TestAction::test_get_add_datasets",
"tests/test_action.py::TestAction::test_get_change_datasets",
"tests/test_action.py::TestAction::test_get_destroy_datasets",
"tests/test_action.py::TestAction::test_get_intersection_datasets",
"tests/test_model.py::TestModel::test_dataset_from_dict",
"tests/test_model.py::TestModel::test_dataset_from_dict_with_access_entry",
"tests/test_model.py::TestModel::test_eq_dataset",
"tests/test_model.py::TestModel::test_eq_dataset_with_access_entry",
"tests/test_util.py::TestUtil::test_dump_dataset"
]
| []
| []
| []
| MIT License | 1,845 | [
"README.rst",
"bqdm/cli.py",
"bqdm/model.py",
"setup.py",
"bqdm/action.py"
]
| [
"README.rst",
"bqdm/cli.py",
"bqdm/model.py",
"setup.py",
"bqdm/action.py"
]
|
laughingman7743__BigQuery-DatasetManager-7 | f0a7640c34dcb591b5a0d39148384e257c9a20ac | 2017-11-03 12:00:27 | 1e930adbfb1714670ad04717401b36b59bf12558 | codecov-io: # [Codecov](https://codecov.io/gh/laughingman7743/BigQuery-DatasetManager/pull/7?src=pr&el=h1) Report
> Merging [#7](https://codecov.io/gh/laughingman7743/BigQuery-DatasetManager/pull/7?src=pr&el=desc) into [master](https://codecov.io/gh/laughingman7743/BigQuery-DatasetManager/commit/f0a7640c34dcb591b5a0d39148384e257c9a20ac?src=pr&el=desc) will **increase** coverage by `0.12%`.
> The diff coverage is `45.45%`.
[](https://codecov.io/gh/laughingman7743/BigQuery-DatasetManager/pull/7?src=pr&el=tree)
```diff
@@ Coverage Diff @@
## master #7 +/- ##
=======================================
+ Coverage 30.87% 31% +0.12%
=======================================
Files 6 6
Lines 353 358 +5
=======================================
+ Hits 109 111 +2
- Misses 244 247 +3
```
| [Impacted Files](https://codecov.io/gh/laughingman7743/BigQuery-DatasetManager/pull/7?src=pr&el=tree) | Coverage Δ | |
|---|---|---|
| [bqdm/action.py](https://codecov.io/gh/laughingman7743/BigQuery-DatasetManager/pull/7?src=pr&el=tree#diff-YnFkbS9hY3Rpb24ucHk=) | `30.46% <ø> (ø)` | :arrow_up: |
| [bqdm/util.py](https://codecov.io/gh/laughingman7743/BigQuery-DatasetManager/pull/7?src=pr&el=tree#diff-YnFkbS91dGlsLnB5) | `53.84% <ø> (-1.33%)` | :arrow_down: |
| [bqdm/cli.py](https://codecov.io/gh/laughingman7743/BigQuery-DatasetManager/pull/7?src=pr&el=tree#diff-YnFkbS9jbGkucHk=) | `0% <0%> (ø)` | :arrow_up: |
| [bqdm/model.py](https://codecov.io/gh/laughingman7743/BigQuery-DatasetManager/pull/7?src=pr&el=tree#diff-YnFkbS9tb2RlbC5weQ==) | `67.07% <50%> (-2.79%)` | :arrow_down: |
------
[Continue to review full report at Codecov](https://codecov.io/gh/laughingman7743/BigQuery-DatasetManager/pull/7?src=pr&el=continue).
> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
> `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
> Powered by [Codecov](https://codecov.io/gh/laughingman7743/BigQuery-DatasetManager/pull/7?src=pr&el=footer). Last update [f0a7640...565060b](https://codecov.io/gh/laughingman7743/BigQuery-DatasetManager/pull/7?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).
| diff --git a/README.rst b/README.rst
index ef9cbc1..1b2503f 100644
--- a/README.rst
+++ b/README.rst
@@ -44,6 +44,8 @@ The resource representation of the dataset is described in `YAML format`_.
description: null
default_table_expiration_ms: null
location: US
+ labels:
+ foo: bar
access_entries:
- role: OWNER
entity_type: specialGroup
@@ -75,6 +77,8 @@ See `the official documentation of BigQuery Datasets`_ for details of key names.
+----------------+-------------+-----------+---------+----------------------------------------------------------+
| location | str | Location in which the dataset is hosted. |
+----------------+-------------+-----------+---------+----------------------------------------------------------+
+| labels | map | Labels for the dataset. |
++----------------+-------------+-----------+---------+----------------------------------------------------------+
| access_entries | seq | Represent grant of an access role to an entity. |
+----------------+-------------+-----------+---------+----------------------------------------------------------+
| access_entries | role | str | Role granted to the entity. One of |
@@ -277,7 +281,4 @@ Run test multiple Python versions
TODO
----
-#. Support labels field (Currently ``google-cloud-bigquery`` `does not support labels field of Datasets`_)
#. Manage table resources
-
-.. _`does not support labels field of Datasets`: https://github.com/GoogleCloudPlatform/google-cloud-python/issues/2931
diff --git a/bqdm/action.py b/bqdm/action.py
index 2ec16c2..c14529a 100644
--- a/bqdm/action.py
+++ b/bqdm/action.py
@@ -1,10 +1,12 @@
# -*- coding: utf-8 -*-
+from __future__ import absolute_import
import codecs
import logging
import os
import sys
import click
+from future.utils import iteritems
from google.cloud import bigquery
from bqdm.model import BigQueryDataset
@@ -116,10 +118,18 @@ class DatasetAction(object):
click.secho(' Changing... {0}'.format(converted.path), fg='yellow')
for d in diff:
click.echo(' {0}'.format(d))
+ old_labels = old_dataset.labels
+ if old_labels:
+ labels = converted.labels.copy()
+ for k, v in iteritems(old_labels):
+ if k not in labels.keys():
+ labels[k] = None
+ converted.labels = labels
self.client.update_dataset(converted, [
'friendly_name',
'description',
'default_table_expiration_ms',
+ 'labels',
'access_entries'
])
click.echo()
diff --git a/bqdm/cli.py b/bqdm/cli.py
index 5405243..ae91d99 100755
--- a/bqdm/cli.py
+++ b/bqdm/cli.py
@@ -13,7 +13,7 @@ import bqdm.message as msg
from bqdm import CONTEXT_SETTINGS
from bqdm.action import DatasetAction
from bqdm.model import BigQueryDataset, BigQueryAccessEntry
-from bqdm.util import list_local_datasets, ordered_dict_constructor, str_representer
+from bqdm.util import list_local_datasets, str_representer
_logger = logging.getLogger(__name__)
@@ -25,7 +25,6 @@ yaml.add_representer(str, str_representer)
yaml.add_representer(unicode, str_representer)
yaml.add_representer(BigQueryDataset, BigQueryDataset.represent)
yaml.add_representer(BigQueryAccessEntry, BigQueryAccessEntry.represent)
-yaml.add_constructor('tag:yaml.org,2002:map', ordered_dict_constructor)
@click.group(context_settings=CONTEXT_SETTINGS)
diff --git a/bqdm/model.py b/bqdm/model.py
index c8cd26d..8da3cd3 100644
--- a/bqdm/model.py
+++ b/bqdm/model.py
@@ -9,13 +9,14 @@ from google.cloud.bigquery.dataset import AccessEntry, Dataset
class BigQueryDataset(object):
def __init__(self, dataset_id, friendly_name, description,
- default_table_expiration_ms, location, access_entries):
+ default_table_expiration_ms, location, labels, access_entries):
self.dataset_id = dataset_id
self.friendly_name = friendly_name
self.description = description
self.default_table_expiration_ms = default_table_expiration_ms
self.location = location
- self.access_entries = access_entries
+ self.labels = labels if labels else None
+ self.access_entries = access_entries if access_entries else None
@staticmethod
def from_dict(value):
@@ -27,6 +28,7 @@ class BigQueryDataset(object):
value.get('description', None),
value.get('default_table_expiration_ms', None),
value.get('location', None),
+ value.get('labels', None),
access_entries)
@staticmethod
@@ -39,6 +41,7 @@ class BigQueryDataset(object):
dataset.description,
dataset.default_table_expiration_ms,
dataset.location,
+ dataset.labels,
access_entries)
@staticmethod
@@ -52,6 +55,7 @@ class BigQueryDataset(object):
dataset.description = value.description
dataset.default_table_expiration_ms = value.default_table_expiration_ms
dataset.location = value.location
+ dataset.labels = value.labels if value.labels is not None else dict()
dataset.access_entries = access_entries
return dataset
@@ -65,6 +69,7 @@ class BigQueryDataset(object):
('description', value.description),
('default_table_expiration_ms', value.default_table_expiration_ms),
('location', value.location),
+ ('labels', value.labels),
('access_entries', value.access_entries),
)
)
@@ -75,6 +80,8 @@ class BigQueryDataset(object):
self.description,
self.default_table_expiration_ms,
self.location,
+ frozenset(sorted(self.labels.items())) if self.labels is not None
+ else self.labels,
frozenset(self.access_entries) if self.access_entries is not None
else self.access_entries,)
diff --git a/bqdm/util.py b/bqdm/util.py
index b63a9a0..1a28f1e 100644
--- a/bqdm/util.py
+++ b/bqdm/util.py
@@ -4,7 +4,6 @@ import codecs
import difflib
import glob
import os
-from collections import OrderedDict
import click
import yaml
@@ -15,10 +14,6 @@ def str_representer(_, data):
return yaml.ScalarNode('tag:yaml.org,2002:str', data)
-def ordered_dict_constructor(loader, data):
- return OrderedDict(loader.construct_pairs(data))
-
-
def dump_dataset(data):
return yaml.dump(data, default_flow_style=False, indent=4,
allow_unicode=True, canonical=False)
| Manage labels field
https://github.com/GoogleCloudPlatform/google-cloud-python/pull/4245/files#diff-bafa3d472438f0a46853cc9879265cadR399 | laughingman7743/BigQuery-DatasetManager | diff --git a/tests/__init__.py b/tests/__init__.py
index 95bd52a..f535f26 100644
--- a/tests/__init__.py
+++ b/tests/__init__.py
@@ -1,11 +1,11 @@
# -*- coding: utf-8 -*-
+from __future__ import absolute_import
import yaml
-from bqdm.util import ordered_dict_constructor, str_representer
+from bqdm.util import str_representer
from bqdm.model import BigQueryDataset, BigQueryAccessEntry
yaml.add_representer(str, str_representer)
yaml.add_representer(BigQueryDataset, BigQueryDataset.represent)
yaml.add_representer(BigQueryAccessEntry, BigQueryAccessEntry.represent)
-yaml.add_constructor('tag:yaml.org,2002:map', ordered_dict_constructor)
diff --git a/tests/test_action.py b/tests/test_action.py
index 16b2cd9..7382fcf 100644
--- a/tests/test_action.py
+++ b/tests/test_action.py
@@ -1,4 +1,5 @@
# -*- coding: utf-8 -*-
+from __future__ import absolute_import
import unittest
from bqdm.action import DatasetAction
@@ -14,6 +15,7 @@ class TestAction(unittest.TestCase):
'test_description',
24 * 30 * 60 * 1000,
'US',
+ None,
None
)
dataset2 = BigQueryDataset(
@@ -22,6 +24,7 @@ class TestAction(unittest.TestCase):
'test_description',
24 * 30 * 60 * 1000,
'US',
+ None,
None
)
@@ -50,6 +53,7 @@ class TestAction(unittest.TestCase):
'test_description',
24 * 30 * 60 * 1000,
'US',
+ None,
None
)
dataset1_2 = BigQueryDataset(
@@ -58,6 +62,7 @@ class TestAction(unittest.TestCase):
'bar',
None,
'UK',
+ None,
None
)
dataset2_1 = BigQueryDataset(
@@ -66,6 +71,7 @@ class TestAction(unittest.TestCase):
'test_description',
24 * 30 * 60 * 1000,
'US',
+ None,
None
)
dataset2_2 = BigQueryDataset(
@@ -74,6 +80,59 @@ class TestAction(unittest.TestCase):
'test_description',
24 * 30 * 60 * 1000,
'US',
+ None,
+ [
+ BigQueryAccessEntry(
+ None,
+ 'view',
+ {
+ 'datasetId': 'test',
+ 'projectId': 'test-project',
+ 'tableId': 'test_table'
+ }
+ )
+ ]
+ )
+ dataset3_1 = BigQueryDataset(
+ 'test3',
+ 'test_friendly_name',
+ 'test_description',
+ 24 * 30 * 60 * 1000,
+ 'US',
+ {
+ 'foo': 'bar'
+ },
+ None
+ )
+ dataset3_2 = BigQueryDataset(
+ 'test3',
+ 'test_friendly_name',
+ 'test_description',
+ 24 * 30 * 60 * 1000,
+ 'US',
+ None,
+ [
+ BigQueryAccessEntry(
+ None,
+ 'view',
+ {
+ 'datasetId': 'test',
+ 'projectId': 'test-project',
+ 'tableId': 'test_table'
+ }
+ )
+ ]
+ )
+ dataset3_3 = BigQueryDataset(
+ 'test3',
+ 'test_friendly_name',
+ 'test_description',
+ 24 * 30 * 60 * 1000,
+ 'US',
+ {
+ 'aaa': 'bbb',
+ 'ccc': 'ddd'
+ },
[
BigQueryAccessEntry(
None,
@@ -117,6 +176,36 @@ class TestAction(unittest.TestCase):
self.assertEqual(actual_count5, 0)
self.assertEqual(actual_results5, tuple())
+ source6 = [dataset3_1, dataset3_2, dataset3_3]
+ target6 = [dataset3_1, dataset3_2, dataset3_3]
+ actual_count6, actual_results6 = DatasetAction.get_change_datasets(source6, target6)
+ self.assertEqual(actual_count6, 0)
+ self.assertEqual(actual_results6, tuple())
+
+ source7 = [dataset3_1]
+ target7 = [dataset3_2]
+ actual_count7, actual_results7 = DatasetAction.get_change_datasets(source7, target7)
+ self.assertEqual(actual_count7, 1)
+ self.assertEqual(actual_results7, tuple([dataset3_2]))
+
+ source8 = [dataset3_1]
+ target8 = [dataset3_3]
+ actual_count8, actual_results8 = DatasetAction.get_change_datasets(source8, target8)
+ self.assertEqual(actual_count8, 1)
+ self.assertEqual(actual_results8, tuple([dataset3_3]))
+
+ source9 = [dataset3_1]
+ target9 = [dataset3_3]
+ actual_count9, actual_results9 = DatasetAction.get_change_datasets(source9, target9)
+ self.assertEqual(actual_count9, 1)
+ self.assertEqual(actual_results9, tuple([dataset3_3]))
+
+ source10 = [dataset3_2]
+ target10 = [dataset3_3]
+ actual_count10, actual_results10 = DatasetAction.get_change_datasets(source10, target10)
+ self.assertEqual(actual_count10, 1)
+ self.assertEqual(actual_results10, tuple([dataset3_3]))
+
def test_get_destroy_datasets(self):
dataset1_1 = BigQueryDataset(
'test1',
@@ -124,6 +213,7 @@ class TestAction(unittest.TestCase):
'test_description',
24 * 30 * 60 * 1000,
'US',
+ None,
None
)
dataset1_2 = BigQueryDataset(
@@ -132,6 +222,7 @@ class TestAction(unittest.TestCase):
'bar',
None,
'UK',
+ None,
None
)
dataset2_1 = BigQueryDataset(
@@ -140,6 +231,7 @@ class TestAction(unittest.TestCase):
'test_description',
24 * 30 * 60 * 1000,
'US',
+ None,
None
)
dataset2_2 = BigQueryDataset(
@@ -148,6 +240,7 @@ class TestAction(unittest.TestCase):
'test_description',
24 * 30 * 60 * 1000,
'US',
+ None,
[
BigQueryAccessEntry(
None,
@@ -198,6 +291,7 @@ class TestAction(unittest.TestCase):
'test_description',
24 * 30 * 60 * 1000,
'US',
+ None,
None
)
dataset1_2 = BigQueryDataset(
@@ -206,6 +300,7 @@ class TestAction(unittest.TestCase):
'bar',
None,
'UK',
+ None,
None
)
dataset2_1 = BigQueryDataset(
@@ -214,6 +309,7 @@ class TestAction(unittest.TestCase):
'test_description',
24 * 30 * 60 * 1000,
'US',
+ None,
None
)
dataset2_2 = BigQueryDataset(
@@ -222,6 +318,7 @@ class TestAction(unittest.TestCase):
'test_description',
24 * 30 * 60 * 1000,
'US',
+ None,
[
BigQueryAccessEntry(
None,
diff --git a/tests/test_model.py b/tests/test_model.py
index 16dbe16..e58673d 100644
--- a/tests/test_model.py
+++ b/tests/test_model.py
@@ -1,4 +1,5 @@
# -*- coding: utf-8 -*-
+from __future__ import absolute_import
import unittest
from bqdm.model import BigQueryDataset, BigQueryAccessEntry
@@ -13,6 +14,7 @@ class TestModel(unittest.TestCase):
'test_description',
24 * 30 * 60 * 1000,
'US',
+ None,
None
)
dataset2 = BigQueryDataset(
@@ -21,6 +23,7 @@ class TestModel(unittest.TestCase):
'test_description',
24 * 30 * 60 * 1000,
'US',
+ None,
None
)
dataset3 = BigQueryDataset(
@@ -29,6 +32,7 @@ class TestModel(unittest.TestCase):
'test_description',
24 * 30 * 60 * 1000,
'EU',
+ None,
None
)
dataset4 = BigQueryDataset(
@@ -37,8 +41,10 @@ class TestModel(unittest.TestCase):
'test_description',
None,
'EU',
+ None,
None
)
+
self.assertEqual(dataset1, dataset2)
self.assertNotEqual(dataset1, dataset3)
self.assertNotEqual(dataset1, dataset4)
@@ -71,6 +77,7 @@ class TestModel(unittest.TestCase):
'test_description',
24 * 30 * 60 * 1000,
'US',
+ None,
[access_entry1]
)
dataset_with_access_entry2 = BigQueryDataset(
@@ -79,6 +86,7 @@ class TestModel(unittest.TestCase):
'test_description',
24 * 30 * 60 * 1000,
'US',
+ None,
[access_entry2]
)
dataset_with_access_entry3 = BigQueryDataset(
@@ -87,6 +95,7 @@ class TestModel(unittest.TestCase):
'test_description',
24 * 30 * 60 * 1000,
'US',
+ None,
[access_entry3]
)
dataset_with_access_entry4 = BigQueryDataset(
@@ -95,6 +104,7 @@ class TestModel(unittest.TestCase):
'test_description',
24 * 30 * 60 * 1000,
'US',
+ None,
[access_entry1]
)
dataset_with_access_entry5 = BigQueryDataset(
@@ -103,6 +113,7 @@ class TestModel(unittest.TestCase):
'test_description',
24 * 30 * 60 * 1000,
'US',
+ None,
[access_entry1, access_entry3]
)
dataset_with_access_entry6 = BigQueryDataset(
@@ -111,6 +122,7 @@ class TestModel(unittest.TestCase):
'test_description',
24 * 30 * 60 * 1000,
'US',
+ None,
[access_entry3, access_entry1]
)
dataset_with_access_entry7 = BigQueryDataset(
@@ -119,8 +131,10 @@ class TestModel(unittest.TestCase):
'test_description',
24 * 30 * 60 * 1000,
'US',
+ None,
[access_entry1, access_entry2]
)
+
self.assertEqual(dataset_with_access_entry1, dataset_with_access_entry2)
self.assertNotEqual(dataset_with_access_entry1, dataset_with_access_entry3)
self.assertNotEqual(dataset_with_access_entry1, dataset_with_access_entry4)
@@ -136,14 +150,17 @@ class TestModel(unittest.TestCase):
'test_description',
24 * 30 * 60 * 1000,
'US',
+ None,
None
)
+
dataset_from_dict1 = BigQueryDataset.from_dict({
'dataset_id': 'test',
'friendly_name': 'test_friendly_name',
'description': 'test_description',
'default_table_expiration_ms': 24 * 30 * 60 * 1000,
'location': 'US',
+ 'labels': None,
'access_entris': None
})
dataset_from_dict2 = BigQueryDataset.from_dict({
@@ -152,6 +169,7 @@ class TestModel(unittest.TestCase):
'description': 'test_description',
'default_table_expiration_ms': None,
'location': 'US',
+ 'labels': None,
'access_entries': None
})
dataset_from_dict3 = BigQueryDataset.from_dict({
@@ -160,8 +178,10 @@ class TestModel(unittest.TestCase):
'description': 'test_description',
'default_table_expiration_ms': None,
'location': 'US',
+ 'labels': None,
'access_entries': None
})
+
self.assertEqual(dataset, dataset_from_dict1)
self.assertNotEqual(dataset, dataset_from_dict2)
self.assertNotEqual(dataset, dataset_from_dict3)
@@ -188,6 +208,7 @@ class TestModel(unittest.TestCase):
'test_description',
24 * 30 * 60 * 1000,
'US',
+ None,
[access_entry1]
)
dataset_with_access_entry2 = BigQueryDataset(
@@ -196,6 +217,7 @@ class TestModel(unittest.TestCase):
'test_description',
24 * 30 * 60 * 1000,
'US',
+ None,
[access_entry2]
)
dataset_with_access_entry3 = BigQueryDataset(
@@ -204,6 +226,7 @@ class TestModel(unittest.TestCase):
'test_description',
24 * 30 * 60 * 1000,
'US',
+ None,
[access_entry1, access_entry2]
)
dataset_with_access_entry4 = BigQueryDataset(
@@ -212,14 +235,17 @@ class TestModel(unittest.TestCase):
'test_description',
24 * 30 * 60 * 1000,
'US',
+ None,
[access_entry1, access_entry1]
)
+
dataset_with_access_entry_from_dict1 = BigQueryDataset.from_dict({
'dataset_id': 'test',
'friendly_name': 'test_friendly_name',
'description': 'test_description',
'default_table_expiration_ms': 24 * 30 * 60 * 1000,
'location': 'US',
+ 'labels': None,
'access_entries': [
{
'role': 'OWNER',
@@ -234,6 +260,7 @@ class TestModel(unittest.TestCase):
'description': 'test_description',
'default_table_expiration_ms': 24 * 30 * 60 * 1000,
'location': 'US',
+ 'labels': None,
'access_entries': [
{
'role': None,
@@ -252,6 +279,7 @@ class TestModel(unittest.TestCase):
'description': 'test_description',
'default_table_expiration_ms': 24 * 30 * 60 * 1000,
'location': 'US',
+ 'labels': None,
'access_entries': [
{
'role': 'OWNER',
@@ -275,6 +303,7 @@ class TestModel(unittest.TestCase):
'description': 'test_description',
'default_table_expiration_ms': 24 * 30 * 60 * 1000,
'location': 'US',
+ 'labels': None,
'access_entries': [
{
'role': 'OWNER',
@@ -288,6 +317,7 @@ class TestModel(unittest.TestCase):
}
]
})
+
self.assertEqual(dataset_with_access_entry1, dataset_with_access_entry_from_dict1)
self.assertNotEqual(dataset_with_access_entry1, dataset_with_access_entry_from_dict2)
self.assertNotEqual(dataset_with_access_entry1, dataset_with_access_entry_from_dict3)
@@ -300,3 +330,60 @@ class TestModel(unittest.TestCase):
self.assertEqual(dataset_with_access_entry4, dataset_with_access_entry_from_dict4)
self.assertEqual(dataset_with_access_entry1, dataset_with_access_entry_from_dict4)
self.assertEqual(dataset_with_access_entry4, dataset_with_access_entry_from_dict1)
+
+ def test_dataset_from_dict_with_label(self):
+ label1 = {
+ 'foo': 'bar'
+ }
+ label2 = {
+ 'aaa': 'bbb',
+ 'ccc': 'ddd'
+ }
+
+ dataset_with_label1 = BigQueryDataset(
+ 'test',
+ 'test_friendly_name',
+ 'test_description',
+ 24 * 30 * 60 * 1000,
+ 'US',
+ label1,
+ None
+ )
+ dataset_with_label2 = BigQueryDataset(
+ 'test',
+ 'test_friendly_name',
+ 'test_description',
+ 24 * 30 * 60 * 1000,
+ 'US',
+ label2,
+ None
+ )
+
+ dataset_with_label_from_dict1 = BigQueryDataset.from_dict({
+ 'dataset_id': 'test',
+ 'friendly_name': 'test_friendly_name',
+ 'description': 'test_description',
+ 'default_table_expiration_ms': 24 * 30 * 60 * 1000,
+ 'location': 'US',
+ 'labels': {
+ 'foo': 'bar'
+ },
+ 'access_entries': None
+ })
+ dataset_with_label_from_dict2 = BigQueryDataset.from_dict({
+ 'dataset_id': 'test',
+ 'friendly_name': 'test_friendly_name',
+ 'description': 'test_description',
+ 'default_table_expiration_ms': 24 * 30 * 60 * 1000,
+ 'location': 'US',
+ 'labels': {
+ 'aaa': 'bbb',
+ 'ccc': 'ddd'
+ },
+ 'access_entries': None
+ })
+
+ self.assertEqual(dataset_with_label1, dataset_with_label_from_dict1)
+ self.assertNotEqual(dataset_with_label1, dataset_with_label_from_dict2)
+ self.assertNotEqual(dataset_with_label2, dataset_with_label_from_dict1)
+ self.assertEqual(dataset_with_label2, dataset_with_label_from_dict2)
diff --git a/tests/test_util.py b/tests/test_util.py
index a122afc..b1d29b5 100644
--- a/tests/test_util.py
+++ b/tests/test_util.py
@@ -1,4 +1,5 @@
# -*- coding: utf-8 -*-
+from __future__ import absolute_import
import unittest
from bqdm.model import BigQueryDataset, BigQueryAccessEntry
@@ -14,6 +15,7 @@ class TestUtil(unittest.TestCase):
'test_description',
24 * 30 * 60 * 1000,
'US',
+ None,
None
)
actual_dump_data1 = dump_dataset(dataset1)
@@ -22,6 +24,7 @@ friendly_name: test_friendly_name
description: test_description
default_table_expiration_ms: 43200000
location: US
+labels: null
access_entries: null
"""
self.assertEqual(actual_dump_data1, expected_dump_data1)
@@ -37,6 +40,7 @@ access_entries: null
'test_description',
24 * 30 * 60 * 1000,
'US',
+ None,
[access_entry2]
)
actual_dump_data2 = dump_dataset(dataset2)
@@ -45,6 +49,7 @@ friendly_name: test_friendly_name
description: test_description
default_table_expiration_ms: 43200000
location: US
+labels: null
access_entries:
- role: OWNER
entity_type: specialGroup
@@ -67,6 +72,7 @@ access_entries:
'test_description',
24 * 30 * 60 * 1000,
'US',
+ None,
[access_entry3]
)
actual_dump_data3 = dump_dataset(dataset3)
@@ -75,6 +81,7 @@ friendly_name: test_friendly_name
description: test_description
default_table_expiration_ms: 43200000
location: US
+labels: null
access_entries:
- role: null
entity_type: view
@@ -91,6 +98,7 @@ access_entries:
'test_description',
24 * 30 * 60 * 1000,
'US',
+ None,
[access_entry2, access_entry3]
)
actual_dump_data4 = dump_dataset(dataset4)
@@ -99,6 +107,7 @@ friendly_name: test_friendly_name
description: test_description
default_table_expiration_ms: 43200000
location: US
+labels: null
access_entries:
- role: OWNER
entity_type: specialGroup
@@ -111,3 +120,53 @@ access_entries:
tableId: test_table
"""
self.assertEqual(actual_dump_data4, expected_dump_data4)
+
+ label5 = {
+ 'foo': 'bar'
+ }
+ dataset5 = BigQueryDataset(
+ 'test5',
+ 'test_friendly_name',
+ 'test_description',
+ 24 * 30 * 60 * 1000,
+ 'US',
+ label5,
+ None
+ )
+ actual_dump_data5 = dump_dataset(dataset5)
+ expected_dump_data5 = """dataset_id: test5
+friendly_name: test_friendly_name
+description: test_description
+default_table_expiration_ms: 43200000
+location: US
+labels:
+ foo: bar
+access_entries: null
+"""
+ self.assertEqual(actual_dump_data5, expected_dump_data5)
+
+ label6 = {
+ 'aaa': 'bbb',
+ 'ccc': 'ddd'
+ }
+ dataset6 = BigQueryDataset(
+ 'test6',
+ 'test_friendly_name',
+ 'test_description',
+ 24 * 30 * 60 * 1000,
+ 'US',
+ label6,
+ None
+ )
+ actual_dump_data6 = dump_dataset(dataset6)
+ expected_dump_data6 = """dataset_id: test6
+friendly_name: test_friendly_name
+description: test_description
+default_table_expiration_ms: 43200000
+location: US
+labels:
+ aaa: bbb
+ ccc: ddd
+access_entries: null
+"""
+ self.assertEqual(actual_dump_data6, expected_dump_data6)
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 3,
"test_score": 0
},
"num_modified_files": 5
} | 0.0 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"pytest",
"pytest-cov",
"pytest-flake8",
"pytest-catchlog"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.6",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work
-e git+https://github.com/laughingman7743/BigQuery-DatasetManager.git@f0a7640c34dcb591b5a0d39148384e257c9a20ac#egg=BigQuery_DatasetManager
cachetools==4.2.4
certifi==2021.5.30
charset-normalizer==2.0.12
click==8.0.4
coverage==6.2
flake8==5.0.4
future==1.0.0
google-api-core==0.1.4
google-auth==1.35.0
google-cloud-bigquery==0.28.0
google-cloud-core==0.28.1
google-crc32c==1.3.0
google-resumable-media==2.3.3
googleapis-common-protos==1.56.3
idna==3.10
importlib-metadata==4.2.0
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
mccabe==0.7.0
more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work
packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work
pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work
protobuf==3.19.6
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pyasn1==0.5.1
pyasn1-modules==0.3.0
pycodestyle==2.9.1
pyflakes==2.5.0
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pytest==7.0.1
pytest-catchlog==1.2.2
pytest-cov==4.0.0
pytest-flake8==1.1.1
pytz==2025.2
PyYAML==6.0.1
requests==2.27.1
rsa==4.9
six==1.17.0
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
tomli==1.2.3
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
urllib3==1.26.20
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
| name: BigQuery-DatasetManager
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=21.4.0=pyhd3eb1b0_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- importlib_metadata=4.8.1=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- more-itertools=8.12.0=pyhd3eb1b0_0
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=21.3=pyhd3eb1b0_0
- pip=21.2.2=py36h06a4308_0
- pluggy=0.13.1=py36h06a4308_0
- py=1.11.0=pyhd3eb1b0_0
- pyparsing=3.0.4=pyhd3eb1b0_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- toml=0.10.2=pyhd3eb1b0_0
- typing_extensions=4.1.1=pyh06a4308_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zipp=3.6.0=pyhd3eb1b0_0
- zlib=1.2.13=h5eee18b_1
- pip:
- cachetools==4.2.4
- charset-normalizer==2.0.12
- click==8.0.4
- coverage==6.2
- flake8==5.0.4
- future==1.0.0
- google-api-core==0.1.4
- google-auth==1.35.0
- google-cloud-bigquery==0.28.0
- google-cloud-core==0.28.1
- google-crc32c==1.3.0
- google-resumable-media==2.3.3
- googleapis-common-protos==1.56.3
- idna==3.10
- importlib-metadata==4.2.0
- mccabe==0.7.0
- protobuf==3.19.6
- pyasn1==0.5.1
- pyasn1-modules==0.3.0
- pycodestyle==2.9.1
- pyflakes==2.5.0
- pytest==7.0.1
- pytest-catchlog==1.2.2
- pytest-cov==4.0.0
- pytest-flake8==1.1.1
- pytz==2025.2
- pyyaml==6.0.1
- requests==2.27.1
- rsa==4.9
- six==1.17.0
- tomli==1.2.3
- urllib3==1.26.20
prefix: /opt/conda/envs/BigQuery-DatasetManager
| [
"tests/test_action.py::TestAction::test_get_add_datasets",
"tests/test_action.py::TestAction::test_get_change_datasets",
"tests/test_action.py::TestAction::test_get_destroy_datasets",
"tests/test_action.py::TestAction::test_get_intersection_datasets",
"tests/test_model.py::TestModel::test_dataset_from_dict",
"tests/test_model.py::TestModel::test_dataset_from_dict_with_access_entry",
"tests/test_model.py::TestModel::test_dataset_from_dict_with_label",
"tests/test_model.py::TestModel::test_eq_dataset",
"tests/test_model.py::TestModel::test_eq_dataset_with_access_entry",
"tests/test_util.py::TestUtil::test_dump_dataset"
]
| []
| []
| []
| MIT License | 1,846 | [
"README.rst",
"bqdm/cli.py",
"bqdm/model.py",
"bqdm/action.py",
"bqdm/util.py"
]
| [
"README.rst",
"bqdm/cli.py",
"bqdm/model.py",
"bqdm/action.py",
"bqdm/util.py"
]
|
oasis-open__cti-python-stix2-100 | 5aa8c66bfc8b03dd76ff97ae3462c791d5861406 | 2017-11-03 12:51:51 | ef6dade6f6773edd14aa16a2e4566e50bf74cbb4 | diff --git a/docs/guide/custom.ipynb b/docs/guide/custom.ipynb
index 2254fa8..48b9ffe 100644
--- a/docs/guide/custom.ipynb
+++ b/docs/guide/custom.ipynb
@@ -99,101 +99,28 @@
},
{
"cell_type": "code",
- "execution_count": 5,
+ "execution_count": 3,
"metadata": {},
"outputs": [
{
- "data": {
- "text/html": [
- "<style type=\"text/css\">.highlight .hll { background-color: #ffffcc }\n",
- ".highlight { background: #f8f8f8; }\n",
- ".highlight .c { color: #408080; font-style: italic } /* Comment */\n",
- ".highlight .err { border: 1px solid #FF0000 } /* Error */\n",
- ".highlight .k { color: #008000; font-weight: bold } /* Keyword */\n",
- ".highlight .o { color: #666666 } /* Operator */\n",
- ".highlight .ch { color: #408080; font-style: italic } /* Comment.Hashbang */\n",
- ".highlight .cm { color: #408080; font-style: italic } /* Comment.Multiline */\n",
- ".highlight .cp { color: #BC7A00 } /* Comment.Preproc */\n",
- ".highlight .cpf { color: #408080; font-style: italic } /* Comment.PreprocFile */\n",
- ".highlight .c1 { color: #408080; font-style: italic } /* Comment.Single */\n",
- ".highlight .cs { color: #408080; font-style: italic } /* Comment.Special */\n",
- ".highlight .gd { color: #A00000 } /* Generic.Deleted */\n",
- ".highlight .ge { font-style: italic } /* Generic.Emph */\n",
- ".highlight .gr { color: #FF0000 } /* Generic.Error */\n",
- ".highlight .gh { color: #000080; font-weight: bold } /* Generic.Heading */\n",
- ".highlight .gi { color: #00A000 } /* Generic.Inserted */\n",
- ".highlight .go { color: #888888 } /* Generic.Output */\n",
- ".highlight .gp { color: #000080; font-weight: bold } /* Generic.Prompt */\n",
- ".highlight .gs { font-weight: bold } /* Generic.Strong */\n",
- ".highlight .gu { color: #800080; font-weight: bold } /* Generic.Subheading */\n",
- ".highlight .gt { color: #0044DD } /* Generic.Traceback */\n",
- ".highlight .kc { color: #008000; font-weight: bold } /* Keyword.Constant */\n",
- ".highlight .kd { color: #008000; font-weight: bold } /* Keyword.Declaration */\n",
- ".highlight .kn { color: #008000; font-weight: bold } /* Keyword.Namespace */\n",
- ".highlight .kp { color: #008000 } /* Keyword.Pseudo */\n",
- ".highlight .kr { color: #008000; font-weight: bold } /* Keyword.Reserved */\n",
- ".highlight .kt { color: #B00040 } /* Keyword.Type */\n",
- ".highlight .m { color: #666666 } /* Literal.Number */\n",
- ".highlight .s { color: #BA2121 } /* Literal.String */\n",
- ".highlight .na { color: #7D9029 } /* Name.Attribute */\n",
- ".highlight .nb { color: #008000 } /* Name.Builtin */\n",
- ".highlight .nc { color: #0000FF; font-weight: bold } /* Name.Class */\n",
- ".highlight .no { color: #880000 } /* Name.Constant */\n",
- ".highlight .nd { color: #AA22FF } /* Name.Decorator */\n",
- ".highlight .ni { color: #999999; font-weight: bold } /* Name.Entity */\n",
- ".highlight .ne { color: #D2413A; font-weight: bold } /* Name.Exception */\n",
- ".highlight .nf { color: #0000FF } /* Name.Function */\n",
- ".highlight .nl { color: #A0A000 } /* Name.Label */\n",
- ".highlight .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */\n",
- ".highlight .nt { color: #008000; font-weight: bold } /* Name.Tag */\n",
- ".highlight .nv { color: #19177C } /* Name.Variable */\n",
- ".highlight .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */\n",
- ".highlight .w { color: #bbbbbb } /* Text.Whitespace */\n",
- ".highlight .mb { color: #666666 } /* Literal.Number.Bin */\n",
- ".highlight .mf { color: #666666 } /* Literal.Number.Float */\n",
- ".highlight .mh { color: #666666 } /* Literal.Number.Hex */\n",
- ".highlight .mi { color: #666666 } /* Literal.Number.Integer */\n",
- ".highlight .mo { color: #666666 } /* Literal.Number.Oct */\n",
- ".highlight .sa { color: #BA2121 } /* Literal.String.Affix */\n",
- ".highlight .sb { color: #BA2121 } /* Literal.String.Backtick */\n",
- ".highlight .sc { color: #BA2121 } /* Literal.String.Char */\n",
- ".highlight .dl { color: #BA2121 } /* Literal.String.Delimiter */\n",
- ".highlight .sd { color: #BA2121; font-style: italic } /* Literal.String.Doc */\n",
- ".highlight .s2 { color: #BA2121 } /* Literal.String.Double */\n",
- ".highlight .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */\n",
- ".highlight .sh { color: #BA2121 } /* Literal.String.Heredoc */\n",
- ".highlight .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */\n",
- ".highlight .sx { color: #008000 } /* Literal.String.Other */\n",
- ".highlight .sr { color: #BB6688 } /* Literal.String.Regex */\n",
- ".highlight .s1 { color: #BA2121 } /* Literal.String.Single */\n",
- ".highlight .ss { color: #19177C } /* Literal.String.Symbol */\n",
- ".highlight .bp { color: #008000 } /* Name.Builtin.Pseudo */\n",
- ".highlight .fm { color: #0000FF } /* Name.Function.Magic */\n",
- ".highlight .vc { color: #19177C } /* Name.Variable.Class */\n",
- ".highlight .vg { color: #19177C } /* Name.Variable.Global */\n",
- ".highlight .vi { color: #19177C } /* Name.Variable.Instance */\n",
- ".highlight .vm { color: #19177C } /* Name.Variable.Magic */\n",
- ".highlight .il { color: #666666 } /* Literal.Number.Integer.Long */</style><div class=\"highlight\"><pre><span></span><span class=\"p\">{</span>\n",
- " <span class=\"nt\">"x_foo"</span><span class=\"p\">:</span> <span class=\"s2\">"bar"</span><span class=\"p\">,</span>\n",
- " <span class=\"nt\">"type"</span><span class=\"p\">:</span> <span class=\"s2\">"identity"</span><span class=\"p\">,</span>\n",
- " <span class=\"nt\">"id"</span><span class=\"p\">:</span> <span class=\"s2\">"identity--8d7f0697-e589-4e3b-aa57-cae798d2d138"</span><span class=\"p\">,</span>\n",
- " <span class=\"nt\">"created"</span><span class=\"p\">:</span> <span class=\"s2\">"2017-09-26T21:02:19.465Z"</span><span class=\"p\">,</span>\n",
- " <span class=\"nt\">"modified"</span><span class=\"p\">:</span> <span class=\"s2\">"2017-09-26T21:02:19.465Z"</span><span class=\"p\">,</span>\n",
- " <span class=\"nt\">"name"</span><span class=\"p\">:</span> <span class=\"s2\">"John Smith"</span><span class=\"p\">,</span>\n",
- " <span class=\"nt\">"identity_class"</span><span class=\"p\">:</span> <span class=\"s2\">"individual"</span>\n",
- "<span class=\"p\">}</span>\n",
- "</pre></div>\n"
- ],
- "text/plain": [
- "<IPython.core.display.HTML object>"
- ]
- },
- "execution_count": 5,
- "metadata": {},
- "output_type": "execute_result"
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "{\n",
+ " \"type\": \"identity\",\n",
+ " \"id\": \"identity--10761df2-93f6-4eb4-9d02-4fccfe5dc91d\",\n",
+ " \"created\": \"2017-11-03T18:20:48.145Z\",\n",
+ " \"modified\": \"2017-11-03T18:20:48.145Z\",\n",
+ " \"name\": \"John Smith\",\n",
+ " \"identity_class\": \"individual\",\n",
+ " \"x_foo\": \"bar\"\n",
+ "}\n"
+ ]
}
],
"source": [
+ "from stix2 import Identity\n",
+ "\n",
"identity = Identity(name=\"John Smith\",\n",
" identity_class=\"individual\",\n",
" custom_properties={\n",
@@ -923,14 +850,14 @@
"language_info": {
"codemirror_mode": {
"name": "ipython",
- "version": 2
+ "version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
- "pygments_lexer": "ipython2",
- "version": "2.7.12"
+ "pygments_lexer": "ipython3",
+ "version": "3.5.2"
}
},
"nbformat": 4,
diff --git a/docs/guide/ts_support.ipynb b/docs/guide/ts_support.ipynb
index f98d7b5..0c03548 100644
--- a/docs/guide/ts_support.ipynb
+++ b/docs/guide/ts_support.ipynb
@@ -114,7 +114,6 @@
"import stix2\n",
"\n",
"stix2.v20.Indicator()\n",
- "\n",
"stix2.v21.Indicator()"
]
},
@@ -169,9 +168,17 @@
},
{
"cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
+ "execution_count": 1,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "{\n \"type\": \"indicator\",\n \"id\": \"indicator--dbcbd659-c927-4f9a-994f-0a2632274394\",\n \"created\": \"2017-09-26T23:33:39.829Z\",\n \"modified\": \"2017-09-26T23:33:39.829Z\",\n \"name\": \"File hash for malware variant\",\n \"pattern\": \"[file:hashes.md5 = 'd41d8cd98f00b204e9800998ecf8427e']\",\n \"valid_from\": \"2017-09-26T23:33:39.829952Z\",\n \"labels\": [\n \"malicious-activity\"\n ]\n}\n"
+ ]
+ }
+ ],
"source": [
"from stix2 import parse\n",
"\n",
diff --git a/stix2/base.py b/stix2/base.py
index b0cf6ff..76b07b8 100644
--- a/stix2/base.py
+++ b/stix2/base.py
@@ -153,15 +153,7 @@ class _STIXBase(collections.Mapping):
super(_STIXBase, self).__setattr__(name, value)
def __str__(self):
- properties = self.object_properties()
-
- def sort_by(element):
- return find_property_index(self, properties, element)
-
- # separators kwarg -> don't include spaces after commas.
- return json.dumps(self, indent=4, cls=STIXJSONEncoder,
- item_sort_key=sort_by,
- separators=(",", ": "))
+ return self.serialize(pretty=True)
def __repr__(self):
props = [(k, self[k]) for k in self.object_properties() if self.get(k)]
@@ -185,6 +177,38 @@ class _STIXBase(collections.Mapping):
def revoke(self):
return _revoke(self)
+ def serialize(self, pretty=False, **kwargs):
+ """
+ Serialize a STIX object.
+
+ Args:
+ pretty (bool): If True, output properties following the STIX specs
+ formatting. This includes indentation. Refer to notes for more
+ details.
+ **kwargs: The arguments for a json.dumps() call.
+
+ Returns:
+ dict: The serialized JSON object.
+
+ Note:
+ The argument ``pretty=True`` will output the STIX object following
+ spec order. Using this argument greatly impacts object serialization
+ performance. If your use case is centered across machine-to-machine
+ operation it is recommended to set ``pretty=False``.
+
+ When ``pretty=True`` the following key-value pairs will be added or
+ overridden: indent=4, separators=(",", ": "), item_sort_key=sort_by.
+ """
+ if pretty:
+ properties = self.object_properties()
+
+ def sort_by(element):
+ return find_property_index(self, properties, element)
+
+ kwargs.update({'indent': 4, 'separators': (",", ": "), 'item_sort_key': sort_by})
+
+ return json.dumps(self, cls=STIXJSONEncoder, **kwargs)
+
class _Observable(_STIXBase):
diff --git a/stix2/sources/__init__.py b/stix2/sources/__init__.py
index 1fe9391..b3e8a29 100644
--- a/stix2/sources/__init__.py
+++ b/stix2/sources/__init__.py
@@ -11,8 +11,11 @@
|
"""
+from abc import ABCMeta, abstractmethod
import uuid
+from six import with_metaclass
+
from stix2.utils import deduplicate
@@ -21,94 +24,85 @@ def make_id():
class DataStore(object):
- """An implementer will create a concrete subclass from
- this class for the specific DataStore.
+ """An implementer can subclass to create custom behavior from
+ this class for the specific DataStores.
Args:
source (DataSource): An existing DataSource to use
as this DataStore's DataSource component
-
sink (DataSink): An existing DataSink to use
as this DataStore's DataSink component
Attributes:
id (str): A unique UUIDv4 to identify this DataStore.
-
source (DataSource): An object that implements DataSource class.
-
sink (DataSink): An object that implements DataSink class.
"""
def __init__(self, source=None, sink=None):
+ super(DataStore, self).__init__()
self.id = make_id()
self.source = source
self.sink = sink
- def get(self, stix_id, allow_custom=False):
+ def get(self, *args, **kwargs):
"""Retrieve the most recent version of a single STIX object by ID.
Translate get() call to the appropriate DataSource call.
Args:
stix_id (str): the id of the STIX object to retrieve.
- allow_custom (bool): whether to retrieve custom objects/properties
- or not. Default: False.
Returns:
stix_obj: the single most recent version of the STIX
object specified by the "id".
"""
- return self.source.get(stix_id, allow_custom=allow_custom)
+ return self.source.get(*args, **kwargs)
- def all_versions(self, stix_id, allow_custom=False):
+ def all_versions(self, *args, **kwargs):
"""Retrieve all versions of a single STIX object by ID.
- Implement: Translate all_versions() call to the appropriate DataSource call
+ Translate all_versions() call to the appropriate DataSource call.
Args:
stix_id (str): the id of the STIX object to retrieve.
- allow_custom (bool): whether to retrieve custom objects/properties
- or not. Default: False.
Returns:
stix_objs (list): a list of STIX objects
"""
- return self.source.all_versions(stix_id, allow_custom=allow_custom)
+ return self.source.all_versions(*args, **kwargs)
- def query(self, query=None, allow_custom=False):
+ def query(self, *args, **kwargs):
"""Retrieve STIX objects matching a set of filters.
- Implement: Specific data source API calls, processing,
- functionality required for retrieving query from the data source.
+ Translate query() call to the appropriate DataSource call.
Args:
query (list): a list of filters (which collectively are the query)
to conduct search on.
- allow_custom (bool): whether to retrieve custom objects/properties
- or not. Default: False.
Returns:
stix_objs (list): a list of STIX objects
"""
- return self.source.query(query=query)
+ return self.source.query(*args, **kwargs)
- def add(self, stix_objs, allow_custom=False):
- """Store STIX objects.
+ def add(self, *args, **kwargs):
+ """Method for storing STIX objects.
- Translates add() to the appropriate DataSink call.
+ Define custom behavior before storing STIX objects using the associated
+ DataSink. Translates add() to the appropriate DataSink call.
Args:
stix_objs (list): a list of STIX objects
- allow_custom (bool): whether to allow custom objects/properties or
- not. Default: False.
+
"""
- return self.sink.add(stix_objs, allow_custom=allow_custom)
+ return self.sink.add(*args, **kwargs)
-class DataSink(object):
+class DataSink(with_metaclass(ABCMeta)):
"""An implementer will create a concrete subclass from
this class for the specific DataSink.
@@ -117,10 +111,12 @@ class DataSink(object):
"""
def __init__(self):
+ super(DataSink, self).__init__()
self.id = make_id()
- def add(self, stix_objs, allow_custom=False):
- """Store STIX objects.
+ @abstractmethod
+ def add(self, stix_objs):
+ """Method for storing STIX objects.
Implement: Specific data sink API calls, processing,
functionality required for adding data to the sink
@@ -128,28 +124,26 @@ class DataSink(object):
Args:
stix_objs (list): a list of STIX objects (where each object is a
STIX object)
- allow_custom (bool): whether to allow custom objects/properties or
- not. Default: False.
"""
- raise NotImplementedError()
-class DataSource(object):
+class DataSource(with_metaclass(ABCMeta)):
"""An implementer will create a concrete subclass from
this class for the specific DataSource.
Attributes:
id (str): A unique UUIDv4 to identify this DataSource.
-
- _filters (set): A collection of filters attached to this DataSource.
+ filters (set): A collection of filters attached to this DataSource.
"""
def __init__(self):
+ super(DataSource, self).__init__()
self.id = make_id()
self.filters = set()
- def get(self, stix_id, _composite_filters=None, allow_custom=False):
+ @abstractmethod
+ def get(self, stix_id):
"""
Implement: Specific data source API calls, processing,
functionality required for retrieving data from the data source
@@ -158,21 +152,17 @@ class DataSource(object):
stix_id (str): the id of the STIX 2.0 object to retrieve. Should
return a single object, the most recent version of the object
specified by the "id".
- _composite_filters (set): set of filters passed from the parent
- the CompositeDataSource, not user supplied
- allow_custom (bool): whether to retrieve custom objects/properties
- or not. Default: False.
Returns:
stix_obj: the STIX object
"""
- raise NotImplementedError()
- def all_versions(self, stix_id, _composite_filters=None, allow_custom=False):
+ @abstractmethod
+ def all_versions(self, stix_id):
"""
- Implement: Similar to get() except returns list of all object versions of
- the specified "id". In addition, implement the specific data
+ Implement: Similar to get() except returns list of all object versions
+ of the specified "id". In addition, implement the specific data
source API calls, processing, functionality required for retrieving
data from the data source.
@@ -180,35 +170,26 @@ class DataSource(object):
stix_id (str): The id of the STIX 2.0 object to retrieve. Should
return a list of objects, all the versions of the object
specified by the "id".
- _composite_filters (set): set of filters passed from the parent
- CompositeDataSource, not user supplied
- allow_custom (bool): whether to retrieve custom objects/properties
- or not. Default: False.
Returns:
stix_objs (list): a list of STIX objects
"""
- raise NotImplementedError()
- def query(self, query=None, _composite_filters=None, allow_custom=False):
+ @abstractmethod
+ def query(self, query=None):
"""
- Implement:Implement the specific data source API calls, processing,
+ Implement: The specific data source API calls, processing,
functionality required for retrieving query from the data source
Args:
query (list): a list of filters (which collectively are the query)
- to conduct search on
- _composite_filters (set): a set of filters passed from the parent
- CompositeDataSource, not user supplied
- allow_custom (bool): whether to retrieve custom objects/properties
- or not. Default: False.
+ to conduct search on.
Returns:
stix_objs (list): a list of STIX objects
"""
- raise NotImplementedError()
class CompositeDataSource(DataSource):
@@ -224,7 +205,7 @@ class CompositeDataSource(DataSource):
Attributes:
- data_sources (dict): A dictionary of DataSource objects; to be
+ data_sources (list): A dictionary of DataSource objects; to be
controlled and used by the Data Source Controller object.
"""
@@ -237,7 +218,7 @@ class CompositeDataSource(DataSource):
super(CompositeDataSource, self).__init__()
self.data_sources = []
- def get(self, stix_id, _composite_filters=None, allow_custom=False):
+ def get(self, stix_id, _composite_filters=None):
"""Retrieve STIX object by STIX ID
Federated retrieve method, iterates through all DataSources
@@ -253,9 +234,7 @@ class CompositeDataSource(DataSource):
stix_id (str): the id of the STIX object to retrieve.
_composite_filters (list): a list of filters passed from a
CompositeDataSource (i.e. if this CompositeDataSource is attached
- to another parent CompositeDataSource), not user supplied
- allow_custom (bool): whether to retrieve custom objects/properties
- or not. Default: False.
+ to another parent CompositeDataSource), not user supplied.
Returns:
stix_obj: the STIX object to be returned.
@@ -273,7 +252,7 @@ class CompositeDataSource(DataSource):
# for every configured Data Source, call its retrieve handler
for ds in self.data_sources:
- data = ds.get(stix_id=stix_id, _composite_filters=all_filters, allow_custom=allow_custom)
+ data = ds.get(stix_id=stix_id, _composite_filters=all_filters)
if data:
all_data.append(data)
@@ -288,22 +267,20 @@ class CompositeDataSource(DataSource):
return stix_obj
- def all_versions(self, stix_id, _composite_filters=None, allow_custom=False):
- """Retrieve STIX objects by STIX ID
+ def all_versions(self, stix_id, _composite_filters=None):
+ """Retrieve all versions of a STIX object by STIX ID.
- Federated all_versions retrieve method - iterates through all DataSources
- defined in "data_sources"
+ Federated all_versions retrieve method - iterates through all
+ DataSources defined in "data_sources".
A composite data source will pass its attached filters to
- each configured data source, pushing filtering to them to handle
+ each configured data source, pushing filtering to them to handle.
Args:
- stix_id (str): id of the STIX objects to retrieve
+ stix_id (str): id of the STIX objects to retrieve.
_composite_filters (list): a list of filters passed from a
- CompositeDataSource (i.e. if this CompositeDataSource is attached
- to a parent CompositeDataSource), not user supplied
- allow_custom (bool): whether to retrieve custom objects/properties
- or not. Default: False.
+ CompositeDataSource (i.e. if this CompositeDataSource is
+ attached to a parent CompositeDataSource), not user supplied.
Returns:
all_data (list): list of STIX objects that have the specified id
@@ -322,7 +299,7 @@ class CompositeDataSource(DataSource):
# retrieve STIX objects from all configured data sources
for ds in self.data_sources:
- data = ds.all_versions(stix_id=stix_id, _composite_filters=all_filters, allow_custom=allow_custom)
+ data = ds.all_versions(stix_id=stix_id, _composite_filters=all_filters)
all_data.extend(data)
# remove exact duplicates (where duplicates are STIX 2.0 objects
@@ -332,19 +309,17 @@ class CompositeDataSource(DataSource):
return all_data
- def query(self, query=None, _composite_filters=None, allow_custom=False):
- """Retrieve STIX objects that match query
+ def query(self, query=None, _composite_filters=None):
+ """Retrieve STIX objects that match a query.
Federate the query to all DataSources attached to the
Composite Data Source.
Args:
- query (list): list of filters to search on
+ query (list): list of filters to search on.
_composite_filters (list): a list of filters passed from a
- CompositeDataSource (i.e. if this CompositeDataSource is attached
- to a parent CompositeDataSource), not user supplied
- allow_custom (bool): whether to retrieve custom objects/properties
- or not. Default: False.
+ CompositeDataSource (i.e. if this CompositeDataSource is
+ attached to a parent CompositeDataSource), not user supplied.
Returns:
all_data (list): list of STIX objects to be returned
@@ -354,7 +329,7 @@ class CompositeDataSource(DataSource):
raise AttributeError('CompositeDataSource has no data sources')
if not query:
- # dont mess with the query (i.e. convert to a set, as thats done
+ # don't mess with the query (i.e. convert to a set, as that's done
# within the specific DataSources that are called)
query = []
@@ -369,7 +344,7 @@ class CompositeDataSource(DataSource):
# federate query to all attached data sources,
# pass composite filters to id
for ds in self.data_sources:
- data = ds.query(query=query, _composite_filters=all_filters, allow_custom=allow_custom)
+ data = ds.query(query=query, _composite_filters=all_filters)
all_data.extend(data)
# remove exact duplicates (where duplicates are STIX 2.0
diff --git a/stix2/sources/filesystem.py b/stix2/sources/filesystem.py
index eb83d8c..e92c525 100644
--- a/stix2/sources/filesystem.py
+++ b/stix2/sources/filesystem.py
@@ -26,14 +26,15 @@ class FileSystemStore(DataStore):
Default: False.
Attributes:
- source (FileSystemSource): FuleSystemSource
+ source (FileSystemSource): FileSystemSource
sink (FileSystemSink): FileSystemSink
"""
def __init__(self, stix_dir, bundlify=False):
- super(FileSystemStore, self).__init__()
- self.source = FileSystemSource(stix_dir=stix_dir)
- self.sink = FileSystemSink(stix_dir=stix_dir, bundlify=bundlify)
+ super(FileSystemStore, self).__init__(
+ source=FileSystemSource(stix_dir=stix_dir),
+ sink=FileSystemSink(stix_dir=stix_dir, bundlify=bundlify)
+ )
class FileSystemSink(DataSink):
@@ -99,11 +100,11 @@ class FileSystemSink(DataSink):
self._check_path_and_write(stix_data)
elif isinstance(stix_data, (str, dict)):
- stix_data = parse(stix_data, allow_custom, version)
+ stix_data = parse(stix_data, allow_custom=allow_custom, version=version)
if stix_data["type"] == "bundle":
# extract STIX objects
for stix_obj in stix_data.get("objects", []):
- self.add(stix_obj)
+ self.add(stix_obj, allow_custom=allow_custom, version=version)
else:
# adding json-formatted STIX
self._check_path_and_write(stix_data)
@@ -111,12 +112,12 @@ class FileSystemSink(DataSink):
elif isinstance(stix_data, Bundle):
# recursively add individual STIX objects
for stix_obj in stix_data.get("objects", []):
- self.add(stix_obj)
+ self.add(stix_obj, allow_custom=allow_custom, version=version)
elif isinstance(stix_data, list):
# recursively add individual STIX objects
for stix_obj in stix_data:
- self.add(stix_obj)
+ self.add(stix_obj, allow_custom=allow_custom, version=version)
else:
raise TypeError("stix_data must be a STIX object (or list of), "
@@ -146,7 +147,7 @@ class FileSystemSource(DataSource):
def stix_dir(self):
return self._stix_dir
- def get(self, stix_id, _composite_filters=None, allow_custom=False, version=None):
+ def get(self, stix_id, allow_custom=False, version=None, _composite_filters=None):
"""Retrieve STIX object from file directory via STIX ID.
Args:
@@ -166,8 +167,7 @@ class FileSystemSource(DataSource):
"""
query = [Filter("id", "=", stix_id)]
- all_data = self.query(query=query, _composite_filters=_composite_filters,
- allow_custom=allow_custom, version=version)
+ all_data = self.query(query=query, allow_custom=allow_custom, version=version, _composite_filters=_composite_filters)
if all_data:
stix_obj = sorted(all_data, key=lambda k: k['modified'])[0]
@@ -176,7 +176,7 @@ class FileSystemSource(DataSource):
return stix_obj
- def all_versions(self, stix_id, _composite_filters=None, allow_custom=False, version=None):
+ def all_versions(self, stix_id, allow_custom=False, version=None, _composite_filters=None):
"""Retrieve STIX object from file directory via STIX ID, all versions.
Note: Since FileSystem sources/sinks don't handle multiple versions
@@ -197,10 +197,9 @@ class FileSystemSource(DataSource):
a python STIX objects and then returned
"""
- return [self.get(stix_id=stix_id, _composite_filters=_composite_filters,
- allow_custom=allow_custom, version=version)]
+ return [self.get(stix_id=stix_id, allow_custom=allow_custom, version=version, _composite_filters=_composite_filters)]
- def query(self, query=None, _composite_filters=None, allow_custom=False, version=None):
+ def query(self, query=None, allow_custom=False, version=None, _composite_filters=None):
"""Search and retrieve STIX objects based on the complete query.
A "complete query" includes the filters from the query, the filters
@@ -305,7 +304,7 @@ class FileSystemSource(DataSource):
all_data = deduplicate(all_data)
# parse python STIX objects from the STIX object dicts
- stix_objs = [parse(stix_obj_dict, allow_custom, version) for stix_obj_dict in all_data]
+ stix_objs = [parse(stix_obj_dict, allow_custom=allow_custom, version=version) for stix_obj_dict in all_data]
return stix_objs
diff --git a/stix2/sources/memory.py b/stix2/sources/memory.py
index 4d3943b..308d0d0 100644
--- a/stix2/sources/memory.py
+++ b/stix2/sources/memory.py
@@ -24,7 +24,7 @@ from stix2.sources import DataSink, DataSource, DataStore
from stix2.sources.filters import Filter, apply_common_filters
-def _add(store, stix_data=None, allow_custom=False):
+def _add(store, stix_data=None, allow_custom=False, version=None):
"""Add STIX objects to MemoryStore/Sink.
Adds STIX objects to an in-memory dictionary for fast lookup.
@@ -34,6 +34,8 @@ def _add(store, stix_data=None, allow_custom=False):
stix_data (list OR dict OR STIX object): STIX objects to be added
allow_custom (bool): whether to allow custom objects/properties or
not. Default: False.
+ version (str): Which STIX2 version to use. (e.g. "2.0", "2.1"). If
+ None, use latest version.
"""
if isinstance(stix_data, _STIXBase):
@@ -44,25 +46,25 @@ def _add(store, stix_data=None, allow_custom=False):
if stix_data["type"] == "bundle":
# adding a json bundle - so just grab STIX objects
for stix_obj in stix_data.get("objects", []):
- _add(store, stix_obj, allow_custom=allow_custom)
+ _add(store, stix_obj, allow_custom=allow_custom, version=version)
else:
# adding a json STIX object
store._data[stix_data["id"]] = stix_data
elif isinstance(stix_data, str):
# adding json encoded string of STIX content
- stix_data = parse(stix_data, allow_custom=allow_custom)
+ stix_data = parse(stix_data, allow_custom=allow_custom, version=version)
if stix_data["type"] == "bundle":
# recurse on each STIX object in bundle
for stix_obj in stix_data.get("objects", []):
- _add(store, stix_obj, allow_custom=allow_custom)
+ _add(store, stix_obj, allow_custom=allow_custom, version=version)
else:
- _add(store, stix_data)
+ _add(store, stix_data, allow_custom=allow_custom, version=version)
elif isinstance(stix_data, list):
# STIX objects are in a list- recurse on each object
for stix_obj in stix_data:
- _add(store, stix_obj, allow_custom=allow_custom)
+ _add(store, stix_obj, allow_custom=allow_custom, version=version)
else:
raise TypeError("stix_data must be a STIX object (or list of), JSON formatted STIX (or list of), or a JSON formatted STIX bundle")
@@ -81,6 +83,8 @@ class MemoryStore(DataStore):
stix_data (list OR dict OR STIX object): STIX content to be added
allow_custom (bool): whether to allow custom objects/properties or
not. Default: False.
+ version (str): Which STIX2 version to use. (e.g. "2.0", "2.1"). If
+ None, use latest version.
Attributes:
_data (dict): the in-memory dict that holds STIX objects
@@ -88,17 +92,18 @@ class MemoryStore(DataStore):
sink (MemorySink): MemorySink
"""
- def __init__(self, stix_data=None, allow_custom=False):
- super(MemoryStore, self).__init__()
+ def __init__(self, stix_data=None, allow_custom=False, version=None):
self._data = {}
if stix_data:
- _add(self, stix_data, allow_custom=allow_custom)
+ _add(self, stix_data, allow_custom=allow_custom, version=version)
- self.source = MemorySource(stix_data=self._data, _store=True, allow_custom=allow_custom)
- self.sink = MemorySink(stix_data=self._data, _store=True, allow_custom=allow_custom)
+ super(MemoryStore, self).__init__(
+ source=MemorySource(stix_data=self._data, allow_custom=allow_custom, version=version, _store=True),
+ sink=MemorySink(stix_data=self._data, allow_custom=allow_custom, version=version, _store=True)
+ )
- def save_to_file(self, file_path, allow_custom=False):
+ def save_to_file(self, *args, **kwargs):
"""Write SITX objects from in-memory dictionary to JSON file, as a STIX
Bundle.
@@ -108,9 +113,9 @@ class MemoryStore(DataStore):
not. Default: False.
"""
- return self.sink.save_to_file(file_path=file_path, allow_custom=allow_custom)
+ return self.sink.save_to_file(*args, **kwargs)
- def load_from_file(self, file_path, allow_custom=False):
+ def load_from_file(self, *args, **kwargs):
"""Load STIX data from JSON file.
File format is expected to be a single JSON
@@ -120,9 +125,11 @@ class MemoryStore(DataStore):
file_path (str): file path to load STIX data from
allow_custom (bool): whether to allow custom objects/properties or
not. Default: False.
+ version (str): Which STIX2 version to use. (e.g. "2.0", "2.1"). If
+ None, use latest version.
"""
- return self.source.load_from_file(file_path=file_path, allow_custom=allow_custom)
+ return self.source.load_from_file(*args, **kwargs)
class MemorySink(DataSink):
@@ -146,17 +153,17 @@ class MemorySink(DataSink):
a MemorySource
"""
- def __init__(self, stix_data=None, _store=False, allow_custom=False):
+ def __init__(self, stix_data=None, allow_custom=False, version=None, _store=False):
super(MemorySink, self).__init__()
self._data = {}
if _store:
self._data = stix_data
elif stix_data:
- _add(self, stix_data, allow_custom=allow_custom)
+ _add(self, stix_data, allow_custom=allow_custom, version=version)
- def add(self, stix_data, allow_custom=False):
- _add(self, stix_data, allow_custom=allow_custom)
+ def add(self, stix_data, allow_custom=False, version=None):
+ _add(self, stix_data, allow_custom=allow_custom, version=version)
add.__doc__ = _add.__doc__
def save_to_file(self, file_path, allow_custom=False):
@@ -190,24 +197,22 @@ class MemorySource(DataSource):
a MemorySink
"""
- def __init__(self, stix_data=None, _store=False, allow_custom=False):
+ def __init__(self, stix_data=None, allow_custom=False, version=None, _store=False):
super(MemorySource, self).__init__()
self._data = {}
if _store:
self._data = stix_data
elif stix_data:
- _add(self, stix_data, allow_custom=allow_custom)
+ _add(self, stix_data, allow_custom=allow_custom, version=version)
- def get(self, stix_id, _composite_filters=None, allow_custom=False):
+ def get(self, stix_id, _composite_filters=None):
"""Retrieve STIX object from in-memory dict via STIX ID.
Args:
stix_id (str): The STIX ID of the STIX object to be retrieved.
- composite_filters (set): set of filters passed from the parent
+ _composite_filters (set): set of filters passed from the parent
CompositeDataSource, not user supplied
- allow_custom (bool): whether to retrieve custom objects/properties
- or not. Default: False.
Returns:
(dict OR STIX object): STIX object that has the supplied
@@ -227,7 +232,7 @@ class MemorySource(DataSource):
# if there are filters from the composite level, process full query
query = [Filter("id", "=", stix_id)]
- all_data = self.query(query=query, _composite_filters=_composite_filters, allow_custom=allow_custom)
+ all_data = self.query(query=query, _composite_filters=_composite_filters)
if all_data:
# reduce to most recent version
@@ -237,7 +242,7 @@ class MemorySource(DataSource):
else:
return None
- def all_versions(self, stix_id, _composite_filters=None, allow_custom=False):
+ def all_versions(self, stix_id, _composite_filters=None):
"""Retrieve STIX objects from in-memory dict via STIX ID, all versions of it
Note: Since Memory sources/sinks don't handle multiple versions of a
@@ -245,10 +250,8 @@ class MemorySource(DataSource):
Args:
stix_id (str): The STIX ID of the STIX 2 object to retrieve.
- composite_filters (set): set of filters passed from the parent
+ _composite_filters (set): set of filters passed from the parent
CompositeDataSource, not user supplied
- allow_custom (bool): whether to retrieve custom objects/properties
- or not. Default: False.
Returns:
(list): list of STIX objects that has the supplied ID. As the
@@ -257,9 +260,9 @@ class MemorySource(DataSource):
is returned in the same form as it as added
"""
- return [self.get(stix_id=stix_id, _composite_filters=_composite_filters, allow_custom=allow_custom)]
+ return [self.get(stix_id=stix_id, _composite_filters=_composite_filters)]
- def query(self, query=None, _composite_filters=None, allow_custom=False):
+ def query(self, query=None, _composite_filters=None):
"""Search and retrieve STIX objects based on the complete query.
A "complete query" includes the filters from the query, the filters
@@ -268,10 +271,8 @@ class MemorySource(DataSource):
Args:
query (list): list of filters to search on
- composite_filters (set): set of filters passed from the
+ _composite_filters (set): set of filters passed from the
CompositeDataSource, not user supplied
- allow_custom (bool): whether to retrieve custom objects/properties
- or not. Default: False.
Returns:
(list): list of STIX objects that matches the supplied
@@ -284,7 +285,7 @@ class MemorySource(DataSource):
query = set()
else:
if not isinstance(query, list):
- # make sure dont make set from a Filter object,
+ # make sure don't make set from a Filter object,
# need to make a set from a list of Filter objects (even if just one Filter)
query = [query]
query = set(query)
@@ -300,8 +301,8 @@ class MemorySource(DataSource):
return all_data
- def load_from_file(self, file_path, allow_custom=False):
+ def load_from_file(self, file_path, allow_custom=False, version=None):
file_path = os.path.abspath(file_path)
stix_data = json.load(open(file_path, "r"))
- _add(self, stix_data, allow_custom=allow_custom)
+ _add(self, stix_data, allow_custom=allow_custom, version=version)
load_from_file.__doc__ = MemoryStore.load_from_file.__doc__
diff --git a/stix2/sources/taxii.py b/stix2/sources/taxii.py
index 414e27f..8eb5069 100644
--- a/stix2/sources/taxii.py
+++ b/stix2/sources/taxii.py
@@ -1,5 +1,5 @@
"""
-Python STIX 2.x TaxiiCollectionStore
+Python STIX 2.x TAXIICollectionStore
"""
from stix2.base import _STIXBase
@@ -20,9 +20,10 @@ class TAXIICollectionStore(DataStore):
collection (taxii2.Collection): TAXII Collection instance
"""
def __init__(self, collection):
- super(TAXIICollectionStore, self).__init__()
- self.source = TAXIICollectionSource(collection)
- self.sink = TAXIICollectionSink(collection)
+ super(TAXIICollectionStore, self).__init__(
+ source=TAXIICollectionSource(collection),
+ sink=TAXIICollectionSink(collection)
+ )
class TAXIICollectionSink(DataSink):
@@ -37,7 +38,7 @@ class TAXIICollectionSink(DataSink):
super(TAXIICollectionSink, self).__init__()
self.collection = collection
- def add(self, stix_data, allow_custom=False):
+ def add(self, stix_data, allow_custom=False, version=None):
"""Add/push STIX content to TAXII Collection endpoint
Args:
@@ -46,6 +47,8 @@ class TAXIICollectionSink(DataSink):
json encoded string, or list of any of the following
allow_custom (bool): whether to allow custom objects/properties or
not. Default: False.
+ version (str): Which STIX2 version to use. (e.g. "2.0", "2.1"). If
+ None, use latest version.
"""
if isinstance(stix_data, _STIXBase):
@@ -62,11 +65,11 @@ class TAXIICollectionSink(DataSink):
elif isinstance(stix_data, list):
# adding list of something - recurse on each
for obj in stix_data:
- self.add(obj, allow_custom=allow_custom)
+ self.add(obj, allow_custom=allow_custom, version=version)
elif isinstance(stix_data, str):
# adding json encoded string of STIX content
- stix_data = parse(stix_data, allow_custom=allow_custom)
+ stix_data = parse(stix_data, allow_custom=allow_custom, version=version)
if stix_data["type"] == "bundle":
bundle = dict(stix_data)
else:
@@ -90,16 +93,18 @@ class TAXIICollectionSource(DataSource):
super(TAXIICollectionSource, self).__init__()
self.collection = collection
- def get(self, stix_id, _composite_filters=None, allow_custom=False):
+ def get(self, stix_id, allow_custom=False, version=None, _composite_filters=None):
"""Retrieve STIX object from local/remote STIX Collection
endpoint.
Args:
stix_id (str): The STIX ID of the STIX object to be retrieved.
- composite_filters (set): set of filters passed from the parent
+ _composite_filters (set): set of filters passed from the parent
CompositeDataSource, not user supplied
allow_custom (bool): whether to retrieve custom objects/properties
or not. Default: False.
+ version (str): Which STIX2 version to use. (e.g. "2.0", "2.1"). If
+ None, use latest version.
Returns:
(STIX object): STIX object that has the supplied STIX ID.
@@ -121,7 +126,7 @@ class TAXIICollectionSource(DataSource):
stix_obj = list(apply_common_filters(stix_objs, query))
if len(stix_obj):
- stix_obj = parse(stix_obj[0], allow_custom=allow_custom)
+ stix_obj = parse(stix_obj[0], allow_custom=allow_custom, version=version)
if stix_obj.id != stix_id:
# check - was added to handle erroneous TAXII servers
stix_obj = None
@@ -130,16 +135,18 @@ class TAXIICollectionSource(DataSource):
return stix_obj
- def all_versions(self, stix_id, _composite_filters=None, allow_custom=False):
+ def all_versions(self, stix_id, allow_custom=False, version=None, _composite_filters=None):
"""Retrieve STIX object from local/remote TAXII Collection
endpoint, all versions of it
Args:
stix_id (str): The STIX ID of the STIX objects to be retrieved.
- composite_filters (set): set of filters passed from the parent
+ _composite_filters (set): set of filters passed from the parent
CompositeDataSource, not user supplied
allow_custom (bool): whether to retrieve custom objects/properties
or not. Default: False.
+ version (str): Which STIX2 version to use. (e.g. "2.0", "2.1"). If
+ None, use latest version.
Returns:
(see query() as all_versions() is just a wrapper)
@@ -151,17 +158,17 @@ class TAXIICollectionSource(DataSource):
Filter("match[version]", "=", "all")
]
- all_data = self.query(query=query, _composite_filters=_composite_filters, allow_custom=allow_custom)
+ all_data = self.query(query=query, allow_custom=allow_custom, _composite_filters=_composite_filters)
# parse STIX objects from TAXII returned json
- all_data = [parse(stix_obj) for stix_obj in all_data]
+ all_data = [parse(stix_obj, allow_custom=allow_custom, version=version) for stix_obj in all_data]
# check - was added to handle erroneous TAXII servers
all_data_clean = [stix_obj for stix_obj in all_data if stix_obj.id == stix_id]
return all_data_clean
- def query(self, query=None, _composite_filters=None, allow_custom=False):
+ def query(self, query=None, allow_custom=False, version=None, _composite_filters=None):
"""Search and retreive STIX objects based on the complete query
A "complete query" includes the filters from the query, the filters
@@ -170,10 +177,12 @@ class TAXIICollectionSource(DataSource):
Args:
query (list): list of filters to search on
- composite_filters (set): set of filters passed from the
+ _composite_filters (set): set of filters passed from the
CompositeDataSource, not user supplied
allow_custom (bool): whether to retrieve custom objects/properties
or not. Default: False.
+ version (str): Which STIX2 version to use. (e.g. "2.0", "2.1"). If
+ None, use latest version.
Returns:
(list): list of STIX objects that matches the supplied
@@ -200,7 +209,7 @@ class TAXIICollectionSource(DataSource):
taxii_filters = self._parse_taxii_filters(query)
# query TAXII collection
- all_data = self.collection.get_objects(filters=taxii_filters, allow_custom=allow_custom)["objects"]
+ all_data = self.collection.get_objects(filters=taxii_filters)["objects"]
# deduplicate data (before filtering as reduces wasted filtering)
all_data = deduplicate(all_data)
@@ -209,7 +218,7 @@ class TAXIICollectionSource(DataSource):
all_data = list(apply_common_filters(all_data, query))
# parse python STIX objects from the STIX object dicts
- stix_objs = [parse(stix_obj_dict, allow_custom=allow_custom) for stix_obj_dict in all_data]
+ stix_objs = [parse(stix_obj_dict, allow_custom=allow_custom, version=version) for stix_obj_dict in all_data]
return stix_objs
| Update DataStores, Sources, Sinks
While working #98 I noticed even further problems with how the stores work. In addition to the fixes, I will adding:
- Proper ABC for DataStore, DataStore, and DataSink.
- The version positional argument was missing in a lot of places.
| oasis-open/cti-python-stix2 | diff --git a/stix2/test/test_bundle.py b/stix2/test/test_bundle.py
index b1cffd0..8b14172 100644
--- a/stix2/test/test_bundle.py
+++ b/stix2/test/test_bundle.py
@@ -1,8 +1,9 @@
+import json
+
import pytest
import stix2
-
EXPECTED_BUNDLE = """{
"type": "bundle",
"id": "bundle--00000000-0000-0000-0000-000000000004",
@@ -41,6 +42,44 @@ EXPECTED_BUNDLE = """{
]
}"""
+EXPECTED_BUNDLE_DICT = {
+ "type": "bundle",
+ "id": "bundle--00000000-0000-0000-0000-000000000004",
+ "spec_version": "2.0",
+ "objects": [
+ {
+ "type": "indicator",
+ "id": "indicator--00000000-0000-0000-0000-000000000001",
+ "created": "2017-01-01T12:34:56.000Z",
+ "modified": "2017-01-01T12:34:56.000Z",
+ "pattern": "[file:hashes.MD5 = 'd41d8cd98f00b204e9800998ecf8427e']",
+ "valid_from": "2017-01-01T12:34:56Z",
+ "labels": [
+ "malicious-activity"
+ ]
+ },
+ {
+ "type": "malware",
+ "id": "malware--00000000-0000-0000-0000-000000000002",
+ "created": "2017-01-01T12:34:56.000Z",
+ "modified": "2017-01-01T12:34:56.000Z",
+ "name": "Cryptolocker",
+ "labels": [
+ "ransomware"
+ ]
+ },
+ {
+ "type": "relationship",
+ "id": "relationship--00000000-0000-0000-0000-000000000003",
+ "created": "2017-01-01T12:34:56.000Z",
+ "modified": "2017-01-01T12:34:56.000Z",
+ "relationship_type": "indicates",
+ "source_ref": "indicator--01234567-89ab-cdef-0123-456789abcdef",
+ "target_ref": "malware--fedcba98-7654-3210-fedc-ba9876543210"
+ }
+ ]
+}
+
def test_empty_bundle():
bundle = stix2.Bundle()
@@ -82,10 +121,17 @@ def test_bundle_with_wrong_spec_version():
assert str(excinfo.value) == "Invalid value for Bundle 'spec_version': must equal '2.0'."
-def test_create_bundle(indicator, malware, relationship):
+def test_create_bundle1(indicator, malware, relationship):
bundle = stix2.Bundle(objects=[indicator, malware, relationship])
assert str(bundle) == EXPECTED_BUNDLE
+ assert bundle.serialize(pretty=True) == EXPECTED_BUNDLE
+
+
+def test_create_bundle2(indicator, malware, relationship):
+ bundle = stix2.Bundle(objects=[indicator, malware, relationship])
+
+ assert json.loads(bundle.serialize()) == EXPECTED_BUNDLE_DICT
def test_create_bundle_with_positional_args(indicator, malware, relationship):
diff --git a/stix2/test/test_data_sources.py b/stix2/test/test_data_sources.py
index 3327ca9..ef0cf26 100644
--- a/stix2/test/test_data_sources.py
+++ b/stix2/test/test_data_sources.py
@@ -1,9 +1,9 @@
import pytest
from taxii2client import Collection
-from stix2 import Filter, MemorySource
-from stix2.sources import (CompositeDataSource, DataSink, DataSource,
- DataStore, make_id, taxii)
+from stix2 import Filter, MemorySink, MemorySource
+from stix2.sources import (CompositeDataSource, DataSink, DataSource, make_id,
+ taxii)
from stix2.sources.filters import apply_common_filters
from stix2.utils import deduplicate
@@ -20,11 +20,6 @@ def collection():
return Collection(COLLECTION_URL, MockTAXIIClient())
[email protected]
-def ds():
- return DataSource()
-
-
IND1 = {
"created": "2017-01-27T13:49:53.935Z",
"id": "indicator--d81f86b9-975b-bc0b-775e-810c5ad45a4f",
@@ -127,21 +122,11 @@ STIX_OBJS1 = [IND1, IND2, IND3, IND4, IND5]
def test_ds_abstract_class_smoke():
- ds1 = DataSource()
- ds2 = DataSink()
- ds3 = DataStore(source=ds1, sink=ds2)
-
- with pytest.raises(NotImplementedError):
- ds3.add(None)
-
- with pytest.raises(NotImplementedError):
- ds3.all_versions("malware--fdd60b30-b67c-11e3-b0b9-f01faf20d111")
-
- with pytest.raises(NotImplementedError):
- ds3.get("malware--fdd60b30-b67c-11e3-b0b9-f01faf20d111")
+ with pytest.raises(TypeError):
+ DataSource()
- with pytest.raises(NotImplementedError):
- ds3.query([Filter("id", "=", "malware--fdd60b30-b67c-11e3-b0b9-f01faf20d111")])
+ with pytest.raises(TypeError):
+ DataSink()
def test_ds_taxii(collection):
@@ -177,7 +162,8 @@ def test_parse_taxii_filters():
assert taxii_filters == expected_params
-def test_add_get_remove_filter(ds):
+def test_add_get_remove_filter():
+ ds = taxii.TAXIICollectionSource(collection)
# First 3 filters are valid, remaining properties are erroneous in some way
valid_filters = [
@@ -226,7 +212,7 @@ def test_add_get_remove_filter(ds):
ds.filters.update(valid_filters)
-def test_apply_common_filters(ds):
+def test_apply_common_filters():
stix_objs = [
{
"created": "2017-01-27T13:49:53.997Z",
@@ -374,35 +360,35 @@ def test_apply_common_filters(ds):
assert len(resp) == 0
-def test_filters0(ds):
+def test_filters0():
# "Return any object modified before 2017-01-28T13:49:53.935Z"
resp = list(apply_common_filters(STIX_OBJS2, [Filter("modified", "<", "2017-01-28T13:49:53.935Z")]))
assert resp[0]['id'] == STIX_OBJS2[1]['id']
assert len(resp) == 2
-def test_filters1(ds):
+def test_filters1():
# "Return any object modified after 2017-01-28T13:49:53.935Z"
resp = list(apply_common_filters(STIX_OBJS2, [Filter("modified", ">", "2017-01-28T13:49:53.935Z")]))
assert resp[0]['id'] == STIX_OBJS2[0]['id']
assert len(resp) == 1
-def test_filters2(ds):
+def test_filters2():
# "Return any object modified after or on 2017-01-28T13:49:53.935Z"
resp = list(apply_common_filters(STIX_OBJS2, [Filter("modified", ">=", "2017-01-27T13:49:53.935Z")]))
assert resp[0]['id'] == STIX_OBJS2[0]['id']
assert len(resp) == 3
-def test_filters3(ds):
+def test_filters3():
# "Return any object modified before or on 2017-01-28T13:49:53.935Z"
resp = list(apply_common_filters(STIX_OBJS2, [Filter("modified", "<=", "2017-01-27T13:49:53.935Z")]))
assert resp[0]['id'] == STIX_OBJS2[1]['id']
assert len(resp) == 2
-def test_filters4(ds):
+def test_filters4():
# Assert invalid Filter cannot be created
with pytest.raises(ValueError) as excinfo:
Filter("modified", "?", "2017-01-27T13:49:53.935Z")
@@ -410,21 +396,21 @@ def test_filters4(ds):
"for specified property: 'modified'")
-def test_filters5(ds):
+def test_filters5():
# "Return any object whose id is not indicator--d81f86b8-975b-bc0b-775e-810c5ad45a4f"
resp = list(apply_common_filters(STIX_OBJS2, [Filter("id", "!=", "indicator--d81f86b8-975b-bc0b-775e-810c5ad45a4f")]))
assert resp[0]['id'] == STIX_OBJS2[0]['id']
assert len(resp) == 1
-def test_filters6(ds):
+def test_filters6():
# Test filtering on non-common property
resp = list(apply_common_filters(STIX_OBJS2, [Filter("name", "=", "Malicious site hosting downloader")]))
assert resp[0]['id'] == STIX_OBJS2[0]['id']
assert len(resp) == 3
-def test_filters7(ds):
+def test_filters7():
# Test filtering on embedded property
stix_objects = list(STIX_OBJS2) + [{
"type": "observed-data",
@@ -463,7 +449,7 @@ def test_filters7(ds):
assert len(resp) == 1
-def test_deduplicate(ds):
+def test_deduplicate():
unique = deduplicate(STIX_OBJS1)
# Only 3 objects are unique
@@ -483,14 +469,14 @@ def test_deduplicate(ds):
def test_add_remove_composite_datasource():
cds = CompositeDataSource()
- ds1 = DataSource()
- ds2 = DataSource()
- ds3 = DataSink()
+ ds1 = MemorySource()
+ ds2 = MemorySource()
+ ds3 = MemorySink()
with pytest.raises(TypeError) as excinfo:
cds.add_data_sources([ds1, ds2, ds1, ds3])
assert str(excinfo.value) == ("DataSource (to be added) is not of type "
- "stix2.DataSource. DataSource type is '<class 'stix2.sources.DataSink'>'")
+ "stix2.DataSource. DataSource type is '<class 'stix2.sources.memory.MemorySink'>'")
cds.add_data_sources([ds1, ds2, ds1])
@@ -506,29 +492,58 @@ def test_composite_datasource_operations():
objects=STIX_OBJS1,
spec_version="2.0",
type="bundle")
- cds = CompositeDataSource()
- ds1 = MemorySource(stix_data=BUNDLE1)
- ds2 = MemorySource(stix_data=STIX_OBJS2)
+ cds1 = CompositeDataSource()
+ ds1_1 = MemorySource(stix_data=BUNDLE1)
+ ds1_2 = MemorySource(stix_data=STIX_OBJS2)
+
+ cds2 = CompositeDataSource()
+ ds2_1 = MemorySource(stix_data=BUNDLE1)
+ ds2_2 = MemorySource(stix_data=STIX_OBJS2)
- cds.add_data_sources([ds1, ds2])
+ cds1.add_data_sources([ds1_1, ds1_2])
+ cds2.add_data_sources([ds2_1, ds2_2])
- indicators = cds.all_versions("indicator--d81f86b9-975b-bc0b-775e-810c5ad45a4f")
+ indicators = cds1.all_versions("indicator--d81f86b9-975b-bc0b-775e-810c5ad45a4f")
# In STIX_OBJS2 changed the 'modified' property to a later time...
assert len(indicators) == 2
- indicator = cds.get("indicator--d81f86b9-975b-bc0b-775e-810c5ad45a4f")
+ cds1.add_data_sources([cds2])
+
+ indicator = cds1.get("indicator--d81f86b9-975b-bc0b-775e-810c5ad45a4f")
assert indicator["id"] == "indicator--d81f86b9-975b-bc0b-775e-810c5ad45a4f"
assert indicator["modified"] == "2017-01-31T13:49:53.935Z"
assert indicator["type"] == "indicator"
- query = [
+ query1 = [
Filter("type", "=", "indicator")
]
- results = cds.query(query)
+ query2 = [
+ Filter("valid_from", "=", "2017-01-27T13:49:53.935382Z")
+ ]
+
+ cds1.filters.update(query2)
+
+ results = cds1.query(query1)
# STIX_OBJS2 has indicator with later time, one with different id, one with
# original time in STIX_OBJS1
assert len(results) == 3
+
+ indicator = cds1.get("indicator--d81f86b9-975b-bc0b-775e-810c5ad45a4f")
+
+ assert indicator["id"] == "indicator--d81f86b9-975b-bc0b-775e-810c5ad45a4f"
+ assert indicator["modified"] == "2017-01-31T13:49:53.935Z"
+ assert indicator["type"] == "indicator"
+
+ # There is only one indicator with different ID. Since we use the same data
+ # when deduplicated, only two indicators (one with different modified).
+ results = cds1.all_versions("indicator--d81f86b9-975b-bc0b-775e-810c5ad45a4f")
+ assert len(results) == 2
+
+ # Since we have filters already associated with our CompositeSource providing
+ # nothing returns the same as cds1.query(query1) (the associated query is query2)
+ results = cds1.query([])
+ assert len(results) == 3
diff --git a/stix2/test/test_filesystem.py b/stix2/test/test_filesystem.py
index 7aaa3f5..85f6966 100644
--- a/stix2/test/test_filesystem.py
+++ b/stix2/test/test_filesystem.py
@@ -340,7 +340,7 @@ def test_filesystem_object_with_custom_property(fs_store):
fs_store.add(camp, True)
- camp_r = fs_store.get(camp.id, True)
+ camp_r = fs_store.get(camp.id, allow_custom=True)
assert camp_r.id == camp.id
assert camp_r.x_empire == camp.x_empire
@@ -352,9 +352,9 @@ def test_filesystem_object_with_custom_property_in_bundle(fs_store):
allow_custom=True)
bundle = Bundle(camp, allow_custom=True)
- fs_store.add(bundle, True)
+ fs_store.add(bundle, allow_custom=True)
- camp_r = fs_store.get(camp.id, True)
+ camp_r = fs_store.get(camp.id, allow_custom=True)
assert camp_r.id == camp.id
assert camp_r.x_empire == camp.x_empire
@@ -367,9 +367,9 @@ def test_filesystem_custom_object(fs_store):
pass
newobj = NewObj(property1='something')
- fs_store.add(newobj, True)
+ fs_store.add(newobj, allow_custom=True)
- newobj_r = fs_store.get(newobj.id, True)
+ newobj_r = fs_store.get(newobj.id, allow_custom=True)
assert newobj_r.id == newobj.id
assert newobj_r.property1 == 'something'
diff --git a/stix2/test/test_identity.py b/stix2/test/test_identity.py
index a9415fe..8e3dd42 100644
--- a/stix2/test/test_identity.py
+++ b/stix2/test/test_identity.py
@@ -62,4 +62,15 @@ def test_parse_no_type():
"identity_class": "individual"
}""")
+
+def test_identity_with_custom():
+ identity = stix2.Identity(
+ name="John Smith",
+ identity_class="individual",
+ custom_properties={'x_foo': 'bar'}
+ )
+
+ assert identity.x_foo == "bar"
+ assert "x_foo" in identity.object_properties()
+
# TODO: Add other examples
diff --git a/stix2/test/test_memory.py b/stix2/test/test_memory.py
index 7a00029..6b1219e 100644
--- a/stix2/test/test_memory.py
+++ b/stix2/test/test_memory.py
@@ -254,7 +254,7 @@ def test_memory_store_object_with_custom_property(mem_store):
mem_store.add(camp, True)
- camp_r = mem_store.get(camp.id, True)
+ camp_r = mem_store.get(camp.id)
assert camp_r.id == camp.id
assert camp_r.x_empire == camp.x_empire
@@ -268,7 +268,7 @@ def test_memory_store_object_with_custom_property_in_bundle(mem_store):
bundle = Bundle(camp, allow_custom=True)
mem_store.add(bundle, True)
- bundle_r = mem_store.get(bundle.id, True)
+ bundle_r = mem_store.get(bundle.id)
camp_r = bundle_r['objects'][0]
assert camp_r.id == camp.id
assert camp_r.x_empire == camp.x_empire
@@ -284,6 +284,6 @@ def test_memory_store_custom_object(mem_store):
newobj = NewObj(property1='something')
mem_store.add(newobj, True)
- newobj_r = mem_store.get(newobj.id, True)
+ newobj_r = mem_store.get(newobj.id)
assert newobj_r.id == newobj.id
assert newobj_r.property1 == 'something'
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_issue_reference",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 2,
"test_score": 2
},
"num_modified_files": 7
} | 0.3 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest pytest-cov",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.6",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | alabaster==0.7.13
antlr4-python3-runtime==4.9.3
async-generator==1.10
attrs==22.2.0
Babel==2.11.0
bleach==4.1.0
bump2version==1.0.1
bumpversion==0.6.0
certifi==2021.5.30
cfgv==3.3.1
charset-normalizer==2.0.12
coverage==6.2
decorator==5.1.1
defusedxml==0.7.1
distlib==0.3.9
docutils==0.18.1
entrypoints==0.4
filelock==3.4.1
identify==2.4.4
idna==3.10
imagesize==1.4.1
importlib-metadata==4.8.3
importlib-resources==5.2.3
iniconfig==1.1.1
ipython-genutils==0.2.0
Jinja2==3.0.3
jsonschema==3.2.0
jupyter-client==7.1.2
jupyter-core==4.9.2
jupyterlab-pygments==0.1.2
MarkupSafe==2.0.1
mistune==0.8.4
nbclient==0.5.9
nbconvert==6.0.7
nbformat==5.1.3
nbsphinx==0.8.8
nest-asyncio==1.6.0
nodeenv==1.6.0
packaging==21.3
pandocfilters==1.5.1
platformdirs==2.4.0
pluggy==1.0.0
pre-commit==2.17.0
py==1.11.0
Pygments==2.14.0
pyparsing==3.1.4
pyrsistent==0.18.0
pytest==7.0.1
pytest-cov==4.0.0
python-dateutil==2.9.0.post0
pytz==2025.2
PyYAML==6.0.1
pyzmq==25.1.2
requests==2.27.1
simplejson==3.20.1
six==1.17.0
snowballstemmer==2.2.0
Sphinx==5.3.0
sphinx-prompt==1.5.0
sphinxcontrib-applehelp==1.0.2
sphinxcontrib-devhelp==1.0.2
sphinxcontrib-htmlhelp==2.0.0
sphinxcontrib-jsmath==1.0.1
sphinxcontrib-qthelp==1.0.3
sphinxcontrib-serializinghtml==1.1.5
-e git+https://github.com/oasis-open/cti-python-stix2.git@5aa8c66bfc8b03dd76ff97ae3462c791d5861406#egg=stix2
stix2-patterns==2.0.0
taxii2-client==2.3.0
testpath==0.6.0
toml==0.10.2
tomli==1.2.3
tornado==6.1
tox==3.28.0
traitlets==4.3.3
typing_extensions==4.1.1
urllib3==1.26.20
virtualenv==20.16.2
webencodings==0.5.1
zipp==3.6.0
| name: cti-python-stix2
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- alabaster==0.7.13
- antlr4-python3-runtime==4.9.3
- async-generator==1.10
- attrs==22.2.0
- babel==2.11.0
- bleach==4.1.0
- bump2version==1.0.1
- bumpversion==0.6.0
- cfgv==3.3.1
- charset-normalizer==2.0.12
- coverage==6.2
- decorator==5.1.1
- defusedxml==0.7.1
- distlib==0.3.9
- docutils==0.18.1
- entrypoints==0.4
- filelock==3.4.1
- identify==2.4.4
- idna==3.10
- imagesize==1.4.1
- importlib-metadata==4.8.3
- importlib-resources==5.2.3
- iniconfig==1.1.1
- ipython-genutils==0.2.0
- jinja2==3.0.3
- jsonschema==3.2.0
- jupyter-client==7.1.2
- jupyter-core==4.9.2
- jupyterlab-pygments==0.1.2
- markupsafe==2.0.1
- mistune==0.8.4
- nbclient==0.5.9
- nbconvert==6.0.7
- nbformat==5.1.3
- nbsphinx==0.8.8
- nest-asyncio==1.6.0
- nodeenv==1.6.0
- packaging==21.3
- pandocfilters==1.5.1
- platformdirs==2.4.0
- pluggy==1.0.0
- pre-commit==2.17.0
- py==1.11.0
- pygments==2.14.0
- pyparsing==3.1.4
- pyrsistent==0.18.0
- pytest==7.0.1
- pytest-cov==4.0.0
- python-dateutil==2.9.0.post0
- pytz==2025.2
- pyyaml==6.0.1
- pyzmq==25.1.2
- requests==2.27.1
- simplejson==3.20.1
- six==1.17.0
- snowballstemmer==2.2.0
- sphinx==5.3.0
- sphinx-prompt==1.5.0
- sphinxcontrib-applehelp==1.0.2
- sphinxcontrib-devhelp==1.0.2
- sphinxcontrib-htmlhelp==2.0.0
- sphinxcontrib-jsmath==1.0.1
- sphinxcontrib-qthelp==1.0.3
- sphinxcontrib-serializinghtml==1.1.5
- stix2-patterns==2.0.0
- taxii2-client==2.3.0
- testpath==0.6.0
- toml==0.10.2
- tomli==1.2.3
- tornado==6.1
- tox==3.28.0
- traitlets==4.3.3
- typing-extensions==4.1.1
- urllib3==1.26.20
- virtualenv==20.16.2
- webencodings==0.5.1
- zipp==3.6.0
prefix: /opt/conda/envs/cti-python-stix2
| [
"stix2/test/test_bundle.py::test_create_bundle1",
"stix2/test/test_bundle.py::test_create_bundle2",
"stix2/test/test_data_sources.py::test_ds_abstract_class_smoke"
]
| []
| [
"stix2/test/test_bundle.py::test_empty_bundle",
"stix2/test/test_bundle.py::test_bundle_with_wrong_type",
"stix2/test/test_bundle.py::test_bundle_id_must_start_with_bundle",
"stix2/test/test_bundle.py::test_bundle_with_wrong_spec_version",
"stix2/test/test_bundle.py::test_create_bundle_with_positional_args",
"stix2/test/test_bundle.py::test_create_bundle_with_positional_listarg",
"stix2/test/test_bundle.py::test_create_bundle_with_listarg_and_positional_arg",
"stix2/test/test_bundle.py::test_create_bundle_with_listarg_and_kwarg",
"stix2/test/test_bundle.py::test_create_bundle_with_arg_listarg_and_kwarg",
"stix2/test/test_bundle.py::test_create_bundle_invalid",
"stix2/test/test_bundle.py::test_parse_bundle[2.0]",
"stix2/test/test_bundle.py::test_parse_unknown_type",
"stix2/test/test_bundle.py::test_stix_object_property",
"stix2/test/test_data_sources.py::test_ds_taxii",
"stix2/test/test_data_sources.py::test_ds_taxii_name",
"stix2/test/test_data_sources.py::test_parse_taxii_filters",
"stix2/test/test_data_sources.py::test_add_get_remove_filter",
"stix2/test/test_data_sources.py::test_apply_common_filters",
"stix2/test/test_data_sources.py::test_filters0",
"stix2/test/test_data_sources.py::test_filters1",
"stix2/test/test_data_sources.py::test_filters2",
"stix2/test/test_data_sources.py::test_filters3",
"stix2/test/test_data_sources.py::test_filters4",
"stix2/test/test_data_sources.py::test_filters5",
"stix2/test/test_data_sources.py::test_filters6",
"stix2/test/test_data_sources.py::test_filters7",
"stix2/test/test_data_sources.py::test_deduplicate",
"stix2/test/test_data_sources.py::test_add_remove_composite_datasource",
"stix2/test/test_data_sources.py::test_composite_datasource_operations",
"stix2/test/test_filesystem.py::test_filesystem_source_nonexistent_folder",
"stix2/test/test_filesystem.py::test_filesystem_sink_nonexistent_folder",
"stix2/test/test_filesystem.py::test_filesytem_source_get_object",
"stix2/test/test_filesystem.py::test_filesytem_source_get_nonexistent_object",
"stix2/test/test_filesystem.py::test_filesytem_source_all_versions",
"stix2/test/test_filesystem.py::test_filesytem_source_query_single",
"stix2/test/test_filesystem.py::test_filesytem_source_query_multiple",
"stix2/test/test_filesystem.py::test_filesystem_sink_add_python_stix_object",
"stix2/test/test_filesystem.py::test_filesystem_sink_add_stix_object_dict",
"stix2/test/test_filesystem.py::test_filesystem_sink_add_stix_bundle_dict",
"stix2/test/test_filesystem.py::test_filesystem_sink_add_json_stix_object",
"stix2/test/test_filesystem.py::test_filesystem_sink_json_stix_bundle",
"stix2/test/test_filesystem.py::test_filesystem_sink_add_objects_list",
"stix2/test/test_filesystem.py::test_filesystem_store_get_stored_as_bundle",
"stix2/test/test_filesystem.py::test_filesystem_store_get_stored_as_object",
"stix2/test/test_filesystem.py::test_filesystem_store_all_versions",
"stix2/test/test_filesystem.py::test_filesystem_store_query",
"stix2/test/test_filesystem.py::test_filesystem_store_query_single_filter",
"stix2/test/test_filesystem.py::test_filesystem_store_empty_query",
"stix2/test/test_filesystem.py::test_filesystem_store_query_multiple_filters",
"stix2/test/test_filesystem.py::test_filesystem_store_query_dont_include_type_folder",
"stix2/test/test_filesystem.py::test_filesystem_store_add",
"stix2/test/test_filesystem.py::test_filesystem_store_add_as_bundle",
"stix2/test/test_filesystem.py::test_filesystem_add_bundle_object",
"stix2/test/test_filesystem.py::test_filesystem_store_add_invalid_object",
"stix2/test/test_filesystem.py::test_filesystem_object_with_custom_property",
"stix2/test/test_filesystem.py::test_filesystem_object_with_custom_property_in_bundle",
"stix2/test/test_filesystem.py::test_filesystem_custom_object",
"stix2/test/test_identity.py::test_identity_example",
"stix2/test/test_identity.py::test_parse_identity[{\\n",
"stix2/test/test_identity.py::test_parse_identity[data1]",
"stix2/test/test_identity.py::test_parse_no_type",
"stix2/test/test_identity.py::test_identity_with_custom",
"stix2/test/test_memory.py::test_memory_source_get",
"stix2/test/test_memory.py::test_memory_source_get_nonexistant_object",
"stix2/test/test_memory.py::test_memory_store_all_versions",
"stix2/test/test_memory.py::test_memory_store_query",
"stix2/test/test_memory.py::test_memory_store_query_single_filter",
"stix2/test/test_memory.py::test_memory_store_query_empty_query",
"stix2/test/test_memory.py::test_memory_store_query_multiple_filters",
"stix2/test/test_memory.py::test_memory_store_save_load_file",
"stix2/test/test_memory.py::test_memory_store_add_stix_object_str",
"stix2/test/test_memory.py::test_memory_store_add_stix_bundle_str",
"stix2/test/test_memory.py::test_memory_store_add_invalid_object",
"stix2/test/test_memory.py::test_memory_store_object_with_custom_property",
"stix2/test/test_memory.py::test_memory_store_object_with_custom_property_in_bundle",
"stix2/test/test_memory.py::test_memory_store_custom_object"
]
| []
| BSD 3-Clause "New" or "Revised" License | 1,847 | [
"stix2/base.py",
"stix2/sources/__init__.py",
"docs/guide/ts_support.ipynb",
"docs/guide/custom.ipynb",
"stix2/sources/taxii.py",
"stix2/sources/memory.py",
"stix2/sources/filesystem.py"
]
| [
"stix2/base.py",
"stix2/sources/__init__.py",
"docs/guide/ts_support.ipynb",
"docs/guide/custom.ipynb",
"stix2/sources/taxii.py",
"stix2/sources/memory.py",
"stix2/sources/filesystem.py"
]
|
|
tox-dev__tox-travis-83 | ffe844135832585a8bad0b5bd56edecbb47ba654 | 2017-11-04 04:37:52 | ffe844135832585a8bad0b5bd56edecbb47ba654 | codecov-io: # [Codecov](https://codecov.io/gh/tox-dev/tox-travis/pull/83?src=pr&el=h1) Report
> Merging [#83](https://codecov.io/gh/tox-dev/tox-travis/pull/83?src=pr&el=desc) into [master](https://codecov.io/gh/tox-dev/tox-travis/commit/ffe844135832585a8bad0b5bd56edecbb47ba654?src=pr&el=desc) will **decrease** coverage by `0.42%`.
> The diff coverage is `63.63%`.
[](https://codecov.io/gh/tox-dev/tox-travis/pull/83?src=pr&el=tree)
```diff
@@ Coverage Diff @@
## master #83 +/- ##
==========================================
- Coverage 77.27% 76.84% -0.43%
==========================================
Files 5 5
Lines 198 203 +5
Branches 46 48 +2
==========================================
+ Hits 153 156 +3
- Misses 38 40 +2
Partials 7 7
```
| [Impacted Files](https://codecov.io/gh/tox-dev/tox-travis/pull/83?src=pr&el=tree) | Coverage Δ | |
|---|---|---|
| [src/tox\_travis/after.py](https://codecov.io/gh/tox-dev/tox-travis/pull/83?src=pr&el=tree#diff-c3JjL3RveF90cmF2aXMvYWZ0ZXIucHk=) | `56.47% <0%> (-1.37%)` | :arrow_down: |
| [src/tox\_travis/detect.py](https://codecov.io/gh/tox-dev/tox-travis/pull/83?src=pr&el=tree#diff-c3JjL3RveF90cmF2aXMvZGV0ZWN0LnB5) | `95.5% <100%> (ø)` | |
| [src/tox\_travis/hooks.py](https://codecov.io/gh/tox-dev/tox-travis/pull/83?src=pr&el=tree#diff-c3JjL3RveF90cmF2aXMvaG9va3MucHk=) | `86.66% <100%> (ø)` | :arrow_up: |
------
[Continue to review full report at Codecov](https://codecov.io/gh/tox-dev/tox-travis/pull/83?src=pr&el=continue).
> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
> `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
> Powered by [Codecov](https://codecov.io/gh/tox-dev/tox-travis/pull/83?src=pr&el=footer). Last update [ffe8441...b94d6fc](https://codecov.io/gh/tox-dev/tox-travis/pull/83?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).
rpkilby: Two thoughts:
- A part of my says the output should be tested for the warnings, but it seems straightforward enough to not warrant tests.
- Would it make sense to name the files `envlist` instead of `detect`? eg,
```python
from envlist import detect_envlist
```
ryanhiebert: Yeah, I've got to figure out how to test this section. Right now the after feature is considered "experimental", so I don't have it fully tested (especially the hooks and monkeypatch).
`envlist` was the original plan, as I specified on #80. My main driver for doing something different was #84 , considering how I'd like to spell that flag. I like `--auto-envlist` less than `--detect`, and `--envlist` isn't a clear option IMO. Avoiding multiple words was something that I liked with `--detect`. Perhaps the flag needs to be `--detect-envlist` (or the negative). In that case it would be multiple words, but I'd have no issue renaming the files to `envlist` then.
ryanhiebert: As I noted on #84, `envlist` is a good name for the feature, so I've updated this PR to use `envlist` as the name that we're renaming toxenv to.
ryanhiebert: I'm glad that I added tests for the changes in `travis:after`. There were some bugs that needed to be addressed. | diff --git a/docs/after.rst b/docs/after.rst
index 664b166..4de27af 100644
--- a/docs/after.rst
+++ b/docs/after.rst
@@ -101,7 +101,7 @@ that you are shipping a working release.
The accepted configuration keys
in the ``[travis:after]`` section are:
-* ``toxenv``. Match with the running toxenvs.
+* ``envlist``. Match with the running toxenvs.
Expansion is allowed, and if set *all* environments listed
must be run in the current Tox run.
* ``travis``. Match with known Travis factors,
diff --git a/docs/toxenv.rst b/docs/envlist.rst
similarity index 100%
rename from docs/toxenv.rst
rename to docs/envlist.rst
diff --git a/docs/index.rst b/docs/index.rst
index ebf5347..90714fc 100644
--- a/docs/index.rst
+++ b/docs/index.rst
@@ -6,7 +6,7 @@ Topics
.. toctree::
:maxdepth: 1
- toxenv
+ envlist
after
contributing
history
diff --git a/src/tox_travis/after.py b/src/tox_travis/after.py
index caf3750..53def96 100644
--- a/src/tox_travis/after.py
+++ b/src/tox_travis/after.py
@@ -22,16 +22,16 @@ INCOMPLETE_TRAVIS_ENVIRONMENT = 34
JOBS_FAILED = 35
-def travis_after_monkeypatch():
+def travis_after_monkeypatch(ini, envlist):
"""Monkeypatch the Tox session to wait for jobs to finish."""
import tox.session
real_subcommand_test = tox.session.Session.subcommand_test
def subcommand_test(self):
retcode = real_subcommand_test(self)
- if retcode == 0 and self.config.option.travis_after:
+ if retcode == 0:
# No need to run if the tests failed anyway
- travis_after(self.config.envlist, self.config._cfg)
+ travis_after(envlist, ini)
return retcode
tox.session.Session.subcommand_test = subcommand_test
@@ -83,8 +83,13 @@ def after_config_matches(envlist, ini):
if not section:
return False # Never wait if it's not configured
- if 'toxenv' in section:
- required = set(split_env(section['toxenv']))
+ if 'envlist' in section or 'toxenv' in section:
+ if 'toxenv' in section:
+ print('The "toxenv" key of the [travis:after] section is '
+ 'deprecated in favor of the "envlist" key.', file=sys.stderr)
+
+ toxenv = section.get('toxenv')
+ required = set(split_env(section.get('envlist', toxenv) or ''))
actual = set(envlist)
if required - actual:
return False
@@ -120,8 +125,8 @@ def get_job_statuses(github_token, api_url, build_id,
build = get_json('{api_url}/builds/{build_id}'.format(
api_url=api_url, build_id=build_id), auth=auth)
jobs = [job for job in build['jobs']
- if job['number'] != job_number
- and not job['allow_failure']] # Ignore allowed failures
+ if job['number'] != job_number and
+ not job['allow_failure']] # Ignore allowed failures
if all(job['finished_at'] for job in jobs):
break # All the jobs have completed
elif any(job['state'] != 'passed'
diff --git a/src/tox_travis/toxenv.py b/src/tox_travis/envlist.py
similarity index 90%
rename from src/tox_travis/toxenv.py
rename to src/tox_travis/envlist.py
index 8bed3c7..2e1ea1e 100644
--- a/src/tox_travis/toxenv.py
+++ b/src/tox_travis/envlist.py
@@ -1,4 +1,4 @@
-"""Default TOXENV based on the Travis environment."""
+"""Default Tox envlist based on the Travis environment."""
from __future__ import print_function
from itertools import product
import os
@@ -9,13 +9,8 @@ from tox.config import _split_env as split_env
from .utils import TRAVIS_FACTORS, parse_dict
-def default_toxenv(config):
+def detect_envlist(ini):
"""Default envlist automatically based on the Travis environment."""
- if 'TOXENV' in os.environ or config.option.env:
- return # Skip any processing if already set
-
- ini = config._cfg
-
# Find the envs that tox knows about
declared_envs = get_declared_envs(ini)
@@ -26,13 +21,8 @@ def default_toxenv(config):
desired_envs = ['-'.join(env) for env in product(*desired_factors)]
# Find matching envs
- matched = match_envs(declared_envs, desired_envs,
- passthru=len(desired_factors) == 1)
-
- # Make the envconfig for undeclared matched envs
- autogen_envconfigs(config, set(matched) - set(config.envconfigs))
-
- config.envlist = matched
+ return match_envs(declared_envs, desired_envs,
+ passthru=len(desired_factors) == 1)
def autogen_envconfigs(config, envs):
@@ -232,9 +222,7 @@ def env_matches(declared, desired):
return all(factor in declared_factors for factor in desired_factors)
-def override_ignore_outcome(config):
- """Override ignore_outcome if unignore_outcomes is set to True."""
- travis_reader = tox.config.SectionReader("travis", config._cfg)
- if travis_reader.getbool('unignore_outcomes', False):
- for envconfig in config.envconfigs.values():
- envconfig.ignore_outcome = False
+def override_ignore_outcome(ini):
+ """Decide whether to override ignore_outcomes."""
+ travis_reader = tox.config.SectionReader("travis", ini)
+ return travis_reader.getbool('unignore_outcomes', False)
diff --git a/src/tox_travis/hooks.py b/src/tox_travis/hooks.py
index c1f00d5..3d83075 100644
--- a/src/tox_travis/hooks.py
+++ b/src/tox_travis/hooks.py
@@ -1,8 +1,11 @@
"""Tox hook implementations."""
+from __future__ import print_function
import os
+import sys
import tox
-from .toxenv import (
- default_toxenv,
+from .envlist import (
+ detect_envlist,
+ autogen_envconfigs,
override_ignore_outcome,
)
from .hacks import pypy_version_monkeypatch
@@ -11,7 +14,7 @@ from .after import travis_after_monkeypatch
@tox.hookimpl
def tox_addoption(parser):
- """Add arguments and override TOXENV."""
+ """Add arguments and needed monkeypatches."""
parser.add_argument(
'--travis-after', dest='travis_after', action='store_true',
help='Exit successfully after all Travis jobs complete successfully.')
@@ -23,8 +26,27 @@ def tox_addoption(parser):
@tox.hookimpl
def tox_configure(config):
"""Check for the presence of the added options."""
- if 'TRAVIS' in os.environ:
- if config.option.travis_after:
- travis_after_monkeypatch()
- default_toxenv(config)
- override_ignore_outcome(config)
+ if 'TRAVIS' not in os.environ:
+ return
+
+ ini = config._cfg
+
+ # envlist
+ if 'TOXENV' not in os.environ and not config.option.env:
+ envlist = detect_envlist(ini)
+ undeclared = set(envlist) - set(config.envconfigs)
+ if undeclared:
+ print('Matching undeclared envs is deprecated. Be sure all the '
+ 'envs that Tox should run are declared in the tox config.',
+ file=sys.stderr)
+ autogen_envconfigs(config, undeclared)
+ config.envlist = envlist
+
+ # Override ignore_outcomes
+ if override_ignore_outcome(ini):
+ for envconfig in config.envconfigs.values():
+ envconfig.ignore_outcome = False
+
+ # after
+ if config.option.travis_after:
+ travis_after_monkeypatch(ini, config.envlist)
| Rename toxenv
We use the name `toxenv` in several places, because the `TOXENV` environment variable is the mechanism I used to implement the primary feature of Env Detection. When #78 is merged, it will no longer be used, except to make sure we don't do anything if it's already been given. So let's not use it as a name.
Some places that I know it's used:
* [ ] The name of the module that implements env detection. (Rename to `detect` or `envlist`)
* [ ] The name of the function that implements env detection. (Name the same as the module above)
* [ ] The name of the file with the documentation for env detection. (Name the same as those above)
* [ ] The name of the setting for the `[travis:after]` section that says which envs to look for. (Either the same as the above, or perhaps just `env`. Keep the current name for backward compatibility.) | tox-dev/tox-travis | diff --git a/tests/test_after.py b/tests/test_after.py
index 06fb01c..50e6738 100644
--- a/tests/test_after.py
+++ b/tests/test_after.py
@@ -1,6 +1,10 @@
"""Tests of the --travis-after flag."""
import pytest
-from tox_travis.after import travis_after
+import py
+from tox_travis.after import (
+ travis_after,
+ after_config_matches,
+)
class TestAfter:
@@ -294,3 +298,106 @@ class TestAfter:
assert excinfo.value.code == 35
out, err = capsys.readouterr()
assert 'Some jobs were not successful.' in out
+
+ def test_after_config_matches_unconfigured(self):
+ """Skip quickly when after section is unconfigured."""
+ inistr = (
+ '[tox]\n'
+ 'envlist = py36\n'
+ )
+ ini = py.iniconfig.IniConfig('', data=inistr)
+ assert not after_config_matches(['py36'], ini)
+
+ def test_after_config_matches_toxenv_match(self, capsys):
+ """Test that it works using the legacy toxenv setting.
+
+ It should also give a warning message.
+ """
+ inistr = (
+ '[tox]\n'
+ 'envlist = py36\n'
+ '\n'
+ '[travis:after]\n'
+ 'toxenv = py36\n'
+ )
+ ini = py.iniconfig.IniConfig('', data=inistr)
+ assert after_config_matches(['py36'], ini)
+ out, err = capsys.readouterr()
+ msg = 'The "toxenv" key of the [travis:after] section is deprecated'
+ assert msg in err
+
+ def test_after_config_matches_toxenv_nomatch(self, capsys):
+ """Test that it doesn't work using the legacy toxenv setting.
+
+ It should also give a warning message.
+ """
+ inistr = (
+ '[tox]\n'
+ 'envlist = py36\n'
+ '\n'
+ '[travis:after]\n'
+ 'toxenv = py36\n'
+ )
+ ini = py.iniconfig.IniConfig('', data=inistr)
+ assert not after_config_matches(['py35'], ini)
+ out, err = capsys.readouterr()
+ msg = 'The "toxenv" key of the [travis:after] section is deprecated'
+ assert msg in err
+
+ def test_after_config_matches_envlist_match(self):
+ """Test that it works."""
+ inistr = (
+ '[tox]\n'
+ 'envlist = py36\n'
+ '\n'
+ '[travis:after]\n'
+ 'envlist = py36\n'
+ )
+ ini = py.iniconfig.IniConfig('', data=inistr)
+ assert after_config_matches(['py36'], ini)
+
+ def test_after_config_matches_envlist_nomatch(self):
+ """Test that it doesn't work."""
+ inistr = (
+ '[tox]\n'
+ 'envlist = py36\n'
+ '\n'
+ '[travis:after]\n'
+ 'envlist = py36\n'
+ )
+ ini = py.iniconfig.IniConfig('', data=inistr)
+ assert not after_config_matches(['py35'], ini)
+
+ def test_after_config_matches_env_match(self, monkeypatch):
+ """Test that it works."""
+ monkeypatch.setenv('TRAVIS_PYTHON_VERSION', '3.6')
+ monkeypatch.setenv('DJANGO', '1.11')
+ inistr = (
+ '[tox]\n'
+ 'envlist = py36\n'
+ '\n'
+ '[travis:after]\n'
+ 'travis =\n'
+ ' python: 3.6\n'
+ 'env =\n'
+ ' DJANGO: 1.11\n'
+ )
+ ini = py.iniconfig.IniConfig('', data=inistr)
+ assert after_config_matches(['py36'], ini)
+
+ def test_after_config_matches_env_nomatch(self, monkeypatch):
+ """Test that it doesn't work."""
+ monkeypatch.setenv('TRAVIS_PYTHON_VERSION', '3.5')
+ monkeypatch.setenv('DJANGO', '1.11')
+ inistr = (
+ '[tox]\n'
+ 'envlist = py36\n'
+ '\n'
+ '[travis:after]\n'
+ 'travis =\n'
+ ' python: 3.6\n'
+ 'env =\n'
+ ' DJANGO: 1.11\n'
+ )
+ ini = py.iniconfig.IniConfig('', data=inistr)
+ assert not after_config_matches(['py35'], ini)
| {
"commit_name": "merge_commit",
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 0,
"test_score": 3
},
"num_modified_files": 5
} | 0.8 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"pytest",
"pytest-mock",
"mock"
],
"pre_install": null,
"python": "3.6",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work
certifi==2021.5.30
distlib==0.3.9
filelock==3.4.1
importlib-metadata==4.8.3
importlib-resources==5.4.0
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
mock==5.2.0
more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work
packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work
platformdirs==2.4.0
pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pytest==6.2.4
pytest-mock==3.6.1
six==1.17.0
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
tox==3.28.0
-e git+https://github.com/tox-dev/tox-travis.git@ffe844135832585a8bad0b5bd56edecbb47ba654#egg=tox_travis
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
virtualenv==20.17.1
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
| name: tox-travis
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=21.4.0=pyhd3eb1b0_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- importlib_metadata=4.8.1=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- more-itertools=8.12.0=pyhd3eb1b0_0
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=21.3=pyhd3eb1b0_0
- pip=21.2.2=py36h06a4308_0
- pluggy=0.13.1=py36h06a4308_0
- py=1.11.0=pyhd3eb1b0_0
- pyparsing=3.0.4=pyhd3eb1b0_0
- pytest=6.2.4=py36h06a4308_2
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- toml=0.10.2=pyhd3eb1b0_0
- typing_extensions=4.1.1=pyh06a4308_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zipp=3.6.0=pyhd3eb1b0_0
- zlib=1.2.13=h5eee18b_1
- pip:
- distlib==0.3.9
- filelock==3.4.1
- importlib-metadata==4.8.3
- importlib-resources==5.4.0
- mock==5.2.0
- platformdirs==2.4.0
- pytest-mock==3.6.1
- six==1.17.0
- tox==3.28.0
- virtualenv==20.17.1
prefix: /opt/conda/envs/tox-travis
| [
"tests/test_after.py::TestAfter::test_after_config_matches_toxenv_match",
"tests/test_after.py::TestAfter::test_after_config_matches_toxenv_nomatch",
"tests/test_after.py::TestAfter::test_after_config_matches_envlist_nomatch"
]
| []
| [
"tests/test_after.py::TestAfter::test_pull_request",
"tests/test_after.py::TestAfter::test_no_github_token",
"tests/test_after.py::TestAfter::test_travis_environment_build_id",
"tests/test_after.py::TestAfter::test_travis_environment_job_number",
"tests/test_after.py::TestAfter::test_travis_environment_api_url",
"tests/test_after.py::TestAfter::test_travis_env_polling_interval",
"tests/test_after.py::TestAfter::test_travis_env_passed",
"tests/test_after.py::TestAfter::test_travis_env_failed",
"tests/test_after.py::TestAfter::test_after_config_matches_unconfigured",
"tests/test_after.py::TestAfter::test_after_config_matches_envlist_match",
"tests/test_after.py::TestAfter::test_after_config_matches_env_match",
"tests/test_after.py::TestAfter::test_after_config_matches_env_nomatch"
]
| []
| MIT License | 1,848 | [
"docs/after.rst",
"src/tox_travis/after.py",
"src/tox_travis/hooks.py",
"docs/toxenv.rst",
"src/tox_travis/toxenv.py",
"docs/index.rst"
]
| [
"docs/after.rst",
"src/tox_travis/after.py",
"src/tox_travis/hooks.py",
"docs/index.rst",
"src/tox_travis/envlist.py",
"docs/envlist.rst"
]
|
cwacek__python-jsonschema-objects-99 | 42388d33e317a2b3202a7922a85b70eb7bf49b97 | 2017-11-04 19:31:00 | a1367dd0fb29f8d218f759bd2baf86e2ae48484d | diff --git a/.codeclimate.yml b/.codeclimate.yml
new file mode 100644
index 0000000..30e4b1d
--- /dev/null
+++ b/.codeclimate.yml
@@ -0,0 +1,9 @@
+engines:
+ pep8:
+ enabled: true
+ checks:
+ E128:
+ enabled: false
+exclude_paths:
+ - versioneer.py
+
diff --git a/.hound.yml b/.hound.yml
deleted file mode 100644
index 7b9ecc1..0000000
--- a/.hound.yml
+++ /dev/null
@@ -1,3 +0,0 @@
-
-flake8:
- enabled: true
diff --git a/.travis.yml b/.travis.yml
index b4be679..6fc198a 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -2,9 +2,23 @@ language: python
python:
- '2.7'
- '3.5'
+env:
+ global:
+ - CC_TEST_REPORTER_ID=dc84306013e5ab029d115d8c2f9b27f23ee83b8d73c2dc35fed00954769fc76b
+
+before_script:
+ - curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter
+ - chmod +x ./cc-test-reporter
+ - ./cc-test-reporter before-build
+
install:
- pip install tox-travis tox
+
script: tox
+
+after_script:
+ - ./cc-test-reporter after-build --exit-code $TRAVIS_TEST_RESULT
+
deploy:
distributions: "sdist bdist_wheel"
provider: pypi
diff --git a/python_jsonschema_objects/classbuilder.py b/python_jsonschema_objects/classbuilder.py
index ed55b99..4c0eb06 100644
--- a/python_jsonschema_objects/classbuilder.py
+++ b/python_jsonschema_objects/classbuilder.py
@@ -1,6 +1,7 @@
import python_jsonschema_objects.util as util
import python_jsonschema_objects.validators as validators
import python_jsonschema_objects.pattern_properties as pattern_properties
+from python_jsonschema_objects.literals import LiteralValue
import collections
import itertools
@@ -16,11 +17,11 @@ logger = logging.getLogger(__name__)
logger.addHandler(logging.NullHandler())
-
# Long is no longer a thing in python3.x
if sys.version_info > (3,):
long = int
+
class ProtocolBase(collections.MutableMapping):
""" An instance of a class generated from the provided
schema. All properties will be validated according to
@@ -75,16 +76,16 @@ class ProtocolBase(collections.MutableMapping):
def __str__(self):
inverter = dict((v, k) for k,v in six.iteritems(self.__prop_names__))
- props = ["%s" % (inverter.get(k, k),) for k, v in
+ props = sorted(["%s" % (inverter.get(k, k),) for k, v in
itertools.chain(six.iteritems(self._properties),
- six.iteritems(self._extended_properties))]
+ six.iteritems(self._extended_properties))])
return "<%s attributes: %s>" % (self.__class__.__name__, ", ".join(props))
def __repr__(self):
inverter = dict((v, k) for k,v in six.iteritems(self.__prop_names__))
- props = ["%s=%s" % (inverter.get(k, k), str(v)) for k, v in
+ props = sorted(["%s=%s" % (inverter.get(k, k), str(v)) for k, v in
itertools.chain(six.iteritems(self._properties),
- six.iteritems(self._extended_properties))]
+ six.iteritems(self._extended_properties))])
return "<%s %s>" % (
self.__class__.__name__,
" ".join(props)
@@ -237,9 +238,9 @@ class ProtocolBase(collections.MutableMapping):
return {}
return cls.__propinfo__[propname]
- def serialize(self):
+ def serialize(self, **opts):
self.validate()
- enc = util.ProtocolJSONEncoder()
+ enc = util.ProtocolJSONEncoder(**opts)
return enc.encode(self)
def validate(self):
@@ -281,18 +282,6 @@ class ProtocolBase(collections.MutableMapping):
return True
-def MakeLiteral(name, typ, value, **properties):
- properties.update({'type': typ})
- klass = type(str(name), tuple((LiteralValue,)), {
- '__propinfo__': {
- '__literal__': properties,
- '__default__': properties.get('default')
- }
- })
-
- return klass(value)
-
-
class TypeProxy(object):
def __init__(self, types):
@@ -322,80 +311,6 @@ class TypeProxy(object):
)
-class LiteralValue(object):
- """Docstring for LiteralValue """
-
- isLiteralClass = True
-
- def __init__(self, value, typ=None):
- """@todo: to be defined
-
- :value: @todo
-
- """
- if isinstance(value, LiteralValue):
- self._value = value._value
- else:
- self._value = value
-
- if self._value is None and self.default() is not None:
- self._value = self.default()
-
- self.validate()
-
- def as_dict(self):
- return self.for_json()
-
- def for_json(self):
- return self._value
-
- @classmethod
- def default(cls):
- return cls.__propinfo__.get('__default__')
-
- @classmethod
- def propinfo(cls, propname):
- if propname not in cls.__propinfo__:
- return {}
- return cls.__propinfo__[propname]
-
- def serialize(self):
- self.validate()
- enc = util.ProtocolJSONEncoder()
- return enc.encode(self)
-
- def __repr__(self):
- return "<%s %s>" % (
- self.__class__.__name__,
- str(self._value)
- )
-
- def __str__(self):
- return str(self._value)
-
- def validate(self):
- info = self.propinfo('__literal__')
-
- # this duplicates logic in validators.ArrayValidator.check_items; unify it.
- for param, paramval in sorted(six.iteritems(info), key=lambda x: x[0].lower() != 'type'):
- validator = validators.registry(param)
- if validator is not None:
- validator(paramval, self._value, info)
-
- def __eq__(self, other):
- return self._value == other
-
- def __hash__(self):
- return hash(self._value)
-
- def __lt__(self, other):
- return self._value < other
-
- def __int__(self):
- return int(self._value)
-
- def __float__(self):
- return float(self._value)
class ClassBuilder(object):
diff --git a/python_jsonschema_objects/examples/README.md b/python_jsonschema_objects/examples/README.md
index 700c7b6..31f59fc 100644
--- a/python_jsonschema_objects/examples/README.md
+++ b/python_jsonschema_objects/examples/README.md
@@ -55,29 +55,36 @@ here that the schema above has been loaded in a variable called
``` python
>>> import python_jsonschema_objects as pjs
->>> builder = pjs.ObjectBuilder(schema)
+>>> builder = pjs.ObjectBuilder(examples['Example Schema'])
>>> ns = builder.build_classes()
>>> Person = ns.ExampleSchema
>>> james = Person(firstName="James", lastName="Bond")
>>> james.lastName
-u'Bond'
+<Literal<str> Bond>
+>>> james.lastName == "Bond"
+True
>>> james
-<example_schema lastName=Bond age=None firstName=James>
+<example_schema address=None age=None deceased=None dogs=None firstName=James gender=None lastName=Bond>
+
```
Validations will also be applied as the object is manipulated.
``` python
->>> james.age = -2
-python_jsonschema_objects.validators.ValidationError: -2 was less
-or equal to than 0
+>>> james.age = -2 # doctest: +IGNORE_EXCEPTION_DETAIL
+Traceback (most recent call last):
+ ...
+ValidationError: -2 is less than 0
+
```
-The object can be serialized out to JSON:
+The object can be serialized out to JSON. Options are passed
+through to the standard library JSONEncoder object.
``` python
->>> james.serialize()
-'{"lastName": "Bond", "age": null, "firstName": "James"}'
+>>> james.serialize(sort_keys=True)
+'{"firstName": "James", "lastName": "Bond"}'
+
```
## Why
@@ -101,7 +108,36 @@ with validation, directly from an input JSON schema. These
classes can seamlessly encode back and forth to JSON valid
according to the schema.
-## Other Features
+## Fully Functional Literals
+
+Literal values are wrapped when constructed to support validation
+and other schema-related operations. However, you can still use
+them just as you would other literals.
+
+``` python
+>>> import python_jsonschema_objects as pjs
+>>> builder = pjs.ObjectBuilder(examples['Example Schema'])
+>>> ns = builder.build_classes()
+>>> Person = ns.ExampleSchema
+>>> james = Person(firstName="James", lastName="Bond")
+>>> str(james.lastName)
+'Bond'
+>>> james.lastName += "ing"
+>>> str(james.lastName)
+'Bonding'
+>>> james.age = 4
+>>> james.age - 1
+3
+>>> 3 + james.age
+7
+>>> james.lastName / 4
+Traceback (most recent call last):
+ ...
+TypeError: unsupported operand type(s) for /: 'str' and 'int'
+
+```
+
+## Resolving Directly from Memory
The ObjectBuilder can be passed a dictionary specifying
'memory' schemas when instantiated. This will allow it to
@@ -221,11 +257,11 @@ The schema and code example below show how this works.
```
``` python
->>> builder = pjs.ObjectBuilder('multiple_objects.json')
+>>> builder = pjs.ObjectBuilder(examples["MultipleObjects"])
>>> classes = builder.build_classes()
->>> print(dir(classes))
-[u'ErrorResponse', 'Local', 'Message', u'Multipleobjects',
-'Status', 'Version', u'VersionGetResponse']
+>>> [str(x) for x in dir(classes)]
+['ErrorResponse', 'Local', 'Message', 'Multipleobjects', 'Status', 'Version', 'VersionGetResponse']
+
```
## Installation
diff --git a/python_jsonschema_objects/literals.py b/python_jsonschema_objects/literals.py
new file mode 100644
index 0000000..9b0c02d
--- /dev/null
+++ b/python_jsonschema_objects/literals.py
@@ -0,0 +1,146 @@
+from python_jsonschema_objects import util
+from python_jsonschema_objects import validators
+import functools
+import logging
+import six
+import operator
+
+
+def MakeLiteral(name, typ, value, **properties):
+ properties.update({'type': typ})
+ klass = type(str(name), tuple((LiteralValue,)), {
+ '__propinfo__': {
+ '__literal__': properties,
+ '__default__': properties.get('default')
+ }
+ })
+
+ return klass(value)
+
+
+class LiteralValue(object):
+ """Docstring for LiteralValue """
+
+ isLiteralClass = True
+
+ def __init__(self, value, typ=None):
+ """@todo: to be defined
+
+ :value: @todo
+
+ """
+ if isinstance(value, LiteralValue):
+ self._value = value._value
+ else:
+ self._value = value
+
+ if self._value is None and self.default() is not None:
+ self._value = self.default()
+
+ self.validate()
+
+ def as_dict(self):
+ return self.for_json()
+
+ def for_json(self):
+ return self._value
+
+ @classmethod
+ def default(cls):
+ return cls.__propinfo__.get('__default__')
+
+ @classmethod
+ def propinfo(cls, propname):
+ if propname not in cls.__propinfo__:
+ return {}
+ return cls.__propinfo__[propname]
+
+ def serialize(self):
+ self.validate()
+ enc = util.ProtocolJSONEncoder()
+ return enc.encode(self)
+
+ def __repr__(self):
+ return "<Literal<%s> %s>" % (
+ self._value.__class__.__name__,
+ str(self._value)
+ )
+
+ def __str__(self):
+ if isinstance(self._value, six.string_types):
+ return self._value
+ return str(self._value)
+
+ def validate(self):
+ info = self.propinfo('__literal__')
+
+ # TODO: this duplicates logic in validators.ArrayValidator.check_items; unify it.
+ for param, paramval in sorted(six.iteritems(info),
+ key=lambda x: x[0].lower() != 'type'):
+ validator = validators.registry(param)
+ if validator is not None:
+ validator(paramval, self._value, info)
+
+ def __eq__(self, other):
+ return self._value == other
+
+ def __hash__(self):
+ return hash(self._value)
+
+ def __lt__(self, other):
+ return self._value < other
+
+ def __int__(self):
+ return int(self._value)
+
+ def __float__(self):
+ return float(self._value)
+
+
+EXCLUDED_OPERATORS = set(
+ util.CLASS_ATTRS +
+ util.NEWCLASS_ATTRS +
+ ["__name__",
+ "__setattr__",
+ "__getattr__",
+ "__dict__",
+ "__matmul__",
+ "__imatmul__",
+ ]
+)
+
+
+def dispatch_to_value(fn):
+ def wrapper(self, other):
+ return fn(self._value, other)
+ pass
+ return wrapper
+
+
+""" This attaches all the literal operators to LiteralValue
+ except for the reverse ones."""
+for op in dir(operator):
+ if op.startswith("__") and op not in EXCLUDED_OPERATORS:
+ opfn = getattr(operator, op)
+ setattr(LiteralValue, op, dispatch_to_value(opfn))
+
+
+""" We also have to patch the reverse operators,
+which aren't conveniently defined anywhere """
+LiteralValue.__radd__ = lambda self, other: other + self._value
+LiteralValue.__rsub__ = lambda self, other: other - self._value
+LiteralValue.__rmul__ = lambda self, other: other * self._value
+LiteralValue.__rtruediv__ = lambda self, other: other / self._value
+LiteralValue.__rfloordiv__ = lambda self, other: other // self._value
+LiteralValue.__rmod__ = lambda self, other: other % self._value
+LiteralValue.__rdivmod__ = lambda self, other: divmod(other, self._value)
+LiteralValue.__rpow__ = lambda self, other, modulo=None: pow(
+ other, self._value, modulo)
+LiteralValue.__rlshift__ = lambda self, other: other << self._value
+LiteralValue.__rrshift__ = lambda self, other: other >> self._value
+LiteralValue.__rand__ = lambda self, other: other & self._value
+LiteralValue.__rxor__ = lambda self, other: other ^ self._value
+LiteralValue.__ror__ = lambda self, other: other | self._value
+
+
+
diff --git a/python_jsonschema_objects/pattern_properties.py b/python_jsonschema_objects/pattern_properties.py
index c2617c2..b15f104 100644
--- a/python_jsonschema_objects/pattern_properties.py
+++ b/python_jsonschema_objects/pattern_properties.py
@@ -3,6 +3,8 @@ import six
import re
import python_jsonschema_objects.validators as validators
import python_jsonschema_objects.util as util
+from python_jsonschema_objects.literals import MakeLiteral
+
import collections
import logging
@@ -97,7 +99,7 @@ class ExtensibleValidator(object):
in validators.SCHEMA_TYPE_MAPPING
if t is not None and isinstance(val, t)]
valtype = valtype[0]
- return cb.MakeLiteral(name, valtype, val)
+ return MakeLiteral(name, valtype, val)
elif isinstance(self._additional_type, type):
return self._make_type(self._additional_type, val)
diff --git a/python_jsonschema_objects/util.py b/python_jsonschema_objects/util.py
index ad8f7da..5b6533f 100644
--- a/python_jsonschema_objects/util.py
+++ b/python_jsonschema_objects/util.py
@@ -124,6 +124,7 @@ from collections import Mapping, Sequence
class _Dummy:
pass
CLASS_ATTRS = dir(_Dummy)
+NEWCLASS_ATTRS = dir(object)
del _Dummy
diff --git a/tox.ini b/tox.ini
index 0207557..dff2994 100644
--- a/tox.ini
+++ b/tox.ini
@@ -4,7 +4,7 @@ envlist = py27, py35
[testenv]
;install_command = pip install {opts} {packages}
-commands = coverage run {envbindir}/py.test {posargs}
+commands = coverage run {envbindir}/py.test --doctest-glob='python_jsonschema_objects/*.md' {posargs}
coverage html --omit=*test* --include=*python_jsonschema_objects*
deps =
.
| Literal Types no longer can be directly operated on
With the new support for default values for literals (which is great), doing stuff like:
`object.value + 1` or `object.name.startswith('John')` no longer works.
```
from python_jsonschema_objects.classbuilder import MakeLiteral
# expect 10, get an error that 'test' + 'test' is not defined
MakeLiteral('test', 'integer', 5) + MakeLiteral('test', 'integer', 5)
# expect "hello world", get an error that 'test' + 'test' is not defined
MakeLiteral('test', 'string', 'hello ') + MakeLiteral('test', 'integer', ' world!')
```
There's a few quick fix: use str(), float(), int() to get the _value or just do ._value everywhere.
However, it'd be great if we just dispatch the calls to the underlying literals.
i have a [gist](https://gist.github.com/blackhathedgehog/c88e1b85352e531fe6a98b0b13a96f2e) that is a quick-and-dirty implementation. i think that an improved implementation might actually run `MakeLiteral` and return a value that is wrapped (and validated).
| cwacek/python-jsonschema-objects | diff --git a/test/conftest.py b/conftest.py
similarity index 66%
rename from test/conftest.py
rename to conftest.py
index 664a782..4f0e1d8 100644
--- a/test/conftest.py
+++ b/conftest.py
@@ -4,15 +4,20 @@ import json
import pkg_resources
import os
import python_jsonschema_objects as pjs
+import python_jsonschema_objects.markdown_support
@pytest.fixture
def markdown_examples():
md = pkg_resources.resource_filename('python_jsonschema_objects.examples', 'README.md')
- examples = pjs.markdown_support.extract_code_blocks(md)
+ examples = python_jsonschema_objects.markdown_support.extract_code_blocks(md)
examples = {json.loads(v)['title']: json.loads(v) for v in examples['schema']}
return examples
[email protected](autouse=True)
+def inject_examples(doctest_namespace, markdown_examples):
+ doctest_namespace['examples'] = markdown_examples
+
@pytest.fixture
def Person(markdown_examples):
diff --git a/test/test_regression_8.py b/test/test_regression_8.py
index 19a08c2..41d5cc2 100644
--- a/test/test_regression_8.py
+++ b/test/test_regression_8.py
@@ -48,7 +48,7 @@ def test_array_elements_compare_to_types(test_instance):
assert test
def test_repr_shows_property_values(test_instance):
- expected = "<example/arrayProp_<anonymous_field> these>"
+ expected = "<Literal<str> these>"
assert repr(test_instance.arrayProp[0]) == expected
def test_str_shows_just_strings(test_instance):
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_hyperlinks",
"has_added_files",
"has_removed_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 2,
"test_score": 0
},
"num_modified_files": 6
} | 0.3 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"nose",
"rednose",
"pyandoc",
"pandoc",
"sphinx",
"sphinx-autobuild",
"recommonmark",
"pytest"
],
"pre_install": null,
"python": "3.5",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | alabaster==0.7.13
attrs==22.2.0
Babel==2.11.0
certifi==2021.5.30
charset-normalizer==2.0.12
colorama==0.4.5
commonmark==0.9.1
docutils==0.18.1
idna==3.10
imagesize==1.4.1
importlib-metadata==4.8.3
inflection==0.2.0
iniconfig==1.1.1
Jinja2==3.0.3
jsonschema==2.6.0
livereload==2.6.3
Markdown==2.4
MarkupSafe==2.0.1
nose==1.3.7
packaging==21.3
pandoc==2.4
pandocfilters==1.5.1
pluggy==1.0.0
plumbum==1.8.3
ply==3.11
py==1.11.0
pyandoc==0.2.0
Pygments==2.14.0
pyparsing==3.1.4
pyrsistent==0.18.0
pytest==7.0.1
-e git+https://github.com/cwacek/python-jsonschema-objects.git@42388d33e317a2b3202a7922a85b70eb7bf49b97#egg=python_jsonschema_objects
pytz==2025.2
recommonmark==0.7.1
rednose==1.3.0
requests==2.27.1
six==1.17.0
snowballstemmer==2.2.0
Sphinx==5.3.0
sphinx-autobuild==2021.3.14
sphinxcontrib-applehelp==1.0.2
sphinxcontrib-devhelp==1.0.2
sphinxcontrib-htmlhelp==2.0.0
sphinxcontrib-jsmath==1.0.1
sphinxcontrib-qthelp==1.0.3
sphinxcontrib-serializinghtml==1.1.5
termstyle==0.1.11
tomli==1.2.3
tornado==6.1
typing_extensions==4.1.1
urllib3==1.26.20
zipp==3.6.0
| name: python-jsonschema-objects
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- alabaster==0.7.13
- attrs==22.2.0
- babel==2.11.0
- charset-normalizer==2.0.12
- colorama==0.4.5
- commonmark==0.9.1
- docutils==0.18.1
- idna==3.10
- imagesize==1.4.1
- importlib-metadata==4.8.3
- inflection==0.2.0
- iniconfig==1.1.1
- jinja2==3.0.3
- jsonschema==2.6.0
- livereload==2.6.3
- markdown==2.4
- markupsafe==2.0.1
- nose==1.3.7
- packaging==21.3
- pandoc==2.4
- pandocfilters==1.5.1
- pluggy==1.0.0
- plumbum==1.8.3
- ply==3.11
- py==1.11.0
- pyandoc==0.2.0
- pygments==2.14.0
- pyparsing==3.1.4
- pyrsistent==0.18.0
- pytest==7.0.1
- pytz==2025.2
- recommonmark==0.7.1
- rednose==1.3.0
- requests==2.27.1
- six==1.17.0
- snowballstemmer==2.2.0
- sphinx==5.3.0
- sphinx-autobuild==2021.3.14
- sphinxcontrib-applehelp==1.0.2
- sphinxcontrib-devhelp==1.0.2
- sphinxcontrib-htmlhelp==2.0.0
- sphinxcontrib-jsmath==1.0.1
- sphinxcontrib-qthelp==1.0.3
- sphinxcontrib-serializinghtml==1.1.5
- termstyle==0.1.11
- tomli==1.2.3
- tornado==6.1
- typing-extensions==4.1.1
- urllib3==1.26.20
- zipp==3.6.0
prefix: /opt/conda/envs/python-jsonschema-objects
| [
"test/test_regression_8.py::test_repr_shows_property_values"
]
| []
| [
"test/test_regression_8.py::test_string_properties_compare_to_strings",
"test/test_regression_8.py::test_arrays_of_strings_compare_to_strings",
"test/test_regression_8.py::test_arrays_can_be_extended",
"test/test_regression_8.py::test_array_elements_compare_to_types",
"test/test_regression_8.py::test_str_shows_just_strings"
]
| []
| MIT License | 1,850 | [
"python_jsonschema_objects/examples/README.md",
"python_jsonschema_objects/literals.py",
".hound.yml",
".travis.yml",
"python_jsonschema_objects/util.py",
"tox.ini",
".codeclimate.yml",
"python_jsonschema_objects/classbuilder.py",
"python_jsonschema_objects/pattern_properties.py"
]
| [
"python_jsonschema_objects/examples/README.md",
"python_jsonschema_objects/literals.py",
".hound.yml",
".travis.yml",
"python_jsonschema_objects/util.py",
"tox.ini",
".codeclimate.yml",
"python_jsonschema_objects/classbuilder.py",
"python_jsonschema_objects/pattern_properties.py"
]
|
|
watson-developer-cloud__python-sdk-297 | 2acf477d3d6ca58ed79ac1d760ed9802d325072c | 2017-11-05 13:05:40 | f0fda953cf81204d2bf11d61d1e792292ced0d6f | diff --git a/examples/conversation_tone_analyzer_integration/__init__.py b/examples/conversation_tone_analyzer_integration/__init__.py
index c4d6c44a..dc36e221 100644
--- a/examples/conversation_tone_analyzer_integration/__init__.py
+++ b/examples/conversation_tone_analyzer_integration/__init__.py
@@ -14,7 +14,6 @@
from .watson_service import WatsonService
from .watson_service import WatsonException
-from .watson_service import WatsonInvalidArgument
from .conversation_v1 import ConversationV1
from .tone_analyzer_v3 import ToneAnalyzerV3
diff --git a/examples/natural_language_classifier_v1.py b/examples/natural_language_classifier_v1.py
index 745b6bec..97554fa3 100644
--- a/examples/natural_language_classifier_v1.py
+++ b/examples/natural_language_classifier_v1.py
@@ -33,7 +33,7 @@ if status['status'] == 'Available':
# delete = natural_language_classifier.remove('2374f9x68-nlc-2697')
# print(json.dumps(delete, indent=2))
-# example of raising a WatsonException
+# example of raising a ValueError
# print(json.dumps(
# natural_language_classifier.create(training_data='', name='weather3'),
# indent=2))
diff --git a/watson_developer_cloud/__init__.py b/watson_developer_cloud/__init__.py
index 925fcb8d..b25873e5 100755
--- a/watson_developer_cloud/__init__.py
+++ b/watson_developer_cloud/__init__.py
@@ -14,6 +14,7 @@
from .watson_service import WatsonService
from .watson_service import WatsonException
+from .watson_service import WatsonApiException
from .watson_service import WatsonInvalidArgument
from .alchemy_data_news_v1 import AlchemyDataNewsV1
from .alchemy_language_v1 import AlchemyLanguageV1
diff --git a/watson_developer_cloud/language_translation_v2.py b/watson_developer_cloud/language_translation_v2.py
index 7829d96c..751b965e 100644
--- a/watson_developer_cloud/language_translation_v2.py
+++ b/watson_developer_cloud/language_translation_v2.py
@@ -19,7 +19,6 @@ The v2 Language Translation service
from __future__ import print_function
from .watson_service import WatsonService
-from .watson_service import WatsonInvalidArgument
class LanguageTranslationV2(WatsonService):
@@ -56,8 +55,7 @@ class LanguageTranslationV2(WatsonService):
monolingual_corpus=None):
if forced_glossary is None and parallel_corpus is None and \
monolingual_corpus is None:
- raise WatsonInvalidArgument(
- 'A glossary or corpus must be provided')
+ raise ValueError('A glossary or corpus must be provided')
params = {'name': name,
'base_model_id': base_model_id}
files = {'forced_glossary': forced_glossary,
@@ -80,7 +78,7 @@ class LanguageTranslationV2(WatsonService):
Translates text from a source language to a target language
"""
if model_id is None and (source is None or target is None):
- raise WatsonInvalidArgument(
+ raise ValueError(
'Either model_id or source and target must be specified')
data = {'text': text, 'source': source, 'target': target,
diff --git a/watson_developer_cloud/watson_service.py b/watson_developer_cloud/watson_service.py
index 5c938b23..83eeaaf6 100755
--- a/watson_developer_cloud/watson_service.py
+++ b/watson_developer_cloud/watson_service.py
@@ -45,9 +45,31 @@ def load_from_vcap_services(service_name):
class WatsonException(Exception):
+ """
+ Custom exception class for Watson Services.
+ """
pass
+class WatsonApiException(WatsonException):
+ """
+ Custom exception class for errors returned from Watson APIs.
+
+ :param int code: The HTTP status code returned.
+ :param str message: A message describing the error.
+ :param dict info: A dictionary of additional information about the error.
+ """
+ def __init__(self, code, message, info=None):
+ # Call the base class constructor with the parameters it needs
+ super(WatsonApiException, self).__init__(message)
+ self.message = message
+ self.code = code
+ self.info = info
+
+ def __str__(self):
+ return 'Error: ' + self.message + ', Code: ' + str(self.code)
+
+
class WatsonInvalidArgument(WatsonException):
pass
@@ -115,7 +137,7 @@ class WatsonService(object):
if api_key is not None:
if username is not None or password is not None:
- raise WatsonInvalidArgument(
+ raise ValueError(
'Cannot set api_key and username and password together')
self.set_api_key(api_key)
else:
@@ -138,10 +160,9 @@ class WatsonService(object):
if (self.username is None or self.password is None)\
and self.api_key is None:
- raise WatsonException(
+ raise ValueError(
'You must specify your username and password service '
- 'credentials ' +
- '(Note: these are different from your Bluemix id)')
+ 'credentials (Note: these are different from your Bluemix id)')
def set_username_and_password(self, username=None, password=None):
if username == 'YOUR SERVICE USERNAME':
@@ -171,7 +192,7 @@ class WatsonService(object):
if isinstance(headers, dict):
self.default_headers = headers
else:
- raise WatsonException("headers parameter must be a dictionary")
+ raise TypeError("headers parameter must be a dictionary")
# Could make this compute the label_id based on the variable name of the
# dictionary passed in (using **kwargs), but
@@ -192,10 +213,8 @@ class WatsonService(object):
def _get_error_message(response):
"""
Gets the error message from a JSON response.
- {
- code: 400
- error: 'Bad request'
- }
+ :return: the error message
+ :rtype: string
"""
error_message = 'Unknown error'
try:
@@ -203,22 +222,36 @@ class WatsonService(object):
if 'error' in error_json:
if isinstance(error_json['error'], dict) and 'description' in \
error_json['error']:
- error_message = 'Error: ' + error_json['error'][
- 'description']
+ error_message = error_json['error']['description']
else:
- error_message = 'Error: ' + error_json['error']
+ error_message = error_json['error']
elif 'error_message' in error_json:
- error_message = 'Error: ' + error_json['error_message']
+ error_message = error_json['error_message']
elif 'msg' in error_json:
- error_message = 'Error: ' + error_json['msg']
+ error_message = error_json['msg']
elif 'statusInfo' in error_json:
- error_message = 'Error: ' + error_json['statusInfo']
- if 'description' in error_json:
- error_message += ', Description: ' + error_json['description']
- error_message += ', Code: ' + str(response.status_code)
+ error_message = error_json['statusInfo']
return error_message
except:
- return {'error': response.text or error_message, 'code': str(response.status_code)}
+ return response.text or error_message
+
+
+ @staticmethod
+ def _get_error_info(response):
+ """
+ Gets the error info (if any) from a JSON response.
+ :return: A `dict` containing additional information about the error.
+ :rtype: dict
+ """
+ info_keys = ['code_description', 'description', 'errors', 'help',
+ 'sub_code', 'warnings']
+ error_info = {}
+ try:
+ error_json = response.json()
+ error_info = {k:v for k, v in error_json.items() if k in info_keys}
+ except:
+ pass
+ return error_info if any(error_info) else None
def _alchemy_html_request(self, method_name=None, url=None, html=None,
@@ -333,13 +366,14 @@ class WatsonService(object):
response_json = response.json()
if 'status' in response_json and response_json['status'] \
== 'ERROR':
- response.status_code = 400
+ status_code = 400
error_message = 'Unknown error'
+
if 'statusInfo' in response_json:
error_message = response_json['statusInfo']
if error_message == 'invalid-api-key':
- response.status_code = 401
- raise WatsonException('Error: ' + error_message)
+ status_code = 401
+ raise WatsonApiException(status_code, error_message)
return response_json
return response
else:
@@ -348,4 +382,6 @@ class WatsonService(object):
'invalid credentials '
else:
error_message = self._get_error_message(response)
- raise WatsonException(error_message)
+ error_info = self._get_error_info(response)
+ raise WatsonApiException(response.status_code, error_message,
+ error_info)
| Exceptions don't have enough information for users
As a Developer _I want_ to have `code`, `message`, `description` whenever a Watson service raises an exception _so that_ I can write code that reacts different depending on the exception.
# Context
It seems like the Python exceptions this SDK is throwing are not very useful for developers:
> **Bruce Adams:**
> I do not have a strong opinion about exception classes. I do find it irritating that `WatsonException` takes a structured error response from as service call and flattens it into a string as the exception args. When I want to make decisions based on the error code (my code needs to react differently to 429 compared to a 500), I have to pick the code out of the string.
More info:
* https://stackoverflow.com/questions/256222/which-exception-should-i-raise-on-bad-illegal-argument-combinations-in-python
* https://www.youtube.com/watch?v=o9pEzgHorH0
## Acceptance Criteria
- [ ] Switch to use `ValueError` when there is a missing or illegal argument
- [ ] Parse the error parameters and make them available to users (`code`, `description`) | watson-developer-cloud/python-sdk | diff --git a/test/test_conversation_v1.py b/test/test_conversation_v1.py
index 03dc4eb7..b4f339f0 100644
--- a/test/test_conversation_v1.py
+++ b/test/test_conversation_v1.py
@@ -16,6 +16,7 @@ import json
import responses
import watson_developer_cloud
from watson_developer_cloud import WatsonException
+from watson_developer_cloud import WatsonApiException
from watson_developer_cloud.conversation_v1 import *
platform_url = 'https://gateway.watsonplatform.net'
@@ -56,13 +57,13 @@ def test_create_counterexample():
def test_rate_limit_exceeded():
endpoint = '/v1/workspaces/{0}/counterexamples'.format('boguswid')
url = '{0}{1}'.format(base_url, endpoint)
- error_code = "'code': '407'"
+ error_code = 429
error_msg = 'Rate limit exceeded'
responses.add(
responses.POST,
url,
body='Rate limit exceeded',
- status=407,
+ status=429,
content_type='application/json')
service = watson_developer_cloud.ConversationV1(
username='username', password='password', version='2017-02-03')
@@ -71,7 +72,8 @@ def test_rate_limit_exceeded():
workspace_id='boguswid', text='I want financial advice today.')
except WatsonException as ex:
assert len(responses.calls) == 1
- assert error_code in str(ex)
+ assert isinstance(ex, WatsonApiException)
+ assert error_code == ex.code
assert error_msg in str(ex)
@responses.activate
diff --git a/test/test_natural_language_understanding.py b/test/test_natural_language_understanding.py
index 97775a64..c59d4eb0 100644
--- a/test/test_natural_language_understanding.py
+++ b/test/test_natural_language_understanding.py
@@ -68,9 +68,9 @@ class TestNaturalLanguageUnderstanding(TestCase):
@pytest.mark.skipif(os.getenv('VCAP_SERVICES') is not None,
reason='credentials may come from VCAP_SERVICES')
def test_missing_credentials(self):
- with pytest.raises(WatsonException):
+ with pytest.raises(ValueError):
NaturalLanguageUnderstandingV1(version='2016-01-23')
- with pytest.raises(WatsonException):
+ with pytest.raises(ValueError):
NaturalLanguageUnderstandingV1(version='2016-01-23',
url='https://bogus.com')
diff --git a/test/test_tone_analyzer_v3.py b/test/test_tone_analyzer_v3.py
index b925c2f2..e8f978a0 100755
--- a/test/test_tone_analyzer_v3.py
+++ b/test/test_tone_analyzer_v3.py
@@ -1,6 +1,9 @@
import responses
import watson_developer_cloud
+from watson_developer_cloud import WatsonException
+from watson_developer_cloud import WatsonApiException
import os
+import json
@responses.activate
@@ -104,3 +107,40 @@ def test_tone_chat():
assert responses.calls[0].request.url == tone_url + tone_args
assert responses.calls[0].response.text == tone_response
assert len(responses.calls) == 1
+
+
+#########################
+# error response
+#########################
+
+
[email protected]
+def test_error():
+ tone_url = 'https://gateway.watsonplatform.net/tone-analyzer/api/v3/tone'
+ tone_args = '?version=2016-05-19'
+ error_code = 400
+ error_message = "Invalid JSON input at line 2, column 12"
+ tone_response = {
+ "code": error_code,
+ "sub_code": "C00012",
+ "error": error_message
+ }
+ responses.add(responses.POST,
+ tone_url,
+ body=json.dumps(tone_response),
+ status=error_code,
+ content_type='application/json')
+
+ tone_analyzer = watson_developer_cloud.ToneAnalyzerV3("2016-05-19",
+ username="username", password="password")
+ text = "Team, I know that times are tough!"
+ try:
+ tone_analyzer.tone(text)
+ except WatsonException as ex:
+ assert len(responses.calls) == 1
+ assert isinstance(ex, WatsonApiException)
+ assert ex.code == error_code
+ assert ex.message == error_message
+ assert len(ex.info) == 1
+ assert ex.info['sub_code'] == 'C00012'
+
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 3,
"issue_text_score": 1,
"test_score": 2
},
"num_modified_files": 5
} | 0.26 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"responses",
"python_dotenv"
],
"pre_install": null,
"python": "3.6",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs==22.2.0
certifi==2021.5.30
cffi==1.15.1
charset-normalizer==2.0.12
cryptography==40.0.2
idna==3.10
importlib-metadata==4.8.3
iniconfig==1.1.1
packaging==21.3
pluggy==1.0.0
py==1.11.0
pycparser==2.21
pyOpenSSL==23.2.0
pyparsing==3.1.4
pysolr==3.10.0
pytest==7.0.1
python-dotenv==0.20.0
requests==2.27.1
responses==0.17.0
six==1.17.0
tomli==1.2.3
typing_extensions==4.1.1
urllib3==1.26.20
-e git+https://github.com/watson-developer-cloud/python-sdk.git@2acf477d3d6ca58ed79ac1d760ed9802d325072c#egg=watson_developer_cloud
zipp==3.6.0
| name: python-sdk
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- argparse==1.4.0
- attrs==22.2.0
- cffi==1.15.1
- charset-normalizer==2.0.12
- cryptography==40.0.2
- idna==3.10
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- packaging==21.3
- pluggy==1.0.0
- py==1.11.0
- pycparser==2.21
- pyopenssl==23.2.0
- pyparsing==3.1.4
- pysolr==3.10.0
- pytest==7.0.1
- python-dotenv==0.20.0
- requests==2.27.1
- responses==0.17.0
- six==1.17.0
- tomli==1.2.3
- typing-extensions==4.1.1
- urllib3==1.26.20
- zipp==3.6.0
prefix: /opt/conda/envs/python-sdk
| [
"test/test_conversation_v1.py::test_create_counterexample",
"test/test_conversation_v1.py::test_rate_limit_exceeded",
"test/test_conversation_v1.py::test_unknown_error",
"test/test_conversation_v1.py::test_delete_counterexample",
"test/test_conversation_v1.py::test_get_counterexample",
"test/test_conversation_v1.py::test_list_counterexamples",
"test/test_conversation_v1.py::test_update_counterexample",
"test/test_conversation_v1.py::test_create_entity",
"test/test_conversation_v1.py::test_delete_entity",
"test/test_conversation_v1.py::test_get_entity",
"test/test_conversation_v1.py::test_list_entities",
"test/test_conversation_v1.py::test_update_entity",
"test/test_conversation_v1.py::test_create_example",
"test/test_conversation_v1.py::test_delete_example",
"test/test_conversation_v1.py::test_get_example",
"test/test_conversation_v1.py::test_list_examples",
"test/test_conversation_v1.py::test_update_example",
"test/test_conversation_v1.py::test_create_intent",
"test/test_conversation_v1.py::test_delete_intent",
"test/test_conversation_v1.py::test_get_intent",
"test/test_conversation_v1.py::test_list_intents",
"test/test_conversation_v1.py::test_update_intent",
"test/test_conversation_v1.py::test_list_logs",
"test/test_conversation_v1.py::test_create_synonym",
"test/test_conversation_v1.py::test_delete_synonym",
"test/test_conversation_v1.py::test_get_synonym",
"test/test_conversation_v1.py::test_list_synonyms",
"test/test_conversation_v1.py::test_update_synonym",
"test/test_conversation_v1.py::test_create_value",
"test/test_conversation_v1.py::test_delete_value",
"test/test_conversation_v1.py::test_get_value",
"test/test_conversation_v1.py::test_list_values",
"test/test_conversation_v1.py::test_update_value",
"test/test_conversation_v1.py::test_create_workspace",
"test/test_conversation_v1.py::test_delete_workspace",
"test/test_conversation_v1.py::test_get_workspace",
"test/test_conversation_v1.py::test_list_workspaces",
"test/test_conversation_v1.py::test_update_workspace",
"test/test_natural_language_understanding.py::TestFeatures::test_categories",
"test/test_natural_language_understanding.py::TestFeatures::test_concepts",
"test/test_natural_language_understanding.py::TestFeatures::test_emotion",
"test/test_natural_language_understanding.py::TestFeatures::test_entities",
"test/test_natural_language_understanding.py::TestFeatures::test_keywords",
"test/test_natural_language_understanding.py::TestFeatures::test_metadata",
"test/test_natural_language_understanding.py::TestFeatures::test_relations",
"test/test_natural_language_understanding.py::TestFeatures::test_semantic_roles",
"test/test_natural_language_understanding.py::TestFeatures::test_sentiment",
"test/test_natural_language_understanding.py::TestNaturalLanguageUnderstanding::test_analyze_throws",
"test/test_natural_language_understanding.py::TestNaturalLanguageUnderstanding::test_delete_model",
"test/test_natural_language_understanding.py::TestNaturalLanguageUnderstanding::test_html_analyze",
"test/test_natural_language_understanding.py::TestNaturalLanguageUnderstanding::test_list_models",
"test/test_natural_language_understanding.py::TestNaturalLanguageUnderstanding::test_missing_credentials",
"test/test_natural_language_understanding.py::TestNaturalLanguageUnderstanding::test_text_analyze",
"test/test_natural_language_understanding.py::TestNaturalLanguageUnderstanding::test_url_analyze",
"test/test_natural_language_understanding.py::TestNaturalLanguageUnderstanding::test_version_date",
"test/test_tone_analyzer_v3.py::test_tone",
"test/test_tone_analyzer_v3.py::test_tone_with_args",
"test/test_tone_analyzer_v3.py::test_tone_with_positional_args",
"test/test_tone_analyzer_v3.py::test_tone_chat",
"test/test_tone_analyzer_v3.py::test_error"
]
| [
"test/test_conversation_v1.py::test_message"
]
| []
| []
| Apache License 2.0 | 1,851 | [
"watson_developer_cloud/watson_service.py",
"watson_developer_cloud/__init__.py",
"watson_developer_cloud/language_translation_v2.py",
"examples/conversation_tone_analyzer_integration/__init__.py",
"examples/natural_language_classifier_v1.py"
]
| [
"watson_developer_cloud/watson_service.py",
"watson_developer_cloud/__init__.py",
"watson_developer_cloud/language_translation_v2.py",
"examples/conversation_tone_analyzer_integration/__init__.py",
"examples/natural_language_classifier_v1.py"
]
|
|
jpadilla__pyjwt-304 | e1e4d02c5d9499bcd59403fff2ad73d67cdc8af4 | 2017-11-05 13:53:01 | e0aa10ee586bf010ce9a99c5582ee8dc9293ba1e | coveralls:
[](https://coveralls.io/builds/14045386)
Coverage decreased (-0.4%) to 99.552% when pulling **09cbf0634e47ee97b93eefae7ef8fa44d8682bc0 on fix-298** into **e1e4d02c5d9499bcd59403fff2ad73d67cdc8af4 on master**.
coveralls:
[](https://coveralls.io/builds/14045386)
Coverage decreased (-0.4%) to 99.552% when pulling **09cbf0634e47ee97b93eefae7ef8fa44d8682bc0 on fix-298** into **e1e4d02c5d9499bcd59403fff2ad73d67cdc8af4 on master**.
coveralls:
[](https://coveralls.io/builds/14045590)
Coverage decreased (-0.1%) to 99.851% when pulling **99c1ee928af045c9b15fdce9c60cb4fbf6157ed1 on fix-298** into **e1e4d02c5d9499bcd59403fff2ad73d67cdc8af4 on master**.
coveralls:
[](https://coveralls.io/builds/14049235)
Coverage remained the same at 100.0% when pulling **8d104bc73c8b7ec1de7d724ff0a8c3be83e1893d on fix-298** into **e1e4d02c5d9499bcd59403fff2ad73d67cdc8af4 on master**.
| diff --git a/.gitignore b/.gitignore
index 9672a5b..a6f0fb1 100644
--- a/.gitignore
+++ b/.gitignore
@@ -16,6 +16,7 @@ develop-eggs/
dist/
downloads/
eggs/
+.eggs/
lib/
lib64/
parts/
diff --git a/jwt/__main__.py b/jwt/__main__.py
index 52e7abf..396dc0d 100644
--- a/jwt/__main__.py
+++ b/jwt/__main__.py
@@ -54,10 +54,13 @@ def encode_payload(args):
def decode_payload(args):
try:
- if sys.stdin.isatty():
- token = sys.stdin.read()
- else:
+ if args.token:
token = args.token
+ else:
+ if sys.stdin.isatty():
+ token = sys.stdin.readline().strip()
+ else:
+ raise IOError('Cannot read from stdin: terminal not a TTY')
token = token.encode('utf-8')
data = decode(token, key=args.key, verify=args.verify)
@@ -133,7 +136,10 @@ def build_argparser():
# Decode subcommand
decode_parser = subparsers.add_parser('decode', help='use to decode a supplied JSON web token')
- decode_parser.add_argument('token', help='JSON web token to decode.')
+ decode_parser.add_argument(
+ 'token',
+ help='JSON web token to decode.',
+ nargs='?')
decode_parser.add_argument(
'-n', '--no-verify',
| pyjwt decode --verify CLI hang
$ pyjwt -v
pyjwt 1.5.3
$ pyjwt decode --no-verify eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzb21lIjoicGF5bG9hZCJ9.4twFt5NiznN84AWoo1d7KO1T_yoc0Z6XOpOVswacPZg
^CTraceback (most recent call last):
File "/usr/local/bin/pyjwt", line 11, in <module>
sys.exit(main())
File "/usr/local/lib/python2.7/dist-packages/jwt/__main__.py", line 157, in main
output = arguments.func(arguments)
File "/usr/local/lib/python2.7/dist-packages/jwt/__main__.py", line 58, in decode_payload
token = sys.stdin.read()
$ pyjwt decode --no-verify eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzb21lIjoicGF5bG9hZCJ9.4twFt5NiznN84AWoo1d7KO1T_yoc0Z6XOpOVswacPZg
^CTraceback (most recent call last):
File "/Users/v612996/anaconda/bin/pyjwt", line 11, in <module>
sys.exit(main())
File "/Users/v612996/anaconda/lib/python3.6/site-packages/jwt/__main__.py", line 157, in main
output = arguments.func(arguments)
File "/Users/v612996/anaconda/lib/python3.6/site-packages/jwt/__main__.py", line 58, in decode_payload
token = sys.stdin.read()
KeyboardInterrupt
$ python --version
Python 3.6.0 :: Anaconda custom (x86_64)
But the same token decoded perfectly under python 2.6 interpreter:
>>> jwt.decode(encoded,verify=False)
{u'some': u'payload'}
What is the work around of "pyjwt decode --no-verify" hang in the CLI?
| jpadilla/pyjwt | diff --git a/tests/test_cli.py b/tests/test_cli.py
index f08cf6b..715c2f1 100644
--- a/tests/test_cli.py
+++ b/tests/test_cli.py
@@ -57,6 +57,37 @@ class TestCli:
assert 'There was an error decoding the token' in str(excinfo.value)
+ def test_decode_payload_terminal_tty(self, monkeypatch):
+ encode_args = [
+ '--key=secret-key',
+ 'encode',
+ 'name=hello-world',
+ ]
+ parser = build_argparser()
+ parsed_encode_args = parser.parse_args(encode_args)
+ token = encode_payload(parsed_encode_args)
+
+ decode_args = ['--key=secret-key', 'decode']
+ parsed_decode_args = parser.parse_args(decode_args)
+
+ monkeypatch.setattr(sys.stdin, 'isatty', lambda: True)
+ monkeypatch.setattr(sys.stdin, 'readline', lambda: token)
+
+ actual = json.loads(decode_payload(parsed_decode_args))
+ assert actual['name'] == 'hello-world'
+
+ def test_decode_payload_raises_terminal_not_a_tty(self, monkeypatch):
+ decode_args = ['--key', '1234', 'decode']
+ parser = build_argparser()
+ args = parser.parse_args(decode_args)
+
+ monkeypatch.setattr(sys.stdin, 'isatty', lambda: False)
+
+ with pytest.raises(IOError) as excinfo:
+ decode_payload(args)
+ assert 'Cannot read from stdin: terminal not a TTY' \
+ in str(excinfo.value)
+
@pytest.mark.parametrize('key,name,job,exp,verify', [
('1234', 'Vader', 'Sith', None, None),
('4567', 'Anakin', 'Jedi', '+1', None),
| {
"commit_name": "merge_commit",
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 1,
"test_score": 2
},
"num_modified_files": 2
} | 1.5 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[crypto]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"pytest",
"pytest-cov"
],
"pre_install": null,
"python": "3.9",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | cffi==1.17.1
coverage==7.8.0
cryptography==44.0.2
exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
packaging @ file:///croot/packaging_1734472117206/work
pluggy @ file:///croot/pluggy_1733169602837/work
pycparser==2.22
-e git+https://github.com/jpadilla/pyjwt.git@e1e4d02c5d9499bcd59403fff2ad73d67cdc8af4#egg=PyJWT
pytest @ file:///croot/pytest_1738938843180/work
pytest-cov==6.0.0
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
| name: pyjwt
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- exceptiongroup=1.2.0=py39h06a4308_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- packaging=24.2=py39h06a4308_0
- pip=25.0=py39h06a4308_0
- pluggy=1.5.0=py39h06a4308_0
- pytest=8.3.4=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tomli=2.0.1=py39h06a4308_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- cffi==1.17.1
- coverage==7.8.0
- cryptography==44.0.2
- pycparser==2.22
- pytest-cov==6.0.0
prefix: /opt/conda/envs/pyjwt
| [
"tests/test_cli.py::TestCli::test_decode_payload_terminal_tty",
"tests/test_cli.py::TestCli::test_decode_payload_raises_terminal_not_a_tty"
]
| []
| [
"tests/test_cli.py::TestCli::test_build_argparse",
"tests/test_cli.py::TestCli::test_encode_payload_raises_value_error_key_is_required",
"tests/test_cli.py::TestCli::test_decode_payload_raises_decoded_error",
"tests/test_cli.py::TestCli::test_decode_payload_raises_decoded_error_isatty",
"tests/test_cli.py::TestCli::test_encode_decode[1234-Vader-Sith-None-None]",
"tests/test_cli.py::TestCli::test_encode_decode[4567-Anakin-Jedi-+1-None]",
"tests/test_cli.py::TestCli::test_encode_decode[4321-Padme-Queen-4070926800-true]",
"tests/test_cli.py::TestCli::test_main[1234-Vader-Sith-None-None]",
"tests/test_cli.py::TestCli::test_main[4567-Anakin-Jedi-+1-None]",
"tests/test_cli.py::TestCli::test_main[4321-Padme-Queen-4070926800-true]",
"tests/test_cli.py::TestCli::test_main_throw_exception"
]
| []
| MIT License | 1,852 | [
".gitignore",
"jwt/__main__.py"
]
| [
".gitignore",
"jwt/__main__.py"
]
|
natasha__yargy-46 | 486a17df07ad1615b7a8d6ef2a4bfe3a39d30340 | 2017-11-06 14:56:21 | 486a17df07ad1615b7a8d6ef2a4bfe3a39d30340 | diff --git a/yargy/interpretation/attribute.py b/yargy/interpretation/attribute.py
index 6f6c264..ca320c6 100644
--- a/yargy/interpretation/attribute.py
+++ b/yargy/interpretation/attribute.py
@@ -55,16 +55,6 @@ class FactAttributeBase(Record):
)
-def prepare_normalized(attribute, item):
- if item is not None:
- if callable(item):
- return FunctionFactAttribute(attribute, item)
- else:
- return ConstFactAttribute(attribute, item)
- else:
- return NormalizedFactAttribute(attribute)
-
-
class FactAttribute(FactAttributeBase):
__attributes__ = ['fact', 'name', 'default']
@@ -76,8 +66,14 @@ class FactAttribute(FactAttributeBase):
def inflected(self, grammemes=None):
return InflectedFactAttribute(self, grammemes)
- def normalized(self, item=None):
- return prepare_normalized(self, item)
+ def normalized(self):
+ return NormalizedFactAttribute(self)
+
+ def const(self, value):
+ return ConstFactAttribute(self, value)
+
+ def custom(self, function):
+ return FunctionFactAttribute(self, function)
class RepeatableFactAttribute(FactAttributeBase):
| Allow define custom value in interpretation rules
Like this
```python
{
'interpretation': {
'attribute': Object.attribute,
'value': SomeEnum.value,
}
}
``` | natasha/yargy | diff --git a/yargy/tests/test_attribute.py b/yargy/tests/test_attribute.py
new file mode 100644
index 0000000..ea52d61
--- /dev/null
+++ b/yargy/tests/test_attribute.py
@@ -0,0 +1,29 @@
+# coding: utf-8
+from __future__ import unicode_literals
+
+
+from yargy import Parser, rule, fact
+from yargy.predicates import gram, dictionary
+
+Money = fact(
+ 'Money',
+ ['count', 'base', 'currency']
+)
+
+
+def test_constant_attribute():
+ MONEY_RULE = rule(
+ gram('INT').interpretation(
+ Money.count
+ ),
+ dictionary({'тысяча'}).interpretation(
+ Money.base.const(10**3)
+ ),
+ dictionary({'рубль', 'доллар'}).interpretation(
+ Money.currency
+ ),
+ ).interpretation(Money)
+
+ parser = Parser(MONEY_RULE)
+ matches = list(parser.match('1 тысяча рублей'))
+ assert matches[0].fact == Money(count=1, base=1000, currency='рублей')
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 3,
"test_score": 3
},
"num_modified_files": 1
} | unknown | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-flake8"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": [
"requirements/base.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | backports.functools-lru-cache==1.3
DAWG-Python==0.7.2
docopt==0.6.2
exceptiongroup==1.2.2
flake8==7.2.0
iniconfig==2.1.0
intervaltree==2.1.0
jellyfish==0.5.6
mccabe==0.7.0
packaging==24.2
pluggy==1.5.0
pycodestyle==2.13.0
pyflakes==3.3.1
pymorphy2==0.8
pymorphy2-dicts==2.4.393442.3710985
pytest==8.3.5
pytest-flake8==1.3.0
sortedcontainers==2.4.0
tomli==2.2.1
-e git+https://github.com/natasha/yargy.git@486a17df07ad1615b7a8d6ef2a4bfe3a39d30340#egg=yargy
| name: yargy
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- backports-functools-lru-cache==1.3
- dawg-python==0.7.2
- docopt==0.6.2
- exceptiongroup==1.2.2
- flake8==7.2.0
- iniconfig==2.1.0
- intervaltree==2.1.0
- jellyfish==0.5.6
- mccabe==0.7.0
- packaging==24.2
- pluggy==1.5.0
- pycodestyle==2.13.0
- pyflakes==3.3.1
- pymorphy2==0.8
- pymorphy2-dicts==2.4.393442.3710985
- pytest==8.3.5
- pytest-flake8==1.3.0
- sortedcontainers==2.4.0
- tomli==2.2.1
prefix: /opt/conda/envs/yargy
| [
"yargy/tests/test_attribute.py::test_constant_attribute"
]
| []
| []
| []
| MIT License | 1,853 | [
"yargy/interpretation/attribute.py"
]
| [
"yargy/interpretation/attribute.py"
]
|
|
tox-dev__tox-669 | cc34546210701f099f59ec79016c4ec058749559 | 2017-11-06 19:43:29 | 36ff71d18d10e3c0d4275179d8912abc385b20f0 | RonnyPfannschmidt: i believe this one needs some unit and integration tests, at least a integration test tho
cryvate: @RonnyPfannschmidt I agree, I will have a look later.
I did not run the tests (I was on the train with flaky connection, so running tox/pip was not easy) so I need to fix my use of .format to be py2.6 compatible.
It isn't nice to have to explicitly list all pip options with arguments. [Another road to travel would be to use shlex.split (available in 2.6 as well).](https://docs.python.org/3/library/shlex.html#shlex.split) This means the wheel is not being re-invented, on the other hand, it might do things that breaks backwards compatibility.
codecov[bot]: # [Codecov](https://codecov.io/gh/tox-dev/tox/pull/669?src=pr&el=h1) Report
> Merging [#669](https://codecov.io/gh/tox-dev/tox/pull/669?src=pr&el=desc) into [master](https://codecov.io/gh/tox-dev/tox/commit/cc34546210701f099f59ec79016c4ec058749559?src=pr&el=desc) will **decrease** coverage by `4.74%`.
> The diff coverage is `50%`.
[](https://codecov.io/gh/tox-dev/tox/pull/669?src=pr&el=tree)
```diff
@@ Coverage Diff @@
## master #669 +/- ##
==========================================
- Coverage 93.86% 89.12% -4.75%
==========================================
Files 11 11
Lines 2364 2372 +8
Branches 0 401 +401
==========================================
- Hits 2219 2114 -105
- Misses 145 179 +34
- Partials 0 79 +79
```
| [Impacted Files](https://codecov.io/gh/tox-dev/tox/pull/669?src=pr&el=tree) | Coverage Δ | |
|---|---|---|
| [tox/config.py](https://codecov.io/gh/tox-dev/tox/pull/669?src=pr&el=tree#diff-dG94L2NvbmZpZy5weQ==) | `94.32% <50%> (-3.26%)` | :arrow_down: |
| [tox/interpreters.py](https://codecov.io/gh/tox-dev/tox/pull/669?src=pr&el=tree#diff-dG94L2ludGVycHJldGVycy5weQ==) | `59.37% <0%> (-22.66%)` | :arrow_down: |
| [tox/\_verlib.py](https://codecov.io/gh/tox-dev/tox/pull/669?src=pr&el=tree#diff-dG94L192ZXJsaWIucHk=) | `71.57% <0%> (-9.48%)` | :arrow_down: |
| [tox/\_quickstart.py](https://codecov.io/gh/tox-dev/tox/pull/669?src=pr&el=tree#diff-dG94L19xdWlja3N0YXJ0LnB5) | `77.62% <0%> (-5.6%)` | :arrow_down: |
| [tox/\_pytestplugin.py](https://codecov.io/gh/tox-dev/tox/pull/669?src=pr&el=tree#diff-dG94L19weXRlc3RwbHVnaW4ucHk=) | `89.15% <0%> (-4.82%)` | :arrow_down: |
| [tox/venv.py](https://codecov.io/gh/tox-dev/tox/pull/669?src=pr&el=tree#diff-dG94L3ZlbnYucHk=) | `92.52% <0%> (-3.74%)` | :arrow_down: |
| [tox/session.py](https://codecov.io/gh/tox-dev/tox/pull/669?src=pr&el=tree#diff-dG94L3Nlc3Npb24ucHk=) | `91.24% <0%> (-3.11%)` | :arrow_down: |
------
[Continue to review full report at Codecov](https://codecov.io/gh/tox-dev/tox/pull/669?src=pr&el=continue).
> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
> `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
> Powered by [Codecov](https://codecov.io/gh/tox-dev/tox/pull/669?src=pr&el=footer). Last update [cc34546...f47fb5d](https://codecov.io/gh/tox-dev/tox/pull/669?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).
asottile: It would be nice to use `shlex.split` but it turns out it's horribly broken in python2.6:
```
Python 2.6.9 (default, Jul 29 2017, 12:47:14)
[GCC 5.4.0 20160609] on linux4
Type "help", "copyright", "credits" or "license" for more information.
>>> import shlex
>>> shlex.split(u'hello world')
['h\x00\x00\x00e\x00\x00\x00l\x00\x00\x00l\x00\x00\x00o\x00\x00\x00', '\x00\x00\x00w\x00\x00\x00o\x00\x00\x00r\x00\x00\x00l\x00\x00\x00d\x00\x00\x00']
``` | diff --git a/.travis.yml b/.travis.yml
index 0b7da097..4910ea00 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -23,7 +23,7 @@ matrix:
language: generic
before_install: if [[ "$TRAVIS_OS_NAME" == "osx" ]]; then source .travis-osx; fi
-install: pip install --pre -U tox
+install: pip install six && pip install --pre -U tox
script: tox -e py
after_success:
- tox -e coverage
diff --git a/CONTRIBUTORS b/CONTRIBUTORS
index c1076cc0..c7592b45 100644
--- a/CONTRIBUTORS
+++ b/CONTRIBUTORS
@@ -18,11 +18,12 @@ Cyril Roelandt
Eli Collins
Eugene Yunak
Fernando L. Pereira
+Henk-Jaap Wagenaar
Igor Duarte Cardoso
Ionel Maries Cristian
-Ionel Maries Cristian
Itxaka Serrano
Jannis Leidel
+Johannes Christ
Josh Smeaton
Julian Krause
Krisztian Fekete
diff --git a/changelog/331.misc.rst b/changelog/331.misc.rst
new file mode 100644
index 00000000..e77d0e2d
--- /dev/null
+++ b/changelog/331.misc.rst
@@ -0,0 +1,1 @@
+Running ``tox`` without a ``setup.py`` now has a more friendly error message and gives troubleshooting suggestions - by @Volcyy.
diff --git a/changelog/663.misc.rst b/changelog/663.misc.rst
new file mode 100644
index 00000000..6852e188
--- /dev/null
+++ b/changelog/663.misc.rst
@@ -0,0 +1,1 @@
+Fix pycodestyle (formerly pep8) errors E741 (ambiguous variable names, in this case, 'l's) and remove ignore of this error in tox.ini - by @cryvate
diff --git a/changelog/668.feature.rst b/changelog/668.feature.rst
new file mode 100644
index 00000000..5493845c
--- /dev/null
+++ b/changelog/668.feature.rst
@@ -0,0 +1,1 @@
+Allow spaces in command line options to pip in deps. Where previously only ``deps=-rreq.txt`` and ``deps=--requirement=req.txt`` worked, now also ``deps=-r req.txt`` and ``deps=--requirement req.txt`` work - by @cryvate
diff --git a/doc/config.rst b/doc/config.rst
index 1cb1bf6a..11d27cd2 100644
--- a/doc/config.rst
+++ b/doc/config.rst
@@ -567,6 +567,11 @@ You can still list environments explicitly along with generated ones::
envlist = {py26,py27}-django{15,16}, docs, flake
+Keep in mind that whitespace characters (except newline) within ``{}``
+are stripped, so the following line defines the same environment names::
+
+ envlist = {py26, py27}-django{ 15, 16 }, docs, flake
+
.. note::
To help with understanding how the variants will produce section values,
diff --git a/tox.ini b/tox.ini
index 0ab76dfa..b190e388 100644
--- a/tox.ini
+++ b/tox.ini
@@ -47,8 +47,6 @@ commands = python -m flake8 --show-source tox setup.py {posargs}
[flake8]
max-complexity = 22
max-line-length = 99
-# TODO: fix E741
-ignore = E741
[testenv:py26-bare]
description = invoke the tox help message under Python 2.6
diff --git a/tox/config.py b/tox/config.py
index 7860b871..b056431b 100755
--- a/tox/config.py
+++ b/tox/config.py
@@ -31,6 +31,18 @@ hookimpl = pluggy.HookimplMarker("tox")
_dummy = object()
+PIP_INSTALL_SHORT_OPTIONS_ARGUMENT = ['-{0}'.format(option) for option in [
+ 'c', 'e', 'r', 'b', 't', 'd',
+]]
+
+PIP_INSTALL_LONG_OPTIONS_ARGUMENT = ['--{0}'.format(option) for option in [
+ 'constraint', 'editable', 'requirement', 'build', 'target', 'download',
+ 'src', 'upgrade-strategy', 'install-options', 'global-option',
+ 'root', 'prefix', 'no-binary', 'only-binary', 'index-url',
+ 'extra-index-url', 'find-links', 'proxy', 'retries', 'timeout',
+ 'exists-action', 'trusted-host', 'client-cert', 'cache-dir',
+]]
+
def get_plugin_manager(plugins=()):
# initialize plugin manager
@@ -124,6 +136,24 @@ class DepOption:
else:
name = depline.strip()
ixserver = None
+
+ # we need to process options, in case they contain a space,
+ # as the subprocess call to pip install will otherwise fail.
+
+ # in case of a short option, we remove the space
+ for option in PIP_INSTALL_SHORT_OPTIONS_ARGUMENT:
+ if name.startswith(option):
+ name = '{0}{1}'.format(
+ option, name[len(option):].strip()
+ )
+
+ # in case of a long option, we add an equal sign
+ for option in PIP_INSTALL_LONG_OPTIONS_ARGUMENT:
+ if name.startswith(option + ' '):
+ name = '{0}={1}'.format(
+ option, name[len(option):].strip()
+ )
+
name = self._replace_forced_dep(name, config)
deps.append(DepConfig(name, ixserver))
return deps
@@ -895,7 +925,7 @@ def _expand_envstr(envstr):
def expand(env):
tokens = re.split(r'\{([^}]+)\}', env)
- parts = [token.split(',') for token in tokens]
+ parts = [re.sub('\s+', '', token).split(',') for token in tokens]
return [''.join(variant) for variant in itertools.product(*parts)]
return mapcat(expand, envlist)
diff --git a/tox/result.py b/tox/result.py
index 06835500..47f68853 100644
--- a/tox/result.py
+++ b/tox/result.py
@@ -63,8 +63,7 @@ class EnvLog:
version=version)
def get_commandlog(self, name):
- l = self.dict.setdefault(name, [])
- return CommandLog(self, l)
+ return CommandLog(self, self.dict.setdefault(name, []))
def set_installed(self, packages):
self.dict["installed_packages"] = packages
diff --git a/tox/session.py b/tox/session.py
index 35cb4dc3..b2aeec6a 100644
--- a/tox/session.py
+++ b/tox/session.py
@@ -109,12 +109,11 @@ class Action(object):
else:
logdir = self.session.config.logdir
try:
- l = logdir.listdir("%s-*" % actionid)
+ log_count = len(logdir.listdir("%s-*" % actionid))
except (py.error.ENOENT, py.error.ENOTDIR):
logdir.ensure(dir=1)
- l = []
- num = len(l)
- path = logdir.join("%s-%s.log" % (actionid, num))
+ log_count = 0
+ path = logdir.join("%s-%s.log" % (actionid, log_count))
f = path.open('w')
f.flush()
return f
@@ -404,7 +403,17 @@ class Session:
def _makesdist(self):
setup = self.config.setupdir.join("setup.py")
if not setup.check():
- raise tox.exception.MissingFile(setup)
+ self.report.error(
+ "No setup.py file found. The expected location is:\n"
+ " %s\n"
+ "You can\n"
+ " 1. Create one:\n"
+ " https://packaging.python.org/tutorials/distributing-packages/#setup-py\n"
+ " 2. Configure tox to avoid running sdist:\n"
+ " http://tox.readthedocs.io/en/latest/example/general.html"
+ "#avoiding-expensive-sdist" % setup
+ )
+ raise SystemExit(1)
action = self.newaction(None, "packaging")
with action:
action.setactivity("sdist-make", setup)
diff --git a/tox/venv.py b/tox/venv.py
index 69cc0c49..af2a80b7 100755
--- a/tox/venv.py
+++ b/tox/venv.py
@@ -195,14 +195,14 @@ class VirtualEnv(object):
sitepackages, develop, deps, alwayscopy)
def _getresolvedeps(self):
- l = []
+ deps = []
for dep in self.envconfig.deps:
if dep.indexserver is None:
res = self.session._resolve_pkg(dep.name)
if res != dep.name:
dep = dep.__class__(res)
- l.append(dep)
- return l
+ deps.append(dep)
+ return deps
def getsupportedinterpreter(self):
return self.envconfig.getsupportedinterpreter()
@@ -273,12 +273,12 @@ class VirtualEnv(object):
self._install([sdistpath], extraopts=extraopts, action=action)
def _installopts(self, indexserver):
- l = []
+ options = []
if indexserver:
- l += ["-i", indexserver]
+ options += ["-i", indexserver]
if self.envconfig.pip_pre:
- l.append("--pre")
- return l
+ options.append("--pre")
+ return options
def run_install_command(self, packages, action, options=()):
argv = self.envconfig.install_command[:]
@@ -312,7 +312,7 @@ class VirtualEnv(object):
if not deps:
return
d = {}
- l = []
+ ixservers = []
for dep in deps:
if isinstance(dep, (str, py.path.local)):
dep = DepConfig(str(dep), None)
@@ -322,11 +322,11 @@ class VirtualEnv(object):
else:
ixserver = dep.indexserver
d.setdefault(ixserver, []).append(dep.name)
- if ixserver not in l:
- l.append(ixserver)
+ if ixserver not in ixservers:
+ ixservers.append(ixserver)
assert ixserver.url is None or isinstance(ixserver.url, str)
- for ixserver in l:
+ for ixserver in ixservers:
packages = d[ixserver]
options = self._installopts(ixserver.url)
if extraopts:
| Allow space after '-r' option in deps configuration file
I was cleaning up a ``tox.ini`` and attempted to change:
[testenv]
deps = -rfoo.txt
to
[testenv]
deps = -r foo.txt
to make it more readable, however it tries to read `` foo.txt`` (with space at beginning, lost when formatted) which does not exist and this was unexpected. I propose it strips whitespace so it is closer to accepting the pip format, as suggested by the ``deps`` option help: "each line specifies a dependency in pip/setuptools format."
[``pip`` itself uses its own config parser.](https://github.com/pypa/pip/blob/62a695c4b905b503f7ff38c0d47cf0ea203853ea/src/pip/_internal/req/req_file.py#L130)
I would be happy to write a PR myself, this can be implemented by adding:
if name.startswith('-r'):
name = '-r' + name[2:].strip()
[after this line.](https://github.com/tox-dev/tox/blob/master/tox/config.py#L125). | tox-dev/tox | diff --git a/tests/test_config.py b/tests/test_config.py
index d83114f7..30da4f04 100644
--- a/tests/test_config.py
+++ b/tests/test_config.py
@@ -118,6 +118,23 @@ class TestVenvConfig:
'dep1==1.5', 'https://pypi.python.org/xyz/pkg1.tar.gz'
]
+ def test_process_deps(self, newconfig):
+ config = newconfig([], """
+ [testenv]
+ deps =
+ -r requirements.txt
+ --index-url https://pypi.org/simple
+ -fhttps://pypi.org/packages
+ --global-option=foo
+ -v dep1
+ --help dep2
+ """) # note that those last two are invalid
+ assert [str(x) for x in config.envconfigs['python'].deps] == [
+ '-rrequirements.txt', '--index-url=https://pypi.org/simple',
+ '-fhttps://pypi.org/packages', '--global-option=foo',
+ '-v dep1', '--help dep2'
+ ]
+
def test_is_same_dep(self):
"""
Ensure correct parseini._is_same_dep is working with a few samples.
@@ -160,7 +177,7 @@ class TestConfigPlatform:
monkeypatch.setattr(sys, "platform", "win32")
config = newconfig([], """
[tox]
- envlist = py27-{win,lin,osx}
+ envlist = py27-{win, lin,osx }
[testenv]
platform =
win: win32
diff --git a/tests/test_venv.py b/tests/test_venv.py
index 527da88d..1eae6e4d 100644
--- a/tests/test_venv.py
+++ b/tests/test_venv.py
@@ -16,8 +16,7 @@ from tox.venv import VirtualEnv
# def test_global_virtualenv(capfd):
# v = VirtualEnv()
-# l = v.list()
-# assert l
+# assert v.list()
# out, err = capfd.readouterr()
# assert not out
# assert not err
@@ -62,9 +61,9 @@ def test_create(monkeypatch, mocksession, newconfig):
assert not venv.path.check()
action = mocksession.newaction(venv, "getenv")
tox_testenv_create(action=action, venv=venv)
- l = mocksession._pcalls
- assert len(l) >= 1
- args = l[0].args
+ pcalls = mocksession._pcalls
+ assert len(pcalls) >= 1
+ args = pcalls[0].args
assert "virtualenv" == str(args[2])
if sys.platform != "win32":
# realpath is needed for stuff like the debian symlinks
@@ -103,9 +102,9 @@ def test_create_sitepackages(monkeypatch, mocksession, newconfig):
venv = VirtualEnv(envconfig, session=mocksession)
action = mocksession.newaction(venv, "getenv")
tox_testenv_create(action=action, venv=venv)
- l = mocksession._pcalls
- assert len(l) >= 1
- args = l[0].args
+ pcalls = mocksession._pcalls
+ assert len(pcalls) >= 1
+ args = pcalls[0].args
assert "--system-site-packages" in map(str, args)
mocksession._clearmocks()
@@ -113,9 +112,9 @@ def test_create_sitepackages(monkeypatch, mocksession, newconfig):
venv = VirtualEnv(envconfig, session=mocksession)
action = mocksession.newaction(venv, "getenv")
tox_testenv_create(action=action, venv=venv)
- l = mocksession._pcalls
- assert len(l) >= 1
- args = l[0].args
+ pcalls = mocksession._pcalls
+ assert len(pcalls) >= 1
+ args = pcalls[0].args
assert "--system-site-packages" not in map(str, args)
assert "--no-site-packages" not in map(str, args)
@@ -131,16 +130,16 @@ def test_install_deps_wildcard(newmocksession):
venv = mocksession.getenv("py123")
action = mocksession.newaction(venv, "getenv")
tox_testenv_create(action=action, venv=venv)
- l = mocksession._pcalls
- assert len(l) == 1
+ pcalls = mocksession._pcalls
+ assert len(pcalls) == 1
distshare = venv.session.config.distshare
distshare.ensure("dep1-1.0.zip")
distshare.ensure("dep1-1.1.zip")
tox_testenv_install_deps(action=action, venv=venv)
- assert len(l) == 2
- args = l[-1].args
- assert l[-1].cwd == venv.envconfig.config.toxinidir
+ assert len(pcalls) == 2
+ args = pcalls[-1].args
+ assert pcalls[-1].cwd == venv.envconfig.config.toxinidir
assert "pip" in str(args[0])
assert args[1] == "install"
args = [arg for arg in args if str(arg).endswith("dep1-1.1.zip")]
@@ -162,21 +161,21 @@ def test_install_deps_indexserver(newmocksession):
venv = mocksession.getenv('py123')
action = mocksession.newaction(venv, "getenv")
tox_testenv_create(action=action, venv=venv)
- l = mocksession._pcalls
- assert len(l) == 1
- l[:] = []
+ pcalls = mocksession._pcalls
+ assert len(pcalls) == 1
+ pcalls[:] = []
tox_testenv_install_deps(action=action, venv=venv)
# two different index servers, two calls
- assert len(l) == 3
- args = " ".join(l[0].args)
+ assert len(pcalls) == 3
+ args = " ".join(pcalls[0].args)
assert "-i " not in args
assert "dep1" in args
- args = " ".join(l[1].args)
+ args = " ".join(pcalls[1].args)
assert "-i ABC" in args
assert "dep2" in args
- args = " ".join(l[2].args)
+ args = " ".join(pcalls[2].args)
assert "-i ABC" in args
assert "dep3" in args
@@ -191,13 +190,13 @@ def test_install_deps_pre(newmocksession):
venv = mocksession.getenv('python')
action = mocksession.newaction(venv, "getenv")
tox_testenv_create(action=action, venv=venv)
- l = mocksession._pcalls
- assert len(l) == 1
- l[:] = []
+ pcalls = mocksession._pcalls
+ assert len(pcalls) == 1
+ pcalls[:] = []
tox_testenv_install_deps(action=action, venv=venv)
- assert len(l) == 1
- args = " ".join(l[0].args)
+ assert len(pcalls) == 1
+ args = " ".join(pcalls[0].args)
assert "--pre " in args
assert "dep1" in args
@@ -209,12 +208,12 @@ def test_installpkg_indexserver(newmocksession, tmpdir):
default = ABC
""")
venv = mocksession.getenv('python')
- l = mocksession._pcalls
+ pcalls = mocksession._pcalls
p = tmpdir.ensure("distfile.tar.gz")
mocksession.installpkg(venv, p)
# two different index servers, two calls
- assert len(l) == 1
- args = " ".join(l[0].args)
+ assert len(pcalls) == 1
+ args = " ".join(pcalls[0].args)
assert "-i ABC" in args
@@ -243,12 +242,12 @@ def test_install_sdist_extras(newmocksession):
venv = mocksession.getenv('python')
action = mocksession.newaction(venv, "getenv")
tox_testenv_create(action=action, venv=venv)
- l = mocksession._pcalls
- assert len(l) == 1
- l[:] = []
+ pcalls = mocksession._pcalls
+ assert len(pcalls) == 1
+ pcalls[:] = []
venv.installpkg('distfile.tar.gz', action=action)
- assert 'distfile.tar.gz[testing,development]' in l[-1].args
+ assert 'distfile.tar.gz[testing,development]' in pcalls[-1].args
def test_develop_extras(newmocksession, tmpdir):
@@ -260,13 +259,13 @@ def test_develop_extras(newmocksession, tmpdir):
venv = mocksession.getenv('python')
action = mocksession.newaction(venv, "getenv")
tox_testenv_create(action=action, venv=venv)
- l = mocksession._pcalls
- assert len(l) == 1
- l[:] = []
+ pcalls = mocksession._pcalls
+ assert len(pcalls) == 1
+ pcalls[:] = []
venv.developpkg(tmpdir, action=action)
expected = "%s[testing,development]" % tmpdir.strpath
- assert expected in l[-1].args
+ assert expected in pcalls[-1].args
def test_env_variables_added_to_needs_reinstall(tmpdir, mocksession, newconfig, monkeypatch):
@@ -285,9 +284,9 @@ def test_env_variables_added_to_needs_reinstall(tmpdir, mocksession, newconfig,
venv._needs_reinstall(tmpdir, action)
- l = mocksession._pcalls
- assert len(l) == 2
- env = l[0].env
+ pcalls = mocksession._pcalls
+ assert len(pcalls) == 2
+ env = pcalls[0].env
# should have access to setenv vars
assert 'CUSTOM_VAR' in env
@@ -397,15 +396,15 @@ def test_install_python3(tmpdir, newmocksession):
venv = mocksession.getenv('py123')
action = mocksession.newaction(venv, "getenv")
tox_testenv_create(action=action, venv=venv)
- l = mocksession._pcalls
- assert len(l) == 1
- args = l[0].args
+ pcalls = mocksession._pcalls
+ assert len(pcalls) == 1
+ args = pcalls[0].args
assert str(args[2]) == 'virtualenv'
- l[:] = []
+ pcalls[:] = []
action = mocksession.newaction(venv, "hello")
venv._install(["hello"], action=action)
- assert len(l) == 1
- args = l[0].args
+ assert len(pcalls) == 1
+ args = pcalls[0].args
assert "pip" in args[0]
for _ in args:
assert "--download-cache" not in args, args
@@ -543,19 +542,19 @@ class TestVenvTest:
venv = mocksession.getenv("python")
action = mocksession.newaction(venv, "getenv")
monkeypatch.setenv("PATH", "xyz")
- l = []
+ sysfind_calls = []
monkeypatch.setattr("py.path.local.sysfind", classmethod(
- lambda *args, **kwargs: l.append(kwargs) or 0 / 0))
+ lambda *args, **kwargs: sysfind_calls.append(kwargs) or 0 / 0))
with pytest.raises(ZeroDivisionError):
venv._install(list('123'), action=action)
- assert l.pop()["paths"] == [venv.envconfig.envbindir]
+ assert sysfind_calls.pop()["paths"] == [venv.envconfig.envbindir]
with pytest.raises(ZeroDivisionError):
venv.test(action)
- assert l.pop()["paths"] == [venv.envconfig.envbindir]
+ assert sysfind_calls.pop()["paths"] == [venv.envconfig.envbindir]
with pytest.raises(ZeroDivisionError):
venv.run_install_command(['qwe'], action=action)
- assert l.pop()["paths"] == [venv.envconfig.envbindir]
+ assert sysfind_calls.pop()["paths"] == [venv.envconfig.envbindir]
monkeypatch.setenv("PIP_RESPECT_VIRTUALENV", "1")
monkeypatch.setenv("PIP_REQUIRE_VIRTUALENV", "1")
monkeypatch.setenv("__PYVENV_LAUNCHER__", "1")
@@ -576,9 +575,9 @@ class TestVenvTest:
assert 'PYTHONPATH' not in os.environ
mocksession.report.expect("warning", "*Discarding $PYTHONPATH from environment*")
- l = mocksession._pcalls
- assert len(l) == 1
- assert 'PYTHONPATH' not in l[0].env
+ pcalls = mocksession._pcalls
+ assert len(pcalls) == 1
+ assert 'PYTHONPATH' not in pcalls[0].env
# passenv = PYTHONPATH allows PYTHONPATH to stay in environment
monkeypatch.setenv("PYTHONPATH", "/my/awesome/library")
@@ -593,9 +592,9 @@ class TestVenvTest:
assert 'PYTHONPATH' in os.environ
mocksession.report.not_expect("warning", "*Discarding $PYTHONPATH from environment*")
- l = mocksession._pcalls
- assert len(l) == 2
- assert l[1].env['PYTHONPATH'] == '/my/awesome/library'
+ pcalls = mocksession._pcalls
+ assert len(pcalls) == 2
+ assert pcalls[1].env['PYTHONPATH'] == '/my/awesome/library'
# FIXME this test fails when run in isolation - find what this depends on
@@ -618,9 +617,9 @@ def test_env_variables_added_to_pcall(tmpdir, mocksession, newconfig, monkeypatc
mocksession.installpkg(venv, pkg)
venv.test()
- l = mocksession._pcalls
- assert len(l) == 2
- for x in l:
+ pcalls = mocksession._pcalls
+ assert len(pcalls) == 2
+ for x in pcalls:
env = x.env
assert env is not None
assert 'ENV_VAR' in env
@@ -630,11 +629,11 @@ def test_env_variables_added_to_pcall(tmpdir, mocksession, newconfig, monkeypatc
assert 'PYTHONPATH' in env
assert env['PYTHONPATH'] == 'value'
# all env variables are passed for installation
- assert l[0].env["YY"] == "456"
- assert "YY" not in l[1].env
+ assert pcalls[0].env["YY"] == "456"
+ assert "YY" not in pcalls[1].env
assert set(["ENV_VAR", "VIRTUAL_ENV", "PYTHONHASHSEED", "X123", "PATH"])\
- .issubset(l[1].env)
+ .issubset(pcalls[1].env)
# setenv does not trigger PYTHONPATH warnings
mocksession.report.not_expect("warning", "*Discarding $PYTHONPATH from environment*")
@@ -650,9 +649,9 @@ def test_installpkg_no_upgrade(tmpdir, newmocksession):
venv.just_created = True
venv.envconfig.envdir.ensure(dir=1)
mocksession.installpkg(venv, pkg)
- l = mocksession._pcalls
- assert len(l) == 1
- assert '-U' not in l[0].args
+ pcalls = mocksession._pcalls
+ assert len(pcalls) == 1
+ assert '-U' not in pcalls[0].args
def test_installpkg_upgrade(newmocksession, tmpdir):
@@ -661,12 +660,12 @@ def test_installpkg_upgrade(newmocksession, tmpdir):
venv = mocksession.getenv('python')
assert not hasattr(venv, 'just_created')
mocksession.installpkg(venv, pkg)
- l = mocksession._pcalls
- assert len(l) == 1
- index = l[0].args.index(str(pkg))
+ pcalls = mocksession._pcalls
+ assert len(pcalls) == 1
+ index = pcalls[0].args.index(str(pkg))
assert index >= 0
- assert '-U' in l[0].args[:index]
- assert '--no-deps' in l[0].args[:index]
+ assert '-U' in pcalls[0].args[:index]
+ assert '--no-deps' in pcalls[0].args[:index]
def test_run_install_command(newmocksession):
@@ -676,11 +675,11 @@ def test_run_install_command(newmocksession):
venv.envconfig.envdir.ensure(dir=1)
action = mocksession.newaction(venv, "hello")
venv.run_install_command(packages=["whatever"], action=action)
- l = mocksession._pcalls
- assert len(l) == 1
- assert 'pip' in l[0].args[0]
- assert 'install' in l[0].args
- env = l[0].env
+ pcalls = mocksession._pcalls
+ assert len(pcalls) == 1
+ assert 'pip' in pcalls[0].args[0]
+ assert 'install' in pcalls[0].args
+ env = pcalls[0].env
assert env is not None
@@ -694,10 +693,10 @@ def test_run_custom_install_command(newmocksession):
venv.envconfig.envdir.ensure(dir=1)
action = mocksession.newaction(venv, "hello")
venv.run_install_command(packages=["whatever"], action=action)
- l = mocksession._pcalls
- assert len(l) == 1
- assert 'easy_install' in l[0].args[0]
- assert l[0].args[1:] == ['whatever']
+ pcalls = mocksession._pcalls
+ assert len(pcalls) == 1
+ assert 'easy_install' in pcalls[0].args[0]
+ assert pcalls[0].args[1:] == ['whatever']
def test_command_relative_issue26(newmocksession, tmpdir, monkeypatch):
@@ -733,16 +732,16 @@ def test_ignore_outcome_failing_cmd(newmocksession):
def test_tox_testenv_create(newmocksession):
- l = []
+ log = []
class Plugin:
@hookimpl
def tox_testenv_create(self, action, venv):
- l.append(1)
+ log.append(1)
@hookimpl
def tox_testenv_install_deps(self, action, venv):
- l.append(2)
+ log.append(2)
mocksession = newmocksession([], """
[testenv]
@@ -752,20 +751,20 @@ def test_tox_testenv_create(newmocksession):
venv = mocksession.getenv('python')
venv.update(action=mocksession.newaction(venv, "getenv"))
- assert l == [1, 2]
+ assert log == [1, 2]
def test_tox_testenv_pre_post(newmocksession):
- l = []
+ log = []
class Plugin:
@hookimpl
def tox_runtest_pre(self, venv):
- l.append('started')
+ log.append('started')
@hookimpl
def tox_runtest_post(self, venv):
- l.append('finished')
+ log.append('finished')
mocksession = newmocksession([], """
[testenv]
@@ -774,6 +773,6 @@ def test_tox_testenv_pre_post(newmocksession):
venv = mocksession.getenv('python')
venv.status = None
- assert l == []
+ assert log == []
mocksession.runtestenv(venv)
- assert l == ['started', 'finished']
+ assert log == ['started', 'finished']
diff --git a/tests/test_z_cmdline.py b/tests/test_z_cmdline.py
index a856c2f4..91122456 100644
--- a/tests/test_z_cmdline.py
+++ b/tests/test_z_cmdline.py
@@ -1,3 +1,4 @@
+import os
import platform
import py
@@ -454,6 +455,21 @@ def test_sdist_fails(cmd, initproj):
])
+def test_no_setup_py_exits(cmd, initproj):
+ initproj("pkg123-0.7", filedefs={
+ 'tox.ini': """
+ [testenv]
+ commands=python -c "2 + 2"
+ """
+ })
+ os.remove("setup.py")
+ result = cmd.run("tox", )
+ assert result.ret
+ result.stdout.fnmatch_lines([
+ "*ERROR*No setup.py file found*"
+ ])
+
+
def test_package_install_fails(cmd, initproj):
initproj("pkg123-0.7", filedefs={
'tests': {'test_hello.py': "def test_hello(): pass"},
@@ -747,9 +763,9 @@ def test_separate_sdist_no_sdistfile(cmd, initproj):
})
result = cmd.run("tox", "--sdistonly")
assert not result.ret
- l = distshare.listdir()
- assert len(l) == 1
- sdistfile = l[0]
+ distshare_files = distshare.listdir()
+ assert len(distshare_files) == 1
+ sdistfile = distshare_files[0]
assert 'pkg123-foo-0.7.zip' in str(sdistfile)
@@ -764,9 +780,9 @@ def test_separate_sdist(cmd, initproj):
})
result = cmd.run("tox", "--sdistonly")
assert not result.ret
- l = distshare.listdir()
- assert len(l) == 1
- sdistfile = l[0]
+ sdistfiles = distshare.listdir()
+ assert len(sdistfiles) == 1
+ sdistfile = sdistfiles[0]
result = cmd.run("tox", "-v", "--notest")
assert not result.ret
result.stdout.fnmatch_lines([
| {
"commit_name": "merge_commit",
"failed_lite_validators": [
"has_hyperlinks",
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 0,
"test_score": 3
},
"num_modified_files": 8
} | 2.9 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-cov",
"pytest-timeout",
"pytest-xdist"
],
"pre_install": null,
"python": "3.6",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs==22.2.0
certifi==2021.5.30
coverage==6.2
distlib==0.3.9
execnet==1.9.0
filelock==3.4.1
importlib-metadata==4.8.3
importlib-resources==5.4.0
iniconfig==1.1.1
packaging==21.3
platformdirs==2.4.0
pluggy==0.13.1
py==1.11.0
pyparsing==3.1.4
pytest==7.0.1
pytest-cov==4.0.0
pytest-timeout==2.1.0
pytest-xdist==3.0.2
six==1.17.0
tomli==1.2.3
-e git+https://github.com/tox-dev/tox.git@cc34546210701f099f59ec79016c4ec058749559#egg=tox
typing_extensions==4.1.1
virtualenv==20.17.1
zipp==3.6.0
| name: tox
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- attrs==22.2.0
- coverage==6.2
- distlib==0.3.9
- execnet==1.9.0
- filelock==3.4.1
- importlib-metadata==4.8.3
- importlib-resources==5.4.0
- iniconfig==1.1.1
- packaging==21.3
- platformdirs==2.4.0
- pluggy==0.13.1
- py==1.11.0
- pyparsing==3.1.4
- pytest==7.0.1
- pytest-cov==4.0.0
- pytest-timeout==2.1.0
- pytest-xdist==3.0.2
- six==1.17.0
- tomli==1.2.3
- typing-extensions==4.1.1
- virtualenv==20.17.1
- zipp==3.6.0
prefix: /opt/conda/envs/tox
| [
"tests/test_config.py::TestVenvConfig::test_process_deps",
"tests/test_config.py::TestConfigPlatform::test_config_parse_platform_with_factors[lin]",
"tests/test_z_cmdline.py::test_no_setup_py_exits"
]
| [
"test_hello.py::test_fail",
"tests/test_config.py::TestVenvConfig::test_force_dep_with_url",
"tests/test_config.py::TestIniParser::test_getbool",
"tests/test_venv.py::test_create",
"tests/test_venv.py::test_install_deps_wildcard",
"tests/test_venv.py::test_install_deps_indexserver",
"tests/test_venv.py::test_install_deps_pre",
"tests/test_venv.py::test_installpkg_indexserver",
"tests/test_venv.py::test_install_recreate",
"tests/test_venv.py::test_install_sdist_extras",
"tests/test_venv.py::test_develop_extras",
"tests/test_venv.py::TestCreationConfig::test_python_recreation",
"tests/test_venv.py::TestVenvTest::test_envbinddir_path",
"tests/test_venv.py::TestVenvTest::test_pythonpath_usage",
"tests/test_venv.py::test_env_variables_added_to_pcall",
"tests/test_venv.py::test_installpkg_no_upgrade",
"tests/test_venv.py::test_installpkg_upgrade",
"tests/test_venv.py::test_run_install_command",
"tests/test_venv.py::test_run_custom_install_command",
"tests/test_z_cmdline.py::test_report_protocol",
"tests/test_z_cmdline.py::test__resolve_pkg"
]
| [
"tests/test_config.py::TestVenvConfig::test_config_parsing_minimal",
"tests/test_config.py::TestVenvConfig::test_config_parsing_multienv",
"tests/test_config.py::TestVenvConfig::test_envdir_set_manually",
"tests/test_config.py::TestVenvConfig::test_envdir_set_manually_with_substitutions",
"tests/test_config.py::TestVenvConfig::test_force_dep_version",
"tests/test_config.py::TestVenvConfig::test_is_same_dep",
"tests/test_config.py::TestConfigPlatform::test_config_parse_platform",
"tests/test_config.py::TestConfigPlatform::test_config_parse_platform_rex",
"tests/test_config.py::TestConfigPlatform::test_config_parse_platform_with_factors[win]",
"tests/test_config.py::TestConfigPackage::test_defaults",
"tests/test_config.py::TestConfigPackage::test_defaults_distshare",
"tests/test_config.py::TestConfigPackage::test_defaults_changed_dir",
"tests/test_config.py::TestConfigPackage::test_project_paths",
"tests/test_config.py::TestParseconfig::test_search_parents",
"tests/test_config.py::TestParseconfig::test_explicit_config_path",
"tests/test_config.py::test_get_homedir",
"tests/test_config.py::TestGetcontextname::test_blank",
"tests/test_config.py::TestGetcontextname::test_jenkins",
"tests/test_config.py::TestGetcontextname::test_hudson_legacy",
"tests/test_config.py::TestIniParserAgainstCommandsKey::test_command_substitution_from_other_section",
"tests/test_config.py::TestIniParserAgainstCommandsKey::test_command_substitution_from_other_section_multiline",
"tests/test_config.py::TestIniParserAgainstCommandsKey::test_command_substitution_from_other_section_posargs",
"tests/test_config.py::TestIniParserAgainstCommandsKey::test_command_section_and_posargs_substitution",
"tests/test_config.py::TestIniParserAgainstCommandsKey::test_command_env_substitution",
"tests/test_config.py::TestIniParserAgainstCommandsKey::test_command_env_substitution_global",
"tests/test_config.py::TestIniParserAgainstCommandsKey::test_regression_issue595",
"tests/test_config.py::TestIniParser::test_getstring_single",
"tests/test_config.py::TestIniParser::test_missing_substitution",
"tests/test_config.py::TestIniParser::test_getstring_fallback_sections",
"tests/test_config.py::TestIniParser::test_getstring_substitution",
"tests/test_config.py::TestIniParser::test_getlist",
"tests/test_config.py::TestIniParser::test_getdict",
"tests/test_config.py::TestIniParser::test_normal_env_sub_works",
"tests/test_config.py::TestIniParser::test_missing_env_sub_raises_config_error_in_non_testenv",
"tests/test_config.py::TestIniParser::test_missing_env_sub_populates_missing_subs",
"tests/test_config.py::TestIniParser::test_getstring_environment_substitution_with_default",
"tests/test_config.py::TestIniParser::test_value_matches_section_substitution",
"tests/test_config.py::TestIniParser::test_value_doesn_match_section_substitution",
"tests/test_config.py::TestIniParser::test_getstring_other_section_substitution",
"tests/test_config.py::TestIniParser::test_argvlist",
"tests/test_config.py::TestIniParser::test_argvlist_windows_escaping",
"tests/test_config.py::TestIniParser::test_argvlist_multiline",
"tests/test_config.py::TestIniParser::test_argvlist_quoting_in_command",
"tests/test_config.py::TestIniParser::test_argvlist_comment_after_command",
"tests/test_config.py::TestIniParser::test_argvlist_command_contains_hash",
"tests/test_config.py::TestIniParser::test_argvlist_positional_substitution",
"tests/test_config.py::TestIniParser::test_argvlist_quoted_posargs",
"tests/test_config.py::TestIniParser::test_argvlist_posargs_with_quotes",
"tests/test_config.py::TestIniParser::test_positional_arguments_are_only_replaced_when_standing_alone",
"tests/test_config.py::TestIniParser::test_posargs_are_added_escaped_issue310",
"tests/test_config.py::TestIniParser::test_substitution_with_multiple_words",
"tests/test_config.py::TestIniParser::test_getargv",
"tests/test_config.py::TestIniParser::test_getpath",
"tests/test_config.py::TestIniParserPrefix::test_basic_section_access",
"tests/test_config.py::TestIniParserPrefix::test_fallback_sections",
"tests/test_config.py::TestIniParserPrefix::test_value_matches_prefixed_section_substitution",
"tests/test_config.py::TestIniParserPrefix::test_value_doesn_match_prefixed_section_substitution",
"tests/test_config.py::TestIniParserPrefix::test_other_section_substitution",
"tests/test_config.py::TestConfigTestEnv::test_commentchars_issue33",
"tests/test_config.py::TestConfigTestEnv::test_defaults",
"tests/test_config.py::TestConfigTestEnv::test_sitepackages_switch",
"tests/test_config.py::TestConfigTestEnv::test_installpkg_tops_develop",
"tests/test_config.py::TestConfigTestEnv::test_specific_command_overrides",
"tests/test_config.py::TestConfigTestEnv::test_whitelist_externals",
"tests/test_config.py::TestConfigTestEnv::test_changedir",
"tests/test_config.py::TestConfigTestEnv::test_ignore_errors",
"tests/test_config.py::TestConfigTestEnv::test_envbindir",
"tests/test_config.py::TestConfigTestEnv::test_envbindir_jython[jython]",
"tests/test_config.py::TestConfigTestEnv::test_envbindir_jython[pypy]",
"tests/test_config.py::TestConfigTestEnv::test_envbindir_jython[pypy3]",
"tests/test_config.py::TestConfigTestEnv::test_passenv_as_multiline_list[win32]",
"tests/test_config.py::TestConfigTestEnv::test_passenv_as_multiline_list[linux2]",
"tests/test_config.py::TestConfigTestEnv::test_passenv_as_space_separated_list[win32]",
"tests/test_config.py::TestConfigTestEnv::test_passenv_as_space_separated_list[linux2]",
"tests/test_config.py::TestConfigTestEnv::test_passenv_with_factor",
"tests/test_config.py::TestConfigTestEnv::test_passenv_from_global_env",
"tests/test_config.py::TestConfigTestEnv::test_passenv_glob_from_global_env",
"tests/test_config.py::TestConfigTestEnv::test_changedir_override",
"tests/test_config.py::TestConfigTestEnv::test_install_command_setting",
"tests/test_config.py::TestConfigTestEnv::test_install_command_must_contain_packages",
"tests/test_config.py::TestConfigTestEnv::test_install_command_substitutions",
"tests/test_config.py::TestConfigTestEnv::test_pip_pre",
"tests/test_config.py::TestConfigTestEnv::test_pip_pre_cmdline_override",
"tests/test_config.py::TestConfigTestEnv::test_simple",
"tests/test_config.py::TestConfigTestEnv::test_substitution_error",
"tests/test_config.py::TestConfigTestEnv::test_substitution_defaults",
"tests/test_config.py::TestConfigTestEnv::test_substitution_notfound_issue246",
"tests/test_config.py::TestConfigTestEnv::test_substitution_notfound_issue515",
"tests/test_config.py::TestConfigTestEnv::test_substitution_nested_env_defaults",
"tests/test_config.py::TestConfigTestEnv::test_substitution_positional",
"tests/test_config.py::TestConfigTestEnv::test_substitution_noargs_issue240",
"tests/test_config.py::TestConfigTestEnv::test_substitution_double",
"tests/test_config.py::TestConfigTestEnv::test_posargs_backslashed_or_quoted",
"tests/test_config.py::TestConfigTestEnv::test_rewrite_posargs",
"tests/test_config.py::TestConfigTestEnv::test_rewrite_simple_posargs",
"tests/test_config.py::TestConfigTestEnv::test_take_dependencies_from_other_testenv[envlist0-deps0]",
"tests/test_config.py::TestConfigTestEnv::test_take_dependencies_from_other_testenv[envlist1-deps1]",
"tests/test_config.py::TestConfigTestEnv::test_take_dependencies_from_other_section",
"tests/test_config.py::TestConfigTestEnv::test_multilevel_substitution",
"tests/test_config.py::TestConfigTestEnv::test_recursive_substitution_cycle_fails",
"tests/test_config.py::TestConfigTestEnv::test_single_value_from_other_secton",
"tests/test_config.py::TestConfigTestEnv::test_factors",
"tests/test_config.py::TestConfigTestEnv::test_factor_ops",
"tests/test_config.py::TestConfigTestEnv::test_default_factors",
"tests/test_config.py::TestConfigTestEnv::test_factors_in_boolean",
"tests/test_config.py::TestConfigTestEnv::test_factors_in_setenv",
"tests/test_config.py::TestConfigTestEnv::test_factor_use_not_checked",
"tests/test_config.py::TestConfigTestEnv::test_factors_groups_touch",
"tests/test_config.py::TestConfigTestEnv::test_period_in_factor",
"tests/test_config.py::TestConfigTestEnv::test_ignore_outcome",
"tests/test_config.py::TestGlobalOptions::test_notest",
"tests/test_config.py::TestGlobalOptions::test_verbosity",
"tests/test_config.py::TestGlobalOptions::test_substitution_jenkins_default",
"tests/test_config.py::TestGlobalOptions::test_substitution_jenkins_context",
"tests/test_config.py::TestGlobalOptions::test_sdist_specification",
"tests/test_config.py::TestGlobalOptions::test_env_selection",
"tests/test_config.py::TestGlobalOptions::test_py_venv",
"tests/test_config.py::TestGlobalOptions::test_default_environments",
"tests/test_config.py::TestGlobalOptions::test_envlist_expansion",
"tests/test_config.py::TestGlobalOptions::test_envlist_cross_product",
"tests/test_config.py::TestGlobalOptions::test_envlist_multiline",
"tests/test_config.py::TestGlobalOptions::test_minversion",
"tests/test_config.py::TestGlobalOptions::test_skip_missing_interpreters_true",
"tests/test_config.py::TestGlobalOptions::test_skip_missing_interpreters_false",
"tests/test_config.py::TestGlobalOptions::test_defaultenv_commandline",
"tests/test_config.py::TestGlobalOptions::test_defaultenv_partial_override",
"tests/test_config.py::TestHashseedOption::test_default",
"tests/test_config.py::TestHashseedOption::test_passing_integer",
"tests/test_config.py::TestHashseedOption::test_passing_string",
"tests/test_config.py::TestHashseedOption::test_passing_empty_string",
"tests/test_config.py::TestHashseedOption::test_passing_no_argument",
"tests/test_config.py::TestHashseedOption::test_setenv",
"tests/test_config.py::TestHashseedOption::test_noset",
"tests/test_config.py::TestHashseedOption::test_noset_with_setenv",
"tests/test_config.py::TestHashseedOption::test_one_random_hashseed",
"tests/test_config.py::TestHashseedOption::test_setenv_in_one_testenv",
"tests/test_config.py::TestSetenv::test_getdict_lazy",
"tests/test_config.py::TestSetenv::test_getdict_lazy_update",
"tests/test_config.py::TestSetenv::test_setenv_uses_os_environ",
"tests/test_config.py::TestSetenv::test_setenv_default_os_environ",
"tests/test_config.py::TestSetenv::test_setenv_uses_other_setenv",
"tests/test_config.py::TestSetenv::test_setenv_recursive_direct",
"tests/test_config.py::TestSetenv::test_setenv_overrides",
"tests/test_config.py::TestSetenv::test_setenv_with_envdir_and_basepython",
"tests/test_config.py::TestSetenv::test_setenv_ordering_1",
"tests/test_config.py::TestSetenv::test_setenv_cross_section_subst_issue294",
"tests/test_config.py::TestSetenv::test_setenv_cross_section_subst_twice",
"tests/test_config.py::TestSetenv::test_setenv_cross_section_mixed",
"tests/test_config.py::TestIndexServer::test_indexserver",
"tests/test_config.py::TestIndexServer::test_parse_indexserver",
"tests/test_config.py::TestIndexServer::test_multiple_homedir_relative_local_indexservers",
"tests/test_config.py::TestConfigConstSubstitutions::test_replace_pathsep_unix[:]",
"tests/test_config.py::TestConfigConstSubstitutions::test_replace_pathsep_unix[;]",
"tests/test_config.py::TestConfigConstSubstitutions::test_pathsep_regex",
"tests/test_config.py::TestParseEnv::test_parse_recreate",
"tests/test_config.py::TestCmdInvocation::test_help",
"tests/test_config.py::TestCmdInvocation::test_version_simple",
"tests/test_config.py::TestCmdInvocation::test_version_no_plugins",
"tests/test_config.py::TestCmdInvocation::test_version_with_normal_plugin",
"tests/test_config.py::TestCmdInvocation::test_version_with_fileless_module",
"tests/test_config.py::TestCmdInvocation::test_listenvs",
"tests/test_config.py::TestCmdInvocation::test_listenvs_verbose_description",
"tests/test_config.py::TestCmdInvocation::test_listenvs_all",
"tests/test_config.py::TestCmdInvocation::test_listenvs_all_verbose_description",
"tests/test_config.py::TestCmdInvocation::test_listenvs_all_verbose_description_no_additional_environments",
"tests/test_config.py::TestCmdInvocation::test_config_specific_ini",
"tests/test_config.py::TestCmdInvocation::test_no_tox_ini",
"tests/test_config.py::TestCmdInvocation::test_override_workdir",
"tests/test_config.py::TestCmdInvocation::test_showconfig_with_force_dep_version",
"tests/test_config.py::test_env_spec[-e",
"tests/test_config.py::TestCommandParser::test_command_parser_for_word",
"tests/test_config.py::TestCommandParser::test_command_parser_for_posargs",
"tests/test_config.py::TestCommandParser::test_command_parser_for_multiple_words",
"tests/test_config.py::TestCommandParser::test_command_parser_for_substitution_with_spaces",
"tests/test_config.py::TestCommandParser::test_command_parser_with_complex_word_set",
"tests/test_config.py::TestCommandParser::test_command_with_runs_of_whitespace",
"tests/test_config.py::TestCommandParser::test_command_with_split_line_in_subst_arguments",
"tests/test_config.py::TestCommandParser::test_command_parsing_for_issue_10",
"tests/test_venv.py::test_getdigest",
"tests/test_venv.py::test_getsupportedinterpreter",
"tests/test_venv.py::test_commandpath_venv_precedence",
"tests/test_venv.py::test_create_sitepackages",
"tests/test_venv.py::test_env_variables_added_to_needs_reinstall",
"tests/test_venv.py::test_test_hashseed_is_in_output",
"tests/test_venv.py::test_test_runtests_action_command_is_in_output",
"tests/test_venv.py::test_install_error",
"tests/test_venv.py::test_install_command_not_installed",
"tests/test_venv.py::test_install_command_whitelisted",
"tests/test_venv.py::test_install_command_not_installed_bash",
"tests/test_venv.py::TestCreationConfig::test_basic",
"tests/test_venv.py::TestCreationConfig::test_matchingdependencies",
"tests/test_venv.py::TestCreationConfig::test_matchingdependencies_file",
"tests/test_venv.py::TestCreationConfig::test_matchingdependencies_latest",
"tests/test_venv.py::TestCreationConfig::test_dep_recreation",
"tests/test_venv.py::TestCreationConfig::test_develop_recreation",
"tests/test_venv.py::test_command_relative_issue26",
"tests/test_venv.py::test_ignore_outcome_failing_cmd",
"tests/test_venv.py::test_tox_testenv_create",
"tests/test_venv.py::test_tox_testenv_pre_post",
"tests/test_z_cmdline.py::test__resolve_pkg_doubledash",
"tests/test_z_cmdline.py::TestSession::test_make_sdist",
"tests/test_z_cmdline.py::TestSession::test_make_sdist_distshare",
"tests/test_z_cmdline.py::TestSession::test_log_pcall",
"tests/test_z_cmdline.py::TestSession::test_summary_status",
"tests/test_z_cmdline.py::TestSession::test_getvenv",
"tests/test_z_cmdline.py::test_minversion",
"tests/test_z_cmdline.py::test_notoxini_help_still_works",
"tests/test_z_cmdline.py::test_notoxini_help_ini_still_works",
"tests/test_z_cmdline.py::test_envdir_equals_toxini_errors_out",
"tests/test_z_cmdline.py::test_run_custom_install_command_error",
"tests/test_z_cmdline.py::test_unknown_interpreter_and_env",
"tests/test_z_cmdline.py::test_unknown_interpreter",
"tests/test_z_cmdline.py::test_skip_platform_mismatch",
"tests/test_z_cmdline.py::test_skip_unknown_interpreter",
"tests/test_z_cmdline.py::test_unknown_dep",
"tests/test_z_cmdline.py::test_venv_special_chars_issue252",
"tests/test_z_cmdline.py::test_unknown_environment",
"tests/test_z_cmdline.py::test_skip_sdist",
"tests/test_z_cmdline.py::test_minimal_setup_py_empty",
"tests/test_z_cmdline.py::test_minimal_setup_py_comment_only",
"tests/test_z_cmdline.py::test_minimal_setup_py_non_functional",
"tests/test_z_cmdline.py::test_sdist_fails",
"tests/test_z_cmdline.py::test_package_install_fails",
"tests/test_z_cmdline.py::TestToxRun::test_toxuone_env",
"tests/test_z_cmdline.py::TestToxRun::test_different_config_cwd",
"tests/test_z_cmdline.py::TestToxRun::test_json",
"tests/test_z_cmdline.py::test_develop",
"tests/test_z_cmdline.py::test_usedevelop",
"tests/test_z_cmdline.py::test_usedevelop_mixed",
"tests/test_z_cmdline.py::test_test_usedevelop[.]",
"tests/test_z_cmdline.py::test_test_usedevelop[src]",
"tests/test_z_cmdline.py::test_alwayscopy",
"tests/test_z_cmdline.py::test_alwayscopy_default",
"tests/test_z_cmdline.py::test_test_piphelp",
"tests/test_z_cmdline.py::test_notest",
"tests/test_z_cmdline.py::test_PYC",
"tests/test_z_cmdline.py::test_env_VIRTUALENV_PYTHON",
"tests/test_z_cmdline.py::test_sdistonly",
"tests/test_z_cmdline.py::test_separate_sdist_no_sdistfile",
"tests/test_z_cmdline.py::test_separate_sdist",
"tests/test_z_cmdline.py::test_sdist_latest",
"tests/test_z_cmdline.py::test_installpkg",
"tests/test_z_cmdline.py::test_envsitepackagesdir",
"tests/test_z_cmdline.py::test_envsitepackagesdir_skip_missing_issue280",
"tests/test_z_cmdline.py::test_verbosity[]",
"tests/test_z_cmdline.py::test_verbosity[-v]",
"tests/test_z_cmdline.py::test_verbosity[-vv]",
"tests/test_z_cmdline.py::test_envtmpdir",
"tests/test_z_cmdline.py::test_missing_env_fails"
]
| []
| MIT License | 1,854 | [
"tox/session.py",
"doc/config.rst",
"tox/config.py",
"tox/venv.py",
"tox/result.py",
"changelog/668.feature.rst",
"CONTRIBUTORS",
".travis.yml",
"tox.ini",
"changelog/663.misc.rst",
"changelog/331.misc.rst"
]
| [
"tox/session.py",
"doc/config.rst",
"tox/config.py",
"tox/venv.py",
"tox/result.py",
"changelog/668.feature.rst",
"CONTRIBUTORS",
".travis.yml",
"tox.ini",
"changelog/663.misc.rst",
"changelog/331.misc.rst"
]
|
Netuitive__netuitive-client-python-18 | 53087a9f6e6bc2e805ae3793f5c4417927f6f3f7 | 2017-11-06 20:03:36 | 53087a9f6e6bc2e805ae3793f5c4417927f6f3f7 | diff --git a/netuitive/check.py b/netuitive/check.py
index b851282..2dd7858 100644
--- a/netuitive/check.py
+++ b/netuitive/check.py
@@ -7,15 +7,15 @@ class Check(object):
:type name: string
:param elementId: Associated Element ID
:type elementId: string
- :param interval: Check interval in seconds
- :type interval: int
+ :param ttl: Check TTL in seconds
+ :type ttl: int
"""
def __init__(self,
name,
elementId,
- interval):
+ ttl):
self.name = name
self.elementId = elementId
- self.interval = interval
+ self.ttl = ttl
diff --git a/netuitive/client.py b/netuitive/client.py
index 96d74e7..82fff65 100644
--- a/netuitive/client.py
+++ b/netuitive/client.py
@@ -165,7 +165,7 @@ class Client(object):
url = self.checkurl + '/' \
+ check.name + '/' \
+ check.elementId + '/' \
- + str(check.interval)
+ + str(check.ttl)
try:
headers = {'User-Agent': self.agent}
request = urllib2.Request(
| Define the check ttl as ttl
This client should use the agreed upon "ttl" for the check ttl, instead of "duration". | Netuitive/netuitive-client-python | diff --git a/tests/test_netuitive.py b/tests/test_netuitive.py
index e3463f4..c75b9b3 100755
--- a/tests/test_netuitive.py
+++ b/tests/test_netuitive.py
@@ -518,7 +518,7 @@ class TestCheck(unittest.TestCase):
self.assertEqual(self.check.name, 'checkName')
self.assertEqual(self.check.elementId, 'elementId')
- self.assertEqual(self.check.interval, 60)
+ self.assertEqual(self.check.ttl, 60)
def tearDown(self):
pass
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 1,
"test_score": 0
},
"num_modified_files": 2
} | 0.2 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.5.1",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs==22.2.0
certifi==2021.5.30
importlib-metadata==4.8.3
iniconfig==1.1.1
-e git+https://github.com/Netuitive/netuitive-client-python.git@53087a9f6e6bc2e805ae3793f5c4417927f6f3f7#egg=netuitive
packaging==21.3
pluggy==1.0.0
py==1.11.0
pyparsing==3.1.4
pytest==7.0.1
tomli==1.2.3
typing_extensions==4.1.1
zipp==3.6.0
| name: netuitive-client-python
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- attrs==22.2.0
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- packaging==21.3
- pluggy==1.0.0
- py==1.11.0
- pyparsing==3.1.4
- pytest==7.0.1
- tomli==1.2.3
- typing-extensions==4.1.1
- wheel==0.23.0
- zipp==3.6.0
prefix: /opt/conda/envs/netuitive-client-python
| [
"tests/test_netuitive.py::TestCheck::test_check"
]
| []
| [
"tests/test_netuitive.py::TestClientInit::test_custom_agent",
"tests/test_netuitive.py::TestClientInit::test_custom_endpoint",
"tests/test_netuitive.py::TestClientInit::test_default_agent",
"tests/test_netuitive.py::TestClientInit::test_infrastructure_endpoint",
"tests/test_netuitive.py::TestClientInit::test_minimum",
"tests/test_netuitive.py::TestClientInit::test_trailing_slash",
"tests/test_netuitive.py::TestElementInit::test_element_localtion",
"tests/test_netuitive.py::TestElementInit::test_element_type",
"tests/test_netuitive.py::TestElementInit::test_no_args",
"tests/test_netuitive.py::TestElementInit::test_post_format",
"tests/test_netuitive.py::TestElementAttributes::test",
"tests/test_netuitive.py::TestElementAttributes::test_post_format",
"tests/test_netuitive.py::TestElementRelations::test",
"tests/test_netuitive.py::TestElementRelations::test_post_format",
"tests/test_netuitive.py::TestElementTags::test",
"tests/test_netuitive.py::TestElementSamples::test_add_sample",
"tests/test_netuitive.py::TestElementSamples::test_add_sample_ms",
"tests/test_netuitive.py::TestElementSamples::test_add_sample_no_timestamp",
"tests/test_netuitive.py::TestElementSamples::test_add_sample_with_tags",
"tests/test_netuitive.py::TestElementSamples::test_add_sanitize",
"tests/test_netuitive.py::TestElementSamples::test_clear_samples",
"tests/test_netuitive.py::TestElementSamples::test_duplicate_metrics",
"tests/test_netuitive.py::TestElementSamples::test_post_format",
"tests/test_netuitive.py::TestElementSamples::test_with_avg",
"tests/test_netuitive.py::TestElementSamples::test_with_cnt",
"tests/test_netuitive.py::TestElementSamples::test_with_max",
"tests/test_netuitive.py::TestElementSamples::test_with_min",
"tests/test_netuitive.py::TestElementSamples::test_with_sparseDataStrategy",
"tests/test_netuitive.py::TestElementSamples::test_with_sum",
"tests/test_netuitive.py::TestElementSamples::test_with_unit",
"tests/test_netuitive.py::TestEvent::test_all_options",
"tests/test_netuitive.py::TestEvent::test_minimum",
"tests/test_netuitive.py::TestEvent::test_no_tags",
"tests/test_netuitive.py::TestEvent::test_post_format_everthing",
"tests/test_netuitive.py::TestEvent::test_post_format_minimum",
"tests/test_netuitive.py::TestEvent::test_post_format_notags"
]
| []
| Apache License 2.0 | 1,855 | [
"netuitive/client.py",
"netuitive/check.py"
]
| [
"netuitive/client.py",
"netuitive/check.py"
]
|
|
Stranger6667__pyanyapi-42 | aebee636ad26f387850a6c8ab820ce4aac3f9adb | 2017-11-07 09:56:44 | aebee636ad26f387850a6c8ab820ce4aac3f9adb | codecov[bot]: # [Codecov](https://codecov.io/gh/Stranger6667/pyanyapi/pull/42?src=pr&el=h1) Report
> Merging [#42](https://codecov.io/gh/Stranger6667/pyanyapi/pull/42?src=pr&el=desc) into [master](https://codecov.io/gh/Stranger6667/pyanyapi/commit/aebee636ad26f387850a6c8ab820ce4aac3f9adb?src=pr&el=desc) will **decrease** coverage by `1.85%`.
> The diff coverage is `100%`.
[](https://codecov.io/gh/Stranger6667/pyanyapi/pull/42?src=pr&el=tree)
```diff
@@ Coverage Diff @@
## master #42 +/- ##
==========================================
- Coverage 99.46% 97.61% -1.86%
==========================================
Files 7 7
Lines 377 377
Branches 42 42
==========================================
- Hits 375 368 -7
- Misses 2 9 +7
```
| [Impacted Files](https://codecov.io/gh/Stranger6667/pyanyapi/pull/42?src=pr&el=tree) | Coverage Δ | |
|---|---|---|
| [pyanyapi/interfaces.py](https://codecov.io/gh/Stranger6667/pyanyapi/pull/42?src=pr&el=tree#diff-cHlhbnlhcGkvaW50ZXJmYWNlcy5weQ==) | `100% <100%> (ø)` | :arrow_up: |
| [pyanyapi/\_compat.py](https://codecov.io/gh/Stranger6667/pyanyapi/pull/42?src=pr&el=tree#diff-cHlhbnlhcGkvX2NvbXBhdC5weQ==) | `58.82% <0%> (-41.18%)` | :arrow_down: |
------
[Continue to review full report at Codecov](https://codecov.io/gh/Stranger6667/pyanyapi/pull/42?src=pr&el=continue).
> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
> `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
> Powered by [Codecov](https://codecov.io/gh/Stranger6667/pyanyapi/pull/42?src=pr&el=footer). Last update [aebee63...6fcd23b](https://codecov.io/gh/Stranger6667/pyanyapi/pull/42?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).
codecov[bot]: # [Codecov](https://codecov.io/gh/Stranger6667/pyanyapi/pull/42?src=pr&el=h1) Report
> Merging [#42](https://codecov.io/gh/Stranger6667/pyanyapi/pull/42?src=pr&el=desc) into [master](https://codecov.io/gh/Stranger6667/pyanyapi/commit/aebee636ad26f387850a6c8ab820ce4aac3f9adb?src=pr&el=desc) will **decrease** coverage by `1.85%`.
> The diff coverage is `100%`.
[](https://codecov.io/gh/Stranger6667/pyanyapi/pull/42?src=pr&el=tree)
```diff
@@ Coverage Diff @@
## master #42 +/- ##
==========================================
- Coverage 99.46% 97.61% -1.86%
==========================================
Files 7 7
Lines 377 377
Branches 42 42
==========================================
- Hits 375 368 -7
- Misses 2 9 +7
```
| [Impacted Files](https://codecov.io/gh/Stranger6667/pyanyapi/pull/42?src=pr&el=tree) | Coverage Δ | |
|---|---|---|
| [pyanyapi/interfaces.py](https://codecov.io/gh/Stranger6667/pyanyapi/pull/42?src=pr&el=tree#diff-cHlhbnlhcGkvaW50ZXJmYWNlcy5weQ==) | `100% <100%> (ø)` | :arrow_up: |
| [pyanyapi/\_compat.py](https://codecov.io/gh/Stranger6667/pyanyapi/pull/42?src=pr&el=tree#diff-cHlhbnlhcGkvX2NvbXBhdC5weQ==) | `58.82% <0%> (-41.18%)` | :arrow_down: |
------
[Continue to review full report at Codecov](https://codecov.io/gh/Stranger6667/pyanyapi/pull/42?src=pr&el=continue).
> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
> `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
> Powered by [Codecov](https://codecov.io/gh/Stranger6667/pyanyapi/pull/42?src=pr&el=footer). Last update [aebee63...6fcd23b](https://codecov.io/gh/Stranger6667/pyanyapi/pull/42?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).
| diff --git a/.travis.yml b/.travis.yml
index 1975b26..b7b5b14 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,17 +1,30 @@
language: python
python:
- 3.5
-env:
- - TOX_ENV=py26
- - TOX_ENV=py27
- - TOX_ENV=py32
- - TOX_ENV=py33
- - TOX_ENV=py34
- - TOX_ENV=py35
- - TOX_ENV=pypy
- - TOX_ENV=pypy3
- - JYTHON=true
+matrix:
+ fast_finish: true
+ include:
+ - python: 3.5
+ env: TOX_ENV=py35
+ - python: 3.4
+ env: TOX_ENV=py34
+ - python: 3.3
+ env: TOX_ENV=py33
+ - python: 3.2
+ env: TOX_ENV=py32
+ - python: 2.7
+ env: TOX_ENV=py27
+ - python: 2.6
+ env: TOX_ENV=py26
+ - python: pypy
+ env: TOX_ENV=pypy
+ - python: pypy3
+ env: TOX_ENV=pypy3
+ - python: 3.5
+ env: $JYTHON=true
install:
+ - if [ $TOX_ENV = "py32" ]; then travis_retry pip install "virtualenv<14.0.0" "tox<1.8.0"; fi
+ - if [ $TOX_ENV = "pypy3" ]; then travis_retry pip install "virtualenv<14.0.0" "tox<1.8.0"; fi
- if [ -z "$JYTHON" ]; then pip install codecov; fi
- if [ "$TOX_ENV" ]; then travis_retry pip install "virtualenv<14.0.0" tox; fi
before_install:
@@ -22,4 +35,4 @@ script:
- if [ "$JYTHON" ]; then travis_retry jython setup.py test; fi
- if [ "$TOX_ENV" ]; then tox -e $TOX_ENV; fi
after_success:
- - codecov
\ No newline at end of file
+ - codecov
diff --git a/pyanyapi/interfaces.py b/pyanyapi/interfaces.py
index 698c637..c0914b2 100644
--- a/pyanyapi/interfaces.py
+++ b/pyanyapi/interfaces.py
@@ -274,7 +274,7 @@ class YAMLInterface(DictInterface):
def perform_parsing(self):
try:
- return yaml.load(self.content)
+ return yaml.safe_load(self.content)
except yaml.error.YAMLError:
raise ResponseParseError(self._error_message, self.content)
| YAMLParser method is vulnerable
from pyanyapi import YAMLParser
YAMLParser({'test': 'container > test'}).parse('!!python/object/apply:os.system ["calc.exe"]').test
Hi, there is a vulnerability in YAMLParser method in Interfaces.py, please see PoC above. It can execute arbitrary python commands resulting in command execution. | Stranger6667/pyanyapi | diff --git a/tests/test_parsers.py b/tests/test_parsers.py
index 38223e2..4958b21 100644
--- a/tests/test_parsers.py
+++ b/tests/test_parsers.py
@@ -63,6 +63,15 @@ def test_yaml_parser_error():
parsed.test
+def test_yaml_parser_vulnerability():
+ """
+ In case of usage of yaml.load `test` value will be equal to 0.
+ """
+ parsed = YAMLParser({'test': 'container > test'}).parse('!!python/object/apply:os.system ["exit 0"]')
+ with pytest.raises(ResponseParseError):
+ parsed.test
+
+
@lxml_is_supported
@pytest.mark.parametrize(
'settings', (
| {
"commit_name": "merge_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 2,
"test_score": 0
},
"num_modified_files": 2
} | 0.5 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-cov"
],
"pre_install": null,
"python": "3.5",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs==22.2.0
certifi==2021.5.30
coverage==6.2
importlib-metadata==4.8.3
iniconfig==1.1.1
lxml==5.3.1
packaging==21.3
pluggy==1.0.0
py==1.11.0
-e git+https://github.com/Stranger6667/pyanyapi.git@aebee636ad26f387850a6c8ab820ce4aac3f9adb#egg=pyanyapi
pyparsing==3.1.4
pytest==7.0.1
pytest-cov==4.0.0
PyYAML==6.0.1
tomli==1.2.3
typing_extensions==4.1.1
ujson==4.3.0
zipp==3.6.0
| name: pyanyapi
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- attrs==22.2.0
- coverage==6.2
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- lxml==5.3.1
- packaging==21.3
- pluggy==1.0.0
- py==1.11.0
- pyparsing==3.1.4
- pytest==7.0.1
- pytest-cov==4.0.0
- pyyaml==6.0.1
- tomli==1.2.3
- typing-extensions==4.1.1
- ujson==4.3.0
- zipp==3.6.0
prefix: /opt/conda/envs/pyanyapi
| [
"tests/test_parsers.py::test_yaml_parser_error",
"tests/test_parsers.py::test_yaml_parser_vulnerability",
"tests/test_parsers.py::test_yaml_parse"
]
| []
| [
"tests/test_parsers.py::test_xml_objectify_parser",
"tests/test_parsers.py::test_xml_objectify_parser_error",
"tests/test_parsers.py::test_xml_parser_error",
"tests/test_parsers.py::test_xml_parsed[settings0]",
"tests/test_parsers.py::test_xml_parsed[settings1]",
"tests/test_parsers.py::test_xml_simple_settings",
"tests/test_parsers.py::test_json_parsed",
"tests/test_parsers.py::test_multiple_parser_join",
"tests/test_parsers.py::test_multiply_parsers_declaration",
"tests/test_parsers.py::test_empty_values[{\"container\":{\"test\":\"value\"}}-test-value]",
"tests/test_parsers.py::test_empty_values[{\"container\":{\"test\":\"value\"}}-second-None]",
"tests/test_parsers.py::test_empty_values[{\"container\":{\"fail\":[1]}}-second-None]",
"tests/test_parsers.py::test_empty_values[{\"container\":[[1],[],[3]]}-third-expected3]",
"tests/test_parsers.py::test_empty_values[{\"container\":null}-null-None]",
"tests/test_parsers.py::test_empty_values[{\"container\":[1,2]}-test-1,2]",
"tests/test_parsers.py::test_attributes",
"tests/test_parsers.py::test_efficient_parsing",
"tests/test_parsers.py::test_simple_config_xml_parser",
"tests/test_parsers.py::test_simple_config_json_parser",
"tests/test_parsers.py::test_settings_inheritance",
"tests/test_parsers.py::test_complex_config",
"tests/test_parsers.py::test_json_parse",
"tests/test_parsers.py::test_json_value_error_parse",
"tests/test_parsers.py::test_regexp_parse",
"tests/test_parsers.py::test_ajax_parser",
"tests/test_parsers.py::test_ajax_parser_cache",
"tests/test_parsers.py::test_ajax_parser_invalid_settings",
"tests/test_parsers.py::test_parse_memoization",
"tests/test_parsers.py::test_regexp_settings",
"tests/test_parsers.py::test_parse_all",
"tests/test_parsers.py::test_parse_all_combined_parser",
"tests/test_parsers.py::test_parse_csv",
"tests/test_parsers.py::test_parse_csv_custom_delimiter",
"tests/test_parsers.py::test_csv_parser_error",
"tests/test_parsers.py::test_children[SubParser]",
"tests/test_parsers.py::test_children[sub_parser1]",
"tests/test_parsers.py::TestIndexOfParser::test_default[foo-b\\xe1r]",
"tests/test_parsers.py::TestIndexOfParser::test_default[foo-b\\xc3\\xa1r]",
"tests/test_parsers.py::TestIndexOfParser::test_parsing_error[has_bar]",
"tests/test_parsers.py::TestIndexOfParser::test_parsing_error[has_baz]"
]
| []
| MIT License | 1,856 | [
"pyanyapi/interfaces.py",
".travis.yml"
]
| [
"pyanyapi/interfaces.py",
".travis.yml"
]
|
mhcomm__pypeman-60 | d72c2b741e728edcc97920915046aba84a95f4d1 | 2017-11-07 14:38:37 | 1fd1436a703791df96cec5f1838aafecb50e7055 | diff --git a/pypeman/channels.py b/pypeman/channels.py
index e02ca05..e448dec 100644
--- a/pypeman/channels.py
+++ b/pypeman/channels.py
@@ -312,8 +312,13 @@ class BaseChannel:
if self.next_node:
if isinstance(result, types.GeneratorType):
- for res in result:
- result = await self.next_node.handle(res)
+ gene = result
+ result = msg # Necessary if all nodes result are dropped
+ for res in gene:
+ try:
+ result = await self.next_node.handle(res)
+ except Dropped:
+ pass
# TODO Here result is last value returned. Is it a good idea ?
else:
result = await self.next_node.handle(result)
diff --git a/pypeman/commands.py b/pypeman/commands.py
index 3225205..bef7cb2 100755
--- a/pypeman/commands.py
+++ b/pypeman/commands.py
@@ -117,7 +117,7 @@ def mk_daemon(mainfunc=lambda: None, pidfile="pypeman.pid"):
# - daemonocle
# - py daemoniker
# Alternatively if we don't want other module dependencies we might just copy
- # the DaemonLite files into your source repository
+ # the DaemonLite files into your source repository
class DaemonizedApp(DaemonLite):
def run(self):
mainfunc()
@@ -127,20 +127,17 @@ def mk_daemon(mainfunc=lambda: None, pidfile="pypeman.pid"):
@begin.subcommand
def start(reload: 'Make server autoreload (Dev only)'=False,
- debug_asyncio: 'Enable asyncio debug'=False,
- cli : "enables an IPython CLI for debugging (not operational)"=False,
- profile : "enables profiling / run stats (not operational)"=False,
- # TODO: can be True if DaemonLite is a hard requirement
- daemon : "if true pypeman will be started as daemon "=bool(DaemonLite),
-
+ debug_asyncio: 'Enable asyncio debug'=False,
+ cli : "enables an IPython CLI for debugging (not operational)"=False,
+ profile : "enables profiling / run stats (not operational)"=False,
+ daemon : "if true pypeman will be started as daemon "=True,
):
""" Start pypeman as daemon (or foreground process) """
- main_func = partial(main, debug_asyncio=debug_asyncio, cli=cli,
+ main_func = partial(main, debug_asyncio=debug_asyncio, cli=cli,
profile=profile)
start_func = partial(reloader_opt, main_func, reload, 2)
if reload:
- print("RELOAD")
start_func()
else:
if daemon:
diff --git a/pypeman/contrib/http.py b/pypeman/contrib/http.py
index 3658dc2..f55bcea 100644
--- a/pypeman/contrib/http.py
+++ b/pypeman/contrib/http.py
@@ -17,21 +17,32 @@ class HTTPEndpoint(endpoints.BaseEndpoint):
def __init__(self, adress='127.0.0.1', port='8080', loop=None, http_args=None):
super().__init__()
self.http_args = http_args or {}
+ self.ssl_context = http_args.pop('ssl_context', None)
+
self._app = None
self.address = adress
self.port = port
self.loop = loop or asyncio.get_event_loop()
- def add_route(self,*args, **kwargs):
- if not self._app:
- self._app = web.Application(loop=self.loop, **self.http_args)
- # TODO route should be added later
+ def add_route(self, *args, **kwargs):
+ if self._app is None:
+ self._app = web.Application(**self.http_args)
+
self._app.router.add_route(*args, **kwargs)
async def start(self):
if self._app is not None:
- srv = await self.loop.create_server(self._app.make_handler(), self.address, self.port)
- print("Server started at http://{}:{}".format(self.address, self.port))
+ srv = await self.loop.create_server(
+ protocol_factory=self._app.make_handler(),
+ host=self.address,
+ port=self.port,
+ ssl=self.ssl_context
+ )
+ print("Server started at http{}://{}:{}".format(
+ 's' if self.ssl_context else '',
+ self.address,
+ self.port
+ ))
return srv
else:
print("No HTTP route.")
diff --git a/pypeman/helpers/reloader.py b/pypeman/helpers/reloader.py
index f675d1e..cadbd4e 100644
--- a/pypeman/helpers/reloader.py
+++ b/pypeman/helpers/reloader.py
@@ -45,7 +45,7 @@ def reloader_opt(to_call, reloader, interval):
lockfile = None
try:
fd, lockfile = tempfile.mkstemp(prefix='process.', suffix='.lock')
- os.close(fd) # We only need this file to exist. We never write to it
+ os.close(fd) # We only need this file to exist. We never write to it.
while os.path.exists(lockfile):
args = [sys.executable] + sys.argv
environ = os.environ.copy()
diff --git a/pypeman/nodes.py b/pypeman/nodes.py
index 67c7452..d13d4a8 100644
--- a/pypeman/nodes.py
+++ b/pypeman/nodes.py
@@ -98,7 +98,7 @@ class BaseNode:
if log_output:
# Enable logging
self._handle_without_log = self.handle
- self.handle = self._log_handle
+ setattr(self, 'handle', self._log_handle)
async def handle(self, msg):
""" Handle message is called by channel to launch process method on it.
@@ -129,8 +129,13 @@ class BaseNode:
if self.next_node:
if isinstance(result, types.GeneratorType):
- for res in result:
- result = await self.next_node.handle(res)
+ gene = result
+ result = msg # Necessary if all nodes result are dropped
+ for res in gene:
+ try:
+ result = await self.next_node.handle(res)
+ except Dropped:
+ pass
# TODO Here result is last value returned. Is it a good idea ?
else:
if self.store_output_as:
@@ -225,7 +230,7 @@ class BaseNode:
if not hasattr(self, '_handle'):
self._handle = self.handle
- self.handle = self._test_handle
+ setattr(self, 'handle', self._test_handle)
if hasattr(self, '_orig_process'):
self.process = self._orig_process
| Dropnode breaks message generator
When you use a node that return a message generator, appending a dropnode raise an exception that break the loop to consume all message generator. We should wait for the last message to reraise the exception. | mhcomm/pypeman | diff --git a/pypeman/tests/test_channel.py b/pypeman/tests/test_channel.py
index 6020e70..ba0b42a 100644
--- a/pypeman/tests/test_channel.py
+++ b/pypeman/tests/test_channel.py
@@ -230,6 +230,39 @@ class ChannelsTests(unittest.TestCase):
self.assertEqual(result.payload, msg.payload, "Channel handle not working")
+ def test_channel_with_generator(self):
+ """ Whether BaseChannel with generator is working """
+
+ chan = BaseChannel(name="test_channel7.3", loop=self.loop)
+ chan2 = BaseChannel(name="test_channel7.31", loop=self.loop)
+ msg = generate_msg()
+ msg2 = msg.copy()
+
+ class TestIter(nodes.BaseNode):
+ def process(self, msg):
+ def iter():
+ for i in range(3):
+ yield msg
+ return iter()
+
+ final_node = nodes.Log()
+ mid_node = nodes.Log()
+
+ chan.add(TestIter(name="testiterr"), nodes.Log(), TestIter(name="testiterr"), final_node)
+ chan2.add(TestIter(name="testiterr"), mid_node, nodes.Drop())
+
+ # Launch channel processing
+ self.start_channels()
+ result = self.loop.run_until_complete(chan.handle(msg))
+
+ self.assertEqual(result.payload, msg.payload, "Generator node not working")
+ self.assertEqual(final_node.processed, 9, "Generator node not working")
+
+ result = self.loop.run_until_complete(chan2.handle(msg2))
+
+ self.assertEqual(mid_node.processed, 3, "Generator node not working with drop_node")
+
+
def test_channel_events(self):
""" Whether BaseChannel handling return a good result """
| {
"commit_name": "merge_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 0,
"test_score": 0
},
"num_modified_files": 5
} | 0.2 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[all]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"nose",
"coverage",
"pytest"
],
"pre_install": null,
"python": "3.6",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | aiocron==1.8
aiohttp==3.8.6
aiosignal==1.2.0
async-timeout==4.0.2
asynctest==0.13.0
attrs==22.2.0
backports.zoneinfo==0.2.1
begins==0.9
certifi==2021.5.30
charset-normalizer==3.0.1
coverage==6.2
croniter==6.0.0
DaemonLite==0.0.2
frozenlist==1.2.0
hl7==0.4.5
idna==3.10
idna-ssl==1.1.0
importlib-metadata==4.8.3
importlib-resources==5.4.0
iniconfig==1.1.1
multidict==5.2.0
nose==1.3.7
packaging==21.3
pluggy==1.0.0
py==1.11.0
pyparsing==3.1.4
-e git+https://github.com/mhcomm/pypeman.git@d72c2b741e728edcc97920915046aba84a95f4d1#egg=pypeman
pytest==7.0.1
python-dateutil==2.9.0.post0
pytz==2025.2
pytz-deprecation-shim==0.1.0.post0
six==1.17.0
tomli==1.2.3
typing_extensions==4.1.1
tzdata==2025.2
tzlocal==4.2
xmltodict==0.14.2
yarl==1.7.2
zipp==3.6.0
| name: pypeman
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- aiocron==1.8
- aiohttp==3.8.6
- aiosignal==1.2.0
- async-timeout==4.0.2
- asynctest==0.13.0
- attrs==22.2.0
- backports-zoneinfo==0.2.1
- begins==0.9
- charset-normalizer==3.0.1
- coverage==6.2
- croniter==6.0.0
- daemonlite==0.0.2
- frozenlist==1.2.0
- hl7==0.4.5
- idna==3.10
- idna-ssl==1.1.0
- importlib-metadata==4.8.3
- importlib-resources==5.4.0
- iniconfig==1.1.1
- multidict==5.2.0
- nose==1.3.7
- packaging==21.3
- pluggy==1.0.0
- py==1.11.0
- pyparsing==3.1.4
- pytest==7.0.1
- python-dateutil==2.9.0.post0
- pytz==2025.2
- pytz-deprecation-shim==0.1.0.post0
- six==1.17.0
- tomli==1.2.3
- typing-extensions==4.1.1
- tzdata==2025.2
- tzlocal==4.2
- xmltodict==0.14.2
- yarl==1.7.2
- zipp==3.6.0
prefix: /opt/conda/envs/pypeman
| [
"pypeman/tests/test_channel.py::ChannelsTests::test_channel_with_generator"
]
| []
| [
"pypeman/tests/test_channel.py::ChannelsTests::test_base_channel",
"pypeman/tests/test_channel.py::ChannelsTests::test_case_channel",
"pypeman/tests/test_channel.py::ChannelsTests::test_channel_events",
"pypeman/tests/test_channel.py::ChannelsTests::test_channel_exception",
"pypeman/tests/test_channel.py::ChannelsTests::test_channel_result",
"pypeman/tests/test_channel.py::ChannelsTests::test_channel_stopped_dont_process_message",
"pypeman/tests/test_channel.py::ChannelsTests::test_cond_channel",
"pypeman/tests/test_channel.py::ChannelsTests::test_file_message_store",
"pypeman/tests/test_channel.py::ChannelsTests::test_ftp_channel",
"pypeman/tests/test_channel.py::ChannelsTests::test_memory_message_store",
"pypeman/tests/test_channel.py::ChannelsTests::test_no_node_base_channel",
"pypeman/tests/test_channel.py::ChannelsTests::test_null_message_store",
"pypeman/tests/test_channel.py::ChannelsTests::test_replay_from_memory_message_store",
"pypeman/tests/test_channel.py::ChannelsTests::test_sub_channel",
"pypeman/tests/test_channel.py::ChannelsTests::test_sub_channel_with_exception"
]
| []
| Apache License 2.0 | 1,857 | [
"pypeman/commands.py",
"pypeman/contrib/http.py",
"pypeman/channels.py",
"pypeman/helpers/reloader.py",
"pypeman/nodes.py"
]
| [
"pypeman/commands.py",
"pypeman/contrib/http.py",
"pypeman/channels.py",
"pypeman/helpers/reloader.py",
"pypeman/nodes.py"
]
|
|
pgmpy__pgmpy-937 | 110b4c1e8ef8c24da83931d87298b96c196c9462 | 2017-11-07 19:16:01 | 110b4c1e8ef8c24da83931d87298b96c196c9462 | codecov[bot]: # [Codecov](https://codecov.io/gh/pgmpy/pgmpy/pull/937?src=pr&el=h1) Report
> Merging [#937](https://codecov.io/gh/pgmpy/pgmpy/pull/937?src=pr&el=desc) into [dev](https://codecov.io/gh/pgmpy/pgmpy/commit/110b4c1e8ef8c24da83931d87298b96c196c9462?src=pr&el=desc) will **decrease** coverage by `<.01%`.
> The diff coverage is `80%`.
[](https://codecov.io/gh/pgmpy/pgmpy/pull/937?src=pr&el=tree)
```diff
@@ Coverage Diff @@
## dev #937 +/- ##
=========================================
- Coverage 94.71% 94.7% -0.01%
=========================================
Files 114 114
Lines 11176 11185 +9
=========================================
+ Hits 10585 10593 +8
- Misses 591 592 +1
```
| [Impacted Files](https://codecov.io/gh/pgmpy/pgmpy/pull/937?src=pr&el=tree) | Coverage Δ | |
|---|---|---|
| [pgmpy/tests/test\_readwrite/test\_ProbModelXML.py](https://codecov.io/gh/pgmpy/pgmpy/pull/937?src=pr&el=tree#diff-cGdtcHkvdGVzdHMvdGVzdF9yZWFkd3JpdGUvdGVzdF9Qcm9iTW9kZWxYTUwucHk=) | `94.95% <ø> (ø)` | :arrow_up: |
| [pgmpy/readwrite/UAI.py](https://codecov.io/gh/pgmpy/pgmpy/pull/937?src=pr&el=tree#diff-cGdtcHkvcmVhZHdyaXRlL1VBSS5weQ==) | `86.4% <0%> (-0.85%)` | :arrow_down: |
| [pgmpy/readwrite/XMLBeliefNetwork.py](https://codecov.io/gh/pgmpy/pgmpy/pull/937?src=pr&el=tree#diff-cGdtcHkvcmVhZHdyaXRlL1hNTEJlbGllZk5ldHdvcmsucHk=) | `92.53% <100%> (+0.11%)` | :arrow_up: |
| [pgmpy/readwrite/ProbModelXML.py](https://codecov.io/gh/pgmpy/pgmpy/pull/937?src=pr&el=tree#diff-cGdtcHkvcmVhZHdyaXRlL1Byb2JNb2RlbFhNTC5weQ==) | `85.68% <100%> (+0.06%)` | :arrow_up: |
| [pgmpy/readwrite/XMLBIF.py](https://codecov.io/gh/pgmpy/pgmpy/pull/937?src=pr&el=tree#diff-cGdtcHkvcmVhZHdyaXRlL1hNTEJJRi5weQ==) | `97.53% <100%> (+0.03%)` | :arrow_up: |
| [pgmpy/readwrite/BIF.py](https://codecov.io/gh/pgmpy/pgmpy/pull/937?src=pr&el=tree#diff-cGdtcHkvcmVhZHdyaXRlL0JJRi5weQ==) | `93.68% <100%> (+0.03%)` | :arrow_up: |
| [pgmpy/models/BayesianModel.py](https://codecov.io/gh/pgmpy/pgmpy/pull/937?src=pr&el=tree#diff-cGdtcHkvbW9kZWxzL0JheWVzaWFuTW9kZWwucHk=) | `95.47% <0%> (+0.41%)` | :arrow_up: |
------
[Continue to review full report at Codecov](https://codecov.io/gh/pgmpy/pgmpy/pull/937?src=pr&el=continue).
> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
> `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
> Powered by [Codecov](https://codecov.io/gh/pgmpy/pgmpy/pull/937?src=pr&el=footer). Last update [110b4c1...36592af](https://codecov.io/gh/pgmpy/pgmpy/pull/937?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).
| diff --git a/pgmpy/readwrite/BIF.py b/pgmpy/readwrite/BIF.py
index fac86ab9..98c11d39 100644
--- a/pgmpy/readwrite/BIF.py
+++ b/pgmpy/readwrite/BIF.py
@@ -284,9 +284,10 @@ class BIFReader(object):
<pgmpy.models.BayesianModel.BayesianModel object at 0x7f20af154320>
"""
try:
- model = BayesianModel(self.variable_edges)
- model.name = self.network_name
+ model = BayesianModel()
model.add_nodes_from(self.variable_names)
+ model.add_edges_from(self.variable_edges)
+ model.name = self.network_name
tabular_cpds = []
for var in sorted(self.variable_cpds.keys()):
diff --git a/pgmpy/readwrite/ProbModelXML.py b/pgmpy/readwrite/ProbModelXML.py
index 67908769..b2499ca3 100644
--- a/pgmpy/readwrite/ProbModelXML.py
+++ b/pgmpy/readwrite/ProbModelXML.py
@@ -1030,7 +1030,9 @@ class ProbModelXMLReader(object):
>>> reader.get_model()
"""
if self.probnet.get('type') == "BayesianNetwork":
- model = BayesianModel(self.probnet['edges'].keys())
+ model = BayesianModel()
+ model.add_nodes_from(self.probnet['Variables'].keys())
+ model.add_edges_from(self.probnet['edges'].keys())
tabular_cpds = []
cpds = self.probnet['Potentials']
@@ -1051,7 +1053,6 @@ class ProbModelXMLReader(object):
for var in variables:
for prop_name, prop_value in self.probnet['Variables'][var].items():
model.node[var][prop_name] = prop_value
-
edges = model.edges()
for edge in edges:
for prop_name, prop_value in self.probnet['edges'][edge].items():
diff --git a/pgmpy/readwrite/UAI.py b/pgmpy/readwrite/UAI.py
index f47598da..ebf86516 100644
--- a/pgmpy/readwrite/UAI.py
+++ b/pgmpy/readwrite/UAI.py
@@ -218,7 +218,9 @@ class UAIReader(object):
>>> reader.get_model()
"""
if self.network_type == 'BAYES':
- model = BayesianModel(self.edges)
+ model = BayesianModel()
+ model.add_nodes_from(self.variables)
+ model.add_edges_from(self.edges)
tabular_cpds = []
for cpd in self.tables:
diff --git a/pgmpy/readwrite/XMLBIF.py b/pgmpy/readwrite/XMLBIF.py
index a301f3e3..826c6a7c 100644
--- a/pgmpy/readwrite/XMLBIF.py
+++ b/pgmpy/readwrite/XMLBIF.py
@@ -177,7 +177,9 @@ class XMLBIFReader(object):
return variable_property
def get_model(self):
- model = BayesianModel(self.get_edges())
+ model = BayesianModel()
+ model.add_nodes_from(self.variables)
+ model.add_edges_from(self.edge_list)
model.name = self.network_name
tabular_cpds = []
diff --git a/pgmpy/readwrite/XMLBeliefNetwork.py b/pgmpy/readwrite/XMLBeliefNetwork.py
index e28d495a..9328542e 100644
--- a/pgmpy/readwrite/XMLBeliefNetwork.py
+++ b/pgmpy/readwrite/XMLBeliefNetwork.py
@@ -186,7 +186,9 @@ class XBNReader(object):
"""
Returns an instance of Bayesian Model.
"""
- model = BayesianModel(self.edges)
+ model = BayesianModel()
+ model.add_nodes_from(self.variables)
+ model.add_edges_from(self.edges)
model.name = self.model_name
tabular_cpds = []
| Reading a XML BIF with isolated nodes
The XMLBIFReader class doesn't allow to return the model from a BIF XML file where there are isolated nodes.
I can create the XMLBIFReader:
`bif = pgmpy.readwrite.XMLBIF.XMLBIFReader('diabetes.xml')`
but when trying to return the model:
`bif_model = bif.get_model()`
It returns an exception because is trying to load the CPD of the isolated node, but this node is not included in the BayesianModel:
`ValueError: ('CPD defined on variable not in the model', <TabularCPD representing P(skin:1) at 0x7f669d905c10>)` arises.
Reviewing the `XMLBIFReader.get_model()`, we can see that the Bayesian model is created from the edges:
`model = BayesianModel(self.get_edges())`
As an isolated node has no edge by definition, I think that the BayesianModel can't know that an isolated node exists when adding the cpds to the BayesianModel.
I provide the following XML BIF as a MWE. It is a XML BIF learnt using WEKA BayesNet class.
[diabetes.zip](https://github.com/pgmpy/pgmpy/files/1449591/diabetes.zip)
I think that even when an isolated node is not the most useful thing to do, it is a nuisance that we can't load the rest of the network.
Execution environment.
pgmpy: 0.1.3
Python: 2.7
OS: Ubuntu 16.04
| pgmpy/pgmpy | diff --git a/pgmpy/tests/test_readwrite/test_ProbModelXML.py b/pgmpy/tests/test_readwrite/test_ProbModelXML.py
index 806e41e3..aa4141e3 100644
--- a/pgmpy/tests/test_readwrite/test_ProbModelXML.py
+++ b/pgmpy/tests/test_readwrite/test_ProbModelXML.py
@@ -547,43 +547,51 @@ class TestProbModelXMLReaderString(unittest.TestCase):
'role': 'chance',
'type': 'finiteStates',
'Coordinates': {'y': '52', 'x': '568'},
- 'AdditionalProperties': {'Title': 'S', 'Relevance': '7.0'}},
+ 'AdditionalProperties': {'Title': 'S', 'Relevance': '7.0'},
+ 'weight': None},
'Bronchitis': {'States': {'no': {}, 'yes': {}},
'role': 'chance',
'type': 'finiteStates',
'Coordinates': {'y': '181', 'x': '698'},
- 'AdditionalProperties': {'Title': 'B', 'Relevance': '7.0'}},
+ 'AdditionalProperties': {'Title': 'B', 'Relevance': '7.0'},
+ 'weight': None},
'VisitToAsia': {'States': {'no': {}, 'yes': {}},
'role': 'chance',
'type': 'finiteStates',
'Coordinates': {'y': '58', 'x': '290'},
- 'AdditionalProperties': {'Title': 'A', 'Relevance': '7.0'}},
+ 'AdditionalProperties': {'Title': 'A', 'Relevance': '7.0'},
+ 'weight': None},
'Tuberculosis': {'States': {'no': {}, 'yes': {}},
'role': 'chance',
'type': 'finiteStates',
'Coordinates': {'y': '150', 'x': '201'},
- 'AdditionalProperties': {'Title': 'T', 'Relevance': '7.0'}},
+ 'AdditionalProperties': {'Title': 'T', 'Relevance': '7.0'},
+ 'weight': None},
'X-ray': {'States': {'no': {}, 'yes': {}},
'role': 'chance',
'AdditionalProperties': {'Title': 'X', 'Relevance': '7.0'},
'Coordinates': {'y': '322', 'x': '252'},
'Comment': 'Indica si el test de rayos X ha sido positivo',
- 'type': 'finiteStates'},
+ 'type': 'finiteStates',
+ 'weight': None},
'Dyspnea': {'States': {'no': {}, 'yes': {}},
'role': 'chance',
'type': 'finiteStates',
'Coordinates': {'y': '321', 'x': '533'},
- 'AdditionalProperties': {'Title': 'D', 'Relevance': '7.0'}},
+ 'AdditionalProperties': {'Title': 'D', 'Relevance': '7.0'},
+ 'weight': None},
'TuberculosisOrCancer': {'States': {'no': {}, 'yes': {}},
'role': 'chance',
'type': 'finiteStates',
'Coordinates': {'y': '238', 'x': '336'},
- 'AdditionalProperties': {'Title': 'E', 'Relevance': '7.0'}},
+ 'AdditionalProperties': {'Title': 'E', 'Relevance': '7.0'},
+ 'weight': None},
'LungCancer': {'States': {'no': {}, 'yes': {}},
'role': 'chance',
'type': 'finiteStates',
'Coordinates': {'y': '152', 'x': '421'},
- 'AdditionalProperties': {'Title': 'L', 'Relevance': '7.0'}}}
+ 'AdditionalProperties': {'Title': 'L', 'Relevance': '7.0'},
+ 'weight': None}}
edge_expected = {'LungCancer': {'TuberculosisOrCancer': {'weight': None,
'directed': 'true'}},
'Smoker': {'LungCancer': {'weight': None,
| {
"commit_name": "merge_commit",
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 2,
"test_score": 3
},
"num_modified_files": 5
} | unknown | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"nose",
"mock",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y build-essential"
],
"python": "3.5",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs==22.2.0
certifi==2021.5.30
decorator==5.1.1
importlib-metadata==4.8.3
iniconfig==1.1.1
mock==5.2.0
networkx==1.11
nose==1.3.7
numpy==1.11.3
packaging==21.3
pandas==0.19.2
-e git+https://github.com/pgmpy/pgmpy.git@110b4c1e8ef8c24da83931d87298b96c196c9462#egg=pgmpy
pluggy==1.0.0
py==1.11.0
pyparsing==2.2.0
pytest==7.0.1
python-dateutil==2.9.0.post0
pytz==2025.2
scipy==0.18.1
six==1.17.0
tomli==1.2.3
typing_extensions==4.1.1
wrapt==1.10.8
zipp==3.6.0
| name: pgmpy
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- attrs==22.2.0
- decorator==5.1.1
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- mock==5.2.0
- networkx==1.11
- nose==1.3.7
- numpy==1.11.3
- packaging==21.3
- pandas==0.19.2
- pluggy==1.0.0
- py==1.11.0
- pyparsing==2.2.0
- pytest==7.0.1
- python-dateutil==2.9.0.post0
- pytz==2025.2
- scipy==0.18.1
- six==1.17.0
- tomli==1.2.3
- typing-extensions==4.1.1
- wrapt==1.10.8
- zipp==3.6.0
prefix: /opt/conda/envs/pgmpy
| [
"pgmpy/tests/test_readwrite/test_ProbModelXML.py::TestProbModelXMLReaderString::test_get_model"
]
| []
| [
"pgmpy/tests/test_readwrite/test_ProbModelXML.py::TestProbModelXMLReaderString::test_additionalconstraints",
"pgmpy/tests/test_readwrite/test_ProbModelXML.py::TestProbModelXMLReaderString::test_additionalproperties",
"pgmpy/tests/test_readwrite/test_ProbModelXML.py::TestProbModelXMLReaderString::test_comment",
"pgmpy/tests/test_readwrite/test_ProbModelXML.py::TestProbModelXMLReaderString::test_decisioncriteria",
"pgmpy/tests/test_readwrite/test_ProbModelXML.py::TestProbModelXMLReaderString::test_edges",
"pgmpy/tests/test_readwrite/test_ProbModelXML.py::TestProbModelXMLReaderString::test_potential",
"pgmpy/tests/test_readwrite/test_ProbModelXML.py::TestProbModelXMLReaderString::test_variables",
"pgmpy/tests/test_readwrite/test_ProbModelXML.py::TestProbModelXMLWriter::test_file",
"pgmpy/tests/test_readwrite/test_ProbModelXML.py::TestProbModelXMLWriter::test_write_file",
"pgmpy/tests/test_readwrite/test_ProbModelXML.py::TestProbModelXMLmethods::test_get_probmodel_data"
]
| []
| MIT License | 1,858 | [
"pgmpy/readwrite/UAI.py",
"pgmpy/readwrite/XMLBIF.py",
"pgmpy/readwrite/XMLBeliefNetwork.py",
"pgmpy/readwrite/BIF.py",
"pgmpy/readwrite/ProbModelXML.py"
]
| [
"pgmpy/readwrite/UAI.py",
"pgmpy/readwrite/XMLBIF.py",
"pgmpy/readwrite/XMLBeliefNetwork.py",
"pgmpy/readwrite/BIF.py",
"pgmpy/readwrite/ProbModelXML.py"
]
|
dask__dask-2871 | d0fac49699b46078b070d318d4c9a02612d0bd97 | 2017-11-08 19:43:43 | 22ab4b4ee000618b681c578ba695a8b2f11c69e4 | jcrist: Ping @pitrou for review. | diff --git a/dask/diagnostics/profile.py b/dask/diagnostics/profile.py
index 48e68a565..ec855173e 100644
--- a/dask/diagnostics/profile.py
+++ b/dask/diagnostics/profile.py
@@ -140,29 +140,35 @@ class ResourceProfiler(Callback):
data will only be collected while a dask scheduler is active.
"""
def __init__(self, dt=1):
- self._tracker = _Tracker(dt)
- self._tracker.start()
- self.results = []
+ self._dt = dt
self._entered = False
+ self._tracker = None
+ self.results = []
+
+ def _is_running(self):
+ return self._tracker is not None and self._tracker.is_alive()
def _start_collect(self):
- assert self._tracker.is_alive(), "Resource tracker is shutdown"
+ if not self._is_running():
+ self._tracker = _Tracker(self._dt)
+ self._tracker.start()
self._tracker.parent_conn.send('collect')
def _stop_collect(self):
- if self._tracker.is_alive():
+ if self._is_running():
self._tracker.parent_conn.send('send_data')
self.results.extend(starmap(ResourceData, self._tracker.parent_conn.recv()))
def __enter__(self):
- self.clear()
self._entered = True
+ self.clear()
self._start_collect()
return super(ResourceProfiler, self).__enter__()
def __exit__(self, *args):
self._entered = False
self._stop_collect()
+ self.close()
super(ResourceProfiler, self).__exit__(*args)
def _start(self, dsk):
@@ -174,7 +180,9 @@ class ResourceProfiler(Callback):
def close(self):
"""Shutdown the resource tracker process"""
- self._tracker.shutdown()
+ if self._is_running():
+ self._tracker.shutdown()
+ self._tracker = None
__del__ = close
| ResourceProfiler keeps running after `__exit__`
If you write something like:
```
with ResourceProfiler(dt=0.01) as rprof:
# ...
```
then the profiler process keeps running at the end of the `with` block. You have to call `rprof.close()` as well, which is unexpected.
(noticed in the distributed test suite)
| dask/dask | diff --git a/dask/diagnostics/tests/test_profiler.py b/dask/diagnostics/tests/test_profiler.py
index 5c062640b..cf374d7a1 100644
--- a/dask/diagnostics/tests/test_profiler.py
+++ b/dask/diagnostics/tests/test_profiler.py
@@ -83,15 +83,20 @@ def test_resource_profiler():
assert len(results) > 0
assert all(isinstance(i, tuple) and len(i) == 3 for i in results)
+ # Tracker stopped on exit
+ assert not rprof._is_running()
+
rprof.clear()
assert rprof.results == []
+ # Close is idempotent
rprof.close()
- assert not rprof._tracker.is_alive()
+ assert not rprof._is_running()
- with pytest.raises(AssertionError):
- with rprof:
- get(dsk, 'e')
+ # Restarts tracker if already closed
+ with rprof:
+ get(dsk2, 'c')
+ assert len(rprof.results) > 0
@pytest.mark.skipif("not psutil")
@@ -114,7 +119,7 @@ def test_resource_profiler_multiple_gets():
assert all(isinstance(i, tuple) and len(i) == 3 for i in results)
rprof.close()
- assert not rprof._tracker.is_alive()
+ assert not rprof._is_running()
def test_cache_profiler():
| {
"commit_name": "merge_commit",
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 0,
"test_score": 2
},
"num_modified_files": 1
} | 1.19 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[complete]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"moto",
"blosc",
"cachey",
"graphviz",
"pyarrow",
"pandas_datareader",
"cityhash",
"flake8",
"mmh3",
"pytest-xdist",
"xxhash",
"backports.lzma",
"mock"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": [
"docs/requirements-docs.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | alabaster==0.7.16
babel==2.17.0
backports.lzma==0.0.14
blosc==1.11.2
boto3==1.37.23
botocore==1.37.23
cachey==0.2.1
certifi==2025.1.31
cffi==1.17.1
charset-normalizer==3.4.1
cityhash==0.4.8
click==8.1.8
cloudpickle==3.1.1
cryptography==44.0.2
-e git+https://github.com/dask/dask.git@d0fac49699b46078b070d318d4c9a02612d0bd97#egg=dask
distributed==1.19.3
docutils==0.21.2
exceptiongroup==1.2.2
execnet==2.1.1
flake8==7.2.0
fsspec==2025.3.1
graphviz==0.20.3
HeapDict==1.0.1
idna==3.10
imagesize==1.4.1
importlib_metadata==8.6.1
iniconfig==2.1.0
Jinja2==3.1.6
jmespath==1.0.1
locket==1.0.0
lxml==5.3.1
MarkupSafe==3.0.2
mccabe==0.7.0
mmh3==5.1.0
mock==5.2.0
moto==5.1.2
msgpack==1.1.0
msgpack-python==0.5.6
numpy==2.0.2
numpydoc==0.6.0
packaging==24.2
pandas==2.2.3
pandas-datareader==0.10.0
partd==1.4.2
pluggy==1.5.0
psutil==7.0.0
pyarrow==19.0.1
pycodestyle==2.13.0
pycparser==2.22
pyflakes==3.3.1
Pygments==2.19.1
pytest==8.3.5
pytest-xdist==3.6.1
python-dateutil==2.9.0.post0
pytz==2025.2
PyYAML==6.0.2
requests==2.32.3
responses==0.25.7
s3transfer==0.11.4
six==1.17.0
snowballstemmer==2.2.0
sortedcontainers==2.4.0
Sphinx==7.4.7
sphinx-rtd-theme==3.0.2
sphinxcontrib-applehelp==2.0.0
sphinxcontrib-devhelp==2.0.0
sphinxcontrib-htmlhelp==2.1.0
sphinxcontrib-jquery==4.1
sphinxcontrib-jsmath==1.0.1
sphinxcontrib-qthelp==2.0.0
sphinxcontrib-serializinghtml==2.0.0
tblib==3.1.0
tomli==2.2.1
toolz==1.0.0
tornado==6.4.2
tzdata==2025.2
urllib3==1.26.20
Werkzeug==3.1.3
xmltodict==0.14.2
xxhash==3.5.0
zict==3.0.0
zipp==3.21.0
| name: dask
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- alabaster==0.7.16
- babel==2.17.0
- backports-lzma==0.0.14
- blosc==1.11.2
- boto3==1.37.23
- botocore==1.37.23
- cachey==0.2.1
- certifi==2025.1.31
- cffi==1.17.1
- charset-normalizer==3.4.1
- cityhash==0.4.8
- click==8.1.8
- cloudpickle==3.1.1
- cryptography==44.0.2
- distributed==1.19.3
- docutils==0.21.2
- exceptiongroup==1.2.2
- execnet==2.1.1
- flake8==7.2.0
- fsspec==2025.3.1
- graphviz==0.20.3
- heapdict==1.0.1
- idna==3.10
- imagesize==1.4.1
- importlib-metadata==8.6.1
- iniconfig==2.1.0
- jinja2==3.1.6
- jmespath==1.0.1
- locket==1.0.0
- lxml==5.3.1
- markupsafe==3.0.2
- mccabe==0.7.0
- mmh3==5.1.0
- mock==5.2.0
- moto==5.1.2
- msgpack==1.1.0
- msgpack-python==0.5.6
- numpy==2.0.2
- numpydoc==0.6.0
- packaging==24.2
- pandas==2.2.3
- pandas-datareader==0.10.0
- partd==1.4.2
- pluggy==1.5.0
- psutil==7.0.0
- pyarrow==19.0.1
- pycodestyle==2.13.0
- pycparser==2.22
- pyflakes==3.3.1
- pygments==2.19.1
- pytest==8.3.5
- pytest-xdist==3.6.1
- python-dateutil==2.9.0.post0
- pytz==2025.2
- pyyaml==6.0.2
- requests==2.32.3
- responses==0.25.7
- s3transfer==0.11.4
- six==1.17.0
- snowballstemmer==2.2.0
- sortedcontainers==2.4.0
- sphinx==7.4.7
- sphinx-rtd-theme==3.0.2
- sphinxcontrib-applehelp==2.0.0
- sphinxcontrib-devhelp==2.0.0
- sphinxcontrib-htmlhelp==2.1.0
- sphinxcontrib-jquery==4.1
- sphinxcontrib-jsmath==1.0.1
- sphinxcontrib-qthelp==2.0.0
- sphinxcontrib-serializinghtml==2.0.0
- tblib==3.1.0
- tomli==2.2.1
- toolz==1.0.0
- tornado==6.4.2
- tzdata==2025.2
- urllib3==1.26.20
- werkzeug==3.1.3
- xmltodict==0.14.2
- xxhash==3.5.0
- zict==3.0.0
- zipp==3.21.0
prefix: /opt/conda/envs/dask
| [
"dask/diagnostics/tests/test_profiler.py::test_resource_profiler",
"dask/diagnostics/tests/test_profiler.py::test_resource_profiler_multiple_gets"
]
| []
| [
"dask/diagnostics/tests/test_profiler.py::test_profiler",
"dask/diagnostics/tests/test_profiler.py::test_profiler_works_under_error",
"dask/diagnostics/tests/test_profiler.py::test_two_gets",
"dask/diagnostics/tests/test_profiler.py::test_cache_profiler",
"dask/diagnostics/tests/test_profiler.py::test_register[Profiler]",
"dask/diagnostics/tests/test_profiler.py::test_register[<lambda>]",
"dask/diagnostics/tests/test_profiler.py::test_register[CacheProfiler]"
]
| []
| BSD 3-Clause "New" or "Revised" License | 1,860 | [
"dask/diagnostics/profile.py"
]
| [
"dask/diagnostics/profile.py"
]
|
pynamodb__PynamoDB-408 | 14e2507cef686952921291fee82a12a21a25444e | 2017-11-08 23:38:48 | 1828bda52376a4b0313146b64ffb447e5392f467 | diff --git a/pynamodb/attributes.py b/pynamodb/attributes.py
index 995b1d9..bf81f09 100644
--- a/pynamodb/attributes.py
+++ b/pynamodb/attributes.py
@@ -163,11 +163,11 @@ class Attribute(object):
def remove(self):
return Path(self).remove()
- def add(self, value):
- return Path(self).add(value)
+ def add(self, *values):
+ return Path(self).add(*values)
- def delete(self, value):
- return Path(self).delete(value)
+ def delete(self, *values):
+ return Path(self).delete(*values)
class AttributeContainerMeta(type):
diff --git a/pynamodb/expressions/operand.py b/pynamodb/expressions/operand.py
index 02c79a7..a3e8758 100644
--- a/pynamodb/expressions/operand.py
+++ b/pynamodb/expressions/operand.py
@@ -275,12 +275,14 @@ class Path(_NumericOperand, _ListAppendOperand, _ConditionOperand):
# Returns an update action that removes this attribute from the item
return RemoveAction(self)
- def add(self, value):
- # Returns an update action that appends the given value to a set or mathematically adds it to a number
+ def add(self, *values):
+ # Returns an update action that appends the given values to a set or mathematically adds a value to a number
+ value = values[0] if len(values) == 1 else values
return AddAction(self, self._to_operand(value))
- def delete(self, value):
- # Returns an update action that removes the given value from a set attribute
+ def delete(self, *values):
+ # Returns an update action that removes the given values from a set attribute
+ value = values[0] if len(values) == 1 else values
return DeleteAction(self, self._to_operand(value))
def exists(self):
| update syntax could be nicer for adding and removing subsets
When calling `Attribute.add()` and `Attribute.delete()` on set attributes, we could detect `*args` and promote them to a set automatically instead of requiring the user create set singletons. | pynamodb/PynamoDB | diff --git a/pynamodb/tests/test_expressions.py b/pynamodb/tests/test_expressions.py
index f89b862..1923035 100644
--- a/pynamodb/tests/test_expressions.py
+++ b/pynamodb/tests/test_expressions.py
@@ -475,6 +475,14 @@ class UpdateExpressionTestCase(TestCase):
assert expression_attribute_values == {':0': {'N': '0'}}
def test_add_action_set(self):
+ action = NumberSetAttribute(attr_name='foo').add(0, 1)
+ placeholder_names, expression_attribute_values = {}, {}
+ expression = action.serialize(placeholder_names, expression_attribute_values)
+ assert expression == "#0 :0"
+ assert placeholder_names == {'foo': '#0'}
+ assert expression_attribute_values == {':0': {'NS': ['0', '1']}}
+
+ def test_add_action_serialized(self):
action = NumberSetAttribute(attr_name='foo').add({'NS': ['0']})
placeholder_names, expression_attribute_values = {}, {}
expression = action.serialize(placeholder_names, expression_attribute_values)
@@ -487,6 +495,22 @@ class UpdateExpressionTestCase(TestCase):
Path('foo').add({'L': [{'N': '0'}]})
def test_delete_action(self):
+ action = NumberSetAttribute(attr_name='foo').delete(0, 1)
+ placeholder_names, expression_attribute_values = {}, {}
+ expression = action.serialize(placeholder_names, expression_attribute_values)
+ assert expression == "#0 :0"
+ assert placeholder_names == {'foo': '#0'}
+ assert expression_attribute_values == {':0': {'NS': ['0', '1']}}
+
+ def test_delete_action_set(self):
+ action = NumberSetAttribute(attr_name='foo').delete(set([0, 1]))
+ placeholder_names, expression_attribute_values = {}, {}
+ expression = action.serialize(placeholder_names, expression_attribute_values)
+ assert expression == "#0 :0"
+ assert placeholder_names == {'foo': '#0'}
+ assert expression_attribute_values == {':0': {'NS': ['0', '1']}}
+
+ def test_delete_action_serialized(self):
action = NumberSetAttribute(attr_name='foo').delete({'NS': ['0']})
placeholder_names, expression_attribute_values = {}, {}
expression = action.serialize(placeholder_names, expression_attribute_values)
diff --git a/pynamodb/tests/test_model.py b/pynamodb/tests/test_model.py
index 240ab46..f0ac212 100644
--- a/pynamodb/tests/test_model.py
+++ b/pynamodb/tests/test_model.py
@@ -966,7 +966,8 @@ class ModelTestCase(TestCase):
SimpleUserModel.views.remove(),
SimpleUserModel.is_active.set(None),
SimpleUserModel.signature.set(None),
- SimpleUserModel.custom_aliases.set(['bob'])
+ SimpleUserModel.custom_aliases.set(['bob']),
+ SimpleUserModel.numbers.delete(0, 1)
])
args = req.call_args[0][1]
@@ -978,13 +979,14 @@ class ModelTestCase(TestCase):
'S': 'foo'
}
},
- 'UpdateExpression': 'SET #0 = :0, #1 = :1, #2 = :2, #3 = :3 REMOVE #4',
+ 'UpdateExpression': 'SET #0 = :0, #1 = :1, #2 = :2, #3 = :3 REMOVE #4 DELETE #5 :4',
'ExpressionAttributeNames': {
'#0': 'email',
'#1': 'is_active',
'#2': 'signature',
'#3': 'aliases',
- '#4': 'views'
+ '#4': 'views',
+ '#5': 'numbers'
},
'ExpressionAttributeValues': {
':0': {
@@ -997,7 +999,10 @@ class ModelTestCase(TestCase):
'NULL': True
},
':3': {
- 'SS': set(['bob'])
+ 'SS': ['bob']
+ },
+ ':4': {
+ 'NS': ['0', '1']
}
},
'ReturnConsumedCapacity': 'TOTAL'
| {
"commit_name": "merge_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 1,
"test_score": 3
},
"num_modified_files": 2
} | 3.2 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest"
],
"pre_install": null,
"python": "3.6",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs==22.2.0
botocore==1.2.0
certifi==2021.5.30
docutils==0.18.1
importlib-metadata==4.8.3
iniconfig==1.1.1
jmespath==0.7.1
packaging==21.3
pluggy==1.0.0
py==1.11.0
-e git+https://github.com/pynamodb/PynamoDB.git@14e2507cef686952921291fee82a12a21a25444e#egg=pynamodb
pyparsing==3.1.4
pytest==7.0.1
python-dateutil==2.9.0.post0
six==1.9.0
tomli==1.2.3
typing_extensions==4.1.1
zipp==3.6.0
| name: PynamoDB
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- attrs==22.2.0
- botocore==1.2.0
- docutils==0.18.1
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- jmespath==0.7.1
- packaging==21.3
- pluggy==1.0.0
- py==1.11.0
- pyparsing==3.1.4
- pytest==7.0.1
- python-dateutil==2.9.0.post0
- six==1.9.0
- tomli==1.2.3
- typing-extensions==4.1.1
- zipp==3.6.0
prefix: /opt/conda/envs/PynamoDB
| [
"pynamodb/tests/test_expressions.py::UpdateExpressionTestCase::test_add_action_set",
"pynamodb/tests/test_expressions.py::UpdateExpressionTestCase::test_delete_action",
"pynamodb/tests/test_model.py::ModelTestCase::test_update"
]
| []
| [
"pynamodb/tests/test_expressions.py::PathTestCase::test_attribute_name",
"pynamodb/tests/test_expressions.py::PathTestCase::test_document_path",
"pynamodb/tests/test_expressions.py::PathTestCase::test_index_attribute_name",
"pynamodb/tests/test_expressions.py::PathTestCase::test_index_document_path",
"pynamodb/tests/test_expressions.py::PathTestCase::test_index_invalid",
"pynamodb/tests/test_expressions.py::PathTestCase::test_index_map_attribute",
"pynamodb/tests/test_expressions.py::ActionTestCase::test_action",
"pynamodb/tests/test_expressions.py::ProjectionExpressionTestCase::test_create_project_expression_with_attribute_names",
"pynamodb/tests/test_expressions.py::ProjectionExpressionTestCase::test_create_project_expression_with_document_paths",
"pynamodb/tests/test_expressions.py::ProjectionExpressionTestCase::test_create_projection_expression",
"pynamodb/tests/test_expressions.py::ProjectionExpressionTestCase::test_create_projection_expression_invalid_attribute_raises",
"pynamodb/tests/test_expressions.py::ProjectionExpressionTestCase::test_create_projection_expression_not_a_list",
"pynamodb/tests/test_expressions.py::ProjectionExpressionTestCase::test_create_projection_expression_repeated_names",
"pynamodb/tests/test_expressions.py::ProjectionExpressionTestCase::test_create_projection_expression_with_attributes",
"pynamodb/tests/test_expressions.py::ConditionExpressionTestCase::test_and",
"pynamodb/tests/test_expressions.py::ConditionExpressionTestCase::test_begins_with",
"pynamodb/tests/test_expressions.py::ConditionExpressionTestCase::test_between",
"pynamodb/tests/test_expressions.py::ConditionExpressionTestCase::test_compound_logic",
"pynamodb/tests/test_expressions.py::ConditionExpressionTestCase::test_contains",
"pynamodb/tests/test_expressions.py::ConditionExpressionTestCase::test_contains_attribute",
"pynamodb/tests/test_expressions.py::ConditionExpressionTestCase::test_contains_list",
"pynamodb/tests/test_expressions.py::ConditionExpressionTestCase::test_contains_number_set",
"pynamodb/tests/test_expressions.py::ConditionExpressionTestCase::test_contains_string_set",
"pynamodb/tests/test_expressions.py::ConditionExpressionTestCase::test_does_not_exist",
"pynamodb/tests/test_expressions.py::ConditionExpressionTestCase::test_dotted_attribute_name",
"pynamodb/tests/test_expressions.py::ConditionExpressionTestCase::test_double_indexing",
"pynamodb/tests/test_expressions.py::ConditionExpressionTestCase::test_equal",
"pynamodb/tests/test_expressions.py::ConditionExpressionTestCase::test_exists",
"pynamodb/tests/test_expressions.py::ConditionExpressionTestCase::test_greater_than",
"pynamodb/tests/test_expressions.py::ConditionExpressionTestCase::test_greater_than_or_equal",
"pynamodb/tests/test_expressions.py::ConditionExpressionTestCase::test_in",
"pynamodb/tests/test_expressions.py::ConditionExpressionTestCase::test_indexing",
"pynamodb/tests/test_expressions.py::ConditionExpressionTestCase::test_invalid_indexing",
"pynamodb/tests/test_expressions.py::ConditionExpressionTestCase::test_is_type",
"pynamodb/tests/test_expressions.py::ConditionExpressionTestCase::test_less_than",
"pynamodb/tests/test_expressions.py::ConditionExpressionTestCase::test_less_than_or_equal",
"pynamodb/tests/test_expressions.py::ConditionExpressionTestCase::test_list_comparison",
"pynamodb/tests/test_expressions.py::ConditionExpressionTestCase::test_map_attribute_dereference",
"pynamodb/tests/test_expressions.py::ConditionExpressionTestCase::test_map_attribute_dereference_via_indexing",
"pynamodb/tests/test_expressions.py::ConditionExpressionTestCase::test_map_attribute_dereference_via_indexing_missing_attribute",
"pynamodb/tests/test_expressions.py::ConditionExpressionTestCase::test_map_attribute_indexing",
"pynamodb/tests/test_expressions.py::ConditionExpressionTestCase::test_not",
"pynamodb/tests/test_expressions.py::ConditionExpressionTestCase::test_not_equal",
"pynamodb/tests/test_expressions.py::ConditionExpressionTestCase::test_or",
"pynamodb/tests/test_expressions.py::ConditionExpressionTestCase::test_size",
"pynamodb/tests/test_expressions.py::ConditionExpressionTestCase::test_sizes",
"pynamodb/tests/test_expressions.py::UpdateExpressionTestCase::test_add_action",
"pynamodb/tests/test_expressions.py::UpdateExpressionTestCase::test_add_action_list",
"pynamodb/tests/test_expressions.py::UpdateExpressionTestCase::test_add_action_serialized",
"pynamodb/tests/test_expressions.py::UpdateExpressionTestCase::test_append_action",
"pynamodb/tests/test_expressions.py::UpdateExpressionTestCase::test_conditional_set_action",
"pynamodb/tests/test_expressions.py::UpdateExpressionTestCase::test_decrement_action",
"pynamodb/tests/test_expressions.py::UpdateExpressionTestCase::test_decrement_action_value",
"pynamodb/tests/test_expressions.py::UpdateExpressionTestCase::test_delete_action_non_set",
"pynamodb/tests/test_expressions.py::UpdateExpressionTestCase::test_delete_action_serialized",
"pynamodb/tests/test_expressions.py::UpdateExpressionTestCase::test_delete_action_set",
"pynamodb/tests/test_expressions.py::UpdateExpressionTestCase::test_increment_action",
"pynamodb/tests/test_expressions.py::UpdateExpressionTestCase::test_increment_action_value",
"pynamodb/tests/test_expressions.py::UpdateExpressionTestCase::test_prepend_action",
"pynamodb/tests/test_expressions.py::UpdateExpressionTestCase::test_remove_action",
"pynamodb/tests/test_expressions.py::UpdateExpressionTestCase::test_set_action",
"pynamodb/tests/test_expressions.py::UpdateExpressionTestCase::test_update",
"pynamodb/tests/test_model.py::ModelTestCase::test_batch_get",
"pynamodb/tests/test_model.py::ModelTestCase::test_batch_write",
"pynamodb/tests/test_model.py::ModelTestCase::test_batch_write_with_unprocessed",
"pynamodb/tests/test_model.py::ModelTestCase::test_car_model_retrieve_from_db",
"pynamodb/tests/test_model.py::ModelTestCase::test_car_model_with_null_retrieve_from_db",
"pynamodb/tests/test_model.py::ModelTestCase::test_complex_key",
"pynamodb/tests/test_model.py::ModelTestCase::test_complex_model_is_complex",
"pynamodb/tests/test_model.py::ModelTestCase::test_complex_model_retrieve_from_db",
"pynamodb/tests/test_model.py::ModelTestCase::test_conditional_operator_map_attribute",
"pynamodb/tests/test_model.py::ModelTestCase::test_count",
"pynamodb/tests/test_model.py::ModelTestCase::test_count_no_hash_key",
"pynamodb/tests/test_model.py::ModelTestCase::test_create_model",
"pynamodb/tests/test_model.py::ModelTestCase::test_delete",
"pynamodb/tests/test_model.py::ModelTestCase::test_delete_doesnt_do_validation_on_null_attributes",
"pynamodb/tests/test_model.py::ModelTestCase::test_deserializing_map_four_layers_deep_works",
"pynamodb/tests/test_model.py::ModelTestCase::test_deserializing_new_style_bool_false_works",
"pynamodb/tests/test_model.py::ModelTestCase::test_deserializing_new_style_bool_true_works",
"pynamodb/tests/test_model.py::ModelTestCase::test_deserializing_old_style_bool_false_works",
"pynamodb/tests/test_model.py::ModelTestCase::test_deserializing_old_style_bool_true_works",
"pynamodb/tests/test_model.py::ModelTestCase::test_dumps",
"pynamodb/tests/test_model.py::ModelTestCase::test_explicit_raw_map_serialize_pass",
"pynamodb/tests/test_model.py::ModelTestCase::test_filter_count",
"pynamodb/tests/test_model.py::ModelTestCase::test_get",
"pynamodb/tests/test_model.py::ModelTestCase::test_global_index",
"pynamodb/tests/test_model.py::ModelTestCase::test_index_count",
"pynamodb/tests/test_model.py::ModelTestCase::test_index_multipage_count",
"pynamodb/tests/test_model.py::ModelTestCase::test_index_queries",
"pynamodb/tests/test_model.py::ModelTestCase::test_invalid_car_model_with_null_retrieve_from_db",
"pynamodb/tests/test_model.py::ModelTestCase::test_invalid_map_model_raises",
"pynamodb/tests/test_model.py::ModelTestCase::test_list_of_map_works_like_list_of_map",
"pynamodb/tests/test_model.py::ModelTestCase::test_list_works_like_list",
"pynamodb/tests/test_model.py::ModelTestCase::test_loads",
"pynamodb/tests/test_model.py::ModelTestCase::test_loads_complex_model",
"pynamodb/tests/test_model.py::ModelTestCase::test_local_index",
"pynamodb/tests/test_model.py::ModelTestCase::test_model_attrs",
"pynamodb/tests/test_model.py::ModelTestCase::test_model_subclass_attributes_inherited_on_create",
"pynamodb/tests/test_model.py::ModelTestCase::test_model_with_invalid_data_does_not_validate",
"pynamodb/tests/test_model.py::ModelTestCase::test_model_with_list",
"pynamodb/tests/test_model.py::ModelTestCase::test_model_with_list_of_map",
"pynamodb/tests/test_model.py::ModelTestCase::test_model_with_list_of_map_retrieve_from_db",
"pynamodb/tests/test_model.py::ModelTestCase::test_model_with_list_retrieve_from_db",
"pynamodb/tests/test_model.py::ModelTestCase::test_model_with_maps",
"pynamodb/tests/test_model.py::ModelTestCase::test_model_with_maps_retrieve_from_db",
"pynamodb/tests/test_model.py::ModelTestCase::test_model_with_maps_with_nulls_retrieve_from_db",
"pynamodb/tests/test_model.py::ModelTestCase::test_model_with_maps_with_pythonic_attributes",
"pynamodb/tests/test_model.py::ModelTestCase::test_model_with_nulls_validates",
"pynamodb/tests/test_model.py::ModelTestCase::test_model_works_like_model",
"pynamodb/tests/test_model.py::ModelTestCase::test_multiple_indices_share_non_key_attribute",
"pynamodb/tests/test_model.py::ModelTestCase::test_new_style_boolean_serializes_as_bool",
"pynamodb/tests/test_model.py::ModelTestCase::test_old_style_boolean_serializes_as_bool",
"pynamodb/tests/test_model.py::ModelTestCase::test_old_style_model_exception",
"pynamodb/tests/test_model.py::ModelTestCase::test_overidden_defaults",
"pynamodb/tests/test_model.py::ModelTestCase::test_overidden_session",
"pynamodb/tests/test_model.py::ModelTestCase::test_overridden_attr_name",
"pynamodb/tests/test_model.py::ModelTestCase::test_projections",
"pynamodb/tests/test_model.py::ModelTestCase::test_query",
"pynamodb/tests/test_model.py::ModelTestCase::test_query_limit_greater_than_available_items_and_page_size",
"pynamodb/tests/test_model.py::ModelTestCase::test_query_limit_greater_than_available_items_multiple_page",
"pynamodb/tests/test_model.py::ModelTestCase::test_query_limit_greater_than_available_items_single_page",
"pynamodb/tests/test_model.py::ModelTestCase::test_query_limit_identical_to_available_items_single_page",
"pynamodb/tests/test_model.py::ModelTestCase::test_query_limit_less_than_available_and_page_size",
"pynamodb/tests/test_model.py::ModelTestCase::test_query_limit_less_than_available_items_multiple_page",
"pynamodb/tests/test_model.py::ModelTestCase::test_rate_limited_scan",
"pynamodb/tests/test_model.py::ModelTestCase::test_raw_map_as_sub_map",
"pynamodb/tests/test_model.py::ModelTestCase::test_raw_map_as_sub_map_deserialize",
"pynamodb/tests/test_model.py::ModelTestCase::test_raw_map_as_sub_map_from_raw_data_works",
"pynamodb/tests/test_model.py::ModelTestCase::test_raw_map_as_sub_map_serialize_pass",
"pynamodb/tests/test_model.py::ModelTestCase::test_raw_map_deserializes",
"pynamodb/tests/test_model.py::ModelTestCase::test_raw_map_from_raw_data_works",
"pynamodb/tests/test_model.py::ModelTestCase::test_raw_map_serialize_fun_one",
"pynamodb/tests/test_model.py::ModelTestCase::test_refresh",
"pynamodb/tests/test_model.py::ModelTestCase::test_result_set_init",
"pynamodb/tests/test_model.py::ModelTestCase::test_result_set_iter",
"pynamodb/tests/test_model.py::ModelTestCase::test_save",
"pynamodb/tests/test_model.py::ModelTestCase::test_scan",
"pynamodb/tests/test_model.py::ModelTestCase::test_scan_limit",
"pynamodb/tests/test_model.py::ModelTestCase::test_scan_limit_with_page_size",
"pynamodb/tests/test_model.py::ModelTestCase::test_update_item",
"pynamodb/tests/test_model.py::ModelInitTestCase::test_raw_map_attribute_with_dict_init",
"pynamodb/tests/test_model.py::ModelInitTestCase::test_raw_map_attribute_with_initialized_instance_init",
"pynamodb/tests/test_model.py::ModelInitTestCase::test_subclassed_map_attribute_with_dict_init",
"pynamodb/tests/test_model.py::ModelInitTestCase::test_subclassed_map_attribute_with_initialized_instance_init",
"pynamodb/tests/test_model.py::ModelInitTestCase::test_subclassed_map_attribute_with_map_attribute_member_with_initialized_instance_init",
"pynamodb/tests/test_model.py::ModelInitTestCase::test_subclassed_map_attribute_with_map_attributes_member_with_dict_init"
]
| []
| MIT License | 1,861 | [
"pynamodb/expressions/operand.py",
"pynamodb/attributes.py"
]
| [
"pynamodb/expressions/operand.py",
"pynamodb/attributes.py"
]
|
|
kopf__httsleep-14 | 1a5e76d39488876abe06c7f359bdf84e1e5433e5 | 2017-11-09 09:31:42 | 1a5e76d39488876abe06c7f359bdf84e1e5433e5 | diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index a162d14..836d8b5 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -3,8 +3,8 @@ httsleep Changelog
Version NEXT
-------------
-* The kwarg ``verify`` is now supported, allowing users of httsleep to specify
- ``verify=False`` in the same way as when directly using the ``requests`` library.
+* The kwargs ``verify`` and ``session`` are now supported, allowing users of httsleep to
+ specify these in the same way as when directly using the ``requests`` library.
Version 0.2.0
-------------
diff --git a/docs/tutorial.rst b/docs/tutorial.rst
index 7c8588b..5624d1e 100644
--- a/docs/tutorial.rst
+++ b/docs/tutorial.rst
@@ -40,6 +40,23 @@ pass a :class:`requests.Request` object in place of the URL in more specific cas
data={'payload': 'here'})
response = httsleep(req, status_code=200)
+.. _Session object: http://docs.python-requests.org/en/master/user/advanced/#session-objects
+
+If you want to share headers, cookies etc. across multiple different HTTP requests (e.g.
+to maintain auth credentials), you might make use of a `Session object`_.
+
+.. code-block:: python
+
+ import requests
+ session = requests.Session()
+ session.verify = False
+ session.headers.update({'Authorization': 'token=%s' % auth_token,
+ 'Content-Type': 'application/json'})
+
+ response = session.post('http://server/jobs/create', data=data)
+ response = httsleep('http://server/jobs/1', session=session, until={'status_code': 200})
+ response = session.get('http://server/jobs/1/output')
+
If we're polling a server with a dodgy network connection, we might not want to
break on a :class:`requests.exceptions.ConnectionError`, but instead keep polling:
diff --git a/httsleep/main.py b/httsleep/main.py
index 649d5ed..00ac861 100644
--- a/httsleep/main.py
+++ b/httsleep/main.py
@@ -12,6 +12,7 @@ from ._compat import string_types
DEFAULT_POLLING_INTERVAL = 2 # in seconds
DEFAULT_MAX_RETRIES = 50
VALID_CONDITIONS = ['status_code', 'json', 'jsonpath', 'text', 'callback']
+DEFAULT_SESSION = requests.Session()
class HttSleeper(object):
@@ -33,10 +34,14 @@ class HttSleeper(object):
:param callback: shorthand for a success condition dependent on a callback
function that takes the response as an argument returning True.
:param auth: a (username, password) tuple for HTTP authentication.
- :param headers: a dict of HTTP headers.
+ :param headers: a dict of HTTP headers. If specified, these will be merged with (and take
+ precedence over) any headers provided in the session.
+ :param session: a Requests session, providing cookie persistence, connection-pooling, and
+ configuration (e.g. headers).
:param verify: Either a boolean, in which case it controls whether we verify the server's
TLS certificate, or a string, in which case it must be a path to a CA
- bundle to use. Defaults to ``True``.
+ bundle to use. If specified, this takes precedence over any value defined
+ in the session (which itself would be ``True``, by default).
:param polling_interval: how many seconds to sleep between requests.
:param max_retries: the maximum number of retries to make, after which
a StopIteration exception is raised.
@@ -49,7 +54,7 @@ class HttSleeper(object):
"""
def __init__(self, url_or_request, until=None, alarms=None,
status_code=None, json=None, jsonpath=None, text=None, callback=None,
- auth=None, headers=None, verify=True,
+ auth=None, headers=None, session=DEFAULT_SESSION, verify=None,
polling_interval=DEFAULT_POLLING_INTERVAL,
max_retries=DEFAULT_MAX_RETRIES,
ignore_exceptions=None,
@@ -87,11 +92,13 @@ class HttSleeper(object):
'jsonpath': jsonpath, 'text': text, 'callback': callback}
until.append({k: v for k, v in condition.items() if v})
- self.verify = verify
+ self.kwargs = {}
+ if verify is not None:
+ self.kwargs['verify'] = verify
self.until = until
self.alarms = alarms
self.polling_interval = int(polling_interval)
- self.session = requests.Session()
+ self.session = session
self.log = logging.getLogger()
self.log.setLevel(loglevel)
@@ -149,7 +156,7 @@ class HttSleeper(object):
"""
while True:
try:
- response = self.session.send(self.request.prepare(), verify=self.verify)
+ response = self.session.send(self.session.prepare_request(self.request), **self.kwargs)
for condition in self.alarms:
if self.meets_condition(response, condition):
raise Alarm(response, condition)
@@ -198,7 +205,7 @@ class HttSleeper(object):
def httsleep(url_or_request, until=None, alarms=None, status_code=None,
json=None, jsonpath=None, text=None, callback=None,
- auth=None, headers=None, verify=True,
+ auth=None, headers=None, session=DEFAULT_SESSION, verify=None,
polling_interval=DEFAULT_POLLING_INTERVAL,
max_retries=DEFAULT_MAX_RETRIES,
ignore_exceptions=None,
@@ -211,7 +218,7 @@ def httsleep(url_or_request, until=None, alarms=None, status_code=None,
return HttSleeper(
url_or_request, until=until, alarms=alarms, status_code=status_code,
json=json, jsonpath=jsonpath, text=text, callback=callback,
- auth=auth, headers=headers, verify=verify,
+ auth=auth, headers=headers, session=session, verify=verify,
polling_interval=polling_interval,
max_retries=max_retries,
ignore_exceptions=ignore_exceptions,
| Support passing in a `Session` object
Users may already have a `requests.Session` object and wish to reuse that rather than having `httsleep` create a blank one. This would save users from re-entering standard headers, settings etc. that they've already configured elsewhere.
### Ideal usage afterwards:
```python
httsleep(url, until=until, alarms=alarms, session=my_session)
```
### ~~~Workaround~~~ Not usable
```python
poller = HttSleeper(url, until=until, alarms=alarms)
poller.session = my_session
poller.run()
```
Not usable because [here](https://github.com/kopf/httsleep/blob/master/httsleep/main.py#L148) the request is prepared without the context of the Session:
```python
response = self.session.send(self.request.prepare()
```
The workaround would be usable if this line was instead:
```python
response = self.session.send(self.session.prepare_request(request))
```
| kopf/httsleep | diff --git a/tests/test_init.py b/tests/test_init.py
index d367d77..93cce22 100644
--- a/tests/test_init.py
+++ b/tests/test_init.py
@@ -35,14 +35,28 @@ def test_headers():
assert obj.request.headers == headers
-def test_default_verify():
+def test_default_kwargs():
obj = HttSleeper(URL, CONDITION)
- assert obj.verify == True
+ assert obj.kwargs == {}
def test_verify():
obj = HttSleeper(URL, CONDITION, verify=False)
- assert obj.verify == False
+ assert obj.kwargs == {'verify': False}
+
+
+def test_default_session():
+ obj = HttSleeper(URL, CONDITION)
+ assert obj.session.headers == requests.utils.default_headers()
+
+
+def test_session():
+ session = requests.Session()
+ session.headers = {'Content-Type': 'test/type'}
+ session.verify = False
+ obj = HttSleeper(URL, CONDITION, session=session)
+ assert obj.session.headers == session.headers
+ assert obj.session.verify == session.verify
def test_ignore_exceptions_default_value():
diff --git a/tests/test_run.py b/tests/test_run.py
index 24f59ff..dbd4350 100644
--- a/tests/test_run.py
+++ b/tests/test_run.py
@@ -4,6 +4,7 @@ import httpretty
from jsonpath_rw.jsonpath import Fields
import mock
import pytest
+import requests
from requests.exceptions import ConnectionError
from requests import Response
@@ -29,11 +30,11 @@ def test_propagate_verify():
resp = Response()
resp.status_code = 200
httsleep = HttSleeper(URL, {'status_code': 200}, verify=False)
- with mock.patch('requests.sessions.Session.send') as mock_session_send:
- mock_session_send.return_value = resp
+ with mock.patch('requests.adapters.HTTPAdapter.send') as mock_adapter_send:
+ mock_adapter_send.return_value = resp
httsleep.run()
- assert mock_session_send.called
- args, kwargs = mock_session_send.call_args
+ assert mock_adapter_send.called
+ args, kwargs = mock_adapter_send.call_args
assert 'verify' in kwargs
assert kwargs['verify'] == False
@@ -44,15 +45,85 @@ def test_default_sends_verify_true():
resp = Response()
resp.status_code = 200
httsleep = HttSleeper(URL, {'status_code': 200})
- with mock.patch('requests.sessions.Session.send') as mock_session_send:
- mock_session_send.return_value = resp
+ with mock.patch('requests.adapters.HTTPAdapter.send') as mock_adapter_send:
+ mock_adapter_send.return_value = resp
httsleep.run()
- assert mock_session_send.called
- args, kwargs = mock_session_send.call_args
+ assert mock_adapter_send.called
+ args, kwargs = mock_adapter_send.call_args
assert 'verify' in kwargs
assert kwargs['verify'] == True
[email protected]
+def test_default_uses_default_session():
+ """Should use a default Session object unless one is specified"""
+ resp = Response()
+ resp.status_code = 200
+ httsleep = HttSleeper(URL, {'status_code': 200})
+ with mock.patch('requests.adapters.HTTPAdapter.send') as mock_adapter_send:
+ mock_adapter_send.return_value = resp
+ httsleep.run()
+ assert mock_adapter_send.called
+ args, kwargs = mock_adapter_send.call_args
+ assert args[0].headers == requests.utils.default_headers()
+ assert 'verify' in kwargs
+ assert kwargs['verify'] == True
+
+
[email protected]
+def test_propagate_session():
+ """Should propagate a Session's headers, verify setting, cookies etc. when specified"""
+ session = requests.Session()
+ session.cookies = {'tasty-cookie': 'chocolate'}
+ session.headers = {'Content-Type': 'test/type'}
+ session.verify = '/session/verify'
+ resp = Response()
+ resp.status_code = 200
+ httsleep = HttSleeper(URL, {'status_code': 200}, session=session)
+ with mock.patch('requests.adapters.HTTPAdapter.send') as mock_adapter_send:
+ mock_adapter_send.return_value = resp
+ httsleep.run()
+ assert mock_adapter_send.called
+ args, kwargs = mock_adapter_send.call_args
+ assert args[0].headers == {'Content-Type': 'test/type', 'Cookie': 'tasty-cookie=chocolate'}
+ assert 'verify' in kwargs
+ assert kwargs['verify'] == '/session/verify'
+
+
[email protected]
+def test_session_headers_and_request_headers_combine():
+ """Should merge headers directly specified over any headers in a specified Session"""
+ session = requests.Session()
+ session.headers = {'session-header': 'mySession', 'conflict-header': 'session-loses'}
+ resp = Response()
+ resp.status_code = 200
+ httsleep = HttSleeper(URL, {'status_code': 200}, session=session,
+ headers={'req-header': 'myRequest', 'conflict-header': 'req-wins'})
+ with mock.patch('requests.adapters.HTTPAdapter.send') as mock_adapter_send:
+ mock_adapter_send.return_value = resp
+ httsleep.run()
+ assert mock_adapter_send.called
+ args, kwargs = mock_adapter_send.call_args
+ assert args[0].headers == {'conflict-header': 'req-wins', 'req-header': 'myRequest', 'session-header': 'mySession'}
+
+
[email protected]
+def test_request_verify_overrules_session_verify():
+ """Should give precedence to the 'verify' setting in the request, over that in a specified Session"""
+ session = requests.Session()
+ session.verify = '/path/to/ca/bundle'
+ resp = Response()
+ resp.status_code = 200
+ httsleep = HttSleeper(URL, {'status_code': 200}, session=session, verify='/override/path')
+ with mock.patch('requests.adapters.HTTPAdapter.send') as mock_adapter_send:
+ mock_adapter_send.return_value = resp
+ httsleep.run()
+ assert mock_adapter_send.called
+ args, kwargs = mock_adapter_send.call_args
+ assert 'verify' in kwargs
+ assert kwargs['verify'] == '/override/path'
+
+
@httpretty.activate
def test_run_alarm():
"""Should raise an Alarm when a failure criteria has been reached"""
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 0,
"test_score": 3
},
"num_modified_files": 3
} | 0.2 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"httpretty",
"mock"
],
"pre_install": null,
"python": "3.9",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | certifi==2025.1.31
charset-normalizer==3.4.1
decorator==5.2.1
exceptiongroup==1.2.2
httpretty==1.1.4
-e git+https://github.com/kopf/httsleep.git@1a5e76d39488876abe06c7f359bdf84e1e5433e5#egg=httsleep
idna==3.10
iniconfig==2.1.0
jsonpath-rw==1.4.0
mock==5.2.0
packaging==24.2
pluggy==1.5.0
ply==3.11
pytest==8.3.5
requests==2.32.3
six==1.17.0
tomli==2.2.1
urllib3==2.3.0
| name: httsleep
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- certifi==2025.1.31
- charset-normalizer==3.4.1
- decorator==5.2.1
- exceptiongroup==1.2.2
- httpretty==1.1.4
- idna==3.10
- iniconfig==2.1.0
- jsonpath-rw==1.4.0
- mock==5.2.0
- packaging==24.2
- pluggy==1.5.0
- ply==3.11
- pytest==8.3.5
- requests==2.32.3
- six==1.17.0
- tomli==2.2.1
- urllib3==2.3.0
prefix: /opt/conda/envs/httsleep
| [
"tests/test_init.py::test_default_kwargs",
"tests/test_init.py::test_verify",
"tests/test_init.py::test_session",
"tests/test_run.py::test_default_uses_default_session",
"tests/test_run.py::test_propagate_session",
"tests/test_run.py::test_session_headers_and_request_headers_combine",
"tests/test_run.py::test_request_verify_overrules_session_verify"
]
| [
"tests/test_run.py::test_run_sleep_default_interval",
"tests/test_run.py::test_run_sleep_custom_interval"
]
| [
"tests/test_init.py::test_request_built_from_url",
"tests/test_init.py::test_url_or_request",
"tests/test_init.py::test_auth",
"tests/test_init.py::test_headers",
"tests/test_init.py::test_default_session",
"tests/test_init.py::test_ignore_exceptions_default_value",
"tests/test_init.py::test_max_retries",
"tests/test_init.py::test_until",
"tests/test_init.py::test_empty_until",
"tests/test_init.py::test_invalid_until",
"tests/test_init.py::test_status_code_cast_as_int",
"tests/test_init.py::test_alarms",
"tests/test_init.py::test_invalid_alarms",
"tests/test_init.py::test_status_code_cast_as_int_in_alarm",
"tests/test_init.py::test_kwarg_condition",
"tests/test_run.py::test_run_success",
"tests/test_run.py::test_propagate_verify",
"tests/test_run.py::test_default_sends_verify_true",
"tests/test_run.py::test_run_alarm",
"tests/test_run.py::test_run_success_alarm",
"tests/test_run.py::test_run_retries",
"tests/test_run.py::test_run_max_retries",
"tests/test_run.py::test_ignore_exceptions",
"tests/test_run.py::test_json_condition",
"tests/test_run.py::test_text_condition",
"tests/test_run.py::test_jsonpath_condition",
"tests/test_run.py::test_precompiled_jsonpath_expression",
"tests/test_run.py::test_jsonpath_condition_multiple_values",
"tests/test_run.py::test_multiple_jsonpath_conditions",
"tests/test_run.py::test_callback_condition",
"tests/test_run.py::test_multiple_success_conditions",
"tests/test_run.py::test_multiple_alarms"
]
| []
| Apache License 2.0 | 1,862 | [
"docs/tutorial.rst",
"CHANGELOG.rst",
"httsleep/main.py"
]
| [
"docs/tutorial.rst",
"CHANGELOG.rst",
"httsleep/main.py"
]
|
|
planetlabs__planet-client-python-129 | 49da66f16774682e377dfd79eebe0f33ea47f8e1 | 2017-11-09 21:30:58 | 0d5160b40fbcdc6bd97059270d78be03f33ea03c | ischneider: Once #130 is merged, the test should pass again.
ischneider: Updated with the ability to extract the filter from a provided saved search in the JSON from the `--filter-json` flag. CI still expected to fail until #131 is merged | diff --git a/planet/scripts/util.py b/planet/scripts/util.py
index 421631d..21dddf5 100644
--- a/planet/scripts/util.py
+++ b/planet/scripts/util.py
@@ -79,20 +79,23 @@ def check_writable(dirpath):
def filter_from_opts(**kw):
- '''Build a AND filter from the provided filter_in OR kwargs defaulting to an
- empty 'and' filter (@todo: API workaround).
+ '''Build a AND filter from the provided kwargs defaulting to an
+ empty 'and' filter (@todo: API workaround) if nothing is provided.
+
+ If the 'filter_json' argument is provided, this will be assumed to contain
+ a filter specification and will be anded with other filters. If the
+ 'filter_json' is a search, the search filter value will be used.
+
All kw values should be tuple or list
'''
filter_in = kw.pop('filter_json', None)
active = and_filter_from_opts(kw)
- no_filters = len(active['config']) == 0
- if no_filters and not filter_in:
- return filters.and_filter()
- if not no_filters and filter_in:
- raise click.ClickException(
- 'Specify filter options or provide using --filter-json, not both')
if filter_in:
- active = filter_in
+ filter_in = filter_in.get('filter', filter_in)
+ if len(active['config']) > 0:
+ active = filters.and_filter(active, filter_in)
+ else:
+ active = filter_in
return active
| cli download command improperly rejects --filter-json argument
To make the download experience nicer, the download command implicitly creates a permissions filter but does not combine it with the provided filter argument and exits with the message:
`Error: Specify filter options or provide using --filter-json, not both`
It seems like the proper behavior would be:
1. if the provided filter is an AND filter, add the permissions filter as a predicate
2. otherwise create a new top-level AND filter with the permissions and provided filter as predicates
| planetlabs/planet-client-python | diff --git a/tests/test_v1_cli.py b/tests/test_v1_cli.py
index 8b56083..838ff07 100644
--- a/tests/test_v1_cli.py
+++ b/tests/test_v1_cli.py
@@ -55,16 +55,47 @@ def test_filter(runner):
def filt(*opts):
return runner.invoke(main, ['data', 'filter'] + list(opts))
assert_success(filt(), {
- "type": "AndFilter",
- "config": []
+ 'type': 'AndFilter',
+ 'config': []
})
assert_success(filt('--string-in', 'eff', 'a b c'), {
- "type": "AndFilter",
- "config": [
+ 'type': 'AndFilter',
+ 'config': [
{'config': ['a', 'b', 'c'], 'field_name': 'eff',
'type': 'StringInFilter'}
]
})
+ filter_spec = {
+ 'type': 'StringInFilter',
+ 'config': ['a'],
+ 'field_name': 'eff'
+ }
+ # if no other options, filter-json is used as is
+ assert_success(filt('--filter-json', json.dumps(filter_spec)), filter_spec)
+ # verify we extract the filter property of a search
+ assert_success(filt('--filter-json', json.dumps({
+ "filter": filter_spec
+ })), filter_spec)
+ # filters are combined - the --string-in option results in a single AND
+ # filter and this is combined with the provided filter_spec in a top-level
+ # AND filter
+ assert_success(filt('--filter-json', json.dumps(filter_spec),
+ '--string-in', 'eff', 'b'), {
+ 'config': [
+ {
+ 'type': 'AndFilter',
+ 'config': [
+ {
+ 'type': 'StringInFilter',
+ 'config': ['b'],
+ 'field_name': 'eff'
+ }
+ ]
+ },
+ filter_spec
+ ],
+ 'type': 'AndFilter'
+ })
# @todo more cases that are easier to write/maintain
| {
"commit_name": "head_commit",
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 1,
"test_score": 1
},
"num_modified_files": 1
} | 1.1 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-cov",
"pytest-mock",
"pytest-xdist"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.6",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | alabaster==0.7.13
attrs==22.2.0
Babel==2.11.0
certifi==2021.5.30
charset-normalizer==2.0.12
click==8.0.4
coverage==6.2
docutils==0.17.1
execnet==1.9.0
flake8==5.0.4
idna==3.10
imagesize==1.4.1
importlib-metadata==4.2.0
iniconfig==1.1.1
Jinja2==3.0.3
MarkupSafe==2.0.1
mccabe==0.7.0
mock==5.2.0
packaging==21.3
pex==2.33.7
-e git+https://github.com/planetlabs/planet-client-python.git@49da66f16774682e377dfd79eebe0f33ea47f8e1#egg=planet
pluggy==1.0.0
py==1.11.0
pycodestyle==2.9.1
pyflakes==2.5.0
Pygments==2.14.0
pyparsing==3.1.4
pytest==7.0.1
pytest-cov==4.0.0
pytest-mock==3.6.1
pytest-xdist==3.0.2
pytz==2025.2
requests==2.27.1
requests-futures==1.0.2
requests-mock==1.12.1
snowballstemmer==2.2.0
Sphinx==4.3.2
sphinxcontrib-applehelp==1.0.2
sphinxcontrib-devhelp==1.0.2
sphinxcontrib-htmlhelp==2.0.0
sphinxcontrib-jsmath==1.0.1
sphinxcontrib-qthelp==1.0.3
sphinxcontrib-serializinghtml==1.1.5
tomli==1.2.3
typing_extensions==4.1.1
urllib3==1.26.20
zipp==3.6.0
| name: planet-client-python
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- alabaster==0.7.13
- attrs==22.2.0
- babel==2.11.0
- charset-normalizer==2.0.12
- click==8.0.4
- coverage==6.2
- docutils==0.17.1
- execnet==1.9.0
- flake8==5.0.4
- idna==3.10
- imagesize==1.4.1
- importlib-metadata==4.2.0
- iniconfig==1.1.1
- jinja2==3.0.3
- markupsafe==2.0.1
- mccabe==0.7.0
- mock==5.2.0
- packaging==21.3
- pex==2.33.7
- pluggy==1.0.0
- py==1.11.0
- pycodestyle==2.9.1
- pyflakes==2.5.0
- pygments==2.14.0
- pyparsing==3.1.4
- pytest==7.0.1
- pytest-cov==4.0.0
- pytest-mock==3.6.1
- pytest-xdist==3.0.2
- pytz==2025.2
- requests==2.27.1
- requests-futures==1.0.2
- requests-mock==1.12.1
- setuptools==20.10.1
- snowballstemmer==2.2.0
- sphinx==4.3.2
- sphinxcontrib-applehelp==1.0.2
- sphinxcontrib-devhelp==1.0.2
- sphinxcontrib-htmlhelp==2.0.0
- sphinxcontrib-jsmath==1.0.1
- sphinxcontrib-qthelp==1.0.3
- sphinxcontrib-serializinghtml==1.1.5
- tomli==1.2.3
- typing-extensions==4.1.1
- urllib3==1.26.20
- zipp==3.6.0
prefix: /opt/conda/envs/planet-client-python
| [
"tests/test_v1_cli.py::test_filter"
]
| [
"tests/test_v1_cli.py::test_filter_options_invalid"
]
| [
"tests/test_v1_cli.py::test_quick_search",
"tests/test_v1_cli.py::test_download_errors",
"tests/test_v1_cli.py::test_download_dry_run",
"tests/test_v1_cli.py::test_download_quick",
"tests/test_v1_cli.py::test_download_search_id",
"tests/test_v1_cli.py::test_create_search",
"tests/test_v1_cli.py::test_geom_filter"
]
| []
| Apache License 2.0 | 1,863 | [
"planet/scripts/util.py"
]
| [
"planet/scripts/util.py"
]
|
pynamodb__PynamoDB-410 | 1828bda52376a4b0313146b64ffb447e5392f467 | 2017-11-10 00:25:08 | 1828bda52376a4b0313146b64ffb447e5392f467 | diff --git a/pynamodb/connection/base.py b/pynamodb/connection/base.py
index ac92ae0..bf425ef 100644
--- a/pynamodb/connection/base.py
+++ b/pynamodb/connection/base.py
@@ -95,6 +95,22 @@ class MetaTable(object):
break
return self._hash_keyname
+ def get_key_names(self, index_name=None):
+ """
+ Returns the names of the primary key attributes and index key attributes (if index_name is specified)
+ """
+ key_names = [self.hash_keyname]
+ if self.range_keyname:
+ key_names.append(self.range_keyname)
+ if index_name is not None:
+ index_hash_keyname = self.get_index_hash_keyname(index_name)
+ if index_hash_keyname not in key_names:
+ key_names.append(index_hash_keyname)
+ index_range_keyname = self.get_index_range_keyname(index_name)
+ if index_range_keyname is not None and index_range_keyname not in key_names:
+ key_names.append(index_range_keyname)
+ return key_names
+
def get_index_hash_keyname(self, index_name):
"""
Returns the name of the hash key for a given index
diff --git a/pynamodb/connection/table.py b/pynamodb/connection/table.py
index 1e7a439..35f46bd 100644
--- a/pynamodb/connection/table.py
+++ b/pynamodb/connection/table.py
@@ -28,6 +28,12 @@ class TableConnection(object):
max_retry_attempts=max_retry_attempts,
base_backoff_ms=base_backoff_ms)
+ def get_meta_table(self, refresh=False):
+ """
+ Returns a MetaTable
+ """
+ return self.connection.get_meta_table(self.table_name, refresh=refresh)
+
def delete_item(self, hash_key,
range_key=None,
condition=None,
diff --git a/pynamodb/pagination.py b/pynamodb/pagination.py
index 8f008e2..6f948b6 100644
--- a/pynamodb/pagination.py
+++ b/pynamodb/pagination.py
@@ -35,6 +35,16 @@ class PageIterator(object):
def next(self):
return self.__next__()
+ @property
+ def key_names(self):
+ # If the current page has a last_evaluated_key, use it to determine key attributes
+ if self._last_evaluated_key:
+ return self._last_evaluated_key.keys()
+
+ # Use the table meta data to determine the key attributes
+ table_meta = self._operation.im_self.get_meta_table()
+ return table_meta.get_key_names(self._kwargs.get('index_name'))
+
@property
def page_size(self):
return self._kwargs.get('limit')
@@ -100,7 +110,20 @@ class ResultIterator(object):
@property
def last_evaluated_key(self):
- return self.page_iter.last_evaluated_key
+ if self._first_iteration:
+ # Not started iterating yet: there cannot be a last_evaluated_key
+ return None
+
+ if self._index == self._count:
+ # Entire page has been consumed: last_evaluated_key is whatever DynamoDB returned
+ # It may correspond to the current item, or it may correspond to an item evaluated but not returned.
+ return self.page_iter.last_evaluated_key
+
+ # In the middle of a page of results: reconstruct a last_evaluated_key from the current item
+ # The operation should be resumed starting at the last item returned, not the last item evaluated.
+ # This can occur if the 'limit' is reached in the middle of a page.
+ item = self._items[self._index - 1]
+ return dict((key, item[key]) for key in self.page_iter.key_names)
@property
def total_count(self):
| Last Evaluated Key and Limited Queries/Scans
The `last_evaluated_key` value returns whatever was last evaluated for the current result page. When limiting the query but not setting the page size to the limit, the value does not represent the last item returned by the iterator. | pynamodb/PynamoDB | diff --git a/pynamodb/tests/test_base_connection.py b/pynamodb/tests/test_base_connection.py
index 4095d6c..b9b33fa 100644
--- a/pynamodb/tests/test_base_connection.py
+++ b/pynamodb/tests/test_base_connection.py
@@ -6,10 +6,12 @@ import json
import six
from pynamodb.compat import CompatTestCase as TestCase
from pynamodb.connection import Connection
+from pynamodb.connection.base import MetaTable
from botocore.vendored import requests
from pynamodb.exceptions import (VerboseClientError,
TableError, DeleteError, UpdateError, PutError, GetError, ScanError, QueryError, TableDoesNotExist)
-from pynamodb.constants import DEFAULT_REGION, UNPROCESSED_ITEMS, STRING_SHORT, BINARY_SHORT, DEFAULT_ENCODING
+from pynamodb.constants import (
+ DEFAULT_REGION, UNPROCESSED_ITEMS, STRING_SHORT, BINARY_SHORT, DEFAULT_ENCODING, TABLE_KEY)
from pynamodb.expressions.operand import Path
from pynamodb.tests.data import DESCRIBE_TABLE_DATA, GET_ITEM_DATA, LIST_TABLE_DATA
from pynamodb.tests.deep_eq import deep_eq
@@ -25,6 +27,23 @@ else:
PATCH_METHOD = 'pynamodb.connection.Connection._make_api_call'
+class MetaTableTestCase(TestCase):
+ """
+ Tests for the meta table class
+ """
+
+ def setUp(self):
+ self.meta_table = MetaTable(DESCRIBE_TABLE_DATA.get(TABLE_KEY))
+
+ def test_get_key_names(self):
+ key_names = self.meta_table.get_key_names()
+ self.assertEqual(key_names, ["ForumName", "Subject"])
+
+ def test_get_key_names_index(self):
+ key_names = self.meta_table.get_key_names("LastPostIndex")
+ self.assertEqual(key_names, ["ForumName", "Subject", "LastPostDateTime"])
+
+
class ConnectionTestCase(TestCase):
"""
Tests for the base connection class
diff --git a/pynamodb/tests/test_model.py b/pynamodb/tests/test_model.py
index f0ac212..ab93c07 100644
--- a/pynamodb/tests/test_model.py
+++ b/pynamodb/tests/test_model.py
@@ -2125,9 +2125,9 @@ class ModelTestCase(TestCase):
items.append(item)
req.side_effect = [
- {'Count': 10, 'ScannedCount': 20, 'Items': items[:10], 'LastEvaluatedKey': 'x'},
- {'Count': 10, 'ScannedCount': 20, 'Items': items[10:20], 'LastEvaluatedKey': 'y'},
- {'Count': 10, 'ScannedCount': 20, 'Items': items[20:30], 'LastEvaluatedKey': 'z'},
+ {'Count': 10, 'ScannedCount': 20, 'Items': items[:10], 'LastEvaluatedKey': {'user_id': 'x'}},
+ {'Count': 10, 'ScannedCount': 20, 'Items': items[10:20], 'LastEvaluatedKey': {'user_id': 'y'}},
+ {'Count': 10, 'ScannedCount': 20, 'Items': items[20:30], 'LastEvaluatedKey': {'user_id': 'z'}},
]
results_iter = UserModel.query('foo', limit=25)
results = list(results_iter)
@@ -2136,7 +2136,7 @@ class ModelTestCase(TestCase):
self.assertEquals(req.mock_calls[0][1][1]['Limit'], 25)
self.assertEquals(req.mock_calls[1][1][1]['Limit'], 25)
self.assertEquals(req.mock_calls[2][1][1]['Limit'], 25)
- self.assertEquals(results_iter.last_evaluated_key, 'z')
+ self.assertEquals(results_iter.last_evaluated_key, {'user_id': items[24]['user_id']})
self.assertEquals(results_iter.total_count, 30)
self.assertEquals(results_iter.page_iter.total_scanned_count, 60)
@@ -2153,9 +2153,9 @@ class ModelTestCase(TestCase):
items.append(item)
req.side_effect = [
- {'Count': 10, 'ScannedCount': 20, 'Items': items[:10], 'LastEvaluatedKey': 'x'},
- {'Count': 10, 'ScannedCount': 20, 'Items': items[10:20], 'LastEvaluatedKey': 'y'},
- {'Count': 10, 'ScannedCount': 20, 'Items': items[20:30], 'LastEvaluatedKey': 'z'},
+ {'Count': 10, 'ScannedCount': 20, 'Items': items[:10], 'LastEvaluatedKey': {'user_id': 'x'}},
+ {'Count': 10, 'ScannedCount': 20, 'Items': items[10:20], 'LastEvaluatedKey': {'user_id': 'y'}},
+ {'Count': 10, 'ScannedCount': 20, 'Items': items[20:30], 'LastEvaluatedKey': {'user_id': 'x'}},
]
results_iter = UserModel.query('foo', limit=25, page_size=10)
results = list(results_iter)
@@ -2164,7 +2164,7 @@ class ModelTestCase(TestCase):
self.assertEquals(req.mock_calls[0][1][1]['Limit'], 10)
self.assertEquals(req.mock_calls[1][1][1]['Limit'], 10)
self.assertEquals(req.mock_calls[2][1][1]['Limit'], 10)
- self.assertEquals(results_iter.last_evaluated_key, 'z')
+ self.assertEquals(results_iter.last_evaluated_key, {'user_id': items[24]['user_id']})
self.assertEquals(results_iter.total_count, 30)
self.assertEquals(results_iter.page_iter.total_scanned_count, 60)
@@ -2181,8 +2181,8 @@ class ModelTestCase(TestCase):
items.append(item)
req.side_effect = [
- {'Count': 10, 'ScannedCount': 20, 'Items': items[:10], 'LastEvaluatedKey': 'x'},
- {'Count': 10, 'ScannedCount': 20, 'Items': items[10:20], 'LastEvaluatedKey': 'y'},
+ {'Count': 10, 'ScannedCount': 20, 'Items': items[:10], 'LastEvaluatedKey': {'user_id': 'x'}},
+ {'Count': 10, 'ScannedCount': 20, 'Items': items[10:20], 'LastEvaluatedKey': {'user_id': 'y'}},
{'Count': 10, 'ScannedCount': 20, 'Items': items[20:30]},
]
results_iter = UserModel.query('foo', limit=50)
@@ -2209,8 +2209,8 @@ class ModelTestCase(TestCase):
items.append(item)
req.side_effect = [
- {'Count': 10, 'ScannedCount': 20, 'Items': items[:10], 'LastEvaluatedKey': 'x'},
- {'Count': 10, 'ScannedCount': 20, 'Items': items[10:20], 'LastEvaluatedKey': 'y'},
+ {'Count': 10, 'ScannedCount': 20, 'Items': items[:10], 'LastEvaluatedKey': {'user_id': 'x'}},
+ {'Count': 10, 'ScannedCount': 20, 'Items': items[10:20], 'LastEvaluatedKey': {'user_id': 'y'}},
{'Count': 10, 'ScannedCount': 20, 'Items': items[20:30]},
]
results_iter = UserModel.query('foo', limit=50, page_size=10)
@@ -2545,9 +2545,9 @@ class ModelTestCase(TestCase):
items.append(item)
req.side_effect = [
- {'Count': 10, 'ScannedCount': 20, 'Items': items[:10], 'LastEvaluatedKey': 'x'},
- {'Count': 10, 'ScannedCount': 20, 'Items': items[10:20], 'LastEvaluatedKey': 'y'},
- {'Count': 10, 'ScannedCount': 20, 'Items': items[20:30], 'LastEvaluatedKey': 'z'},
+ {'Count': 10, 'ScannedCount': 20, 'Items': items[:10], 'LastEvaluatedKey': {'user_id': 'x'}},
+ {'Count': 10, 'ScannedCount': 20, 'Items': items[10:20], 'LastEvaluatedKey': {'user_id': 'y'}},
+ {'Count': 10, 'ScannedCount': 20, 'Items': items[20:30], 'LastEvaluatedKey': {'user_id': 'z'}},
]
results_iter = UserModel.scan(limit=25, page_size=10)
results = list(results_iter)
@@ -2556,7 +2556,7 @@ class ModelTestCase(TestCase):
self.assertEquals(req.mock_calls[0][1][1]['Limit'], 10)
self.assertEquals(req.mock_calls[1][1][1]['Limit'], 10)
self.assertEquals(req.mock_calls[2][1][1]['Limit'], 10)
- self.assertEquals(results_iter.last_evaluated_key, 'z')
+ self.assertEquals(results_iter.last_evaluated_key, {'user_id': items[24]['user_id']})
self.assertEquals(results_iter.total_count, 30)
self.assertEquals(results_iter.page_iter.total_scanned_count, 60)
| {
"commit_name": "merge_commit",
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 1,
"test_score": 2
},
"num_modified_files": 3
} | 3.2 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-cov",
"pytest-mock"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.6",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs==22.2.0
botocore==1.2.0
certifi==2021.5.30
coverage==6.2
docutils==0.18.1
importlib-metadata==4.8.3
iniconfig==1.1.1
jmespath==0.7.1
packaging==21.3
pluggy==1.0.0
py==1.11.0
-e git+https://github.com/pynamodb/PynamoDB.git@1828bda52376a4b0313146b64ffb447e5392f467#egg=pynamodb
pyparsing==3.1.4
pytest==7.0.1
pytest-cov==4.0.0
pytest-mock==3.6.1
python-dateutil==2.9.0.post0
six==1.9.0
tomli==1.2.3
typing_extensions==4.1.1
zipp==3.6.0
| name: PynamoDB
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- attrs==22.2.0
- botocore==1.2.0
- coverage==6.2
- docutils==0.18.1
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- jmespath==0.7.1
- packaging==21.3
- pluggy==1.0.0
- py==1.11.0
- pyparsing==3.1.4
- pytest==7.0.1
- pytest-cov==4.0.0
- pytest-mock==3.6.1
- python-dateutil==2.9.0.post0
- six==1.9.0
- tomli==1.2.3
- typing-extensions==4.1.1
- zipp==3.6.0
prefix: /opt/conda/envs/PynamoDB
| [
"pynamodb/tests/test_base_connection.py::MetaTableTestCase::test_get_key_names",
"pynamodb/tests/test_base_connection.py::MetaTableTestCase::test_get_key_names_index",
"pynamodb/tests/test_model.py::ModelTestCase::test_query_limit_less_than_available_and_page_size",
"pynamodb/tests/test_model.py::ModelTestCase::test_query_limit_less_than_available_items_multiple_page",
"pynamodb/tests/test_model.py::ModelTestCase::test_scan_limit_with_page_size"
]
| [
"pynamodb/tests/test_base_connection.py::ConnectionTestCase::test_create_connection"
]
| [
"pynamodb/tests/test_base_connection.py::ConnectionTestCase::test_batch_get_item",
"pynamodb/tests/test_base_connection.py::ConnectionTestCase::test_batch_write_item",
"pynamodb/tests/test_base_connection.py::ConnectionTestCase::test_create_prepared_request",
"pynamodb/tests/test_base_connection.py::ConnectionTestCase::test_create_table",
"pynamodb/tests/test_base_connection.py::ConnectionTestCase::test_delete_item",
"pynamodb/tests/test_base_connection.py::ConnectionTestCase::test_delete_table",
"pynamodb/tests/test_base_connection.py::ConnectionTestCase::test_describe_table",
"pynamodb/tests/test_base_connection.py::ConnectionTestCase::test_get_expected_map",
"pynamodb/tests/test_base_connection.py::ConnectionTestCase::test_get_item",
"pynamodb/tests/test_base_connection.py::ConnectionTestCase::test_get_query_filter_map",
"pynamodb/tests/test_base_connection.py::ConnectionTestCase::test_handle_binary_attributes_for_unprocessed_items",
"pynamodb/tests/test_base_connection.py::ConnectionTestCase::test_handle_binary_attributes_for_unprocessed_keys",
"pynamodb/tests/test_base_connection.py::ConnectionTestCase::test_list_tables",
"pynamodb/tests/test_base_connection.py::ConnectionTestCase::test_make_api_call_retries_properly",
"pynamodb/tests/test_base_connection.py::ConnectionTestCase::test_make_api_call_throws_retry_disabled",
"pynamodb/tests/test_base_connection.py::ConnectionTestCase::test_make_api_call_throws_verbose_error_after_backoff",
"pynamodb/tests/test_base_connection.py::ConnectionTestCase::test_make_api_call_throws_verbose_error_after_backoff_later_succeeds",
"pynamodb/tests/test_base_connection.py::ConnectionTestCase::test_make_api_call_throws_when_retries_exhausted",
"pynamodb/tests/test_base_connection.py::ConnectionTestCase::test_put_item",
"pynamodb/tests/test_base_connection.py::ConnectionTestCase::test_query",
"pynamodb/tests/test_base_connection.py::ConnectionTestCase::test_rate_limited_scan",
"pynamodb/tests/test_base_connection.py::ConnectionTestCase::test_rate_limited_scan_retries_max_sleep",
"pynamodb/tests/test_base_connection.py::ConnectionTestCase::test_rate_limited_scan_retries_min_sleep",
"pynamodb/tests/test_base_connection.py::ConnectionTestCase::test_rate_limited_scan_retries_on_rate_unavailable",
"pynamodb/tests/test_base_connection.py::ConnectionTestCase::test_rate_limited_scan_retries_on_rate_unavailable_within_s",
"pynamodb/tests/test_base_connection.py::ConnectionTestCase::test_rate_limited_scan_retries_timeout",
"pynamodb/tests/test_base_connection.py::ConnectionTestCase::test_ratelimited_scan_exception_on_max_threshold",
"pynamodb/tests/test_base_connection.py::ConnectionTestCase::test_ratelimited_scan_raises_non_client_error",
"pynamodb/tests/test_base_connection.py::ConnectionTestCase::test_ratelimited_scan_raises_other_client_errors",
"pynamodb/tests/test_base_connection.py::ConnectionTestCase::test_ratelimited_scan_retries_on_throttling",
"pynamodb/tests/test_base_connection.py::ConnectionTestCase::test_ratelimited_scan_with_pagination_ends",
"pynamodb/tests/test_base_connection.py::ConnectionTestCase::test_scan",
"pynamodb/tests/test_base_connection.py::ConnectionTestCase::test_subsequent_client_is_cached_when_credentials_truthy",
"pynamodb/tests/test_base_connection.py::ConnectionTestCase::test_subsequent_client_is_not_cached_when_credentials_none",
"pynamodb/tests/test_base_connection.py::ConnectionTestCase::test_update_item",
"pynamodb/tests/test_base_connection.py::ConnectionTestCase::test_update_table",
"pynamodb/tests/test_model.py::ModelTestCase::test_batch_get",
"pynamodb/tests/test_model.py::ModelTestCase::test_batch_write",
"pynamodb/tests/test_model.py::ModelTestCase::test_batch_write_with_unprocessed",
"pynamodb/tests/test_model.py::ModelTestCase::test_car_model_retrieve_from_db",
"pynamodb/tests/test_model.py::ModelTestCase::test_car_model_with_null_retrieve_from_db",
"pynamodb/tests/test_model.py::ModelTestCase::test_complex_key",
"pynamodb/tests/test_model.py::ModelTestCase::test_complex_model_is_complex",
"pynamodb/tests/test_model.py::ModelTestCase::test_complex_model_retrieve_from_db",
"pynamodb/tests/test_model.py::ModelTestCase::test_conditional_operator_map_attribute",
"pynamodb/tests/test_model.py::ModelTestCase::test_count",
"pynamodb/tests/test_model.py::ModelTestCase::test_count_no_hash_key",
"pynamodb/tests/test_model.py::ModelTestCase::test_create_model",
"pynamodb/tests/test_model.py::ModelTestCase::test_delete",
"pynamodb/tests/test_model.py::ModelTestCase::test_delete_doesnt_do_validation_on_null_attributes",
"pynamodb/tests/test_model.py::ModelTestCase::test_deserializing_map_four_layers_deep_works",
"pynamodb/tests/test_model.py::ModelTestCase::test_deserializing_new_style_bool_false_works",
"pynamodb/tests/test_model.py::ModelTestCase::test_deserializing_new_style_bool_true_works",
"pynamodb/tests/test_model.py::ModelTestCase::test_deserializing_old_style_bool_false_works",
"pynamodb/tests/test_model.py::ModelTestCase::test_deserializing_old_style_bool_true_works",
"pynamodb/tests/test_model.py::ModelTestCase::test_dumps",
"pynamodb/tests/test_model.py::ModelTestCase::test_explicit_raw_map_serialize_pass",
"pynamodb/tests/test_model.py::ModelTestCase::test_filter_count",
"pynamodb/tests/test_model.py::ModelTestCase::test_get",
"pynamodb/tests/test_model.py::ModelTestCase::test_global_index",
"pynamodb/tests/test_model.py::ModelTestCase::test_index_count",
"pynamodb/tests/test_model.py::ModelTestCase::test_index_multipage_count",
"pynamodb/tests/test_model.py::ModelTestCase::test_index_queries",
"pynamodb/tests/test_model.py::ModelTestCase::test_invalid_car_model_with_null_retrieve_from_db",
"pynamodb/tests/test_model.py::ModelTestCase::test_invalid_map_model_raises",
"pynamodb/tests/test_model.py::ModelTestCase::test_list_of_map_works_like_list_of_map",
"pynamodb/tests/test_model.py::ModelTestCase::test_list_works_like_list",
"pynamodb/tests/test_model.py::ModelTestCase::test_loads",
"pynamodb/tests/test_model.py::ModelTestCase::test_loads_complex_model",
"pynamodb/tests/test_model.py::ModelTestCase::test_local_index",
"pynamodb/tests/test_model.py::ModelTestCase::test_model_attrs",
"pynamodb/tests/test_model.py::ModelTestCase::test_model_subclass_attributes_inherited_on_create",
"pynamodb/tests/test_model.py::ModelTestCase::test_model_with_invalid_data_does_not_validate",
"pynamodb/tests/test_model.py::ModelTestCase::test_model_with_list",
"pynamodb/tests/test_model.py::ModelTestCase::test_model_with_list_of_map",
"pynamodb/tests/test_model.py::ModelTestCase::test_model_with_list_of_map_retrieve_from_db",
"pynamodb/tests/test_model.py::ModelTestCase::test_model_with_list_retrieve_from_db",
"pynamodb/tests/test_model.py::ModelTestCase::test_model_with_maps",
"pynamodb/tests/test_model.py::ModelTestCase::test_model_with_maps_retrieve_from_db",
"pynamodb/tests/test_model.py::ModelTestCase::test_model_with_maps_with_nulls_retrieve_from_db",
"pynamodb/tests/test_model.py::ModelTestCase::test_model_with_maps_with_pythonic_attributes",
"pynamodb/tests/test_model.py::ModelTestCase::test_model_with_nulls_validates",
"pynamodb/tests/test_model.py::ModelTestCase::test_model_works_like_model",
"pynamodb/tests/test_model.py::ModelTestCase::test_multiple_indices_share_non_key_attribute",
"pynamodb/tests/test_model.py::ModelTestCase::test_new_style_boolean_serializes_as_bool",
"pynamodb/tests/test_model.py::ModelTestCase::test_old_style_boolean_serializes_as_bool",
"pynamodb/tests/test_model.py::ModelTestCase::test_old_style_model_exception",
"pynamodb/tests/test_model.py::ModelTestCase::test_overidden_defaults",
"pynamodb/tests/test_model.py::ModelTestCase::test_overidden_session",
"pynamodb/tests/test_model.py::ModelTestCase::test_overridden_attr_name",
"pynamodb/tests/test_model.py::ModelTestCase::test_projections",
"pynamodb/tests/test_model.py::ModelTestCase::test_query",
"pynamodb/tests/test_model.py::ModelTestCase::test_query_limit_greater_than_available_items_and_page_size",
"pynamodb/tests/test_model.py::ModelTestCase::test_query_limit_greater_than_available_items_multiple_page",
"pynamodb/tests/test_model.py::ModelTestCase::test_query_limit_greater_than_available_items_single_page",
"pynamodb/tests/test_model.py::ModelTestCase::test_query_limit_identical_to_available_items_single_page",
"pynamodb/tests/test_model.py::ModelTestCase::test_rate_limited_scan",
"pynamodb/tests/test_model.py::ModelTestCase::test_raw_map_as_sub_map",
"pynamodb/tests/test_model.py::ModelTestCase::test_raw_map_as_sub_map_deserialize",
"pynamodb/tests/test_model.py::ModelTestCase::test_raw_map_as_sub_map_from_raw_data_works",
"pynamodb/tests/test_model.py::ModelTestCase::test_raw_map_as_sub_map_serialize_pass",
"pynamodb/tests/test_model.py::ModelTestCase::test_raw_map_deserializes",
"pynamodb/tests/test_model.py::ModelTestCase::test_raw_map_from_raw_data_works",
"pynamodb/tests/test_model.py::ModelTestCase::test_raw_map_serialize_fun_one",
"pynamodb/tests/test_model.py::ModelTestCase::test_refresh",
"pynamodb/tests/test_model.py::ModelTestCase::test_result_set_init",
"pynamodb/tests/test_model.py::ModelTestCase::test_result_set_iter",
"pynamodb/tests/test_model.py::ModelTestCase::test_save",
"pynamodb/tests/test_model.py::ModelTestCase::test_scan",
"pynamodb/tests/test_model.py::ModelTestCase::test_scan_limit",
"pynamodb/tests/test_model.py::ModelTestCase::test_update",
"pynamodb/tests/test_model.py::ModelTestCase::test_update_item",
"pynamodb/tests/test_model.py::ModelInitTestCase::test_raw_map_attribute_with_dict_init",
"pynamodb/tests/test_model.py::ModelInitTestCase::test_raw_map_attribute_with_initialized_instance_init",
"pynamodb/tests/test_model.py::ModelInitTestCase::test_subclassed_map_attribute_with_dict_init",
"pynamodb/tests/test_model.py::ModelInitTestCase::test_subclassed_map_attribute_with_initialized_instance_init",
"pynamodb/tests/test_model.py::ModelInitTestCase::test_subclassed_map_attribute_with_map_attribute_member_with_initialized_instance_init",
"pynamodb/tests/test_model.py::ModelInitTestCase::test_subclassed_map_attribute_with_map_attributes_member_with_dict_init"
]
| []
| MIT License | 1,864 | [
"pynamodb/pagination.py",
"pynamodb/connection/table.py",
"pynamodb/connection/base.py"
]
| [
"pynamodb/pagination.py",
"pynamodb/connection/table.py",
"pynamodb/connection/base.py"
]
|
|
MechanicalSoup__MechanicalSoup-166 | 8c149d6baeb012ce44b1d7ece85dccfed7cc5c71 | 2017-11-10 02:14:52 | 7171e2b79ba0fbe02a7245066cb5536ddb2fe94e | moy: Don't forget to update the changelog.
I'm wondering whether we're loosing some potential flexibility by doing this. Currently, we're not, but what if we ever want to provide a hook that the user could execute between the "prepare" and the "send" step? Will it still be possible?
hemberger: ChangeLog has been updated.
Your question is a good one. From the current version of the code, we're only gaining generality. Since request construction and sending was all done internally in `submit`, even without this PR we would need to change the API to allow users to modify the prepared request before sending. I don't think this should be any harder of a task after this PR is merged. However, it might never be unnecessary -- I think the idea behind `requests.Sessions.request` is to allow people to specify almost anything you'd need to do for both the preparing and sending in a single call.
moy: > without this PR we would need to change the API to allow users to modify the prepared request before sending
Yes, we would need to modify our API, but it's rather simple to provide a `add_hook(callback)` and to call the callback between prepare and send before the PR.
> I don't think this should be any harder of a task after this PR is merged.
The problem is that the lines of code between prepare and send are currently in our code, so we can still add whatever we want (like calling a user-provided callback) there. After the PR, the only lines of code between prepare and send are in the requests library, we can't modify them anymore.
> I think the idea behind requests.Sessions.request is to allow people to specify almost anything
Yes, but the question is whether this "almost" is sufficient for 100% use-cases. The request library provides the flexibility of allowing tweaking the prepared request before sending:
http://docs.python-requests.org/en/master/user/advanced/#prepared-requests
We don't currently need it, but it'd be nice to keep the possibility to do it in the future.
Re-reading the code, I think there's another way to expose the full flexibility of the requests library: merge your PR and then split `_request` into:
* `_extract_form_data()` that would build `kwargs` (i.e. the current `_request()`, except its last line)
* `_send_form_data()` that would call `self.session.request(..., kwargs)`
(Or perhaps these would deserve a name not starting with `_`)
and expose `_request()` that would just call these two functions. This way, the user may, if needed, call `_extract_form_data()` and do whatever tweaking is needed to actually send the HTTP request. This would slightly increase the flexibility of the code, and would also split the form-related code and the http-related code better.
I short, I think we can merge the PR, and we may want to do the split I suggest later.
hemberger: Yep, that split sounds completely natural to me. The problem with the previous split was that it combined `prepare` and `send`, but had no way of conveniently passing any parameters to `send`. | diff --git a/docs/ChangeLog.rst b/docs/ChangeLog.rst
index 9b61e30..472b8e1 100644
--- a/docs/ChangeLog.rst
+++ b/docs/ChangeLog.rst
@@ -5,6 +5,19 @@ Release Notes
Version 1.0 (in development)
============================
+Main changes:
+-------------
+* ``Browser.submit`` and ``StatefulBrowser.submit_selected`` accept a larger
+ number of keyword arguments. Arguments are forwarded to
+ `requests.Session.request <http://docs.python-requests.org/en/master/api/#requests.Session.request>`__.
+ [`#166 <https://github.com/MechanicalSoup/MechanicalSoup/pull/166>`__]
+
+Internal changes:
+-----------------
+* Private methods ``Browser._build_request`` and ``Browser._prepare_request``
+ have been replaced by a single method ``Browser._request``.
+ [`#166 <https://github.com/MechanicalSoup/MechanicalSoup/pull/166>`__]
+
Version 0.9
===========
diff --git a/mechanicalsoup/browser.py b/mechanicalsoup/browser.py
index 9c5e2f4..02513f9 100644
--- a/mechanicalsoup/browser.py
+++ b/mechanicalsoup/browser.py
@@ -121,7 +121,7 @@ class Browser(object):
Browser.add_soup(response, self.soup_config)
return response
- def _build_request(self, form, url=None, **kwargs):
+ def _request(self, form, url=None, **kwargs):
method = str(form.get("method", "get"))
action = form.get("action")
url = urllib.parse.urljoin(url, action)
@@ -185,11 +185,7 @@ class Browser(object):
else:
kwargs["data"] = data
- return requests.Request(method, url, files=files, **kwargs)
-
- def _prepare_request(self, form, url=None, **kwargs):
- request = self._build_request(form, url, **kwargs)
- return self.session.prepare_request(request)
+ return self.session.request(method, url, files=files, **kwargs)
def submit(self, form, url=None, **kwargs):
"""Prepares and sends a form request.
@@ -197,8 +193,8 @@ class Browser(object):
:param form: The filled-out form.
:param url: URL of the page the form is on. If the form action is a
relative path, then this must be specified.
- :param \*\*kwargs: Arguments forwarded to `requests.Request
- <http://docs.python-requests.org/en/master/api/#requests.Request>`__.
+ :param \*\*kwargs: Arguments forwarded to `requests.Session.request
+ <http://docs.python-requests.org/en/master/api/#requests.Session.request>`__.
:return: `requests.Response
<http://docs.python-requests.org/en/master/api/#requests.Response>`__
@@ -206,8 +202,7 @@ class Browser(object):
"""
if isinstance(form, Form):
form = form.form
- request = self._prepare_request(form, url, **kwargs)
- response = self.session.send(request)
+ response = self._request(form, url, **kwargs)
Browser.add_soup(response, self.soup_config)
return response
| Unexpected keyword argument 'proxies'
The use of requests.Request base class does not include a proxies keyword like the requests.request class.
```python
import requests
import mechanicalsoup
self.Session = requests.Session()
self.browser = mechanicalsoup.StatefulBrowser(session=self.Session)
self.browser.get(searchURL.url, proxies=self.proxy)
```
Full error log is:
```
response = self.browser.submit_selected(proxies=self.proxy)
File "C:\Users\Kevin\Desktop\Project\dev\lib\site-packages\mechanicalsoup\stateful_browser.py", line 194, in submit_selected
*args, **kwargs)
File "C:\Users\Kevin\Desktop\Project\dev\lib\site-packages\mechanicalsoup\browser.py", line 209, in submit
request = self._prepare_request(form, url, **kwargs)
File "C:\Users\Kevin\Desktop\Project\dev\lib\site-packages\mechanicalsoup\browser.py", line 191, in _prepare_request
request = self._build_request(form, url, **kwargs)
File "C:\Users\Kevin\Desktop\Project\dev\lib\site-packages\mechanicalsoup\browser.py", line 188, in _build_request
return requests.Request(method, url, files=files, **kwargs)
TypeError: __init__() got an unexpected keyword argument 'proxies'
``` | MechanicalSoup/MechanicalSoup | diff --git a/tests/test_browser.py b/tests/test_browser.py
index 2bb9192..1ff9871 100644
--- a/tests/test_browser.py
+++ b/tests/test_browser.py
@@ -64,26 +64,26 @@ form_html = """
"""
-def test_build_request():
+def test__request():
form = BeautifulSoup(form_html, "lxml").form
browser = mechanicalsoup.Browser()
- request = browser._build_request(form)
+ response = browser._request(form)
- assert request.data["customer"] == "Philip J. Fry"
- assert request.data["telephone"] == "555"
- assert request.data["comments"] == "freezer"
- assert request.data["size"] == "medium"
- assert request.data["topping"] == ["cheese", "onion"]
- assert request.data["shape"] == "square"
+ data = response.json()['form']
+ assert data["customer"] == "Philip J. Fry"
+ assert data["telephone"] == "555"
+ assert data["comments"] == "freezer"
+ assert data["size"] == "medium"
+ assert data["topping"] == ["cheese", "onion"]
+ assert data["shape"] == "square"
- request = browser._prepare_request(form)
- assert "application/x-www-form-urlencoded" in request.headers[
+ assert "application/x-www-form-urlencoded" in response.request.headers[
"Content-Type"]
browser.close()
-def test_prepare_request_file():
+def test__request_file():
form = BeautifulSoup(form_html, "lxml").form
# create a temporary file for testing file upload
@@ -94,15 +94,16 @@ def test_prepare_request_file():
form.find("input", {"name": "pic"})["value"] = pic_path
browser = mechanicalsoup.Browser()
- request = browser._build_request(form)
+ response = browser._request(form)
- assert request.files
- assert request.files["pic"]
- assert request.files["pic"].read() == ":-)".encode("utf8")
- assert "pic" not in request.data
+ # Check that only "files" includes a "pic" keyword in the response
+ for key, value in response.json().items():
+ if key == "files":
+ assert value["pic"] == ":-)"
+ else:
+ assert (value is None) or ("pic" not in value)
- request = browser._prepare_request(form)
- assert "multipart/form-data" in request.headers["Content-Type"]
+ assert "multipart/form-data" in response.request.headers["Content-Type"]
browser.close()
| {
"commit_name": "merge_commit",
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 0,
"test_score": 3
},
"num_modified_files": 2
} | 0.9 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-cov",
"pytest-flake8",
"pytest-mock",
"requests_mock"
],
"pre_install": null,
"python": "3.6",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs==22.2.0
beautifulsoup4==4.12.3
certifi==2021.5.30
charset-normalizer==2.0.12
coverage==6.2
flake8==5.0.4
idna==3.10
importlib-metadata==4.2.0
iniconfig==1.1.1
lxml==5.3.1
mccabe==0.7.0
-e git+https://github.com/MechanicalSoup/MechanicalSoup.git@8c149d6baeb012ce44b1d7ece85dccfed7cc5c71#egg=MechanicalSoup
packaging==21.3
pluggy==1.0.0
py==1.11.0
pycodestyle==2.9.1
pyflakes==2.5.0
pyparsing==3.1.4
pytest==7.0.1
pytest-cov==4.0.0
pytest-flake8==1.1.1
pytest-mock==3.6.1
requests==2.27.1
requests-mock==1.12.1
six==1.17.0
soupsieve==2.3.2.post1
tomli==1.2.3
typing_extensions==4.1.1
urllib3==1.26.20
zipp==3.6.0
| name: MechanicalSoup
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- attrs==22.2.0
- beautifulsoup4==4.12.3
- charset-normalizer==2.0.12
- coverage==6.2
- flake8==5.0.4
- idna==3.10
- importlib-metadata==4.2.0
- iniconfig==1.1.1
- lxml==5.3.1
- mccabe==0.7.0
- packaging==21.3
- pluggy==1.0.0
- py==1.11.0
- pycodestyle==2.9.1
- pyflakes==2.5.0
- pyparsing==3.1.4
- pytest==7.0.1
- pytest-cov==4.0.0
- pytest-flake8==1.1.1
- pytest-mock==3.6.1
- requests==2.27.1
- requests-mock==1.12.1
- six==1.17.0
- soupsieve==2.3.2.post1
- tomli==1.2.3
- typing-extensions==4.1.1
- urllib3==1.26.20
- zipp==3.6.0
prefix: /opt/conda/envs/MechanicalSoup
| [
"tests/test_browser.py::test__request",
"tests/test_browser.py::test__request_file"
]
| [
"tests/test_browser.py::flake-8::FLAKE8"
]
| [
"tests/test_browser.py::test_submit_online",
"tests/test_browser.py::test_no_404",
"tests/test_browser.py::test_set_cookiejar",
"tests/test_browser.py::test_get_cookiejar",
"tests/test_browser.py::test_post"
]
| [
"tests/test_browser.py::test_404"
]
| MIT License | 1,866 | [
"mechanicalsoup/browser.py",
"docs/ChangeLog.rst"
]
| [
"mechanicalsoup/browser.py",
"docs/ChangeLog.rst"
]
|
great-expectations__great_expectations-122 | c5ba7058a8afc99b7b9ce523d3cb183961a321a3 | 2017-11-10 04:47:45 | c5ba7058a8afc99b7b9ce523d3cb183961a321a3 | diff --git a/.gitignore b/.gitignore
index 8cc0d85e1..7b686a190 100644
--- a/.gitignore
+++ b/.gitignore
@@ -103,3 +103,5 @@ ENV/
# vim backup files
*~
+
+.DS_Store
\ No newline at end of file
diff --git a/examples/notebooks/Distributional_Expectations_Demo.ipynb b/examples/notebooks/Distributional_Expectations_Demo.ipynb
index b6c61bd5d..4745ffa67 100644
--- a/examples/notebooks/Distributional_Expectations_Demo.ipynb
+++ b/examples/notebooks/Distributional_Expectations_Demo.ipynb
@@ -2,7 +2,7 @@
"cells": [
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 0,
"metadata": {
"collapsed": true
},
@@ -14,7 +14,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 0,
"metadata": {
"collapsed": true
},
@@ -29,7 +29,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 0,
"metadata": {
"collapsed": true
},
@@ -57,7 +57,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 0,
"metadata": {},
"outputs": [],
"source": [
@@ -69,7 +69,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 0,
"metadata": {},
"outputs": [],
"source": [
@@ -78,7 +78,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 0,
"metadata": {},
"outputs": [],
"source": [
@@ -87,7 +87,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 0,
"metadata": {
"collapsed": true
},
@@ -104,7 +104,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 0,
"metadata": {
"collapsed": true
},
@@ -115,7 +115,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 0,
"metadata": {
"collapsed": true
},
@@ -127,7 +127,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 0,
"metadata": {
"collapsed": true
},
@@ -138,7 +138,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 0,
"metadata": {
"collapsed": true
},
@@ -150,7 +150,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 0,
"metadata": {
"collapsed": true
},
@@ -161,7 +161,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 0,
"metadata": {
"collapsed": true
},
@@ -172,7 +172,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 0,
"metadata": {
"collapsed": true
},
@@ -184,7 +184,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 0,
"metadata": {
"collapsed": true
},
@@ -195,7 +195,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 0,
"metadata": {
"collapsed": true
},
@@ -206,7 +206,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 0,
"metadata": {
"collapsed": true
},
@@ -217,7 +217,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 0,
"metadata": {
"collapsed": true
},
@@ -229,7 +229,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 0,
"metadata": {
"collapsed": true
},
@@ -241,7 +241,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 0,
"metadata": {
"collapsed": true
},
@@ -252,7 +252,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 0,
"metadata": {
"collapsed": true
},
@@ -263,7 +263,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 0,
"metadata": {
"collapsed": true
},
@@ -275,7 +275,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 0,
"metadata": {
"collapsed": true
},
@@ -286,7 +286,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 0,
"metadata": {
"collapsed": true
},
@@ -298,7 +298,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 0,
"metadata": {
"collapsed": true
},
@@ -309,7 +309,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 0,
"metadata": {
"collapsed": true
},
@@ -321,7 +321,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 0,
"metadata": {
"collapsed": true
},
@@ -336,7 +336,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 0,
"metadata": {
"collapsed": true
},
@@ -351,7 +351,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 0,
"metadata": {
"collapsed": true
},
@@ -362,7 +362,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 0,
"metadata": {
"collapsed": true
},
@@ -374,7 +374,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 0,
"metadata": {
"collapsed": true
},
@@ -402,7 +402,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 0,
"metadata": {
"collapsed": true
},
@@ -413,7 +413,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 0,
"metadata": {
"collapsed": true
},
@@ -424,7 +424,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 0,
"metadata": {
"collapsed": true
},
@@ -435,7 +435,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 0,
"metadata": {
"collapsed": true
},
@@ -446,7 +446,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 0,
"metadata": {
"collapsed": true
},
@@ -457,7 +457,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 0,
"metadata": {
"collapsed": true
},
@@ -468,7 +468,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 0,
"metadata": {
"collapsed": true
},
@@ -479,7 +479,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 0,
"metadata": {
"collapsed": true
},
@@ -491,7 +491,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 0,
"metadata": {
"collapsed": true
},
@@ -502,7 +502,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 0,
"metadata": {
"collapsed": true
},
@@ -513,7 +513,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 0,
"metadata": {
"collapsed": true
},
@@ -524,7 +524,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 0,
"metadata": {
"collapsed": true
},
@@ -539,7 +539,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 0,
"metadata": {
"collapsed": true
},
@@ -550,7 +550,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 0,
"metadata": {
"collapsed": true
},
@@ -561,7 +561,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 0,
"metadata": {
"collapsed": true
},
@@ -573,7 +573,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 0,
"metadata": {
"collapsed": true
},
@@ -584,7 +584,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 0,
"metadata": {
"collapsed": true,
"scrolled": true
@@ -596,7 +596,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 0,
"metadata": {
"collapsed": true
},
@@ -611,7 +611,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 0,
"metadata": {
"collapsed": true
},
@@ -622,7 +622,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 0,
"metadata": {
"collapsed": true
},
@@ -638,7 +638,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 0,
"metadata": {
"collapsed": true
},
@@ -650,7 +650,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 0,
"metadata": {
"collapsed": true
},
@@ -681,4 +681,4 @@
},
"nbformat": 4,
"nbformat_minor": 2
-}
+}
\ No newline at end of file
diff --git a/examples/notebooks/Distributional_Expectations_Demo_Prep.ipynb b/examples/notebooks/Distributional_Expectations_Demo_Prep.ipynb
index b00d6ef62..4e62e3846 100644
--- a/examples/notebooks/Distributional_Expectations_Demo_Prep.ipynb
+++ b/examples/notebooks/Distributional_Expectations_Demo_Prep.ipynb
@@ -2,7 +2,7 @@
"cells": [
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 0,
"metadata": {
"collapsed": true
},
@@ -14,7 +14,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 0,
"metadata": {},
"outputs": [],
"source": [
@@ -43,7 +43,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 0,
"metadata": {
"collapsed": true
},
@@ -60,7 +60,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 0,
"metadata": {
"collapsed": true
},
@@ -80,7 +80,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 0,
"metadata": {},
"outputs": [],
"source": [
@@ -96,7 +96,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 0,
"metadata": {},
"outputs": [],
"source": [
@@ -130,4 +130,4 @@
},
"nbformat": 4,
"nbformat_minor": 2
-}
+}
\ No newline at end of file
diff --git a/great_expectations/dataset/base.py b/great_expectations/dataset/base.py
index 72e23313b..14acf8ecf 100644
--- a/great_expectations/dataset/base.py
+++ b/great_expectations/dataset/base.py
@@ -327,7 +327,7 @@ class DataSet(object):
return return_obj
- def calc_map_expectation_success(self, success_count, nonnull_count, exception_count, mostly):
+ def calc_map_expectation_success(self, success_count, nonnull_count, mostly):
if nonnull_count > 0:
percent_success = float(success_count)/nonnull_count
@@ -335,7 +335,7 @@ class DataSet(object):
success = bool(percent_success >= mostly)
else:
- success = bool(exception_count == 0)
+ success = bool(nonnull_count-success_count == 0)
else:
success = True
diff --git a/great_expectations/dataset/pandas_dataset.py b/great_expectations/dataset/pandas_dataset.py
index 3e3f68fa4..dd8fba971 100644
--- a/great_expectations/dataset/pandas_dataset.py
+++ b/great_expectations/dataset/pandas_dataset.py
@@ -54,7 +54,7 @@ class MetaPandasDataSet(DataSet):
exception_index_list = list(series[(boolean_mapped_success_values==False)&(boolean_mapped_null_values==False)].index)
exception_count = len(exception_list)
- success, percent_success = self.calc_map_expectation_success(success_count, nonnull_count, exception_count, mostly)
+ success, percent_success = self.calc_map_expectation_success(success_count, nonnull_count, mostly)
return_obj = self.format_column_map_output(
output_format, success,
@@ -93,9 +93,10 @@ class MetaPandasDataSet(DataSet):
series = self[column]
null_indexes = series.isnull()
+ element_count = int(len(series))
nonnull_values = series[null_indexes == False]
nonnull_count = (null_indexes == False).sum()
- null_count = nonnull_count - len(series)
+ null_count = element_count - nonnull_count
result_obj = func(self, nonnull_values, *args, **kwargs)
@@ -112,18 +113,17 @@ class MetaPandasDataSet(DataSet):
}
elif (output_format == "SUMMARY"):
+ new_summary_obj = {
+ "element_count": element_count,
+ "missing_count": null_count,
+ "missing_percent": null_count*1.0 / element_count if element_count > 0 else None
+ }
+
if "summary_obj" in result_obj and result_obj["summary_obj"] is not None:
- result_obj["summary_obj"].update({
- "element_count": nonnull_count,
- "missing_count": null_count,
- "missing_percent": nonnull_count / null_count if null_count > 0 else 0
- })
+ result_obj["summary_obj"].update(new_summary_obj)
else:
- result_obj["summary_obj"] = {
- "element_count": nonnull_count,
- "missing_count": null_count,
- "missing_percent": nonnull_count / null_count if null_count > 0 else 0
- }
+ result_obj["summary_obj"] = new_summary_obj
+
return_obj = {
"success" : bool(result_obj["success"]),
"true_value" : result_obj["true_value"],
@@ -238,7 +238,7 @@ class PandasDataSet(MetaPandasDataSet, pd.DataFrame):
exception_count = len(exception_list)
# Pass element_count instead of nonnull_count, because that's the right denominator for this expectation
- success, percent_success = self.calc_map_expectation_success(success_count, element_count, exception_count, mostly)
+ success, percent_success = self.calc_map_expectation_success(success_count, element_count, mostly)
return_obj = self.format_column_map_output(
output_format, success,
@@ -271,7 +271,7 @@ class PandasDataSet(MetaPandasDataSet, pd.DataFrame):
exception_count = len(exception_list)
# Pass element_count instead of nonnull_count, because that's the right denominator for this expectation
- success, percent_success = self.calc_map_expectation_success(success_count, element_count, exception_count, mostly)
+ success, percent_success = self.calc_map_expectation_success(success_count, element_count, mostly)
return_obj = self.format_column_map_output(
output_format, success,
| Add unit tests for `format_column_map_output` and `calc_map_expectation_success` | great-expectations/great_expectations | diff --git a/tests/test_dataset.py b/tests/test_dataset.py
index c71006652..50e96e1ef 100644
--- a/tests/test_dataset.py
+++ b/tests/test_dataset.py
@@ -1,3 +1,4 @@
+import pandas as pd
import great_expectations as ge
import unittest
@@ -80,5 +81,153 @@ class TestDataset(unittest.TestCase):
}
)
+ def test_format_column_map_output(self):
+ df = ge.dataset.PandasDataSet({
+ "x" : list("abcdefghijklmnopqrstuvwxyz")
+ })
+
+ success = True
+ element_count = 20
+ nonnull_values = pd.Series(range(15))
+ nonnull_count = 15
+ boolean_mapped_success_values = pd.Series([True for i in range(15)])
+ success_count = 15
+ exception_list = []
+ exception_index_list = []
+
+ self.assertEqual(
+ df.format_column_map_output(
+ "BOOLEAN_ONLY",
+ success,
+ element_count,
+ nonnull_values, nonnull_count,
+ boolean_mapped_success_values, success_count,
+ exception_list, exception_index_list
+ ),
+ True
+ )
+
+ self.assertEqual(
+ df.format_column_map_output(
+ "BASIC",
+ success,
+ element_count,
+ nonnull_values, nonnull_count,
+ boolean_mapped_success_values, success_count,
+ exception_list, exception_index_list
+ ),
+ {
+ 'success': True,
+ 'summary_obj': {
+ 'exception_percent': 0.0,
+ 'partial_exception_list': [],
+ 'exception_percent_nonmissing': 0.0,
+ 'exception_count': 0
+ }
+ }
+ )
+
+ self.assertEqual(
+ df.format_column_map_output(
+ "COMPLETE",
+ success,
+ element_count,
+ nonnull_values, nonnull_count,
+ boolean_mapped_success_values, success_count,
+ exception_list, exception_index_list
+ ),
+ {
+ 'success': True,
+ 'exception_list': [],
+ 'exception_index_list': [],
+ }
+ )
+
+ self.assertEqual(
+ df.format_column_map_output(
+ "SUMMARY",
+ success,
+ element_count,
+ nonnull_values, nonnull_count,
+ boolean_mapped_success_values, success_count,
+ exception_list, exception_index_list
+ ),
+ {
+ 'success': True,
+ 'summary_obj': {
+ 'element_count': 20,
+ 'exception_count': 0,
+ 'exception_percent': 0.0,
+ 'exception_percent_nonmissing': 0.0,
+ 'missing_count': 5,
+ 'missing_percent': 0.25,
+ 'partial_exception_counts': {},
+ 'partial_exception_index_list': [],
+ 'partial_exception_list': []
+ }
+ }
+ )
+
+
+
+ def test_calc_map_expectation_success(self):
+ df = ge.dataset.PandasDataSet({
+ "x" : list("abcdefghijklmnopqrstuvwxyz")
+ })
+ self.assertEqual(
+ df.calc_map_expectation_success(
+ success_count=10,
+ nonnull_count=10,
+ mostly=None
+ ),
+ (True, 1.0)
+ )
+
+ self.assertEqual(
+ df.calc_map_expectation_success(
+ success_count=90,
+ nonnull_count=100,
+ mostly=.9
+ ),
+ (True, .9)
+ )
+
+ self.assertEqual(
+ df.calc_map_expectation_success(
+ success_count=90,
+ nonnull_count=100,
+ mostly=.8
+ ),
+ (True, .9)
+ )
+
+ self.assertEqual(
+ df.calc_map_expectation_success(
+ success_count=80,
+ nonnull_count=100,
+ mostly=.9
+ ),
+ (False, .8)
+ )
+
+ self.assertEqual(
+ df.calc_map_expectation_success(
+ success_count=0,
+ nonnull_count=0,
+ mostly=None
+ ),
+ (True, None)
+ )
+
+ self.assertEqual(
+ df.calc_map_expectation_success(
+ success_count=0,
+ nonnull_count=100,
+ mostly=None
+ ),
+ (False, 0.0)
+ )
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/tests/test_pandas_dataset.py b/tests/test_pandas_dataset.py
index 7490d5102..2f92e50e2 100644
--- a/tests/test_pandas_dataset.py
+++ b/tests/test_pandas_dataset.py
@@ -1206,6 +1206,19 @@ class TestPandasDataset(unittest.TestCase):
}
)
+ self.assertEqual(
+ df.expect_column_mean_to_be_between("x", 3, 7, output_format="SUMMARY"),
+ {
+ 'success': True,
+ 'true_value': 4.375,
+ 'summary_obj': {
+ 'element_count': 10,
+ 'missing_count': 2,
+ 'missing_percent': .2
+ },
+ }
+ )
+
def test_positional_arguments(self):
df = ge.dataset.PandasDataSet({
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 1,
"test_score": 0
},
"num_modified_files": 5
} | 0.2 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest"
],
"pre_install": null,
"python": "3.6",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | argh==0.27.2
attrs==22.2.0
certifi==2021.5.30
-e git+https://github.com/great-expectations/great_expectations.git@c5ba7058a8afc99b7b9ce523d3cb183961a321a3#egg=great_expectations
importlib-metadata==4.8.3
iniconfig==1.1.1
jsonschema==3.2.0
numpy==1.19.5
packaging==21.3
pandas==1.1.5
pluggy==1.0.0
py==1.11.0
pyparsing==3.1.4
pyrsistent==0.18.0
pytest==7.0.1
python-dateutil==2.9.0.post0
pytz==2025.2
scipy==1.5.4
six==1.17.0
tomli==1.2.3
typing_extensions==4.1.1
zipp==3.6.0
| name: great_expectations
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- argh==0.27.2
- attrs==22.2.0
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- jsonschema==3.2.0
- numpy==1.19.5
- packaging==21.3
- pandas==1.1.5
- pluggy==1.0.0
- py==1.11.0
- pyparsing==3.1.4
- pyrsistent==0.18.0
- pytest==7.0.1
- python-dateutil==2.9.0.post0
- pytz==2025.2
- scipy==1.5.4
- six==1.17.0
- tomli==1.2.3
- typing-extensions==4.1.1
- zipp==3.6.0
prefix: /opt/conda/envs/great_expectations
| [
"tests/test_dataset.py::TestDataset::test_calc_map_expectation_success",
"tests/test_pandas_dataset.py::TestPandasDataset::test_expectation_decorator_summary_mode"
]
| [
"tests/test_pandas_dataset.py::TestPandasDataset::test_expect_column_mean_to_be_between"
]
| [
"tests/test_dataset.py::TestDataset::test_dataset",
"tests/test_dataset.py::TestDataset::test_format_column_map_output",
"tests/test_dataset.py::TestDataset::test_set_default_expectation_argument",
"tests/test_pandas_dataset.py::TestPandasDataset::test_expect_column_most_common_value_to_be",
"tests/test_pandas_dataset.py::TestPandasDataset::test_expect_column_most_common_value_to_be_in_set",
"tests/test_pandas_dataset.py::TestPandasDataset::test_expect_column_proportion_of_unique_values_to_be_between",
"tests/test_pandas_dataset.py::TestPandasDataset::test_expect_column_stdev_to_be_between",
"tests/test_pandas_dataset.py::TestPandasDataset::test_expect_column_unique_value_count_to_be_between",
"tests/test_pandas_dataset.py::TestPandasDataset::test_expect_column_value_lengths_to_be_between",
"tests/test_pandas_dataset.py::TestPandasDataset::test_expect_column_values_to_be_between",
"tests/test_pandas_dataset.py::TestPandasDataset::test_expect_column_values_to_be_dateutil_parseable",
"tests/test_pandas_dataset.py::TestPandasDataset::test_expect_column_values_to_be_in_set",
"tests/test_pandas_dataset.py::TestPandasDataset::test_expect_column_values_to_be_in_type_list",
"tests/test_pandas_dataset.py::TestPandasDataset::test_expect_column_values_to_be_json_parseable",
"tests/test_pandas_dataset.py::TestPandasDataset::test_expect_column_values_to_be_null",
"tests/test_pandas_dataset.py::TestPandasDataset::test_expect_column_values_to_be_of_type",
"tests/test_pandas_dataset.py::TestPandasDataset::test_expect_column_values_to_be_unique",
"tests/test_pandas_dataset.py::TestPandasDataset::test_expect_column_values_to_match_json_schema",
"tests/test_pandas_dataset.py::TestPandasDataset::test_expect_column_values_to_match_regex",
"tests/test_pandas_dataset.py::TestPandasDataset::test_expect_column_values_to_match_regex_list",
"tests/test_pandas_dataset.py::TestPandasDataset::test_expect_column_values_to_match_strftime_format",
"tests/test_pandas_dataset.py::TestPandasDataset::test_expect_column_values_to_not_be_in_set",
"tests/test_pandas_dataset.py::TestPandasDataset::test_expect_column_values_to_not_be_null",
"tests/test_pandas_dataset.py::TestPandasDataset::test_expect_column_values_to_not_match_regex",
"tests/test_pandas_dataset.py::TestPandasDataset::test_expect_table_row_count_to_be_between",
"tests/test_pandas_dataset.py::TestPandasDataset::test_expect_table_row_count_to_equal",
"tests/test_pandas_dataset.py::TestPandasDataset::test_positional_arguments"
]
| []
| Apache License 2.0 | 1,867 | [
"examples/notebooks/Distributional_Expectations_Demo.ipynb",
"examples/notebooks/Distributional_Expectations_Demo_Prep.ipynb",
".gitignore",
"great_expectations/dataset/pandas_dataset.py",
"great_expectations/dataset/base.py"
]
| [
"examples/notebooks/Distributional_Expectations_Demo.ipynb",
"examples/notebooks/Distributional_Expectations_Demo_Prep.ipynb",
".gitignore",
"great_expectations/dataset/pandas_dataset.py",
"great_expectations/dataset/base.py"
]
|
|
Clinical-Genomics__scout-656 | e41d7b94106581fa28da793e2ab19c466e2f2f5a | 2017-11-10 12:04:32 | e41d7b94106581fa28da793e2ab19c466e2f2f5a | diff --git a/scout/build/variant.py b/scout/build/variant.py
index 3cf04f188..391398ca7 100644
--- a/scout/build/variant.py
+++ b/scout/build/variant.py
@@ -258,10 +258,20 @@ def build_variant(variant, institute_id, gene_to_panels = None,
# Add the callers
call_info = variant.get('callers', {})
+ if call_info.get('gatk'):
+ variant_obj['gatk'] = call_info['gatk']
- for caller in call_info:
- if call_info[caller]:
- variant_obj[caller] = call_info[caller]
+ if call_info.get('samtools'):
+ variant_obj['samtools'] = call_info['samtools']
+
+ if call_info.get('freebayes'):
+ variant_obj['freebayes'] = call_info['freebayes']
+
+ if call_info.get('mutect'):
+ variant_obj['mutect'] = call_info['mutect']
+
+ if call_info.get('pindel'):
+ variant_obj['pindel'] = call_info['pindel']
# Add the conservation
conservation_info = variant.get('conservation', {})
@@ -308,16 +318,6 @@ def build_variant(variant, institute_id, gene_to_panels = None,
if variant.get('local_obs_hom_old'):
variant_obj['local_obs_hom_old'] = variant['local_obs_hom_old']
- # Add the sv counts:
- if frequencies.get('clingen_cgh_benign'):
- variant_obj['clingen_cgh_benign'] = frequencies['clingen_cgh_benign']
- if frequencies.get('clingen_cgh_pathogenic'):
- variant_obj['clingen_cgh_pathogenic'] = frequencies['clingen_cgh_pathogenic']
- if frequencies.get('clingen_ngi'):
- variant_obj['clingen_ngi'] = frequencies['clingen_ngi']
- if frequencies.get('decipher'):
- variant_obj['decipher'] = frequencies['decipher']
-
# Add the severity predictors
if variant.get('cadd_score'):
diff --git a/scout/constants/__init__.py b/scout/constants/__init__.py
index 80dde1844..e6835b108 100644
--- a/scout/constants/__init__.py
+++ b/scout/constants/__init__.py
@@ -37,34 +37,3 @@ PAR_COORDINATES = {
},
}
-CALLERS = {
- 'snv': [{
- 'id': 'gatk',
- 'name': 'GATK',
- }, {
- 'id': 'freebayes',
- 'name': 'Freebayes',
- }, {
- 'id': 'samtools',
- 'name': 'SAMtools',
- }, {
- 'id': 'mutect',
- 'name': 'MuTect',
- }, {
- 'id': 'pindel',
- 'name': 'Pindel',
- }],
- 'sv': [{
- 'id': 'cnvnator',
- 'name': 'CNVnator',
- }, {
- 'id': 'delly',
- 'name': 'Delly',
- }, {
- 'id': 'tiddit',
- 'name': 'TIDDIT',
- }, {
- 'id': 'manta',
- 'name': 'Manta',
- }]
-}
diff --git a/scout/parse/variant/callers.py b/scout/parse/variant/callers.py
index 687cccd6a..617d2624c 100644
--- a/scout/parse/variant/callers.py
+++ b/scout/parse/variant/callers.py
@@ -1,34 +1,41 @@
-from scout.constants import CALLERS
-
def parse_callers(variant):
"""Parse how the different variant callers have performed
-
+
Args:
variant(dict): A variant dictionary
-
+
Returns:
- callers(dict): A dictionary on the form
+ callers(dict): A dictionary on the form
{'gatk': <filter>,'freebayes': <filter>,'samtools': <filter>}
"""
- relevant_callers = CALLERS['sv' if variant.var_type == 'sv' else 'snv']
- callers = {caller['id']: None for caller in relevant_callers}
+ callers = {
+ 'gatk': None,
+ 'freebayes': None,
+ 'samtools': None,
+ 'mutect': None,
+ 'pindel': None,
+ }
raw_info = variant.INFO.get('set')
if raw_info:
info = raw_info.split('-')
for call in info:
if call == 'FilteredInAll':
- for caller in callers:
- callers[caller] = 'Filtered'
+ callers['gatk'] = 'Filtered'
+ callers['samtools'] = 'Filtered'
+ callers['freebayes'] = 'Filtered'
elif call == 'Intersection':
- for caller in callers:
- callers[caller] = 'Pass'
+ callers['gatk'] = 'Pass'
+ callers['samtools'] = 'Pass'
+ callers['freebayes'] = 'Pass'
elif 'filterIn' in call:
- for caller in callers:
- if caller in call:
- callers[caller] = 'Filtered'
-
- elif call in set(callers.keys()):
+ if 'gatk' in call:
+ callers['gatk'] = 'Filtered'
+ if 'samtools' in call:
+ callers['samtools'] = 'Filtered'
+ if 'freebayes' in call:
+ callers['freebayes'] = 'Filtered'
+ elif call in ['gatk', 'samtools', 'freebayes']:
callers[call] = 'Pass'
# The following is parsing of a custom made merge
other_info = variant.INFO.get('FOUND_IN')
diff --git a/scout/parse/variant/coordinates.py b/scout/parse/variant/coordinates.py
index fa24acf8c..5031d6b0a 100644
--- a/scout/parse/variant/coordinates.py
+++ b/scout/parse/variant/coordinates.py
@@ -19,7 +19,20 @@ def get_cytoband_coordinates(chrom, pos):
return coordinate
def get_sub_category(alt_len, ref_len, category, svtype=None):
- """Get the subcategory"""
+ """Get the subcategory for a VCF variant
+
+ The sub categories are:
+ 'snv', 'indel', 'del', 'ins', 'dup', 'bnd', 'inv'
+
+ Args:
+ alt_len(int)
+ ref_len(int)
+ category(str)
+ svtype(str)
+
+ Returns:
+ subcategory(str)
+ """
subcategory = ''
if category in ('snv', 'indel', 'cancer'):
@@ -32,99 +45,147 @@ def get_sub_category(alt_len, ref_len, category, svtype=None):
return subcategory
-def get_length(alt_len, ref_len, category, svtype=None, svlen=None):
- """docstring for get_length"""
+def get_length(alt_len, ref_len, category, pos, end, svtype=None, svlen=None):
+ """Return the length of a variant
+
+ Args:
+ alt_len(int)
+ ref_len(int)
+ category(str)
+ svtype(str)
+ svlen(int)
+ """
+ # -1 would indicate uncertain length
+ length = -1
if category in ('snv', 'indel', 'cancer'):
if ref_len == alt_len:
length = alt_len
else:
- length = abs(ref_len-alt_len)
+ length = abs(ref_len - alt_len)
+
elif category == 'sv':
if svtype == 'bnd':
length = int(10e10)
else:
if svlen:
length = abs(int(svlen))
- else:
- # -1 would indicate uncertain length
- length = -1
+ # Some software does not give a length but they give END
+ elif end:
+ if end != pos:
+ length = end - pos
return length
-def get_end(pos, length, alt, category, svtype=None):
- """docstring for get_length"""
- end = None
+def get_end(pos, alt, category, snvend=None, svend=None, svlen=None):
+ """Return the end coordinate for a variant
+
+ Args:
+ pos(int)
+ alt(str)
+ category(str)
+ snvend(str)
+ svend(int)
+ svlen(int)
+
+ Returns:
+ end(int)
+ """
+ # If nothing is known we set end to be same as start
+ end = pos
+ # If variant is snv or indel we know that cyvcf2 can handle end pos
if category in ('snv', 'indel', 'cancer'):
- end = pos + length
+ end = snvend
+ # With SVs we have to be a bit more careful
elif category == 'sv':
+ # The END field from INFO usually works fine
+ end = svend
+
+ # For some cases like insertions the callers set end to same as pos
+ # In those cases we can hope that there is a svlen...
+ if svend == pos:
+ if svlen:
+ end = pos + svlen
+ # If variant is 'BND' they have ':' in alt field
+ # Information about other end is in the alt field
if ':' in alt:
other_coordinates = alt.strip('ACGTN[]').split(':')
# For BND end will represent the end position of the other end
try:
end = int(other_coordinates[1])
except ValueError as err:
- end = pos + length
- else:
- end = pos + length
-
- return end
+ pass
+ return end
-def parse_coordinates(chrom, ref, alt, position, category, svtype, svlen, end, mate_id=None):
+def parse_coordinates(variant, category):
"""Find out the coordinates for a variant
Args:
- chrom(str)
- ref(str)
- alt(str)
- position(int)
- category(str)
- svtype(str)
- svlen(int)
- end(int)
- mate_id(str)
+ variant(cyvcf2.Variant)
Returns:
coordinates(dict): A dictionary on the form:
{
+ 'position':<int>,
'end':<int>,
+ 'end_chrom':<str>,
'length':<int>,
'sub_category':<str>,
'mate_id':<str>,
+ 'cytoband_start':<str>,
+ 'cytoband_end':<str>,
}
"""
- coordinates = {
- 'end': end,
- 'length': None,
- 'sub_category': None,
- 'mate_id':None,
- 'cytoband_start':None,
- 'cytoband_end':None,
- 'end_chrom':None,
- }
+ ref = variant.REF
+ alt = variant.ALT[0]
+ chrom = variant.CHROM
+ if (chrom.startswith('chr') or chrom.startswith('CHR')):
+ chrom = chrom[3:]
+
+ svtype = variant.INFO.get('SVTYPE')
if svtype:
svtype = svtype.lower()
+ mate_id = variant.INFO.get('MATEID')
+
+ svlen = variant.INFO.get('SVLEN')
+
+ svend = variant.INFO.get('END')
+ snvend = int(variant.end)
+
+ position = int(variant.POS)
+
ref_len = len(ref)
alt_len = len(alt)
- coordinates['mate_id'] = mate_id
- coordinates['sub_category'] = get_sub_category(alt_len, ref_len, category, svtype)
- coordinates['length'] = get_length(alt_len, ref_len, category, svtype, svlen)
- coordinates['end'] = get_end(position, coordinates['length'], alt, category, svtype)
- coordinates['end_chrom'] = chrom
-
- if coordinates['sub_category'] == 'bnd':
- if ':' in alt:
- other_coordinates = alt.strip('ACGTN[]').split(':')
- # BND will often be translocations between different chromosomes
- other_chrom = other_coordinates[0]
- coordinates['end_chrom'] = other_coordinates[0].lstrip('chrCHR')
-
- coordinates['cytoband_start'] = get_cytoband_coordinates(
- chrom, position
- )
- coordinates['cytoband_end'] = get_cytoband_coordinates(
- coordinates['end_chrom'], coordinates['end']
- )
+
+ sub_category = get_sub_category(alt_len, ref_len, category, svtype)
+ end = get_end(position, alt, category, snvend, svend)
+
+ length = get_length(alt_len, ref_len, category, position, end, svtype, svlen)
+ end_chrom = chrom
+
+ if sub_category == 'bnd':
+ if ':' in alt:
+ other_coordinates = alt.strip('ACGTN[]').split(':')
+ # BND will often be translocations between different chromosomes
+ other_chrom = other_coordinates[0]
+ if (other_chrom.startswith('chr') or other_chrom.startswith('CHR')):
+ other_chrom = other_chrom[3:]
+ end_chrom = other_chrom
+
+ cytoband_start = get_cytoband_coordinates(chrom, position)
+ cytoband_end = get_cytoband_coordinates(end_chrom, end)
+
+ coordinates = {
+ 'position': position,
+ 'end': end,
+ 'length': length,
+ 'sub_category': sub_category,
+ 'mate_id': mate_id,
+ 'cytoband_start': cytoband_start,
+ 'cytoband_end': cytoband_end,
+ 'end_chrom': end_chrom,
+ }
+
return coordinates
diff --git a/scout/parse/variant/frequency.py b/scout/parse/variant/frequency.py
index bb2f2ea99..aef802199 100644
--- a/scout/parse/variant/frequency.py
+++ b/scout/parse/variant/frequency.py
@@ -85,39 +85,3 @@ def parse_frequency(variant, info_key):
raw_annotation = None if raw_annotation == '.' else raw_annotation
frequency = float(raw_annotation) if raw_annotation else None
return frequency
-
-def parse_sv_frequencies(variant):
- """Parsing of some custom sv frequencies
-
- These are very specific at the moment, this will hopefully get better over time when the
- field of structural variants is more developed.
-
- Args:
- variant(cyvcf2.Variant)
-
- Returns:
- sv_frequencies(dict)
- """
- frequency_keys = [
- 'clingen_cgh_benignAF',
- 'clingen_cgh_benign',
- 'clingen_cgh_pathogenicAF',
- 'clingen_cgh_pathogenic',
- 'clingen_ngi',
- 'clingen_ngiAF',
- 'decipherAF',
- 'decipher'
- ]
- sv_frequencies = {}
-
- for key in frequency_keys:
- value = variant.INFO.get(key, 0)
- if 'AF' in key:
- value = float(value)
- else:
- value = int(value)
- if value > 0:
- sv_frequencies[key] = value
-
- return sv_frequencies
-
\ No newline at end of file
diff --git a/scout/parse/variant/variant.py b/scout/parse/variant/variant.py
index 625c8901d..2decdfaa7 100644
--- a/scout/parse/variant/variant.py
+++ b/scout/parse/variant/variant.py
@@ -7,7 +7,7 @@ from .genotype import parse_genotypes
from .compound import parse_compounds
from .clnsig import parse_clnsig
from .gene import parse_genes
-from .frequency import (parse_frequencies, parse_sv_frequencies)
+from .frequency import parse_frequencies
from .conservation import parse_conservations
from .ids import parse_ids
from .callers import parse_callers
@@ -81,20 +81,19 @@ def parse_variant(variant, case, variant_type='clinical',
category = 'snv'
parsed_variant['category'] = category
- #sub category is 'snv', 'indel', 'del', 'ins', 'dup', 'inv', 'cnv'
- # 'snv' and 'indel' are subcatogories of snv
- parsed_variant['sub_category'] = None
################# General information #################
parsed_variant['reference'] = variant.REF
- # We allways assume splitted and normalized vcfs
+
+ ### We allways assume splitted and normalized vcfs!!!
if len(variant.ALT) > 1:
raise VcfError("Variants are only allowed to have one alternative")
parsed_variant['alternative'] = variant.ALT[0]
# cyvcf2 will set QUAL to None if '.' in vcf
parsed_variant['quality'] = variant.QUAL
+
if variant.FILTER:
parsed_variant['filters'] = variant.FILTER.split(';')
else:
@@ -109,38 +108,19 @@ def parse_variant(variant, case, variant_type='clinical',
################# Position specific #################
parsed_variant['chromosome'] = chrom
- # position = start
- parsed_variant['position'] = int(variant.POS)
- svtype = variant.INFO.get('SVTYPE')
-
- svlen = variant.INFO.get('SVLEN')
-
- end = int(variant.end)
-
- mate_id = variant.INFO.get('MATEID')
-
- coordinates = parse_coordinates(
- chrom=parsed_variant['chromosome'],
- ref=parsed_variant['reference'],
- alt=parsed_variant['alternative'],
- position=parsed_variant['position'],
- category=parsed_variant['category'],
- svtype=svtype,
- svlen=svlen,
- end=end,
- mate_id=mate_id,
- )
+ coordinates = parse_coordinates(variant, category)
+ parsed_variant['position'] = coordinates['position']
parsed_variant['sub_category'] = coordinates['sub_category']
parsed_variant['mate_id'] = coordinates['mate_id']
- parsed_variant['end'] = int(coordinates['end'])
- parsed_variant['length'] = int(coordinates['length'])
+ parsed_variant['end'] = coordinates['end']
+ parsed_variant['length'] = coordinates['length']
parsed_variant['end_chrom'] = coordinates['end_chrom']
parsed_variant['cytoband_start'] = coordinates['cytoband_start']
parsed_variant['cytoband_end'] = coordinates['cytoband_end']
- ################# Add rank score #################
+ ################# Add the rank score #################
# The rank score is central for displaying variants in scout.
rank_score = parse_rank_score(variant.INFO.get('RankScore', ''), genmod_key)
@@ -153,14 +133,14 @@ def parse_variant(variant, case, variant_type='clinical',
else:
parsed_variant['samples'] = []
- ################# Add compound information #################
+ ################# Add the compound information #################
compounds = parse_compounds(compound_info=variant.INFO.get('Compounds'),
case_id=genmod_key,
variant_type=variant_type)
if compounds:
parsed_variant['compounds'] = compounds
- ################# Add inheritance patterns #################
+ ################# Add the inheritance patterns #################
genetic_models = parse_genetic_models(variant.INFO.get('GeneticModels'), genmod_key)
if genetic_models:
@@ -176,7 +156,7 @@ def parse_variant(variant, case, variant_type='clinical',
if azqual:
parsed_variant['azqual'] = float(azqual)
- ################# Add gene and transcript information #################
+ ################# Add the gene and transcript information #################
raw_transcripts = []
if vep_header:
vep_info = variant.INFO.get('CSQ')
@@ -212,7 +192,7 @@ def parse_variant(variant, case, variant_type='clinical',
parsed_variant['hgnc_ids'] = list(hgnc_ids)
- ################# Add clinsig prediction #################
+ ################# Add the clinsig prediction #################
clnsig_predictions = parse_clnsig(
acc=variant.INFO.get('CLNACC'),
sig=variant.INFO.get('CLNSIG'),
@@ -237,7 +217,7 @@ def parse_variant(variant, case, variant_type='clinical',
if local_obs_hom_old:
parsed_variant['local_obs_hom_old'] = int(local_obs_hom_old)
- ###################### Add severity predictions ######################
+ ###################### Add the severity predictions ######################
cadd = parse_cadd(variant, parsed_transcripts)
if cadd:
parsed_variant['cadd_score'] = cadd
@@ -246,7 +226,7 @@ def parse_variant(variant, case, variant_type='clinical',
if spidex:
parsed_variant['spidex'] = float(spidex)
- ###################### Add conservation ######################
+ ###################### Add the conservation ######################
parsed_variant['conservation'] = parse_conservations(variant)
@@ -257,9 +237,4 @@ def parse_variant(variant, case, variant_type='clinical',
results = [int(i) for i in rank_result.split('|')]
parsed_variant['rank_result'] = dict(zip(rank_results_header, results))
- ###################### Add SV specific annotations ######################
- sv_frequencies = parse_sv_frequencies(variant)
- for key in sv_frequencies:
- parsed_variant['frequencies'][key] = sv_frequencies[key]
-
return parsed_variant
diff --git a/scout/server/blueprints/variants/controllers.py b/scout/server/blueprints/variants/controllers.py
index 763c52e25..9175f830a 100644
--- a/scout/server/blueprints/variants/controllers.py
+++ b/scout/server/blueprints/variants/controllers.py
@@ -6,7 +6,7 @@ from flask import url_for, flash
from flask_mail import Message
from scout.constants import (CLINSIG_MAP, ACMG_MAP, MANUAL_RANK_OPTIONS, ACMG_OPTIONS,
- ACMG_COMPLETE_MAP, CALLERS)
+ ACMG_COMPLETE_MAP)
from scout.constants.acmg import ACMG_CRITERIA
from scout.models.event import VERBS_MAP
from scout.server.utils import institute_and_case
@@ -57,13 +57,8 @@ def sv_variant(store, institute_id, case_name, variant_id):
('1000G', variant_obj.get('thousand_genomes_frequency')),
('1000G (left)', variant_obj.get('thousand_genomes_frequency_left')),
('1000G (right)', variant_obj.get('thousand_genomes_frequency_right')),
- ('ClinGen CGH (benign)', variant_obj.get('clingen_cgh_benign')),
- ('ClinGen CGH (pathogenic)', variant_obj.get('clingen_cgh_pathogenic')),
- ('ClinGen NGI', variant_obj.get('clingen_ngi')),
- ('Decipher', variant_obj.get('decipher')),
]
- variant_obj['callers'] = callers(variant_obj, category='sv')
overlapping_snvs = (parse_variant(store, institute_obj, case_obj, variant) for variant in
store.overlapping(variant_obj))
@@ -211,7 +206,7 @@ def variant(store, institute_obj, case_obj, variant_id):
variant_obj['alamut_link'] = alamut_link(variant_obj)
variant_obj['spidex_human'] = spidex_human(variant_obj)
variant_obj['expected_inheritance'] = expected_inheritance(variant_obj)
- variant_obj['callers'] = callers(variant_obj, category='snv')
+ variant_obj['callers'] = callers(variant_obj)
for gene_obj in variant_obj.get('genes', []):
parse_gene(gene_obj)
@@ -458,11 +453,13 @@ def expected_inheritance(variant_obj):
return list(manual_models)
-def callers(variant_obj, category='snv'):
- """Return info about callers."""
- calls = [(caller['name'], variant_obj.get(caller['id']))
- for caller in CALLERS[category] if variant_obj.get(caller['id'])]
- return calls
+def callers(variant_obj):
+ """Return call for all callers."""
+ calls = [('GATK', variant_obj.get('gatk', 'NA')),
+ ('Samtools', variant_obj.get('samtools', 'NA')),
+ ('Freebayes', variant_obj.get('freebayes', 'NA'))]
+ existing_calls = [(name, caller) for name, caller in calls if caller]
+ return existing_calls
def sanger(store, mail, institute_obj, case_obj, user_obj, variant_obj, sender):
diff --git a/scout/server/blueprints/variants/templates/variants/sv-variant.html b/scout/server/blueprints/variants/templates/variants/sv-variant.html
index 6a82238e0..f6b15cffb 100644
--- a/scout/server/blueprints/variants/templates/variants/sv-variant.html
+++ b/scout/server/blueprints/variants/templates/variants/sv-variant.html
@@ -222,13 +222,6 @@
{% endfor %}
</tbody>
</table>
- {% if variant.callers %}
- <div class="panel-footer">
- {% for name, caller in variant.callers %}
- <span class="label label-default">{{ name }}: {{ caller }}</span>
- {% endfor %}
- </div>
- {% endif %}
</div>
{% endmacro %}
| CSV - length -1 for a deletion of 80 genes
https://scout.scilifelab.se/cust003/17159/sv/variants?variant_type=clinical&gene_panels=EP&hgnc_symbols=&size=&chrom=&thousand_genomes_frequency=
please have a look. Something doesn't fit here.
A deletion of 1 bp can not contain 80 genes.
thanks,
Michela | Clinical-Genomics/scout | diff --git a/tests/parse/test_frequency.py b/tests/parse/test_frequency.py
index 1712e3348..08529ae8a 100644
--- a/tests/parse/test_frequency.py
+++ b/tests/parse/test_frequency.py
@@ -1,5 +1,4 @@
-from scout.parse.variant.frequency import (parse_frequency, parse_frequencies,
- parse_sv_frequencies)
+from scout.parse.variant.frequency import parse_frequency, parse_frequencies
def test_parse_frequency(cyvcf2_variant):
# GIVEN a variant dict with a frequency in info_dict
@@ -49,16 +48,3 @@ def test_parse_frequencies(cyvcf2_variant):
# THEN the frequencies should be returned in a dictionary
assert frequencies['thousand_g'] == float(variant.INFO['1000GAF'])
assert frequencies['exac'] == float(variant.INFO['EXACAF'])
-
-def test_parse_sv_frequencies_clingen_benign(cyvcf2_variant):
- variant = cyvcf2_variant
- # GIVEN a variant dict with a differenct frequencies
- variant.INFO['clingen_cgh_benignAF'] = '0.01'
- variant.INFO['clingen_cgh_benign'] = '3'
-
- # WHEN frequencies are parsed
- frequencies = parse_sv_frequencies(variant)
-
- # THEN the frequencies should be returned in a dictionary
- assert frequencies['clingen_cgh_benignAF'] == float(variant.INFO['clingen_cgh_benignAF'])
- assert frequencies['clingen_cgh_benign'] == int(variant.INFO['clingen_cgh_benign'])
diff --git a/tests/parse/test_parse_callers.py b/tests/parse/test_parse_callers.py
index 9325539b3..b68364328 100644
--- a/tests/parse/test_parse_callers.py
+++ b/tests/parse/test_parse_callers.py
@@ -64,48 +64,3 @@ def test_parse_callers_filtered_all(cyvcf2_variant):
assert callers['gatk'] == 'Filtered'
assert callers['freebayes'] == 'Filtered'
assert callers['samtools'] == 'Filtered'
-
-def test_parse_sv_callers_filtered_all(cyvcf2_variant):
- variant = cyvcf2_variant
- variant.var_type = 'sv'
- # GIVEN information that all callers agree on filtered
- variant.INFO['set'] = 'FilteredInAll'
-
- # WHEN parsing the information
- callers = parse_callers(variant)
-
- #THEN all callers should be filtered
- assert callers['cnvnator'] == 'Filtered'
- assert callers['delly'] == 'Filtered'
- assert callers['tiddit'] == 'Filtered'
- assert callers['manta'] == 'Filtered'
-
-def test_parse_sv_callers_intersection(cyvcf2_variant):
- variant = cyvcf2_variant
- variant.var_type = 'sv'
- # GIVEN information that all callers agree on filtered
- variant.INFO['set'] = 'Intersection'
-
- # WHEN parsing the information
- callers = parse_callers(variant)
-
- #THEN all callers should be filtered
- assert callers['cnvnator'] == 'Pass'
- assert callers['delly'] == 'Pass'
- assert callers['tiddit'] == 'Pass'
- assert callers['manta'] == 'Pass'
-
-def test_parse_sv_callers_filterin_tiddit(cyvcf2_variant):
- variant = cyvcf2_variant
- variant.var_type = 'sv'
- # GIVEN information that all callers agree on filtered
- variant.INFO['set'] = 'manta-filterIntiddit'
-
- # WHEN parsing the information
- callers = parse_callers(variant)
-
- #THEN all callers should be filtered
- assert callers['cnvnator'] == None
- assert callers['delly'] == None
- assert callers['tiddit'] == 'Filtered'
- assert callers['manta'] == 'Pass'
diff --git a/tests/parse/test_parse_coordinates.py b/tests/parse/test_parse_coordinates.py
new file mode 100644
index 000000000..791148fb3
--- /dev/null
+++ b/tests/parse/test_parse_coordinates.py
@@ -0,0 +1,253 @@
+from scout.parse.variant.coordinates import (get_cytoband_coordinates, get_sub_category,
+ get_length, get_end, parse_coordinates)
+
+
+class CyvcfVariant(object):
+ """Mock a cyvcf variant
+
+ Default is to return a variant with three individuals high genotype
+ quality.
+ """
+ def __init__(self, chrom='1', pos=80000, ref='A', alt='C', end=None,
+ gt_quals=[60, 60, 60], gt_types=[1, 1, 0], var_type='snv',
+ info_dict={}):
+ super(CyvcfVariant, self).__init__()
+ self.CHROM = chrom
+ self.POS = pos
+ self.REF = ref
+ self.ALT = [alt]
+ self.end = end or pos
+ self.gt_quals = gt_quals
+ self.gt_types = gt_types
+ self.var_type = var_type
+ self.INFO = info_dict
+
+
+def test_parse_coordinates_snv():
+ variant = CyvcfVariant()
+
+ coordinates = parse_coordinates(variant, 'snv')
+
+ assert coordinates['position'] == variant.POS
+
+def test_parse_coordinates_indel():
+ variant = CyvcfVariant(alt='ACCC', end=80003)
+
+ coordinates = parse_coordinates(variant, 'snv')
+
+ assert coordinates['position'] == variant.POS
+ assert coordinates['end'] == variant.end
+
+def test_parse_coordinates_translocation():
+ info_dict = {
+ 'SVTYPE': 'BND',
+ }
+ variant = CyvcfVariant(
+ ref='N',
+ alt='N[hs37d5:12060532[',
+ pos=724779,
+ end=724779,
+ var_type='sv',
+ info_dict=info_dict,
+ )
+
+ coordinates = parse_coordinates(variant, 'sv')
+
+ assert coordinates['position'] == variant.POS
+ assert coordinates['end'] == 12060532
+ assert coordinates['end_chrom'] == 'hs37d5'
+ assert coordinates['length'] == 10e10
+ assert coordinates['sub_category'] == 'bnd'
+
+
+###### parse subcategory #######
+def test_get_subcategory_snv():
+ alt_len = 1
+ ref_len = 1
+ category = 'snv'
+ svtype = None
+
+ sub_category = get_sub_category(alt_len, ref_len, category, svtype)
+
+ assert sub_category == 'snv'
+
+def test_get_subcategory_indel():
+ alt_len = 1
+ ref_len = 3
+ category = 'snv'
+ svtype = None
+
+ sub_category = get_sub_category(alt_len, ref_len, category, svtype)
+
+ assert sub_category == 'indel'
+
+###### parse length #######
+
+# get_length(alt_len, ref_len, category, pos, end, svtype=None, svlen=None)
+def test_get_length_snv():
+ alt_len = 1
+ ref_len = 1
+ category = 'snv'
+ pos = end = 879537
+
+ length = get_length(alt_len, ref_len, category, pos, end)
+
+ assert length == 1
+
+def test_get_length_indel():
+ alt_len = 3
+ ref_len = 1
+ category = 'snv'
+ pos = end = 879537
+
+ length = get_length(alt_len, ref_len, category, pos, end)
+
+ assert length == 2
+
+def test_get_sv_length_small_ins():
+ ## GIVEN an insertion with whole sequence in alt field
+ alt_len = 296
+ ref_len = 1
+ category = 'sv'
+ # Pos and end is same for insertions
+ pos = end = 144343218
+ svtype = 'ins'
+ svlen = 296
+
+ ## WHEN parsing the length
+ length = get_length(alt_len, ref_len, category, pos, end, svtype, svlen)
+
+ ## THEN assert that the length is correct
+ assert length == 296
+
+def test_get_sv_length_large_ins_no_length():
+ ## GIVEN an imprecise insertion
+ alt_len = 5
+ ref_len = 1
+ category = 'sv'
+ # Pos and end is same for insertions
+ pos = end = 133920667
+ svtype = 'ins'
+ svlen = None
+
+ ## WHEN parsing the length
+ length = get_length(alt_len, ref_len, category, pos, end, svtype, svlen)
+
+ ## THEN assert that the length is correct
+ assert length == -1
+
+def test_get_sv_length_translocation():
+ ## GIVEN an translocation
+ alt_len = 16
+ ref_len = 1
+ category = 'sv'
+ pos = 726044
+ end = None
+ svtype = 'bnd'
+ svlen = None
+
+ ## WHEN parsing the length
+ length = get_length(alt_len, ref_len, category, pos, end, svtype, svlen)
+
+ ## THEN assert that the length is correct
+ assert length == 10e10
+
+def test_get_sv_length_cnvnator_del():
+ ## GIVEN an cnvnator type deletion
+ alt_len = 5
+ ref_len = 1
+ category = 'sv'
+ pos = 1
+ end = 10000
+ svtype = 'del'
+ svlen = -10000
+
+ ## WHEN parsing the length
+ length = get_length(alt_len, ref_len, category, pos, end, svtype, svlen)
+
+ ## THEN assert that the length is correct
+ assert length == 10000
+
+def test_get_sv_length_del_no_length():
+ ## GIVEN an deletion without len
+ alt_len = 5
+ ref_len = 1
+ category = 'sv'
+ pos = 869314
+ end = 870246
+ svtype = 'del'
+ svlen = None
+
+ ## WHEN parsing the length
+ length = get_length(alt_len, ref_len, category, pos, end, svtype, svlen)
+
+ ## THEN assert that the length is correct
+ assert length == end - pos
+
+###### parse end #######
+# get_end(pos, alt, category, snvend, svend, svlen)
+
+# snv/indels are easy since cyvcf2 are parsing the end for us
+
+def test_get_end_snv():
+ alt = 'T'
+ category = 'snv'
+ pos = snvend = 879537
+
+ end = get_end(pos, alt, category, snvend, svend=None, svlen=None)
+
+ assert end == snvend
+
+def test_get_end_indel():
+ alt = 'C'
+ category = 'indel'
+ pos = 302253
+ snvend = 302265
+
+ end = get_end(pos, alt, category, snvend, svend=None, svlen=None)
+
+ assert end == snvend
+
+# SVs are much harder since there are a lot of corner cases
+# Most SVs (except translocations) have END annotated in INFO field
+# The problem is that many times END==POS and then we have to do some magic on our own
+
+def test_get_end_tiddit_translocation():
+ ## GIVEN a translocation
+ alt = 'N[hs37d5:12060532['
+ category = 'sv'
+ pos = 724779
+
+ ## WHEN parsing the end coordinate
+ end = get_end(pos, alt, category, snvend=None, svend=None, svlen=None)
+
+ ## THEN assert that the end is the same as en coordinate described in alt field
+ assert end == 12060532
+
+def test_get_end_tiddit_translocation():
+ ## GIVEN a translocation
+ alt = 'N[hs37d5:12060532['
+ category = 'sv'
+ pos = 724779
+
+ ## WHEN parsing the end coordinate
+ end = get_end(pos, alt, category, snvend=None, svend=None, svlen=None)
+
+ ## THEN assert that the end is the same as en coordinate described in alt field
+ assert end == 12060532
+
+def test_get_end_deletion():
+ ## GIVEN a translocation
+ alt = '<DEL>'
+ category = 'sv'
+ pos = 869314
+ svend = 870246
+ svlen = None
+
+ ## WHEN parsing the end coordinate
+ end = get_end(pos, alt, category, snvend=None, svend=svend, svlen=svlen)
+
+ ## THEN assert that the end is the same as en coordinate described in alt field
+ assert end == svend
+
+
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 3,
"test_score": 1
},
"num_modified_files": 8
} | 3.4 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | babel==2.17.0
blinker==1.9.0
cachelib==0.13.0
certifi==2025.1.31
charset-normalizer==3.4.1
click==8.1.8
coloredlogs==15.0.1
Cython==3.0.12
cyvcf2==0.31.1
dnspython==2.7.0
dominate==2.9.1
exceptiongroup==1.2.2
Flask==3.1.0
flask-babel==4.0.0
Flask-Bootstrap==3.3.7.1
Flask-DebugToolbar==0.16.0
Flask-Login==0.6.3
Flask-Mail==0.10.0
Flask-Markdown==0.3
Flask-OAuthlib==0.9.6
Flask-PyMongo==3.0.1
Flask-WTF==1.2.2
humanfriendly==10.0
idna==3.10
importlib_metadata==8.6.1
iniconfig==2.1.0
intervaltree==3.1.0
itsdangerous==2.2.0
Jinja2==3.1.6
livereload==2.7.1
loqusdb==2.6.0
Markdown==3.7
MarkupSafe==3.0.2
mongo-adapter==0.3.3
mongomock==4.3.0
numpy==2.0.2
oauthlib==2.1.0
packaging==24.2
path==17.1.0
path.py==12.5.0
ped-parser==1.6.6
pluggy==1.5.0
pymongo==4.11.3
pytest==8.3.5
python-dateutil==2.9.0.post0
pytz==2025.2
PyYAML==6.0.2
query-phenomizer==1.2.1
requests==2.32.3
requests-oauthlib==1.1.0
-e git+https://github.com/Clinical-Genomics/scout.git@e41d7b94106581fa28da793e2ab19c466e2f2f5a#egg=scout_browser
sentinels==1.0.0
six==1.17.0
sortedcontainers==2.4.0
tomli==2.2.1
tornado==6.4.2
urllib3==2.3.0
vcftoolbox==1.5.1
visitor==0.1.3
Werkzeug==3.1.3
WTForms==3.2.1
zipp==3.21.0
| name: scout
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- babel==2.17.0
- blinker==1.9.0
- cachelib==0.13.0
- certifi==2025.1.31
- charset-normalizer==3.4.1
- click==8.1.8
- coloredlogs==15.0.1
- cython==3.0.12
- cyvcf2==0.31.1
- dnspython==2.7.0
- dominate==2.9.1
- exceptiongroup==1.2.2
- flask==3.1.0
- flask-babel==4.0.0
- flask-bootstrap==3.3.7.1
- flask-debugtoolbar==0.16.0
- flask-login==0.6.3
- flask-mail==0.10.0
- flask-markdown==0.3
- flask-oauthlib==0.9.6
- flask-pymongo==3.0.1
- flask-wtf==1.2.2
- humanfriendly==10.0
- idna==3.10
- importlib-metadata==8.6.1
- iniconfig==2.1.0
- intervaltree==3.1.0
- itsdangerous==2.2.0
- jinja2==3.1.6
- livereload==2.7.1
- loqusdb==2.6.0
- markdown==3.7
- markupsafe==3.0.2
- mongo-adapter==0.3.3
- mongomock==4.3.0
- numpy==2.0.2
- oauthlib==2.1.0
- packaging==24.2
- path==17.1.0
- path-py==12.5.0
- ped-parser==1.6.6
- pluggy==1.5.0
- pymongo==4.11.3
- pytest==8.3.5
- python-dateutil==2.9.0.post0
- pytz==2025.2
- pyyaml==6.0.2
- query-phenomizer==1.2.1
- requests==2.32.3
- requests-oauthlib==1.1.0
- sentinels==1.0.0
- six==1.17.0
- sortedcontainers==2.4.0
- tomli==2.2.1
- tornado==6.4.2
- urllib3==2.3.0
- vcftoolbox==1.5.1
- visitor==0.1.3
- werkzeug==3.1.3
- wtforms==3.2.1
- zipp==3.21.0
prefix: /opt/conda/envs/scout
| [
"tests/parse/test_parse_coordinates.py::test_parse_coordinates_snv",
"tests/parse/test_parse_coordinates.py::test_parse_coordinates_indel",
"tests/parse/test_parse_coordinates.py::test_parse_coordinates_translocation",
"tests/parse/test_parse_coordinates.py::test_get_sv_length_small_ins",
"tests/parse/test_parse_coordinates.py::test_get_sv_length_large_ins_no_length",
"tests/parse/test_parse_coordinates.py::test_get_sv_length_translocation",
"tests/parse/test_parse_coordinates.py::test_get_sv_length_cnvnator_del",
"tests/parse/test_parse_coordinates.py::test_get_sv_length_del_no_length",
"tests/parse/test_parse_coordinates.py::test_get_end_snv",
"tests/parse/test_parse_coordinates.py::test_get_end_indel",
"tests/parse/test_parse_coordinates.py::test_get_end_tiddit_translocation",
"tests/parse/test_parse_coordinates.py::test_get_end_deletion"
]
| []
| [
"tests/parse/test_frequency.py::test_parse_frequency",
"tests/parse/test_frequency.py::test_parse_frequency_non_existing_keyword",
"tests/parse/test_frequency.py::test_parse_frequency_non_existing_freq",
"tests/parse/test_frequency.py::test_parse_frequencies",
"tests/parse/test_parse_callers.py::test_parse_callers",
"tests/parse/test_parse_callers.py::test_parse_callers_only_one",
"tests/parse/test_parse_callers.py::test_parse_callers_complex",
"tests/parse/test_parse_callers.py::test_parse_callers_intersection",
"tests/parse/test_parse_callers.py::test_parse_callers_filtered_all",
"tests/parse/test_parse_coordinates.py::test_get_subcategory_snv",
"tests/parse/test_parse_coordinates.py::test_get_subcategory_indel",
"tests/parse/test_parse_coordinates.py::test_get_length_snv",
"tests/parse/test_parse_coordinates.py::test_get_length_indel"
]
| []
| BSD 3-Clause "New" or "Revised" License | 1,868 | [
"scout/parse/variant/callers.py",
"scout/build/variant.py",
"scout/parse/variant/frequency.py",
"scout/server/blueprints/variants/controllers.py",
"scout/parse/variant/variant.py",
"scout/constants/__init__.py",
"scout/server/blueprints/variants/templates/variants/sv-variant.html",
"scout/parse/variant/coordinates.py"
]
| [
"scout/parse/variant/callers.py",
"scout/build/variant.py",
"scout/parse/variant/frequency.py",
"scout/server/blueprints/variants/controllers.py",
"scout/parse/variant/variant.py",
"scout/constants/__init__.py",
"scout/server/blueprints/variants/templates/variants/sv-variant.html",
"scout/parse/variant/coordinates.py"
]
|
|
OpenMined__PySyft-396 | 7222ce4e3f5ce54ab79f3039be6723a312600a32 | 2017-11-10 13:35:27 | 06ce023225dd613d8fb14ab2046135b93ab22376 | codecov[bot]: # [Codecov](https://codecov.io/gh/OpenMined/PySyft/pull/396?src=pr&el=h1) Report
> Merging [#396](https://codecov.io/gh/OpenMined/PySyft/pull/396?src=pr&el=desc) into [master](https://codecov.io/gh/OpenMined/PySyft/commit/7222ce4e3f5ce54ab79f3039be6723a312600a32?src=pr&el=desc) will **decrease** coverage by `0.23%`.
> The diff coverage is `n/a`.
[](https://codecov.io/gh/OpenMined/PySyft/pull/396?src=pr&el=tree)
```diff
@@ Coverage Diff @@
## master #396 +/- ##
=========================================
- Coverage 99.54% 99.3% -0.24%
=========================================
Files 4 4
Lines 1748 1866 +118
=========================================
+ Hits 1740 1853 +113
- Misses 8 13 +5
```
| [Impacted Files](https://codecov.io/gh/OpenMined/PySyft/pull/396?src=pr&el=tree) | Coverage Δ | |
|---|---|---|
| [PySyft/tests/test\_tensor.py](https://codecov.io/gh/OpenMined/PySyft/pull/396?src=pr&el=tree#diff-UHlTeWZ0L3Rlc3RzL3Rlc3RfdGVuc29yLnB5) | `99.05% <0%> (-0.31%)` | :arrow_down: |
------
[Continue to review full report at Codecov](https://codecov.io/gh/OpenMined/PySyft/pull/396?src=pr&el=continue).
> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
> `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
> Powered by [Codecov](https://codecov.io/gh/OpenMined/PySyft/pull/396?src=pr&el=footer). Last update [7222ce4...26f9871](https://codecov.io/gh/OpenMined/PySyft/pull/396?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).
| diff --git a/syft/tensor.py b/syft/tensor.py
index 3bbdaffd6f..e54015a827 100644
--- a/syft/tensor.py
+++ b/syft/tensor.py
@@ -3095,7 +3095,7 @@ class TensorBase(object):
return NotImplemented
out = self.data.strides
- output = tuple(map(lambda x: x / 8, out))
+ output = tuple(map(lambda x: int(x / 8), out))
if dim is None:
return output
@@ -3481,6 +3481,114 @@ class TensorBase(object):
return TensorBase(np.concatenate(sub_arrays, axis=dim))
+ def storage_offset(self):
+ """
+ Returns this tensor’s offset in the underlying
+ storage in terms of number of storage elements (not bytes).
+
+ Parameters
+ ----------
+
+ Returns
+ -------
+ Offset of the underlying storage
+ """
+ if self.encrypted:
+ return NotImplemented
+
+ offset = 0
+
+ # Base ndarray has 0 offset
+ if self.data.base is None:
+ offset = 0
+
+ elif type(self.data.base) is bytes:
+ offset = 0
+
+ else:
+ offset_raw = len(self.data.base.tobytes()) - len(self.data.tobytes())
+ offset = offset_raw / self.data.dtype.itemsize
+
+ return offset
+
+ def set_(self, source=None, offset=0, size=None, stride=None):
+ """
+ Sets the source `numpy.ndarray`, offset, size, and strides.
+
+ If only a tensor is passed in :attr:`source`, this tensor will share
+ the same `numpy.ndarray` and have the same size and strides as the
+ given tensor. Changes to elements in one tensor will be reflected
+ in the other.
+
+ If :attr:`source` is `numpy.ndarray`, the method sets the underlying
+ `numpy.ndarray`, offset, size, and stride.
+
+ Parameters
+ ----------
+
+ source: TensorBase or `numpy.ndarray` or None
+ Input Tensor or ndarray
+
+ offset: int
+ The offset in the underlying `numpy.ndarray` in items not bytes.
+
+ size: Tuple
+ The desired size. Defaults to the size of the source.
+
+ stride: Tuple
+ The desired stride. Defaults to C-contiguous strides.
+ """
+
+ TYPE_ERROR = ''' Received invalid combination of arguments. Expected on of:
+ * no arguments
+ * (syft.TensorBase source)
+ * (np.ndarray storage)
+ * (np.ndarray storage, int offset, tuple size)
+ * (np.ndarray storage, int offset, tuple size, tuple stride)
+ '''
+
+ if self.encrypted or \
+ (source is not None and type(source) is TensorBase and
+ source.encrypted):
+ return NotImplemented
+
+ # Calling as _set(source=ndarray)
+ if source is not None and \
+ type(source) is np.ndarray and \
+ (offset, size, stride) == (0, None, None):
+ self.data = source
+
+ # Calling as _set(source=ndarray, offset, size)
+ # Calling as _set(source=ndarray, offset, size, stride)
+ elif source is not None and type(source) is np.ndarray \
+ and size is not None:
+
+ _stride = stride
+ if stride is not None:
+ _stride = np.multiply(stride, 8)
+
+ offset_nd = offset * self.data.dtype.itemsize
+ self.data = np.ndarray(shape=size,
+ buffer=source.data,
+ dtype=self.data.dtype,
+ offset=offset_nd,
+ strides=_stride)
+
+ # Calling as _set(source=TensorBase)
+ elif source is not None and \
+ type(source) is TensorBase and \
+ (offset, size, stride) == (0, None, None):
+ self.data = source.data
+
+ # Calling as _set()
+ elif (source, offset, size, stride) == (None, 0, None, None):
+ self.data = np.array(None)
+
+ else:
+ raise TypeError(TYPE_ERROR)
+
+ return self
+
def uniform(self, low=0, high=1):
"""
Returns a new tensor filled with numbers sampled uniformly
| Implement Default set Functionality for Base Tensor Type
**User Story A:** As a Data Scientist using Syft's Base Tensor type, I want to leverage a default method for computing operations on a Tensor of arbitrary type. For this ticket to be complete, set_() should operate inline. For a reference on the operation this performs check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation.
**Acceptance Criteria:**
- If the Base Tensor type's attribute "encrypted" is set to True, it should return a NotImplemented error.
- a unit test demonstrating the correct operation on the Base Tensor type implemented over int and float Tensors.
- inline documentation in the python code. For inspiration on inline documentation, please check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation for this operator. | OpenMined/PySyft | diff --git a/tests/test_tensor.py b/tests/test_tensor.py
index e7296b87c8..58848538ab 100644
--- a/tests/test_tensor.py
+++ b/tests/test_tensor.py
@@ -5,6 +5,7 @@ from syft import tensor
import numpy as np
import math
import pytest
+import struct
# Here's our "unit tests".
@@ -20,7 +21,6 @@ class DimTests(unittest.TestCase):
def test_as_view(self):
t = TensorBase(np.array([1.0, 2.0, 3.0]))
t1 = t.view([-1, 1])
- print(t.data.dtype)
self.assertTrue(syft.equal(t.view_as(t1), TensorBase(np.array([[1.0], [2.0], [3.0]]))))
def test_resize(self):
@@ -1575,6 +1575,220 @@ class RenormTests(unittest.TestCase):
self.assertTrue(np.allclose(t, np.array([[1.0, 2.0, 3.0], [2.735054, 3.418817, 4.102581]])))
+class StorageTests(unittest.TestCase):
+
+ def test_storage_offset(self):
+ # int
+ # create custom buffer
+ data = [7, 4, 5, 5, 8, 2, 1, 1, 4, 3, 9, 4, 9, 9, 3, 1]
+ buf = struct.pack('16i', *data)
+
+ # Use custom buffer and ndarray tensors
+ t1 = TensorBase(np.ndarray(shape=(4, 4), buffer=buf, dtype=np.int32))
+ t2 = TensorBase(np.array([[7, 4, 5, 5],
+ [8, 2, 1, 1],
+ [4, 3, 9, 4],
+ [9, 9, 3, 1]], dtype=np.int32))
+
+ # Test default offset = 0
+ self.assertEqual(t1.storage_offset(), 0)
+ self.assertEqual(t2.storage_offset(), 0)
+
+ # value of first element in first row [7,4,5,5]
+ self.assertEqual(t1[0][0], 7)
+ self.assertEqual(t2[0][0], 7)
+
+ t1.set_(t1.data, offset=8, size=(2, 4))
+ self.assertEqual(t1.storage_offset(), 8)
+ self.assertEqual(t1[0][0], 4)
+
+ t2.set_(t2.data, offset=8, size=(2, 4))
+ self.assertEqual(t2.storage_offset(), 8)
+ self.assertEqual(t2[0][0], 4)
+
+ t1 = TensorBase(np.ndarray(shape=(4, 4), buffer=buf, dtype=np.int32))
+ t1.set_(t1.data, offset=4, size=(3, 4))
+ self.assertEqual(t1.storage_offset(), 4)
+ self.assertEqual(t1[0][0], 8)
+
+ t2 = TensorBase(np.array([[7, 4, 5, 5],
+ [8, 2, 1, 1],
+ [4, 3, 9, 4],
+ [9, 9, 3, 1]], dtype=np.int32))
+ t2.set_(t2.data, offset=4, size=(3, 4))
+ self.assertEqual(t2.storage_offset(), 4)
+ self.assertEqual(t2[0][0], 8)
+
+ def test_storage_offset_encrypted(self):
+ t1 = TensorBase(np.array([1, 2, 4, 4]), encrypted=True)
+ res = t1.storage_offset()
+ self.assertEqual(res, NotImplemented)
+
+ def test_tensor_set_encrypted(self):
+ t1 = TensorBase(np.array([]))
+ t2 = TensorBase(np.array([1, 2, 3, 4]), encrypted=True)
+ res = t1.set_(t2)
+ self.assertEqual(res, NotImplemented)
+
+ res = t2.set_(t1)
+ self.assertEqual(res, NotImplemented)
+
+ def test_tensor_set_source_nd(self):
+ t1 = np.array([1, 2, 3, 4])
+ t2 = np.array([0.1, 0.2, 0.3, 0.4])
+
+ tb = TensorBase([])
+ tb2 = TensorBase([])
+
+ r1 = tb.set_(t1)
+ r2 = tb2.set_(t2)
+
+ self.assertEqual(tb, t1)
+ self.assertEqual(tb2, t2)
+
+ self.assertEqual(r1, t1)
+ self.assertEqual(r2, t2)
+
+ def test_tensor_set_empty(self):
+ t1 = TensorBase([1, 2, 3, 4])
+ t2 = TensorBase([0.1, 0.2, 0.3, 0.4])
+
+ # Tensor with none storage
+ tn = TensorBase([])
+ tn.data = np.array(None)
+
+ # test set_ with no argument
+ result = t1.set_()
+ result_f = t2.set_()
+
+ self.assertEqual(result.data, tn.data)
+ self.assertEqual(result_f.data, tn.data)
+
+ def test_tensor_set_(self):
+ t1 = TensorBase([1, 2, 3, 4])
+ t2 = TensorBase([0.1, 0.2, 0.3, 0.4])
+
+ # test call signature
+ with pytest.raises(TypeError):
+ t1.set_(offset=2)
+ t1.set_(size=2)
+ t1.set_(stride=(1,))
+ t1.set_(offset=2, size=(1,))
+ t1.set_(offset=2, size=(1,), stride=(1,))
+ t1.set_(t2, offset=2, size=(1,), stride=(1,))
+
+ # end test call signature
+
+ # tests on ints
+
+ # begin setting tensor
+
+ t1 = TensorBase([])
+ t2 = TensorBase(np.array([1, 2, 3, 4]))
+ t1.set_(t2)
+
+ # memory location is the same
+ self.assertEqual(t1.data.__array_interface__['data'],
+ t2.data.__array_interface__['data'])
+
+ # data is the same
+ self.assertTrue((t1.data == t2.data).all())
+ self.assertEqual(t1.data.dtype, np.int)
+
+ # stride and size are the same
+ self.assertEqual(t1.size(), t2.size())
+ self.assertEqual(t1.stride(), t2.stride())
+
+ # end setting tensor
+
+ # begin set offset and size
+
+ t1 = TensorBase([1, 2, 3, 4])
+
+ t1.set_(t1.data, offset=1, size=(3,))
+ self.assertEqual(t1[0], 2)
+ self.assertEqual(t1[2], 4)
+
+ with pytest.raises(IndexError):
+ t1[3]
+
+ # end set offset and size
+
+ # begin set strides
+ t1 = TensorBase([])
+ t2 = TensorBase(np.zeros(shape=(3, 4, 9, 10), dtype=np.int))
+
+ # set strides on new ndarray
+ strides = (10, 360, 90, 1)
+ size = (9, 3, 4, 10)
+ t1.set_(t2.data, 0, size, strides)
+
+ self.assertEqual(t1.data.base.__array_interface__['data'],
+ t2.data.__array_interface__['data'])
+
+ self.assertEqual(t1.stride(), strides)
+
+ # set strides on underlying ndarray
+ t1 = TensorBase(np.zeros(shape=(3, 4, 9, 10))).uniform_()
+ strides = (10, 360, 90, 1)
+ size = (9, 3, 4, 10)
+
+ t1.set_(t1.data, offset=0, size=size, stride=strides)
+ self.assertEqual(t1.stride(), strides)
+
+ # end set strides
+
+ # tests on floats #######
+
+ # begin setting the underlying ndarray
+
+ t1 = TensorBase([])
+ t2 = TensorBase(np.array([1.0, 2.0, 3.0]))
+ t1.set_(t2)
+ self.assertEqual(t1.data.__array_interface__['data'], t2.data.__array_interface__['data'])
+ self.assertTrue((t1.data == t2.data).all())
+ self.assertEqual(t1.data.dtype, np.float)
+ self.assertEqual(t1.size(), t2.size())
+ self.assertEqual(t1.stride(), t2.stride())
+
+ # end setting the underlying ndarray
+
+ # begin set offset and size
+
+ t2 = TensorBase(np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]))
+
+ t2.set_(t2.data, offset=3, size=(3,))
+ self.assertEqual(t2[0], 4.0)
+ self.assertEqual(t2[2], 6.0)
+ with pytest.raises(IndexError):
+ t2[3]
+
+ # end set offset and size
+
+ # begin set strides
+
+ t1 = TensorBase([])
+ shape = (3, 4, 9, 10)
+ t2 = TensorBase(np.zeros(shape=shape, dtype=np.float))
+
+ # set strides on new ndarray
+ strides = (10, 360, 90, 1)
+ size = (9, 3, 4, 10)
+ t1.set_(t2.data, 0, size, strides)
+ self.assertEqual(t1.data.base.__array_interface__['data'],
+ t2.data.__array_interface__['data'])
+ self.assertEqual(t1.stride(), strides)
+
+ # set strides on underlying ndarray
+ t1 = TensorBase(np.zeros(shape=shape, dtype=np.float))
+ strides = (10, 360, 90, 1)
+ size = (9, 3, 4, 10)
+
+ t1.set_(t1.data, offset=0, size=size, stride=strides)
+ self.assertEqual(t1.stride(), strides)
+ # end set strides
+
+
class SparseTests(unittest.TestCase):
def test_sparse(self):
matrix = TensorBase(np.array([[1, 0], [0, 0]]))
| {
"commit_name": "merge_commit",
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 3,
"issue_text_score": 1,
"test_score": 3
},
"num_modified_files": 1
} | PySyft/hydrogen | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-flake8"
],
"pre_install": [
"apt-get update",
"apt-get install -y musl-dev g++ libgmp3-dev libmpfr-dev ca-certificates libmpc-dev redis-server"
],
"python": "3.6",
"reqs_path": [
"requirements.txt",
"dev-requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | anyio==3.6.2
argon2-cffi==21.3.0
argon2-cffi-bindings==21.2.0
args==0.1.0
async-generator==1.10
attrs==22.2.0
Babel==2.11.0
backcall==0.2.0
bleach==4.1.0
certifi==2021.5.30
cffi==1.15.1
charset-normalizer==2.0.12
clint==0.5.1
comm==0.1.4
contextvars==2.4
coverage==6.2
dataclasses==0.8
decorator==5.1.1
defusedxml==0.7.1
entrypoints==0.4
flake8==5.0.4
idna==3.10
immutables==0.19
importlib-metadata==4.2.0
iniconfig==1.1.1
ipykernel==5.5.6
ipython==7.16.3
ipython-genutils==0.2.0
ipywidgets==7.8.5
jedi==0.17.2
Jinja2==3.0.3
joblib==1.1.1
json5==0.9.16
jsonschema==3.2.0
jupyter==1.1.1
jupyter-client==7.1.2
jupyter-console==6.4.3
jupyter-core==4.9.2
jupyter-server==1.13.1
jupyterlab==3.2.9
jupyterlab-pygments==0.1.2
jupyterlab-server==2.10.3
jupyterlab_widgets==1.1.11
line-profiler==4.1.3
MarkupSafe==2.0.1
mccabe==0.7.0
mistune==0.8.4
nbclassic==0.3.5
nbclient==0.5.9
nbconvert==6.0.7
nbformat==5.1.3
nest-asyncio==1.6.0
notebook==6.4.10
numpy==1.19.5
packaging==21.3
pandocfilters==1.5.1
parso==0.7.1
pexpect==4.9.0
phe==1.5.0
pickleshare==0.7.5
pluggy==1.0.0
prometheus-client==0.17.1
prompt-toolkit==3.0.36
ptyprocess==0.7.0
py==1.11.0
pycodestyle==2.9.1
pycparser==2.21
pyflakes==2.5.0
Pygments==2.14.0
pyparsing==3.1.4
pyRserve==1.0.4
pyrsistent==0.18.0
pytest==7.0.1
pytest-flake8==1.1.1
python-dateutil==2.9.0.post0
pytz==2025.2
pyzmq==25.1.2
requests==2.27.1
scikit-learn==0.24.2
scipy==1.5.4
Send2Trash==1.8.3
six==1.17.0
sklearn==0.0
sniffio==1.2.0
-e git+https://github.com/OpenMined/PySyft.git@7222ce4e3f5ce54ab79f3039be6723a312600a32#egg=syft
terminado==0.12.1
testpath==0.6.0
threadpoolctl==3.1.0
tomli==1.2.3
tornado==6.1
traitlets==4.3.3
typing_extensions==4.1.1
urllib3==1.26.20
wcwidth==0.2.13
webencodings==0.5.1
websocket-client==1.3.1
widgetsnbextension==3.6.10
zipp==3.6.0
| name: PySyft
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- anyio==3.6.2
- argon2-cffi==21.3.0
- argon2-cffi-bindings==21.2.0
- args==0.1.0
- async-generator==1.10
- attrs==22.2.0
- babel==2.11.0
- backcall==0.2.0
- bleach==4.1.0
- cffi==1.15.1
- charset-normalizer==2.0.12
- clint==0.5.1
- comm==0.1.4
- contextvars==2.4
- coverage==6.2
- dataclasses==0.8
- decorator==5.1.1
- defusedxml==0.7.1
- entrypoints==0.4
- flake8==5.0.4
- idna==3.10
- immutables==0.19
- importlib-metadata==4.2.0
- iniconfig==1.1.1
- ipykernel==5.5.6
- ipython==7.16.3
- ipython-genutils==0.2.0
- ipywidgets==7.8.5
- jedi==0.17.2
- jinja2==3.0.3
- joblib==1.1.1
- json5==0.9.16
- jsonschema==3.2.0
- jupyter==1.1.1
- jupyter-client==7.1.2
- jupyter-console==6.4.3
- jupyter-core==4.9.2
- jupyter-server==1.13.1
- jupyterlab==3.2.9
- jupyterlab-pygments==0.1.2
- jupyterlab-server==2.10.3
- jupyterlab-widgets==1.1.11
- line-profiler==4.1.3
- markupsafe==2.0.1
- mccabe==0.7.0
- mistune==0.8.4
- nbclassic==0.3.5
- nbclient==0.5.9
- nbconvert==6.0.7
- nbformat==5.1.3
- nest-asyncio==1.6.0
- notebook==6.4.10
- numpy==1.19.5
- packaging==21.3
- pandocfilters==1.5.1
- parso==0.7.1
- pexpect==4.9.0
- phe==1.5.0
- pickleshare==0.7.5
- pluggy==1.0.0
- prometheus-client==0.17.1
- prompt-toolkit==3.0.36
- ptyprocess==0.7.0
- py==1.11.0
- pycodestyle==2.9.1
- pycparser==2.21
- pyflakes==2.5.0
- pygments==2.14.0
- pyparsing==3.1.4
- pyrserve==1.0.4
- pyrsistent==0.18.0
- pytest==7.0.1
- pytest-flake8==1.1.1
- python-dateutil==2.9.0.post0
- pytz==2025.2
- pyzmq==25.1.2
- requests==2.27.1
- scikit-learn==0.24.2
- scipy==1.5.4
- send2trash==1.8.3
- six==1.17.0
- sklearn==0.0
- sniffio==1.2.0
- terminado==0.12.1
- testpath==0.6.0
- threadpoolctl==3.1.0
- tomli==1.2.3
- tornado==6.1
- traitlets==4.3.3
- typing-extensions==4.1.1
- urllib3==1.26.20
- wcwidth==0.2.13
- webencodings==0.5.1
- websocket-client==1.3.1
- widgetsnbextension==3.6.10
- zipp==3.6.0
prefix: /opt/conda/envs/PySyft
| [
"tests/test_tensor.py::StorageTests::test_storage_offset",
"tests/test_tensor.py::StorageTests::test_storage_offset_encrypted",
"tests/test_tensor.py::StorageTests::test_tensor_set_",
"tests/test_tensor.py::StorageTests::test_tensor_set_empty",
"tests/test_tensor.py::StorageTests::test_tensor_set_encrypted",
"tests/test_tensor.py::StorageTests::test_tensor_set_source_nd"
]
| []
| [
"tests/test_tensor.py::DimTests::test_as_view",
"tests/test_tensor.py::DimTests::test_dim_one",
"tests/test_tensor.py::DimTests::test_resize",
"tests/test_tensor.py::DimTests::test_resize_as",
"tests/test_tensor.py::DimTests::test_view",
"tests/test_tensor.py::DiagTests::test_one_dim_tensor_below_diag",
"tests/test_tensor.py::DiagTests::test_one_dim_tensor_main_diag",
"tests/test_tensor.py::DiagTests::test_one_dim_tensor_upper_diag",
"tests/test_tensor.py::DiagTests::test_two_dim_tensor_below_diag",
"tests/test_tensor.py::DiagTests::test_two_dim_tensor_main_diag",
"tests/test_tensor.py::DiagTests::test_two_dim_tensor_upper_diag",
"tests/test_tensor.py::AddTests::test_inplace",
"tests/test_tensor.py::AddTests::test_scalar",
"tests/test_tensor.py::AddTests::test_simple",
"tests/test_tensor.py::CeilTests::test_ceil",
"tests/test_tensor.py::CeilTests::test_ceil_",
"tests/test_tensor.py::ZeroTests::test_zero",
"tests/test_tensor.py::FloorTests::test_floor",
"tests/test_tensor.py::SubTests::test_inplace",
"tests/test_tensor.py::SubTests::test_scalar",
"tests/test_tensor.py::SubTests::test_simple",
"tests/test_tensor.py::MaxTests::test_axis",
"tests/test_tensor.py::MaxTests::test_no_dim",
"tests/test_tensor.py::MultTests::test_inplace",
"tests/test_tensor.py::MultTests::test_scalar",
"tests/test_tensor.py::MultTests::test_simple",
"tests/test_tensor.py::DivTests::test_inplace",
"tests/test_tensor.py::DivTests::test_scalar",
"tests/test_tensor.py::DivTests::test_simple",
"tests/test_tensor.py::AbsTests::test_abs",
"tests/test_tensor.py::AbsTests::test_abs_",
"tests/test_tensor.py::ShapeTests::test_shape",
"tests/test_tensor.py::SqrtTests::test_sqrt",
"tests/test_tensor.py::SqrtTests::test_sqrt_",
"tests/test_tensor.py::SumTests::test_dim_is_not_none_int",
"tests/test_tensor.py::SumTests::test_dim_none_int",
"tests/test_tensor.py::EqualTests::test_equal",
"tests/test_tensor.py::EqualTests::test_equal_operation",
"tests/test_tensor.py::EqualTests::test_inequality_operation",
"tests/test_tensor.py::EqualTests::test_not_equal",
"tests/test_tensor.py::EqualTests::test_shape_inequality_operation",
"tests/test_tensor.py::EqualTests::test_shape_not_equal",
"tests/test_tensor.py::SigmoidTests::test_sigmoid",
"tests/test_tensor.py::AddmmTests::test_addmm_1d",
"tests/test_tensor.py::AddmmTests::test_addmm_1d_",
"tests/test_tensor.py::AddmmTests::test_addmm_2d",
"tests/test_tensor.py::AddmmTests::test_addmm_2d_",
"tests/test_tensor.py::AddcmulTests::test_addcmul_1d",
"tests/test_tensor.py::AddcmulTests::test_addcmul_1d_",
"tests/test_tensor.py::AddcmulTests::test_addcmul_2d",
"tests/test_tensor.py::AddcmulTests::test_addcmul_2d_",
"tests/test_tensor.py::AddcdivTests::test_addcdiv_1d",
"tests/test_tensor.py::AddcdivTests::test_addcdiv_1d_",
"tests/test_tensor.py::AddcdivTests::test_addcdiv_2d",
"tests/test_tensor.py::AddcdivTests::test_addcdiv_2d_",
"tests/test_tensor.py::AddmvTests::test_addmv",
"tests/test_tensor.py::AddmvTests::test_addmv_",
"tests/test_tensor.py::BmmTests::test_bmm",
"tests/test_tensor.py::BmmTests::test_bmm_size",
"tests/test_tensor.py::AddbmmTests::test_addbmm",
"tests/test_tensor.py::AddbmmTests::test_addbmm_",
"tests/test_tensor.py::BaddbmmTests::test_baddbmm",
"tests/test_tensor.py::BaddbmmTests::test_baddbmm_",
"tests/test_tensor.py::TransposeTests::test_t",
"tests/test_tensor.py::TransposeTests::test_transpose",
"tests/test_tensor.py::TransposeTests::test_transpose_",
"tests/test_tensor.py::UnsqueezeTests::test_unsqueeze",
"tests/test_tensor.py::UnsqueezeTests::test_unsqueeze_",
"tests/test_tensor.py::ExpTests::test_exp",
"tests/test_tensor.py::ExpTests::test_exp_",
"tests/test_tensor.py::FracTests::test_frac",
"tests/test_tensor.py::FracTests::test_frac_",
"tests/test_tensor.py::RsqrtTests::test_rsqrt",
"tests/test_tensor.py::RsqrtTests::test_rsqrt_",
"tests/test_tensor.py::SignTests::test_sign",
"tests/test_tensor.py::SignTests::test_sign_",
"tests/test_tensor.py::NumpyTests::test_numpy",
"tests/test_tensor.py::ReciprocalTests::test_reciprocal",
"tests/test_tensor.py::ReciprocalTests::test_reciprocal_",
"tests/test_tensor.py::LogTests::test_log",
"tests/test_tensor.py::LogTests::test_log_",
"tests/test_tensor.py::LogTests::test_log_1p",
"tests/test_tensor.py::LogTests::test_log_1p_",
"tests/test_tensor.py::ClampTests::test_clamp_float",
"tests/test_tensor.py::ClampTests::test_clamp_float_in_place",
"tests/test_tensor.py::ClampTests::test_clamp_int",
"tests/test_tensor.py::ClampTests::test_clamp_int_in_place",
"tests/test_tensor.py::CloneTests::test_clone",
"tests/test_tensor.py::ChunkTests::test_chunk",
"tests/test_tensor.py::ChunkTests::test_chunk_same_size",
"tests/test_tensor.py::GtTests::test_gt__in_place_with_number",
"tests/test_tensor.py::GtTests::test_gt__in_place_with_tensor",
"tests/test_tensor.py::GtTests::test_gt_with_encrypted",
"tests/test_tensor.py::GtTests::test_gt_with_number",
"tests/test_tensor.py::GtTests::test_gt_with_tensor",
"tests/test_tensor.py::GeTests::test_ge__in_place_with_number",
"tests/test_tensor.py::GeTests::test_ge__in_place_with_tensor",
"tests/test_tensor.py::GeTests::test_ge_with_encrypted",
"tests/test_tensor.py::GeTests::test_ge_with_number",
"tests/test_tensor.py::GeTests::test_ge_with_tensor",
"tests/test_tensor.py::LtTests::test_lt__in_place_with_number",
"tests/test_tensor.py::LtTests::test_lt__in_place_with_tensor",
"tests/test_tensor.py::LtTests::test_lt_with_encrypted",
"tests/test_tensor.py::LtTests::test_lt_with_number",
"tests/test_tensor.py::LtTests::test_lt_with_tensor",
"tests/test_tensor.py::LeTests::test_le__in_place_with_number",
"tests/test_tensor.py::LeTests::test_le__in_place_with_tensor",
"tests/test_tensor.py::LeTests::test_le_with_encrypted",
"tests/test_tensor.py::LeTests::test_le_with_number",
"tests/test_tensor.py::LeTests::test_le_with_tensor",
"tests/test_tensor.py::BernoulliTests::test_bernoulli",
"tests/test_tensor.py::BernoulliTests::test_bernoulli_",
"tests/test_tensor.py::MultinomialTests::test_multinomial",
"tests/test_tensor.py::CauchyTests::test_cauchy_",
"tests/test_tensor.py::UniformTests::test_uniform",
"tests/test_tensor.py::UniformTests::test_uniform_",
"tests/test_tensor.py::GeometricTests::test_geometric_",
"tests/test_tensor.py::NormalTests::test_normal",
"tests/test_tensor.py::NormalTests::test_normal_",
"tests/test_tensor.py::FillTests::test_fill_",
"tests/test_tensor.py::TopkTests::test_topK",
"tests/test_tensor.py::TolistTests::test_to_list",
"tests/test_tensor.py::TraceTests::test_trace",
"tests/test_tensor.py::RoundTests::test_round",
"tests/test_tensor.py::RoundTests::test_round_",
"tests/test_tensor.py::RepeatTests::test_repeat",
"tests/test_tensor.py::PowTests::test_pow",
"tests/test_tensor.py::PowTests::test_pow_",
"tests/test_tensor.py::NegTests::test_neg",
"tests/test_tensor.py::NegTests::test_neg_",
"tests/test_tensor.py::SinTests::test_sin",
"tests/test_tensor.py::SinhTests::test_sinh",
"tests/test_tensor.py::CosTests::test_cos",
"tests/test_tensor.py::CoshTests::test_cosh",
"tests/test_tensor.py::TanTests::test_tan",
"tests/test_tensor.py::TanhTests::test_tanh_",
"tests/test_tensor.py::ProdTests::test_prod",
"tests/test_tensor.py::RandomTests::test_random_",
"tests/test_tensor.py::NonzeroTests::test_non_zero",
"tests/test_tensor.py::CumprodTest::test_cumprod",
"tests/test_tensor.py::CumprodTest::test_cumprod_",
"tests/test_tensor.py::SqueezeTests::test_squeeze",
"tests/test_tensor.py::ExpandAsTests::test_expand_as",
"tests/test_tensor.py::MeanTests::test_mean",
"tests/test_tensor.py::NotEqualTests::test_ne",
"tests/test_tensor.py::NotEqualTests::test_ne_",
"tests/test_tensor.py::IndexTests::test_index",
"tests/test_tensor.py::IndexTests::test_index_add_",
"tests/test_tensor.py::IndexTests::test_index_copy_",
"tests/test_tensor.py::IndexTests::test_index_fill_",
"tests/test_tensor.py::IndexTests::test_index_select",
"tests/test_tensor.py::IndexTests::test_index_slice_notation",
"tests/test_tensor.py::IndexTests::test_indexing",
"tests/test_tensor.py::GatherTests::test_gather_numerical_1",
"tests/test_tensor.py::GatherTests::test_gather_numerical_2",
"tests/test_tensor.py::ScatterTests::test_scatter_dim_out_Of_range",
"tests/test_tensor.py::ScatterTests::test_scatter_index_out_of_range",
"tests/test_tensor.py::ScatterTests::test_scatter_index_src_dimension_mismatch",
"tests/test_tensor.py::ScatterTests::test_scatter_index_type",
"tests/test_tensor.py::ScatterTests::test_scatter_numerical_0",
"tests/test_tensor.py::ScatterTests::test_scatter_numerical_1",
"tests/test_tensor.py::ScatterTests::test_scatter_numerical_2",
"tests/test_tensor.py::ScatterTests::test_scatter_numerical_3",
"tests/test_tensor.py::ScatterTests::test_scatter_numerical_4",
"tests/test_tensor.py::ScatterTests::test_scatter_numerical_5",
"tests/test_tensor.py::ScatterTests::test_scatter_numerical_6",
"tests/test_tensor.py::RemainderTests::test_remainder_",
"tests/test_tensor.py::RemainderTests::test_remainder_broadcasting",
"tests/test_tensor.py::MvTests::test_mv",
"tests/test_tensor.py::MvTests::test_mv_tensor",
"tests/test_tensor.py::NarrowTests::test_narrow_float",
"tests/test_tensor.py::NarrowTests::test_narrow_int",
"tests/test_tensor.py::MaskedScatterTests::test_masked_scatter_1",
"tests/test_tensor.py::MaskedScatterTests::test_masked_scatter_braodcasting_1",
"tests/test_tensor.py::MaskedScatterTests::test_masked_scatter_braodcasting_2",
"tests/test_tensor.py::MaskedFillTests::test_masked_fill_",
"tests/test_tensor.py::MaskedFillTests::test_masked_fill_broadcasting",
"tests/test_tensor.py::MaskedSelectTests::test_masked_select",
"tests/test_tensor.py::MaskedSelectTests::test_masked_select_broadcasting_1",
"tests/test_tensor.py::MaskedSelectTests::test_masked_select_broadcasting_2",
"tests/test_tensor.py::MaskedSelectTests::test_tensor_base_masked_select",
"tests/test_tensor.py::EqTests::test_eq_in_place_with_number",
"tests/test_tensor.py::EqTests::test_eq_in_place_with_tensor",
"tests/test_tensor.py::EqTests::test_eq_with_number",
"tests/test_tensor.py::EqTests::test_eq_with_tensor",
"tests/test_tensor.py::MmTests::test_mm_1d",
"tests/test_tensor.py::MmTests::test_mm_2d",
"tests/test_tensor.py::MmTests::test_mm_3d",
"tests/test_tensor.py::NewTensorTests::test_encrypted_error",
"tests/test_tensor.py::NewTensorTests::test_return_new_float_tensor",
"tests/test_tensor.py::NewTensorTests::test_return_new_int_tensor",
"tests/test_tensor.py::HalfTests::test_half_1",
"tests/test_tensor.py::HalfTests::test_half_2",
"tests/test_tensor.py::FmodTests::test_fmod_number",
"tests/test_tensor.py::FmodTests::test_fmod_tensor",
"tests/test_tensor.py::FmodTestsBis::test_fmod_number",
"tests/test_tensor.py::FmodTestsBis::test_fmod_tensor",
"tests/test_tensor.py::NumelTests::test_numel_2d",
"tests/test_tensor.py::NumelTests::test_numel_3d",
"tests/test_tensor.py::NumelTests::test_numel_encrypted",
"tests/test_tensor.py::NumelTests::test_numel_float",
"tests/test_tensor.py::NumelTests::test_numel_int",
"tests/test_tensor.py::NumelTests::test_numel_str",
"tests/test_tensor.py::NelementTests::test_nelement_2d",
"tests/test_tensor.py::NelementTests::test_nelement_3d",
"tests/test_tensor.py::NelementTests::test_nelement_encrypted",
"tests/test_tensor.py::NelementTests::test_nelement_float",
"tests/test_tensor.py::NelementTests::test_nelement_int",
"tests/test_tensor.py::NelementTests::test_nelement_str",
"tests/test_tensor.py::SizeTests::test_size_2d",
"tests/test_tensor.py::SizeTests::test_size_3d",
"tests/test_tensor.py::SizeTests::test_size_float",
"tests/test_tensor.py::SizeTests::test_size_int",
"tests/test_tensor.py::SizeTests::test_size_str",
"tests/test_tensor.py::LerpTests::test_lerp",
"tests/test_tensor.py::LerpTests::test_lerp_",
"tests/test_tensor.py::ModeTests::testMode_axis_None",
"tests/test_tensor.py::ModeTests::testMode_axis_col",
"tests/test_tensor.py::ModeTests::testMode_axis_row",
"tests/test_tensor.py::RenormTests::testRenorm",
"tests/test_tensor.py::RenormTests::testRenorm_",
"tests/test_tensor.py::SparseTests::test_sparse",
"tests/test_tensor.py::SparseTests::test_sparse_",
"tests/test_tensor.py::StrideTests::test_stride",
"tests/test_tensor.py::UnfoldTest::test_unfold_big",
"tests/test_tensor.py::UnfoldTest::test_unfold_small",
"tests/test_tensor.py::SplitTests::test_split",
"tests/test_tensor.py::CrossTests::test_cross"
]
| []
| Apache License 2.0 | 1,869 | [
"syft/tensor.py"
]
| [
"syft/tensor.py"
]
|
alvinwan__TexSoup-12 | b95820ac9f507916ce0a777cfcefe003ceb10c20 | 2017-11-10 18:03:57 | fa0be81ffe1ceb6189d2fdcec2114f706cdefe76 | diff --git a/TexSoup/reader.py b/TexSoup/reader.py
index 6125322..c6012fa 100644
--- a/TexSoup/reader.py
+++ b/TexSoup/reader.py
@@ -136,11 +136,19 @@ def tokenize_math(text):
>>> tokenize_math(b)
'$$\\min_x$$'
"""
+
+ def escaped_dollar():
+ return text.peek() == '$' and result[-1] == '\\'
+
+ def end_detected():
+ return (text.peek((0, len(starter))) == starter
+ and not escaped_dollar())
+
result = TokenWithPosition('', text.position)
if text.startswith('$'):
starter = '$$' if text.startswith('$$') else '$'
result += text.forward(len(starter))
- while text.hasNext() and text.peek((0, len(starter))) != starter:
+ while text.hasNext() and not end_detected():
result += next(text)
if not text.startswith(starter):
raise EOFError('Expecting %s. Instead got %s' % (
@@ -267,4 +275,4 @@ def read_arg(src, c):
content.append(read_tex(src))
else:
content.append(next(src))
- return Arg.parse(content)
\ No newline at end of file
+ return Arg.parse(content)
| $ and $$ math is not parsed
To reproduce:
```python
In [4]: list(TexSoup.read('$\lambda$').children)
Out[4]: [TexCmd('lambda$')]
```
Expected:
`$` and `$$` should be treated as paired delimiters and result in a correct environment.
TexSoup version:
0.0.3 | alvinwan/TexSoup | diff --git a/tests/test_parser.py b/tests/test_parser.py
index de08b65..232daf0 100644
--- a/tests/test_parser.py
+++ b/tests/test_parser.py
@@ -216,6 +216,13 @@ def test_math_environment_whitespace():
assert '\$' in contents[1], 'Dollar sign not escaped!'
+def test_math_environment_escape():
+ """Tests $ escapes in math environment."""
+ soup = TexSoup("$ \$ $")
+ contents = list(soup.contents)
+ assert '\$' in contents[0][0], 'Dollar sign not escaped!'
+
+
def test_punctuation_command_structure():
"""Tests that commands for punctuation work."""
soup = TexSoup(r"""\right. \right[ \right( \right|""")
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 1,
"test_score": 1
},
"num_modified_files": 1
} | 0.1 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"coverage",
"coveralls"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | certifi==2025.1.31
charset-normalizer==3.4.1
coverage==3.7.1
coveralls==1.1
docopt==0.6.2
exceptiongroup==1.2.2
idna==3.10
iniconfig==2.1.0
packaging==24.2
pluggy==1.5.0
pytest==8.3.5
requests==2.32.3
-e git+https://github.com/alvinwan/TexSoup.git@b95820ac9f507916ce0a777cfcefe003ceb10c20#egg=TexSoup
tomli==2.2.1
urllib3==2.3.0
| name: TexSoup
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- certifi==2025.1.31
- charset-normalizer==3.4.1
- coverage==3.7.1
- coveralls==1.1
- docopt==0.6.2
- exceptiongroup==1.2.2
- idna==3.10
- iniconfig==2.1.0
- packaging==24.2
- pluggy==1.5.0
- pytest==8.3.5
- requests==2.32.3
- tomli==2.2.1
- urllib3==2.3.0
prefix: /opt/conda/envs/TexSoup
| [
"tests/test_parser.py::test_math_environment_escape"
]
| []
| [
"TexSoup/__init__.py::TexSoup.TexSoup",
"TexSoup/data.py::TexSoup.data.TexArgs",
"TexSoup/data.py::TexSoup.data.TexArgs.__repr__",
"TexSoup/data.py::TexSoup.data.TexArgs.__str__",
"TexSoup/data.py::TexSoup.data.TexCmd",
"TexSoup/data.py::TexSoup.data.TexEnv",
"TexSoup/data.py::TexSoup.data.TexNode.__match__",
"TexSoup/reader.py::TexSoup.reader.next_token",
"TexSoup/reader.py::TexSoup.reader.tokenize",
"TexSoup/reader.py::TexSoup.reader.tokenize_math",
"TexSoup/reader.py::TexSoup.reader.tokenize_string",
"TexSoup/utils.py::TexSoup.utils.Buffer",
"TexSoup/utils.py::TexSoup.utils.Buffer.__getitem__",
"TexSoup/utils.py::TexSoup.utils.Buffer.backward",
"TexSoup/utils.py::TexSoup.utils.Buffer.forward",
"TexSoup/utils.py::TexSoup.utils.to_buffer",
"tests/test_parser.py::test_commands_only",
"tests/test_parser.py::test_commands_envs_only",
"tests/test_parser.py::test_commands_envs_text",
"tests/test_parser.py::test_text_preserved",
"tests/test_parser.py::test_command_name_parse",
"tests/test_parser.py::test_commands_without_arguments",
"tests/test_parser.py::test_unlabeled_environment",
"tests/test_parser.py::test_ignore_environment",
"tests/test_parser.py::test_inline_math",
"tests/test_parser.py::test_escaped_characters",
"tests/test_parser.py::test_basic_whitespace",
"tests/test_parser.py::test_whitespace_in_command",
"tests/test_parser.py::test_math_environment_whitespace",
"tests/test_parser.py::test_punctuation_command_structure",
"tests/test_parser.py::test_unclosed_environments",
"tests/test_parser.py::test_unclosed_math_environments",
"tests/test_parser.py::test_arg_parse"
]
| []
| BSD 2-Clause "Simplified" License | 1,871 | [
"TexSoup/reader.py"
]
| [
"TexSoup/reader.py"
]
|
|
alchemistry__alchemlyb-35 | 8915ece9daa2ad17094b2e61565bcfe128a374c7 | 2017-11-11 01:13:54 | a1a3e5fec26c5349238255f5e33a50b98b4d774d | codecov-io: # [Codecov](https://codecov.io/gh/alchemistry/alchemlyb/pull/35?src=pr&el=h1) Report
> Merging [#35](https://codecov.io/gh/alchemistry/alchemlyb/pull/35?src=pr&el=desc) into [master](https://codecov.io/gh/alchemistry/alchemlyb/commit/8915ece9daa2ad17094b2e61565bcfe128a374c7?src=pr&el=desc) will **decrease** coverage by `33.43%`.
> The diff coverage is `37.5%`.
[](https://codecov.io/gh/alchemistry/alchemlyb/pull/35?src=pr&el=tree)
```diff
@@ Coverage Diff @@
## master #35 +/- ##
===========================================
- Coverage 95.04% 61.61% -33.44%
===========================================
Files 7 9 +2
Lines 202 482 +280
Branches 28 100 +72
===========================================
+ Hits 192 297 +105
- Misses 5 159 +154
- Partials 5 26 +21
```
| [Impacted Files](https://codecov.io/gh/alchemistry/alchemlyb/pull/35?src=pr&el=tree) | Coverage Δ | |
|---|---|---|
| [src/alchemlyb/\_\_init\_\_.py](https://codecov.io/gh/alchemistry/alchemlyb/pull/35?src=pr&el=tree#diff-c3JjL2FsY2hlbWx5Yi9fX2luaXRfXy5weQ==) | `100% <100%> (ø)` | |
| [src/alchemlyb/\_version.py](https://codecov.io/gh/alchemistry/alchemlyb/pull/35?src=pr&el=tree#diff-c3JjL2FsY2hlbWx5Yi9fdmVyc2lvbi5weQ==) | `36.82% <36.82%> (ø)` | |
------
[Continue to review full report at Codecov](https://codecov.io/gh/alchemistry/alchemlyb/pull/35?src=pr&el=continue).
> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
> `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
> Powered by [Codecov](https://codecov.io/gh/alchemistry/alchemlyb/pull/35?src=pr&el=footer). Last update [8915ece...f7dfdcc](https://codecov.io/gh/alchemistry/alchemlyb/pull/35?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).
dotsdl: @orbeckst this is pretty slick. I haven't used `versioneer` for any projects before, but this looks like a solution for simplifying the (always tedious) release process. It even works when the current commit isn't tagged, grabbing what looks like the first tag it finds in the branch and appending a number indicating the commit.
I tried it out myself, and it appears to work as advertised. I did:
1. `git tag 0.2.0`
2. `python setup.py sdist`
3. `mkvirtualenv alchemlyb-vers`
4. `workon alchemlyb-vers`
5. `pip install numpy six` # for pymbar installation
6. `pip install dist/alchemlyb-0.2.0.tar.gz`
7. `cd ~ ; python -c "import alchemlyb; print(alchemlyb.__version__)"
And we get '0.2.0' out of this as expected. Very nice!
davidlmobley: @nathanmlim possibly of interest | diff --git a/.coveragerc b/.coveragerc
index 973f00a..9533f1a 100644
--- a/.coveragerc
+++ b/.coveragerc
@@ -3,3 +3,5 @@ branch = True
omit =
# omit all tests
src/alchemlyb/tests/*
+ # omit the versioneer-installed _version.py
+ src/alchemlyb/_version.py
diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 0000000..ead0a18
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1,1 @@
+src/alchemlyb/_version.py export-subst
diff --git a/MANIFEST.in b/MANIFEST.in
index c50ff0b..ea2e81a 100644
--- a/MANIFEST.in
+++ b/MANIFEST.in
@@ -2,3 +2,5 @@ include *.rst
recursive-include src/alchemlyb *.gz *.bz2 *.zip *.rst *.txt
include README.rst
include LICENSE
+include versioneer.py
+include src/alchemlyb/_version.py
diff --git a/setup.cfg b/setup.cfg
index 3c6e79c..67c482e 100644
--- a/setup.cfg
+++ b/setup.cfg
@@ -1,2 +1,10 @@
[bdist_wheel]
universal=1
+
+[versioneer]
+VCS = git
+style = pep440
+versionfile_source = src/alchemlyb/_version.py
+versionfile_build = alchemlyb/_version.py
+tag_prefix =
+parentdir_prefix = alchemlyb-
\ No newline at end of file
diff --git a/setup.py b/setup.py
index 2843724..2d9738e 100755
--- a/setup.py
+++ b/setup.py
@@ -9,8 +9,11 @@ For a basic installation just type the command::
from setuptools import setup, find_packages
+import versioneer
+
setup(name='alchemlyb',
- version='0.2.0-dev',
+ version=versioneer.get_version(),
+ cmdclass=versioneer.get_cmdclass(),
description='the simple alchemistry library',
author='David Dotson',
author_email='[email protected]',
diff --git a/src/alchemlyb/__init__.py b/src/alchemlyb/__init__.py
index e69de29..74f4e66 100644
--- a/src/alchemlyb/__init__.py
+++ b/src/alchemlyb/__init__.py
@@ -0,0 +1,4 @@
+
+from ._version import get_versions
+__version__ = get_versions()['version']
+del get_versions
diff --git a/src/alchemlyb/_version.py b/src/alchemlyb/_version.py
new file mode 100644
index 0000000..0f192af
--- /dev/null
+++ b/src/alchemlyb/_version.py
@@ -0,0 +1,520 @@
+
+# This file helps to compute a version number in source trees obtained from
+# git-archive tarball (such as those provided by githubs download-from-tag
+# feature). Distribution tarballs (built by setup.py sdist) and build
+# directories (produced by setup.py build) will contain a much shorter file
+# that just contains the computed version number.
+
+# This file is released into the public domain. Generated by
+# versioneer-0.18 (https://github.com/warner/python-versioneer)
+
+"""Git implementation of _version.py."""
+
+import errno
+import os
+import re
+import subprocess
+import sys
+
+
+def get_keywords():
+ """Get the keywords needed to look up the version information."""
+ # these strings will be replaced by git during git-archive.
+ # setup.py/versioneer.py will grep for the variable names, so they must
+ # each be defined on a line of their own. _version.py will just call
+ # get_keywords().
+ git_refnames = "$Format:%d$"
+ git_full = "$Format:%H$"
+ git_date = "$Format:%ci$"
+ keywords = {"refnames": git_refnames, "full": git_full, "date": git_date}
+ return keywords
+
+
+class VersioneerConfig:
+ """Container for Versioneer configuration parameters."""
+
+
+def get_config():
+ """Create, populate and return the VersioneerConfig() object."""
+ # these strings are filled in when 'setup.py versioneer' creates
+ # _version.py
+ cfg = VersioneerConfig()
+ cfg.VCS = "git"
+ cfg.style = "pep440"
+ cfg.tag_prefix = ""
+ cfg.parentdir_prefix = "alchemlyb-"
+ cfg.versionfile_source = "src/alchemlyb/_version.py"
+ cfg.verbose = False
+ return cfg
+
+
+class NotThisMethod(Exception):
+ """Exception raised if a method is not valid for the current scenario."""
+
+
+LONG_VERSION_PY = {}
+HANDLERS = {}
+
+
+def register_vcs_handler(vcs, method): # decorator
+ """Decorator to mark a method as the handler for a particular VCS."""
+ def decorate(f):
+ """Store f in HANDLERS[vcs][method]."""
+ if vcs not in HANDLERS:
+ HANDLERS[vcs] = {}
+ HANDLERS[vcs][method] = f
+ return f
+ return decorate
+
+
+def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False,
+ env=None):
+ """Call the given command(s)."""
+ assert isinstance(commands, list)
+ p = None
+ for c in commands:
+ try:
+ dispcmd = str([c] + args)
+ # remember shell=False, so use git.cmd on windows, not just git
+ p = subprocess.Popen([c] + args, cwd=cwd, env=env,
+ stdout=subprocess.PIPE,
+ stderr=(subprocess.PIPE if hide_stderr
+ else None))
+ break
+ except EnvironmentError:
+ e = sys.exc_info()[1]
+ if e.errno == errno.ENOENT:
+ continue
+ if verbose:
+ print("unable to run %s" % dispcmd)
+ print(e)
+ return None, None
+ else:
+ if verbose:
+ print("unable to find command, tried %s" % (commands,))
+ return None, None
+ stdout = p.communicate()[0].strip()
+ if sys.version_info[0] >= 3:
+ stdout = stdout.decode()
+ if p.returncode != 0:
+ if verbose:
+ print("unable to run %s (error)" % dispcmd)
+ print("stdout was %s" % stdout)
+ return None, p.returncode
+ return stdout, p.returncode
+
+
+def versions_from_parentdir(parentdir_prefix, root, verbose):
+ """Try to determine the version from the parent directory name.
+
+ Source tarballs conventionally unpack into a directory that includes both
+ the project name and a version string. We will also support searching up
+ two directory levels for an appropriately named parent directory
+ """
+ rootdirs = []
+
+ for i in range(3):
+ dirname = os.path.basename(root)
+ if dirname.startswith(parentdir_prefix):
+ return {"version": dirname[len(parentdir_prefix):],
+ "full-revisionid": None,
+ "dirty": False, "error": None, "date": None}
+ else:
+ rootdirs.append(root)
+ root = os.path.dirname(root) # up a level
+
+ if verbose:
+ print("Tried directories %s but none started with prefix %s" %
+ (str(rootdirs), parentdir_prefix))
+ raise NotThisMethod("rootdir doesn't start with parentdir_prefix")
+
+
+@register_vcs_handler("git", "get_keywords")
+def git_get_keywords(versionfile_abs):
+ """Extract version information from the given file."""
+ # the code embedded in _version.py can just fetch the value of these
+ # keywords. When used from setup.py, we don't want to import _version.py,
+ # so we do it with a regexp instead. This function is not used from
+ # _version.py.
+ keywords = {}
+ try:
+ f = open(versionfile_abs, "r")
+ for line in f.readlines():
+ if line.strip().startswith("git_refnames ="):
+ mo = re.search(r'=\s*"(.*)"', line)
+ if mo:
+ keywords["refnames"] = mo.group(1)
+ if line.strip().startswith("git_full ="):
+ mo = re.search(r'=\s*"(.*)"', line)
+ if mo:
+ keywords["full"] = mo.group(1)
+ if line.strip().startswith("git_date ="):
+ mo = re.search(r'=\s*"(.*)"', line)
+ if mo:
+ keywords["date"] = mo.group(1)
+ f.close()
+ except EnvironmentError:
+ pass
+ return keywords
+
+
+@register_vcs_handler("git", "keywords")
+def git_versions_from_keywords(keywords, tag_prefix, verbose):
+ """Get version information from git keywords."""
+ if not keywords:
+ raise NotThisMethod("no keywords at all, weird")
+ date = keywords.get("date")
+ if date is not None:
+ # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant
+ # datestamp. However we prefer "%ci" (which expands to an "ISO-8601
+ # -like" string, which we must then edit to make compliant), because
+ # it's been around since git-1.5.3, and it's too difficult to
+ # discover which version we're using, or to work around using an
+ # older one.
+ date = date.strip().replace(" ", "T", 1).replace(" ", "", 1)
+ refnames = keywords["refnames"].strip()
+ if refnames.startswith("$Format"):
+ if verbose:
+ print("keywords are unexpanded, not using")
+ raise NotThisMethod("unexpanded keywords, not a git-archive tarball")
+ refs = set([r.strip() for r in refnames.strip("()").split(",")])
+ # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of
+ # just "foo-1.0". If we see a "tag: " prefix, prefer those.
+ TAG = "tag: "
+ tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)])
+ if not tags:
+ # Either we're using git < 1.8.3, or there really are no tags. We use
+ # a heuristic: assume all version tags have a digit. The old git %d
+ # expansion behaves like git log --decorate=short and strips out the
+ # refs/heads/ and refs/tags/ prefixes that would let us distinguish
+ # between branches and tags. By ignoring refnames without digits, we
+ # filter out many common branch names like "release" and
+ # "stabilization", as well as "HEAD" and "master".
+ tags = set([r for r in refs if re.search(r'\d', r)])
+ if verbose:
+ print("discarding '%s', no digits" % ",".join(refs - tags))
+ if verbose:
+ print("likely tags: %s" % ",".join(sorted(tags)))
+ for ref in sorted(tags):
+ # sorting will prefer e.g. "2.0" over "2.0rc1"
+ if ref.startswith(tag_prefix):
+ r = ref[len(tag_prefix):]
+ if verbose:
+ print("picking %s" % r)
+ return {"version": r,
+ "full-revisionid": keywords["full"].strip(),
+ "dirty": False, "error": None,
+ "date": date}
+ # no suitable tags, so version is "0+unknown", but full hex is still there
+ if verbose:
+ print("no suitable tags, using unknown + full revision id")
+ return {"version": "0+unknown",
+ "full-revisionid": keywords["full"].strip(),
+ "dirty": False, "error": "no suitable tags", "date": None}
+
+
+@register_vcs_handler("git", "pieces_from_vcs")
+def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
+ """Get version from 'git describe' in the root of the source tree.
+
+ This only gets called if the git-archive 'subst' keywords were *not*
+ expanded, and _version.py hasn't already been rewritten with a short
+ version string, meaning we're inside a checked out source tree.
+ """
+ GITS = ["git"]
+ if sys.platform == "win32":
+ GITS = ["git.cmd", "git.exe"]
+
+ out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root,
+ hide_stderr=True)
+ if rc != 0:
+ if verbose:
+ print("Directory %s not under git control" % root)
+ raise NotThisMethod("'git rev-parse --git-dir' returned error")
+
+ # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty]
+ # if there isn't one, this yields HEX[-dirty] (no NUM)
+ describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty",
+ "--always", "--long",
+ "--match", "%s*" % tag_prefix],
+ cwd=root)
+ # --long was added in git-1.5.5
+ if describe_out is None:
+ raise NotThisMethod("'git describe' failed")
+ describe_out = describe_out.strip()
+ full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root)
+ if full_out is None:
+ raise NotThisMethod("'git rev-parse' failed")
+ full_out = full_out.strip()
+
+ pieces = {}
+ pieces["long"] = full_out
+ pieces["short"] = full_out[:7] # maybe improved later
+ pieces["error"] = None
+
+ # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty]
+ # TAG might have hyphens.
+ git_describe = describe_out
+
+ # look for -dirty suffix
+ dirty = git_describe.endswith("-dirty")
+ pieces["dirty"] = dirty
+ if dirty:
+ git_describe = git_describe[:git_describe.rindex("-dirty")]
+
+ # now we have TAG-NUM-gHEX or HEX
+
+ if "-" in git_describe:
+ # TAG-NUM-gHEX
+ mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe)
+ if not mo:
+ # unparseable. Maybe git-describe is misbehaving?
+ pieces["error"] = ("unable to parse git-describe output: '%s'"
+ % describe_out)
+ return pieces
+
+ # tag
+ full_tag = mo.group(1)
+ if not full_tag.startswith(tag_prefix):
+ if verbose:
+ fmt = "tag '%s' doesn't start with prefix '%s'"
+ print(fmt % (full_tag, tag_prefix))
+ pieces["error"] = ("tag '%s' doesn't start with prefix '%s'"
+ % (full_tag, tag_prefix))
+ return pieces
+ pieces["closest-tag"] = full_tag[len(tag_prefix):]
+
+ # distance: number of commits since tag
+ pieces["distance"] = int(mo.group(2))
+
+ # commit: short hex revision ID
+ pieces["short"] = mo.group(3)
+
+ else:
+ # HEX: no tags
+ pieces["closest-tag"] = None
+ count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"],
+ cwd=root)
+ pieces["distance"] = int(count_out) # total number of commits
+
+ # commit date: see ISO-8601 comment in git_versions_from_keywords()
+ date = run_command(GITS, ["show", "-s", "--format=%ci", "HEAD"],
+ cwd=root)[0].strip()
+ pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1)
+
+ return pieces
+
+
+def plus_or_dot(pieces):
+ """Return a + if we don't already have one, else return a ."""
+ if "+" in pieces.get("closest-tag", ""):
+ return "."
+ return "+"
+
+
+def render_pep440(pieces):
+ """Build up version string, with post-release "local version identifier".
+
+ Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you
+ get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty
+
+ Exceptions:
+ 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty]
+ """
+ if pieces["closest-tag"]:
+ rendered = pieces["closest-tag"]
+ if pieces["distance"] or pieces["dirty"]:
+ rendered += plus_or_dot(pieces)
+ rendered += "%d.g%s" % (pieces["distance"], pieces["short"])
+ if pieces["dirty"]:
+ rendered += ".dirty"
+ else:
+ # exception #1
+ rendered = "0+untagged.%d.g%s" % (pieces["distance"],
+ pieces["short"])
+ if pieces["dirty"]:
+ rendered += ".dirty"
+ return rendered
+
+
+def render_pep440_pre(pieces):
+ """TAG[.post.devDISTANCE] -- No -dirty.
+
+ Exceptions:
+ 1: no tags. 0.post.devDISTANCE
+ """
+ if pieces["closest-tag"]:
+ rendered = pieces["closest-tag"]
+ if pieces["distance"]:
+ rendered += ".post.dev%d" % pieces["distance"]
+ else:
+ # exception #1
+ rendered = "0.post.dev%d" % pieces["distance"]
+ return rendered
+
+
+def render_pep440_post(pieces):
+ """TAG[.postDISTANCE[.dev0]+gHEX] .
+
+ The ".dev0" means dirty. Note that .dev0 sorts backwards
+ (a dirty tree will appear "older" than the corresponding clean one),
+ but you shouldn't be releasing software with -dirty anyways.
+
+ Exceptions:
+ 1: no tags. 0.postDISTANCE[.dev0]
+ """
+ if pieces["closest-tag"]:
+ rendered = pieces["closest-tag"]
+ if pieces["distance"] or pieces["dirty"]:
+ rendered += ".post%d" % pieces["distance"]
+ if pieces["dirty"]:
+ rendered += ".dev0"
+ rendered += plus_or_dot(pieces)
+ rendered += "g%s" % pieces["short"]
+ else:
+ # exception #1
+ rendered = "0.post%d" % pieces["distance"]
+ if pieces["dirty"]:
+ rendered += ".dev0"
+ rendered += "+g%s" % pieces["short"]
+ return rendered
+
+
+def render_pep440_old(pieces):
+ """TAG[.postDISTANCE[.dev0]] .
+
+ The ".dev0" means dirty.
+
+ Eexceptions:
+ 1: no tags. 0.postDISTANCE[.dev0]
+ """
+ if pieces["closest-tag"]:
+ rendered = pieces["closest-tag"]
+ if pieces["distance"] or pieces["dirty"]:
+ rendered += ".post%d" % pieces["distance"]
+ if pieces["dirty"]:
+ rendered += ".dev0"
+ else:
+ # exception #1
+ rendered = "0.post%d" % pieces["distance"]
+ if pieces["dirty"]:
+ rendered += ".dev0"
+ return rendered
+
+
+def render_git_describe(pieces):
+ """TAG[-DISTANCE-gHEX][-dirty].
+
+ Like 'git describe --tags --dirty --always'.
+
+ Exceptions:
+ 1: no tags. HEX[-dirty] (note: no 'g' prefix)
+ """
+ if pieces["closest-tag"]:
+ rendered = pieces["closest-tag"]
+ if pieces["distance"]:
+ rendered += "-%d-g%s" % (pieces["distance"], pieces["short"])
+ else:
+ # exception #1
+ rendered = pieces["short"]
+ if pieces["dirty"]:
+ rendered += "-dirty"
+ return rendered
+
+
+def render_git_describe_long(pieces):
+ """TAG-DISTANCE-gHEX[-dirty].
+
+ Like 'git describe --tags --dirty --always -long'.
+ The distance/hash is unconditional.
+
+ Exceptions:
+ 1: no tags. HEX[-dirty] (note: no 'g' prefix)
+ """
+ if pieces["closest-tag"]:
+ rendered = pieces["closest-tag"]
+ rendered += "-%d-g%s" % (pieces["distance"], pieces["short"])
+ else:
+ # exception #1
+ rendered = pieces["short"]
+ if pieces["dirty"]:
+ rendered += "-dirty"
+ return rendered
+
+
+def render(pieces, style):
+ """Render the given version pieces into the requested style."""
+ if pieces["error"]:
+ return {"version": "unknown",
+ "full-revisionid": pieces.get("long"),
+ "dirty": None,
+ "error": pieces["error"],
+ "date": None}
+
+ if not style or style == "default":
+ style = "pep440" # the default
+
+ if style == "pep440":
+ rendered = render_pep440(pieces)
+ elif style == "pep440-pre":
+ rendered = render_pep440_pre(pieces)
+ elif style == "pep440-post":
+ rendered = render_pep440_post(pieces)
+ elif style == "pep440-old":
+ rendered = render_pep440_old(pieces)
+ elif style == "git-describe":
+ rendered = render_git_describe(pieces)
+ elif style == "git-describe-long":
+ rendered = render_git_describe_long(pieces)
+ else:
+ raise ValueError("unknown style '%s'" % style)
+
+ return {"version": rendered, "full-revisionid": pieces["long"],
+ "dirty": pieces["dirty"], "error": None,
+ "date": pieces.get("date")}
+
+
+def get_versions():
+ """Get version information or return default if unable to do so."""
+ # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have
+ # __file__, we can work backwards from there to the root. Some
+ # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which
+ # case we can only use expanded keywords.
+
+ cfg = get_config()
+ verbose = cfg.verbose
+
+ try:
+ return git_versions_from_keywords(get_keywords(), cfg.tag_prefix,
+ verbose)
+ except NotThisMethod:
+ pass
+
+ try:
+ root = os.path.realpath(__file__)
+ # versionfile_source is the relative path from the top of the source
+ # tree (where the .git directory might live) to this file. Invert
+ # this to find the root from __file__.
+ for i in cfg.versionfile_source.split('/'):
+ root = os.path.dirname(root)
+ except NameError:
+ return {"version": "0+unknown", "full-revisionid": None,
+ "dirty": None,
+ "error": "unable to find root of source tree",
+ "date": None}
+
+ try:
+ pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose)
+ return render(pieces, cfg.style)
+ except NotThisMethod:
+ pass
+
+ try:
+ if cfg.parentdir_prefix:
+ return versions_from_parentdir(cfg.parentdir_prefix, root, verbose)
+ except NotThisMethod:
+ pass
+
+ return {"version": "0+unknown", "full-revisionid": None,
+ "dirty": None,
+ "error": "unable to compute version", "date": None}
diff --git a/versioneer.py b/versioneer.py
new file mode 100644
index 0000000..64fea1c
--- /dev/null
+++ b/versioneer.py
@@ -0,0 +1,1822 @@
+
+# Version: 0.18
+
+"""The Versioneer - like a rocketeer, but for versions.
+
+The Versioneer
+==============
+
+* like a rocketeer, but for versions!
+* https://github.com/warner/python-versioneer
+* Brian Warner
+* License: Public Domain
+* Compatible With: python2.6, 2.7, 3.2, 3.3, 3.4, 3.5, 3.6, and pypy
+* [![Latest Version]
+(https://pypip.in/version/versioneer/badge.svg?style=flat)
+](https://pypi.python.org/pypi/versioneer/)
+* [![Build Status]
+(https://travis-ci.org/warner/python-versioneer.png?branch=master)
+](https://travis-ci.org/warner/python-versioneer)
+
+This is a tool for managing a recorded version number in distutils-based
+python projects. The goal is to remove the tedious and error-prone "update
+the embedded version string" step from your release process. Making a new
+release should be as easy as recording a new tag in your version-control
+system, and maybe making new tarballs.
+
+
+## Quick Install
+
+* `pip install versioneer` to somewhere to your $PATH
+* add a `[versioneer]` section to your setup.cfg (see below)
+* run `versioneer install` in your source tree, commit the results
+
+## Version Identifiers
+
+Source trees come from a variety of places:
+
+* a version-control system checkout (mostly used by developers)
+* a nightly tarball, produced by build automation
+* a snapshot tarball, produced by a web-based VCS browser, like github's
+ "tarball from tag" feature
+* a release tarball, produced by "setup.py sdist", distributed through PyPI
+
+Within each source tree, the version identifier (either a string or a number,
+this tool is format-agnostic) can come from a variety of places:
+
+* ask the VCS tool itself, e.g. "git describe" (for checkouts), which knows
+ about recent "tags" and an absolute revision-id
+* the name of the directory into which the tarball was unpacked
+* an expanded VCS keyword ($Id$, etc)
+* a `_version.py` created by some earlier build step
+
+For released software, the version identifier is closely related to a VCS
+tag. Some projects use tag names that include more than just the version
+string (e.g. "myproject-1.2" instead of just "1.2"), in which case the tool
+needs to strip the tag prefix to extract the version identifier. For
+unreleased software (between tags), the version identifier should provide
+enough information to help developers recreate the same tree, while also
+giving them an idea of roughly how old the tree is (after version 1.2, before
+version 1.3). Many VCS systems can report a description that captures this,
+for example `git describe --tags --dirty --always` reports things like
+"0.7-1-g574ab98-dirty" to indicate that the checkout is one revision past the
+0.7 tag, has a unique revision id of "574ab98", and is "dirty" (it has
+uncommitted changes.
+
+The version identifier is used for multiple purposes:
+
+* to allow the module to self-identify its version: `myproject.__version__`
+* to choose a name and prefix for a 'setup.py sdist' tarball
+
+## Theory of Operation
+
+Versioneer works by adding a special `_version.py` file into your source
+tree, where your `__init__.py` can import it. This `_version.py` knows how to
+dynamically ask the VCS tool for version information at import time.
+
+`_version.py` also contains `$Revision$` markers, and the installation
+process marks `_version.py` to have this marker rewritten with a tag name
+during the `git archive` command. As a result, generated tarballs will
+contain enough information to get the proper version.
+
+To allow `setup.py` to compute a version too, a `versioneer.py` is added to
+the top level of your source tree, next to `setup.py` and the `setup.cfg`
+that configures it. This overrides several distutils/setuptools commands to
+compute the version when invoked, and changes `setup.py build` and `setup.py
+sdist` to replace `_version.py` with a small static file that contains just
+the generated version data.
+
+## Installation
+
+See [INSTALL.md](./INSTALL.md) for detailed installation instructions.
+
+## Version-String Flavors
+
+Code which uses Versioneer can learn about its version string at runtime by
+importing `_version` from your main `__init__.py` file and running the
+`get_versions()` function. From the "outside" (e.g. in `setup.py`), you can
+import the top-level `versioneer.py` and run `get_versions()`.
+
+Both functions return a dictionary with different flavors of version
+information:
+
+* `['version']`: A condensed version string, rendered using the selected
+ style. This is the most commonly used value for the project's version
+ string. The default "pep440" style yields strings like `0.11`,
+ `0.11+2.g1076c97`, or `0.11+2.g1076c97.dirty`. See the "Styles" section
+ below for alternative styles.
+
+* `['full-revisionid']`: detailed revision identifier. For Git, this is the
+ full SHA1 commit id, e.g. "1076c978a8d3cfc70f408fe5974aa6c092c949ac".
+
+* `['date']`: Date and time of the latest `HEAD` commit. For Git, it is the
+ commit date in ISO 8601 format. This will be None if the date is not
+ available.
+
+* `['dirty']`: a boolean, True if the tree has uncommitted changes. Note that
+ this is only accurate if run in a VCS checkout, otherwise it is likely to
+ be False or None
+
+* `['error']`: if the version string could not be computed, this will be set
+ to a string describing the problem, otherwise it will be None. It may be
+ useful to throw an exception in setup.py if this is set, to avoid e.g.
+ creating tarballs with a version string of "unknown".
+
+Some variants are more useful than others. Including `full-revisionid` in a
+bug report should allow developers to reconstruct the exact code being tested
+(or indicate the presence of local changes that should be shared with the
+developers). `version` is suitable for display in an "about" box or a CLI
+`--version` output: it can be easily compared against release notes and lists
+of bugs fixed in various releases.
+
+The installer adds the following text to your `__init__.py` to place a basic
+version in `YOURPROJECT.__version__`:
+
+ from ._version import get_versions
+ __version__ = get_versions()['version']
+ del get_versions
+
+## Styles
+
+The setup.cfg `style=` configuration controls how the VCS information is
+rendered into a version string.
+
+The default style, "pep440", produces a PEP440-compliant string, equal to the
+un-prefixed tag name for actual releases, and containing an additional "local
+version" section with more detail for in-between builds. For Git, this is
+TAG[+DISTANCE.gHEX[.dirty]] , using information from `git describe --tags
+--dirty --always`. For example "0.11+2.g1076c97.dirty" indicates that the
+tree is like the "1076c97" commit but has uncommitted changes (".dirty"), and
+that this commit is two revisions ("+2") beyond the "0.11" tag. For released
+software (exactly equal to a known tag), the identifier will only contain the
+stripped tag, e.g. "0.11".
+
+Other styles are available. See [details.md](details.md) in the Versioneer
+source tree for descriptions.
+
+## Debugging
+
+Versioneer tries to avoid fatal errors: if something goes wrong, it will tend
+to return a version of "0+unknown". To investigate the problem, run `setup.py
+version`, which will run the version-lookup code in a verbose mode, and will
+display the full contents of `get_versions()` (including the `error` string,
+which may help identify what went wrong).
+
+## Known Limitations
+
+Some situations are known to cause problems for Versioneer. This details the
+most significant ones. More can be found on Github
+[issues page](https://github.com/warner/python-versioneer/issues).
+
+### Subprojects
+
+Versioneer has limited support for source trees in which `setup.py` is not in
+the root directory (e.g. `setup.py` and `.git/` are *not* siblings). The are
+two common reasons why `setup.py` might not be in the root:
+
+* Source trees which contain multiple subprojects, such as
+ [Buildbot](https://github.com/buildbot/buildbot), which contains both
+ "master" and "slave" subprojects, each with their own `setup.py`,
+ `setup.cfg`, and `tox.ini`. Projects like these produce multiple PyPI
+ distributions (and upload multiple independently-installable tarballs).
+* Source trees whose main purpose is to contain a C library, but which also
+ provide bindings to Python (and perhaps other langauges) in subdirectories.
+
+Versioneer will look for `.git` in parent directories, and most operations
+should get the right version string. However `pip` and `setuptools` have bugs
+and implementation details which frequently cause `pip install .` from a
+subproject directory to fail to find a correct version string (so it usually
+defaults to `0+unknown`).
+
+`pip install --editable .` should work correctly. `setup.py install` might
+work too.
+
+Pip-8.1.1 is known to have this problem, but hopefully it will get fixed in
+some later version.
+
+[Bug #38](https://github.com/warner/python-versioneer/issues/38) is tracking
+this issue. The discussion in
+[PR #61](https://github.com/warner/python-versioneer/pull/61) describes the
+issue from the Versioneer side in more detail.
+[pip PR#3176](https://github.com/pypa/pip/pull/3176) and
+[pip PR#3615](https://github.com/pypa/pip/pull/3615) contain work to improve
+pip to let Versioneer work correctly.
+
+Versioneer-0.16 and earlier only looked for a `.git` directory next to the
+`setup.cfg`, so subprojects were completely unsupported with those releases.
+
+### Editable installs with setuptools <= 18.5
+
+`setup.py develop` and `pip install --editable .` allow you to install a
+project into a virtualenv once, then continue editing the source code (and
+test) without re-installing after every change.
+
+"Entry-point scripts" (`setup(entry_points={"console_scripts": ..})`) are a
+convenient way to specify executable scripts that should be installed along
+with the python package.
+
+These both work as expected when using modern setuptools. When using
+setuptools-18.5 or earlier, however, certain operations will cause
+`pkg_resources.DistributionNotFound` errors when running the entrypoint
+script, which must be resolved by re-installing the package. This happens
+when the install happens with one version, then the egg_info data is
+regenerated while a different version is checked out. Many setup.py commands
+cause egg_info to be rebuilt (including `sdist`, `wheel`, and installing into
+a different virtualenv), so this can be surprising.
+
+[Bug #83](https://github.com/warner/python-versioneer/issues/83) describes
+this one, but upgrading to a newer version of setuptools should probably
+resolve it.
+
+### Unicode version strings
+
+While Versioneer works (and is continually tested) with both Python 2 and
+Python 3, it is not entirely consistent with bytes-vs-unicode distinctions.
+Newer releases probably generate unicode version strings on py2. It's not
+clear that this is wrong, but it may be surprising for applications when then
+write these strings to a network connection or include them in bytes-oriented
+APIs like cryptographic checksums.
+
+[Bug #71](https://github.com/warner/python-versioneer/issues/71) investigates
+this question.
+
+
+## Updating Versioneer
+
+To upgrade your project to a new release of Versioneer, do the following:
+
+* install the new Versioneer (`pip install -U versioneer` or equivalent)
+* edit `setup.cfg`, if necessary, to include any new configuration settings
+ indicated by the release notes. See [UPGRADING](./UPGRADING.md) for details.
+* re-run `versioneer install` in your source tree, to replace
+ `SRC/_version.py`
+* commit any changed files
+
+## Future Directions
+
+This tool is designed to make it easily extended to other version-control
+systems: all VCS-specific components are in separate directories like
+src/git/ . The top-level `versioneer.py` script is assembled from these
+components by running make-versioneer.py . In the future, make-versioneer.py
+will take a VCS name as an argument, and will construct a version of
+`versioneer.py` that is specific to the given VCS. It might also take the
+configuration arguments that are currently provided manually during
+installation by editing setup.py . Alternatively, it might go the other
+direction and include code from all supported VCS systems, reducing the
+number of intermediate scripts.
+
+
+## License
+
+To make Versioneer easier to embed, all its code is dedicated to the public
+domain. The `_version.py` that it creates is also in the public domain.
+Specifically, both are released under the Creative Commons "Public Domain
+Dedication" license (CC0-1.0), as described in
+https://creativecommons.org/publicdomain/zero/1.0/ .
+
+"""
+
+from __future__ import print_function
+try:
+ import configparser
+except ImportError:
+ import ConfigParser as configparser
+import errno
+import json
+import os
+import re
+import subprocess
+import sys
+
+
+class VersioneerConfig:
+ """Container for Versioneer configuration parameters."""
+
+
+def get_root():
+ """Get the project root directory.
+
+ We require that all commands are run from the project root, i.e. the
+ directory that contains setup.py, setup.cfg, and versioneer.py .
+ """
+ root = os.path.realpath(os.path.abspath(os.getcwd()))
+ setup_py = os.path.join(root, "setup.py")
+ versioneer_py = os.path.join(root, "versioneer.py")
+ if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)):
+ # allow 'python path/to/setup.py COMMAND'
+ root = os.path.dirname(os.path.realpath(os.path.abspath(sys.argv[0])))
+ setup_py = os.path.join(root, "setup.py")
+ versioneer_py = os.path.join(root, "versioneer.py")
+ if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)):
+ err = ("Versioneer was unable to run the project root directory. "
+ "Versioneer requires setup.py to be executed from "
+ "its immediate directory (like 'python setup.py COMMAND'), "
+ "or in a way that lets it use sys.argv[0] to find the root "
+ "(like 'python path/to/setup.py COMMAND').")
+ raise VersioneerBadRootError(err)
+ try:
+ # Certain runtime workflows (setup.py install/develop in a setuptools
+ # tree) execute all dependencies in a single python process, so
+ # "versioneer" may be imported multiple times, and python's shared
+ # module-import table will cache the first one. So we can't use
+ # os.path.dirname(__file__), as that will find whichever
+ # versioneer.py was first imported, even in later projects.
+ me = os.path.realpath(os.path.abspath(__file__))
+ me_dir = os.path.normcase(os.path.splitext(me)[0])
+ vsr_dir = os.path.normcase(os.path.splitext(versioneer_py)[0])
+ if me_dir != vsr_dir:
+ print("Warning: build in %s is using versioneer.py from %s"
+ % (os.path.dirname(me), versioneer_py))
+ except NameError:
+ pass
+ return root
+
+
+def get_config_from_root(root):
+ """Read the project setup.cfg file to determine Versioneer config."""
+ # This might raise EnvironmentError (if setup.cfg is missing), or
+ # configparser.NoSectionError (if it lacks a [versioneer] section), or
+ # configparser.NoOptionError (if it lacks "VCS="). See the docstring at
+ # the top of versioneer.py for instructions on writing your setup.cfg .
+ setup_cfg = os.path.join(root, "setup.cfg")
+ parser = configparser.SafeConfigParser()
+ with open(setup_cfg, "r") as f:
+ parser.readfp(f)
+ VCS = parser.get("versioneer", "VCS") # mandatory
+
+ def get(parser, name):
+ if parser.has_option("versioneer", name):
+ return parser.get("versioneer", name)
+ return None
+ cfg = VersioneerConfig()
+ cfg.VCS = VCS
+ cfg.style = get(parser, "style") or ""
+ cfg.versionfile_source = get(parser, "versionfile_source")
+ cfg.versionfile_build = get(parser, "versionfile_build")
+ cfg.tag_prefix = get(parser, "tag_prefix")
+ if cfg.tag_prefix in ("''", '""'):
+ cfg.tag_prefix = ""
+ cfg.parentdir_prefix = get(parser, "parentdir_prefix")
+ cfg.verbose = get(parser, "verbose")
+ return cfg
+
+
+class NotThisMethod(Exception):
+ """Exception raised if a method is not valid for the current scenario."""
+
+
+# these dictionaries contain VCS-specific tools
+LONG_VERSION_PY = {}
+HANDLERS = {}
+
+
+def register_vcs_handler(vcs, method): # decorator
+ """Decorator to mark a method as the handler for a particular VCS."""
+ def decorate(f):
+ """Store f in HANDLERS[vcs][method]."""
+ if vcs not in HANDLERS:
+ HANDLERS[vcs] = {}
+ HANDLERS[vcs][method] = f
+ return f
+ return decorate
+
+
+def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False,
+ env=None):
+ """Call the given command(s)."""
+ assert isinstance(commands, list)
+ p = None
+ for c in commands:
+ try:
+ dispcmd = str([c] + args)
+ # remember shell=False, so use git.cmd on windows, not just git
+ p = subprocess.Popen([c] + args, cwd=cwd, env=env,
+ stdout=subprocess.PIPE,
+ stderr=(subprocess.PIPE if hide_stderr
+ else None))
+ break
+ except EnvironmentError:
+ e = sys.exc_info()[1]
+ if e.errno == errno.ENOENT:
+ continue
+ if verbose:
+ print("unable to run %s" % dispcmd)
+ print(e)
+ return None, None
+ else:
+ if verbose:
+ print("unable to find command, tried %s" % (commands,))
+ return None, None
+ stdout = p.communicate()[0].strip()
+ if sys.version_info[0] >= 3:
+ stdout = stdout.decode()
+ if p.returncode != 0:
+ if verbose:
+ print("unable to run %s (error)" % dispcmd)
+ print("stdout was %s" % stdout)
+ return None, p.returncode
+ return stdout, p.returncode
+
+
+LONG_VERSION_PY['git'] = '''
+# This file helps to compute a version number in source trees obtained from
+# git-archive tarball (such as those provided by githubs download-from-tag
+# feature). Distribution tarballs (built by setup.py sdist) and build
+# directories (produced by setup.py build) will contain a much shorter file
+# that just contains the computed version number.
+
+# This file is released into the public domain. Generated by
+# versioneer-0.18 (https://github.com/warner/python-versioneer)
+
+"""Git implementation of _version.py."""
+
+import errno
+import os
+import re
+import subprocess
+import sys
+
+
+def get_keywords():
+ """Get the keywords needed to look up the version information."""
+ # these strings will be replaced by git during git-archive.
+ # setup.py/versioneer.py will grep for the variable names, so they must
+ # each be defined on a line of their own. _version.py will just call
+ # get_keywords().
+ git_refnames = "%(DOLLAR)sFormat:%%d%(DOLLAR)s"
+ git_full = "%(DOLLAR)sFormat:%%H%(DOLLAR)s"
+ git_date = "%(DOLLAR)sFormat:%%ci%(DOLLAR)s"
+ keywords = {"refnames": git_refnames, "full": git_full, "date": git_date}
+ return keywords
+
+
+class VersioneerConfig:
+ """Container for Versioneer configuration parameters."""
+
+
+def get_config():
+ """Create, populate and return the VersioneerConfig() object."""
+ # these strings are filled in when 'setup.py versioneer' creates
+ # _version.py
+ cfg = VersioneerConfig()
+ cfg.VCS = "git"
+ cfg.style = "%(STYLE)s"
+ cfg.tag_prefix = "%(TAG_PREFIX)s"
+ cfg.parentdir_prefix = "%(PARENTDIR_PREFIX)s"
+ cfg.versionfile_source = "%(VERSIONFILE_SOURCE)s"
+ cfg.verbose = False
+ return cfg
+
+
+class NotThisMethod(Exception):
+ """Exception raised if a method is not valid for the current scenario."""
+
+
+LONG_VERSION_PY = {}
+HANDLERS = {}
+
+
+def register_vcs_handler(vcs, method): # decorator
+ """Decorator to mark a method as the handler for a particular VCS."""
+ def decorate(f):
+ """Store f in HANDLERS[vcs][method]."""
+ if vcs not in HANDLERS:
+ HANDLERS[vcs] = {}
+ HANDLERS[vcs][method] = f
+ return f
+ return decorate
+
+
+def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False,
+ env=None):
+ """Call the given command(s)."""
+ assert isinstance(commands, list)
+ p = None
+ for c in commands:
+ try:
+ dispcmd = str([c] + args)
+ # remember shell=False, so use git.cmd on windows, not just git
+ p = subprocess.Popen([c] + args, cwd=cwd, env=env,
+ stdout=subprocess.PIPE,
+ stderr=(subprocess.PIPE if hide_stderr
+ else None))
+ break
+ except EnvironmentError:
+ e = sys.exc_info()[1]
+ if e.errno == errno.ENOENT:
+ continue
+ if verbose:
+ print("unable to run %%s" %% dispcmd)
+ print(e)
+ return None, None
+ else:
+ if verbose:
+ print("unable to find command, tried %%s" %% (commands,))
+ return None, None
+ stdout = p.communicate()[0].strip()
+ if sys.version_info[0] >= 3:
+ stdout = stdout.decode()
+ if p.returncode != 0:
+ if verbose:
+ print("unable to run %%s (error)" %% dispcmd)
+ print("stdout was %%s" %% stdout)
+ return None, p.returncode
+ return stdout, p.returncode
+
+
+def versions_from_parentdir(parentdir_prefix, root, verbose):
+ """Try to determine the version from the parent directory name.
+
+ Source tarballs conventionally unpack into a directory that includes both
+ the project name and a version string. We will also support searching up
+ two directory levels for an appropriately named parent directory
+ """
+ rootdirs = []
+
+ for i in range(3):
+ dirname = os.path.basename(root)
+ if dirname.startswith(parentdir_prefix):
+ return {"version": dirname[len(parentdir_prefix):],
+ "full-revisionid": None,
+ "dirty": False, "error": None, "date": None}
+ else:
+ rootdirs.append(root)
+ root = os.path.dirname(root) # up a level
+
+ if verbose:
+ print("Tried directories %%s but none started with prefix %%s" %%
+ (str(rootdirs), parentdir_prefix))
+ raise NotThisMethod("rootdir doesn't start with parentdir_prefix")
+
+
+@register_vcs_handler("git", "get_keywords")
+def git_get_keywords(versionfile_abs):
+ """Extract version information from the given file."""
+ # the code embedded in _version.py can just fetch the value of these
+ # keywords. When used from setup.py, we don't want to import _version.py,
+ # so we do it with a regexp instead. This function is not used from
+ # _version.py.
+ keywords = {}
+ try:
+ f = open(versionfile_abs, "r")
+ for line in f.readlines():
+ if line.strip().startswith("git_refnames ="):
+ mo = re.search(r'=\s*"(.*)"', line)
+ if mo:
+ keywords["refnames"] = mo.group(1)
+ if line.strip().startswith("git_full ="):
+ mo = re.search(r'=\s*"(.*)"', line)
+ if mo:
+ keywords["full"] = mo.group(1)
+ if line.strip().startswith("git_date ="):
+ mo = re.search(r'=\s*"(.*)"', line)
+ if mo:
+ keywords["date"] = mo.group(1)
+ f.close()
+ except EnvironmentError:
+ pass
+ return keywords
+
+
+@register_vcs_handler("git", "keywords")
+def git_versions_from_keywords(keywords, tag_prefix, verbose):
+ """Get version information from git keywords."""
+ if not keywords:
+ raise NotThisMethod("no keywords at all, weird")
+ date = keywords.get("date")
+ if date is not None:
+ # git-2.2.0 added "%%cI", which expands to an ISO-8601 -compliant
+ # datestamp. However we prefer "%%ci" (which expands to an "ISO-8601
+ # -like" string, which we must then edit to make compliant), because
+ # it's been around since git-1.5.3, and it's too difficult to
+ # discover which version we're using, or to work around using an
+ # older one.
+ date = date.strip().replace(" ", "T", 1).replace(" ", "", 1)
+ refnames = keywords["refnames"].strip()
+ if refnames.startswith("$Format"):
+ if verbose:
+ print("keywords are unexpanded, not using")
+ raise NotThisMethod("unexpanded keywords, not a git-archive tarball")
+ refs = set([r.strip() for r in refnames.strip("()").split(",")])
+ # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of
+ # just "foo-1.0". If we see a "tag: " prefix, prefer those.
+ TAG = "tag: "
+ tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)])
+ if not tags:
+ # Either we're using git < 1.8.3, or there really are no tags. We use
+ # a heuristic: assume all version tags have a digit. The old git %%d
+ # expansion behaves like git log --decorate=short and strips out the
+ # refs/heads/ and refs/tags/ prefixes that would let us distinguish
+ # between branches and tags. By ignoring refnames without digits, we
+ # filter out many common branch names like "release" and
+ # "stabilization", as well as "HEAD" and "master".
+ tags = set([r for r in refs if re.search(r'\d', r)])
+ if verbose:
+ print("discarding '%%s', no digits" %% ",".join(refs - tags))
+ if verbose:
+ print("likely tags: %%s" %% ",".join(sorted(tags)))
+ for ref in sorted(tags):
+ # sorting will prefer e.g. "2.0" over "2.0rc1"
+ if ref.startswith(tag_prefix):
+ r = ref[len(tag_prefix):]
+ if verbose:
+ print("picking %%s" %% r)
+ return {"version": r,
+ "full-revisionid": keywords["full"].strip(),
+ "dirty": False, "error": None,
+ "date": date}
+ # no suitable tags, so version is "0+unknown", but full hex is still there
+ if verbose:
+ print("no suitable tags, using unknown + full revision id")
+ return {"version": "0+unknown",
+ "full-revisionid": keywords["full"].strip(),
+ "dirty": False, "error": "no suitable tags", "date": None}
+
+
+@register_vcs_handler("git", "pieces_from_vcs")
+def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
+ """Get version from 'git describe' in the root of the source tree.
+
+ This only gets called if the git-archive 'subst' keywords were *not*
+ expanded, and _version.py hasn't already been rewritten with a short
+ version string, meaning we're inside a checked out source tree.
+ """
+ GITS = ["git"]
+ if sys.platform == "win32":
+ GITS = ["git.cmd", "git.exe"]
+
+ out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root,
+ hide_stderr=True)
+ if rc != 0:
+ if verbose:
+ print("Directory %%s not under git control" %% root)
+ raise NotThisMethod("'git rev-parse --git-dir' returned error")
+
+ # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty]
+ # if there isn't one, this yields HEX[-dirty] (no NUM)
+ describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty",
+ "--always", "--long",
+ "--match", "%%s*" %% tag_prefix],
+ cwd=root)
+ # --long was added in git-1.5.5
+ if describe_out is None:
+ raise NotThisMethod("'git describe' failed")
+ describe_out = describe_out.strip()
+ full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root)
+ if full_out is None:
+ raise NotThisMethod("'git rev-parse' failed")
+ full_out = full_out.strip()
+
+ pieces = {}
+ pieces["long"] = full_out
+ pieces["short"] = full_out[:7] # maybe improved later
+ pieces["error"] = None
+
+ # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty]
+ # TAG might have hyphens.
+ git_describe = describe_out
+
+ # look for -dirty suffix
+ dirty = git_describe.endswith("-dirty")
+ pieces["dirty"] = dirty
+ if dirty:
+ git_describe = git_describe[:git_describe.rindex("-dirty")]
+
+ # now we have TAG-NUM-gHEX or HEX
+
+ if "-" in git_describe:
+ # TAG-NUM-gHEX
+ mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe)
+ if not mo:
+ # unparseable. Maybe git-describe is misbehaving?
+ pieces["error"] = ("unable to parse git-describe output: '%%s'"
+ %% describe_out)
+ return pieces
+
+ # tag
+ full_tag = mo.group(1)
+ if not full_tag.startswith(tag_prefix):
+ if verbose:
+ fmt = "tag '%%s' doesn't start with prefix '%%s'"
+ print(fmt %% (full_tag, tag_prefix))
+ pieces["error"] = ("tag '%%s' doesn't start with prefix '%%s'"
+ %% (full_tag, tag_prefix))
+ return pieces
+ pieces["closest-tag"] = full_tag[len(tag_prefix):]
+
+ # distance: number of commits since tag
+ pieces["distance"] = int(mo.group(2))
+
+ # commit: short hex revision ID
+ pieces["short"] = mo.group(3)
+
+ else:
+ # HEX: no tags
+ pieces["closest-tag"] = None
+ count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"],
+ cwd=root)
+ pieces["distance"] = int(count_out) # total number of commits
+
+ # commit date: see ISO-8601 comment in git_versions_from_keywords()
+ date = run_command(GITS, ["show", "-s", "--format=%%ci", "HEAD"],
+ cwd=root)[0].strip()
+ pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1)
+
+ return pieces
+
+
+def plus_or_dot(pieces):
+ """Return a + if we don't already have one, else return a ."""
+ if "+" in pieces.get("closest-tag", ""):
+ return "."
+ return "+"
+
+
+def render_pep440(pieces):
+ """Build up version string, with post-release "local version identifier".
+
+ Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you
+ get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty
+
+ Exceptions:
+ 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty]
+ """
+ if pieces["closest-tag"]:
+ rendered = pieces["closest-tag"]
+ if pieces["distance"] or pieces["dirty"]:
+ rendered += plus_or_dot(pieces)
+ rendered += "%%d.g%%s" %% (pieces["distance"], pieces["short"])
+ if pieces["dirty"]:
+ rendered += ".dirty"
+ else:
+ # exception #1
+ rendered = "0+untagged.%%d.g%%s" %% (pieces["distance"],
+ pieces["short"])
+ if pieces["dirty"]:
+ rendered += ".dirty"
+ return rendered
+
+
+def render_pep440_pre(pieces):
+ """TAG[.post.devDISTANCE] -- No -dirty.
+
+ Exceptions:
+ 1: no tags. 0.post.devDISTANCE
+ """
+ if pieces["closest-tag"]:
+ rendered = pieces["closest-tag"]
+ if pieces["distance"]:
+ rendered += ".post.dev%%d" %% pieces["distance"]
+ else:
+ # exception #1
+ rendered = "0.post.dev%%d" %% pieces["distance"]
+ return rendered
+
+
+def render_pep440_post(pieces):
+ """TAG[.postDISTANCE[.dev0]+gHEX] .
+
+ The ".dev0" means dirty. Note that .dev0 sorts backwards
+ (a dirty tree will appear "older" than the corresponding clean one),
+ but you shouldn't be releasing software with -dirty anyways.
+
+ Exceptions:
+ 1: no tags. 0.postDISTANCE[.dev0]
+ """
+ if pieces["closest-tag"]:
+ rendered = pieces["closest-tag"]
+ if pieces["distance"] or pieces["dirty"]:
+ rendered += ".post%%d" %% pieces["distance"]
+ if pieces["dirty"]:
+ rendered += ".dev0"
+ rendered += plus_or_dot(pieces)
+ rendered += "g%%s" %% pieces["short"]
+ else:
+ # exception #1
+ rendered = "0.post%%d" %% pieces["distance"]
+ if pieces["dirty"]:
+ rendered += ".dev0"
+ rendered += "+g%%s" %% pieces["short"]
+ return rendered
+
+
+def render_pep440_old(pieces):
+ """TAG[.postDISTANCE[.dev0]] .
+
+ The ".dev0" means dirty.
+
+ Eexceptions:
+ 1: no tags. 0.postDISTANCE[.dev0]
+ """
+ if pieces["closest-tag"]:
+ rendered = pieces["closest-tag"]
+ if pieces["distance"] or pieces["dirty"]:
+ rendered += ".post%%d" %% pieces["distance"]
+ if pieces["dirty"]:
+ rendered += ".dev0"
+ else:
+ # exception #1
+ rendered = "0.post%%d" %% pieces["distance"]
+ if pieces["dirty"]:
+ rendered += ".dev0"
+ return rendered
+
+
+def render_git_describe(pieces):
+ """TAG[-DISTANCE-gHEX][-dirty].
+
+ Like 'git describe --tags --dirty --always'.
+
+ Exceptions:
+ 1: no tags. HEX[-dirty] (note: no 'g' prefix)
+ """
+ if pieces["closest-tag"]:
+ rendered = pieces["closest-tag"]
+ if pieces["distance"]:
+ rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"])
+ else:
+ # exception #1
+ rendered = pieces["short"]
+ if pieces["dirty"]:
+ rendered += "-dirty"
+ return rendered
+
+
+def render_git_describe_long(pieces):
+ """TAG-DISTANCE-gHEX[-dirty].
+
+ Like 'git describe --tags --dirty --always -long'.
+ The distance/hash is unconditional.
+
+ Exceptions:
+ 1: no tags. HEX[-dirty] (note: no 'g' prefix)
+ """
+ if pieces["closest-tag"]:
+ rendered = pieces["closest-tag"]
+ rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"])
+ else:
+ # exception #1
+ rendered = pieces["short"]
+ if pieces["dirty"]:
+ rendered += "-dirty"
+ return rendered
+
+
+def render(pieces, style):
+ """Render the given version pieces into the requested style."""
+ if pieces["error"]:
+ return {"version": "unknown",
+ "full-revisionid": pieces.get("long"),
+ "dirty": None,
+ "error": pieces["error"],
+ "date": None}
+
+ if not style or style == "default":
+ style = "pep440" # the default
+
+ if style == "pep440":
+ rendered = render_pep440(pieces)
+ elif style == "pep440-pre":
+ rendered = render_pep440_pre(pieces)
+ elif style == "pep440-post":
+ rendered = render_pep440_post(pieces)
+ elif style == "pep440-old":
+ rendered = render_pep440_old(pieces)
+ elif style == "git-describe":
+ rendered = render_git_describe(pieces)
+ elif style == "git-describe-long":
+ rendered = render_git_describe_long(pieces)
+ else:
+ raise ValueError("unknown style '%%s'" %% style)
+
+ return {"version": rendered, "full-revisionid": pieces["long"],
+ "dirty": pieces["dirty"], "error": None,
+ "date": pieces.get("date")}
+
+
+def get_versions():
+ """Get version information or return default if unable to do so."""
+ # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have
+ # __file__, we can work backwards from there to the root. Some
+ # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which
+ # case we can only use expanded keywords.
+
+ cfg = get_config()
+ verbose = cfg.verbose
+
+ try:
+ return git_versions_from_keywords(get_keywords(), cfg.tag_prefix,
+ verbose)
+ except NotThisMethod:
+ pass
+
+ try:
+ root = os.path.realpath(__file__)
+ # versionfile_source is the relative path from the top of the source
+ # tree (where the .git directory might live) to this file. Invert
+ # this to find the root from __file__.
+ for i in cfg.versionfile_source.split('/'):
+ root = os.path.dirname(root)
+ except NameError:
+ return {"version": "0+unknown", "full-revisionid": None,
+ "dirty": None,
+ "error": "unable to find root of source tree",
+ "date": None}
+
+ try:
+ pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose)
+ return render(pieces, cfg.style)
+ except NotThisMethod:
+ pass
+
+ try:
+ if cfg.parentdir_prefix:
+ return versions_from_parentdir(cfg.parentdir_prefix, root, verbose)
+ except NotThisMethod:
+ pass
+
+ return {"version": "0+unknown", "full-revisionid": None,
+ "dirty": None,
+ "error": "unable to compute version", "date": None}
+'''
+
+
+@register_vcs_handler("git", "get_keywords")
+def git_get_keywords(versionfile_abs):
+ """Extract version information from the given file."""
+ # the code embedded in _version.py can just fetch the value of these
+ # keywords. When used from setup.py, we don't want to import _version.py,
+ # so we do it with a regexp instead. This function is not used from
+ # _version.py.
+ keywords = {}
+ try:
+ f = open(versionfile_abs, "r")
+ for line in f.readlines():
+ if line.strip().startswith("git_refnames ="):
+ mo = re.search(r'=\s*"(.*)"', line)
+ if mo:
+ keywords["refnames"] = mo.group(1)
+ if line.strip().startswith("git_full ="):
+ mo = re.search(r'=\s*"(.*)"', line)
+ if mo:
+ keywords["full"] = mo.group(1)
+ if line.strip().startswith("git_date ="):
+ mo = re.search(r'=\s*"(.*)"', line)
+ if mo:
+ keywords["date"] = mo.group(1)
+ f.close()
+ except EnvironmentError:
+ pass
+ return keywords
+
+
+@register_vcs_handler("git", "keywords")
+def git_versions_from_keywords(keywords, tag_prefix, verbose):
+ """Get version information from git keywords."""
+ if not keywords:
+ raise NotThisMethod("no keywords at all, weird")
+ date = keywords.get("date")
+ if date is not None:
+ # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant
+ # datestamp. However we prefer "%ci" (which expands to an "ISO-8601
+ # -like" string, which we must then edit to make compliant), because
+ # it's been around since git-1.5.3, and it's too difficult to
+ # discover which version we're using, or to work around using an
+ # older one.
+ date = date.strip().replace(" ", "T", 1).replace(" ", "", 1)
+ refnames = keywords["refnames"].strip()
+ if refnames.startswith("$Format"):
+ if verbose:
+ print("keywords are unexpanded, not using")
+ raise NotThisMethod("unexpanded keywords, not a git-archive tarball")
+ refs = set([r.strip() for r in refnames.strip("()").split(",")])
+ # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of
+ # just "foo-1.0". If we see a "tag: " prefix, prefer those.
+ TAG = "tag: "
+ tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)])
+ if not tags:
+ # Either we're using git < 1.8.3, or there really are no tags. We use
+ # a heuristic: assume all version tags have a digit. The old git %d
+ # expansion behaves like git log --decorate=short and strips out the
+ # refs/heads/ and refs/tags/ prefixes that would let us distinguish
+ # between branches and tags. By ignoring refnames without digits, we
+ # filter out many common branch names like "release" and
+ # "stabilization", as well as "HEAD" and "master".
+ tags = set([r for r in refs if re.search(r'\d', r)])
+ if verbose:
+ print("discarding '%s', no digits" % ",".join(refs - tags))
+ if verbose:
+ print("likely tags: %s" % ",".join(sorted(tags)))
+ for ref in sorted(tags):
+ # sorting will prefer e.g. "2.0" over "2.0rc1"
+ if ref.startswith(tag_prefix):
+ r = ref[len(tag_prefix):]
+ if verbose:
+ print("picking %s" % r)
+ return {"version": r,
+ "full-revisionid": keywords["full"].strip(),
+ "dirty": False, "error": None,
+ "date": date}
+ # no suitable tags, so version is "0+unknown", but full hex is still there
+ if verbose:
+ print("no suitable tags, using unknown + full revision id")
+ return {"version": "0+unknown",
+ "full-revisionid": keywords["full"].strip(),
+ "dirty": False, "error": "no suitable tags", "date": None}
+
+
+@register_vcs_handler("git", "pieces_from_vcs")
+def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
+ """Get version from 'git describe' in the root of the source tree.
+
+ This only gets called if the git-archive 'subst' keywords were *not*
+ expanded, and _version.py hasn't already been rewritten with a short
+ version string, meaning we're inside a checked out source tree.
+ """
+ GITS = ["git"]
+ if sys.platform == "win32":
+ GITS = ["git.cmd", "git.exe"]
+
+ out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root,
+ hide_stderr=True)
+ if rc != 0:
+ if verbose:
+ print("Directory %s not under git control" % root)
+ raise NotThisMethod("'git rev-parse --git-dir' returned error")
+
+ # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty]
+ # if there isn't one, this yields HEX[-dirty] (no NUM)
+ describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty",
+ "--always", "--long",
+ "--match", "%s*" % tag_prefix],
+ cwd=root)
+ # --long was added in git-1.5.5
+ if describe_out is None:
+ raise NotThisMethod("'git describe' failed")
+ describe_out = describe_out.strip()
+ full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root)
+ if full_out is None:
+ raise NotThisMethod("'git rev-parse' failed")
+ full_out = full_out.strip()
+
+ pieces = {}
+ pieces["long"] = full_out
+ pieces["short"] = full_out[:7] # maybe improved later
+ pieces["error"] = None
+
+ # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty]
+ # TAG might have hyphens.
+ git_describe = describe_out
+
+ # look for -dirty suffix
+ dirty = git_describe.endswith("-dirty")
+ pieces["dirty"] = dirty
+ if dirty:
+ git_describe = git_describe[:git_describe.rindex("-dirty")]
+
+ # now we have TAG-NUM-gHEX or HEX
+
+ if "-" in git_describe:
+ # TAG-NUM-gHEX
+ mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe)
+ if not mo:
+ # unparseable. Maybe git-describe is misbehaving?
+ pieces["error"] = ("unable to parse git-describe output: '%s'"
+ % describe_out)
+ return pieces
+
+ # tag
+ full_tag = mo.group(1)
+ if not full_tag.startswith(tag_prefix):
+ if verbose:
+ fmt = "tag '%s' doesn't start with prefix '%s'"
+ print(fmt % (full_tag, tag_prefix))
+ pieces["error"] = ("tag '%s' doesn't start with prefix '%s'"
+ % (full_tag, tag_prefix))
+ return pieces
+ pieces["closest-tag"] = full_tag[len(tag_prefix):]
+
+ # distance: number of commits since tag
+ pieces["distance"] = int(mo.group(2))
+
+ # commit: short hex revision ID
+ pieces["short"] = mo.group(3)
+
+ else:
+ # HEX: no tags
+ pieces["closest-tag"] = None
+ count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"],
+ cwd=root)
+ pieces["distance"] = int(count_out) # total number of commits
+
+ # commit date: see ISO-8601 comment in git_versions_from_keywords()
+ date = run_command(GITS, ["show", "-s", "--format=%ci", "HEAD"],
+ cwd=root)[0].strip()
+ pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1)
+
+ return pieces
+
+
+def do_vcs_install(manifest_in, versionfile_source, ipy):
+ """Git-specific installation logic for Versioneer.
+
+ For Git, this means creating/changing .gitattributes to mark _version.py
+ for export-subst keyword substitution.
+ """
+ GITS = ["git"]
+ if sys.platform == "win32":
+ GITS = ["git.cmd", "git.exe"]
+ files = [manifest_in, versionfile_source]
+ if ipy:
+ files.append(ipy)
+ try:
+ me = __file__
+ if me.endswith(".pyc") or me.endswith(".pyo"):
+ me = os.path.splitext(me)[0] + ".py"
+ versioneer_file = os.path.relpath(me)
+ except NameError:
+ versioneer_file = "versioneer.py"
+ files.append(versioneer_file)
+ present = False
+ try:
+ f = open(".gitattributes", "r")
+ for line in f.readlines():
+ if line.strip().startswith(versionfile_source):
+ if "export-subst" in line.strip().split()[1:]:
+ present = True
+ f.close()
+ except EnvironmentError:
+ pass
+ if not present:
+ f = open(".gitattributes", "a+")
+ f.write("%s export-subst\n" % versionfile_source)
+ f.close()
+ files.append(".gitattributes")
+ run_command(GITS, ["add", "--"] + files)
+
+
+def versions_from_parentdir(parentdir_prefix, root, verbose):
+ """Try to determine the version from the parent directory name.
+
+ Source tarballs conventionally unpack into a directory that includes both
+ the project name and a version string. We will also support searching up
+ two directory levels for an appropriately named parent directory
+ """
+ rootdirs = []
+
+ for i in range(3):
+ dirname = os.path.basename(root)
+ if dirname.startswith(parentdir_prefix):
+ return {"version": dirname[len(parentdir_prefix):],
+ "full-revisionid": None,
+ "dirty": False, "error": None, "date": None}
+ else:
+ rootdirs.append(root)
+ root = os.path.dirname(root) # up a level
+
+ if verbose:
+ print("Tried directories %s but none started with prefix %s" %
+ (str(rootdirs), parentdir_prefix))
+ raise NotThisMethod("rootdir doesn't start with parentdir_prefix")
+
+
+SHORT_VERSION_PY = """
+# This file was generated by 'versioneer.py' (0.18) from
+# revision-control system data, or from the parent directory name of an
+# unpacked source archive. Distribution tarballs contain a pre-generated copy
+# of this file.
+
+import json
+
+version_json = '''
+%s
+''' # END VERSION_JSON
+
+
+def get_versions():
+ return json.loads(version_json)
+"""
+
+
+def versions_from_file(filename):
+ """Try to determine the version from _version.py if present."""
+ try:
+ with open(filename) as f:
+ contents = f.read()
+ except EnvironmentError:
+ raise NotThisMethod("unable to read _version.py")
+ mo = re.search(r"version_json = '''\n(.*)''' # END VERSION_JSON",
+ contents, re.M | re.S)
+ if not mo:
+ mo = re.search(r"version_json = '''\r\n(.*)''' # END VERSION_JSON",
+ contents, re.M | re.S)
+ if not mo:
+ raise NotThisMethod("no version_json in _version.py")
+ return json.loads(mo.group(1))
+
+
+def write_to_version_file(filename, versions):
+ """Write the given version number to the given _version.py file."""
+ os.unlink(filename)
+ contents = json.dumps(versions, sort_keys=True,
+ indent=1, separators=(",", ": "))
+ with open(filename, "w") as f:
+ f.write(SHORT_VERSION_PY % contents)
+
+ print("set %s to '%s'" % (filename, versions["version"]))
+
+
+def plus_or_dot(pieces):
+ """Return a + if we don't already have one, else return a ."""
+ if "+" in pieces.get("closest-tag", ""):
+ return "."
+ return "+"
+
+
+def render_pep440(pieces):
+ """Build up version string, with post-release "local version identifier".
+
+ Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you
+ get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty
+
+ Exceptions:
+ 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty]
+ """
+ if pieces["closest-tag"]:
+ rendered = pieces["closest-tag"]
+ if pieces["distance"] or pieces["dirty"]:
+ rendered += plus_or_dot(pieces)
+ rendered += "%d.g%s" % (pieces["distance"], pieces["short"])
+ if pieces["dirty"]:
+ rendered += ".dirty"
+ else:
+ # exception #1
+ rendered = "0+untagged.%d.g%s" % (pieces["distance"],
+ pieces["short"])
+ if pieces["dirty"]:
+ rendered += ".dirty"
+ return rendered
+
+
+def render_pep440_pre(pieces):
+ """TAG[.post.devDISTANCE] -- No -dirty.
+
+ Exceptions:
+ 1: no tags. 0.post.devDISTANCE
+ """
+ if pieces["closest-tag"]:
+ rendered = pieces["closest-tag"]
+ if pieces["distance"]:
+ rendered += ".post.dev%d" % pieces["distance"]
+ else:
+ # exception #1
+ rendered = "0.post.dev%d" % pieces["distance"]
+ return rendered
+
+
+def render_pep440_post(pieces):
+ """TAG[.postDISTANCE[.dev0]+gHEX] .
+
+ The ".dev0" means dirty. Note that .dev0 sorts backwards
+ (a dirty tree will appear "older" than the corresponding clean one),
+ but you shouldn't be releasing software with -dirty anyways.
+
+ Exceptions:
+ 1: no tags. 0.postDISTANCE[.dev0]
+ """
+ if pieces["closest-tag"]:
+ rendered = pieces["closest-tag"]
+ if pieces["distance"] or pieces["dirty"]:
+ rendered += ".post%d" % pieces["distance"]
+ if pieces["dirty"]:
+ rendered += ".dev0"
+ rendered += plus_or_dot(pieces)
+ rendered += "g%s" % pieces["short"]
+ else:
+ # exception #1
+ rendered = "0.post%d" % pieces["distance"]
+ if pieces["dirty"]:
+ rendered += ".dev0"
+ rendered += "+g%s" % pieces["short"]
+ return rendered
+
+
+def render_pep440_old(pieces):
+ """TAG[.postDISTANCE[.dev0]] .
+
+ The ".dev0" means dirty.
+
+ Eexceptions:
+ 1: no tags. 0.postDISTANCE[.dev0]
+ """
+ if pieces["closest-tag"]:
+ rendered = pieces["closest-tag"]
+ if pieces["distance"] or pieces["dirty"]:
+ rendered += ".post%d" % pieces["distance"]
+ if pieces["dirty"]:
+ rendered += ".dev0"
+ else:
+ # exception #1
+ rendered = "0.post%d" % pieces["distance"]
+ if pieces["dirty"]:
+ rendered += ".dev0"
+ return rendered
+
+
+def render_git_describe(pieces):
+ """TAG[-DISTANCE-gHEX][-dirty].
+
+ Like 'git describe --tags --dirty --always'.
+
+ Exceptions:
+ 1: no tags. HEX[-dirty] (note: no 'g' prefix)
+ """
+ if pieces["closest-tag"]:
+ rendered = pieces["closest-tag"]
+ if pieces["distance"]:
+ rendered += "-%d-g%s" % (pieces["distance"], pieces["short"])
+ else:
+ # exception #1
+ rendered = pieces["short"]
+ if pieces["dirty"]:
+ rendered += "-dirty"
+ return rendered
+
+
+def render_git_describe_long(pieces):
+ """TAG-DISTANCE-gHEX[-dirty].
+
+ Like 'git describe --tags --dirty --always -long'.
+ The distance/hash is unconditional.
+
+ Exceptions:
+ 1: no tags. HEX[-dirty] (note: no 'g' prefix)
+ """
+ if pieces["closest-tag"]:
+ rendered = pieces["closest-tag"]
+ rendered += "-%d-g%s" % (pieces["distance"], pieces["short"])
+ else:
+ # exception #1
+ rendered = pieces["short"]
+ if pieces["dirty"]:
+ rendered += "-dirty"
+ return rendered
+
+
+def render(pieces, style):
+ """Render the given version pieces into the requested style."""
+ if pieces["error"]:
+ return {"version": "unknown",
+ "full-revisionid": pieces.get("long"),
+ "dirty": None,
+ "error": pieces["error"],
+ "date": None}
+
+ if not style or style == "default":
+ style = "pep440" # the default
+
+ if style == "pep440":
+ rendered = render_pep440(pieces)
+ elif style == "pep440-pre":
+ rendered = render_pep440_pre(pieces)
+ elif style == "pep440-post":
+ rendered = render_pep440_post(pieces)
+ elif style == "pep440-old":
+ rendered = render_pep440_old(pieces)
+ elif style == "git-describe":
+ rendered = render_git_describe(pieces)
+ elif style == "git-describe-long":
+ rendered = render_git_describe_long(pieces)
+ else:
+ raise ValueError("unknown style '%s'" % style)
+
+ return {"version": rendered, "full-revisionid": pieces["long"],
+ "dirty": pieces["dirty"], "error": None,
+ "date": pieces.get("date")}
+
+
+class VersioneerBadRootError(Exception):
+ """The project root directory is unknown or missing key files."""
+
+
+def get_versions(verbose=False):
+ """Get the project version from whatever source is available.
+
+ Returns dict with two keys: 'version' and 'full'.
+ """
+ if "versioneer" in sys.modules:
+ # see the discussion in cmdclass.py:get_cmdclass()
+ del sys.modules["versioneer"]
+
+ root = get_root()
+ cfg = get_config_from_root(root)
+
+ assert cfg.VCS is not None, "please set [versioneer]VCS= in setup.cfg"
+ handlers = HANDLERS.get(cfg.VCS)
+ assert handlers, "unrecognized VCS '%s'" % cfg.VCS
+ verbose = verbose or cfg.verbose
+ assert cfg.versionfile_source is not None, \
+ "please set versioneer.versionfile_source"
+ assert cfg.tag_prefix is not None, "please set versioneer.tag_prefix"
+
+ versionfile_abs = os.path.join(root, cfg.versionfile_source)
+
+ # extract version from first of: _version.py, VCS command (e.g. 'git
+ # describe'), parentdir. This is meant to work for developers using a
+ # source checkout, for users of a tarball created by 'setup.py sdist',
+ # and for users of a tarball/zipball created by 'git archive' or github's
+ # download-from-tag feature or the equivalent in other VCSes.
+
+ get_keywords_f = handlers.get("get_keywords")
+ from_keywords_f = handlers.get("keywords")
+ if get_keywords_f and from_keywords_f:
+ try:
+ keywords = get_keywords_f(versionfile_abs)
+ ver = from_keywords_f(keywords, cfg.tag_prefix, verbose)
+ if verbose:
+ print("got version from expanded keyword %s" % ver)
+ return ver
+ except NotThisMethod:
+ pass
+
+ try:
+ ver = versions_from_file(versionfile_abs)
+ if verbose:
+ print("got version from file %s %s" % (versionfile_abs, ver))
+ return ver
+ except NotThisMethod:
+ pass
+
+ from_vcs_f = handlers.get("pieces_from_vcs")
+ if from_vcs_f:
+ try:
+ pieces = from_vcs_f(cfg.tag_prefix, root, verbose)
+ ver = render(pieces, cfg.style)
+ if verbose:
+ print("got version from VCS %s" % ver)
+ return ver
+ except NotThisMethod:
+ pass
+
+ try:
+ if cfg.parentdir_prefix:
+ ver = versions_from_parentdir(cfg.parentdir_prefix, root, verbose)
+ if verbose:
+ print("got version from parentdir %s" % ver)
+ return ver
+ except NotThisMethod:
+ pass
+
+ if verbose:
+ print("unable to compute version")
+
+ return {"version": "0+unknown", "full-revisionid": None,
+ "dirty": None, "error": "unable to compute version",
+ "date": None}
+
+
+def get_version():
+ """Get the short version string for this project."""
+ return get_versions()["version"]
+
+
+def get_cmdclass():
+ """Get the custom setuptools/distutils subclasses used by Versioneer."""
+ if "versioneer" in sys.modules:
+ del sys.modules["versioneer"]
+ # this fixes the "python setup.py develop" case (also 'install' and
+ # 'easy_install .'), in which subdependencies of the main project are
+ # built (using setup.py bdist_egg) in the same python process. Assume
+ # a main project A and a dependency B, which use different versions
+ # of Versioneer. A's setup.py imports A's Versioneer, leaving it in
+ # sys.modules by the time B's setup.py is executed, causing B to run
+ # with the wrong versioneer. Setuptools wraps the sub-dep builds in a
+ # sandbox that restores sys.modules to it's pre-build state, so the
+ # parent is protected against the child's "import versioneer". By
+ # removing ourselves from sys.modules here, before the child build
+ # happens, we protect the child from the parent's versioneer too.
+ # Also see https://github.com/warner/python-versioneer/issues/52
+
+ cmds = {}
+
+ # we add "version" to both distutils and setuptools
+ from distutils.core import Command
+
+ class cmd_version(Command):
+ description = "report generated version string"
+ user_options = []
+ boolean_options = []
+
+ def initialize_options(self):
+ pass
+
+ def finalize_options(self):
+ pass
+
+ def run(self):
+ vers = get_versions(verbose=True)
+ print("Version: %s" % vers["version"])
+ print(" full-revisionid: %s" % vers.get("full-revisionid"))
+ print(" dirty: %s" % vers.get("dirty"))
+ print(" date: %s" % vers.get("date"))
+ if vers["error"]:
+ print(" error: %s" % vers["error"])
+ cmds["version"] = cmd_version
+
+ # we override "build_py" in both distutils and setuptools
+ #
+ # most invocation pathways end up running build_py:
+ # distutils/build -> build_py
+ # distutils/install -> distutils/build ->..
+ # setuptools/bdist_wheel -> distutils/install ->..
+ # setuptools/bdist_egg -> distutils/install_lib -> build_py
+ # setuptools/install -> bdist_egg ->..
+ # setuptools/develop -> ?
+ # pip install:
+ # copies source tree to a tempdir before running egg_info/etc
+ # if .git isn't copied too, 'git describe' will fail
+ # then does setup.py bdist_wheel, or sometimes setup.py install
+ # setup.py egg_info -> ?
+
+ # we override different "build_py" commands for both environments
+ if "setuptools" in sys.modules:
+ from setuptools.command.build_py import build_py as _build_py
+ else:
+ from distutils.command.build_py import build_py as _build_py
+
+ class cmd_build_py(_build_py):
+ def run(self):
+ root = get_root()
+ cfg = get_config_from_root(root)
+ versions = get_versions()
+ _build_py.run(self)
+ # now locate _version.py in the new build/ directory and replace
+ # it with an updated value
+ if cfg.versionfile_build:
+ target_versionfile = os.path.join(self.build_lib,
+ cfg.versionfile_build)
+ print("UPDATING %s" % target_versionfile)
+ write_to_version_file(target_versionfile, versions)
+ cmds["build_py"] = cmd_build_py
+
+ if "cx_Freeze" in sys.modules: # cx_freeze enabled?
+ from cx_Freeze.dist import build_exe as _build_exe
+ # nczeczulin reports that py2exe won't like the pep440-style string
+ # as FILEVERSION, but it can be used for PRODUCTVERSION, e.g.
+ # setup(console=[{
+ # "version": versioneer.get_version().split("+", 1)[0], # FILEVERSION
+ # "product_version": versioneer.get_version(),
+ # ...
+
+ class cmd_build_exe(_build_exe):
+ def run(self):
+ root = get_root()
+ cfg = get_config_from_root(root)
+ versions = get_versions()
+ target_versionfile = cfg.versionfile_source
+ print("UPDATING %s" % target_versionfile)
+ write_to_version_file(target_versionfile, versions)
+
+ _build_exe.run(self)
+ os.unlink(target_versionfile)
+ with open(cfg.versionfile_source, "w") as f:
+ LONG = LONG_VERSION_PY[cfg.VCS]
+ f.write(LONG %
+ {"DOLLAR": "$",
+ "STYLE": cfg.style,
+ "TAG_PREFIX": cfg.tag_prefix,
+ "PARENTDIR_PREFIX": cfg.parentdir_prefix,
+ "VERSIONFILE_SOURCE": cfg.versionfile_source,
+ })
+ cmds["build_exe"] = cmd_build_exe
+ del cmds["build_py"]
+
+ if 'py2exe' in sys.modules: # py2exe enabled?
+ try:
+ from py2exe.distutils_buildexe import py2exe as _py2exe # py3
+ except ImportError:
+ from py2exe.build_exe import py2exe as _py2exe # py2
+
+ class cmd_py2exe(_py2exe):
+ def run(self):
+ root = get_root()
+ cfg = get_config_from_root(root)
+ versions = get_versions()
+ target_versionfile = cfg.versionfile_source
+ print("UPDATING %s" % target_versionfile)
+ write_to_version_file(target_versionfile, versions)
+
+ _py2exe.run(self)
+ os.unlink(target_versionfile)
+ with open(cfg.versionfile_source, "w") as f:
+ LONG = LONG_VERSION_PY[cfg.VCS]
+ f.write(LONG %
+ {"DOLLAR": "$",
+ "STYLE": cfg.style,
+ "TAG_PREFIX": cfg.tag_prefix,
+ "PARENTDIR_PREFIX": cfg.parentdir_prefix,
+ "VERSIONFILE_SOURCE": cfg.versionfile_source,
+ })
+ cmds["py2exe"] = cmd_py2exe
+
+ # we override different "sdist" commands for both environments
+ if "setuptools" in sys.modules:
+ from setuptools.command.sdist import sdist as _sdist
+ else:
+ from distutils.command.sdist import sdist as _sdist
+
+ class cmd_sdist(_sdist):
+ def run(self):
+ versions = get_versions()
+ self._versioneer_generated_versions = versions
+ # unless we update this, the command will keep using the old
+ # version
+ self.distribution.metadata.version = versions["version"]
+ return _sdist.run(self)
+
+ def make_release_tree(self, base_dir, files):
+ root = get_root()
+ cfg = get_config_from_root(root)
+ _sdist.make_release_tree(self, base_dir, files)
+ # now locate _version.py in the new base_dir directory
+ # (remembering that it may be a hardlink) and replace it with an
+ # updated value
+ target_versionfile = os.path.join(base_dir, cfg.versionfile_source)
+ print("UPDATING %s" % target_versionfile)
+ write_to_version_file(target_versionfile,
+ self._versioneer_generated_versions)
+ cmds["sdist"] = cmd_sdist
+
+ return cmds
+
+
+CONFIG_ERROR = """
+setup.cfg is missing the necessary Versioneer configuration. You need
+a section like:
+
+ [versioneer]
+ VCS = git
+ style = pep440
+ versionfile_source = src/myproject/_version.py
+ versionfile_build = myproject/_version.py
+ tag_prefix =
+ parentdir_prefix = myproject-
+
+You will also need to edit your setup.py to use the results:
+
+ import versioneer
+ setup(version=versioneer.get_version(),
+ cmdclass=versioneer.get_cmdclass(), ...)
+
+Please read the docstring in ./versioneer.py for configuration instructions,
+edit setup.cfg, and re-run the installer or 'python versioneer.py setup'.
+"""
+
+SAMPLE_CONFIG = """
+# See the docstring in versioneer.py for instructions. Note that you must
+# re-run 'versioneer.py setup' after changing this section, and commit the
+# resulting files.
+
+[versioneer]
+#VCS = git
+#style = pep440
+#versionfile_source =
+#versionfile_build =
+#tag_prefix =
+#parentdir_prefix =
+
+"""
+
+INIT_PY_SNIPPET = """
+from ._version import get_versions
+__version__ = get_versions()['version']
+del get_versions
+"""
+
+
+def do_setup():
+ """Main VCS-independent setup function for installing Versioneer."""
+ root = get_root()
+ try:
+ cfg = get_config_from_root(root)
+ except (EnvironmentError, configparser.NoSectionError,
+ configparser.NoOptionError) as e:
+ if isinstance(e, (EnvironmentError, configparser.NoSectionError)):
+ print("Adding sample versioneer config to setup.cfg",
+ file=sys.stderr)
+ with open(os.path.join(root, "setup.cfg"), "a") as f:
+ f.write(SAMPLE_CONFIG)
+ print(CONFIG_ERROR, file=sys.stderr)
+ return 1
+
+ print(" creating %s" % cfg.versionfile_source)
+ with open(cfg.versionfile_source, "w") as f:
+ LONG = LONG_VERSION_PY[cfg.VCS]
+ f.write(LONG % {"DOLLAR": "$",
+ "STYLE": cfg.style,
+ "TAG_PREFIX": cfg.tag_prefix,
+ "PARENTDIR_PREFIX": cfg.parentdir_prefix,
+ "VERSIONFILE_SOURCE": cfg.versionfile_source,
+ })
+
+ ipy = os.path.join(os.path.dirname(cfg.versionfile_source),
+ "__init__.py")
+ if os.path.exists(ipy):
+ try:
+ with open(ipy, "r") as f:
+ old = f.read()
+ except EnvironmentError:
+ old = ""
+ if INIT_PY_SNIPPET not in old:
+ print(" appending to %s" % ipy)
+ with open(ipy, "a") as f:
+ f.write(INIT_PY_SNIPPET)
+ else:
+ print(" %s unmodified" % ipy)
+ else:
+ print(" %s doesn't exist, ok" % ipy)
+ ipy = None
+
+ # Make sure both the top-level "versioneer.py" and versionfile_source
+ # (PKG/_version.py, used by runtime code) are in MANIFEST.in, so
+ # they'll be copied into source distributions. Pip won't be able to
+ # install the package without this.
+ manifest_in = os.path.join(root, "MANIFEST.in")
+ simple_includes = set()
+ try:
+ with open(manifest_in, "r") as f:
+ for line in f:
+ if line.startswith("include "):
+ for include in line.split()[1:]:
+ simple_includes.add(include)
+ except EnvironmentError:
+ pass
+ # That doesn't cover everything MANIFEST.in can do
+ # (http://docs.python.org/2/distutils/sourcedist.html#commands), so
+ # it might give some false negatives. Appending redundant 'include'
+ # lines is safe, though.
+ if "versioneer.py" not in simple_includes:
+ print(" appending 'versioneer.py' to MANIFEST.in")
+ with open(manifest_in, "a") as f:
+ f.write("include versioneer.py\n")
+ else:
+ print(" 'versioneer.py' already in MANIFEST.in")
+ if cfg.versionfile_source not in simple_includes:
+ print(" appending versionfile_source ('%s') to MANIFEST.in" %
+ cfg.versionfile_source)
+ with open(manifest_in, "a") as f:
+ f.write("include %s\n" % cfg.versionfile_source)
+ else:
+ print(" versionfile_source already in MANIFEST.in")
+
+ # Make VCS-specific changes. For git, this means creating/changing
+ # .gitattributes to mark _version.py for export-subst keyword
+ # substitution.
+ do_vcs_install(manifest_in, cfg.versionfile_source, ipy)
+ return 0
+
+
+def scan_setup_py():
+ """Validate the contents of setup.py against Versioneer's expectations."""
+ found = set()
+ setters = False
+ errors = 0
+ with open("setup.py", "r") as f:
+ for line in f.readlines():
+ if "import versioneer" in line:
+ found.add("import")
+ if "versioneer.get_cmdclass()" in line:
+ found.add("cmdclass")
+ if "versioneer.get_version()" in line:
+ found.add("get_version")
+ if "versioneer.VCS" in line:
+ setters = True
+ if "versioneer.versionfile_source" in line:
+ setters = True
+ if len(found) != 3:
+ print("")
+ print("Your setup.py appears to be missing some important items")
+ print("(but I might be wrong). Please make sure it has something")
+ print("roughly like the following:")
+ print("")
+ print(" import versioneer")
+ print(" setup( version=versioneer.get_version(),")
+ print(" cmdclass=versioneer.get_cmdclass(), ...)")
+ print("")
+ errors += 1
+ if setters:
+ print("You should remove lines like 'versioneer.VCS = ' and")
+ print("'versioneer.versionfile_source = ' . This configuration")
+ print("now lives in setup.cfg, and should be removed from setup.py")
+ print("")
+ errors += 1
+ return errors
+
+
+if __name__ == "__main__":
+ cmd = sys.argv[1]
+ if cmd == "setup":
+ errors = do_setup()
+ errors += scan_setup_py()
+ if errors:
+ sys.exit(1)
| add __version__ or other version information
I have not found a way to ask `alchemlyb` which version it is. Something like
```python
alchemlyb.__version__
```
would be useful.
Maybe use [versioneer](https://github.com/warner/python-versioneer) to be fancy and hip.
| alchemistry/alchemlyb | diff --git a/src/alchemlyb/tests/test_version.py b/src/alchemlyb/tests/test_version.py
new file mode 100644
index 0000000..4f2afc7
--- /dev/null
+++ b/src/alchemlyb/tests/test_version.py
@@ -0,0 +1,16 @@
+import alchemlyb
+
+def test_version():
+ try:
+ version = alchemlyb.__version__
+ except AttributeError:
+ raise AssertionError("alchemlyb does not have __version__")
+
+ assert len(version) > 0
+
+def test_version_get_versions():
+ import alchemlyb._version
+ version = alchemlyb._version.get_versions()
+
+ assert alchemlyb.__version__ == version["version"]
+
| {
"commit_name": "merge_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks",
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 1,
"test_score": 2
},
"num_modified_files": 4
} | 0.1 | {
"env_vars": null,
"env_yml_path": [
"environment.yml"
],
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": true,
"packages": "environment.yml",
"pip_packages": [
"pytest",
"pytest-cov",
"pytest-pep8"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.5",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | alabaster==0.7.12
-e git+https://github.com/alchemistry/alchemlyb.git@8915ece9daa2ad17094b2e61565bcfe128a374c7#egg=alchemlyb
attrs==22.1.0
Babel==2.9.0
certifi==2020.6.20
colorama==0.4.4
coverage==5.5
docutils==0.14
execnet==1.9.0
imagesize==1.3.0
importlib-metadata==2.1.3
iniconfig==1.1.1
Jinja2==2.11.3
MarkupSafe==1.0
numpy==1.15.2
packaging==20.9
pandas==0.23.4
pathlib2==2.3.7.post1
pep8==1.7.1
pluggy==0.13.1
py==1.11.0
Pygments==2.11.2
pymbar==3.1.0
pyparsing==2.4.7
pytest==6.1.2
pytest-cache==1.0
pytest-cov==2.12.1
pytest-pep8==1.0.6
python-dateutil==2.8.2
pytz==2021.3
requests==2.13.0
scikit-learn==0.20.0
scipy==1.1.0
six==1.16.0
snowballstemmer==2.1.0
Sphinx==3.5.3
sphinxcontrib-applehelp==1.0.2
sphinxcontrib-devhelp==1.0.2
sphinxcontrib-htmlhelp==1.0.3
sphinxcontrib-jsmath==1.0.1
sphinxcontrib-qthelp==1.0.3
sphinxcontrib-serializinghtml==1.1.5
toml==0.10.2
zipp==1.2.0
| name: alchemlyb
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- alabaster=0.7.12=pyhd3eb1b0_0
- babel=2.9.0=pyhd3eb1b0_0
- blas=1.0=openblas
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2020.6.20=pyhd3eb1b0_3
- colorama=0.4.4=pyhd3eb1b0_0
- docutils=0.14=py35hd11081d_0
- imagesize=1.3.0=pyhd3eb1b0_0
- jinja2=2.11.3=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgfortran-ng=7.5.0=ha8ba4b0_17
- libgfortran4=7.5.0=ha8ba4b0_17
- libgomp=11.2.0=h1234567_1
- libopenblas=0.3.18=hf726d26_0
- libstdcxx-ng=11.2.0=h1234567_1
- markupsafe=1.0=py35h14c3975_1
- ncurses=6.4=h6a678d5_0
- numpy=1.15.2=py35h99e49ec_0
- numpy-base=1.15.2=py35h2f8d375_0
- openssl=1.1.1w=h7f8727e_0
- packaging=20.9=pyhd3eb1b0_0
- pandas=0.23.4=py35h04863e7_0
- pip=10.0.1=py35_0
- pygments=2.11.2=pyhd3eb1b0_0
- pyparsing=2.4.7=pyhd3eb1b0_0
- python=3.5.6=h12debd9_1
- python-dateutil=2.8.2=pyhd3eb1b0_0
- pytz=2021.3=pyhd3eb1b0_0
- readline=8.2=h5eee18b_0
- requests=2.13.0=py35_0
- scikit-learn=0.20.0=py35h22eb022_1
- scipy=1.1.0=py35he2b7bc3_1
- setuptools=40.2.0=py35_0
- six=1.16.0=pyhd3eb1b0_1
- snowballstemmer=2.1.0=pyhd3eb1b0_0
- sphinx=3.5.3=pyhd3eb1b0_0
- sphinxcontrib-applehelp=1.0.2=pyhd3eb1b0_0
- sphinxcontrib-devhelp=1.0.2=pyhd3eb1b0_0
- sphinxcontrib-htmlhelp=1.0.3=pyhd3eb1b0_0
- sphinxcontrib-jsmath=1.0.1=pyhd3eb1b0_0
- sphinxcontrib-qthelp=1.0.3=pyhd3eb1b0_0
- sphinxcontrib-serializinghtml=1.1.5=pyhd3eb1b0_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- attrs==22.1.0
- coverage==5.5
- execnet==1.9.0
- importlib-metadata==2.1.3
- iniconfig==1.1.1
- pathlib2==2.3.7.post1
- pep8==1.7.1
- pluggy==0.13.1
- py==1.11.0
- pymbar==3.1.0
- pytest==6.1.2
- pytest-cache==1.0
- pytest-cov==2.12.1
- pytest-pep8==1.0.6
- toml==0.10.2
- zipp==1.2.0
prefix: /opt/conda/envs/alchemlyb
| [
"src/alchemlyb/tests/test_version.py::test_version",
"src/alchemlyb/tests/test_version.py::test_version_get_versions"
]
| []
| []
| []
| BSD 3-Clause "New" or "Revised" License | 1,872 | [
"MANIFEST.in",
"setup.py",
".gitattributes",
"src/alchemlyb/__init__.py",
"src/alchemlyb/_version.py",
"setup.cfg",
".coveragerc",
"versioneer.py"
]
| [
"MANIFEST.in",
"setup.py",
".gitattributes",
"src/alchemlyb/__init__.py",
"src/alchemlyb/_version.py",
"setup.cfg",
".coveragerc",
"versioneer.py"
]
|
berkerpeksag__astor-88 | abdd707e215d57178aae5ea2dd7a8ffe327ef272 | 2017-11-11 04:30:24 | 991e6e9436c2512241e036464f99114438932d85 | diff --git a/.travis.yml b/.travis.yml
index 419cb0e..64bedd8 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -9,6 +9,9 @@ python:
- 3.6
- pypy
- pypy3.3-5.2-alpha1
+matrix:
+ allow_failures:
+ - python: 2.6
cache: pip
install:
- pip install tox-travis
diff --git a/astor/__init__.py b/astor/__init__.py
index de48a5c..bb96de4 100644
--- a/astor/__init__.py
+++ b/astor/__init__.py
@@ -19,7 +19,7 @@ from .op_util import get_op_symbol, get_op_precedence # NOQA
from .op_util import symbol_data # NOQA
from .tree_walk import TreeWalk # NOQA
-__version__ = '0.6.1'
+__version__ = '0.6.2'
parse_file = code_to_ast.parse_file
@@ -34,6 +34,7 @@ codetoast = code_to_ast
dump = dump_tree
all_symbols = symbol_data
treewalk = tree_walk
+codegen = code_gen
"""
exec(deprecated)
diff --git a/docs/changelog.rst b/docs/changelog.rst
index fb259ff..54bc9b7 100644
--- a/docs/changelog.rst
+++ b/docs/changelog.rst
@@ -2,6 +2,25 @@
Release Notes
=============
+0.6.2 - 2017-11-11
+------------------
+
+Bug fixes
+---------
+
+* Restore backwards compatibility that was broken after 0.6.1.
+ You can now continue to use the following pattern::
+
+ import astor
+
+ class SpamCodeGenerator(astor.codegen.SourceGenerator):
+ ...
+
+ (Reported by Dan Moldovan and fixed by Berker Peksag in `Issue 87`_.)
+
+.. _`Issue 87`: https://github.com/berkerpeksag/astor/issues/87
+
+
0.6.1 - 2017-11-11
------------------
diff --git a/tox.ini b/tox.ini
index 5f8e1ae..5149f5c 100644
--- a/tox.ini
+++ b/tox.ini
@@ -4,7 +4,7 @@ skipsdist = True
[testenv]
usedevelop = True
-commands = nosetests -v
+commands = nosetests -v --nocapture {posargs}
deps =
-rrequirements-tox.txt
py2{6,7},pypy: unittest2
| Suspected API breakage from 0.6 to 0.6.1
Hi, our builds started failing with `AttributeError: module 'astor' has no attribute 'codegen'`:
https://travis-ci.org/google/tangent/jobs/300437272
I wonder if it's related to the new 0.6.1 release? | berkerpeksag/astor | diff --git a/tests/support.py b/tests/support.py
new file mode 100644
index 0000000..db8c4ea
--- /dev/null
+++ b/tests/support.py
@@ -0,0 +1,44 @@
+import importlib
+import sys
+
+
+def _save_and_remove_module(name, orig_modules):
+ """Helper function to save and remove a module from sys.modules
+ Raise ImportError if the module can't be imported.
+ """
+ # try to import the module and raise an error if it can't be imported
+ if name not in sys.modules:
+ __import__(name)
+ del sys.modules[name]
+ for modname in list(sys.modules):
+ if modname == name or modname.startswith(name + '.'):
+ orig_modules[modname] = sys.modules[modname]
+ del sys.modules[modname]
+
+
+def import_fresh_module(name, fresh=(), blocked=()):
+ """Import and return a module, deliberately bypassing sys.modules.
+
+ This function imports and returns a fresh copy of the named Python module
+ by removing the named module from sys.modules before doing the import.
+ Note that unlike reload, the original module is not affected by
+ this operation.
+ """
+ orig_modules = {}
+ names_to_remove = []
+ _save_and_remove_module(name, orig_modules)
+ try:
+ for fresh_name in fresh:
+ _save_and_remove_module(fresh_name, orig_modules)
+ for blocked_name in blocked:
+ if not _save_and_block_module(blocked_name, orig_modules):
+ names_to_remove.append(blocked_name)
+ fresh_module = importlib.import_module(name)
+ except ImportError:
+ fresh_module = None
+ finally:
+ for orig_name, module in orig_modules.items():
+ sys.modules[orig_name] = module
+ for name_to_remove in names_to_remove:
+ del sys.modules[name_to_remove]
+ return fresh_module
diff --git a/tests/test_misc.py b/tests/test_misc.py
index 983de40..7a7f5a4 100644
--- a/tests/test_misc.py
+++ b/tests/test_misc.py
@@ -8,6 +8,8 @@ except ImportError:
import astor
+from .support import import_fresh_module
+
class GetSymbolTestCase(unittest.TestCase):
@@ -22,16 +24,27 @@ class PublicAPITestCase(unittest.TestCase):
def test_aliases(self):
self.assertIs(astor.parse_file, astor.code_to_ast.parse_file)
-
-class DeprecationTestCase(unittest.TestCase):
-
- def test_deprecate_parsefile(self):
- with self.assertWarns(DeprecationWarning):
- astor.parsefile(__file__)
-
- def test_deprecate_astor_codegen(self):
- with self.assertWarns(DeprecationWarning):
+ def test_codegen_from_root(self):
+ with self.assertWarns(DeprecationWarning) as cm:
+ astor = import_fresh_module('astor')
+ astor.codegen.SourceGenerator
+ self.assertEqual(len(cm.warnings), 1)
+ # This message comes from 'astor/__init__.py'.
+ self.assertEqual(
+ str(cm.warnings[0].message),
+ 'astor.codegen is deprecated. Please use astor.code_gen.'
+ )
+
+ def test_codegen_as_submodule(self):
+ with self.assertWarns(DeprecationWarning) as cm:
import astor.codegen
+ self.assertEqual(len(cm.warnings), 1)
+ # This message comes from 'astor/codegen.py'.
+ self.assertEqual(
+ str(cm.warnings[0].message),
+ 'astor.codegen module is deprecated. Please import '
+ 'astor.code_gen module instead.'
+ )
class FastCompareTestCase(unittest.TestCase):
| {
"commit_name": "merge_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 2,
"test_score": 2
},
"num_modified_files": 4
} | 0.6 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"nose",
"pytest"
],
"pre_install": null,
"python": "3.6",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | -e git+https://github.com/berkerpeksag/astor.git@abdd707e215d57178aae5ea2dd7a8ffe327ef272#egg=astor
attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work
certifi==2021.5.30
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work
nose==1.3.7
packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work
pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pytest==6.2.4
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
| name: astor
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=21.4.0=pyhd3eb1b0_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- importlib-metadata=4.8.1=py36h06a4308_0
- importlib_metadata=4.8.1=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- more-itertools=8.12.0=pyhd3eb1b0_0
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=21.3=pyhd3eb1b0_0
- pip=21.2.2=py36h06a4308_0
- pluggy=0.13.1=py36h06a4308_0
- py=1.11.0=pyhd3eb1b0_0
- pyparsing=3.0.4=pyhd3eb1b0_0
- pytest=6.2.4=py36h06a4308_2
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- toml=0.10.2=pyhd3eb1b0_0
- typing_extensions=4.1.1=pyh06a4308_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zipp=3.6.0=pyhd3eb1b0_0
- zlib=1.2.13=h5eee18b_1
- pip:
- nose==1.3.7
prefix: /opt/conda/envs/astor
| [
"tests/test_misc.py::PublicAPITestCase::test_codegen_from_root"
]
| []
| [
"tests/test_misc.py::GetSymbolTestCase::test_get_mat_mult",
"tests/test_misc.py::PublicAPITestCase::test_aliases",
"tests/test_misc.py::PublicAPITestCase::test_codegen_as_submodule",
"tests/test_misc.py::FastCompareTestCase::test_fast_compare"
]
| []
| BSD 3-Clause "New" or "Revised" License | 1,875 | [
".travis.yml",
"tox.ini",
"docs/changelog.rst",
"astor/__init__.py"
]
| [
".travis.yml",
"tox.ini",
"docs/changelog.rst",
"astor/__init__.py"
]
|
|
hylang__hy-1456 | 97987d739c4649d1722d489d3771f558b145a0fb | 2017-11-11 23:17:08 | 5c720c0110908e3f47dba2e4cc1c820d16f359a1 | diff --git a/hy/models.py b/hy/models.py
index 3a769e86..fda7789f 100644
--- a/hy/models.py
+++ b/hy/models.py
@@ -179,7 +179,7 @@ if not PY3: # do not add long on python3
def check_inf_nan_cap(arg, value):
if isinstance(arg, string_types):
- if isinf(value) and "Inf" not in arg:
+ if isinf(value) and "i" in arg.lower() and "Inf" not in arg:
raise ValueError('Inf must be capitalized as "Inf"')
if isnan(value) and "NaN" not in arg:
raise ValueError('NaN must be capitalized as "NaN"')
| 1e1000 should not be a symbol
Hy counts `1e308` as a floating-point number, but `2e308` as a symbol.
```Python
=> (type 1e308)
type(1e+308)
<class 'float'>
=> (type 2e308)
type(2e308)
Traceback (most recent call last):
File "c:\users\me\documents\github\hy\hy\importer.py", line 201, in hy_eval
return eval(ast_compile(expr, "<eval>", "eval"), namespace)
File "<eval>", line 1, in <module>
NameError: name '2e308' is not defined
```
This is inconsistent. Float literals that are too large should be `inf`, because that's how Python does it.
```Python
>>> 1.7e308
1.7e+308
>>> 1.8e308
inf
``` | hylang/hy | diff --git a/tests/test_lex.py b/tests/test_lex.py
index bdb412a1..6efeb605 100644
--- a/tests/test_lex.py
+++ b/tests/test_lex.py
@@ -103,6 +103,12 @@ def test_lex_expression_float():
assert objs == [HyExpression([HySymbol("foo"), HyFloat(1.e7)])]
+def test_lex_big_float():
+ # https://github.com/hylang/hy/issues/1448
+ assert tokenize("1e900") == [HyFloat(1e900)]
+ assert tokenize("1e900-1e900j") == [HyComplex(1e900, -1e900)]
+
+
def test_lex_nan_and_inf():
assert isnan(tokenize("NaN")[0])
| {
"commit_name": "head_commit",
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 1,
"test_score": 0
},
"num_modified_files": 1
} | 0.13 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"flake8",
"tox",
"Pygments",
"Sphinx",
"sphinx_rtd_theme"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.6",
"reqs_path": [
"requirements-dev.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | alabaster==0.7.13
appdirs==1.4.4
args==0.1.0
astor==0.8.1
attrs==22.2.0
Babel==2.11.0
certifi==2021.5.30
charset-normalizer==2.0.12
clint==0.5.1
coverage==6.2
distlib==0.3.9
docutils==0.17.1
filelock==3.4.1
flake8==5.0.4
-e git+https://github.com/hylang/hy.git@97987d739c4649d1722d489d3771f558b145a0fb#egg=hy
idna==3.10
imagesize==1.4.1
importlib-metadata==4.2.0
importlib-resources==5.4.0
iniconfig==1.1.1
Jinja2==3.0.3
MarkupSafe==2.0.1
mccabe==0.7.0
packaging==21.3
platformdirs==2.4.0
pluggy==1.0.0
py==1.11.0
pycodestyle==2.9.1
pyflakes==2.5.0
Pygments==2.14.0
pyparsing==3.1.4
pytest==7.0.1
pytz==2025.2
requests==2.27.1
rply==0.7.8
six==1.17.0
snowballstemmer==2.2.0
Sphinx==4.3.2
sphinx-rtd-theme==1.3.0
sphinxcontrib-applehelp==1.0.2
sphinxcontrib-devhelp==1.0.2
sphinxcontrib-htmlhelp==2.0.0
sphinxcontrib-jquery==4.1
sphinxcontrib-jsmath==1.0.1
sphinxcontrib-qthelp==1.0.3
sphinxcontrib-serializinghtml==1.1.5
toml==0.10.2
tomli==1.2.3
tox==3.28.0
typing_extensions==4.1.1
urllib3==1.26.20
virtualenv==20.16.2
zipp==3.6.0
| name: hy
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- alabaster==0.7.13
- appdirs==1.4.4
- args==0.1.0
- astor==0.8.1
- attrs==22.2.0
- babel==2.11.0
- charset-normalizer==2.0.12
- clint==0.5.1
- coverage==6.2
- distlib==0.3.9
- docutils==0.17.1
- filelock==3.4.1
- flake8==5.0.4
- idna==3.10
- imagesize==1.4.1
- importlib-metadata==4.2.0
- importlib-resources==5.4.0
- iniconfig==1.1.1
- jinja2==3.0.3
- markupsafe==2.0.1
- mccabe==0.7.0
- packaging==21.3
- platformdirs==2.4.0
- pluggy==1.0.0
- py==1.11.0
- pycodestyle==2.9.1
- pyflakes==2.5.0
- pygments==2.14.0
- pyparsing==3.1.4
- pytest==7.0.1
- pytz==2025.2
- requests==2.27.1
- rply==0.7.8
- six==1.17.0
- snowballstemmer==2.2.0
- sphinx==4.3.2
- sphinx-rtd-theme==1.3.0
- sphinxcontrib-applehelp==1.0.2
- sphinxcontrib-devhelp==1.0.2
- sphinxcontrib-htmlhelp==2.0.0
- sphinxcontrib-jquery==4.1
- sphinxcontrib-jsmath==1.0.1
- sphinxcontrib-qthelp==1.0.3
- sphinxcontrib-serializinghtml==1.1.5
- toml==0.10.2
- tomli==1.2.3
- tox==3.28.0
- typing-extensions==4.1.1
- urllib3==1.26.20
- virtualenv==20.16.2
- zipp==3.6.0
prefix: /opt/conda/envs/hy
| [
"tests/test_lex.py::test_lex_big_float"
]
| []
| [
"tests/test_lex.py::test_lex_exception",
"tests/test_lex.py::test_unbalanced_exception",
"tests/test_lex.py::test_lex_single_quote_err",
"tests/test_lex.py::test_lex_expression_symbols",
"tests/test_lex.py::test_lex_expression_strings",
"tests/test_lex.py::test_lex_expression_integer",
"tests/test_lex.py::test_lex_symbols",
"tests/test_lex.py::test_lex_strings",
"tests/test_lex.py::test_lex_bracket_strings",
"tests/test_lex.py::test_lex_integers",
"tests/test_lex.py::test_lex_fractions",
"tests/test_lex.py::test_lex_expression_float",
"tests/test_lex.py::test_lex_nan_and_inf",
"tests/test_lex.py::test_lex_expression_complex",
"tests/test_lex.py::test_lex_digit_separators",
"tests/test_lex.py::test_lex_bad_attrs",
"tests/test_lex.py::test_lex_line_counting",
"tests/test_lex.py::test_lex_line_counting_multi",
"tests/test_lex.py::test_lex_line_counting_multi_inner",
"tests/test_lex.py::test_dicts",
"tests/test_lex.py::test_sets",
"tests/test_lex.py::test_nospace",
"tests/test_lex.py::test_escapes",
"tests/test_lex.py::test_unicode_escapes",
"tests/test_lex.py::test_complex",
"tests/test_lex.py::test_tag_macro",
"tests/test_lex.py::test_lex_comment_382",
"tests/test_lex.py::test_lex_mangling_star",
"tests/test_lex.py::test_lex_mangling_hyphen",
"tests/test_lex.py::test_lex_mangling_qmark",
"tests/test_lex.py::test_lex_mangling_bang",
"tests/test_lex.py::test_unmangle",
"tests/test_lex.py::test_simple_cons",
"tests/test_lex.py::test_dotted_list",
"tests/test_lex.py::test_cons_list",
"tests/test_lex.py::test_discard"
]
| []
| MIT License | 1,877 | [
"hy/models.py"
]
| [
"hy/models.py"
]
|
|
nose-devs__nose2-369 | 862b130652b9118eb8d5681923c04edb000245d3 | 2017-11-11 23:49:52 | 90945cad86df2d11cc9332219ee85aca97311f6e | coveralls:
[](https://coveralls.io/builds/14156452)
Coverage increased (+0.2%) to 87.69% when pulling **d436976ece996497dac644fc59a40b2ead323ae7 on ptthiem:issue/167** into **862b130652b9118eb8d5681923c04edb000245d3 on nose-devs:master**.
ptthiem: There is a small warning being thrown by the test, but it seems to be working. I'll check it tomorrow afternoon
coveralls:
[](https://coveralls.io/builds/14157959)
Coverage increased (+0.07%) to 87.527% when pulling **d436976ece996497dac644fc59a40b2ead323ae7 on ptthiem:issue/167** into **862b130652b9118eb8d5681923c04edb000245d3 on nose-devs:master**.
coveralls:
[](https://coveralls.io/builds/14158069)
Coverage increased (+0.2%) to 87.636% when pulling **6a73c8057173469da7eae5a0d4c9b0a07e9867bf on ptthiem:issue/167** into **862b130652b9118eb8d5681923c04edb000245d3 on nose-devs:master**.
| diff --git a/nose2/plugins/layers.py b/nose2/plugins/layers.py
index 43025ca..eda14dc 100644
--- a/nose2/plugins/layers.py
+++ b/nose2/plugins/layers.py
@@ -235,6 +235,9 @@ class LayerReporter(events.Plugin):
if event.errorList and hasattr(event.test, 'layer'):
# walk back layers to build full description
self.describeLayers(event)
+ # we need to remove "\n" from description to keep a well indented report when tests have docstrings
+ # see https://github.com/nose-devs/nose2/issues/327 for more information
+ event.description = event.description.replace('\n', ' ')
def describeLayers(self, event):
desc = [event.description]
diff --git a/nose2/plugins/mp.py b/nose2/plugins/mp.py
index a8346d0..b712bb3 100644
--- a/nose2/plugins/mp.py
+++ b/nose2/plugins/mp.py
@@ -80,8 +80,8 @@ class MultiProcess(events.Plugin):
if testid.startswith(failed_import_id):
self.cases[testid].run(result_)
- # XXX The length of the filtered list needs to be known
- # for _startProcs, until this can be cleaned up. This
+ # XXX Process-Handling: The length of the filtered list needs to be
+ # known for _startProcs, until this can be cleaned up. This
# wasn't the best way to deal with too few tests
flat = [x for x in flat if not x.startswith(failed_import_id)]
procs = self._startProcs(len(flat))
@@ -91,22 +91,26 @@ class MultiProcess(events.Plugin):
if not flat:
break
caseid = flat.pop(0)
+ # NOTE: it throws errors on broken pipes and bad serialization
conn.send(caseid)
rdrs = [conn for proc, conn in procs if proc.is_alive()]
while flat or rdrs:
ready, _, _ = select.select(rdrs, [], [], self.testRunTimeout)
for conn in ready:
- # XXX proc could be dead
+ # XXX Process-Handling: If we get an EOFError on receive the
+ # process finished= or we lost the process and the test it was
+ # working on. Also do we rebuild the process?
try:
remote_events = conn.recv()
except EOFError:
# probably dead/12
log.warning("Subprocess connection closed unexpectedly")
- continue # XXX or die?
+ continue
+ # If remote_events is None, the process exited normally,
+ # which should mean that we didn't any more tests for it.
if remote_events is None:
- # XXX proc is done, how to mark it dead?
log.debug("Conn closed %s", conn)
rdrs.remove(conn)
continue
@@ -119,9 +123,10 @@ class MultiProcess(events.Plugin):
self._localize(event)
getattr(self.session.hooks, hook)(event)
- # send a new test to the worker if there is one left
+ # Send the next test_id
+ # NOTE: send throws errors on broken pipes and bad serialization
if not flat:
- # if there isn't send None - it's the 'done' flag
+ # If there are no more, send None - it's the 'done' flag
conn.send(None)
continue
caseid = flat.pop(0)
@@ -129,6 +134,7 @@ class MultiProcess(events.Plugin):
for _, conn in procs:
conn.close()
+
# ensure we wait until all processes are done before
# exiting, to allow plugins running there to finalize
for proc, _ in procs:
@@ -174,7 +180,7 @@ class MultiProcess(events.Plugin):
return parent_conn
def _startProcs(self, test_count):
- # XXX create session export
+ # Create session export
session_export = self._exportSession()
procs = []
count = min(test_count, self.procs)
@@ -190,11 +196,15 @@ class MultiProcess(events.Plugin):
return procs
def _flatten(self, suite):
- # XXX
- # examine suite tests to find out if they have class
- # or module fixtures and group them that way into names
- # of test classes or modules
- # ALSO record all test cases in self.cases
+ """
+ Flatten test-suite into list of IDs, AND record all test case
+ into self.cases
+
+ CAVEAT: Due to current limitation of the MP plugin, examine the suite
+ tests to find out if they have class or module fixtures and
+ group them that way into name of test classes or module.
+ This is aid in their dispatch.
+ """
log.debug("Flattening test into list of IDs")
mods = {}
classes = {}
@@ -244,19 +254,27 @@ class MultiProcess(events.Plugin):
"main process" % event.test))._tests[0]
def _exportSession(self):
- # argparse isn't pickleable
- # no plugin instances
- # no hooks
+ """
+ Generate the session information passed to work process.
+
+ CAVEAT: The entire contents of which *MUST* be pickeable
+ and safe to use in the subprocess.
+
+ This probably includes:
+ * No argparse namespaces/named-tuples
+ * No plugin instances
+ * No hokes
+ :return:
+ """
export = {'config': self.session.config,
'verbosity': self.session.verbosity,
'startDir': self.session.startDir,
'topLevelDir': self.session.topLevelDir,
'logLevel': self.session.logLevel,
- # XXX classes or modules?
'pluginClasses': []}
- # XXX fire registerInSubprocess -- add those plugin classes
- # (classes must be pickleable!)
- event = RegisterInSubprocessEvent() # FIXME should be own event type
+ event = RegisterInSubprocessEvent()
+ # fire registerInSubprocess on plugins -- add those plugin classes
+ # CAVEAT: classes must be pickleable!
self.session.hooks.registerInSubprocess(event)
export['pluginClasses'].extend(event.pluginClasses)
return export
@@ -268,31 +286,16 @@ def procserver(session_export, conn):
rlog.setLevel(session_export['logLevel'])
# make a real session from the "session" we got
- ssn = session.Session()
- ssn.config = session_export['config']
- ssn.hooks = RecordingPluginInterface()
- ssn.verbosity = session_export['verbosity']
- ssn.startDir = session_export['startDir']
- ssn.topLevelDir = session_export['topLevelDir']
- ssn.prepareSysPath()
- loader_ = loader.PluggableTestLoader(ssn)
- ssn.testLoader = loader_
- result_ = result.PluggableTestResult(ssn)
- ssn.testResult = result_
- runner_ = runner.PluggableTestRunner(ssn) # needed??
- ssn.testRunner = runner_
- # load and register plugins
- ssn.plugins = [
- plugin(session=ssn) for plugin in session_export['pluginClasses']]
- rlog.debug("Plugins loaded: %s", ssn.plugins)
- for plugin in ssn.plugins:
- plugin.register()
- rlog.debug("Registered %s in subprocess", plugin)
+ ssn = import_session(rlog, session_export)
if isinstance(conn, collections.Sequence):
conn = connection.Client(conn[:2], authkey=conn[2])
- event = SubprocessEvent(loader_, result_, runner_, ssn.plugins, conn)
+ event = SubprocessEvent(ssn.testLoader,
+ ssn.testResult,
+ ssn.testRunner,
+ ssn.plugins,
+ conn)
res = ssn.hooks.startSubprocess(event)
if event.handled and not res:
conn.send(None)
@@ -308,7 +311,7 @@ def procserver(session_export, conn):
# deal with the case that testid is something other
# than a simple string.
test = event.loader.loadTestsFromName(testid)
- # xxx try/except?
+ # XXX If there a need to protect the loop? try/except?
rlog.debug("Execute test %s (%s)", testid, test)
executor(test, event.result)
events = [e for e in ssn.hooks.flush()]
@@ -319,6 +322,38 @@ def procserver(session_export, conn):
ssn.hooks.stopSubprocess(event)
+def import_session(rlog, session_export):
+ ssn = session.Session()
+ ssn.config = session_export['config']
+ ssn.hooks = RecordingPluginInterface()
+ ssn.verbosity = session_export['verbosity']
+ ssn.startDir = session_export['startDir']
+ ssn.topLevelDir = session_export['topLevelDir']
+ ssn.prepareSysPath()
+ loader_ = loader.PluggableTestLoader(ssn)
+ ssn.testLoader = loader_
+ result_ = result.PluggableTestResult(ssn)
+ ssn.testResult = result_
+ runner_ = runner.PluggableTestRunner(ssn) # needed??
+ ssn.testRunner = runner_
+ # load and register plugins, forcing multiprocess to the end
+ ssn.plugins = [
+ plugin(session=ssn) for plugin in session_export['pluginClasses']
+ if plugin is not MultiProcess
+ ]
+ rlog.debug("Plugins loaded: %s", ssn.plugins)
+
+ for plugin in ssn.plugins:
+ plugin.register()
+ rlog.debug("Registered %s in subprocess", plugin)
+
+ # instantiating the plugin will register it.
+ ssn.plugins.append(MultiProcess(session=ssn))
+ rlog.debug("Registered %s in subprocess", MultiProcess)
+ ssn.plugins[-1].pluginsLoaded(events.PluginsLoadedEvent(ssn.plugins))
+ return ssn
+
+
# test generator
def gentests(conn):
while True:
| MP plugin does't call startSubprocess in subprocess
My very quick diagnosis is:
In [mp.py](https://github.com/nose-devs/nose2/blob/master/nose2/plugins/mp.py):
- The new hook methods are registered on [line 27](https://github.com/nose-devs/nose2/blob/master/nose2/plugins/mp.py#L27)
- However that is only called in the master process
- Hence, when in the subprocess on [line 197](https://github.com/nose-devs/nose2/blob/master/nose2/plugins/mp.py#L197) we register the plugins, the session doesn't know to look for `startSubprocess` (or `stopSubprocess` for that matter)
- Hence when it tries to dispatch it on [line 202](https://github.com/nose-devs/nose2/blob/master/nose2/plugins/mp.py#L202) it won't call the plugins
| nose-devs/nose2 | diff --git a/nose2/tests/functional/support/scenario/layers/test_layers.py b/nose2/tests/functional/support/scenario/layers/test_layers.py
index e800780..a35bb0f 100644
--- a/nose2/tests/functional/support/scenario/layers/test_layers.py
+++ b/nose2/tests/functional/support/scenario/layers/test_layers.py
@@ -180,6 +180,8 @@ class InnerD(unittest.TestCase):
layer = LayerD
def test(self):
+ """test with docstring
+ """
self.assertEqual(
{'base': 'setup',
'layerD': 'setup'},
diff --git a/nose2/tests/functional/test_layers_plugin.py b/nose2/tests/functional/test_layers_plugin.py
index 9666dba..c658bbe 100644
--- a/nose2/tests/functional/test_layers_plugin.py
+++ b/nose2/tests/functional/test_layers_plugin.py
@@ -56,7 +56,7 @@ class TestLayers(FunctionalTestCase):
Base
test \(test_layers.Outer\) ... ok
LayerD
- test \(test_layers.InnerD\) ... ok
+ test \(test_layers.InnerD\) test with docstring ... ok
LayerA
test \(test_layers.InnerA\) ... ok
LayerB
diff --git a/nose2/tests/unit/test_mp_plugin.py b/nose2/tests/unit/test_mp_plugin.py
index 02a9949..e808bdd 100644
--- a/nose2/tests/unit/test_mp_plugin.py
+++ b/nose2/tests/unit/test_mp_plugin.py
@@ -1,6 +1,7 @@
from nose2 import session
from nose2.tests._common import TestCase, Conn
from nose2.plugins import mp
+from six.moves import configparser
import sys
@@ -58,3 +59,19 @@ class TestMPPlugin(TestCase):
finally:
sys.platform = platform
+ def test_session_import(self):
+ config = configparser.ConfigParser()
+ config.add_section(mp.MultiProcess.configSection)
+ export_session = {
+ "config": config,
+ "verbosity": None,
+ "startDir": '',
+ "topLevelDir": '',
+ "pluginClasses": [mp.MultiProcess]
+ }
+ import logging
+ session = mp.import_session(logging.root, export_session)
+ self.assertIn('registerInSubprocess', session.hooks.methods)
+ self.assertIn('startSubprocess', session.hooks.methods)
+ self.assertIn('stopSubprocess', session.hooks.methods)
+ pass
| {
"commit_name": "merge_commit",
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 1,
"test_score": 2
},
"num_modified_files": 2
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[coverage_plugin]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"nose2",
"pytest"
],
"pre_install": null,
"python": "3.5",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs==22.2.0
certifi==2021.5.30
coverage==6.2
importlib-metadata==4.8.3
iniconfig==1.1.1
-e git+https://github.com/nose-devs/nose2.git@862b130652b9118eb8d5681923c04edb000245d3#egg=nose2
packaging==21.3
pluggy==1.0.0
py==1.11.0
pyparsing==3.1.4
pytest==7.0.1
six==1.17.0
tomli==1.2.3
typing_extensions==4.1.1
zipp==3.6.0
| name: nose2
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- attrs==22.2.0
- coverage==6.2
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- packaging==21.3
- pluggy==1.0.0
- py==1.11.0
- pyparsing==3.1.4
- pytest==7.0.1
- six==1.17.0
- tomli==1.2.3
- typing-extensions==4.1.1
- zipp==3.6.0
prefix: /opt/conda/envs/nose2
| [
"nose2/tests/functional/test_layers_plugin.py::TestLayers::test_layer_reporter_output",
"nose2/tests/unit/test_mp_plugin.py::TestMPPlugin::test_session_import"
]
| [
"nose2/tests/functional/support/scenario/layers/test_layers.py::Outer::test",
"nose2/tests/functional/support/scenario/layers/test_layers.py::InnerA::test",
"nose2/tests/functional/support/scenario/layers/test_layers.py::InnerA_1::test",
"nose2/tests/functional/support/scenario/layers/test_layers.py::InnerB_1::test",
"nose2/tests/functional/support/scenario/layers/test_layers.py::InnerC::test",
"nose2/tests/functional/support/scenario/layers/test_layers.py::InnerC::test2",
"nose2/tests/functional/support/scenario/layers/test_layers.py::InnerD::test"
]
| [
"nose2/tests/functional/support/scenario/layers/test_layers.py::NoLayer::test",
"nose2/tests/functional/test_layers_plugin.py::TestLayers::test_layer_reporter_error_output",
"nose2/tests/functional/test_layers_plugin.py::TestLayers::test_layers_and_attributes",
"nose2/tests/functional/test_layers_plugin.py::TestLayers::test_layers_and_non_layers",
"nose2/tests/functional/test_layers_plugin.py::TestLayers::test_methods_run_once_per_class",
"nose2/tests/functional/test_layers_plugin.py::TestLayers::test_runs_layer_fixtures",
"nose2/tests/functional/test_layers_plugin.py::TestLayers::test_scenario_fails_without_plugin",
"nose2/tests/functional/test_layers_plugin.py::TestLayers::test_setup_fail",
"nose2/tests/functional/test_layers_plugin.py::TestLayers::test_teardown_fail",
"nose2/tests/unit/test_mp_plugin.py::TestMPPlugin::test_address",
"nose2/tests/unit/test_mp_plugin.py::TestMPPlugin::test_gentests",
"nose2/tests/unit/test_mp_plugin.py::TestMPPlugin::test_recording_plugin_interface"
]
| []
| BSD | 1,878 | [
"nose2/plugins/layers.py",
"nose2/plugins/mp.py"
]
| [
"nose2/plugins/layers.py",
"nose2/plugins/mp.py"
]
|
twisted__tubes-78 | 685a112141021b52b4f51d91c4bf11773cc6911b | 2017-11-12 07:19:42 | da65e5b6151db1ce7b036a14444c19bf46621320 | diff --git a/tubes/protocol.py b/tubes/protocol.py
index a5212fb..ec82031 100644
--- a/tubes/protocol.py
+++ b/tubes/protocol.py
@@ -20,8 +20,11 @@ from .itube import StopFlowCalled, IDrain, IFount, ISegment
from .listening import Flow
from twisted.python.failure import Failure
-from twisted.internet.interfaces import IPushProducer, IListeningPort
+from twisted.internet.interfaces import (
+ IPushProducer, IListeningPort, IHalfCloseableProtocol
+)
from twisted.internet.protocol import Protocol as _Protocol
+from twisted.internet.error import ConnectionDone
if 0:
# Workaround for inability of pydoctor to resolve references.
@@ -206,6 +209,7 @@ class _TransportFount(object):
+@implementer(IHalfCloseableProtocol)
class _ProtocolPlumbing(_Protocol):
"""
An adapter between an L{ITransport} and L{IFount} / L{IDrain} interfaces.
@@ -274,6 +278,22 @@ class _ProtocolPlumbing(_Protocol):
self._drain.fount.stopFlow()
+ def readConnectionLost(self):
+ """
+ An end-of-file was received.
+ """
+ self._fount.drain.flowStopped(Failure(ConnectionDone()))
+ self._fount.drain = None
+
+
+ def writeConnectionLost(self):
+ """
+ The write output was closed.
+ """
+ self._drain.fount.stopFlow()
+ self._drain.fount = None
+
+
def _factoryFromFlow(flow):
"""
| _ProtocolPlumbing does not implement IHalfCloseableProtocol, leading to the misleading appearance of horrifying race conditions during testing
If you were to make a script of JSON commands for `fanchat` and use the `stdio` endpoint to hook them together into a little test, then do something like
```console
$ cat fcscript.txt | python fanchat.py
```
you would get very weird non-deterministic behavior where half of the output would vanish.
This is because, in the absence of a protocol providing `IHalfCloseableProtocol` as the protocol, "EOF" means "shut down both read *and write* halves of the connection".
Understandably, further writes to the `StandardIO` would be lost.
To remedy this, `IHalfCloseableProtocol` should be implemented - which, by the way, would also allow us to separate the `fount` and `drain` termination on transports which support such a distinction. | twisted/tubes | diff --git a/tubes/test/test_protocol.py b/tubes/test/test_protocol.py
index 7eb4b3e..5450278 100644
--- a/tubes/test/test_protocol.py
+++ b/tubes/test/test_protocol.py
@@ -7,12 +7,16 @@ Tests for L{tubes.protocol}.
"""
from zope.interface import implementer
+from zope.interface.verify import verifyObject
from twisted.trial.unittest import SynchronousTestCase as TestCase
from twisted.python.failure import Failure
from twisted.test.proto_helpers import StringTransport
-from twisted.internet.interfaces import IStreamServerEndpoint
+from twisted.internet.interfaces import (
+ IStreamServerEndpoint, IHalfCloseableProtocol
+)
+from twisted.internet.error import ConnectionDone
from ..protocol import flowFountFromEndpoint, flowFromEndpoint
from ..tube import tube, series
@@ -404,6 +408,72 @@ class FlowListenerTests(TestCase):
self.assertEqual(ports[0].currentlyProducing, True)
+ def test_readConnectionLost(self):
+ """
+ The protocol created by L{flowFountFromEndpoint} provides half-close
+ support, and when it receives an EOF (i.e.: C{readConnectionLost}) it
+ will signal the end of the flow to its fount's drain, but not to its
+ drain's fount.
+ """
+ endpoint, ports = fakeEndpointWithPorts()
+ fffep = flowFountFromEndpoint(endpoint)
+ fffep.callback(None)
+ flowFount = self.successResultOf(fffep)
+ protocol = ports[0].factory.buildProtocol(None)
+ verifyObject(IHalfCloseableProtocol, protocol)
+ aTransport = StringTransport()
+ protocol.makeConnection(aTransport)
+ accepted = FakeDrain()
+ flowFount.flowTo(accepted)
+ [flow] = accepted.received
+ receivedData = FakeDrain()
+ dataSender = FakeFount()
+ flow.fount.flowTo(receivedData)
+ dataSender.flowTo(flow.drain)
+ self.assertEqual(len(receivedData.stopped), 0)
+ self.assertEqual(dataSender.flowIsStopped, False)
+ protocol.readConnectionLost()
+ self.assertEqual(len(receivedData.stopped), 1)
+ self.assertIsInstance(receivedData.stopped[0], Failure)
+ receivedData.stopped[0].trap(ConnectionDone)
+ self.assertEqual(dataSender.flowIsStopped, False)
+ protocol.connectionLost(ConnectionDone())
+ self.assertEqual(len(receivedData.stopped), 1)
+ self.assertEqual(dataSender.flowIsStopped, True)
+
+
+ def test_writeConnectionLost(self):
+ """
+ The protocol created by L{flowFountFromEndpoint} provides half-close
+ support, and when it receives an EOF (i.e.: C{writeConnectionLost}) it
+ will signal the end of the flow to its drain's fount, but not to its
+ fount's drain.
+ """
+ endpoint, ports = fakeEndpointWithPorts()
+ fffep = flowFountFromEndpoint(endpoint)
+ fffep.callback(None)
+ flowFount = self.successResultOf(fffep)
+ protocol = ports[0].factory.buildProtocol(None)
+ verifyObject(IHalfCloseableProtocol, protocol)
+ aTransport = StringTransport()
+ protocol.makeConnection(aTransport)
+ accepted = FakeDrain()
+ flowFount.flowTo(accepted)
+ [flow] = accepted.received
+ receivedData = FakeDrain()
+ dataSender = FakeFount()
+ flow.fount.flowTo(receivedData)
+ dataSender.flowTo(flow.drain)
+ self.assertEqual(len(receivedData.stopped), 0)
+ self.assertEqual(dataSender.flowIsStopped, False)
+ protocol.writeConnectionLost()
+ self.assertEqual(len(receivedData.stopped), 0)
+ self.assertEqual(dataSender.flowIsStopped, 1)
+ protocol.connectionLost(ConnectionDone())
+ self.assertEqual(len(receivedData.stopped), 1)
+ self.assertEqual(dataSender.flowIsStopped, 1)
+
+
def test_backpressure(self):
"""
When the L{IFount} returned by L{flowFountFromEndpoint} is paused, it
diff --git a/tubes/test/util.py b/tubes/test/util.py
index 054a928..9e291d1 100644
--- a/tubes/test/util.py
+++ b/tubes/test/util.py
@@ -137,6 +137,7 @@ class FakeFount(object):
flowIsPaused = 0
flowIsStopped = False
+
def __init__(self, outputType=None):
self._pauser = Pauser(self._actuallyPause, self._actuallyResume)
self.outputType = outputType
@@ -170,9 +171,9 @@ class FakeFount(object):
def stopFlow(self):
"""
- Record that the flow was stopped by setting C{flowIsStopped}.
+ Record that the flow was stopped by incrementing C{flowIsStopped}.
"""
- self.flowIsStopped = True
+ self.flowIsStopped += 1
def _actuallyPause(self):
| {
"commit_name": "head_commit",
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 0,
"test_score": 0
},
"num_modified_files": 1
} | 0.2 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.6",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs==22.2.0
Automat==22.10.0
certifi==2021.5.30
characteristic==14.3.0
constantly==15.1.0
hyperlink==21.0.0
idna==3.10
importlib-metadata==4.8.3
incremental==22.10.0
iniconfig==1.1.1
packaging==21.3
pluggy==1.0.0
py==1.11.0
pyparsing==3.1.4
pytest==7.0.1
six==1.17.0
tomli==1.2.3
-e git+https://github.com/twisted/tubes.git@685a112141021b52b4f51d91c4bf11773cc6911b#egg=Tubes
Twisted==22.4.0
typing_extensions==4.1.1
zipp==3.6.0
zope.interface==5.5.2
| name: tubes
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- attrs==22.2.0
- automat==22.10.0
- characteristic==14.3.0
- constantly==15.1.0
- hyperlink==21.0.0
- idna==3.10
- importlib-metadata==4.8.3
- incremental==22.10.0
- iniconfig==1.1.1
- packaging==21.3
- pluggy==1.0.0
- py==1.11.0
- pyparsing==3.1.4
- pytest==7.0.1
- six==1.17.0
- tomli==1.2.3
- twisted==22.4.0
- typing-extensions==4.1.1
- zipp==3.6.0
- zope-interface==5.5.2
prefix: /opt/conda/envs/tubes
| [
"tubes/test/test_protocol.py::FlowListenerTests::test_readConnectionLost",
"tubes/test/test_protocol.py::FlowListenerTests::test_writeConnectionLost"
]
| []
| [
"tubes/test/test_protocol.py::FlowConnectorTests::test_connectionLostSendsFlowStopped",
"tubes/test/test_protocol.py::FlowConnectorTests::test_connectionLostSendsStopFlow",
"tubes/test/test_protocol.py::FlowConnectorTests::test_dataReceivedBeforeFlowing",
"tubes/test/test_protocol.py::FlowConnectorTests::test_dataReceivedBeforeFlowingThenFlowTo",
"tubes/test/test_protocol.py::FlowConnectorTests::test_dataReceivedWhenFlowingToNone",
"tubes/test/test_protocol.py::FlowConnectorTests::test_drainReceivingWritesToTransport",
"tubes/test/test_protocol.py::FlowConnectorTests::test_flowStoppedStopsConnection",
"tubes/test/test_protocol.py::FlowConnectorTests::test_flowToDeliversData",
"tubes/test/test_protocol.py::FlowConnectorTests::test_flowToSetsDrain",
"tubes/test/test_protocol.py::FlowConnectorTests::test_flowingFrom",
"tubes/test/test_protocol.py::FlowConnectorTests::test_flowingFromAttribute",
"tubes/test/test_protocol.py::FlowConnectorTests::test_flowingFromTwice",
"tubes/test/test_protocol.py::FlowConnectorTests::test_flowingToNoneAfterFlowingToSomething",
"tubes/test/test_protocol.py::FlowConnectorTests::test_pauseUnpauseFromOtherDrain",
"tubes/test/test_protocol.py::FlowConnectorTests::test_pauseUnpauseFromTransport",
"tubes/test/test_protocol.py::FlowConnectorTests::test_stopFlowStopsConnection",
"tubes/test/test_protocol.py::FlowConnectorTests::test_stopProducing",
"tubes/test/test_protocol.py::FlowListenerTests::test_acceptAfterDeferredButBeforeFlowTo",
"tubes/test/test_protocol.py::FlowListenerTests::test_acceptBeforeActuallyListening",
"tubes/test/test_protocol.py::FlowListenerTests::test_backpressure",
"tubes/test/test_protocol.py::FlowListenerTests::test_fromEndpoint",
"tubes/test/test_protocol.py::FlowListenerTests::test_oneConnectionAccepted",
"tubes/test/test_protocol.py::FlowListenerTests::test_stopping"
]
| []
| MIT License | 1,880 | [
"tubes/protocol.py"
]
| [
"tubes/protocol.py"
]
|
|
ska-sa__fakenewsredis-3 | 771b41c2fb00ae84508e5a5df8f8b578b6650ac1 | 2017-11-12 19:19:04 | 0472a6e928d9502f7549b6c829dd86570ec00c0e | diff --git a/README.rst b/README.rst
index 4f29a1f..14388a4 100644
--- a/README.rst
+++ b/README.rst
@@ -1,5 +1,5 @@
fakenewsredis: A fake version of a redis-py
-===========================================
+==========================================
.. image:: https://secure.travis-ci.org/ska-sa/fakenewsredis.svg?branch=master
:target: http://travis-ci.org/ska-sa/fakenewsredis
@@ -270,17 +270,17 @@ Revision history
-----
This is the first release of fakenewsredis, based on `fakeredis`_ 0.9.0, with the following features and fixes:
-- fakeredis `#78 <https://github.com/jamesls/fakeredis/issues/78>`_ Behaviour of transaction() does not match redis-py
-- fakeredis `#79 <https://github.com/jamesls/fakeredis/issues/79>`_ Implement redis-py's .lock()
-- fakeredis `#90 <https://github.com/jamesls/fakeredis/issues/90>`_ HINCRBYFLOAT changes hash value type to float
-- fakeredis `#101 <https://github.com/jamesls/fakeredis/issues/101>`_ Should raise an error when attempting to get a key holding a list)
-- fakeredis `#146 <https://github.com/jamesls/fakeredis/issues/146>`_ Pubsub messages and channel names are forced to be ASCII strings on Python 2
-- fakeredis `#163 <https://github.com/jamesls/fakeredis/issues/163>`_ getset does not to_bytes the value
-- fakeredis `#165 <https://github.com/jamesls/fakeredis/issues/165>`_ linsert implementation is incomplete
-- fakeredis `#128 <https://github.com/jamesls/fakeredis/pull/128>`_ Remove `_ex_keys` mapping
-- fakeredis `#139 <https://github.com/jamesls/fakeredis/pull/139>`_ Fixed all flake8 errors and added flake8 to Travis CI
-- fakeredis `#166 <https://github.com/jamesls/fakeredis/pull/166>`_ Add type checking
-- fakeredis `#168 <https://github.com/jamesls/fakeredis/pull/168>`_ Use repr to encode floats in to_bytes
+- fakeredis [#78](https://github.com/jamesls/fakeredis/issues/78) Behaviour of transaction() does not match redis-py
+- fakeredis [#79](https://github.com/jamesls/fakeredis/issues/79) Implement redis-py's .lock()
+- fakeredis [#90](https://github.com/jamesls/fakeredis/issues/90) HINCRBYFLOAT changes hash value type to float
+- fakeredis [#101](https://github.com/jamesls/fakeredis/issues/101) Should raise an error when attempting to get a key holding a list)
+- fakeredis [#146](https://github.com/jamesls/fakeredis/issues/146) Pubsub messages and channel names are forced to be ASCII strings on Python 2
+- fakeredis [#163](https://github.com/jamesls/fakeredis/issues/163) getset does not to_bytes the value
+- fakeredis [#165](https://github.com/jamesls/fakeredis/issues/165) linsert implementation is incomplete
+- fakeredis [#128](https://github.com/jamesls/fakeredis/pull/128) Remove `_ex_keys` mapping
+- fakeredis [#139](https://github.com/jamesls/fakeredis/pull/139) Fixed all flake8 errors and added flake8 to Travis CI
+- fakeredis [#166](https://github.com/jamesls/fakeredis/pull/166) Add type checking
+- fakeredis [#168](https://github.com/jamesls/fakeredis/pull/168) Use repr to encode floats in to_bytes
.. _fakeredis: https://github.com/jamesls/fakeredis
.. _redis-py: http://redis-py.readthedocs.org/en/latest/index.html
diff --git a/fakenewsredis.py b/fakenewsredis.py
index 6e8fdcc..79930f1 100644
--- a/fakenewsredis.py
+++ b/fakenewsredis.py
@@ -142,6 +142,18 @@ class _StrKeyDict(MutableMapping):
value = self._dict[to_bytes(key)][0]
self._dict[to_bytes(key)] = (value, timestamp)
+ def setx(self, key, value, src=None):
+ """Set a value, keeping the existing expiry time if any. If
+ `src` is specified, it is used as the source of the expiry
+ """
+ if src is None:
+ src = key
+ try:
+ _, expiration = self._dict[to_bytes(src)]
+ except KeyError:
+ expiration = None
+ self._dict[to_bytes(key)] = (value, expiration)
+
def persist(self, key):
try:
value, _ = self._dict[to_bytes(key)]
@@ -294,11 +306,12 @@ class FakeStrictRedis(object):
def decr(self, name, amount=1):
try:
- self._db[name] = to_bytes(int(self._get_string(name, b'0')) - amount)
+ value = int(self._get_string(name, b'0')) - amount
+ self._db.setx(name, to_bytes(value))
except (TypeError, ValueError):
raise redis.ResponseError("value is not an integer or out of "
"range.")
- return int(self._db[name])
+ return value
def exists(self, name):
return name in self._db
@@ -381,11 +394,12 @@ class FakeStrictRedis(object):
if not isinstance(amount, int):
raise redis.ResponseError("value is not an integer or out "
"of range.")
- self._db[name] = to_bytes(int(self._get_string(name, b'0')) + amount)
+ value = int(self._get_string(name, b'0')) + amount
+ self._db.setx(name, to_bytes(value))
except (TypeError, ValueError):
raise redis.ResponseError("value is not an integer or out of "
"range.")
- return int(self._db[name])
+ return value
def incrby(self, name, amount=1):
"""
@@ -395,10 +409,11 @@ class FakeStrictRedis(object):
def incrbyfloat(self, name, amount=1.0):
try:
- self._db[name] = to_bytes(float(self._get_string(name, b'0')) + amount)
+ value = float(self._get_string(name, b'0')) + amount
+ self._db.setx(name, to_bytes(value))
except (TypeError, ValueError):
raise redis.ResponseError("value is not a valid float.")
- return float(self._db[name])
+ return value
def keys(self, pattern=None):
return [key for key in self._db
@@ -457,7 +472,7 @@ class FakeStrictRedis(object):
value = self._db[src]
except KeyError:
raise redis.ResponseError("No such key: %s" % src)
- self._db[dst] = value
+ self._db.setx(dst, value, src=src)
del self._db[src]
return True
@@ -512,7 +527,7 @@ class FakeStrictRedis(object):
new_byte = byte_to_int(val[byte]) ^ (1 << actual_bitoffset)
reconstructed = bytearray(val)
reconstructed[byte] = new_byte
- self._db[name] = bytes(reconstructed)
+ self._db.setx(name, bytes(reconstructed))
def setex(self, name, time, value):
if isinstance(time, timedelta):
@@ -541,7 +556,7 @@ class FakeStrictRedis(object):
if len(val) < offset:
val += b'\x00' * (offset - len(val))
val = val[0:offset] + to_bytes(value) + val[offset+len(value):]
- self.set(name, val)
+ self._db.setx(name, val)
return len(val)
def strlen(self, name):
@@ -800,7 +815,7 @@ class FakeStrictRedis(object):
end = None
else:
end += 1
- self._db[name] = val[start:end]
+ self._db.setx(name, val[start:end])
return True
def lindex(self, name, index):
@@ -843,7 +858,7 @@ class FakeStrictRedis(object):
if el is not None:
el = to_bytes(el)
dst_list.insert(0, el)
- self._db[dst] = dst_list
+ self._db.setx(dst, dst_list)
return el
def blpop(self, keys, timeout=0):
| Mutating operations incorrectly clear expiry
A number of operations modify an existing value, then assign back to `self._db`, which has the side-effect of clearing the expiry time. According to the redis documentation, only operations that completely replace a key (rather than modifying it) clear the expiry. I haven't written any tests yet, but looking at the code, it is probably at least
- decr, incr, incrby, incrbyfloat
- setbit
- ltrim
- rpoplpush
Some other operations where I'm not sure what redis will do
- getset
- rename, renamenx | ska-sa/fakenewsredis | diff --git a/test_fakenewsredis.py b/test_fakenewsredis.py
index d60751f..064d24f 100644
--- a/test_fakenewsredis.py
+++ b/test_fakenewsredis.py
@@ -201,6 +201,11 @@ class TestFakeStrictRedis(unittest.TestCase):
with self.assertRaises(redis.ResponseError):
self.redis.setbit('foo', 0, 1)
+ def test_setbit_expiry(self):
+ self.redis.set('foo', b'0x00', ex=10)
+ self.redis.setbit('foo', 1, 1)
+ self.assertGreater(self.redis.ttl('foo'), 0)
+
def test_bitcount(self):
self.redis.delete('foo')
self.assertEqual(self.redis.bitcount('foo'), 0)
@@ -296,6 +301,11 @@ class TestFakeStrictRedis(unittest.TestCase):
self.assertEqual(self.redis.incr('foo', 5), 20)
self.assertEqual(self.redis.get('foo'), b'20')
+ def test_incr_expiry(self):
+ self.redis.set('foo', 15, ex=10)
+ self.redis.incr('foo', 5)
+ self.assertGreater(self.redis.ttl('foo'), 0)
+
def test_incr_bad_type(self):
self.redis.set('foo', 'bar')
with self.assertRaises(redis.ResponseError):
@@ -326,6 +336,11 @@ class TestFakeStrictRedis(unittest.TestCase):
self.assertEqual(self.redis.incrbyfloat('foo', 1.0), 1.0)
self.assertEqual(self.redis.incrbyfloat('foo', 1.0), 2.0)
+ def test_incrbyfloat_expiry(self):
+ self.redis.set('foo', 1.5, ex=10)
+ self.redis.incrbyfloat('foo', 2.5)
+ self.assertGreater(self.redis.ttl('foo'), 0)
+
def test_incrbyfloat_bad_type(self):
self.redis.set('foo', 'bar')
with self.assertRaisesRegexp(redis.ResponseError, 'not a valid float'):
@@ -348,6 +363,11 @@ class TestFakeStrictRedis(unittest.TestCase):
self.redis.decr('foo')
self.assertEqual(self.redis.get('foo'), b'-1')
+ def test_decr_expiry(self):
+ self.redis.set('foo', 10, ex=10)
+ self.redis.decr('foo', 5)
+ self.assertGreater(self.redis.ttl('foo'), 0)
+
def test_decr_badtype(self):
self.redis.set('foo', 'bar')
with self.assertRaises(redis.ResponseError):
@@ -389,6 +409,12 @@ class TestFakeStrictRedis(unittest.TestCase):
self.assertEqual(self.redis.get('foo'), b'unique value')
self.assertEqual(self.redis.get('bar'), b'unique value2')
+ def test_rename_expiry(self):
+ self.redis.set('foo', 'value1', ex=10)
+ self.redis.set('bar', 'value2')
+ self.redis.rename('foo', 'bar')
+ self.assertGreater(self.redis.ttl('bar'), 0)
+
def test_mget(self):
self.redis.set('foo', 'one')
self.redis.set('bar', 'two')
@@ -743,6 +769,12 @@ class TestFakeStrictRedis(unittest.TestCase):
def test_ltrim_with_non_existent_key(self):
self.assertTrue(self.redis.ltrim('foo', 0, -1))
+ def test_ltrim_expiry(self):
+ self.redis.rpush('foo', 'one', 'two', 'three')
+ self.redis.expire('foo', 10)
+ self.redis.ltrim('foo', 1, 2)
+ self.assertGreater(self.redis.ttl('foo'), 0)
+
def test_ltrim_wrong_type(self):
self.redis.set('foo', 'bar')
with self.assertRaises(redis.ResponseError):
@@ -834,6 +866,13 @@ class TestFakeStrictRedis(unittest.TestCase):
self.assertEqual(self.redis.rpoplpush('foo', 'bar'), b'one')
self.assertEqual(self.redis.rpop('bar'), b'one')
+ def test_rpoplpush_expiry(self):
+ self.redis.rpush('foo', 'one')
+ self.redis.rpush('bar', 'two')
+ self.redis.expire('bar', 10)
+ self.redis.rpoplpush('foo', 'bar')
+ self.assertGreater(self.redis.ttl('bar'), 0)
+
def test_rpoplpush_wrong_type(self):
self.redis.set('foo', 'bar')
self.redis.rpush('list', 'element')
@@ -1273,6 +1312,11 @@ class TestFakeStrictRedis(unittest.TestCase):
self.assertEqual(self.redis.setrange('bar', 2, 'test'), 6)
self.assertEqual(self.redis.get('bar'), b'\x00\x00test')
+ def test_setrange_expiry(self):
+ self.redis.set('foo', 'test', ex=10)
+ self.redis.setrange('foo', 1, 'aste')
+ self.assertGreater(self.redis.ttl('foo'), 0)
+
def test_sinter(self):
self.redis.sadd('foo', 'member1')
self.redis.sadd('foo', 'member2')
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 2,
"test_score": 0
},
"num_modified_files": 2
} | 0.9 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"nose",
"pytest"
],
"pre_install": null,
"python": "3.6",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs==22.2.0
certifi==2021.5.30
-e git+https://github.com/ska-sa/fakenewsredis.git@771b41c2fb00ae84508e5a5df8f8b578b6650ac1#egg=fakenewsredis
flake8==2.6.2
importlib-metadata==4.8.3
iniconfig==1.1.1
mccabe==0.5.3
nose==1.3.4
packaging==21.3
pluggy==1.0.0
py==1.11.0
pycodestyle==2.0.0
pyflakes==1.2.3
pyparsing==3.1.4
pytest==7.0.1
redis==2.10.5
tomli==1.2.3
typing_extensions==4.1.1
zipp==3.6.0
| name: fakenewsredis
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- attrs==22.2.0
- flake8==2.6.2
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- mccabe==0.5.3
- nose==1.3.4
- packaging==21.3
- pluggy==1.0.0
- py==1.11.0
- pycodestyle==2.0.0
- pyflakes==1.2.3
- pyparsing==3.1.4
- pytest==7.0.1
- redis==2.10.5
- tomli==1.2.3
- typing-extensions==4.1.1
- zipp==3.6.0
prefix: /opt/conda/envs/fakenewsredis
| [
"test_fakenewsredis.py::TestFakeStrictRedis::test_decr_expiry",
"test_fakenewsredis.py::TestFakeStrictRedis::test_incr_expiry",
"test_fakenewsredis.py::TestFakeStrictRedis::test_incrbyfloat_expiry",
"test_fakenewsredis.py::TestFakeStrictRedis::test_ltrim_expiry",
"test_fakenewsredis.py::TestFakeStrictRedis::test_rename_expiry",
"test_fakenewsredis.py::TestFakeStrictRedis::test_rpoplpush_expiry",
"test_fakenewsredis.py::TestFakeStrictRedis::test_setbit_expiry",
"test_fakenewsredis.py::TestFakeStrictRedis::test_setrange_expiry",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_decr_expiry",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_incr_expiry",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_incrbyfloat_expiry",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_ltrim_expiry",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_rename_expiry",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_rpoplpush_expiry",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_setbit_expiry",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_setrange_expiry"
]
| []
| [
"test_fakenewsredis.py::TestFakeStrictRedis::test_append",
"test_fakenewsredis.py::TestFakeStrictRedis::test_append_with_no_preexisting_key",
"test_fakenewsredis.py::TestFakeStrictRedis::test_append_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_basic_sort",
"test_fakenewsredis.py::TestFakeStrictRedis::test_bitcount",
"test_fakenewsredis.py::TestFakeStrictRedis::test_bitcount_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_blocking_operations_when_empty",
"test_fakenewsredis.py::TestFakeStrictRedis::test_blpop_allow_single_key",
"test_fakenewsredis.py::TestFakeStrictRedis::test_blpop_single_list",
"test_fakenewsredis.py::TestFakeStrictRedis::test_blpop_test_multiple_lists",
"test_fakenewsredis.py::TestFakeStrictRedis::test_blpop_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_brpop_single_key",
"test_fakenewsredis.py::TestFakeStrictRedis::test_brpop_test_multiple_lists",
"test_fakenewsredis.py::TestFakeStrictRedis::test_brpop_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_brpoplpush_multi_keys",
"test_fakenewsredis.py::TestFakeStrictRedis::test_brpoplpush_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_contains",
"test_fakenewsredis.py::TestFakeStrictRedis::test_decr",
"test_fakenewsredis.py::TestFakeStrictRedis::test_decr_badtype",
"test_fakenewsredis.py::TestFakeStrictRedis::test_decr_newkey",
"test_fakenewsredis.py::TestFakeStrictRedis::test_delete",
"test_fakenewsredis.py::TestFakeStrictRedis::test_delete_expire",
"test_fakenewsredis.py::TestFakeStrictRedis::test_delete_multiple",
"test_fakenewsredis.py::TestFakeStrictRedis::test_delete_nonexistent_key",
"test_fakenewsredis.py::TestFakeStrictRedis::test_echo",
"test_fakenewsredis.py::TestFakeStrictRedis::test_empty_sort",
"test_fakenewsredis.py::TestFakeStrictRedis::test_exists",
"test_fakenewsredis.py::TestFakeStrictRedis::test_flushdb",
"test_fakenewsredis.py::TestFakeStrictRedis::test_foo",
"test_fakenewsredis.py::TestFakeStrictRedis::test_get_does_not_exist",
"test_fakenewsredis.py::TestFakeStrictRedis::test_get_invalid_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_get_with_non_str_keys",
"test_fakenewsredis.py::TestFakeStrictRedis::test_getbit",
"test_fakenewsredis.py::TestFakeStrictRedis::test_getbit_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_getset_exists",
"test_fakenewsredis.py::TestFakeStrictRedis::test_getset_not_exist",
"test_fakenewsredis.py::TestFakeStrictRedis::test_getset_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_hdel",
"test_fakenewsredis.py::TestFakeStrictRedis::test_hdel_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_hexists",
"test_fakenewsredis.py::TestFakeStrictRedis::test_hexists_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_hgetall",
"test_fakenewsredis.py::TestFakeStrictRedis::test_hgetall_empty_key",
"test_fakenewsredis.py::TestFakeStrictRedis::test_hgetall_with_tuples",
"test_fakenewsredis.py::TestFakeStrictRedis::test_hgetall_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_hincrby",
"test_fakenewsredis.py::TestFakeStrictRedis::test_hincrby_with_no_starting_value",
"test_fakenewsredis.py::TestFakeStrictRedis::test_hincrby_with_range_param",
"test_fakenewsredis.py::TestFakeStrictRedis::test_hincrby_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_hincrbyfloat",
"test_fakenewsredis.py::TestFakeStrictRedis::test_hincrbyfloat_on_non_float_value_raises_error",
"test_fakenewsredis.py::TestFakeStrictRedis::test_hincrbyfloat_precision",
"test_fakenewsredis.py::TestFakeStrictRedis::test_hincrbyfloat_with_no_starting_value",
"test_fakenewsredis.py::TestFakeStrictRedis::test_hincrbyfloat_with_non_float_amount_raises_error",
"test_fakenewsredis.py::TestFakeStrictRedis::test_hincrbyfloat_with_range_param",
"test_fakenewsredis.py::TestFakeStrictRedis::test_hincrbyfloat_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_hkeys",
"test_fakenewsredis.py::TestFakeStrictRedis::test_hkeys_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_hlen",
"test_fakenewsredis.py::TestFakeStrictRedis::test_hlen_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_hmget",
"test_fakenewsredis.py::TestFakeStrictRedis::test_hmget_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_hmset_convert_values",
"test_fakenewsredis.py::TestFakeStrictRedis::test_hmset_does_not_mutate_input_params",
"test_fakenewsredis.py::TestFakeStrictRedis::test_hmset_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_hmsetset",
"test_fakenewsredis.py::TestFakeStrictRedis::test_hmsetset_empty_raises_error",
"test_fakenewsredis.py::TestFakeStrictRedis::test_hscan",
"test_fakenewsredis.py::TestFakeStrictRedis::test_hset_then_hget",
"test_fakenewsredis.py::TestFakeStrictRedis::test_hset_update",
"test_fakenewsredis.py::TestFakeStrictRedis::test_hset_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_hsetnx",
"test_fakenewsredis.py::TestFakeStrictRedis::test_hvals",
"test_fakenewsredis.py::TestFakeStrictRedis::test_hvals_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_incr_bad_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_incr_by",
"test_fakenewsredis.py::TestFakeStrictRedis::test_incr_followed_by_mget",
"test_fakenewsredis.py::TestFakeStrictRedis::test_incr_followed_by_mget_returns_strings",
"test_fakenewsredis.py::TestFakeStrictRedis::test_incr_preexisting_key",
"test_fakenewsredis.py::TestFakeStrictRedis::test_incr_with_float",
"test_fakenewsredis.py::TestFakeStrictRedis::test_incr_with_no_preexisting_key",
"test_fakenewsredis.py::TestFakeStrictRedis::test_incrbyfloat",
"test_fakenewsredis.py::TestFakeStrictRedis::test_incrbyfloat_bad_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_incrbyfloat_precision",
"test_fakenewsredis.py::TestFakeStrictRedis::test_incrbyfloat_with_noexist",
"test_fakenewsredis.py::TestFakeStrictRedis::test_key_patterns",
"test_fakenewsredis.py::TestFakeStrictRedis::test_lindex",
"test_fakenewsredis.py::TestFakeStrictRedis::test_lindex_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_linsert_after",
"test_fakenewsredis.py::TestFakeStrictRedis::test_linsert_before",
"test_fakenewsredis.py::TestFakeStrictRedis::test_linsert_no_pivot",
"test_fakenewsredis.py::TestFakeStrictRedis::test_linsert_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_llen",
"test_fakenewsredis.py::TestFakeStrictRedis::test_llen_no_exist",
"test_fakenewsredis.py::TestFakeStrictRedis::test_llen_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_lpop",
"test_fakenewsredis.py::TestFakeStrictRedis::test_lpop_empty_list",
"test_fakenewsredis.py::TestFakeStrictRedis::test_lpop_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_lpush_key_does_not_exist",
"test_fakenewsredis.py::TestFakeStrictRedis::test_lpush_then_lrange_all",
"test_fakenewsredis.py::TestFakeStrictRedis::test_lpush_then_lrange_portion",
"test_fakenewsredis.py::TestFakeStrictRedis::test_lpush_with_nonstr_key",
"test_fakenewsredis.py::TestFakeStrictRedis::test_lpush_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_lpushx",
"test_fakenewsredis.py::TestFakeStrictRedis::test_lpushx_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_lrem_default_value",
"test_fakenewsredis.py::TestFakeStrictRedis::test_lrem_does_not_exist",
"test_fakenewsredis.py::TestFakeStrictRedis::test_lrem_negative_count",
"test_fakenewsredis.py::TestFakeStrictRedis::test_lrem_positive_count",
"test_fakenewsredis.py::TestFakeStrictRedis::test_lrem_return_value",
"test_fakenewsredis.py::TestFakeStrictRedis::test_lrem_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_lrem_zero_count",
"test_fakenewsredis.py::TestFakeStrictRedis::test_lset",
"test_fakenewsredis.py::TestFakeStrictRedis::test_lset_index_out_of_range",
"test_fakenewsredis.py::TestFakeStrictRedis::test_lset_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_ltrim",
"test_fakenewsredis.py::TestFakeStrictRedis::test_ltrim_with_non_existent_key",
"test_fakenewsredis.py::TestFakeStrictRedis::test_ltrim_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_mget",
"test_fakenewsredis.py::TestFakeStrictRedis::test_mget_mixed_types",
"test_fakenewsredis.py::TestFakeStrictRedis::test_mget_with_no_keys_raises_error",
"test_fakenewsredis.py::TestFakeStrictRedis::test_move_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_mset",
"test_fakenewsredis.py::TestFakeStrictRedis::test_mset_accepts_kwargs",
"test_fakenewsredis.py::TestFakeStrictRedis::test_mset_with_no_keys_raises_error",
"test_fakenewsredis.py::TestFakeStrictRedis::test_msetnx",
"test_fakenewsredis.py::TestFakeStrictRedis::test_multidb",
"test_fakenewsredis.py::TestFakeStrictRedis::test_multiple_bits_set",
"test_fakenewsredis.py::TestFakeStrictRedis::test_multiple_successful_watch_calls",
"test_fakenewsredis.py::TestFakeStrictRedis::test_persist",
"test_fakenewsredis.py::TestFakeStrictRedis::test_pfadd",
"test_fakenewsredis.py::TestFakeStrictRedis::test_pfcount",
"test_fakenewsredis.py::TestFakeStrictRedis::test_pfmerge",
"test_fakenewsredis.py::TestFakeStrictRedis::test_ping",
"test_fakenewsredis.py::TestFakeStrictRedis::test_pipeline",
"test_fakenewsredis.py::TestFakeStrictRedis::test_pipeline_as_context_manager",
"test_fakenewsredis.py::TestFakeStrictRedis::test_pipeline_ignore_errors",
"test_fakenewsredis.py::TestFakeStrictRedis::test_pipeline_non_transactional",
"test_fakenewsredis.py::TestFakeStrictRedis::test_pipeline_proxies_to_redis_object",
"test_fakenewsredis.py::TestFakeStrictRedis::test_pipeline_raises_when_watched_key_changed",
"test_fakenewsredis.py::TestFakeStrictRedis::test_pipeline_succeeds_despite_unwatched_key_changed",
"test_fakenewsredis.py::TestFakeStrictRedis::test_pipeline_succeeds_when_watching_nonexistent_key",
"test_fakenewsredis.py::TestFakeStrictRedis::test_pipeline_transaction_shortcut",
"test_fakenewsredis.py::TestFakeStrictRedis::test_pipeline_transaction_value_from_callable",
"test_fakenewsredis.py::TestFakeStrictRedis::test_pttl_should_return_minus_one_for_non_expiring_key",
"test_fakenewsredis.py::TestFakeStrictRedis::test_pttl_should_return_minus_two_for_non_existent_key",
"test_fakenewsredis.py::TestFakeStrictRedis::test_pubsub_binary_message",
"test_fakenewsredis.py::TestFakeStrictRedis::test_pubsub_ignore_sub_messages_listen",
"test_fakenewsredis.py::TestFakeStrictRedis::test_pubsub_listen",
"test_fakenewsredis.py::TestFakeStrictRedis::test_pubsub_psubscribe",
"test_fakenewsredis.py::TestFakeStrictRedis::test_pubsub_punsubscribe",
"test_fakenewsredis.py::TestFakeStrictRedis::test_pubsub_subscribe",
"test_fakenewsredis.py::TestFakeStrictRedis::test_pubsub_unsubscribe",
"test_fakenewsredis.py::TestFakeStrictRedis::test_rename",
"test_fakenewsredis.py::TestFakeStrictRedis::test_rename_does_exist",
"test_fakenewsredis.py::TestFakeStrictRedis::test_rename_nonexistent_key",
"test_fakenewsredis.py::TestFakeStrictRedis::test_renamenx_doesnt_exist",
"test_fakenewsredis.py::TestFakeStrictRedis::test_rpop",
"test_fakenewsredis.py::TestFakeStrictRedis::test_rpop_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_rpoplpush",
"test_fakenewsredis.py::TestFakeStrictRedis::test_rpoplpush_to_nonexistent_destination",
"test_fakenewsredis.py::TestFakeStrictRedis::test_rpoplpush_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_rpush",
"test_fakenewsredis.py::TestFakeStrictRedis::test_rpush_then_lrange_with_nested_list1",
"test_fakenewsredis.py::TestFakeStrictRedis::test_rpush_then_lrange_with_nested_list2",
"test_fakenewsredis.py::TestFakeStrictRedis::test_rpush_then_lrange_with_nested_list3",
"test_fakenewsredis.py::TestFakeStrictRedis::test_rpush_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_rpushx",
"test_fakenewsredis.py::TestFakeStrictRedis::test_rpushx_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_sadd",
"test_fakenewsredis.py::TestFakeStrictRedis::test_sadd_as_str_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_sadd_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_saving_non_ascii_chars_as_key",
"test_fakenewsredis.py::TestFakeStrictRedis::test_saving_non_ascii_chars_as_value",
"test_fakenewsredis.py::TestFakeStrictRedis::test_saving_unicode_type_as_key",
"test_fakenewsredis.py::TestFakeStrictRedis::test_saving_unicode_type_as_value",
"test_fakenewsredis.py::TestFakeStrictRedis::test_scan",
"test_fakenewsredis.py::TestFakeStrictRedis::test_scan_all_in_single_call",
"test_fakenewsredis.py::TestFakeStrictRedis::test_scan_iter_multiple_pages",
"test_fakenewsredis.py::TestFakeStrictRedis::test_scan_iter_multiple_pages_with_match",
"test_fakenewsredis.py::TestFakeStrictRedis::test_scan_iter_single_page",
"test_fakenewsredis.py::TestFakeStrictRedis::test_scan_multiple_pages_with_count_arg",
"test_fakenewsredis.py::TestFakeStrictRedis::test_scan_single",
"test_fakenewsredis.py::TestFakeStrictRedis::test_scard",
"test_fakenewsredis.py::TestFakeStrictRedis::test_scard_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_sdiff",
"test_fakenewsredis.py::TestFakeStrictRedis::test_sdiff_empty",
"test_fakenewsredis.py::TestFakeStrictRedis::test_sdiff_one_key",
"test_fakenewsredis.py::TestFakeStrictRedis::test_sdiff_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_sdiffstore",
"test_fakenewsredis.py::TestFakeStrictRedis::test_set_None_value",
"test_fakenewsredis.py::TestFakeStrictRedis::test_set_ex",
"test_fakenewsredis.py::TestFakeStrictRedis::test_set_ex_using_timedelta",
"test_fakenewsredis.py::TestFakeStrictRedis::test_set_existing_key_persists",
"test_fakenewsredis.py::TestFakeStrictRedis::test_set_float_value",
"test_fakenewsredis.py::TestFakeStrictRedis::test_set_non_str_keys",
"test_fakenewsredis.py::TestFakeStrictRedis::test_set_px",
"test_fakenewsredis.py::TestFakeStrictRedis::test_set_px_using_timedelta",
"test_fakenewsredis.py::TestFakeStrictRedis::test_set_raises_wrong_ex",
"test_fakenewsredis.py::TestFakeStrictRedis::test_set_raises_wrong_px",
"test_fakenewsredis.py::TestFakeStrictRedis::test_set_then_get",
"test_fakenewsredis.py::TestFakeStrictRedis::test_set_using_timedelta_raises_wrong_ex",
"test_fakenewsredis.py::TestFakeStrictRedis::test_set_using_timedelta_raises_wrong_px",
"test_fakenewsredis.py::TestFakeStrictRedis::test_setbit_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_setbits_and_getkeys",
"test_fakenewsredis.py::TestFakeStrictRedis::test_setex",
"test_fakenewsredis.py::TestFakeStrictRedis::test_setex_raises_wrong_ex",
"test_fakenewsredis.py::TestFakeStrictRedis::test_setex_using_float",
"test_fakenewsredis.py::TestFakeStrictRedis::test_setex_using_timedelta",
"test_fakenewsredis.py::TestFakeStrictRedis::test_setex_using_timedelta_raises_wrong_ex",
"test_fakenewsredis.py::TestFakeStrictRedis::test_setitem_getitem",
"test_fakenewsredis.py::TestFakeStrictRedis::test_setnx",
"test_fakenewsredis.py::TestFakeStrictRedis::test_setrange",
"test_fakenewsredis.py::TestFakeStrictRedis::test_sinter",
"test_fakenewsredis.py::TestFakeStrictRedis::test_sinter_bytes_keys",
"test_fakenewsredis.py::TestFakeStrictRedis::test_sinter_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_sinterstore",
"test_fakenewsredis.py::TestFakeStrictRedis::test_sismember",
"test_fakenewsredis.py::TestFakeStrictRedis::test_sismember_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_smembers",
"test_fakenewsredis.py::TestFakeStrictRedis::test_smembers_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_smove",
"test_fakenewsredis.py::TestFakeStrictRedis::test_smove_non_existent_key",
"test_fakenewsredis.py::TestFakeStrictRedis::test_sort_alpha",
"test_fakenewsredis.py::TestFakeStrictRedis::test_sort_descending",
"test_fakenewsredis.py::TestFakeStrictRedis::test_sort_range_offset_norange",
"test_fakenewsredis.py::TestFakeStrictRedis::test_sort_range_offset_range",
"test_fakenewsredis.py::TestFakeStrictRedis::test_sort_range_offset_range_and_desc",
"test_fakenewsredis.py::TestFakeStrictRedis::test_sort_range_with_large_range",
"test_fakenewsredis.py::TestFakeStrictRedis::test_sort_with_by_and_get_option",
"test_fakenewsredis.py::TestFakeStrictRedis::test_sort_with_hash",
"test_fakenewsredis.py::TestFakeStrictRedis::test_sort_with_set",
"test_fakenewsredis.py::TestFakeStrictRedis::test_sort_with_store_option",
"test_fakenewsredis.py::TestFakeStrictRedis::test_sort_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_spop",
"test_fakenewsredis.py::TestFakeStrictRedis::test_spop_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_srandmember",
"test_fakenewsredis.py::TestFakeStrictRedis::test_srandmember_number",
"test_fakenewsredis.py::TestFakeStrictRedis::test_srandmember_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_srem",
"test_fakenewsredis.py::TestFakeStrictRedis::test_srem_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_sscan",
"test_fakenewsredis.py::TestFakeStrictRedis::test_strlen",
"test_fakenewsredis.py::TestFakeStrictRedis::test_strlen_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_substr",
"test_fakenewsredis.py::TestFakeStrictRedis::test_substr_noexist_key",
"test_fakenewsredis.py::TestFakeStrictRedis::test_substr_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_sunion",
"test_fakenewsredis.py::TestFakeStrictRedis::test_sunion_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_sunionstore",
"test_fakenewsredis.py::TestFakeStrictRedis::test_ttl_should_return_minus_one_for_non_expiring_key",
"test_fakenewsredis.py::TestFakeStrictRedis::test_ttl_should_return_minus_two_for_non_existent_key",
"test_fakenewsredis.py::TestFakeStrictRedis::test_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_unset_bits",
"test_fakenewsredis.py::TestFakeStrictRedis::test_watch_state_is_cleared_across_multiple_watches",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zadd",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zadd_errors",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zadd_multiple",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zadd_uses_str",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zadd_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zcard",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zcard_non_existent_key",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zcard_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zcount",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zcount_exclusive",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zcount_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zincrby",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zincrby_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zinterstore",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zinterstore_max",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zinterstore_mixed_set_types",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zinterstore_nokey",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zinterstore_onekey",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zinterstore_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zlexcount",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zlexcount_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zrange_descending",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zrange_descending_with_scores",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zrange_same_score",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zrange_with_positive_indices",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zrange_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zrangebylex",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zrangebylex_raises_error",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zrangebylex_with_limit",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zrangebylex_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zrangebyscore",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zrangebyscore_raises_error",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zrangebyscore_slice",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zrangebyscore_withscores",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zrangebyscore_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zrangebysore_exclusive",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zrank",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zrank_non_existent_member",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zrank_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zrem",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zrem_non_existent_member",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zrem_numeric_member",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zrem_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zremrangebylex",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zremrangebylex_badkey",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zremrangebylex_error",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zremrangebylex_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zremrangebyrank",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zremrangebyrank_negative_indices",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zremrangebyrank_out_of_bounds",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zremrangebyrank_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zremrangebyscore",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zremrangebyscore_badkey",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zremrangebyscore_exclusive",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zremrangebyscore_raises_error",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zremrangebyscore_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zrevrange",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zrevrange_sorted_keys",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zrevrange_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zrevrangebylex",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zrevrangebylex_raises_error",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zrevrangebylex_with_limit",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zrevrangebylex_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zrevrangebyscore",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zrevrangebyscore_exclusive",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zrevrangebyscore_raises_error",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zrevrangebyscore_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zrevrank",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zrevrank_non_existent_member",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zrevrank_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zscore",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zscore_non_existent_member",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zscore_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zunionstore",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zunionstore_badkey",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zunionstore_max",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zunionstore_min",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zunionstore_mixed_set_types",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zunionstore_nokey",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zunionstore_sum",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zunionstore_weights",
"test_fakenewsredis.py::TestFakeStrictRedis::test_zunionstore_wrong_type",
"test_fakenewsredis.py::TestFakeRedis::test_expire_should_expire_immediately_with_millisecond_timedelta",
"test_fakenewsredis.py::TestFakeRedis::test_expire_should_expire_key",
"test_fakenewsredis.py::TestFakeRedis::test_expire_should_expire_key_using_timedelta",
"test_fakenewsredis.py::TestFakeRedis::test_expire_should_not_handle_floating_point_values",
"test_fakenewsredis.py::TestFakeRedis::test_expire_should_return_false_for_missing_key",
"test_fakenewsredis.py::TestFakeRedis::test_expire_should_return_true_for_existing_key",
"test_fakenewsredis.py::TestFakeRedis::test_expireat_should_expire_key_by_datetime",
"test_fakenewsredis.py::TestFakeRedis::test_expireat_should_expire_key_by_timestamp",
"test_fakenewsredis.py::TestFakeRedis::test_expireat_should_return_false_for_missing_key",
"test_fakenewsredis.py::TestFakeRedis::test_expireat_should_return_true_for_existing_key",
"test_fakenewsredis.py::TestFakeRedis::test_lock",
"test_fakenewsredis.py::TestFakeRedis::test_lrem_default_value",
"test_fakenewsredis.py::TestFakeRedis::test_lrem_does_not_exist",
"test_fakenewsredis.py::TestFakeRedis::test_lrem_negative_count",
"test_fakenewsredis.py::TestFakeRedis::test_lrem_postitive_count",
"test_fakenewsredis.py::TestFakeRedis::test_lrem_return_value",
"test_fakenewsredis.py::TestFakeRedis::test_lrem_zero_count",
"test_fakenewsredis.py::TestFakeRedis::test_pexpire_should_expire_key",
"test_fakenewsredis.py::TestFakeRedis::test_pexpire_should_expire_key_using_timedelta",
"test_fakenewsredis.py::TestFakeRedis::test_pexpire_should_return_falsey_for_missing_key",
"test_fakenewsredis.py::TestFakeRedis::test_pexpire_should_return_truthy_for_existing_key",
"test_fakenewsredis.py::TestFakeRedis::test_pexpireat_should_expire_key_by_datetime",
"test_fakenewsredis.py::TestFakeRedis::test_pexpireat_should_expire_key_by_timestamp",
"test_fakenewsredis.py::TestFakeRedis::test_pexpireat_should_return_false_for_missing_key",
"test_fakenewsredis.py::TestFakeRedis::test_pexpireat_should_return_true_for_existing_key",
"test_fakenewsredis.py::TestFakeRedis::test_psetex_expire_value",
"test_fakenewsredis.py::TestFakeRedis::test_psetex_expire_value_using_timedelta",
"test_fakenewsredis.py::TestFakeRedis::test_pttl_should_return_none_for_non_expiring_key",
"test_fakenewsredis.py::TestFakeRedis::test_pttl_should_return_value_for_expiring_key",
"test_fakenewsredis.py::TestFakeRedis::test_set_ex_should_expire_value",
"test_fakenewsredis.py::TestFakeRedis::test_set_nx_doesnt_set_value_twice",
"test_fakenewsredis.py::TestFakeRedis::test_set_px_should_expire_value",
"test_fakenewsredis.py::TestFakeRedis::test_set_xx_set_value_when_exists",
"test_fakenewsredis.py::TestFakeRedis::test_setex",
"test_fakenewsredis.py::TestFakeRedis::test_setex_using_timedelta",
"test_fakenewsredis.py::TestFakeRedis::test_ttl_should_return_none_for_non_expiring_key",
"test_fakenewsredis.py::TestFakeRedis::test_ttl_should_return_value_for_expiring_key",
"test_fakenewsredis.py::TestFakeRedis::test_ttls_should_always_be_long",
"test_fakenewsredis.py::TestFakeRedis::test_zadd_deprecated",
"test_fakenewsredis.py::TestFakeRedis::test_zadd_missing_required_params",
"test_fakenewsredis.py::TestFakeRedis::test_zadd_with_multiple_keypairs",
"test_fakenewsredis.py::TestFakeRedis::test_zadd_with_name_is_non_string",
"test_fakenewsredis.py::TestFakeRedis::test_zadd_with_single_keypair",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_append",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_append_with_no_preexisting_key",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_append_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_basic_sort",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_bitcount",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_bitcount_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_blocking_operations_when_empty",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_blpop_allow_single_key",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_blpop_single_list",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_blpop_test_multiple_lists",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_blpop_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_brpop_single_key",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_brpop_test_multiple_lists",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_brpop_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_brpoplpush_multi_keys",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_brpoplpush_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_contains",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_decr",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_decr_badtype",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_decr_newkey",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_delete",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_delete_expire",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_delete_multiple",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_delete_nonexistent_key",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_echo",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_empty_sort",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_exists",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_flushdb",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_foo",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_get_does_not_exist",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_get_invalid_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_get_with_non_str_keys",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_getbit",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_getbit_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_getset_exists",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_getset_not_exist",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_getset_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_hdel",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_hdel_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_hexists",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_hexists_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_hgetall",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_hgetall_empty_key",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_hgetall_with_tuples",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_hgetall_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_hincrby",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_hincrby_with_no_starting_value",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_hincrby_with_range_param",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_hincrby_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_hincrbyfloat",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_hincrbyfloat_on_non_float_value_raises_error",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_hincrbyfloat_precision",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_hincrbyfloat_with_no_starting_value",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_hincrbyfloat_with_non_float_amount_raises_error",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_hincrbyfloat_with_range_param",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_hincrbyfloat_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_hkeys",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_hkeys_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_hlen",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_hlen_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_hmget",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_hmget_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_hmset_convert_values",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_hmset_does_not_mutate_input_params",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_hmset_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_hmsetset",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_hmsetset_empty_raises_error",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_hscan",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_hset_then_hget",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_hset_update",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_hset_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_hsetnx",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_hvals",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_hvals_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_incr_bad_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_incr_by",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_incr_followed_by_mget",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_incr_followed_by_mget_returns_strings",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_incr_preexisting_key",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_incr_with_float",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_incr_with_no_preexisting_key",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_incrbyfloat",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_incrbyfloat_bad_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_incrbyfloat_precision",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_incrbyfloat_with_noexist",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_key_patterns",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_lindex",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_lindex_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_linsert_after",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_linsert_before",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_linsert_no_pivot",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_linsert_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_llen",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_llen_no_exist",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_llen_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_lpop",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_lpop_empty_list",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_lpop_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_lpush_key_does_not_exist",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_lpush_then_lrange_all",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_lpush_then_lrange_portion",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_lpush_with_nonstr_key",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_lpush_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_lpushx",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_lpushx_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_lrem_default_value",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_lrem_does_not_exist",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_lrem_negative_count",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_lrem_positive_count",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_lrem_return_value",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_lrem_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_lrem_zero_count",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_lset",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_lset_index_out_of_range",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_lset_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_ltrim",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_ltrim_with_non_existent_key",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_ltrim_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_mget",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_mget_mixed_types",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_mget_with_no_keys_raises_error",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_move_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_mset",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_mset_accepts_kwargs",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_mset_with_no_keys_raises_error",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_msetnx",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_multidb",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_multiple_bits_set",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_multiple_successful_watch_calls",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_persist",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_pfadd",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_pfcount",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_pfmerge",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_ping",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_pipeline",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_pipeline_as_context_manager",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_pipeline_ignore_errors",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_pipeline_non_transactional",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_pipeline_proxies_to_redis_object",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_pipeline_raises_when_watched_key_changed",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_pipeline_succeeds_despite_unwatched_key_changed",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_pipeline_succeeds_when_watching_nonexistent_key",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_pipeline_transaction_shortcut",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_pipeline_transaction_value_from_callable",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_pttl_should_return_minus_one_for_non_expiring_key",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_pttl_should_return_minus_two_for_non_existent_key",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_pubsub_binary_message",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_pubsub_ignore_sub_messages_listen",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_pubsub_listen",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_pubsub_psubscribe",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_pubsub_punsubscribe",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_pubsub_subscribe",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_pubsub_unsubscribe",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_rename",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_rename_does_exist",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_rename_nonexistent_key",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_renamenx_doesnt_exist",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_rpop",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_rpop_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_rpoplpush",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_rpoplpush_to_nonexistent_destination",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_rpoplpush_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_rpush",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_rpush_then_lrange_with_nested_list1",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_rpush_then_lrange_with_nested_list2",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_rpush_then_lrange_with_nested_list3",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_rpush_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_rpushx",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_rpushx_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_sadd",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_sadd_as_str_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_sadd_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_saving_non_ascii_chars_as_key",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_saving_non_ascii_chars_as_value",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_saving_unicode_type_as_key",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_saving_unicode_type_as_value",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_scan",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_scan_all_in_single_call",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_scan_iter_multiple_pages",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_scan_iter_multiple_pages_with_match",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_scan_iter_single_page",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_scan_multiple_pages_with_count_arg",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_scan_single",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_scard",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_scard_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_sdiff",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_sdiff_empty",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_sdiff_one_key",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_sdiff_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_sdiffstore",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_set_None_value",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_set_ex",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_set_ex_using_timedelta",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_set_existing_key_persists",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_set_float_value",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_set_non_str_keys",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_set_px",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_set_px_using_timedelta",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_set_raises_wrong_ex",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_set_raises_wrong_px",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_set_then_get",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_set_using_timedelta_raises_wrong_ex",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_set_using_timedelta_raises_wrong_px",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_setbit_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_setbits_and_getkeys",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_setex",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_setex_raises_wrong_ex",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_setex_using_float",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_setex_using_timedelta",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_setex_using_timedelta_raises_wrong_ex",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_setitem_getitem",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_setnx",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_setrange",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_sinter",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_sinter_bytes_keys",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_sinter_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_sinterstore",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_sismember",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_sismember_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_smembers",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_smembers_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_smove",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_smove_non_existent_key",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_sort_alpha",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_sort_descending",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_sort_range_offset_norange",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_sort_range_offset_range",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_sort_range_offset_range_and_desc",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_sort_range_with_large_range",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_sort_with_by_and_get_option",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_sort_with_hash",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_sort_with_set",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_sort_with_store_option",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_sort_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_spop",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_spop_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_srandmember",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_srandmember_number",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_srandmember_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_srem",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_srem_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_sscan",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_strlen",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_strlen_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_substr",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_substr_noexist_key",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_substr_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_sunion",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_sunion_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_sunionstore",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_ttl_should_return_minus_one_for_non_expiring_key",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_ttl_should_return_minus_two_for_non_existent_key",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_unset_bits",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_watch_state_is_cleared_across_multiple_watches",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zadd",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zadd_errors",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zadd_multiple",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zadd_uses_str",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zadd_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zcard",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zcard_non_existent_key",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zcard_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zcount",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zcount_exclusive",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zcount_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zincrby",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zincrby_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zinterstore",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zinterstore_max",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zinterstore_mixed_set_types",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zinterstore_nokey",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zinterstore_onekey",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zinterstore_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zlexcount",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zlexcount_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zrange_descending",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zrange_descending_with_scores",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zrange_same_score",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zrange_with_positive_indices",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zrange_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zrangebylex",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zrangebylex_raises_error",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zrangebylex_with_limit",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zrangebylex_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zrangebyscore",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zrangebyscore_raises_error",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zrangebyscore_slice",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zrangebyscore_withscores",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zrangebyscore_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zrangebysore_exclusive",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zrank",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zrank_non_existent_member",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zrank_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zrem",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zrem_non_existent_member",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zrem_numeric_member",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zrem_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zremrangebylex",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zremrangebylex_badkey",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zremrangebylex_error",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zremrangebylex_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zremrangebyrank",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zremrangebyrank_negative_indices",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zremrangebyrank_out_of_bounds",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zremrangebyrank_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zremrangebyscore",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zremrangebyscore_badkey",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zremrangebyscore_exclusive",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zremrangebyscore_raises_error",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zremrangebyscore_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zrevrange",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zrevrange_sorted_keys",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zrevrange_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zrevrangebylex",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zrevrangebylex_raises_error",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zrevrangebylex_with_limit",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zrevrangebylex_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zrevrangebyscore",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zrevrangebyscore_exclusive",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zrevrangebyscore_raises_error",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zrevrangebyscore_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zrevrank",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zrevrank_non_existent_member",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zrevrank_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zscore",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zscore_non_existent_member",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zscore_wrong_type",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zunionstore",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zunionstore_badkey",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zunionstore_max",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zunionstore_min",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zunionstore_mixed_set_types",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zunionstore_nokey",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zunionstore_sum",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zunionstore_weights",
"test_fakenewsredis.py::TestFakeStrictRedisDecodeResponses::test_zunionstore_wrong_type",
"test_fakenewsredis.py::TestFakeRedisDecodeResponses::test_expire_should_expire_immediately_with_millisecond_timedelta",
"test_fakenewsredis.py::TestFakeRedisDecodeResponses::test_expire_should_expire_key",
"test_fakenewsredis.py::TestFakeRedisDecodeResponses::test_expire_should_expire_key_using_timedelta",
"test_fakenewsredis.py::TestFakeRedisDecodeResponses::test_expire_should_not_handle_floating_point_values",
"test_fakenewsredis.py::TestFakeRedisDecodeResponses::test_expire_should_return_false_for_missing_key",
"test_fakenewsredis.py::TestFakeRedisDecodeResponses::test_expire_should_return_true_for_existing_key",
"test_fakenewsredis.py::TestFakeRedisDecodeResponses::test_expireat_should_expire_key_by_datetime",
"test_fakenewsredis.py::TestFakeRedisDecodeResponses::test_expireat_should_expire_key_by_timestamp",
"test_fakenewsredis.py::TestFakeRedisDecodeResponses::test_expireat_should_return_false_for_missing_key",
"test_fakenewsredis.py::TestFakeRedisDecodeResponses::test_expireat_should_return_true_for_existing_key",
"test_fakenewsredis.py::TestFakeRedisDecodeResponses::test_lock",
"test_fakenewsredis.py::TestFakeRedisDecodeResponses::test_lrem_default_value",
"test_fakenewsredis.py::TestFakeRedisDecodeResponses::test_lrem_does_not_exist",
"test_fakenewsredis.py::TestFakeRedisDecodeResponses::test_lrem_negative_count",
"test_fakenewsredis.py::TestFakeRedisDecodeResponses::test_lrem_postitive_count",
"test_fakenewsredis.py::TestFakeRedisDecodeResponses::test_lrem_return_value",
"test_fakenewsredis.py::TestFakeRedisDecodeResponses::test_lrem_zero_count",
"test_fakenewsredis.py::TestFakeRedisDecodeResponses::test_pexpire_should_expire_key",
"test_fakenewsredis.py::TestFakeRedisDecodeResponses::test_pexpire_should_expire_key_using_timedelta",
"test_fakenewsredis.py::TestFakeRedisDecodeResponses::test_pexpire_should_return_falsey_for_missing_key",
"test_fakenewsredis.py::TestFakeRedisDecodeResponses::test_pexpire_should_return_truthy_for_existing_key",
"test_fakenewsredis.py::TestFakeRedisDecodeResponses::test_pexpireat_should_expire_key_by_datetime",
"test_fakenewsredis.py::TestFakeRedisDecodeResponses::test_pexpireat_should_expire_key_by_timestamp",
"test_fakenewsredis.py::TestFakeRedisDecodeResponses::test_pexpireat_should_return_false_for_missing_key",
"test_fakenewsredis.py::TestFakeRedisDecodeResponses::test_pexpireat_should_return_true_for_existing_key",
"test_fakenewsredis.py::TestFakeRedisDecodeResponses::test_psetex_expire_value",
"test_fakenewsredis.py::TestFakeRedisDecodeResponses::test_psetex_expire_value_using_timedelta",
"test_fakenewsredis.py::TestFakeRedisDecodeResponses::test_pttl_should_return_none_for_non_expiring_key",
"test_fakenewsredis.py::TestFakeRedisDecodeResponses::test_pttl_should_return_value_for_expiring_key",
"test_fakenewsredis.py::TestFakeRedisDecodeResponses::test_set_ex_should_expire_value",
"test_fakenewsredis.py::TestFakeRedisDecodeResponses::test_set_nx_doesnt_set_value_twice",
"test_fakenewsredis.py::TestFakeRedisDecodeResponses::test_set_px_should_expire_value",
"test_fakenewsredis.py::TestFakeRedisDecodeResponses::test_set_xx_set_value_when_exists",
"test_fakenewsredis.py::TestFakeRedisDecodeResponses::test_setex",
"test_fakenewsredis.py::TestFakeRedisDecodeResponses::test_setex_using_timedelta",
"test_fakenewsredis.py::TestFakeRedisDecodeResponses::test_ttl_should_return_none_for_non_expiring_key",
"test_fakenewsredis.py::TestFakeRedisDecodeResponses::test_ttl_should_return_value_for_expiring_key",
"test_fakenewsredis.py::TestFakeRedisDecodeResponses::test_ttls_should_always_be_long",
"test_fakenewsredis.py::TestFakeRedisDecodeResponses::test_zadd_deprecated",
"test_fakenewsredis.py::TestFakeRedisDecodeResponses::test_zadd_missing_required_params",
"test_fakenewsredis.py::TestFakeRedisDecodeResponses::test_zadd_with_multiple_keypairs",
"test_fakenewsredis.py::TestFakeRedisDecodeResponses::test_zadd_with_name_is_non_string",
"test_fakenewsredis.py::TestFakeRedisDecodeResponses::test_zadd_with_single_keypair",
"test_fakenewsredis.py::TestInitArgs::test_can_accept_any_kwargs",
"test_fakenewsredis.py::TestInitArgs::test_can_pass_through_extra_args",
"test_fakenewsredis.py::TestInitArgs::test_from_url",
"test_fakenewsredis.py::TestInitArgs::test_from_url_db_value_error",
"test_fakenewsredis.py::TestInitArgs::test_from_url_with_db_arg",
"test_fakenewsredis.py::TestImportation::test_searches_for_c_stdlib_and_raises_if_missing"
]
| []
| BSD License | 1,882 | [
"README.rst",
"fakenewsredis.py"
]
| [
"README.rst",
"fakenewsredis.py"
]
|
|
tox-dev__tox-travis-93 | 53867873da9189cc04ed043147cbe1c915fb69d8 | 2017-11-12 22:43:57 | 53867873da9189cc04ed043147cbe1c915fb69d8 | codecov-io: # [Codecov](https://codecov.io/gh/tox-dev/tox-travis/pull/93?src=pr&el=h1) Report
> Merging [#93](https://codecov.io/gh/tox-dev/tox-travis/pull/93?src=pr&el=desc) into [master](https://codecov.io/gh/tox-dev/tox-travis/commit/53867873da9189cc04ed043147cbe1c915fb69d8?src=pr&el=desc) will **increase** coverage by `0.1%`.
> The diff coverage is `100%`.
[](https://codecov.io/gh/tox-dev/tox-travis/pull/93?src=pr&el=tree)
```diff
@@ Coverage Diff @@
## master #93 +/- ##
=========================================
+ Coverage 88.88% 88.99% +0.1%
=========================================
Files 5 5
Lines 207 209 +2
Branches 47 48 +1
=========================================
+ Hits 184 186 +2
Misses 19 19
Partials 4 4
```
| [Impacted Files](https://codecov.io/gh/tox-dev/tox-travis/pull/93?src=pr&el=tree) | Coverage Δ | |
|---|---|---|
| [src/tox\_travis/hooks.py](https://codecov.io/gh/tox-dev/tox-travis/pull/93?src=pr&el=tree#diff-c3JjL3RveF90cmF2aXMvaG9va3MucHk=) | `100% <100%> (ø)` | :arrow_up: |
------
[Continue to review full report at Codecov](https://codecov.io/gh/tox-dev/tox-travis/pull/93?src=pr&el=continue).
> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
> `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
> Powered by [Codecov](https://codecov.io/gh/tox-dev/tox-travis/pull/93?src=pr&el=footer). Last update [5386787...61c0497](https://codecov.io/gh/tox-dev/tox-travis/pull/93?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).
ryanhiebert: Sounds good. The release will be the test of that, though I'm fairly confident it will work from my experimenting on #91. | diff --git a/.travis.yml b/.travis.yml
index 5b2f4fe..efd799d 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -18,21 +18,27 @@ install:
- pip install wheel codecov coverage
- python setup.py bdist_wheel
- pip install ./dist/tox_travis-*.whl
-script:
- - tox --installpkg ./dist/tox_travis-*.whl --travis-after
+script: tox --installpkg ./dist/tox_travis-*.whl
after_success: coverage combine && codecov
-branches:
- only:
- - master
- - /^\d+(\.\d+)*$/
-matrix:
+if: tag IS present OR branch = master
+jobs:
fast_finish: true
include:
- python: 3.6
env: TOXENV=docs
- python: 3.6
env: TOXENV=desc
+ - stage: deploy
+ python: 3.6
+ env: TRAVIS_STAGE=deploy
+ install: true
+ script: true
+ after_success: true
+
+stages:
+ - name: deploy
+ if: tag IS present
deploy:
provider: pypi
@@ -41,6 +47,5 @@ deploy:
secure: KjQrEjwmfP+jqdHNQ6bJoNjOJHHz0kirrSORat2uJTulXaUs/nuDcZqTu7gxMFaM92z3eJZzTZmxO71cDhJiBt+FQhEtL/q8wd7Fv5d5v5EIlLFNqdEyCaTthSgXQa/HJTtbzjdFIEN8qCofHu+zEWMnb1ZHgUcK7hZHMCrHcVF4kD+k1myNro+1Pp/sGIUMUOkqocz+8OI2FuEQh0txXl0MLf2UEk53EK2noD4D/fm/YDDYJbAWlNPBbCBaU/ZGfzuFivh00bx9lAg7UB6t/A3iIasRUiAJbHdxvrxxGFAeOV/t09TcTtEcwBRyPe8JzSuReCROccyFB2TLOzfkt9h7TkdC2CWrMmXpI6UogTct++r3kavdsJuAZMbSy1jrnxkxtB1CW7DOly4v4JuyewpET7CnTjkhd9zIowESwJFjxwmns63AS2okQdPTCqsbbNp53Jk5fpf6qXwMFdaHT1kU1MpwoQPT0HnwLz3xybvjgfgu3t4KfEBvc0DCp89VMjCM9xkKTlziZkwOhXqaNhu+cVqo1/eUY/HDT/7V7xiL/U6U11UOrqtxkdDofoIl4NuiT7uoVaVctm/Y4kBEkJRZCwcjRsZJ0c06SvMvxhMDBUEM5IiXS6tH6Zp08MDYlclpKFGKdzOrxP2X0rVFIZ99KLyhfRNZuZcu92tDpP8=
on:
tags: true
- python: 3.6
- condition: $TOXENV != docs && $TOXENV != desc
+ condition: $TRAVIS_STAGE = deploy
distributions: bdist_wheel
diff --git a/HISTORY.rst b/HISTORY.rst
index fe03e3a..c508bfe 100644
--- a/HISTORY.rst
+++ b/HISTORY.rst
@@ -1,6 +1,11 @@
0.10 (TBD)
++++++++++
+* Deprecate the After All feature.
+ Travis now has `Build Stages`_, which are a better solution.
+
+.. _`Build Stages`: https://docs.travis-ci.com/user/build-stages
+
0.9 (2017-11-12)
++++++++++++++++
diff --git a/docs/after.rst b/docs/after.rst
index 4de27af..da02c95 100644
--- a/docs/after.rst
+++ b/docs/after.rst
@@ -2,6 +2,22 @@
After All
=========
+.. deprecated:: 0.10
+
+.. warning::
+
+ This feature is deprecated.
+
+ Travis has added `Build Stages`_,
+ which are a better solution to this problem.
+ You will also likely want to check out `Conditions`_,
+ which make it much easier to determine
+ which jobs, stages, and builds will run.
+
+.. _`Build Stages`: https://docs.travis-ci.com/user/build-stages
+.. _`Conditions`: https://docs.travis-ci.com/user/conditional-builds-stages-jobs
+
+
Inspired by `travis-after-all`_ and `travis_after_all`_,
this feature allows a job to wait for other jobs to finish
before it calls itself complete.
@@ -77,7 +93,7 @@ that corresponds to using the above ``travis:after`` section:
This example deploys when the build is from a tag
and the build is on Python 3.5
and the build is using DJANGO="1.8".
-Together ``tox --travis-after`` and Tox's ``on`` conditions
+Together ``tox --travis-after`` and Travis' ``on`` conditions
make sure that the deploy only happens after all tests pass.
If any configuration item does not match,
diff --git a/src/tox_travis/hooks.py b/src/tox_travis/hooks.py
index 7624593..9b84632 100644
--- a/src/tox_travis/hooks.py
+++ b/src/tox_travis/hooks.py
@@ -51,6 +51,13 @@ def tox_configure(config):
for envconfig in config.envconfigs.values():
envconfig.ignore_outcome = False
+ # after
+ if config.option.travis_after:
+ print('The after all feature has been deprecated. Check out Travis\' '
+ 'build stages, which are a better solution. '
+ 'See https://tox-travis.readthedocs.io/en/stable/after.html '
+ 'for more details.', file=sys.stderr)
+
def tox_subcommand_test_post(config):
"""Wait for this job if the configuration matches."""
diff --git a/tox.ini b/tox.ini
index d1bb173..898e673 100644
--- a/tox.ini
+++ b/tox.ini
@@ -28,9 +28,6 @@ deps =
commands =
python setup.py check --restructuredtext --strict
-[travis:after]
-toxenv = py36
-
[flake8]
ignore = D203
| Consider deprecating travis:after in favor of Build Stages
https://blog.travis-ci.com/2017-05-11-introducing-build-stages
I don't have any plans to remove travis:after, but with the announcement of build stages for Travis, I'm watching it closely, and considering whether it will fully cover the use-cases that travis:after does. I suspect that it will end up as the better option, and that we will end up adding a note to the docs declaring that the better fix.
Right now it's still early days, and we need to watch and see. There are still bugs in this beta feature that need to be ironed out, but I'm very glad to see Travis supporting this feature natively. | tox-dev/tox-travis | diff --git a/tests/test_after.py b/tests/test_after.py
index b48316b..7d934d4 100644
--- a/tests/test_after.py
+++ b/tests/test_after.py
@@ -1,15 +1,65 @@
"""Tests of the --travis-after flag."""
import pytest
import py
+import subprocess
+from contextlib import contextmanager
from tox_travis.after import (
travis_after,
after_config_matches,
)
+ini = b"""
+[tox]
+envlist = py35, py36
+"""
+
+coverage_config = b"""
+[run]
+branch = True
+parallel = True
+source = tox_travis
+
+[paths]
+source =
+ src
+ */site-packages
+"""
+
+
class TestAfter:
"""Test the logic of waiting for other jobs to finish."""
+ def call(self, command):
+ """Return the raw output of the given command."""
+ proc = subprocess.Popen(
+ command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+ stdout, stderr = proc.communicate()
+ return proc.returncode, stdout.decode('utf-8'), stderr.decode('utf-8')
+
+ @contextmanager
+ def configure(self, tmpdir, monkeypatch, tox_ini, version):
+ """Configure the environment for a test."""
+ origdir = tmpdir.chdir()
+ tmpdir.join('tox.ini').write(tox_ini)
+ tmpdir.join('.coveragerc').write(coverage_config)
+ monkeypatch.setenv('TRAVIS', 'true')
+ monkeypatch.setenv('TRAVIS_PYTHON_VERSION', version)
+
+ yield
+
+ # Change back to the original directory
+ # Copy .coverage.* report files
+ origdir.chdir()
+ for f in tmpdir.listdir(lambda f: f.basename.startswith('.coverage.')):
+ f.copy(origdir)
+
+ def test_after_deprecated(self, tmpdir, monkeypatch):
+ """Show deprecation message when using --travis-after."""
+ with self.configure(tmpdir, monkeypatch, ini, '3.6'):
+ _, _, stderr = self.call(['tox', '-l', '--travis-after'])
+ assert 'The after all feature has been deprecated.' in stderr
+
def test_pull_request(self, mocker, monkeypatch, capsys):
"""Pull requests should not run after-all."""
mocker.patch('tox_travis.after.after_config_matches',
diff --git a/tests/test_envlist.py b/tests/test_envlist.py
index 91daef9..72890a3 100644
--- a/tests/test_envlist.py
+++ b/tests/test_envlist.py
@@ -210,7 +210,7 @@ class TestToxEnv:
assert self.tox_envs() == expected
def test_travis_config_filename(self, tmpdir, monkeypatch):
- """Give the correct env for CPython 2.7."""
+ """Give the correct env for manual filename."""
with self.configure(tmpdir, monkeypatch, tox_ini, 'CPython', 3, 6,
ini_filename='spam.ini'):
assert self.tox_envs(ini_filename='spam.ini') == ['py36']
| {
"commit_name": "merge_commit",
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 2,
"test_score": 0
},
"num_modified_files": 5
} | 0.9 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"pytest",
"pytest-mock",
"mock",
"coverage_pth"
],
"pre_install": null,
"python": "3.6",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work
certifi==2021.5.30
coverage==6.2
coverage-pth==0.0.2
distlib==0.3.9
filelock==3.4.1
importlib-metadata==4.8.3
importlib-resources==5.4.0
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
mock==5.2.0
more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work
packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work
platformdirs==2.4.0
pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pytest==6.2.4
pytest-mock==3.6.1
six==1.17.0
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
tox==3.28.0
-e git+https://github.com/tox-dev/tox-travis.git@53867873da9189cc04ed043147cbe1c915fb69d8#egg=tox_travis
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
virtualenv==20.17.1
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
| name: tox-travis
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=21.4.0=pyhd3eb1b0_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- importlib_metadata=4.8.1=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- more-itertools=8.12.0=pyhd3eb1b0_0
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=21.3=pyhd3eb1b0_0
- pip=21.2.2=py36h06a4308_0
- pluggy=0.13.1=py36h06a4308_0
- py=1.11.0=pyhd3eb1b0_0
- pyparsing=3.0.4=pyhd3eb1b0_0
- pytest=6.2.4=py36h06a4308_2
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- toml=0.10.2=pyhd3eb1b0_0
- typing_extensions=4.1.1=pyh06a4308_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zipp=3.6.0=pyhd3eb1b0_0
- zlib=1.2.13=h5eee18b_1
- pip:
- coverage==6.2
- coverage-pth==0.0.2
- distlib==0.3.9
- filelock==3.4.1
- importlib-metadata==4.8.3
- importlib-resources==5.4.0
- mock==5.2.0
- platformdirs==2.4.0
- pytest-mock==3.6.1
- six==1.17.0
- tox==3.28.0
- virtualenv==20.17.1
prefix: /opt/conda/envs/tox-travis
| [
"tests/test_after.py::TestAfter::test_after_deprecated"
]
| [
"tests/test_envlist.py::TestToxEnv::test_travis_config_filename",
"tests/test_envlist.py::TestToxEnv::test_travis_default_26",
"tests/test_envlist.py::TestToxEnv::test_travis_default_27",
"tests/test_envlist.py::TestToxEnv::test_travis_default_32",
"tests/test_envlist.py::TestToxEnv::test_travis_default_33",
"tests/test_envlist.py::TestToxEnv::test_travis_default_34",
"tests/test_envlist.py::TestToxEnv::test_travis_default_pypy",
"tests/test_envlist.py::TestToxEnv::test_travis_default_pypy3",
"tests/test_envlist.py::TestToxEnv::test_travis_python_version_py27",
"tests/test_envlist.py::TestToxEnv::test_travis_python_version_py35",
"tests/test_envlist.py::TestToxEnv::test_travis_python_version_pypy",
"tests/test_envlist.py::TestToxEnv::test_travis_python_version_pypy3",
"tests/test_envlist.py::TestToxEnv::test_travis_not_matching",
"tests/test_envlist.py::TestToxEnv::test_travis_nightly",
"tests/test_envlist.py::TestToxEnv::test_travis_override",
"tests/test_envlist.py::TestToxEnv::test_respect_overridden_toxenv",
"tests/test_envlist.py::TestToxEnv::test_keep_if_no_match",
"tests/test_envlist.py::TestToxEnv::test_default_tox_ini_overrides",
"tests/test_envlist.py::TestToxEnv::test_factors",
"tests/test_envlist.py::TestToxEnv::test_match_and_keep",
"tests/test_envlist.py::TestToxEnv::test_django_factors",
"tests/test_envlist.py::TestToxEnv::test_non_python_factor",
"tests/test_envlist.py::TestToxEnv::test_travis_factors_py27",
"tests/test_envlist.py::TestToxEnv::test_travis_factors_py35",
"tests/test_envlist.py::TestToxEnv::test_travis_factors_osx",
"tests/test_envlist.py::TestToxEnv::test_travis_factors_py27_osx",
"tests/test_envlist.py::TestToxEnv::test_travis_factors_language",
"tests/test_envlist.py::TestToxEnv::test_travis_env_py27",
"tests/test_envlist.py::TestToxEnv::test_travis_env_py27_dj19",
"tests/test_envlist.py::TestToxEnv::test_travis_env_py35_dj110"
]
| [
"tests/test_after.py::TestAfter::test_pull_request",
"tests/test_after.py::TestAfter::test_not_after_config_matches",
"tests/test_after.py::TestAfter::test_no_github_token",
"tests/test_after.py::TestAfter::test_travis_environment_build_id",
"tests/test_after.py::TestAfter::test_travis_environment_job_number",
"tests/test_after.py::TestAfter::test_travis_environment_api_url",
"tests/test_after.py::TestAfter::test_travis_env_polling_interval",
"tests/test_after.py::TestAfter::test_travis_env_passed",
"tests/test_after.py::TestAfter::test_travis_env_failed",
"tests/test_after.py::TestAfter::test_after_config_matches_unconfigured",
"tests/test_after.py::TestAfter::test_after_config_matches_toxenv_match",
"tests/test_after.py::TestAfter::test_after_config_matches_toxenv_nomatch",
"tests/test_after.py::TestAfter::test_after_config_matches_envlist_match",
"tests/test_after.py::TestAfter::test_after_config_matches_envlist_nomatch",
"tests/test_after.py::TestAfter::test_after_config_matches_env_match",
"tests/test_after.py::TestAfter::test_after_config_matches_env_nomatch",
"tests/test_envlist.py::TestToxEnv::test_not_travis",
"tests/test_envlist.py::TestToxEnv::test_legacy_warning",
"tests/test_envlist.py::TestToxEnv::test_travis_ignore_outcome",
"tests/test_envlist.py::TestToxEnv::test_travis_ignore_outcome_unignore_outcomes",
"tests/test_envlist.py::TestToxEnv::test_travis_ignore_outcome_not_unignore_outcomes",
"tests/test_envlist.py::TestToxEnv::test_local_ignore_outcome_unignore_outcomes"
]
| []
| MIT License | 1,883 | [
"docs/after.rst",
"HISTORY.rst",
"src/tox_travis/hooks.py",
".travis.yml",
"tox.ini"
]
| [
"docs/after.rst",
"HISTORY.rst",
"src/tox_travis/hooks.py",
".travis.yml",
"tox.ini"
]
|
watson-developer-cloud__python-sdk-305 | f0fda953cf81204d2bf11d61d1e792292ced0d6f | 2017-11-13 03:13:48 | f0fda953cf81204d2bf11d61d1e792292ced0d6f | diff --git a/examples/conversation_tone_analyzer_integration/tone_detection.py b/examples/conversation_tone_analyzer_integration/tone_detection.py
index b46444f9..d3ac374f 100644
--- a/examples/conversation_tone_analyzer_integration/tone_detection.py
+++ b/examples/conversation_tone_analyzer_integration/tone_detection.py
@@ -31,21 +31,20 @@ EMOTION_TONE_LABEL = 'emotion_tone'
WRITING_TONE_LABEL = 'writing_tone'
SOCIAL_TONE_LABEL = 'social_tone'
-"""
-updateUserTone processes the Tone Analyzer payload to pull out the emotion,
-writing and social tones, and identify the meaningful tones (i.e.,
-those tones that meet the specified thresholds).
-The conversationPayload json object is updated to include these tones.
-@param conversationPayload json object returned by the Watson Conversation
-Service
-@param toneAnalyzerPayload json object returned by the Watson Tone Analyzer
-Service
-@returns conversationPayload where the user object has been updated with tone
-information from the toneAnalyzerPayload
-"""
-
def updateUserTone(conversationPayload, toneAnalyzerPayload, maintainHistory):
+ """
+ updateUserTone processes the Tone Analyzer payload to pull out the emotion,
+ writing and social tones, and identify the meaningful tones (i.e.,
+ those tones that meet the specified thresholds).
+ The conversationPayload json object is updated to include these tones.
+ @param conversationPayload json object returned by the Watson Conversation
+ Service
+ @param toneAnalyzerPayload json object returned by the Watson Tone Analyzer
+ Service
+ @returns conversationPayload where the user object has been updated with tone
+ information from the toneAnalyzerPayload
+ """
emotionTone = None
writingTone = None
socialTone = None
@@ -80,18 +79,15 @@ def updateUserTone(conversationPayload, toneAnalyzerPayload, maintainHistory):
return conversationPayload
-'''
- initToneContext initializes a user object containing tone data (from the
- Watson Tone Analyzer)
- @returns user json object with the emotion, writing and social tones. The
- current
- tone identifies the tone for a specific conversation turn, and the history
- provides the conversation for
- all tones up to the current tone for a conversation instance with a user.
- '''
-
-
def initUser():
+ """
+ initUser initializes a user object containing tone data (from the
+ Watson Tone Analyzer)
+ @returns user json object with the emotion, writing and social tones. The
+ current tone identifies the tone for a specific conversation turn, and the
+ history provides the conversation for all tones up to the current tone for a
+ conversation instance with a user.
+ """
return {
'user': {
'tone': {
@@ -109,19 +105,18 @@ def initUser():
}
-'''
- updateEmotionTone updates the user emotion tone with the primary emotion -
- the emotion tone that has
- a score greater than or equal to the EMOTION_SCORE_THRESHOLD; otherwise
- primary emotion will be 'neutral'
- @param user a json object representing user information (tone) to be used in
- conversing with the Conversation Service
- @param emotionTone a json object containing the emotion tones in the payload
- returned by the Tone Analyzer
- '''
def updateEmotionTone(user, emotionTone, maintainHistory):
+ """
+ updateEmotionTone updates the user emotion tone with the primary emotion -
+ the emotion tone that has a score greater than or equal to the
+ EMOTION_SCORE_THRESHOLD; otherwise primary emotion will be 'neutral'
+ @param user a json object representing user information (tone) to be used in
+ conversing with the Conversation Service
+ @param emotionTone a json object containing the emotion tones in the payload
+ returned by the Tone Analyzer
+ """
maxScore = 0.0
primaryEmotion = None
primaryEmotionScore = None
@@ -148,17 +143,15 @@ def updateEmotionTone(user, emotionTone, maintainHistory):
})
-'''
- updateWritingTone updates the user with the writing tones interpreted based
- on the specified thresholds
- @param: user a json object representing user information (tone) to be used
- in conversing with the Conversation Service
- @param: writingTone a json object containing the writing tones in the
- payload returned by the Tone Analyzer
-'''
-
-
def updateWritingTone(user, writingTone, maintainHistory):
+ """
+ updateWritingTone updates the user with the writing tones interpreted based
+ on the specified thresholds
+ @param: user a json object representing user information (tone) to be used
+ in conversing with the Conversation Service
+ @param: writingTone a json object containing the writing tones in the
+ payload returned by the Tone Analyzer
+ """
currentWriting = []
currentWritingObject = []
@@ -189,21 +182,18 @@ def updateWritingTone(user, writingTone, maintainHistory):
if maintainHistory:
if 'history' not in user['tone']['writing']:
user['tone']['writing']['history'] = []
- user['tone']['writing']['history'].append(currentWritingObject) # TODO -
- # is this the correct location??? AW
-
-
-"""
- updateSocialTone updates the user with the social tones interpreted based on
- the specified thresholds
- @param user a json object representing user information (tone) to be used in
- conversing with the Conversation Service
- @param socialTone a json object containing the social tones in the payload
- returned by the Tone Analyzer
-"""
+ user['tone']['writing']['history'].append(currentWritingObject)
def updateSocialTone(user, socialTone, maintainHistory):
+ """
+ updateSocialTone updates the user with the social tones interpreted based on
+ the specified thresholds
+ @param user a json object representing user information (tone) to be used in
+ conversing with the Conversation Service
+ @param socialTone a json object containing the social tones in the payload
+ returned by the Tone Analyzer
+ """
currentSocial = []
currentSocialObject = []
diff --git a/examples/personality_insights_v3.py b/examples/personality_insights_v3.py
index b3efdbc0..02c806a7 100755
--- a/examples/personality_insights_v3.py
+++ b/examples/personality_insights_v3.py
@@ -1,13 +1,12 @@
+"""
+The example returns a JSON response whose content is the same as that in
+ ../resources/personality-v3-expect2.txt
+"""
from __future__ import print_function
import json
from os.path import join, dirname
from watson_developer_cloud import PersonalityInsightsV3
-"""
-The example returns a JSON response whose content is the same as that in
- ../resources/personality-v3-expect2.txt
-"""
-
personality_insights = PersonalityInsightsV3(
version='2016-10-20',
username='YOUR SERVICE USERNAME',
diff --git a/pylint.sh b/pylint.sh
index 60cf35e9..4e0862af 100644
--- a/pylint.sh
+++ b/pylint.sh
@@ -4,6 +4,5 @@
PYTHON_VERSION=$(python -c 'import sys; print(".".join(map(str, sys.version_info[:2])))')
echo "Python version: $PYTHON_VERSION"
if [ $PYTHON_VERSION = '2.7' ]; then
- pylint watson_developer_cloud
- pylint test
+ pylint watson_developer_cloud test examples
fi
diff --git a/watson_developer_cloud/conversation_v1.py b/watson_developer_cloud/conversation_v1.py
index 71867d41..822556bb 100644
--- a/watson_developer_cloud/conversation_v1.py
+++ b/watson_developer_cloud/conversation_v1.py
@@ -134,12 +134,9 @@ class ConversationV1(WatsonService):
'metadata': metadata,
'learning_opt_out': learning_opt_out
}
+ url = '/v1/workspaces'
response = self.request(
- method='POST',
- url='/v1/workspaces',
- params=params,
- json=data,
- accept_json=True)
+ method='POST', url=url, params=params, json=data, accept_json=True)
return response
def delete_workspace(self, workspace_id):
@@ -154,11 +151,8 @@ class ConversationV1(WatsonService):
if workspace_id is None:
raise ValueError('workspace_id must be provided')
params = {'version': self.version}
- self.request(
- method='DELETE',
- url='/v1/workspaces/{0}'.format(workspace_id),
- params=params,
- accept_json=True)
+ url = '/v1/workspaces/{0}'.format(*self._encode_path_vars(workspace_id))
+ self.request(method='DELETE', url=url, params=params, accept_json=True)
return None
def get_workspace(self, workspace_id, export=None):
@@ -175,11 +169,9 @@ class ConversationV1(WatsonService):
if workspace_id is None:
raise ValueError('workspace_id must be provided')
params = {'version': self.version, 'export': export}
+ url = '/v1/workspaces/{0}'.format(*self._encode_path_vars(workspace_id))
response = self.request(
- method='GET',
- url='/v1/workspaces/{0}'.format(workspace_id),
- params=params,
- accept_json=True)
+ method='GET', url=url, params=params, accept_json=True)
return response
def list_workspaces(self,
@@ -206,8 +198,9 @@ class ConversationV1(WatsonService):
'sort': sort,
'cursor': cursor
}
+ url = '/v1/workspaces'
response = self.request(
- method='GET', url='/v1/workspaces', params=params, accept_json=True)
+ method='GET', url=url, params=params, accept_json=True)
return response
def update_workspace(self,
@@ -262,12 +255,9 @@ class ConversationV1(WatsonService):
'metadata': metadata,
'learning_opt_out': learning_opt_out
}
+ url = '/v1/workspaces/{0}'.format(*self._encode_path_vars(workspace_id))
response = self.request(
- method='POST',
- url='/v1/workspaces/{0}'.format(workspace_id),
- params=params,
- json=data,
- accept_json=True)
+ method='POST', url=url, params=params, json=data, accept_json=True)
return response
#########################
@@ -316,12 +306,10 @@ class ConversationV1(WatsonService):
'intents': intents,
'output': output
}
+ url = '/v1/workspaces/{0}/message'.format(
+ *self._encode_path_vars(workspace_id))
response = self.request(
- method='POST',
- url='/v1/workspaces/{0}/message'.format(workspace_id),
- params=params,
- json=data,
- accept_json=True)
+ method='POST', url=url, params=params, json=data, accept_json=True)
return response
#########################
@@ -357,12 +345,10 @@ class ConversationV1(WatsonService):
'description': description,
'examples': examples
}
+ url = '/v1/workspaces/{0}/intents'.format(
+ *self._encode_path_vars(workspace_id))
response = self.request(
- method='POST',
- url='/v1/workspaces/{0}/intents'.format(workspace_id),
- params=params,
- json=data,
- accept_json=True)
+ method='POST', url=url, params=params, json=data, accept_json=True)
return response
def delete_intent(self, workspace_id, intent):
@@ -380,11 +366,9 @@ class ConversationV1(WatsonService):
if intent is None:
raise ValueError('intent must be provided')
params = {'version': self.version}
- self.request(
- method='DELETE',
- url='/v1/workspaces/{0}/intents/{1}'.format(workspace_id, intent),
- params=params,
- accept_json=True)
+ url = '/v1/workspaces/{0}/intents/{1}'.format(*self._encode_path_vars(
+ workspace_id, intent))
+ self.request(method='DELETE', url=url, params=params, accept_json=True)
return None
def get_intent(self, workspace_id, intent, export=None):
@@ -404,11 +388,10 @@ class ConversationV1(WatsonService):
if intent is None:
raise ValueError('intent must be provided')
params = {'version': self.version, 'export': export}
+ url = '/v1/workspaces/{0}/intents/{1}'.format(*self._encode_path_vars(
+ workspace_id, intent))
response = self.request(
- method='GET',
- url='/v1/workspaces/{0}/intents/{1}'.format(workspace_id, intent),
- params=params,
- accept_json=True)
+ method='GET', url=url, params=params, accept_json=True)
return response
def list_intents(self,
@@ -442,11 +425,10 @@ class ConversationV1(WatsonService):
'sort': sort,
'cursor': cursor
}
+ url = '/v1/workspaces/{0}/intents'.format(
+ *self._encode_path_vars(workspace_id))
response = self.request(
- method='GET',
- url='/v1/workspaces/{0}/intents'.format(workspace_id),
- params=params,
- accept_json=True)
+ method='GET', url=url, params=params, accept_json=True)
return response
def update_intent(self,
@@ -481,12 +463,10 @@ class ConversationV1(WatsonService):
'description': new_description,
'examples': new_examples
}
+ url = '/v1/workspaces/{0}/intents/{1}'.format(*self._encode_path_vars(
+ workspace_id, intent))
response = self.request(
- method='POST',
- url='/v1/workspaces/{0}/intents/{1}'.format(workspace_id, intent),
- params=params,
- json=data,
- accept_json=True)
+ method='POST', url=url, params=params, json=data, accept_json=True)
return response
#########################
@@ -513,13 +493,10 @@ class ConversationV1(WatsonService):
raise ValueError('text must be provided')
params = {'version': self.version}
data = {'text': text}
+ url = '/v1/workspaces/{0}/intents/{1}/examples'.format(
+ *self._encode_path_vars(workspace_id, intent))
response = self.request(
- method='POST',
- url='/v1/workspaces/{0}/intents/{1}/examples'.format(
- workspace_id, intent),
- params=params,
- json=data,
- accept_json=True)
+ method='POST', url=url, params=params, json=data, accept_json=True)
return response
def delete_example(self, workspace_id, intent, text):
@@ -540,12 +517,9 @@ class ConversationV1(WatsonService):
if text is None:
raise ValueError('text must be provided')
params = {'version': self.version}
- self.request(
- method='DELETE',
- url='/v1/workspaces/{0}/intents/{1}/examples/{2}'.format(
- workspace_id, intent, text),
- params=params,
- accept_json=True)
+ url = '/v1/workspaces/{0}/intents/{1}/examples/{2}'.format(
+ *self._encode_path_vars(workspace_id, intent, text))
+ self.request(method='DELETE', url=url, params=params, accept_json=True)
return None
def get_example(self, workspace_id, intent, text):
@@ -567,12 +541,10 @@ class ConversationV1(WatsonService):
if text is None:
raise ValueError('text must be provided')
params = {'version': self.version}
+ url = '/v1/workspaces/{0}/intents/{1}/examples/{2}'.format(
+ *self._encode_path_vars(workspace_id, intent, text))
response = self.request(
- method='GET',
- url='/v1/workspaces/{0}/intents/{1}/examples/{2}'.format(
- workspace_id, intent, text),
- params=params,
- accept_json=True)
+ method='GET', url=url, params=params, accept_json=True)
return response
def list_examples(self,
@@ -607,12 +579,10 @@ class ConversationV1(WatsonService):
'sort': sort,
'cursor': cursor
}
+ url = '/v1/workspaces/{0}/intents/{1}/examples'.format(
+ *self._encode_path_vars(workspace_id, intent))
response = self.request(
- method='GET',
- url='/v1/workspaces/{0}/intents/{1}/examples'.format(
- workspace_id, intent),
- params=params,
- accept_json=True)
+ method='GET', url=url, params=params, accept_json=True)
return response
def update_example(self, workspace_id, intent, text, new_text=None):
@@ -636,13 +606,10 @@ class ConversationV1(WatsonService):
raise ValueError('text must be provided')
params = {'version': self.version}
data = {'text': new_text}
+ url = '/v1/workspaces/{0}/intents/{1}/examples/{2}'.format(
+ *self._encode_path_vars(workspace_id, intent, text))
response = self.request(
- method='POST',
- url='/v1/workspaces/{0}/intents/{1}/examples/{2}'.format(
- workspace_id, intent, text),
- params=params,
- json=data,
- accept_json=True)
+ method='POST', url=url, params=params, json=data, accept_json=True)
return response
#########################
@@ -684,12 +651,10 @@ class ConversationV1(WatsonService):
'values': values,
'fuzzy_match': fuzzy_match
}
+ url = '/v1/workspaces/{0}/entities'.format(
+ *self._encode_path_vars(workspace_id))
response = self.request(
- method='POST',
- url='/v1/workspaces/{0}/entities'.format(workspace_id),
- params=params,
- json=data,
- accept_json=True)
+ method='POST', url=url, params=params, json=data, accept_json=True)
return response
def delete_entity(self, workspace_id, entity):
@@ -707,11 +672,9 @@ class ConversationV1(WatsonService):
if entity is None:
raise ValueError('entity must be provided')
params = {'version': self.version}
- self.request(
- method='DELETE',
- url='/v1/workspaces/{0}/entities/{1}'.format(workspace_id, entity),
- params=params,
- accept_json=True)
+ url = '/v1/workspaces/{0}/entities/{1}'.format(*self._encode_path_vars(
+ workspace_id, entity))
+ self.request(method='DELETE', url=url, params=params, accept_json=True)
return None
def get_entity(self, workspace_id, entity, export=None):
@@ -731,11 +694,10 @@ class ConversationV1(WatsonService):
if entity is None:
raise ValueError('entity must be provided')
params = {'version': self.version, 'export': export}
+ url = '/v1/workspaces/{0}/entities/{1}'.format(*self._encode_path_vars(
+ workspace_id, entity))
response = self.request(
- method='GET',
- url='/v1/workspaces/{0}/entities/{1}'.format(workspace_id, entity),
- params=params,
- accept_json=True)
+ method='GET', url=url, params=params, accept_json=True)
return response
def list_entities(self,
@@ -769,11 +731,10 @@ class ConversationV1(WatsonService):
'sort': sort,
'cursor': cursor
}
+ url = '/v1/workspaces/{0}/entities'.format(
+ *self._encode_path_vars(workspace_id))
response = self.request(
- method='GET',
- url='/v1/workspaces/{0}/entities'.format(workspace_id),
- params=params,
- accept_json=True)
+ method='GET', url=url, params=params, accept_json=True)
return response
def update_entity(self,
@@ -813,12 +774,10 @@ class ConversationV1(WatsonService):
'fuzzy_match': new_fuzzy_match,
'values': new_values
}
+ url = '/v1/workspaces/{0}/entities/{1}'.format(*self._encode_path_vars(
+ workspace_id, entity))
response = self.request(
- method='POST',
- url='/v1/workspaces/{0}/entities/{1}'.format(workspace_id, entity),
- params=params,
- json=data,
- accept_json=True)
+ method='POST', url=url, params=params, json=data, accept_json=True)
return response
#########################
@@ -862,13 +821,10 @@ class ConversationV1(WatsonService):
'patterns': patterns,
'type': value_type
}
+ url = '/v1/workspaces/{0}/entities/{1}/values'.format(
+ *self._encode_path_vars(workspace_id, entity))
response = self.request(
- method='POST',
- url='/v1/workspaces/{0}/entities/{1}/values'.format(
- workspace_id, entity),
- params=params,
- json=data,
- accept_json=True)
+ method='POST', url=url, params=params, json=data, accept_json=True)
return response
def delete_value(self, workspace_id, entity, value):
@@ -889,12 +845,9 @@ class ConversationV1(WatsonService):
if value is None:
raise ValueError('value must be provided')
params = {'version': self.version}
- self.request(
- method='DELETE',
- url='/v1/workspaces/{0}/entities/{1}/values/{2}'.format(
- workspace_id, entity, value),
- params=params,
- accept_json=True)
+ url = '/v1/workspaces/{0}/entities/{1}/values/{2}'.format(
+ *self._encode_path_vars(workspace_id, entity, value))
+ self.request(method='DELETE', url=url, params=params, accept_json=True)
return None
def get_value(self, workspace_id, entity, value, export=None):
@@ -917,12 +870,10 @@ class ConversationV1(WatsonService):
if value is None:
raise ValueError('value must be provided')
params = {'version': self.version, 'export': export}
+ url = '/v1/workspaces/{0}/entities/{1}/values/{2}'.format(
+ *self._encode_path_vars(workspace_id, entity, value))
response = self.request(
- method='GET',
- url='/v1/workspaces/{0}/entities/{1}/values/{2}'.format(
- workspace_id, entity, value),
- params=params,
- accept_json=True)
+ method='GET', url=url, params=params, accept_json=True)
return response
def list_values(self,
@@ -960,12 +911,10 @@ class ConversationV1(WatsonService):
'sort': sort,
'cursor': cursor
}
+ url = '/v1/workspaces/{0}/entities/{1}/values'.format(
+ *self._encode_path_vars(workspace_id, entity))
response = self.request(
- method='GET',
- url='/v1/workspaces/{0}/entities/{1}/values'.format(
- workspace_id, entity),
- params=params,
- accept_json=True)
+ method='GET', url=url, params=params, accept_json=True)
return response
def update_value(self,
@@ -1007,13 +956,10 @@ class ConversationV1(WatsonService):
'synonyms': new_synonyms,
'patterns': new_patterns
}
+ url = '/v1/workspaces/{0}/entities/{1}/values/{2}'.format(
+ *self._encode_path_vars(workspace_id, entity, value))
response = self.request(
- method='POST',
- url='/v1/workspaces/{0}/entities/{1}/values/{2}'.format(
- workspace_id, entity, value),
- params=params,
- json=data,
- accept_json=True)
+ method='POST', url=url, params=params, json=data, accept_json=True)
return response
#########################
@@ -1043,13 +989,10 @@ class ConversationV1(WatsonService):
raise ValueError('synonym must be provided')
params = {'version': self.version}
data = {'synonym': synonym}
+ url = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms'.format(
+ *self._encode_path_vars(workspace_id, entity, value))
response = self.request(
- method='POST',
- url='/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms'.format(
- workspace_id, entity, value),
- params=params,
- json=data,
- accept_json=True)
+ method='POST', url=url, params=params, json=data, accept_json=True)
return response
def delete_synonym(self, workspace_id, entity, value, synonym):
@@ -1073,12 +1016,9 @@ class ConversationV1(WatsonService):
if synonym is None:
raise ValueError('synonym must be provided')
params = {'version': self.version}
- self.request(
- method='DELETE',
- url='/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms/{3}'.
- format(workspace_id, entity, value, synonym),
- params=params,
- accept_json=True)
+ url = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms/{3}'.format(
+ *self._encode_path_vars(workspace_id, entity, value, synonym))
+ self.request(method='DELETE', url=url, params=params, accept_json=True)
return None
def get_synonym(self, workspace_id, entity, value, synonym):
@@ -1103,12 +1043,10 @@ class ConversationV1(WatsonService):
if synonym is None:
raise ValueError('synonym must be provided')
params = {'version': self.version}
+ url = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms/{3}'.format(
+ *self._encode_path_vars(workspace_id, entity, value, synonym))
response = self.request(
- method='GET',
- url='/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms/{3}'.
- format(workspace_id, entity, value, synonym),
- params=params,
- accept_json=True)
+ method='GET', url=url, params=params, accept_json=True)
return response
def list_synonyms(self,
@@ -1147,12 +1085,10 @@ class ConversationV1(WatsonService):
'sort': sort,
'cursor': cursor
}
+ url = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms'.format(
+ *self._encode_path_vars(workspace_id, entity, value))
response = self.request(
- method='GET',
- url='/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms'.format(
- workspace_id, entity, value),
- params=params,
- accept_json=True)
+ method='GET', url=url, params=params, accept_json=True)
return response
def update_synonym(self,
@@ -1184,13 +1120,10 @@ class ConversationV1(WatsonService):
raise ValueError('synonym must be provided')
params = {'version': self.version}
data = {'synonym': new_synonym}
+ url = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms/{3}'.format(
+ *self._encode_path_vars(workspace_id, entity, value, synonym))
response = self.request(
- method='POST',
- url='/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms/{3}'.
- format(workspace_id, entity, value, synonym),
- params=params,
- json=data,
- accept_json=True)
+ method='POST', url=url, params=params, json=data, accept_json=True)
return response
#########################
@@ -1261,12 +1194,10 @@ class ConversationV1(WatsonService):
'event_name': event_name,
'variable': variable
}
+ url = '/v1/workspaces/{0}/dialog_nodes'.format(
+ *self._encode_path_vars(workspace_id))
response = self.request(
- method='POST',
- url='/v1/workspaces/{0}/dialog_nodes'.format(workspace_id),
- params=params,
- json=data,
- accept_json=True)
+ method='POST', url=url, params=params, json=data, accept_json=True)
return response
def delete_dialog_node(self, workspace_id, dialog_node):
@@ -1284,12 +1215,9 @@ class ConversationV1(WatsonService):
if dialog_node is None:
raise ValueError('dialog_node must be provided')
params = {'version': self.version}
- self.request(
- method='DELETE',
- url='/v1/workspaces/{0}/dialog_nodes/{1}'.format(
- workspace_id, dialog_node),
- params=params,
- accept_json=True)
+ url = '/v1/workspaces/{0}/dialog_nodes/{1}'.format(
+ *self._encode_path_vars(workspace_id, dialog_node))
+ self.request(method='DELETE', url=url, params=params, accept_json=True)
return None
def get_dialog_node(self, workspace_id, dialog_node):
@@ -1308,12 +1236,10 @@ class ConversationV1(WatsonService):
if dialog_node is None:
raise ValueError('dialog_node must be provided')
params = {'version': self.version}
+ url = '/v1/workspaces/{0}/dialog_nodes/{1}'.format(
+ *self._encode_path_vars(workspace_id, dialog_node))
response = self.request(
- method='GET',
- url='/v1/workspaces/{0}/dialog_nodes/{1}'.format(
- workspace_id, dialog_node),
- params=params,
- accept_json=True)
+ method='GET', url=url, params=params, accept_json=True)
return response
def list_dialog_nodes(self,
@@ -1344,11 +1270,10 @@ class ConversationV1(WatsonService):
'sort': sort,
'cursor': cursor
}
+ url = '/v1/workspaces/{0}/dialog_nodes'.format(
+ *self._encode_path_vars(workspace_id))
response = self.request(
- method='GET',
- url='/v1/workspaces/{0}/dialog_nodes'.format(workspace_id),
- params=params,
- accept_json=True)
+ method='GET', url=url, params=params, accept_json=True)
return response
def update_dialog_node(self,
@@ -1419,13 +1344,10 @@ class ConversationV1(WatsonService):
'variable': new_variable,
'actions': new_actions
}
+ url = '/v1/workspaces/{0}/dialog_nodes/{1}'.format(
+ *self._encode_path_vars(workspace_id, dialog_node))
response = self.request(
- method='POST',
- url='/v1/workspaces/{0}/dialog_nodes/{1}'.format(
- workspace_id, dialog_node),
- params=params,
- json=data,
- accept_json=True)
+ method='POST', url=url, params=params, json=data, accept_json=True)
return response
#########################
@@ -1460,11 +1382,10 @@ class ConversationV1(WatsonService):
'page_limit': page_limit,
'cursor': cursor
}
+ url = '/v1/workspaces/{0}/logs'.format(
+ *self._encode_path_vars(workspace_id))
response = self.request(
- method='GET',
- url='/v1/workspaces/{0}/logs'.format(workspace_id),
- params=params,
- accept_json=True)
+ method='GET', url=url, params=params, accept_json=True)
return response
#########################
@@ -1489,12 +1410,10 @@ class ConversationV1(WatsonService):
raise ValueError('text must be provided')
params = {'version': self.version}
data = {'text': text}
+ url = '/v1/workspaces/{0}/counterexamples'.format(
+ *self._encode_path_vars(workspace_id))
response = self.request(
- method='POST',
- url='/v1/workspaces/{0}/counterexamples'.format(workspace_id),
- params=params,
- json=data,
- accept_json=True)
+ method='POST', url=url, params=params, json=data, accept_json=True)
return response
def delete_counterexample(self, workspace_id, text):
@@ -1513,12 +1432,9 @@ class ConversationV1(WatsonService):
if text is None:
raise ValueError('text must be provided')
params = {'version': self.version}
- self.request(
- method='DELETE',
- url='/v1/workspaces/{0}/counterexamples/{1}'.format(
- workspace_id, text),
- params=params,
- accept_json=True)
+ url = '/v1/workspaces/{0}/counterexamples/{1}'.format(
+ *self._encode_path_vars(workspace_id, text))
+ self.request(method='DELETE', url=url, params=params, accept_json=True)
return None
def get_counterexample(self, workspace_id, text):
@@ -1538,12 +1454,10 @@ class ConversationV1(WatsonService):
if text is None:
raise ValueError('text must be provided')
params = {'version': self.version}
+ url = '/v1/workspaces/{0}/counterexamples/{1}'.format(
+ *self._encode_path_vars(workspace_id, text))
response = self.request(
- method='GET',
- url='/v1/workspaces/{0}/counterexamples/{1}'.format(
- workspace_id, text),
- params=params,
- accept_json=True)
+ method='GET', url=url, params=params, accept_json=True)
return response
def list_counterexamples(self,
@@ -1575,11 +1489,10 @@ class ConversationV1(WatsonService):
'sort': sort,
'cursor': cursor
}
+ url = '/v1/workspaces/{0}/counterexamples'.format(
+ *self._encode_path_vars(workspace_id))
response = self.request(
- method='GET',
- url='/v1/workspaces/{0}/counterexamples'.format(workspace_id),
- params=params,
- accept_json=True)
+ method='GET', url=url, params=params, accept_json=True)
return response
def update_counterexample(self, workspace_id, text, new_text=None):
@@ -1601,13 +1514,10 @@ class ConversationV1(WatsonService):
raise ValueError('text must be provided')
params = {'version': self.version}
data = {'text': new_text}
+ url = '/v1/workspaces/{0}/counterexamples/{1}'.format(
+ *self._encode_path_vars(workspace_id, text))
response = self.request(
- method='POST',
- url='/v1/workspaces/{0}/counterexamples/{1}'.format(
- workspace_id, text),
- params=params,
- json=data,
- accept_json=True)
+ method='POST', url=url, params=params, json=data, accept_json=True)
return response
diff --git a/watson_developer_cloud/discovery_v1.py b/watson_developer_cloud/discovery_v1.py
index dd84dfe0..acb264fc 100644
--- a/watson_developer_cloud/discovery_v1.py
+++ b/watson_developer_cloud/discovery_v1.py
@@ -105,12 +105,9 @@ class DiscoveryV1(WatsonService):
raise ValueError('name must be provided')
params = {'version': self.version}
data = {'name': name, 'description': description, 'size': size}
+ url = '/v1/environments'
response = self.request(
- method='POST',
- url='/v1/environments',
- params=params,
- json=data,
- accept_json=True)
+ method='POST', url=url, params=params, json=data, accept_json=True)
return response
def delete_environment(self, environment_id):
@@ -124,11 +121,10 @@ class DiscoveryV1(WatsonService):
if environment_id is None:
raise ValueError('environment_id must be provided')
params = {'version': self.version}
+ url = '/v1/environments/{0}'.format(
+ *self._encode_path_vars(environment_id))
response = self.request(
- method='DELETE',
- url='/v1/environments/{0}'.format(environment_id),
- params=params,
- accept_json=True)
+ method='DELETE', url=url, params=params, accept_json=True)
return response
def get_environment(self, environment_id):
@@ -142,11 +138,10 @@ class DiscoveryV1(WatsonService):
if environment_id is None:
raise ValueError('environment_id must be provided')
params = {'version': self.version}
+ url = '/v1/environments/{0}'.format(
+ *self._encode_path_vars(environment_id))
response = self.request(
- method='GET',
- url='/v1/environments/{0}'.format(environment_id),
- params=params,
- accept_json=True)
+ method='GET', url=url, params=params, accept_json=True)
return response
def list_environments(self, name=None):
@@ -160,11 +155,9 @@ class DiscoveryV1(WatsonService):
:rtype: dict
"""
params = {'version': self.version, 'name': name}
+ url = '/v1/environments'
response = self.request(
- method='GET',
- url='/v1/environments',
- params=params,
- accept_json=True)
+ method='GET', url=url, params=params, accept_json=True)
return response
def list_fields(self, environment_id, collection_ids):
@@ -190,11 +183,10 @@ class DiscoveryV1(WatsonService):
",".join(collection_ids)
if isinstance(collection_ids, list) else collection_ids
}
+ url = '/v1/environments/{0}/fields'.format(
+ *self._encode_path_vars(environment_id))
response = self.request(
- method='GET',
- url='/v1/environments/{0}/fields'.format(environment_id),
- params=params,
- accept_json=True)
+ method='GET', url=url, params=params, accept_json=True)
return response
def update_environment(self, environment_id, name=None, description=None):
@@ -214,12 +206,10 @@ class DiscoveryV1(WatsonService):
raise ValueError('environment_id must be provided')
params = {'version': self.version}
data = {'name': name, 'description': description}
+ url = '/v1/environments/{0}'.format(
+ *self._encode_path_vars(environment_id))
response = self.request(
- method='PUT',
- url='/v1/environments/{0}'.format(environment_id),
- params=params,
- json=data,
- accept_json=True)
+ method='PUT', url=url, params=params, json=data, accept_json=True)
return response
#########################
@@ -272,12 +262,10 @@ class DiscoveryV1(WatsonService):
'enrichments': enrichments,
'normalizations': normalizations
}
+ url = '/v1/environments/{0}/configurations'.format(
+ *self._encode_path_vars(environment_id))
response = self.request(
- method='POST',
- url='/v1/environments/{0}/configurations'.format(environment_id),
- params=params,
- json=data,
- accept_json=True)
+ method='POST', url=url, params=params, json=data, accept_json=True)
return response
def delete_configuration(self, environment_id, configuration_id):
@@ -301,12 +289,10 @@ class DiscoveryV1(WatsonService):
if configuration_id is None:
raise ValueError('configuration_id must be provided')
params = {'version': self.version}
+ url = '/v1/environments/{0}/configurations/{1}'.format(
+ *self._encode_path_vars(environment_id, configuration_id))
response = self.request(
- method='DELETE',
- url='/v1/environments/{0}/configurations/{1}'.format(
- environment_id, configuration_id),
- params=params,
- accept_json=True)
+ method='DELETE', url=url, params=params, accept_json=True)
return response
def get_configuration(self, environment_id, configuration_id):
@@ -323,12 +309,10 @@ class DiscoveryV1(WatsonService):
if configuration_id is None:
raise ValueError('configuration_id must be provided')
params = {'version': self.version}
+ url = '/v1/environments/{0}/configurations/{1}'.format(
+ *self._encode_path_vars(environment_id, configuration_id))
response = self.request(
- method='GET',
- url='/v1/environments/{0}/configurations/{1}'.format(
- environment_id, configuration_id),
- params=params,
- accept_json=True)
+ method='GET', url=url, params=params, accept_json=True)
return response
def list_configurations(self, environment_id, name=None):
@@ -345,11 +329,10 @@ class DiscoveryV1(WatsonService):
if environment_id is None:
raise ValueError('environment_id must be provided')
params = {'version': self.version, 'name': name}
+ url = '/v1/environments/{0}/configurations'.format(
+ *self._encode_path_vars(environment_id))
response = self.request(
- method='GET',
- url='/v1/environments/{0}/configurations'.format(environment_id),
- params=params,
- accept_json=True)
+ method='GET', url=url, params=params, accept_json=True)
return response
def update_configuration(self,
@@ -401,13 +384,10 @@ class DiscoveryV1(WatsonService):
'enrichments': enrichments,
'normalizations': normalizations
}
+ url = '/v1/environments/{0}/configurations/{1}'.format(
+ *self._encode_path_vars(environment_id, configuration_id))
response = self.request(
- method='PUT',
- url='/v1/environments/{0}/configurations/{1}'.format(
- environment_id, configuration_id),
- params=params,
- json=data,
- accept_json=True)
+ method='PUT', url=url, params=params, json=data, accept_json=True)
return response
#########################
@@ -462,9 +442,11 @@ class DiscoveryV1(WatsonService):
metadata_tuple = None
if metadata:
metadata_tuple = (None, metadata, 'text/plain')
+ url = '/v1/environments/{0}/preview'.format(
+ *self._encode_path_vars(environment_id))
response = self.request(
method='POST',
- url='/v1/environments/{0}/preview'.format(environment_id),
+ url=url,
params=params,
files={
'configuration': configuration_tuple,
@@ -506,12 +488,10 @@ class DiscoveryV1(WatsonService):
'configuration_id': configuration_id,
'language': language
}
+ url = '/v1/environments/{0}/collections'.format(
+ *self._encode_path_vars(environment_id))
response = self.request(
- method='POST',
- url='/v1/environments/{0}/collections'.format(environment_id),
- params=params,
- json=data,
- accept_json=True)
+ method='POST', url=url, params=params, json=data, accept_json=True)
return response
def delete_collection(self, environment_id, collection_id):
@@ -528,12 +508,10 @@ class DiscoveryV1(WatsonService):
if collection_id is None:
raise ValueError('collection_id must be provided')
params = {'version': self.version}
+ url = '/v1/environments/{0}/collections/{1}'.format(
+ *self._encode_path_vars(environment_id, collection_id))
response = self.request(
- method='DELETE',
- url='/v1/environments/{0}/collections/{1}'.format(
- environment_id, collection_id),
- params=params,
- accept_json=True)
+ method='DELETE', url=url, params=params, accept_json=True)
return response
def get_collection(self, environment_id, collection_id):
@@ -550,12 +528,10 @@ class DiscoveryV1(WatsonService):
if collection_id is None:
raise ValueError('collection_id must be provided')
params = {'version': self.version}
+ url = '/v1/environments/{0}/collections/{1}'.format(
+ *self._encode_path_vars(environment_id, collection_id))
response = self.request(
- method='GET',
- url='/v1/environments/{0}/collections/{1}'.format(
- environment_id, collection_id),
- params=params,
- accept_json=True)
+ method='GET', url=url, params=params, accept_json=True)
return response
def list_collection_fields(self, environment_id, collection_id):
@@ -574,12 +550,10 @@ class DiscoveryV1(WatsonService):
if collection_id is None:
raise ValueError('collection_id must be provided')
params = {'version': self.version}
+ url = '/v1/environments/{0}/collections/{1}/fields'.format(
+ *self._encode_path_vars(environment_id, collection_id))
response = self.request(
- method='GET',
- url='/v1/environments/{0}/collections/{1}/fields'.format(
- environment_id, collection_id),
- params=params,
- accept_json=True)
+ method='GET', url=url, params=params, accept_json=True)
return response
def list_collections(self, environment_id, name=None):
@@ -596,11 +570,10 @@ class DiscoveryV1(WatsonService):
if environment_id is None:
raise ValueError('environment_id must be provided')
params = {'version': self.version, 'name': name}
+ url = '/v1/environments/{0}/collections'.format(
+ *self._encode_path_vars(environment_id))
response = self.request(
- method='GET',
- url='/v1/environments/{0}/collections'.format(environment_id),
- params=params,
- accept_json=True)
+ method='GET', url=url, params=params, accept_json=True)
return response
def update_collection(self,
@@ -630,13 +603,10 @@ class DiscoveryV1(WatsonService):
'description': description,
'configuration_id': configuration_id
}
+ url = '/v1/environments/{0}/collections/{1}'.format(
+ *self._encode_path_vars(environment_id, collection_id))
response = self.request(
- method='PUT',
- url='/v1/environments/{0}/collections/{1}'.format(
- environment_id, collection_id),
- params=params,
- json=data,
- accept_json=True)
+ method='PUT', url=url, params=params, json=data, accept_json=True)
return response
#########################
@@ -693,10 +663,11 @@ class DiscoveryV1(WatsonService):
metadata_tuple = None
if metadata:
metadata_tuple = (None, metadata, 'text/plain')
+ url = '/v1/environments/{0}/collections/{1}/documents'.format(
+ *self._encode_path_vars(environment_id, collection_id))
response = self.request(
method='POST',
- url='/v1/environments/{0}/collections/{1}/documents'.format(
- environment_id, collection_id),
+ url=url,
params=params,
files={'file': file_tuple,
'metadata': metadata_tuple},
@@ -724,12 +695,10 @@ class DiscoveryV1(WatsonService):
if document_id is None:
raise ValueError('document_id must be provided')
params = {'version': self.version}
+ url = '/v1/environments/{0}/collections/{1}/documents/{2}'.format(
+ *self._encode_path_vars(environment_id, collection_id, document_id))
response = self.request(
- method='DELETE',
- url='/v1/environments/{0}/collections/{1}/documents/{2}'.format(
- environment_id, collection_id, document_id),
- params=params,
- accept_json=True)
+ method='DELETE', url=url, params=params, accept_json=True)
return response
def get_document_status(self, environment_id, collection_id, document_id):
@@ -754,12 +723,10 @@ class DiscoveryV1(WatsonService):
if document_id is None:
raise ValueError('document_id must be provided')
params = {'version': self.version}
+ url = '/v1/environments/{0}/collections/{1}/documents/{2}'.format(
+ *self._encode_path_vars(environment_id, collection_id, document_id))
response = self.request(
- method='GET',
- url='/v1/environments/{0}/collections/{1}/documents/{2}'.format(
- environment_id, collection_id, document_id),
- params=params,
- accept_json=True)
+ method='GET', url=url, params=params, accept_json=True)
return response
def update_document(self,
@@ -803,10 +770,11 @@ class DiscoveryV1(WatsonService):
metadata_tuple = None
if metadata:
metadata_tuple = (None, metadata, 'text/plain')
+ url = '/v1/environments/{0}/collections/{1}/documents/{2}'.format(
+ *self._encode_path_vars(environment_id, collection_id, document_id))
response = self.request(
method='POST',
- url='/v1/environments/{0}/collections/{1}/documents/{2}'.format(
- environment_id, collection_id, document_id),
+ url=url,
params=params,
files={'file': file_tuple,
'metadata': metadata_tuple},
@@ -888,11 +856,10 @@ class DiscoveryV1(WatsonService):
'deduplicate.field':
deduplicate_field
}
+ url = '/v1/environments/{0}/query'.format(
+ *self._encode_path_vars(environment_id))
response = self.request(
- method='GET',
- url='/v1/environments/{0}/query'.format(environment_id),
- params=params,
- accept_json=True)
+ method='GET', url=url, params=params, accept_json=True)
return response
def federated_query_notices(self,
@@ -964,11 +931,10 @@ class DiscoveryV1(WatsonService):
'deduplicate.field':
deduplicate_field
}
+ url = '/v1/environments/{0}/notices'.format(
+ *self._encode_path_vars(environment_id))
response = self.request(
- method='GET',
- url='/v1/environments/{0}/notices'.format(environment_id),
- params=params,
- accept_json=True)
+ method='GET', url=url, params=params, accept_json=True)
return response
def query(self,
@@ -1056,12 +1022,10 @@ class DiscoveryV1(WatsonService):
'deduplicate.field':
deduplicate_field
}
+ url = '/v1/environments/{0}/collections/{1}/query'.format(
+ *self._encode_path_vars(environment_id, collection_id))
response = self.request(
- method='GET',
- url='/v1/environments/{0}/collections/{1}/query'.format(
- environment_id, collection_id),
- params=params,
- accept_json=True)
+ method='GET', url=url, params=params, accept_json=True)
return response
def query_notices(self,
@@ -1147,12 +1111,10 @@ class DiscoveryV1(WatsonService):
'deduplicate.field':
deduplicate_field
}
+ url = '/v1/environments/{0}/collections/{1}/notices'.format(
+ *self._encode_path_vars(environment_id, collection_id))
response = self.request(
- method='GET',
- url='/v1/environments/{0}/collections/{1}/notices'.format(
- environment_id, collection_id),
- params=params,
- accept_json=True)
+ method='GET', url=url, params=params, accept_json=True)
return response
#########################
@@ -1189,13 +1151,10 @@ class DiscoveryV1(WatsonService):
'filter': filter,
'examples': examples
}
+ url = '/v1/environments/{0}/collections/{1}/training_data'.format(
+ *self._encode_path_vars(environment_id, collection_id))
response = self.request(
- method='POST',
- url='/v1/environments/{0}/collections/{1}/training_data'.format(
- environment_id, collection_id),
- params=params,
- json=data,
- accept_json=True)
+ method='POST', url=url, params=params, json=data, accept_json=True)
return response
def create_training_example(self,
@@ -1229,14 +1188,10 @@ class DiscoveryV1(WatsonService):
'cross_reference': cross_reference,
'relevance': relevance
}
+ url = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples'.format(
+ *self._encode_path_vars(environment_id, collection_id, query_id))
response = self.request(
- method='POST',
- url=
- '/v1/environments/{0}/collections/{1}/training_data/{2}/examples'.
- format(environment_id, collection_id, query_id),
- params=params,
- json=data,
- accept_json=True)
+ method='POST', url=url, params=params, json=data, accept_json=True)
return response
def delete_all_training_data(self, environment_id, collection_id):
@@ -1252,12 +1207,9 @@ class DiscoveryV1(WatsonService):
if collection_id is None:
raise ValueError('collection_id must be provided')
params = {'version': self.version}
- self.request(
- method='DELETE',
- url='/v1/environments/{0}/collections/{1}/training_data'.format(
- environment_id, collection_id),
- params=params,
- accept_json=True)
+ url = '/v1/environments/{0}/collections/{1}/training_data'.format(
+ *self._encode_path_vars(environment_id, collection_id))
+ self.request(method='DELETE', url=url, params=params, accept_json=True)
return None
def delete_training_data(self, environment_id, collection_id, query_id):
@@ -1276,12 +1228,9 @@ class DiscoveryV1(WatsonService):
if query_id is None:
raise ValueError('query_id must be provided')
params = {'version': self.version}
- self.request(
- method='DELETE',
- url='/v1/environments/{0}/collections/{1}/training_data/{2}'.format(
- environment_id, collection_id, query_id),
- params=params,
- accept_json=True)
+ url = '/v1/environments/{0}/collections/{1}/training_data/{2}'.format(
+ *self._encode_path_vars(environment_id, collection_id, query_id))
+ self.request(method='DELETE', url=url, params=params, accept_json=True)
return None
def delete_training_example(self, environment_id, collection_id, query_id,
@@ -1304,13 +1253,10 @@ class DiscoveryV1(WatsonService):
if example_id is None:
raise ValueError('example_id must be provided')
params = {'version': self.version}
- self.request(
- method='DELETE',
- url=
- '/v1/environments/{0}/collections/{1}/training_data/{2}/examples/{3}'.
- format(environment_id, collection_id, query_id, example_id),
- params=params,
- accept_json=True)
+ url = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples/{3}'.format(
+ *self._encode_path_vars(environment_id, collection_id, query_id,
+ example_id))
+ self.request(method='DELETE', url=url, params=params, accept_json=True)
return None
def get_training_data(self, environment_id, collection_id, query_id):
@@ -1331,12 +1277,10 @@ class DiscoveryV1(WatsonService):
if query_id is None:
raise ValueError('query_id must be provided')
params = {'version': self.version}
+ url = '/v1/environments/{0}/collections/{1}/training_data/{2}'.format(
+ *self._encode_path_vars(environment_id, collection_id, query_id))
response = self.request(
- method='GET',
- url='/v1/environments/{0}/collections/{1}/training_data/{2}'.format(
- environment_id, collection_id, query_id),
- params=params,
- accept_json=True)
+ method='GET', url=url, params=params, accept_json=True)
return response
def get_training_example(self, environment_id, collection_id, query_id,
@@ -1360,13 +1304,11 @@ class DiscoveryV1(WatsonService):
if example_id is None:
raise ValueError('example_id must be provided')
params = {'version': self.version}
+ url = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples/{3}'.format(
+ *self._encode_path_vars(environment_id, collection_id, query_id,
+ example_id))
response = self.request(
- method='GET',
- url=
- '/v1/environments/{0}/collections/{1}/training_data/{2}/examples/{3}'.
- format(environment_id, collection_id, query_id, example_id),
- params=params,
- accept_json=True)
+ method='GET', url=url, params=params, accept_json=True)
return response
def list_training_data(self, environment_id, collection_id):
@@ -1383,12 +1325,10 @@ class DiscoveryV1(WatsonService):
if collection_id is None:
raise ValueError('collection_id must be provided')
params = {'version': self.version}
+ url = '/v1/environments/{0}/collections/{1}/training_data'.format(
+ *self._encode_path_vars(environment_id, collection_id))
response = self.request(
- method='GET',
- url='/v1/environments/{0}/collections/{1}/training_data'.format(
- environment_id, collection_id),
- params=params,
- accept_json=True)
+ method='GET', url=url, params=params, accept_json=True)
return response
def list_training_examples(self, environment_id, collection_id, query_id):
@@ -1408,13 +1348,10 @@ class DiscoveryV1(WatsonService):
if query_id is None:
raise ValueError('query_id must be provided')
params = {'version': self.version}
+ url = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples'.format(
+ *self._encode_path_vars(environment_id, collection_id, query_id))
response = self.request(
- method='GET',
- url=
- '/v1/environments/{0}/collections/{1}/training_data/{2}/examples'.
- format(environment_id, collection_id, query_id),
- params=params,
- accept_json=True)
+ method='GET', url=url, params=params, accept_json=True)
return response
def update_training_example(self,
@@ -1446,14 +1383,11 @@ class DiscoveryV1(WatsonService):
raise ValueError('example_id must be provided')
params = {'version': self.version}
data = {'cross_reference': cross_reference, 'relevance': relevance}
+ url = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples/{3}'.format(
+ *self._encode_path_vars(environment_id, collection_id, query_id,
+ example_id))
response = self.request(
- method='PUT',
- url=
- '/v1/environments/{0}/collections/{1}/training_data/{2}/examples/{3}'.
- format(environment_id, collection_id, query_id, example_id),
- params=params,
- json=data,
- accept_json=True)
+ method='PUT', url=url, params=params, json=data, accept_json=True)
return response
diff --git a/watson_developer_cloud/language_translator_v2.py b/watson_developer_cloud/language_translator_v2.py
index 060fa1d8..b98bda0c 100644
--- a/watson_developer_cloud/language_translator_v2.py
+++ b/watson_developer_cloud/language_translator_v2.py
@@ -88,8 +88,9 @@ class LanguageTranslatorV2(WatsonService):
'source': source,
'target': target
}
+ url = '/v2/translate'
response = self.request(
- method='POST', url='/v2/translate', json=data, accept_json=True)
+ method='POST', url=url, json=data, accept_json=True)
return response
#########################
@@ -108,9 +109,10 @@ class LanguageTranslatorV2(WatsonService):
raise ValueError('text must be provided')
data = text
headers = {'content-type': 'text/plain'}
+ url = '/v2/identify'
response = self.request(
method='POST',
- url='/v2/identify',
+ url=url,
headers=headers,
data=data,
accept_json=True)
@@ -126,8 +128,8 @@ class LanguageTranslatorV2(WatsonService):
:return: A `dict` containing the `IdentifiableLanguages` response.
:rtype: dict
"""
- response = self.request(
- method='GET', url='/v2/identifiable_languages', accept_json=True)
+ url = '/v2/identifiable_languages'
+ response = self.request(method='GET', url=url, accept_json=True)
return response
#########################
@@ -184,9 +186,10 @@ class LanguageTranslatorV2(WatsonService):
mime_type = 'text/plain'
monolingual_corpus_tuple = (monolingual_corpus_filename,
monolingual_corpus, mime_type)
+ url = '/v2/models'
response = self.request(
method='POST',
- url='/v2/models',
+ url=url,
params=params,
files={
'forced_glossary': forced_glossary_tuple,
@@ -206,10 +209,8 @@ class LanguageTranslatorV2(WatsonService):
"""
if model_id is None:
raise ValueError('model_id must be provided')
- response = self.request(
- method='DELETE',
- url='/v2/models/{0}'.format(model_id),
- accept_json=True)
+ url = '/v2/models/{0}'.format(*self._encode_path_vars(model_id))
+ response = self.request(method='DELETE', url=url, accept_json=True)
return response
def get_model(self, model_id):
@@ -222,10 +223,8 @@ class LanguageTranslatorV2(WatsonService):
"""
if model_id is None:
raise ValueError('model_id must be provided')
- response = self.request(
- method='GET',
- url='/v2/models/{0}'.format(model_id),
- accept_json=True)
+ url = '/v2/models/{0}'.format(*self._encode_path_vars(model_id))
+ response = self.request(method='GET', url=url, accept_json=True)
return response
def list_models(self, source=None, target=None, default_models=None):
@@ -239,8 +238,9 @@ class LanguageTranslatorV2(WatsonService):
:rtype: dict
"""
params = {'source': source, 'target': target, 'default': default_models}
+ url = '/v2/models'
response = self.request(
- method='GET', url='/v2/models', params=params, accept_json=True)
+ method='GET', url=url, params=params, accept_json=True)
return response
diff --git a/watson_developer_cloud/natural_language_classifier_v1.py b/watson_developer_cloud/natural_language_classifier_v1.py
index d33fcba3..47ff3267 100644
--- a/watson_developer_cloud/natural_language_classifier_v1.py
+++ b/watson_developer_cloud/natural_language_classifier_v1.py
@@ -87,11 +87,10 @@ class NaturalLanguageClassifierV1(WatsonService):
if text is None:
raise ValueError('text must be provided')
data = {'text': text}
+ url = '/v1/classifiers/{0}/classify'.format(
+ *self._encode_path_vars(classifier_id))
response = self.request(
- method='POST',
- url='/v1/classifiers/{0}/classify'.format(classifier_id),
- json=data,
- accept_json=True)
+ method='POST', url=url, json=data, accept_json=True)
return response
def create_classifier(self,
@@ -124,9 +123,10 @@ class NaturalLanguageClassifierV1(WatsonService):
training_data_filename = training_data.name
mime_type = 'text/csv'
training_data_tuple = (training_data_filename, training_data, mime_type)
+ url = '/v1/classifiers'
response = self.request(
method='POST',
- url='/v1/classifiers',
+ url=url,
files={
'metadata': metadata_tuple,
'training_data': training_data_tuple
@@ -143,10 +143,9 @@ class NaturalLanguageClassifierV1(WatsonService):
"""
if classifier_id is None:
raise ValueError('classifier_id must be provided')
- self.request(
- method='DELETE',
- url='/v1/classifiers/{0}'.format(classifier_id),
- accept_json=True)
+ url = '/v1/classifiers/{0}'.format(
+ *self._encode_path_vars(classifier_id))
+ self.request(method='DELETE', url=url, accept_json=True)
return None
def get_classifier(self, classifier_id):
@@ -161,10 +160,9 @@ class NaturalLanguageClassifierV1(WatsonService):
"""
if classifier_id is None:
raise ValueError('classifier_id must be provided')
- response = self.request(
- method='GET',
- url='/v1/classifiers/{0}'.format(classifier_id),
- accept_json=True)
+ url = '/v1/classifiers/{0}'.format(
+ *self._encode_path_vars(classifier_id))
+ response = self.request(method='GET', url=url, accept_json=True)
return response
def list_classifiers(self):
@@ -176,8 +174,8 @@ class NaturalLanguageClassifierV1(WatsonService):
:return: A `dict` containing the `ClassifierList` response.
:rtype: dict
"""
- response = self.request(
- method='GET', url='/v1/classifiers', accept_json=True)
+ url = '/v1/classifiers'
+ response = self.request(method='GET', url=url, accept_json=True)
return response
diff --git a/watson_developer_cloud/natural_language_understanding_v1.py b/watson_developer_cloud/natural_language_understanding_v1.py
index 41710c36..c737ad3d 100644
--- a/watson_developer_cloud/natural_language_understanding_v1.py
+++ b/watson_developer_cloud/natural_language_understanding_v1.py
@@ -169,12 +169,9 @@ class NaturalLanguageUnderstandingV1(WatsonService):
'language': language,
'limit_text_characters': limit_text_characters
}
+ url = '/v1/analyze'
response = self.request(
- method='POST',
- url='/v1/analyze',
- params=params,
- json=data,
- accept_json=True)
+ method='POST', url=url, params=params, json=data, accept_json=True)
return response
#########################
@@ -194,11 +191,9 @@ class NaturalLanguageUnderstandingV1(WatsonService):
if model_id is None:
raise ValueError('model_id must be provided')
params = {'version': self.version}
+ url = '/v1/models/{0}'.format(*self._encode_path_vars(model_id))
response = self.request(
- method='DELETE',
- url='/v1/models/{0}'.format(model_id),
- params=params,
- accept_json=True)
+ method='DELETE', url=url, params=params, accept_json=True)
return response
def list_models(self):
@@ -213,8 +208,9 @@ class NaturalLanguageUnderstandingV1(WatsonService):
:rtype: dict
"""
params = {'version': self.version}
+ url = '/v1/models'
response = self.request(
- method='GET', url='/v1/models', params=params, accept_json=True)
+ method='GET', url=url, params=params, accept_json=True)
return response
diff --git a/watson_developer_cloud/personality_insights_v3.py b/watson_developer_cloud/personality_insights_v3.py
index c51c4686..cb4a359d 100755
--- a/watson_developer_cloud/personality_insights_v3.py
+++ b/watson_developer_cloud/personality_insights_v3.py
@@ -166,9 +166,10 @@ class PersonalityInsightsV3(WatsonService):
data = json.dumps(content)
else:
data = content
+ url = '/v3/profile'
response = self.request(
method='POST',
- url='/v3/profile',
+ url=url,
headers=headers,
params=params,
data=data,
diff --git a/watson_developer_cloud/tone_analyzer_v3.py b/watson_developer_cloud/tone_analyzer_v3.py
index 435bd77b..ee538289 100755
--- a/watson_developer_cloud/tone_analyzer_v3.py
+++ b/watson_developer_cloud/tone_analyzer_v3.py
@@ -166,9 +166,10 @@ class ToneAnalyzerV3(WatsonService):
data = json.dumps(tone_input)
else:
data = tone_input
+ url = '/v3/tone'
response = self.request(
method='POST',
- url='/v3/tone',
+ url=url,
headers=headers,
params=params,
data=data,
@@ -201,9 +202,10 @@ class ToneAnalyzerV3(WatsonService):
headers = {'Accept-Language': accept_language}
params = {'version': self.version}
data = {'utterances': utterances}
+ url = '/v3/tone_chat'
response = self.request(
method='POST',
- url='/v3/tone_chat',
+ url=url,
headers=headers,
params=params,
json=data,
diff --git a/watson_developer_cloud/visual_recognition_v3.py b/watson_developer_cloud/visual_recognition_v3.py
index c620885e..e521e804 100644
--- a/watson_developer_cloud/visual_recognition_v3.py
+++ b/watson_developer_cloud/visual_recognition_v3.py
@@ -106,9 +106,10 @@ class VisualRecognitionV3(WatsonService):
parameters_tuple = None
if parameters:
parameters_tuple = (None, parameters, 'text/plain')
+ url = '/v3/classify'
response = self.request(
method='POST',
- url='/v3/classify',
+ url=url,
headers=headers,
params=params,
files={
@@ -143,9 +144,10 @@ class VisualRecognitionV3(WatsonService):
parameters_tuple = None
if parameters:
parameters_tuple = (None, parameters, 'text/plain')
+ url = '/v3/detect_faces'
response = self.request(
method='POST',
- url='/v3/detect_faces',
+ url=url,
params=params,
files={
'images_file': images_file_tuple,
@@ -174,9 +176,10 @@ class VisualRecognitionV3(WatsonService):
raise ValueError('name must be provided')
params = {'version': self.version}
data = {'name': name}
+ url = '/v3/classifiers'
response = self.request(
method='POST',
- url='/v3/classifiers',
+ url=url,
params=params,
data=data,
files=kwargs,
@@ -193,11 +196,9 @@ class VisualRecognitionV3(WatsonService):
if classifier_id is None:
raise ValueError('classifier_id must be provided')
params = {'version': self.version}
- self.request(
- method='DELETE',
- url='/v3/classifiers/{0}'.format(classifier_id),
- params=params,
- accept_json=True)
+ url = '/v3/classifiers/{0}'.format(
+ *self._encode_path_vars(classifier_id))
+ self.request(method='DELETE', url=url, params=params, accept_json=True)
return None
def get_classifier(self, classifier_id):
@@ -211,11 +212,10 @@ class VisualRecognitionV3(WatsonService):
if classifier_id is None:
raise ValueError('classifier_id must be provided')
params = {'version': self.version}
+ url = '/v3/classifiers/{0}'.format(
+ *self._encode_path_vars(classifier_id))
response = self.request(
- method='GET',
- url='/v3/classifiers/{0}'.format(classifier_id),
- params=params,
- accept_json=True)
+ method='GET', url=url, params=params, accept_json=True)
return response
def list_classifiers(self, verbose=None):
@@ -227,11 +227,9 @@ class VisualRecognitionV3(WatsonService):
:rtype: dict
"""
params = {'version': self.version, 'verbose': verbose}
+ url = '/v3/classifiers'
response = self.request(
- method='GET',
- url='/v3/classifiers',
- params=params,
- accept_json=True)
+ method='GET', url=url, params=params, accept_json=True)
return response
def update_classifier(self,
@@ -249,9 +247,11 @@ class VisualRecognitionV3(WatsonService):
if classifier_id is None:
raise ValueError('classifier_id must be provided')
params = {'version': self.version}
+ url = '/v3/classifiers/{0}'.format(
+ *self._encode_path_vars(classifier_id))
response = self.request(
method='POST',
- url='/v3/classifiers/{0}'.format(classifier_id),
+ url=url,
params=params,
files=kwargs,
accept_json=True)
diff --git a/watson_developer_cloud/watson_service.py b/watson_developer_cloud/watson_service.py
index 619ea733..6b703735 100755
--- a/watson_developer_cloud/watson_service.py
+++ b/watson_developer_cloud/watson_service.py
@@ -227,6 +227,10 @@ class WatsonService(object):
return val._to_dict()
return val
+ @staticmethod
+ def _encode_path_vars(*args):
+ return (requests.utils.quote(x, safe='') for x in args)
+
@staticmethod
def _get_error_message(response):
"""
| Conversation - Error on .delete_example when example is "#"
When deleting an intent example with text "#" the following error raises:
`DEBUG:urllib3.connectionpool:https://gateway.watsonplatform.net:443 "DELETE /conversation/api/v1/workspaces/00e477c9-790b-47e7-ee11-48fcx1c22496c/intents/what_is_conversational_experience/examples/?version=2017-05-26 HTTP/1.1" 404 None`
Python 3.5.2 on Linux
watson-developer-cloud==0.26.1 | watson-developer-cloud/python-sdk | diff --git a/test/test_conversation_v1.py b/test/test_conversation_v1.py
index f696abcd..a70d4160 100644
--- a/test/test_conversation_v1.py
+++ b/test/test_conversation_v1.py
@@ -140,7 +140,7 @@ def test_get_counterexample():
service = watson_developer_cloud.ConversationV1(
username='username', password='password', version='2017-02-03')
counterexample = service.get_counterexample(
- workspace_id='boguswid', text='What are you wearing%3F')
+ workspace_id='boguswid', text='What are you wearing?')
assert len(responses.calls) == 1
assert responses.calls[0].request.url.startswith(url)
assert counterexample == response
@@ -203,8 +203,8 @@ def test_update_counterexample():
username='username', password='password', version='2017-02-03')
counterexample = service.update_counterexample(
workspace_id='boguswid',
- text='What are you wearing%3F',
- new_text='What are you wearing%3F')
+ text='What are you wearing?',
+ new_text='What are you wearing?')
assert len(responses.calls) == 1
assert responses.calls[0].request.url.startswith(url)
assert counterexample == response
diff --git a/test/test_watson_service.py b/test/test_watson_service.py
new file mode 100755
index 00000000..62ff3ee1
--- /dev/null
+++ b/test/test_watson_service.py
@@ -0,0 +1,63 @@
+# coding=utf-8
+import json
+
+from watson_developer_cloud import WatsonService
+
+import responses
+
+##############################################################################
+# Service
+##############################################################################
+
+class AnyServiceV1(WatsonService):
+ default_url = 'https://gateway.watsonplatform.net/test/api'
+
+ def __init__(self, version, url=default_url, username=None, password=None):
+ WatsonService.__init__(
+ self,
+ vcap_services_name='test',
+ url=url,
+ username=username,
+ password=password,
+ use_vcap_services=True)
+ self.version = version
+
+ def op_with_path_params(self, path0, path1):
+ if path0 is None:
+ raise ValueError('path0 must be provided')
+ if path1 is None:
+ raise ValueError('path1 must be provided')
+ params = {'version': self.version}
+ url = '/v1/foo/{0}/bar/{1}/baz'.format(
+ *self._encode_path_vars(path0, path1))
+ response = self.request(
+ method='GET', url=url, params=params, accept_json=True)
+ return response
+
+
[email protected]
+def test_url_encoding():
+ service = AnyServiceV1('2017-07-07', username='username', password='password')
+
+ # All characters in path0 _must_ be encoded in path segments
+ path0 = ' \"<>^`{}|/\\?#%[]'
+ path0_encoded = '%20%22%3C%3E%5E%60%7B%7D%7C%2F%5C%3F%23%25%5B%5D'
+ # All non-ASCII chars _must_ be encoded in path segments
+ path1 = u'比萨浇头'.encode('utf8') # "pizza toppings"
+ path1_encoded = '%E6%AF%94%E8%90%A8%E6%B5%87%E5%A4%B4'
+
+ path_encoded = '/v1/foo/' + path0_encoded + '/bar/' + path1_encoded + '/baz'
+ test_url = service.default_url + path_encoded
+
+ responses.add(responses.GET,
+ test_url,
+ status=200,
+ body=json.dumps({"foobar": "baz"}),
+ content_type='application/json')
+
+ response = service.op_with_path_params(path0, path1)
+
+ assert response is not None
+ assert len(responses.calls) == 1
+ assert path_encoded in responses.calls[0].request.url
+ assert 'version=2017-07-07' in responses.calls[0].request.url
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 0,
"test_score": 3
},
"num_modified_files": 12
} | 0.26 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"responses",
"python_dotenv"
],
"pre_install": null,
"python": "3.6",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs==22.2.0
certifi==2021.5.30
cffi==1.15.1
charset-normalizer==2.0.12
cryptography==40.0.2
idna==3.10
importlib-metadata==4.8.3
iniconfig==1.1.1
packaging==21.3
pluggy==1.0.0
py==1.11.0
pycparser==2.21
pyOpenSSL==23.2.0
pyparsing==3.1.4
pysolr==3.10.0
pytest==7.0.1
python-dateutil==2.9.0.post0
python-dotenv==0.20.0
requests==2.27.1
responses==0.17.0
six==1.17.0
tomli==1.2.3
typing_extensions==4.1.1
urllib3==1.26.20
-e git+https://github.com/watson-developer-cloud/python-sdk.git@f0fda953cf81204d2bf11d61d1e792292ced0d6f#egg=watson_developer_cloud
zipp==3.6.0
| name: python-sdk
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- argparse==1.4.0
- attrs==22.2.0
- cffi==1.15.1
- charset-normalizer==2.0.12
- cryptography==40.0.2
- idna==3.10
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- packaging==21.3
- pluggy==1.0.0
- py==1.11.0
- pycparser==2.21
- pyopenssl==23.2.0
- pyparsing==3.1.4
- pysolr==3.10.0
- pytest==7.0.1
- python-dateutil==2.9.0.post0
- python-dotenv==0.20.0
- requests==2.27.1
- responses==0.17.0
- six==1.17.0
- tomli==1.2.3
- typing-extensions==4.1.1
- urllib3==1.26.20
- zipp==3.6.0
prefix: /opt/conda/envs/python-sdk
| [
"test/test_conversation_v1.py::test_get_counterexample",
"test/test_conversation_v1.py::test_update_counterexample",
"test/test_watson_service.py::test_url_encoding"
]
| [
"test/test_conversation_v1.py::test_message",
"test/test_conversation_v1.py::test_message_with_models"
]
| [
"test/test_conversation_v1.py::test_create_counterexample",
"test/test_conversation_v1.py::test_rate_limit_exceeded",
"test/test_conversation_v1.py::test_unknown_error",
"test/test_conversation_v1.py::test_delete_counterexample",
"test/test_conversation_v1.py::test_list_counterexamples",
"test/test_conversation_v1.py::test_create_entity",
"test/test_conversation_v1.py::test_delete_entity",
"test/test_conversation_v1.py::test_get_entity",
"test/test_conversation_v1.py::test_list_entities",
"test/test_conversation_v1.py::test_update_entity",
"test/test_conversation_v1.py::test_create_example",
"test/test_conversation_v1.py::test_delete_example",
"test/test_conversation_v1.py::test_get_example",
"test/test_conversation_v1.py::test_list_examples",
"test/test_conversation_v1.py::test_update_example",
"test/test_conversation_v1.py::test_create_intent",
"test/test_conversation_v1.py::test_delete_intent",
"test/test_conversation_v1.py::test_get_intent",
"test/test_conversation_v1.py::test_list_intents",
"test/test_conversation_v1.py::test_update_intent",
"test/test_conversation_v1.py::test_intent_models",
"test/test_conversation_v1.py::test_list_logs",
"test/test_conversation_v1.py::test_create_synonym",
"test/test_conversation_v1.py::test_delete_synonym",
"test/test_conversation_v1.py::test_get_synonym",
"test/test_conversation_v1.py::test_list_synonyms",
"test/test_conversation_v1.py::test_update_synonym",
"test/test_conversation_v1.py::test_create_value",
"test/test_conversation_v1.py::test_delete_value",
"test/test_conversation_v1.py::test_get_value",
"test/test_conversation_v1.py::test_list_values",
"test/test_conversation_v1.py::test_update_value",
"test/test_conversation_v1.py::test_create_workspace",
"test/test_conversation_v1.py::test_delete_workspace",
"test/test_conversation_v1.py::test_get_workspace",
"test/test_conversation_v1.py::test_list_workspaces",
"test/test_conversation_v1.py::test_update_workspace"
]
| []
| Apache License 2.0 | 1,884 | [
"watson_developer_cloud/watson_service.py",
"watson_developer_cloud/discovery_v1.py",
"examples/conversation_tone_analyzer_integration/tone_detection.py",
"watson_developer_cloud/personality_insights_v3.py",
"watson_developer_cloud/conversation_v1.py",
"pylint.sh",
"watson_developer_cloud/language_translator_v2.py",
"watson_developer_cloud/tone_analyzer_v3.py",
"watson_developer_cloud/visual_recognition_v3.py",
"watson_developer_cloud/natural_language_understanding_v1.py",
"examples/personality_insights_v3.py",
"watson_developer_cloud/natural_language_classifier_v1.py"
]
| [
"watson_developer_cloud/watson_service.py",
"watson_developer_cloud/discovery_v1.py",
"examples/conversation_tone_analyzer_integration/tone_detection.py",
"watson_developer_cloud/personality_insights_v3.py",
"watson_developer_cloud/conversation_v1.py",
"pylint.sh",
"watson_developer_cloud/language_translator_v2.py",
"watson_developer_cloud/tone_analyzer_v3.py",
"watson_developer_cloud/visual_recognition_v3.py",
"watson_developer_cloud/natural_language_understanding_v1.py",
"examples/personality_insights_v3.py",
"watson_developer_cloud/natural_language_classifier_v1.py"
]
|
|
numpy__numpydoc-143 | 8c1e85c746d1c95b9433b2ae97057b7f447c83d1 | 2017-11-13 11:10:39 | 8c1e85c746d1c95b9433b2ae97057b7f447c83d1 | diff --git a/doc/install.rst b/doc/install.rst
index d408189..5658dbb 100644
--- a/doc/install.rst
+++ b/doc/install.rst
@@ -9,8 +9,8 @@ The extension is available from:
* `numpydoc on GitHub <https://github.com/numpy/numpydoc/>`_
'numpydoc' should be added to the ``extensions`` option in your Sphinx
-``conf.py``.
-
+``conf.py``. (Note that `sphinx.ext.autosummary` will automatically be loaded
+as well.)
Sphinx config options
=====================
diff --git a/numpydoc/docscrape_sphinx.py b/numpydoc/docscrape_sphinx.py
index 640efa7..087ddaf 100644
--- a/numpydoc/docscrape_sphinx.py
+++ b/numpydoc/docscrape_sphinx.py
@@ -84,10 +84,11 @@ class SphinxDocString(NumpyDocString):
param_type)])
else:
out += self._str_indent([untyped_fmt % param.strip()])
- if desc:
- if self.use_blockquotes:
- out += ['']
- out += self._str_indent(desc, 8)
+ if desc and self.use_blockquotes:
+ out += ['']
+ elif not desc:
+ desc = ['..']
+ out += self._str_indent(desc, 8)
out += ['']
return out
diff --git a/numpydoc/numpydoc.py b/numpydoc/numpydoc.py
index 26abd66..0a6cc79 100644
--- a/numpydoc/numpydoc.py
+++ b/numpydoc/numpydoc.py
@@ -151,6 +151,8 @@ def setup(app, get_doc_object_=get_doc_object):
app.add_domain(NumpyPythonDomain)
app.add_domain(NumpyCDomain)
+ app.setup_extension('sphinx.ext.autosummary')
+
metadata = {'version': __version__,
'parallel_read_safe': True}
return metadata
| dependency on sphinx.ext.autosummary
It appears that numpydoc has a hard dependency on sphinx.ext.autosummary being active (it inserts some `.. autosummary::` directives). This is fine, but perhaps `numpydoc.setup` should just call `sphinx.ext.autosummary.setup` in that case? (in the sense that I don't see much of a point in erroring out instead, which is the current behavior if sphinx.ext.autosummary is not listed in conf.py) | numpy/numpydoc | diff --git a/numpydoc/tests/test_docscrape.py b/numpydoc/tests/test_docscrape.py
index fa3f700..21bbe28 100644
--- a/numpydoc/tests/test_docscrape.py
+++ b/numpydoc/tests/test_docscrape.py
@@ -64,6 +64,7 @@ doc_txt = '''\
list of str
This is not a real return value. It exists to test
anonymous return values.
+ no_description
Other Parameters
----------------
@@ -184,7 +185,7 @@ def test_other_parameters():
def test_returns():
- assert_equal(len(doc['Returns']), 2)
+ assert_equal(len(doc['Returns']), 3)
arg, arg_type, desc = doc['Returns'][0]
assert_equal(arg, 'out')
assert_equal(arg_type, 'ndarray')
@@ -197,6 +198,11 @@ def test_returns():
assert desc[0].startswith('This is not a real')
assert desc[-1].endswith('anonymous return values.')
+ arg, arg_type, desc = doc['Returns'][2]
+ assert_equal(arg, 'no_description')
+ assert_equal(arg_type, '')
+ assert not ''.join(desc).strip()
+
def test_yields():
section = doc_yields['Yields']
@@ -373,6 +379,7 @@ out : ndarray
list of str
This is not a real return value. It exists to test
anonymous return values.
+no_description
Other Parameters
----------------
@@ -506,6 +513,9 @@ of the one-dimensional normal distribution to higher dimensions.
This is not a real return value. It exists to test
anonymous return values.
+ no_description
+ ..
+
:Other Parameters:
spam : parrot
| {
"commit_name": "merge_commit",
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 1,
"test_score": 3
},
"num_modified_files": 3
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest"
],
"pre_install": [
"pip install --upgrade pip setuptools",
"pip install nose"
],
"python": "3.6",
"reqs_path": [
"requirements/base.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | alabaster==0.7.13
attrs==22.2.0
Babel==2.11.0
certifi==2021.5.30
charset-normalizer==2.0.12
docutils==0.18.1
idna==3.10
imagesize==1.4.1
importlib-metadata==4.8.3
iniconfig==1.1.1
Jinja2==3.0.3
MarkupSafe==2.0.1
nose==1.3.7
-e git+https://github.com/numpy/numpydoc.git@8c1e85c746d1c95b9433b2ae97057b7f447c83d1#egg=numpydoc
packaging==21.3
pluggy==1.0.0
py==1.11.0
Pygments==2.14.0
pyparsing==3.1.4
pytest==7.0.1
pytz==2025.2
requests==2.27.1
snowballstemmer==2.2.0
Sphinx==5.3.0
sphinxcontrib-applehelp==1.0.2
sphinxcontrib-devhelp==1.0.2
sphinxcontrib-htmlhelp==2.0.0
sphinxcontrib-jsmath==1.0.1
sphinxcontrib-qthelp==1.0.3
sphinxcontrib-serializinghtml==1.1.5
tomli==1.2.3
typing_extensions==4.1.1
urllib3==1.26.20
zipp==3.6.0
| name: numpydoc
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- alabaster==0.7.13
- attrs==22.2.0
- babel==2.11.0
- charset-normalizer==2.0.12
- docutils==0.18.1
- idna==3.10
- imagesize==1.4.1
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- jinja2==3.0.3
- markupsafe==2.0.1
- nose==1.3.7
- packaging==21.3
- pip==21.3.1
- pluggy==1.0.0
- py==1.11.0
- pygments==2.14.0
- pyparsing==3.1.4
- pytest==7.0.1
- pytz==2025.2
- requests==2.27.1
- setuptools==59.6.0
- snowballstemmer==2.2.0
- sphinx==5.3.0
- sphinxcontrib-applehelp==1.0.2
- sphinxcontrib-devhelp==1.0.2
- sphinxcontrib-htmlhelp==2.0.0
- sphinxcontrib-jsmath==1.0.1
- sphinxcontrib-qthelp==1.0.3
- sphinxcontrib-serializinghtml==1.1.5
- tomli==1.2.3
- typing-extensions==4.1.1
- urllib3==1.26.20
- zipp==3.6.0
prefix: /opt/conda/envs/numpydoc
| [
"numpydoc/tests/test_docscrape.py::test_sphinx_str"
]
| []
| [
"numpydoc/tests/test_docscrape.py::test_signature",
"numpydoc/tests/test_docscrape.py::test_summary",
"numpydoc/tests/test_docscrape.py::test_extended_summary",
"numpydoc/tests/test_docscrape.py::test_parameters",
"numpydoc/tests/test_docscrape.py::test_other_parameters",
"numpydoc/tests/test_docscrape.py::test_returns",
"numpydoc/tests/test_docscrape.py::test_yields",
"numpydoc/tests/test_docscrape.py::test_returnyield",
"numpydoc/tests/test_docscrape.py::test_section_twice",
"numpydoc/tests/test_docscrape.py::test_notes",
"numpydoc/tests/test_docscrape.py::test_references",
"numpydoc/tests/test_docscrape.py::test_examples",
"numpydoc/tests/test_docscrape.py::test_index",
"numpydoc/tests/test_docscrape.py::test_str",
"numpydoc/tests/test_docscrape.py::test_yield_str",
"numpydoc/tests/test_docscrape.py::test_sphinx_yields_str",
"numpydoc/tests/test_docscrape.py::test_parameters_without_extended_description",
"numpydoc/tests/test_docscrape.py::test_escape_stars",
"numpydoc/tests/test_docscrape.py::test_empty_extended_summary",
"numpydoc/tests/test_docscrape.py::test_raises",
"numpydoc/tests/test_docscrape.py::test_warns",
"numpydoc/tests/test_docscrape.py::test_see_also",
"numpydoc/tests/test_docscrape.py::test_see_also_parse_error",
"numpydoc/tests/test_docscrape.py::test_see_also_print",
"numpydoc/tests/test_docscrape.py::test_unknown_section",
"numpydoc/tests/test_docscrape.py::test_empty_first_line",
"numpydoc/tests/test_docscrape.py::test_no_summary",
"numpydoc/tests/test_docscrape.py::test_unicode",
"numpydoc/tests/test_docscrape.py::test_plot_examples",
"numpydoc/tests/test_docscrape.py::test_use_blockquotes",
"numpydoc/tests/test_docscrape.py::test_class_members",
"numpydoc/tests/test_docscrape.py::test_duplicate_signature",
"numpydoc/tests/test_docscrape.py::test_class_members_doc",
"numpydoc/tests/test_docscrape.py::test_class_members_doc_sphinx",
"numpydoc/tests/test_docscrape.py::test_templated_sections"
]
| []
| BSD License | 1,885 | [
"numpydoc/numpydoc.py",
"numpydoc/docscrape_sphinx.py",
"doc/install.rst"
]
| [
"numpydoc/numpydoc.py",
"numpydoc/docscrape_sphinx.py",
"doc/install.rst"
]
|
|
nose-devs__nose2-370 | 862b130652b9118eb8d5681923c04edb000245d3 | 2017-11-13 16:40:20 | 90945cad86df2d11cc9332219ee85aca97311f6e | coveralls:
[](https://coveralls.io/builds/14177954)
Coverage increased (+0.003%) to 87.456% when pulling **9dbc760a4ebbee8a5e5c5201446966b012b5d80d on artragis:fix_327** into **862b130652b9118eb8d5681923c04edb000245d3 on nose-devs:master**.
coveralls:
[](https://coveralls.io/builds/14177954)
Coverage increased (+0.003%) to 87.456% when pulling **9dbc760a4ebbee8a5e5c5201446966b012b5d80d on artragis:fix_327** into **862b130652b9118eb8d5681923c04edb000245d3 on nose-devs:master**.
katrinabrock: Did adding a docstring to the test actually cause it to fail? If not, please write a test that fails in mainline to demonstrate the issue.
artragis: > Did adding a docstring to the test actually cause it to fail? If not, please write a test that fails in mainline to demonstrate the issue.
Yes it did. That's why I had to change the "expected" text
| diff --git a/nose2/plugins/layers.py b/nose2/plugins/layers.py
index 43025ca..eda14dc 100644
--- a/nose2/plugins/layers.py
+++ b/nose2/plugins/layers.py
@@ -235,6 +235,9 @@ class LayerReporter(events.Plugin):
if event.errorList and hasattr(event.test, 'layer'):
# walk back layers to build full description
self.describeLayers(event)
+ # we need to remove "\n" from description to keep a well indented report when tests have docstrings
+ # see https://github.com/nose-devs/nose2/issues/327 for more information
+ event.description = event.description.replace('\n', ' ')
def describeLayers(self, event):
desc = [event.description]
| Layer-reporter does not indent docstring
Given a test
def test_mymethond(self):
"""what this does
hi there
"""
nose2 will output 'what this does' when the test is run, but the text will not be indented to reflect the layers used.
Result of test run:
TopLayer
SecondLayer
test_find_unassigned_signals (test_wrapper.SecondLayerTests) ... ok
test_no_newer_definitions (test_wrapper.SecondLayerTests)
Test that versions in API Wrapper are the latest ... ok
test_only_add_customer_once (test_wrapper.SecondLayerTests) ... ok
test_only_one_parquet_file_pr_customer (test_wrapper.SecondLayerTests) ... ok
Expected:
TopLayer
SecondLayer
test_find_unassigned_signals (test_wrapper.SecondLayerTests) ... ok
test_no_newer_definitions (test_wrapper.SecondLayerTests)
Test that versions in API Wrapper are the latest ... ok
test_only_add_customer_once (test_wrapper.SecondLayerTests) ... ok
test_only_one_parquet_file_pr_customer (test_wrapper.SecondLayerTests) ... ok
or maybe even
TopLayer
SecondLayer
test_find_unassigned_signals (test_wrapper.SecondLayerTests) ... ok
Test that versions in API Wrapper are the latest (test_wrapper.SecondLayerTests) ... ok
test_only_add_customer_once (test_wrapper.SecondLayerTests) ... ok
test_only_one_parquet_file_pr_customer (test_wrapper.SecondLayerTests) ... ok | nose-devs/nose2 | diff --git a/nose2/tests/functional/support/scenario/layers/test_layers.py b/nose2/tests/functional/support/scenario/layers/test_layers.py
index e800780..a35bb0f 100644
--- a/nose2/tests/functional/support/scenario/layers/test_layers.py
+++ b/nose2/tests/functional/support/scenario/layers/test_layers.py
@@ -180,6 +180,8 @@ class InnerD(unittest.TestCase):
layer = LayerD
def test(self):
+ """test with docstring
+ """
self.assertEqual(
{'base': 'setup',
'layerD': 'setup'},
diff --git a/nose2/tests/functional/test_layers_plugin.py b/nose2/tests/functional/test_layers_plugin.py
index 9666dba..c658bbe 100644
--- a/nose2/tests/functional/test_layers_plugin.py
+++ b/nose2/tests/functional/test_layers_plugin.py
@@ -56,7 +56,7 @@ class TestLayers(FunctionalTestCase):
Base
test \(test_layers.Outer\) ... ok
LayerD
- test \(test_layers.InnerD\) ... ok
+ test \(test_layers.InnerD\) test with docstring ... ok
LayerA
test \(test_layers.InnerA\) ... ok
LayerB
| {
"commit_name": "merge_commit",
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 2,
"test_score": 0
},
"num_modified_files": 1
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[coverage_plugin,doc]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.5",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | alabaster==0.7.13
attrs==22.2.0
Babel==2.11.0
certifi==2021.5.30
charset-normalizer==2.0.12
coverage==6.2
docutils==0.18.1
idna==3.10
imagesize==1.4.1
importlib-metadata==4.8.3
iniconfig==1.1.1
Jinja2==3.0.3
MarkupSafe==2.0.1
mock==5.2.0
-e git+https://github.com/nose-devs/nose2.git@862b130652b9118eb8d5681923c04edb000245d3#egg=nose2
packaging==21.3
pluggy==1.0.0
py==1.11.0
Pygments==2.14.0
pyparsing==3.1.4
pytest==7.0.1
pytz==2025.2
requests==2.27.1
six==1.17.0
snowballstemmer==2.2.0
Sphinx==5.3.0
sphinx-rtd-theme==2.0.0
sphinxcontrib-applehelp==1.0.2
sphinxcontrib-devhelp==1.0.2
sphinxcontrib-htmlhelp==2.0.0
sphinxcontrib-jquery==4.1
sphinxcontrib-jsmath==1.0.1
sphinxcontrib-qthelp==1.0.3
sphinxcontrib-serializinghtml==1.1.5
tomli==1.2.3
typing_extensions==4.1.1
urllib3==1.26.20
zipp==3.6.0
| name: nose2
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- alabaster==0.7.13
- attrs==22.2.0
- babel==2.11.0
- charset-normalizer==2.0.12
- coverage==6.2
- docutils==0.18.1
- idna==3.10
- imagesize==1.4.1
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- jinja2==3.0.3
- markupsafe==2.0.1
- mock==5.2.0
- packaging==21.3
- pluggy==1.0.0
- py==1.11.0
- pygments==2.14.0
- pyparsing==3.1.4
- pytest==7.0.1
- pytz==2025.2
- requests==2.27.1
- six==1.17.0
- snowballstemmer==2.2.0
- sphinx==5.3.0
- sphinx-rtd-theme==2.0.0
- sphinxcontrib-applehelp==1.0.2
- sphinxcontrib-devhelp==1.0.2
- sphinxcontrib-htmlhelp==2.0.0
- sphinxcontrib-jquery==4.1
- sphinxcontrib-jsmath==1.0.1
- sphinxcontrib-qthelp==1.0.3
- sphinxcontrib-serializinghtml==1.1.5
- tomli==1.2.3
- typing-extensions==4.1.1
- urllib3==1.26.20
- zipp==3.6.0
prefix: /opt/conda/envs/nose2
| [
"nose2/tests/functional/test_layers_plugin.py::TestLayers::test_layer_reporter_output"
]
| [
"nose2/tests/functional/support/scenario/layers/test_layers.py::Outer::test",
"nose2/tests/functional/support/scenario/layers/test_layers.py::InnerA::test",
"nose2/tests/functional/support/scenario/layers/test_layers.py::InnerA_1::test",
"nose2/tests/functional/support/scenario/layers/test_layers.py::InnerB_1::test",
"nose2/tests/functional/support/scenario/layers/test_layers.py::InnerC::test",
"nose2/tests/functional/support/scenario/layers/test_layers.py::InnerC::test2",
"nose2/tests/functional/support/scenario/layers/test_layers.py::InnerD::test"
]
| [
"nose2/tests/functional/support/scenario/layers/test_layers.py::NoLayer::test",
"nose2/tests/functional/test_layers_plugin.py::TestLayers::test_layer_reporter_error_output",
"nose2/tests/functional/test_layers_plugin.py::TestLayers::test_layers_and_attributes",
"nose2/tests/functional/test_layers_plugin.py::TestLayers::test_layers_and_non_layers",
"nose2/tests/functional/test_layers_plugin.py::TestLayers::test_methods_run_once_per_class",
"nose2/tests/functional/test_layers_plugin.py::TestLayers::test_runs_layer_fixtures",
"nose2/tests/functional/test_layers_plugin.py::TestLayers::test_scenario_fails_without_plugin",
"nose2/tests/functional/test_layers_plugin.py::TestLayers::test_setup_fail",
"nose2/tests/functional/test_layers_plugin.py::TestLayers::test_teardown_fail"
]
| []
| BSD | 1,886 | [
"nose2/plugins/layers.py"
]
| [
"nose2/plugins/layers.py"
]
|
joke2k__faker-652 | b0ce0cfcb9c875a394f1cec0c9f5ce3f7f7981a2 | 2017-11-13 20:15:38 | 29dff0a0f2a31edac21a18cfa50b5bc9206304b2 | diff --git a/faker/providers/address/hu_HU/__init__.py b/faker/providers/address/hu_HU/__init__.py
index e9e82b9a..4e74b61d 100644
--- a/faker/providers/address/hu_HU/__init__.py
+++ b/faker/providers/address/hu_HU/__init__.py
@@ -20,9 +20,6 @@ class Provider(AddressProvider):
city_formats = ('{{city_prefix}}{{city_part}}{{city_suffix}}', '{{city_part}}{{city_suffix}}', '{{real_city_name}}')
- street_address_with_county_formats = (
- '{{street_name}} {{building_number}}\n{{county}} megye\n{{postcode}} {{city}}',)
-
street_address_formats = ('{{street_name}} {{building_number}}',)
address_formats = ("{{street_address}}\n{{postcode}} {{city}}",)
@@ -106,8 +103,10 @@ class Provider(AddressProvider):
return self.random_element(self.counties)
def street_address_with_county(self):
- pattern = self.random_element(self.street_address_with_county_formats)
- return self.generator.parse(pattern)
+ return "{street_address}\n{county} megye\n{postcode} {city}".format(street_address=self.street_address(),
+ county=self.county(),
+ postcode=self.postcode(),
+ city=self.city().capitalize())
def city_prefix(self):
return self.random_element(self.city_prefs)
@@ -127,7 +126,7 @@ class Provider(AddressProvider):
super(Provider, self).random_digit())
def street_name(self):
- return super(Provider, self).street_name().title()
+ return super(Provider, self).street_name().capitalize()
def building_number(self):
numeric_part = super(Provider, self).random_int(1, 250)
diff --git a/faker/providers/automotive/hu_HU/__init__.py b/faker/providers/automotive/hu_HU/__init__.py
new file mode 100644
index 00000000..7bbc3fd9
--- /dev/null
+++ b/faker/providers/automotive/hu_HU/__init__.py
@@ -0,0 +1,11 @@
+# coding=utf-8
+
+
+from __future__ import unicode_literals
+from .. import Provider as AutomotiveProvider
+
+class Provider(AutomotiveProvider):
+ # from https://en.wikipedia.org/wiki/Vehicle_registration_plates_of_Hungary
+ license_formats = (
+ '???-###',
+ )
diff --git a/faker/providers/color/hu_HU/__init__.py b/faker/providers/color/hu_HU/__init__.py
new file mode 100644
index 00000000..f5c378f5
--- /dev/null
+++ b/faker/providers/color/hu_HU/__init__.py
@@ -0,0 +1,14 @@
+# coding=utf-8
+from collections import OrderedDict
+
+from faker.providers import BaseProvider
+
+
+class Provider(BaseProvider):
+
+ safe_colors = (
+ 'fekete', 'bordó', 'zöld', 'királykék', 'oliva',
+ 'bíbor', 'kékeszöld', 'citromzöld', 'kék', 'ezüst',
+ 'szürke', 'sárga', 'mályva', 'akvamarin', 'fehér',
+ )
+
diff --git a/faker/providers/company/hu_HU/__init__.py b/faker/providers/company/hu_HU/__init__.py
index 3ace97c2..879c3f21 100644
--- a/faker/providers/company/hu_HU/__init__.py
+++ b/faker/providers/company/hu_HU/__init__.py
@@ -8,17 +8,11 @@ class Provider(CompanyProvider):
formats = (
'{{last_name}} {{company_suffix}}',
'{{last_name}} {{last_name}} {{company_suffix}}',
- '{{last_name}}'
+ '{{last_name}} és {{last_name}} {{company_suffix}}',
+ '{{last_name}} és társa {{company_suffix}}'
)
- company_suffixes = (
- 'Kft',
- 'és Tsa',
- 'Kht',
- 'ZRT',
- 'NyRT',
- 'BT'
- )
+ company_suffixes = ('Kft.', 'Kht.', 'Zrt.', 'Bt.', 'Nyrt.', 'Kkt.')
def company_suffix(self):
return self.random_element(self.company_suffixes)
diff --git a/faker/providers/job/hu_HU/__init__.py b/faker/providers/job/hu_HU/__init__.py
new file mode 100644
index 00000000..3f296a95
--- /dev/null
+++ b/faker/providers/job/hu_HU/__init__.py
@@ -0,0 +1,9 @@
+# coding=utf-8
+from .. import BaseProvider
+
+class Provider(BaseProvider):
+ # Derived from KSH's FEOR'08
+ jobs = ('Titkár(nő)', 'Értékbecslő', 'Közterület-felügyelő', 'Építőmérnök', 'Köszörűs', 'Gépjármű- és motorkarbantartó', 'Mezőgazdasági mérnök', 'Számítógéphálózat- és rendszertechnikus', 'Adósságbehajtó', 'Fémöntőminta-készítő', 'Gyümölcs- és zöldségfeldolgozó', 'Telekommunikációs mérnök', 'Könyv- és lapkiadó szerkesztője', 'Geológus', 'Manikűrös', 'Energetikus', 'Kézbesítő', 'Kontroller', 'Mentőtiszt', 'Háztartási takarító és kisegítő', 'Dekoratőr', 'Tejfeldolgozó', 'Gyógytornász', 'Csomagkihordó', 'Kádár', 'Színész', 'Anyaggazdálkodó', 'Szoftverfejlesztő', 'Adó- és illetékhivatali ügyintéző', 'Utaskísérő', 'Táj- és kertépítészmérnök', 'Muzeológus', 'Koreográfus', 'Tetőfedő', 'Telepőr', 'Pedikűrös', 'Fémfeldolgozó', 'Intézményi takarító és kisegítő', 'Irodai szakmai irányító', 'Recepciós', 'Gépíró, szövegszerkesztő', 'Ifjúságsegítő', 'Pap', 'Adatbázis- és hálózati elemző', 'Szoftver- és alkalmazásfejlesztő', 'Burkoló', 'Történész', 'Intézményi takarító és kisegítő ', 'Kohó- és anyagtechnikus', 'Jogi asszisztens', 'Tőzsde- és pénzügyi ügynök', 'Varró', 'Bolti pénztáros', 'Kémikus', 'Kőműves', 'Szakorvos', 'Elemző közgazdász', 'Kézi mosó, vasaló', 'Irattáros', 'Földmérő és térinformatikus', 'Vendéglős', 'Élelmiszer-ipari mérnök', 'Kisállattartó és -tenyésztő', 'Szociológus', 'Lakatos', 'Pszichológus', 'Utcaseprő', 'Adatbázis-tervező és -üzemeltető', 'Gyermekfelügyelő', 'Metróvezető', 'Háztartási alkalmazott', 'Könyvelő', 'Általános irodai adminisztrátor', 'Épületasztalos', 'Ékszerkészítő', 'Üvegező', 'Könyvtári, levéltári nyilvántartó', 'Általános iskolai tanár, tanító', 'Szemétgyűjtő', 'Rendőr', 'Orvosi laboratóriumi asszisztens', 'Kubikos', 'Adatrögzítő', 'Informatikatanár', 'Fizikus', 'Vegyésztechnikus', 'Hímző', 'Ügynök', 'Kalapos', 'Egyéb művészetek tanára', 'Zöldségtermesztő', 'Dísznövény-, virág- és faiskolai kertész, csemetenevelő', 'Csipkeverő', 'Postai ügyfélkapcsolati foglalkozású', 'Tolmács', 'Kódoló', 'Fa- és könnyűipari mérnök', 'Szarvasmarha-, ló-, sertés-, juhtartó és -tenyésztő ', 'Település- és közlekedéstervező mérnök', 'Rendszergazda', 'Állatorvosi asszisztens', 'Újságíró', 'Piaci, utcai étel- és italárus', 'Néprajzkutató', 'Vám- és pénzügyőr', 'Hordár', 'Webrendszer-technikus', 'Hivatalsegéd', 'Üzletpolitikai elemző', 'Fogorvos', 'Statisztikus', 'Stukkózó', 'Utazásszervező', 'Épületbádogos', 'Szociális gondozó', 'Villamosipari technikus (elektronikai technikus)', 'Iratkezelő', 'Matróz', 'Trolibuszvezető', 'Banki pénztáros', 'Szikvízkészítő', 'Kovács', 'Minőségbiztosítási mérnök', 'Csillagász', 'Író', 'Könyvtáros', 'Fényképész', 'Bányászati technikus', 'Üzletpolitikai elemző, szervező', 'Jelnyelvi tolmács', 'Alkalmazásprogramozó', 'Cipőkészítő', 'Drágakőcsiszoló', 'Botanikus', 'Járműtakarító', 'Biztosítási ügynök', 'Gépészmérnök', 'Légiforgalmi irányító', 'Üveggyártó', 'Gumitermékgyártó', 'Repülőgépmotor-karbantartó', 'Építészmérnök', 'Tűzoltó', 'Könyvkötő', 'Pultos', 'Borász', 'Gyógyszerész', 'Kozmetikus', 'Segédápoló', 'Ápoló', 'Fordító', 'Munkavédelmi és üzembiztonsági foglalkozású', 'Végrehajtó, adósságbehajtó', 'Gyógyszertári asszisztens', 'Szőrmefestő', 'Bőrtermékkészítő', 'Műsorszóró és audiovizuális technikus', 'Kártevőirtó', 'Rakodómunkás', 'Szabásminta-készítő', 'Hulladékosztályozó', 'Erdő- és természetvédelmi mérnök', 'Készlet- és anyagnyilvántartó', 'Fogászati asszisztens', 'Séf', 'Könyvszakértő', 'Bróker', 'Áru- és divatbemutató', 'Kölcsönző', 'Épületgondnok', 'Telekommunikációs technikus', 'Környezetvédelmi technikus', 'Házvezető', 'Famegmunkáló', 'Szállodai recepciós', 'Kézi csomagoló', 'Ötvös', 'Csecsemő- és kisgyermeknevelő', 'Kerékpár-karbantartó', 'Operatőr', 'Ügyvéd', 'Szigetelő', 'Fizioterápiás asszisztens', 'Kereskedő', 'Biológus', 'Ruházati gép kezelője és gyártósor mellett dolgozó', 'Szűcs', 'Ügyféltájékoztató', 'Gyógynövénytermesztő', 'Lelkész', 'Énekes', 'Munka- és termelésszervező ', 'Légiforgalmi irányítástechnikus', 'Számítógép-hálózati elemző', 'Szabó', 'Szakács', 'Növényorvos ', 'Testőr', 'Erdő- és természetvédelmi technikus', 'Kőfaragó', 'Bányászati szakmai irányító', 'Régész', 'Lakossági kérdező', 'Számviteli ügyintéző', 'Természetvédelmi őr', 'Egyetemi, főiskolai oktató', 'Óvodapedagógus', 'Gyomírtó', 'Növényvédelmi szakértő', 'Védőnő', 'Egészségügyi dokumentátor ', 'Finommechanikai műszerész', 'Műszaki rajzoló', 'Demográfus', 'Általános orvos', 'Fedélzeti tiszt', 'Vagyonőr', 'Rendszerelemző', 'Tímár', 'Hajózómérnök', 'Hálózat- és multimédia-fejlesztő', 'Konyhai kisegítő', 'Mozigépész', 'Épületvillamossági szerelő', 'Bionövény-termesztő', 'Fogtechnikus', 'Büntetés-végrehajtási őr', 'Erdész', 'Vízgazdálkodási gépkezelő', 'Szerszámkészítő', 'Vegyészmérnök', 'Festő', 'Iratkezelő, irattáros', 'Légiforgalmi irányítástechnikai berendezések üzemeltetője', 'Masszőr', 'Zenetanár', 'Zálogházi ügyintéző és pénzkölcsönző', 'Jogtanácsos', 'Tehergépkocsi-vezető', 'Bolti eladó', 'Pénzintézeti ügyintéző', 'Növényorvosi asszisztens', 'Fitnesz- és rekreációs program irányítója', 'Zeneszerző', 'Építményszerkezet-szerelő', 'Vegyes profilú gazdálkodó', 'Pultfeltöltő', 'Képzőművész', 'Végrehajtó', 'Szerencsejáték-szervező', 'Jegypénztáros', 'Konyhafőnök', 'Műtőssegéd', 'Adótanácsadó', 'Jogász', 'Orvosi képalkotó diagnosztikai asszisztens', 'Zoológus', 'Látszerész', 'Szállítási, szállítmányozási nyilvántartó', 'Kárpitos', 'Házi gondozó', 'Táncművész', 'Cipész', 'Élelmiszer-ipari technikus', 'Zenész', 'Könyvelő (analitikus)', 'Felvásárló', 'Személyzeti és pályaválasztási szakértő', 'Bányamérnök', 'Pincér', 'Mosodai gép kezelője', 'Dietetikus', 'Rendező', 'Bognár', 'Targoncavezető', 'Hobbiállat-gondozó', 'Segédrendező', 'Marketing- és PR-ügyintéző', 'Bőrdíszműves', 'Darukezelő', 'Hallás- és beszédterapeuta', 'Konduktor', 'Villamosmérnök (energetikai mérnök)', 'Meteorológus', 'Táplálkozási tanácsadó', 'Cirkuszi előadóművész', 'Húsfeldolgozó', 'Vezető eladó', 'Könyvvizsgáló', 'Feldolgozóipari szakmai irányító', 'Pedagógiai szakértő', 'Telefonos értékesítési ügynök', 'Villamosvezető', 'Baromfitartó és -tenyésztő', 'Politológus', 'Mérőóra-leolvasó', 'Egyéb növénytermesztési foglalkozású', 'Méhész', 'Felvonószerelő', 'Személygépkocsi-vezető', 'Textilműves', 'Építő- és építésztechnikus', 'Bőröndös', 'Gipszkartonozó', 'Kalauz', 'Járművezető-oktató', 'Bérelszámoló', 'Bútorasztalos', 'Villanyszerelő', 'Kesztyűs', 'Nyomdai előkészítő', 'Mezőgazdasági technikus', 'Szőlő-, gyümölcstermesztő', 'Oktatási asszisztens', 'Édesiparitermék-gyártó', 'Fodrász', 'Nyomdász', 'Keramikus', 'Általános egészségügyi asszisztens', 'Ács', 'Kereskedelmi ügyintéző', 'Környezetfelmérő', 'Kéményseprő', 'Fotó- és mozgófilmlaboráns', 'Statisztikai ügyintéző', 'Szakképzett edző', 'Fa- és könnyűipari technikus', 'Múzeumi gyűjteménygondnok', 'Árufeltöltő', 'Idegenvezető', 'Mozdonyvezető', 'Kohó- és anyagmérnök', 'Műköves', 'Állatorvos', 'Földmérő és térinformatikai technikus ', 'Nyelvtanár', 'Ügyész', 'Sportoló', 'Címfestő', 'Nyelvész', 'Gyógypedagógus', 'Üzemanyagtöltő állomás kezelője', 'Fémcsiszoló', 'Kulturális szervező', 'Lakberendező', 'Grafikus és multimédia-tervező ', 'Középiskolai tanár', 'Cukrász', 'Légijármű-vezető', 'Sportszervező', 'Parkolóőr', 'Favágó', 'Matematikus', 'Pénzügyi elemző és befektetési tanácsadó', 'Konferencia- és rendezvényszervező', 'Faesztergályos', 'Kályha- és kandallóépítő', 'Közjegyző', 'Festékszóró', 'Statiszta', 'Minőségbiztosítási technikus', 'Épületszerkezet-tisztító', 'Menetjegyellenőr', 'Kereskedelmi tervező ', 'Munkaerő-piaci szolgáltatási ügyintéző', 'Adószakértő', 'Hegesztő', 'Gyorséttermi eladó', 'Iparművész', 'Díszítő', 'Szociálpolitikus', 'Gyártmány- és ruhatervező', 'Ingatlanforgalmazási ügyintéző', 'Kormányos', 'Díszletező', 'Segédszínész', 'Levéltáros', 'Robbantómester', 'Villamosipari technikus (energetikai technikus)', 'Ortopédiai eszközkészítő', 'Gépésztechnikus', 'Szociális segítő', 'Pék', 'Ipari alpinista', 'Villamosmérnök (elektronikai mérnök)', 'Személyi asszisztens', 'Ablaktisztító', 'Portás', 'Filozófus', 'Forgácsoló', 'Bábművész', 'Kárszakértő', 'Humánpolitikai adminisztrátor', 'Hangszerkészítő', 'Társadalombiztosítási és segélyezési hatósági ügyintéző', 'Optometrista', 'Szántóföldinövény-termesztő', 'Ingatlanügynök', 'Nyomozó', 'Egyéb, máshova nem sorolható technikus', 'Vezető takarító', 'Autóbuszvezető', 'Kárbecslő', 'Piaci árus', 'Bíró', 'Általános iskolai tanár', 'Szerszámköszörűs', 'Építőipari szakmai irányító')
+
+ def job(self):
+ return self.random_element(self.jobs)
| Summary ticket for ``hu_HU`` provider
Summary ticket for issues with the ``hu_HU`` provider (I'm working on a PR to fix these).
- [x] ``providers.address.street_name`` (and descendants): incorrectly capitalises street/place/etc.
- [x] ``providers.address.street_address_with_county``: does not capitalise place name
- [x] ``providers.automotive.license_plate``: seems to be the UK licence plate structure, the correct Hungarian licence plate regex is ``\d{3}-[A-Z]{3}``
- [x] ``provides.company.company_suffix``: misspellings and miscapitalizations (e.g. ``Zrt.`` as ``ZRT``
- [x] ``providers.job``: this could be replaced with a professions list from KSH
| joke2k/faker | diff --git a/tests/providers/test_address.py b/tests/providers/test_address.py
index af0aaf46..f7dd5b71 100644
--- a/tests/providers/test_address.py
+++ b/tests/providers/test_address.py
@@ -221,7 +221,43 @@ class TestHuHU(unittest.TestCase):
assert pcd[2] > "0"
def test_street_address(self):
- """ Tests the street address in the hu_HU locale """
+ """Tests street address. A street address must consist of a street name, a place type and a number, and end in a period point."""
+ address = self.factory.street_address()
+ assert address[-1] == '.'
+ # Check for correct capitalisation of place type
+ assert address.split(" ")[-2][0].islower()
+ # Check for street number format
+ assert re.match(r"\d{1,4}\.", address.split(" ")[-1])
+
+ def test_street_address_with_county(self):
+ """Tests street address with country. A street address must be:
+ - in three rows,
+ - starting with a valid street address,
+ - contain a valid post code,
+ - contain the place name validly capitalized.
+ """
+ address = self.factory.street_address_with_county()
+ # Number of rows
+ assert len(address.split("\n")) == 3
+ first, second, last = address.split("\n")
+
+ # Test street address
+ assert first[0].isupper()
+ assert first.split(" ")[-2][0].islower()
+ assert re.match(r"\d{1,4}\.", first.split(" ")[-1])
+
+ # Test county line
+ assert second.split(" ")[-1][0].islower()
+ assert second.split(" ")[0][0].isupper()
+
+ # Test postcode
+ assert re.match(r"H-[1-9]\d{3}", last.split(" ")[0])
+
+ # Test place name capitalization
+ assert last.split(" ")[-1][0].isupper()
+
+ def test_address(self):
+ """ Tests the address provider in the hu_HU locale """
address = self.factory.address()
assert isinstance(address, string_types)
address_with_county = self.factory.street_address_with_county()
diff --git a/tests/providers/test_automotive.py b/tests/providers/test_automotive.py
index 9f2984d4..ddabaa2b 100644
--- a/tests/providers/test_automotive.py
+++ b/tests/providers/test_automotive.py
@@ -18,3 +18,13 @@ class TestPtBR(unittest.TestCase):
plate = self.factory.license_plate()
assert isinstance(plate, string_types)
assert self.format.match(plate)
+
+class TestHuHU(unittest.TestCase):
+
+ def setUp(self):
+ self.factory = Faker('hu_HU')
+
+ def test_hu_HU_plate_format(self):
+ plate = self.factory.license_plate()
+
+ assert re.match("[A-Z]{3}-\d{3}", plate)
diff --git a/tests/providers/test_company.py b/tests/providers/test_company.py
index c7146ede..495b0498 100644
--- a/tests/providers/test_company.py
+++ b/tests/providers/test_company.py
@@ -59,16 +59,23 @@ class TestHuHU(unittest.TestCase):
def setUp(self):
self.factory = Faker('hu_HU')
+ self.valid_suffixes = ('Kft.',
+ 'Kht.',
+ 'Zrt.',
+ 'Bt.',
+ 'Nyrt.',
+ 'Kkt.')
+
def test_company_suffix(self):
- suffixes = HuProvider.company_suffixes
suffix = self.factory.company_suffix()
assert isinstance(suffix, string_types)
- assert suffix in suffixes
+ assert suffix in self.valid_suffixes
def test_company(self):
company = self.factory.company()
assert isinstance(company, string_types)
+ assert company.split(" ")[-1] in self.valid_suffixes
class TestPlPL(unittest.TestCase):
diff --git a/tests/providers/test_internet.py b/tests/providers/test_internet.py
index 3e3094e8..555e7975 100644
--- a/tests/providers/test_internet.py
+++ b/tests/providers/test_internet.py
@@ -65,7 +65,7 @@ class TestHuHU(unittest.TestCase):
""" Tests internet module in the hu_HU locale. """
def setUp(self):
- self.factory = Faker('hu')
+ self.factory = Faker('hu_HU')
def test_internet(self):
domain_name = self.factory.domain_name()
diff --git a/tests/providers/test_job.py b/tests/providers/test_job.py
index 4b0f88a8..a6cb19c5 100644
--- a/tests/providers/test_job.py
+++ b/tests/providers/test_job.py
@@ -9,6 +9,7 @@ from faker import Faker
from tests import string_types
+
class TestJob(unittest.TestCase):
"""
Test Job
@@ -33,3 +34,13 @@ class TestKoKR(unittest.TestCase):
def test_job(self):
job = self.factory.job()
assert isinstance(job, string_types)
+
+class TestHuHU(unittest.TestCase):
+ "Tests the job module in the Hungarian locale."
+
+ def setUp(self):
+ self.factory = Faker('hu_HU')
+
+ def test_job(self):
+ job = self.factory.job()
+ assert isinstance(job, string_types)
diff --git a/tests/providers/test_phone_number.py b/tests/providers/test_phone_number.py
index d1b8dd61..ed4c22c9 100644
--- a/tests/providers/test_phone_number.py
+++ b/tests/providers/test_phone_number.py
@@ -2,6 +2,7 @@
from __future__ import unicode_literals
+import re
import unittest
from faker import Faker
@@ -61,3 +62,12 @@ class TestPhoneNumber(unittest.TestCase):
assert len(msisdn) == 13
assert msisdn.isdigit()
assert msisdn[0:4] in formats
+
+class TestHuHU(unittest.TestCase):
+
+ def setUp(self):
+ self.factory = Faker('hu_HU')
+
+ def test_phone_number(self):
+ phone_number = self.factory.phone_number()
+ re.match(r"[1-9]\d/\d{3} \d{4}", phone_number)
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 1,
"test_score": 3
},
"num_modified_files": 2
} | 0.8 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-cov",
"pytest-xdist",
"pytest-mock",
"pytest-asyncio"
],
"pre_install": [],
"python": "3.6",
"reqs_path": [
"tests/requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs==22.2.0
certifi==2021.5.30
coverage==6.2
dnspython==2.2.1
email-validator==1.0.3
execnet==1.9.0
-e git+https://github.com/joke2k/faker.git@b0ce0cfcb9c875a394f1cec0c9f5ce3f7f7981a2#egg=Faker
idna==3.10
importlib-metadata==4.8.3
iniconfig==1.1.1
mock==2.0.0
packaging==21.3
pbr==6.1.1
pluggy==1.0.0
py==1.11.0
pyparsing==3.1.4
pytest==7.0.1
pytest-asyncio==0.16.0
pytest-cov==4.0.0
pytest-mock==3.6.1
pytest-xdist==3.0.2
python-dateutil==2.9.0.post0
six==1.17.0
text-unidecode==1.3
tomli==1.2.3
typing_extensions==4.1.1
UkPostcodeParser==1.1.2
zipp==3.6.0
| name: faker
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- attrs==22.2.0
- coverage==6.2
- dnspython==2.2.1
- email-validator==1.0.3
- execnet==1.9.0
- idna==3.10
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- mock==2.0.0
- packaging==21.3
- pbr==6.1.1
- pluggy==1.0.0
- py==1.11.0
- pyparsing==3.1.4
- pytest==7.0.1
- pytest-asyncio==0.16.0
- pytest-cov==4.0.0
- pytest-mock==3.6.1
- pytest-xdist==3.0.2
- python-dateutil==2.9.0.post0
- six==1.17.0
- text-unidecode==1.3
- tomli==1.2.3
- typing-extensions==4.1.1
- ukpostcodeparser==1.1.2
- zipp==3.6.0
prefix: /opt/conda/envs/faker
| [
"tests/providers/test_address.py::TestHuHU::test_street_address",
"tests/providers/test_address.py::TestHuHU::test_street_address_with_county",
"tests/providers/test_automotive.py::TestHuHU::test_hu_HU_plate_format",
"tests/providers/test_company.py::TestHuHU::test_company",
"tests/providers/test_company.py::TestHuHU::test_company_suffix"
]
| []
| [
"tests/providers/test_address.py::TestDeDE::test_city",
"tests/providers/test_address.py::TestDeDE::test_country",
"tests/providers/test_address.py::TestDeDE::test_state",
"tests/providers/test_address.py::TestDeDE::test_street_suffix_long",
"tests/providers/test_address.py::TestDeDE::test_street_suffix_short",
"tests/providers/test_address.py::TestElGR::test_city",
"tests/providers/test_address.py::TestElGR::test_latlng",
"tests/providers/test_address.py::TestElGR::test_line_address",
"tests/providers/test_address.py::TestElGR::test_region",
"tests/providers/test_address.py::TestEnAU::test_city_prefix",
"tests/providers/test_address.py::TestEnAU::test_postcode",
"tests/providers/test_address.py::TestEnAU::test_state",
"tests/providers/test_address.py::TestEnAU::test_state_abbr",
"tests/providers/test_address.py::TestEnCA::test_city_prefix",
"tests/providers/test_address.py::TestEnCA::test_postal_code_letter",
"tests/providers/test_address.py::TestEnCA::test_postalcode",
"tests/providers/test_address.py::TestEnCA::test_province",
"tests/providers/test_address.py::TestEnCA::test_province_abbr",
"tests/providers/test_address.py::TestEnCA::test_secondary_address",
"tests/providers/test_address.py::TestEnGB::test_postcode",
"tests/providers/test_address.py::TestEnUS::test_city_prefix",
"tests/providers/test_address.py::TestEnUS::test_military_apo",
"tests/providers/test_address.py::TestEnUS::test_military_dpo",
"tests/providers/test_address.py::TestEnUS::test_military_ship",
"tests/providers/test_address.py::TestEnUS::test_military_state",
"tests/providers/test_address.py::TestEnUS::test_state",
"tests/providers/test_address.py::TestEnUS::test_state_abbr",
"tests/providers/test_address.py::TestEnUS::test_zipcode",
"tests/providers/test_address.py::TestEnUS::test_zipcode_plus4",
"tests/providers/test_address.py::TestHuHU::test_address",
"tests/providers/test_address.py::TestHuHU::test_postcode_first_digit",
"tests/providers/test_address.py::TestJaJP::test_address",
"tests/providers/test_address.py::TestNeNP::test_address",
"tests/providers/test_address.py::TestNoNO::test_address",
"tests/providers/test_address.py::TestNoNO::test_city_suffix",
"tests/providers/test_address.py::TestNoNO::test_postcode",
"tests/providers/test_address.py::TestNoNO::test_street_suffix",
"tests/providers/test_address.py::TestZhTW::test_address",
"tests/providers/test_address.py::TestZhCN::test_address",
"tests/providers/test_address.py::TestPtBr::test_address",
"tests/providers/test_automotive.py::TestPtBR::test_plate_has_been_generated",
"tests/providers/test_company.py::TestJaJP::test_company",
"tests/providers/test_company.py::TestPtBR::test_pt_BR_cnpj",
"tests/providers/test_company.py::TestPtBR::test_pt_BR_company_id",
"tests/providers/test_company.py::TestPtBR::test_pt_BR_company_id_checksum",
"tests/providers/test_company.py::TestPlPL::test_company_vat",
"tests/providers/test_company.py::TestPlPL::test_company_vat_checksum",
"tests/providers/test_company.py::TestPlPL::test_local_regon",
"tests/providers/test_company.py::TestPlPL::test_local_regon_checksum",
"tests/providers/test_company.py::TestPlPL::test_regon",
"tests/providers/test_company.py::TestPlPL::test_regon_checksum",
"tests/providers/test_internet.py::TestJaJP::test_internet",
"tests/providers/test_internet.py::TestZhCN::test_email",
"tests/providers/test_internet.py::TestZhTW::test_email",
"tests/providers/test_internet.py::TestHuHU::test_internet",
"tests/providers/test_internet.py::TestPlPL::test_free_email_domain",
"tests/providers/test_internet.py::TestPlPL::test_tld",
"tests/providers/test_internet.py::TestNlNl::test_ascii_company_email",
"tests/providers/test_internet.py::TestNlNl::test_ascii_free_email",
"tests/providers/test_internet.py::TestNlNl::test_ascii_safe_email",
"tests/providers/test_internet.py::TestArAa::test_ascii_company_email",
"tests/providers/test_internet.py::TestArAa::test_ascii_free_email",
"tests/providers/test_internet.py::TestArAa::test_ascii_safe_email",
"tests/providers/test_job.py::TestJob::test_job",
"tests/providers/test_job.py::TestKoKR::test_job",
"tests/providers/test_job.py::TestHuHU::test_job",
"tests/providers/test_phone_number.py::TestPhoneNumber::test_msisdn",
"tests/providers/test_phone_number.py::TestPhoneNumber::test_msisdn_pt_br",
"tests/providers/test_phone_number.py::TestPhoneNumber::test_phone_number",
"tests/providers/test_phone_number.py::TestPhoneNumber::test_phone_number_ja",
"tests/providers/test_phone_number.py::TestHuHU::test_phone_number"
]
| []
| MIT License | 1,887 | [
"faker/providers/automotive/hu_HU/__init__.py",
"faker/providers/color/hu_HU/__init__.py",
"faker/providers/address/hu_HU/__init__.py",
"faker/providers/company/hu_HU/__init__.py",
"faker/providers/job/hu_HU/__init__.py"
]
| [
"faker/providers/automotive/hu_HU/__init__.py",
"faker/providers/color/hu_HU/__init__.py",
"faker/providers/address/hu_HU/__init__.py",
"faker/providers/company/hu_HU/__init__.py",
"faker/providers/job/hu_HU/__init__.py"
]
|
|
ucfopen__canvasapi-107 | d05071ddc2e4a37ebd49d162f4f080757befeb4c | 2017-11-13 21:24:00 | db3c377b68f2953e1618f4e4588cc2db8603841e | diff --git a/canvasapi/requester.py b/canvasapi/requester.py
index eff4b3a..c017a42 100644
--- a/canvasapi/requester.py
+++ b/canvasapi/requester.py
@@ -24,6 +24,7 @@ class Requester(object):
self.base_url = base_url
self.access_token = access_token
self._session = requests.Session()
+ self._cache = []
def request(
self, method, endpoint=None, headers=None, use_auth=True,
@@ -84,6 +85,12 @@ class Requester(object):
# Call the request method
response = req_method(full_url, headers, _kwargs)
+ # Add response to internal cache
+ if len(self._cache) > 4:
+ self._cache.pop()
+
+ self._cache.insert(0, response)
+
# Raise for status codes
if response.status_code == 400:
raise BadRequest(response.json())
| Add a Requester cache for debugging
We should add a cache of requests and responses onto `Requester` to make debugging easier.
This could be as simple as a tuple recording the last request that was sent and the last response received, or we could save several requests and responses. | ucfopen/canvasapi | diff --git a/tests/test_requester.py b/tests/test_requester.py
index d65f2d4..fb582a7 100644
--- a/tests/test_requester.py
+++ b/tests/test_requester.py
@@ -77,6 +77,23 @@ class TestRequester(unittest.TestCase):
response = self.requester.request('PUT', 'fake_put_request')
self.assertEqual(response.status_code, 200)
+ def test_request_cache(self, m):
+ register_uris({'requests': ['get']}, m)
+
+ response = self.requester.request('GET', 'fake_get_request')
+ self.assertEqual(response, self.requester._cache[0])
+
+ def test_request_cache_clear_after_5(self, m):
+ register_uris({'requests': ['get', 'post']}, m)
+
+ for i in range(5):
+ self.requester.request('GET', 'fake_get_request')
+
+ response = self.requester.request('POST', 'fake_post_request')
+
+ self.assertLessEqual(len(self.requester._cache), 5)
+ self.assertEqual(response, self.requester._cache[0])
+
def test_request_400(self, m):
register_uris({'requests': ['400']}, m)
| {
"commit_name": "head_commit",
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 2,
"test_score": 1
},
"num_modified_files": 1
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"flake8",
"pycodestyle",
"requests_mock"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | -e git+https://github.com/ucfopen/canvasapi.git@d05071ddc2e4a37ebd49d162f4f080757befeb4c#egg=canvasapi
certifi==2025.1.31
charset-normalizer==3.4.1
exceptiongroup==1.2.2
flake8==7.2.0
idna==3.10
iniconfig==2.1.0
mccabe==0.7.0
packaging==24.2
pluggy==1.5.0
pycodestyle==2.13.0
pyflakes==3.3.1
pytest==8.3.5
pytz==2025.2
requests==2.32.3
requests-mock==1.12.1
six==1.17.0
tomli==2.2.1
urllib3==2.3.0
| name: canvasapi
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- certifi==2025.1.31
- charset-normalizer==3.4.1
- exceptiongroup==1.2.2
- flake8==7.2.0
- idna==3.10
- iniconfig==2.1.0
- mccabe==0.7.0
- packaging==24.2
- pluggy==1.5.0
- pycodestyle==2.13.0
- pyflakes==3.3.1
- pytest==8.3.5
- pytz==2025.2
- requests==2.32.3
- requests-mock==1.12.1
- six==1.17.0
- tomli==2.2.1
- urllib3==2.3.0
prefix: /opt/conda/envs/canvasapi
| [
"tests/test_requester.py::TestRequester::test_request_cache",
"tests/test_requester.py::TestRequester::test_request_cache_clear_after_5"
]
| []
| [
"tests/test_requester.py::TestRequester::test_request_400",
"tests/test_requester.py::TestRequester::test_request_401_InvalidAccessToken",
"tests/test_requester.py::TestRequester::test_request_401_Unauthorized",
"tests/test_requester.py::TestRequester::test_request_404",
"tests/test_requester.py::TestRequester::test_request_500",
"tests/test_requester.py::TestRequester::test_request_delete",
"tests/test_requester.py::TestRequester::test_request_get",
"tests/test_requester.py::TestRequester::test_request_get_datetime",
"tests/test_requester.py::TestRequester::test_request_post",
"tests/test_requester.py::TestRequester::test_request_post_datetime",
"tests/test_requester.py::TestRequester::test_request_put"
]
| []
| MIT License | 1,888 | [
"canvasapi/requester.py"
]
| [
"canvasapi/requester.py"
]
|
|
ucfopen__canvasapi-110 | f24904ff3e8275ba1f134692b1e7cc08e6972eda | 2017-11-13 23:02:39 | db3c377b68f2953e1618f4e4588cc2db8603841e | diff --git a/canvasapi/canvas.py b/canvasapi/canvas.py
index 0e3f030..687649c 100644
--- a/canvasapi/canvas.py
+++ b/canvasapi/canvas.py
@@ -164,8 +164,9 @@ class Canvas(object):
:rtype: :class:`canvasapi.user.User`
"""
if id_type:
- user_id = user
- uri = 'users/{}:{}'.format(id_type, user_id)
+ uri = 'users/{}:{}'.format(id_type, user)
+ elif user == 'self':
+ uri = 'users/self'
else:
user_id = obj_or_id(user, "user", (User,))
uri = 'users/{}'.format(user_id)
| Canvas.get_user() no longer accepts 'self' argument
_(Note: this issue only affects the current version of `develop`)_
Previously, it was possible to pass `'self'` as an argument to `Canvas.get_user()` (`canvas.get_user('self')`) instead of an ID.
Somewhere along the line (likely in the wider adoption of `obj_or_id`, #96), this functionality was broken.
Restore this functionality and add a test explicitly testing `'self'` to prevent future regressions.
When #108 is finished, we may ultimately remove this behavior but at that time there will be an adequate replacement for the functionality. | ucfopen/canvasapi | diff --git a/tests/fixtures/user.json b/tests/fixtures/user.json
index bc71d63..2aa9773 100644
--- a/tests/fixtures/user.json
+++ b/tests/fixtures/user.json
@@ -226,6 +226,14 @@
"name": "John Doe"
}
},
+ "get_by_id_self": {
+ "method": "GET",
+ "endpoint": "users/self",
+ "data": {
+ "id": 1,
+ "name": "John Doe"
+ }
+ },
"get_file": {
"method": "GET",
"endpoint": "users/1/files/1",
diff --git a/tests/test_canvas.py b/tests/test_canvas.py
index e8331ab..dc5ec34 100644
--- a/tests/test_canvas.py
+++ b/tests/test_canvas.py
@@ -149,6 +149,14 @@ class TestCanvas(unittest.TestCase):
self.assertIsInstance(user, User)
self.assertTrue(hasattr(user, 'name'))
+ def test_get_user_self(self, m):
+ register_uris({'user': ['get_by_id_self']}, m)
+
+ user = self.canvas.get_user('self')
+
+ self.assertIsInstance(user, User)
+ self.assertTrue(hasattr(user, 'name'))
+
def test_get_user_fail(self, m):
register_uris({'generic': ['not_found']}, m)
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_issue_reference"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 0,
"test_score": 0
},
"num_modified_files": 1
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-cov",
"pytest-xdist",
"pytest-mock",
"pytest-asyncio"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.6",
"reqs_path": [
"requirements.txt",
"dev_requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | alabaster==0.7.13
attrs==22.2.0
Babel==2.11.0
-e git+https://github.com/ucfopen/canvasapi.git@f24904ff3e8275ba1f134692b1e7cc08e6972eda#egg=canvasapi
certifi==2021.5.30
charset-normalizer==2.0.12
coverage==6.2
docutils==0.17.1
execnet==1.9.0
flake8==5.0.4
idna==3.10
imagesize==1.4.1
importlib-metadata==4.2.0
iniconfig==1.1.1
Jinja2==3.0.3
MarkupSafe==2.0.1
mccabe==0.7.0
packaging==21.3
pluggy==1.0.0
py==1.11.0
pycodestyle==2.9.1
pyflakes==2.5.0
Pygments==2.14.0
pyparsing==3.1.4
pytest==7.0.1
pytest-asyncio==0.16.0
pytest-cov==4.0.0
pytest-mock==3.6.1
pytest-xdist==3.0.2
pytz==2025.2
requests==2.27.1
requests-mock==1.12.1
six==1.17.0
snowballstemmer==2.2.0
Sphinx==4.3.2
sphinx-rtd-theme==1.3.0
sphinxcontrib-applehelp==1.0.2
sphinxcontrib-devhelp==1.0.2
sphinxcontrib-htmlhelp==2.0.0
sphinxcontrib-jquery==4.1
sphinxcontrib-jsmath==1.0.1
sphinxcontrib-qthelp==1.0.3
sphinxcontrib-serializinghtml==1.1.5
tomli==1.2.3
typing_extensions==4.1.1
urllib3==1.26.20
zipp==3.6.0
| name: canvasapi
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- alabaster==0.7.13
- attrs==22.2.0
- babel==2.11.0
- charset-normalizer==2.0.12
- coverage==6.2
- docutils==0.17.1
- execnet==1.9.0
- flake8==5.0.4
- idna==3.10
- imagesize==1.4.1
- importlib-metadata==4.2.0
- iniconfig==1.1.1
- jinja2==3.0.3
- markupsafe==2.0.1
- mccabe==0.7.0
- packaging==21.3
- pluggy==1.0.0
- py==1.11.0
- pycodestyle==2.9.1
- pyflakes==2.5.0
- pygments==2.14.0
- pyparsing==3.1.4
- pytest==7.0.1
- pytest-asyncio==0.16.0
- pytest-cov==4.0.0
- pytest-mock==3.6.1
- pytest-xdist==3.0.2
- pytz==2025.2
- requests==2.27.1
- requests-mock==1.12.1
- six==1.17.0
- snowballstemmer==2.2.0
- sphinx==4.3.2
- sphinx-rtd-theme==1.3.0
- sphinxcontrib-applehelp==1.0.2
- sphinxcontrib-devhelp==1.0.2
- sphinxcontrib-htmlhelp==2.0.0
- sphinxcontrib-jquery==4.1
- sphinxcontrib-jsmath==1.0.1
- sphinxcontrib-qthelp==1.0.3
- sphinxcontrib-serializinghtml==1.1.5
- tomli==1.2.3
- typing-extensions==4.1.1
- urllib3==1.26.20
- zipp==3.6.0
prefix: /opt/conda/envs/canvasapi
| [
"tests/test_canvas.py::TestCanvas::test_get_user_self"
]
| []
| [
"tests/test_canvas.py::TestCanvas::test_clear_course_nicknames",
"tests/test_canvas.py::TestCanvas::test_conversations_batch_update",
"tests/test_canvas.py::TestCanvas::test_conversations_batch_updated_fail_on_event",
"tests/test_canvas.py::TestCanvas::test_conversations_batch_updated_fail_on_ids",
"tests/test_canvas.py::TestCanvas::test_conversations_get_running_batches",
"tests/test_canvas.py::TestCanvas::test_conversations_mark_all_as_read",
"tests/test_canvas.py::TestCanvas::test_conversations_unread_count",
"tests/test_canvas.py::TestCanvas::test_create_account",
"tests/test_canvas.py::TestCanvas::test_create_appointment_group",
"tests/test_canvas.py::TestCanvas::test_create_appointment_group_fail_on_context_codes",
"tests/test_canvas.py::TestCanvas::test_create_appointment_group_fail_on_title",
"tests/test_canvas.py::TestCanvas::test_create_calendar_event",
"tests/test_canvas.py::TestCanvas::test_create_calendar_event_fail",
"tests/test_canvas.py::TestCanvas::test_create_conversation",
"tests/test_canvas.py::TestCanvas::test_create_group",
"tests/test_canvas.py::TestCanvas::test_get_account",
"tests/test_canvas.py::TestCanvas::test_get_account_fail",
"tests/test_canvas.py::TestCanvas::test_get_account_sis_id",
"tests/test_canvas.py::TestCanvas::test_get_accounts",
"tests/test_canvas.py::TestCanvas::test_get_activity_stream_summary",
"tests/test_canvas.py::TestCanvas::test_get_appointment_group",
"tests/test_canvas.py::TestCanvas::test_get_calendar_event",
"tests/test_canvas.py::TestCanvas::test_get_conversation",
"tests/test_canvas.py::TestCanvas::test_get_conversations",
"tests/test_canvas.py::TestCanvas::test_get_course",
"tests/test_canvas.py::TestCanvas::test_get_course_accounts",
"tests/test_canvas.py::TestCanvas::test_get_course_fail",
"tests/test_canvas.py::TestCanvas::test_get_course_nickname",
"tests/test_canvas.py::TestCanvas::test_get_course_nickname_fail",
"tests/test_canvas.py::TestCanvas::test_get_course_nicknames",
"tests/test_canvas.py::TestCanvas::test_get_course_non_unicode_char",
"tests/test_canvas.py::TestCanvas::test_get_course_sis_id",
"tests/test_canvas.py::TestCanvas::test_get_course_with_start_date",
"tests/test_canvas.py::TestCanvas::test_get_courses",
"tests/test_canvas.py::TestCanvas::test_get_file",
"tests/test_canvas.py::TestCanvas::test_get_group",
"tests/test_canvas.py::TestCanvas::test_get_group_category",
"tests/test_canvas.py::TestCanvas::test_get_group_sis_id",
"tests/test_canvas.py::TestCanvas::test_get_outcome",
"tests/test_canvas.py::TestCanvas::test_get_outcome_group",
"tests/test_canvas.py::TestCanvas::test_get_root_outcome_group",
"tests/test_canvas.py::TestCanvas::test_get_section",
"tests/test_canvas.py::TestCanvas::test_get_section_sis_id",
"tests/test_canvas.py::TestCanvas::test_get_todo_items",
"tests/test_canvas.py::TestCanvas::test_get_upcoming_events",
"tests/test_canvas.py::TestCanvas::test_get_user",
"tests/test_canvas.py::TestCanvas::test_get_user_by_id_type",
"tests/test_canvas.py::TestCanvas::test_get_user_fail",
"tests/test_canvas.py::TestCanvas::test_list_appointment_groups",
"tests/test_canvas.py::TestCanvas::test_list_calendar_events",
"tests/test_canvas.py::TestCanvas::test_list_group_participants",
"tests/test_canvas.py::TestCanvas::test_list_user_participants",
"tests/test_canvas.py::TestCanvas::test_reserve_time_slot",
"tests/test_canvas.py::TestCanvas::test_reserve_time_slot_by_participant_id",
"tests/test_canvas.py::TestCanvas::test_search_accounts",
"tests/test_canvas.py::TestCanvas::test_search_all_courses",
"tests/test_canvas.py::TestCanvas::test_search_recipients",
"tests/test_canvas.py::TestCanvas::test_set_course_nickname"
]
| []
| MIT License | 1,889 | [
"canvasapi/canvas.py"
]
| [
"canvasapi/canvas.py"
]
|
|
pypa__setuptools_scm-186 | fc824aaaa952ded5f6ee54bcddafb0d96f4b44c4 | 2017-11-14 05:31:23 | 0373c11d2c8968a857ff06c94f101abebf825507 | diff --git a/.gitignore b/.gitignore
index 7bdd112..19ae6c2 100644
--- a/.gitignore
+++ b/.gitignore
@@ -6,6 +6,9 @@
## Directory-based project format:
.idea/
+### Other editors
+.*.swp
+
### Python template
# Byte-compiled / optimized
diff --git a/setuptools_scm/git.py b/setuptools_scm/git.py
index 7fa1b32..6ec9962 100644
--- a/setuptools_scm/git.py
+++ b/setuptools_scm/git.py
@@ -1,15 +1,20 @@
from .utils import do_ex, trace, has_command
from .version import meta
+
from os.path import isfile, join
+import subprocess
+import sys
+import tarfile
import warnings
+
try:
from os.path import samefile
except ImportError:
from .win_py31_compat import samefile
-FILES_COMMAND = 'git ls-files'
+FILES_COMMAND = sys.executable + ' -m setuptools_scm.git'
DEFAULT_DESCRIBE = 'git describe --dirty --tags --long --match *.*'
@@ -116,3 +121,17 @@ def parse(root, describe_command=DEFAULT_DESCRIBE, pre_parse=warn_on_shallow):
return meta(tag, distance=number, node=node, dirty=dirty)
else:
return meta(tag, node=node, dirty=dirty)
+
+
+def _list_files_in_archive():
+ """List the files that 'git archive' generates.
+ """
+ cmd = ['git', 'archive', 'HEAD']
+ proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
+ tf = tarfile.open(fileobj=proc.stdout, mode='r|*')
+ for name in tf.getnames():
+ print(name)
+
+
+if __name__ == "__main__":
+ _list_files_in_archive()
diff --git a/setuptools_scm/utils.py b/setuptools_scm/utils.py
index f744337..0e8a555 100644
--- a/setuptools_scm/utils.py
+++ b/setuptools_scm/utils.py
@@ -61,7 +61,7 @@ def _popen_pipes(cmd, cwd):
def do_ex(cmd, cwd='.'):
trace('cmd', repr(cmd))
- if not isinstance(cmd, (list, tuple)):
+ if os.name == "posix" and not isinstance(cmd, (list, tuple)):
cmd = shlex.split(cmd)
p = _popen_pipes(cmd, cwd)
| support git's export-ignore
`git archive` reads the `export-ignore` gitattribute (https://git-scm.com/docs/gitattributes#_creating_an_archive) which allows marking some files as NOT packaged into the archive. It would be nice if setuptools_scm did the same for the sdist.
Typical use cases would be to remove CI scripts.
Unfortunately AFAICT there is no way to ask git for the files it would archive short of actually running git archive and examining the resulting tarball. OTOH it appears that such a step is much faster than the sdist build itself, so perhaps that remains an acceptable approach? | pypa/setuptools_scm | diff --git a/testing/test_git.py b/testing/test_git.py
index ddae5d4..4f4ad53 100644
--- a/testing/test_git.py
+++ b/testing/test_git.py
@@ -112,3 +112,15 @@ def test_alphanumeric_tags_match(wd):
wd.commit_testfile()
wd('git tag newstyle-development-started')
assert wd.version.startswith('0.1.dev1+g')
+
+
+def test_git_archive_export_ignore(wd):
+ wd.write('test1.txt', 'test')
+ wd.write('test2.txt', 'test')
+ wd.write('.git/info/attributes',
+ # Explicitly include test1.txt so that the test is not affected by
+ # a potentially global gitattributes file on the test machine.
+ '/test1.txt -export-ignore\n/test2.txt export-ignore')
+ wd('git add test1.txt test2.txt')
+ wd.commit()
+ assert integration.find_files(str(wd.cwd)) == ['test1.txt']
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 1,
"test_score": 0
},
"num_modified_files": 3
} | 1.15 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest"
],
"pre_install": [
"python setup.py egg_info"
],
"python": "3.6",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs==22.2.0
certifi==2021.5.30
importlib-metadata==4.8.3
iniconfig==1.1.1
packaging==21.3
pluggy==1.0.0
py==1.11.0
pyparsing==3.1.4
pytest==7.0.1
-e git+https://github.com/pypa/setuptools_scm.git@fc824aaaa952ded5f6ee54bcddafb0d96f4b44c4#egg=setuptools_scm
tomli==1.2.3
typing_extensions==4.1.1
zipp==3.6.0
| name: setuptools_scm
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- attrs==22.2.0
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- packaging==21.3
- pluggy==1.0.0
- py==1.11.0
- pyparsing==3.1.4
- pytest==7.0.1
- tomli==1.2.3
- typing-extensions==4.1.1
- zipp==3.6.0
prefix: /opt/conda/envs/setuptools_scm
| [
"testing/test_git.py::test_git_archive_export_ignore"
]
| []
| [
"testing/test_git.py::test_version_from_git",
"testing/test_git.py::test_unicode_version_scheme",
"testing/test_git.py::test_git_worktree",
"testing/test_git.py::test_git_dirty_notag",
"testing/test_git.py::test_git_parse_shallow_warns",
"testing/test_git.py::test_git_parse_shallow_fail",
"testing/test_git.py::test_git_shallow_autocorrect",
"testing/test_git.py::test_find_files_stop_at_root_git",
"testing/test_git.py::test_parse_no_worktree",
"testing/test_git.py::test_alphanumeric_tags_match"
]
| []
| MIT License | 1,890 | [
".gitignore",
"setuptools_scm/utils.py",
"setuptools_scm/git.py"
]
| [
".gitignore",
"setuptools_scm/utils.py",
"setuptools_scm/git.py"
]
|
|
numpy__numpydoc-145 | 40b3733b4bf4604ff7622b5eab592edcef750591 | 2017-11-14 07:48:31 | 1f197e32a31db2280b71be183e6724f9457ce78e | jnothman: Ping @Dreem-Devices, @tacaswell, @stefanv who commented on the original issue.
tacaswell: I'm going to ping my co worker @danielballan who is much better at naming things than I am.
rgommers: LGTM. Needs a rebase.
rgommers: @jnothman want to rebase this? I think it can go into 0.9.0 | diff --git a/doc/format.rst b/doc/format.rst
index 87f5ff7..cdeec0b 100644
--- a/doc/format.rst
+++ b/doc/format.rst
@@ -252,13 +252,21 @@ The sections of a function's docstring are:
Support for the **Yields** section was added in `numpydoc
<https://github.com/numpy/numpydoc>`_ version 0.6.
-7. **Other Parameters**
+7. **Receives**
+
+ Explanation of parameters passed to a generator's ``.send()`` method,
+ formatted as for Parameters, above. Since, like for Yields and Returns, a
+ single object is always passed to the method, this may describe either the
+ single parameter, or positional arguments passed as a tuple. If a docstring
+ includes Receives it must also include Yields.
+
+8. **Other Parameters**
An optional section used to describe infrequently used parameters.
It should only be used if a function has a large number of keyword
parameters, to prevent cluttering the **Parameters** section.
-8. **Raises**
+9. **Raises**
An optional section detailing which errors get raised and under
what conditions::
@@ -271,16 +279,16 @@ The sections of a function's docstring are:
This section should be used judiciously, i.e., only for errors
that are non-obvious or have a large chance of getting raised.
-9. **Warns**
+10. **Warns**
An optional section detailing which warnings get raised and
under what conditions, formatted similarly to Raises.
-10. **Warnings**
+11. **Warnings**
An optional section with cautions to the user in free text/reST.
-11. **See Also**
+12. **See Also**
An optional section used to refer to related code. This section
can be very useful, but should be used judiciously. The goal is to
@@ -319,7 +327,7 @@ The sections of a function's docstring are:
func_b, func_c_, func_d
func_e
-12. **Notes**
+13. **Notes**
An optional section that provides additional information about the
code, possibly including a discussion of the algorithm. This
@@ -364,7 +372,7 @@ The sections of a function's docstring are:
where filename is a path relative to the reference guide source
directory.
-13. **References**
+14. **References**
References cited in the **notes** section may be listed here,
e.g. if you cited the article below using the text ``[1]_``,
@@ -397,7 +405,7 @@ The sections of a function's docstring are:
.. highlight:: pycon
-14. **Examples**
+15. **Examples**
An optional section for examples, using the `doctest
<http://docs.python.org/library/doctest.html>`_ format.
diff --git a/numpydoc/docscrape.py b/numpydoc/docscrape.py
index f3453c6..4e3fc4c 100644
--- a/numpydoc/docscrape.py
+++ b/numpydoc/docscrape.py
@@ -127,6 +127,7 @@ class NumpyDocString(Mapping):
'Parameters': [],
'Returns': [],
'Yields': [],
+ 'Receives': [],
'Raises': [],
'Warns': [],
'Other Parameters': [],
@@ -350,6 +351,9 @@ class NumpyDocString(Mapping):
if has_returns and has_yields:
msg = 'Docstring contains both a Returns and Yields section.'
raise ValueError(msg)
+ if not has_yields and 'Receives' in section_names:
+ msg = 'Docstring contains a Receives section but not Yields.'
+ raise ValueError(msg)
for (section, content) in sections:
if not section.startswith('..'):
@@ -359,8 +363,8 @@ class NumpyDocString(Mapping):
self._error_location("The section %s appears twice"
% section)
- if section in ('Parameters', 'Returns', 'Yields', 'Raises',
- 'Warns', 'Other Parameters', 'Attributes',
+ if section in ('Parameters', 'Returns', 'Yields', 'Receives',
+ 'Raises', 'Warns', 'Other Parameters', 'Attributes',
'Methods'):
self[section] = self._parse_param_list(content)
elif section.startswith('.. index::'):
@@ -484,7 +488,7 @@ class NumpyDocString(Mapping):
out += self._str_signature()
out += self._str_summary()
out += self._str_extended_summary()
- for param_list in ('Parameters', 'Returns', 'Yields',
+ for param_list in ('Parameters', 'Returns', 'Yields', 'Receives',
'Other Parameters', 'Raises', 'Warns'):
out += self._str_param_list(param_list)
out += self._str_section('Warnings')
diff --git a/numpydoc/docscrape_sphinx.py b/numpydoc/docscrape_sphinx.py
index 4cc95d8..9b23235 100644
--- a/numpydoc/docscrape_sphinx.py
+++ b/numpydoc/docscrape_sphinx.py
@@ -374,6 +374,7 @@ class SphinxDocString(NumpyDocString):
'parameters': self._str_param_list('Parameters'),
'returns': self._str_returns('Returns'),
'yields': self._str_returns('Yields'),
+ 'receives': self._str_returns('Receives'),
'other_parameters': self._str_param_list('Other Parameters'),
'raises': self._str_param_list('Raises'),
'warns': self._str_param_list('Warns'),
diff --git a/numpydoc/numpydoc.py b/numpydoc/numpydoc.py
index c8e676f..2544d0f 100644
--- a/numpydoc/numpydoc.py
+++ b/numpydoc/numpydoc.py
@@ -27,8 +27,9 @@ try:
except ImportError:
from collections import Callable
import hashlib
+import itertools
-from docutils.nodes import citation, Text, reference
+from docutils.nodes import citation, Text, section, comment, reference
import sphinx
from sphinx.addnodes import pending_xref, desc_content, only
@@ -73,18 +74,39 @@ def rename_references(app, what, name, obj, options, lines):
sixu('.. [%s]') % new_r)
-def _ascend(node, cls):
- while node and not isinstance(node, cls):
- node = node.parent
- return node
+def _is_cite_in_numpydoc_docstring(citation_node):
+ # Find DEDUPLICATION_TAG in comment as last node of sibling section
+
+ # XXX: I failed to use citation_node.traverse to do this:
+ section_node = citation_node.parent
+
+ def is_docstring_section(node):
+ return isinstance(node, (section, desc_content))
+
+ while not is_docstring_section(section_node):
+ section_node = section_node.parent
+ if section_node is None:
+ return False
+
+ sibling_sections = itertools.chain(section_node.traverse(is_docstring_section,
+ include_self=True,
+ descend=False,
+ siblings=True))
+ for sibling_section in sibling_sections:
+ if not sibling_section.children:
+ continue
+ last_child = sibling_section.children[-1]
+ if not isinstance(last_child, comment):
+ continue
+ if last_child.rawsource.strip() == DEDUPLICATION_TAG.strip():
+ return True
+ return False
def relabel_references(app, doc):
# Change 'hash-ref' to 'ref' in label text
for citation_node in doc.traverse(citation):
- if _ascend(citation_node, desc_content) is None:
- # no desc node in ancestry -> not in a docstring
- # XXX: should we also somehow check it's in a References section?
+ if not _is_cite_in_numpydoc_docstring(citation_node):
continue
label_node = citation_node[0]
prefix, _, new_label = label_node[0].astext().partition('-')
diff --git a/numpydoc/templates/numpydoc_docstring.rst b/numpydoc/templates/numpydoc_docstring.rst
index 1900db5..79ab1f8 100644
--- a/numpydoc/templates/numpydoc_docstring.rst
+++ b/numpydoc/templates/numpydoc_docstring.rst
@@ -4,6 +4,7 @@
{{parameters}}
{{returns}}
{{yields}}
+{{receives}}
{{other_parameters}}
{{raises}}
{{warns}}
| support for coroutine
I have a lot of coroutine to comment but i have not seen any suppport for this python feature.
The yield allows to comment what goes out of the coroutine but it would be nice to be able to specify what goes in in a specific manner.
| numpy/numpydoc | diff --git a/numpydoc/tests/test_docscrape.py b/numpydoc/tests/test_docscrape.py
index 2085948..a0fb19c 100644
--- a/numpydoc/tests/test_docscrape.py
+++ b/numpydoc/tests/test_docscrape.py
@@ -150,6 +150,25 @@ int
doc_yields = NumpyDocString(doc_yields_txt)
+doc_sent_txt = """
+Test generator
+
+Yields
+------
+a : int
+ The number of apples.
+
+Receives
+--------
+b : int
+ The number of bananas.
+c : int
+ The number of oranges.
+
+"""
+doc_sent = NumpyDocString(doc_sent_txt)
+
+
def test_signature():
assert doc['Signature'].startswith('numpy.multivariate_normal(')
assert doc['Signature'].endswith('spam=None)')
@@ -216,6 +235,38 @@ def test_yields():
assert desc[0].endswith(end)
+def test_sent():
+ section = doc_sent['Receives']
+ assert len(section) == 2
+ truth = [('b', 'int', 'bananas.'),
+ ('c', 'int', 'oranges.')]
+ for (arg, arg_type, desc), (arg_, arg_type_, end) in zip(section, truth):
+ assert arg == arg_
+ assert arg_type == arg_type_
+ assert desc[0].startswith('The number of')
+ assert desc[0].endswith(end)
+
+
+def test_returnyield():
+ doc_text = """
+Test having returns and yields.
+
+Returns
+-------
+int
+ The number of apples.
+
+Yields
+------
+a : int
+ The number of apples.
+b : int
+ The number of bananas.
+
+"""
+ assert_raises(ValueError, NumpyDocString, doc_text)
+
+
def test_returnyield():
doc_text = """
Test having returns and yields.
@@ -468,6 +519,25 @@ int
.. index:: """)
+def test_receives_str():
+ line_by_line_compare(str(doc_sent),
+"""Test generator
+
+Yields
+------
+a : int
+ The number of apples.
+
+Receives
+--------
+b : int
+ The number of bananas.
+c : int
+ The number of oranges.
+
+.. index:: """)
+
+
def test_no_index_in_str():
assert "index" not in str(NumpyDocString("""Test idx
| {
"commit_name": "merge_commit",
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 2,
"test_score": 3
},
"num_modified_files": 5
} | 0.8 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y texlive texlive-latex-extra latexmk",
"pip install --upgrade pip setuptools"
],
"python": "3.6",
"reqs_path": [
"doc/requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | alabaster==0.7.13
attrs==22.2.0
Babel==2.11.0
certifi==2021.5.30
charset-normalizer==2.0.12
cycler==0.11.0
docutils==0.18.1
idna==3.10
imagesize==1.4.1
importlib-metadata==4.8.3
iniconfig==1.1.1
Jinja2==3.0.3
kiwisolver==1.3.1
MarkupSafe==2.0.1
matplotlib==3.3.4
numpy==1.19.5
-e git+https://github.com/numpy/numpydoc.git@40b3733b4bf4604ff7622b5eab592edcef750591#egg=numpydoc
packaging==21.3
Pillow==8.4.0
pluggy==1.0.0
py==1.11.0
Pygments==2.14.0
pyparsing==3.1.4
pytest==7.0.1
python-dateutil==2.9.0.post0
pytz==2025.2
requests==2.27.1
six==1.17.0
snowballstemmer==2.2.0
Sphinx==5.3.0
sphinxcontrib-applehelp==1.0.2
sphinxcontrib-devhelp==1.0.2
sphinxcontrib-htmlhelp==2.0.0
sphinxcontrib-jsmath==1.0.1
sphinxcontrib-qthelp==1.0.3
sphinxcontrib-serializinghtml==1.1.5
tomli==1.2.3
typing_extensions==4.1.1
urllib3==1.26.20
zipp==3.6.0
| name: numpydoc
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- alabaster==0.7.13
- attrs==22.2.0
- babel==2.11.0
- charset-normalizer==2.0.12
- cycler==0.11.0
- docutils==0.18.1
- idna==3.10
- imagesize==1.4.1
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- jinja2==3.0.3
- kiwisolver==1.3.1
- markupsafe==2.0.1
- matplotlib==3.3.4
- numpy==1.19.5
- packaging==21.3
- pillow==8.4.0
- pip==21.3.1
- pluggy==1.0.0
- py==1.11.0
- pygments==2.14.0
- pyparsing==3.1.4
- pytest==7.0.1
- python-dateutil==2.9.0.post0
- pytz==2025.2
- requests==2.27.1
- setuptools==59.6.0
- six==1.17.0
- snowballstemmer==2.2.0
- sphinx==5.3.0
- sphinxcontrib-applehelp==1.0.2
- sphinxcontrib-devhelp==1.0.2
- sphinxcontrib-htmlhelp==2.0.0
- sphinxcontrib-jsmath==1.0.1
- sphinxcontrib-qthelp==1.0.3
- sphinxcontrib-serializinghtml==1.1.5
- tomli==1.2.3
- typing-extensions==4.1.1
- urllib3==1.26.20
- zipp==3.6.0
prefix: /opt/conda/envs/numpydoc
| [
"numpydoc/tests/test_docscrape.py::test_sent"
]
| []
| [
"numpydoc/tests/test_docscrape.py::test_signature",
"numpydoc/tests/test_docscrape.py::test_summary",
"numpydoc/tests/test_docscrape.py::test_extended_summary",
"numpydoc/tests/test_docscrape.py::test_parameters",
"numpydoc/tests/test_docscrape.py::test_other_parameters",
"numpydoc/tests/test_docscrape.py::test_returns",
"numpydoc/tests/test_docscrape.py::test_yields",
"numpydoc/tests/test_docscrape.py::test_returnyield",
"numpydoc/tests/test_docscrape.py::test_section_twice",
"numpydoc/tests/test_docscrape.py::test_notes",
"numpydoc/tests/test_docscrape.py::test_references",
"numpydoc/tests/test_docscrape.py::test_examples",
"numpydoc/tests/test_docscrape.py::test_index",
"numpydoc/tests/test_docscrape.py::test_str",
"numpydoc/tests/test_docscrape.py::test_yield_str",
"numpydoc/tests/test_docscrape.py::test_receives_str",
"numpydoc/tests/test_docscrape.py::test_no_index_in_str",
"numpydoc/tests/test_docscrape.py::test_sphinx_str",
"numpydoc/tests/test_docscrape.py::test_sphinx_yields_str",
"numpydoc/tests/test_docscrape.py::test_parameters_without_extended_description",
"numpydoc/tests/test_docscrape.py::test_escape_stars",
"numpydoc/tests/test_docscrape.py::test_empty_extended_summary",
"numpydoc/tests/test_docscrape.py::test_raises",
"numpydoc/tests/test_docscrape.py::test_warns",
"numpydoc/tests/test_docscrape.py::test_see_also",
"numpydoc/tests/test_docscrape.py::test_see_also_parse_error",
"numpydoc/tests/test_docscrape.py::test_see_also_print",
"numpydoc/tests/test_docscrape.py::test_unknown_section",
"numpydoc/tests/test_docscrape.py::test_empty_first_line",
"numpydoc/tests/test_docscrape.py::test_no_summary",
"numpydoc/tests/test_docscrape.py::test_unicode",
"numpydoc/tests/test_docscrape.py::test_plot_examples",
"numpydoc/tests/test_docscrape.py::test_use_blockquotes",
"numpydoc/tests/test_docscrape.py::test_class_members",
"numpydoc/tests/test_docscrape.py::test_duplicate_signature",
"numpydoc/tests/test_docscrape.py::test_class_members_doc",
"numpydoc/tests/test_docscrape.py::test_class_members_doc_sphinx",
"numpydoc/tests/test_docscrape.py::test_templated_sections",
"numpydoc/tests/test_docscrape.py::test_nonstandard_property",
"numpydoc/tests/test_docscrape.py::test_args_and_kwargs"
]
| []
| BSD License | 1,891 | [
"numpydoc/docscrape.py",
"numpydoc/docscrape_sphinx.py",
"doc/format.rst",
"numpydoc/numpydoc.py",
"numpydoc/templates/numpydoc_docstring.rst"
]
| [
"numpydoc/docscrape.py",
"numpydoc/docscrape_sphinx.py",
"doc/format.rst",
"numpydoc/numpydoc.py",
"numpydoc/templates/numpydoc_docstring.rst"
]
|
G-Node__python-odml-195 | e618e125963abd2bd214274861ae7636f3fdfae5 | 2017-11-14 15:16:09 | eeff5922987b064681d1328f81af317d8171808f | diff --git a/odml/section.py b/odml/section.py
index 407bf31..2086b0b 100644
--- a/odml/section.py
+++ b/odml/section.py
@@ -26,13 +26,16 @@ class BaseSection(base.sectionable, Section):
_format = format.Section
- def __init__(self, name, type=None, parent=None,
- definition=None, reference=None):
+ def __init__(self, name, type=None, parent=None, definition=None, reference=None,
+ repository=None, link=None, include=None):
self._parent = None
self._name = name
self._props = base.SmartList()
self._definition = definition
self._reference = reference
+ self._repository = repository
+ self._link = link
+ self._include = include
super(BaseSection, self).__init__()
# this may fire a change event, so have the section setup then
self.type = type
diff --git a/odml/tools/odmlparser.py b/odml/tools/odmlparser.py
index eb0ac3f..31093b6 100644
--- a/odml/tools/odmlparser.py
+++ b/odml/tools/odmlparser.py
@@ -7,8 +7,8 @@ Parses odML files and documents.
"""
-import yaml
import json
+import yaml
from .. import format
from . import xmlparser
@@ -20,13 +20,13 @@ allowed_parsers = ['XML', 'YAML', 'JSON']
class ODMLWriter:
- '''
+ """
A generic odML document writer, for XML, YAML and JSON.
Usage:
xml_writer = ODMLWriter(parser='XML')
xml_writer.write_file(odml_document, filepath)
- '''
+ """
def __init__(self, parser='XML'):
self.doc = None # odML document
@@ -55,7 +55,6 @@ class ODMLWriter:
self.parsed_doc = parsed_doc
def get_sections(self, section_list):
-
section_seq = []
for section in section_list:
@@ -81,7 +80,6 @@ class ODMLWriter:
return section_seq
def get_properties(self, props_list):
-
props_seq = []
for prop in props_list:
@@ -96,11 +94,10 @@ class ODMLWriter:
prop_dict[attr] = t
props_seq.append(prop_dict)
-
+
return props_seq
def write_file(self, odml_document, filename):
-
file = open(filename, 'w')
file.write(self.to_string(odml_document))
file.close()
@@ -108,7 +105,7 @@ class ODMLWriter:
def to_string(self, odml_document):
string_doc = ''
- if self.parser == 'XML' or self.parser == 'ODML':
+ if self.parser == 'XML':
string_doc = str(xmlparser.XMLWriter(odml_document))
else:
self.to_dict(odml_document)
@@ -129,8 +126,8 @@ class ODMLReader:
based on the given data exchange format, like XML, YAML or JSON.
Usage:
- yaml_odml_doc = ODMLReader(parser='YAML').fromFile(open("odml_doc.yaml"))
- json_odml_doc = ODMLReader(parser='JSON').fromFile(open("odml_doc.json"))
+ yaml_odml_doc = ODMLReader(parser='YAML').from_file("odml_doc.yaml")
+ json_odml_doc = ODMLReader(parser='JSON').from_file("odml_doc.json")
"""
def __init__(self, parser='XML'):
@@ -151,7 +148,6 @@ class ODMLReader:
return None
def to_odml(self):
-
self.odml_version = self.parsed_doc['odml-version']
self.parsed_doc = self.parsed_doc['Document']
@@ -172,7 +168,6 @@ class ODMLReader:
return self.doc
def parse_sections(self, section_list):
-
odml_sections = []
for section in section_list:
@@ -197,7 +192,6 @@ class ODMLReader:
return odml_sections
-
def parse_properties(self, props_list):
odml_props = []
@@ -218,7 +212,6 @@ class ODMLReader:
return odml_props
-
def from_file(self, file):
if self.parser == 'XML':
@@ -227,25 +220,24 @@ class ODMLReader:
return odml_doc
elif self.parser == 'YAML':
- try:
- self.parsed_doc = yaml.load(file)
- except yaml.parser.ParserError as e:
- print(e)
- return
- finally:
- file.close()
+ with open(file) as yaml_data:
+ try:
+ self.parsed_doc = yaml.load(yaml_data)
+ except yaml.parser.ParserError as e:
+ print(e)
+ return
+
return self.to_odml()
elif self.parser == 'JSON':
- try:
- self.parsed_doc = json.load(file)
- except json.decoder.JSONDecodeError as e:
- print(e)
- return
- finally:
- file.close()
- return self.to_odml()
+ with open(file) as json_data:
+ try:
+ self.parsed_doc = json.load(json_data)
+ except ValueError as e: # Python 2 does not support JSONDecodeError
+ print("JSON Decoder Error: %s" % e)
+ return
+ return self.to_odml()
def from_string(self, string):
@@ -253,17 +245,19 @@ class ODMLReader:
odml_doc = xmlparser.XMLReader().fromString(string)
self.doc = odml_doc
return self.doc
+
elif self.parser == 'YAML':
try:
- odml_doc = yaml.load(string)
+ self.parsed_doc = yaml.load(string)
except yaml.parser.ParserError as e:
print(e)
return
return self.to_odml()
+
elif self.parser == 'JSON':
try:
- odml_doc = json.loads(string)
- except json.decoder.JSONDecodeError as e:
- print(e)
+ self.parsed_doc = json.loads(string)
+ except ValueError as e: # Python 2 does not support JSONDecodeError
+ print("JSON Decoder Error: %s" % e)
return
return self.to_odml()
| fileio/odmlparser error when loading JSON or YAML
When loading a JSON odML file via `fileio.py` the following error occurs:
odml.load('f.json', 'json')
... odmlparser.py#246 : AttributeError: 'str' object has no attribute 'close'
When loading a YAML odML file via `fileio.py` the following error occurs:
odml.load('f.yaml', 'yaml')
... odmlparser.py#236 : AttributeError: 'str' object has no attribute 'close'
| G-Node/python-odml | diff --git a/test/test_parser.py b/test/test_parser.py
index 8f9156a..80c89eb 100644
--- a/test/test_parser.py
+++ b/test/test_parser.py
@@ -23,7 +23,6 @@ class TestParser(unittest.TestCase):
self.odml_doc = self.xml_reader.from_file(self.basefile)
-
def tearDown(self):
if os.path.exists(self.xml_file):
os.remove(self.xml_file)
@@ -34,40 +33,33 @@ class TestParser(unittest.TestCase):
if os.path.exists(self.json_file):
os.remove(self.json_file)
-
def test_xml(self):
-
self.xml_writer.write_file(self.odml_doc, self.xml_file)
- xml_doc = self.xml_reader.from_file(open(self.xml_file))
+ xml_doc = self.xml_reader.from_file(self.xml_file)
self.assertEqual(xml_doc, self.odml_doc)
def test_yaml(self):
-
self.yaml_writer.write_file(self.odml_doc, self.yaml_file)
- yaml_doc = self.yaml_reader.from_file(open(self.yaml_file))
+ yaml_doc = self.yaml_reader.from_file(self.yaml_file)
self.assertEqual(yaml_doc, self.odml_doc)
-
def test_json(self):
-
self.json_writer.write_file(self.odml_doc, self.json_file)
- json_doc = self.json_reader.from_file(open(self.json_file))
+ json_doc = self.json_reader.from_file(self.json_file)
self.assertEqual(json_doc, self.odml_doc)
-
def test_json_yaml_xml(self):
-
self.json_writer.write_file(self.odml_doc, self.json_file)
- json_doc = self.json_reader.from_file(open(self.json_file))
+ json_doc = self.json_reader.from_file(self.json_file)
self.yaml_writer.write_file(json_doc, self.yaml_file)
- yaml_doc = self.yaml_reader.from_file(open(self.yaml_file))
+ yaml_doc = self.yaml_reader.from_file(self.yaml_file)
self.xml_writer.write_file(yaml_doc, self.xml_file)
- xml_doc = self.xml_reader.from_file(open(self.xml_file))
+ xml_doc = self.xml_reader.from_file(self.xml_file)
self.assertEqual(json_doc, self.odml_doc)
self.assertEqual(json_doc, yaml_doc)
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 1,
"test_score": 2
},
"num_modified_files": 2
} | 1.3 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "lxml enum34 pyyaml rdflib",
"pip_packages": [
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y libxml2-dev libxslt1-dev lib32z1-dev"
],
"python": "3.5",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs==22.2.0
brotlipy==0.7.0
certifi==2021.5.30
cffi @ file:///tmp/build/80754af9/cffi_1625814693874/work
charset-normalizer @ file:///tmp/build/80754af9/charset-normalizer_1630003229654/work
cryptography @ file:///tmp/build/80754af9/cryptography_1635366128178/work
html5lib @ file:///Users/ktietz/demo/mc3/conda-bld/html5lib_1629144453894/work
idna @ file:///tmp/build/80754af9/idna_1637925883363/work
importlib-metadata==4.8.3
iniconfig==1.1.1
isodate @ file:///Users/ktietz/demo/mc3/conda-bld/isodate_1630584690429/work
keepalive @ file:///home/conda/feedstock_root/build_artifacts/keepalive_1635948558527/work
lxml @ file:///tmp/build/80754af9/lxml_1616442911898/work
-e git+https://github.com/G-Node/python-odml.git@e618e125963abd2bd214274861ae7636f3fdfae5#egg=odML
packaging==21.3
pluggy==1.0.0
py==1.11.0
pycparser @ file:///tmp/build/80754af9/pycparser_1636541352034/work
pyOpenSSL @ file:///opt/conda/conda-bld/pyopenssl_1643788558760/work
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
PySocks @ file:///tmp/build/80754af9/pysocks_1605305763431/work
pytest==7.0.1
PyYAML==5.4.1
rdflib @ file:///home/conda/feedstock_root/build_artifacts/rdflib_1610581402529/work
requests @ file:///opt/conda/conda-bld/requests_1641824580448/work
six @ file:///tmp/build/80754af9/six_1644875935023/work
SPARQLWrapper @ file:///home/conda/feedstock_root/build_artifacts/sparqlwrapper_1629916978493/work
tomli==1.2.3
typing_extensions==4.1.1
urllib3 @ file:///opt/conda/conda-bld/urllib3_1643638302206/work
webencodings==0.5.1
zipp==3.6.0
| name: python-odml
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- brotlipy=0.7.0=py36h27cfd23_1003
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- cffi=1.14.6=py36h400218f_0
- charset-normalizer=2.0.4=pyhd3eb1b0_0
- cryptography=35.0.0=py36hd23ed53_0
- enum34=1.1.10=py36h06a4308_0
- html5lib=1.1=pyhd3eb1b0_0
- icu=58.2=he6710b0_3
- idna=3.3=pyhd3eb1b0_0
- isodate=0.6.0=pyhd3eb1b0_1
- keepalive=0.5=pyhd8ed1ab_6
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- libxml2=2.9.14=h74e7548_0
- libxslt=1.1.35=h4e12654_0
- lxml=4.6.3=py36h9120a33_0
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- pycparser=2.21=pyhd3eb1b0_0
- pyopenssl=22.0.0=pyhd3eb1b0_0
- pyparsing=3.0.4=pyhd3eb1b0_0
- pysocks=1.7.1=py36h06a4308_0
- python=3.6.13=h12debd9_1
- python_abi=3.6=2_cp36m
- pyyaml=5.4.1=py36h27cfd23_1
- rdflib=5.0.0=py36h5fab9bb_3
- readline=8.2=h5eee18b_0
- requests=2.27.1=pyhd3eb1b0_0
- setuptools=58.0.4=py36h06a4308_0
- six=1.16.0=pyhd3eb1b0_1
- sparqlwrapper=1.8.5=py36h5fab9bb_1006
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- urllib3=1.26.8=pyhd3eb1b0_0
- webencodings=0.5.1=py36_1
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- yaml=0.2.5=h7b6447c_0
- zlib=1.2.13=h5eee18b_1
- pip:
- attrs==22.2.0
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- packaging==21.3
- pluggy==1.0.0
- py==1.11.0
- pytest==7.0.1
- tomli==1.2.3
- typing-extensions==4.1.1
- zipp==3.6.0
prefix: /opt/conda/envs/python-odml
| [
"test/test_parser.py::TestParser::test_json",
"test/test_parser.py::TestParser::test_json_yaml_xml",
"test/test_parser.py::TestParser::test_yaml"
]
| []
| [
"test/test_parser.py::TestParser::test_xml"
]
| []
| BSD 4-Clause "Original" or "Old" License | 1,892 | [
"odml/section.py",
"odml/tools/odmlparser.py"
]
| [
"odml/section.py",
"odml/tools/odmlparser.py"
]
|
|
ethereum__py_ecc-6 | 812722660d87c5c7366b1b4927dbf49a8ecbf3f9 | 2017-11-15 03:22:45 | 865972fd536dc9ddb0c2f14235c2d04429cb982c | diff --git a/py_ecc/secp256k1/secp256k1.py b/py_ecc/secp256k1/secp256k1.py
index 68f1ca1..db93ee5 100644
--- a/py_ecc/secp256k1/secp256k1.py
+++ b/py_ecc/secp256k1/secp256k1.py
@@ -6,8 +6,11 @@ import sys
if sys.version_info.major == 2:
safe_ord = ord
else:
- def safe_ord(x):
- return x
+ def safe_ord(value):
+ if isinstance(value, int):
+ return value
+ else:
+ return ord(value)
# Elliptic curve parameters (secp256k1)
| secp256k1.py fails on Python 3.4
Error test:
```python
import binascii
import rlp
# sha3 from module `pysha3` not `ssh3`
import sha3
from py_ecc.secp256k1 import ecdsa_raw_recover
n = 0
p = 20000000000
g = 100000
v = 1000
Tn = ''
Tp = p.to_bytes((p.bit_length()//8) + 1,byteorder='big')
Tg = g.to_bytes((g.bit_length()//8) + 1,byteorder='big')
Tt = binascii.unhexlify("687422eEA2cB73B5d3e242bA5456b782919AFc85")
Tv = v.to_bytes((v.bit_length()//8) + 1,byteorder='big')
Td = binascii.unhexlify("c0de")
transaction = [Tn, Tp, Tg, Tt, Tv, Td]
rlp_data=rlp.encode(transaction)
unsigned_message=sha3.keccak_256(rlp_data).hexdigest()
v = 28
r = int("5897c2c7c7412b0a555fb6f053ddb6047c59666bbebc6f5573134e074992d841",16)
s = int("1c71d1c62b74caff8695a186e2a24dd701070ba9946748318135e3ac0950b1d4",16)
ecdsa_raw_recover(unsigned_message, (v, r, s))
```
Error message:
> Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/apalau/python3.4/lib64/python3.4/site-packages/py_ecc/secp256k1/secp256k1.py", line 132, in ecdsa_raw_recover
z = bytes_to_int(msghash)
File "/home/apalau/python3.4/lib64/python3.4/site-packages/py_ecc/secp256k1/secp256k1.py", line 21, in bytes_to_int
o = (o << 8) + safe_ord(b)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
On Python 2.7 the same `ecdsa_raw_recover(unsigned_message, (v, r, s))` works well.
Python version:
> python --version
> Python 3.4.5
| ethereum/py_ecc | diff --git a/tests/test_secp256k1.py b/tests/test_secp256k1.py
index c7fbe23..a56bba1 100644
--- a/tests/test_secp256k1.py
+++ b/tests/test_secp256k1.py
@@ -12,3 +12,11 @@ def test_privtopub():
def test_ecdsa_raw_sign():
v, r, s = ecdsa_raw_sign(b'\x35' * 32, priv)
assert ecdsa_raw_recover(b'\x35' * 32, (v, r, s)) == pub
+
+
+def test_issue_4_bug():
+ unsigned_message = '6a74f15f29c3227c5d1d2e27894da58d417a484ef53bc7aa57ee323b42ded656'
+ v = 28
+ r = int("5897c2c7c7412b0a555fb6f053ddb6047c59666bbebc6f5573134e074992d841", 16)
+ s = int("1c71d1c62b74caff8695a186e2a24dd701070ba9946748318135e3ac0950b1d4", 16)
+ ecdsa_raw_recover(unsigned_message, (v, r, s))
| {
"commit_name": "head_commit",
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 0,
"test_score": 2
},
"num_modified_files": 1
} | 1.4 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"pytest",
"pytest-xdist"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.6",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work
certifi==2021.5.30
execnet==1.9.0
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work
packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work
pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
-e git+https://github.com/ethereum/py_ecc.git@812722660d87c5c7366b1b4927dbf49a8ecbf3f9#egg=py_ecc
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pytest==6.2.4
pytest-xdist==3.0.2
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
| name: py_ecc
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=21.4.0=pyhd3eb1b0_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- importlib-metadata=4.8.1=py36h06a4308_0
- importlib_metadata=4.8.1=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- more-itertools=8.12.0=pyhd3eb1b0_0
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=21.3=pyhd3eb1b0_0
- pip=21.2.2=py36h06a4308_0
- pluggy=0.13.1=py36h06a4308_0
- py=1.11.0=pyhd3eb1b0_0
- pyparsing=3.0.4=pyhd3eb1b0_0
- pytest=6.2.4=py36h06a4308_2
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- toml=0.10.2=pyhd3eb1b0_0
- typing_extensions=4.1.1=pyh06a4308_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zipp=3.6.0=pyhd3eb1b0_0
- zlib=1.2.13=h5eee18b_1
- pip:
- execnet==1.9.0
- pytest-xdist==3.0.2
prefix: /opt/conda/envs/py_ecc
| [
"tests/test_secp256k1.py::test_issue_4_bug"
]
| []
| [
"tests/test_secp256k1.py::test_privtopub",
"tests/test_secp256k1.py::test_ecdsa_raw_sign"
]
| []
| MIT License | 1,893 | [
"py_ecc/secp256k1/secp256k1.py"
]
| [
"py_ecc/secp256k1/secp256k1.py"
]
|
|
mjs__imapclient-316 | 2abdac690fa653fa2d0d55b7617be24101597698 | 2017-11-15 15:56:52 | 2abdac690fa653fa2d0d55b7617be24101597698 | diff --git a/doc/src/releases.rst b/doc/src/releases.rst
index 7319e53..791ce0c 100644
--- a/doc/src/releases.rst
+++ b/doc/src/releases.rst
@@ -19,6 +19,11 @@ Changed
are not used anymore.
- More precise exceptions available in `imapclient.exceptions` are raised when
an error happens
+- GMail labels are now strings instead of bytes in Python 3.
+
+Fixed
+-----
+- GMail labels using international characters are now handled properly.
Other
-----
diff --git a/imapclient/imapclient.py b/imapclient/imapclient.py
index bf10a1d..a54f515 100644
--- a/imapclient/imapclient.py
+++ b/imapclient/imapclient.py
@@ -1012,7 +1012,9 @@ class IMAPClient(object):
attribute (eg. Gmail).
"""
response = self.fetch(messages, [b'X-GM-LABELS'])
- return self._filter_fetch_dict(response, b'X-GM-LABELS')
+ response = self._filter_fetch_dict(response, b'X-GM-LABELS')
+ return {msg: utf7_decode_sequence(labels)
+ for msg, labels in iteritems(response)}
def add_gmail_labels(self, messages, labels, silent=False):
"""Add *labels* to *messages* in the currently selected folder.
@@ -1348,8 +1350,10 @@ class IMAPClient(object):
self._check_resp('OK', command, typ, data)
def _gm_label_store(self, cmd, messages, labels, silent):
- return self._store(cmd, messages, self._normalise_labels(labels),
+ response = self._store(cmd, messages, self._normalise_labels(labels),
b'X-GM-LABELS', silent=silent)
+ return {msg: utf7_decode_sequence(labels)
+ for msg, labels in iteritems(response)} if response else None
def _store(self, cmd, messages, flags, fetch_key, silent):
"""Worker function for the various flag manipulation methods.
@@ -1385,7 +1389,7 @@ class IMAPClient(object):
def _normalise_labels(self, labels):
if isinstance(labels, (text_type, binary_type)):
labels = (labels,)
- return [_quote(l) for l in labels]
+ return [_quote(encode_utf7(l)) for l in labels]
@property
def welcome(self):
@@ -1599,6 +1603,10 @@ def debug_trunc(v, maxlen):
return repr(v[:hl]) + "..." + repr(v[-hl:])
+def utf7_decode_sequence(seq):
+ return [decode_utf7(s) for s in seq]
+
+
class IMAPlibLoggerAdapter(LoggerAdapter):
"""Adapter preventing IMAP secrets from going to the logging facility."""
| UTF-7 decoding of Gmail labels
Originally reported by: **Menno Smits (Bitbucket: [mjs0](https://bitbucket.org/mjs0))**
---
As worked around here in the Nylas sync engine:
https://github.com/nylas/sync-engine/commit/fdeee59be8feea1c4fac4d9972b3462d128c25f2
Fixing this might break backwards compatibility (so might require a 2.0)
---
- Bitbucket: https://bitbucket.org/mjs0/imapclient/issue/184
| mjs/imapclient | diff --git a/livetest.py b/livetest.py
index 7e01fa3..1a4a89c 100644
--- a/livetest.py
+++ b/livetest.py
@@ -1,4 +1,5 @@
#!/usr/bin/python
+# -*- coding: utf-8 -*-
# Copyright (c) 2014, Menno Smits
# Released subject to the New BSD License
@@ -623,9 +624,9 @@ def createUidTestClass(conf, use_uid):
actual_labels = set(answer[msg_id])
self.assertSetEqual(actual_labels, set(expected_labels))
- FOO = b'_imapclient_foo'
- BAR = b'_imapclient_bar'
- BAZ = b'_imapclient_baz'
+ FOO = '_imapclient_foo'
+ BAR = '_imapclient_bar'
+ BAZ = u'_imapclient_bÂz'
all_labels = [FOO, BAR, BAZ]
base_labels = [FOO, BAR]
try:
diff --git a/tests/test_store.py b/tests/test_store.py
index 8b3319b..2f0911f 100644
--- a/tests/test_store.py
+++ b/tests/test_store.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
# Copyright (c) 2016, Menno Smits
# Released subject to the New BSD License
# Please see http://en.wikipedia.org/wiki/BSD_licenses
@@ -82,12 +83,12 @@ class TestGmailLabels(IMAPClientTest):
def test_get(self):
with patch.object(self.client, 'fetch', autospec=True,
- return_value={123: {b'X-GM-LABELS': [b'foo', b'bar']},
+ return_value={123: {b'X-GM-LABELS': [b'foo', b'&AUE-abel']},
444: {b'X-GM-LABELS': [b'foo']}}):
out = self.client.get_gmail_labels(sentinel.messages)
self.client.fetch.assert_called_with(sentinel.messages, [b'X-GM-LABELS'])
- self.assertEqual(out, {123: [b'foo', b'bar'],
- 444: [b'foo']})
+ self.assertEqual(out, {123: ['foo', u'Łabel'],
+ 444: ['foo']})
def test_set(self):
self.check(self.client.set_gmail_labels, b'X-GM-LABELS')
@@ -108,7 +109,7 @@ class TestGmailLabels(IMAPClientTest):
cc = self.client._command_and_check
cc.return_value = [
- b'11 (X-GM-LABELS (blah "f\\"o\\"o") UID 1)',
+ b'11 (X-GM-LABELS (&AUE-abel "f\\"o\\"o") UID 1)',
b'22 (X-GM-LABELS ("f\\"o\\"o") UID 2)',
b'11 (UID 1 FLAGS (dont))',
b'22 (UID 2 FLAGS (care))',
@@ -123,8 +124,8 @@ class TestGmailLabels(IMAPClientTest):
self.assertIsNone(resp)
else:
self.assertEqual(resp, {
- 1: (b'blah', b'f"o"o'),
- 2: (b'f"o"o',),
+ 1: [u'Łabel', 'f"o"o'],
+ 2: ['f"o"o',],
})
cc.reset_mock()
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 3,
"issue_text_score": 2,
"test_score": 0
},
"num_modified_files": 2
} | 1.0 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.6",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs==22.2.0
certifi==2021.5.30
-e git+https://github.com/mjs/imapclient.git@2abdac690fa653fa2d0d55b7617be24101597698#egg=IMAPClient
importlib-metadata==4.8.3
iniconfig==1.1.1
packaging==21.3
pluggy==1.0.0
py==1.11.0
pyparsing==3.1.4
pytest==7.0.1
six==1.17.0
tomli==1.2.3
typing_extensions==4.1.1
zipp==3.6.0
| name: imapclient
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- attrs==22.2.0
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- packaging==21.3
- pluggy==1.0.0
- py==1.11.0
- pyparsing==3.1.4
- pytest==7.0.1
- six==1.17.0
- tomli==1.2.3
- typing-extensions==4.1.1
- zipp==3.6.0
prefix: /opt/conda/envs/imapclient
| [
"tests/test_store.py::TestGmailLabels::test_add",
"tests/test_store.py::TestGmailLabels::test_get",
"tests/test_store.py::TestGmailLabels::test_remove",
"tests/test_store.py::TestGmailLabels::test_set"
]
| [
"livetest.py::TestSocketTimeout::test_small_connection_timeout_fail",
"livetest.py::TestSocketTimeout::test_small_read_timeout_fail"
]
| [
"tests/test_store.py::TestFlagsConsts::test_flags_are_bytes",
"tests/test_store.py::TestFlags::test_add",
"tests/test_store.py::TestFlags::test_get",
"tests/test_store.py::TestFlags::test_remove",
"tests/test_store.py::TestFlags::test_set"
]
| []
| BSD License | 1,894 | [
"doc/src/releases.rst",
"imapclient/imapclient.py"
]
| [
"doc/src/releases.rst",
"imapclient/imapclient.py"
]
|
|
mirumee__google-i18n-address-30 | c0f6abf05be235c29fc0a22098081b717ba6e704 | 2017-11-16 16:18:59 | c0f6abf05be235c29fc0a22098081b717ba6e704 | diff --git a/README.rst b/README.rst
index dc2cd14..1dd7670 100644
--- a/README.rst
+++ b/README.rst
@@ -201,6 +201,7 @@ useful for constructing address forms specific for a particular country:
>>> from i18naddress import get_validation_rules
>>> get_validation_rules({'country_code': 'US', 'country_area': 'CA'})
ValidationRules(
+ country_code='US',
country_name='UNITED STATES',
address_format='%N%n%O%n%A%n%C, %S %Z',
address_latin_format='%N%n%O%n%A%n%C, %S %Z',
@@ -215,8 +216,8 @@ useful for constructing address forms specific for a particular country:
city_area_choices=[],
postal_code_type='zip',
postal_code_matchers=[re.compile('^(\\d{5})(?:[ \\-](\\d{4}))?$'), re.compile('^9[0-5]|96[01]')],
- postal_code_examples='90000,96199',
- postal_code_prefix=')
+ postal_code_examples=['90000', '96199'],
+ postal_code_prefix='')
All known fields
----------------
diff --git a/i18naddress/__init__.py b/i18naddress/__init__.py
index 9104eee..81ba563 100644
--- a/i18naddress/__init__.py
+++ b/i18naddress/__init__.py
@@ -4,10 +4,10 @@ import io
import json
import os
import re
-from collections import defaultdict, namedtuple
+from collections import defaultdict
VALID_COUNTRY_CODE = re.compile(r'^\w{2,3}$')
-VALIDATION_DATA_DIR = os.path.join(os.path.dirname(__file__), 'data')
+VALIDATION_DATA_DIR = os.path.join(os.path.dirname(__file__), 'data')
VALIDATION_DATA_PATH = os.path.join(VALIDATION_DATA_DIR, '%s.json')
FIELD_MAPPING = {
@@ -36,16 +36,88 @@ def load_validation_data(country_code='all'):
return json.load(data)
-ValidationRules = namedtuple(
- 'ValidationRules', [
+class ValidationRules(object):
+ __slots__ = [
+ 'country_code',
'country_name',
- 'address_format', 'address_latin_format',
- 'allowed_fields', 'required_fields', 'upper_fields',
- 'country_area_type', 'country_area_choices',
- 'city_type', 'city_choices',
- 'city_area_type', 'city_area_choices',
- 'postal_code_type', 'postal_code_matchers', 'postal_code_examples',
- 'postal_code_prefix'])
+ 'address_format',
+ 'address_latin_format',
+ 'allowed_fields',
+ 'required_fields',
+ 'upper_fields',
+ 'country_area_type',
+ 'country_area_choices',
+ 'city_type',
+ 'city_choices',
+ 'city_area_type',
+ 'city_area_choices',
+ 'postal_code_type',
+ 'postal_code_matchers',
+ 'postal_code_examples',
+ 'postal_code_prefix']
+
+ def __init__(
+ self, country_code, country_name, address_format,
+ address_latin_format, allowed_fields, required_fields,
+ upper_fields, country_area_type, country_area_choices,
+ city_type, city_choices, city_area_type, city_area_choices,
+ postal_code_type, postal_code_matchers, postal_code_examples,
+ postal_code_prefix):
+ self.country_code = country_code
+ self.country_name = country_name
+ self.address_format = address_format
+ self.address_latin_format = address_latin_format
+ self.allowed_fields = allowed_fields
+ self.required_fields = required_fields
+ self.upper_fields = upper_fields
+ self.country_area_type = country_area_type
+ self.country_area_choices = country_area_choices
+ self.city_type = city_type
+ self.city_choices = city_choices
+ self.city_area_type = city_area_type
+ self.city_area_choices = city_area_choices
+ self.postal_code_type = postal_code_type
+ self.postal_code_matchers = postal_code_matchers
+ self.postal_code_examples = postal_code_examples
+ self.postal_code_prefix = postal_code_prefix
+
+ def __repr__(self):
+ return (
+ 'ValidationRules('
+ 'country_code=%r, '
+ 'country_name=%r, '
+ 'address_format=%r, '
+ 'address_latin_format=%r, '
+ 'allowed_fields=%r, '
+ 'required_fields=%r, '
+ 'upper_fields=%r, '
+ 'country_area_type=%r, '
+ 'country_area_choices=%r, '
+ 'city_type=%r, '
+ 'city_choices=%r, '
+ 'city_area_type=%r, '
+ 'city_area_choices=%r, '
+ 'postal_code_type=%r, '
+ 'postal_code_matchers=%r, '
+ 'postal_code_examples=%r, '
+ 'postal_code_prefix=%r)' % (
+ self.country_code,
+ self.country_name,
+ self.address_format,
+ self.address_latin_format,
+ self.allowed_fields,
+ self.required_fields,
+ self.upper_fields,
+ self.country_area_type,
+ self.country_area_choices,
+ self.city_type,
+ self.city_choices,
+ self.city_area_type,
+ self.city_area_choices,
+ self.postal_code_type,
+ self.postal_code_matchers,
+ self.postal_code_examples,
+ self.postal_code_prefix))
def _make_choices(rules, translated=False):
@@ -132,7 +204,9 @@ def get_validation_rules(address):
if 'zip' in country_data:
postal_code_matchers.append(
re.compile('^' + country_data['zip'] + '$'))
- postal_code_examples = country_data.get('zipex')
+ postal_code_examples = []
+ if 'zipex' in country_data:
+ postal_code_examples = country_data['zipex'].split(',')
city_choices = []
city_area_choices = []
@@ -164,7 +238,7 @@ def get_validation_rules(address):
postal_code_matchers.append(
re.compile('^' + country_area_data['zip']))
if 'zipex' in country_area_data:
- postal_code_examples = country_area_data['zipex']
+ postal_code_examples = country_area_data['zipex'].split(',')
city = None
city_choices = []
if 'sub_keys' in country_area_data:
@@ -187,7 +261,7 @@ def get_validation_rules(address):
postal_code_matchers.append(
re.compile('^' + city_data['zip']))
if 'zipex' in city_data:
- postal_code_examples = city_data['zipex']
+ postal_code_examples = city_data['zipex'].split(',')
city_area_choices = []
if 'sub_keys' in city_data:
city_area_keys = city_data['sub_keys'].split('~')
@@ -200,7 +274,7 @@ def get_validation_rules(address):
city_area_choices = _compact_choices(
city_area_choices, city_area_keys)
return ValidationRules(
- country_name,
+ country_code, country_name,
address_format, address_latin_format,
allowed_fields, required_fields, upper_fields,
country_area_type, country_area_choices,
| Could the postal_code_examples be returned as array not string?
```python
ValidationRules.postal_code_examples
```
returns a list of zip codes examples but as string separated by `,`. | mirumee/google-i18n-address | diff --git a/tests/test_i18naddress.py b/tests/test_i18naddress.py
index 8dbfb56..65c3fc7 100644
--- a/tests/test_i18naddress.py
+++ b/tests/test_i18naddress.py
@@ -22,6 +22,7 @@ def test_dictionary_access():
def test_validation_rules_canada():
validation_data = get_validation_rules({'country_code': 'CA'})
+ assert validation_data.country_code == 'CA'
assert validation_data.country_area_choices == [
('AB', 'Alberta'),
('BC', 'British Columbia'),
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 0,
"test_score": 3
},
"num_modified_files": 2
} | 2.1 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-cov"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.6",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs==22.2.0
certifi==2021.5.30
charset-normalizer==2.0.12
coverage==6.2
-e git+https://github.com/mirumee/google-i18n-address.git@c0f6abf05be235c29fc0a22098081b717ba6e704#egg=google_i18n_address
idna==3.10
importlib-metadata==4.8.3
iniconfig==1.1.1
packaging==21.3
pluggy==1.0.0
py==1.11.0
pyparsing==3.1.4
pytest==7.0.1
pytest-cov==4.0.0
requests==2.27.1
tomli==1.2.3
typing_extensions==4.1.1
urllib3==1.26.20
zipp==3.6.0
| name: google-i18n-address
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- attrs==22.2.0
- charset-normalizer==2.0.12
- coverage==6.2
- idna==3.10
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- packaging==21.3
- pluggy==1.0.0
- py==1.11.0
- pyparsing==3.1.4
- pytest==7.0.1
- pytest-cov==4.0.0
- requests==2.27.1
- tomli==1.2.3
- typing-extensions==4.1.1
- urllib3==1.26.20
- zipp==3.6.0
prefix: /opt/conda/envs/google-i18n-address
| [
"tests/test_i18naddress.py::test_validation_rules_canada"
]
| []
| [
"tests/test_i18naddress.py::test_invalid_country_code",
"tests/test_i18naddress.py::test_dictionary_access",
"tests/test_i18naddress.py::test_validation_rules_switzerland",
"tests/test_i18naddress.py::test_field_order_poland",
"tests/test_i18naddress.py::test_field_order_china",
"tests/test_i18naddress.py::test_locality_types[CN-levels0]",
"tests/test_i18naddress.py::test_locality_types[JP-levels1]",
"tests/test_i18naddress.py::test_locality_types[KR-levels2]"
]
| []
| BSD 3-Clause "New" or "Revised" License | 1,897 | [
"README.rst",
"i18naddress/__init__.py"
]
| [
"README.rst",
"i18naddress/__init__.py"
]
|
|
oasis-open__cti-python-stix2-111 | ef3ce9f6f0a678e604bda63f9eb5742ed53f8eff | 2017-11-16 21:47:03 | 4a9c38e0b50415f4733072fc76eb8ebd0749c84b | diff --git a/docs/guide/datastore.ipynb b/docs/guide/datastore.ipynb
index 7fc0997..24a2b4f 100644
--- a/docs/guide/datastore.ipynb
+++ b/docs/guide/datastore.ipynb
@@ -23,7 +23,7 @@
},
{
"cell_type": "code",
- "execution_count": 2,
+ "execution_count": 40,
"metadata": {
"collapsed": true,
"nbsphinx": "hidden"
@@ -262,6 +262,277 @@
"# attach multiple filters to a MemoryStore\n",
"mem.source.filters.update([f1,f2])"
]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## De-Referencing Relationships\n",
+ "\n",
+ "Given a STIX object, there are several ways to find other STIX objects related to it. To illustrate this, let's first create a [DataStore](../api/stix2.sources.rst#stix2.sources.DataStore) and add some objects and relationships."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 13,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from stix2 import Campaign, Identity, Indicator, Malware, Relationship\n",
+ "\n",
+ "mem = MemoryStore()\n",
+ "cam = Campaign(name='Charge', description='Attack!')\n",
+ "idy = Identity(name='John Doe', identity_class=\"individual\")\n",
+ "ind = Indicator(labels=['malicious-activity'], pattern=\"[file:hashes.MD5 = 'd41d8cd98f00b204e9800998ecf8427e']\")\n",
+ "mal = Malware(labels=['ransomware'], name=\"Cryptolocker\", created_by_ref=idy)\n",
+ "rel1 = Relationship(ind, 'indicates', mal,)\n",
+ "rel2 = Relationship(mal, 'targets', idy)\n",
+ "rel3 = Relationship(cam, 'uses', mal)\n",
+ "mem.add([cam, idy, ind, mal, rel1, rel2, rel3])"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "If a STIX object has a `created_by_ref` property, you can use the [creator_of()](../api/stix2.sources.rst#stix2.sources.DataSource.creator_of) method to retrieve the [Identity](../api/stix2.v20.sdo.rst#stix2.v20.sdo.Identity) object that created it."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 14,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/html": [
+ "<style type=\"text/css\">.highlight .hll { background-color: #ffffcc }\n",
+ ".highlight { background: #f8f8f8; }\n",
+ ".highlight .c { color: #408080; font-style: italic } /* Comment */\n",
+ ".highlight .err { border: 1px solid #FF0000 } /* Error */\n",
+ ".highlight .k { color: #008000; font-weight: bold } /* Keyword */\n",
+ ".highlight .o { color: #666666 } /* Operator */\n",
+ ".highlight .ch { color: #408080; font-style: italic } /* Comment.Hashbang */\n",
+ ".highlight .cm { color: #408080; font-style: italic } /* Comment.Multiline */\n",
+ ".highlight .cp { color: #BC7A00 } /* Comment.Preproc */\n",
+ ".highlight .cpf { color: #408080; font-style: italic } /* Comment.PreprocFile */\n",
+ ".highlight .c1 { color: #408080; font-style: italic } /* Comment.Single */\n",
+ ".highlight .cs { color: #408080; font-style: italic } /* Comment.Special */\n",
+ ".highlight .gd { color: #A00000 } /* Generic.Deleted */\n",
+ ".highlight .ge { font-style: italic } /* Generic.Emph */\n",
+ ".highlight .gr { color: #FF0000 } /* Generic.Error */\n",
+ ".highlight .gh { color: #000080; font-weight: bold } /* Generic.Heading */\n",
+ ".highlight .gi { color: #00A000 } /* Generic.Inserted */\n",
+ ".highlight .go { color: #888888 } /* Generic.Output */\n",
+ ".highlight .gp { color: #000080; font-weight: bold } /* Generic.Prompt */\n",
+ ".highlight .gs { font-weight: bold } /* Generic.Strong */\n",
+ ".highlight .gu { color: #800080; font-weight: bold } /* Generic.Subheading */\n",
+ ".highlight .gt { color: #0044DD } /* Generic.Traceback */\n",
+ ".highlight .kc { color: #008000; font-weight: bold } /* Keyword.Constant */\n",
+ ".highlight .kd { color: #008000; font-weight: bold } /* Keyword.Declaration */\n",
+ ".highlight .kn { color: #008000; font-weight: bold } /* Keyword.Namespace */\n",
+ ".highlight .kp { color: #008000 } /* Keyword.Pseudo */\n",
+ ".highlight .kr { color: #008000; font-weight: bold } /* Keyword.Reserved */\n",
+ ".highlight .kt { color: #B00040 } /* Keyword.Type */\n",
+ ".highlight .m { color: #666666 } /* Literal.Number */\n",
+ ".highlight .s { color: #BA2121 } /* Literal.String */\n",
+ ".highlight .na { color: #7D9029 } /* Name.Attribute */\n",
+ ".highlight .nb { color: #008000 } /* Name.Builtin */\n",
+ ".highlight .nc { color: #0000FF; font-weight: bold } /* Name.Class */\n",
+ ".highlight .no { color: #880000 } /* Name.Constant */\n",
+ ".highlight .nd { color: #AA22FF } /* Name.Decorator */\n",
+ ".highlight .ni { color: #999999; font-weight: bold } /* Name.Entity */\n",
+ ".highlight .ne { color: #D2413A; font-weight: bold } /* Name.Exception */\n",
+ ".highlight .nf { color: #0000FF } /* Name.Function */\n",
+ ".highlight .nl { color: #A0A000 } /* Name.Label */\n",
+ ".highlight .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */\n",
+ ".highlight .nt { color: #008000; font-weight: bold } /* Name.Tag */\n",
+ ".highlight .nv { color: #19177C } /* Name.Variable */\n",
+ ".highlight .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */\n",
+ ".highlight .w { color: #bbbbbb } /* Text.Whitespace */\n",
+ ".highlight .mb { color: #666666 } /* Literal.Number.Bin */\n",
+ ".highlight .mf { color: #666666 } /* Literal.Number.Float */\n",
+ ".highlight .mh { color: #666666 } /* Literal.Number.Hex */\n",
+ ".highlight .mi { color: #666666 } /* Literal.Number.Integer */\n",
+ ".highlight .mo { color: #666666 } /* Literal.Number.Oct */\n",
+ ".highlight .sa { color: #BA2121 } /* Literal.String.Affix */\n",
+ ".highlight .sb { color: #BA2121 } /* Literal.String.Backtick */\n",
+ ".highlight .sc { color: #BA2121 } /* Literal.String.Char */\n",
+ ".highlight .dl { color: #BA2121 } /* Literal.String.Delimiter */\n",
+ ".highlight .sd { color: #BA2121; font-style: italic } /* Literal.String.Doc */\n",
+ ".highlight .s2 { color: #BA2121 } /* Literal.String.Double */\n",
+ ".highlight .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */\n",
+ ".highlight .sh { color: #BA2121 } /* Literal.String.Heredoc */\n",
+ ".highlight .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */\n",
+ ".highlight .sx { color: #008000 } /* Literal.String.Other */\n",
+ ".highlight .sr { color: #BB6688 } /* Literal.String.Regex */\n",
+ ".highlight .s1 { color: #BA2121 } /* Literal.String.Single */\n",
+ ".highlight .ss { color: #19177C } /* Literal.String.Symbol */\n",
+ ".highlight .bp { color: #008000 } /* Name.Builtin.Pseudo */\n",
+ ".highlight .fm { color: #0000FF } /* Name.Function.Magic */\n",
+ ".highlight .vc { color: #19177C } /* Name.Variable.Class */\n",
+ ".highlight .vg { color: #19177C } /* Name.Variable.Global */\n",
+ ".highlight .vi { color: #19177C } /* Name.Variable.Instance */\n",
+ ".highlight .vm { color: #19177C } /* Name.Variable.Magic */\n",
+ ".highlight .il { color: #666666 } /* Literal.Number.Integer.Long */</style><div class=\"highlight\"><pre><span></span><span class=\"p\">{</span>\n",
+ " <span class=\"nt\">"type"</span><span class=\"p\">:</span> <span class=\"s2\">"identity"</span><span class=\"p\">,</span>\n",
+ " <span class=\"nt\">"id"</span><span class=\"p\">:</span> <span class=\"s2\">"identity--be3baac0-9aba-48a8-81e4-4408b1c379a8"</span><span class=\"p\">,</span>\n",
+ " <span class=\"nt\">"created"</span><span class=\"p\">:</span> <span class=\"s2\">"2017-11-21T22:14:45.213Z"</span><span class=\"p\">,</span>\n",
+ " <span class=\"nt\">"modified"</span><span class=\"p\">:</span> <span class=\"s2\">"2017-11-21T22:14:45.213Z"</span><span class=\"p\">,</span>\n",
+ " <span class=\"nt\">"name"</span><span class=\"p\">:</span> <span class=\"s2\">"John Doe"</span><span class=\"p\">,</span>\n",
+ " <span class=\"nt\">"identity_class"</span><span class=\"p\">:</span> <span class=\"s2\">"individual"</span>\n",
+ "<span class=\"p\">}</span>\n",
+ "</pre></div>\n"
+ ],
+ "text/plain": [
+ "<IPython.core.display.HTML object>"
+ ]
+ },
+ "execution_count": 14,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "print(mem.creator_of(mal))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Use the [relationships()](../api/stix2.sources.rst#stix2.sources.DataSource.relationships) method to retrieve all the relationship objects that reference a STIX object."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 15,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "3"
+ ]
+ },
+ "execution_count": 15,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "rels = mem.relationships(mal)\n",
+ "len(rels)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "You can limit it to only specific relationship types:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 27,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "[Relationship(type='relationship', id='relationship--bd6fd399-c907-4feb-b1da-b90f15942f1d', created='2017-11-21T22:14:45.214Z', modified='2017-11-21T22:14:45.214Z', relationship_type=u'indicates', source_ref='indicator--5ee33ff0-c50d-456b-a8dd-b5d1b69a66e8', target_ref='malware--66c0bc78-4e27-4d80-a565-a07e6eb6fba4')]"
+ ]
+ },
+ "execution_count": 27,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "mem.relationships(mal, relationship_type='indicates')"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "You can limit it to only relationships where the given object is the source:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 28,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "[Relationship(type='relationship', id='relationship--7eb7f5cd-8bf2-4f7c-8756-84c0b5693b9a', created='2017-11-21T22:14:45.215Z', modified='2017-11-21T22:14:45.215Z', relationship_type=u'targets', source_ref='malware--66c0bc78-4e27-4d80-a565-a07e6eb6fba4', target_ref='identity--be3baac0-9aba-48a8-81e4-4408b1c379a8')]"
+ ]
+ },
+ "execution_count": 28,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "mem.relationships(mal, source_only=True)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "And you can limit it to only relationships where the given object is the target:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 30,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "[Relationship(type='relationship', id='relationship--bd6fd399-c907-4feb-b1da-b90f15942f1d', created='2017-11-21T22:14:45.214Z', modified='2017-11-21T22:14:45.214Z', relationship_type=u'indicates', source_ref='indicator--5ee33ff0-c50d-456b-a8dd-b5d1b69a66e8', target_ref='malware--66c0bc78-4e27-4d80-a565-a07e6eb6fba4'),\n",
+ " Relationship(type='relationship', id='relationship--3c759d40-c92a-430e-aab6-77d5c5763302', created='2017-11-21T22:14:45.215Z', modified='2017-11-21T22:14:45.215Z', relationship_type=u'uses', source_ref='campaign--82ab7aa4-d13b-4e99-8a09-ebcba30668a7', target_ref='malware--66c0bc78-4e27-4d80-a565-a07e6eb6fba4')]"
+ ]
+ },
+ "execution_count": 30,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "mem.relationships(mal, target_only=True)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Finally, you can retrieve all STIX objects related to a given STIX object using [related_to()](../api/stix2.sources.rst#stix2.sources.DataSource.related_to). This calls [relationships()](../api/stix2.sources.rst#stix2.sources.DataSource.relationships) but then performs the extra step of getting the objects that these Relationships point to. [related_to()](../api/stix2.sources.rst#stix2.sources.DataSource.related_to) takes all the same arguments that [relationships()](../api/stix2.sources.rst#stix2.sources.DataSource.relationships) does."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 42,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "[Campaign(type='campaign', id='campaign--82ab7aa4-d13b-4e99-8a09-ebcba30668a7', created='2017-11-21T22:14:45.213Z', modified='2017-11-21T22:14:45.213Z', name=u'Charge', description=u'Attack!')]"
+ ]
+ },
+ "execution_count": 42,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "mem.related_to(mal, target_only=True, relationship_type='uses')"
+ ]
}
],
"metadata": {
diff --git a/docs/guide/environment.ipynb b/docs/guide/environment.ipynb
index 2d85911..0cb5796 100644
--- a/docs/guide/environment.ipynb
+++ b/docs/guide/environment.ipynb
@@ -128,7 +128,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "You can retrieve STIX objects from the [DataSources](../api/stix2.sources.rst#stix2.sources.DataSource) in the [Environment](../api/stix2.environment.rst#stix2.environment.Environment) with [get()](../api/stix2.environment.rst#stix2.environment.Environment.get), [query()](../api/stix2.environment.rst#stix2.environment.Environment.query), and [all_versions()](../api/stix2.environment.rst#stix2.environment.Environment.all_versions), just as you would for a [DataSource](../api/stix2.sources.rst#stix2.sources.DataSource)."
+ "You can retrieve STIX objects from the [DataSources](../api/stix2.sources.rst#stix2.sources.DataSource) in the [Environment](../api/stix2.environment.rst#stix2.environment.Environment) with [get()](../api/stix2.environment.rst#stix2.environment.Environment.get), [query()](../api/stix2.environment.rst#stix2.environment.Environment.query), [all_versions()](../api/stix2.environment.rst#stix2.environment.Environment.all_versions), [creator_of()](../api/stix2.sources.rst#stix2.sources.DataSource.creator_of), [related_to()](../api/stix2.sources.rst#stix2.sources.DataSource.related_to), and [relationships()](../api/stix2.sources.rst#stix2.sources.DataSource.relationships) just as you would for a [DataSource](../api/stix2.sources.rst#stix2.sources.DataSource)."
]
},
{
diff --git a/stix2/environment.py b/stix2/environment.py
index 64a73b1..ab16b09 100644
--- a/stix2/environment.py
+++ b/stix2/environment.py
@@ -105,30 +105,13 @@ class Environment(object):
return self.factory.create(*args, **kwargs)
create.__doc__ = ObjectFactory.create.__doc__
- def get(self, *args, **kwargs):
- try:
- return self.source.get(*args, **kwargs)
- except AttributeError:
- raise AttributeError('Environment has no data source to query')
- get.__doc__ = DataStore.get.__doc__
-
- def all_versions(self, *args, **kwargs):
- """Retrieve all versions of a single STIX object by ID.
- """
- try:
- return self.source.all_versions(*args, **kwargs)
- except AttributeError:
- raise AttributeError('Environment has no data source to query')
- all_versions.__doc__ = DataStore.all_versions.__doc__
-
- def query(self, *args, **kwargs):
- """Retrieve STIX objects matching a set of filters.
- """
- try:
- return self.source.query(*args, **kwargs)
- except AttributeError:
- raise AttributeError('Environment has no data source to query')
- query.__doc__ = DataStore.query.__doc__
+ get = DataStore.__dict__['get']
+ all_versions = DataStore.__dict__['all_versions']
+ query = DataStore.__dict__['query']
+ creator_of = DataStore.__dict__['creator_of']
+ relationships = DataStore.__dict__['relationships']
+ related_to = DataStore.__dict__['related_to']
+ add = DataStore.__dict__['add']
def add_filters(self, *args, **kwargs):
try:
@@ -142,31 +125,6 @@ class Environment(object):
except AttributeError:
raise AttributeError('Environment has no data source')
- def add(self, *args, **kwargs):
- try:
- return self.sink.add(*args, **kwargs)
- except AttributeError:
- raise AttributeError('Environment has no data sink to put objects in')
- add.__doc__ = DataStore.add.__doc__
-
def parse(self, *args, **kwargs):
return _parse(*args, **kwargs)
parse.__doc__ = _parse.__doc__
-
- def creator_of(self, obj):
- """Retrieve the Identity refered to by the object's `created_by_ref`.
-
- Args:
- obj: The STIX object whose `created_by_ref` property will be looked
- up.
-
- Returns:
- The STIX object's creator, or None, if the object contains no
- `created_by_ref` property or the object's creator cannot be found.
-
- """
- creator_id = obj.get('created_by_ref', '')
- if creator_id:
- return self.get(creator_id)
- else:
- return None
diff --git a/stix2/sources/__init__.py b/stix2/sources/__init__.py
index b3e8a29..adc6def 100644
--- a/stix2/sources/__init__.py
+++ b/stix2/sources/__init__.py
@@ -16,6 +16,7 @@ import uuid
from six import with_metaclass
+from stix2.sources.filters import Filter
from stix2.utils import deduplicate
@@ -58,7 +59,10 @@ class DataStore(object):
object specified by the "id".
"""
- return self.source.get(*args, **kwargs)
+ try:
+ return self.source.get(*args, **kwargs)
+ except AttributeError:
+ raise AttributeError('%s has no data source to query' % self.__class__.__name__)
def all_versions(self, *args, **kwargs):
"""Retrieve all versions of a single STIX object by ID.
@@ -72,7 +76,10 @@ class DataStore(object):
stix_objs (list): a list of STIX objects
"""
- return self.source.all_versions(*args, **kwargs)
+ try:
+ return self.source.all_versions(*args, **kwargs)
+ except AttributeError:
+ raise AttributeError('%s has no data source to query' % self.__class__.__name__)
def query(self, *args, **kwargs):
"""Retrieve STIX objects matching a set of filters.
@@ -87,7 +94,83 @@ class DataStore(object):
stix_objs (list): a list of STIX objects
"""
- return self.source.query(*args, **kwargs)
+ try:
+ return self.source.query(*args, **kwargs)
+ except AttributeError:
+ raise AttributeError('%s has no data source to query' % self.__class__.__name__)
+
+ def creator_of(self, *args, **kwargs):
+ """Retrieve the Identity refered to by the object's `created_by_ref`.
+
+ Translate creator_of() call to the appropriate DataSource call.
+
+ Args:
+ obj: The STIX object whose `created_by_ref` property will be looked
+ up.
+
+ Returns:
+ The STIX object's creator, or None, if the object contains no
+ `created_by_ref` property or the object's creator cannot be found.
+
+ """
+ try:
+ return self.source.creator_of(*args, **kwargs)
+ except AttributeError:
+ raise AttributeError('%s has no data source to query' % self.__class__.__name__)
+
+ def relationships(self, *args, **kwargs):
+ """Retrieve Relationships involving the given STIX object.
+
+ Translate relationships() call to the appropriate DataSource call.
+
+ Only one of `source_only` and `target_only` may be `True`.
+
+ Args:
+ obj (STIX object OR dict OR str): The STIX object (or its ID) whose
+ relationships will be looked up.
+ relationship_type (str): Only retrieve Relationships of this type.
+ If None, all relationships will be returned, regardless of type.
+ source_only (bool): Only retrieve Relationships for which this
+ object is the source_ref. Default: False.
+ target_only (bool): Only retrieve Relationships for which this
+ object is the target_ref. Default: False.
+
+ Returns:
+ (list): List of Relationship objects involving the given STIX object.
+
+ """
+ try:
+ return self.source.relationships(*args, **kwargs)
+ except AttributeError:
+ raise AttributeError('%s has no data source to query' % self.__class__.__name__)
+
+ def related_to(self, *args, **kwargs):
+ """Retrieve STIX Objects that have a Relationship involving the given
+ STIX object.
+
+ Translate related_to() call to the appropriate DataSource call.
+
+ Only one of `source_only` and `target_only` may be `True`.
+
+ Args:
+ obj (STIX object OR dict OR str): The STIX object (or its ID) whose
+ related objects will be looked up.
+ relationship_type (str): Only retrieve objects related by this
+ Relationships type. If None, all related objects will be
+ returned, regardless of type.
+ source_only (bool): Only examine Relationships for which this
+ object is the source_ref. Default: False.
+ target_only (bool): Only examine Relationships for which this
+ object is the target_ref. Default: False.
+
+ Returns:
+ (list): List of STIX objects related to the given STIX object.
+
+ """
+ try:
+ return self.source.related_to(*args, **kwargs)
+ except AttributeError:
+ raise AttributeError('%s has no data source to query' % self.__class__.__name__)
def add(self, *args, **kwargs):
"""Method for storing STIX objects.
@@ -99,7 +182,10 @@ class DataStore(object):
stix_objs (list): a list of STIX objects
"""
- return self.sink.add(*args, **kwargs)
+ try:
+ return self.sink.add(*args, **kwargs)
+ except AttributeError:
+ raise AttributeError('%s has no data sink to put objects in' % self.__class__.__name__)
class DataSink(with_metaclass(ABCMeta)):
@@ -191,6 +277,108 @@ class DataSource(with_metaclass(ABCMeta)):
"""
+ def creator_of(self, obj):
+ """Retrieve the Identity refered to by the object's `created_by_ref`.
+
+ Args:
+ obj: The STIX object whose `created_by_ref` property will be looked
+ up.
+
+ Returns:
+ The STIX object's creator, or None, if the object contains no
+ `created_by_ref` property or the object's creator cannot be found.
+
+ """
+ creator_id = obj.get('created_by_ref', '')
+ if creator_id:
+ return self.get(creator_id)
+ else:
+ return None
+
+ def relationships(self, obj, relationship_type=None, source_only=False, target_only=False):
+ """Retrieve Relationships involving the given STIX object.
+
+ Only one of `source_only` and `target_only` may be `True`.
+
+ Args:
+ obj (STIX object OR dict OR str): The STIX object (or its ID) whose
+ relationships will be looked up.
+ relationship_type (str): Only retrieve Relationships of this type.
+ If None, all relationships will be returned, regardless of type.
+ source_only (bool): Only retrieve Relationships for which this
+ object is the source_ref. Default: False.
+ target_only (bool): Only retrieve Relationships for which this
+ object is the target_ref. Default: False.
+
+ Returns:
+ (list): List of Relationship objects involving the given STIX object.
+
+ """
+ results = []
+ filters = [Filter('type', '=', 'relationship')]
+
+ try:
+ obj_id = obj['id']
+ except KeyError:
+ raise ValueError("STIX object has no 'id' property")
+ except TypeError:
+ # Assume `obj` is an ID string
+ obj_id = obj
+
+ if relationship_type:
+ filters.append(Filter('relationship_type', '=', relationship_type))
+
+ if source_only and target_only:
+ raise ValueError("Search either source only or target only, but not both")
+
+ if not target_only:
+ results.extend(self.query(filters + [Filter('source_ref', '=', obj_id)]))
+ if not source_only:
+ results.extend(self.query(filters + [Filter('target_ref', '=', obj_id)]))
+
+ return results
+
+ def related_to(self, obj, relationship_type=None, source_only=False, target_only=False):
+ """Retrieve STIX Objects that have a Relationship involving the given
+ STIX object.
+
+ Only one of `source_only` and `target_only` may be `True`.
+
+ Args:
+ obj (STIX object OR dict OR str): The STIX object (or its ID) whose
+ related objects will be looked up.
+ relationship_type (str): Only retrieve objects related by this
+ Relationships type. If None, all related objects will be
+ returned, regardless of type.
+ source_only (bool): Only examine Relationships for which this
+ object is the source_ref. Default: False.
+ target_only (bool): Only examine Relationships for which this
+ object is the target_ref. Default: False.
+
+ Returns:
+ (list): List of STIX objects related to the given STIX object.
+
+ """
+ results = []
+ rels = self.relationships(obj, relationship_type, source_only, target_only)
+
+ try:
+ obj_id = obj['id']
+ except TypeError:
+ # Assume `obj` is an ID string
+ obj_id = obj
+
+ # Get all unique ids from the relationships except that of the object
+ ids = set()
+ for r in rels:
+ ids.update((r.source_ref, r.target_ref))
+ ids.remove(obj_id)
+
+ for i in ids:
+ results.append(self.get(i))
+
+ return results
+
class CompositeDataSource(DataSource):
"""Controller for all the attached DataSources.
@@ -354,6 +542,80 @@ class CompositeDataSource(DataSource):
return all_data
+ def relationships(self, *args, **kwargs):
+ """Retrieve Relationships involving the given STIX object.
+
+ Only one of `source_only` and `target_only` may be `True`.
+
+ Federated relationships retrieve method - iterates through all
+ DataSources defined in "data_sources".
+
+ Args:
+ obj (STIX object OR dict OR str): The STIX object (or its ID) whose
+ relationships will be looked up.
+ relationship_type (str): Only retrieve Relationships of this type.
+ If None, all relationships will be returned, regardless of type.
+ source_only (bool): Only retrieve Relationships for which this
+ object is the source_ref. Default: False.
+ target_only (bool): Only retrieve Relationships for which this
+ object is the target_ref. Default: False.
+
+ Returns:
+ (list): List of Relationship objects involving the given STIX object.
+
+ """
+ if not self.has_data_sources():
+ raise AttributeError('CompositeDataSource has no data sources')
+
+ results = []
+ for ds in self.data_sources:
+ results.extend(ds.relationships(*args, **kwargs))
+
+ # remove exact duplicates (where duplicates are STIX 2.0
+ # objects with the same 'id' and 'modified' values)
+ if len(results) > 0:
+ results = deduplicate(results)
+
+ return results
+
+ def related_to(self, *args, **kwargs):
+ """Retrieve STIX Objects that have a Relationship involving the given
+ STIX object.
+
+ Only one of `source_only` and `target_only` may be `True`.
+
+ Federated related objects method - iterates through all
+ DataSources defined in "data_sources".
+
+ Args:
+ obj (STIX object OR dict OR str): The STIX object (or its ID) whose
+ related objects will be looked up.
+ relationship_type (str): Only retrieve objects related by this
+ Relationships type. If None, all related objects will be
+ returned, regardless of type.
+ source_only (bool): Only examine Relationships for which this
+ object is the source_ref. Default: False.
+ target_only (bool): Only examine Relationships for which this
+ object is the target_ref. Default: False.
+
+ Returns:
+ (list): List of STIX objects related to the given STIX object.
+
+ """
+ if not self.has_data_sources():
+ raise AttributeError('CompositeDataSource has no data sources')
+
+ results = []
+ for ds in self.data_sources:
+ results.extend(ds.related_to(*args, **kwargs))
+
+ # remove exact duplicates (where duplicates are STIX 2.0
+ # objects with the same 'id' and 'modified' values)
+ if len(results) > 0:
+ results = deduplicate(results)
+
+ return results
+
def add_data_source(self, data_source):
"""Attach a DataSource to CompositeDataSource instance
diff --git a/stix2/sources/filters.py b/stix2/sources/filters.py
index 5772112..5af48cd 100644
--- a/stix2/sources/filters.py
+++ b/stix2/sources/filters.py
@@ -10,6 +10,11 @@ FILTER_OPS = ['=', '!=', 'in', '>', '<', '>=', '<=']
"""Supported filter value types"""
FILTER_VALUE_TYPES = [bool, dict, float, int, list, str, tuple]
+try:
+ FILTER_VALUE_TYPES.append(unicode)
+except NameError:
+ # Python 3 doesn't need to worry about unicode
+ pass
def _check_filter_components(prop, op, value):
| Add functions to get related objects
In preparation for the Workbench layer, the Environment API should have some functions to explore/retrieve/dereference related objects. This would include something like `created_by()` (for `created_by_ref`) and `relationships()`. `relationships()` might have parameters like `source_only`, `target_only`, and `relationship_type`.
We will need to modify Filters to allow filtering on non-common properties first, however, as we cannot currently filter on `source_ref` and `target_ref`.
Steps:
- [x] `created_by()`/`creator_of()`
- [x] filters
- [ ] `relationships()`
- [ ] `related_to()` | oasis-open/cti-python-stix2 | diff --git a/stix2/test/constants.py b/stix2/test/constants.py
index 839b547..3db39d6 100644
--- a/stix2/test/constants.py
+++ b/stix2/test/constants.py
@@ -28,6 +28,18 @@ MARKING_IDS = [
"marking-definition--68520ae2-fefe-43a9-84ee-2c2a934d2c7d",
"marking-definition--2802dfb1-1019-40a8-8848-68d0ec0e417f",
]
+RELATIONSHIP_IDS = [
+ 'relationship--06520621-5352-4e6a-b976-e8fa3d437ffd',
+ 'relationship--181c9c09-43e6-45dd-9374-3bec192f05ef',
+ 'relationship--a0cbb21c-8daf-4a7f-96aa-7155a4ef8f70'
+]
+
+# All required args for a Campaign instance
+CAMPAIGN_KWARGS = dict(
+ name="Green Group Attacks Against Finance",
+ description="Campaign by Green Group against a series of targets in the financial services sector.",
+)
+
# All required args for a Campaign instance, plus some optional args
CAMPAIGN_MORE_KWARGS = dict(
diff --git a/stix2/test/test_data_sources.py b/stix2/test/test_data_sources.py
index ef0cf26..d7f238a 100644
--- a/stix2/test/test_data_sources.py
+++ b/stix2/test/test_data_sources.py
@@ -547,3 +547,11 @@ def test_composite_datasource_operations():
# nothing returns the same as cds1.query(query1) (the associated query is query2)
results = cds1.query([])
assert len(results) == 3
+
+
+def test_composite_datastore_no_datasource():
+ cds = CompositeDataSource()
+
+ with pytest.raises(AttributeError) as excinfo:
+ cds.get("indicator--d81f86b9-975b-bc0b-775e-810c5ad45a4f")
+ assert 'CompositeDataSource has no data source' in str(excinfo.value)
diff --git a/stix2/test/test_environment.py b/stix2/test/test_environment.py
index c669a33..84ca803 100644
--- a/stix2/test/test_environment.py
+++ b/stix2/test/test_environment.py
@@ -2,8 +2,22 @@ import pytest
import stix2
-from .constants import (FAKE_TIME, IDENTITY_ID, IDENTITY_KWARGS, INDICATOR_ID,
- INDICATOR_KWARGS, MALWARE_ID)
+from .constants import (CAMPAIGN_ID, CAMPAIGN_KWARGS, FAKE_TIME, IDENTITY_ID,
+ IDENTITY_KWARGS, INDICATOR_ID, INDICATOR_KWARGS,
+ MALWARE_ID, MALWARE_KWARGS, RELATIONSHIP_IDS)
+
+
[email protected]
+def ds():
+ cam = stix2.Campaign(id=CAMPAIGN_ID, **CAMPAIGN_KWARGS)
+ idy = stix2.Identity(id=IDENTITY_ID, **IDENTITY_KWARGS)
+ ind = stix2.Indicator(id=INDICATOR_ID, **INDICATOR_KWARGS)
+ mal = stix2.Malware(id=MALWARE_ID, **MALWARE_KWARGS)
+ rel1 = stix2.Relationship(ind, 'indicates', mal, id=RELATIONSHIP_IDS[0])
+ rel2 = stix2.Relationship(mal, 'targets', idy, id=RELATIONSHIP_IDS[1])
+ rel3 = stix2.Relationship(cam, 'uses', mal, id=RELATIONSHIP_IDS[2])
+ stix_objs = [cam, idy, ind, mal, rel1, rel2, rel3]
+ yield stix2.MemoryStore(stix_objs)
def test_object_factory_created_by_ref_str():
@@ -150,6 +164,14 @@ def test_environment_no_datastore():
env.query(INDICATOR_ID)
assert 'Environment has no data source' in str(excinfo.value)
+ with pytest.raises(AttributeError) as excinfo:
+ env.relationships(INDICATOR_ID)
+ assert 'Environment has no data source' in str(excinfo.value)
+
+ with pytest.raises(AttributeError) as excinfo:
+ env.related_to(INDICATOR_ID)
+ assert 'Environment has no data source' in str(excinfo.value)
+
def test_environment_add_filters():
env = stix2.Environment(factory=stix2.ObjectFactory())
@@ -186,7 +208,7 @@ def test_parse_malware():
assert mal.name == "Cryptolocker"
-def test_created_by():
+def test_creator_of():
identity = stix2.Identity(**IDENTITY_KWARGS)
factory = stix2.ObjectFactory(created_by_ref=identity.id)
env = stix2.Environment(store=stix2.MemoryStore(), factory=factory)
@@ -197,7 +219,7 @@ def test_created_by():
assert creator is identity
-def test_created_by_no_datasource():
+def test_creator_of_no_datasource():
identity = stix2.Identity(**IDENTITY_KWARGS)
factory = stix2.ObjectFactory(created_by_ref=identity.id)
env = stix2.Environment(factory=factory)
@@ -208,7 +230,7 @@ def test_created_by_no_datasource():
assert 'Environment has no data source' in str(excinfo.value)
-def test_created_by_not_found():
+def test_creator_of_not_found():
identity = stix2.Identity(**IDENTITY_KWARGS)
factory = stix2.ObjectFactory(created_by_ref=identity.id)
env = stix2.Environment(store=stix2.MemoryStore(), factory=factory)
@@ -216,3 +238,113 @@ def test_created_by_not_found():
ind = env.create(stix2.Indicator, **INDICATOR_KWARGS)
creator = env.creator_of(ind)
assert creator is None
+
+
+def test_creator_of_no_created_by_ref():
+ env = stix2.Environment(store=stix2.MemoryStore())
+ ind = env.create(stix2.Indicator, **INDICATOR_KWARGS)
+ creator = env.creator_of(ind)
+ assert creator is None
+
+
+def test_relationships(ds):
+ env = stix2.Environment(store=ds)
+ mal = env.get(MALWARE_ID)
+ resp = env.relationships(mal)
+
+ assert len(resp) == 3
+ assert any(x['id'] == RELATIONSHIP_IDS[0] for x in resp)
+ assert any(x['id'] == RELATIONSHIP_IDS[1] for x in resp)
+ assert any(x['id'] == RELATIONSHIP_IDS[2] for x in resp)
+
+
+def test_relationships_no_id(ds):
+ env = stix2.Environment(store=ds)
+ mal = {
+ "type": "malware",
+ "name": "some variant"
+ }
+ with pytest.raises(ValueError) as excinfo:
+ env.relationships(mal)
+ assert "object has no 'id' property" in str(excinfo.value)
+
+
+def test_relationships_by_type(ds):
+ env = stix2.Environment(store=ds)
+ mal = env.get(MALWARE_ID)
+ resp = env.relationships(mal, relationship_type='indicates')
+
+ assert len(resp) == 1
+ assert resp[0]['id'] == RELATIONSHIP_IDS[0]
+
+
+def test_relationships_by_source(ds):
+ env = stix2.Environment(store=ds)
+ resp = env.relationships(MALWARE_ID, source_only=True)
+
+ assert len(resp) == 1
+ assert resp[0]['id'] == RELATIONSHIP_IDS[1]
+
+
+def test_relationships_by_target(ds):
+ env = stix2.Environment(store=ds)
+ resp = env.relationships(MALWARE_ID, target_only=True)
+
+ assert len(resp) == 2
+ assert any(x['id'] == RELATIONSHIP_IDS[0] for x in resp)
+ assert any(x['id'] == RELATIONSHIP_IDS[2] for x in resp)
+
+
+def test_relationships_by_target_and_type(ds):
+ env = stix2.Environment(store=ds)
+ resp = env.relationships(MALWARE_ID, relationship_type='uses', target_only=True)
+
+ assert len(resp) == 1
+ assert any(x['id'] == RELATIONSHIP_IDS[2] for x in resp)
+
+
+def test_relationships_by_target_and_source(ds):
+ env = stix2.Environment(store=ds)
+ with pytest.raises(ValueError) as excinfo:
+ env.relationships(MALWARE_ID, target_only=True, source_only=True)
+
+ assert 'not both' in str(excinfo.value)
+
+
+def test_related_to(ds):
+ env = stix2.Environment(store=ds)
+ mal = env.get(MALWARE_ID)
+ resp = env.related_to(mal)
+
+ assert len(resp) == 3
+ assert any(x['id'] == CAMPAIGN_ID for x in resp)
+ assert any(x['id'] == INDICATOR_ID for x in resp)
+ assert any(x['id'] == IDENTITY_ID for x in resp)
+
+
+def test_related_to_no_id(ds):
+ env = stix2.Environment(store=ds)
+ mal = {
+ "type": "malware",
+ "name": "some variant"
+ }
+ with pytest.raises(ValueError) as excinfo:
+ env.related_to(mal)
+ assert "object has no 'id' property" in str(excinfo.value)
+
+
+def test_related_to_by_source(ds):
+ env = stix2.Environment(store=ds)
+ resp = env.related_to(MALWARE_ID, source_only=True)
+
+ assert len(resp) == 1
+ assert resp[0]['id'] == IDENTITY_ID
+
+
+def test_related_to_by_target(ds):
+ env = stix2.Environment(store=ds)
+ resp = env.related_to(MALWARE_ID, target_only=True)
+
+ assert len(resp) == 2
+ assert any(x['id'] == CAMPAIGN_ID for x in resp)
+ assert any(x['id'] == INDICATOR_ID for x in resp)
diff --git a/stix2/test/test_filesystem.py b/stix2/test/test_filesystem.py
index 85f6966..68fc185 100644
--- a/stix2/test/test_filesystem.py
+++ b/stix2/test/test_filesystem.py
@@ -4,7 +4,12 @@ import shutil
import pytest
from stix2 import (Bundle, Campaign, CustomObject, FileSystemSink,
- FileSystemSource, FileSystemStore, Filter, properties)
+ FileSystemSource, FileSystemStore, Filter, Identity,
+ Indicator, Malware, Relationship, properties)
+
+from .constants import (CAMPAIGN_ID, CAMPAIGN_KWARGS, IDENTITY_ID,
+ IDENTITY_KWARGS, INDICATOR_ID, INDICATOR_KWARGS,
+ MALWARE_ID, MALWARE_KWARGS, RELATIONSHIP_IDS)
FS_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)), "stix2_data")
@@ -40,6 +45,25 @@ def fs_sink():
shutil.rmtree(os.path.join(FS_PATH, "campaign"), True)
[email protected](scope='module')
+def rel_fs_store():
+ cam = Campaign(id=CAMPAIGN_ID, **CAMPAIGN_KWARGS)
+ idy = Identity(id=IDENTITY_ID, **IDENTITY_KWARGS)
+ ind = Indicator(id=INDICATOR_ID, **INDICATOR_KWARGS)
+ mal = Malware(id=MALWARE_ID, **MALWARE_KWARGS)
+ rel1 = Relationship(ind, 'indicates', mal, id=RELATIONSHIP_IDS[0])
+ rel2 = Relationship(mal, 'targets', idy, id=RELATIONSHIP_IDS[1])
+ rel3 = Relationship(cam, 'uses', mal, id=RELATIONSHIP_IDS[2])
+ stix_objs = [cam, idy, ind, mal, rel1, rel2, rel3]
+ fs = FileSystemStore(FS_PATH)
+ for o in stix_objs:
+ fs.add(o)
+ yield fs
+
+ for o in stix_objs:
+ os.remove(os.path.join(FS_PATH, o.type, o.id + '.json'))
+
+
def test_filesystem_source_nonexistent_folder():
with pytest.raises(ValueError) as excinfo:
FileSystemSource('nonexistent-folder')
@@ -375,3 +399,75 @@ def test_filesystem_custom_object(fs_store):
# remove dir
shutil.rmtree(os.path.join(FS_PATH, "x-new-obj"), True)
+
+
+def test_relationships(rel_fs_store):
+ mal = rel_fs_store.get(MALWARE_ID)
+ resp = rel_fs_store.relationships(mal)
+
+ assert len(resp) == 3
+ assert any(x['id'] == RELATIONSHIP_IDS[0] for x in resp)
+ assert any(x['id'] == RELATIONSHIP_IDS[1] for x in resp)
+ assert any(x['id'] == RELATIONSHIP_IDS[2] for x in resp)
+
+
+def test_relationships_by_type(rel_fs_store):
+ mal = rel_fs_store.get(MALWARE_ID)
+ resp = rel_fs_store.relationships(mal, relationship_type='indicates')
+
+ assert len(resp) == 1
+ assert resp[0]['id'] == RELATIONSHIP_IDS[0]
+
+
+def test_relationships_by_source(rel_fs_store):
+ resp = rel_fs_store.relationships(MALWARE_ID, source_only=True)
+
+ assert len(resp) == 1
+ assert resp[0]['id'] == RELATIONSHIP_IDS[1]
+
+
+def test_relationships_by_target(rel_fs_store):
+ resp = rel_fs_store.relationships(MALWARE_ID, target_only=True)
+
+ assert len(resp) == 2
+ assert any(x['id'] == RELATIONSHIP_IDS[0] for x in resp)
+ assert any(x['id'] == RELATIONSHIP_IDS[2] for x in resp)
+
+
+def test_relationships_by_target_and_type(rel_fs_store):
+ resp = rel_fs_store.relationships(MALWARE_ID, relationship_type='uses', target_only=True)
+
+ assert len(resp) == 1
+ assert any(x['id'] == RELATIONSHIP_IDS[2] for x in resp)
+
+
+def test_relationships_by_target_and_source(rel_fs_store):
+ with pytest.raises(ValueError) as excinfo:
+ rel_fs_store.relationships(MALWARE_ID, target_only=True, source_only=True)
+
+ assert 'not both' in str(excinfo.value)
+
+
+def test_related_to(rel_fs_store):
+ mal = rel_fs_store.get(MALWARE_ID)
+ resp = rel_fs_store.related_to(mal)
+
+ assert len(resp) == 3
+ assert any(x['id'] == CAMPAIGN_ID for x in resp)
+ assert any(x['id'] == INDICATOR_ID for x in resp)
+ assert any(x['id'] == IDENTITY_ID for x in resp)
+
+
+def test_related_to_by_source(rel_fs_store):
+ resp = rel_fs_store.related_to(MALWARE_ID, source_only=True)
+
+ assert len(resp) == 1
+ assert any(x['id'] == IDENTITY_ID for x in resp)
+
+
+def test_related_to_by_target(rel_fs_store):
+ resp = rel_fs_store.related_to(MALWARE_ID, target_only=True)
+
+ assert len(resp) == 2
+ assert any(x['id'] == CAMPAIGN_ID for x in resp)
+ assert any(x['id'] == INDICATOR_ID for x in resp)
diff --git a/stix2/test/test_memory.py b/stix2/test/test_memory.py
index 6b1219e..a7d88a8 100644
--- a/stix2/test/test_memory.py
+++ b/stix2/test/test_memory.py
@@ -3,10 +3,15 @@ import shutil
import pytest
-from stix2 import (Bundle, Campaign, CustomObject, Filter, MemorySource,
- MemoryStore, properties)
+from stix2 import (Bundle, Campaign, CustomObject, Filter, Identity, Indicator,
+ Malware, MemorySource, MemoryStore, Relationship,
+ properties)
from stix2.sources import make_id
+from .constants import (CAMPAIGN_ID, CAMPAIGN_KWARGS, IDENTITY_ID,
+ IDENTITY_KWARGS, INDICATOR_ID, INDICATOR_KWARGS,
+ MALWARE_ID, MALWARE_KWARGS, RELATIONSHIP_IDS)
+
IND1 = {
"created": "2017-01-27T13:49:53.935Z",
"id": "indicator--d81f86b9-975b-bc0b-775e-810c5ad45a4f",
@@ -118,6 +123,19 @@ def mem_source():
yield MemorySource(STIX_OBJS1)
[email protected]
+def rel_mem_store():
+ cam = Campaign(id=CAMPAIGN_ID, **CAMPAIGN_KWARGS)
+ idy = Identity(id=IDENTITY_ID, **IDENTITY_KWARGS)
+ ind = Indicator(id=INDICATOR_ID, **INDICATOR_KWARGS)
+ mal = Malware(id=MALWARE_ID, **MALWARE_KWARGS)
+ rel1 = Relationship(ind, 'indicates', mal, id=RELATIONSHIP_IDS[0])
+ rel2 = Relationship(mal, 'targets', idy, id=RELATIONSHIP_IDS[1])
+ rel3 = Relationship(cam, 'uses', mal, id=RELATIONSHIP_IDS[2])
+ stix_objs = [cam, idy, ind, mal, rel1, rel2, rel3]
+ yield MemoryStore(stix_objs)
+
+
def test_memory_source_get(mem_source):
resp = mem_source.get("indicator--d81f86b8-975b-bc0b-775e-810c5ad45a4f")
assert resp["id"] == "indicator--d81f86b8-975b-bc0b-775e-810c5ad45a4f"
@@ -287,3 +305,75 @@ def test_memory_store_custom_object(mem_store):
newobj_r = mem_store.get(newobj.id)
assert newobj_r.id == newobj.id
assert newobj_r.property1 == 'something'
+
+
+def test_relationships(rel_mem_store):
+ mal = rel_mem_store.get(MALWARE_ID)
+ resp = rel_mem_store.relationships(mal)
+
+ assert len(resp) == 3
+ assert any(x['id'] == RELATIONSHIP_IDS[0] for x in resp)
+ assert any(x['id'] == RELATIONSHIP_IDS[1] for x in resp)
+ assert any(x['id'] == RELATIONSHIP_IDS[2] for x in resp)
+
+
+def test_relationships_by_type(rel_mem_store):
+ mal = rel_mem_store.get(MALWARE_ID)
+ resp = rel_mem_store.relationships(mal, relationship_type='indicates')
+
+ assert len(resp) == 1
+ assert resp[0]['id'] == RELATIONSHIP_IDS[0]
+
+
+def test_relationships_by_source(rel_mem_store):
+ resp = rel_mem_store.relationships(MALWARE_ID, source_only=True)
+
+ assert len(resp) == 1
+ assert resp[0]['id'] == RELATIONSHIP_IDS[1]
+
+
+def test_relationships_by_target(rel_mem_store):
+ resp = rel_mem_store.relationships(MALWARE_ID, target_only=True)
+
+ assert len(resp) == 2
+ assert any(x['id'] == RELATIONSHIP_IDS[0] for x in resp)
+ assert any(x['id'] == RELATIONSHIP_IDS[2] for x in resp)
+
+
+def test_relationships_by_target_and_type(rel_mem_store):
+ resp = rel_mem_store.relationships(MALWARE_ID, relationship_type='uses', target_only=True)
+
+ assert len(resp) == 1
+ assert any(x['id'] == RELATIONSHIP_IDS[2] for x in resp)
+
+
+def test_relationships_by_target_and_source(rel_mem_store):
+ with pytest.raises(ValueError) as excinfo:
+ rel_mem_store.relationships(MALWARE_ID, target_only=True, source_only=True)
+
+ assert 'not both' in str(excinfo.value)
+
+
+def test_related_to(rel_mem_store):
+ mal = rel_mem_store.get(MALWARE_ID)
+ resp = rel_mem_store.related_to(mal)
+
+ assert len(resp) == 3
+ assert any(x['id'] == CAMPAIGN_ID for x in resp)
+ assert any(x['id'] == INDICATOR_ID for x in resp)
+ assert any(x['id'] == IDENTITY_ID for x in resp)
+
+
+def test_related_to_by_source(rel_mem_store):
+ resp = rel_mem_store.related_to(MALWARE_ID, source_only=True)
+
+ assert len(resp) == 1
+ assert any(x['id'] == IDENTITY_ID for x in resp)
+
+
+def test_related_to_by_target(rel_mem_store):
+ resp = rel_mem_store.related_to(MALWARE_ID, target_only=True)
+
+ assert len(resp) == 2
+ assert any(x['id'] == CAMPAIGN_ID for x in resp)
+ assert any(x['id'] == INDICATOR_ID for x in resp)
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 1,
"test_score": 1
},
"num_modified_files": 5
} | 0.4 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-cov",
"coverage"
],
"pre_install": null,
"python": "3.6",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | alabaster==0.7.13
antlr4-python3-runtime==4.9.3
async-generator==1.10
attrs==22.2.0
Babel==2.11.0
bleach==4.1.0
bump2version==1.0.1
bumpversion==0.6.0
certifi==2021.5.30
cfgv==3.3.1
charset-normalizer==2.0.12
coverage==6.2
decorator==5.1.1
defusedxml==0.7.1
distlib==0.3.9
docutils==0.18.1
entrypoints==0.4
filelock==3.4.1
identify==2.4.4
idna==3.10
imagesize==1.4.1
importlib-metadata==4.8.3
importlib-resources==5.2.3
iniconfig==1.1.1
ipython-genutils==0.2.0
Jinja2==3.0.3
jsonschema==3.2.0
jupyter-client==7.1.2
jupyter-core==4.9.2
jupyterlab-pygments==0.1.2
MarkupSafe==2.0.1
mistune==0.8.4
nbclient==0.5.9
nbconvert==6.0.7
nbformat==5.1.3
nbsphinx==0.8.8
nest-asyncio==1.6.0
nodeenv==1.6.0
packaging==21.3
pandocfilters==1.5.1
platformdirs==2.4.0
pluggy==1.0.0
pre-commit==2.17.0
py==1.11.0
Pygments==2.14.0
pyparsing==3.1.4
pyrsistent==0.18.0
pytest==7.0.1
pytest-cov==4.0.0
python-dateutil==2.9.0.post0
pytz==2025.2
PyYAML==6.0.1
pyzmq==25.1.2
requests==2.27.1
simplejson==3.20.1
six==1.17.0
snowballstemmer==2.2.0
Sphinx==5.3.0
sphinx-prompt==1.5.0
sphinxcontrib-applehelp==1.0.2
sphinxcontrib-devhelp==1.0.2
sphinxcontrib-htmlhelp==2.0.0
sphinxcontrib-jsmath==1.0.1
sphinxcontrib-qthelp==1.0.3
sphinxcontrib-serializinghtml==1.1.5
-e git+https://github.com/oasis-open/cti-python-stix2.git@ef3ce9f6f0a678e604bda63f9eb5742ed53f8eff#egg=stix2
stix2-patterns==2.0.0
taxii2-client==2.3.0
testpath==0.6.0
toml==0.10.2
tomli==1.2.3
tornado==6.1
tox==3.28.0
traitlets==4.3.3
typing_extensions==4.1.1
urllib3==1.26.20
virtualenv==20.16.2
webencodings==0.5.1
zipp==3.6.0
| name: cti-python-stix2
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- alabaster==0.7.13
- antlr4-python3-runtime==4.9.3
- async-generator==1.10
- attrs==22.2.0
- babel==2.11.0
- bleach==4.1.0
- bump2version==1.0.1
- bumpversion==0.6.0
- cfgv==3.3.1
- charset-normalizer==2.0.12
- coverage==6.2
- decorator==5.1.1
- defusedxml==0.7.1
- distlib==0.3.9
- docutils==0.18.1
- entrypoints==0.4
- filelock==3.4.1
- identify==2.4.4
- idna==3.10
- imagesize==1.4.1
- importlib-metadata==4.8.3
- importlib-resources==5.2.3
- iniconfig==1.1.1
- ipython-genutils==0.2.0
- jinja2==3.0.3
- jsonschema==3.2.0
- jupyter-client==7.1.2
- jupyter-core==4.9.2
- jupyterlab-pygments==0.1.2
- markupsafe==2.0.1
- mistune==0.8.4
- nbclient==0.5.9
- nbconvert==6.0.7
- nbformat==5.1.3
- nbsphinx==0.8.8
- nest-asyncio==1.6.0
- nodeenv==1.6.0
- packaging==21.3
- pandocfilters==1.5.1
- platformdirs==2.4.0
- pluggy==1.0.0
- pre-commit==2.17.0
- py==1.11.0
- pygments==2.14.0
- pyparsing==3.1.4
- pyrsistent==0.18.0
- pytest==7.0.1
- pytest-cov==4.0.0
- python-dateutil==2.9.0.post0
- pytz==2025.2
- pyyaml==6.0.1
- pyzmq==25.1.2
- requests==2.27.1
- simplejson==3.20.1
- six==1.17.0
- snowballstemmer==2.2.0
- sphinx==5.3.0
- sphinx-prompt==1.5.0
- sphinxcontrib-applehelp==1.0.2
- sphinxcontrib-devhelp==1.0.2
- sphinxcontrib-htmlhelp==2.0.0
- sphinxcontrib-jsmath==1.0.1
- sphinxcontrib-qthelp==1.0.3
- sphinxcontrib-serializinghtml==1.1.5
- stix2-patterns==2.0.0
- taxii2-client==2.3.0
- testpath==0.6.0
- toml==0.10.2
- tomli==1.2.3
- tornado==6.1
- tox==3.28.0
- traitlets==4.3.3
- typing-extensions==4.1.1
- urllib3==1.26.20
- virtualenv==20.16.2
- webencodings==0.5.1
- zipp==3.6.0
prefix: /opt/conda/envs/cti-python-stix2
| [
"stix2/test/test_environment.py::test_environment_no_datastore",
"stix2/test/test_environment.py::test_relationships",
"stix2/test/test_environment.py::test_relationships_no_id",
"stix2/test/test_environment.py::test_relationships_by_type",
"stix2/test/test_environment.py::test_relationships_by_source",
"stix2/test/test_environment.py::test_relationships_by_target",
"stix2/test/test_environment.py::test_relationships_by_target_and_type",
"stix2/test/test_environment.py::test_relationships_by_target_and_source",
"stix2/test/test_environment.py::test_related_to",
"stix2/test/test_environment.py::test_related_to_no_id",
"stix2/test/test_environment.py::test_related_to_by_source",
"stix2/test/test_environment.py::test_related_to_by_target",
"stix2/test/test_filesystem.py::test_relationships",
"stix2/test/test_filesystem.py::test_relationships_by_type",
"stix2/test/test_filesystem.py::test_relationships_by_source",
"stix2/test/test_filesystem.py::test_relationships_by_target",
"stix2/test/test_filesystem.py::test_relationships_by_target_and_type",
"stix2/test/test_filesystem.py::test_relationships_by_target_and_source",
"stix2/test/test_filesystem.py::test_related_to",
"stix2/test/test_filesystem.py::test_related_to_by_source",
"stix2/test/test_filesystem.py::test_related_to_by_target",
"stix2/test/test_memory.py::test_relationships",
"stix2/test/test_memory.py::test_relationships_by_type",
"stix2/test/test_memory.py::test_relationships_by_source",
"stix2/test/test_memory.py::test_relationships_by_target",
"stix2/test/test_memory.py::test_relationships_by_target_and_type",
"stix2/test/test_memory.py::test_relationships_by_target_and_source",
"stix2/test/test_memory.py::test_related_to",
"stix2/test/test_memory.py::test_related_to_by_source",
"stix2/test/test_memory.py::test_related_to_by_target"
]
| []
| [
"stix2/test/test_data_sources.py::test_ds_abstract_class_smoke",
"stix2/test/test_data_sources.py::test_ds_taxii",
"stix2/test/test_data_sources.py::test_ds_taxii_name",
"stix2/test/test_data_sources.py::test_parse_taxii_filters",
"stix2/test/test_data_sources.py::test_add_get_remove_filter",
"stix2/test/test_data_sources.py::test_apply_common_filters",
"stix2/test/test_data_sources.py::test_filters0",
"stix2/test/test_data_sources.py::test_filters1",
"stix2/test/test_data_sources.py::test_filters2",
"stix2/test/test_data_sources.py::test_filters3",
"stix2/test/test_data_sources.py::test_filters4",
"stix2/test/test_data_sources.py::test_filters5",
"stix2/test/test_data_sources.py::test_filters6",
"stix2/test/test_data_sources.py::test_filters7",
"stix2/test/test_data_sources.py::test_deduplicate",
"stix2/test/test_data_sources.py::test_add_remove_composite_datasource",
"stix2/test/test_data_sources.py::test_composite_datasource_operations",
"stix2/test/test_data_sources.py::test_composite_datastore_no_datasource",
"stix2/test/test_environment.py::test_object_factory_created_by_ref_str",
"stix2/test/test_environment.py::test_object_factory_created_by_ref_obj",
"stix2/test/test_environment.py::test_object_factory_override_default",
"stix2/test/test_environment.py::test_object_factory_created",
"stix2/test/test_environment.py::test_object_factory_external_resource",
"stix2/test/test_environment.py::test_object_factory_obj_markings",
"stix2/test/test_environment.py::test_object_factory_list_append",
"stix2/test/test_environment.py::test_object_factory_list_replace",
"stix2/test/test_environment.py::test_environment_functions",
"stix2/test/test_environment.py::test_environment_source_and_sink",
"stix2/test/test_environment.py::test_environment_datastore_and_sink",
"stix2/test/test_environment.py::test_environment_add_filters",
"stix2/test/test_environment.py::test_environment_datastore_and_no_object_factory",
"stix2/test/test_environment.py::test_parse_malware",
"stix2/test/test_environment.py::test_creator_of",
"stix2/test/test_environment.py::test_creator_of_no_datasource",
"stix2/test/test_environment.py::test_creator_of_not_found",
"stix2/test/test_environment.py::test_creator_of_no_created_by_ref",
"stix2/test/test_filesystem.py::test_filesystem_source_nonexistent_folder",
"stix2/test/test_filesystem.py::test_filesystem_sink_nonexistent_folder",
"stix2/test/test_filesystem.py::test_filesytem_source_get_object",
"stix2/test/test_filesystem.py::test_filesytem_source_get_nonexistent_object",
"stix2/test/test_filesystem.py::test_filesytem_source_all_versions",
"stix2/test/test_filesystem.py::test_filesytem_source_query_single",
"stix2/test/test_filesystem.py::test_filesytem_source_query_multiple",
"stix2/test/test_filesystem.py::test_filesystem_sink_add_python_stix_object",
"stix2/test/test_filesystem.py::test_filesystem_sink_add_stix_object_dict",
"stix2/test/test_filesystem.py::test_filesystem_sink_add_stix_bundle_dict",
"stix2/test/test_filesystem.py::test_filesystem_sink_add_json_stix_object",
"stix2/test/test_filesystem.py::test_filesystem_sink_json_stix_bundle",
"stix2/test/test_filesystem.py::test_filesystem_sink_add_objects_list",
"stix2/test/test_filesystem.py::test_filesystem_store_get_stored_as_bundle",
"stix2/test/test_filesystem.py::test_filesystem_store_get_stored_as_object",
"stix2/test/test_filesystem.py::test_filesystem_store_all_versions",
"stix2/test/test_filesystem.py::test_filesystem_store_query",
"stix2/test/test_filesystem.py::test_filesystem_store_query_single_filter",
"stix2/test/test_filesystem.py::test_filesystem_store_empty_query",
"stix2/test/test_filesystem.py::test_filesystem_store_query_multiple_filters",
"stix2/test/test_filesystem.py::test_filesystem_store_query_dont_include_type_folder",
"stix2/test/test_filesystem.py::test_filesystem_store_add",
"stix2/test/test_filesystem.py::test_filesystem_store_add_as_bundle",
"stix2/test/test_filesystem.py::test_filesystem_add_bundle_object",
"stix2/test/test_filesystem.py::test_filesystem_store_add_invalid_object",
"stix2/test/test_filesystem.py::test_filesystem_object_with_custom_property",
"stix2/test/test_filesystem.py::test_filesystem_object_with_custom_property_in_bundle",
"stix2/test/test_filesystem.py::test_filesystem_custom_object",
"stix2/test/test_memory.py::test_memory_source_get",
"stix2/test/test_memory.py::test_memory_source_get_nonexistant_object",
"stix2/test/test_memory.py::test_memory_store_all_versions",
"stix2/test/test_memory.py::test_memory_store_query",
"stix2/test/test_memory.py::test_memory_store_query_single_filter",
"stix2/test/test_memory.py::test_memory_store_query_empty_query",
"stix2/test/test_memory.py::test_memory_store_query_multiple_filters",
"stix2/test/test_memory.py::test_memory_store_save_load_file",
"stix2/test/test_memory.py::test_memory_store_add_stix_object_str",
"stix2/test/test_memory.py::test_memory_store_add_stix_bundle_str",
"stix2/test/test_memory.py::test_memory_store_add_invalid_object",
"stix2/test/test_memory.py::test_memory_store_object_with_custom_property",
"stix2/test/test_memory.py::test_memory_store_object_with_custom_property_in_bundle",
"stix2/test/test_memory.py::test_memory_store_custom_object"
]
| []
| BSD 3-Clause "New" or "Revised" License | 1,898 | [
"stix2/environment.py",
"stix2/sources/__init__.py",
"stix2/sources/filters.py",
"docs/guide/datastore.ipynb",
"docs/guide/environment.ipynb"
]
| [
"stix2/environment.py",
"stix2/sources/__init__.py",
"stix2/sources/filters.py",
"docs/guide/datastore.ipynb",
"docs/guide/environment.ipynb"
]
|
|
witchard__grole-15 | d47d0ec83f7d76912d5b6b00fd130d79f892939c | 2017-11-17 02:19:46 | a766ad29789b27e75f388ef0f7ce8d999d52c4e4 | coveralls:
[](https://coveralls.io/builds/14246503)
Coverage decreased (-0.8%) to 89.64% when pulling **b79589e9daec23c08537795327876a336be505df on errors** into **d47d0ec83f7d76912d5b6b00fd130d79f892939c on master**.
coveralls:
[](https://coveralls.io/builds/14246507)
Coverage increased (+0.1%) to 90.583% when pulling **b79589e9daec23c08537795327876a336be505df on errors** into **d47d0ec83f7d76912d5b6b00fd130d79f892939c on master**.
coveralls:
[](https://coveralls.io/builds/14246523)
Coverage increased (+5.6%) to 96.035% when pulling **ed28971b3184dcc7a9a4275edd8fc66ac7d1bd61 on errors** into **d47d0ec83f7d76912d5b6b00fd130d79f892939c on master**.
| diff --git a/grole.py b/grole.py
index 72eba4a..bd9ed83 100755
--- a/grole.py
+++ b/grole.py
@@ -376,6 +376,9 @@ class Grole:
self._logger.info('{}: {} -> {}'.format(peer, req.path, res.code))
except EOFError:
self._logger.debug('Connection closed from {}'.format(peer))
+ except Exception as e:
+ self._logger.error('Connection error ({}) from {}'.format(e, peer))
+ writer.close()
def run(self, host='localhost', port=1234):
"""
@@ -389,7 +392,11 @@ class Grole:
# Setup loop
loop = asyncio.get_event_loop()
coro = asyncio.start_server(self._handle, host, port, loop=loop)
- server = loop.run_until_complete(coro)
+ try:
+ server = loop.run_until_complete(coro)
+ except Exception as e:
+ self._logger.error('Could not launch server: {}'.format(e))
+ return
# Run the server
self._logger.info('Serving on {}'.format(server.sockets[0].getsockname()))
| HTTPS connections result in exceptions
To reproduce simply run grole.py and connect to https://127.0.0.1:1234/
ERROR:asyncio:Task exception was never retrieved
future: <Task finished coro=<Grole._handle() done, defined at ./grole.py:336> exception=UnicodeDecodeError('utf-8', b'[Long hex string that I redacted]\n', 4, 5, 'invalid start byte')>
Traceback (most recent call last):
File "/usr/lib/python3.5/asyncio/tasks.py", line 239, in _step
result = coro.send(None)
File "./grole.py", line 349, in _handle
await req._read(reader)
File "./grole.py", line 45, in _read
self.method, self.location, self.version = start_line.decode().split()
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xae in position 4: invalid start byte | witchard/grole | diff --git a/test/helpers.py b/test/helpers.py
index 51c1394..85f307b 100644
--- a/test/helpers.py
+++ b/test/helpers.py
@@ -32,3 +32,19 @@ class FakeWriter():
def get_extra_info(self, arg):
return 'fake'
+
+class ErrorWriter():
+ def __init__(self):
+ self.closed = False
+
+ async def drain(self):
+ return
+
+ def write(self, data):
+ raise Exception('Broken')
+
+ def get_extra_info(self, arg):
+ return 'fake'
+
+ def close(self):
+ self.closed = True
diff --git a/test/test_grole.py b/test/test_grole.py
index 26eb5e7..02a7a6d 100644
--- a/test/test_grole.py
+++ b/test/test_grole.py
@@ -1,6 +1,6 @@
import unittest
import pathlib
-from helpers import FakeReader, FakeWriter, a_wait
+from helpers import *
import grole
@@ -43,6 +43,18 @@ class TestGrole(unittest.TestCase):
data = wr.data.split(b'\r\n')[0]
self.assertEqual(b'HTTP/1.1 500 Internal Server Error', data)
+ def test_close_big_error(self):
+ @self.app.route('/')
+ def error(env, req):
+ a = []
+ return a[1]
+
+ rd = FakeReader(data=b'GET / HTTP/1.1\r\n\r\n')
+ wr = ErrorWriter()
+ a_wait(self.app._handle(rd, wr))
+ self.assertTrue(wr.closed)
+
+
def test_404(self):
rd = FakeReader(data=b'GET / HTTP/1.1\r\n\r\n')
wr = FakeWriter()
diff --git a/test/test_main.py b/test/test_main.py
new file mode 100644
index 0000000..4df7d18
--- /dev/null
+++ b/test/test_main.py
@@ -0,0 +1,17 @@
+import unittest
+
+import grole
+
+class TestMain(unittest.TestCase):
+
+ def test_launch(self):
+ # Success is that it doesn't do anything
+ grole.main(['-p', '80'])
+
+ def test_launch2(self):
+ # Success is that it doesn't do anything
+ grole.main(['-p', '80', '-q'])
+
+ def test_launch3(self):
+ # Success is that it doesn't do anything
+ grole.main(['-p', '80', '-v'])
diff --git a/test/test_serve.py b/test/test_serve.py
index 1e6955c..45a725e 100644
--- a/test/test_serve.py
+++ b/test/test_serve.py
@@ -36,4 +36,11 @@ class TestServe(unittest.TestCase):
self.assertEqual(html, b'foo\n')
p.terminate()
+ def test_https(self):
+ p = multiprocessing.Process(target=simple_server)
+ p.start()
+ time.sleep(0.1)
+ self.assertRaises(urllib.error.URLError)
+ p.terminate()
+
| {
"commit_name": "merge_commit",
"failed_lite_validators": [
"has_hyperlinks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 2,
"test_score": 0
},
"num_modified_files": 1
} | 0.2 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"coverage",
"coveralls",
"pytest"
],
"pre_install": [],
"python": "3.6",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work
certifi==2021.5.30
charset-normalizer==2.0.12
coverage==6.2
coveralls==3.3.1
docopt==0.6.2
-e git+https://github.com/witchard/grole.git@d47d0ec83f7d76912d5b6b00fd130d79f892939c#egg=grole
idna==3.10
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work
packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work
pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pytest==6.2.4
requests==2.27.1
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
urllib3==1.26.20
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
| name: grole
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=21.4.0=pyhd3eb1b0_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- importlib-metadata=4.8.1=py36h06a4308_0
- importlib_metadata=4.8.1=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- more-itertools=8.12.0=pyhd3eb1b0_0
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=21.3=pyhd3eb1b0_0
- pip=21.2.2=py36h06a4308_0
- pluggy=0.13.1=py36h06a4308_0
- py=1.11.0=pyhd3eb1b0_0
- pyparsing=3.0.4=pyhd3eb1b0_0
- pytest=6.2.4=py36h06a4308_2
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- toml=0.10.2=pyhd3eb1b0_0
- typing_extensions=4.1.1=pyh06a4308_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zipp=3.6.0=pyhd3eb1b0_0
- zlib=1.2.13=h5eee18b_1
- pip:
- charset-normalizer==2.0.12
- coverage==6.2
- coveralls==3.3.1
- docopt==0.6.2
- idna==3.10
- requests==2.27.1
- urllib3==1.26.20
prefix: /opt/conda/envs/grole
| [
"test/test_grole.py::TestGrole::test_close_big_error",
"test/test_main.py::TestMain::test_launch",
"test/test_main.py::TestMain::test_launch2",
"test/test_main.py::TestMain::test_launch3"
]
| []
| [
"test/test_grole.py::TestGrole::test_404",
"test/test_grole.py::TestGrole::test_async",
"test/test_grole.py::TestGrole::test_error",
"test/test_grole.py::TestGrole::test_hello",
"test/test_grole.py::TestStatic::test_file",
"test/test_grole.py::TestStatic::test_index",
"test/test_grole.py::TestStatic::test_index2",
"test/test_grole.py::TestStatic::test_notfound",
"test/test_grole.py::TestDoc::test_doc",
"test/test_serve.py::TestServe::test_fileserver",
"test/test_serve.py::TestServe::test_https",
"test/test_serve.py::TestServe::test_simple"
]
| []
| MIT License | 1,899 | [
"grole.py"
]
| [
"grole.py"
]
|
refnx__refnx-126 | 568a56132fe0cd8418cff41ffedfc276bdb99af4 | 2017-11-17 08:14:29 | 568a56132fe0cd8418cff41ffedfc276bdb99af4 | diff --git a/refnx/reflect/spline.py b/refnx/reflect/spline.py
index 6d7cd091..0a542992 100644
--- a/refnx/reflect/spline.py
+++ b/refnx/reflect/spline.py
@@ -15,7 +15,7 @@ class Spline(Component):
"""
def __init__(self, extent, vs, dz, left, right, solvent, name='',
- interpolator=Pchip, zgrad=True, microslab_max_thickness=2):
+ interpolator=Pchip, zgrad=True, microslab_max_thickness=1):
"""
Parameters
----------
@@ -65,9 +65,9 @@ class Spline(Component):
microslab is `microslab_max_thickness`.
"""
self.name = name
- self.left_Slab = left
- self.right_Slab = right
- self.solvent_Slab = solvent
+ self.left_slab = left
+ self.right_slab = right
+ self.solvent_slab = solvent
self.microslab_max_thickness = microslab_max_thickness
self.extent = (
@@ -95,45 +95,87 @@ class Spline(Component):
self.zgrad = zgrad
self.interpolator = interpolator
- def __call__(self, z):
- # calculate spline value at z
- zeds = np.cumsum(self.dz)
+ self.__cached_interpolator = {'zeds': np.array([]),
+ 'vs': np.array([]),
+ 'interp': None,
+ 'extent': -1}
+
+ def _interpolator(self):
+ dz = np.array(self.dz)
+ zeds = np.cumsum(dz)
# if dz's sum to more than 1, then normalise to unit interval.
- if np.sum(self.dz) > 1:
- zeds /= np.sum(self.dz)
+ if zeds[-1] > 1:
+ zeds /= zeds[-1]
+ zeds = np.clip(zeds, 0, 1)
vs = np.array(self.vs)
left_sld = Structure.overall_sld(
- np.atleast_2d(self.left_Slab.slabs[-1]),
- self.solvent_Slab.slabs)[..., 1]
+ np.atleast_2d(self.left_slab.slabs[-1]),
+ self.solvent_slab.slabs)[..., 1]
right_sld = Structure.overall_sld(
- np.atleast_2d(self.right_Slab.slabs[0]),
- self.solvent_Slab.slabs)[..., 1]
+ np.atleast_2d(self.right_slab.slabs[0]),
+ self.solvent_slab.slabs)[..., 1]
if self.zgrad:
- zeds = np.r_[-1.1, 0, zeds, 1, 2.1]
- vs = np.r_[left_sld, left_sld, vs, right_sld, right_sld]
+ zeds = np.concatenate([[-1.1, 0], zeds, [1, 2.1]])
+ print(left_sld.shape, right_sld.shape)
+ vs = np.concatenate([left_sld, left_sld, vs, right_sld, right_sld])
+ else:
+ zeds = np.concatenate([[0], zeds, [1]])
+ vs = np.concatenate([left_sld, vs, right_sld])
+
+ # cache the interpolator
+ cache_zeds = self.__cached_interpolator['zeds']
+ cache_vs = self.__cached_interpolator['vs']
+ cache_extent = self.__cached_interpolator['extent']
+
+ # you don't need to recreate the interpolator
+ if (np.array_equal(zeds, cache_zeds) and
+ np.array_equal(vs, cache_vs) and
+ np.equal(self.extent, cache_extent)):
+ return self.__cached_interpolator['interp']
else:
- zeds = np.r_[0, zeds, 1]
- vs = np.r_[left_sld, vs, right_sld]
- return self.interpolator(zeds, vs)(z / float(self.extent))
+ self.__cached_interpolator['zeds'] = zeds
+ self.__cached_interpolator['vs'] = vs
+ self.__cached_interpolator['extent'] = float(self.extent)
+
+ # TODO make vfp zero for z > self.extent
+ interpolator = self.interpolator(zeds, vs)
+ self.__cached_interpolator['interp'] = interpolator
+ return interpolator
+
+ def __call__(self, z):
+ """
+ Calculates the spline value at z
+
+ Parameters
+ ----------
+ z : float
+ Distance along spline
+
+ Returns
+ -------
+ sld : float
+ Real part of SLD
+ """
+ interpolator = self._interpolator()
+ vs = interpolator(z / float(self.extent))
+ return vs
@property
def parameters(self):
p = Parameters(name=self.name)
p.extend([self.extent, self.dz, self.vs,
- self.left_Slab,
- self.right_Slab,
- self.solvent_Slab])
+ self.left_slab.parameters,
+ self.right_slab.parameters,
+ self.solvent_slab.parameters])
return p
def lnprob(self):
- zeds = np.cumsum(self.dz)
- if zeds[-1] > 1:
- return -np.inf
+ return 0
@property
def slabs(self):
@@ -142,8 +184,8 @@ class Spline(Component):
slabs = np.zeros((int(num_slabs), 5))
slabs[:, 0] = slab_thick
- # give each slab a miniscule roughness
- slabs[:, 3] = 0.5
+ # give last slab a miniscule roughness so it doesn't get contracted
+ slabs[-1:, 3] = 0.5
dist = np.cumsum(slabs[..., 0]) - 0.5 * slab_thick
slabs[:, 1] = self(dist)
| reflect.spline issues
lnprob doesn't return 0
parameters needs to return list of parameters
remove minimal roughness
speedup like brush code. | refnx/refnx | diff --git a/refnx/reflect/test/test_spline.py b/refnx/reflect/test/test_spline.py
index 36a9634b..cafd086e 100644
--- a/refnx/reflect/test/test_spline.py
+++ b/refnx/reflect/test/test_spline.py
@@ -1,6 +1,9 @@
import numpy as np
-from numpy.testing import assert_allclose, assert_equal, assert_almost_equal
+from numpy.testing import (assert_allclose, assert_equal, assert_almost_equal,
+ assert_)
from refnx.reflect import SLD, Slab, Structure, Spline
+from refnx.analysis import Parameter
+from refnx._lib import flatten
class TestReflect(object):
@@ -14,10 +17,9 @@ class TestReflect(object):
# smoke test to make Spline at least gives us something
a = Spline(100, [2],
[0.5], self.left, self.right, self.solvent, zgrad=False,
- microslab_max_thickness=2)
+ microslab_max_thickness=1)
b = a.slabs
assert_equal(b[:, 2], 0)
- assert_equal(b[:, 3], 0.5)
# microslabs are assessed in the middle of the slab
assert_equal(b[0, 1], a(0.5 * b[0, 0]))
@@ -25,12 +27,24 @@ class TestReflect(object):
# with the ends turned off the profile should be a straight line
assert_equal(a(50), 2.0)
+ # construct a structure
+ a = Spline(100, [2., 3., 4.],
+ [0.25] * 3, self.left, self.right, self.solvent,
+ zgrad=False, microslab_max_thickness=1)
+
+ s = self.left | a | self.right | self.solvent
+ # calculate an SLD profile
+ s.sld_profile()
+ # ask for the parameters
+ for p in flatten(s.parameters):
+ assert_(isinstance(p, Parameter))
+
def test_left_right_influence(self):
# make sure that if the left and right components change, so does the
# spline
a = Spline(100, [2],
[0.5], self.left, self.right, self.solvent, zgrad=False,
- microslab_max_thickness=2)
+ microslab_max_thickness=1)
# change the SLD of the left component, spline should respond
self.left.sld.real.value = 2.
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 3,
"issue_text_score": 2,
"test_score": 0
},
"num_modified_files": 1
} | 0.0 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "numpy>=1.16.0 scipy>=1.0.0 emcee>=2.2.1 six>=1.11.0 uncertainties>=3.0.1 pandas>=0.23.4 pytest>=3.6.0 h5py>=2.8.0 xlrd>=1.1.0 ptemcee>=1.0.0",
"pip_packages": [
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.6",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work
certifi==2021.5.30
emcee @ file:///home/conda/feedstock_root/build_artifacts/emcee_1713796893786/work
future==0.18.2
h5py @ file:///tmp/build/80754af9/h5py_1593454121459/work
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work
numpy @ file:///tmp/build/80754af9/numpy_and_numpy_base_1603483703303/work
packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work
pandas==1.1.5
pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work
ptemcee==1.0.0
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pytest==6.2.4
python-dateutil @ file:///tmp/build/80754af9/python-dateutil_1626374649649/work
pytz==2021.3
-e git+https://github.com/refnx/refnx.git@568a56132fe0cd8418cff41ffedfc276bdb99af4#egg=refnx
scipy @ file:///tmp/build/80754af9/scipy_1597686635649/work
six @ file:///tmp/build/80754af9/six_1644875935023/work
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
uncertainties @ file:///home/conda/feedstock_root/build_artifacts/uncertainties_1720452225073/work
xlrd @ file:///croot/xlrd_1685030938141/work
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
| name: refnx
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=21.4.0=pyhd3eb1b0_0
- blas=1.0=openblas
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- emcee=3.1.6=pyhd8ed1ab_0
- future=0.18.2=py36_1
- h5py=2.10.0=py36hd6299e0_1
- hdf5=1.10.6=hb1b8bf9_0
- importlib-metadata=4.8.1=py36h06a4308_0
- importlib_metadata=4.8.1=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgfortran-ng=7.5.0=ha8ba4b0_17
- libgfortran4=7.5.0=ha8ba4b0_17
- libgomp=11.2.0=h1234567_1
- libopenblas=0.3.18=hf726d26_0
- libstdcxx-ng=11.2.0=h1234567_1
- more-itertools=8.12.0=pyhd3eb1b0_0
- ncurses=6.4=h6a678d5_0
- numpy=1.19.2=py36h6163131_0
- numpy-base=1.19.2=py36h75fe3a5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=21.3=pyhd3eb1b0_0
- pandas=1.1.5=py36ha9443f7_0
- pip=21.2.2=py36h06a4308_0
- pluggy=0.13.1=py36h06a4308_0
- ptemcee=1.0.0=py_0
- py=1.11.0=pyhd3eb1b0_0
- pyparsing=3.0.4=pyhd3eb1b0_0
- pytest=6.2.4=py36h06a4308_2
- python=3.6.13=h12debd9_1
- python-dateutil=2.8.2=pyhd3eb1b0_0
- pytz=2021.3=pyhd3eb1b0_0
- readline=8.2=h5eee18b_0
- scipy=1.5.2=py36habc2bb6_0
- setuptools=58.0.4=py36h06a4308_0
- six=1.16.0=pyhd3eb1b0_1
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- toml=0.10.2=pyhd3eb1b0_0
- typing_extensions=4.1.1=pyh06a4308_0
- uncertainties=3.2.2=pyhd8ed1ab_1
- wheel=0.37.1=pyhd3eb1b0_0
- xlrd=2.0.1=pyhd3eb1b0_1
- xz=5.6.4=h5eee18b_1
- zipp=3.6.0=pyhd3eb1b0_0
- zlib=1.2.13=h5eee18b_1
prefix: /opt/conda/envs/refnx
| [
"refnx/reflect/test/test_spline.py::TestReflect::test_spline_smoke"
]
| []
| [
"refnx/reflect/test/test_spline.py::TestReflect::test_left_right_influence"
]
| []
| BSD 3-Clause "New" or "Revised" License | 1,901 | [
"refnx/reflect/spline.py"
]
| [
"refnx/reflect/spline.py"
]
|
|
jwplayer__jwplatform-py-20 | be9d31a94f85b8846c8517b5fe2b065c5d7bfad9 | 2017-11-17 21:41:54 | be9d31a94f85b8846c8517b5fe2b065c5d7bfad9 | diff --git a/jwplatform/client.py b/jwplatform/client.py
index 18edad5..f00b7e1 100644
--- a/jwplatform/client.py
+++ b/jwplatform/client.py
@@ -61,11 +61,11 @@ class Client(object):
self.__key = key
self.__secret = secret
- self._scheme = kwargs.pop('scheme', 'https')
- self._host = kwargs.pop('host', 'api.jwplatform.com')
- self._port = int(kwargs.pop('port', 80))
- self._api_version = kwargs.pop('version', 'v1')
- self._agent = kwargs.pop('agent', None)
+ self._scheme = kwargs.get('scheme') or 'https'
+ self._host = kwargs.get('host') or 'api.jwplatform.com'
+ self._port = int(kwargs['port']) if kwargs.get('port') else 80
+ self._api_version = kwargs.get('version') or 'v1'
+ self._agent = kwargs.get('agent')
self._connection = requests.Session()
self._connection.mount(self._scheme, RetryAdapter())
| Client with null kwargs does not use default parameters
Currently jwplatform.Client instantiation only uses default parameters if a kwarg doesn't exist. If the kwarg is `None` this value is still used. It would be expected that `None` values for a kwarg use the default value.
**Current**
```python
>>> import jwplatform
>>> client = jwplatform.Client('key', 'secret', host=None)
>>> client._host == 'api.jwplatform.com'
False
```
**Expected**
```python
>>> import jwplatform
>>> client = jwplatform.Client('key', 'secret', host=None)
>>> client._host == 'api.jwplatform.com'
True
```
| jwplayer/jwplatform-py | diff --git a/tests/test_init.py b/tests/test_init.py
index dc3ab77..3502914 100644
--- a/tests/test_init.py
+++ b/tests/test_init.py
@@ -50,3 +50,33 @@ def test_custom_initialization():
assert 'User-Agent' in jwp_client._connection.headers
assert jwp_client._connection.headers['User-Agent'] == \
'python-jwplatform/{}-{}'.format(jwplatform.__version__, AGENT)
+
+
+def test_custom_initialization_empty_kwargs():
+
+ KEY = 'api_key'
+ SECRET = 'api_secret'
+ SCHEME = None
+ HOST = None
+ PORT = None
+ API_VERSION = None
+ AGENT = None
+
+ jwp_client = jwplatform.Client(
+ KEY, SECRET,
+ scheme=SCHEME,
+ host=HOST,
+ port=PORT,
+ version=API_VERSION,
+ agent=AGENT)
+
+ assert jwp_client._Client__key == KEY
+ assert jwp_client._Client__secret == SECRET
+ assert jwp_client._scheme == 'https'
+ assert jwp_client._host == 'api.jwplatform.com'
+ assert jwp_client._port == 80
+ assert jwp_client._api_version == 'v1'
+ assert jwp_client._agent is None
+ assert 'User-Agent' in jwp_client._connection.headers
+ assert jwp_client._connection.headers['User-Agent'] == \
+ 'python-jwplatform/{}'.format(jwplatform.__version__)
| {
"commit_name": "head_commit",
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 1,
"test_score": 0
},
"num_modified_files": 1
} | 1.2 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "",
"pip_packages": [
"pytest",
"responses"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | certifi==2025.1.31
charset-normalizer==3.4.1
exceptiongroup==1.2.2
idna==3.10
iniconfig==2.1.0
-e git+https://github.com/jwplayer/jwplatform-py.git@be9d31a94f85b8846c8517b5fe2b065c5d7bfad9#egg=jwplatform
packaging==24.2
pluggy==1.5.0
pytest==8.3.5
PyYAML==6.0.2
requests==2.32.3
responses==0.25.7
tomli==2.2.1
urllib3==2.3.0
| name: jwplatform-py
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- certifi==2025.1.31
- charset-normalizer==3.4.1
- exceptiongroup==1.2.2
- idna==3.10
- iniconfig==2.1.0
- packaging==24.2
- pluggy==1.5.0
- pytest==8.3.5
- pyyaml==6.0.2
- requests==2.32.3
- responses==0.25.7
- tomli==2.2.1
- urllib3==2.3.0
prefix: /opt/conda/envs/jwplatform-py
| [
"tests/test_init.py::test_custom_initialization_empty_kwargs"
]
| []
| [
"tests/test_init.py::test_default_initialization",
"tests/test_init.py::test_custom_initialization"
]
| []
| MIT License | 1,902 | [
"jwplatform/client.py"
]
| [
"jwplatform/client.py"
]
|
|
wearewhys__magnivore-9 | a9c896df3d054cb943a7f07540e04697952e0d62 | 2017-11-20 15:44:17 | c7ede540cfa23acdc9030772d46252d3114845fe | diff --git a/magnivore/Targets.py b/magnivore/Targets.py
index c2aa61c..27ce660 100644
--- a/magnivore/Targets.py
+++ b/magnivore/Targets.py
@@ -66,6 +66,16 @@ class Targets:
return query.join(model, 'LEFT OUTER', on=expression)
return query.join(model, on=expression)
+ def _apply_pick(self, query, join):
+ model = self.source_models[join['table']]
+ selects = []
+ for column, value in join['picks'].items():
+ if value is True:
+ selects.append(getattr(model, column))
+ elif value == 'sum':
+ selects.append(fn.Sum(getattr(model, column)))
+ return query.select(*selects)
+
def get(self, joins, limit=None, offset=0):
"""
Retrieves the targets for the given joins
@@ -76,6 +86,7 @@ class Targets:
aggregations = []
conditions = []
models = []
+ picks = []
for join in joins:
models.append(self.source_models[join['table']])
if 'conditions' in join:
@@ -84,7 +95,14 @@ class Targets:
if 'aggregation' in join:
aggregations.append(join)
- query = models[0].select(*models)
+ if 'picks' in join:
+ picks.append(join)
+
+ query = models[0]
+ if picks == []:
+ query = query.select(*models)
+ for pick in picks:
+ query = self._apply_pick(query, pick)
joins.pop(0)
for join in joins:
| Add ability to specify selected columns
It should be possible to specify the columns to be selected in when retrieving items. This is necessary as it would allow to retrieve aggregated sets e.g. count queries | wearewhys/magnivore | diff --git a/tests/unit/Targets.py b/tests/unit/Targets.py
index a0668e5..159af9c 100644
--- a/tests/unit/Targets.py
+++ b/tests/unit/Targets.py
@@ -193,6 +193,24 @@ def test_get_aggregations_eq(mocker, targets, joins, nodes, nodes_query):
assert nodes_query.join().group_by().having().execute.call_count == 1
+def test_get_picks(targets, joins, nodes, nodes_query):
+ joins[0]['picks'] = {
+ 'field': True
+ }
+ targets.get(joins)
+ nodes.select.assert_called_with(nodes.field)
+ assert nodes_query.join().execute.call_count == 1
+
+
+def test_get_picks_sum(targets, joins, nodes, nodes_query):
+ joins[0]['picks'] = {
+ 'field': 'sum'
+ }
+ targets.get(joins)
+ nodes.select.assert_called_with(fn.Sum(nodes.field))
+ assert nodes_query.join().execute.call_count == 1
+
+
def test_get_log_query(targets, joins, nodes_query, logger):
targets.get(joins)
calls = [call.logger.log('get-targets', nodes_query.join())]
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 2,
"test_score": 2
},
"num_modified_files": 1
} | 0.31 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"pytest",
"pytest-mock",
"psycopg2",
"PyMySQL"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.6",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | aratrum==0.3.2
attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work
certifi==2021.5.30
click==8.0.4
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
-e git+https://github.com/wearewhys/magnivore.git@a9c896df3d054cb943a7f07540e04697952e0d62#egg=magnivore
more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work
packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work
peewee==3.17.9
pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work
psycopg2==2.7.7
py @ file:///opt/conda/conda-bld/py_1644396412707/work
PyMySQL==1.0.2
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pytest==6.2.4
pytest-mock==3.6.1
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
ujson==4.3.0
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
| name: magnivore
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=21.4.0=pyhd3eb1b0_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- importlib-metadata=4.8.1=py36h06a4308_0
- importlib_metadata=4.8.1=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- more-itertools=8.12.0=pyhd3eb1b0_0
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=21.3=pyhd3eb1b0_0
- pip=21.2.2=py36h06a4308_0
- pluggy=0.13.1=py36h06a4308_0
- py=1.11.0=pyhd3eb1b0_0
- pyparsing=3.0.4=pyhd3eb1b0_0
- pytest=6.2.4=py36h06a4308_2
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- toml=0.10.2=pyhd3eb1b0_0
- typing_extensions=4.1.1=pyh06a4308_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zipp=3.6.0=pyhd3eb1b0_0
- zlib=1.2.13=h5eee18b_1
- pip:
- aratrum==0.3.2
- click==8.0.4
- peewee==3.17.9
- psycopg2==2.7.7
- pymysql==1.0.2
- pytest-mock==3.6.1
- ujson==4.3.0
prefix: /opt/conda/envs/magnivore
| [
"tests/unit/Targets.py::test_get_picks",
"tests/unit/Targets.py::test_get_picks_sum"
]
| []
| [
"tests/unit/Targets.py::test_get_targets_empty",
"tests/unit/Targets.py::test_get",
"tests/unit/Targets.py::test_get_triple_join",
"tests/unit/Targets.py::test_get_limit",
"tests/unit/Targets.py::test_get_limit_with_offset",
"tests/unit/Targets.py::test_get_switch",
"tests/unit/Targets.py::test_get_join_on",
"tests/unit/Targets.py::test_get_join_outer",
"tests/unit/Targets.py::test_get_conditions",
"tests/unit/Targets.py::test_get_conditions_greater[gt]",
"tests/unit/Targets.py::test_get_conditions_greater[lt]",
"tests/unit/Targets.py::test_get_conditions_greater[not]",
"tests/unit/Targets.py::test_get_conditions_in",
"tests/unit/Targets.py::test_get_conditions_isnull",
"tests/unit/Targets.py::test_get_aggregations",
"tests/unit/Targets.py::test_get_aggregations_eq",
"tests/unit/Targets.py::test_get_log_query",
"tests/unit/Targets.py::test_get_log_targets_count"
]
| []
| Apache License 2.0 | 1,903 | [
"magnivore/Targets.py"
]
| [
"magnivore/Targets.py"
]
|
|
wearewhys__magnivore-10 | c7ede540cfa23acdc9030772d46252d3114845fe | 2017-11-20 16:31:43 | c7ede540cfa23acdc9030772d46252d3114845fe | diff --git a/README.rst b/README.rst
index 5ec15ba..8dca6f7 100644
--- a/README.rst
+++ b/README.rst
@@ -12,7 +12,7 @@ A simple migration rule::
{
"profiles": {
- "joins": [
+ "sources": [
{"table": "users"},
{"table": "addresses", "on":"user"}
],
diff --git a/magnivore/RulesParser.py b/magnivore/RulesParser.py
index 85def1c..47a81af 100644
--- a/magnivore/RulesParser.py
+++ b/magnivore/RulesParser.py
@@ -21,7 +21,7 @@ class RulesParser():
def _process(self, table, table_rules):
model = self.receiver[table]
- targets = self.targets.get(table_rules['joins'])
+ targets = self.targets.get(table_rules['sources'])
if 'transform' in table_rules:
transformations = table_rules['transform']
diff --git a/magnivore/Targets.py b/magnivore/Targets.py
index 27ce660..31a311e 100644
--- a/magnivore/Targets.py
+++ b/magnivore/Targets.py
@@ -8,23 +8,23 @@ class Targets:
self.source_models = source_models
self.logger = logger
- def _apply_aggregation(self, query, joins):
- model = self.source_models[joins['table']]
- model_field = getattr(model, joins['aggregation']['group'])
+ def _apply_aggregation(self, query, source):
+ model = self.source_models[source['table']]
+ model_field = getattr(model, source['aggregation']['group'])
query = query.group_by(model_field)
- aggregation = joins['aggregation']['function']
+ aggregation = source['aggregation']['function']
if aggregation == 'count':
aggregation_function = fn.Count(model_field)
- condition = joins['aggregation']['condition']
+ condition = source['aggregation']['condition']
if condition['operator'] == 'gt':
query = query.having(aggregation_function > condition['value'])
elif condition['operator'] == 'eq':
query = query.having(aggregation_function == condition['value'])
return query
- def _apply_condition(self, query, joins):
- conditions = joins['conditions']
- model = self.source_models[joins['table']]
+ def _apply_condition(self, query, source):
+ conditions = source['conditions']
+ model = self.source_models[source['table']]
for field, condition in conditions.items():
model_field = getattr(model, field)
if type(condition) == dict:
@@ -43,15 +43,15 @@ class Targets:
query = query.where(model_field == condition)
return query
- def _apply_join(self, query, join, models):
- model = self.source_models[join['table']]
+ def _apply_join(self, query, source, models):
+ model = self.source_models[source['table']]
previous_model = models[models.index(model)-1]
- if 'switch' in join:
- if join['switch']:
+ if 'switch' in source:
+ if source['switch']:
previous_model = models[0]
- on = join['on']
+ on = source['on']
if type(on) is list:
left_side = getattr(previous_model, on[0])
right_side = getattr(model, on[1])
@@ -59,44 +59,44 @@ class Targets:
else:
expression = getattr(model, on)
- if 'switch' in join:
+ if 'switch' in source:
query = query.switch(models[0])
- if 'outer' in join:
+ if 'outer' in source:
return query.join(model, 'LEFT OUTER', on=expression)
return query.join(model, on=expression)
- def _apply_pick(self, query, join):
- model = self.source_models[join['table']]
+ def _apply_pick(self, query, source):
+ model = self.source_models[source['table']]
selects = []
- for column, value in join['picks'].items():
+ for column, value in source['picks'].items():
if value is True:
selects.append(getattr(model, column))
elif value == 'sum':
selects.append(fn.Sum(getattr(model, column)))
return query.select(*selects)
- def get(self, joins, limit=None, offset=0):
+ def get(self, sources, limit=None, offset=0):
"""
Retrieves the targets for the given joins
"""
- if len(joins) == 0:
+ if len(sources) == 0:
raise ValueError
aggregations = []
conditions = []
models = []
picks = []
- for join in joins:
- models.append(self.source_models[join['table']])
- if 'conditions' in join:
- conditions.append(join)
+ for source in sources:
+ models.append(self.source_models[source['table']])
+ if 'conditions' in source:
+ conditions.append(source)
- if 'aggregation' in join:
- aggregations.append(join)
+ if 'aggregation' in source:
+ aggregations.append(source)
- if 'picks' in join:
- picks.append(join)
+ if 'picks' in source:
+ picks.append(source)
query = models[0]
if picks == []:
@@ -104,9 +104,9 @@ class Targets:
for pick in picks:
query = self._apply_pick(query, pick)
- joins.pop(0)
- for join in joins:
- query = self._apply_join(query, join, models)
+ sources.pop(0)
+ for source in sources:
+ query = self._apply_join(query, source, models)
for condition in conditions:
query = self._apply_condition(query, condition)
| Improve rulesets naming for join section
The join section should have better keyword naming:
- *joins* should be renamed to *sources* | wearewhys/magnivore | diff --git a/tests/integration/RulesParser.py b/tests/integration/RulesParser.py
index 76ca84a..c5ba559 100644
--- a/tests/integration/RulesParser.py
+++ b/tests/integration/RulesParser.py
@@ -9,7 +9,7 @@ from pytest import fixture
def rules():
rules = {
'profiles': {
- 'joins': [
+ 'sources': [
{'table': 'users'},
{'table': 'addresses', 'on': 'user'}
],
@@ -60,7 +60,7 @@ def test_transform_match(logger, config_setup, donor_setup, receiver_setup,
rules['profiles']['track'] = 'editor'
article_rules = {
'articles': {
- 'joins': [
+ 'sources': [
{'table': 'posts'}
],
'transform': {
diff --git a/tests/integration/Targets.py b/tests/integration/Targets.py
index 1c2aa63..3422798 100644
--- a/tests/integration/Targets.py
+++ b/tests/integration/Targets.py
@@ -14,11 +14,11 @@ def interface(config_setup):
def test_get(interface, donor_setup, receiver_setup, tracker_setup):
targets = Targets(interface.donor(), Logger())
- joins = [
+ sources = [
{'table': 'users'},
{'table': 'addresses', 'on': 'user'}
]
- items = targets.get(joins)
+ items = targets.get(sources)
results = []
for item in items:
results.append(item)
diff --git a/tests/unit/RulesParser.py b/tests/unit/RulesParser.py
index 911f2da..c25f1e0 100644
--- a/tests/unit/RulesParser.py
+++ b/tests/unit/RulesParser.py
@@ -14,7 +14,7 @@ from pytest import fixture
def rules():
rules = {
'profiles': {
- 'joins': [
+ 'sources': [
{'table': 'nodes'},
{'table': 'points', 'on': 'node'}
],
diff --git a/tests/unit/Targets.py b/tests/unit/Targets.py
index 159af9c..70d3703 100644
--- a/tests/unit/Targets.py
+++ b/tests/unit/Targets.py
@@ -31,12 +31,12 @@ def targets(nodes, points, logger):
@fixture
-def joins():
- joins = [
+def sources():
+ sources = [
{'table': 'nodes'},
{'table': 'points', 'on': 'node'}
]
- return joins
+ return sources
@fixture(params=['gt', 'lt', 'not'])
@@ -56,113 +56,113 @@ def test_get_targets_empty(targets):
targets.get([])
-def test_get(targets, joins, nodes, nodes_query, points):
- targets.get(joins)
+def test_get(targets, sources, nodes, nodes_query, points):
+ targets.get(sources)
nodes.select.assert_called_with(nodes, points)
nodes_query.join.assert_called_with(points, on=points.node)
assert nodes_query.join().execute.call_count == 1
-def test_get_triple_join(targets, joins, nodes, nodes_query, points):
+def test_get_triple_join(targets, sources, nodes, nodes_query, points):
dots = MagicMock()
targets.source_models['dots'] = dots
- joins.append({'table': 'dots', 'on': ['id', 'point']})
- targets.get(joins)
+ sources.append({'table': 'dots', 'on': ['id', 'point']})
+ targets.get(sources)
nodes_query.join().join.assert_called_with(dots, on=False)
assert nodes_query.join().join().execute.call_count == 1
-def test_get_limit(targets, joins, nodes, nodes_query, points):
- targets.get(joins, limit=100)
+def test_get_limit(targets, sources, nodes, nodes_query, points):
+ targets.get(sources, limit=100)
nodes_query.join().limit.assert_called_with(100)
assert nodes_query.join().limit().offset().execute.call_count == 1
-def test_get_limit_with_offset(targets, joins, nodes, nodes_query, points):
- targets.get(joins, limit=100, offset=10)
+def test_get_limit_with_offset(targets, sources, nodes, nodes_query, points):
+ targets.get(sources, limit=100, offset=10)
nodes_query.join().limit().offset.assert_called_with(10)
assert nodes_query.join().limit().offset().execute.call_count == 1
-def test_get_switch(targets, joins, nodes, nodes_query, points):
- joins[1]['switch'] = True
- targets.get(joins)
+def test_get_switch(targets, sources, nodes, nodes_query, points):
+ sources[1]['switch'] = True
+ targets.get(sources)
nodes.select.assert_called_with(nodes, points)
nodes_query.switch().join.assert_called_with(points, on=points.node)
assert nodes_query.switch().join().execute.call_count == 1
-def test_get_join_on(targets, joins, nodes, nodes_query, points):
- joins[1]['on'] = ['id', 'node']
- targets.get(joins)
+def test_get_join_on(targets, sources, nodes, nodes_query, points):
+ sources[1]['on'] = ['id', 'node']
+ targets.get(sources)
nodes.select.assert_called_with(nodes, points)
nodes_query.join.assert_called_with(points, on=(nodes.id == points.node))
assert nodes_query.join().execute.call_count == 1
-def test_get_join_outer(targets, joins, nodes, nodes_query, points):
- joins[1]['outer'] = True
- targets.get(joins)
+def test_get_join_outer(targets, sources, nodes, nodes_query, points):
+ sources[1]['outer'] = True
+ targets.get(sources)
nodes.select.assert_called_with(nodes, points)
nodes_query.join.assert_called_with(points, 'LEFT OUTER', on=points.node)
assert nodes_query.join().execute.call_count == 1
-def test_get_conditions(targets, joins, nodes, nodes_query):
- joins[0]['conditions'] = {
+def test_get_conditions(targets, sources, nodes, nodes_query):
+ sources[0]['conditions'] = {
'somefield': 'myvalue'
}
- joins[1]['conditions'] = {
+ sources[1]['conditions'] = {
'somefield': 'myvalue'
}
- targets.get(joins)
+ targets.get(sources)
expression = (nodes.somefield == 'myvalue')
nodes_query.join().where().where.assert_called_with(expression)
assert nodes_query.join().where().where().execute.call_count == 1
-def test_get_conditions_greater(operator, targets, joins, nodes, nodes_query):
- joins[0]['conditions'] = {
+def test_get_conditions_greater(operator, targets, sources, nodes):
+ sources[0]['conditions'] = {
'somefield': {
'operator': operator[0],
'value': 'myvalue'
}
}
- targets.get(joins)
- nodes_query.join().where.assert_called_with(operator[1])
- assert nodes_query.join().where().execute.call_count == 1
+ targets.get(sources)
+ nodes.select().join().where.assert_called_with(operator[1])
+ assert nodes.select().join().where().execute.call_count == 1
-def test_get_conditions_in(targets, joins, nodes, nodes_query):
- joins[0]['conditions'] = {
+def test_get_conditions_in(targets, sources, nodes, nodes_query):
+ sources[0]['conditions'] = {
'somefield': {
'operator': 'in',
'value': ['myvalue']
}
}
- targets.get(joins)
+ targets.get(sources)
expression = (nodes.somefield << ['myvalue'])
nodes_query.join().where.assert_called_with(expression)
assert nodes_query.join().where().execute.call_count == 1
-def test_get_conditions_isnull(targets, joins, nodes, nodes_query):
- joins[0]['conditions'] = {
+def test_get_conditions_isnull(targets, sources, nodes, nodes_query):
+ sources[0]['conditions'] = {
'somefield': {
'operator': 'isnull',
'value': True
}
}
- targets.get(joins)
+ targets.get(sources)
expression = (nodes.somefield.is_null(True))
nodes_query.join().where.assert_called_with(expression)
assert nodes_query.join().where().execute.call_count == 1
-def test_get_aggregations(mocker, targets, joins, nodes, nodes_query):
+def test_get_aggregations(mocker, targets, sources, nodes, nodes_query):
mocker.patch.object(fn, 'Count')
fn.Count.return_value = 0
- joins[0]['aggregation'] = {
+ sources[0]['aggregation'] = {
'function': 'count',
'group': 'email',
'condition': {
@@ -170,16 +170,16 @@ def test_get_aggregations(mocker, targets, joins, nodes, nodes_query):
'value': 1
}
}
- targets.get(joins)
+ targets.get(sources)
nodes_query.join().group_by.assert_called_with(nodes.email)
nodes_query.join().group_by().having.assert_called_with(fn.Count() > 1)
assert nodes_query.join().group_by().having().execute.call_count == 1
-def test_get_aggregations_eq(mocker, targets, joins, nodes, nodes_query):
+def test_get_aggregations_eq(mocker, targets, sources, nodes, nodes_query):
mocker.patch.object(fn, 'Count')
fn.Count.return_value = 0
- joins[0]['aggregation'] = {
+ sources[0]['aggregation'] = {
'function': 'count',
'group': 'email',
'condition': {
@@ -187,37 +187,37 @@ def test_get_aggregations_eq(mocker, targets, joins, nodes, nodes_query):
'value': 1
}
}
- targets.get(joins)
+ targets.get(sources)
nodes_query.join().group_by.assert_called_with(nodes.email)
nodes_query.join().group_by().having.assert_called_with(fn.Count() == 1)
assert nodes_query.join().group_by().having().execute.call_count == 1
-def test_get_picks(targets, joins, nodes, nodes_query):
- joins[0]['picks'] = {
+def test_get_picks(targets, sources, nodes, nodes_query):
+ sources[0]['picks'] = {
'field': True
}
- targets.get(joins)
+ targets.get(sources)
nodes.select.assert_called_with(nodes.field)
assert nodes_query.join().execute.call_count == 1
-def test_get_picks_sum(targets, joins, nodes, nodes_query):
- joins[0]['picks'] = {
+def test_get_picks_sum(targets, sources, nodes, nodes_query):
+ sources[0]['picks'] = {
'field': 'sum'
}
- targets.get(joins)
+ targets.get(sources)
nodes.select.assert_called_with(fn.Sum(nodes.field))
assert nodes_query.join().execute.call_count == 1
-def test_get_log_query(targets, joins, nodes_query, logger):
- targets.get(joins)
+def test_get_log_query(targets, sources, nodes_query, logger):
+ targets.get(sources)
calls = [call.logger.log('get-targets', nodes_query.join())]
logger.log.assert_has_calls(calls)
-def test_get_log_targets_count(targets, joins, nodes_query, logger):
- targets.get(joins)
+def test_get_log_targets_count(targets, sources, nodes_query, logger):
+ targets.get(sources)
calls = [call.logger.log('get-targets-count', nodes_query.join().count())]
logger.log.assert_has_calls(calls)
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 0,
"test_score": 0
},
"num_modified_files": 3
} | 0.31 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"pytest",
"pytest-mock"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc",
"pip install psycopg2-binary pymysql"
],
"python": "3.6",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | aratrum==0.3.2
attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work
certifi==2021.5.30
click==8.0.4
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
-e git+https://github.com/wearewhys/magnivore.git@c7ede540cfa23acdc9030772d46252d3114845fe#egg=magnivore
more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work
packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work
peewee==3.17.9
pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work
psycopg2-binary==2.9.5
py @ file:///opt/conda/conda-bld/py_1644396412707/work
PyMySQL==1.0.2
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pytest==6.2.4
pytest-mock==3.6.1
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
ujson==4.3.0
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
| name: magnivore
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=21.4.0=pyhd3eb1b0_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- importlib-metadata=4.8.1=py36h06a4308_0
- importlib_metadata=4.8.1=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- more-itertools=8.12.0=pyhd3eb1b0_0
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=21.3=pyhd3eb1b0_0
- pip=21.2.2=py36h06a4308_0
- pluggy=0.13.1=py36h06a4308_0
- py=1.11.0=pyhd3eb1b0_0
- pyparsing=3.0.4=pyhd3eb1b0_0
- pytest=6.2.4=py36h06a4308_2
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- toml=0.10.2=pyhd3eb1b0_0
- typing_extensions=4.1.1=pyh06a4308_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zipp=3.6.0=pyhd3eb1b0_0
- zlib=1.2.13=h5eee18b_1
- pip:
- aratrum==0.3.2
- click==8.0.4
- peewee==3.17.9
- psycopg2-binary==2.9.5
- pymysql==1.0.2
- pytest-mock==3.6.1
- ujson==4.3.0
prefix: /opt/conda/envs/magnivore
| [
"tests/integration/RulesParser.py::test_transform",
"tests/integration/RulesParser.py::test_transform_track",
"tests/integration/RulesParser.py::test_transform_match",
"tests/unit/RulesParser.py::test_parse",
"tests/unit/RulesParser.py::test_parse_list",
"tests/unit/RulesParser.py::test_parse_track",
"tests/unit/RulesParser.py::test_parse_track_none",
"tests/unit/RulesParser.py::test_parse_sync",
"tests/unit/RulesParser.py::test_parse_log_table",
"tests/unit/RulesParser.py::test_parse_log_label"
]
| []
| [
"tests/integration/Targets.py::test_get",
"tests/unit/RulesParser.py::test_rules_parser_init_configfile",
"tests/unit/Targets.py::test_get_targets_empty",
"tests/unit/Targets.py::test_get",
"tests/unit/Targets.py::test_get_triple_join",
"tests/unit/Targets.py::test_get_limit",
"tests/unit/Targets.py::test_get_limit_with_offset",
"tests/unit/Targets.py::test_get_switch",
"tests/unit/Targets.py::test_get_join_on",
"tests/unit/Targets.py::test_get_join_outer",
"tests/unit/Targets.py::test_get_conditions",
"tests/unit/Targets.py::test_get_conditions_greater[gt]",
"tests/unit/Targets.py::test_get_conditions_greater[lt]",
"tests/unit/Targets.py::test_get_conditions_greater[not]",
"tests/unit/Targets.py::test_get_conditions_in",
"tests/unit/Targets.py::test_get_conditions_isnull",
"tests/unit/Targets.py::test_get_aggregations",
"tests/unit/Targets.py::test_get_aggregations_eq",
"tests/unit/Targets.py::test_get_picks",
"tests/unit/Targets.py::test_get_picks_sum",
"tests/unit/Targets.py::test_get_log_query",
"tests/unit/Targets.py::test_get_log_targets_count"
]
| []
| Apache License 2.0 | 1,904 | [
"README.rst",
"magnivore/RulesParser.py",
"magnivore/Targets.py"
]
| [
"README.rst",
"magnivore/RulesParser.py",
"magnivore/Targets.py"
]
|
|
Azure__msrest-for-python-67 | 24deba7a7a9e335314058ec2d0b39a710f61be60 | 2017-11-20 21:05:32 | 24deba7a7a9e335314058ec2d0b39a710f61be60 | diff --git a/msrest/service_client.py b/msrest/service_client.py
index eed50c5..d86fcbb 100644
--- a/msrest/service_client.py
+++ b/msrest/service_client.py
@@ -164,10 +164,15 @@ class ServiceClient(object):
"""
if content is None:
content = {}
- file_data = {f: self._format_data(d) for f, d in content.items()}
- if headers:
- headers.pop('Content-Type', None)
- return self.send(request, headers, None, files=file_data, **config)
+ content_type = headers.pop('Content-Type', None) if headers else None
+
+ if content_type and content_type.lower() == 'application/x-www-form-urlencoded':
+ # Do NOT use "add_content" that assumes input is JSON
+ request.data = {f: d for f, d in content.items() if d is not None}
+ return self.send(request, headers, None, **config)
+ else: # Assume "multipart/form-data"
+ file_data = {f: self._format_data(d) for f, d in content.items() if d is not None}
+ return self.send(request, headers, None, files=file_data, **config)
def send(self, request, headers=None, content=None, **config):
"""Prepare and send request object according to configuration.
| Optional formData parameters crash msrest
If a parameter that is supposed to be formData is optional, we give `None` to requests:
```python
files = [('Text', (None, 'cognituve services')), ('Mode', (None, None)), ('PreContextText', (None, None)), ('PostContextText', (None, None))]
data = {}
@staticmethod
def _encode_files(files, data):
"""Build the body for a multipart/form-data request.
Will successfully encode files when passed as a dict or a list of
tuples. Order is retained if data is a list of tuples but arbitrary
if parameters are supplied as a dict.
The tuples may be 2-tuples (filename, fileobj), 3-tuples (filename, fileobj, contentype)
or 4-tuples (filename, fileobj, contentype, custom_headers).
"""
if (not files):
raise ValueError("Files must be provided.")
elif isinstance(data, basestring):
raise ValueError("Data must not be a string.")
new_fields = []
fields = to_key_val_list(data or {})
files = to_key_val_list(files or {})
for field, val in fields:
if isinstance(val, basestring) or not hasattr(val, '__iter__'):
val = [val]
for v in val:
if v is not None:
# Don't call str() on bytestrings: in Py3 it all goes wrong.
if not isinstance(v, bytes):
v = str(v)
new_fields.append(
(field.decode('utf-8') if isinstance(field, bytes) else field,
v.encode('utf-8') if isinstance(v, str) else v))
for (k, v) in files:
# support for explicit filename
ft = None
fh = None
if isinstance(v, (tuple, list)):
if len(v) == 2:
fn, fp = v
elif len(v) == 3:
fn, fp, ft = v
else:
fn, fp, ft, fh = v
else:
fn = guess_filename(v) or k
fp = v
if isinstance(fp, (str, bytes, bytearray)):
fdata = fp
else:
> fdata = fp.read()
E AttributeError: 'NoneType' object has no attribute 'read'
``` | Azure/msrest-for-python | diff --git a/tests/test_client.py b/tests/test_client.py
index ee10d48..650eac5 100644
--- a/tests/test_client.py
+++ b/tests/test_client.py
@@ -204,6 +204,17 @@ class TestServiceClient(unittest.TestCase):
ServiceClient.send_formdata(mock_client, request, {'Content-Type':'1234'}, {'1':'1', '2':'2'})
mock_client.send.assert_called_with(request, {}, None, files={'1':'formatted', '2':'formatted'})
+ ServiceClient.send_formdata(mock_client, request, {'Content-Type':'1234'}, {'1':'1', '2':None})
+ mock_client.send.assert_called_with(request, {}, None, files={'1':'formatted'})
+
+ ServiceClient.send_formdata(mock_client, request, {'Content-Type':'application/x-www-form-urlencoded'}, {'1':'1', '2':'2'})
+ mock_client.send.assert_called_with(request, {}, None)
+ self.assertEqual(request.data, {'1':'1', '2':'2'})
+
+ ServiceClient.send_formdata(mock_client, request, {'Content-Type':'application/x-www-form-urlencoded'}, {'1':'1', '2':None})
+ mock_client.send.assert_called_with(request, {}, None)
+ self.assertEqual(request.data, {'1':'1'})
+
def test_format_data(self):
mock_client = mock.create_autospec(ServiceClient)
| {
"commit_name": "head_commit",
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 0,
"test_score": 0
},
"num_modified_files": 1
} | 0.4 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"numpy>=1.16.0",
"pandas>=1.0.0"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": [
"requirements/base.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | certifi==2025.1.31
charset-normalizer==3.4.1
exceptiongroup==1.2.2
idna==3.10
iniconfig==2.1.0
isodate==0.7.2
-e git+https://github.com/Azure/msrest-for-python.git@24deba7a7a9e335314058ec2d0b39a710f61be60#egg=msrest
numpy==2.0.2
oauthlib==3.2.2
packaging==24.2
pandas==2.2.3
pluggy==1.5.0
pytest==8.3.5
python-dateutil==2.9.0.post0
pytz==2025.2
requests==2.32.3
requests-oauthlib==2.0.0
six==1.17.0
tomli==2.2.1
tzdata==2025.2
urllib3==2.3.0
| name: msrest-for-python
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- certifi==2025.1.31
- charset-normalizer==3.4.1
- exceptiongroup==1.2.2
- idna==3.10
- iniconfig==2.1.0
- isodate==0.7.2
- numpy==2.0.2
- oauthlib==3.2.2
- packaging==24.2
- pandas==2.2.3
- pluggy==1.5.0
- pytest==8.3.5
- python-dateutil==2.9.0.post0
- pytz==2025.2
- requests==2.32.3
- requests-oauthlib==2.0.0
- six==1.17.0
- tomli==2.2.1
- tzdata==2025.2
- urllib3==2.3.0
prefix: /opt/conda/envs/msrest-for-python
| [
"tests/test_client.py::TestServiceClient::test_client_formdata_send"
]
| []
| [
"tests/test_client.py::TestServiceClient::test_client_header",
"tests/test_client.py::TestServiceClient::test_client_request",
"tests/test_client.py::TestServiceClient::test_client_send",
"tests/test_client.py::TestServiceClient::test_format_data",
"tests/test_client.py::TestServiceClient::test_format_url",
"tests/test_client.py::TestServiceClient::test_session_callback"
]
| []
| MIT License | 1,905 | [
"msrest/service_client.py"
]
| [
"msrest/service_client.py"
]
|
|
PyCQA__pyflakes-313 | 8d0f995dafda7105a6966057fd11383f1ea6fb71 | 2017-11-21 03:44:16 | 8a1feac08dae2478e3f67ab4018af86ff4ec56f0 | taion: Hold on, this breaks on http://mypy.readthedocs.io/en/latest/kinds_of_types.html#class-name-forward-references.
taion: This is ready to go now.
taion: Sorry for the repeated updates. This is now fixed.
myint: Thanks!
I was testing this against the CPython standard library and it seemed to crash when run against one of the test files ([`test_functools.py`](https://github.com/python/cpython/blob/bdb8315c21825487b54852ff0511fb4881ea2181/Lib/test/test_functools.py)). You can reproduce it by doing the above or more specifically:
```
$ wget https://raw.githubusercontent.com/python/cpython/bdb8315c21825487b54852ff0511fb4881ea2181/Lib/test/test_functools.py
$ ./py/bin/pyflakes test_functools.py
Traceback (most recent call last):
File "./py/bin/pyflakes", line 11, in <module>
load_entry_point('pyflakes==1.6.0', 'console_scripts', 'pyflakes')()
File "/Users/myint/tmp/pyflakes/py/lib/python3.6/site-packages/pyflakes/api.py", line 208, in main
warnings = checkRecursive(args, reporter)
File "/Users/myint/tmp/pyflakes/py/lib/python3.6/site-packages/pyflakes/api.py", line 165, in checkRecursive
warnings += checkPath(sourcePath, reporter)
File "/Users/myint/tmp/pyflakes/py/lib/python3.6/site-packages/pyflakes/api.py", line 112, in checkPath
return check(codestr, filename, reporter)
File "/Users/myint/tmp/pyflakes/py/lib/python3.6/site-packages/pyflakes/api.py", line 73, in check
w = checker.Checker(tree, filename)
File "/Users/myint/tmp/pyflakes/py/lib/python3.6/site-packages/pyflakes/checker.py", line 498, in __init__
self.runDeferred(self._deferredFunctions)
File "/Users/myint/tmp/pyflakes/py/lib/python3.6/site-packages/pyflakes/checker.py", line 535, in runDeferred
handler()
File "/Users/myint/tmp/pyflakes/py/lib/python3.6/site-packages/pyflakes/checker.py", line 929, in handleForwardAnnotation
parsed = ast.parse(annotation.s).body[0].value
File "/opt/local/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ast.py", line 35, in parse
return compile(source, filename, mode, PyCF_ONLY_AST)
File "<unknown>", line 1
This is a new annotation
^
SyntaxError: invalid syntax
```
taion: Ah, my bad. Didn't handle annotations that weren't actually annotations. I've addressed it now and added test cases.
I've also added a new reported error here since there weren't any existing errors that covered this, and I don't think there are any reasons to want illegal annotations in normal code.
If you think this new error is reasonable, could you please advise on whether the naming is appropriate, given that this will be user-facing? The alternative would be to refer to this as a "string literal annotation" rather than a "forward annotation".
taion: Rebased and squashed.
Can you confirm that you're okay with the naming and the semantics around the new error? Something like `a: 'A B'` or `a: 'A; B'` is legal Python, but I think it's vanishing unlikely to actually be intentionally used. | diff --git a/pyflakes/checker.py b/pyflakes/checker.py
index d8f093a..a070822 100644
--- a/pyflakes/checker.py
+++ b/pyflakes/checker.py
@@ -922,6 +922,39 @@ class Checker(object):
self.popScope()
self.scopeStack = saved_stack
+ def handleAnnotation(self, annotation, node):
+ if isinstance(annotation, ast.Str):
+ # Defer handling forward annotation.
+ def handleForwardAnnotation():
+ try:
+ tree = ast.parse(annotation.s)
+ except SyntaxError:
+ self.report(
+ messages.ForwardAnnotationSyntaxError,
+ node,
+ annotation.s,
+ )
+ return
+
+ body = tree.body
+ if len(body) != 1 or not isinstance(body[0], ast.Expr):
+ self.report(
+ messages.ForwardAnnotationSyntaxError,
+ node,
+ annotation.s,
+ )
+ return
+
+ parsed_annotation = tree.body[0].value
+ for descendant in ast.walk(parsed_annotation):
+ ast.copy_location(descendant, annotation)
+
+ self.handleNode(parsed_annotation, node)
+
+ self.deferFunction(handleForwardAnnotation)
+ else:
+ self.handleNode(annotation, node)
+
def ignore(self, node):
pass
@@ -1160,9 +1193,11 @@ class Checker(object):
if arg in args[:idx]:
self.report(messages.DuplicateArgument, node, arg)
- for child in annotations + defaults:
- if child:
- self.handleNode(child, node)
+ for annotation in annotations:
+ self.handleAnnotation(annotation, node)
+
+ for default in defaults:
+ self.handleNode(default, node)
def runFunction():
@@ -1375,7 +1410,7 @@ class Checker(object):
# Otherwise it's not really ast.Store and shouldn't silence
# UndefinedLocal warnings.
self.handleNode(node.target, node)
- self.handleNode(node.annotation, node)
+ self.handleAnnotation(node.annotation, node)
if node.value:
# If the assignment has value, handle the *value* now.
self.handleNode(node.value, node)
diff --git a/pyflakes/messages.py b/pyflakes/messages.py
index 9e9406c..670f95f 100644
--- a/pyflakes/messages.py
+++ b/pyflakes/messages.py
@@ -231,3 +231,11 @@ class AssertTuple(Message):
Assertion test is a tuple, which are always True.
"""
message = 'assertion is always true, perhaps remove parentheses?'
+
+
+class ForwardAnnotationSyntaxError(Message):
+ message = 'syntax error in forward annotation %r'
+
+ def __init__(self, filename, loc, annotation):
+ Message.__init__(self, filename, loc)
+ self.message_args = (annotation,)
| Typing.TYPE_CHECKING imports raise F401
```
$ pip install flake8
```
```
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from my_module.test_class import MyClass
object: 'MyClass' = None
```
Flake 8 gives the following error in this scenario:
`my_module\test_class.py:4:5: F401 'my_module.test_class.MyClass' imported but unused`
My current work around is this:
```
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from my_module.test_class import MyClass # noqa
object: 'MyClass' = None
```
Any better solutions? Couldwe somehow automatically ignore all F401 errors within the `if TYPE_CHECKING:` block? | PyCQA/pyflakes | diff --git a/pyflakes/test/test_other.py b/pyflakes/test/test_other.py
index ba052f1..14f213c 100644
--- a/pyflakes/test/test_other.py
+++ b/pyflakes/test/test_other.py
@@ -1890,3 +1890,77 @@ class TestAsyncStatements(TestCase):
class C:
foo: not_a_real_type = None
''', m.UndefinedName)
+ self.flakes('''
+ from foo import Bar
+ bar: Bar
+ ''')
+ self.flakes('''
+ from foo import Bar
+ bar: 'Bar'
+ ''')
+ self.flakes('''
+ import foo
+ bar: foo.Bar
+ ''')
+ self.flakes('''
+ import foo
+ bar: 'foo.Bar'
+ ''')
+ self.flakes('''
+ from foo import Bar
+ def f(bar: Bar): pass
+ ''')
+ self.flakes('''
+ from foo import Bar
+ def f(bar: 'Bar'): pass
+ ''')
+ self.flakes('''
+ from foo import Bar
+ def f(bar) -> Bar: return bar
+ ''')
+ self.flakes('''
+ from foo import Bar
+ def f(bar) -> 'Bar': return bar
+ ''')
+ self.flakes('''
+ bar: 'Bar'
+ ''', m.UndefinedName)
+ self.flakes('''
+ bar: 'foo.Bar'
+ ''', m.UndefinedName)
+ self.flakes('''
+ from foo import Bar
+ bar: str
+ ''', m.UnusedImport)
+ self.flakes('''
+ from foo import Bar
+ def f(bar: str): pass
+ ''', m.UnusedImport)
+ self.flakes('''
+ def f(a: A) -> A: pass
+ class A: pass
+ ''', m.UndefinedName, m.UndefinedName)
+ self.flakes('''
+ def f(a: 'A') -> 'A': return a
+ class A: pass
+ ''')
+ self.flakes('''
+ a: A
+ class A: pass
+ ''', m.UndefinedName)
+ self.flakes('''
+ a: 'A'
+ class A: pass
+ ''')
+ self.flakes('''
+ a: 'A B'
+ ''', m.ForwardAnnotationSyntaxError)
+ self.flakes('''
+ a: 'A; B'
+ ''', m.ForwardAnnotationSyntaxError)
+ self.flakes('''
+ a: '1 + 2'
+ ''')
+ self.flakes('''
+ a: 'a: "A"'
+ ''', m.ForwardAnnotationSyntaxError)
| {
"commit_name": "merge_commit",
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 0,
"test_score": 0
},
"num_modified_files": 2
} | 1.6 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"flake8",
"pytest"
],
"pre_install": null,
"python": "3.6",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work
certifi==2021.5.30
flake8==5.0.4
importlib-metadata==4.2.0
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
mccabe==0.7.0
more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work
packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work
pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pycodestyle==2.9.1
-e git+https://github.com/PyCQA/pyflakes.git@8d0f995dafda7105a6966057fd11383f1ea6fb71#egg=pyflakes
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pytest==6.2.4
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
| name: pyflakes
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=21.4.0=pyhd3eb1b0_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- importlib_metadata=4.8.1=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- more-itertools=8.12.0=pyhd3eb1b0_0
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=21.3=pyhd3eb1b0_0
- pip=21.2.2=py36h06a4308_0
- pluggy=0.13.1=py36h06a4308_0
- py=1.11.0=pyhd3eb1b0_0
- pyparsing=3.0.4=pyhd3eb1b0_0
- pytest=6.2.4=py36h06a4308_2
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- toml=0.10.2=pyhd3eb1b0_0
- typing_extensions=4.1.1=pyh06a4308_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zipp=3.6.0=pyhd3eb1b0_0
- zlib=1.2.13=h5eee18b_1
- pip:
- flake8==5.0.4
- importlib-metadata==4.2.0
- mccabe==0.7.0
- pycodestyle==2.9.1
prefix: /opt/conda/envs/pyflakes
| [
"pyflakes/test/test_other.py::TestAsyncStatements::test_variable_annotations"
]
| []
| [
"pyflakes/test/test_other.py::Test::test_attrAugmentedAssignment",
"pyflakes/test/test_other.py::Test::test_breakInsideLoop",
"pyflakes/test/test_other.py::Test::test_breakOutsideLoop",
"pyflakes/test/test_other.py::Test::test_classFunctionDecorator",
"pyflakes/test/test_other.py::Test::test_classNameDefinedPreviously",
"pyflakes/test/test_other.py::Test::test_classNameUndefinedInClassBody",
"pyflakes/test/test_other.py::Test::test_classRedefinedAsFunction",
"pyflakes/test/test_other.py::Test::test_classRedefinition",
"pyflakes/test/test_other.py::Test::test_classWithReturn",
"pyflakes/test/test_other.py::Test::test_classWithYield",
"pyflakes/test/test_other.py::Test::test_classWithYieldFrom",
"pyflakes/test/test_other.py::Test::test_comparison",
"pyflakes/test/test_other.py::Test::test_containment",
"pyflakes/test/test_other.py::Test::test_continueInFinally",
"pyflakes/test/test_other.py::Test::test_continueInsideLoop",
"pyflakes/test/test_other.py::Test::test_continueOutsideLoop",
"pyflakes/test/test_other.py::Test::test_defaultExceptLast",
"pyflakes/test/test_other.py::Test::test_defaultExceptNotLast",
"pyflakes/test/test_other.py::Test::test_doubleAssignmentConditionally",
"pyflakes/test/test_other.py::Test::test_doubleAssignmentWithUse",
"pyflakes/test/test_other.py::Test::test_duplicateArgs",
"pyflakes/test/test_other.py::Test::test_ellipsis",
"pyflakes/test/test_other.py::Test::test_extendedSlice",
"pyflakes/test/test_other.py::Test::test_functionDecorator",
"pyflakes/test/test_other.py::Test::test_functionRedefinedAsClass",
"pyflakes/test/test_other.py::Test::test_globalDeclaredInDifferentScope",
"pyflakes/test/test_other.py::Test::test_identity",
"pyflakes/test/test_other.py::Test::test_localReferencedBeforeAssignment",
"pyflakes/test/test_other.py::Test::test_loopControl",
"pyflakes/test/test_other.py::Test::test_modernProperty",
"pyflakes/test/test_other.py::Test::test_moduleWithReturn",
"pyflakes/test/test_other.py::Test::test_moduleWithYield",
"pyflakes/test/test_other.py::Test::test_moduleWithYieldFrom",
"pyflakes/test/test_other.py::Test::test_redefinedClassFunction",
"pyflakes/test/test_other.py::Test::test_redefinedFunction",
"pyflakes/test/test_other.py::Test::test_redefinedIfElseFunction",
"pyflakes/test/test_other.py::Test::test_redefinedIfElseInListComp",
"pyflakes/test/test_other.py::Test::test_redefinedIfFunction",
"pyflakes/test/test_other.py::Test::test_redefinedInDictComprehension",
"pyflakes/test/test_other.py::Test::test_redefinedInGenerator",
"pyflakes/test/test_other.py::Test::test_redefinedInSetComprehension",
"pyflakes/test/test_other.py::Test::test_redefinedTryExceptFunction",
"pyflakes/test/test_other.py::Test::test_redefinedTryFunction",
"pyflakes/test/test_other.py::Test::test_starredAssignmentErrors",
"pyflakes/test/test_other.py::Test::test_starredAssignmentNoError",
"pyflakes/test/test_other.py::Test::test_unaryPlus",
"pyflakes/test/test_other.py::Test::test_undefinedBaseClass",
"pyflakes/test/test_other.py::Test::test_varAugmentedAssignment",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assert_static",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assert_tuple",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assert_tuple_empty",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assert_with_message",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assert_without_message",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assignInForLoop",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assignInListComprehension",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assignToGlobal",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assignToMember",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assignToNonlocal",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_assignmentInsideLoop",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_augmentedAssignmentImportedFunctionCall",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_closedOver",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_dictComprehension",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_doubleClosedOver",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_exceptWithoutNameInFunction",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_exceptWithoutNameInFunctionTuple",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_exceptionUnusedInExcept",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_exceptionUnusedInExceptInFunction",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_exceptionUsedInExcept",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_f_string",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_generatorExpression",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_ifexp",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_listUnpacking",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_setComprehensionAndLiteral",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_tracebackhideSpecialVariable",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_tupleUnpacking",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_unusedVariable",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_unusedVariableAsLocals",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_unusedVariableNoLocals",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_variableUsedInLoop",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementAttributeName",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementComplicatedTarget",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementListNames",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementNameDefinedInBody",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementNoNames",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementSingleName",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementSingleNameRedefined",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementSingleNameUndefined",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementSubscript",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementSubscriptUndefined",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementTupleNames",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementTupleNamesRedefined",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementTupleNamesUndefined",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementUndefinedInExpression",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_withStatementUndefinedInside",
"pyflakes/test/test_other.py::TestUnusedAssignment::test_yieldFromUndefined",
"pyflakes/test/test_other.py::TestAsyncStatements::test_asyncDef",
"pyflakes/test/test_other.py::TestAsyncStatements::test_asyncDefAwait",
"pyflakes/test/test_other.py::TestAsyncStatements::test_asyncDefUndefined",
"pyflakes/test/test_other.py::TestAsyncStatements::test_asyncFor",
"pyflakes/test/test_other.py::TestAsyncStatements::test_asyncWith",
"pyflakes/test/test_other.py::TestAsyncStatements::test_asyncWithItem",
"pyflakes/test/test_other.py::TestAsyncStatements::test_continueInAsyncForFinally",
"pyflakes/test/test_other.py::TestAsyncStatements::test_formatstring",
"pyflakes/test/test_other.py::TestAsyncStatements::test_loopControlInAsyncFor",
"pyflakes/test/test_other.py::TestAsyncStatements::test_loopControlInAsyncForElse",
"pyflakes/test/test_other.py::TestAsyncStatements::test_matmul"
]
| []
| MIT License | 1,906 | [
"pyflakes/messages.py",
"pyflakes/checker.py"
]
| [
"pyflakes/messages.py",
"pyflakes/checker.py"
]
|
dropbox__pyannotate-26 | ba80fabf4d9bb9888e8b46bbd47affc5766470f8 | 2017-11-21 09:56:07 | 40edbfeed62a78cd683cd3eb56a7412ae40dd124 | NeonGraal: I've signed the CLA now too | diff --git a/pyannotate_tools/annotations/__main__.py b/pyannotate_tools/annotations/__main__.py
index 709fafa..f1c8190 100644
--- a/pyannotate_tools/annotations/__main__.py
+++ b/pyannotate_tools/annotations/__main__.py
@@ -42,7 +42,7 @@ def main():
# Run pass 2 with output written to a temporary file.
infile = args.type_info
- generate_annotations_json(infile, tf.name)
+ generate_annotations_json(infile, tf.name, target_stream=tf)
# Run pass 3 reading from a temporary file.
FixAnnotateJson.stub_json_file = tf.name
diff --git a/pyannotate_tools/annotations/main.py b/pyannotate_tools/annotations/main.py
index 123fa0c..aea22c2 100644
--- a/pyannotate_tools/annotations/main.py
+++ b/pyannotate_tools/annotations/main.py
@@ -2,7 +2,7 @@
import json
-from typing import List
+from typing import List, Optional, IO
from mypy_extensions import TypedDict
from pyannotate_tools.annotations.types import ARG_STAR, ARG_STARSTAR
@@ -22,8 +22,8 @@ FunctionData = TypedDict('FunctionData', {'path': str,
'samples': int})
-def generate_annotations_json(source_path, target_path):
- # type: (str, str) -> None
+def generate_annotations_json(source_path, target_path, source_stream=None, target_stream=None):
+ # type: (str, str, Optional[IO[str]], Optional[IO[str]]) -> None
"""Produce annotation data JSON file from a JSON file with runtime-collected types.
Data formats:
@@ -31,7 +31,7 @@ def generate_annotations_json(source_path, target_path):
* The source JSON is a list of pyannotate_tools.annotations.parse.RawEntry items.
* The output JSON is a list of FunctionData items.
"""
- items = parse_json(source_path)
+ items = parse_json(source_path, source_stream)
results = []
for item in items:
arg_types, return_type = infer_annotation(item.type_comments)
@@ -55,5 +55,8 @@ def generate_annotations_json(source_path, target_path):
'samples': item.samples
} # type: FunctionData
results.append(data)
- with open(target_path, 'w') as f:
- json.dump(results, f, sort_keys=True, indent=4)
+ if target_stream:
+ json.dump(results, target_stream, sort_keys=True, indent=4)
+ else:
+ with open(target_path, 'w') as f:
+ json.dump(results, f, sort_keys=True, indent=4)
diff --git a/pyannotate_tools/annotations/parse.py b/pyannotate_tools/annotations/parse.py
index 28a7851..bc9d3c1 100644
--- a/pyannotate_tools/annotations/parse.py
+++ b/pyannotate_tools/annotations/parse.py
@@ -9,7 +9,7 @@ import json
import re
import sys
-from typing import Any, List, Mapping, Set, Tuple
+from typing import Any, List, Mapping, Set, Tuple, Optional, IO
from typing_extensions import Text
from mypy_extensions import NoReturn, TypedDict
@@ -86,14 +86,17 @@ class ParseError(Exception):
self.comment = comment
-def parse_json(path):
- # type: (str) -> List[FunctionInfo]
+def parse_json(path, stream=None):
+ # type: (str, Optional[IO[str]]) -> List[FunctionInfo]
"""Deserialize a JSON file containing runtime collected types.
The input JSON is expected to to have a list of RawEntry items.
"""
- with open(path) as f:
- data = json.load(f) # type: List[RawEntry]
+ if stream:
+ data = json.load(stream) # type: List[RawEntry]
+ else:
+ with open(path) as f:
+ data = json.load(f)
result = []
def assert_type(value, typ):
| Permission denied for Temp file on Windows
When I run "pyannotate --type-info ./annotate.json ." with on Windows (both 2.7.14 and 3.6.3, probably others) , I get the following error:
Traceback (most recent call last):
File "c:\python27\lib\runpy.py", line 174, in _run_module_as_main
"__main__", fname, loader, pkg_name)
File "c:\python27\lib\runpy.py", line 72, in _run_code
exec code in run_globals
File "C:\Python27\Scripts\pyannotate.exe\__main__.py", line 9, in <module>
File "c:\python27\lib\site-packages\pyannotate_tools\annotations\__main__.py", line 45, in main
generate_annotations_json(infile, tf.name)
File "c:\python27\lib\site-packages\pyannotate_tools\annotations\main.py", line 58, in generate_annotations_json
with open(target_path, 'w') as f:
IOError: [Errno 13] Permission denied: 'c:\\temp\\tmp2ui1ku'
A little bit of googling suggests this might be the problem [Permission Denied To Write To My Temporary File](https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file) | dropbox/pyannotate | diff --git a/pyannotate_tools/annotations/tests/main_test.py b/pyannotate_tools/annotations/tests/main_test.py
index 9609a7d..6c27a20 100644
--- a/pyannotate_tools/annotations/tests/main_test.py
+++ b/pyannotate_tools/annotations/tests/main_test.py
@@ -3,7 +3,7 @@ import tempfile
import textwrap
import unittest
-from typing import Iterator
+from typing import Iterator, Tuple, IO
from pyannotate_tools.annotations.infer import InferError
from pyannotate_tools.annotations.main import generate_annotations_json
@@ -25,10 +25,12 @@ class TestMain(unittest.TestCase):
}
]
"""
- target = tempfile.NamedTemporaryFile(mode='r')
- with self.temporary_json_file(data) as source_path:
- generate_annotations_json(source_path, target.name)
+ target = tempfile.NamedTemporaryFile(mode='w+')
+ with self.temporary_json_file(data) as source:
+ generate_annotations_json(source.name, target.name, source_stream=source, target_stream=target)
+ target.flush()
+ target.seek(0)
actual = target.read()
actual = actual.replace(' \n', '\n')
expected = textwrap.dedent("""\
@@ -66,8 +68,8 @@ class TestMain(unittest.TestCase):
]
"""
with self.assertRaises(InferError) as e:
- with self.temporary_json_file(data) as source_path:
- generate_annotations_json(source_path, '/dummy')
+ with self.temporary_json_file(data) as source:
+ generate_annotations_json(source.name, '/dummy', source_stream=source)
assert str(e.exception) == textwrap.dedent("""\
Ambiguous argument kinds:
(List[int], str) -> None
@@ -75,8 +77,9 @@ class TestMain(unittest.TestCase):
@contextlib.contextmanager
def temporary_json_file(self, data):
- # type: (str) -> Iterator[str]
- with tempfile.NamedTemporaryFile(mode='w') as source:
+ # type: (str) -> Iterator[IO[str]]
+ with tempfile.NamedTemporaryFile(mode='w+') as source:
source.write(data)
source.flush()
- yield source.name
+ source.seek(0)
+ yield source
diff --git a/pyannotate_tools/annotations/tests/parse_test.py b/pyannotate_tools/annotations/tests/parse_test.py
index c0daeb2..78650fb 100644
--- a/pyannotate_tools/annotations/tests/parse_test.py
+++ b/pyannotate_tools/annotations/tests/parse_test.py
@@ -40,11 +40,12 @@ class TestParseJson(unittest.TestCase):
}
]
"""
- with tempfile.NamedTemporaryFile(mode='w') as f:
+ with tempfile.NamedTemporaryFile(mode='w+') as f:
f.write(data)
f.flush()
+ f.seek(0)
- result = parse_json(f.name)
+ result = parse_json(f.name, f)
assert len(result) == 1
item = result[0]
assert item.path == 'pkg/thing.py'
| {
"commit_name": "merge_commit",
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 0,
"test_score": 2
},
"num_modified_files": 3
} | 1.0 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest"
],
"pre_install": null,
"python": "3.6",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs==22.2.0
certifi==2021.5.30
importlib-metadata==4.8.3
iniconfig==1.1.1
mypy-extensions==1.0.0
packaging==21.3
pluggy==1.0.0
py==1.11.0
-e git+https://github.com/dropbox/pyannotate.git@ba80fabf4d9bb9888e8b46bbd47affc5766470f8#egg=pyannotate
pyparsing==3.1.4
pytest==7.0.1
six==1.17.0
tomli==1.2.3
typing==3.7.4.3
typing_extensions==4.1.1
zipp==3.6.0
| name: pyannotate
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- attrs==22.2.0
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- mypy-extensions==1.0.0
- packaging==21.3
- pluggy==1.0.0
- py==1.11.0
- pyparsing==3.1.4
- pytest==7.0.1
- six==1.17.0
- tomli==1.2.3
- typing==3.7.4.3
- typing-extensions==4.1.1
- zipp==3.6.0
prefix: /opt/conda/envs/pyannotate
| [
"pyannotate_tools/annotations/tests/main_test.py::TestMain::test_ambiguous_kind",
"pyannotate_tools/annotations/tests/main_test.py::TestMain::test_generation",
"pyannotate_tools/annotations/tests/parse_test.py::TestParseJson::test_parse_json"
]
| []
| [
"pyannotate_tools/annotations/tests/parse_test.py::TestParseError::test_str_conversion",
"pyannotate_tools/annotations/tests/parse_test.py::TestTokenize::test_special_cases",
"pyannotate_tools/annotations/tests/parse_test.py::TestTokenize::test_tokenize",
"pyannotate_tools/annotations/tests/parse_test.py::TestParseTypeComment::test_any_and_unknown",
"pyannotate_tools/annotations/tests/parse_test.py::TestParseTypeComment::test_bad_annotation",
"pyannotate_tools/annotations/tests/parse_test.py::TestParseTypeComment::test_empty",
"pyannotate_tools/annotations/tests/parse_test.py::TestParseTypeComment::test_function",
"pyannotate_tools/annotations/tests/parse_test.py::TestParseTypeComment::test_generic",
"pyannotate_tools/annotations/tests/parse_test.py::TestParseTypeComment::test_optional",
"pyannotate_tools/annotations/tests/parse_test.py::TestParseTypeComment::test_simple_args",
"pyannotate_tools/annotations/tests/parse_test.py::TestParseTypeComment::test_star_args",
"pyannotate_tools/annotations/tests/parse_test.py::TestParseTypeComment::test_star_star_args",
"pyannotate_tools/annotations/tests/parse_test.py::TestParseTypeComment::test_tuple",
"pyannotate_tools/annotations/tests/parse_test.py::TestParseTypeComment::test_unicode",
"pyannotate_tools/annotations/tests/parse_test.py::TestParseTypeComment::test_union"
]
| []
| Apache License 2.0 | 1,907 | [
"pyannotate_tools/annotations/parse.py",
"pyannotate_tools/annotations/main.py",
"pyannotate_tools/annotations/__main__.py"
]
| [
"pyannotate_tools/annotations/parse.py",
"pyannotate_tools/annotations/main.py",
"pyannotate_tools/annotations/__main__.py"
]
|
wearewhys__magnivore-12 | be723f7f575376d0ce25b0590bd46dcc6f34ace8 | 2017-11-21 11:53:18 | acf182faeb0cf80157ec5d7b448b355687dcbd94 | diff --git a/magnivore/Lexicon.py b/magnivore/Lexicon.py
index f9fa08d..84ae7a2 100644
--- a/magnivore/Lexicon.py
+++ b/magnivore/Lexicon.py
@@ -1,5 +1,6 @@
# -*- coding: utf-8 -*-
import re
+from decimal import Decimal
from functools import reduce
from .Tracker import Tracker
@@ -38,7 +39,8 @@ class Lexicon:
The factor rule multiplies the value by a factor.
"""
value = cls._dot_reduce(rule['from'], target)
- return value * rule['factor']
+ original_type = type(value)
+ return original_type(Decimal(value) * Decimal(rule['factor']))
@classmethod
def format(cls, rule, target):
| Lexicon.factor should check the type of the values
Lexicon.factor should check the values types or errors will happen | wearewhys/magnivore | diff --git a/tests/unit/Lexicon.py b/tests/unit/Lexicon.py
index 4f8e888..f1c85d6 100644
--- a/tests/unit/Lexicon.py
+++ b/tests/unit/Lexicon.py
@@ -1,5 +1,6 @@
# -*- coding: utf-8 -*-
import re
+from decimal import Decimal
from unittest.mock import MagicMock
from magnivore.Lexicon import Lexicon
@@ -48,17 +49,20 @@ def test_lexicon_transform(target):
assert result == rule['transform'][target.temperature]
[email protected]('from_data, target', [
- ('value', MagicMock(value=100)),
- ('related.value', MagicMock(related=MagicMock(value=100)))
[email protected]('from_data, target, expected', [
+ ('value', MagicMock(value=100), 50),
+ ('value', MagicMock(value=Decimal(100)), Decimal(50)),
+ ('value', MagicMock(value=100.0), 50.0),
+ ('related.value', MagicMock(related=MagicMock(value=100)), 50)
])
-def test_lexicon_factor(from_data, target):
+def test_lexicon_factor(from_data, target, expected):
rule = {
'from': from_data,
'factor': 0.5
}
result = Lexicon.factor(rule, target)
- assert result == 50
+ assert result == expected
+ assert type(result) == type(expected)
@mark.parametrize('from_data, format, expected', [
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 3,
"test_score": 1
},
"num_modified_files": 1
} | 0.4 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"pytest",
"pytest-mock"
],
"pre_install": null,
"python": "3.6",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | aratrum==0.3.2
attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work
certifi==2021.5.30
click==8.0.4
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
-e git+https://github.com/wearewhys/magnivore.git@be723f7f575376d0ce25b0590bd46dcc6f34ace8#egg=magnivore
more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work
packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work
peewee==3.17.9
pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pytest==6.2.4
pytest-mock==3.6.1
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
ujson==4.3.0
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
| name: magnivore
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=21.4.0=pyhd3eb1b0_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- importlib-metadata=4.8.1=py36h06a4308_0
- importlib_metadata=4.8.1=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- more-itertools=8.12.0=pyhd3eb1b0_0
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=21.3=pyhd3eb1b0_0
- pip=21.2.2=py36h06a4308_0
- pluggy=0.13.1=py36h06a4308_0
- py=1.11.0=pyhd3eb1b0_0
- pyparsing=3.0.4=pyhd3eb1b0_0
- pytest=6.2.4=py36h06a4308_2
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- toml=0.10.2=pyhd3eb1b0_0
- typing_extensions=4.1.1=pyh06a4308_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zipp=3.6.0=pyhd3eb1b0_0
- zlib=1.2.13=h5eee18b_1
- pip:
- aratrum==0.3.2
- click==8.0.4
- peewee==3.17.9
- pytest-mock==3.6.1
- ujson==4.3.0
prefix: /opt/conda/envs/magnivore
| [
"tests/unit/Lexicon.py::test_lexicon_factor[value-target0-50]",
"tests/unit/Lexicon.py::test_lexicon_factor[value-target1-expected1]",
"tests/unit/Lexicon.py::test_lexicon_factor[related.value-target3-50]"
]
| []
| [
"tests/unit/Lexicon.py::test_lexicon_basic",
"tests/unit/Lexicon.py::test_lexicon_basic_dot",
"tests/unit/Lexicon.py::test_lexicon_basic_dot_double",
"tests/unit/Lexicon.py::test_lexicon_basic_null[field]",
"tests/unit/Lexicon.py::test_lexicon_basic_null[table.field]",
"tests/unit/Lexicon.py::test_lexicon_basic_null[table.field.nested]",
"tests/unit/Lexicon.py::test_lexicon_transform[target0]",
"tests/unit/Lexicon.py::test_lexicon_transform[target1]",
"tests/unit/Lexicon.py::test_lexicon_factor[value-target2-50.0]",
"tests/unit/Lexicon.py::test_lexicon_format[birthyear-{}-0-0-1992-0-0]",
"tests/unit/Lexicon.py::test_lexicon_format[from_data1-{}-{}-0-1992-9-0]",
"tests/unit/Lexicon.py::test_lexicon_format_dot[rel.birthyear-{}-0-0-1992-0-0]",
"tests/unit/Lexicon.py::test_lexicon_format_dot[from_data1-{}-{}-0-1992-9-0]",
"tests/unit/Lexicon.py::test_lexicon_match",
"tests/unit/Lexicon.py::test_lexicon_match_none",
"tests/unit/Lexicon.py::test_lexicon_match_from",
"tests/unit/Lexicon.py::test_lexicon_match_dot",
"tests/unit/Lexicon.py::test_lexicon_match_from_none",
"tests/unit/Lexicon.py::test_lexicon_match_none_log",
"tests/unit/Lexicon.py::test_lexicon_sync",
"tests/unit/Lexicon.py::test_lexicon_sync_none",
"tests/unit/Lexicon.py::test_lexicon_static",
"tests/unit/Lexicon.py::test_lexicon_expression",
"tests/unit/Lexicon.py::test_lexicon_expression_dot",
"tests/unit/Lexicon.py::test_lexicon_expression_none"
]
| []
| Apache License 2.0 | 1,908 | [
"magnivore/Lexicon.py"
]
| [
"magnivore/Lexicon.py"
]
|
|
wearewhys__magnivore-14 | acf182faeb0cf80157ec5d7b448b355687dcbd94 | 2017-11-21 15:44:33 | acf182faeb0cf80157ec5d7b448b355687dcbd94 | diff --git a/magnivore/Lexicon.py b/magnivore/Lexicon.py
index 84ae7a2..acf038b 100644
--- a/magnivore/Lexicon.py
+++ b/magnivore/Lexicon.py
@@ -2,6 +2,7 @@
import re
from decimal import Decimal
from functools import reduce
+from math import ceil, floor
from .Tracker import Tracker
@@ -40,7 +41,12 @@ class Lexicon:
"""
value = cls._dot_reduce(rule['from'], target)
original_type = type(value)
- return original_type(Decimal(value) * Decimal(rule['factor']))
+ result = Decimal(value) * Decimal(rule['factor'])
+ if 'round' in rule:
+ if rule['round'] == 'up':
+ return original_type(ceil(result))
+ return original_type(floor(result))
+ return original_type(result)
@classmethod
def format(cls, rule, target):
| Add possibility to specify whether to round up or down in factor | wearewhys/magnivore | diff --git a/tests/unit/Lexicon.py b/tests/unit/Lexicon.py
index f1c85d6..3af833c 100644
--- a/tests/unit/Lexicon.py
+++ b/tests/unit/Lexicon.py
@@ -65,6 +65,19 @@ def test_lexicon_factor(from_data, target, expected):
assert type(result) == type(expected)
[email protected]('rounding, expected', [
+ ('down', 47),
+ ('up', 48)
+])
+def test_lexicon_factor_round(rounding, expected):
+ rule = {
+ 'from': 'value',
+ 'round': rounding,
+ 'factor': 0.5
+ }
+ assert Lexicon.factor(rule, MagicMock(value=95)) == expected
+
+
@mark.parametrize('from_data, format, expected', [
('birthyear', '{}-0-0', '1992-0-0'),
(['birthyear', 'birthmonth'], '{}-{}-0', '1992-9-0')
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 3,
"test_score": 0
},
"num_modified_files": 1
} | 0.4 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"pytest",
"pytest-mock",
"psycopg2",
"PyMySQL"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.6",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | aratrum==0.3.2
attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work
certifi==2021.5.30
click==8.0.4
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
-e git+https://github.com/wearewhys/magnivore.git@acf182faeb0cf80157ec5d7b448b355687dcbd94#egg=magnivore
more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work
packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work
peewee==3.17.9
pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work
psycopg2==2.7.7
py @ file:///opt/conda/conda-bld/py_1644396412707/work
PyMySQL==1.0.2
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pytest==6.2.4
pytest-mock==3.6.1
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
ujson==4.3.0
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
| name: magnivore
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=21.4.0=pyhd3eb1b0_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- importlib-metadata=4.8.1=py36h06a4308_0
- importlib_metadata=4.8.1=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- more-itertools=8.12.0=pyhd3eb1b0_0
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=21.3=pyhd3eb1b0_0
- pip=21.2.2=py36h06a4308_0
- pluggy=0.13.1=py36h06a4308_0
- py=1.11.0=pyhd3eb1b0_0
- pyparsing=3.0.4=pyhd3eb1b0_0
- pytest=6.2.4=py36h06a4308_2
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- toml=0.10.2=pyhd3eb1b0_0
- typing_extensions=4.1.1=pyh06a4308_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zipp=3.6.0=pyhd3eb1b0_0
- zlib=1.2.13=h5eee18b_1
- pip:
- aratrum==0.3.2
- click==8.0.4
- peewee==3.17.9
- psycopg2==2.7.7
- pymysql==1.0.2
- pytest-mock==3.6.1
- ujson==4.3.0
prefix: /opt/conda/envs/magnivore
| [
"tests/unit/Lexicon.py::test_lexicon_factor_round[up-48]"
]
| []
| [
"tests/unit/Lexicon.py::test_lexicon_basic",
"tests/unit/Lexicon.py::test_lexicon_basic_dot",
"tests/unit/Lexicon.py::test_lexicon_basic_dot_double",
"tests/unit/Lexicon.py::test_lexicon_basic_null[field]",
"tests/unit/Lexicon.py::test_lexicon_basic_null[table.field]",
"tests/unit/Lexicon.py::test_lexicon_basic_null[table.field.nested]",
"tests/unit/Lexicon.py::test_lexicon_transform[target0]",
"tests/unit/Lexicon.py::test_lexicon_transform[target1]",
"tests/unit/Lexicon.py::test_lexicon_factor[value-target0-50]",
"tests/unit/Lexicon.py::test_lexicon_factor[value-target1-expected1]",
"tests/unit/Lexicon.py::test_lexicon_factor[value-target2-50.0]",
"tests/unit/Lexicon.py::test_lexicon_factor[related.value-target3-50]",
"tests/unit/Lexicon.py::test_lexicon_factor_round[down-47]",
"tests/unit/Lexicon.py::test_lexicon_format[birthyear-{}-0-0-1992-0-0]",
"tests/unit/Lexicon.py::test_lexicon_format[from_data1-{}-{}-0-1992-9-0]",
"tests/unit/Lexicon.py::test_lexicon_format_dot[rel.birthyear-{}-0-0-1992-0-0]",
"tests/unit/Lexicon.py::test_lexicon_format_dot[from_data1-{}-{}-0-1992-9-0]",
"tests/unit/Lexicon.py::test_lexicon_match",
"tests/unit/Lexicon.py::test_lexicon_match_none",
"tests/unit/Lexicon.py::test_lexicon_match_from",
"tests/unit/Lexicon.py::test_lexicon_match_dot",
"tests/unit/Lexicon.py::test_lexicon_match_from_none",
"tests/unit/Lexicon.py::test_lexicon_match_none_log",
"tests/unit/Lexicon.py::test_lexicon_sync",
"tests/unit/Lexicon.py::test_lexicon_sync_none",
"tests/unit/Lexicon.py::test_lexicon_static",
"tests/unit/Lexicon.py::test_lexicon_expression",
"tests/unit/Lexicon.py::test_lexicon_expression_dot",
"tests/unit/Lexicon.py::test_lexicon_expression_none"
]
| []
| Apache License 2.0 | 1,909 | [
"magnivore/Lexicon.py"
]
| [
"magnivore/Lexicon.py"
]
|
|
Hrabal__TemPy-30 | 7995be8f846c0aa8338fa0f3bc01aa3e3a21a6b8 | 2017-11-21 20:30:31 | 7995be8f846c0aa8338fa0f3bc01aa3e3a21a6b8 | diff --git a/tempy/tempy.py b/tempy/tempy.py
index 3385be4..83ec459 100755
--- a/tempy/tempy.py
+++ b/tempy/tempy.py
@@ -2,19 +2,20 @@
# @author: Federico Cerchiari <[email protected]>
"""Main Tempy classes"""
import html
+from collections import deque, Iterable
from copy import copy
-from uuid import uuid4
-from itertools import chain
from functools import wraps
-from collections import deque
+from itertools import chain
from types import GeneratorType
+from uuid import uuid4
-from .exceptions import TagError, WrongContentError, DOMModByKeyError, DOMModByIndexError
+from .exceptions import TagError, WrongContentError, WrongArgsError, DOMModByKeyError, DOMModByIndexError
from .tempyrepr import REPRFinder
class DOMGroup:
"""Wrapper used to manage element insertion."""
+
def __init__(self, name, obj):
super().__init__()
if not name and issubclass(obj.__class__, DOMElement):
@@ -167,7 +168,7 @@ class DOMElement(REPRFinder):
if n == 0:
self.parent.pop(self._own_index)
return self
- return self.after(self * (n-1))
+ return self.after(self * (n - 1))
def to_code(self, pretty=False):
ret = []
@@ -252,6 +253,7 @@ class DOMElement(REPRFinder):
# this trick is used to avoid circular imports
class Patched(tempyREPR_cls, DOMElement):
pass
+
child = Patched(child)
try:
yield child.render(pretty=pretty)
@@ -272,6 +274,7 @@ class DOMElement(REPRFinder):
Takes args and kwargs and calls the decorated method one time for each argument provided.
The reverse parameter should be used for prepending (relative to self) methods.
"""
+
def _receiver(func):
@wraps(func)
def wrapped(inst, *tags, **kwtags):
@@ -279,7 +282,9 @@ class DOMElement(REPRFinder):
inst._stable = False
func(inst, i, dom_group)
return inst
+
return wrapped
+
return _receiver
def _insert(self, dom_group, idx=None, prepend=False):
@@ -298,7 +303,7 @@ class DOMElement(REPRFinder):
for i_group, elem in enumerate(dom_group):
if elem is not None:
# Element insertion in this DOMElement childs
- self.childs.insert(idx+i_group, elem)
+ self.childs.insert(idx + i_group, elem)
# Managing child attributes if needed
if issubclass(elem.__class__, DOMElement):
elem.parent = self
@@ -393,7 +398,6 @@ class DOMElement(REPRFinder):
def wrap(self, other):
"""Wraps this element inside another empty tag."""
- # TODO: make multiple with content_receiver
if other.childs:
raise TagError(self, 'Wrapping in a non empty Tag is forbidden.')
if self.parent:
@@ -402,6 +406,51 @@ class DOMElement(REPRFinder):
other.append(self)
return self
+ def wrap_many(self, *args, strict=False):
+ """Wraps different copies of this element inside all empty tags
+ listed in params or param's (non-empty) iterators.
+
+ Returns list of copies of this element wrapped inside args
+ or None if not succeeded, in the same order and same structure,
+ i.e. args = (Div(), (Div())) -> value = (A(...), (A(...)))
+
+ If on some args it must raise TagError, it will only if strict is True,
+ otherwise it will do nothing with them and return Nones on their positions"""
+
+ for arg in args:
+ is_elem = arg and isinstance(arg, DOMElement)
+ is_elem_iter = (not is_elem and arg and isinstance(arg, Iterable) and
+ isinstance(iter(arg).__next__(), DOMElement))
+ if not (is_elem or is_elem_iter):
+ raise WrongArgsError(self, 'Argument {} is not DOMElement nor iterable of DOMElements'.format(arg))
+
+ wcopies = []
+ failure = []
+
+ def wrap_next(tag, idx):
+ nonlocal wcopies, failure
+ next_copy = self.__copy__()
+ try:
+ return next_copy.wrap(tag)
+ except TagError:
+ failure.append(idx)
+ return next_copy
+
+ for arg_idx, arg in enumerate(args):
+ if isinstance(arg, DOMElement):
+ wcopies.append(wrap_next(arg, (arg_idx, -1)))
+ else:
+ iter_wcopies = []
+ for iter_idx, t in enumerate(arg):
+ iter_wcopies.append(wrap_next(t, (arg_idx, iter_idx)))
+ wcopies.append(type(arg)(iter_wcopies))
+
+ if failure and strict:
+ raise TagError(self, 'Wrapping in a non empty Tag is forbidden, failed on arguments ' +
+ ', '.join(list(map(lambda idx: str(idx[0]) if idx[1] == -1 else '[{1}] of {0}'.format(*idx),
+ failure))))
+ return wcopies
+
def wrap_inner(self, other):
self.move_childs(other)
self(other)
@@ -599,7 +648,6 @@ class DOMElement(REPRFinder):
class Escaped(DOMElement):
-
def __init__(self, content, **kwargs):
super().__init__(**kwargs)
self._render = content
| TODO: Wrapping into multiple containers
`DOMElement.wrap` now accepts a single `DOMElement` instance and wraps `self` into this other instance.
Method signature should change to accept a iterable as first argument or multiple (single or iterable) arguments. `self` (copies of) will be wrapped inside each given element, i.e:
some_divs = [Div() for _ in range(10)]
to_be_wrapped = Span()
to_be_wrapped.wrap(some_divs, P(), A(), (Pre() for _ in range(10)))
wrap will add `to_be_wrapped` into each div in `some_divs`, and into each `DOMElement` found in args.
Extra implementation:
add kwargs in signature so wrapping will perform a named insertion.
https://codeclimate.com/github/Hrabal/TemPy/tempy/tempy.py#issue_59a0588692503c0001000033 | Hrabal/TemPy | diff --git a/tests/test_DOMElement.py b/tests/test_DOMElement.py
index f8a95d7..87737ff 100755
--- a/tests/test_DOMElement.py
+++ b/tests/test_DOMElement.py
@@ -4,14 +4,13 @@
"""
import unittest
+from tempy.elements import Tag, TagAttrs
+from tempy.exceptions import WrongContentError, WrongArgsError, TagError, DOMModByKeyError, DOMModByIndexError
from tempy.tags import Div, A, P, Html, Head, Body
from tempy.tempy import DOMElement, DOMGroup, Escaped
-from tempy.elements import Tag, TagAttrs
-from tempy.exceptions import WrongContentError, TagError, DOMModByKeyError, DOMModByIndexError
class TestDOMelement(unittest.TestCase):
-
def setUp(self):
self.page = Html()
@@ -84,13 +83,13 @@ class TestDOMelement(unittest.TestCase):
new1 = Div().append_to(self.page)
new2 = Div()
new1.after(new2)
- self.assertEqual(new1._own_index, new2._own_index-1)
+ self.assertEqual(new1._own_index, new2._own_index - 1)
def test_before(self):
new1 = Div().append_to(self.page)
new2 = Div()
new1.before(new2)
- self.assertEqual(new1._own_index, new2._own_index+1)
+ self.assertEqual(new1._own_index, new2._own_index + 1)
def test_prepend(self):
self.page(Div(), Div())
@@ -134,6 +133,53 @@ class TestDOMelement(unittest.TestCase):
self.assertTrue(to_wrap in container)
self.assertTrue(container in outermost)
+ def test_wrap_many(self):
+ def flatten(cnt):
+ res = []
+ for el in cnt:
+ if isinstance(el, DOMElement):
+ res.append(el)
+ else:
+ res.extend(el)
+ return res
+
+ def test_return_values(inp, outp):
+ self.assertEqual(len(inp), len(outp))
+ for _ in range(len(inp)):
+ t1, t2 = type(inp[_]), type(outp[_])
+ self.assertTrue(t1 == t2 or
+ issubclass(t1, DOMElement) and issubclass(t2, DOMElement))
+
+ def test_correctly_wrapped(child, parent):
+ self.assertTrue(child in parent)
+ self.assertTrue(child.get_parent() == parent)
+
+ # check if it works correct with correct arguments
+ args = (Div(), [Div(), Div()], (Div(), Div()))
+ new = A().wrap_many(*args)
+ test_return_values(args, new)
+ for c, p in zip(flatten(new), flatten(args)):
+ test_correctly_wrapped(c, p)
+
+ # check if it raises TagError with strict and returns None without
+ args = (Div()(A()), (Div(), Div()))
+ with self.assertRaisesRegex(TagError, r'^.+arguments 0$'):
+ A().wrap_many(*args, strict=True)
+ new = A().wrap_many(*args)
+ self.assertIs(new[0].get_parent(), None)
+
+ args = (Div()(A()), (Div(), Div()(A())))
+ with self.assertRaisesRegex(TagError, r'^.+arguments 0, \[1\] of 1'):
+ A().wrap_many(*args, strict=True)
+ new = A().wrap_many(*args)
+ self.assertIs(new[0].get_parent(), None)
+ self.assertIs(new[1][1].get_parent(), None)
+
+ # check if it raises WrongArgsError
+ args = (Div(), '')
+ with self.assertRaises(WrongArgsError):
+ A().wrap_many(*args)
+
def test_replace_with(self):
old = Div().append_to(self.page)
old.replace_with(A())
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_hyperlinks",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 1,
"test_score": 3
},
"num_modified_files": 1
} | 1.0 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"pytest",
"pytest-coverage"
],
"pre_install": null,
"python": "3.9",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | coverage==7.8.0
exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
packaging @ file:///croot/packaging_1734472117206/work
pluggy @ file:///croot/pluggy_1733169602837/work
pytest @ file:///croot/pytest_1738938843180/work
pytest-cov==6.0.0
pytest-cover==3.0.0
pytest-coverage==0.0
-e git+https://github.com/Hrabal/TemPy.git@7995be8f846c0aa8338fa0f3bc01aa3e3a21a6b8#egg=tem_py
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
| name: TemPy
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- exceptiongroup=1.2.0=py39h06a4308_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- packaging=24.2=py39h06a4308_0
- pip=25.0=py39h06a4308_0
- pluggy=1.5.0=py39h06a4308_0
- pytest=8.3.4=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tomli=2.0.1=py39h06a4308_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- coverage==7.8.0
- pytest-cov==6.0.0
- pytest-cover==3.0.0
- pytest-coverage==0.0
prefix: /opt/conda/envs/TemPy
| [
"tests/test_DOMElement.py::TestDOMelement::test_wrap_many"
]
| []
| [
"tests/test_DOMElement.py::TestDOMelement::test__find_content",
"tests/test_DOMElement.py::TestDOMelement::test__insert_negative_index",
"tests/test_DOMElement.py::TestDOMelement::test_add",
"tests/test_DOMElement.py::TestDOMelement::test_after",
"tests/test_DOMElement.py::TestDOMelement::test_append",
"tests/test_DOMElement.py::TestDOMelement::test_append_to",
"tests/test_DOMElement.py::TestDOMelement::test_attrs",
"tests/test_DOMElement.py::TestDOMelement::test_before",
"tests/test_DOMElement.py::TestDOMelement::test_bft",
"tests/test_DOMElement.py::TestDOMelement::test_children",
"tests/test_DOMElement.py::TestDOMelement::test_childs_index",
"tests/test_DOMElement.py::TestDOMelement::test_clone",
"tests/test_DOMElement.py::TestDOMelement::test_contents",
"tests/test_DOMElement.py::TestDOMelement::test_copy",
"tests/test_DOMElement.py::TestDOMelement::test_create_call_generator",
"tests/test_DOMElement.py::TestDOMelement::test_create_call_list",
"tests/test_DOMElement.py::TestDOMelement::test_create_call_multitag",
"tests/test_DOMElement.py::TestDOMelement::test_create_call_singletag",
"tests/test_DOMElement.py::TestDOMelement::test_create_call_tuple",
"tests/test_DOMElement.py::TestDOMelement::test_create_instantiation",
"tests/test_DOMElement.py::TestDOMelement::test_dft",
"tests/test_DOMElement.py::TestDOMelement::test_dft_reverse",
"tests/test_DOMElement.py::TestDOMelement::test_empty",
"tests/test_DOMElement.py::TestDOMelement::test_equality",
"tests/test_DOMElement.py::TestDOMelement::test_escaped",
"tests/test_DOMElement.py::TestDOMelement::test_get_parent",
"tests/test_DOMElement.py::TestDOMelement::test_getattr",
"tests/test_DOMElement.py::TestDOMelement::test_hash",
"tests/test_DOMElement.py::TestDOMelement::test_iadd",
"tests/test_DOMElement.py::TestDOMelement::test_imul",
"tests/test_DOMElement.py::TestDOMelement::test_imul_zero",
"tests/test_DOMElement.py::TestDOMelement::test_inject",
"tests/test_DOMElement.py::TestDOMelement::test_is_root",
"tests/test_DOMElement.py::TestDOMelement::test_isub",
"tests/test_DOMElement.py::TestDOMelement::test_iter_chidls",
"tests/test_DOMElement.py::TestDOMelement::test_iter_reversed",
"tests/test_DOMElement.py::TestDOMelement::test_move",
"tests/test_DOMElement.py::TestDOMelement::test_move_childs",
"tests/test_DOMElement.py::TestDOMelement::test_mul",
"tests/test_DOMElement.py::TestDOMelement::test_next",
"tests/test_DOMElement.py::TestDOMelement::test_next_all",
"tests/test_DOMElement.py::TestDOMelement::test_next_childs",
"tests/test_DOMElement.py::TestDOMelement::test_next_magic",
"tests/test_DOMElement.py::TestDOMelement::test_own_index",
"tests/test_DOMElement.py::TestDOMelement::test_parent",
"tests/test_DOMElement.py::TestDOMelement::test_pop",
"tests/test_DOMElement.py::TestDOMelement::test_prepend",
"tests/test_DOMElement.py::TestDOMelement::test_prepend_to",
"tests/test_DOMElement.py::TestDOMelement::test_prev",
"tests/test_DOMElement.py::TestDOMelement::test_prev_all",
"tests/test_DOMElement.py::TestDOMelement::test_remove",
"tests/test_DOMElement.py::TestDOMelement::test_render_raise",
"tests/test_DOMElement.py::TestDOMelement::test_replace_with",
"tests/test_DOMElement.py::TestDOMelement::test_reverse",
"tests/test_DOMElement.py::TestDOMelement::test_root",
"tests/test_DOMElement.py::TestDOMelement::test_siblings",
"tests/test_DOMElement.py::TestDOMelement::test_slice",
"tests/test_DOMElement.py::TestDOMelement::test_sub",
"tests/test_DOMElement.py::TestDOMelement::test_wrap",
"tests/test_DOMElement.py::TestDOMelement::test_wrap_inner"
]
| []
| Apache License 2.0 | 1,910 | [
"tempy/tempy.py"
]
| [
"tempy/tempy.py"
]
|
|
pyrates__roll-31 | ff3dc372850dbdda786722d8e1fcd90b0d10e6d8 | 2017-11-22 22:22:08 | ff3dc372850dbdda786722d8e1fcd90b0d10e6d8 | diff --git a/docs/changelog.md b/docs/changelog.md
index cc237cd..c97fe01 100644
--- a/docs/changelog.md
+++ b/docs/changelog.md
@@ -8,6 +8,11 @@ A changelog:
*Analogy: git blame :p*
+## In progress
+
+* Only set the body and Content-Length header when necessary
+ ([#31](https://github.com/pyrates/roll/pull/31))
+
## 0.6.0 — 2017-11-22
* Changed `Roll.hook` signature to also accept kwargs
diff --git a/roll/__init__.py b/roll/__init__.py
index 0af795d..a9a4ff6 100644
--- a/roll/__init__.py
+++ b/roll/__init__.py
@@ -146,6 +146,10 @@ class Protocol(asyncio.Protocol):
"""
__slots__ = ('app', 'req', 'parser', 'resp', 'writer')
+ _BODYLESS_METHODS = ('HEAD', 'CONNECT')
+ _BODYLESS_STATUSES = (HTTPStatus.CONTINUE, HTTPStatus.SWITCHING_PROTOCOLS,
+ HTTPStatus.PROCESSING, HTTPStatus.NO_CONTENT,
+ HTTPStatus.NOT_MODIFIED)
Query = Query
Request = Request
Response = Response
@@ -201,7 +205,11 @@ class Protocol(asyncio.Protocol):
self.response.status.value, self.response.status.phrase.encode())
if not isinstance(self.response.body, bytes):
self.response.body = str(self.response.body).encode()
- if 'Content-Length' not in self.response.headers:
+ # https://tools.ietf.org/html/rfc7230#section-3.3.2 :scream:
+ bodyless = (self.response.status in self._BODYLESS_STATUSES or
+ (hasattr(self, 'request') and
+ self.request.method in self._BODYLESS_METHODS))
+ if 'Content-Length' not in self.response.headers and not bodyless:
length = len(self.response.body)
self.response.headers['Content-Length'] = length
for key, value in self.response.headers.items():
@@ -211,7 +219,9 @@ class Protocol(asyncio.Protocol):
payload += b'%b: %b\r\n' % (key.encode(), str(v).encode())
else:
payload += b'%b: %b\r\n' % (key.encode(), str(value).encode())
- payload += b'\r\n%b' % self.response.body
+ payload += b'\r\n'
+ if self.response.body and not bodyless:
+ payload += self.response.body
self.writer.write(payload)
if not self.parser.should_keep_alive():
self.writer.close()
| "built-in" headers
Which headers should Roll provides and which should be let to the users?
https://stackoverflow.com/questions/4726515/what-http-response-headers-are-required/25586633#25586633
cf #23 | pyrates/roll | diff --git a/roll/testing.py b/roll/testing.py
index 96afd23..ab769c7 100644
--- a/roll/testing.py
+++ b/roll/testing.py
@@ -79,6 +79,9 @@ class Client:
async def options(self, path, **kwargs):
return await self.request(path, method='OPTIONS', **kwargs)
+ async def connect(self, path, **kwargs):
+ return await self.request(path, method='CONNECT', **kwargs)
+
@pytest.fixture
def client(app, event_loop):
diff --git a/tests/test_response.py b/tests/test_response.py
index 0f60035..7353355 100644
--- a/tests/test_response.py
+++ b/tests/test_response.py
@@ -23,6 +23,8 @@ async def test_can_set_status_from_httpstatus(client, app):
resp = await client.get('/test')
assert resp.status == HTTPStatus.ACCEPTED
+ assert client.protocol.writer.data == \
+ b'HTTP/1.1 202 Accepted\r\nContent-Length: 0\r\n\r\n'
async def test_write(client, app):
@@ -37,6 +39,56 @@ async def test_write(client, app):
b'HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\nbody'
+async def test_write_get_204_no_content_type(client, app):
+
+ @app.route('/test')
+ async def get(req, resp):
+ resp.status = HTTPStatus.NO_CONTENT
+
+ await client.get('/test')
+ assert client.protocol.writer.data == b'HTTP/1.1 204 No Content\r\n\r\n'
+
+
+async def test_write_get_304_no_content_type(client, app):
+
+ @app.route('/test')
+ async def get(req, resp):
+ resp.status = HTTPStatus.NOT_MODIFIED
+
+ await client.get('/test')
+ assert client.protocol.writer.data == b'HTTP/1.1 304 Not Modified\r\n\r\n'
+
+
+async def test_write_get_1XX_no_content_type(client, app):
+
+ @app.route('/test')
+ async def get(req, resp):
+ resp.status = HTTPStatus.CONTINUE
+
+ await client.get('/test')
+ assert client.protocol.writer.data == b'HTTP/1.1 100 Continue\r\n\r\n'
+
+
+async def test_write_head_no_content_type(client, app):
+
+ @app.route('/test', methods=['HEAD'])
+ async def head(req, resp):
+ resp.status = HTTPStatus.OK
+
+ await client.head('/test')
+ assert client.protocol.writer.data == b'HTTP/1.1 200 OK\r\n\r\n'
+
+
+async def test_write_connect_no_content_type(client, app):
+
+ @app.route('/test', methods=['CONNECT'])
+ async def connect(req, resp):
+ resp.status = HTTPStatus.OK
+
+ await client.connect('/test')
+ assert client.protocol.writer.data == b'HTTP/1.1 200 OK\r\n\r\n'
+
+
async def test_write_set_cookie(client, app):
@app.route('/test')
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 3,
"test_score": 1
},
"num_modified_files": 2
} | 0.6 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-asyncio"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.6",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs==22.2.0
autoroutes==0.2.0
certifi==2021.5.30
httptools==0.0.9
importlib-metadata==4.8.3
iniconfig==1.1.1
packaging==21.3
pluggy==1.0.0
py==1.11.0
pyparsing==3.1.4
pytest==7.0.1
pytest-asyncio==0.16.0
-e git+https://github.com/pyrates/roll.git@ff3dc372850dbdda786722d8e1fcd90b0d10e6d8#egg=roll
tomli==1.2.3
typing_extensions==4.1.1
uvloop==0.8.1
zipp==3.6.0
| name: roll
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- attrs==22.2.0
- autoroutes==0.2.0
- httptools==0.0.9
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- packaging==21.3
- pluggy==1.0.0
- py==1.11.0
- pyparsing==3.1.4
- pytest==7.0.1
- pytest-asyncio==0.16.0
- tomli==1.2.3
- typing-extensions==4.1.1
- uvloop==0.8.1
- zipp==3.6.0
prefix: /opt/conda/envs/roll
| [
"tests/test_response.py::test_write_get_204_no_content_type",
"tests/test_response.py::test_write_get_304_no_content_type",
"tests/test_response.py::test_write_get_1XX_no_content_type",
"tests/test_response.py::test_write_head_no_content_type",
"tests/test_response.py::test_write_connect_no_content_type"
]
| []
| [
"tests/test_response.py::test_can_set_status_from_numeric_value",
"tests/test_response.py::test_can_set_status_from_httpstatus",
"tests/test_response.py::test_write",
"tests/test_response.py::test_write_set_cookie",
"tests/test_response.py::test_write_multiple_set_cookie"
]
| []
| null | 1,911 | [
"docs/changelog.md",
"roll/__init__.py"
]
| [
"docs/changelog.md",
"roll/__init__.py"
]
|
|
firebase__firebase-admin-python-96 | d8a93457a5dfba8ddb12d229a6f717565f0975e2 | 2017-11-23 01:37:34 | d8a93457a5dfba8ddb12d229a6f717565f0975e2 | diff --git a/firebase_admin/db.py b/firebase_admin/db.py
index d6f5f99..1efa31e 100644
--- a/firebase_admin/db.py
+++ b/firebase_admin/db.py
@@ -442,10 +442,10 @@ class Query(object):
Query: The updated Query instance.
Raises:
- ValueError: If the value is empty or None.
+ ValueError: If the value is None.
"""
- if not start:
- raise ValueError('Start value must not be empty or None.')
+ if start is None:
+ raise ValueError('Start value must not be None.')
self._params['startAt'] = json.dumps(start)
return self
@@ -462,10 +462,10 @@ class Query(object):
Query: The updated Query instance.
Raises:
- ValueError: If the value is empty or None.
+ ValueError: If the value is None.
"""
- if not end:
- raise ValueError('End value must not be empty or None.')
+ if end is None:
+ raise ValueError('End value must not be None.')
self._params['endAt'] = json.dumps(end)
return self
@@ -481,10 +481,10 @@ class Query(object):
Query: The updated Query instance.
Raises:
- ValueError: If the value is empty or None.
+ ValueError: If the value is None.
"""
- if not value:
- raise ValueError('Equal to value must not be empty or None.')
+ if value is None:
+ raise ValueError('Equal to value must not be None.')
self._params['equalTo'] = json.dumps(value)
return self
| Unable to query by boolean False
* Operating System version: OSX 10.11.4
* Firebase SDK version: Firebase Admin Python SDK 2.4.0
* Firebase Product: database
In firebase-admin-python/firebase_admin/db.py , it's unable to use equal_to(), start_at(), and end_at() with a boolean False value. It throws `ValueError: Equal to value must not be empty or None.`
Suggest the condition of False boolean value to be catered.
| firebase/firebase-admin-python | diff --git a/tests/test_db.py b/tests/test_db.py
index 98be17a..79547c2 100644
--- a/tests/test_db.py
+++ b/tests/test_db.py
@@ -694,16 +694,31 @@ class TestQuery(object):
with pytest.raises(ValueError):
query.start_at(None)
+ @pytest.mark.parametrize('arg', ['', 'foo', True, False, 0, 1, dict()])
+ def test_valid_start_at(self, arg):
+ query = self.ref.order_by_child('foo').start_at(arg)
+ assert query._querystr == 'orderBy="foo"&startAt={0}'.format(json.dumps(arg))
+
def test_end_at_none(self):
query = self.ref.order_by_child('foo')
with pytest.raises(ValueError):
query.end_at(None)
+ @pytest.mark.parametrize('arg', ['', 'foo', True, False, 0, 1, dict()])
+ def test_valid_end_at(self, arg):
+ query = self.ref.order_by_child('foo').end_at(arg)
+ assert query._querystr == 'endAt={0}&orderBy="foo"'.format(json.dumps(arg))
+
def test_equal_to_none(self):
query = self.ref.order_by_child('foo')
with pytest.raises(ValueError):
query.equal_to(None)
+ @pytest.mark.parametrize('arg', ['', 'foo', True, False, 0, 1, dict()])
+ def test_valid_equal_to(self, arg):
+ query = self.ref.order_by_child('foo').equal_to(arg)
+ assert query._querystr == 'equalTo={0}&orderBy="foo"'.format(json.dumps(arg))
+
def test_range_query(self, initquery):
query, order_by = initquery
query.start_at(1)
| {
"commit_name": "merge_commit",
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 1,
"test_score": 1
},
"num_modified_files": 1
} | 2.5 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pylint",
"pytest",
"pytest-cov"
],
"pre_install": [],
"python": "3.9",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | astroid==1.4.9
cachetools==5.5.2
certifi==2025.1.31
chardet==5.2.0
charset-normalizer==3.4.1
colorama==0.4.6
coverage==7.8.0
distlib==0.3.9
exceptiongroup==1.2.2
filelock==3.18.0
-e git+https://github.com/firebase/firebase-admin-python.git@d8a93457a5dfba8ddb12d229a6f717565f0975e2#egg=firebase_admin
google-api-core==2.24.2
google-auth==2.38.0
google-cloud-core==2.4.3
google-cloud-firestore==2.20.1
google-cloud-storage==3.1.0
google-crc32c==1.7.1
google-resumable-media==2.7.2
googleapis-common-protos==1.69.2
grpcio==1.71.0
grpcio-status==1.71.0
idna==3.10
iniconfig==2.1.0
isort==6.0.1
lazy-object-proxy==1.10.0
mccabe==0.7.0
packaging==24.2
platformdirs==4.3.7
pluggy==1.5.0
proto-plus==1.26.1
protobuf==5.29.4
pyasn1==0.6.1
pyasn1_modules==0.4.2
pylint==1.6.4
pyproject-api==1.9.0
pytest==8.3.5
pytest-cov==6.0.0
requests==2.32.3
rsa==4.9
six==1.17.0
tomli==2.2.1
tox==4.25.0
typing_extensions==4.13.0
urllib3==2.3.0
virtualenv==20.29.3
wrapt==1.17.2
| name: firebase-admin-python
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- astroid==1.4.9
- cachetools==5.5.2
- certifi==2025.1.31
- chardet==5.2.0
- charset-normalizer==3.4.1
- colorama==0.4.6
- coverage==7.8.0
- distlib==0.3.9
- exceptiongroup==1.2.2
- filelock==3.18.0
- google-api-core==2.24.2
- google-auth==2.38.0
- google-cloud-core==2.4.3
- google-cloud-firestore==2.20.1
- google-cloud-storage==3.1.0
- google-crc32c==1.7.1
- google-resumable-media==2.7.2
- googleapis-common-protos==1.69.2
- grpcio==1.71.0
- grpcio-status==1.71.0
- idna==3.10
- iniconfig==2.1.0
- isort==6.0.1
- lazy-object-proxy==1.10.0
- mccabe==0.7.0
- packaging==24.2
- platformdirs==4.3.7
- pluggy==1.5.0
- proto-plus==1.26.1
- protobuf==5.29.4
- pyasn1==0.6.1
- pyasn1-modules==0.4.2
- pylint==1.6.4
- pyproject-api==1.9.0
- pytest==8.3.5
- pytest-cov==6.0.0
- requests==2.32.3
- rsa==4.9
- six==1.17.0
- tomli==2.2.1
- tox==4.25.0
- typing-extensions==4.13.0
- urllib3==2.3.0
- virtualenv==20.29.3
- wrapt==1.17.2
prefix: /opt/conda/envs/firebase-admin-python
| [
"tests/test_db.py::TestQuery::test_valid_start_at[]",
"tests/test_db.py::TestQuery::test_valid_start_at[False]",
"tests/test_db.py::TestQuery::test_valid_start_at[0]",
"tests/test_db.py::TestQuery::test_valid_start_at[arg6]",
"tests/test_db.py::TestQuery::test_valid_end_at[]",
"tests/test_db.py::TestQuery::test_valid_end_at[False]",
"tests/test_db.py::TestQuery::test_valid_end_at[0]",
"tests/test_db.py::TestQuery::test_valid_end_at[arg6]",
"tests/test_db.py::TestQuery::test_valid_equal_to[]",
"tests/test_db.py::TestQuery::test_valid_equal_to[False]",
"tests/test_db.py::TestQuery::test_valid_equal_to[0]",
"tests/test_db.py::TestQuery::test_valid_equal_to[arg6]"
]
| [
"tests/test_db.py::TestDatabseInitialization::test_valid_db_url[https://test.firebaseio.com]",
"tests/test_db.py::TestDatabseInitialization::test_valid_db_url[https://test.firebaseio.com/]"
]
| [
"tests/test_db.py::TestReferencePath::test_valid_path[/-expected0]",
"tests/test_db.py::TestReferencePath::test_valid_path[-expected1]",
"tests/test_db.py::TestReferencePath::test_valid_path[/foo-expected2]",
"tests/test_db.py::TestReferencePath::test_valid_path[foo-expected3]",
"tests/test_db.py::TestReferencePath::test_valid_path[/foo/bar-expected4]",
"tests/test_db.py::TestReferencePath::test_valid_path[foo/bar-expected5]",
"tests/test_db.py::TestReferencePath::test_valid_path[/foo/bar/-expected6]",
"tests/test_db.py::TestReferencePath::test_invalid_key[None]",
"tests/test_db.py::TestReferencePath::test_invalid_key[True]",
"tests/test_db.py::TestReferencePath::test_invalid_key[False]",
"tests/test_db.py::TestReferencePath::test_invalid_key[0]",
"tests/test_db.py::TestReferencePath::test_invalid_key[1]",
"tests/test_db.py::TestReferencePath::test_invalid_key[path5]",
"tests/test_db.py::TestReferencePath::test_invalid_key[path6]",
"tests/test_db.py::TestReferencePath::test_invalid_key[path7]",
"tests/test_db.py::TestReferencePath::test_invalid_key[path8]",
"tests/test_db.py::TestReferencePath::test_invalid_key[foo#]",
"tests/test_db.py::TestReferencePath::test_invalid_key[foo.]",
"tests/test_db.py::TestReferencePath::test_invalid_key[foo$]",
"tests/test_db.py::TestReferencePath::test_invalid_key[foo[]",
"tests/test_db.py::TestReferencePath::test_invalid_key[foo]]",
"tests/test_db.py::TestReferencePath::test_valid_child[foo-expected0]",
"tests/test_db.py::TestReferencePath::test_valid_child[foo/bar-expected1]",
"tests/test_db.py::TestReferencePath::test_valid_child[foo/bar/-expected2]",
"tests/test_db.py::TestReferencePath::test_invalid_child[None]",
"tests/test_db.py::TestReferencePath::test_invalid_child[]",
"tests/test_db.py::TestReferencePath::test_invalid_child[/foo]",
"tests/test_db.py::TestReferencePath::test_invalid_child[/foo/bar]",
"tests/test_db.py::TestReferencePath::test_invalid_child[True]",
"tests/test_db.py::TestReferencePath::test_invalid_child[False]",
"tests/test_db.py::TestReferencePath::test_invalid_child[0]",
"tests/test_db.py::TestReferencePath::test_invalid_child[1]",
"tests/test_db.py::TestReferencePath::test_invalid_child[child8]",
"tests/test_db.py::TestReferencePath::test_invalid_child[child9]",
"tests/test_db.py::TestReferencePath::test_invalid_child[child10]",
"tests/test_db.py::TestReferencePath::test_invalid_child[foo#]",
"tests/test_db.py::TestReferencePath::test_invalid_child[foo.]",
"tests/test_db.py::TestReferencePath::test_invalid_child[foo$]",
"tests/test_db.py::TestReferencePath::test_invalid_child[foo[]",
"tests/test_db.py::TestReferencePath::test_invalid_child[foo]]",
"tests/test_db.py::TestReferencePath::test_invalid_child[child16]",
"tests/test_db.py::TestReference::test_get_value[]",
"tests/test_db.py::TestReference::test_get_value[foo]",
"tests/test_db.py::TestReference::test_get_value[0]",
"tests/test_db.py::TestReference::test_get_value[1]",
"tests/test_db.py::TestReference::test_get_value[100]",
"tests/test_db.py::TestReference::test_get_value[1.2]",
"tests/test_db.py::TestReference::test_get_value[True]",
"tests/test_db.py::TestReference::test_get_value[False]",
"tests/test_db.py::TestReference::test_get_value[data8]",
"tests/test_db.py::TestReference::test_get_value[data9]",
"tests/test_db.py::TestReference::test_get_value[data10]",
"tests/test_db.py::TestReference::test_get_value[data11]",
"tests/test_db.py::TestReference::test_get_with_etag[]",
"tests/test_db.py::TestReference::test_get_with_etag[foo]",
"tests/test_db.py::TestReference::test_get_with_etag[0]",
"tests/test_db.py::TestReference::test_get_with_etag[1]",
"tests/test_db.py::TestReference::test_get_with_etag[100]",
"tests/test_db.py::TestReference::test_get_with_etag[1.2]",
"tests/test_db.py::TestReference::test_get_with_etag[True]",
"tests/test_db.py::TestReference::test_get_with_etag[False]",
"tests/test_db.py::TestReference::test_get_with_etag[data8]",
"tests/test_db.py::TestReference::test_get_with_etag[data9]",
"tests/test_db.py::TestReference::test_get_with_etag[data10]",
"tests/test_db.py::TestReference::test_get_with_etag[data11]",
"tests/test_db.py::TestReference::test_get_if_changed[]",
"tests/test_db.py::TestReference::test_get_if_changed[foo]",
"tests/test_db.py::TestReference::test_get_if_changed[0]",
"tests/test_db.py::TestReference::test_get_if_changed[1]",
"tests/test_db.py::TestReference::test_get_if_changed[100]",
"tests/test_db.py::TestReference::test_get_if_changed[1.2]",
"tests/test_db.py::TestReference::test_get_if_changed[True]",
"tests/test_db.py::TestReference::test_get_if_changed[False]",
"tests/test_db.py::TestReference::test_get_if_changed[data8]",
"tests/test_db.py::TestReference::test_get_if_changed[data9]",
"tests/test_db.py::TestReference::test_get_if_changed[data10]",
"tests/test_db.py::TestReference::test_get_if_changed[data11]",
"tests/test_db.py::TestReference::test_get_if_changed_invalid_etag[0]",
"tests/test_db.py::TestReference::test_get_if_changed_invalid_etag[1]",
"tests/test_db.py::TestReference::test_get_if_changed_invalid_etag[True]",
"tests/test_db.py::TestReference::test_get_if_changed_invalid_etag[False]",
"tests/test_db.py::TestReference::test_get_if_changed_invalid_etag[etag4]",
"tests/test_db.py::TestReference::test_get_if_changed_invalid_etag[etag5]",
"tests/test_db.py::TestReference::test_get_if_changed_invalid_etag[etag6]",
"tests/test_db.py::TestReference::test_order_by_query[]",
"tests/test_db.py::TestReference::test_order_by_query[foo]",
"tests/test_db.py::TestReference::test_order_by_query[0]",
"tests/test_db.py::TestReference::test_order_by_query[1]",
"tests/test_db.py::TestReference::test_order_by_query[100]",
"tests/test_db.py::TestReference::test_order_by_query[1.2]",
"tests/test_db.py::TestReference::test_order_by_query[True]",
"tests/test_db.py::TestReference::test_order_by_query[False]",
"tests/test_db.py::TestReference::test_order_by_query[data8]",
"tests/test_db.py::TestReference::test_order_by_query[data9]",
"tests/test_db.py::TestReference::test_order_by_query[data10]",
"tests/test_db.py::TestReference::test_order_by_query[data11]",
"tests/test_db.py::TestReference::test_limit_query[]",
"tests/test_db.py::TestReference::test_limit_query[foo]",
"tests/test_db.py::TestReference::test_limit_query[0]",
"tests/test_db.py::TestReference::test_limit_query[1]",
"tests/test_db.py::TestReference::test_limit_query[100]",
"tests/test_db.py::TestReference::test_limit_query[1.2]",
"tests/test_db.py::TestReference::test_limit_query[True]",
"tests/test_db.py::TestReference::test_limit_query[False]",
"tests/test_db.py::TestReference::test_limit_query[data8]",
"tests/test_db.py::TestReference::test_limit_query[data9]",
"tests/test_db.py::TestReference::test_limit_query[data10]",
"tests/test_db.py::TestReference::test_limit_query[data11]",
"tests/test_db.py::TestReference::test_range_query[]",
"tests/test_db.py::TestReference::test_range_query[foo]",
"tests/test_db.py::TestReference::test_range_query[0]",
"tests/test_db.py::TestReference::test_range_query[1]",
"tests/test_db.py::TestReference::test_range_query[100]",
"tests/test_db.py::TestReference::test_range_query[1.2]",
"tests/test_db.py::TestReference::test_range_query[True]",
"tests/test_db.py::TestReference::test_range_query[False]",
"tests/test_db.py::TestReference::test_range_query[data8]",
"tests/test_db.py::TestReference::test_range_query[data9]",
"tests/test_db.py::TestReference::test_range_query[data10]",
"tests/test_db.py::TestReference::test_range_query[data11]",
"tests/test_db.py::TestReference::test_set_value[]",
"tests/test_db.py::TestReference::test_set_value[foo]",
"tests/test_db.py::TestReference::test_set_value[0]",
"tests/test_db.py::TestReference::test_set_value[1]",
"tests/test_db.py::TestReference::test_set_value[100]",
"tests/test_db.py::TestReference::test_set_value[1.2]",
"tests/test_db.py::TestReference::test_set_value[True]",
"tests/test_db.py::TestReference::test_set_value[False]",
"tests/test_db.py::TestReference::test_set_value[data8]",
"tests/test_db.py::TestReference::test_set_value[data9]",
"tests/test_db.py::TestReference::test_set_value[data10]",
"tests/test_db.py::TestReference::test_set_value[data11]",
"tests/test_db.py::TestReference::test_set_none_value",
"tests/test_db.py::TestReference::test_set_non_json_value[value0]",
"tests/test_db.py::TestReference::test_set_non_json_value[value1]",
"tests/test_db.py::TestReference::test_set_non_json_value[value2]",
"tests/test_db.py::TestReference::test_update_children",
"tests/test_db.py::TestReference::test_set_if_unchanged_success[]",
"tests/test_db.py::TestReference::test_set_if_unchanged_success[foo]",
"tests/test_db.py::TestReference::test_set_if_unchanged_success[0]",
"tests/test_db.py::TestReference::test_set_if_unchanged_success[1]",
"tests/test_db.py::TestReference::test_set_if_unchanged_success[100]",
"tests/test_db.py::TestReference::test_set_if_unchanged_success[1.2]",
"tests/test_db.py::TestReference::test_set_if_unchanged_success[True]",
"tests/test_db.py::TestReference::test_set_if_unchanged_success[False]",
"tests/test_db.py::TestReference::test_set_if_unchanged_success[data8]",
"tests/test_db.py::TestReference::test_set_if_unchanged_success[data9]",
"tests/test_db.py::TestReference::test_set_if_unchanged_success[data10]",
"tests/test_db.py::TestReference::test_set_if_unchanged_success[data11]",
"tests/test_db.py::TestReference::test_set_if_unchanged_failure[]",
"tests/test_db.py::TestReference::test_set_if_unchanged_failure[foo]",
"tests/test_db.py::TestReference::test_set_if_unchanged_failure[0]",
"tests/test_db.py::TestReference::test_set_if_unchanged_failure[1]",
"tests/test_db.py::TestReference::test_set_if_unchanged_failure[100]",
"tests/test_db.py::TestReference::test_set_if_unchanged_failure[1.2]",
"tests/test_db.py::TestReference::test_set_if_unchanged_failure[True]",
"tests/test_db.py::TestReference::test_set_if_unchanged_failure[False]",
"tests/test_db.py::TestReference::test_set_if_unchanged_failure[data8]",
"tests/test_db.py::TestReference::test_set_if_unchanged_failure[data9]",
"tests/test_db.py::TestReference::test_set_if_unchanged_failure[data10]",
"tests/test_db.py::TestReference::test_set_if_unchanged_failure[data11]",
"tests/test_db.py::TestReference::test_set_if_unchanged_invalid_etag[0]",
"tests/test_db.py::TestReference::test_set_if_unchanged_invalid_etag[1]",
"tests/test_db.py::TestReference::test_set_if_unchanged_invalid_etag[True]",
"tests/test_db.py::TestReference::test_set_if_unchanged_invalid_etag[False]",
"tests/test_db.py::TestReference::test_set_if_unchanged_invalid_etag[etag4]",
"tests/test_db.py::TestReference::test_set_if_unchanged_invalid_etag[etag5]",
"tests/test_db.py::TestReference::test_set_if_unchanged_invalid_etag[etag6]",
"tests/test_db.py::TestReference::test_set_if_unchanged_none_value",
"tests/test_db.py::TestReference::test_set_if_unchanged_non_json_value[value0]",
"tests/test_db.py::TestReference::test_set_if_unchanged_non_json_value[value1]",
"tests/test_db.py::TestReference::test_set_if_unchanged_non_json_value[value2]",
"tests/test_db.py::TestReference::test_update_children_default",
"tests/test_db.py::TestReference::test_set_invalid_update[None]",
"tests/test_db.py::TestReference::test_set_invalid_update[update1]",
"tests/test_db.py::TestReference::test_set_invalid_update[update2]",
"tests/test_db.py::TestReference::test_set_invalid_update[update3]",
"tests/test_db.py::TestReference::test_set_invalid_update[]",
"tests/test_db.py::TestReference::test_set_invalid_update[foo]",
"tests/test_db.py::TestReference::test_set_invalid_update[0]",
"tests/test_db.py::TestReference::test_set_invalid_update[1]",
"tests/test_db.py::TestReference::test_set_invalid_update[update8]",
"tests/test_db.py::TestReference::test_set_invalid_update[update9]",
"tests/test_db.py::TestReference::test_set_invalid_update[update10]",
"tests/test_db.py::TestReference::test_push[]",
"tests/test_db.py::TestReference::test_push[foo]",
"tests/test_db.py::TestReference::test_push[0]",
"tests/test_db.py::TestReference::test_push[1]",
"tests/test_db.py::TestReference::test_push[100]",
"tests/test_db.py::TestReference::test_push[1.2]",
"tests/test_db.py::TestReference::test_push[True]",
"tests/test_db.py::TestReference::test_push[False]",
"tests/test_db.py::TestReference::test_push[data8]",
"tests/test_db.py::TestReference::test_push[data9]",
"tests/test_db.py::TestReference::test_push[data10]",
"tests/test_db.py::TestReference::test_push[data11]",
"tests/test_db.py::TestReference::test_push_default",
"tests/test_db.py::TestReference::test_push_none_value",
"tests/test_db.py::TestReference::test_delete",
"tests/test_db.py::TestReference::test_transaction",
"tests/test_db.py::TestReference::test_transaction_scalar",
"tests/test_db.py::TestReference::test_transaction_error",
"tests/test_db.py::TestReference::test_transaction_invalid_function[None]",
"tests/test_db.py::TestReference::test_transaction_invalid_function[0]",
"tests/test_db.py::TestReference::test_transaction_invalid_function[1]",
"tests/test_db.py::TestReference::test_transaction_invalid_function[True]",
"tests/test_db.py::TestReference::test_transaction_invalid_function[False]",
"tests/test_db.py::TestReference::test_transaction_invalid_function[foo]",
"tests/test_db.py::TestReference::test_transaction_invalid_function[func6]",
"tests/test_db.py::TestReference::test_transaction_invalid_function[func7]",
"tests/test_db.py::TestReference::test_transaction_invalid_function[func8]",
"tests/test_db.py::TestReference::test_get_root_reference",
"tests/test_db.py::TestReference::test_get_reference[/-expected0]",
"tests/test_db.py::TestReference::test_get_reference[-expected1]",
"tests/test_db.py::TestReference::test_get_reference[/foo-expected2]",
"tests/test_db.py::TestReference::test_get_reference[foo-expected3]",
"tests/test_db.py::TestReference::test_get_reference[/foo/bar-expected4]",
"tests/test_db.py::TestReference::test_get_reference[foo/bar-expected5]",
"tests/test_db.py::TestReference::test_get_reference[/foo/bar/-expected6]",
"tests/test_db.py::TestReference::test_server_error[400]",
"tests/test_db.py::TestReference::test_server_error[401]",
"tests/test_db.py::TestReference::test_server_error[500]",
"tests/test_db.py::TestReference::test_other_error[400]",
"tests/test_db.py::TestReference::test_other_error[401]",
"tests/test_db.py::TestReference::test_other_error[500]",
"tests/test_db.py::TestReferenceWithAuthOverride::test_get_value",
"tests/test_db.py::TestReferenceWithAuthOverride::test_set_value",
"tests/test_db.py::TestReferenceWithAuthOverride::test_order_by_query",
"tests/test_db.py::TestReferenceWithAuthOverride::test_range_query",
"tests/test_db.py::TestDatabseInitialization::test_no_app",
"tests/test_db.py::TestDatabseInitialization::test_no_db_url",
"tests/test_db.py::TestDatabseInitialization::test_invalid_db_url[None]",
"tests/test_db.py::TestDatabseInitialization::test_invalid_db_url[]",
"tests/test_db.py::TestDatabseInitialization::test_invalid_db_url[foo]",
"tests/test_db.py::TestDatabseInitialization::test_invalid_db_url[http://test.firebaseio.com]",
"tests/test_db.py::TestDatabseInitialization::test_invalid_db_url[https://google.com]",
"tests/test_db.py::TestDatabseInitialization::test_invalid_db_url[True]",
"tests/test_db.py::TestDatabseInitialization::test_invalid_db_url[False]",
"tests/test_db.py::TestDatabseInitialization::test_invalid_db_url[1]",
"tests/test_db.py::TestDatabseInitialization::test_invalid_db_url[0]",
"tests/test_db.py::TestDatabseInitialization::test_invalid_db_url[url9]",
"tests/test_db.py::TestDatabseInitialization::test_invalid_db_url[url10]",
"tests/test_db.py::TestDatabseInitialization::test_invalid_db_url[url11]",
"tests/test_db.py::TestDatabseInitialization::test_invalid_db_url[url12]",
"tests/test_db.py::TestDatabseInitialization::test_valid_auth_override[override0]",
"tests/test_db.py::TestDatabseInitialization::test_valid_auth_override[override1]",
"tests/test_db.py::TestDatabseInitialization::test_valid_auth_override[None]",
"tests/test_db.py::TestDatabseInitialization::test_invalid_auth_override[]",
"tests/test_db.py::TestDatabseInitialization::test_invalid_auth_override[foo]",
"tests/test_db.py::TestDatabseInitialization::test_invalid_auth_override[0]",
"tests/test_db.py::TestDatabseInitialization::test_invalid_auth_override[1]",
"tests/test_db.py::TestDatabseInitialization::test_invalid_auth_override[True]",
"tests/test_db.py::TestDatabseInitialization::test_invalid_auth_override[False]",
"tests/test_db.py::TestDatabseInitialization::test_invalid_auth_override[override6]",
"tests/test_db.py::TestDatabseInitialization::test_invalid_auth_override[override7]",
"tests/test_db.py::TestDatabseInitialization::test_invalid_auth_override[override8]",
"tests/test_db.py::TestDatabseInitialization::test_http_timeout",
"tests/test_db.py::TestDatabseInitialization::test_app_delete",
"tests/test_db.py::TestDatabseInitialization::test_user_agent_format",
"tests/test_db.py::TestQuery::test_invalid_path[]",
"tests/test_db.py::TestQuery::test_invalid_path[None]",
"tests/test_db.py::TestQuery::test_invalid_path[/]",
"tests/test_db.py::TestQuery::test_invalid_path[/foo]",
"tests/test_db.py::TestQuery::test_invalid_path[0]",
"tests/test_db.py::TestQuery::test_invalid_path[1]",
"tests/test_db.py::TestQuery::test_invalid_path[True]",
"tests/test_db.py::TestQuery::test_invalid_path[False]",
"tests/test_db.py::TestQuery::test_invalid_path[path8]",
"tests/test_db.py::TestQuery::test_invalid_path[path9]",
"tests/test_db.py::TestQuery::test_invalid_path[path10]",
"tests/test_db.py::TestQuery::test_invalid_path[path11]",
"tests/test_db.py::TestQuery::test_invalid_path[$foo]",
"tests/test_db.py::TestQuery::test_invalid_path[.foo]",
"tests/test_db.py::TestQuery::test_invalid_path[#foo]",
"tests/test_db.py::TestQuery::test_invalid_path[[foo]",
"tests/test_db.py::TestQuery::test_invalid_path[foo]]",
"tests/test_db.py::TestQuery::test_invalid_path[$key]",
"tests/test_db.py::TestQuery::test_invalid_path[$value]",
"tests/test_db.py::TestQuery::test_invalid_path[$priority]",
"tests/test_db.py::TestQuery::test_order_by_valid_path[foo-foo]",
"tests/test_db.py::TestQuery::test_order_by_valid_path[foo/bar-foo/bar]",
"tests/test_db.py::TestQuery::test_order_by_valid_path[foo/bar/-foo/bar]",
"tests/test_db.py::TestQuery::test_filter_by_valid_path[foo-foo]",
"tests/test_db.py::TestQuery::test_filter_by_valid_path[foo/bar-foo/bar]",
"tests/test_db.py::TestQuery::test_filter_by_valid_path[foo/bar/-foo/bar]",
"tests/test_db.py::TestQuery::test_order_by_key",
"tests/test_db.py::TestQuery::test_key_filter",
"tests/test_db.py::TestQuery::test_order_by_value",
"tests/test_db.py::TestQuery::test_value_filter",
"tests/test_db.py::TestQuery::test_multiple_limits",
"tests/test_db.py::TestQuery::test_invalid_limit[None]",
"tests/test_db.py::TestQuery::test_invalid_limit[-1]",
"tests/test_db.py::TestQuery::test_invalid_limit[foo]",
"tests/test_db.py::TestQuery::test_invalid_limit[1.2]",
"tests/test_db.py::TestQuery::test_invalid_limit[limit4]",
"tests/test_db.py::TestQuery::test_invalid_limit[limit5]",
"tests/test_db.py::TestQuery::test_invalid_limit[limit6]",
"tests/test_db.py::TestQuery::test_invalid_limit[limit7]",
"tests/test_db.py::TestQuery::test_start_at_none",
"tests/test_db.py::TestQuery::test_valid_start_at[foo]",
"tests/test_db.py::TestQuery::test_valid_start_at[True]",
"tests/test_db.py::TestQuery::test_valid_start_at[1]",
"tests/test_db.py::TestQuery::test_end_at_none",
"tests/test_db.py::TestQuery::test_valid_end_at[foo]",
"tests/test_db.py::TestQuery::test_valid_end_at[True]",
"tests/test_db.py::TestQuery::test_valid_end_at[1]",
"tests/test_db.py::TestQuery::test_equal_to_none",
"tests/test_db.py::TestQuery::test_valid_equal_to[foo]",
"tests/test_db.py::TestQuery::test_valid_equal_to[True]",
"tests/test_db.py::TestQuery::test_valid_equal_to[1]",
"tests/test_db.py::TestQuery::test_range_query[foo]",
"tests/test_db.py::TestQuery::test_range_query[$key]",
"tests/test_db.py::TestQuery::test_range_query[$value]",
"tests/test_db.py::TestQuery::test_limit_first_query[foo]",
"tests/test_db.py::TestQuery::test_limit_first_query[$key]",
"tests/test_db.py::TestQuery::test_limit_first_query[$value]",
"tests/test_db.py::TestQuery::test_limit_last_query[foo]",
"tests/test_db.py::TestQuery::test_limit_last_query[$key]",
"tests/test_db.py::TestQuery::test_limit_last_query[$value]",
"tests/test_db.py::TestQuery::test_all_in[foo]",
"tests/test_db.py::TestQuery::test_all_in[$key]",
"tests/test_db.py::TestQuery::test_all_in[$value]",
"tests/test_db.py::TestQuery::test_invalid_query_args",
"tests/test_db.py::TestSorter::test_order_by_value[result0-expected0]",
"tests/test_db.py::TestSorter::test_order_by_value[result1-expected1]",
"tests/test_db.py::TestSorter::test_order_by_value[result2-expected2]",
"tests/test_db.py::TestSorter::test_order_by_value[result3-expected3]",
"tests/test_db.py::TestSorter::test_order_by_value[result4-expected4]",
"tests/test_db.py::TestSorter::test_order_by_value[result5-expected5]",
"tests/test_db.py::TestSorter::test_order_by_value[result6-expected6]",
"tests/test_db.py::TestSorter::test_order_by_value[result7-expected7]",
"tests/test_db.py::TestSorter::test_order_by_value[result8-expected8]",
"tests/test_db.py::TestSorter::test_order_by_value[result9-expected9]",
"tests/test_db.py::TestSorter::test_order_by_value[result10-expected10]",
"tests/test_db.py::TestSorter::test_order_by_value[result11-expected11]",
"tests/test_db.py::TestSorter::test_order_by_value[result12-expected12]",
"tests/test_db.py::TestSorter::test_order_by_value[result13-expected13]",
"tests/test_db.py::TestSorter::test_order_by_value[result14-expected14]",
"tests/test_db.py::TestSorter::test_order_by_value_with_list[result0-expected0]",
"tests/test_db.py::TestSorter::test_order_by_value_with_list[result1-expected1]",
"tests/test_db.py::TestSorter::test_order_by_value_with_list[result2-expected2]",
"tests/test_db.py::TestSorter::test_order_by_value_with_list[result3-expected3]",
"tests/test_db.py::TestSorter::test_order_by_value_with_list[result4-expected4]",
"tests/test_db.py::TestSorter::test_order_by_value_with_list[result5-expected5]",
"tests/test_db.py::TestSorter::test_order_by_value_with_list[result6-expected6]",
"tests/test_db.py::TestSorter::test_order_by_value_with_list[result7-expected7]",
"tests/test_db.py::TestSorter::test_invalid_sort[None]",
"tests/test_db.py::TestSorter::test_invalid_sort[False]",
"tests/test_db.py::TestSorter::test_invalid_sort[True]",
"tests/test_db.py::TestSorter::test_invalid_sort[0]",
"tests/test_db.py::TestSorter::test_invalid_sort[1]",
"tests/test_db.py::TestSorter::test_invalid_sort[foo]",
"tests/test_db.py::TestSorter::test_order_by_key[result0-expected0]",
"tests/test_db.py::TestSorter::test_order_by_key[result1-expected1]",
"tests/test_db.py::TestSorter::test_order_by_key[result2-expected2]",
"tests/test_db.py::TestSorter::test_order_by_child[result0-expected0]",
"tests/test_db.py::TestSorter::test_order_by_child[result1-expected1]",
"tests/test_db.py::TestSorter::test_order_by_child[result2-expected2]",
"tests/test_db.py::TestSorter::test_order_by_child[result3-expected3]",
"tests/test_db.py::TestSorter::test_order_by_child[result4-expected4]",
"tests/test_db.py::TestSorter::test_order_by_child[result5-expected5]",
"tests/test_db.py::TestSorter::test_order_by_child[result6-expected6]",
"tests/test_db.py::TestSorter::test_order_by_child[result7-expected7]",
"tests/test_db.py::TestSorter::test_order_by_child[result8-expected8]",
"tests/test_db.py::TestSorter::test_order_by_child[result9-expected9]",
"tests/test_db.py::TestSorter::test_order_by_child[result10-expected10]",
"tests/test_db.py::TestSorter::test_order_by_child[result11-expected11]",
"tests/test_db.py::TestSorter::test_order_by_child[result12-expected12]",
"tests/test_db.py::TestSorter::test_order_by_child[result13-expected13]",
"tests/test_db.py::TestSorter::test_order_by_child[result14-expected14]",
"tests/test_db.py::TestSorter::test_order_by_grand_child[result0-expected0]",
"tests/test_db.py::TestSorter::test_order_by_grand_child[result1-expected1]",
"tests/test_db.py::TestSorter::test_order_by_grand_child[result2-expected2]",
"tests/test_db.py::TestSorter::test_order_by_grand_child[result3-expected3]",
"tests/test_db.py::TestSorter::test_order_by_grand_child[result4-expected4]",
"tests/test_db.py::TestSorter::test_order_by_grand_child[result5-expected5]",
"tests/test_db.py::TestSorter::test_order_by_grand_child[result6-expected6]",
"tests/test_db.py::TestSorter::test_order_by_grand_child[result7-expected7]",
"tests/test_db.py::TestSorter::test_order_by_grand_child[result8-expected8]",
"tests/test_db.py::TestSorter::test_order_by_grand_child[result9-expected9]",
"tests/test_db.py::TestSorter::test_order_by_grand_child[result10-expected10]",
"tests/test_db.py::TestSorter::test_order_by_grand_child[result11-expected11]",
"tests/test_db.py::TestSorter::test_order_by_grand_child[result12-expected12]",
"tests/test_db.py::TestSorter::test_order_by_grand_child[result13-expected13]",
"tests/test_db.py::TestSorter::test_order_by_grand_child[result14-expected14]",
"tests/test_db.py::TestSorter::test_child_path_resolution[result0-expected0]",
"tests/test_db.py::TestSorter::test_child_path_resolution[result1-expected1]",
"tests/test_db.py::TestSorter::test_child_path_resolution[result2-expected2]"
]
| []
| Apache License 2.0 | 1,912 | [
"firebase_admin/db.py"
]
| [
"firebase_admin/db.py"
]
|
|
PlasmaPy__PlasmaPy-170 | 69712cb40b8b588400301edfd6925d41d2f13eac | 2017-11-23 06:23:44 | 69712cb40b8b588400301edfd6925d41d2f13eac | diff --git a/plasmapy/physics/parameters.py b/plasmapy/physics/parameters.py
index c08fb40c..88b2a900 100644
--- a/plasmapy/physics/parameters.py
+++ b/plasmapy/physics/parameters.py
@@ -14,6 +14,7 @@
# bit more than @quantity_input as it can allow
from ..utils import _check_quantity, check_relativistic, check_quantity
+from ..utils.exceptions import PhysicsError
r"""Values should be returned as an Astropy Quantity in SI units.
@@ -105,14 +106,22 @@ def Alfven_speed(B, density, ion="p"):
UnitConversionError
If the magnetic field or density is not in appropriate units.
- UserWarning
- If the Alfven velocity exceeds 10% of the speed of light, or
- if units are not provided and SI units are assumed.
+ RelativityError
+ If the Alfven velocity is greater than or equal to the speed of light
ValueError
If the density is negative, or the ion mass or charge state
cannot be found.
+ UserWarning
+ if units are not provided and SI units are assumed.
+
+ Warns
+ -----
+ RelativityWarning
+ If the Alfven velocity exceeds 10% of the speed of light
+
+
Notes
-----
The Alfven velocity :math:`V_A` is the typical propagation speed
@@ -228,6 +237,9 @@ def ion_sound_speed(*ignore, T_e=0*units.K, T_i=0*units.K,
ValueError
If the ion mass, adiabatic index, or temperature are invalid.
+ PhysicsError
+ If an adiabatic index is less than one.
+
UnitConversionError
If the temperature is in incorrect units.
@@ -293,11 +305,11 @@ def ion_sound_speed(*ignore, T_e=0*units.K, T_i=0*units.K,
"a float or int in ion_sound_speed")
if not 1 <= gamma_e <= np.inf:
- raise ValueError("The adiabatic index for electrons must be between "
- "one and infinity")
+ raise PhysicsError("The adiabatic index for electrons must be between "
+ "one and infinity")
if not 1 <= gamma_i <= np.inf:
- raise ValueError("The adiabatic index for ions must be between "
- "one and infinity")
+ raise PhysicsError("The adiabatic index for ions must be between "
+ "one and infinity")
T_i = T_i.to(units.K, equivalencies=units.temperature_energy())
T_e = T_e.to(units.K, equivalencies=units.temperature_energy())
@@ -332,7 +344,7 @@ def thermal_speed(T, particle="e", method="most_probable"):
method : string, optional
Method to be used for calculating the thermal speed. Options are
- 'most_probable' (default), 'rms', and 'mean_magnitude'.
+ 'most_probable' (default), 'rms', and 'mean_magnitude'.
Returns
-------
@@ -1145,7 +1157,8 @@ def lower_hybrid_frequency(B, n_i, ion='p'):
The lower hybrid frequency is given through the relation
.. math::
- \frac{1}{\omega_{lh}^2} = \frac{1}{\omega_{ci}^2 + \omega_{pi}^2} + \frac{1}{\omega_{ci}\omega_{ce}}
+ \frac{1}{\omega_{lh}^2} = \frac{1}{\omega_{ci}^2 + \omega_{pi}^2} +
+ \frac{1}{\omega_{ci}\omega_{ce}}
where :math:`\omega_{ci}` is the ion gyrofrequency,
:math:`\omega_{ce}` is the electron gyrofrequency, and
diff --git a/plasmapy/physics/quantum.py b/plasmapy/physics/quantum.py
index 64248c27..8a14f9c3 100644
--- a/plasmapy/physics/quantum.py
+++ b/plasmapy/physics/quantum.py
@@ -7,6 +7,7 @@
from ..constants import c, h, hbar, m_e, eps0, e, k_B
from ..atomic import ion_mass
from ..utils import _check_quantity, _check_relativistic, check_quantity
+from ..utils.exceptions import RelativityError
from .relativity import Lorentz_factor
@@ -37,7 +38,7 @@ def deBroglie_wavelength(V, particle):
UnitConversionError
If the velocity is not in appropriate units.
- ValueError
+ RelativityError
If the magnitude of V is faster than the speed of light.
UserWarning
@@ -72,8 +73,9 @@ def deBroglie_wavelength(V, particle):
V = np.abs(V)
if np.any(V >= c):
- raise ValueError("Velocity input in deBroglie_wavelength cannot be "
- "greater than or equal to the speed of light.")
+ raise RelativityError("Velocity input in deBroglie_wavelength cannot "
+ "be greater than or equal to the speed of "
+ "light.")
if not isinstance(particle, units.Quantity):
try:
@@ -145,7 +147,7 @@ def thermal_deBroglie_wavelength(T_e):
See also
--------
-
+
Example
-------
@@ -158,6 +160,7 @@ def thermal_deBroglie_wavelength(T_e):
lambda_dbTh = h / np.sqrt(2 * np.pi * m_e * k_B * T_e)
return lambda_dbTh.to(units.m)
+
@check_quantity({
'n_e': {'units': units.m**-3, 'can_be_negative': False}
})
@@ -214,6 +217,7 @@ def Fermi_energy(n_e):
energy_F = coeff * (3 * n_e / np.pi) ** (2/3)
return energy_F.to(units.Joule)
+
@check_quantity({
'n_e': {'units': units.m**-3, 'can_be_negative': False}
})
@@ -246,14 +250,14 @@ def Thomas_Fermi_length(n_e):
Notes
-----
- The Thomas-Fermi screening length is the exponential scale length for
+ The Thomas-Fermi screening length is the exponential scale length for
charge screening and is given by
.. math::
\lambda_TF = \sqrt{\frac{2 \epsilon_0 E_F}{3 n_e e^2}}
for an electron degenerate gas.
-
+
This quantity is often used in place of the Debye length for analysis
of cold, dense plasmas (e.g. warm dense matter, condensed matter).
@@ -276,4 +280,4 @@ def Thomas_Fermi_length(n_e):
"""
energy_F = Fermi_energy(n_e)
lambda_TF = np.sqrt(2 * eps0 * energy_F / (3 * n_e * e ** 2))
- return lambda_TF.to(units.m)
\ No newline at end of file
+ return lambda_TF.to(units.m)
diff --git a/plasmapy/physics/relativity.py b/plasmapy/physics/relativity.py
index f63100a8..efcfe0d0 100644
--- a/plasmapy/physics/relativity.py
+++ b/plasmapy/physics/relativity.py
@@ -4,6 +4,7 @@
from ..constants import c
from ..atomic import (ion_mass, charge_state)
from ..utils import _check_quantity
+from ..utils.exceptions import RelativityError
def Lorentz_factor(V):
@@ -59,8 +60,8 @@ def Lorentz_factor(V):
_check_quantity(V, 'V', 'Lorentz_factor', units.m/units.s)
if not np.all(np.abs(V) <= c):
- raise ValueError("The Lorentz factor cannot be calculated for speeds "
- "faster than the speed of light.")
+ raise RelativityError("The Lorentz factor cannot be calculated for "
+ "speeds faster than the speed of light. ")
if V.size > 1:
diff --git a/plasmapy/utils/checks.py b/plasmapy/utils/checks.py
index d0c847d4..fa762090 100644
--- a/plasmapy/utils/checks.py
+++ b/plasmapy/utils/checks.py
@@ -4,6 +4,8 @@
import numpy as np
from astropy import units as u
from ..constants import c
+import warnings
+from plasmapy.utils.exceptions import RelativityWarning, RelativityError
def check_quantity(validations):
@@ -103,7 +105,7 @@ def wrapper(*args, **kwargs):
def check_relativistic(func=None, betafrac=0.1):
- r"""Raises an error when the output of the decorated
+ r"""Warns or raises an error when the output of the decorated
function is greater than `betafrac` times the speed of light
Parameters
@@ -131,9 +133,14 @@ def check_relativistic(func=None, betafrac=0.1):
ValueError
If V contains any NaNs
- UserWarning
- If V is greater than betafrac times the speed of light
+ RelativityError
+ If V is greater than or equal to the speed of light
+ Warns
+ -----
+ RelativityWarning
+ If V is greater than or equal to betafrac times the speed of light,
+ but less than the speed of light
Examples
--------
@@ -285,7 +292,7 @@ def _check_quantity(arg, argname, funcname, units, can_be_negative=True,
def _check_relativistic(V, funcname, betafrac=0.1):
- r"""Raise UserWarnings if a velocity is relativistic or superrelativistic
+ r"""Warn or raise error if a velocity is relativistic or superrelativistic
Parameters
----------
@@ -296,8 +303,7 @@ def _check_relativistic(V, funcname, betafrac=0.1):
The name of the original function to be printed in the error messages.
betafrac : float
- The minimum fraction of the speed of light that will raise a
- UserWarning
+ The minimum fraction of the speed of light that will generate a warning
Raises
------
@@ -310,8 +316,14 @@ def _check_relativistic(V, funcname, betafrac=0.1):
ValueError
If V contains any NaNs
- UserWarning
- If V is greater than betafrac times the speed of light
+ RelativityError
+ If V is greater than or equal to the speed of light
+
+ Warns
+ -----
+ RelativityWarning
+ If V is greater than or equal to the specified fraction of the speed of
+ light
Examples
--------
@@ -332,14 +344,16 @@ def _check_relativistic(V, funcname, betafrac=0.1):
if np.any(np.isnan(V.value)):
raise ValueError("V includes NaNs in " + funcname)
- beta = np.max(np.abs((V/c).value))
+ beta = np.max(np.abs((V.si/c).value))
if beta == np.inf:
- raise UserWarning(funcname + " is yielding an infinite velocity.")
+ raise RelativityError(funcname + " is yielding an infinite velocity.")
elif beta >= 1:
- raise UserWarning(funcname + " is yielding a velocity that is " +
- str(round(beta, 3)) + " times the speed of light.")
+ raise RelativityError(funcname + " is yielding a velocity that is " +
+ str(round(beta, 3)) + " times the speed of " +
+ "light.")
elif beta >= betafrac:
- raise UserWarning(funcname + " is yielding a velocity that is " +
- str(round(beta*100, 3)) + "% of the speed of " +
- "light. Relativistic effects may be important.")
+ warnings.warn(funcname + " is yielding a velocity that is " +
+ str(round(beta*100, 3)) + "% of the speed of " +
+ "light. Relativistic effects may be important.",
+ RelativityWarning)
diff --git a/plasmapy/utils/exceptions.py b/plasmapy/utils/exceptions.py
new file mode 100644
index 00000000..fb4cf204
--- /dev/null
+++ b/plasmapy/utils/exceptions.py
@@ -0,0 +1,53 @@
+"""
+plasmapy.utils.exceptions
+===============
+
+Custom Error and Warning names to improve readability
+"""
+
+
+# ----------
+# Exceptions:
+# ----------
+
+class PlasmaPyError(Exception):
+ """Base class of PlasmaPy custom errors.
+
+ All custom exceptions raised by PlasmaPy should inherit from this class
+ and be defined in this module.
+
+ Custom exceptions can inherit from other exception types too. Thus, if code
+ already knows how to handle a ValueError, it won't need any specific
+ modification.
+ """
+
+
+class PhysicsError(PlasmaPyError, ValueError):
+ """Error for use of a physics value outside PlasmaPy theoretical bounds"""
+
+
+class RelativityError(PhysicsError):
+ """Error for use of a speed greater than or equal to the speed of light"""
+
+
+# ----------
+# Warnings:
+# ----------
+
+class PlasmaPyWarning(Warning):
+ """Base class of PlasmaPy custom warnings.
+
+ All PlasmaPy custom warnings should inherit from this class and be defined
+ in this module.
+
+ Warnings should be issued using warnings.warn, which will not break
+ execution if unhandled.
+ """
+
+
+class PhysicsWarning(PlasmaPyWarning):
+ """Warning for using a mildly worrisome physics value"""
+
+
+class RelativityWarning(PhysicsWarning):
+ """Warning for use of a speed quantity approaching the speed of light"""
| Create physics exceptions and warnings
Several of the exceptions and warnings that come up in PlasmaPy result from when we try to violate the laws of physics. Most of the time these violations cause a `UserWarning` or raise a `ValueError`, but these are pretty generic and don't give much insight into the cause of the problem. To help with exception handling, I propose that we create new exceptions and warnings, such as `PhysicsError` and `PhysicsWarning`. We could additionally be more specific and also have `RelativityError` and/or `RelativityWarning`. One possibility would be to put these in a new file called `plasmapy/utils/exceptions.py`.
This would be a good first contribution for someone who is somewhat familiar with Python. Here's documentation on [user-defined exceptions](https://docs.python.org/3/tutorial/errors.html#user-defined-exceptions. Thank you!
| PlasmaPy/PlasmaPy | diff --git a/plasmapy/physics/tests/test_parameters.py b/plasmapy/physics/tests/test_parameters.py
index 8f658d34..67f50d7e 100644
--- a/plasmapy/physics/tests/test_parameters.py
+++ b/plasmapy/physics/tests/test_parameters.py
@@ -3,10 +3,11 @@
import numpy as np
import pytest
from astropy import units as u
+from warnings import simplefilter
-
+from ...utils.exceptions import RelativityWarning, RelativityError
+from ...utils.exceptions import PhysicsError
from ...constants import c, m_p, m_e, e, mu0
-
from ..parameters import (Alfven_speed,
gyrofrequency,
gyroradius,
@@ -21,6 +22,7 @@
upper_hybrid_frequency,
lower_hybrid_frequency)
+
B = 1.0*u.T
Z = 1
ion = 'p'
@@ -106,10 +108,10 @@ def test_Alfven_speed():
with pytest.raises(ValueError):
Alfven_speed(B, n_i, ion='spacecats')
- with pytest.raises(UserWarning): # relativistic
+ with pytest.warns(RelativityWarning): # relativistic
Alfven_speed(5e1*u.T, 5e19*u.m**-3, ion='p')
- with pytest.raises(UserWarning): # super-relativistic
+ with pytest.raises(RelativityError): # super-relativistic
Alfven_speed(5e8*u.T, 5e19*u.m**-3, ion='p')
with pytest.raises(ValueError):
@@ -121,10 +123,10 @@ def test_Alfven_speed():
with pytest.raises(ValueError):
Alfven_speed(1*u.T, np.nan*u.m**-3, ion='p')
- with pytest.raises(UserWarning):
+ with pytest.raises(RelativityError):
assert Alfven_speed(np.inf*u.T, 1*u.m**-3, ion='p') == np.inf*u.m/u.s
- with pytest.raises(UserWarning):
+ with pytest.raises(RelativityError):
assert Alfven_speed(-np.inf*u.T, 1*u.m**-3, ion='p') == np.inf*u.m/u.s
with pytest.raises(UserWarning):
@@ -151,8 +153,8 @@ def test_ion_sound_speed():
assert ion_sound_speed(T_e=T_e, gamma_e=1) == ion_sound_speed(T_e=T_e)
- with pytest.raises(UserWarning):
- assert ion_sound_speed(T_i=T_i, gamma_i=np.inf) == np.inf*u.m/u.s
+ with pytest.raises(RelativityError):
+ ion_sound_speed(T_i=T_i, gamma_i=np.inf)
with pytest.raises(ValueError):
ion_sound_speed(T_i=np.array([5, 6, 5])*u.K, T_e=np.array([3, 4])*u.K)
@@ -163,10 +165,10 @@ def test_ion_sound_speed():
with pytest.raises(TypeError):
ion_sound_speed('p')
- with pytest.raises(ValueError):
+ with pytest.raises(PhysicsError):
ion_sound_speed(T_i=T_i, gamma_i=0.9999)
- with pytest.raises(ValueError):
+ with pytest.raises(PhysicsError):
ion_sound_speed(T_i=T_i, gamma_e=0.9999)
with pytest.raises(TypeError):
@@ -181,10 +183,10 @@ def test_ion_sound_speed():
with pytest.raises(ValueError):
ion_sound_speed(T_i=-np.abs(T_i))
- with pytest.raises(UserWarning):
- ion_sound_speed(T_i=5e12*u.K)
+ with pytest.warns(RelativityWarning):
+ ion_sound_speed(T_i=5e11*u.K)
- with pytest.raises(UserWarning):
+ with pytest.raises(RelativityError):
ion_sound_speed(T_i=5e19*u.K)
with pytest.raises(u.UnitConversionError):
@@ -226,10 +228,10 @@ def test_thermal_speed():
with pytest.raises(ValueError):
thermal_speed(-T_e)
- with pytest.raises(UserWarning):
+ with pytest.warns(RelativityWarning):
thermal_speed(1e9*u.K)
- with pytest.raises(UserWarning):
+ with pytest.raises(RelativityError):
thermal_speed(5e19*u.K)
with pytest.raises(UserWarning):
@@ -254,10 +256,10 @@ def test_thermal_speed():
with pytest.raises(ValueError):
thermal_speed(-T_e, particle='p')
- with pytest.raises(UserWarning):
+ with pytest.warns(RelativityWarning):
thermal_speed(1e11*u.K, particle='p')
- with pytest.raises(UserWarning):
+ with pytest.raises(RelativityError):
thermal_speed(1e14*u.K, particle='p')
with pytest.raises(ValueError):
diff --git a/plasmapy/physics/tests/test_quantum.py b/plasmapy/physics/tests/test_quantum.py
index 22ba9741..060a8b6c 100644
--- a/plasmapy/physics/tests/test_quantum.py
+++ b/plasmapy/physics/tests/test_quantum.py
@@ -2,11 +2,13 @@
import pytest
import astropy.units as u
from ...constants import c, h
-from ..quantum import (deBroglie_wavelength,
- thermal_deBroglie_wavelength,
- Fermi_energy,
+from ...utils.exceptions import RelativityError
+from ..quantum import (deBroglie_wavelength,
+ thermal_deBroglie_wavelength,
+ Fermi_energy,
Thomas_Fermi_length)
+
def test_deBroglie_wavelength():
dbwavelength1 = deBroglie_wavelength(2e7*u.cm/u.s, 'e')
@@ -39,7 +41,7 @@ def test_deBroglie_wavelength():
assert deBroglie_wavelength(1*u.m/u.s, 5*u.kg) == \
deBroglie_wavelength(100*u.cm/u.s, 5000*u.g)
- with pytest.raises(ValueError):
+ with pytest.raises(RelativityError):
deBroglie_wavelength(c*1.000000001, 'e')
with pytest.raises(UserWarning):
@@ -51,12 +53,15 @@ def test_deBroglie_wavelength():
with pytest.raises(ValueError):
deBroglie_wavelength(8*u.m/u.s, 'sddsf')
+
# defining some plasma parameters for tests
T_e = 1 * u.eV
n_e = 1e23 * u.cm**-3
# should probably change this to use unittest module
# add tests for numpy arrays as inputs
# add tests for different astropy units (random fuzzing method?)
+
+
def test_thermal_deBroglie_wavelength():
r"""Test the thermal_deBroglie_wavelength function in quantum.py."""
lambda_dbTh = thermal_deBroglie_wavelength(T_e)
@@ -77,6 +82,7 @@ def test_thermal_deBroglie_wavelength():
with pytest.raises(ValueError):
thermal_deBroglie_wavelength(T_e=-1*u.eV)
+
def test_Fermi_energy():
r"""Test the Fermi_energy function in quantum.py."""
energy_F = Fermi_energy(n_e)
@@ -97,6 +103,7 @@ def test_Fermi_energy():
with pytest.raises(ValueError):
Fermi_energy(n_e=-1*u.m**-3)
+
def test_Thomas_Fermi_length():
r"""Test the Thomas_Fermi_length function in quantum.py."""
lambda_TF = Thomas_Fermi_length(n_e)
@@ -116,4 +123,3 @@ def test_Thomas_Fermi_length():
Thomas_Fermi_length("Bad Input")
with pytest.raises(ValueError):
Thomas_Fermi_length(n_e=-1*u.m**-3)
-
\ No newline at end of file
diff --git a/plasmapy/physics/tests/test_relativity.py b/plasmapy/physics/tests/test_relativity.py
index 30080f09..d4df1c74 100644
--- a/plasmapy/physics/tests/test_relativity.py
+++ b/plasmapy/physics/tests/test_relativity.py
@@ -5,6 +5,7 @@
from astropy import units as u
from ...constants import c
from ..relativity import Lorentz_factor
+from ...utils.exceptions import RelativityError
def test_Lorentz_factor():
@@ -25,7 +26,7 @@ def test_Lorentz_factor():
assert (Lorentz_factor(3*u.m/u.s)*u.dimensionless_unscaled).unit == \
u.dimensionless_unscaled
- with pytest.raises(ValueError):
+ with pytest.raises(RelativityError):
Lorentz_factor(1.0000000001*c)
with pytest.raises((ValueError, UserWarning)):
diff --git a/plasmapy/physics/tests/test_transport.py b/plasmapy/physics/tests/test_transport.py
index a1553e55..f69e6094 100644
--- a/plasmapy/physics/tests/test_transport.py
+++ b/plasmapy/physics/tests/test_transport.py
@@ -5,6 +5,7 @@
import pytest
from astropy import units as u
+from ...utils.exceptions import RelativityWarning, RelativityError
from ...constants import c, m_p, m_e, e, mu0
from ..transport import (Coulomb_logarithm)
@@ -38,8 +39,11 @@ def test_Coulomb_logarithm():
assert np.isclose(Coulomb_logarithm(1e5*u.K, 5*u.m**-3, ('e', 'e'),
V=1e4*u.m/u.s), 21.379082011)
- with pytest.raises(UserWarning):
- Coulomb_logarithm(1e5*u.K, 1*u.m**-3, ('e', 'p'), 299792458*u.m/u.s)
+ with pytest.warns(RelativityWarning):
+ Coulomb_logarithm(1e5*u.K, 1*u.m**-3, ('e', 'p'), 0.9*c)
+
+ with pytest.raises(RelativityError):
+ Coulomb_logarithm(1e5*u.K, 1*u.m**-3, ('e', 'p'), 1.0*c)
with pytest.raises(u.UnitConversionError):
Coulomb_logarithm(1e5*u.g, 1*u.m**-3, ('e', 'p'), 29979245*u.m/u.s)
diff --git a/plasmapy/utils/tests/test_checks.py b/plasmapy/utils/tests/test_checks.py
index d8c54062..c88e3f2a 100644
--- a/plasmapy/utils/tests/test_checks.py
+++ b/plasmapy/utils/tests/test_checks.py
@@ -4,6 +4,7 @@
from astropy import units as u
import pytest
+from ...utils.exceptions import RelativityWarning, RelativityError
from ...constants import c
from ..checks import (
_check_quantity, _check_relativistic, check_relativistic,
@@ -224,21 +225,25 @@ def func(x, y, z=10*u.eV):
]
# (speed, betafrac, error)
-relativisitc_error_examples = [
- (0.11*c, 0.1, UserWarning),
- (1.0*c, 0.1, UserWarning),
- (1.1*c, 0.1, UserWarning),
- (np.inf*u.cm/u.s, 0.1, UserWarning),
- (-0.11*c, 0.1, UserWarning),
- (-1.0*c, 0.1, UserWarning),
- (-1.1*c, 0.1, UserWarning),
- (-np.inf*u.cm/u.s, 0.1, UserWarning),
- (2997924581*u.cm/u.s, 0.1, UserWarning),
- (0.02*c, 0.01, UserWarning),
+relativistic_error_examples = [
(u.m/u.s, 0.1, TypeError),
(51513.35, 0.1, TypeError),
(5*u.m, 0.1, u.UnitConversionError),
- (np.nan*u.m/u.s, 0.1, ValueError)
+ (np.nan*u.m/u.s, 0.1, ValueError),
+ (1.0*c, 0.1, RelativityError),
+ (1.1*c, 0.1, RelativityError),
+ (np.inf*u.cm/u.s, 0.1, RelativityError),
+ (-1.0*c, 0.1, RelativityError),
+ (-1.1*c, 0.1, RelativityError),
+ (-np.inf*u.cm/u.s, 0.1, RelativityError),
+]
+
+# (speed, betafrac, warning)
+relativistic_warning_examples = [
+ (0.11*c, 0.1),
+ (-0.11*c, 0.1),
+ (2997924581*u.cm/u.s, 0.1),
+ (0.02*c, 0.01),
]
@@ -248,12 +253,19 @@ def test__check_relativisitc_valid(speed, betafrac):
_check_relativistic(speed, 'f', betafrac=betafrac)
[email protected]("speed, betafrac, error", relativisitc_error_examples)
[email protected]("speed, betafrac, error", relativistic_error_examples)
def test__check_relativistic_errors(speed, betafrac, error):
with pytest.raises(error):
_check_relativistic(speed, 'f', betafrac=betafrac)
[email protected]("speed, betafrac",
+ relativistic_warning_examples)
+def test__check_relativistic_warnings(speed, betafrac):
+ with pytest.warns(RelativityWarning):
+ _check_relativistic(speed, 'f', betafrac=betafrac)
+
+
# Tests for check_relativistic decorator
@pytest.mark.parametrize("speed, betafrac", non_relativistic_speed_examples)
def test_check_relativistic_decorator(speed, betafrac):
@@ -289,7 +301,7 @@ def speed_func():
speed_func()
[email protected]("speed, betafrac, error", relativisitc_error_examples)
[email protected]("speed, betafrac, error", relativistic_error_examples)
def test_check_relativistic_decorator_errors(speed, betafrac, error):
@check_relativistic(betafrac=betafrac)
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_hyperlinks",
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 2,
"test_score": 2
},
"num_modified_files": 4
} | unknown | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest pytest-cov pytest-xdist pytest-mock pytest-asyncio",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.6",
"reqs_path": [
"requirements/base.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | astropy==4.1
attrs==22.2.0
certifi==2021.5.30
coverage==6.2
execnet==1.9.0
importlib-metadata==4.8.3
iniconfig==1.1.1
numpy==1.19.5
packaging==21.3
-e git+https://github.com/PlasmaPy/PlasmaPy.git@69712cb40b8b588400301edfd6925d41d2f13eac#egg=plasmapy
pluggy==1.0.0
py==1.11.0
pyparsing==3.1.4
pytest==7.0.1
pytest-asyncio==0.16.0
pytest-cov==4.0.0
pytest-mock==3.6.1
pytest-xdist==3.0.2
scipy==1.5.4
tomli==1.2.3
typing_extensions==4.1.1
zipp==3.6.0
| name: PlasmaPy
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- astropy==4.1
- attrs==22.2.0
- coverage==6.2
- execnet==1.9.0
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- numpy==1.19.5
- packaging==21.3
- pluggy==1.0.0
- py==1.11.0
- pyparsing==3.1.4
- pytest==7.0.1
- pytest-asyncio==0.16.0
- pytest-cov==4.0.0
- pytest-mock==3.6.1
- pytest-xdist==3.0.2
- scipy==1.5.4
- tomli==1.2.3
- typing-extensions==4.1.1
- zipp==3.6.0
prefix: /opt/conda/envs/PlasmaPy
| [
"plasmapy/physics/tests/test_parameters.py::test_Alfven_speed",
"plasmapy/physics/tests/test_parameters.py::test_ion_sound_speed",
"plasmapy/physics/tests/test_parameters.py::test_thermal_speed",
"plasmapy/physics/tests/test_parameters.py::test_gyrofrequency",
"plasmapy/physics/tests/test_parameters.py::test_gyroradius",
"plasmapy/physics/tests/test_parameters.py::test_plasma_frequency",
"plasmapy/physics/tests/test_parameters.py::test_Debye_length",
"plasmapy/physics/tests/test_parameters.py::test_Debye_number",
"plasmapy/physics/tests/test_parameters.py::test_inertial_length",
"plasmapy/physics/tests/test_parameters.py::test_magnetic_pressure",
"plasmapy/physics/tests/test_parameters.py::test_magnetic_energy_density",
"plasmapy/physics/tests/test_parameters.py::test_upper_hybrid_frequency",
"plasmapy/physics/tests/test_parameters.py::test_lower_hybrid_frequency",
"plasmapy/physics/tests/test_quantum.py::test_deBroglie_wavelength",
"plasmapy/physics/tests/test_relativity.py::test_Lorentz_factor",
"plasmapy/physics/tests/test_transport.py::test_Coulomb_logarithm",
"plasmapy/utils/tests/test_checks.py::test__check_quantity_errors_non_default[value0-units0-False-False-True-ValueError]",
"plasmapy/utils/tests/test_checks.py::test__check_quantity_errors_non_default[value1-units1-True-False-False-ValueError]",
"plasmapy/utils/tests/test_checks.py::test__check_quantity_errors_default[value0-units0-TypeError]",
"plasmapy/utils/tests/test_checks.py::test__check_quantity_errors_default[value1-5-TypeError]",
"plasmapy/utils/tests/test_checks.py::test__check_quantity_errors_default[value2-units2-TypeError]",
"plasmapy/utils/tests/test_checks.py::test__check_quantity_errors_default[value3-units3-TypeError]",
"plasmapy/utils/tests/test_checks.py::test__check_quantity_errors_default[value4-units4-TypeError]",
"plasmapy/utils/tests/test_checks.py::test__check_quantity_errors_default[5.0-units5-UserWarning]",
"plasmapy/utils/tests/test_checks.py::test__check_quantity_errors_default[value6-units6-UnitConversionError]",
"plasmapy/utils/tests/test_checks.py::test__check_quantity_errors_default[value7-units7-ValueError]",
"plasmapy/utils/tests/test_checks.py::test__check_quantity_non_default[value0-units0-True-True-True]",
"plasmapy/utils/tests/test_checks.py::test__check_quantity_default[value0-units0]",
"plasmapy/utils/tests/test_checks.py::test__check_quantity_default[value1-units1]",
"plasmapy/utils/tests/test_checks.py::test__check_quantity_default[value2-units2]",
"plasmapy/utils/tests/test_checks.py::test__check_quantity_default[value3-units3]",
"plasmapy/utils/tests/test_checks.py::test__check_quantity_default[value4-units4]",
"plasmapy/utils/tests/test_checks.py::test__check_quantity_default[value5-units5]",
"plasmapy/utils/tests/test_checks.py::test__check_quantity_default[value6-units6]",
"plasmapy/utils/tests/test_checks.py::test__check_quantity_default[value7-units7]",
"plasmapy/utils/tests/test_checks.py::test__check_quantity_default[value8-units8]",
"plasmapy/utils/tests/test_checks.py::test_check_quantity_decorator_errors_default[value0-units0-TypeError]",
"plasmapy/utils/tests/test_checks.py::test_check_quantity_decorator_errors_default[value1-5-TypeError]",
"plasmapy/utils/tests/test_checks.py::test_check_quantity_decorator_errors_default[value2-units2-TypeError]",
"plasmapy/utils/tests/test_checks.py::test_check_quantity_decorator_errors_default[value3-units3-TypeError]",
"plasmapy/utils/tests/test_checks.py::test_check_quantity_decorator_errors_default[value4-units4-TypeError]",
"plasmapy/utils/tests/test_checks.py::test_check_quantity_decorator_errors_default[5.0-units5-UserWarning]",
"plasmapy/utils/tests/test_checks.py::test_check_quantity_decorator_errors_default[value6-units6-UnitConversionError]",
"plasmapy/utils/tests/test_checks.py::test_check_quantity_decorator_errors_default[value7-units7-ValueError]",
"plasmapy/utils/tests/test_checks.py::test_check_quantity_decorator_errors_non_default[value0-units0-False-False-True-ValueError]",
"plasmapy/utils/tests/test_checks.py::test_check_quantity_decorator_errors_non_default[value1-units1-True-False-False-ValueError]",
"plasmapy/utils/tests/test_checks.py::test_check_quantity_decorator_default[value0-units0]",
"plasmapy/utils/tests/test_checks.py::test_check_quantity_decorator_default[value1-units1]",
"plasmapy/utils/tests/test_checks.py::test_check_quantity_decorator_default[value2-units2]",
"plasmapy/utils/tests/test_checks.py::test_check_quantity_decorator_default[value3-units3]",
"plasmapy/utils/tests/test_checks.py::test_check_quantity_decorator_default[value4-units4]",
"plasmapy/utils/tests/test_checks.py::test_check_quantity_decorator_default[value5-units5]",
"plasmapy/utils/tests/test_checks.py::test_check_quantity_decorator_default[value6-units6]",
"plasmapy/utils/tests/test_checks.py::test_check_quantity_decorator_default[value7-units7]",
"plasmapy/utils/tests/test_checks.py::test_check_quantity_decorator_default[value8-units8]",
"plasmapy/utils/tests/test_checks.py::test_check_quantity_decorator_non_default[value0-units0-True-True-True]",
"plasmapy/utils/tests/test_checks.py::test_check_quantity_decorator_missing_validated_params",
"plasmapy/utils/tests/test_checks.py::test_check_quantity_decorator_two_args_default",
"plasmapy/utils/tests/test_checks.py::test_check_quantity_decorator_two_args_not_default",
"plasmapy/utils/tests/test_checks.py::test_check_quantity_decorator_two_args_one_kwargs_default",
"plasmapy/utils/tests/test_checks.py::test_check_quantity_decorator_two_args_one_kwargs_not_default",
"plasmapy/utils/tests/test_checks.py::test__check_relativisitc_valid[speed0-0.1]",
"plasmapy/utils/tests/test_checks.py::test__check_relativisitc_valid[speed1-0.1]",
"plasmapy/utils/tests/test_checks.py::test__check_relativisitc_valid[speed2-0.1]",
"plasmapy/utils/tests/test_checks.py::test__check_relativisitc_valid[speed3-0.1]",
"plasmapy/utils/tests/test_checks.py::test__check_relativistic_errors[speed0-0.1-TypeError]",
"plasmapy/utils/tests/test_checks.py::test__check_relativistic_errors[51513.35-0.1-TypeError]",
"plasmapy/utils/tests/test_checks.py::test__check_relativistic_errors[speed2-0.1-UnitConversionError]",
"plasmapy/utils/tests/test_checks.py::test__check_relativistic_errors[speed3-0.1-ValueError]",
"plasmapy/utils/tests/test_checks.py::test__check_relativistic_errors[speed4-0.1-RelativityError]",
"plasmapy/utils/tests/test_checks.py::test__check_relativistic_errors[speed5-0.1-RelativityError]",
"plasmapy/utils/tests/test_checks.py::test__check_relativistic_errors[speed6-0.1-RelativityError]",
"plasmapy/utils/tests/test_checks.py::test__check_relativistic_errors[speed7-0.1-RelativityError]",
"plasmapy/utils/tests/test_checks.py::test__check_relativistic_errors[speed8-0.1-RelativityError]",
"plasmapy/utils/tests/test_checks.py::test__check_relativistic_errors[speed9-0.1-RelativityError]",
"plasmapy/utils/tests/test_checks.py::test__check_relativistic_warnings[speed0-0.1]",
"plasmapy/utils/tests/test_checks.py::test__check_relativistic_warnings[speed1-0.1]",
"plasmapy/utils/tests/test_checks.py::test__check_relativistic_warnings[speed2-0.1]",
"plasmapy/utils/tests/test_checks.py::test__check_relativistic_warnings[speed3-0.01]",
"plasmapy/utils/tests/test_checks.py::test_check_relativistic_decorator[speed0-0.1]",
"plasmapy/utils/tests/test_checks.py::test_check_relativistic_decorator[speed1-0.1]",
"plasmapy/utils/tests/test_checks.py::test_check_relativistic_decorator[speed2-0.1]",
"plasmapy/utils/tests/test_checks.py::test_check_relativistic_decorator[speed3-0.1]",
"plasmapy/utils/tests/test_checks.py::test_check_relativistic_decorator_no_args[speed0]",
"plasmapy/utils/tests/test_checks.py::test_check_relativistic_decorator_no_args[speed1]",
"plasmapy/utils/tests/test_checks.py::test_check_relativistic_decorator_no_args[speed2]",
"plasmapy/utils/tests/test_checks.py::test_check_relativistic_decorator_no_args[speed3]",
"plasmapy/utils/tests/test_checks.py::test_check_relativistic_decorator_no_args_parentheses[speed0]",
"plasmapy/utils/tests/test_checks.py::test_check_relativistic_decorator_no_args_parentheses[speed1]",
"plasmapy/utils/tests/test_checks.py::test_check_relativistic_decorator_no_args_parentheses[speed2]",
"plasmapy/utils/tests/test_checks.py::test_check_relativistic_decorator_no_args_parentheses[speed3]",
"plasmapy/utils/tests/test_checks.py::test_check_relativistic_decorator_errors[speed0-0.1-TypeError]",
"plasmapy/utils/tests/test_checks.py::test_check_relativistic_decorator_errors[51513.35-0.1-TypeError]",
"plasmapy/utils/tests/test_checks.py::test_check_relativistic_decorator_errors[speed2-0.1-UnitConversionError]",
"plasmapy/utils/tests/test_checks.py::test_check_relativistic_decorator_errors[speed3-0.1-ValueError]",
"plasmapy/utils/tests/test_checks.py::test_check_relativistic_decorator_errors[speed4-0.1-RelativityError]",
"plasmapy/utils/tests/test_checks.py::test_check_relativistic_decorator_errors[speed5-0.1-RelativityError]",
"plasmapy/utils/tests/test_checks.py::test_check_relativistic_decorator_errors[speed6-0.1-RelativityError]",
"plasmapy/utils/tests/test_checks.py::test_check_relativistic_decorator_errors[speed7-0.1-RelativityError]",
"plasmapy/utils/tests/test_checks.py::test_check_relativistic_decorator_errors[speed8-0.1-RelativityError]",
"plasmapy/utils/tests/test_checks.py::test_check_relativistic_decorator_errors[speed9-0.1-RelativityError]"
]
| [
"plasmapy/physics/tests/test_quantum.py::test_thermal_deBroglie_wavelength",
"plasmapy/physics/tests/test_quantum.py::test_Fermi_energy",
"plasmapy/physics/tests/test_quantum.py::test_Thomas_Fermi_length"
]
| []
| []
| BSD 3-Clause "New" or "Revised" License | 1,913 | [
"plasmapy/utils/exceptions.py",
"plasmapy/physics/quantum.py",
"plasmapy/utils/checks.py",
"plasmapy/physics/parameters.py",
"plasmapy/physics/relativity.py"
]
| [
"plasmapy/utils/exceptions.py",
"plasmapy/physics/quantum.py",
"plasmapy/utils/checks.py",
"plasmapy/physics/parameters.py",
"plasmapy/physics/relativity.py"
]
|
|
sprymix__csscompressor-8 | bec3e582cb5ab7182a0ca08ba381e491b94ed10c | 2017-11-25 03:33:22 | bec3e582cb5ab7182a0ca08ba381e491b94ed10c | diff --git a/csscompressor/__init__.py b/csscompressor/__init__.py
index e1ae16b..e34af04 100644
--- a/csscompressor/__init__.py
+++ b/csscompressor/__init__.py
@@ -113,6 +113,7 @@ def _preserve_call_tokens(css, regexp, preserved_tokens, remove_ws=False):
max_idx = len(css) - 1
append_idx = 0
sb = []
+ nest_term = None
for match in regexp.finditer(css):
name = match.group(1)
@@ -121,17 +122,29 @@ def _preserve_call_tokens(css, regexp, preserved_tokens, remove_ws=False):
term = match.group(2) if match.lastindex > 1 else None
if not term:
term = ')'
+ nest_term = '('
found_term = False
end_idx = match.end(0) - 1
+ nest_idx = end_idx if nest_term else 0
+ nested = False
while not found_term and (end_idx + 1) <= max_idx:
+ if nest_term:
+ nest_idx = css.find(nest_term, nest_idx + 1)
end_idx = css.find(term, end_idx + 1)
if end_idx > 0:
+ if nest_idx > 0 and nest_idx < end_idx and \
+ css[nest_idx - 1] != '\\':
+ nested = True
+
if css[end_idx - 1] != '\\':
- found_term = True
- if term != ')':
- end_idx = css.find(')', end_idx)
+ if nested:
+ nested = False
+ else:
+ found_term = True
+ if term != ')':
+ end_idx = css.find(')', end_idx)
else:
raise ValueError('malformed css')
@@ -139,7 +152,7 @@ def _preserve_call_tokens(css, regexp, preserved_tokens, remove_ws=False):
assert found_term
- token = css[start_idx:end_idx]
+ token = css[start_idx:end_idx].strip()
if remove_ws:
token = _ws_re.sub('', token)
| Major breakage when using some calc statements
I noticed csscompressor completely breaks some css rules with + in them. For example:
`>>> csscompressor.compress("calc( (10vh - 100px) + 30px )");
'calc( (10vh - 100px)+30px)'
> > > csscompressor.compress("calc( (10vh - 100px) / 4 + 30px )");
> > > 'calc( (10vh - 100px) / 4+30px)'
> > > `
The + and - operators must always be surrounded by whitespace, according to the [spec](https://developer.mozilla.org/en-US/docs/Web/CSS/calc), and when compressed, this rule is now broken and doesn't work in the browser.
Considering calc should be well-supported by just about every browser updated in the last 4 years, calc is super handy... but unfortunately breaks if you decide to compress with csscompress.
| sprymix/csscompressor | diff --git a/csscompressor/tests/test_compress.py b/csscompressor/tests/test_compress.py
index 8d11e01..e65768a 100644
--- a/csscompressor/tests/test_compress.py
+++ b/csscompressor/tests/test_compress.py
@@ -52,3 +52,16 @@ class Tests(unittest.TestCase):
a {content: calc(10px-10%}
'''
self.assertRaises(ValueError, compress, input)
+
+ def test_nested_1(self):
+ input = '''
+ a { width: calc( (10vh - 100px) / 4 + 30px ) }
+ '''
+ output = compress(input)
+ assert output == "a{width:calc((10vh - 100px) / 4 + 30px)}"
+
+ def test_nested_2(self):
+ input = '''
+ a { width: calc( ((10vh - 100px) / 4 + 30px ) }
+ '''
+ self.assertRaises(ValueError, compress, input)
| {
"commit_name": "merge_commit",
"failed_lite_validators": [
"has_hyperlinks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 1,
"test_score": 2
},
"num_modified_files": 1
} | 0.9 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"pytest"
],
"pre_install": null,
"python": "3.5",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work
certifi==2021.5.30
-e git+https://github.com/sprymix/csscompressor.git@bec3e582cb5ab7182a0ca08ba381e491b94ed10c#egg=csscompressor
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work
packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work
pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pytest==6.2.4
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
| name: csscompressor
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=21.4.0=pyhd3eb1b0_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- importlib-metadata=4.8.1=py36h06a4308_0
- importlib_metadata=4.8.1=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- more-itertools=8.12.0=pyhd3eb1b0_0
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=21.3=pyhd3eb1b0_0
- pip=21.2.2=py36h06a4308_0
- pluggy=0.13.1=py36h06a4308_0
- py=1.11.0=pyhd3eb1b0_0
- pyparsing=3.0.4=pyhd3eb1b0_0
- pytest=6.2.4=py36h06a4308_2
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- toml=0.10.2=pyhd3eb1b0_0
- typing_extensions=4.1.1=pyh06a4308_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zipp=3.6.0=pyhd3eb1b0_0
- zlib=1.2.13=h5eee18b_1
prefix: /opt/conda/envs/csscompressor
| [
"csscompressor/tests/test_compress.py::Tests::test_nested_1",
"csscompressor/tests/test_compress.py::Tests::test_nested_2"
]
| []
| [
"csscompressor/tests/test_compress.py::Tests::test_compress_1",
"csscompressor/tests/test_compress.py::Tests::test_compress_2",
"csscompressor/tests/test_compress.py::Tests::test_linelen_1",
"csscompressor/tests/test_compress.py::Tests::test_linelen_2",
"csscompressor/tests/test_compress.py::Tests::test_linelen_3"
]
| []
| BSD | 1,914 | [
"csscompressor/__init__.py"
]
| [
"csscompressor/__init__.py"
]
|
|
networkx__networkx-2773 | 3d7ea0d690e59c2d5d223528ea9e21b21fb7f8a4 | 2017-11-25 17:52:23 | 93b4b9227aa8a7ac4cbd946cf3dae3b168e17b45 | diff --git a/networkx/generators/degree_seq.py b/networkx/generators/degree_seq.py
index 6d57bcf05..c42faebc7 100644
--- a/networkx/generators/degree_seq.py
+++ b/networkx/generators/degree_seq.py
@@ -426,7 +426,7 @@ def expected_degree_graph(w, seed=None, selfloops=True):
# weights dictates the order of the (integer) node labels, so we
# need to remember the permutation applied in the sorting.
order = sorted(enumerate(w), key=itemgetter(1), reverse=True)
- mapping = {c: v for c, (u, v) in enumerate(order)}
+ mapping = {c: u for c, (u, v) in enumerate(order)}
seq = [v for u, v in order]
last = n
if not selfloops:
| node-mapping bug expected_degree_graph
Hi I used the NX1 expected_degree_graph generator. It has the same interface as the NX2.
https://networkx.github.io/documentation/stable/reference/generated/networkx.generators.degree_seq.expected_degree_graph.html#networkx.generators.degree_seq.expected_degree_graph
But NX2 will not generate the graph correctly. The total number of edge is always 1. No further error message provided.
Same script works well for NX1. (I downgrade to older version.
```python
D = 10
N = 1000
degree_l = [D for i in range(N)]
G = nx.expected_degree_graph(degree_l, seed=datetime.now(), selfloops=False)
``` | networkx/networkx | diff --git a/networkx/generators/tests/test_degree_seq.py b/networkx/generators/tests/test_degree_seq.py
index c1aca1791..bde2c7954 100644
--- a/networkx/generators/tests/test_degree_seq.py
+++ b/networkx/generators/tests/test_degree_seq.py
@@ -92,6 +92,8 @@ def test_expected_degree_graph():
# test that fixed seed delivers the same graph
deg_seq = [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3]
G1 = nx.expected_degree_graph(deg_seq, seed=1000)
+ assert_equal(len(G1), 12)
+
G2 = nx.expected_degree_graph(deg_seq, seed=1000)
assert_true(nx.is_isomorphic(G1, G2))
@@ -105,6 +107,7 @@ def test_expected_degree_graph_selfloops():
G1 = nx.expected_degree_graph(deg_seq, seed=1000, selfloops=False)
G2 = nx.expected_degree_graph(deg_seq, seed=1000, selfloops=False)
assert_true(nx.is_isomorphic(G1, G2))
+ assert_equal(len(G1), 12)
def test_expected_degree_graph_skew():
@@ -112,6 +115,7 @@ def test_expected_degree_graph_skew():
G1 = nx.expected_degree_graph(deg_seq, seed=1000)
G2 = nx.expected_degree_graph(deg_seq, seed=1000)
assert_true(nx.is_isomorphic(G1, G2))
+ assert_equal(len(G1), 5)
def test_havel_hakimi_construction():
| {
"commit_name": "merge_commit",
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 1,
"test_score": 0
},
"num_modified_files": 1
} | 2.0 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"nose",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y libgdal-dev graphviz"
],
"python": "3.6",
"reqs_path": [
"requirements/default.txt",
"requirements/test.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs==22.2.0
certifi==2021.5.30
charset-normalizer==2.0.12
codecov==2.1.13
coverage==6.2
decorator==5.1.1
idna==3.10
importlib-metadata==4.8.3
iniconfig==1.1.1
-e git+https://github.com/networkx/networkx.git@3d7ea0d690e59c2d5d223528ea9e21b21fb7f8a4#egg=networkx
nose==1.3.7
nose-ignore-docstring==0.2
packaging==21.3
pluggy==1.0.0
py==1.11.0
pyparsing==3.1.4
pytest==7.0.1
requests==2.27.1
tomli==1.2.3
typing_extensions==4.1.1
urllib3==1.26.20
zipp==3.6.0
| name: networkx
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- attrs==22.2.0
- charset-normalizer==2.0.12
- codecov==2.1.13
- coverage==6.2
- decorator==5.1.1
- idna==3.10
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- nose==1.3.7
- nose-ignore-docstring==0.2
- packaging==21.3
- pluggy==1.0.0
- py==1.11.0
- pyparsing==3.1.4
- pytest==7.0.1
- requests==2.27.1
- tomli==1.2.3
- typing-extensions==4.1.1
- urllib3==1.26.20
- zipp==3.6.0
prefix: /opt/conda/envs/networkx
| [
"networkx/generators/tests/test_degree_seq.py::test_expected_degree_graph_skew"
]
| []
| [
"networkx/generators/tests/test_degree_seq.py::TestConfigurationModel::test_empty_degree_sequence",
"networkx/generators/tests/test_degree_seq.py::TestConfigurationModel::test_degree_zero",
"networkx/generators/tests/test_degree_seq.py::TestConfigurationModel::test_degree_sequence",
"networkx/generators/tests/test_degree_seq.py::TestConfigurationModel::test_random_seed",
"networkx/generators/tests/test_degree_seq.py::TestConfigurationModel::test_directed_disallowed",
"networkx/generators/tests/test_degree_seq.py::TestConfigurationModel::test_odd_degree_sum",
"networkx/generators/tests/test_degree_seq.py::test_directed_configuation_raise_unequal",
"networkx/generators/tests/test_degree_seq.py::test_directed_configuation_mode",
"networkx/generators/tests/test_degree_seq.py::test_expected_degree_graph_empty",
"networkx/generators/tests/test_degree_seq.py::test_expected_degree_graph",
"networkx/generators/tests/test_degree_seq.py::test_expected_degree_graph_selfloops",
"networkx/generators/tests/test_degree_seq.py::test_havel_hakimi_construction",
"networkx/generators/tests/test_degree_seq.py::test_directed_havel_hakimi",
"networkx/generators/tests/test_degree_seq.py::test_degree_sequence_tree",
"networkx/generators/tests/test_degree_seq.py::test_random_degree_sequence_graph",
"networkx/generators/tests/test_degree_seq.py::test_random_degree_sequence_graph_raise",
"networkx/generators/tests/test_degree_seq.py::test_random_degree_sequence_large"
]
| []
| BSD 3-Clause | 1,915 | [
"networkx/generators/degree_seq.py"
]
| [
"networkx/generators/degree_seq.py"
]
|
|
networkx__networkx-2774 | 18c2fa79edbd578bea3e7a1935502f54c58385d7 | 2017-11-25 23:18:37 | 93b4b9227aa8a7ac4cbd946cf3dae3b168e17b45 | diff --git a/networkx/algorithms/covering.py b/networkx/algorithms/covering.py
index a70a8db4c..43c5124c2 100644
--- a/networkx/algorithms/covering.py
+++ b/networkx/algorithms/covering.py
@@ -72,9 +72,12 @@ def min_edge_cover(G, matching_algorithm=None):
maxcardinality=True)
maximum_matching = matching_algorithm(G)
# ``min_cover`` is superset of ``maximum_matching``
- min_cover = set(maximum_matching.items())
+ try:
+ min_cover = set(maximum_matching.items()) # bipartite matching case returns dict
+ except AttributeError:
+ min_cover = maximum_matching
# iterate for uncovered nodes
- uncovered_nodes = set(G) - {v for u, v in min_cover}
+ uncovered_nodes = set(G) - {v for u, v in min_cover} - {u for u, v in min_cover}
for v in uncovered_nodes:
# Since `v` is uncovered, each edge incident to `v` will join it
# with a covered node (otherwise, if there were an edge joining
diff --git a/networkx/algorithms/matching.py b/networkx/algorithms/matching.py
index 4ff1da4df..ccf9c3770 100644
--- a/networkx/algorithms/matching.py
+++ b/networkx/algorithms/matching.py
@@ -69,7 +69,8 @@ def matching_dict_to_set(matching):
# appear in `matching.items()`, so we use a set of sets. This way,
# only the (frozen)set `{u, v}` appears as an element in the
# returned set.
- return set(map(frozenset, matching.items()))
+
+ return set((u,v) for (u,v) in set(map(frozenset, matching.items())))
def is_matching(G, matching):
@@ -172,11 +173,8 @@ def max_weight_matching(G, maxcardinality=False, weight='weight'):
Returns
-------
- mate : dictionary
- The matching is returned as a dictionary, mate, such that
- mate[v] == w if node v is matched to node w. Unmatched nodes do not
- occur as a key in mate.
-
+ matching : set
+ A maximal matching of the graph.
Notes
-----
@@ -249,7 +247,7 @@ def max_weight_matching(G, maxcardinality=False, weight='weight'):
# Get a list of vertices.
gnodes = list(G)
if not gnodes:
- return {} # don't bother with empty graphs
+ return set( ) # don't bother with empty graphs
# Find the maximum edge weight.
maxweight = 0
@@ -931,4 +929,4 @@ def max_weight_matching(G, maxcardinality=False, weight='weight'):
if allinteger:
verifyOptimum()
- return mate
+ return matching_dict_to_set(mate)
diff --git a/networkx/drawing/layout.py b/networkx/drawing/layout.py
index 71d7df3b7..93a88c3fe 100644
--- a/networkx/drawing/layout.py
+++ b/networkx/drawing/layout.py
@@ -232,6 +232,7 @@ def fruchterman_reingold_layout(G, k=None,
pos=None,
fixed=None,
iterations=50,
+ threshold = 1e-4,
weight='weight',
scale=1,
center=None,
@@ -257,7 +258,11 @@ def fruchterman_reingold_layout(G, k=None,
Nodes to keep fixed at initial position.
iterations : int optional (default=50)
- Number of iterations of spring-force relaxation
+ Maximum number of iterations taken
+
+ threshold: float optional (default = 1e-4)
+ Threshold for relative error in node position changes.
+ The iteration stops if the error is below this threshold.
weight : string or None optional (default='weight')
The edge attribute that holds the numerical value used for
@@ -318,18 +323,18 @@ def fruchterman_reingold_layout(G, k=None,
raise ValueError
A = nx.to_scipy_sparse_matrix(G, weight=weight, dtype='f')
if k is None and fixed is not None:
- # We must adjust k by domain size for layouts not near 1x1
+ # We must adjust k by domain size for layouts not near 1x1
nnodes, _ = A.shape
k = dom_size / np.sqrt(nnodes)
pos = _sparse_fruchterman_reingold(A, k, pos_arr, fixed,
- iterations, dim)
+ iterations, threshold, dim)
except:
A = nx.to_numpy_matrix(G, weight=weight)
if k is None and fixed is not None:
# We must adjust k by domain size for layouts not near 1x1
nnodes, _ = A.shape
k = dom_size / np.sqrt(nnodes)
- pos = _fruchterman_reingold(A, k, pos_arr, fixed, iterations, dim)
+ pos = _fruchterman_reingold(A, k, pos_arr, fixed, iterations, threshold, dim)
if fixed is None:
pos = rescale_layout(pos, scale=scale) + center
pos = dict(zip(G, pos))
@@ -340,7 +345,7 @@ spring_layout = fruchterman_reingold_layout
def _fruchterman_reingold(A, k=None, pos=None, fixed=None,
- iterations=50, dim=2):
+ iterations=50, threshold = 1e-4, dim=2):
# Position nodes in adjacency matrix A using Fruchterman-Reingold
# Entry point for NetworkX graph is fruchterman_reingold_layout()
try:
@@ -401,11 +406,14 @@ def _fruchterman_reingold(A, k=None, pos=None, fixed=None,
pos += delta_pos
# cool temperature
t -= dt
+ err = np.linalg.norm(delta_pos)/nnodes
+ if err < threshold:
+ break
return pos
def _sparse_fruchterman_reingold(A, k=None, pos=None, fixed=None,
- iterations=50, dim=2):
+ iterations=50, threshold=1e-4, dim=2):
# Position nodes in adjacency matrix A using Fruchterman-Reingold
# Entry point for NetworkX graph is fruchterman_reingold_layout()
# Sparse version
@@ -472,9 +480,13 @@ def _sparse_fruchterman_reingold(A, k=None, pos=None, fixed=None,
# update positions
length = np.sqrt((displacement**2).sum(axis=0))
length = np.where(length < 0.01, 0.1, length)
- pos += (displacement * t / length).T
+ delta_pos = (displacement * t / length).T
+ pos += delta_pos
# cool temperature
t -= dt
+ err = np.linalg.norm(delta_pos)/nnodes
+ if err < threshold:
+ break
return pos
diff --git a/networkx/drawing/nx_agraph.py b/networkx/drawing/nx_agraph.py
index 535c2e559..4cd5b5de9 100644
--- a/networkx/drawing/nx_agraph.py
+++ b/networkx/drawing/nx_agraph.py
@@ -150,18 +150,29 @@ def to_agraph(N):
# add nodes
for n, nodedata in N.nodes(data=True):
- A.add_node(n, **nodedata)
+ A.add_node(n)
+ if nodedata is not None:
+ a = A.get_node(n)
+ a.attr.update({k: str(v) for k, v in nodedata.items()})
# loop over edges
-
if N.is_multigraph():
for u, v, key, edgedata in N.edges(data=True, keys=True):
- str_edata = {k: str(v) for k, v in edgedata.items() if k != 'key'}
- A.add_edge(u, v, key=str(key), **str_edata)
+ str_edgedata = {k: str(v) for k, v in edgedata.items() if k != 'key'}
+ A.add_edge(u, v, key=str(key))
+ if edgedata is not None:
+ a = A.get_edge(u,v)
+ a.attr.update(str_edgedata)
+
+
else:
for u, v, edgedata in N.edges(data=True):
str_edgedata = {k: str(v) for k, v in edgedata.items()}
- A.add_edge(u, v, **str_edgedata)
+ A.add_edge(u, v)
+ if edgedata is not None:
+ a = A.get_edge(u,v)
+ a.attr.update(str_edgedata)
+
return A
| maximal_matching and max_weight_matching have different return types
The former returns a set of edges, the latter a dictionary. Should these return the same type of object?
| networkx/networkx | diff --git a/networkx/algorithms/tests/test_covering.py b/networkx/algorithms/tests/test_covering.py
index 1b87c2fa5..7d2c44cd6 100644
--- a/networkx/algorithms/tests/test_covering.py
+++ b/networkx/algorithms/tests/test_covering.py
@@ -24,7 +24,7 @@ class TestMinEdgeCover:
G = nx.Graph()
G.add_edge(0, 1)
assert_equal(nx.min_edge_cover(G),
- {(0, 1), (1, 0)})
+ {(0, 1)})
def test_bipartite_explicit(self):
G = nx.Graph()
@@ -34,6 +34,7 @@ class TestMinEdgeCover:
(2, 'c'), (3, 'c'), (4, 'a')])
min_cover = nx.min_edge_cover(G, nx.algorithms.bipartite.matching.
eppstein_matching)
+ min_cover2 = nx.min_edge_cover(G)
assert_true(nx.is_edge_cover(G, min_cover))
assert_equal(len(min_cover), 8)
@@ -41,7 +42,7 @@ class TestMinEdgeCover:
G = nx.complete_graph(10)
min_cover = nx.min_edge_cover(G)
assert_true(nx.is_edge_cover(G, min_cover))
- assert_equal(len(min_cover), 10)
+ assert_equal(len(min_cover), 5)
class TestIsEdgeCover:
diff --git a/networkx/algorithms/tests/test_matching.py b/networkx/algorithms/tests/test_matching.py
index b6b4ef4b1..0eb0f1c32 100644
--- a/networkx/algorithms/tests/test_matching.py
+++ b/networkx/algorithms/tests/test_matching.py
@@ -5,7 +5,8 @@ from nose.tools import assert_equal
from nose.tools import assert_false
from nose.tools import assert_true
import networkx as nx
-
+from networkx.algorithms.matching import matching_dict_to_set
+from networkx.testing import assert_edges_equal
class TestMaxWeightMatching(object):
"""Unit tests for the
@@ -16,28 +17,28 @@ class TestMaxWeightMatching(object):
def test_trivial1(self):
"""Empty graph"""
G = nx.Graph()
- assert_equal(nx.max_weight_matching(G), {})
+ assert_equal(nx.max_weight_matching(G), set())
def test_trivial2(self):
"""Self loop"""
G = nx.Graph()
G.add_edge(0, 0, weight=100)
- assert_equal(nx.max_weight_matching(G), {})
+ assert_equal(nx.max_weight_matching(G), set())
def test_trivial3(self):
"""Single edge"""
G = nx.Graph()
G.add_edge(0, 1)
- assert_equal(nx.max_weight_matching(G),
- {0: 1, 1: 0})
+ assert_edges_equal(nx.max_weight_matching(G),
+ matching_dict_to_set({0: 1, 1: 0}))
def test_trivial4(self):
"""Small graph"""
G = nx.Graph()
G.add_edge('one', 'two', weight=10)
G.add_edge('two', 'three', weight=11)
- assert_equal(nx.max_weight_matching(G),
- {'three': 'two', 'two': 'three'})
+ assert_edges_equal(nx.max_weight_matching(G),
+ matching_dict_to_set({'three': 'two', 'two': 'three'}))
def test_trivial5(self):
"""Path"""
@@ -45,18 +46,18 @@ class TestMaxWeightMatching(object):
G.add_edge(1, 2, weight=5)
G.add_edge(2, 3, weight=11)
G.add_edge(3, 4, weight=5)
- assert_equal(nx.max_weight_matching(G),
- {2: 3, 3: 2})
- assert_equal(nx.max_weight_matching(G, 1),
- {1: 2, 2: 1, 3: 4, 4: 3})
+ assert_edges_equal(nx.max_weight_matching(G),
+ matching_dict_to_set({2: 3, 3: 2}))
+ assert_edges_equal(nx.max_weight_matching(G, 1),
+ matching_dict_to_set({1: 2, 2: 1, 3: 4, 4: 3}))
def test_trivial6(self):
"""Small graph with arbitrary weight attribute"""
G = nx.Graph()
G.add_edge('one', 'two', weight=10, abcd=11)
G.add_edge('two', 'three', weight=11, abcd=10)
- assert_equal(nx.max_weight_matching(G, weight='abcd'),
- {'one': 'two', 'two': 'one'})
+ assert_edges_equal(nx.max_weight_matching(G, weight='abcd'),
+ matching_dict_to_set({'one': 'two', 'two': 'one'}))
def test_floating_point_weights(self):
"""Floating point weights"""
@@ -65,8 +66,8 @@ class TestMaxWeightMatching(object):
G.add_edge(2, 3, weight=math.exp(1))
G.add_edge(1, 3, weight=3.0)
G.add_edge(1, 4, weight=math.sqrt(2.0))
- assert_equal(nx.max_weight_matching(G),
- {1: 4, 2: 3, 3: 2, 4: 1})
+ assert_edges_equal(nx.max_weight_matching(G),
+ matching_dict_to_set({1: 4, 2: 3, 3: 2, 4: 1}))
def test_negative_weights(self):
"""Negative weights"""
@@ -76,38 +77,38 @@ class TestMaxWeightMatching(object):
G.add_edge(2, 3, weight=1)
G.add_edge(2, 4, weight=-1)
G.add_edge(3, 4, weight=-6)
- assert_equal(nx.max_weight_matching(G),
- {1: 2, 2: 1})
- assert_equal(nx.max_weight_matching(G, 1),
- {1: 3, 2: 4, 3: 1, 4: 2})
+ assert_edges_equal(nx.max_weight_matching(G),
+ matching_dict_to_set({1: 2, 2: 1}))
+ assert_edges_equal(nx.max_weight_matching(G, 1),
+ matching_dict_to_set({1: 3, 2: 4, 3: 1, 4: 2}))
def test_s_blossom(self):
"""Create S-blossom and use it for augmentation:"""
G = nx.Graph()
G.add_weighted_edges_from([(1, 2, 8), (1, 3, 9),
(2, 3, 10), (3, 4, 7)])
- assert_equal(nx.max_weight_matching(G),
- {1: 2, 2: 1, 3: 4, 4: 3})
+ assert_edges_equal(nx.max_weight_matching(G),
+ matching_dict_to_set({1: 2, 2: 1, 3: 4, 4: 3}))
G.add_weighted_edges_from([(1, 6, 5), (4, 5, 6)])
- assert_equal(nx.max_weight_matching(G),
- {1: 6, 2: 3, 3: 2, 4: 5, 5: 4, 6: 1})
+ assert_edges_equal(nx.max_weight_matching(G),
+ matching_dict_to_set({1: 6, 2: 3, 3: 2, 4: 5, 5: 4, 6: 1}))
def test_s_t_blossom(self):
"""Create S-blossom, relabel as T-blossom, use for augmentation:"""
G = nx.Graph()
G.add_weighted_edges_from([(1, 2, 9), (1, 3, 8), (2, 3, 10),
(1, 4, 5), (4, 5, 4), (1, 6, 3)])
- assert_equal(nx.max_weight_matching(G),
- {1: 6, 2: 3, 3: 2, 4: 5, 5: 4, 6: 1})
+ assert_edges_equal(nx.max_weight_matching(G),
+ matching_dict_to_set({1: 6, 2: 3, 3: 2, 4: 5, 5: 4, 6: 1}))
G.add_edge(4, 5, weight=3)
G.add_edge(1, 6, weight=4)
- assert_equal(nx.max_weight_matching(G),
- {1: 6, 2: 3, 3: 2, 4: 5, 5: 4, 6: 1})
+ assert_edges_equal(nx.max_weight_matching(G),
+ matching_dict_to_set({1: 6, 2: 3, 3: 2, 4: 5, 5: 4, 6: 1}))
G.remove_edge(1, 6)
G.add_edge(3, 6, weight=4)
- assert_equal(nx.max_weight_matching(G),
- {1: 2, 2: 1, 3: 6, 4: 5, 5: 4, 6: 3})
+ assert_edges_equal(nx.max_weight_matching(G),
+ matching_dict_to_set({1: 2, 2: 1, 3: 6, 4: 5, 5: 4, 6: 3}))
def test_nested_s_blossom(self):
"""Create nested S-blossom, use for augmentation:"""
@@ -117,7 +118,7 @@ class TestMaxWeightMatching(object):
(2, 4, 8), (3, 5, 8), (4, 5, 10),
(5, 6, 6)])
assert_equal(nx.max_weight_matching(G),
- {1: 3, 2: 4, 3: 1, 4: 2, 5: 6, 6: 5})
+ matching_dict_to_set({1: 3, 2: 4, 3: 1, 4: 2, 5: 6, 6: 5}))
def test_nested_s_blossom_relabel(self):
"""Create S-blossom, relabel as S, include in nested S-blossom:"""
@@ -125,8 +126,8 @@ class TestMaxWeightMatching(object):
G.add_weighted_edges_from([(1, 2, 10), (1, 7, 10), (2, 3, 12),
(3, 4, 20), (3, 5, 20), (4, 5, 25),
(5, 6, 10), (6, 7, 10), (7, 8, 8)])
- assert_equal(nx.max_weight_matching(G),
- {1: 2, 2: 1, 3: 4, 4: 3, 5: 6, 6: 5, 7: 8, 8: 7})
+ assert_edges_equal(nx.max_weight_matching(G),
+ matching_dict_to_set({1: 2, 2: 1, 3: 4, 4: 3, 5: 6, 6: 5, 7: 8, 8: 7}))
def test_nested_s_blossom_expand(self):
"""Create nested S-blossom, augment, expand recursively:"""
@@ -135,8 +136,8 @@ class TestMaxWeightMatching(object):
(2, 4, 12), (3, 5, 12), (4, 5, 14),
(4, 6, 12), (5, 7, 12), (6, 7, 14),
(7, 8, 12)])
- assert_equal(nx.max_weight_matching(G),
- {1: 2, 2: 1, 3: 5, 4: 6, 5: 3, 6: 4, 7: 8, 8: 7})
+ assert_edges_equal(nx.max_weight_matching(G),
+ matching_dict_to_set({1: 2, 2: 1, 3: 5, 4: 6, 5: 3, 6: 4, 7: 8, 8: 7}))
def test_s_blossom_relabel_expand(self):
"""Create S-blossom, relabel as T, expand:"""
@@ -144,8 +145,8 @@ class TestMaxWeightMatching(object):
G.add_weighted_edges_from([(1, 2, 23), (1, 5, 22), (1, 6, 15),
(2, 3, 25), (3, 4, 22), (4, 5, 25),
(4, 8, 14), (5, 7, 13)])
- assert_equal(nx.max_weight_matching(G),
- {1: 6, 2: 3, 3: 2, 4: 8, 5: 7, 6: 1, 7: 5, 8: 4})
+ assert_edges_equal(nx.max_weight_matching(G),
+ matching_dict_to_set({1: 6, 2: 3, 3: 2, 4: 8, 5: 7, 6: 1, 7: 5, 8: 4}))
def test_nested_s_blossom_relabel_expand(self):
"""Create nested S-blossom, relabel as T, expand:"""
@@ -153,8 +154,8 @@ class TestMaxWeightMatching(object):
G.add_weighted_edges_from([(1, 2, 19), (1, 3, 20), (1, 8, 8),
(2, 3, 25), (2, 4, 18), (3, 5, 18),
(4, 5, 13), (4, 7, 7), (5, 6, 7)])
- assert_equal(nx.max_weight_matching(G),
- {1: 8, 2: 3, 3: 2, 4: 7, 5: 6, 6: 5, 7: 4, 8: 1})
+ assert_edges_equal(nx.max_weight_matching(G),
+ matching_dict_to_set({1: 8, 2: 3, 3: 2, 4: 7, 5: 6, 6: 5, 7: 4, 8: 1}))
def test_nasty_blossom1(self):
"""Create blossom, relabel as T in more than one way, expand,
@@ -165,9 +166,9 @@ class TestMaxWeightMatching(object):
(3, 4, 45), (4, 5, 50), (1, 6, 30),
(3, 9, 35), (4, 8, 35), (5, 7, 26),
(9, 10, 5)])
- assert_equal(nx.max_weight_matching(G),
- {1: 6, 2: 3, 3: 2, 4: 8, 5: 7,
- 6: 1, 7: 5, 8: 4, 9: 10, 10: 9})
+ assert_edges_equal(nx.max_weight_matching(G),
+ matching_dict_to_set({1: 6, 2: 3, 3: 2, 4: 8, 5: 7,
+ 6: 1, 7: 5, 8: 4, 9: 10, 10: 9}))
def test_nasty_blossom2(self):
"""Again but slightly different:"""
@@ -176,9 +177,9 @@ class TestMaxWeightMatching(object):
(3, 4, 45), (4, 5, 50), (1, 6, 30),
(3, 9, 35), (4, 8, 26), (5, 7, 40),
(9, 10, 5)])
- assert_equal(nx.max_weight_matching(G),
- {1: 6, 2: 3, 3: 2, 4: 8, 5: 7,
- 6: 1, 7: 5, 8: 4, 9: 10, 10: 9})
+ assert_edges_equal(nx.max_weight_matching(G),
+ matching_dict_to_set({1: 6, 2: 3, 3: 2, 4: 8, 5: 7,
+ 6: 1, 7: 5, 8: 4, 9: 10, 10: 9}))
def test_nasty_blossom_least_slack(self):
"""Create blossom, relabel as T, expand such that a new
@@ -189,9 +190,9 @@ class TestMaxWeightMatching(object):
(3, 4, 45), (4, 5, 50), (1, 6, 30),
(3, 9, 35), (4, 8, 28), (5, 7, 26),
(9, 10, 5)])
- assert_equal(nx.max_weight_matching(G),
- {1: 6, 2: 3, 3: 2, 4: 8, 5: 7,
- 6: 1, 7: 5, 8: 4, 9: 10, 10: 9})
+ assert_edges_equal(nx.max_weight_matching(G),
+ matching_dict_to_set({1: 6, 2: 3, 3: 2, 4: 8, 5: 7,
+ 6: 1, 7: 5, 8: 4, 9: 10, 10: 9}))
def test_nasty_blossom_augmenting(self):
"""Create nested blossom, relabel as T in more than one way"""
@@ -203,9 +204,9 @@ class TestMaxWeightMatching(object):
(5, 6, 94), (6, 7, 50), (1, 8, 30),
(3, 11, 35), (5, 9, 36), (7, 10, 26),
(11, 12, 5)])
- assert_equal(nx.max_weight_matching(G),
- {1: 8, 2: 3, 3: 2, 4: 6, 5: 9, 6: 4,
- 7: 10, 8: 1, 9: 5, 10: 7, 11: 12, 12: 11})
+ assert_edges_equal(nx.max_weight_matching(G),
+ matching_dict_to_set({1: 8, 2: 3, 3: 2, 4: 6, 5: 9, 6: 4,
+ 7: 10, 8: 1, 9: 5, 10: 7, 11: 12, 12: 11}))
def test_nasty_blossom_expand_recursively(self):
"""Create nested S-blossom, relabel as S, expand recursively:"""
@@ -214,9 +215,9 @@ class TestMaxWeightMatching(object):
(2, 4, 55), (3, 5, 55), (4, 5, 50),
(1, 8, 15), (5, 7, 30), (7, 6, 10),
(8, 10, 10), (4, 9, 30)])
- assert_equal(nx.max_weight_matching(G),
- {1: 2, 2: 1, 3: 5, 4: 9, 5: 3,
- 6: 7, 7: 6, 8: 10, 9: 4, 10: 8})
+ assert_edges_equal(nx.max_weight_matching(G),
+ matching_dict_to_set({1: 2, 2: 1, 3: 5, 4: 9, 5: 3,
+ 6: 7, 7: 6, 8: 10, 9: 4, 10: 8}))
class TestIsMatching(object):
diff --git a/networkx/drawing/tests/test_agraph.py b/networkx/drawing/tests/test_agraph.py
index 46074d114..9d23a74ea 100644
--- a/networkx/drawing/tests/test_agraph.py
+++ b/networkx/drawing/tests/test_agraph.py
@@ -24,6 +24,7 @@ class TestAGraph(object):
G.graph['metal'] = 'bronze'
return G
+
def assert_equal(self, G1, G2):
assert_nodes_equal(G1.nodes(), G2.nodes())
assert_edges_equal(G1.edges(), G2.edges())
@@ -79,3 +80,21 @@ class TestAGraph(object):
G.add_edge(1, 2, weight=7)
G.add_edge(2, 3, weight=8)
nx.nx_agraph.view_pygraphviz(G, edgelabel='weight')
+
+ def test_from_agraph_name(self):
+ G = nx.Graph(name='test')
+ A = nx.nx_agraph.to_agraph(G)
+ H = nx.nx_agraph.from_agraph(A)
+ assert_equal(G.name, 'test')
+
+
+ def test_graph_with_reserved_keywords(self):
+ # test attribute/keyword clash case for #1582
+ # node: n
+ # edges: u,v
+ G = nx.Graph()
+ G = self.build_graph(G)
+ G.node['E']['n']='keyword'
+ G.edges[('A','B')]['u']='keyword'
+ G.edges[('A','B')]['v']='keyword'
+ A = nx.nx_agraph.to_agraph(G)
| {
"commit_name": "merge_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 1,
"test_score": 0
},
"num_modified_files": 4
} | 2.0 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"nose",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y libgdal-dev graphviz"
],
"python": "3.6",
"reqs_path": [
"requirements/default.txt",
"requirements/test.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs==22.2.0
certifi==2021.5.30
charset-normalizer==2.0.12
codecov==2.1.13
coverage==6.2
decorator==5.1.1
idna==3.10
importlib-metadata==4.8.3
iniconfig==1.1.1
-e git+https://github.com/networkx/networkx.git@18c2fa79edbd578bea3e7a1935502f54c58385d7#egg=networkx
nose==1.3.7
nose-ignore-docstring==0.2
packaging==21.3
pluggy==1.0.0
py==1.11.0
pyparsing==3.1.4
pytest==7.0.1
requests==2.27.1
tomli==1.2.3
typing_extensions==4.1.1
urllib3==1.26.20
zipp==3.6.0
| name: networkx
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- attrs==22.2.0
- charset-normalizer==2.0.12
- codecov==2.1.13
- coverage==6.2
- decorator==5.1.1
- idna==3.10
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- nose==1.3.7
- nose-ignore-docstring==0.2
- packaging==21.3
- pluggy==1.0.0
- py==1.11.0
- pyparsing==3.1.4
- pytest==7.0.1
- requests==2.27.1
- tomli==1.2.3
- typing-extensions==4.1.1
- urllib3==1.26.20
- zipp==3.6.0
prefix: /opt/conda/envs/networkx
| [
"networkx/algorithms/tests/test_covering.py::TestMinEdgeCover::test_graph_single_edge",
"networkx/algorithms/tests/test_covering.py::TestMinEdgeCover::test_complete_graph",
"networkx/algorithms/tests/test_matching.py::TestMaxWeightMatching::test_trivial1",
"networkx/algorithms/tests/test_matching.py::TestMaxWeightMatching::test_trivial2",
"networkx/algorithms/tests/test_matching.py::TestMaxWeightMatching::test_trivial3",
"networkx/algorithms/tests/test_matching.py::TestMaxWeightMatching::test_trivial4",
"networkx/algorithms/tests/test_matching.py::TestMaxWeightMatching::test_trivial5",
"networkx/algorithms/tests/test_matching.py::TestMaxWeightMatching::test_trivial6",
"networkx/algorithms/tests/test_matching.py::TestMaxWeightMatching::test_floating_point_weights",
"networkx/algorithms/tests/test_matching.py::TestMaxWeightMatching::test_negative_weights",
"networkx/algorithms/tests/test_matching.py::TestMaxWeightMatching::test_s_blossom",
"networkx/algorithms/tests/test_matching.py::TestMaxWeightMatching::test_s_t_blossom",
"networkx/algorithms/tests/test_matching.py::TestMaxWeightMatching::test_nested_s_blossom",
"networkx/algorithms/tests/test_matching.py::TestMaxWeightMatching::test_nested_s_blossom_relabel",
"networkx/algorithms/tests/test_matching.py::TestMaxWeightMatching::test_nested_s_blossom_expand",
"networkx/algorithms/tests/test_matching.py::TestMaxWeightMatching::test_s_blossom_relabel_expand",
"networkx/algorithms/tests/test_matching.py::TestMaxWeightMatching::test_nested_s_blossom_relabel_expand",
"networkx/algorithms/tests/test_matching.py::TestMaxWeightMatching::test_nasty_blossom1",
"networkx/algorithms/tests/test_matching.py::TestMaxWeightMatching::test_nasty_blossom2",
"networkx/algorithms/tests/test_matching.py::TestMaxWeightMatching::test_nasty_blossom_least_slack",
"networkx/algorithms/tests/test_matching.py::TestMaxWeightMatching::test_nasty_blossom_augmenting",
"networkx/algorithms/tests/test_matching.py::TestMaxWeightMatching::test_nasty_blossom_expand_recursively"
]
| [
"networkx/drawing/tests/test_agraph.py::TestAGraph::test_from_agraph_name",
"networkx/drawing/tests/test_agraph.py::TestAGraph::test_undirected",
"networkx/drawing/tests/test_agraph.py::TestAGraph::test_directed",
"networkx/drawing/tests/test_agraph.py::TestAGraph::test_multi_undirected",
"networkx/drawing/tests/test_agraph.py::TestAGraph::test_multi_directed",
"networkx/drawing/tests/test_agraph.py::TestAGraph::test_view_pygraphviz",
"networkx/drawing/tests/test_agraph.py::TestAGraph::test_view_pygraphviz_edgelable",
"networkx/drawing/tests/test_agraph.py::TestAGraph::test_graph_with_reserved_keywords"
]
| [
"networkx/algorithms/tests/test_covering.py::TestMinEdgeCover::test_empty_graph",
"networkx/algorithms/tests/test_covering.py::TestMinEdgeCover::test_graph_with_loop",
"networkx/algorithms/tests/test_covering.py::TestMinEdgeCover::test_bipartite_explicit",
"networkx/algorithms/tests/test_covering.py::TestIsEdgeCover::test_empty_graph",
"networkx/algorithms/tests/test_covering.py::TestIsEdgeCover::test_graph_with_loop",
"networkx/algorithms/tests/test_covering.py::TestIsEdgeCover::test_graph_single_edge",
"networkx/algorithms/tests/test_matching.py::TestIsMatching::test_dict",
"networkx/algorithms/tests/test_matching.py::TestIsMatching::test_empty_matching",
"networkx/algorithms/tests/test_matching.py::TestIsMatching::test_single_edge",
"networkx/algorithms/tests/test_matching.py::TestIsMatching::test_edge_order",
"networkx/algorithms/tests/test_matching.py::TestIsMatching::test_valid",
"networkx/algorithms/tests/test_matching.py::TestIsMatching::test_invalid",
"networkx/algorithms/tests/test_matching.py::TestIsMaximalMatching::test_dict",
"networkx/algorithms/tests/test_matching.py::TestIsMaximalMatching::test_valid",
"networkx/algorithms/tests/test_matching.py::TestIsMaximalMatching::test_not_matching",
"networkx/algorithms/tests/test_matching.py::TestIsMaximalMatching::test_not_maximal",
"networkx/algorithms/tests/test_matching.py::TestMaximalMatching::test_valid_matching",
"networkx/algorithms/tests/test_matching.py::TestMaximalMatching::test_single_edge_matching",
"networkx/algorithms/tests/test_matching.py::TestMaximalMatching::test_self_loops",
"networkx/algorithms/tests/test_matching.py::TestMaximalMatching::test_ordering"
]
| []
| BSD 3-Clause | 1,916 | [
"networkx/drawing/nx_agraph.py",
"networkx/drawing/layout.py",
"networkx/algorithms/matching.py",
"networkx/algorithms/covering.py"
]
| [
"networkx/drawing/nx_agraph.py",
"networkx/drawing/layout.py",
"networkx/algorithms/matching.py",
"networkx/algorithms/covering.py"
]
|
|
Clinical-Genomics__scout-676 | 96e4730530858967fd3b1542c79cc5a7f77ece12 | 2017-11-27 08:03:26 | 81909cf2520a9f33b4cd6196706206c652277260 | diff --git a/scout/adapter/mongo/query.py b/scout/adapter/mongo/query.py
index 3ec4fe991..914733acc 100644
--- a/scout/adapter/mongo/query.py
+++ b/scout/adapter/mongo/query.py
@@ -12,6 +12,7 @@ class QueryHandler(object):
'genetic_models': list,
'thousand_genomes_frequency': float,
'exac_frequency': float,
+ 'clingen_ngi': int,
'cadd_score': float,
'cadd_inclusive": boolean,
'genetic_models': list(str),
@@ -24,6 +25,7 @@ class QueryHandler(object):
'chrom': str,
'start': int,
'end': int,
+ 'svtype': list,
'gene_panels': list(str),
}
@@ -144,6 +146,14 @@ class QueryHandler(object):
]
})
+ if query.get('clingen_ngi') is not None:
+ mongo_query_minor.append({
+ '$or': [
+ {'clingen_ngi': {'$exists': False}},
+ {'clingen_ngi': {'$lt': query['clingen_ngi'] + 1}},
+ ]
+ })
+
if query.get('cadd_score') is not None:
cadd = query['cadd_score']
cadd_query = {'cadd_score': {'$gt': float(cadd)}}
diff --git a/scout/server/blueprints/variants/forms.py b/scout/server/blueprints/variants/forms.py
index bab4716d7..407cbe9d7 100644
--- a/scout/server/blueprints/variants/forms.py
+++ b/scout/server/blueprints/variants/forms.py
@@ -90,3 +90,4 @@ class SvFiltersForm(FlaskForm):
svtype = SelectMultipleField('SVType', choices=SV_TYPE_CHOICES)
thousand_genomes_frequency = BetterDecimalField('1000 Genomes', places=2)
+ clingen_ngi = IntegerField('ClinGen NGI obs')
diff --git a/scout/server/blueprints/variants/templates/variants/sv-variant.html b/scout/server/blueprints/variants/templates/variants/sv-variant.html
index e4e54740a..249c9cb4b 100644
--- a/scout/server/blueprints/variants/templates/variants/sv-variant.html
+++ b/scout/server/blueprints/variants/templates/variants/sv-variant.html
@@ -93,8 +93,11 @@
Position
<div class="pull-right">
<a class="md-label" href="{{ url_for('pileup.viewer', bam=case.bam_files, bai=case.bai_files, sample=case.sample_names, contig=variant.chromosome, start=(variant.position - 50), stop=(variant.end + 50), vcf=case.vcf_files.vcf_sv) }}" target="_blank">
- Alignment: {{ variant.chromosome }}:{{ variant.position }}-{{ variant.end }}
- </a>
+ Alignment: {{ variant.chromosome }}
+ </a>:
+ <a class="md-label" href="{{ url_for('pileup.viewer', bam=case.bam_files, bai=case.bai_files, sample=case.sample_names, contig=variant.chromosome, start=(variant.position - 500), stop=(variant.position + 500), vcf=case.vcf_files.vcf_sv) }}" target="_blank">
+{{ variant.position }}</a> -
+ <a class="md-label" href="{{ url_for('pileup.viewer', bam=case.bam_files, bai=case.bai_files, sample=case.sample_names, contig=variant.chromosome, start=(variant.end - 500), stop=(variant.end + 500), vcf=case.vcf_files.vcf_sv) }}" target="_blank">{{ variant.end }}</a>
</div>
</li>
<li class="list-group-item">
diff --git a/scout/server/blueprints/variants/templates/variants/sv-variants.html b/scout/server/blueprints/variants/templates/variants/sv-variants.html
index 4a20b3618..5c4674b10 100644
--- a/scout/server/blueprints/variants/templates/variants/sv-variants.html
+++ b/scout/server/blueprints/variants/templates/variants/sv-variants.html
@@ -152,6 +152,8 @@
{{ form.thousand_genomes_frequency(class="form-control") }}
</div>
<div class="col-xs-3">
+ {{ form.clingen_ngi.label(class="control-label") }}
+ {{ form.clingen_ngi(class="form-control") }}
</div>
<div class="col-xs-3">
{{ form.svtype.label(class="control-label") }}
@@ -177,6 +179,7 @@
functional_annotations=severe_so_terms,
region_annotations=['exonic', 'splicing'],
thousand_genomes_frequency=institute.frequency_cutoff,
+ clingen_ngi=15,
size=100,
gene_panels=form.data.get('gene_panels')) }}"
class="btn btn-default form-control">
@@ -258,7 +261,11 @@
<div>{{ annotation }}</div>
{% endfor %}
</td>
- <td>{{ variant.thousand_genomes_frequency|human_decimal if variant.thousand_genomes_frequency }}</td>
+ <td>
+ {% if variant.thousand_genomes_frequency %}
+ {{ variant.thousand_genomes_frequency|human_decimal }}
+ {% endif %}
+ </td>
<td>
<div class="flex">
<div>
| SV frequency filter
- [x] add filter boxes for filter frequencies of interest (e.g. ClinGen NGI, array, SweGen)
- [x] clinical filter settings update for structural variants
- [x] clickable coordinates for start end of structural variant to enable view the edges of large variants
| Clinical-Genomics/scout | diff --git a/tests/adapter/test_query.py b/tests/adapter/test_query.py
index d6c424276..bad5131af 100644
--- a/tests/adapter/test_query.py
+++ b/tests/adapter/test_query.py
@@ -195,6 +195,22 @@ def test_build_chrom(adapter):
assert mongo_query['chromosome'] == chrom
+
+def test_build_ngi_sv(adapter):
+ case_id = 'cust000'
+ count = 1
+ query = {'clingen_ngi': count}
+
+ mongo_query = adapter.build_query(case_id, query=query)
+ assert mongo_query['$and'] == [
+ {
+ '$or':[
+ {'clingen_ngi': {'$exists': False}},
+ {'clingen_ngi': {'$lt': query['clingen_ngi'] + 1}}
+ ]
+ }
+ ]
+
def test_build_range(adapter):
case_id = 'cust000'
chrom = '1'
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 1,
"test_score": 2
},
"num_modified_files": 4
} | 3.5 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest"
],
"pre_install": null,
"python": "3.9",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | babel==2.17.0
blinker==1.9.0
cachelib==0.13.0
certifi==2025.1.31
charset-normalizer==3.4.1
click==8.1.8
coloredlogs==15.0.1
Cython==3.0.12
cyvcf2==0.31.1
dnspython==2.7.0
dominate==2.9.1
exceptiongroup==1.2.2
Flask==3.1.0
flask-babel==4.0.0
Flask-Bootstrap==3.3.7.1
Flask-DebugToolbar==0.16.0
Flask-Login==0.6.3
Flask-Mail==0.10.0
Flask-Markdown==0.3
Flask-OAuthlib==0.9.6
Flask-PyMongo==3.0.1
Flask-WTF==1.2.2
humanfriendly==10.0
idna==3.10
importlib_metadata==8.6.1
iniconfig==2.1.0
intervaltree==3.1.0
itsdangerous==2.2.0
Jinja2==3.1.6
livereload==2.7.1
loqusdb==2.6.0
Markdown==3.7
MarkupSafe==3.0.2
mongo-adapter==0.3.3
mongomock==4.3.0
numpy==2.0.2
oauthlib==2.1.0
packaging==24.2
path==17.1.0
path.py==12.5.0
ped-parser==1.6.6
pluggy==1.5.0
pymongo==4.11.3
pytest==8.3.5
python-dateutil==2.9.0.post0
pytz==2025.2
PyYAML==6.0.2
query-phenomizer==1.2.1
requests==2.32.3
requests-oauthlib==1.1.0
-e git+https://github.com/Clinical-Genomics/scout.git@96e4730530858967fd3b1542c79cc5a7f77ece12#egg=scout_browser
sentinels==1.0.0
six==1.17.0
sortedcontainers==2.4.0
tomli==2.2.1
tornado==6.4.2
urllib3==2.3.0
vcftoolbox==1.5.1
visitor==0.1.3
Werkzeug==3.1.3
WTForms==3.2.1
zipp==3.21.0
| name: scout
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- babel==2.17.0
- blinker==1.9.0
- cachelib==0.13.0
- certifi==2025.1.31
- charset-normalizer==3.4.1
- click==8.1.8
- coloredlogs==15.0.1
- cython==3.0.12
- cyvcf2==0.31.1
- dnspython==2.7.0
- dominate==2.9.1
- exceptiongroup==1.2.2
- flask==3.1.0
- flask-babel==4.0.0
- flask-bootstrap==3.3.7.1
- flask-debugtoolbar==0.16.0
- flask-login==0.6.3
- flask-mail==0.10.0
- flask-markdown==0.3
- flask-oauthlib==0.9.6
- flask-pymongo==3.0.1
- flask-wtf==1.2.2
- humanfriendly==10.0
- idna==3.10
- importlib-metadata==8.6.1
- iniconfig==2.1.0
- intervaltree==3.1.0
- itsdangerous==2.2.0
- jinja2==3.1.6
- livereload==2.7.1
- loqusdb==2.6.0
- markdown==3.7
- markupsafe==3.0.2
- mongo-adapter==0.3.3
- mongomock==4.3.0
- numpy==2.0.2
- oauthlib==2.1.0
- packaging==24.2
- path==17.1.0
- path-py==12.5.0
- ped-parser==1.6.6
- pluggy==1.5.0
- pymongo==4.11.3
- pytest==8.3.5
- python-dateutil==2.9.0.post0
- pytz==2025.2
- pyyaml==6.0.2
- query-phenomizer==1.2.1
- requests==2.32.3
- requests-oauthlib==1.1.0
- sentinels==1.0.0
- six==1.17.0
- sortedcontainers==2.4.0
- tomli==2.2.1
- tornado==6.4.2
- urllib3==2.3.0
- vcftoolbox==1.5.1
- visitor==0.1.3
- werkzeug==3.1.3
- wtforms==3.2.1
- zipp==3.21.0
prefix: /opt/conda/envs/scout
| [
"tests/adapter/test_query.py::test_build_ngi_sv"
]
| []
| [
"tests/adapter/test_query.py::test_build_query",
"tests/adapter/test_query.py::test_build_thousand_g_query",
"tests/adapter/test_query.py::test_build_non_existing_thousand_g",
"tests/adapter/test_query.py::test_build_cadd_exclusive",
"tests/adapter/test_query.py::test_build_cadd_inclusive",
"tests/adapter/test_query.py::test_build_thousand_g_and_cadd",
"tests/adapter/test_query.py::test_build_clinsig",
"tests/adapter/test_query.py::test_build_clinsig_filter",
"tests/adapter/test_query.py::test_build_clinsig_always",
"tests/adapter/test_query.py::test_build_clinsig_always_only",
"tests/adapter/test_query.py::test_build_chrom",
"tests/adapter/test_query.py::test_build_range"
]
| []
| BSD 3-Clause "New" or "Revised" License | 1,917 | [
"scout/adapter/mongo/query.py",
"scout/server/blueprints/variants/templates/variants/sv-variant.html",
"scout/server/blueprints/variants/forms.py",
"scout/server/blueprints/variants/templates/variants/sv-variants.html"
]
| [
"scout/adapter/mongo/query.py",
"scout/server/blueprints/variants/templates/variants/sv-variant.html",
"scout/server/blueprints/variants/forms.py",
"scout/server/blueprints/variants/templates/variants/sv-variants.html"
]
|
|
lbl-srg__BuildingsPy-181 | ad2f3e7ffb0a01117e5f09ac498a87b5c02ca158 | 2017-11-27 20:38:23 | 923b1087e255f7f35224aa7c1653abf9c038f849 | diff --git a/buildingspy/development/error_dictionary.py b/buildingspy/development/error_dictionary.py
index 2304f63..4a3c8d3 100644
--- a/buildingspy/development/error_dictionary.py
+++ b/buildingspy/development/error_dictionary.py
@@ -138,6 +138,13 @@ class ErrorDictionary(object):
'model_message': "\"inner Modelica.StateGraph.StateGraphRoot\" is missing in '{}'.\n",
'summary_message': "Number of models with missing StateGraphRoot : {}\n"}
+ self._error_dict["mismatched displayUnits"] = {
+ 'tool_message': "Mismatched displayUnit",
+ 'counter': 0,
+ 'buildingspy_var': "iMisDisUni",
+ 'model_message': "\"Mismatched displayUnit in '{}'.\n",
+ 'summary_message': "Number of models with mismatched displayUnit : {}\n"}
+
def get_dictionary(self):
""" Return the dictionary with all error data
"""
diff --git a/buildingspy/development/refactor.py b/buildingspy/development/refactor.py
index ba4d363..2c064b0 100644
--- a/buildingspy/development/refactor.py
+++ b/buildingspy/development/refactor.py
@@ -637,6 +637,10 @@ def move_class(source, target):
"""
##############################################################
+ # First, remove empty subdirectories
+ _remove_empty_folders(source.replace(".", os.path.sep),
+ removeRoot=False)
+ ##############################################################
# Check if it is a directory with a package.mo file
if os.path.isdir(source.replace(".", os.path.sep)):
_move_class_directory(source, target)
@@ -665,6 +669,26 @@ def move_class(source, target):
_update_all_references(source, target)
+def _remove_empty_folders(path, removeRoot=True):
+ ''' Remove empty directories
+ '''
+ if not os.path.isdir(path):
+ return
+
+ # remove empty subfolders
+ files = os.listdir(path)
+ if len(files):
+ for f in files:
+ fullpath = os.path.join(path, f)
+ if os.path.isdir(fullpath):
+ _remove_empty_folders(fullpath)
+
+ # if folder empty, delete it
+ files = os.listdir(path)
+ if len(files) == 0 and removeRoot:
+ os.rmdir(path)
+
+
def _update_all_references(source, target):
""" Updates all references in `.mo` and `.mos` files.
| add test for Mismatched displayUnit
Add a test for `Mismatched displayUnit` to the regression testing | lbl-srg/BuildingsPy | diff --git a/buildingspy/tests/test_development_error_dictionary.py b/buildingspy/tests/test_development_error_dictionary.py
index 393e2cc..ee9d12b 100644
--- a/buildingspy/tests/test_development_error_dictionary.py
+++ b/buildingspy/tests/test_development_error_dictionary.py
@@ -39,7 +39,8 @@ class Test_development_error_dictionary(unittest.TestCase):
'type inconsistent definition equations',
'unspecified initial conditions',
'unused connector',
- 'stateGraphRoot missing'])
+ 'stateGraphRoot missing',
+ 'mismatched displayUnits'])
self.assertEqual(len(k), len(k_expected), "Wrong number of keys.")
for i in range(len(k)):
@@ -63,7 +64,8 @@ class Test_development_error_dictionary(unittest.TestCase):
'Type inconsistent definition equation',
'Dymola has selected default initial condition',
'Warning: The following connector variables are not used in the model',
- "A \\\"stateGraphRoot\\\" component was automatically introduced."])
+ "A \\\"stateGraphRoot\\\" component was automatically introduced.",
+ "Mismatched displayUnit"])
self.assertEqual(len(k), len(k_expected), "Wrong number of tool messages.")
for i in range(len(k)):
| {
"commit_name": "merge_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 2,
"test_score": 0
},
"num_modified_files": 2
} | 1.6 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"pytidylib",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y tidy"
],
"python": "3.6",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work
-e git+https://github.com/lbl-srg/BuildingsPy.git@ad2f3e7ffb0a01117e5f09ac498a87b5c02ca158#egg=buildingspy
certifi==2021.5.30
future==1.0.0
gitdb==4.0.9
GitPython==3.1.18
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
Jinja2==3.0.3
MarkupSafe==2.0.1
more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work
packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work
pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pytest==6.2.4
pytidylib==0.3.2
smmap==5.0.0
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
| name: BuildingsPy
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=21.4.0=pyhd3eb1b0_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- importlib-metadata=4.8.1=py36h06a4308_0
- importlib_metadata=4.8.1=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- more-itertools=8.12.0=pyhd3eb1b0_0
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=21.3=pyhd3eb1b0_0
- pip=21.2.2=py36h06a4308_0
- pluggy=0.13.1=py36h06a4308_0
- py=1.11.0=pyhd3eb1b0_0
- pyparsing=3.0.4=pyhd3eb1b0_0
- pytest=6.2.4=py36h06a4308_2
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- toml=0.10.2=pyhd3eb1b0_0
- typing_extensions=4.1.1=pyh06a4308_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zipp=3.6.0=pyhd3eb1b0_0
- zlib=1.2.13=h5eee18b_1
- pip:
- future==1.0.0
- gitdb==4.0.9
- gitpython==3.1.18
- jinja2==3.0.3
- markupsafe==2.0.1
- pytidylib==0.3.2
- smmap==5.0.0
prefix: /opt/conda/envs/BuildingsPy
| [
"buildingspy/tests/test_development_error_dictionary.py::Test_development_error_dictionary::test_keys",
"buildingspy/tests/test_development_error_dictionary.py::Test_development_error_dictionary::test_tool_messages"
]
| []
| []
| []
| null | 1,918 | [
"buildingspy/development/error_dictionary.py",
"buildingspy/development/refactor.py"
]
| [
"buildingspy/development/error_dictionary.py",
"buildingspy/development/refactor.py"
]
|
|
jupyterhub__kubespawner-105 | 054f6d61cb23232983ca3db74177b2732f15de14 | 2017-11-27 21:58:36 | 054f6d61cb23232983ca3db74177b2732f15de14 | diff --git a/kubespawner/objects.py b/kubespawner/objects.py
index e2632b7..29ca165 100644
--- a/kubespawner/objects.py
+++ b/kubespawner/objects.py
@@ -36,12 +36,11 @@ def make_pod(
volumes=[],
volume_mounts=[],
labels={},
+ annotations={},
cpu_limit=None,
cpu_guarantee=None,
mem_limit=None,
mem_guarantee=None,
- extra_resource_limits=None,
- extra_resource_guarantees=None,
lifecycle_hooks=None,
init_containers=None,
service_account=None,
@@ -97,6 +96,8 @@ def make_pod(
String specifying the working directory for the notebook container
- labels:
Labels to add to the spawned pod.
+ - annotations:
+ Annotations to add to the spawned pod.
- cpu_limit:
Float specifying the max number of CPU cores the user's pod is
allowed to use.
@@ -131,6 +132,8 @@ def make_pod(
pod.metadata = V1ObjectMeta()
pod.metadata.name = name
pod.metadata.labels = labels.copy()
+ if annotations:
+ pod.metadata.annotations = annotations.copy()
pod.spec = V1PodSpec()
@@ -199,19 +202,12 @@ def make_pod(
notebook_container.resources.requests['cpu'] = cpu_guarantee
if mem_guarantee:
notebook_container.resources.requests['memory'] = mem_guarantee
- if extra_resource_guarantees:
- for k in extra_resource_guarantees:
- notebook_container.resources.requests[k] = extra_resource_guarantees[k]
notebook_container.resources.limits = {}
if cpu_limit:
notebook_container.resources.limits['cpu'] = cpu_limit
if mem_limit:
notebook_container.resources.limits['memory'] = mem_limit
- if extra_resource_limits:
- for k in extra_resource_limits:
- notebook_container.resources.limits[k] = extra_resource_limits[k]
-
notebook_container.volume_mounts = volume_mounts + hack_volume_mounts
pod.spec.containers.append(notebook_container)
diff --git a/kubespawner/spawner.py b/kubespawner/spawner.py
index c2bffd9..ca13bab 100644
--- a/kubespawner/spawner.py
+++ b/kubespawner/spawner.py
@@ -279,6 +279,23 @@ class KubeSpawner(Spawner):
"""
)
+ singleuser_extra_annotations = Dict(
+ {},
+ config=True,
+ help="""
+ Extra kubernetes annotations to set on the spawned single-user pods.
+
+ The keys and values specified here are added as annotations on the spawned single-user
+ kubernetes pods. The keys and values must both be strings.
+
+ See https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations/ for more
+ info on what annotations are and why you might want to use them!
+
+ {username} and {userid} are expanded to the escaped, dns-label safe
+ username & integer user id respectively, wherever they are used.
+ """
+ )
+
singleuser_image_spec = Unicode(
'jupyterhub/singleuser:latest',
config=True,
@@ -668,28 +685,6 @@ class KubeSpawner(Spawner):
"""
)
- extra_resource_guarantees = Dict(
- {},
- config=True,
- help="""
- The dictionary used to request arbitrary resources.
- Default is None and means no additional resources are requested.
- For example, to request 3 Nvidia GPUs
- `{"nvidia.com/gpu": "3"}`
- """
- )
-
- extra_resource_limits = Dict(
- {},
- config=True,
- help="""
- The dictionary used to limit arbitrary resources.
- Default is None and means no additional resources are limited.
- For example, to add a limit of 3 Nvidia GPUs
- `{"nvidia.com/gpu": "3"}`
- """
- )
-
def _expand_user_properties(self, template):
# Make sure username and servername match the restrictions for DNS labels
safe_chars = set(string.ascii_lowercase + string.digits)
@@ -764,6 +759,7 @@ class KubeSpawner(Spawner):
real_cmd = None
labels = self._build_pod_labels(self._expand_all(self.singleuser_extra_labels))
+ annotations = self._expand_all(self.singleuser_extra_annotations)
return make_pod(
name=self.pod_name,
@@ -781,12 +777,11 @@ class KubeSpawner(Spawner):
volume_mounts=self._expand_all(self.volume_mounts),
working_dir=self.singleuser_working_dir,
labels=labels,
+ annotations=annotations,
cpu_limit=self.cpu_limit,
cpu_guarantee=self.cpu_guarantee,
mem_limit=self.mem_limit,
mem_guarantee=self.mem_guarantee,
- extra_resource_limits=self.extra_resource_limits,
- extra_resource_guarantees=self.extra_resource_guarantees,
lifecycle_hooks=self.singleuser_lifecycle_hooks,
init_containers=self.singleuser_init_containers,
service_account=self.singleuser_service_account,
| Add configuration for annotations on spawned singleuser pods
The spawner supports [configuring extra labels on spawned pods](https://github.com/jupyterhub/kubespawner/blob/06a2e09bc05e873a3e9e8b29d60beceb193fb2b7/kubespawner/spawner.py#L264-L280).
It should also support configuring extra annotations on spawned pods. | jupyterhub/kubespawner | diff --git a/tests/test_objects.py b/tests/test_objects.py
index cc0bde8..5369fb0 100644
--- a/tests/test_objects.py
+++ b/tests/test_objects.py
@@ -90,6 +90,49 @@ def test_make_labeled_pod():
"apiVersion": "v1"
}
+def test_make_annotated_pod():
+ """
+ Test specification of the simplest possible pod specification with annotations
+ """
+ assert api_client.sanitize_for_serialization(make_pod(
+ name='test',
+ image_spec='jupyter/singleuser:latest',
+ cmd=['jupyterhub-singleuser'],
+ port=8888,
+ image_pull_policy='IfNotPresent',
+ annotations={"test": "true"}
+ )) == {
+ "metadata": {
+ "name": "test",
+ "annotations": {"test": "true"},
+ "labels": {},
+ },
+ "spec": {
+ "securityContext": {},
+ "containers": [
+ {
+ "env": [],
+ "name": "notebook",
+ "image": "jupyter/singleuser:latest",
+ "imagePullPolicy": "IfNotPresent",
+ "args": ["jupyterhub-singleuser"],
+ "ports": [{
+ "name": "notebook-port",
+ "containerPort": 8888
+ }],
+ 'volumeMounts': [{'name': 'no-api-access-please', 'mountPath': '/var/run/secrets/kubernetes.io/serviceaccount', 'readOnly': True}],
+ "resources": {
+ "limits": {},
+ "requests": {}
+ }
+ }
+ ],
+ 'volumes': [{'name': 'no-api-access-please', 'emptyDir': {}}],
+ },
+ "kind": "Pod",
+ "apiVersion": "v1"
+ }
+
def test_make_pod_with_image_pull_secrets():
"""
Test specification of the simplest possible pod specification
@@ -631,65 +674,6 @@ def test_make_pod_with_extra_containers():
"apiVersion": "v1"
}
-def test_make_pod_with_extra_resources():
- """
- Test specification of extra resources (like GPUs)
- """
- assert api_client.sanitize_for_serialization(make_pod(
- name='test',
- image_spec='jupyter/singleuser:latest',
- cpu_limit=2,
- cpu_guarantee=1,
- extra_resource_limits={"nvidia.com/gpu": "5", "k8s.io/new-resource": "1"},
- extra_resource_guarantees={"nvidia.com/gpu": "3"},
- cmd=['jupyterhub-singleuser'],
- port=8888,
- mem_limit='1Gi',
- mem_guarantee='512Mi',
- image_pull_policy='IfNotPresent',
- image_pull_secret="myregistrykey",
- node_selector={"disk": "ssd"}
- )) == {
- "metadata": {
- "name": "test",
- "labels": {},
- },
- "spec": {
- "securityContext": {},
- "imagePullSecrets": [{"name": "myregistrykey"}],
- "nodeSelector": {"disk": "ssd"},
- "containers": [
- {
- "env": [],
- "name": "notebook",
- "image": "jupyter/singleuser:latest",
- "imagePullPolicy": "IfNotPresent",
- "args": ["jupyterhub-singleuser"],
- "ports": [{
- "name": "notebook-port",
- "containerPort": 8888
- }],
- 'volumeMounts': [{'name': 'no-api-access-please', 'mountPath': '/var/run/secrets/kubernetes.io/serviceaccount', 'readOnly': True}],
- "resources": {
- "limits": {
- "cpu": 2,
- "memory": '1Gi',
- "nvidia.com/gpu": "5",
- "k8s.io/new-resource": "1"
- },
- "requests": {
- "cpu": 1,
- "memory": '512Mi',
- "nvidia.com/gpu": "3"
- }
- }
- }
- ],
- 'volumes': [{'name': 'no-api-access-please', 'emptyDir': {}}],
- },
- "kind": "Pod",
- "apiVersion": "v1"
- }
def test_make_pvc_simple():
"""
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 2,
"test_score": 2
},
"num_modified_files": 2
} | 0.6 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.6",
"reqs_path": [
"requirements/base.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | alembic==1.7.7
async-generator==1.10
attrs==22.2.0
cachetools==4.2.4
certifi==2021.5.30
certipy==0.1.3
cffi==1.15.1
charset-normalizer==2.0.12
cryptography==40.0.2
decorator==5.1.1
entrypoints==0.4
escapism==1.0.1
google-auth==2.22.0
greenlet==2.0.2
idna==3.10
importlib-metadata==4.8.3
importlib-resources==5.4.0
iniconfig==1.1.1
ipaddress==1.0.23
ipython-genutils==0.2.0
Jinja2==3.0.3
jsonschema==3.2.0
jupyter-telemetry==0.1.0
jupyterhub==2.3.1
-e git+https://github.com/jupyterhub/kubespawner.git@054f6d61cb23232983ca3db74177b2732f15de14#egg=jupyterhub_kubespawner
kubernetes==3.0.0
Mako==1.1.6
MarkupSafe==2.0.1
oauthlib==3.2.2
packaging==21.3
pamela==1.2.0
pluggy==1.0.0
prometheus-client==0.17.1
py==1.11.0
pyasn1==0.5.1
pyasn1-modules==0.3.0
pycparser==2.21
pyOpenSSL==23.2.0
pyparsing==3.1.4
pyrsistent==0.18.0
pytest==7.0.1
python-dateutil==2.9.0.post0
python-json-logger==2.0.7
PyYAML==6.0.1
requests==2.27.1
rsa==4.9
ruamel.yaml==0.18.3
ruamel.yaml.clib==0.2.8
six==1.17.0
SQLAlchemy==1.4.54
tomli==1.2.3
tornado==6.1
traitlets==4.3.3
typing_extensions==4.1.1
urllib3==1.26.20
websocket-client==0.40.0
zipp==3.6.0
| name: kubespawner
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- alembic==1.7.7
- async-generator==1.10
- attrs==22.2.0
- cachetools==4.2.4
- certipy==0.1.3
- cffi==1.15.1
- charset-normalizer==2.0.12
- cryptography==40.0.2
- decorator==5.1.1
- entrypoints==0.4
- escapism==1.0.1
- google-auth==2.22.0
- greenlet==2.0.2
- idna==3.10
- importlib-metadata==4.8.3
- importlib-resources==5.4.0
- iniconfig==1.1.1
- ipaddress==1.0.23
- ipython-genutils==0.2.0
- jinja2==3.0.3
- jsonschema==3.2.0
- jupyter-telemetry==0.1.0
- jupyterhub==2.3.1
- kubernetes==3.0.0
- mako==1.1.6
- markupsafe==2.0.1
- oauthlib==3.2.2
- packaging==21.3
- pamela==1.2.0
- pluggy==1.0.0
- prometheus-client==0.17.1
- py==1.11.0
- pyasn1==0.5.1
- pyasn1-modules==0.3.0
- pycparser==2.21
- pyopenssl==23.2.0
- pyparsing==3.1.4
- pyrsistent==0.18.0
- pytest==7.0.1
- python-dateutil==2.9.0.post0
- python-json-logger==2.0.7
- pyyaml==6.0.1
- requests==2.27.1
- rsa==4.9
- ruamel-yaml==0.18.3
- ruamel-yaml-clib==0.2.8
- six==1.17.0
- sqlalchemy==1.4.54
- tomli==1.2.3
- tornado==6.1
- traitlets==4.3.3
- typing-extensions==4.1.1
- urllib3==1.26.20
- websocket-client==0.40.0
- zipp==3.6.0
prefix: /opt/conda/envs/kubespawner
| [
"tests/test_objects.py::test_make_annotated_pod"
]
| []
| [
"tests/test_objects.py::test_make_simplest_pod",
"tests/test_objects.py::test_make_labeled_pod",
"tests/test_objects.py::test_make_pod_with_image_pull_secrets",
"tests/test_objects.py::test_set_pod_uid_fs_gid",
"tests/test_objects.py::test_run_privileged_container",
"tests/test_objects.py::test_make_pod_resources_all",
"tests/test_objects.py::test_make_pod_with_env",
"tests/test_objects.py::test_make_pod_with_lifecycle",
"tests/test_objects.py::test_make_pod_with_init_containers",
"tests/test_objects.py::test_make_pod_with_extra_container_config",
"tests/test_objects.py::test_make_pod_with_extra_pod_config",
"tests/test_objects.py::test_make_pod_with_extra_containers",
"tests/test_objects.py::test_make_pvc_simple",
"tests/test_objects.py::test_make_resources_all"
]
| []
| BSD 3-Clause "New" or "Revised" License | 1,919 | [
"kubespawner/objects.py",
"kubespawner/spawner.py"
]
| [
"kubespawner/objects.py",
"kubespawner/spawner.py"
]
|
|
Azure__WALinuxAgent-951 | ab261b5f2ed0dfce4dd94adf924e68e0aaff5e7b | 2017-11-28 01:19:07 | 6e9b985c1d7d564253a1c344bab01b45093103cd | boumenot: Let me know if this is the style of unit test you were thinking of. | diff --git a/azurelinuxagent/agent.py b/azurelinuxagent/agent.py
index e99f7bed..87ab3c14 100644
--- a/azurelinuxagent/agent.py
+++ b/azurelinuxagent/agent.py
@@ -144,7 +144,7 @@ def main(args=[]):
if command == "version":
version()
elif command == "help":
- usage()
+ print(usage())
elif command == "start":
start(conf_file_path=conf_file_path)
else:
@@ -228,15 +228,16 @@ def version():
def usage():
"""
- Show agent usage
+ Return agent usage message
"""
- print("")
- print((("usage: {0} [-verbose] [-force] [-help] "
+ s = "\n"
+ s += ("usage: {0} [-verbose] [-force] [-help] "
"-configuration-path:<path to configuration file>"
"-deprovision[+user]|-register-service|-version|-daemon|-start|"
- "-run-exthandlers]"
- "").format(sys.argv[0])))
- print("")
+ "-run-exthandlers|-show-configuration]"
+ "").format(sys.argv[0])
+ s += "\n"
+ return s
def start(conf_file_path=None):
"""
| WALA usage prompt lacks of " waagent -show-configuration"
We can perform "waagent -show-configuration" to get current WALA configuration,but "waagent -help"lacks of this usage prompt. | Azure/WALinuxAgent | diff --git a/tests/test_agent.py b/tests/test_agent.py
index 51b157dd..95994dba 100644
--- a/tests/test_agent.py
+++ b/tests/test_agent.py
@@ -15,9 +15,7 @@
# Requires Python 2.4+ and Openssl 1.0+
#
-import mock
import os.path
-import sys
from azurelinuxagent.agent import *
from azurelinuxagent.common.conf import *
@@ -168,3 +166,22 @@ class TestAgent(AgentTestCase):
for k in sorted(configuration.keys()):
actual_configuration.append("{0} = {1}".format(k, configuration[k]))
self.assertEqual(EXPECTED_CONFIGURATION, actual_configuration)
+
+ def test_agent_usage_message(self):
+ message = usage()
+
+ # Python 2.6 does not have assertIn()
+ self.assertTrue("-verbose" in message)
+ self.assertTrue("-force" in message)
+ self.assertTrue("-help" in message)
+ self.assertTrue("-configuration-path" in message)
+ self.assertTrue("-deprovision" in message)
+ self.assertTrue("-register-service" in message)
+ self.assertTrue("-version" in message)
+ self.assertTrue("-daemon" in message)
+ self.assertTrue("-start" in message)
+ self.assertTrue("-run-exthandlers" in message)
+ self.assertTrue("-show-configuration" in message)
+
+ # sanity check
+ self.assertFalse("-not-a-valid-option" in message)
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 1,
"test_score": 2
},
"num_modified_files": 1
} | 2.2 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pyasn1",
"nose",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.4",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs==22.2.0
certifi==2021.5.30
importlib-metadata==4.8.3
iniconfig==1.1.1
nose==1.3.7
packaging==21.3
pluggy==1.0.0
py==1.11.0
pyasn1==0.5.1
pyparsing==3.1.4
pytest==7.0.1
tomli==1.2.3
typing_extensions==4.1.1
-e git+https://github.com/Azure/WALinuxAgent.git@ab261b5f2ed0dfce4dd94adf924e68e0aaff5e7b#egg=WALinuxAgent
zipp==3.6.0
| name: WALinuxAgent
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- attrs==22.2.0
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- nose==1.3.7
- packaging==21.3
- pluggy==1.0.0
- py==1.11.0
- pyasn1==0.5.1
- pyparsing==3.1.4
- pytest==7.0.1
- tomli==1.2.3
- typing-extensions==4.1.1
- zipp==3.6.0
prefix: /opt/conda/envs/WALinuxAgent
| [
"tests/test_agent.py::TestAgent::test_agent_usage_message"
]
| []
| [
"tests/test_agent.py::TestAgent::test_accepts_configuration_path",
"tests/test_agent.py::TestAgent::test_agent_accepts_configuration_path",
"tests/test_agent.py::TestAgent::test_agent_does_not_pass_configuration_path",
"tests/test_agent.py::TestAgent::test_agent_ensures_extension_log_directory",
"tests/test_agent.py::TestAgent::test_agent_get_configuration",
"tests/test_agent.py::TestAgent::test_agent_logs_if_extension_log_directory_is_a_file",
"tests/test_agent.py::TestAgent::test_agent_passes_configuration_path",
"tests/test_agent.py::TestAgent::test_agent_uses_default_configuration_path",
"tests/test_agent.py::TestAgent::test_checks_configuration_path",
"tests/test_agent.py::TestAgent::test_configuration_path_defaults_to_none",
"tests/test_agent.py::TestAgent::test_rejects_missing_configuration_path"
]
| []
| Apache License 2.0 | 1,920 | [
"azurelinuxagent/agent.py"
]
| [
"azurelinuxagent/agent.py"
]
|
zackhsi__venmo-44 | 86cfe5d3b2a962d42c90b9d39b5e251c205156d0 | 2017-11-28 01:55:37 | 86cfe5d3b2a962d42c90b9d39b5e251c205156d0 | diff --git a/.gitignore b/.gitignore
index c7c7428..830ddaf 100644
--- a/.gitignore
+++ b/.gitignore
@@ -10,3 +10,4 @@ build
__pycache__
*.pyc
+.cache
diff --git a/.travis.yml b/.travis.yml
index 1ed605c..bfd2407 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -7,3 +7,4 @@ install:
- make init
script:
- flake8
+ - make test
diff --git a/Makefile b/Makefile
index f3bdd59..08f2575 100644
--- a/Makefile
+++ b/Makefile
@@ -1,3 +1,6 @@
init:
pip install pipenv --upgrade
pipenv install --dev --skip-lock
+
+test:
+ py.test --disable-socket tests
diff --git a/Pipfile b/Pipfile
index e91b975..32fa1ce 100644
--- a/Pipfile
+++ b/Pipfile
@@ -13,3 +13,6 @@ venmo = {path = ".", editable = true}
[dev-packages]
flake8 = "*"
+pytest = "*"
+pytest-socket = "*"
+mock = "*"
diff --git a/venmo/payment.py b/venmo/payment.py
index e2f49a8..950ddec 100644
--- a/venmo/payment.py
+++ b/venmo/payment.py
@@ -36,11 +36,11 @@ def _pay_or_charge(user, amount, note):
}
if user.startswith('@'):
username = user[1:]
- user_id = venmo.user.id_from_username(username.lower())
+ user_id = venmo.user.id_from_username(username)
if not user_id:
logger.error('Could not find user @{}'.format(username))
return
- data['user_id'] = user_id.lower()
+ data['user_id'] = user_id
else:
data['phone'] = user
diff --git a/venmo/user.py b/venmo/user.py
index 978f91e..4875ea3 100644
--- a/venmo/user.py
+++ b/venmo/user.py
@@ -10,7 +10,7 @@ import venmo
def id_from_username(username):
for u in search(username):
- if u['username'] == username:
+ if u['username'].lower() == username.lower():
return u['id']
return None
| Call on id_from_username(username.lower()) fails
https://github.com/zackhsi/venmo/blob/86cfe5d3b2a962d42c90b9d39b5e251c205156d0/venmo/payment.py#L39
Because the line linked above makes the call on `username.lower()`, it looks this call will never return an id for a username that has uppercase letters, because `id_from_username` makes a comparison between the string passed to the function (in this case a lowercase forced string) and the username string returned by venmo. So a function call of `id_from_username('myusername')` for a username that is actually MyUserName will compare MyUserName to myusername and thus return None. | zackhsi/venmo | diff --git a/tests/user_test.py b/tests/user_test.py
new file mode 100644
index 0000000..60caf70
--- /dev/null
+++ b/tests/user_test.py
@@ -0,0 +1,31 @@
+import sys
+
+import venmo
+
+if sys.version_info <= (3, 3):
+ import mock
+else:
+ from unittest import mock
+
+
[email protected](venmo.user, 'search')
+def test_id_from_username_case_insensitive(mock_search):
+ # Mock out Venmo API response. It is case insensitive.
+ mock_search.return_value = [
+ {
+ "id": "975376293560320029",
+ "username": "zackhsi",
+ "display_name": "Zack Hsi",
+ "profile_picture_url": "https://venmopics.appspot.com/u/v2/f/172a1500-63f5-4d78-b15a-a06dc9c0ad82" # noqa
+ },
+ ]
+
+ ids = [
+ venmo.user.id_from_username('zackhsi'),
+ venmo.user.id_from_username('Zackhsi'),
+ venmo.user.id_from_username('ZACKHSI'),
+ ]
+ # Assert that all return ids.
+ assert all(ids)
+ # Assert that the same id is returned.
+ assert len(set(ids)) == 1
| {
"commit_name": "merge_commit",
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 2,
"test_score": 0
},
"num_modified_files": 6
} | unknown | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"pytest",
"pytest-cov",
"pytest-xdist",
"pytest-mock",
"pytest-asyncio"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.6",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work
certifi==2021.5.30
charset-normalizer==2.0.12
coverage==6.2
execnet==1.9.0
idna==3.10
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work
packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work
pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pytest==6.2.4
pytest-asyncio==0.16.0
pytest-cov==4.0.0
pytest-mock==3.6.1
pytest-xdist==3.0.2
requests==2.27.1
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
tomli==1.2.3
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
urllib3==1.26.20
-e git+https://github.com/zackhsi/venmo.git@86cfe5d3b2a962d42c90b9d39b5e251c205156d0#egg=venmo
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
| name: venmo
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=21.4.0=pyhd3eb1b0_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- importlib-metadata=4.8.1=py36h06a4308_0
- importlib_metadata=4.8.1=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- more-itertools=8.12.0=pyhd3eb1b0_0
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=21.3=pyhd3eb1b0_0
- pip=21.2.2=py36h06a4308_0
- pluggy=0.13.1=py36h06a4308_0
- py=1.11.0=pyhd3eb1b0_0
- pyparsing=3.0.4=pyhd3eb1b0_0
- pytest=6.2.4=py36h06a4308_2
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- toml=0.10.2=pyhd3eb1b0_0
- typing_extensions=4.1.1=pyh06a4308_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zipp=3.6.0=pyhd3eb1b0_0
- zlib=1.2.13=h5eee18b_1
- pip:
- charset-normalizer==2.0.12
- coverage==6.2
- execnet==1.9.0
- idna==3.10
- pytest-asyncio==0.16.0
- pytest-cov==4.0.0
- pytest-mock==3.6.1
- pytest-xdist==3.0.2
- requests==2.27.1
- tomli==1.2.3
- urllib3==1.26.20
prefix: /opt/conda/envs/venmo
| [
"tests/user_test.py::test_id_from_username_case_insensitive"
]
| []
| []
| []
| null | 1,921 | [
"Makefile",
".gitignore",
".travis.yml",
"Pipfile",
"venmo/payment.py",
"venmo/user.py"
]
| [
"Makefile",
".gitignore",
".travis.yml",
"Pipfile",
"venmo/payment.py",
"venmo/user.py"
]
|
|
ucfopen__canvasapi-117 | d265d4a49df7041dca888247f48feda7e288cf15 | 2017-11-28 22:30:18 | db3c377b68f2953e1618f4e4588cc2db8603841e | diff --git a/canvasapi/canvas.py b/canvasapi/canvas.py
index 687649c..13193ea 100644
--- a/canvasapi/canvas.py
+++ b/canvasapi/canvas.py
@@ -1,5 +1,7 @@
from __future__ import absolute_import, division, print_function, unicode_literals
+import warnings
+
from canvasapi.account import Account
from canvasapi.course import Course
from canvasapi.exceptions import RequiredFieldMissing
@@ -10,7 +12,10 @@ from canvasapi.paginated_list import PaginatedList
from canvasapi.requester import Requester
from canvasapi.section import Section
from canvasapi.user import User
-from canvasapi.util import combine_kwargs, obj_or_id
+from canvasapi.util import combine_kwargs, get_institution_url, obj_or_id
+
+
+warnings.simplefilter('always', DeprecationWarning)
class Canvas(object):
@@ -25,6 +30,16 @@ class Canvas(object):
:param access_token: The API key to authenticate requests with.
:type access_token: str
"""
+ new_url = get_institution_url(base_url)
+
+ if 'api/v1' in base_url:
+ warnings.warn(
+ "`base_url` no longer requires an API version be specified. "
+ "Rewriting `base_url` to {}".format(new_url),
+ DeprecationWarning
+ )
+ base_url = new_url + '/api/v1/'
+
self.__requester = Requester(base_url, access_token)
def create_account(self, **kwargs):
diff --git a/canvasapi/util.py b/canvasapi/util.py
index 88c469c..86d6ee4 100644
--- a/canvasapi/util.py
+++ b/canvasapi/util.py
@@ -122,3 +122,19 @@ def obj_or_id(parameter, param_name, object_types):
obj_type_list = ",".join([obj_type.__name__ for obj_type in object_types])
message = 'Parameter {} must be of type {} or int.'.format(param_name, obj_type_list)
raise TypeError(message)
+
+
+def get_institution_url(base_url):
+ """
+ Trim '/api/v1' from a given root URL.
+
+ :param base_url: The base URL of the API.
+ :type base_url: str
+ :rtype: str
+ """
+ index = base_url.find('/api/v1')
+
+ if index != -1:
+ return base_url[0:index]
+
+ return base_url
| Deprecate /api/v1 from Canvas constructor
Currently we require `/api/v1/` to be appended to the end of an institution's Canvas URL when initializing the `Canvas` object.
We don't check if the URL is malformed in anyway, and as a result, sometimes unexpected behavior can present itself. We recently ran into this issue with one of our own applications where the base URL was set to `instructure.edu//api/v1/`.
We should implement a fix for this in two ways:
* Remove the `/api/version` requirement in the URL as we don't currently support targeting more than one API version
* Force URLs to be formatted properly (i.e. `*.someurl.com` with no trailing slash, `https://` or `http://` allowed) and manually append the `/api/v1/` string ourselves afterward
We should also warn the user that `/api/v1/` has been deprecated and is no longer required if they include it in their base URL. | ucfopen/canvasapi | diff --git a/tests/settings.py b/tests/settings.py
index 789a25c..e67c5f6 100644
--- a/tests/settings.py
+++ b/tests/settings.py
@@ -1,6 +1,7 @@
from __future__ import absolute_import, division, print_function, unicode_literals
-BASE_URL = 'http://example.com/api/v1/'
+BASE_URL = 'http://example.com'
+BASE_URL_WITH_VERSION = 'http://example.com/api/v1/'
API_KEY = '123'
INVALID_ID = 9001
diff --git a/tests/test_canvas.py b/tests/test_canvas.py
index dc5ec34..3d75228 100644
--- a/tests/test_canvas.py
+++ b/tests/test_canvas.py
@@ -1,5 +1,7 @@
from __future__ import absolute_import, division, print_function, unicode_literals
+
import unittest
+import warnings
from datetime import datetime
import pytz
@@ -30,6 +32,12 @@ class TestCanvas(unittest.TestCase):
def setUp(self):
self.canvas = Canvas(settings.BASE_URL, settings.API_KEY)
+ # Canvas()
+ def test_init_deprecate_url_contains_version(self, m):
+ with warnings.catch_warnings(record=True) as w:
+ Canvas(settings.BASE_URL_WITH_VERSION, settings.API_KEY)
+ self.assertTrue(issubclass(w[0].category, DeprecationWarning))
+
# create_account()
def test_create_account(self, m):
register_uris({'account': ['create']}, m)
diff --git a/tests/test_course.py b/tests/test_course.py
index 415f426..fb6e76c 100644
--- a/tests/test_course.py
+++ b/tests/test_course.py
@@ -176,14 +176,16 @@ class TestCourse(unittest.TestCase):
register_uris({'course': ['upload', 'upload_final']}, m)
filename = 'testfile_course_{}'.format(uuid.uuid4().hex)
- with open(filename, 'w+') as file:
- response = self.course.upload(file)
- self.assertTrue(response[0])
- self.assertIsInstance(response[1], dict)
- self.assertIn('url', response[1])
+ try:
+ with open(filename, 'w+') as file:
+ response = self.course.upload(file)
- cleanup_file(filename)
+ self.assertTrue(response[0])
+ self.assertIsInstance(response[1], dict)
+ self.assertIn('url', response[1])
+ finally:
+ cleanup_file(filename)
# reset()
def test_reset(self, m):
diff --git a/tests/test_group.py b/tests/test_group.py
index 526eb23..e948c44 100644
--- a/tests/test_group.py
+++ b/tests/test_group.py
@@ -152,13 +152,14 @@ class TestGroup(unittest.TestCase):
register_uris({'group': ['upload', 'upload_final']}, m)
filename = 'testfile_group_{}'.format(uuid.uuid4().hex)
- with open(filename, 'w+') as file:
- response = self.group.upload(file)
- self.assertTrue(response[0])
- self.assertIsInstance(response[1], dict)
- self.assertIn('url', response[1])
-
- cleanup_file(filename)
+ try:
+ with open(filename, 'w+') as file:
+ response = self.group.upload(file)
+ self.assertTrue(response[0])
+ self.assertIsInstance(response[1], dict)
+ self.assertIn('url', response[1])
+ finally:
+ cleanup_file(filename)
# preview_processed_html()
def test_preview_processed_html(self, m):
diff --git a/tests/test_submission.py b/tests/test_submission.py
index 8a083e0..2ccc29c 100644
--- a/tests/test_submission.py
+++ b/tests/test_submission.py
@@ -37,14 +37,16 @@ class TestSubmission(unittest.TestCase):
register_uris({'submission': ['upload_comment', 'upload_comment_final']}, m)
filename = 'testfile_submission_{}'.format(uuid.uuid4().hex)
- with open(filename, 'w+') as file:
- response = self.submission_course.upload_comment(file)
- self.assertTrue(response[0])
- self.assertIsInstance(response[1], dict)
- self.assertIn('url', response[1])
+ try:
+ with open(filename, 'w+') as file:
+ response = self.submission_course.upload_comment(file)
- cleanup_file(filename)
+ self.assertTrue(response[0])
+ self.assertIsInstance(response[1], dict)
+ self.assertIn('url', response[1])
+ finally:
+ cleanup_file(filename)
def test_upload_comment_section(self, m):
# Sections do not support uploading file comments
diff --git a/tests/test_uploader.py b/tests/test_uploader.py
index a72ecd2..6cea063 100644
--- a/tests/test_uploader.py
+++ b/tests/test_uploader.py
@@ -22,7 +22,6 @@ class TestUploader(unittest.TestCase):
def tearDown(self):
self.file.close()
-
cleanup_file(self.filename)
# start()
diff --git a/tests/test_user.py b/tests/test_user.py
index fa5d5b7..d2ed67c 100644
--- a/tests/test_user.py
+++ b/tests/test_user.py
@@ -203,14 +203,16 @@ class TestUser(unittest.TestCase):
register_uris({'user': ['upload', 'upload_final']}, m)
filename = 'testfile_user_{}'.format(uuid.uuid4().hex)
- with open(filename, 'w+') as file:
- response = self.user.upload(file)
- self.assertTrue(response[0])
- self.assertIsInstance(response[1], dict)
- self.assertIn('url', response[1])
+ try:
+ with open(filename, 'w+') as file:
+ response = self.user.upload(file)
- cleanup_file(filename)
+ self.assertTrue(response[0])
+ self.assertIsInstance(response[1], dict)
+ self.assertIn('url', response[1])
+ finally:
+ cleanup_file(filename)
# list_groups()
def test_list_groups(self, m):
diff --git a/tests/test_util.py b/tests/test_util.py
index 71677d0..472b4f1 100644
--- a/tests/test_util.py
+++ b/tests/test_util.py
@@ -6,7 +6,9 @@ import requests_mock
from canvasapi import Canvas
from canvasapi.course import CourseNickname
from canvasapi.user import User
-from canvasapi.util import combine_kwargs, is_multivalued, obj_or_id
+from canvasapi.util import (
+ combine_kwargs, get_institution_url, is_multivalued, obj_or_id
+)
from itertools import chain
from six import integer_types, iterkeys, itervalues, iteritems
from six.moves import zip
@@ -408,3 +410,8 @@ class TestUtil(unittest.TestCase):
with self.assertRaises(TypeError):
obj_or_id(nick, 'nickname_id', (CourseNickname,))
+
+ # get_institution_url()
+ def test_get_institution_url(self, m):
+ base_url = 'https://my.canvas.edu/api/v1'
+ self.assertEqual(get_institution_url(base_url), 'https://my.canvas.edu')
diff --git a/tests/util.py b/tests/util.py
index 3b92514..89a2616 100644
--- a/tests/util.py
+++ b/tests/util.py
@@ -4,6 +4,7 @@ import os
import requests_mock
+from canvasapi.util import get_institution_url
from tests import settings
@@ -17,7 +18,6 @@ def register_uris(requirements, requests_mocker):
:param requests_mocker: requests_mock.mocker.Mocker
"""
for fixture, objects in requirements.items():
-
try:
with open('tests/fixtures/{}.json'.format(fixture)) as file:
data = json.loads(file.read())
@@ -40,7 +40,7 @@ def register_uris(requirements, requests_mocker):
if obj['endpoint'] == 'ANY':
url = requests_mock.ANY
else:
- url = settings.BASE_URL + obj['endpoint']
+ url = get_institution_url(settings.BASE_URL) + '/api/v1/' + obj['endpoint']
try:
requests_mocker.register_uri(
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 0,
"test_score": 2
},
"num_modified_files": 2
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"flake8",
"pycodestyle",
"requests_mock"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | -e git+https://github.com/ucfopen/canvasapi.git@d265d4a49df7041dca888247f48feda7e288cf15#egg=canvasapi
certifi==2025.1.31
charset-normalizer==3.4.1
exceptiongroup==1.2.2
flake8==7.2.0
idna==3.10
iniconfig==2.1.0
mccabe==0.7.0
packaging==24.2
pluggy==1.5.0
pycodestyle==2.13.0
pyflakes==3.3.1
pytest==8.3.5
pytz==2025.2
requests==2.32.3
requests-mock==1.12.1
six==1.17.0
tomli==2.2.1
urllib3==2.3.0
| name: canvasapi
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- certifi==2025.1.31
- charset-normalizer==3.4.1
- exceptiongroup==1.2.2
- flake8==7.2.0
- idna==3.10
- iniconfig==2.1.0
- mccabe==0.7.0
- packaging==24.2
- pluggy==1.5.0
- pycodestyle==2.13.0
- pyflakes==3.3.1
- pytest==8.3.5
- pytz==2025.2
- requests==2.32.3
- requests-mock==1.12.1
- six==1.17.0
- tomli==2.2.1
- urllib3==2.3.0
prefix: /opt/conda/envs/canvasapi
| [
"tests/test_canvas.py::TestCanvas::test_clear_course_nicknames",
"tests/test_canvas.py::TestCanvas::test_conversations_batch_update",
"tests/test_canvas.py::TestCanvas::test_conversations_batch_updated_fail_on_event",
"tests/test_canvas.py::TestCanvas::test_conversations_batch_updated_fail_on_ids",
"tests/test_canvas.py::TestCanvas::test_conversations_get_running_batches",
"tests/test_canvas.py::TestCanvas::test_conversations_mark_all_as_read",
"tests/test_canvas.py::TestCanvas::test_conversations_unread_count",
"tests/test_canvas.py::TestCanvas::test_create_account",
"tests/test_canvas.py::TestCanvas::test_create_appointment_group",
"tests/test_canvas.py::TestCanvas::test_create_appointment_group_fail_on_context_codes",
"tests/test_canvas.py::TestCanvas::test_create_appointment_group_fail_on_title",
"tests/test_canvas.py::TestCanvas::test_create_calendar_event",
"tests/test_canvas.py::TestCanvas::test_create_calendar_event_fail",
"tests/test_canvas.py::TestCanvas::test_create_conversation",
"tests/test_canvas.py::TestCanvas::test_create_group",
"tests/test_canvas.py::TestCanvas::test_get_account",
"tests/test_canvas.py::TestCanvas::test_get_account_fail",
"tests/test_canvas.py::TestCanvas::test_get_account_sis_id",
"tests/test_canvas.py::TestCanvas::test_get_accounts",
"tests/test_canvas.py::TestCanvas::test_get_activity_stream_summary",
"tests/test_canvas.py::TestCanvas::test_get_appointment_group",
"tests/test_canvas.py::TestCanvas::test_get_calendar_event",
"tests/test_canvas.py::TestCanvas::test_get_conversation",
"tests/test_canvas.py::TestCanvas::test_get_conversations",
"tests/test_canvas.py::TestCanvas::test_get_course",
"tests/test_canvas.py::TestCanvas::test_get_course_accounts",
"tests/test_canvas.py::TestCanvas::test_get_course_fail",
"tests/test_canvas.py::TestCanvas::test_get_course_nickname",
"tests/test_canvas.py::TestCanvas::test_get_course_nickname_fail",
"tests/test_canvas.py::TestCanvas::test_get_course_nicknames",
"tests/test_canvas.py::TestCanvas::test_get_course_non_unicode_char",
"tests/test_canvas.py::TestCanvas::test_get_course_sis_id",
"tests/test_canvas.py::TestCanvas::test_get_course_with_start_date",
"tests/test_canvas.py::TestCanvas::test_get_courses",
"tests/test_canvas.py::TestCanvas::test_get_file",
"tests/test_canvas.py::TestCanvas::test_get_group",
"tests/test_canvas.py::TestCanvas::test_get_group_category",
"tests/test_canvas.py::TestCanvas::test_get_group_sis_id",
"tests/test_canvas.py::TestCanvas::test_get_outcome",
"tests/test_canvas.py::TestCanvas::test_get_outcome_group",
"tests/test_canvas.py::TestCanvas::test_get_root_outcome_group",
"tests/test_canvas.py::TestCanvas::test_get_section",
"tests/test_canvas.py::TestCanvas::test_get_section_sis_id",
"tests/test_canvas.py::TestCanvas::test_get_todo_items",
"tests/test_canvas.py::TestCanvas::test_get_upcoming_events",
"tests/test_canvas.py::TestCanvas::test_get_user",
"tests/test_canvas.py::TestCanvas::test_get_user_by_id_type",
"tests/test_canvas.py::TestCanvas::test_get_user_fail",
"tests/test_canvas.py::TestCanvas::test_get_user_self",
"tests/test_canvas.py::TestCanvas::test_list_appointment_groups",
"tests/test_canvas.py::TestCanvas::test_list_calendar_events",
"tests/test_canvas.py::TestCanvas::test_list_group_participants",
"tests/test_canvas.py::TestCanvas::test_list_user_participants",
"tests/test_canvas.py::TestCanvas::test_reserve_time_slot",
"tests/test_canvas.py::TestCanvas::test_reserve_time_slot_by_participant_id",
"tests/test_canvas.py::TestCanvas::test_search_accounts",
"tests/test_canvas.py::TestCanvas::test_search_all_courses",
"tests/test_canvas.py::TestCanvas::test_search_recipients",
"tests/test_canvas.py::TestCanvas::test_set_course_nickname",
"tests/test_course.py::TestCourse::test__str__",
"tests/test_course.py::TestCourse::test_add_grading_standards",
"tests/test_course.py::TestCourse::test_add_grading_standards_empty_list",
"tests/test_course.py::TestCourse::test_add_grading_standards_missing_name_key",
"tests/test_course.py::TestCourse::test_add_grading_standards_missing_value_key",
"tests/test_course.py::TestCourse::test_add_grading_standards_non_dict_list",
"tests/test_course.py::TestCourse::test_conclude",
"tests/test_course.py::TestCourse::test_course_files",
"tests/test_course.py::TestCourse::test_create_assignment",
"tests/test_course.py::TestCourse::test_create_assignment_fail",
"tests/test_course.py::TestCourse::test_create_assignment_group",
"tests/test_course.py::TestCourse::test_create_course_section",
"tests/test_course.py::TestCourse::test_create_discussion_topic",
"tests/test_course.py::TestCourse::test_create_external_feed",
"tests/test_course.py::TestCourse::test_create_external_tool",
"tests/test_course.py::TestCourse::test_create_folder",
"tests/test_course.py::TestCourse::test_create_group_category",
"tests/test_course.py::TestCourse::test_create_module",
"tests/test_course.py::TestCourse::test_create_module_fail",
"tests/test_course.py::TestCourse::test_create_page",
"tests/test_course.py::TestCourse::test_create_page_fail",
"tests/test_course.py::TestCourse::test_create_quiz",
"tests/test_course.py::TestCourse::test_create_quiz_fail",
"tests/test_course.py::TestCourse::test_delete",
"tests/test_course.py::TestCourse::test_delete_external_feed",
"tests/test_course.py::TestCourse::test_edit_front_page",
"tests/test_course.py::TestCourse::test_enroll_user",
"tests/test_course.py::TestCourse::test_get_assignment",
"tests/test_course.py::TestCourse::test_get_assignment_group",
"tests/test_course.py::TestCourse::test_get_assignments",
"tests/test_course.py::TestCourse::test_get_course_level_assignment_data",
"tests/test_course.py::TestCourse::test_get_course_level_participation_data",
"tests/test_course.py::TestCourse::test_get_course_level_student_summary_data",
"tests/test_course.py::TestCourse::test_get_discussion_topic",
"tests/test_course.py::TestCourse::test_get_discussion_topics",
"tests/test_course.py::TestCourse::test_get_enrollments",
"tests/test_course.py::TestCourse::test_get_external_tool",
"tests/test_course.py::TestCourse::test_get_external_tools",
"tests/test_course.py::TestCourse::test_get_file",
"tests/test_course.py::TestCourse::test_get_folder",
"tests/test_course.py::TestCourse::test_get_full_discussion_topic",
"tests/test_course.py::TestCourse::test_get_grading_standards",
"tests/test_course.py::TestCourse::test_get_module",
"tests/test_course.py::TestCourse::test_get_modules",
"tests/test_course.py::TestCourse::test_get_outcome_group",
"tests/test_course.py::TestCourse::test_get_outcome_groups_in_context",
"tests/test_course.py::TestCourse::test_get_outcome_links_in_context",
"tests/test_course.py::TestCourse::test_get_outcome_result_rollups",
"tests/test_course.py::TestCourse::test_get_outcome_results",
"tests/test_course.py::TestCourse::test_get_page",
"tests/test_course.py::TestCourse::test_get_pages",
"tests/test_course.py::TestCourse::test_get_quiz",
"tests/test_course.py::TestCourse::test_get_quiz_fail",
"tests/test_course.py::TestCourse::test_get_quizzes",
"tests/test_course.py::TestCourse::test_get_recent_students",
"tests/test_course.py::TestCourse::test_get_root_outcome_group",
"tests/test_course.py::TestCourse::test_get_section",
"tests/test_course.py::TestCourse::test_get_settings",
"tests/test_course.py::TestCourse::test_get_single_grading_standard",
"tests/test_course.py::TestCourse::test_get_submission",
"tests/test_course.py::TestCourse::test_get_user",
"tests/test_course.py::TestCourse::test_get_user_id_type",
"tests/test_course.py::TestCourse::test_get_user_in_a_course_level_assignment_data",
"tests/test_course.py::TestCourse::test_get_user_in_a_course_level_messaging_data",
"tests/test_course.py::TestCourse::test_get_user_in_a_course_level_participation_data",
"tests/test_course.py::TestCourse::test_get_users",
"tests/test_course.py::TestCourse::test_list_assignment_groups",
"tests/test_course.py::TestCourse::test_list_external_feeds",
"tests/test_course.py::TestCourse::test_list_folders",
"tests/test_course.py::TestCourse::test_list_gradeable_students",
"tests/test_course.py::TestCourse::test_list_group_categories",
"tests/test_course.py::TestCourse::test_list_groups",
"tests/test_course.py::TestCourse::test_list_multiple_submissions",
"tests/test_course.py::TestCourse::test_list_multiple_submissions_grouped_param",
"tests/test_course.py::TestCourse::test_list_sections",
"tests/test_course.py::TestCourse::test_list_submissions",
"tests/test_course.py::TestCourse::test_list_tabs",
"tests/test_course.py::TestCourse::test_mark_submission_as_read",
"tests/test_course.py::TestCourse::test_mark_submission_as_unread",
"tests/test_course.py::TestCourse::test_preview_html",
"tests/test_course.py::TestCourse::test_reorder_pinned_topics",
"tests/test_course.py::TestCourse::test_reorder_pinned_topics_comma_separated_string",
"tests/test_course.py::TestCourse::test_reorder_pinned_topics_invalid_input",
"tests/test_course.py::TestCourse::test_reorder_pinned_topics_tuple",
"tests/test_course.py::TestCourse::test_reset",
"tests/test_course.py::TestCourse::test_show_front_page",
"tests/test_course.py::TestCourse::test_subit_assignment_fail",
"tests/test_course.py::TestCourse::test_submit_assignment",
"tests/test_course.py::TestCourse::test_update",
"tests/test_course.py::TestCourse::test_update_settings",
"tests/test_course.py::TestCourse::test_update_submission",
"tests/test_course.py::TestCourse::test_update_tab",
"tests/test_course.py::TestCourse::test_upload",
"tests/test_course.py::TestCourseNickname::test__str__",
"tests/test_course.py::TestCourseNickname::test_remove",
"tests/test_group.py::TestGroup::test__str__",
"tests/test_group.py::TestGroup::test_create_discussion_topic",
"tests/test_group.py::TestGroup::test_create_external_feed",
"tests/test_group.py::TestGroup::test_create_folder",
"tests/test_group.py::TestGroup::test_create_membership",
"tests/test_group.py::TestGroup::test_create_page",
"tests/test_group.py::TestGroup::test_create_page_fail",
"tests/test_group.py::TestGroup::test_delete",
"tests/test_group.py::TestGroup::test_delete_external_feed",
"tests/test_group.py::TestGroup::test_edit",
"tests/test_group.py::TestGroup::test_edit_front_page",
"tests/test_group.py::TestGroup::test_get_activity_stream_summary",
"tests/test_group.py::TestGroup::test_get_discussion_topic",
"tests/test_group.py::TestGroup::test_get_discussion_topics",
"tests/test_group.py::TestGroup::test_get_file",
"tests/test_group.py::TestGroup::test_get_folder",
"tests/test_group.py::TestGroup::test_get_full_discussion_topic",
"tests/test_group.py::TestGroup::test_get_membership",
"tests/test_group.py::TestGroup::test_get_page",
"tests/test_group.py::TestGroup::test_get_pages",
"tests/test_group.py::TestGroup::test_group_files",
"tests/test_group.py::TestGroup::test_invite",
"tests/test_group.py::TestGroup::test_list_external_feeds",
"tests/test_group.py::TestGroup::test_list_folders",
"tests/test_group.py::TestGroup::test_list_memberships",
"tests/test_group.py::TestGroup::test_list_tabs",
"tests/test_group.py::TestGroup::test_list_users",
"tests/test_group.py::TestGroup::test_preview_processed_html",
"tests/test_group.py::TestGroup::test_remove_user",
"tests/test_group.py::TestGroup::test_reorder_pinned_topics",
"tests/test_group.py::TestGroup::test_reorder_pinned_topics_comma_separated_string",
"tests/test_group.py::TestGroup::test_reorder_pinned_topics_invalid_input",
"tests/test_group.py::TestGroup::test_reorder_pinned_topics_tuple",
"tests/test_group.py::TestGroup::test_show_front_page",
"tests/test_group.py::TestGroup::test_update_membership",
"tests/test_group.py::TestGroup::test_upload",
"tests/test_group.py::TestGroupMembership::test__str__",
"tests/test_group.py::TestGroupMembership::test_remove_self",
"tests/test_group.py::TestGroupMembership::test_remove_user",
"tests/test_group.py::TestGroupMembership::test_update",
"tests/test_group.py::TestGroupCategory::test__str__",
"tests/test_group.py::TestGroupCategory::test_assign_members",
"tests/test_group.py::TestGroupCategory::test_create_group",
"tests/test_group.py::TestGroupCategory::test_delete_category",
"tests/test_group.py::TestGroupCategory::test_list_groups",
"tests/test_group.py::TestGroupCategory::test_list_users",
"tests/test_group.py::TestGroupCategory::test_update",
"tests/test_submission.py::TestSubmission::test__str__",
"tests/test_submission.py::TestSubmission::test_upload_comment",
"tests/test_submission.py::TestSubmission::test_upload_comment_section",
"tests/test_uploader.py::TestUploader::test_start",
"tests/test_uploader.py::TestUploader::test_start_file_does_not_exist",
"tests/test_uploader.py::TestUploader::test_start_path",
"tests/test_uploader.py::TestUploader::test_upload_fail",
"tests/test_uploader.py::TestUploader::test_upload_no_upload_params",
"tests/test_uploader.py::TestUploader::test_upload_no_upload_url",
"tests/test_user.py::TestUser::test__str__",
"tests/test_user.py::TestUser::test_add_observee",
"tests/test_user.py::TestUser::test_add_observee_with_credentials",
"tests/test_user.py::TestUser::test_create_bookmark",
"tests/test_user.py::TestUser::test_create_folder",
"tests/test_user.py::TestUser::test_edit",
"tests/test_user.py::TestUser::test_get_avatars",
"tests/test_user.py::TestUser::test_get_bookmark",
"tests/test_user.py::TestUser::test_get_color",
"tests/test_user.py::TestUser::test_get_colors",
"tests/test_user.py::TestUser::test_get_courses",
"tests/test_user.py::TestUser::test_get_file",
"tests/test_user.py::TestUser::test_get_folder",
"tests/test_user.py::TestUser::test_get_missing_submissions",
"tests/test_user.py::TestUser::test_get_page_views",
"tests/test_user.py::TestUser::test_get_profile",
"tests/test_user.py::TestUser::test_list_bookmarks",
"tests/test_user.py::TestUser::test_list_calendar_events_for_user",
"tests/test_user.py::TestUser::test_list_communication_channels",
"tests/test_user.py::TestUser::test_list_enrollments",
"tests/test_user.py::TestUser::test_list_folders",
"tests/test_user.py::TestUser::test_list_groups",
"tests/test_user.py::TestUser::test_list_observees",
"tests/test_user.py::TestUser::test_list_user_logins",
"tests/test_user.py::TestUser::test_merge_into_id",
"tests/test_user.py::TestUser::test_merge_into_user",
"tests/test_user.py::TestUser::test_remove_observee",
"tests/test_user.py::TestUser::test_show_observee",
"tests/test_user.py::TestUser::test_update_color",
"tests/test_user.py::TestUser::test_update_color_no_hashtag",
"tests/test_user.py::TestUser::test_update_settings",
"tests/test_user.py::TestUser::test_upload",
"tests/test_user.py::TestUser::test_user_files",
"tests/test_user.py::TestUser::test_user_get_assignments",
"tests/test_user.py::TestUserDisplay::test__str__",
"tests/test_util.py::TestUtil::test_combine_kwargs_empty",
"tests/test_util.py::TestUtil::test_combine_kwargs_multiple_dicts",
"tests/test_util.py::TestUtil::test_combine_kwargs_multiple_mixed",
"tests/test_util.py::TestUtil::test_combine_kwargs_multiple_nested_dicts",
"tests/test_util.py::TestUtil::test_combine_kwargs_nested_dict",
"tests/test_util.py::TestUtil::test_combine_kwargs_single",
"tests/test_util.py::TestUtil::test_combine_kwargs_single_dict",
"tests/test_util.py::TestUtil::test_combine_kwargs_single_generator_empty",
"tests/test_util.py::TestUtil::test_combine_kwargs_single_generator_multiple_items",
"tests/test_util.py::TestUtil::test_combine_kwargs_single_generator_single_item",
"tests/test_util.py::TestUtil::test_combine_kwargs_single_list_empty",
"tests/test_util.py::TestUtil::test_combine_kwargs_single_list_multiple_items",
"tests/test_util.py::TestUtil::test_combine_kwargs_single_list_single_item",
"tests/test_util.py::TestUtil::test_combine_kwargs_super_nested_dict",
"tests/test_util.py::TestUtil::test_combine_kwargs_the_gauntlet",
"tests/test_util.py::TestUtil::test_get_institution_url",
"tests/test_util.py::TestUtil::test_is_multivalued_bool",
"tests/test_util.py::TestUtil::test_is_multivalued_bytes",
"tests/test_util.py::TestUtil::test_is_multivalued_chain",
"tests/test_util.py::TestUtil::test_is_multivalued_dict",
"tests/test_util.py::TestUtil::test_is_multivalued_dict_items",
"tests/test_util.py::TestUtil::test_is_multivalued_dict_iter",
"tests/test_util.py::TestUtil::test_is_multivalued_dict_keys",
"tests/test_util.py::TestUtil::test_is_multivalued_dict_values",
"tests/test_util.py::TestUtil::test_is_multivalued_generator_call",
"tests/test_util.py::TestUtil::test_is_multivalued_generator_expr",
"tests/test_util.py::TestUtil::test_is_multivalued_integer_types",
"tests/test_util.py::TestUtil::test_is_multivalued_list",
"tests/test_util.py::TestUtil::test_is_multivalued_list_iter",
"tests/test_util.py::TestUtil::test_is_multivalued_set",
"tests/test_util.py::TestUtil::test_is_multivalued_set_iter",
"tests/test_util.py::TestUtil::test_is_multivalued_str",
"tests/test_util.py::TestUtil::test_is_multivalued_tuple",
"tests/test_util.py::TestUtil::test_is_multivalued_tuple_iter",
"tests/test_util.py::TestUtil::test_is_multivalued_unicode",
"tests/test_util.py::TestUtil::test_is_multivalued_zip",
"tests/test_util.py::TestUtil::test_obj_or_id_int",
"tests/test_util.py::TestUtil::test_obj_or_id_obj",
"tests/test_util.py::TestUtil::test_obj_or_id_obj_no_id",
"tests/test_util.py::TestUtil::test_obj_or_id_str_invalid",
"tests/test_util.py::TestUtil::test_obj_or_id_str_valid"
]
| [
"tests/test_canvas.py::TestCanvas::test_init_deprecate_url_contains_version"
]
| []
| []
| MIT License | 1,922 | [
"canvasapi/util.py",
"canvasapi/canvas.py"
]
| [
"canvasapi/util.py",
"canvasapi/canvas.py"
]
|
|
Azure__WALinuxAgent-954 | b943cbc7067fbb8500a6a2ca1c7588f803ff7c81 | 2017-11-29 00:43:30 | 6e9b985c1d7d564253a1c344bab01b45093103cd | diff --git a/azurelinuxagent/common/event.py b/azurelinuxagent/common/event.py
index 108cf009..af4dee6c 100644
--- a/azurelinuxagent/common/event.py
+++ b/azurelinuxagent/common/event.py
@@ -63,6 +63,7 @@ class WALAEventOperation:
Partition = "Partition"
ProcessGoalState = "ProcessGoalState"
Provision = "Provision"
+ GuestState = "GuestState"
ReportStatus = "ReportStatus"
Restart = "Restart"
UnhandledError = "UnhandledError"
diff --git a/azurelinuxagent/pa/provision/cloudinit.py b/azurelinuxagent/pa/provision/cloudinit.py
index c6745260..22c3f9ca 100644
--- a/azurelinuxagent/pa/provision/cloudinit.py
+++ b/azurelinuxagent/pa/provision/cloudinit.py
@@ -26,9 +26,9 @@ from datetime import datetime
import azurelinuxagent.common.conf as conf
import azurelinuxagent.common.logger as logger
import azurelinuxagent.common.utils.fileutil as fileutil
-import azurelinuxagent.common.utils.shellutil as shellutil
-from azurelinuxagent.common.event import elapsed_milliseconds
+from azurelinuxagent.common.event import elapsed_milliseconds, \
+ WALAEventOperation
from azurelinuxagent.common.exception import ProvisionError, ProtocolError
from azurelinuxagent.common.future import ustr
from azurelinuxagent.common.protocol import OVF_FILE_NAME
@@ -67,6 +67,9 @@ class CloudInitProvisionHandler(ProvisionHandler):
self.report_event("Provision succeed",
is_success=True,
duration=elapsed_milliseconds(utc_start))
+ self.report_event(self.create_guest_state_telemetry_messsage(),
+ is_success=True,
+ operation=WALAEventOperation.GuestState)
except ProvisionError as e:
logger.error("Provisioning failed: {0}", ustr(e))
diff --git a/azurelinuxagent/pa/provision/default.py b/azurelinuxagent/pa/provision/default.py
index d2789750..5d6f1565 100644
--- a/azurelinuxagent/pa/provision/default.py
+++ b/azurelinuxagent/pa/provision/default.py
@@ -22,6 +22,7 @@ Provision handler
import os
import os.path
import re
+import socket
import time
from datetime import datetime
@@ -88,10 +89,14 @@ class ProvisionHandler(object):
self.write_provisioned()
- self.report_event("Provision succeed",
+ self.report_event("Provision succeeded",
is_success=True,
duration=elapsed_milliseconds(utc_start))
+ self.report_event(self.create_guest_state_telemetry_messsage(),
+ is_success=True,
+ operation=WALAEventOperation.GuestState)
+
self.report_ready(thumbprint)
logger.info("Provisioning complete")
@@ -264,12 +269,53 @@ class ProvisionHandler(object):
logger.info("Deploy ssh key pairs.")
self.osutil.deploy_ssh_keypair(ovfenv.username, keypair)
- def report_event(self, message, is_success=False, duration=0):
+ def report_event(self, message, is_success=False, duration=0,
+ operation=WALAEventOperation.Provision):
add_event(name=AGENT_NAME,
message=message,
duration=duration,
is_success=is_success,
- op=WALAEventOperation.Provision)
+ op=operation)
+
+ def get_cpu_count(self):
+ try:
+ count = len([x for x in open('/proc/cpuinfo').readlines()
+ if x.startswith("processor")])
+ return count
+ except Exception as e:
+ logger.verbose(u"Failed to determine the CPU count: {0}.", ustr(e))
+ pass
+ return -1
+
+ def get_mem_size_mb(self):
+ try:
+ for line in open('/proc/meminfo').readlines():
+ m = re.match('^MemTotal:\s*(\d+) kB$', line)
+ if m is not None:
+ return int(int(m.group(1)) / 1024)
+ except Exception as e:
+ logger.verbose(u"Failed to determine the memory size: {0}..", ustr(e))
+ pass
+ return -1
+
+ def create_guest_state_telemetry_messsage(self):
+ """
+ Create a GuestState JSON message that contains the current CPU, Memory
+ (MB), and hostname of the guest.
+
+ e.g.
+
+ {
+ "cpu": 1,
+ "mem": 1024,
+ "hostname": "server1234"
+ }
+ """
+ cpu = self.get_cpu_count()
+ mem = self.get_mem_size_mb()
+
+ return """{{"cpu": {0}, "mem": {1}, "hostname": "{2}"}}"""\
+ .format(cpu, mem, socket.gethostname())
def report_not_ready(self, sub_status, description):
status = ProvisionStatus(status="NotReady", subStatus=sub_status,
| Telemetry Event to Report Detected CPU and Memory
There are cases where customers are paying for X CPUs and Y Memory, but they are not actually getting it. This is due to their kernel being improperly configured, or just being too old. The telemetry we have reports what Hyper-V gave the customer, which only tells half the story. I would like the agent to report the values from /proc/cpuinfo and /proc/meminfo (or something comparable), so we can detect these types of conditions.
| Azure/WALinuxAgent | diff --git a/tests/pa/test_provision.py b/tests/pa/test_provision.py
index 7045fccf..ab0a9102 100644
--- a/tests/pa/test_provision.py
+++ b/tests/pa/test_provision.py
@@ -15,9 +15,13 @@
# Requires Python 2.4+ and Openssl 1.0+
#
+import json
+import socket
+
import azurelinuxagent.common.utils.fileutil as fileutil
-from azurelinuxagent.common.exception import ProtocolError
+from azurelinuxagent.common.event import WALAEventOperation
+from azurelinuxagent.common.exception import ProvisionError
from azurelinuxagent.common.osutil.default import DefaultOSUtil
from azurelinuxagent.common.protocol import OVF_FILE_NAME
from azurelinuxagent.pa.provision import get_provision_handler
@@ -115,6 +119,85 @@ class TestProvision(AgentTestCase):
ph.osutil.is_current_instance_id.assert_called_once()
deprovision_handler.run_changed_unique_id.assert_called_once()
+ @distros()
+ @patch('azurelinuxagent.common.osutil.default.DefaultOSUtil.get_instance_id',
+ return_value='B9F3C233-9913-9F42-8EB3-BA656DF32502')
+ def test_provision_telemetry_success(self, mock_util, distro_name, distro_version,
+ distro_full_name):
+ """
+ Assert that the agent issues two telemetry messages as part of a
+ successful provisioning.
+
+ 1. Provision
+ 2. GuestState
+ """
+ ph = get_provision_handler(distro_name, distro_version,
+ distro_full_name)
+ ph.report_event = MagicMock()
+ ph.reg_ssh_host_key = MagicMock(return_value='--thumprint--')
+
+ mock_osutil = MagicMock()
+ mock_osutil.decode_customdata = Mock(return_value="")
+
+ ph.osutil = mock_osutil
+ ph.protocol_util.osutil = mock_osutil
+ ph.protocol_util.get_protocol_by_file = MagicMock()
+ ph.protocol_util.get_protocol = MagicMock()
+
+ conf.get_dvd_mount_point = Mock(return_value=self.tmp_dir)
+ ovfenv_file = os.path.join(self.tmp_dir, OVF_FILE_NAME)
+ ovfenv_data = load_data("ovf-env.xml")
+ fileutil.write_file(ovfenv_file, ovfenv_data)
+
+ ph.run()
+
+ call1 = call("Provision succeeded", duration=ANY, is_success=True)
+ call2 = call(ANY, is_success=True, operation=WALAEventOperation.GuestState)
+ ph.report_event.assert_has_calls([call1, call2])
+
+ args, kwargs = ph.report_event.call_args_list[1]
+ guest_state_json = json.loads(args[0])
+ self.assertTrue(1 <= guest_state_json['cpu'])
+ self.assertTrue(1 <= guest_state_json['mem'])
+ self.assertEqual(socket.gethostname(), guest_state_json['hostname'])
+
+ @distros()
+ @patch(
+ 'azurelinuxagent.common.osutil.default.DefaultOSUtil.get_instance_id',
+ return_value='B9F3C233-9913-9F42-8EB3-BA656DF32502')
+ def test_provision_telemetry_fail(self, mock_util, distro_name,
+ distro_version,
+ distro_full_name):
+ """
+ Assert that the agent issues one telemetry message as part of a
+ failed provisioning.
+
+ 1. Provision
+ """
+ ph = get_provision_handler(distro_name, distro_version,
+ distro_full_name)
+ ph.report_event = MagicMock()
+ ph.reg_ssh_host_key = MagicMock(side_effect=ProvisionError(
+ "--unit-test--"))
+
+ mock_osutil = MagicMock()
+ mock_osutil.decode_customdata = Mock(return_value="")
+
+ ph.osutil = mock_osutil
+ ph.protocol_util.osutil = mock_osutil
+ ph.protocol_util.get_protocol_by_file = MagicMock()
+ ph.protocol_util.get_protocol = MagicMock()
+
+ conf.get_dvd_mount_point = Mock(return_value=self.tmp_dir)
+ ovfenv_file = os.path.join(self.tmp_dir, OVF_FILE_NAME)
+ ovfenv_data = load_data("ovf-env.xml")
+ fileutil.write_file(ovfenv_file, ovfenv_data)
+
+ ph.run()
+ ph.report_event.assert_called_once_with(
+ "[ProvisionError] --unit-test--")
+
+
if __name__ == '__main__':
unittest.main()
diff --git a/tests/tools.py b/tests/tools.py
index 94fab7f5..65e27c6e 100644
--- a/tests/tools.py
+++ b/tests/tools.py
@@ -34,9 +34,9 @@ from azurelinuxagent.common.version import PY_VERSION_MAJOR
#Import mock module for Python2 and Python3
try:
- from unittest.mock import Mock, patch, MagicMock, DEFAULT, call
+ from unittest.mock import Mock, patch, MagicMock, DEFAULT, ANY, call
except ImportError:
- from mock import Mock, patch, MagicMock, DEFAULT, call
+ from mock import Mock, patch, MagicMock, DEFAULT, ANY, call
test_dir = os.path.dirname(os.path.abspath(__file__))
data_dir = os.path.join(test_dir, "data")
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 1,
"test_score": 2
},
"num_modified_files": 3
} | 2.2 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pyasn1",
"pip_packages": [
"nose",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.4",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs==22.2.0
certifi==2021.5.30
importlib-metadata==4.8.3
iniconfig==1.1.1
nose==1.3.7
packaging==21.3
pluggy==1.0.0
py==1.11.0
pyasn1 @ file:///Users/ktietz/demo/mc3/conda-bld/pyasn1_1629708007385/work
pyparsing==3.1.4
pytest==7.0.1
tomli==1.2.3
typing_extensions==4.1.1
-e git+https://github.com/Azure/WALinuxAgent.git@b943cbc7067fbb8500a6a2ca1c7588f803ff7c81#egg=WALinuxAgent
zipp==3.6.0
| name: WALinuxAgent
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- pyasn1=0.4.8=pyhd3eb1b0_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- attrs==22.2.0
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- nose==1.3.7
- packaging==21.3
- pluggy==1.0.0
- py==1.11.0
- pyparsing==3.1.4
- pytest==7.0.1
- tomli==1.2.3
- typing-extensions==4.1.1
- zipp==3.6.0
prefix: /opt/conda/envs/WALinuxAgent
| [
"tests/pa/test_provision.py::TestProvision::test_provision_telemetry_success"
]
| []
| [
"tests/pa/test_provision.py::TestProvision::test_customdata",
"tests/pa/test_provision.py::TestProvision::test_is_provisioned_is_provisioned",
"tests/pa/test_provision.py::TestProvision::test_is_provisioned_not_deprovisioned",
"tests/pa/test_provision.py::TestProvision::test_is_provisioned_not_provisioned",
"tests/pa/test_provision.py::TestProvision::test_provision",
"tests/pa/test_provision.py::TestProvision::test_provision_telemetry_fail",
"tests/pa/test_provision.py::TestProvision::test_provisioning_is_skipped_when_not_enabled"
]
| []
| Apache License 2.0 | 1,924 | [
"azurelinuxagent/pa/provision/default.py",
"azurelinuxagent/common/event.py",
"azurelinuxagent/pa/provision/cloudinit.py"
]
| [
"azurelinuxagent/pa/provision/default.py",
"azurelinuxagent/common/event.py",
"azurelinuxagent/pa/provision/cloudinit.py"
]
|
|
samkohn__larpix-control-67 | 726cfac3948552f082bb645a6f7cdcf7d5c8cfee | 2017-11-29 09:39:51 | eb91fe77d6458a579f2b8ef362cc9e42ca1e89f1 | samkohn: @dadwyer since you proposed this idea I want to make sure you get the chance to look over the changes before I merge them in. | diff --git a/larpix/larpix.py b/larpix/larpix.py
index f1f7684..b337ec6 100644
--- a/larpix/larpix.py
+++ b/larpix/larpix.py
@@ -710,11 +710,31 @@ class Controller(object):
'''
Controls a collection of LArPix Chip objects.
+ Properties and attributes:
+
+ - ``chips``: the ``Chip`` objects that the controller controls
+ - ``all_chip``: all possible ``Chip`` objects (considering there are
+ a finite number of chip IDs), initialized on object construction
+ - ``port``: the path to the serial port, i.e. "/dev/(whatever)"
+ (default: ``'/dev/ttyUSB1'``)
+ - ``timeout``: the timeout used for serial commands, in seconds.
+ This can be changed between calls to the read and write commands.
+ (default: ``1``)
+ - ``reads``: list of all the PacketCollections that have been sent
+ back to this controller. PacketCollections are created by
+ ``run``, ``write_configuration``, and ``read_configuration``, but
+ not by any of the ``serial_*`` methods.
+ - ``use_all_chips``: if ``True``, look up chip objects in
+ ``self.all_chips``, else look up in ``self.chips`` (default:
+ ``False``)
+
'''
start_byte = b'\x73'
stop_byte = b'\x71'
def __init__(self, port='/dev/ttyUSB1'):
self.chips = []
+ self.all_chips = self._init_chips()
+ self.use_all_chips = False
self.reads = []
self.nreads = 0
self.port = port
@@ -723,15 +743,23 @@ class Controller(object):
self.max_write = 8192
self._serial = serial.Serial
- def init_chips(self, nchips = 256, iochain = 0):
- self.chips = [Chip(i, iochain) for i in range(256)]
+ def _init_chips(self, nchips = 256, iochain = 0):
+ '''
+ Return all possible chips.
+
+ '''
+ return [Chip(i, iochain) for i in range(256)]
def get_chip(self, chip_id, io_chain):
- for chip in self.chips:
+ if self.use_all_chips:
+ chip_list = self.all_chips
+ else:
+ chip_list = self.chips
+ for chip in chip_list:
if chip.chip_id == chip_id and chip.io_chain == io_chain:
return chip
- raise ValueError('Could not find chip (%d, %d)' % (chip_id,
- io_chain))
+ raise ValueError('Could not find chip (%d, %d) (using all_chips'
+ '? %s)' % (chip_id, io_chain, self.use_all_chips))
def serial_flush(self):
with self._serial(self.port, baudrate=self.baudrate,
diff --git a/larpix/tasks.py b/larpix/tasks.py
index a01da07..abace8a 100644
--- a/larpix/tasks.py
+++ b/larpix/tasks.py
@@ -58,15 +58,13 @@ def get_chip_ids(**settings):
logger.info('Executing get_chip_ids')
if 'controller' in settings:
controller = settings['controller']
- if not controller.chips:
- controller.init_chips()
else:
controller = larpix.Controller(settings['port'])
- controller.init_chips()
+ controller.use_all_chips = True
stored_timeout = controller.timeout
controller.timeout=0.1
chips = []
- for chip in controller.chips:
+ for chip in controller.all_chips:
controller.read_configuration(chip, 0, timeout=0.1)
if len(chip.reads) == 0:
print('Chip ID %d: Packet lost in black hole. No connection?' %
@@ -81,6 +79,7 @@ def get_chip_ids(**settings):
chips.append(chip)
logger.info('Found chip %s' % chip)
controller.timeout = stored_timeout
+ controller.use_all_chips = False
return chips
def simple_stats(**settings):
| Separate the functionality of "init_chips" (broadcasting) from the list of known actual chips
Controller objects should know which chips actually exist and which are just there for command broadcasting. Proposed revision:
- `controller.chips` is for known chips
- `controller.all_chips` is for all possible chips (i.e. all chip IDs combined with all known daisy chains)
- `controller.init_chips` becomes `controller._init_chips` and is called automatically during initialization to initialize `controller.all_chips` | samkohn/larpix-control | diff --git a/test/test_larpix.py b/test/test_larpix.py
index b22de84..af9e035 100644
--- a/test/test_larpix.py
+++ b/test/test_larpix.py
@@ -1461,9 +1461,8 @@ def test_configuration_from_dict_reg_reset_cycles():
def test_controller_init_chips():
controller = Controller(None)
- controller.init_chips()
- result = list(map(str, controller.chips))
- expected = list(map(str, (Chip(i, 0) for i in range(256))))
+ result = list(map(repr, controller._init_chips()))
+ expected = list(map(repr, (Chip(i, 0) for i in range(256))))
assert result == expected
def test_controller_get_chip():
@@ -1472,6 +1471,13 @@ def test_controller_get_chip():
controller.chips.append(chip)
assert controller.get_chip(1, 3) == chip
+def test_controller_get_chip_all_chips():
+ controller = Controller(None)
+ controller.use_all_chips = True
+ result = controller.get_chip(5, 0)
+ expected = controller.all_chips[5]
+ assert result == expected
+
def test_controller_get_chip_error():
controller = Controller(None)
chip = Chip(1, 3)
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 0,
"test_score": 1
},
"num_modified_files": 2
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": [
"requirements/base.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | bitarray==3.3.0
bitstring==4.3.1
exceptiongroup==1.2.2
iniconfig==2.1.0
-e git+https://github.com/samkohn/larpix-control.git@726cfac3948552f082bb645a6f7cdcf7d5c8cfee#egg=larpix_control
packaging==24.2
pluggy==1.5.0
pyserial==3.5
pytest==8.3.5
tomli==2.2.1
| name: larpix-control
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- bitarray==3.3.0
- bitstring==4.3.1
- exceptiongroup==1.2.2
- iniconfig==2.1.0
- packaging==24.2
- pluggy==1.5.0
- pyserial==3.5
- pytest==8.3.5
- tomli==2.2.1
prefix: /opt/conda/envs/larpix-control
| [
"test/test_larpix.py::test_controller_init_chips",
"test/test_larpix.py::test_controller_get_chip_all_chips"
]
| [
"test/test_larpix.py::test_configuration_set_pixel_trim_thresholds_errors",
"test/test_larpix.py::test_configuration_set_global_threshold_errors",
"test/test_larpix.py::test_configuration_set_csa_gain_errors",
"test/test_larpix.py::test_configuration_set_csa_bypass_errors",
"test/test_larpix.py::test_configuration_set_internal_bypass_errors",
"test/test_larpix.py::test_configuration_set_csa_bypass_select_errors",
"test/test_larpix.py::test_configuration_set_csa_monitor_select_errors",
"test/test_larpix.py::test_configuration_set_csa_testpulse_enable_errors",
"test/test_larpix.py::test_configuration_set_csa_testpulse_dac_amplitude_errors",
"test/test_larpix.py::test_configuration_set_test_mode_errors",
"test/test_larpix.py::test_configuration_set_cross_trigger_mode_errors",
"test/test_larpix.py::test_configuration_set_periodic_reset_errors",
"test/test_larpix.py::test_configuration_set_fifo_diagnostic_errors",
"test/test_larpix.py::test_configuration_set_test_burst_length_errors",
"test/test_larpix.py::test_configuration_set_adc_burst_length_errors",
"test/test_larpix.py::test_configuration_set_channel_mask_errors",
"test/test_larpix.py::test_configuration_set_external_trigger_mask_errors",
"test/test_larpix.py::test_configuration_set_reset_cycles_errors",
"test/test_larpix.py::test_configuration_write_errors",
"test/test_larpix.py::test_controller_get_chip_error",
"test/test_larpix.py::test_controller_format_UART",
"test/test_larpix.py::test_controller_format_bytestream",
"test/test_larpix.py::test_controller_write_configuration",
"test/test_larpix.py::test_controller_write_configuration_one_reg",
"test/test_larpix.py::test_controller_write_configuration_write_read",
"test/test_larpix.py::test_controller_get_configuration_bytestreams",
"test/test_larpix.py::test_controller_parse_input",
"test/test_larpix.py::test_controller_parse_input_dropped_data_byte",
"test/test_larpix.py::test_controller_parse_input_dropped_start_byte",
"test/test_larpix.py::test_controller_parse_input_dropped_stop_byte",
"test/test_larpix.py::test_controller_parse_input_dropped_stopstart_bytes"
]
| [
"test/test_larpix.py::test_FakeSerialPort_write",
"test/test_larpix.py::test_FakeSerialPort_read",
"test/test_larpix.py::test_FakeSerialPort_read_multi",
"test/test_larpix.py::test_chip_str",
"test/test_larpix.py::test_chip_get_configuration_packets",
"test/test_larpix.py::test_chip_sync_configuration",
"test/test_larpix.py::test_chip_export_reads",
"test/test_larpix.py::test_chip_export_reads_no_new_reads",
"test/test_larpix.py::test_chip_export_reads_all",
"test/test_larpix.py::test_controller_save_output",
"test/test_larpix.py::test_controller_load",
"test/test_larpix.py::test_packet_bits_bytes",
"test/test_larpix.py::test_packet_init_default",
"test/test_larpix.py::test_packet_init_bytestream",
"test/test_larpix.py::test_packet_bytes_zeros",
"test/test_larpix.py::test_packet_bytes_custom",
"test/test_larpix.py::test_packet_bytes_properties",
"test/test_larpix.py::test_packet_export_test",
"test/test_larpix.py::test_packet_export_data",
"test/test_larpix.py::test_packet_export_config_read",
"test/test_larpix.py::test_packet_export_config_write",
"test/test_larpix.py::test_packet_set_packet_type",
"test/test_larpix.py::test_packet_get_packet_type",
"test/test_larpix.py::test_packet_set_chipid",
"test/test_larpix.py::test_packet_get_chipid",
"test/test_larpix.py::test_packet_set_parity_bit_value",
"test/test_larpix.py::test_packet_get_parity_bit_value",
"test/test_larpix.py::test_packet_compute_parity",
"test/test_larpix.py::test_packet_assign_parity",
"test/test_larpix.py::test_packet_has_valid_parity",
"test/test_larpix.py::test_packet_set_channel_id",
"test/test_larpix.py::test_packet_get_channel_id",
"test/test_larpix.py::test_packet_set_timestamp",
"test/test_larpix.py::test_packet_get_timestamp",
"test/test_larpix.py::test_packet_set_dataword",
"test/test_larpix.py::test_packet_get_dataword",
"test/test_larpix.py::test_packet_get_dataword_ADC_bug",
"test/test_larpix.py::test_packet_set_fifo_half_flag",
"test/test_larpix.py::test_packet_get_fifo_half_flag",
"test/test_larpix.py::test_packet_set_fifo_full_flag",
"test/test_larpix.py::test_packet_get_fifo_full_flag",
"test/test_larpix.py::test_packet_set_register_address",
"test/test_larpix.py::test_packet_get_register_address",
"test/test_larpix.py::test_packet_set_register_data",
"test/test_larpix.py::test_packet_get_register_data",
"test/test_larpix.py::test_packet_set_test_counter",
"test/test_larpix.py::test_packet_get_test_counter",
"test/test_larpix.py::test_configuration_get_nondefault_registers",
"test/test_larpix.py::test_configuration_get_nondefault_registers_array",
"test/test_larpix.py::test_configuration_get_nondefault_registers_many_changes",
"test/test_larpix.py::test_configuration_set_pixel_trim_thresholds",
"test/test_larpix.py::test_configuration_get_pixel_trim_thresholds",
"test/test_larpix.py::test_configuration_set_global_threshold",
"test/test_larpix.py::test_configuration_get_global_threshold",
"test/test_larpix.py::test_configuration_set_csa_gain",
"test/test_larpix.py::test_configuration_get_csa_gain",
"test/test_larpix.py::test_configuration_set_csa_bypass",
"test/test_larpix.py::test_configuration_get_csa_bypass",
"test/test_larpix.py::test_configuration_set_internal_bypass",
"test/test_larpix.py::test_configuration_get_internal_bypass",
"test/test_larpix.py::test_configuration_set_csa_bypass_select",
"test/test_larpix.py::test_configuration_get_csa_bypass_select",
"test/test_larpix.py::test_configuration_set_csa_monitor_select",
"test/test_larpix.py::test_configuration_get_csa_monitor_select",
"test/test_larpix.py::test_configuration_set_csa_testpulse_enable",
"test/test_larpix.py::test_configuration_get_csa_testpulse_enable",
"test/test_larpix.py::test_configuration_set_csa_testpulse_dac_amplitude",
"test/test_larpix.py::test_configuration_get_csa_testpulse_dac_amplitude",
"test/test_larpix.py::test_configuration_set_test_mode",
"test/test_larpix.py::test_configuration_get_test_mode",
"test/test_larpix.py::test_configuration_set_cross_trigger_mode",
"test/test_larpix.py::test_configuration_get_cross_trigger_mode",
"test/test_larpix.py::test_configuration_set_periodic_reset",
"test/test_larpix.py::test_configuration_get_periodic_reset",
"test/test_larpix.py::test_configuration_set_fifo_diagnostic",
"test/test_larpix.py::test_configuration_get_fifo_diagnostic",
"test/test_larpix.py::test_configuration_set_test_burst_length",
"test/test_larpix.py::test_configuration_get_test_burst_length",
"test/test_larpix.py::test_configuration_set_adc_burst_length",
"test/test_larpix.py::test_configuration_get_adc_burst_length",
"test/test_larpix.py::test_configuration_set_channel_mask",
"test/test_larpix.py::test_configuration_get_channel_mask",
"test/test_larpix.py::test_configuration_set_external_trigger_mask",
"test/test_larpix.py::test_configuration_get_external_trigger_mask",
"test/test_larpix.py::test_configuration_set_reset_cycles",
"test/test_larpix.py::test_configuration_get_reset_cycles",
"test/test_larpix.py::test_configuration_disable_channels",
"test/test_larpix.py::test_configuration_disable_channels_default",
"test/test_larpix.py::test_configuration_enable_channels",
"test/test_larpix.py::test_configuration_enable_channels_default",
"test/test_larpix.py::test_configuration_enable_external_trigger",
"test/test_larpix.py::test_configuration_enable_external_trigger_default",
"test/test_larpix.py::test_configuration_disable_external_trigger",
"test/test_larpix.py::test_configuration_enable_testpulse",
"test/test_larpix.py::test_configuration_enable_testpulse_default",
"test/test_larpix.py::test_configuration_disable_testpulse",
"test/test_larpix.py::test_configuration_disable_testpulse_default",
"test/test_larpix.py::test_configuration_enable_analog_monitor",
"test/test_larpix.py::test_configuration_disable_analog_monitor",
"test/test_larpix.py::test_configuration_trim_threshold_data",
"test/test_larpix.py::test_configuration_global_threshold_data",
"test/test_larpix.py::test_configuration_csa_gain_and_bypasses_data",
"test/test_larpix.py::test_configuration_csa_bypass_select_data",
"test/test_larpix.py::test_configuration_csa_monitor_select_data",
"test/test_larpix.py::test_configuration_csa_testpulse_enable_data",
"test/test_larpix.py::test_configuration_csa_testpulse_dac_amplitude_data",
"test/test_larpix.py::test_configuration_test_mode_xtrig_reset_diag_data",
"test/test_larpix.py::test_configuration_sample_cycles_data",
"test/test_larpix.py::test_configuration_test_burst_length_data",
"test/test_larpix.py::test_configuration_adc_burst_length_data",
"test/test_larpix.py::test_configuration_channel_mask_data",
"test/test_larpix.py::test_configuration_external_trigger_mask_data",
"test/test_larpix.py::test_configuration_reset_cycles_data",
"test/test_larpix.py::test_configuration_to_dict",
"test/test_larpix.py::test_configuration_from_dict",
"test/test_larpix.py::test_configuration_write",
"test/test_larpix.py::test_configuration_write_force",
"test/test_larpix.py::test_configuration_read_absolute",
"test/test_larpix.py::test_configuration_read_default",
"test/test_larpix.py::test_configuration_read_local",
"test/test_larpix.py::test_configuration_from_dict_reg_pixel_trim",
"test/test_larpix.py::test_configuration_from_dict_reg_global_threshold",
"test/test_larpix.py::test_configuration_from_dict_reg_csa_gain",
"test/test_larpix.py::test_configuration_from_dict_reg_csa_bypass",
"test/test_larpix.py::test_configuration_from_dict_reg_internal_bypass",
"test/test_larpix.py::test_configuration_from_dict_reg_csa_bypass_select",
"test/test_larpix.py::test_configuration_from_dict_reg_csa_monitor_select",
"test/test_larpix.py::test_configuration_from_dict_reg_csa_testpulse_enable",
"test/test_larpix.py::test_configuration_from_dict_reg_csa_testpulse_dac_amplitude",
"test/test_larpix.py::test_configuration_from_dict_reg_test_mode",
"test/test_larpix.py::test_configuration_from_dict_reg_cross_trigger_mode",
"test/test_larpix.py::test_configuration_from_dict_reg_periodic_reset",
"test/test_larpix.py::test_configuration_from_dict_reg_fifo_diagnostic",
"test/test_larpix.py::test_configuration_from_dict_reg_sample_cycles",
"test/test_larpix.py::test_configuration_from_dict_reg_test_burst_length",
"test/test_larpix.py::test_configuration_from_dict_reg_adc_burst_length",
"test/test_larpix.py::test_configuration_from_dict_reg_channel_mask",
"test/test_larpix.py::test_configuration_from_dict_reg_external_trigger_mask",
"test/test_larpix.py::test_configuration_from_dict_reg_reset_cycles",
"test/test_larpix.py::test_controller_get_chip",
"test/test_larpix.py::test_controller_serial_read_mock",
"test/test_larpix.py::test_controller_serial_write_mock",
"test/test_larpix.py::test_controller_serial_write_read_mock",
"test/test_larpix.py::test_packetcollection_getitem_int",
"test/test_larpix.py::test_packetcollection_getitem_int_bits",
"test/test_larpix.py::test_packetcollection_getitem_slice",
"test/test_larpix.py::test_packetcollection_getitem_slice_bits",
"test/test_larpix.py::test_packetcollection_origin",
"test/test_larpix.py::test_packetcollection_to_dict",
"test/test_larpix.py::test_packetcollection_from_dict"
]
| []
| null | 1,925 | [
"larpix/larpix.py",
"larpix/tasks.py"
]
| [
"larpix/larpix.py",
"larpix/tasks.py"
]
|
samkohn__larpix-control-68 | c015c00b1f83d2b36fefe0bba5d9cfdd167792e3 | 2017-11-29 10:12:26 | eb91fe77d6458a579f2b8ef362cc9e42ca1e89f1 | diff --git a/larpix/larpix.py b/larpix/larpix.py
index b41ce5e..f1f7684 100644
--- a/larpix/larpix.py
+++ b/larpix/larpix.py
@@ -174,14 +174,14 @@ class Configuration(object):
}
# These registers store 32 bits over 4 registers each, and those
# 32 bits correspond to entries in a 32-entry list.
- complex_array_spec = [
+ self._complex_array_spec = [
(range(34, 38), 'csa_bypass_select'),
(range(38, 42), 'csa_monitor_select'),
(range(42, 46), 'csa_testpulse_enable'),
(range(52, 56), 'channel_mask'),
(range(56, 60), 'external_trigger_mask')]
self._complex_array = {}
- for addresses, label in complex_array_spec:
+ for addresses, label in self._complex_array_spec:
for i, address in enumerate(addresses):
self._complex_array[address] = (label, i)
# These registers each correspond to an entry in an array
@@ -202,6 +202,19 @@ class Configuration(object):
for register_name in self.register_names:
if getattr(self, register_name) != getattr(default_config, register_name):
d[register_name] = getattr(self, register_name)
+ # Attempt to simplify some of the long values (array values)
+ for (name, value) in d.items():
+ if (name in (label for _, label in self._complex_array_spec)
+ or name == 'pixel_trim_thresholds'):
+ different_values = []
+ for ch, (val, default_val) in enumerate(zip(value, getattr(
+ default_config, name))):
+ if val != default_val:
+ different_values.append({'channel': ch, 'value': val})
+ if len(different_values) < 5:
+ d[name] = different_values
+ else:
+ pass
return d
@property
| Configuration.get_nondefault_registers() is too verbose for arrays
It should only return array entries that are different from the default. There are some decisions to be made about how to represent that in the dict, and when/whether to conclude that enough entries are different that the whole array should be shown anyway | samkohn/larpix-control | diff --git a/test/test_larpix.py b/test/test_larpix.py
index f505c2f..b22de84 100644
--- a/test/test_larpix.py
+++ b/test/test_larpix.py
@@ -528,6 +528,27 @@ def test_configuration_get_nondefault_registers():
expected['adc_burst_length'] = c.adc_burst_length
assert c.get_nondefault_registers() == expected
+def test_configuration_get_nondefault_registers_array():
+ c = Configuration()
+ c.channel_mask[1] = 1
+ c.channel_mask[5] = 1
+ result = c.get_nondefault_registers()
+ expected = {
+ 'channel_mask': [
+ { 'channel': 1, 'value': 1 },
+ { 'channel': 5, 'value': 1 }
+ ]
+ }
+ assert result == expected
+
+def test_configuration_get_nondefault_registers_many_changes():
+ c = Configuration()
+ c.channel_mask[:20] = [1]*20
+ result = c.get_nondefault_registers()
+ expected = { 'channel_mask': [1]*20 + [0]*12 }
+ assert result == expected
+
+
def test_configuration_set_pixel_trim_thresholds():
c = Configuration()
expected = [0x05] * Chip.num_channels
| {
"commit_name": "head_commit",
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 2,
"test_score": 0
},
"num_modified_files": 1
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": null,
"pre_install": null,
"python": "3.9",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | bitarray==3.3.0
bitstring==4.3.1
exceptiongroup==1.2.2
iniconfig==2.1.0
-e git+https://github.com/samkohn/larpix-control.git@c015c00b1f83d2b36fefe0bba5d9cfdd167792e3#egg=larpix_control
packaging==24.2
pluggy==1.5.0
pyserial==3.5
pytest==8.3.5
tomli==2.2.1
| name: larpix-control
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- bitarray==3.3.0
- bitstring==4.3.1
- exceptiongroup==1.2.2
- iniconfig==2.1.0
- packaging==24.2
- pluggy==1.5.0
- pyserial==3.5
- pytest==8.3.5
- tomli==2.2.1
prefix: /opt/conda/envs/larpix-control
| [
"test/test_larpix.py::test_configuration_get_nondefault_registers_array"
]
| [
"test/test_larpix.py::test_configuration_set_pixel_trim_thresholds_errors",
"test/test_larpix.py::test_configuration_set_global_threshold_errors",
"test/test_larpix.py::test_configuration_set_csa_gain_errors",
"test/test_larpix.py::test_configuration_set_csa_bypass_errors",
"test/test_larpix.py::test_configuration_set_internal_bypass_errors",
"test/test_larpix.py::test_configuration_set_csa_bypass_select_errors",
"test/test_larpix.py::test_configuration_set_csa_monitor_select_errors",
"test/test_larpix.py::test_configuration_set_csa_testpulse_enable_errors",
"test/test_larpix.py::test_configuration_set_csa_testpulse_dac_amplitude_errors",
"test/test_larpix.py::test_configuration_set_test_mode_errors",
"test/test_larpix.py::test_configuration_set_cross_trigger_mode_errors",
"test/test_larpix.py::test_configuration_set_periodic_reset_errors",
"test/test_larpix.py::test_configuration_set_fifo_diagnostic_errors",
"test/test_larpix.py::test_configuration_set_test_burst_length_errors",
"test/test_larpix.py::test_configuration_set_adc_burst_length_errors",
"test/test_larpix.py::test_configuration_set_channel_mask_errors",
"test/test_larpix.py::test_configuration_set_external_trigger_mask_errors",
"test/test_larpix.py::test_configuration_set_reset_cycles_errors",
"test/test_larpix.py::test_configuration_write_errors",
"test/test_larpix.py::test_controller_get_chip_error",
"test/test_larpix.py::test_controller_format_UART",
"test/test_larpix.py::test_controller_format_bytestream",
"test/test_larpix.py::test_controller_write_configuration",
"test/test_larpix.py::test_controller_write_configuration_one_reg",
"test/test_larpix.py::test_controller_write_configuration_write_read",
"test/test_larpix.py::test_controller_get_configuration_bytestreams",
"test/test_larpix.py::test_controller_parse_input",
"test/test_larpix.py::test_controller_parse_input_dropped_data_byte",
"test/test_larpix.py::test_controller_parse_input_dropped_start_byte",
"test/test_larpix.py::test_controller_parse_input_dropped_stop_byte",
"test/test_larpix.py::test_controller_parse_input_dropped_stopstart_bytes"
]
| [
"test/test_larpix.py::test_FakeSerialPort_write",
"test/test_larpix.py::test_FakeSerialPort_read",
"test/test_larpix.py::test_FakeSerialPort_read_multi",
"test/test_larpix.py::test_chip_str",
"test/test_larpix.py::test_chip_get_configuration_packets",
"test/test_larpix.py::test_chip_sync_configuration",
"test/test_larpix.py::test_chip_export_reads",
"test/test_larpix.py::test_chip_export_reads_no_new_reads",
"test/test_larpix.py::test_chip_export_reads_all",
"test/test_larpix.py::test_controller_save_output",
"test/test_larpix.py::test_controller_load",
"test/test_larpix.py::test_packet_bits_bytes",
"test/test_larpix.py::test_packet_init_default",
"test/test_larpix.py::test_packet_init_bytestream",
"test/test_larpix.py::test_packet_bytes_zeros",
"test/test_larpix.py::test_packet_bytes_custom",
"test/test_larpix.py::test_packet_bytes_properties",
"test/test_larpix.py::test_packet_export_test",
"test/test_larpix.py::test_packet_export_data",
"test/test_larpix.py::test_packet_export_config_read",
"test/test_larpix.py::test_packet_export_config_write",
"test/test_larpix.py::test_packet_set_packet_type",
"test/test_larpix.py::test_packet_get_packet_type",
"test/test_larpix.py::test_packet_set_chipid",
"test/test_larpix.py::test_packet_get_chipid",
"test/test_larpix.py::test_packet_set_parity_bit_value",
"test/test_larpix.py::test_packet_get_parity_bit_value",
"test/test_larpix.py::test_packet_compute_parity",
"test/test_larpix.py::test_packet_assign_parity",
"test/test_larpix.py::test_packet_has_valid_parity",
"test/test_larpix.py::test_packet_set_channel_id",
"test/test_larpix.py::test_packet_get_channel_id",
"test/test_larpix.py::test_packet_set_timestamp",
"test/test_larpix.py::test_packet_get_timestamp",
"test/test_larpix.py::test_packet_set_dataword",
"test/test_larpix.py::test_packet_get_dataword",
"test/test_larpix.py::test_packet_get_dataword_ADC_bug",
"test/test_larpix.py::test_packet_set_fifo_half_flag",
"test/test_larpix.py::test_packet_get_fifo_half_flag",
"test/test_larpix.py::test_packet_set_fifo_full_flag",
"test/test_larpix.py::test_packet_get_fifo_full_flag",
"test/test_larpix.py::test_packet_set_register_address",
"test/test_larpix.py::test_packet_get_register_address",
"test/test_larpix.py::test_packet_set_register_data",
"test/test_larpix.py::test_packet_get_register_data",
"test/test_larpix.py::test_packet_set_test_counter",
"test/test_larpix.py::test_packet_get_test_counter",
"test/test_larpix.py::test_configuration_get_nondefault_registers",
"test/test_larpix.py::test_configuration_get_nondefault_registers_many_changes",
"test/test_larpix.py::test_configuration_set_pixel_trim_thresholds",
"test/test_larpix.py::test_configuration_get_pixel_trim_thresholds",
"test/test_larpix.py::test_configuration_set_global_threshold",
"test/test_larpix.py::test_configuration_get_global_threshold",
"test/test_larpix.py::test_configuration_set_csa_gain",
"test/test_larpix.py::test_configuration_get_csa_gain",
"test/test_larpix.py::test_configuration_set_csa_bypass",
"test/test_larpix.py::test_configuration_get_csa_bypass",
"test/test_larpix.py::test_configuration_set_internal_bypass",
"test/test_larpix.py::test_configuration_get_internal_bypass",
"test/test_larpix.py::test_configuration_set_csa_bypass_select",
"test/test_larpix.py::test_configuration_get_csa_bypass_select",
"test/test_larpix.py::test_configuration_set_csa_monitor_select",
"test/test_larpix.py::test_configuration_get_csa_monitor_select",
"test/test_larpix.py::test_configuration_set_csa_testpulse_enable",
"test/test_larpix.py::test_configuration_get_csa_testpulse_enable",
"test/test_larpix.py::test_configuration_set_csa_testpulse_dac_amplitude",
"test/test_larpix.py::test_configuration_get_csa_testpulse_dac_amplitude",
"test/test_larpix.py::test_configuration_set_test_mode",
"test/test_larpix.py::test_configuration_get_test_mode",
"test/test_larpix.py::test_configuration_set_cross_trigger_mode",
"test/test_larpix.py::test_configuration_get_cross_trigger_mode",
"test/test_larpix.py::test_configuration_set_periodic_reset",
"test/test_larpix.py::test_configuration_get_periodic_reset",
"test/test_larpix.py::test_configuration_set_fifo_diagnostic",
"test/test_larpix.py::test_configuration_get_fifo_diagnostic",
"test/test_larpix.py::test_configuration_set_test_burst_length",
"test/test_larpix.py::test_configuration_get_test_burst_length",
"test/test_larpix.py::test_configuration_set_adc_burst_length",
"test/test_larpix.py::test_configuration_get_adc_burst_length",
"test/test_larpix.py::test_configuration_set_channel_mask",
"test/test_larpix.py::test_configuration_get_channel_mask",
"test/test_larpix.py::test_configuration_set_external_trigger_mask",
"test/test_larpix.py::test_configuration_get_external_trigger_mask",
"test/test_larpix.py::test_configuration_set_reset_cycles",
"test/test_larpix.py::test_configuration_get_reset_cycles",
"test/test_larpix.py::test_configuration_disable_channels",
"test/test_larpix.py::test_configuration_disable_channels_default",
"test/test_larpix.py::test_configuration_enable_channels",
"test/test_larpix.py::test_configuration_enable_channels_default",
"test/test_larpix.py::test_configuration_enable_external_trigger",
"test/test_larpix.py::test_configuration_enable_external_trigger_default",
"test/test_larpix.py::test_configuration_disable_external_trigger",
"test/test_larpix.py::test_configuration_enable_testpulse",
"test/test_larpix.py::test_configuration_enable_testpulse_default",
"test/test_larpix.py::test_configuration_disable_testpulse",
"test/test_larpix.py::test_configuration_disable_testpulse_default",
"test/test_larpix.py::test_configuration_enable_analog_monitor",
"test/test_larpix.py::test_configuration_disable_analog_monitor",
"test/test_larpix.py::test_configuration_trim_threshold_data",
"test/test_larpix.py::test_configuration_global_threshold_data",
"test/test_larpix.py::test_configuration_csa_gain_and_bypasses_data",
"test/test_larpix.py::test_configuration_csa_bypass_select_data",
"test/test_larpix.py::test_configuration_csa_monitor_select_data",
"test/test_larpix.py::test_configuration_csa_testpulse_enable_data",
"test/test_larpix.py::test_configuration_csa_testpulse_dac_amplitude_data",
"test/test_larpix.py::test_configuration_test_mode_xtrig_reset_diag_data",
"test/test_larpix.py::test_configuration_sample_cycles_data",
"test/test_larpix.py::test_configuration_test_burst_length_data",
"test/test_larpix.py::test_configuration_adc_burst_length_data",
"test/test_larpix.py::test_configuration_channel_mask_data",
"test/test_larpix.py::test_configuration_external_trigger_mask_data",
"test/test_larpix.py::test_configuration_reset_cycles_data",
"test/test_larpix.py::test_configuration_to_dict",
"test/test_larpix.py::test_configuration_from_dict",
"test/test_larpix.py::test_configuration_write",
"test/test_larpix.py::test_configuration_write_force",
"test/test_larpix.py::test_configuration_read_absolute",
"test/test_larpix.py::test_configuration_read_default",
"test/test_larpix.py::test_configuration_read_local",
"test/test_larpix.py::test_configuration_from_dict_reg_pixel_trim",
"test/test_larpix.py::test_configuration_from_dict_reg_global_threshold",
"test/test_larpix.py::test_configuration_from_dict_reg_csa_gain",
"test/test_larpix.py::test_configuration_from_dict_reg_csa_bypass",
"test/test_larpix.py::test_configuration_from_dict_reg_internal_bypass",
"test/test_larpix.py::test_configuration_from_dict_reg_csa_bypass_select",
"test/test_larpix.py::test_configuration_from_dict_reg_csa_monitor_select",
"test/test_larpix.py::test_configuration_from_dict_reg_csa_testpulse_enable",
"test/test_larpix.py::test_configuration_from_dict_reg_csa_testpulse_dac_amplitude",
"test/test_larpix.py::test_configuration_from_dict_reg_test_mode",
"test/test_larpix.py::test_configuration_from_dict_reg_cross_trigger_mode",
"test/test_larpix.py::test_configuration_from_dict_reg_periodic_reset",
"test/test_larpix.py::test_configuration_from_dict_reg_fifo_diagnostic",
"test/test_larpix.py::test_configuration_from_dict_reg_sample_cycles",
"test/test_larpix.py::test_configuration_from_dict_reg_test_burst_length",
"test/test_larpix.py::test_configuration_from_dict_reg_adc_burst_length",
"test/test_larpix.py::test_configuration_from_dict_reg_channel_mask",
"test/test_larpix.py::test_configuration_from_dict_reg_external_trigger_mask",
"test/test_larpix.py::test_configuration_from_dict_reg_reset_cycles",
"test/test_larpix.py::test_controller_init_chips",
"test/test_larpix.py::test_controller_get_chip",
"test/test_larpix.py::test_controller_serial_read_mock",
"test/test_larpix.py::test_controller_serial_write_mock",
"test/test_larpix.py::test_controller_serial_write_read_mock",
"test/test_larpix.py::test_packetcollection_getitem_int",
"test/test_larpix.py::test_packetcollection_getitem_int_bits",
"test/test_larpix.py::test_packetcollection_getitem_slice",
"test/test_larpix.py::test_packetcollection_getitem_slice_bits",
"test/test_larpix.py::test_packetcollection_origin",
"test/test_larpix.py::test_packetcollection_to_dict",
"test/test_larpix.py::test_packetcollection_from_dict"
]
| []
| null | 1,926 | [
"larpix/larpix.py"
]
| [
"larpix/larpix.py"
]
|
|
borgbackup__borg-3397 | 1cf6e1e1030655946e487337cc855fa2d1137907 | 2017-11-29 16:01:05 | a439fa3e720c8bb2a82496768ffcce282fb7f7b7 | diff --git a/docs/3rd_party/README b/docs/3rd_party/README
new file mode 100644
index 00000000..1f7b9b6a
--- /dev/null
+++ b/docs/3rd_party/README
@@ -0,0 +1,5 @@
+Here we store 3rd party documentation, licenses, etc.
+
+Please note that all files inside the "borg" package directory (except the
+stuff excluded in setup.py) will be INSTALLED, so don't keep docs or licenses
+there.
diff --git a/src/borg/algorithms/blake2/COPYING b/docs/3rd_party/blake2/COPYING
similarity index 100%
rename from src/borg/algorithms/blake2/COPYING
rename to docs/3rd_party/blake2/COPYING
diff --git a/src/borg/algorithms/blake2/README.md b/docs/3rd_party/blake2/README.md
similarity index 100%
rename from src/borg/algorithms/blake2/README.md
rename to docs/3rd_party/blake2/README.md
diff --git a/src/borg/algorithms/crc32_slice_by_8.c b/src/borg/algorithms/crc32_slice_by_8.c
index b289fbb8..3ab0c840 100644
--- a/src/borg/algorithms/crc32_slice_by_8.c
+++ b/src/borg/algorithms/crc32_slice_by_8.c
@@ -332,14 +332,12 @@ uint32_t crc32_slice_by_8(const void* data, size_t length, uint32_t previousCrc3
uint32_t crc = ~previousCrc32; // same as previousCrc32 ^ 0xFFFFFFFF
const uint32_t* current;
- const uint8_t* currentChar;
+ const uint8_t* currentChar = (const uint8_t*) data;
// enabling optimization (at least -O2) automatically unrolls the inner for-loop
const size_t Unroll = 4;
const size_t BytesAtOnce = 8 * Unroll;
- currentChar = (const uint8_t*) data;
-
// wanted: 32 bit / 4 Byte alignment, compute leading, unaligned bytes length
uintptr_t unaligned_length = (4 - (((uintptr_t) currentChar) & 3)) & 3;
// process unaligned bytes, if any (standard algorithm)
diff --git a/src/borg/archiver.py b/src/borg/archiver.py
index a14d4af5..887cb772 100644
--- a/src/borg/archiver.py
+++ b/src/borg/archiver.py
@@ -3806,6 +3806,7 @@ def get_args(self, argv, cmd):
return forced_result
# we only take specific options from the forced "borg serve" command:
result.restrict_to_paths = forced_result.restrict_to_paths
+ result.restrict_to_repositories = forced_result.restrict_to_repositories
result.append_only = forced_result.append_only
return result
diff --git a/src/borg/fuse.py b/src/borg/fuse.py
index 52ed1ad6..a85684a0 100644
--- a/src/borg/fuse.py
+++ b/src/borg/fuse.py
@@ -362,7 +362,7 @@ def make_versioned_name(name, version, add_dir=False):
return name + version_enc + ext
if 'source' in item and hardlinkable(item.mode):
- source = os.path.join(*item.source.split(os.sep)[stripped_components:])
+ source = os.sep.join(item.source.split(os.sep)[stripped_components:])
chunks, link_target = hardlink_masters.get(item.source, (None, source))
if link_target:
# Hard link was extracted previously, just link
| port last-minute changes of 1.1.3 to master
https://github.com/borgbackup/borg/pull/3391/commits | borgbackup/borg | diff --git a/src/borg/testsuite/archiver.py b/src/borg/testsuite/archiver.py
index a25cb5de..910b5372 100644
--- a/src/borg/testsuite/archiver.py
+++ b/src/borg/testsuite/archiver.py
@@ -3546,10 +3546,22 @@ def test_get_args():
assert args.restrict_to_paths == ['/p1', '/p2']
assert args.umask == 0o027
assert args.log_level == 'info'
+ # similar, but with --restrict-to-repository
+ args = archiver.get_args(['borg', 'serve', '--restrict-to-repository=/r1', '--restrict-to-repository=/r2', ],
+ 'borg serve --info --umask=0027')
+ assert args.restrict_to_repositories == ['/r1', '/r2']
# trying to cheat - break out of path restriction
args = archiver.get_args(['borg', 'serve', '--restrict-to-path=/p1', '--restrict-to-path=/p2', ],
'borg serve --restrict-to-path=/')
assert args.restrict_to_paths == ['/p1', '/p2']
+ # trying to cheat - break out of repository restriction
+ args = archiver.get_args(['borg', 'serve', '--restrict-to-repository=/r1', '--restrict-to-repository=/r2', ],
+ 'borg serve --restrict-to-repository=/')
+ assert args.restrict_to_repositories == ['/r1', '/r2']
+ # trying to cheat - break below repository restriction
+ args = archiver.get_args(['borg', 'serve', '--restrict-to-repository=/r1', '--restrict-to-repository=/r2', ],
+ 'borg serve --restrict-to-repository=/r1/below')
+ assert args.restrict_to_repositories == ['/r1', '/r2']
# trying to cheat - try to execute different subcommand
args = archiver.get_args(['borg', 'serve', '--restrict-to-path=/p1', '--restrict-to-path=/p2', ],
'borg init --encryption=repokey /')
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_added_files",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 3,
"test_score": 3
},
"num_modified_files": 3
} | 1.1 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-xdist",
"pytest-cov"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc libacl1-dev libacl1 libssl-dev liblz4-dev libzstd-dev build-essential pkg-config python3-pkgconfig"
],
"python": "3.9",
"reqs_path": [
"requirements.d/development.txt",
"requirements.d/docs.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | alabaster==0.7.16
babel==2.17.0
-e git+https://github.com/borgbackup/borg.git@1cf6e1e1030655946e487337cc855fa2d1137907#egg=borgbackup
cachetools==5.5.2
certifi==2025.1.31
chardet==5.2.0
charset-normalizer==3.4.1
colorama==0.4.6
coverage==7.8.0
Cython==3.0.12
distlib==0.3.9
docutils==0.21.2
exceptiongroup==1.2.2
execnet==2.1.1
filelock==3.18.0
guzzle_sphinx_theme==0.7.11
idna==3.10
imagesize==1.4.1
importlib_metadata==8.6.1
iniconfig==2.1.0
Jinja2==3.1.6
MarkupSafe==3.0.2
msgpack-python==0.5.6
packaging==24.2
platformdirs==4.3.7
pluggy==1.5.0
py-cpuinfo==9.0.0
Pygments==2.19.1
pyproject-api==1.9.0
pytest==8.3.5
pytest-benchmark==5.1.0
pytest-cov==6.0.0
pytest-xdist==3.6.1
pyzmq==26.3.0
requests==2.32.3
setuptools-scm==8.2.0
snowballstemmer==2.2.0
Sphinx==7.4.7
sphinxcontrib-applehelp==2.0.0
sphinxcontrib-devhelp==2.0.0
sphinxcontrib-htmlhelp==2.1.0
sphinxcontrib-jsmath==1.0.1
sphinxcontrib-qthelp==2.0.0
sphinxcontrib-serializinghtml==2.0.0
tomli==2.2.1
tox==4.25.0
typing_extensions==4.13.0
urllib3==2.3.0
virtualenv==20.29.3
zipp==3.21.0
| name: borg
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- alabaster==0.7.16
- babel==2.17.0
- cachetools==5.5.2
- certifi==2025.1.31
- chardet==5.2.0
- charset-normalizer==3.4.1
- colorama==0.4.6
- coverage==7.8.0
- cython==3.0.12
- distlib==0.3.9
- docutils==0.21.2
- exceptiongroup==1.2.2
- execnet==2.1.1
- filelock==3.18.0
- guzzle-sphinx-theme==0.7.11
- idna==3.10
- imagesize==1.4.1
- importlib-metadata==8.6.1
- iniconfig==2.1.0
- jinja2==3.1.6
- markupsafe==3.0.2
- msgpack-python==0.5.6
- packaging==24.2
- platformdirs==4.3.7
- pluggy==1.5.0
- py-cpuinfo==9.0.0
- pygments==2.19.1
- pyproject-api==1.9.0
- pytest==8.3.5
- pytest-benchmark==5.1.0
- pytest-cov==6.0.0
- pytest-xdist==3.6.1
- pyzmq==26.3.0
- requests==2.32.3
- setuptools-scm==8.2.0
- snowballstemmer==2.2.0
- sphinx==7.4.7
- sphinxcontrib-applehelp==2.0.0
- sphinxcontrib-devhelp==2.0.0
- sphinxcontrib-htmlhelp==2.1.0
- sphinxcontrib-jsmath==1.0.1
- sphinxcontrib-qthelp==2.0.0
- sphinxcontrib-serializinghtml==2.0.0
- tomli==2.2.1
- tox==4.25.0
- typing-extensions==4.13.0
- urllib3==2.3.0
- virtualenv==20.29.3
- zipp==3.21.0
prefix: /opt/conda/envs/borg
| [
"src/borg/testsuite/archiver.py::test_get_args"
]
| [
"src/borg/testsuite/archiver.py::test_return_codes[python]",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_common_options",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_auto_compressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_auto_uncompressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_lz4_compressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_lzma_compressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_none_compressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_none_uncompressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_zlib_compressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_config",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_corrupted_repository",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_json",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_no_cache_sync",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_stdin",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_debug_dump_archive",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_debug_dump_manifest",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_debug_info",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_debug_refcount_obj",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_delete_multiple",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_detect_attic_repo",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_info_json",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_list_json",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_list_repository_format",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_list_size",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_log_json",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_rechunkify",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_recompress",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_target",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_check_usage",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_corrupted_manifest",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_manifest_rebuild_corrupted_chunk",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_missing_file_chunk",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_missing_manifest",
"src/borg/testsuite/archiver.py::ManifestAuthenticationTest::test_disable",
"src/borg/testsuite/archiver.py::ManifestAuthenticationTest::test_disable2",
"src/borg/testsuite/archiver.py::ManifestAuthenticationTest::test_not_required",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_common_options",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_auto_compressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_auto_uncompressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_lz4_compressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_lz4_uncompressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_lzma_compressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_lzma_uncompressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_none_compressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_none_uncompressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_zlib_compressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_zlib_uncompressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_json",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_no_cache_sync",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_stdin",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_debug_dump_archive",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_debug_dump_manifest",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_debug_info",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_debug_refcount_obj",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_delete_force",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_delete_multiple",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_detect_attic_repo",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_info_json",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_init_nested_repositories",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_list_json",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_list_repository_format",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_list_size",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_rechunkify",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_recompress",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_target",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_remote_repo_restrict_to_path",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_remote_repo_restrict_to_repository",
"src/borg/testsuite/archiver.py::ArchiverCorruptionTestCase::test_cache_chunks",
"src/borg/testsuite/archiver.py::ArchiverCorruptionTestCase::test_cache_files",
"src/borg/testsuite/archiver.py::ArchiverCorruptionTestCase::test_chunks_archive",
"src/borg/testsuite/archiver.py::ArchiverCorruptionTestCase::test_old_version_interfered",
"src/borg/testsuite/archiver.py::DiffArchiverTestCase::test_sort_option"
]
| [
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_aes_counter_uniqueness_keyfile",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_aes_counter_uniqueness_passphrase",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_atime",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_bad_filters",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_basic_functionality",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_benchmark_crud",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_break_lock",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_change_passphrase",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_check_cache",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_comment",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_lz4_uncompressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_lzma_uncompressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_zlib_uncompressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_dry_run",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_pattern",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_pattern_exclude_folder_but_recurse",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_pattern_exclude_folder_no_recurse",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_pattern_file",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_pattern_intermediate_folders_first",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_pattern_root",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_read_special_broken_symlink",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_topical",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_without_root",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_debug_dump_archive_items",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_debug_dump_repo_objs",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_debug_profile",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_debug_put_get_delete_obj",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_delete",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_delete_double_force",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_delete_force",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_delete_repo",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_exclude_caches",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_exclude_keep_tagged",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_exclude_keep_tagged_deprecation",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_exclude_normalization",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_exclude_tagged",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_export_tar",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_export_tar_gz",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_export_tar_strip_components",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_export_tar_strip_components_links",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_extract_hardlinks",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_extract_include_exclude",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_extract_include_exclude_regex",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_extract_include_exclude_regex_from_file",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_extract_list_output",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_extract_pattern_opt",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_extract_progress",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_extract_with_pattern",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_file_status",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_file_status_cs_cache_mode",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_file_status_excluded",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_file_status_ms_cache_mode",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_file_status_rc_cache_mode",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_help",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_info",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_init_interrupt",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_init_nested_repositories",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_init_requires_encryption_option",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_key_export_keyfile",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_key_export_paperkey",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_key_export_qr",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_key_export_repokey",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_key_import_errors",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_key_import_paperkey",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_list_chunk_counts",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_list_format",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_list_hash",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_list_json_args",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_list_prefix",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_overwrite",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_path_normalization",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_progress_off",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_progress_on",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_prune_repository",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_prune_repository_glob",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_prune_repository_prefix",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_prune_repository_save_space",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_basic",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_dry_run",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_exclude_caches",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_exclude_keep_tagged",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_exclude_tagged",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_list_output",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_skips_nothing_to_do",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_subtree_hardlinks",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_target_rc",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_rename",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_repeated_files",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_repository_move",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_repository_swap_detection",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_repository_swap_detection2",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_repository_swap_detection2_no_cache",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_repository_swap_detection_no_cache",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_repository_swap_detection_repokey_blank_passphrase",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_security_dir_compat",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_sparse_file",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_strip_components",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_symlink_extract",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_umask",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unix_socket",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unknown_feature_on_cache_sync",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unknown_feature_on_change_passphrase",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unknown_feature_on_create",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unknown_feature_on_delete",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unknown_feature_on_read",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unknown_feature_on_rename",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unknown_mandatory_feature_in_cache",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unknown_unencrypted",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unusual_filenames",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_usage",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_with_lock",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_attic013_acl_bug",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_empty_repository",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_extra_chunks",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_manifest_rebuild_duplicate_archive",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_missing_archive_item_chunk",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_missing_archive_metadata",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_verify_data",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_verify_data_unencrypted",
"src/borg/testsuite/archiver.py::ManifestAuthenticationTest::test_fresh_init_tam_required",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_aes_counter_uniqueness_keyfile",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_aes_counter_uniqueness_passphrase",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_atime",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_bad_filters",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_basic_functionality",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_benchmark_crud",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_break_lock",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_change_passphrase",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_check_cache",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_comment",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_corrupted_repository",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_dry_run",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_pattern",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_pattern_exclude_folder_but_recurse",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_pattern_exclude_folder_no_recurse",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_pattern_file",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_pattern_intermediate_folders_first",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_pattern_root",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_read_special_broken_symlink",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_topical",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_without_root",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_debug_dump_archive_items",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_debug_dump_repo_objs",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_debug_profile",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_delete",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_delete_double_force",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_delete_repo",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_exclude_caches",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_exclude_keep_tagged",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_exclude_keep_tagged_deprecation",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_exclude_normalization",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_exclude_tagged",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_export_tar",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_export_tar_gz",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_export_tar_strip_components",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_export_tar_strip_components_links",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_extract_hardlinks",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_extract_include_exclude",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_extract_include_exclude_regex",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_extract_include_exclude_regex_from_file",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_extract_list_output",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_extract_pattern_opt",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_extract_progress",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_extract_with_pattern",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_file_status",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_file_status_cs_cache_mode",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_file_status_excluded",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_file_status_ms_cache_mode",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_file_status_rc_cache_mode",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_help",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_info",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_init_interrupt",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_init_requires_encryption_option",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_key_export_keyfile",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_key_export_paperkey",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_key_export_qr",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_key_export_repokey",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_key_import_errors",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_key_import_paperkey",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_list_chunk_counts",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_list_format",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_list_hash",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_list_json_args",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_list_prefix",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_log_json",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_overwrite",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_path_normalization",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_progress_off",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_progress_on",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_prune_repository",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_prune_repository_glob",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_prune_repository_prefix",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_prune_repository_save_space",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_basic",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_dry_run",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_exclude_caches",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_exclude_keep_tagged",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_exclude_tagged",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_list_output",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_skips_nothing_to_do",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_subtree_hardlinks",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_target_rc",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_rename",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_repeated_files",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_repository_move",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_repository_swap_detection",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_repository_swap_detection2",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_repository_swap_detection2_no_cache",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_repository_swap_detection_no_cache",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_repository_swap_detection_repokey_blank_passphrase",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_security_dir_compat",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_sparse_file",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_strip_components",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_strip_components_doesnt_leak",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_symlink_extract",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_umask",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unix_socket",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unknown_feature_on_cache_sync",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unknown_feature_on_change_passphrase",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unknown_feature_on_create",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unknown_feature_on_delete",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unknown_feature_on_read",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unknown_feature_on_rename",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unknown_mandatory_feature_in_cache",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unknown_unencrypted",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unusual_filenames",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_usage",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_with_lock",
"src/borg/testsuite/archiver.py::DiffArchiverTestCase::test_basic_functionality",
"src/borg/testsuite/archiver.py::test_chunk_content_equal",
"src/borg/testsuite/archiver.py::TestBuildFilter::test_basic",
"src/borg/testsuite/archiver.py::TestBuildFilter::test_empty",
"src/borg/testsuite/archiver.py::TestBuildFilter::test_strip_components",
"src/borg/testsuite/archiver.py::TestCommonOptions::test_simple",
"src/borg/testsuite/archiver.py::TestCommonOptions::test_flag_position_independence[-p-progress-True-before]",
"src/borg/testsuite/archiver.py::TestCommonOptions::test_flag_position_independence[-p-progress-True-after]",
"src/borg/testsuite/archiver.py::TestCommonOptions::test_flag_position_independence[-p-progress-True-both]",
"src/borg/testsuite/archiver.py::TestCommonOptions::test_flag_position_independence[--lock-wait=3-lock_wait-3-before]",
"src/borg/testsuite/archiver.py::TestCommonOptions::test_flag_position_independence[--lock-wait=3-lock_wait-3-after]",
"src/borg/testsuite/archiver.py::TestCommonOptions::test_flag_position_independence[--lock-wait=3-lock_wait-3-both]",
"src/borg/testsuite/archiver.py::test_parse_storage_quota",
"src/borg/testsuite/archiver.py::test_help_formatting[benchmark",
"src/borg/testsuite/archiver.py::test_help_formatting[benchmark-parser1]",
"src/borg/testsuite/archiver.py::test_help_formatting[borgfs-parser2]",
"src/borg/testsuite/archiver.py::test_help_formatting[break-lock-parser3]",
"src/borg/testsuite/archiver.py::test_help_formatting[change-passphrase-parser4]",
"src/borg/testsuite/archiver.py::test_help_formatting[check-parser5]",
"src/borg/testsuite/archiver.py::test_help_formatting[config-parser6]",
"src/borg/testsuite/archiver.py::test_help_formatting[create-parser7]",
"src/borg/testsuite/archiver.py::test_help_formatting[debug",
"src/borg/testsuite/archiver.py::test_help_formatting[debug-parser18]",
"src/borg/testsuite/archiver.py::test_help_formatting[delete-parser19]",
"src/borg/testsuite/archiver.py::test_help_formatting[diff-parser20]",
"src/borg/testsuite/archiver.py::test_help_formatting[export-tar-parser21]",
"src/borg/testsuite/archiver.py::test_help_formatting[extract-parser22]",
"src/borg/testsuite/archiver.py::test_help_formatting[help-parser23]",
"src/borg/testsuite/archiver.py::test_help_formatting[info-parser24]",
"src/borg/testsuite/archiver.py::test_help_formatting[init-parser25]",
"src/borg/testsuite/archiver.py::test_help_formatting[key",
"src/borg/testsuite/archiver.py::test_help_formatting[key-parser30]",
"src/borg/testsuite/archiver.py::test_help_formatting[list-parser31]",
"src/borg/testsuite/archiver.py::test_help_formatting[mount-parser32]",
"src/borg/testsuite/archiver.py::test_help_formatting[prune-parser33]",
"src/borg/testsuite/archiver.py::test_help_formatting[recreate-parser34]",
"src/borg/testsuite/archiver.py::test_help_formatting[rename-parser35]",
"src/borg/testsuite/archiver.py::test_help_formatting[serve-parser36]",
"src/borg/testsuite/archiver.py::test_help_formatting[umount-parser37]",
"src/borg/testsuite/archiver.py::test_help_formatting[upgrade-parser38]",
"src/borg/testsuite/archiver.py::test_help_formatting[with-lock-parser39]",
"src/borg/testsuite/archiver.py::test_help_formatting_helptexts[patterns-\\nFile",
"src/borg/testsuite/archiver.py::test_help_formatting_helptexts[placeholders-\\nRepository",
"src/borg/testsuite/archiver.py::test_help_formatting_helptexts[compression-\\nIt"
]
| []
| BSD License | 1,927 | [
"src/borg/fuse.py",
"src/borg/algorithms/blake2/README.md",
"src/borg/algorithms/crc32_slice_by_8.c",
"src/borg/archiver.py",
"src/borg/algorithms/blake2/COPYING",
"docs/3rd_party/README"
]
| [
"src/borg/fuse.py",
"src/borg/algorithms/crc32_slice_by_8.c",
"docs/3rd_party/blake2/COPYING",
"src/borg/archiver.py",
"docs/3rd_party/blake2/README.md",
"docs/3rd_party/README"
]
|
|
lepture__mistune-143 | cef69acaa506567595e95ab6ecea25a806de622e | 2017-11-29 17:11:39 | c674108105e3419c6bfdf247c6082a9c6f5852fb | diff --git a/mistune.py b/mistune.py
index 5b05fcb..175ff01 100644
--- a/mistune.py
+++ b/mistune.py
@@ -503,7 +503,7 @@ class InlineLexer(object):
'linebreak', 'strikethrough', 'text',
]
inline_html_rules = [
- 'escape', 'autolink', 'url', 'link', 'reflink',
+ 'escape', 'inline_html', 'autolink', 'url', 'link', 'reflink',
'nolink', 'double_emphasis', 'emphasis', 'code',
'linebreak', 'strikethrough', 'text',
]
| nested html links are broken with parse_block_html
this is a variant of #81
example_in = '<div><a href="https://example.com">Example.com</a></div>'
mistune.markdown(example_in, escape=False, parse_block_html=True)
will generate:
<div><a href="<a href="https://example.com">Example.com">https://example.com">Example.com</a></a></div>
if escape is toggled to True, it is also broken:
'<div><a href="<a href="https://example.com">Example.com">https://example.com">Example.com</a></a></div>
| lepture/mistune | diff --git a/tests/test_extra.py b/tests/test_extra.py
index c1d37d9..3cb9799 100644
--- a/tests/test_extra.py
+++ b/tests/test_extra.py
@@ -116,6 +116,21 @@ def test_parse_block_html():
assert '<strong>' not in ret
+def test_parse_nested_html():
+ ret = mistune.markdown(
+ '<div><a href="http://example.org">**foo**</a></div>',
+ parse_block_html=True, escape=False
+ )
+ assert '<div><a href="http://example.org">' in ret
+ assert '<strong>' not in ret
+
+ ret = mistune.markdown(
+ '<div><a href="http://example.org">**foo**</a></div>',
+ parse_block_html=True, parse_inline_html=True, escape=False
+ )
+ assert '<div><a href="http://example.org"><strong>' in ret
+
+
def test_trigger_more_cases():
markdown = mistune.Markdown(
inline=mistune.InlineLexer,
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks",
"has_issue_reference"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 2,
"test_score": 3
},
"num_modified_files": 1
} | 0.8 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"nose",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
-e git+https://github.com/lepture/mistune.git@cef69acaa506567595e95ab6ecea25a806de622e#egg=mistune
nose==1.3.7
packaging @ file:///croot/packaging_1734472117206/work
pluggy @ file:///croot/pluggy_1733169602837/work
pytest @ file:///croot/pytest_1738938843180/work
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
| name: mistune
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- exceptiongroup=1.2.0=py39h06a4308_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- packaging=24.2=py39h06a4308_0
- pip=25.0=py39h06a4308_0
- pluggy=1.5.0=py39h06a4308_0
- pytest=8.3.4=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tomli=2.0.1=py39h06a4308_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- nose==1.3.7
prefix: /opt/conda/envs/mistune
| [
"tests/test_extra.py::test_parse_nested_html"
]
| []
| [
"tests/test_extra.py::test_escape",
"tests/test_extra.py::test_linebreak",
"tests/test_extra.py::test_safe_links",
"tests/test_extra.py::test_skip_style",
"tests/test_extra.py::test_use_xhtml",
"tests/test_extra.py::test_parse_inline_html",
"tests/test_extra.py::test_block_html",
"tests/test_extra.py::test_parse_block_html",
"tests/test_extra.py::test_trigger_more_cases",
"tests/test_extra.py::test_not_escape_block_tags",
"tests/test_extra.py::test_not_escape_inline_tags",
"tests/test_extra.py::test_hard_wrap_renderer"
]
| []
| BSD 3-Clause "New" or "Revised" License | 1,928 | [
"mistune.py"
]
| [
"mistune.py"
]
|
|
samkohn__larpix-control-74 | 345deb77ced183828f951008ad804a06819ccd52 | 2017-11-30 10:39:37 | eb91fe77d6458a579f2b8ef362cc9e42ca1e89f1 | diff --git a/larpix/larpix.py b/larpix/larpix.py
index d4ae36b..a0efae8 100644
--- a/larpix/larpix.py
+++ b/larpix/larpix.py
@@ -1332,7 +1332,7 @@ class PacketCollection(object):
d['message'] = str(self.message)
d['read_id'] = 'None' if self.read_id is None else self.read_id
d['bytestream'] = ('None' if self.bytestream is None else
- self.bytestream.decode('utf-8'))
+ self.bytestream.decode('raw_unicode_escape'))
return d
def from_dict(self, d):
@@ -1342,7 +1342,7 @@ class PacketCollection(object):
'''
self.message = d['message']
self.read_id = d['read_id']
- self.bytestream = d['bytestream'].encode('utf-8')
+ self.bytestream = d['bytestream'].encode('raw_unicode_escape')
self.parent = None
self.packets = []
for p in d['packets']:
| Some bytestreams don't parse well to JSON in Python 2 (PacketCollection.to_dict)
``UnicodeDecodeError: 'utf8' codec can't decode byte 0xd8 in position 1: invalid continuation byte``. Indeed byte ``b"\xd8"`` is in position 1. I think I'll need to insert some Python version logic into the to_dict and from_dict methods. | samkohn/larpix-control | diff --git a/test/test_larpix.py b/test/test_larpix.py
index af9e035..8c5165b 100644
--- a/test/test_larpix.py
+++ b/test/test_larpix.py
@@ -189,7 +189,7 @@ def test_controller_save_output(tmpdir):
'parent': 'None',
'message': 'hi',
'read_id': 0,
- 'bytestream': p.bytes().decode('utf-8')
+ 'bytestream': p.bytes().decode('raw_unicode_escape')
}
]
}
@@ -1699,6 +1699,7 @@ def test_packetcollection_origin():
def test_packetcollection_to_dict():
packet = Packet()
+ packet.chipid = 246
packet.packet_type = Packet.TEST_PACKET
collection = PacketCollection([packet], bytestream=packet.bytes(),
message='hello')
@@ -1708,11 +1709,11 @@ def test_packetcollection_to_dict():
'parent': 'None',
'message': 'hello',
'read_id': 'None',
- 'bytestream': packet.bytes().decode('utf-8'),
+ 'bytestream': packet.bytes().decode('raw_unicode_escape'),
'packets': [{
'bits': packet.bits.bin,
'type': 'test',
- 'chipid': 0,
+ 'chipid': packet.chipid,
'parity': 0,
'valid_parity': True,
'counter': 0
| {
"commit_name": "head_commit",
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 2,
"test_score": 0
},
"num_modified_files": 1
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pyserial bitstring pytest",
"pip_packages": [
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | bitarray @ file:///home/conda/feedstock_root/build_artifacts/bitarray_1741686834964/work
bitstring @ file:///home/conda/feedstock_root/build_artifacts/bitstring_1742657504808/work
exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
-e git+https://github.com/samkohn/larpix-control.git@345deb77ced183828f951008ad804a06819ccd52#egg=larpix_control
packaging @ file:///croot/packaging_1734472117206/work
pluggy @ file:///croot/pluggy_1733169602837/work
pyserial @ file:///croot/pyserial_1736540546229/work
pytest @ file:///croot/pytest_1738938843180/work
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
| name: larpix-control
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- bitarray=3.1.1=py39h8cd3c5a_0
- bitstring=4.3.1=pyhd8ed1ab_0
- ca-certificates=2025.2.25=h06a4308_0
- exceptiongroup=1.2.0=py39h06a4308_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc=14.2.0=h767d61c_2
- libgcc-ng=14.2.0=h69a702a_2
- libgomp=14.2.0=h767d61c_2
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- packaging=24.2=py39h06a4308_0
- pip=25.0=py39h06a4308_0
- pluggy=1.5.0=py39h06a4308_0
- pyserial=3.5=py39h06a4308_2
- pytest=8.3.4=py39h06a4308_0
- python=3.9.21=he870216_1
- python_abi=3.9=2_cp39
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tomli=2.0.1=py39h06a4308_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
prefix: /opt/conda/envs/larpix-control
| [
"test/test_larpix.py::test_packetcollection_to_dict"
]
| [
"test/test_larpix.py::test_configuration_set_pixel_trim_thresholds_errors",
"test/test_larpix.py::test_configuration_set_global_threshold_errors",
"test/test_larpix.py::test_configuration_set_csa_gain_errors",
"test/test_larpix.py::test_configuration_set_csa_bypass_errors",
"test/test_larpix.py::test_configuration_set_internal_bypass_errors",
"test/test_larpix.py::test_configuration_set_csa_bypass_select_errors",
"test/test_larpix.py::test_configuration_set_csa_monitor_select_errors",
"test/test_larpix.py::test_configuration_set_csa_testpulse_enable_errors",
"test/test_larpix.py::test_configuration_set_csa_testpulse_dac_amplitude_errors",
"test/test_larpix.py::test_configuration_set_test_mode_errors",
"test/test_larpix.py::test_configuration_set_cross_trigger_mode_errors",
"test/test_larpix.py::test_configuration_set_periodic_reset_errors",
"test/test_larpix.py::test_configuration_set_fifo_diagnostic_errors",
"test/test_larpix.py::test_configuration_set_test_burst_length_errors",
"test/test_larpix.py::test_configuration_set_adc_burst_length_errors",
"test/test_larpix.py::test_configuration_set_channel_mask_errors",
"test/test_larpix.py::test_configuration_set_external_trigger_mask_errors",
"test/test_larpix.py::test_configuration_set_reset_cycles_errors",
"test/test_larpix.py::test_configuration_write_errors",
"test/test_larpix.py::test_controller_get_chip_error",
"test/test_larpix.py::test_controller_format_UART",
"test/test_larpix.py::test_controller_format_bytestream",
"test/test_larpix.py::test_controller_write_configuration",
"test/test_larpix.py::test_controller_write_configuration_one_reg",
"test/test_larpix.py::test_controller_write_configuration_write_read",
"test/test_larpix.py::test_controller_get_configuration_bytestreams",
"test/test_larpix.py::test_controller_parse_input",
"test/test_larpix.py::test_controller_parse_input_dropped_data_byte",
"test/test_larpix.py::test_controller_parse_input_dropped_start_byte",
"test/test_larpix.py::test_controller_parse_input_dropped_stop_byte",
"test/test_larpix.py::test_controller_parse_input_dropped_stopstart_bytes"
]
| [
"test/test_larpix.py::test_FakeSerialPort_write",
"test/test_larpix.py::test_FakeSerialPort_read",
"test/test_larpix.py::test_FakeSerialPort_read_multi",
"test/test_larpix.py::test_chip_str",
"test/test_larpix.py::test_chip_get_configuration_packets",
"test/test_larpix.py::test_chip_sync_configuration",
"test/test_larpix.py::test_chip_export_reads",
"test/test_larpix.py::test_chip_export_reads_no_new_reads",
"test/test_larpix.py::test_chip_export_reads_all",
"test/test_larpix.py::test_controller_save_output",
"test/test_larpix.py::test_controller_load",
"test/test_larpix.py::test_packet_bits_bytes",
"test/test_larpix.py::test_packet_init_default",
"test/test_larpix.py::test_packet_init_bytestream",
"test/test_larpix.py::test_packet_bytes_zeros",
"test/test_larpix.py::test_packet_bytes_custom",
"test/test_larpix.py::test_packet_bytes_properties",
"test/test_larpix.py::test_packet_export_test",
"test/test_larpix.py::test_packet_export_data",
"test/test_larpix.py::test_packet_export_config_read",
"test/test_larpix.py::test_packet_export_config_write",
"test/test_larpix.py::test_packet_set_packet_type",
"test/test_larpix.py::test_packet_get_packet_type",
"test/test_larpix.py::test_packet_set_chipid",
"test/test_larpix.py::test_packet_get_chipid",
"test/test_larpix.py::test_packet_set_parity_bit_value",
"test/test_larpix.py::test_packet_get_parity_bit_value",
"test/test_larpix.py::test_packet_compute_parity",
"test/test_larpix.py::test_packet_assign_parity",
"test/test_larpix.py::test_packet_has_valid_parity",
"test/test_larpix.py::test_packet_set_channel_id",
"test/test_larpix.py::test_packet_get_channel_id",
"test/test_larpix.py::test_packet_set_timestamp",
"test/test_larpix.py::test_packet_get_timestamp",
"test/test_larpix.py::test_packet_set_dataword",
"test/test_larpix.py::test_packet_get_dataword",
"test/test_larpix.py::test_packet_get_dataword_ADC_bug",
"test/test_larpix.py::test_packet_set_fifo_half_flag",
"test/test_larpix.py::test_packet_get_fifo_half_flag",
"test/test_larpix.py::test_packet_set_fifo_full_flag",
"test/test_larpix.py::test_packet_get_fifo_full_flag",
"test/test_larpix.py::test_packet_set_register_address",
"test/test_larpix.py::test_packet_get_register_address",
"test/test_larpix.py::test_packet_set_register_data",
"test/test_larpix.py::test_packet_get_register_data",
"test/test_larpix.py::test_packet_set_test_counter",
"test/test_larpix.py::test_packet_get_test_counter",
"test/test_larpix.py::test_configuration_get_nondefault_registers",
"test/test_larpix.py::test_configuration_get_nondefault_registers_array",
"test/test_larpix.py::test_configuration_get_nondefault_registers_many_changes",
"test/test_larpix.py::test_configuration_set_pixel_trim_thresholds",
"test/test_larpix.py::test_configuration_get_pixel_trim_thresholds",
"test/test_larpix.py::test_configuration_set_global_threshold",
"test/test_larpix.py::test_configuration_get_global_threshold",
"test/test_larpix.py::test_configuration_set_csa_gain",
"test/test_larpix.py::test_configuration_get_csa_gain",
"test/test_larpix.py::test_configuration_set_csa_bypass",
"test/test_larpix.py::test_configuration_get_csa_bypass",
"test/test_larpix.py::test_configuration_set_internal_bypass",
"test/test_larpix.py::test_configuration_get_internal_bypass",
"test/test_larpix.py::test_configuration_set_csa_bypass_select",
"test/test_larpix.py::test_configuration_get_csa_bypass_select",
"test/test_larpix.py::test_configuration_set_csa_monitor_select",
"test/test_larpix.py::test_configuration_get_csa_monitor_select",
"test/test_larpix.py::test_configuration_set_csa_testpulse_enable",
"test/test_larpix.py::test_configuration_get_csa_testpulse_enable",
"test/test_larpix.py::test_configuration_set_csa_testpulse_dac_amplitude",
"test/test_larpix.py::test_configuration_get_csa_testpulse_dac_amplitude",
"test/test_larpix.py::test_configuration_set_test_mode",
"test/test_larpix.py::test_configuration_get_test_mode",
"test/test_larpix.py::test_configuration_set_cross_trigger_mode",
"test/test_larpix.py::test_configuration_get_cross_trigger_mode",
"test/test_larpix.py::test_configuration_set_periodic_reset",
"test/test_larpix.py::test_configuration_get_periodic_reset",
"test/test_larpix.py::test_configuration_set_fifo_diagnostic",
"test/test_larpix.py::test_configuration_get_fifo_diagnostic",
"test/test_larpix.py::test_configuration_set_test_burst_length",
"test/test_larpix.py::test_configuration_get_test_burst_length",
"test/test_larpix.py::test_configuration_set_adc_burst_length",
"test/test_larpix.py::test_configuration_get_adc_burst_length",
"test/test_larpix.py::test_configuration_set_channel_mask",
"test/test_larpix.py::test_configuration_get_channel_mask",
"test/test_larpix.py::test_configuration_set_external_trigger_mask",
"test/test_larpix.py::test_configuration_get_external_trigger_mask",
"test/test_larpix.py::test_configuration_set_reset_cycles",
"test/test_larpix.py::test_configuration_get_reset_cycles",
"test/test_larpix.py::test_configuration_disable_channels",
"test/test_larpix.py::test_configuration_disable_channels_default",
"test/test_larpix.py::test_configuration_enable_channels",
"test/test_larpix.py::test_configuration_enable_channels_default",
"test/test_larpix.py::test_configuration_enable_external_trigger",
"test/test_larpix.py::test_configuration_enable_external_trigger_default",
"test/test_larpix.py::test_configuration_disable_external_trigger",
"test/test_larpix.py::test_configuration_enable_testpulse",
"test/test_larpix.py::test_configuration_enable_testpulse_default",
"test/test_larpix.py::test_configuration_disable_testpulse",
"test/test_larpix.py::test_configuration_disable_testpulse_default",
"test/test_larpix.py::test_configuration_enable_analog_monitor",
"test/test_larpix.py::test_configuration_disable_analog_monitor",
"test/test_larpix.py::test_configuration_trim_threshold_data",
"test/test_larpix.py::test_configuration_global_threshold_data",
"test/test_larpix.py::test_configuration_csa_gain_and_bypasses_data",
"test/test_larpix.py::test_configuration_csa_bypass_select_data",
"test/test_larpix.py::test_configuration_csa_monitor_select_data",
"test/test_larpix.py::test_configuration_csa_testpulse_enable_data",
"test/test_larpix.py::test_configuration_csa_testpulse_dac_amplitude_data",
"test/test_larpix.py::test_configuration_test_mode_xtrig_reset_diag_data",
"test/test_larpix.py::test_configuration_sample_cycles_data",
"test/test_larpix.py::test_configuration_test_burst_length_data",
"test/test_larpix.py::test_configuration_adc_burst_length_data",
"test/test_larpix.py::test_configuration_channel_mask_data",
"test/test_larpix.py::test_configuration_external_trigger_mask_data",
"test/test_larpix.py::test_configuration_reset_cycles_data",
"test/test_larpix.py::test_configuration_to_dict",
"test/test_larpix.py::test_configuration_from_dict",
"test/test_larpix.py::test_configuration_write",
"test/test_larpix.py::test_configuration_write_force",
"test/test_larpix.py::test_configuration_read_absolute",
"test/test_larpix.py::test_configuration_read_default",
"test/test_larpix.py::test_configuration_read_local",
"test/test_larpix.py::test_configuration_from_dict_reg_pixel_trim",
"test/test_larpix.py::test_configuration_from_dict_reg_global_threshold",
"test/test_larpix.py::test_configuration_from_dict_reg_csa_gain",
"test/test_larpix.py::test_configuration_from_dict_reg_csa_bypass",
"test/test_larpix.py::test_configuration_from_dict_reg_internal_bypass",
"test/test_larpix.py::test_configuration_from_dict_reg_csa_bypass_select",
"test/test_larpix.py::test_configuration_from_dict_reg_csa_monitor_select",
"test/test_larpix.py::test_configuration_from_dict_reg_csa_testpulse_enable",
"test/test_larpix.py::test_configuration_from_dict_reg_csa_testpulse_dac_amplitude",
"test/test_larpix.py::test_configuration_from_dict_reg_test_mode",
"test/test_larpix.py::test_configuration_from_dict_reg_cross_trigger_mode",
"test/test_larpix.py::test_configuration_from_dict_reg_periodic_reset",
"test/test_larpix.py::test_configuration_from_dict_reg_fifo_diagnostic",
"test/test_larpix.py::test_configuration_from_dict_reg_sample_cycles",
"test/test_larpix.py::test_configuration_from_dict_reg_test_burst_length",
"test/test_larpix.py::test_configuration_from_dict_reg_adc_burst_length",
"test/test_larpix.py::test_configuration_from_dict_reg_channel_mask",
"test/test_larpix.py::test_configuration_from_dict_reg_external_trigger_mask",
"test/test_larpix.py::test_configuration_from_dict_reg_reset_cycles",
"test/test_larpix.py::test_controller_init_chips",
"test/test_larpix.py::test_controller_get_chip",
"test/test_larpix.py::test_controller_get_chip_all_chips",
"test/test_larpix.py::test_controller_serial_read_mock",
"test/test_larpix.py::test_controller_serial_write_mock",
"test/test_larpix.py::test_controller_serial_write_read_mock",
"test/test_larpix.py::test_packetcollection_getitem_int",
"test/test_larpix.py::test_packetcollection_getitem_int_bits",
"test/test_larpix.py::test_packetcollection_getitem_slice",
"test/test_larpix.py::test_packetcollection_getitem_slice_bits",
"test/test_larpix.py::test_packetcollection_origin",
"test/test_larpix.py::test_packetcollection_from_dict"
]
| []
| null | 1,929 | [
"larpix/larpix.py"
]
| [
"larpix/larpix.py"
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.