instance_id
stringlengths 10
57
| patch
stringlengths 261
37.7k
| repo
stringlengths 7
53
| base_commit
stringlengths 40
40
| hints_text
stringclasses 301
values | test_patch
stringlengths 212
2.22M
| problem_statement
stringlengths 23
37.7k
| version
stringclasses 1
value | environment_setup_commit
stringlengths 40
40
| FAIL_TO_PASS
listlengths 1
4.94k
| PASS_TO_PASS
listlengths 0
7.82k
| meta
dict | created_at
stringlengths 25
25
| license
stringclasses 8
values | __index_level_0__
int64 0
6.41k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
jorisroovers__gitlint-214
|
diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml
index b477e11..4e76ff1 100644
--- a/.github/workflows/checks.yml
+++ b/.github/workflows/checks.yml
@@ -7,7 +7,7 @@ jobs:
runs-on: "ubuntu-latest"
strategy:
matrix:
- python-version: ["3.6", "3.7", "3.8", "3.9", "3.10", pypy3]
+ python-version: ["3.6", "3.7", "3.8", "3.9", "3.10", pypy-3.9]
os: ["macos-latest", "ubuntu-latest"]
steps:
- uses: actions/checkout@v3
@@ -21,7 +21,7 @@ jobs:
run: mv .git ._git
- name: Setup python
- uses: actions/setup-python@v2
+ uses: actions/[email protected]
with:
python-version: ${{ matrix.python-version }}
@@ -92,7 +92,7 @@ jobs:
run: Rename-Item .git ._git
- name: Setup python
- uses: actions/setup-python@v2
+ uses: actions/[email protected]
with:
python-version: ${{ matrix.python-version }}
diff --git a/gitlint-core/gitlint/git.py b/gitlint-core/gitlint/git.py
index 2ac8b3d..117f5f4 100644
--- a/gitlint-core/gitlint/git.py
+++ b/gitlint-core/gitlint/git.py
@@ -337,7 +337,11 @@ class GitContext(PropertyCache):
@property
@cache
def current_branch(self):
- current_branch = _git("rev-parse", "--abbrev-ref", "HEAD", _cwd=self.repository_path).strip()
+ try:
+ current_branch = _git("rev-parse", "--abbrev-ref", "HEAD", _cwd=self.repository_path).strip()
+ except GitContextError:
+ # Maybe there is no commit. Try another way to get current branch (need Git 2.22+)
+ current_branch = _git("branch", "--show-current", _cwd=self.repository_path).strip()
return current_branch
@staticmethod
|
jorisroovers/gitlint
|
fa60987263dba4b2cf503bff937444034d1d6c1b
|
diff --git a/gitlint-core/gitlint/tests/cli/test_cli_hooks.py b/gitlint-core/gitlint/tests/cli/test_cli_hooks.py
index 825345f..94c35dc 100644
--- a/gitlint-core/gitlint/tests/cli/test_cli_hooks.py
+++ b/gitlint-core/gitlint/tests/cli/test_cli_hooks.py
@@ -132,6 +132,9 @@ class CLIHookTests(BaseTestCase):
for i in range(0, len(set_editors)):
if set_editors[i]:
os.environ['EDITOR'] = set_editors[i]
+ else:
+ # When set_editors[i] == None, ensure we don't fallback to EDITOR set in shell invocating the tests
+ os.environ.pop('EDITOR', None)
with self.patch_input(['e', 'e', 'n']):
with self.tempdir() as tmpdir:
diff --git a/gitlint-core/gitlint/tests/git/test_git.py b/gitlint-core/gitlint/tests/git/test_git.py
index 7b9b7c6..e9e5645 100644
--- a/gitlint-core/gitlint/tests/git/test_git.py
+++ b/gitlint-core/gitlint/tests/git/test_git.py
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
import os
-from unittest.mock import patch
+from unittest.mock import patch, call
from gitlint.shell import ErrorReturnCode, CommandNotFound
@@ -64,8 +64,12 @@ class GitTests(BaseTestCase):
# assert that commit message was read using git command
sh.git.assert_called_once_with("log", "-1", "--pretty=%H", **self.expected_sh_special_args)
- sh.git.reset_mock()
+ @patch('gitlint.git.sh')
+ def test_git_no_commits_get_branch(self, sh):
+ """ Check that we can still read the current branch name when there's no commits. This is useful when
+ when trying to lint the first commit using the --staged flag.
+ """
# Unknown reference 'HEAD' commits: returned by 'git rev-parse'
err = (b"HEAD"
b"fatal: ambiguous argument 'HEAD': unknown revision or path not in the working tree."
@@ -74,15 +78,22 @@ class GitTests(BaseTestCase):
sh.git.side_effect = [
"#\n", # git config --get core.commentchar
- ErrorReturnCode("rev-parse --abbrev-ref HEAD", b"", err)
+ ErrorReturnCode("rev-parse --abbrev-ref HEAD", b"", err),
+ 'test-branch', # git branch --show-current
]
- with self.assertRaisesMessage(GitContextError, expected_msg):
- context = GitContext.from_commit_msg("test")
- context.current_branch
+ context = GitContext.from_commit_msg("test")
+ self.assertEqual(context.current_branch, 'test-branch')
- # assert that commit message was read using git command
- sh.git.assert_called_with("rev-parse", "--abbrev-ref", "HEAD", _tty_out=False, _cwd=None)
+ # assert that we try using `git rev-parse` first, and if that fails (as will be the case with the first commit),
+ # we fallback to `git branch --show-current` to determine the current branch name.
+ expected_calls = [
+ call("config", "--get", "core.commentchar", _tty_out=False, _cwd=None, _ok_code=[0, 1]),
+ call("rev-parse", "--abbrev-ref", "HEAD", _tty_out=False, _cwd=None),
+ call("branch", "--show-current", _tty_out=False, _cwd=None)
+ ]
+
+ self.assertEqual(sh.git.mock_calls, expected_calls)
@patch("gitlint.git._git")
def test_git_commentchar(self, git):
diff --git a/qa/test_gitlint.py b/qa/test_gitlint.py
index 0200d76..36fba69 100644
--- a/qa/test_gitlint.py
+++ b/qa/test_gitlint.py
@@ -178,7 +178,7 @@ class IntegrationTests(BaseTestCase):
expected = "Missing git configuration: please set user.email\n"
self.assertEqualStdout(output, expected)
- def test_git_errors(self):
+ def test_git_empty_repo(self):
# Repo has no commits: caused by `git log`
empty_git_repo = self.create_tmp_git_repo()
output = gitlint(_cwd=empty_git_repo, _tty_in=True, _ok_code=[self.GIT_CONTEXT_ERROR_CODE])
@@ -186,7 +186,13 @@ class IntegrationTests(BaseTestCase):
expected = "Current branch has no commits. Gitlint requires at least one commit to function.\n"
self.assertEqualStdout(output, expected)
- # Repo has no commits: caused by `git rev-parse`
+ def test_git_empty_repo_staged(self):
+ """ When repo is empty, we can still use gitlint when using --staged flag and piping a message into it """
+ empty_git_repo = self.create_tmp_git_repo()
+ expected = ("1: T3 Title has trailing punctuation (.): \"WIP: Pïpe test.\"\n"
+ "1: T5 Title contains the word \'WIP\' (case-insensitive): \"WIP: Pïpe test.\"\n"
+ "3: B6 Body message is missing\n")
+
output = gitlint(echo("WIP: Pïpe test."), "--staged", _cwd=empty_git_repo, _tty_in=False,
- _err_to_out=True, _ok_code=[self.GIT_CONTEXT_ERROR_CODE])
+ _err_to_out=True, _ok_code=[3])
self.assertEqualStdout(output, expected)
diff --git a/test-requirements.txt b/test-requirements.txt
index 78a383d..df3c4ab 100644
--- a/test-requirements.txt
+++ b/test-requirements.txt
@@ -4,5 +4,5 @@ python-coveralls==2.9.3
radon==5.1.0
flake8-polyfill==1.0.2 # Required when installing both flake8 and radon>=4.3.1
pytest==7.0.1;
-pylint==2.12.2;
+pylint==2.13.5;
-r requirements.txt
|
Gitlint requires at least one commit to function
### The Problem
*Gitlint version: 0.15.1*
When linting a staged commit with `--staged` in an empty repo or orphan branch with no commits a `GitContextError` is raised with the message:
> Current branch has no commits. Gitlint requires at least one commit to function.
While the error is clear, I feel that under the circumstances gitlint should give a little leeway, especially since the exception in this case comes down to a debug log line in **gitlint/lint.py** (when removed, gitlint works without issue):
```
10 class GitLinter:
...
69 def lint(self, commit):
70 """ Lint the last commit in a given git context by applying all ignore, title, body and commit rules. """
71 LOG.debug("Linting commit %s", commit.sha or "[SHA UNKNOWN]")
72 LOG.debug("Commit Object\n" + str(commit))
^
```
In **gitlint/git.py**:
```
127 class GitCommit:
...
162 def __str__(self):
163 date_str = arrow.get(self.date).format(GIT_TIMEFORMAT) if self.date else None
164 return (f"--- Commit Message ----\n{self.message}\n"
165 "--- Meta info ---------\n"
166 f"Author: {self.author_name} <{self.author_email}>\n"
167 f"Date: {date_str}\n"
168 f"is-merge-commit: {self.is_merge_commit}\n"
169 f"is-fixup-commit: {self.is_fixup_commit}\n"
170 f"is-squash-commit: {self.is_squash_commit}\n"
171 f"is-revert-commit: {self.is_revert_commit}\n"
172 f"Branches: {self.branches}\n"
^
173 f"Changed Files: {self.changed_files}\n"
174 "-----------------------")
```
`StagedLocalGitCommit.branches` attempts to get the current branch name by calling `git rev-parse --abbrev-ref HEAD` which fails.
### Possible Solutions
#### 1) Be forgiving of `GitContextError` in `gitlint.git.StagedLocalGitCommit.branches`
Catch the exception and return an empty list. I don't know where this property is normally used other than debugging messages but if users can handle an empty list then this seems reasonable.
#### 2) Use `git branch --show-current` to get the branch name
The `--show-current` option was added to git in 2.22.0 (June 2019) so may be a little new to rely on. It can also return empty output for detached HEAD which will need to be handled.
|
0.0
|
fa60987263dba4b2cf503bff937444034d1d6c1b
|
[
"gitlint-core/gitlint/tests/git/test_git.py::GitTests::test_git_no_commits_get_branch",
"qa/test_gitlint.py::IntegrationTests::test_git_empty_repo_staged"
] |
[
"gitlint-core/gitlint/tests/cli/test_cli_hooks.py::CLIHookTests::test_install_hook",
"gitlint-core/gitlint/tests/cli/test_cli_hooks.py::CLIHookTests::test_install_hook_negative",
"gitlint-core/gitlint/tests/cli/test_cli_hooks.py::CLIHookTests::test_install_hook_target",
"gitlint-core/gitlint/tests/cli/test_cli_hooks.py::CLIHookTests::test_run_hook_config",
"gitlint-core/gitlint/tests/cli/test_cli_hooks.py::CLIHookTests::test_run_hook_edit",
"gitlint-core/gitlint/tests/cli/test_cli_hooks.py::CLIHookTests::test_run_hook_local_commit",
"gitlint-core/gitlint/tests/cli/test_cli_hooks.py::CLIHookTests::test_run_hook_negative",
"gitlint-core/gitlint/tests/cli/test_cli_hooks.py::CLIHookTests::test_run_hook_no",
"gitlint-core/gitlint/tests/cli/test_cli_hooks.py::CLIHookTests::test_run_hook_no_tty",
"gitlint-core/gitlint/tests/cli/test_cli_hooks.py::CLIHookTests::test_run_hook_stdin_no_violations",
"gitlint-core/gitlint/tests/cli/test_cli_hooks.py::CLIHookTests::test_run_hook_stdin_violations",
"gitlint-core/gitlint/tests/cli/test_cli_hooks.py::CLIHookTests::test_run_hook_yes",
"gitlint-core/gitlint/tests/cli/test_cli_hooks.py::CLIHookTests::test_uninstall_hook",
"gitlint-core/gitlint/tests/cli/test_cli_hooks.py::CLIHookTests::test_uninstall_hook_negative",
"gitlint-core/gitlint/tests/git/test_git.py::GitTests::test_get_latest_commit_command_not_found",
"gitlint-core/gitlint/tests/git/test_git.py::GitTests::test_get_latest_commit_git_error",
"gitlint-core/gitlint/tests/git/test_git.py::GitTests::test_git_commentchar",
"gitlint-core/gitlint/tests/git/test_git.py::GitTests::test_git_hooks_dir",
"gitlint-core/gitlint/tests/git/test_git.py::GitTests::test_git_no_commits_error",
"qa/test_gitlint.py::IntegrationTests::test_fixup_commit",
"qa/test_gitlint.py::IntegrationTests::test_git_empty_repo",
"qa/test_gitlint.py::IntegrationTests::test_msg_filename",
"qa/test_gitlint.py::IntegrationTests::test_msg_filename_no_tty",
"qa/test_gitlint.py::IntegrationTests::test_no_git_email_set",
"qa/test_gitlint.py::IntegrationTests::test_no_git_name_set",
"qa/test_gitlint.py::IntegrationTests::test_revert_commit",
"qa/test_gitlint.py::IntegrationTests::test_squash_commit",
"qa/test_gitlint.py::IntegrationTests::test_successful",
"qa/test_gitlint.py::IntegrationTests::test_successful_gitconfig",
"qa/test_gitlint.py::IntegrationTests::test_successful_merge_commit",
"qa/test_gitlint.py::IntegrationTests::test_violations"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-08-19 12:16:44+00:00
|
mit
| 3,335 |
|
jorisroovers__gitlint-312
|
diff --git a/docs/contrib_rules.md b/docs/contrib_rules.md
index 336e42a..370d39b 100644
--- a/docs/contrib_rules.md
+++ b/docs/contrib_rules.md
@@ -42,6 +42,7 @@ ID | Name | gitlint version | Description
------|-------------------------------------|------------------ |-------------------------------------------
CT1 | contrib-title-conventional-commits | >= 0.12.0 | Enforces [Conventional Commits](https://www.conventionalcommits.org/) commit message style on the title.
CC1 | contrib-body-requires-signed-off-by | >= 0.12.0 | Commit body must contain a `Signed-off-by` line.
+CC2 | contrib-disallow-cleanup-commits | >= 0.18.0 | Commit title must not contain `fixup!`, `squash!`, `amend!`.
## CT1: contrib-title-conventional-commits ##
@@ -63,5 +64,11 @@ ID | Name | gitlint version | Description
CC1 | contrib-body-requires-signed-off-by | >= 0.12.0 | Commit body must contain a `Signed-off-by` line. This means, a line that starts with the `Signed-off-by` keyword.
+## CC2: contrib-disallow-cleanup-commits ##
+
+ID | Name | gitlint version | Description
+------|----------------------------------|--------------------|-------------------------------------------
+CC2 | contrib-disallow-cleanup-commits | >= 0.18.0 | Commit title must not contain `fixup!`, `squash!` or `amend!`. This means `git commit --fixup` and `git commit --squash` commits are not allowed.
+
## Contributing Contrib rules
We'd love for you to contribute new Contrib rules to gitlint or improve existing ones! Please visit the [Contributing](contributing) page on how to get started.
diff --git a/gitlint-core/gitlint/contrib/rules/disallow_cleanup_commits.py b/gitlint-core/gitlint/contrib/rules/disallow_cleanup_commits.py
new file mode 100644
index 0000000..815e31f
--- /dev/null
+++ b/gitlint-core/gitlint/contrib/rules/disallow_cleanup_commits.py
@@ -0,0 +1,22 @@
+from gitlint.rules import CommitRule, RuleViolation
+
+
+class DisallowCleanupCommits(CommitRule):
+ """ This rule checks the commits for "fixup!"/"squash!"/"amend!" commits
+ and rejects them.
+ """
+
+ name = "contrib-disallow-cleanup-commits"
+ id = "CC2"
+
+ def validate(self, commit):
+ if commit.is_fixup_commit:
+ return [RuleViolation(self.id, "Fixup commits are not allowed", line_nr=1)]
+
+ if commit.is_squash_commit:
+ return [RuleViolation(self.id, "Squash commits are not allowed", line_nr=1)]
+
+ if commit.is_fixup_amend_commit:
+ return [RuleViolation(self.id, "Amend commits are not allowed", line_nr=1)]
+
+ return []
|
jorisroovers/gitlint
|
c50eb150bbe4376d401b6c8d97f2b975877bb886
|
diff --git a/gitlint-core/gitlint/tests/contrib/rules/test_disallow_cleanup_commits.py b/gitlint-core/gitlint/tests/contrib/rules/test_disallow_cleanup_commits.py
new file mode 100644
index 0000000..0d916c9
--- /dev/null
+++ b/gitlint-core/gitlint/tests/contrib/rules/test_disallow_cleanup_commits.py
@@ -0,0 +1,38 @@
+
+# -*- coding: utf-8 -*-
+from gitlint.tests.base import BaseTestCase
+from gitlint.rules import RuleViolation
+from gitlint.contrib.rules.disallow_cleanup_commits import DisallowCleanupCommits
+
+from gitlint.config import LintConfig
+
+
+class ContribDisallowCleanupCommitsTest(BaseTestCase):
+
+ def test_enable(self):
+ # Test that rule can be enabled in config
+ for rule_ref in ['CC2', 'contrib-disallow-cleanup-commits']:
+ config = LintConfig()
+ config.contrib = [rule_ref]
+ self.assertIn(DisallowCleanupCommits(), config.rules)
+
+ def test_disallow_fixup_squash_commit(self):
+ # No violations when no 'fixup!' line and no 'squash!' line is present
+ rule = DisallowCleanupCommits()
+ violations = rule.validate(self.gitcommit("Föobar\n\nMy Body"))
+ self.assertListEqual(violations, [])
+
+ # Assert violation when 'fixup!' in title
+ violations = rule.validate(self.gitcommit("fixup! Föobar\n\nMy Body"))
+ expected_violation = RuleViolation("CC2", "Fixup commits are not allowed", line_nr=1)
+ self.assertListEqual(violations, [expected_violation])
+
+ # Assert violation when 'squash!' in title
+ violations = rule.validate(self.gitcommit("squash! Föobar\n\nMy Body"))
+ expected_violation = RuleViolation("CC2", "Squash commits are not allowed", line_nr=1)
+ self.assertListEqual(violations, [expected_violation])
+
+ # Assert violation when 'amend!' in title
+ violations = rule.validate(self.gitcommit("amend! Föobar\n\nMy Body"))
+ expected_violation = RuleViolation("CC2", "Amend commits are not allowed", line_nr=1)
+ self.assertListEqual(violations, [expected_violation])
|
Add a rule to disallow commit messages starting with "fixup!"
They are created with the `git commit --fixup=<commit-sha>` command and are supposed to be squashed.
If they are present, they usually indicate that someone forgot to do `git rebase -i` and squash them.
A similar thing could be achieved with the `title-must-not-contain-word` rule, but unfortunately, the currently used regex:
https://github.com/jorisroovers/gitlint/blob/7f7c52fc2ee54ef8d8f1cfa8033b457c1cbac6b2/gitlint/rules.py#L158
prevents using the `fixup!` word since then the regex doesn't match at all:
```
In [11]: re.search(r"\b%s\b" % "fixup", "fixup! Some title")
Out[11]: <re.Match object; span=(0, 5), match='fixup'>
In [12]: re.search(r"\b%s\b" % "fixup!", "fixup! Some title")
```
Simply using `fixup` as a forbidden word is an incomplete solution since the term "fixup" is valid in other parts of the title, e.g.: "Add another check to fixup tests"
|
0.0
|
c50eb150bbe4376d401b6c8d97f2b975877bb886
|
[
"gitlint-core/gitlint/tests/contrib/rules/test_disallow_cleanup_commits.py::ContribDisallowCleanupCommitsTest::test_disallow_fixup_squash_commit",
"gitlint-core/gitlint/tests/contrib/rules/test_disallow_cleanup_commits.py::ContribDisallowCleanupCommitsTest::test_enable"
] |
[] |
{
"failed_lite_validators": [
"has_added_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-08-01 15:54:13+00:00
|
mit
| 3,336 |
|
joscha0__daily-wiki-13
|
diff --git a/getwiki.py b/getwiki.py
index 395aac1..0c1db59 100644
--- a/getwiki.py
+++ b/getwiki.py
@@ -33,4 +33,4 @@ def get_wiki(language):
img = imgs[0]
img['src'] = 'http:'+img['src']
- return img, text
+ return str(img), str(text)
diff --git a/sendmail.py b/sendmail.py
index 41288e4..1538d0e 100644
--- a/sendmail.py
+++ b/sendmail.py
@@ -10,7 +10,7 @@ from getwiki import get_wiki
def send_email(img, text, email):
unsubscribe_tag = f'<a href="https://daily-wiki-newsletter.herokuapp.com/unsubscribe/{email}">unsubscribe</a>'
- msg = MIMEText(str(img) + 3*'<br>' + text + 3 *
+ msg = MIMEText(img + 3*'<br>' + text + 3 *
'<br>' + unsubscribe_tag, 'html')
msg['Subject'] = 'today wiki'
msg['From'] = '[email protected]'
@@ -42,9 +42,16 @@ if __name__ == "__main__":
languages = ["en", "de", "fr", "sv", "ja", "zh"]
wikis = {}
for language in languages:
- img, text = get_wiki(language)
+ try:
+ img, text = get_wiki(language)
+ except:
+ print(f"Error getting article for {language}")
wikis[language] = (img, text)
data = firestore.getusers()
for email in data:
img, text = wikis[data[email]["language"]]
- send_email(img, text, email)
+ try:
+ send_email(img, text, email)
+ print(f"Sent email to {email}")
+ except:
+ print(f"Email failed to send to {email}")
|
joscha0/daily-wiki
|
1630910248178e4d9d865f66e7d8b186b39d1315
|
diff --git a/tests/test_getwiki.py b/tests/test_getwiki.py
new file mode 100644
index 0000000..ac45dae
--- /dev/null
+++ b/tests/test_getwiki.py
@@ -0,0 +1,28 @@
+import unittest
+from getwiki import get_wiki
+
+
+class TestFirestore(unittest.TestCase):
+
+ def test_get_wiki(self):
+ languages = ["en", "de", "fr", "sv", "ja", "zh"]
+ wikis = {}
+ for language in languages:
+ img, text = get_wiki(language)
+ wikis[language] = (img, text)
+ output = True
+ for key, value in wikis.items():
+ if output == False:
+ break
+ if not value[0].startswith('<img'):
+ print('\n\nNot an Image:'+value[0])
+ if len(value[1]) < 10:
+ print('\n\nShort Text:'+value[0])
+ self.assertIn(key, languages)
+ self.assertIsInstance(value, tuple)
+ self.assertIsInstance(value[0], str)
+ self.assertIsInstance(value[1], str)
+ self.assertTrue(len(value) == 2)
+
+ if __name__ == "__main__":
+ unittest.main()
|
fix email invalid
if one email is invalid throws error
`Traceback (most recent call last):
File "sendmail.py", line 50, in <module>
send_email(img, text, email)
File "sendmail.py", line 21, in send_email
s.sendmail(msg['From'], msg['To'], msg.as_string())
File "/app/.heroku/python/lib/python3.6/smtplib.py", line 881, in sendmail
raise SMTPRecipientsRefused(senderrs)
smtplib.SMTPRecipientsRefused: {'[email protected]': (450, b'4.1.2 <[email protected]>: Recipient address rejected: Domain not found')}
`
|
0.0
|
1630910248178e4d9d865f66e7d8b186b39d1315
|
[
"tests/test_getwiki.py::TestFirestore::test_get_wiki"
] |
[] |
{
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-10-21 12:46:56+00:00
|
mit
| 3,337 |
|
joshbarrass__SkyrimCrafting-4
|
diff --git a/app.py b/app.py
new file mode 100644
index 0000000..9f54825
--- /dev/null
+++ b/app.py
@@ -0,0 +1,1 @@
+from database.wrapper import Database
diff --git a/database/__init__.py b/database/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/database/database.py b/database/database.py
deleted file mode 100644
index 3e051af..0000000
--- a/database/database.py
+++ /dev/null
@@ -1,15 +0,0 @@
-from sqlalchemy import create_engine
-from sqlalchemy.orm import sessionmaker
-
-from models import Item, PotionEffect, PotionItem, Recipe, CraftingIngredient
-
-class Database:
- def __init__(self, url):
- self.engine = create_engine(url)
- Item.metadata.create_all(self.engine)
- PotionEffect.metadata.create_all(self.engine)
- PotionItem.metadata.create_all(self.engine)
- Recipe.metadata.create_all(self.engine)
- CraftingIngredient.metadata.create_all(self.engine)
-
- self.SessionMaker = sessionmaker(bind=self.engine)
diff --git a/database/models.py b/database/models.py
index 05dab98..046ff7e 100644
--- a/database/models.py
+++ b/database/models.py
@@ -110,6 +110,9 @@ class Recipe(Base):
"{table}.id".format(table=Requirement.__tablename__)
),
)
+ requirement = relationship(
+ "Requirement", foreign_keys="Recipe.requirement_id"
+ )
quantity = Column(Integer)
def __repr__(self):
diff --git a/database/wrapper.py b/database/wrapper.py
new file mode 100644
index 0000000..a498efc
--- /dev/null
+++ b/database/wrapper.py
@@ -0,0 +1,216 @@
+from typing import List, Tuple, Union
+
+from sqlalchemy import create_engine
+from sqlalchemy.orm import sessionmaker
+
+from database.models import Item, PotionEffect, PotionItem, Requirement, Recipe, CraftingIngredient
+
+class Database:
+ def __init__(self, url):
+ self.engine = create_engine(url)
+ Item.metadata.create_all(self.engine)
+ PotionEffect.metadata.create_all(self.engine)
+ PotionItem.metadata.create_all(self.engine)
+ Recipe.metadata.create_all(self.engine)
+ CraftingIngredient.metadata.create_all(self.engine)
+
+ self.NewSession = sessionmaker(bind=self.engine)
+ self.session = None
+
+ def new_session(self, commit=False):
+ if self.session is not None and commit:
+ self.session.commit()
+ self.session = self.NewSession()
+
+ def have_session(self):
+ if self.session is None:
+ self.session = self.NewSession()
+
+ def commit(self):
+ return self.session.commit()
+
+ def rollback(self):
+ return self.session.rollback()
+
+ def close_session(self):
+ self.session.close()
+ self.session = None
+
+ def new_item(
+ self,
+ name: str,
+ value: int,
+ weight: float,
+ id: int = None
+ ) -> Item:
+ self.have_session()
+ newitem = Item(
+ name=name,
+ value=value,
+ weight=weight,
+ )
+
+ if id is not None:
+ newitem.id = id
+
+ self.session.add(newitem)
+ return newitem
+
+ def get_item_by_ID(self, ID: Union[int, str]) -> Item:
+ self.have_session()
+ if isinstance(ID, str):
+ ID = int(ID, 16)
+ return self.session.query(Item).filter_by(id=ID).first()
+
+ def get_items_by_name(self, name: str) -> List[Item]:
+ self.have_session()
+ return self.session.query(Item).filter_by(name=name).all()
+
+ def new_potion_effect(
+ self,
+ name: str,
+ desc: str,
+ cost: float,
+ mag: int,
+ dur: int,
+ value: int,
+ is_negative: bool,
+ vary_duration: bool,
+ id: int = None,
+ ) -> PotionEffect:
+ self.have_session()
+ neweffect = PotionEffect(
+ name=name,
+ is_negative=is_negative,
+ description=desc,
+ base_cost=cost,
+ base_mag=mag,
+ base_dur=dur,
+ value=value,
+ vary_duration=vary_duration,
+ )
+
+ if id is not None:
+ neweffect.id = id
+
+ self.session.add(neweffect)
+ return neweffect
+
+ def get_effect_by_ID(self, ID: int) -> PotionEffect:
+ self.have_session()
+ return self.session.query(PotionEffect).filter_by(id=ID
+ ).first()
+
+ def get_effects_by_name(self, name: str) -> List[PotionEffect]:
+ self.have_session()
+ return self.session.query(PotionEffect).filter_by(name=name
+ ).all()
+
+ def get_effects_by_item(self, item: Item) -> List[PotionItem]:
+ self.have_session()
+ assert item.id is not None
+ potionitems = self.session.query(PotionItem).filter_by(
+ item_id=item.id,
+ ).all()
+ return potionitems
+
+ def add_effect_to_ingredient(
+ self,
+ effect: PotionEffect,
+ item: PotionEffect,
+ mag_mult: float = 1,
+ dur_mult: float = 1,
+ val_mult: float = 1
+ ):
+ self.have_session()
+ assert item.id is not None
+ assert effect.id is not None
+ new = PotionItem(
+ item_id=item.id,
+ effect_id=effect.id,
+ mag_multiplier=mag_mult,
+ dur_multiplier=dur_mult,
+ val_multiplier=val_mult
+ )
+ return self.session.add(new)
+
+ def get_items_by_effect(self,
+ effect: PotionEffect) -> List[PotionItem]:
+ self.have_session()
+ assert PotionEffect.id is not None
+ potion_items = self.session.query(PotionItem).filter_by(
+ effect_id=effect.id
+ ).all()
+ return potion_items
+
+ def add_requirement(self, name: str, desc: str) -> Requirement:
+ self.have_session()
+ requirement = Requirement(name=name, desc=desc)
+ self.session.add(requirement)
+ return requirement
+
+ def get_requirements_by_name(self, name: str) -> List[Requirement]:
+ self.have_session()
+ reqs = self.session.query(Requirement).filter_by(name=name
+ ).all()
+ return reqs
+
+ def add_recipe(
+ self,
+ result: Item,
+ quantity: int,
+ requirement: Requirement = None
+ ) -> Recipe:
+ self.have_session()
+ assert result.id is not None
+ recipe = Recipe(result_id=result.id, quantity=quantity)
+
+ if requirement is not None:
+ assert requirement.id is not None
+ recipe.requirement_id = requirement.id
+
+ self.session.add(recipe)
+ return recipe
+
+ def add_ingredient_to_recipe(
+ self, recipe: Recipe, ingredient: Item, quantity: int = 1
+ ):
+ self.have_session()
+ assert recipe.id is not None
+ assert ingredient.id is not None
+ self.session.add(
+ CraftingIngredient(
+ recipe_id=recipe.id,
+ ingredient_id=ingredient.id,
+ quantity=quantity,
+ )
+ )
+
+ def get_ingredients_for_recipe(
+ self, recipe: Recipe
+ ) -> List[CraftingIngredient]:
+ self.have_session()
+ assert recipe.id is not None
+ crafting_ingredients = self.session.query(
+ CraftingIngredient
+ ).filter_by(
+ recipe_id=recipe.id,
+ ).all()
+ return crafting_ingredients
+
+ def get_recipes_for_item(
+ self, item: Item, requirements: List[Requirement] = None
+ ):
+ """Get all available Recipes that produce a given item. Requirements can be used to restrict the available recipes. A list of Requirements should be given as requirements. requirements=[] will list all recipes with no prerequisites, whilst requirements=None will list all recipes regardless of requirements."""
+ self.have_session()
+ assert item.id is not None
+ query = self.session.query(Recipe).filter_by(result_id=item.id)
+
+ if requirements is not None:
+ reqs = [None]
+ for req in requirements:
+ assert req.id is not None
+ reqs.append(req.id)
+ query.filter(Recipe.requirement_id.in_(reqs))
+
+ return query.all()
|
joshbarrass/SkyrimCrafting
|
77faa4caad3880493564deacc5c102e9440bb85f
|
diff --git a/test/test_wrappers.py b/test/test_wrappers.py
new file mode 100644
index 0000000..d7f0cc2
--- /dev/null
+++ b/test/test_wrappers.py
@@ -0,0 +1,194 @@
+import unittest
+from sqlalchemy import MetaData
+from database.wrapper import Database
+from database.models import Item, PotionEffect, PotionItem, Requirement, Recipe, CraftingIngredient
+
+TEST_ITEM_NAME = "Test"
+TEST_ITEM_VALUE = 1
+TEST_ITEM_WEIGHT = 0.5
+TEST_ITEM_ID = 100
+
+TEST_EFFECT_NAME = "TestEffect"
+TEST_EFFECT_DESC = "Description"
+TEST_EFFECT_COST = 1
+TEST_EFFECT_MAG = 2
+TEST_EFFECT_DUR = 3
+TEST_EFFECT_VALUE = 4
+TEST_EFFECT_NEG = True
+TEST_EFFECT_VARYDUR = False
+TEST_EFFECT_ID = 200
+
+TEST_REQUIREMENT_NAME = "Requirement"
+TEST_REQUIREMENT_DESC = "This is a test"
+
+TEST_RECIPE_QUANTITY = 2
+
+class TestWrappers(unittest.TestCase):
+ def setUp(self):
+ self.db = Database("sqlite:///:memory:")
+ testitem = self.db.new_item(
+ TEST_ITEM_NAME, TEST_ITEM_VALUE, TEST_ITEM_WEIGHT,
+ TEST_ITEM_ID
+ )
+ self.db.new_potion_effect(
+ TEST_EFFECT_NAME, TEST_EFFECT_DESC, TEST_EFFECT_COST,
+ TEST_EFFECT_MAG, TEST_EFFECT_DUR, TEST_EFFECT_VALUE,
+ TEST_EFFECT_NEG, TEST_EFFECT_VARYDUR, TEST_EFFECT_ID
+ )
+ testreq = self.db.add_requirement(
+ TEST_REQUIREMENT_NAME, TEST_REQUIREMENT_DESC
+ )
+ self.db.commit()
+ testrecipe = self.db.add_recipe(
+ testitem, TEST_RECIPE_QUANTITY, testreq
+ )
+ self.db.commit()
+ self.db.add_ingredient_to_recipe(testrecipe, testitem)
+ self.db.commit()
+
+ def tearDown(self):
+ self.db.close_session()
+ m = MetaData()
+ m.reflect(self.db.engine)
+ m.drop_all(self.db.engine)
+ self.db.engine.dispose()
+ self.db = None
+
+ def assertTestItem(self, item):
+ self.assertEqual(
+ item.name, TEST_ITEM_NAME, "Name does not match"
+ )
+ self.assertEqual(
+ item.value, TEST_ITEM_VALUE, "Value does not match"
+ )
+ self.assertEqual(
+ item.weight, TEST_ITEM_WEIGHT, "Weight does not match"
+ )
+ self.assertEqual(item.id, TEST_ITEM_ID, "ID does not match")
+
+ def assertTestEffect(self, effect: PotionEffect):
+ self.assertEqual(
+ effect.name, TEST_EFFECT_NAME, "Name does not match"
+ )
+ self.assertEqual(
+ effect.description, TEST_EFFECT_DESC,
+ "Description does not match"
+ )
+ self.assertEqual(
+ effect.base_cost, TEST_EFFECT_COST, "Cost does not match"
+ )
+ self.assertEqual(
+ effect.base_mag, TEST_EFFECT_MAG,
+ "Magnitude does not match"
+ )
+ self.assertEqual(
+ effect.base_dur, TEST_EFFECT_DUR, "Duration does not match"
+ )
+ self.assertEqual(
+ effect.value, TEST_EFFECT_VALUE, "Value does not match"
+ )
+ self.assertEqual(
+ effect.is_negative, TEST_EFFECT_NEG,
+ "is_negative does not match"
+ )
+ self.assertEqual(
+ effect.vary_duration, TEST_EFFECT_VARYDUR,
+ "vary_duration does not match"
+ )
+ self.assertEqual(
+ effect.id, TEST_EFFECT_ID, "ID does not match"
+ )
+
+ def assertTestRequirement(self, req: Requirement):
+ self.assertEqual(
+ req.name, TEST_REQUIREMENT_NAME, "Name does not match"
+ )
+ self.assertEqual(
+ req.desc, TEST_REQUIREMENT_DESC,
+ "Description does not match"
+ )
+
+ def assertTestRecipe(self, recipe: Recipe):
+ self.assertEqual(
+ recipe.result_id, TEST_ITEM_ID, "Wrong item ID"
+ )
+ self.assertEqual(
+ recipe.requirement.name, TEST_REQUIREMENT_NAME,
+ "Wrong requirement name"
+ )
+ self.assertEqual(
+ recipe.quantity, TEST_RECIPE_QUANTITY, "Wrong quantity"
+ )
+
+ def test_new_item(self):
+ items = self.db.session.query(Item).filter_by(
+ name=TEST_ITEM_NAME
+ ).all()
+ self.assertEqual(len(items), 1, "Should only be one item")
+ self.assertTestItem(items[0])
+
+ def test_get_item_by_id(self):
+ item = self.db.get_item_by_ID(TEST_ITEM_ID)
+ self.assertTestItem(item)
+
+ def test_get_items_by_name(self):
+ items = self.db.get_items_by_name(TEST_ITEM_NAME)
+ self.assertEqual(len(items), 1)
+ self.assertTestItem(items[0])
+
+ def test_new_potion_effect(self):
+ effect = self.db.session.query(PotionEffect).filter_by(
+ id=TEST_EFFECT_ID
+ ).first()
+ self.assertTestEffect(effect)
+
+ def test_get_effect_by_ID(self):
+ effect = self.db.get_effect_by_ID(TEST_EFFECT_ID)
+ self.assertTestEffect(effect)
+
+ def test_get_effect_by_name(self):
+ effects = self.db.get_effects_by_name(TEST_EFFECT_NAME)
+ self.assertEqual(len(effects), 1)
+ self.assertTestEffect(effects[0])
+
+ def test_effect_association(self):
+ item = self.db.get_item_by_ID(TEST_ITEM_ID)
+ effect = self.db.get_effect_by_ID(TEST_EFFECT_ID)
+ self.db.add_effect_to_ingredient(effect, item, 1, 2, 3)
+ self.db.commit()
+
+ potionitems = self.db.get_effects_by_item(item)
+ self.assertEqual(len(potionitems), 1)
+ self.assertTestEffect(potionitems[0].effect)
+ self.assertTestItem(potionitems[0].item)
+
+ potionitems = self.db.get_items_by_effect(effect)
+ self.assertEqual(len(potionitems), 1)
+ self.assertTestEffect(potionitems[0].effect)
+ self.assertTestItem(potionitems[0].item)
+
+ def test_add_requirement(self):
+ req = self.db.session.query(Requirement).filter_by(
+ name=TEST_REQUIREMENT_NAME
+ ).first()
+ self.assertTestRequirement(req)
+
+ def test_get_requirements_by_name(self):
+ reqs = self.db.get_requirements_by_name(TEST_REQUIREMENT_NAME)
+ self.assertEqual(len(reqs), 1)
+ self.assertTestRequirement(reqs[0])
+
+ def test_add_recipe(self):
+ recipe = self.db.session.query(Recipe).first()
+ self.assertTestRecipe(recipe)
+
+ def test_get_ingredients_for_recipe(self):
+ recipe = self.db.session.query(Recipe).first()
+ ingredients = self.db.get_ingredients_for_recipe(recipe)
+ self.assertEqual(len(ingredients), 1)
+ self.assertTestItem(ingredients[0].ingredient)
+ self.assertTrue(recipe is ingredients[0].recipe)
+ self.assertEqual(ingredients[0].quantity, 1)
+
+if __name__ == '__main__':
+ unittest.main()
|
Add database wrapper functions
These functions should simplify the process of retrieving data. At this stage, these functions should be generic; there may be things we don't need at this stage. When it comes to implementing the functionality of the program, these functions should be the basis for interacting with the database, and it would be better to implement more complex functions that use the database on top of these functions; the amount of direct interaction with SQLAlchemy should be minimised.
|
0.0
|
77faa4caad3880493564deacc5c102e9440bb85f
|
[
"test/test_wrappers.py::TestWrappers::test_add_recipe",
"test/test_wrappers.py::TestWrappers::test_add_requirement",
"test/test_wrappers.py::TestWrappers::test_effect_association",
"test/test_wrappers.py::TestWrappers::test_get_effect_by_ID",
"test/test_wrappers.py::TestWrappers::test_get_effect_by_name",
"test/test_wrappers.py::TestWrappers::test_get_ingredients_for_recipe",
"test/test_wrappers.py::TestWrappers::test_get_item_by_id",
"test/test_wrappers.py::TestWrappers::test_get_items_by_name",
"test/test_wrappers.py::TestWrappers::test_get_requirements_by_name",
"test/test_wrappers.py::TestWrappers::test_new_item",
"test/test_wrappers.py::TestWrappers::test_new_potion_effect"
] |
[] |
{
"failed_lite_validators": [
"has_added_files",
"has_removed_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-10-01 15:54:21+00:00
|
mit
| 3,338 |
|
josiah-wolf-oberholtzer__uqbar-94
|
diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml
index d1960e1..84cbc1e 100644
--- a/.github/workflows/publish.yml
+++ b/.github/workflows/publish.yml
@@ -9,11 +9,11 @@ jobs:
name: Build docs
runs-on: ubuntu-latest
steps:
- - uses: actions/checkout@v3
+ - uses: actions/checkout@v4
- name: Set up Python
- uses: actions/setup-python@v4
+ uses: actions/setup-python@v5
with:
- python-version: "3.11"
+ python-version: "3.12"
cache: pip
cache-dependency-path: "**/pyproject.toml"
- name: Install Uqbar
@@ -22,7 +22,7 @@ jobs:
run: sudo apt-get install --yes graphviz
- name: Build docs
run: make docs
- - uses: actions/upload-artifact@v3
+ - uses: actions/upload-artifact@v4
with:
name: docs
path: ./docs/build/html/
@@ -31,7 +31,7 @@ jobs:
name: Build source distribution
runs-on: ubuntu-latest
steps:
- - uses: actions/checkout@v3
+ - uses: actions/checkout@v4
- name: Build sdist
run: pipx run build --sdist
- name: Build universal wheel
@@ -46,11 +46,11 @@ jobs:
needs: [build-docs, build-dist]
runs-on: ubuntu-latest
steps:
- - uses: actions/download-artifact@v3
+ - uses: actions/download-artifact@v4
with:
name: dist
path: dist
- - uses: pypa/[email protected]
+ - uses: pypa/[email protected]
with:
user: __token__
password: ${{ secrets.PYPI_API_TOKEN }}
@@ -60,12 +60,12 @@ jobs:
needs: [upload-to-pypi]
runs-on: ubuntu-latest
steps:
- - uses: actions/download-artifact@v3
+ - uses: actions/download-artifact@v4
with:
name: docs
path: docs
- name: Clone gh-pages
- uses: actions/checkout@v3
+ uses: actions/checkout@v4
with:
path: gh-pages
ref: gh-pages
diff --git a/pyproject.toml b/pyproject.toml
index 0e220cb..6445b34 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -17,6 +17,7 @@ classifiers = [
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
+ "Programming Language :: Python :: 3.12",
]
dependencies = [
"Sphinx >= 5.3.0",
@@ -60,7 +61,7 @@ skip-magic-trailing-comma = true
target-version = ["py311"]
[tool.cibuildwheel]
-build = "cp38-* cp39-* cp310-* cp311-*"
+build = "cp38-* cp39-* cp310-* cp311-* cp312-*"
test-command = ['python -c "import uqbar"']
[tool.isort]
diff --git a/uqbar/_version.py b/uqbar/_version.py
index 27cde40..09e40b5 100644
--- a/uqbar/_version.py
+++ b/uqbar/_version.py
@@ -1,2 +1,2 @@
-__version_info__ = (0, 7, 1)
+__version_info__ = (0, 7, 2)
__version__ = ".".join(str(x) for x in __version_info__)
diff --git a/uqbar/book/sphinx.py b/uqbar/book/sphinx.py
index a8337d3..5e88741 100644
--- a/uqbar/book/sphinx.py
+++ b/uqbar/book/sphinx.py
@@ -3,12 +3,13 @@ import contextlib
import importlib
import inspect
import itertools
+import logging
import pickle
import sqlite3
import traceback
from typing import Any, Dict
-from docutils.frontend import OptionParser
+from docutils.frontend import get_default_settings
from docutils.nodes import Element, General, doctest_block, literal_block
from docutils.parsers.rst import Directive, Parser
from docutils.parsers.rst.directives import flag, register_directive
@@ -17,6 +18,8 @@ from sphinx.util.nodes import set_source_info
from .console import Console, ConsoleError, ConsoleInput, ConsoleOutput
+logger = logging.getLogger(__name__)
+
try:
import black
@@ -357,7 +360,7 @@ def parse_rst(rst_string):
parser = Parser()
for name, class_ in []: # Add custom directives here
register_directive(name, class_)
- settings = OptionParser(components=(Parser,)).get_default_values()
+ settings = get_default_settings(Parser)
document = new_document("test", settings)
parser.parse(rst_string, document)
document = parser.document
diff --git a/uqbar/io.py b/uqbar/io.py
index 13c7d8d..26d6e41 100644
--- a/uqbar/io.py
+++ b/uqbar/io.py
@@ -6,12 +6,12 @@ import cProfile
import collections
import io
import os
-import pathlib
import platform
import pstats
import subprocess
import sys
import time
+from pathlib import Path
from typing import Generator, List, Optional, Sequence, Tuple, Union
@@ -25,7 +25,7 @@ class DirectoryChange:
### INITIALIZER ###
def __init__(self, directory, verbose=False):
- directory = pathlib.Path(directory).resolve().absolute()
+ directory = Path(directory).resolve().absolute()
if not directory.is_dir():
directory = directory.parent
self._directory = directory
@@ -37,7 +37,7 @@ class DirectoryChange:
def __enter__(self):
if self.verbose:
print("Changing directory to {} ...".format(self.directory))
- self._directory_stack.append(pathlib.Path.cwd())
+ self._directory_stack.append(Path.cwd())
os.chdir(str(self._directory))
return self
@@ -227,18 +227,16 @@ class Timer:
return self._verbose
-def find_common_prefix(
- paths: Sequence[Union[str, pathlib.Path]]
-) -> Optional[pathlib.Path]:
+def find_common_prefix(paths: Sequence[Union[str, Path]]) -> Optional[Path]:
"""
Find the common prefix of two or more paths.
::
- >>> import pathlib
- >>> one = pathlib.Path('foo/bar/baz')
- >>> two = pathlib.Path('foo/quux/biz')
- >>> three = pathlib.Path('foo/quux/wuux')
+ >>> from pathlib import Path
+ >>> one = Path('foo/bar/baz')
+ >>> two = Path('foo/quux/biz')
+ >>> three = Path('foo/quux/wuux')
::
@@ -250,7 +248,7 @@ def find_common_prefix(
"""
counter: collections.Counter = collections.Counter()
for path in paths:
- path = pathlib.Path(path)
+ path = Path(path)
counter.update([path])
counter.update(path.parents)
valid_paths = sorted(
@@ -272,21 +270,19 @@ def find_executable(name: str, flags=os.X_OK) -> List[str]:
"""
result = []
extensions = [x for x in os.environ.get("PATHEXT", "").split(os.pathsep) if x]
- path = os.environ.get("PATH", None)
- if path is None:
- return []
- for path in os.environ.get("PATH", "").split(os.pathsep):
- path = os.path.join(path, name)
- if os.access(path, flags):
- result.append(path)
+ for directory_name in os.environ.get("PATH", "").split(os.pathsep):
+ executable_path = Path(directory_name) / name
+ executable_path = executable_path.resolve().absolute()
+ if os.access(executable_path, flags):
+ result.append(str(executable_path))
for extension in extensions:
- path_extension = path + extension
- if os.access(path_extension, flags):
- result.append(path_extension)
+ extension_path = executable_path.with_suffix(extension)
+ if os.access(extension_path, flags):
+ result.append(str(extension_path))
return result
-def open_path(path: pathlib.Path) -> None:
+def open_path(path: Path) -> None:
if platform.system() == "Darwin":
subprocess.run(["open", str(path)], check=True)
elif platform.system() == "Linux":
@@ -295,9 +291,7 @@ def open_path(path: pathlib.Path) -> None:
os.startfile(str(path)) # type: ignore
-def relative_to(
- source_path: Union[str, pathlib.Path], target_path: Union[str, pathlib.Path]
-) -> pathlib.Path:
+def relative_to(source_path: Union[str, Path], target_path: Union[str, Path]) -> Path:
"""
Generates relative path from ``source_path`` to ``target_path``.
@@ -305,9 +299,9 @@ def relative_to(
::
- >>> import os, pathlib
- >>> source = pathlib.Path('foo/bar/baz')
- >>> target = pathlib.Path('foo/quux/biz')
+ >>> from pathlib import Path
+ >>> source = Path('foo/bar/baz')
+ >>> target = Path('foo/quux/biz')
::
@@ -318,6 +312,7 @@ def relative_to(
::
+ >>> import os
>>> import uqbar.io
>>> str(uqbar.io.relative_to(source, target)).replace(os.path.sep, "/")
'../../quux/biz'
@@ -325,34 +320,32 @@ def relative_to(
:param source_path: the source path
:param target_path: the target path
"""
- source_path = pathlib.Path(source_path).absolute()
+ source_path = Path(source_path).absolute()
if source_path.is_file():
source_path = source_path.parent
- target_path = pathlib.Path(target_path).absolute()
+ target_path = Path(target_path).absolute()
common_prefix = find_common_prefix([source_path, target_path])
if not common_prefix:
raise ValueError("No common prefix")
source_path = source_path.relative_to(common_prefix)
target_path = target_path.relative_to(common_prefix)
- result = pathlib.Path(*[".."] * len(source_path.parts))
+ result = Path(*[".."] * len(source_path.parts))
return result / target_path
def walk(
- root_path: Union[str, pathlib.Path], top_down: bool = True
-) -> Generator[
- Tuple[pathlib.Path, Sequence[pathlib.Path], Sequence[pathlib.Path]], None, None
-]:
+ root_path: Union[str, Path], top_down: bool = True
+) -> Generator[Tuple[Path, Sequence[Path], Sequence[Path]], None, None]:
"""
Walks a directory tree.
- Like :py:func:`os.walk` but yielding instances of :py:class:`pathlib.Path`
+ Like :py:func:`os.walk` but yielding instances of :py:class:`Path`
instead of strings.
:param root_path: foo
:param top_down: bar
"""
- root_path = pathlib.Path(root_path)
+ root_path = Path(root_path)
directory_paths, file_paths = [], []
for path in sorted(root_path.iterdir()):
if path.is_dir():
@@ -368,10 +361,7 @@ def walk(
def write(
- contents: str,
- path: Union[str, pathlib.Path],
- verbose: bool = False,
- logger_func=None,
+ contents: str, path: Union[str, Path], verbose: bool = False, logger_func=None
) -> bool:
"""
Writes ``contents`` to ``path``.
@@ -386,7 +376,7 @@ def write(
:param verbose: whether to print output
"""
print_func = logger_func or print
- path = pathlib.Path(path)
+ path = Path(path)
printed_path = str(path).replace(os.path.sep, "/") # same display on Windows
if path.exists():
old_contents = path.read_text()
diff --git a/uqbar/objects.py b/uqbar/objects.py
index 59d6c37..08f2702 100644
--- a/uqbar/objects.py
+++ b/uqbar/objects.py
@@ -197,8 +197,8 @@ def get_vars(expr):
::
- >>> args
- OrderedDict([('arg1', 'a'), ('arg2', 'b')])
+ >>> dict(args)
+ {'arg1': 'a', 'arg2': 'b'}
::
|
josiah-wolf-oberholtzer/uqbar
|
4328e723fd91ba10aa2634ff59b5127ca9ffa5af
|
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index 2e84441..d4079fa 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -20,11 +20,11 @@ jobs:
name: Build docs
runs-on: ubuntu-latest
steps:
- - uses: actions/checkout@v3
+ - uses: actions/checkout@v4
- name: Set up Python
- uses: actions/setup-python@v4
+ uses: actions/setup-python@v5
with:
- python-version: "3.11"
+ python-version: "3.12"
cache: pip
cache-dependency-path: "**/pyproject.toml"
- name: Install Uqbar
@@ -38,11 +38,11 @@ jobs:
name: Lint
runs-on: ubuntu-latest
steps:
- - uses: actions/checkout@v3
+ - uses: actions/checkout@v4
- name: Set up Python
- uses: actions/setup-python@v4
+ uses: actions/setup-python@v5
with:
- python-version: "3.11"
+ python-version: "3.12"
cache: pip
cache-dependency-path: "**/pyproject.toml"
- name: Install Uqbar
@@ -61,16 +61,16 @@ jobs:
fail-fast: false
matrix:
os: [ubuntu-latest]
- python-version: ["3.8", "3.9", "3.10", "3.11"]
+ python-version: ["3.8", "3.9", "3.10", "3.11", "3.12"]
include:
- os: macos-latest
- python-version: "3.10"
+ python-version: "3.11"
- os: windows-latest
python-version: "3.11"
steps:
- - uses: actions/checkout@v3
+ - uses: actions/checkout@v4
- name: Set up Python ${{ matrix.python-version }}
- uses: actions/setup-python@v4
+ uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
cache: pip
diff --git a/tests/conftest.py b/tests/conftest.py
index c4414e1..f9974d7 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -1,9 +1,8 @@
-import os
-import pathlib
import shutil
+import sys
+from pathlib import Path
import pytest
-from sphinx.testing.path import path
pytest_plugins = "sphinx.testing.fixtures"
@@ -15,16 +14,20 @@ collect_ignore = ["roots"]
def remove_sphinx_projects(sphinx_test_tempdir):
# Even upon exception, remove any directory from temp area
# which looks like a Sphinx project. This ONLY runs once.
- roots_path = pathlib.Path(sphinx_test_tempdir)
- for d in roots_path.iterdir():
- if d.is_dir():
- if pathlib.Path(d, "_build").exists():
+ roots_path = Path(sphinx_test_tempdir)
+ for path in roots_path.iterdir():
+ if path.is_dir():
+ if (Path(path) / "_build").exists():
# This directory is a Sphinx project, remove it
- shutil.rmtree(str(d))
- yield
+ shutil.rmtree(path)
@pytest.fixture()
def rootdir(remove_sphinx_projects):
- roots = path(os.path.dirname(__file__) or ".").abspath() / "roots"
- yield roots
+ root_path = Path(__file__).parent / "roots"
+ if sys.version_info > (3, 8):
+ from sphinx.testing.path import path
+
+ yield path(str(root_path))
+ else:
+ yield root_path
diff --git a/tests/test_io_find_executable.py b/tests/test_io_find_executable.py
index a915807..030af81 100644
--- a/tests/test_io_find_executable.py
+++ b/tests/test_io_find_executable.py
@@ -1,12 +1,17 @@
import platform
import sys
+from pathlib import Path
import uqbar.io
def test_find_executable():
+ print(f"{sys.executable=}")
file_name = "python"
if platform.system() == "Windows":
file_name = "python.exe"
found = uqbar.io.find_executable(file_name)
- assert any(sys.executable.startswith(_) for _ in found)
+ sys_executable = str(Path(sys.executable).resolve())
+ print(f"{sys_executable=}")
+ print(f"{found=}")
+ assert sys_executable in found
diff --git a/tests/test_sphinx_book.py b/tests/test_sphinx_book.py
index 1659576..89458f5 100644
--- a/tests/test_sphinx_book.py
+++ b/tests/test_sphinx_book.py
@@ -1,4 +1,3 @@
-import os
import pathlib
import shutil
import sys
@@ -576,15 +575,13 @@ def test_sphinx_book_text_broken_strict(app, status, warning, rm_dirs):
)
)
assert normalize(ansi_escape(warning.getvalue())) == normalize(
- """
- {srcdir}index.rst:15: WARNING:
+ f"""
+ {app.srcdir / "index.rst"}:15: WARNING:
<literal_block xml:space="preserve">>>> print(this_name_does_not_exist)</literal_block>
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'this_name_does_not_exist' is not defined
- """.format(
- srcdir=app.srcdir + os.path.sep
- )
+ """
)
|
Sphinx 8/9 warning and deprecation warning
```bash
tests/conftest.py:6
/build/uqbar-0.7.1/tests/conftest.py:6: RemovedInSphinx90Warning: 'sphinx.testing.path' is deprecated. Use 'os.path' or 'pathlib' instead.
from sphinx.testing.path import path
tests/test_book_sphinx.py: 11 warnings
/build/uqbar-0.7.1/uqbar/book/sphinx.py:360: DeprecationWarning: The frontend.OptionParser class will be replaced by a subclass of argparse.ArgumentParser in Docutils 0.21 or later.
settings = OptionParser(components=(Parser,)).get_default_values()
tests/test_book_sphinx.py: 759 warnings
/nix/store/y4dxr00qg40pwgxx9nxj61091zk8bsvl-python3-3.12.1/lib/python3.12/optparse.py:1000: DeprecationWarning: The frontend.Option class will be removed in Docutils 0.21 or later.
option = self.option_class(*args, **kwargs)
tests/test_sphinx_book.py::test_sphinx_book_text_broken_strict
/build/uqbar-0.7.1/tests/test_sphinx_book.py:578: RemovedInSphinx80Warning: Sphinx 8 will drop support for representing paths as strings. Use "pathlib.Path" or "os.fspath" instead.
assert normalize(ansi_escape(warning.getvalue())) == normalize(
```
|
0.0
|
4328e723fd91ba10aa2634ff59b5127ca9ffa5af
|
[
"tests/test_io_find_executable.py::test_find_executable"
] |
[
"tests/test_sphinx_book.py::test_sphinx_book_latex_cached",
"tests/test_sphinx_book.py::test_sphinx_book_text_cached",
"tests/test_sphinx_book.py::test_sphinx_book_text_uncached",
"tests/test_sphinx_book.py::test_sphinx_book_text_broken_setup",
"tests/test_sphinx_book.py::test_sphinx_book_text_broken_teardown"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2024-02-14 14:02:10+00:00
|
mit
| 3,339 |
|
joweich__chat-miner-93
|
diff --git a/chatminer/chatparsers.py b/chatminer/chatparsers.py
index d402c2a..d1d2890 100644
--- a/chatminer/chatparsers.py
+++ b/chatminer/chatparsers.py
@@ -164,8 +164,11 @@ class WhatsAppParser(Parser):
datestr, dayfirst=self._datefmt.is_dayfirst, fuzzy=True
)
- if ":" in author_and_body:
+ if ": " in author_and_body:
author, body = [x.strip() for x in author_and_body.split(": ", 1)]
+ elif ":." in author_and_body:
+ author = [x.strip() for x in author_and_body.split(":.", 1)][0]
+ body = "<Disappearing Message>"
else:
author = "System"
body = author_and_body.strip()
|
joweich/chat-miner
|
a812fc4f70cf40e6f3d0b65f9a044ae4f2a4aab3
|
diff --git a/test/test_whatsapp.py b/test/test_whatsapp.py
index f95dc1f..5459ef5 100644
--- a/test/test_whatsapp.py
+++ b/test/test_whatsapp.py
@@ -13,7 +13,7 @@ def assert_equal_from_file(file):
parse_dates=["timestamp"],
infer_datetime_format=True,
)
- assert_frame_equal(df_test, df_res)
+ assert_frame_equal(df_test, df_res, check_dtype=False)
def test_dateformat1():
diff --git a/test/whatsapp/test_dateformat1.txt b/test/whatsapp/test_dateformat1.txt
index 61f666d..74c85a4 100644
--- a/test/whatsapp/test_dateformat1.txt
+++ b/test/whatsapp/test_dateformat1.txt
@@ -1,3 +1,4 @@
+12/24/19, 11:23 - John Doe:.
12/24/19, 11:23 - John Doe: Lorem ipsum dolor sit amet.
12/24/19, 11:23 - John Doe: Lorem ipsum : dolor sit amet.
12/26/19, 11:55 - John-John Doe: Lorem ipsum : dolor sit amet.
diff --git a/test/whatsapp/test_dateformat1_target.csv b/test/whatsapp/test_dateformat1_target.csv
index fa1477a..345a5b6 100644
--- a/test/whatsapp/test_dateformat1_target.csv
+++ b/test/whatsapp/test_dateformat1_target.csv
@@ -8,3 +8,4 @@ timestamp,author,message,weekday,hour,words,letters
2019-12-26 11:55:00,John-John Doe,Lorem ipsum : dolor sit amet.,Thursday,11,6,29
2019-12-24 11:23:00,John Doe,Lorem ipsum : dolor sit amet.,Tuesday,11,6,29
2019-12-24 11:23:00,John Doe,Lorem ipsum dolor sit amet.,Tuesday,11,5,27
+2019-12-24 11:23:00,John Doe,<Disappearing Message>,Tuesday,11,2,22
|
ValueError: not enough values to unpack (expected 2, got 1)
Seeing the following error while using the WhatsApp parser:
```
22.04.2023 12:04:32 INFO
Depending on the platform, the message format in chat logs might not be
standardized accross devices/versions/localization and might change over
time. Please report issues including your message format via GitHub.
22.04.2023 12:04:32 INFO Initialized parser.
22.04.2023 12:04:32 INFO Starting reading raw messages...
22.04.2023 12:04:33 INFO Inferred date format: month/day/year
22.04.2023 12:04:33 INFO Finished reading 39999 raw messages.
22.04.2023 12:04:33 INFO Starting parsing raw messages...
0%| | 1/39999 [00:00<?, ?it/s]
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[6], line 4
1 from chatminer.chatparsers import WhatsAppParser
3 parser = WhatsAppParser("WhatsApp-Chat-Sarmad.txt")
----> 4 parser.parse_file()
5 df = parser.parsed_messages.get_df()
File E:\Projects\whatsapp-chat-miner\whatsapp-analysis\lib\site-packages\chatminer\chatparsers.py:74, in Parser.parse_file(self)
71 self._logger.info("Finished reading %i raw messages.", len(self._raw_messages))
73 self._logger.info("Starting parsing raw messages...")
---> 74 self._parse_raw_messages()
75 self._logger.info("Finished parsing raw messages.")
File E:\Projects\whatsapp-chat-miner\whatsapp-analysis\lib\site-packages\chatminer\chatparsers.py:84, in Parser._parse_raw_messages(self)
82 with logging_redirect_tqdm():
83 for raw_mess in tqdm(self._raw_messages):
---> 84 parsed_mess = self._parse_message(raw_mess)
85 if parsed_mess:
86 self.parsed_messages.append(parsed_mess)
File E:\Projects\whatsapp-chat-miner\whatsapp-analysis\lib\site-packages\chatminer\chatparsers.py:168, in WhatsAppParser._parse_message(self, mess)
163 time = datetimeparser.parse(
164 datestr, dayfirst=self._datefmt.is_dayfirst, fuzzy=True
165 )
167 if ":" in author_and_body:
--> 168 author, body = [x.strip() for x in author_and_body.split(": ", 1)]
169 else:
170 author = "System"
ValueError: not enough values to unpack (expected 2, got 1)
```
Might be because of a format that is not being covered.
|
0.0
|
a812fc4f70cf40e6f3d0b65f9a044ae4f2a4aab3
|
[
"test/test_whatsapp.py::test_dateformat1"
] |
[
"test/test_whatsapp.py::test_dateformat2",
"test/test_whatsapp.py::test_dateformat3",
"test/test_whatsapp.py::test_dateformat4",
"test/test_whatsapp.py::test_dateformat5",
"test/test_whatsapp.py::test_unicode"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2023-04-26 19:45:58+00:00
|
mit
| 3,340 |
|
jparise__flake8-assertive-8
|
diff --git a/flake8_assertive.py b/flake8_assertive.py
index e2dff4c..841356c 100644
--- a/flake8_assertive.py
+++ b/flake8_assertive.py
@@ -49,6 +49,13 @@ def is_assert_method_call(node):
node.func.attr.startswith('assert'))
+def args(node):
+ for arg in node.args:
+ yield arg
+ for arg in node.keywords:
+ yield arg.value
+
+
def wrap_deprecated(func, name):
"""Return a check function for a deprecated assert method call.
@@ -121,56 +128,56 @@ class Checker(object):
yield error
def check_assertequal(self, node):
- if any(arg for arg in node.args if is_constant(arg, None)):
+ if any(arg for arg in args(node) if is_constant(arg, None)):
yield self.error(node, 'A502', 'assertIsNone', obj=None)
- elif any(arg for arg in node.args if is_constant(arg, True)):
+ elif any(arg for arg in args(node) if is_constant(arg, True)):
yield self.error(node, 'A502', 'assertTrue', obj=True)
- elif any(arg for arg in node.args if is_constant(arg, False)):
+ elif any(arg for arg in args(node) if is_constant(arg, False)):
yield self.error(node, 'A502', 'assertFalse', obj=False)
- elif any(arg for arg in node.args if is_function_call(arg, 'round')):
+ elif any(arg for arg in args(node) if is_function_call(arg, 'round')):
yield self.error(node, 'A501',
'built-in rounding of assertAlmostEqual',
op='round')
def check_assertalmostequal(self, node):
- if any(arg for arg in node.args if is_function_call(arg, 'round')):
+ if any(arg for arg in args(node) if is_function_call(arg, 'round')):
yield self.error(node, 'A501',
'built-in rounding of assertAlmostEqual',
op='round')
def check_assertnotequal(self, node):
- if any(arg for arg in node.args if is_constant(arg, None)):
+ if any(arg for arg in args(node) if is_constant(arg, None)):
yield self.error(node, 'A502', 'assertIsNotNone', obj=None)
- elif any(arg for arg in node.args if is_constant(arg, True)):
+ elif any(arg for arg in args(node) if is_constant(arg, True)):
yield self.error(node, 'A502', 'assertFalse', obj=True)
- elif any(arg for arg in node.args if is_constant(arg, False)):
+ elif any(arg for arg in args(node) if is_constant(arg, False)):
yield self.error(node, 'A502', 'assertTrue', obj=False)
- elif any(arg for arg in node.args if is_function_call(arg, 'round')):
+ elif any(arg for arg in args(node) if is_function_call(arg, 'round')):
yield self.error(node, 'A501',
'built-in rounding of assertNotAlmostEqual',
op='round')
def check_assertnotalmostequal(self, node):
- if any(arg for arg in node.args if is_function_call(arg, 'round')):
+ if any(arg for arg in args(node) if is_function_call(arg, 'round')):
yield self.error(node, 'A501',
'built-in rounding of assertNotAlmostEqual',
op='round')
def check_asserttrue(self, node):
- if (isinstance(node.args[0], ast.Compare) and
- len(node.args[0].ops) == 1):
- op = node.args[0].ops[0]
+ arg = next(args(node), None)
+ if arg and isinstance(arg, ast.Compare) and len(arg.ops) == 1:
+ op = arg.ops[0]
if isinstance(op, ast.In):
yield self.error(node, 'A501', 'assertIn', op='in')
elif isinstance(op, ast.NotIn):
yield self.error(node, 'A501', 'assertNotIn', op='in')
elif isinstance(op, ast.Is):
- if is_constant(node.args[0].comparators[0], None):
+ if is_constant(arg.comparators[0], None):
yield self.error(node, 'A502', 'assertIsNone', obj=None)
else:
yield self.error(node, 'A501', 'assertIs', op='is')
elif isinstance(op, ast.IsNot):
- if is_constant(node.args[0].comparators[0], None):
+ if is_constant(arg.comparators[0], None):
yield self.error(node, 'A502', 'assertIsNotNone', obj=None)
else:
yield self.error(node, 'A501', 'assertIsNot', op='is')
@@ -186,25 +193,25 @@ class Checker(object):
yield self.error(node, 'A500', 'assertGreater', op='>')
elif isinstance(op, ast.GtE):
yield self.error(node, 'A500', 'assertGreaterEqual', op='>=')
- elif is_function_call(node.args[0], 'isinstance'):
+ elif is_function_call(arg, 'isinstance'):
yield self.error(
node, 'A501', 'assertIsInstance', op='isinstance()')
def check_assertfalse(self, node):
- if (isinstance(node.args[0], ast.Compare) and
- len(node.args[0].ops) == 1):
- op = node.args[0].ops[0]
+ arg = next(args(node), None)
+ if arg and isinstance(arg, ast.Compare) and len(arg.ops) == 1:
+ op = arg.ops[0]
if isinstance(op, ast.In):
yield self.error(node, 'A501', 'assertNotIn', op='in')
elif isinstance(op, ast.NotIn):
yield self.error(node, 'A501', 'assertIn', op='in')
elif isinstance(op, ast.Is):
- if is_constant(node.args[0].comparators[0], None):
+ if is_constant(arg.comparators[0], None):
yield self.error(node, 'A502', 'assertIsNotNone', obj=None)
else:
yield self.error(node, 'A501', 'assertIsNot', op='is')
elif isinstance(op, ast.IsNot):
- if is_constant(node.args[0].comparators[0], None):
+ if is_constant(arg.comparators[0], None):
yield self.error(node, 'A502', 'assertIsNone', obj=None)
else:
yield self.error(node, 'A501', 'assertIs', op='is')
@@ -212,7 +219,7 @@ class Checker(object):
yield self.error(node, 'A500', 'assertNotEqual', op='==')
elif isinstance(op, ast.NotEq):
yield self.error(node, 'A500', 'assertEqual', op='!=')
- elif is_function_call(node.args[0], 'isinstance'):
+ elif is_function_call(arg, 'isinstance'):
yield self.error(
node, 'A501', 'assertNotIsInstance', op='isinstance()')
|
jparise/flake8-assertive
|
36d4999f2b345c8f9e812cf7c8c297db94d874bd
|
diff --git a/tests/test_checker.py b/tests/test_checker.py
index 4118ad3..0752a24 100644
--- a/tests/test_checker.py
+++ b/tests/test_checker.py
@@ -148,6 +148,15 @@ class TestChecks(unittest.TestCase):
self.check(
"self.assertFalse(1 != 0)", "A500", "assertEqual() for '!='")
+ def test_keyword_args(self):
+ self.check("self.assertTrue(expr=1)", expected=None)
+ self.check("self.assertTrue(expr=(True is True))", expected="A501")
+ self.check("self.assertEqual(first=1, second=1)", expected=None)
+ self.check("self.assertEqual(first=1, second=None)", "A502")
+ self.check("self.assertEqual(first=None, second=1)", "A502")
+ self.check("self.assertEqual(1, second=1)", expected=None)
+ self.check("self.assertEqual(None, second=1)", "A502")
+
def test_multiple_comparison_ops(self):
self.check("self.assertTrue(1 == 1 == 1)", expected=None)
self.check("self.assertFalse(1 == 1 == 1)", expected=None)
|
can not handle keyword arguments
For the following test case
```python
class TestCase:
def test_one(
self,
):
self.assertTrue(
expr=some_value,
)
```
flake8 raises the following exception.
```python
Traceback (most recent call last):
File "/home/wavenator/.local/bin/flake8", line 8, in <module>
sys.exit(main())
File "/home/wavenator/.local/lib/python3.7/site-packages/flake8/main/cli.py", line 18, in main
app.run(argv)
File "/home/wavenator/.local/lib/python3.7/site-packages/flake8/main/application.py", line 393, in run
self._run(argv)
File "/home/wavenator/.local/lib/python3.7/site-packages/flake8/main/application.py", line 381, in _run
self.run_checks()
File "/home/wavenator/.local/lib/python3.7/site-packages/flake8/main/application.py", line 300, in run_checks
self.file_checker_manager.run()
File "/home/wavenator/.local/lib/python3.7/site-packages/flake8/checker.py", line 331, in run
self.run_serial()
File "/home/wavenator/.local/lib/python3.7/site-packages/flake8/checker.py", line 315, in run_serial
checker.run_checks()
File "/home/wavenator/.local/lib/python3.7/site-packages/flake8/checker.py", line 598, in run_checks
self.run_ast_checks()
File "/home/wavenator/.local/lib/python3.7/site-packages/flake8/checker.py", line 502, in run_ast_checks
for (line_number, offset, text, check) in runner:
File "/home/wavenator/.local/lib/python3.7/site-packages/flake8_assertive.py", line 120, in run
for error in func(node):
File "/home/wavenator/.local/lib/python3.7/site-packages/flake8_assertive.py", line 160, in check_asserttrue
if (isinstance(node.args[0], ast.Compare) and
IndexError: list index out of range
```
It happens because in `check_asserttrue` you assume `.args` exists although it does not in functions with keyword arguments.
I can produce a fix if you want. I also assume that this behavior might happen in other tests in your code. I can fix them if you want me to.
Thanks and I really appreciate your work!
EDIT:
Yep it happens in `check_assertfalse` too.
|
0.0
|
36d4999f2b345c8f9e812cf7c8c297db94d874bd
|
[
"tests/test_checker.py::TestChecks::test_keyword_args"
] |
[
"tests/test_checker.py::TestChecks::test_assertalmostequal_round",
"tests/test_checker.py::TestChecks::test_assertalmostequals",
"tests/test_checker.py::TestChecks::test_assertequal_false",
"tests/test_checker.py::TestChecks::test_assertequal_none",
"tests/test_checker.py::TestChecks::test_assertequal_round",
"tests/test_checker.py::TestChecks::test_assertequal_true",
"tests/test_checker.py::TestChecks::test_assertequals",
"tests/test_checker.py::TestChecks::test_assertfalse_equal",
"tests/test_checker.py::TestChecks::test_assertfalse_in",
"tests/test_checker.py::TestChecks::test_assertfalse_is",
"tests/test_checker.py::TestChecks::test_assertfalse_is_none",
"tests/test_checker.py::TestChecks::test_assertfalse_isinstance",
"tests/test_checker.py::TestChecks::test_assertnotalmostequal_round",
"tests/test_checker.py::TestChecks::test_assertnotalmostequals",
"tests/test_checker.py::TestChecks::test_assertnotequal_false",
"tests/test_checker.py::TestChecks::test_assertnotequal_none",
"tests/test_checker.py::TestChecks::test_assertnotequal_round",
"tests/test_checker.py::TestChecks::test_assertnotequal_true",
"tests/test_checker.py::TestChecks::test_assertnotequals",
"tests/test_checker.py::TestChecks::test_asserttrue_equal",
"tests/test_checker.py::TestChecks::test_asserttrue_greater",
"tests/test_checker.py::TestChecks::test_asserttrue_in",
"tests/test_checker.py::TestChecks::test_asserttrue_is",
"tests/test_checker.py::TestChecks::test_asserttrue_is_none",
"tests/test_checker.py::TestChecks::test_asserttrue_isinstance",
"tests/test_checker.py::TestChecks::test_asserttrue_less",
"tests/test_checker.py::TestChecks::test_deprecated",
"tests/test_checker.py::TestChecks::test_multiple_comparison_ops",
"tests/test_checker.py::TestChecks::test_pattern",
"tests/test_checker.py::TestChecks::test_snakecase"
] |
{
"failed_lite_validators": [
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-12-08 16:10:46+00:00
|
mit
| 3,341 |
|
jpetrucciani__hubspot3-78
|
diff --git a/hubspot3/base.py b/hubspot3/base.py
index 7f9f82f..95937e5 100644
--- a/hubspot3/base.py
+++ b/hubspot3/base.py
@@ -10,7 +10,8 @@ import urllib.request
import urllib.parse
import urllib.error
import zlib
-from typing import List, Union
+from typing import Callable, List, Optional, Union
+from typing_extensions import Literal
from hubspot3 import utils
from hubspot3.utils import force_utf8
from hubspot3.error import (
@@ -30,6 +31,9 @@ from hubspot3.error import (
class BaseClient:
"""Base abstract object for interacting with the HubSpot APIs"""
+ # These rules are too restrictive for the `__init__()` method and attributes.
+ # pylint: disable=too-many-arguments,too-many-instance-attributes
+
# Controls how long we sleep for during retries, overridden by unittests
# so tests run faster
sleep_multiplier = 1
@@ -41,6 +45,12 @@ class BaseClient:
refresh_token: str = None,
client_id: str = None,
client_secret: str = None,
+ oauth2_token_getter: Optional[
+ Callable[[Literal["access_token", "refresh_token"], str], str]
+ ] = None,
+ oauth2_token_setter: Optional[
+ Callable[[Literal["access_token", "refresh_token"], str, str], None]
+ ] = None,
timeout: int = 10,
mixins: List = None,
api_base: str = "api.hubapi.com",
@@ -58,10 +68,18 @@ class BaseClient:
self.__class__.__bases__ = (mixin_class,) + self.__class__.__bases__
self.api_key = api_key
- self.access_token = access_token
- self.refresh_token = refresh_token
+ # These are used as fallbacks if there aren't setters/getters, or if no remote tokens can be
+ # found. The properties without `__` prefixes should generally be used instead of these.
+ self.__access_token = access_token
+ self.__refresh_token = refresh_token
self.client_id = client_id
self.client_secret = client_secret
+ if (oauth2_token_getter is None) != (oauth2_token_setter is None):
+ raise HubspotBadConfig(
+ "You must either specify both the oauth2 token setter and getter, or neither."
+ )
+ self.oauth2_token_getter = oauth2_token_getter
+ self.oauth2_token_setter = oauth2_token_setter
self.log = utils.get_log("hubspot3")
if not disable_auth:
if self.api_key and self.access_token:
@@ -88,8 +106,41 @@ class BaseClient:
"api_key": self.api_key,
"access_token": self.access_token,
"refresh_token": self.refresh_token,
+ "oauth2_token_getter": self.oauth2_token_getter,
+ "oauth2_token_setter": self.oauth2_token_setter,
}
+ @property
+ def access_token(self):
+ if self.oauth2_token_getter:
+ return (
+ self.oauth2_token_getter("access_token", self.client_id)
+ or self.__access_token
+ )
+ return self.__access_token
+
+ @access_token.setter
+ def access_token(self, access_token):
+ if self.oauth2_token_setter:
+ self.oauth2_token_setter("access_token", self.client_id, access_token)
+ self.__access_token = access_token
+
+ @property
+ def refresh_token(self):
+ if self.oauth2_token_getter:
+ return (
+ self.oauth2_token_getter("refresh_token", self.client_id)
+ or self.__refresh_token
+ )
+ return self.__refresh_token
+
+ @refresh_token.setter
+ def refresh_token(self, refresh_token):
+ if self.oauth2_token_setter:
+ self.oauth2_token_setter("refresh_token", self.client_id, refresh_token)
+ else:
+ self.__refresh_token = refresh_token
+
def _prepare_connection_type(self):
connection_types = {
"http": http.client.HTTPConnection,
|
jpetrucciani/hubspot3
|
3833b4b1c44927e8478d578b727df82d7feffb57
|
diff --git a/hubspot3/test/test_lines.py b/hubspot3/test/test_lines.py
index a606a5f..35fab46 100644
--- a/hubspot3/test/test_lines.py
+++ b/hubspot3/test/test_lines.py
@@ -130,6 +130,10 @@ class TestLinesClient(object):
mock_instance = mock_associations_client.return_value
lines_client.link_line_item_to_deal(1, 1)
mock_associations_client.assert_called_with(
- access_token=None, api_key=None, refresh_token=None
+ access_token=None,
+ api_key=None,
+ refresh_token=None,
+ oauth2_token_getter=None,
+ oauth2_token_setter=None,
)
mock_instance.link_line_item_to_deal.assert_called_with(1, 1)
|
Proposal to improve support for oauth2 authentication with multiple clients
## Introduction
Hi @jpetrucciani, I've submitted a small handful of PRs in the past and I'm a regular user/advocate of the project. The company I work at would like to use the library in a distributed environment with oauth2 authentication, but we've run into contention issues where the different containers essentially fight over access tokens because only one can be active at any given time. This leads to almost every request initially failing with 401 errors and then only working after a new access token has been requested from Hubspot. It would be ideal if we could share the tokens across workers through an in-memory store like Redis to avoid these issues. This is a significant enough change that I thought it would be good to open an issue to discuss the approach before implementing it (and I would be happy to implement it, this isn't a request for you to do so).
## How oauth2 is currently handled
The easiest way to initialize the client is through the [`Hubspot3`](https://github.com/jpetrucciani/hubspot3/blob/adca3f8e3e85daa149320eb5229a877eefec1143/hubspot3/__init__.py#L83) class in `__init__.py`. This supports four options which are all required for [Hubspot's oauth authentication scheme](https://developers.hubspot.com/docs/methods/oauth2/oauth2-overview):
- `client_id` - The client ID of the app that's configured for oauth2 authentication. This is non-sensitive and doesn't change.
- `client_secret` - The client secret for the app. This is sensitive and doesn't change.
- `access_token` - This is a temporary token that provides access to the API as an alternative to using the API key. This is sensitive and expires after 6 hours.
- `refresh_token` - This is a temporary token that is required to generate new access tokens after they have expired. This is sensitive, and although it doesn't explicitly expire, it will rotate regularly through the course of requesting new access tokens.
These are stored in a dictionary called `auth` on a `Hubspot3` instance after initialization, and the arguments are passed into the different client classes when they're accessed as properties. For example, accessing the `contacts` property on the client will initialize a new `ContactsClient` instance via this code:
```python
@property
def contacts(self):
"""returns a hubspot3 contacts client"""
from hubspot3.contacts import ContactsClient
return ContactsClient(**self.auth, **self.options)
```
All of the various clients inherit from [BaseClient](https://github.com/jpetrucciani/hubspot3/blob/adca3f8e3e85daa149320eb5229a877eefec1143/hubspot3/base.py#L30) which stores the credentials on instance properties when initialized. The credentials are then used in [`BaseClient._call_raw()`](https://github.com/jpetrucciani/hubspot3/blob/adca3f8e3e85daa149320eb5229a877eefec1143/hubspot3/base.py#L215) whenever a request is made, and a new access token is requested if a `HubspotUnauthorized` exception is raised. The `access_token` and `refresh_token` properties are then replaced on the instance by [this code](https://github.com/jpetrucciani/hubspot3/blob/adca3f8e3e85daa149320eb5229a877eefec1143/hubspot3/base.py#L288):
```python
client = OAuth2Client(**self.options)
refresh_result = client.refresh_tokens(
client_id=self.client_id,
client_secret=self.client_secret,
refresh_token=self.refresh_token,
)
self.access_token = refresh_result["access_token"]
self.refresh_token = refresh_result["refresh_token"]
```
The `OAuth2Client` class handles refreshing the tokens, but it isn't responsible for storage or maintenance of the tokens.
## Proposal for supporting dynamic storage of tokens
A relatively simple and backwards compatible change is adding two new initialization parameters to the `Hubspot3` and `BaseClient` classes:
- `oauth2_token_setter` - A setter with type `typing.Callable([BaseClient, typing.Literal['access_token', 'refresh_token'], str, str)`, a signature of `callable(base_client, token_type, client_id, token)`, and a default value of `lambda self, token_type, client_id, token: setattr(self, token_type, token)`. This would be used to store either of the tokens through either some external mechanism or just on the instance. The client ID is included to accommodate for the possibility of multiple clients being used in the same application.
- `oauth2_token_getter` - A getter with type `typing.Callable([BaseClient, typing.Literal['access_token', 'refresh_token'], str)`, a signature of `callable(token_type, client_id)`, and a default value of `lambda self, token_type, client_id: getattr(self, token_type)`. This would be used to retrieve either of the tokens through some external mechanism.
The logic in the `__init__()` methods of `BaseClient` and `Hubspot3` as well as the `BaseClient._call_raw()` method would then use the setter and getter in place of direct attribute access. The `access_token`/`refresh_token` attributes would still be used by default, and this should be completely backward compatible while also supporting more sophisticated storage mechanisms.
## Conclusion
Apologies for the verbose issue, but I wanted to clearly lay out what I'm proposing. If this sounds good to you, then I'll go ahead and implement it.
|
0.0
|
3833b4b1c44927e8478d578b727df82d7feffb57
|
[
"hubspot3/test/test_lines.py::TestLinesClient::test_link_line_item_to_deal"
] |
[
"hubspot3/test/test_lines.py::TestLinesClient::test_get_path[-crm-objects/v1/objects/line_items/]",
"hubspot3/test/test_lines.py::TestLinesClient::test_get_path[batch-create-crm-objects/v1/objects/line_items/batch-create]",
"hubspot3/test/test_lines.py::TestLinesClient::test_get_path[batch-read-crm-objects/v1/objects/line_items/batch-read]",
"hubspot3/test/test_lines.py::TestLinesClient::test_create",
"hubspot3/test/test_lines.py::TestLinesClient::test_delete",
"hubspot3/test/test_lines.py::TestLinesClient::test_get",
"hubspot3/test/test_lines.py::TestLinesClient::test_update",
"hubspot3/test/test_lines.py::TestLinesClient::test_get_all"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-12-04 19:43:52+00:00
|
mit
| 3,342 |
|
jriddy__zerial-36
|
diff --git a/src/zerial/numpy.py b/src/zerial/numpy.py
index e5f936e..5431318 100644
--- a/src/zerial/numpy.py
+++ b/src/zerial/numpy.py
@@ -33,8 +33,6 @@ if sys.version_info >= (3, 0):
return x.decode()
else:
return str(x)
-
- buffer_to_ndarray = np.frombuffer
else:
numpy_required_passthrus = DEFAULT_PASSTHRUS
@@ -47,14 +45,14 @@ else:
num_to_bytes = lambda obj: memoryview(obj.data)
- buffer_to_ndarray = lambda v, *xs, **kw: np.frombuffer(
- v.tobytes() if isinstance(v, memoryview) else v,
- *xs,
- **kw
- )
+ tostr = lambda x: x
- def tostr(x):
- return x
+
+def buffer_to_ndarray(v, *xs, **kw):
+ v = v.tobytes() if isinstance(v, memoryview) else v
+ # We have to copy to get an "owned", writable array
+ # TODO: find a better way around this that isn't as expensive
+ return np.frombuffer(v, *xs, **kw).copy()
@attr.s
|
jriddy/zerial
|
30867c7d8f6565c180bb34560a5f3b2393896c8a
|
diff --git a/tests/test_numpy.py b/tests/test_numpy.py
new file mode 100644
index 0000000..9f46692
--- /dev/null
+++ b/tests/test_numpy.py
@@ -0,0 +1,82 @@
+import pytest
+
+import attr
+import numpy as np
+
+from zerial.numpy import NdarrayEncoder, the_numpy_structurer
+
+
[email protected]
+def encoder():
+ return NdarrayEncoder()
+
+
[email protected]
+def npztr():
+ return the_numpy_structurer
+
+
+def test_encoder_barfs_on_refcounted_python_objects_in_array(encoder, npztr):
+ arr = np.array([object()])
+ with pytest.raises(TypeError) as ce:
+ encoder.encode(arr, npztr)
+ assert str(ce.value).startswith("cowardly refusing")
+
+
[email protected]('arr', [
+ np.array([]),
+ np.empty((1024, 256, 16), dtype=np.float64),
+ np.random.random((10, 10, 10)),
+ np.random.random((5, 15, 2)).T,
+ # TODO: add more tests here
+])
+def test_encode_decode_stability(arr, encoder, npztr):
+ encoded = encoder.encode(arr, npztr)
+ if isinstance(encoded['%data'], memoryview):
+ # force memory read
+ encoded['%data'] = encoded['%data'].tobytes()
+ decoded = encoder.decode(encoded, npztr)
+ assert (arr == decoded).all()
+
+
+def test_encodes_toplevel_when_given_as_type(npztr, encoder):
+ arr = np.array(range(10), dtype=np.int_)
+ des = npztr.destructure(arr, np.ndarray)
+ enc = encoder.encode(arr, npztr)
+ assert des == enc
+
+
+def test_encodes_toplevel_fails_when_not_given_as_type(npztr, encoder):
+ arr = np.linspace(0, 1)
+ with pytest.raises(attr.exceptions.NotAnAttrsClassError):
+ npztr.destructure(arr)
+
+
[email protected](eq=False)
+class Example(object):
+ arr = attr.ib(type=np.ndarray)
+ other = attr.ib(type=str, default='')
+
+ def __eq__(self, other):
+ return (
+ self.__class__ == other.__class__ and
+ self.other == other.other and
+ (self.arr == other.arr).all()
+ )
+
+
+def test_can_encode_structured_ndarray(npztr):
+ example = Example(np.array([1, 19, 18]))
+ destructed = npztr.destructure(example)
+ restructed = npztr.restructure(Example, destructed)
+ assert example == restructed
+
+
+def test_restructured_array_is_writable(npztr):
+ arr = np.array([1, 2], dtype=np.int_)
+ example = Example(arr)
+ destructured = npztr.destructure(example)
+ restructured = npztr.restructure(Example, destructured)
+ new_arr = restructured.arr
+ new_arr += 2
+ assert ((arr + 2) == new_arr).all()
|
Numpy arrays coming from serialization are not writable
Looks like `np.frombuffer` keeps the `owndata` flag as `False`, which prevents the array from becoming writable.
|
0.0
|
30867c7d8f6565c180bb34560a5f3b2393896c8a
|
[
"tests/test_numpy.py::test_restructured_array_is_writable"
] |
[
"tests/test_numpy.py::test_encoder_barfs_on_refcounted_python_objects_in_array",
"tests/test_numpy.py::test_encode_decode_stability[arr0]",
"tests/test_numpy.py::test_encode_decode_stability[arr1]",
"tests/test_numpy.py::test_encode_decode_stability[arr2]",
"tests/test_numpy.py::test_encode_decode_stability[arr3]",
"tests/test_numpy.py::test_encodes_toplevel_when_given_as_type",
"tests/test_numpy.py::test_encodes_toplevel_fails_when_not_given_as_type",
"tests/test_numpy.py::test_can_encode_structured_ndarray"
] |
{
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-11-08 20:08:59+00:00
|
mit
| 3,343 |
|
jrobichaud__django-structlog-263
|
diff --git a/.readthedocs.yaml b/.readthedocs.yaml
new file mode 100644
index 0000000..31b2ea0
--- /dev/null
+++ b/.readthedocs.yaml
@@ -0,0 +1,22 @@
+# .readthedocs.yaml
+# Read the Docs configuration file
+# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details
+
+# Required
+version: 2
+
+# Set the version of Python and other tools you might need
+build:
+ os: ubuntu-22.04
+ tools:
+ python: "3.11"
+
+# Build documentation in the docs/ directory with Sphinx
+sphinx:
+ configuration: docs/conf.py
+
+# We recommend specifying your dependencies to enable reproducible builds:
+# https://docs.readthedocs.io/en/stable/guides/reproducible-builds.html
+python:
+ install:
+ - requirements: docs/requirements.txt
diff --git a/django_structlog/__init__.py b/django_structlog/__init__.py
index e7fa852..84b7404 100644
--- a/django_structlog/__init__.py
+++ b/django_structlog/__init__.py
@@ -4,6 +4,6 @@
name = "django_structlog"
-VERSION = (5, 1, 0)
+VERSION = (5, 2, 0)
__version__ = ".".join(str(v) for v in VERSION)
diff --git a/django_structlog/celery/receivers.py b/django_structlog/celery/receivers.py
index b44d3e6..19bc4f5 100644
--- a/django_structlog/celery/receivers.py
+++ b/django_structlog/celery/receivers.py
@@ -39,6 +39,7 @@ def receiver_task_pre_run(task_id, task, *args, **kwargs):
signals.bind_extra_task_metadata.send(
sender=receiver_task_pre_run, task=task, logger=logger
)
+ logger.info("task_started", task=task.name)
def receiver_task_retry(request=None, reason=None, einfo=None, **kwargs):
diff --git a/docs/changelog.rst b/docs/changelog.rst
index 8a08055..b42b2d2 100644
--- a/docs/changelog.rst
+++ b/docs/changelog.rst
@@ -2,6 +2,13 @@ Change Log
==========
+5.2.0 (June 29, 2023)
+---------------------
+
+*New:*
+ - Add new event ``task_started``. See `#260 <https://github.com/jrobichaud/django-structlog/issues/260>`_. Special thanks to `@adrenaline681 <https://github.com/adrenaline681>`_.
+
+
5.1.0 (April 22, 2023)
----------------------
diff --git a/docs/events.rst b/docs/events.rst
index e51026c..1fcafcc 100644
--- a/docs/events.rst
+++ b/docs/events.rst
@@ -78,6 +78,8 @@ Task Events
+--------------------+-------------+------------------------------------------------+
| task_retrying | WARNING | Worker retry task |
+--------------------+-------------+------------------------------------------------+
+| task_started | INFO | task just started executing |
++--------------------+-------------+------------------------------------------------+
| task_succeeded | INFO | Task completed successfully |
+--------------------+-------------+------------------------------------------------+
| task_failed | ERROR/INFO* | Task failed |
@@ -122,6 +124,8 @@ These metadata appear once along with their associated event
+------------------+------------------+----------------------------------------+
| task_retrying | reason | reason for retry |
+------------------+------------------+----------------------------------------+
+| task_started | task | name of the task |
++------------------+------------------+----------------------------------------+
| task_failed | error | exception as string |
+------------------+------------------+----------------------------------------+
| task_failed | exception* | exception's traceback |
|
jrobichaud/django-structlog
|
66a9dc16e2298503df93dd6a1f350affd5e499b9
|
diff --git a/test_app/tests/celery/test_receivers.py b/test_app/tests/celery/test_receivers.py
index 1170537..85e95d6 100644
--- a/test_app/tests/celery/test_receivers.py
+++ b/test_app/tests/celery/test_receivers.py
@@ -220,12 +220,16 @@ class TestReceivers(TestCase):
"request_id": expected_request_uuid,
"user_id": expected_user_id,
}
+ task.name = "task_name"
structlog.contextvars.bind_contextvars(foo="bar")
context = structlog.contextvars.get_merged_contextvars(self.logger)
self.assertDictEqual({"foo": "bar"}, context)
- receivers.receiver_task_pre_run(task_id, task)
+ with self.assertLogs(
+ logging.getLogger("django_structlog.celery.receivers"), logging.INFO
+ ) as log_results:
+ receivers.receiver_task_pre_run(task_id, task)
context = structlog.contextvars.get_merged_contextvars(self.logger)
self.assertDictEqual(
@@ -237,6 +241,13 @@ class TestReceivers(TestCase):
context,
)
+ self.assertEqual(1, len(log_results.records))
+ record = log_results.records[0]
+ self.assertEqual("task_started", record.msg["event"])
+ self.assertEqual("INFO", record.levelname)
+ self.assertIn("task", record.msg)
+ self.assertEqual("task_name", record.msg["task"])
+
def test_signal_bind_extra_task_metadata(self):
@receiver(signals.bind_extra_task_metadata)
def receiver_bind_extra_request_metadata(
|
Does django-structlog has compatibility with Celery Beat?
I've configured django-structlog to work with Celery by following the documentation, but I noticed that my Celery Beat worker doesn't produce any logs whenever it sends a new task or if the schedule was changed in the admin panel.
Can django-structlog also log these events from Celery Beat?
|
0.0
|
66a9dc16e2298503df93dd6a1f350affd5e499b9
|
[
"test_app/tests/celery/test_receivers.py::TestReceivers::test_receiver_task_pre_run"
] |
[
"test_app/tests/celery/test_receivers.py::TestReceivers::test_receiver_after_task_publish",
"test_app/tests/celery/test_receivers.py::TestReceivers::test_receiver_after_task_publish_celery_3",
"test_app/tests/celery/test_receivers.py::TestReceivers::test_receiver_before_task_publish_celery_3",
"test_app/tests/celery/test_receivers.py::TestReceivers::test_receiver_before_task_publish_celery_4",
"test_app/tests/celery/test_receivers.py::TestReceivers::test_receiver_task_failure",
"test_app/tests/celery/test_receivers.py::TestReceivers::test_receiver_task_failure_with_throws",
"test_app/tests/celery/test_receivers.py::TestReceivers::test_receiver_task_rejected",
"test_app/tests/celery/test_receivers.py::TestReceivers::test_receiver_task_retry",
"test_app/tests/celery/test_receivers.py::TestReceivers::test_receiver_task_revoked",
"test_app/tests/celery/test_receivers.py::TestReceivers::test_receiver_task_success",
"test_app/tests/celery/test_receivers.py::TestReceivers::test_receiver_task_unknown",
"test_app/tests/celery/test_receivers.py::TestReceivers::test_signal_bind_extra_task_metadata",
"test_app/tests/celery/test_receivers.py::TestReceivers::test_signal_modify_context_before_task_publish_celery_3",
"test_app/tests/celery/test_receivers.py::TestReceivers::test_signal_modify_context_before_task_publish_celery_4"
] |
{
"failed_lite_validators": [
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-06-30 00:42:42+00:00
|
mit
| 3,344 |
|
jrobichaud__django-structlog-309
|
diff --git a/django_structlog/app_settings.py b/django_structlog/app_settings.py
index e54b01b..6f5e914 100644
--- a/django_structlog/app_settings.py
+++ b/django_structlog/app_settings.py
@@ -1,3 +1,5 @@
+import logging
+
from django.conf import settings
@@ -9,5 +11,9 @@ class AppSettings:
def CELERY_ENABLED(self):
return getattr(settings, self.PREFIX + "CELERY_ENABLED", False)
+ @property
+ def STATUS_4XX_LOG_LEVEL(self):
+ return getattr(settings, self.PREFIX + "STATUS_4XX_LOG_LEVEL", logging.WARNING)
+
app_settings = AppSettings()
diff --git a/django_structlog/middlewares/request.py b/django_structlog/middlewares/request.py
index bf0375d..5a11f5a 100644
--- a/django_structlog/middlewares/request.py
+++ b/django_structlog/middlewares/request.py
@@ -1,3 +1,4 @@
+import logging
import uuid
import structlog
@@ -7,6 +8,7 @@ from django.http import Http404
from asgiref import sync
from .. import signals
+from ..app_settings import app_settings
logger = structlog.getLogger(__name__)
@@ -31,7 +33,14 @@ class BaseRequestMiddleWare:
logger=logger,
response=response,
)
- logger.info(
+ if response.status_code >= 500:
+ level = logging.ERROR
+ elif response.status_code >= 400:
+ level = app_settings.STATUS_4XX_LOG_LEVEL
+ else:
+ level = logging.INFO
+ logger.log(
+ level,
"request_finished",
code=response.status_code,
request=self.format_request(request),
@@ -112,9 +121,9 @@ class RequestMiddleware(BaseRequestMiddleWare):
"""``RequestMiddleware`` adds request metadata to ``structlog``'s logger context automatically.
>>> MIDDLEWARE = [
- ... # ...
- ... 'django_structlog.middlewares.RequestMiddleware',
- ... ]
+ ... # ...
+ ... 'django_structlog.middlewares.RequestMiddleware',
+ ... ]
"""
diff --git a/docs/celery.rst b/docs/celery.rst
index 70a8d07..09c4a67 100644
--- a/docs/celery.rst
+++ b/docs/celery.rst
@@ -1,3 +1,5 @@
+.. _celery_integration:
+
Celery Integration
==================
diff --git a/docs/changelog.rst b/docs/changelog.rst
index f012f44..1627e28 100644
--- a/docs/changelog.rst
+++ b/docs/changelog.rst
@@ -17,6 +17,7 @@ See: :ref:`upgrade_6.0`
- :class:`django_structlog.middlewares.SyncRequestMiddleware`
- :class:`django_structlog.middlewares.AsyncRequestMiddleware`
- :class:`django_structlog.middlewares.request_middleware_router`
+ - ``4XX`` status codes now log by default as ``WARNING`` and ``5XX`` as ``ERROR``. The behaviour of ``4XX`` can be customized with :ref:`configuration`. See `#308 <https://github.com/jrobichaud/django-structlog/issues/308>`_. Special thanks to `@adinhodovic <https://github.com/adinhodovic>`_.
5.3.0 (June 30, 2023)
diff --git a/docs/configuration.rst b/docs/configuration.rst
new file mode 100644
index 0000000..7ff608f
--- /dev/null
+++ b/docs/configuration.rst
@@ -0,0 +1,25 @@
+.. _configuration:
+
+Configuration
+=============
+
+In your ``settings.py`` you can customize ``django-structlog``.
+
+Example:
+
+.. code-block:: python
+
+ import logging
+ DJANGO_STRUCTLOG_STATUS_4XX_LOG_LEVEL = logging.INFO
+
+
+Settings
+--------
+
++---------------------------------------+---------+-----------------+-------------------------------+
+| Key | Type | Default | Description |
++=======================================+=========+=================+===============================+
+| DJANGO_STRUCTLOG_CELERY_ENABLED | boolean | False | See :ref:`celery_integration` |
++---------------------------------------+---------+-----------------+-------------------------------+
+| DJANGO_STRUCTLOG_STATUS_4XX_LOG_LEVEL | int | logging.WARNING | Log level of 4XX status codes |
++---------------------------------------+---------+-----------------+-------------------------------+
diff --git a/docs/events.rst b/docs/events.rst
index 5cbce35..90c9e1d 100644
--- a/docs/events.rst
+++ b/docs/events.rst
@@ -7,15 +7,15 @@ Django's RequestMiddleware
Request Events
^^^^^^^^^^^^^^
-+------------------+---------+------------------------------+
-| Event | Type | Description |
-+==================+=========+==============================+
-| request_started | INFO | Django received a request |
-+------------------+---------+------------------------------+
-| request_finished | INFO | request completed normally |
-+------------------+---------+------------------------------+
-| request_failed | ERROR | unhandled exception occurred |
-+------------------+---------+------------------------------+
++------------------+--------------------+----------------------------------------------------+
+| Event | Type | Description |
++==================+====================+====================================================+
+| request_started | INFO | Django received a request |
++------------------+--------------------+----------------------------------------------------+
+| request_finished | INFO/WARNING/ERROR | request completed with status (2XX or 3XX)/4XX/5XX |
++------------------+--------------------+----------------------------------------------------+
+| request_failed | ERROR | unhandled exception occurred |
++------------------+--------------------+----------------------------------------------------+
Request Bound Metadata
^^^^^^^^^^^^^^^^^^^^^^
diff --git a/docs/index.rst b/docs/index.rst
index dd8bdd6..2c4c189 100644
--- a/docs/index.rst
+++ b/docs/index.rst
@@ -11,6 +11,7 @@ Contents, indices and tables
getting_started
celery
+ configuration
api_documentation
events
example_outputs
|
jrobichaud/django-structlog
|
8df457d0979b0581ea3ca28184902c4c1a28d138
|
diff --git a/test_app/tests/middlewares/test_request.py b/test_app/tests/middlewares/test_request.py
index 2685854..d69c8c6 100644
--- a/test_app/tests/middlewares/test_request.py
+++ b/test_app/tests/middlewares/test_request.py
@@ -7,8 +7,13 @@ from unittest.mock import patch, Mock
from django.contrib.auth.models import AnonymousUser, User
from django.core.exceptions import PermissionDenied
from django.dispatch import receiver
-from django.http import Http404, HttpResponseNotFound, HttpResponseForbidden
-from django.test import TestCase, RequestFactory
+from django.http import (
+ Http404,
+ HttpResponseNotFound,
+ HttpResponseForbidden,
+ HttpResponseServerError,
+)
+from django.test import TestCase, RequestFactory, override_settings
import structlog
from django_structlog import middlewares
@@ -31,7 +36,7 @@ class TestRequestMiddleware(TestCase):
def test_process_request_without_user(self):
mock_response = Mock()
- mock_response.status_code.return_value = 200
+ mock_response.status_code = 200
expected_uuid = "00000000-0000-0000-0000-000000000000"
def get_response(_response):
@@ -61,7 +66,7 @@ class TestRequestMiddleware(TestCase):
def test_process_request_with_null_user(self):
mock_response = Mock()
- mock_response.status_code.return_value = 200
+ mock_response.status_code = 200
expected_uuid = "00000000-0000-0000-0000-000000000000"
def get_response(_response):
@@ -92,7 +97,7 @@ class TestRequestMiddleware(TestCase):
def test_process_request_anonymous(self):
mock_response = Mock()
- mock_response.status_code.return_value = 200
+ mock_response.status_code = 200
expected_uuid = "00000000-0000-0000-0000-000000000000"
def get_response(_response):
@@ -125,7 +130,7 @@ class TestRequestMiddleware(TestCase):
def test_process_request_user(self):
mock_response = Mock()
- mock_response.status_code.return_value = 200
+ mock_response.status_code = 200
expected_uuid = "00000000-0000-0000-0000-000000000000"
def get_response(_response):
@@ -161,7 +166,7 @@ class TestRequestMiddleware(TestCase):
def test_process_request_user_uuid(self):
mock_response = Mock()
- mock_response.status_code.return_value = 200
+ mock_response.status_code = 200
expected_uuid = "00000000-0000-0000-0000-000000000000"
def get_response(_response):
@@ -189,7 +194,7 @@ class TestRequestMiddleware(TestCase):
def test_process_request_user_without_id(self):
mock_response = Mock()
- mock_response.status_code.return_value = 200
+ mock_response.status_code = 200
def get_response(_response):
with self.assertLogs(__name__, logging.INFO) as log_results:
@@ -215,7 +220,7 @@ class TestRequestMiddleware(TestCase):
def test_log_user_in_request_finished(self):
mock_response = Mock()
- mock_response.status_code.return_value = 200
+ mock_response.status_code = 200
expected_uuid = "00000000-0000-0000-0000-000000000000"
mock_user = User.objects.create()
@@ -252,7 +257,7 @@ class TestRequestMiddleware(TestCase):
def test_log_user_in_request_finished_with_exception(self):
mock_response = Mock()
- mock_response.status_code.return_value = 200
+ mock_response.status_code = 200
expected_uuid = "00000000-0000-0000-0000-000000000000"
mock_user = User.objects.create()
@@ -308,7 +313,7 @@ class TestRequestMiddleware(TestCase):
)
mock_response = Mock()
- mock_response.status_code.return_value = 200
+ mock_response.status_code = 200
def get_response(_response):
with self.assertLogs(__name__, logging.INFO) as log_results:
@@ -335,7 +340,7 @@ class TestRequestMiddleware(TestCase):
def test_signal_bind_extra_request_finished_metadata(self):
mock_response = Mock()
- mock_response.status_code.return_value = 200
+ mock_response.status_code = 200
@receiver(bind_extra_request_finished_metadata)
def receiver_bind_extra_request_metadata(
@@ -520,7 +525,7 @@ class TestRequestMiddleware(TestCase):
self.assertIsNone(record.msg["user_id"])
record = log_results.records[1]
- self.assertEqual("INFO", record.levelname)
+ self.assertEqual("WARNING", record.levelname)
self.assertIn("request_id", record.msg)
self.assertEqual(expected_uuid, record.msg["request_id"])
self.assertIn("user_id", record.msg)
@@ -569,6 +574,57 @@ class TestRequestMiddleware(TestCase):
self.assertIn("user_id", record.msg)
self.assertIsNone(record.msg["user_id"])
+ record = log_results.records[1]
+ self.assertEqual("WARNING", record.levelname)
+ self.assertIn("request_id", record.msg)
+ self.assertEqual(expected_uuid, record.msg["request_id"])
+ self.assertIn("user_id", record.msg)
+ self.assertIsNone(record.msg["user_id"])
+
+ self.assertIn("code", record.msg)
+ self.assertEqual(record.msg["code"], 404)
+ self.assertNotIn("exception", record.msg)
+ self.assertIn("request", record.msg)
+
+ with self.assertLogs(__name__, logging.INFO) as log_results:
+ self.logger.info("hello")
+ self.assertEqual(1, len(log_results.records))
+ record = log_results.records[0]
+ self.assertNotIn("request_id", record.msg)
+ self.assertNotIn("user_id", record.msg)
+ self.assertFalse(hasattr(request, "_raised_exception"))
+
+ @override_settings(DJANGO_STRUCTLOG_STATUS_4XX_LOG_LEVEL=logging.INFO)
+ def test_process_request_4XX_can_be_personalized(self):
+ expected_uuid = "00000000-0000-0000-0000-000000000000"
+
+ request = self.factory.get("/foo")
+ request.user = AnonymousUser()
+
+ middleware = middlewares.RequestMiddleware(None)
+
+ exception = Http404()
+
+ def get_response(_response):
+ """Simulate an exception"""
+ middleware.process_exception(request, exception)
+ return HttpResponseNotFound()
+
+ middleware.get_response = get_response
+
+ with patch("uuid.UUID.__str__", return_value=expected_uuid), self.assertLogs(
+ logging.getLogger("django_structlog"), logging.INFO
+ ) as log_results:
+ middleware(request)
+
+ self.assertEqual(2, len(log_results.records))
+ record = log_results.records[0]
+ self.assertEqual("INFO", record.levelname)
+ self.assertIn("request_id", record.msg)
+ self.assertEqual(expected_uuid, record.msg["request_id"])
+ self.assertIn("user_id", record.msg)
+ self.assertIsNone(record.msg["user_id"])
+
record = log_results.records[1]
self.assertEqual("INFO", record.levelname)
self.assertIn("request_id", record.msg)
@@ -589,9 +645,55 @@ class TestRequestMiddleware(TestCase):
self.assertNotIn("user_id", record.msg)
self.assertFalse(hasattr(request, "_raised_exception"))
+ def test_process_request_500_are_processed_as_errors(self):
+ expected_uuid = "00000000-0000-0000-0000-000000000000"
+
+ request = self.factory.get("/foo")
+ request.user = AnonymousUser()
+
+ middleware = middlewares.RequestMiddleware(None)
+
+ def get_response(_response):
+ return HttpResponseServerError()
+
+ middleware.get_response = get_response
+
+ with patch("uuid.UUID.__str__", return_value=expected_uuid), self.assertLogs(
+ logging.getLogger("django_structlog"), logging.INFO
+ ) as log_results:
+ middleware(request)
+
+ self.assertEqual(2, len(log_results.records))
+ record = log_results.records[0]
+ self.assertEqual("INFO", record.levelname)
+ self.assertIn("request_id", record.msg)
+ self.assertEqual(expected_uuid, record.msg["request_id"])
+ self.assertIn("user_id", record.msg)
+ self.assertIsNone(record.msg["user_id"])
+
+ record = log_results.records[1]
+ self.assertEqual("ERROR", record.levelname)
+ self.assertIn("request_id", record.msg)
+ self.assertEqual(expected_uuid, record.msg["request_id"])
+ self.assertIn("user_id", record.msg)
+ self.assertIsNone(record.msg["user_id"])
+
+ self.assertIn("code", record.msg)
+ self.assertEqual(record.msg["code"], 500)
+ self.assertNotIn("exception", record.msg)
+ self.assertIn("request", record.msg)
+
+ with self.assertLogs(__name__, logging.INFO) as log_results:
+ self.logger.info("hello")
+ self.assertEqual(1, len(log_results.records))
+ record = log_results.records[0]
+ self.assertNotIn("request_id", record.msg)
+ self.assertNotIn("user_id", record.msg)
+ self.assertFalse(hasattr(request, "_raised_exception"))
+
def test_should_log_request_id_from_request_x_request_id_header(self):
mock_response = Mock()
- mock_response.status_code.return_value = 200
+ mock_response.status_code = 200
x_request_id = "my-fake-request-id"
def get_response(_response):
@@ -615,7 +717,7 @@ class TestRequestMiddleware(TestCase):
def test_should_log_correlation_id_from_request_x_correlation_id_header(self):
mock_response = Mock()
- mock_response.status_code.return_value = 200
+ mock_response.status_code = 200
x_correlation_id = "my-fake-correlation-id"
def get_response(_response):
|
request(middleware): Use log levels when logging responses
Would be nice if error levels were used when logging responses. Similar to Django's request handler:
https://github.com/django/django/blob/main/django/utils/log.py#L233-L249
Would simplify integration with structlog's stdlibs `filter_by_level` that filters based on method name and `add_log_level` that adds the log level. I currently add my processor for adding status_code -> level. But having issues with a custom filter to exclude log levels based on `level` instead of `method_name` since I think the python logging framework drops my log either way based on the `method_name` when setting logging level to warning for example.
Opinionated request, understandable if it does not go through.
|
0.0
|
8df457d0979b0581ea3ca28184902c4c1a28d138
|
[
"test_app/tests/middlewares/test_request.py::TestRequestMiddleware::test_process_request_403_are_processed_as_regular_requests",
"test_app/tests/middlewares/test_request.py::TestRequestMiddleware::test_process_request_404_are_processed_as_regular_requests",
"test_app/tests/middlewares/test_request.py::TestRequestMiddleware::test_process_request_500_are_processed_as_errors"
] |
[
"test_app/tests/middlewares/test_request.py::TestRequestMiddleware::test_process_request_4XX_can_be_personalized",
"test_app/tests/middlewares/test_request.py::TestRequestMiddleware::test_process_request_anonymous",
"test_app/tests/middlewares/test_request.py::TestRequestMiddleware::test_process_request_error",
"test_app/tests/middlewares/test_request.py::TestRequestMiddleware::test_process_request_user_uuid",
"test_app/tests/middlewares/test_request.py::TestRequestMiddleware::test_process_request_user_without_id",
"test_app/tests/middlewares/test_request.py::TestRequestMiddleware::test_process_request_with_null_user",
"test_app/tests/middlewares/test_request.py::TestRequestMiddleware::test_process_request_without_user",
"test_app/tests/middlewares/test_request.py::TestRequestMiddleware::test_should_log_correlation_id_from_request_x_correlation_id_header",
"test_app/tests/middlewares/test_request.py::TestRequestMiddleware::test_should_log_request_id_from_request_x_request_id_header",
"test_app/tests/middlewares/test_request.py::TestRequestMiddlewareRouter::test_async",
"test_app/tests/middlewares/test_request.py::TestRequestMiddlewareRouter::test_sync",
"test_app/tests/middlewares/test_request.py::TestGetRequestHeader::test_django_22_or_higher",
"test_app/tests/middlewares/test_request.py::TestGetRequestHeader::test_django_prior_to_22"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-09-12 01:44:49+00:00
|
mit
| 3,345 |
|
jrobichaud__django-structlog-318
|
diff --git a/config/urls.py b/config/urls.py
index 0bffaba..4e37443 100644
--- a/config/urls.py
+++ b/config/urls.py
@@ -29,6 +29,7 @@ urlpatterns = [
re_path(
r"^about/", TemplateView.as_view(template_name="pages/about.html"), name="about"
),
+ re_path(r"^revoke_task", views.revoke_task, name="revoke_task"),
# Django Admin, use {% url 'admin:index' %}
re_path(settings.ADMIN_URL, admin.site.urls),
# User management
diff --git a/django_structlog/celery/receivers.py b/django_structlog/celery/receivers.py
index dc14f2d..b976582 100644
--- a/django_structlog/celery/receivers.py
+++ b/django_structlog/celery/receivers.py
@@ -79,8 +79,16 @@ def receiver_task_failure(
def receiver_task_revoked(
request=None, terminated=None, signum=None, expired=None, **kwargs
):
+ metadata = getattr(request, "__django_structlog__", {}).copy()
+ metadata["task_id"] = request.id
+ metadata["task"] = request.task
+
logger.warning(
- "task_revoked", terminated=terminated, signum=signum, expired=expired
+ "task_revoked",
+ terminated=terminated,
+ signum=signum,
+ expired=expired,
+ **metadata,
)
diff --git a/django_structlog_demo_project/home/views.py b/django_structlog_demo_project/home/views.py
index e1c77a4..00f5a27 100644
--- a/django_structlog_demo_project/home/views.py
+++ b/django_structlog_demo_project/home/views.py
@@ -35,6 +35,12 @@ def log_with_standard_logger(request):
return HttpResponse(status=200)
+def revoke_task(request):
+ async_result = successful_task.apply_async(countdown=1)
+ async_result.revoke()
+ return HttpResponse(status=201)
+
+
async def async_view(request):
for num in range(1, 2):
await asyncio.sleep(1)
diff --git a/django_structlog_demo_project/templates/pages/home.html b/django_structlog_demo_project/templates/pages/home.html
index 119c101..8bba5da 100644
--- a/django_structlog_demo_project/templates/pages/home.html
+++ b/django_structlog_demo_project/templates/pages/home.html
@@ -34,6 +34,13 @@
<button type="submit" form="form5">Standard logger</button>
</div>
+ <div>
+ <form action="{% url 'revoke_task' %}" method="post" id="form6" target="dummyframe">
+ {% csrf_token %}
+ </form>
+ <button type="submit" form="form6">Revoke task</button>
+ </div>
+
<div>
<form action="{% url 'async_view' %}" method="post" id="form6" target="dummyframe">
{% csrf_token %}
diff --git a/docs/changelog.rst b/docs/changelog.rst
index 7240ad3..95d9a02 100644
--- a/docs/changelog.rst
+++ b/docs/changelog.rst
@@ -10,6 +10,9 @@ See: :ref:`upgrade_6.0`
- Python 3.12 support
- Add support of logging :ref:`commands`
+*Fixes:*
+ - Add missing metadata when a task is revoked. See `#317 <https://github.com/jrobichaud/django-structlog/issues/317>`_. Special thanks to `@badziyoussef <https://github.com/badziyoussef>`_.
+
*Changes:*
- Drop support of python 3.7
- Drop legacy code still supporting celery < 4
diff --git a/docs/events.rst b/docs/events.rst
index 90c9e1d..5f2551f 100644
--- a/docs/events.rst
+++ b/docs/events.rst
@@ -88,7 +88,7 @@ Task Events
+--------------------+-------------+------------------------------------------------+
| task_not_found | ERROR | Celery app did not discover the requested task |
+--------------------+-------------+------------------------------------------------+
-| task_task_rejected | ERROR | Task could not be enqueued |
+| task_rejected | ERROR | Task could not be enqueued |
+--------------------+-------------+------------------------------------------------+
\* if task threw an expected exception, it will logged as ``INFO``. See `Celery's Task.throws <https://docs.celeryproject.org/en/latest/userguide/tasks.html#Task.throws>`_
@@ -136,5 +136,9 @@ These metadata appear once along with their associated event
+------------------+------------------+----------------------------------------+
| task_revoked | expired | see Celery's documentation |
+------------------+------------------+----------------------------------------+
+| task_revoked | task_id | id of the task being revoked |
++------------------+------------------+----------------------------------------+
+| task_revoked | task | name of the task being revoked |
++------------------+------------------+----------------------------------------+
\* if task threw an expected exception, ``exception`` will be omitted. See `Celery's Task.throws <https://docs.celeryproject.org/en/latest/userguide/tasks.html#Task.throws>`_
|
jrobichaud/django-structlog
|
42a0e8dfca8f85c2286ef4a2d31f1142287e346f
|
diff --git a/django_structlog_demo_project/home/tests/test_views.py b/django_structlog_demo_project/home/tests/test_views.py
index 2f6c214..0f40625 100644
--- a/django_structlog_demo_project/home/tests/test_views.py
+++ b/django_structlog_demo_project/home/tests/test_views.py
@@ -42,3 +42,9 @@ class TestAsyncView:
async def test(self):
response = await views.async_view(None)
assert response.status_code == 200
+
+
+class TestRevokeTask:
+ def test(self):
+ response = views.revoke_task(None)
+ assert response.status_code == 201
diff --git a/test_app/tests/celery/test_receivers.py b/test_app/tests/celery/test_receivers.py
index 997982c..ee394a5 100644
--- a/test_app/tests/celery/test_receivers.py
+++ b/test_app/tests/celery/test_receivers.py
@@ -347,10 +347,23 @@ class TestReceivers(TestCase):
self.assertEqual(expected_exception, record.msg["error"])
def test_receiver_task_revoked(self):
+ expected_request_uuid = "00000000-0000-0000-0000-000000000000"
+ task_id = "11111111-1111-1111-1111-111111111111"
+ expected_user_id = "1234"
+ expected_task_name = "task_name"
+ request = Mock()
+ request.__django_structlog__ = {
+ "request_id": expected_request_uuid,
+ "user_id": expected_user_id,
+ }
+ request.task = expected_task_name
+ request.id = task_id
with self.assertLogs(
logging.getLogger("django_structlog.celery.receivers"), logging.WARNING
) as log_results:
- receivers.receiver_task_revoked(terminated=True, signum=1, expired=False)
+ receivers.receiver_task_revoked(
+ request=request, terminated=True, signum=1, expired=False
+ )
self.assertEqual(1, len(log_results.records))
record = log_results.records[0]
@@ -362,6 +375,14 @@ class TestReceivers(TestCase):
self.assertEqual(1, record.msg["signum"])
self.assertIn("expired", record.msg)
self.assertFalse(record.msg["expired"])
+ self.assertIn("task_id", record.msg)
+ self.assertEqual(task_id, record.msg["task_id"])
+ self.assertIn("task", record.msg)
+ self.assertEqual(expected_task_name, record.msg["task"])
+ self.assertIn("request_id", record.msg)
+ self.assertEqual(expected_request_uuid, record.msg["request_id"])
+ self.assertIn("user_id", record.msg)
+ self.assertEqual(expected_user_id, record.msg["user_id"])
def test_receiver_task_unknown(self):
expected_message = "foo"
|
Add child_task_id and child_task_name to task_revoked log
To be able to know which task was revoked, it could be a good idea to bind child_task_id and child_task_name to task_revoked log
|
0.0
|
42a0e8dfca8f85c2286ef4a2d31f1142287e346f
|
[
"test_app/tests/celery/test_receivers.py::TestReceivers::test_receiver_task_revoked"
] |
[
"django_structlog_demo_project/home/tests/test_views.py::TestRaiseException::test",
"django_structlog_demo_project/home/tests/test_views.py::TestLogWithStandardLogger::test",
"django_structlog_demo_project/home/tests/test_views.py::TestAsyncView::test",
"test_app/tests/celery/test_receivers.py::TestReceivers::test_receiver_after_task_publish",
"test_app/tests/celery/test_receivers.py::TestReceivers::test_receiver_after_task_publish_celery_3",
"test_app/tests/celery/test_receivers.py::TestReceivers::test_receiver_before_task_publish_celery_3",
"test_app/tests/celery/test_receivers.py::TestReceivers::test_receiver_before_task_publish_celery_4",
"test_app/tests/celery/test_receivers.py::TestReceivers::test_receiver_task_failure",
"test_app/tests/celery/test_receivers.py::TestReceivers::test_receiver_task_failure_with_throws",
"test_app/tests/celery/test_receivers.py::TestReceivers::test_receiver_task_pre_run",
"test_app/tests/celery/test_receivers.py::TestReceivers::test_receiver_task_rejected",
"test_app/tests/celery/test_receivers.py::TestReceivers::test_receiver_task_retry",
"test_app/tests/celery/test_receivers.py::TestReceivers::test_receiver_task_success",
"test_app/tests/celery/test_receivers.py::TestReceivers::test_receiver_task_unknown",
"test_app/tests/celery/test_receivers.py::TestReceivers::test_signal_bind_extra_task_metadata",
"test_app/tests/celery/test_receivers.py::TestReceivers::test_signal_modify_context_before_task_publish_celery_3",
"test_app/tests/celery/test_receivers.py::TestReceivers::test_signal_modify_context_before_task_publish_celery_4",
"test_app/tests/celery/test_receivers.py::TestConnectCelerySignals::test_call"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-09-26 00:43:44+00:00
|
mit
| 3,346 |
|
jsfehler__flake8-multiline-containers-128
|
diff --git a/flake8_multiline_containers.py b/flake8_multiline_containers.py
index e96b0b9..7803c14 100644
--- a/flake8_multiline_containers.py
+++ b/flake8_multiline_containers.py
@@ -10,6 +10,10 @@ STRING_REGEX = re.compile(
r'"([^"\\]*(\\.[^"\\]*)*)"|\'([^\'\\]*(\\.[^\'\\]*)*)\'',
)
+MULTILINE_STRING_REGEX = re.compile(
+ r'"""|\'\'\'',
+)
+
# Matches anything that looks like a:
# function call, function definition, or class definition with inheritance
# Actual tuples should be ignored
@@ -69,6 +73,8 @@ class MultilineContainers:
inside_conditional_block = attr.ib(default=0)
+ inside_multiline_string = False
+
def _number_of_matches_in_line(
self,
open_character: str,
@@ -91,6 +97,15 @@ class MultilineContainers:
if re.search(r'^\s*#', line):
return 0, 0, ONLY_COMMENTS_STRING
+ # Multiline strings should be ignored.
+ # If a line has only 1 triple quote, assume it's multiline
+ matches = MULTILINE_STRING_REGEX.findall(line)
+ if len(matches) == 1:
+ self.inside_multiline_string = not self.inside_multiline_string
+
+ if self.inside_multiline_string:
+ return 0, 0, line
+
# Remove strings from the line. Strings are always ignored.
temp_line = STRING_REGEX.sub('', line)
|
jsfehler/flake8-multiline-containers
|
a90bd084811ce980a27033a597f633a7b7f141d2
|
diff --git a/tests/dummy/string/multiline.py b/tests/dummy/string/multiline.py
new file mode 100644
index 0000000..5c52218
--- /dev/null
+++ b/tests/dummy/string/multiline.py
@@ -0,0 +1,23 @@
+# Triple quote strings should be ignored
+
+foo = """(a=10"""
+
+foo = """(a=10
+)
+"""
+
+foo = """
+(a=10
+ )
+"""
+
+foo = '''(a=10'''
+
+foo = '''(a=10
+)
+'''
+
+foo = '''
+(a=10
+ )
+'''
diff --git a/tests/test_string_ignore.py b/tests/test_string_ignore.py
index 60a4230..f32b081 100644
--- a/tests/test_string_ignore.py
+++ b/tests/test_string_ignore.py
@@ -15,6 +15,11 @@ def string_brackets_file_path(dummy_file_path):
return f'{dummy_file_path}/string/string_brackets.py'
[email protected]
+def multiline_string_file_path(dummy_file_path):
+ return f'{dummy_file_path}/string/multiline.py'
+
+
def test_js101_string_ignore(string_file_path):
"""When opening and closing characters are in a string
Then the linter should not detect them.
@@ -69,3 +74,31 @@ def test_js102_string_brackets_ignore(string_brackets_file_path):
r = style_guide.check_files([p])
assert 1 == r.total_errors
+
+
+def test_js101_multiline_string_ignore(multiline_string_file_path):
+ """When opening and closing characters are in a string
+ Then the linter should not detect them.
+ """
+ style_guide = flake8.get_style_guide(
+ select=['JS101'],
+ )
+
+ p = os.path.abspath(multiline_string_file_path)
+ r = style_guide.check_files([p])
+
+ assert 0 == r.total_errors
+
+
+def test_js102_multiline_string_ignore(multiline_string_file_path):
+ """When opening and closing characters are in a string
+ Then the linter should not detect them.
+ """
+ style_guide = flake8.get_style_guide(
+ select=['JS102'],
+ )
+
+ p = os.path.abspath(multiline_string_file_path)
+ r = style_guide.check_files([p])
+
+ assert 0 == r.total_errors
|
False positives inside multiline string
I evaluated `flake8-multiline-containers 0.0.19` and running it on the following code raises two warnings:
```
foo = """
(lorem
) lorem ipsum!
"""
```
```
test.py:2:6: JS101 Multi-line container not broken after opening character
test.py:3:2: JS102 Multi-line container does not close on same column as opening
```
As there are no containers and hence no multi-line containers in this code I see these as false positives.
|
0.0
|
a90bd084811ce980a27033a597f633a7b7f141d2
|
[
"tests/test_string_ignore.py::test_js101_multiline_string_ignore",
"tests/test_string_ignore.py::test_js102_multiline_string_ignore"
] |
[
"tests/test_string_ignore.py::test_js101_string_ignore",
"tests/test_string_ignore.py::test_js102_string_ignore",
"tests/test_string_ignore.py::test_js101_string_brackets_ignore",
"tests/test_string_ignore.py::test_js102_string_brackets_ignore"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2022-05-01 22:11:05+00:00
|
mit
| 3,347 |
|
jtauber__termdoc-23
|
diff --git a/README.md b/README.md
index c3e2ffe..2e85876 100644
--- a/README.md
+++ b/README.md
@@ -16,7 +16,7 @@ pip install termdoc
## HTDM
-The core data structure is a term-document matrix supporting hierarchical documents. Documents are labelled with a tuple such as `(1, 7, 5)` or `("Plato", "Republic", "Book 5")` (the type of each item in the tuple does not matter). This hierarchy could represent divisions of a work, grouping of multiple works, or some combination. Counts are aggregated at each level of the hierarchy (including at the top level to get totals across all documents).
+The core data structure is a term-document matrix supporting hierarchical documents. Documents are labelled with a delimited string such as "1.7.5" or "Plato.Republic.5". This hierarchy could represent divisions of a work, grouping of multiple works, or some combination. Counts are aggregated at each level of the hierarchy (including at the top level to get totals across all documents).
HTDMs can be loaded with `load`:
diff --git a/termdoc/htdm.py b/termdoc/htdm.py
index d68eb0b..e44c6f9 100644
--- a/termdoc/htdm.py
+++ b/termdoc/htdm.py
@@ -42,7 +42,7 @@ class HTDM:
address = self.address_sep.join(address.split(self.address_sep)[:-1])
first = False
- def load(self, filename, field_sep="\t", address_sep=None):
+ def load(self, filename, field_sep="\t", address_sep=None, prefix=None):
address_sep = address_sep or self.address_sep
with open(filename) as f:
for line in f:
@@ -55,6 +55,8 @@ class HTDM:
count = 1
else:
raise ValueError(f"{fields} should have 2 or 3 fields")
+ if prefix:
+ address = prefix + address_sep + address
self.increment_count(address, term, count)
def get_counts(self, prefix=""):
|
jtauber/termdoc
|
5de2d3d8ee9965da1a05a9b069683a7e1073f005
|
diff --git a/tests.py b/tests.py
index 8859571..4a531fe 100755
--- a/tests.py
+++ b/tests.py
@@ -99,6 +99,25 @@ class Test1(unittest.TestCase):
c = termdoc.HTDM()
self.assertRaises(ValueError, c.load, "test_data/test4e.tsv")
+ def test_load5(self):
+ import termdoc
+
+ c = termdoc.HTDM()
+ c.load("test_data/test2.tsv", prefix="xxx")
+
+ self.assertEqual(c.get_counts()["foo"], 10)
+ self.assertEqual(c.get_counts()["bar"], 5)
+ self.assertEqual(c.get_counts()["baz"], 5)
+ self.assertEqual(c.get_counts("xxx")["foo"], 10)
+ self.assertEqual(c.get_counts("xxx")["bar"], 5)
+ self.assertEqual(c.get_counts("xxx")["baz"], 5)
+ self.assertEqual(c.get_counts("xxx.1")["foo"], 9)
+ self.assertEqual(c.get_counts("xxx.1")["bar"], 5)
+ self.assertEqual(c.get_counts("xxx.1")["baz"], 0)
+ self.assertEqual(c.get_counts("xxx.2")["foo"], 1)
+ self.assertEqual(c.get_counts("xxx.2")["bar"], 0)
+ self.assertEqual(c.get_counts("xxx.2")["baz"], 5)
+
def test_prune(self):
import termdoc
|
allow loading at arbitrary point in tree
`load` should take an option `prefix` which gets prepended to all addresses loaded
|
0.0
|
5de2d3d8ee9965da1a05a9b069683a7e1073f005
|
[
"tests.py::Test1::test_load5"
] |
[
"tests.py::Test1::test_graft",
"tests.py::Test1::test_leaf_entries",
"tests.py::Test1::test_load1",
"tests.py::Test1::test_load2",
"tests.py::Test1::test_load3",
"tests.py::Test1::test_load4",
"tests.py::Test1::test_multi_level",
"tests.py::Test1::test_prune",
"tests.py::Test1::test_single_level",
"tests.py::TestDuplicates::test_allow",
"tests.py::TestDuplicates::test_error",
"tests.py::TestDuplicates::test_explicit_allow",
"tests.py::TestDuplicates::test_ignore",
"tests.py::TestDuplicates::test_multi_level_error"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-08-05 04:58:10+00:00
|
mit
| 3,348 |
|
jtesta__ssh-audit-44
|
diff --git a/ssh-audit.py b/ssh-audit.py
index a5702ab..c51241f 100755
--- a/ssh-audit.py
+++ b/ssh-audit.py
@@ -3366,7 +3366,7 @@ def build_struct(banner: Optional['SSH.Banner'], kex: Optional['SSH2.Kex'] = Non
host_keys = kex.host_keys()
# Normalize all RSA key types to 'ssh-rsa'. Otherwise, due to Python's order-indifference dictionary types, we would iterate key types in unpredictable orders, which interferes with the docker testing framework (i.e.: tests would fail because elements are reported out of order, even though the output is semantically the same).
- for host_key_type in host_keys.keys():
+ for host_key_type in list(host_keys.keys())[:]:
if host_key_type in SSH2.HostKeyTest.RSA_FAMILY:
val = host_keys[host_key_type]
del host_keys[host_key_type]
|
jtesta/ssh-audit
|
282770e6989f3b3158498e109b3768f5aa3d1e7e
|
diff --git a/test/test_build_struct.py b/test/test_build_struct.py
new file mode 100644
index 0000000..37c4c0f
--- /dev/null
+++ b/test/test_build_struct.py
@@ -0,0 +1,41 @@
+import os
+
+import pytest
+
+
[email protected]
+def kex(ssh_audit):
+ kex_algs, key_algs = [], []
+ enc, mac, compression, languages = [], [], ['none'], []
+ cli = ssh_audit.SSH2.KexParty(enc, mac, compression, languages)
+ enc, mac, compression, languages = [], [], ['none'], []
+ srv = ssh_audit.SSH2.KexParty(enc, mac, compression, languages)
+ cookie = os.urandom(16)
+ kex = ssh_audit.SSH2.Kex(cookie, kex_algs, key_algs, cli, srv, 0)
+ return kex
+
+
+def test_prevent_runtime_error_regression(ssh_audit, kex):
+ """Prevent a regression of https://github.com/jtesta/ssh-audit/issues/41
+
+ The following test setup does not contain any sensible data.
+ It was made up to reproduce a situation when there are several host
+ keys, and an error occurred when iterating and modifying them at the
+ same time.
+ """
+ kex.set_host_key("ssh-rsa", b"\x00\x00\x00\x07ssh-rsa\x00\x00\x00")
+ kex.set_host_key("ssh-rsa1", b"\x00\x00\x00\x07ssh-rsa\x00\x00\x00")
+ kex.set_host_key("ssh-rsa2", b"\x00\x00\x00\x07ssh-rsa\x00\x00\x00")
+ kex.set_host_key("ssh-rsa3", b"\x00\x00\x00\x07ssh-rsa\x00\x00\x00")
+ kex.set_host_key("ssh-rsa4", b"\x00\x00\x00\x07ssh-rsa\x00\x00\x00")
+ kex.set_host_key("ssh-rsa5", b"\x00\x00\x00\x07ssh-rsa\x00\x00\x00")
+ kex.set_host_key("ssh-rsa6", b"\x00\x00\x00\x07ssh-rsa\x00\x00\x00")
+ kex.set_host_key("ssh-rsa7", b"\x00\x00\x00\x07ssh-rsa\x00\x00\x00")
+ kex.set_host_key("ssh-rsa8", b"\x00\x00\x00\x07ssh-rsa\x00\x00\x00")
+
+ rv = ssh_audit.build_struct(banner=None, kex=kex)
+
+ assert len(rv["fingerprints"]) == 9
+
+ for key in ['banner', 'compression', 'enc', 'fingerprints', 'kex', 'key', 'mac']:
+ assert key in rv
|
RuntimeError when auditing SSH-Server
```
❯ python3.8 ssh-audit.py xx.xxx.xxx.xxx -p 22022 --json
Traceback (most recent call last):
File "ssh-audit.py", line 3103, in <module>
main()
File "ssh-audit.py", line 3099, in main
audit(conf)
File "ssh-audit.py", line 3088, in audit
print(json.dumps(build_struct(banner, kex=kex, client_host=s.client_host), sort_keys=True))
File "ssh-audit.py", line 2996, in build_struct
for host_key_type in host_keys.keys():
RuntimeError: dictionary keys changed during iteration
```
This is reproducible for one of my old, inherited SSH Servers, but not for the new one, which I configured after your guide.
I can provide you the address in private if you need it to debug.
Anyway, the problem is pretty obvious, and the exception says it clearly. It is no good idea to change an Iterable while iterating over it.
The fix is trivial - just wrap `host_keys.keys()` from above in a `list()`.
The above line is not covered by a test, though, as all the JSON generation. So, this is good chance to raise test coverage.
I'll try to find some time and create a PR for this issue.
|
0.0
|
282770e6989f3b3158498e109b3768f5aa3d1e7e
|
[
"test/test_build_struct.py::test_prevent_runtime_error_regression"
] |
[] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2020-07-01 19:54:06+00:00
|
mit
| 3,349 |
|
jubatus__jubatus-python-client-69
|
diff --git a/jubatus/common/client.py b/jubatus/common/client.py
index d599319..9cd91a8 100644
--- a/jubatus/common/client.py
+++ b/jubatus/common/client.py
@@ -54,6 +54,10 @@ class ClientBase(object):
(`unpack_encoding=None`)
"""
def __init__(self, host, port, name, timeout=10):
+ check_types(host, string_types)
+ check_types(port, int_types)
+ check_types(name, string_types)
+ check_types(timeout, int_types)
address = msgpackrpc.Address(host, port)
self.client = msgpackrpc.Client(address, timeout=timeout, pack_encoding='utf-8', unpack_encoding=None)
self.jubatus_client = Client(self.client, name)
@@ -65,6 +69,7 @@ class ClientBase(object):
return self.jubatus_client.name
def set_name(self, name):
+ check_types(name, string_types)
self.jubatus_client.name = name
def save(self, id):
|
jubatus/jubatus-python-client
|
34f9f83ee2d230672518102e541286425c92c287
|
diff --git a/test/jubatus_test/common/test_client.py b/test/jubatus_test/common/test_client.py
index 0e929f8..065b538 100644
--- a/test/jubatus_test/common/test_client.py
+++ b/test/jubatus_test/common/test_client.py
@@ -67,5 +67,22 @@ class ClientTest(unittest.TestCase):
self.assertEqual("test", c.call("test", [], AnyType(), []))
self.assertRaises(TypeError, c.call, "test", [1], AnyType(), [])
+class ClientBaseTest(unittest.TestCase):
+ def test_constructor(self):
+ self.assertIsInstance(jubatus.common.ClientBase("127.0.0.1", 9199, "cluster", 10), jubatus.common.ClientBase)
+
+ # invalid host
+ self.assertRaises(TypeError, jubatus.common.ClientBase, 127001, 9199, "cluster", 10)
+
+ # invalid port
+ self.assertRaises(TypeError, jubatus.common.ClientBase, "127.0.0.1", "9199", "cluster", 10)
+
+ # invalid name
+ self.assertRaises(TypeError, jubatus.common.ClientBase, "127.0.0.1", 9199, 10, 10)
+
+ # invalid timeout
+ self.assertRaises(TypeError, jubatus.common.ClientBase, "127.0.0.1", 9199, "cluster", "test")
+ self.assertRaises(TypeError, jubatus.common.ClientBase, "127.0.0.1", 9199, "cluster", 1.5)
+
if __name__ == '__main__':
unittest.main()
|
no type validation for constructor arguments
Currently argument types are validated, but constructor arguments are not.
For example, the following code:
```
c = jubatus.Classifier("localhost", 9199, 0) # it should be ("localhost", 9199, "") to work
c.get_status()
```
raises "TypeMismatch (error 2)" on RPC call, which is difficult to understand.
|
0.0
|
34f9f83ee2d230672518102e541286425c92c287
|
[
"test/jubatus_test/common/test_client.py::ClientBaseTest::test_constructor"
] |
[
"test/jubatus_test/common/test_client.py::ClientTest::test_remote_error",
"test/jubatus_test/common/test_client.py::ClientTest::test_type_mismatch",
"test/jubatus_test/common/test_client.py::ClientTest::test_unknown_method",
"test/jubatus_test/common/test_client.py::ClientTest::test_wrong_number_of_arguments"
] |
{
"failed_lite_validators": [
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2016-05-19 05:04:03+00:00
|
mit
| 3,350 |
|
jugmac00__hibpcli-34
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 30cb6e7..569bdf2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,8 @@
## unreleased
+- add new subcommand "password" for checking a single password
+
## 0.2.0 (02.11.2019)
### added
diff --git a/README.md b/README.md
index cf2b4e5..e414da2 100644
--- a/README.md
+++ b/README.md
@@ -9,33 +9,29 @@ A command line interface for the "haveibeenpwned.com" API - speaks keepass.
## current state
-Very alpha.
+A little bit alpha.
## usage
```
-$ hibpcli keepass
+$ hibpcli keepass --path PATHTOKEEPASSDB --password PASSWORDFORKEEPASSDB
-Please enter the path to the database: tests/test.kdbx
-Please enter the master password for the database:
The passwords of following entries are leaked:
[Entry: "test_title (test_user)"]
```
-or
-
```
-$ hibpcli keepass --path PATHTOKEEPASSDB --password PASSWORDFORKEEPASSDB
+$ hibpcli password --password test
-The passwords of following entries are leaked:
-[Entry: "test_title (test_user)"]
+Please change your password!
```
+
## scope
- check passwords in db via hibp online API (currently)
- check passwords in db via offline check (future)
-- enter passwords manually (future)
+- enter passwords manually (currently)
## contributions, feature requests, bug reports
diff --git a/hibpcli/cli.py b/hibpcli/cli.py
index 0c8236c..d82084e 100644
--- a/hibpcli/cli.py
+++ b/hibpcli/cli.py
@@ -1,6 +1,7 @@
import click
from hibpcli.keepass import check_passwords_from_db
+from hibpcli.password import Password
@click.group()
@@ -31,7 +32,23 @@ def keepass(path, password):
click.echo("Hooray, everything is safe!")
[email protected]()
[email protected]('--password', default=None, help='Password which should be checked.')
+def password(password):
+ """Check a single password."""
+ #breakpoint()
+ if password is None:
+ password = click.prompt(
+ "Please enter a password which should be checked", hide_input=True
+ )
+ p = Password(password)
+ if p.is_leaked():
+ click.echo("Please change your password!")
+ else:
+ click.echo("Your password is safe!")
+
main.add_command(keepass)
+main.add_command(password)
if __name__ == "__main__":
|
jugmac00/hibpcli
|
be86cf6454c55eb637646041632a4b52798fbb39
|
diff --git a/tests/test_cli.py b/tests/test_cli.py
index f6245f6..d58f909 100644
--- a/tests/test_cli.py
+++ b/tests/test_cli.py
@@ -4,6 +4,7 @@ from click.testing import CliRunner
from unittest.mock import patch
from hibpcli.cli import main
+from hibpcli.password import Password
@patch("hibpcli.cli.check_passwords_from_db")
@@ -64,3 +65,36 @@ def test_keepass_subcommand_with_path_and_password_options(mock_check):
[b'Entry: "test_title (test_user)"']
"""
assert result.output == textwrap.dedent(expected_output)
+
+
[email protected](Password, "is_leaked", return_value=True)
+def test_password_subcommand_for_leaked_password(mock_password):
+ runner = CliRunner()
+ result = runner.invoke(
+ main, ["password", "--password", "test"]
+ )
+ expected_output = "Please change your password!\n"
+ assert result.output == expected_output
+
+
[email protected](Password, "is_leaked", return_value=False)
+def test_password_subcommand_for_safe_password(mock_password):
+ runner = CliRunner()
+ result = runner.invoke(
+ main, ["password", "--password", "test"]
+ )
+ expected_output = "Your password is safe!\n"
+ assert result.output == expected_output
+
+
[email protected](Password, "is_leaked", return_value=False)
+def test_password_subcommand_with_prompt(mock_password):
+ runner = CliRunner()
+ result = runner.invoke(
+ main, ["password"], input="test"
+ )
+ expected_output = """\
+ Please enter a password which should be checked:
+ Your password is safe!
+ """
+ assert result.output == textwrap.dedent(expected_output)
|
Enable single password testing
One should be able to check single password against the hibp API for being leaked or not.
Also see #17 for more information about the new interface.
|
0.0
|
be86cf6454c55eb637646041632a4b52798fbb39
|
[
"tests/test_cli.py::test_password_subcommand_for_leaked_password",
"tests/test_cli.py::test_password_subcommand_for_safe_password",
"tests/test_cli.py::test_password_subcommand_with_prompt"
] |
[
"tests/test_cli.py::test_keepass_subcommand_returns_leaked_entry",
"tests/test_cli.py::test_keepass_subcommand_returns_all_ok",
"tests/test_cli.py::test_keepass_subcommand_with_path_option",
"tests/test_cli.py::test_keepass_subcommand_with_path_and_password_options"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_issue_reference",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-11-02 11:34:18+00:00
|
mit
| 3,351 |
|
jugmac00__hibpcli-35
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 42be033..f21e4fd 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,7 @@
- add new subcommand "password" for checking a single password
- add pdb++ to dev dependencies
+- add some basic error handling
## 0.2.0 (02.11.2019)
diff --git a/hibpcli/cli.py b/hibpcli/cli.py
index d82084e..41240b5 100644
--- a/hibpcli/cli.py
+++ b/hibpcli/cli.py
@@ -1,5 +1,6 @@
import click
+from hibpcli.exceptions import ApiError
from hibpcli.keepass import check_passwords_from_db
from hibpcli.password import Password
@@ -23,29 +24,36 @@ def keepass(path, password):
password = click.prompt(
"Please enter the master password for the database", hide_input=True
)
- # needs error handling
- rv = check_passwords_from_db(path=path, master_password=password)
- if rv:
- click.echo("The passwords of following entries are leaked:")
- click.echo(rv)
+ try:
+ rv = check_passwords_from_db(path=path, master_password=password)
+ except ApiError as e:
+ click.echo(str(e))
else:
- click.echo("Hooray, everything is safe!")
+ if rv:
+ click.echo("The passwords of following entries are leaked:")
+ click.echo(rv)
+ else:
+ click.echo("Hooray, everything is safe!")
@click.command()
@click.option('--password', default=None, help='Password which should be checked.')
def password(password):
"""Check a single password."""
- #breakpoint()
if password is None:
password = click.prompt(
"Please enter a password which should be checked", hide_input=True
)
p = Password(password)
- if p.is_leaked():
- click.echo("Please change your password!")
+ try:
+ is_leaked = p.is_leaked()
+ except ApiError as e:
+ click.echo(str(e))
else:
- click.echo("Your password is safe!")
+ if is_leaked:
+ click.echo("Please change your password!")
+ else:
+ click.echo("Your password is safe!")
main.add_command(keepass)
main.add_command(password)
diff --git a/hibpcli/exceptions.py b/hibpcli/exceptions.py
new file mode 100644
index 0000000..d71d7bd
--- /dev/null
+++ b/hibpcli/exceptions.py
@@ -0,0 +1,5 @@
+class HibpError(Exception):
+ pass
+
+class ApiError(HibpError):
+ pass
\ No newline at end of file
diff --git a/hibpcli/password.py b/hibpcli/password.py
index 52aec95..5b9ce80 100644
--- a/hibpcli/password.py
+++ b/hibpcli/password.py
@@ -1,5 +1,8 @@
import hashlib
import httpx
+import socket
+
+from hibpcli.exceptions import ApiError
class Password:
@@ -9,15 +12,19 @@ class Password:
def is_leaked(self):
hex_digest = self._generate_hash()
first_hash_part, second_hash_part = hex_digest[:5], hex_digest[5:]
- result = httpx.get(
- f"https://api.pwnedpasswords.com/range/{first_hash_part}"
- ).text
- # the result is text with entries split by new line
- # one entry consists of the rest of the hash and count of
- # leak, separated by a colon
- # cut off string - information after the hash is of no interest
- partial_hash_list = [line[:35] for line in result.splitlines()]
- return second_hash_part in partial_hash_list
+ try:
+ result = httpx.get(
+ f"https://api.pwnedpasswords.com/range/{first_hash_part}"
+ ).text
+ except socket.gaierror as e:
+ raise ApiError("Error: Could not get a result from the API.")
+ else:
+ # the result is text with entries split by new line
+ # one entry consists of the rest of the hash and count of
+ # leak, separated by a colon
+ # cut off string - information after the hash is of no interest
+ partial_hash_list = [line[:35] for line in result.splitlines()]
+ return second_hash_part in partial_hash_list
def _generate_hash(self):
hash_object = hashlib.sha1(bytes(self.password, "UTF-8"))
|
jugmac00/hibpcli
|
62c364e78c4924dbb98ebf8a3b124834faeb0316
|
diff --git a/tests/test_cli.py b/tests/test_cli.py
index d58f909..0f28614 100644
--- a/tests/test_cli.py
+++ b/tests/test_cli.py
@@ -4,6 +4,7 @@ from click.testing import CliRunner
from unittest.mock import patch
from hibpcli.cli import main
+from hibpcli.exceptions import ApiError
from hibpcli.password import Password
@@ -98,3 +99,24 @@ def test_password_subcommand_with_prompt(mock_password):
Your password is safe!
"""
assert result.output == textwrap.dedent(expected_output)
+
+
[email protected](Password,"is_leaked")
+def test_keepass_subcommand_error_handling(mock_password):
+ mock_password.side_effect = ApiError("Error")
+ runner = CliRunner()
+ result = runner.invoke(
+ main, ["keepass", "--path", "tests/test.kdbx", "--password", "test"]
+ )
+ expected_output = "Error\n"
+ assert result.output == expected_output
+
+
[email protected](Password, "is_leaked", side_effect=ApiError("Error"))
+def test_password_subcommand_error_handling(mock_password):
+ runner = CliRunner()
+ result = runner.invoke(
+ main, ["password", "--password", "test"]
+ )
+ expected_output = "Error\n"
+ assert result.output == expected_output
diff --git a/tests/test_password.py b/tests/test_password.py
index e218f07..7878b1b 100644
--- a/tests/test_password.py
+++ b/tests/test_password.py
@@ -1,7 +1,9 @@
import pytest
+import socket
from unittest.mock import patch
+from hibpcli.exceptions import ApiError
from hibpcli.password import Password
# this is just a small part of a real response
@@ -19,3 +21,11 @@ def test_is_leaked_password(mock_get):
p = Password("test")
assert p.is_leaked() is True
mock_get.assert_called_with("https://api.pwnedpasswords.com/range/A94A8")
+
+
+@patch("hibpcli.password.httpx.get")
+def test_is_leaked_raises_api_error(mock_get):
+ mock_get.side_effect = socket.gaierror
+ p = Password("test")
+ with pytest.raises(ApiError):
+ p.is_leaked()
|
Catch network/API errors
**current behaviour**
When the hibp API is not available, the user gets a nasty traceback.
**wished behaviour**
When the hibp API is not available, the user gets a decent error message.
|
0.0
|
62c364e78c4924dbb98ebf8a3b124834faeb0316
|
[
"tests/test_cli.py::test_keepass_subcommand_returns_leaked_entry",
"tests/test_cli.py::test_keepass_subcommand_returns_all_ok",
"tests/test_cli.py::test_keepass_subcommand_with_path_option",
"tests/test_cli.py::test_keepass_subcommand_with_path_and_password_options",
"tests/test_cli.py::test_password_subcommand_for_leaked_password",
"tests/test_cli.py::test_password_subcommand_for_safe_password",
"tests/test_cli.py::test_password_subcommand_with_prompt",
"tests/test_cli.py::test_keepass_subcommand_error_handling",
"tests/test_cli.py::test_password_subcommand_error_handling",
"tests/test_password.py::test_password_signature",
"tests/test_password.py::test_is_leaked_password",
"tests/test_password.py::test_is_leaked_raises_api_error"
] |
[] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-11-02 22:02:15+00:00
|
mit
| 3,352 |
|
jugmac00__hibpcli-59
|
diff --git a/CHANGES.rst b/CHANGES.rst
index 1d5dd93..b1f39f3 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -9,6 +9,7 @@ added
- add the `bandit` security checker
- add support for Python 3.9
- add type annotations
+- improve message when there are no known leaks for a password(@eumiro)
0.4.1 (30.09.2020)
------------------
diff --git a/src/hibpcli/cli.py b/src/hibpcli/cli.py
index 2b05521..ac754e7 100644
--- a/src/hibpcli/cli.py
+++ b/src/hibpcli/cli.py
@@ -30,7 +30,7 @@ def check_keepass(path: str, password: Optional[str]) -> None:
click.echo("The passwords of following entries are leaked:")
click.echo(rv)
else:
- click.echo("Hooray, everything is safe!")
+ click.echo("Your passwords have not been reported leaked until now.")
@click.command()
@@ -50,7 +50,7 @@ def check_password(password: Optional[str]) -> None:
if is_leaked:
click.echo("Please change your password!")
else:
- click.echo("Your password is safe!")
+ click.echo("Your password has not been reported leaked until now.")
main.add_command(check_keepass)
|
jugmac00/hibpcli
|
acb7eec3538310dd85c099e8e52561b85c25d6e0
|
diff --git a/tests/test_cli_for_check_keepass.py b/tests/test_cli_for_check_keepass.py
index 88ca03d..c698180 100644
--- a/tests/test_cli_for_check_keepass.py
+++ b/tests/test_cli_for_check_keepass.py
@@ -34,7 +34,7 @@ def test_keepass_subcommand_returns_all_ok(mock_check):
expected_output = textwrap.dedent(
"""\
Please enter the master password for the database:
- Hooray, everything is safe!
+ Your passwords have not been reported leaked until now.
""" # noqa: W291
)
assert result.output == expected_output
diff --git a/tests/test_cli_for_check_password.py b/tests/test_cli_for_check_password.py
index d87a37d..62a805c 100644
--- a/tests/test_cli_for_check_password.py
+++ b/tests/test_cli_for_check_password.py
@@ -19,7 +19,7 @@ def test_password_subcommand_for_leaked_password(mock_password):
def test_password_subcommand_for_safe_password(mock_password):
runner = CliRunner()
result = runner.invoke(main, ["check-password", "--password", "test"])
- expected_output = "Your password is safe!\n"
+ expected_output = "Your password has not been reported leaked until now.\n"
assert result.output == expected_output
@@ -29,7 +29,7 @@ def test_password_subcommand_with_prompt(mock_password):
result = runner.invoke(main, ["check-password"], input="test")
expected_output = """\
Please enter a password which should be checked:
- Your password is safe!
+ Your password has not been reported leaked until now.
""" # noqa: W291
assert result.output == textwrap.dedent(expected_output)
|
Change the message if no leak found
The wording of messages _“Hooray, everything is safe!”_ and _“Your password is safe!”_ implies these passwords are safe. Actually they only have not been reported as unsafe _until now_.
How about: _“Your password is probably safe.”_ or _“This password has not been reported unsafe until now.”_ or let's find a better message in the discussion.
|
0.0
|
acb7eec3538310dd85c099e8e52561b85c25d6e0
|
[
"tests/test_cli_for_check_keepass.py::test_keepass_subcommand_returns_all_ok",
"tests/test_cli_for_check_password.py::test_password_subcommand_for_safe_password",
"tests/test_cli_for_check_password.py::test_password_subcommand_with_prompt"
] |
[
"tests/test_cli_for_check_keepass.py::test_keepass_subcommand_returns_leaked_entry",
"tests/test_cli_for_check_keepass.py::test_keepass_subcommand_with_path",
"tests/test_cli_for_check_keepass.py::test_keepass_subcommand_with_path_and_password_options",
"tests/test_cli_for_check_keepass.py::test_keepass_subcommand_error_handling",
"tests/test_cli_for_check_password.py::test_password_subcommand_for_leaked_password",
"tests/test_cli_for_check_password.py::test_password_subcommand_error_handling"
] |
{
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-11-23 17:21:10+00:00
|
mit
| 3,353 |
|
jugmac00__hibpcli-61
|
diff --git a/CHANGES.rst b/CHANGES.rst
index b1f39f3..2025e39 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -10,6 +10,7 @@ added
- add support for Python 3.9
- add type annotations
- improve message when there are no known leaks for a password(@eumiro)
+- provide user friendly error message when given password is wrong
0.4.1 (30.09.2020)
------------------
diff --git a/setup.py b/setup.py
index 1f01e4d..517a56f 100644
--- a/setup.py
+++ b/setup.py
@@ -53,7 +53,7 @@ setup(
zip_safe=True,
install_requires=[
"click>=7.1.2",
- "pykeepass>=3.2.0",
+ "pykeepass>=3.2.1",
"httpx>=0.13.3",
],
entry_points={"console_scripts": ["hibpcli = hibpcli.cli:main"]},
diff --git a/src/hibpcli/cli.py b/src/hibpcli/cli.py
index ac754e7..4c52ff7 100644
--- a/src/hibpcli/cli.py
+++ b/src/hibpcli/cli.py
@@ -1,7 +1,7 @@
from typing import Optional
import click
-from hibpcli.exceptions import ApiError
+from hibpcli.exceptions import ApiError, KeepassError
from hibpcli.keepass import check_passwords_from_db
from hibpcli.password import Password
@@ -23,6 +23,8 @@ def check_keepass(path: str, password: Optional[str]) -> None:
)
try:
rv = check_passwords_from_db(path=path, master_password=password)
+ except KeepassError:
+ click.echo("The entered password is not correct. Please try again.")
except ApiError as e:
click.echo(str(e))
else:
diff --git a/src/hibpcli/exceptions.py b/src/hibpcli/exceptions.py
index dc11309..1f17636 100644
--- a/src/hibpcli/exceptions.py
+++ b/src/hibpcli/exceptions.py
@@ -4,3 +4,7 @@ class HibpError(Exception):
class ApiError(HibpError):
pass
+
+
+class KeepassError(HibpError):
+ pass
diff --git a/src/hibpcli/keepass.py b/src/hibpcli/keepass.py
index 723237d..6835589 100644
--- a/src/hibpcli/keepass.py
+++ b/src/hibpcli/keepass.py
@@ -1,12 +1,20 @@
from typing import List
+from hibpcli.exceptions import KeepassError
from hibpcli.password import Password
from pykeepass import PyKeePass # type: ignore
+from pykeepass.exceptions import CredentialsError
def check_passwords_from_db(path: str, master_password: str) -> List[str]:
""" - """
- kp = PyKeePass(path, password=master_password)
- return [
- entry for entry in kp.entries if Password(password=entry.password).is_leaked()
- ]
+ try:
+ kp = PyKeePass(path, password=master_password)
+ except CredentialsError:
+ raise KeepassError
+ else:
+ return [
+ entry
+ for entry in kp.entries
+ if Password(password=entry.password).is_leaked()
+ ]
|
jugmac00/hibpcli
|
316c2618f38b7c227680da479d8d054fceab7369
|
diff --git a/tests/test_cli_for_check_keepass.py b/tests/test_cli_for_check_keepass.py
index c698180..791a47a 100644
--- a/tests/test_cli_for_check_keepass.py
+++ b/tests/test_cli_for_check_keepass.py
@@ -80,3 +80,11 @@ def test_keepass_subcommand_error_handling(mock_password):
)
expected_output = "Error\n"
assert result.output == expected_output
+
+
+def test_keepass_wrong_password():
+ runner = CliRunner()
+ result = runner.invoke(
+ main, ["check-keepass", "tests/test.kdbx", "--password", "wrong-password"]
+ )
+ assert result.output == "The entered password is not correct. Please try again.\n"
|
catch exception when keepass password is wrong
currently users get to see:
> pykeepass.exceptions.CredentialsIntegrityError: Credentials are wrong or integrity check failed
|
0.0
|
316c2618f38b7c227680da479d8d054fceab7369
|
[
"tests/test_cli_for_check_keepass.py::test_keepass_wrong_password"
] |
[
"tests/test_cli_for_check_keepass.py::test_keepass_subcommand_returns_leaked_entry",
"tests/test_cli_for_check_keepass.py::test_keepass_subcommand_returns_all_ok",
"tests/test_cli_for_check_keepass.py::test_keepass_subcommand_with_path",
"tests/test_cli_for_check_keepass.py::test_keepass_subcommand_with_path_and_password_options",
"tests/test_cli_for_check_keepass.py::test_keepass_subcommand_error_handling"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-12-19 20:34:38+00:00
|
mit
| 3,354 |
|
juju__juju-crashdump-54
|
diff --git a/jujucrashdump/crashdump.py b/jujucrashdump/crashdump.py
index e6c9411..4038f91 100755
--- a/jujucrashdump/crashdump.py
+++ b/jujucrashdump/crashdump.py
@@ -270,9 +270,12 @@ class CrashCollector(object):
tar_cmd = (
"sudo find {dirs} -mount -type f -size -{max_size}c -o -size "
"{max_size}c 2>/dev/null | sudo tar -pcf /tmp/juju-dump-{uniq}.tar"
+ "{excludes}"
" --files-from - 2>/dev/null"
).format(dirs=" ".join(directories),
max_size=self.max_size,
+ excludes=''.join(
+ [' --exclude {}'.format(x) for x in self.exclude]),
uniq=self.uniq)
self._run_all(';'.join([
tar_cmd,
diff --git a/tox.ini b/tox.ini
index 259c672..7585ac1 100644
--- a/tox.ini
+++ b/tox.ini
@@ -14,8 +14,9 @@ deps =
[testenv]
commands = nosetests tests
deps =
- nose
futures
+ mock
+ nose
pyaml
[travis]
|
juju/juju-crashdump
|
2ec95c6a0e51dfae2410136652e01ed84d3a7fb1
|
diff --git a/tests/__init__.py b/tests/__init__.py
new file mode 100644
index 0000000..17dd8e7
--- /dev/null
+++ b/tests/__init__.py
@@ -0,0 +1,13 @@
+# Copyright 2020 Canonical Ltd
+#
+# 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.
diff --git a/tests/test_jujucrashdump_crashdump.py b/tests/test_jujucrashdump_crashdump.py
new file mode 100644
index 0000000..158352c
--- /dev/null
+++ b/tests/test_jujucrashdump_crashdump.py
@@ -0,0 +1,77 @@
+# Copyright 2020 Canonical Ltd
+#
+# 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 mock
+
+import tests.utils as utils
+
+import jujucrashdump.crashdump as crashdump
+
+class TestCrashCollector(utils.BaseTestCase):
+
+ def setUp(self):
+ self.target = crashdump.CrashCollector('aModel', 42, ['extra_dir'])
+ self._patches = {}
+ self._patches_start = {}
+
+ def tearDown(self):
+ self.target = None
+ for k, v in self._patches.items():
+ v.stop()
+ setattr(self, k, None)
+ self._patches = None
+ self._patches_start = None
+
+ def patch_target(self, attr, return_value=None):
+ mocked = mock.patch.object(self.target, attr)
+ self._patches[attr] = mocked
+ started = mocked.start()
+ started.return_value = return_value
+ self._patches_start[attr] = started
+ setattr(self, attr, started)
+
+ def test_create_unit_tarballs(self):
+ self.patch_object(crashdump, 'DIRECTORIES')
+ self.target.uniq = 'fake-uuid'
+ self.patch_target('_run_all')
+ self.DIRECTORIES.__iter__.return_value = ['dir']
+ self.target.create_unit_tarballs()
+ self._run_all.assert_called_once_with(
+ 'sudo find dir extra_dir /var/lib/lxd/containers/*/rootfsdir '
+ '/var/lib/lxd/containers/*/rootfsextra_dir -mount -type f '
+ '-size -42c -o -size 42c 2>/dev/null | '
+ 'sudo tar -pcf /tmp/juju-dump-fake-uuid.tar '
+ '--files-from - 2>/dev/null;'
+ 'sudo tar --append -f /tmp/juju-dump-fake-uuid.tar '
+ '-C /tmp/fake-uuid/cmd_output . || true;'
+ 'sudo tar --append -f /tmp/juju-dump-fake-uuid.tar '
+ '-C /tmp/fake-uuid/ journalctl || true;'
+ 'sudo tar --append -f /tmp/juju-dump-fake-uuid.tar '
+ '-C /tmp/fake-uuid/addon_output . || true')
+ self._run_all.reset_mock()
+ self.target.exclude = ('exc0', 'exc1')
+ self.target.create_unit_tarballs()
+ self._run_all.assert_called_once_with(
+ 'sudo find dir extra_dir /var/lib/lxd/containers/*/rootfsdir '
+ '/var/lib/lxd/containers/*/rootfsextra_dir -mount -type f '
+ '-size -42c -o -size 42c 2>/dev/null | '
+ 'sudo tar -pcf /tmp/juju-dump-fake-uuid.tar '
+ '--exclude exc0 --exclude exc1 '
+ '--files-from - 2>/dev/null;'
+ 'sudo tar --append -f /tmp/juju-dump-fake-uuid.tar '
+ '-C /tmp/fake-uuid/cmd_output . || true;'
+ 'sudo tar --append -f /tmp/juju-dump-fake-uuid.tar '
+ '-C /tmp/fake-uuid/ journalctl || true;'
+ 'sudo tar --append -f /tmp/juju-dump-fake-uuid.tar '
+ '-C /tmp/fake-uuid/addon_output . || true')
diff --git a/tests/utils.py b/tests/utils.py
new file mode 100644
index 0000000..7ac4699
--- /dev/null
+++ b/tests/utils.py
@@ -0,0 +1,79 @@
+# Copyright 2016 Canonical Ltd
+# 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.
+"""Unit test helpers from https://github.com/openstack/charms.openstack/"""
+
+import contextlib
+import io
+import mock
+import unittest
+
+
[email protected]
+def patch_open():
+ '''Patch open() to allow mocking both open() itself and the file that is
+ yielded.
+
+ Yields the mock for "open" and "file", respectively.'''
+ mock_open = mock.MagicMock(spec=open)
+ mock_file = mock.MagicMock(spec=io.FileIO)
+
+ @contextlib.contextmanager
+ def stub_open(*args, **kwargs):
+ mock_open(*args, **kwargs)
+ yield mock_file
+
+ with mock.patch('builtins.open', stub_open):
+ yield mock_open, mock_file
+
+
+class BaseTestCase(unittest.TestCase):
+
+ def setUp(self):
+ self._patches = {}
+ self._patches_start = {}
+
+ def tearDown(self):
+ for k, v in self._patches.items():
+ v.stop()
+ setattr(self, k, None)
+ self._patches = None
+ self._patches_start = None
+
+ def patch_object(self, obj, attr, return_value=None, name=None, new=None,
+ **kwargs):
+ if name is None:
+ name = attr
+ if new is not None:
+ mocked = mock.patch.object(obj, attr, new=new, **kwargs)
+ else:
+ mocked = mock.patch.object(obj, attr, **kwargs)
+ self._patches[name] = mocked
+ started = mocked.start()
+ if new is None:
+ started.return_value = return_value
+ self._patches_start[name] = started
+ setattr(self, name, started)
+
+ def patch(self, item, return_value=None, name=None, new=None, **kwargs):
+ if name is None:
+ raise RuntimeError("Must pass 'name' to .patch()")
+ if new is not None:
+ mocked = mock.patch(item, new=new, **kwargs)
+ else:
+ mocked = mock.patch(item, **kwargs)
+ self._patches[name] = mocked
+ started = mocked.start()
+ if new is None:
+ started.return_value = return_value
+ self._patches_start[name] = started
+ setattr(self, name, started)
|
Exclude argument is not passed on to tar collecting data on units
It appears the exclude (-x / --exclude) was first developed for a specific set of juju specific files.
Since juju crashdump now also collects data from other places on the system, it would be useful to pass the exclude list on to the tar command collecting data elsewhere too.
https://github.com/juju/juju-crashdump/blob/2ec95c6a0e51dfae2410136652e01ed84d3a7fb1/jujucrashdump/crashdump.py#L270-L282
|
0.0
|
2ec95c6a0e51dfae2410136652e01ed84d3a7fb1
|
[
"tests/test_jujucrashdump_crashdump.py::TestCrashCollector::test_create_unit_tarballs"
] |
[] |
{
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-02-07 10:00:21+00:00
|
mit
| 3,355 |
|
juju__python-libjuju-555
|
diff --git a/juju/client/jujudata.py b/juju/client/jujudata.py
index 8b844c2..629ad52 100644
--- a/juju/client/jujudata.py
+++ b/juju/client/jujudata.py
@@ -8,6 +8,7 @@ import yaml
from juju import tag
from juju.client.gocookies import GoCookieJar
from juju.errors import JujuError
+from juju.utils import juju_config_dir
class NoModelException(Exception):
@@ -121,8 +122,7 @@ class FileJujuData(JujuData):
'''Provide access to the Juju client configuration files.
Any configuration file is read once and then cached.'''
def __init__(self):
- self.path = os.environ.get('JUJU_DATA') or '~/.local/share/juju'
- self.path = os.path.abspath(os.path.expanduser(self.path))
+ self.path = juju_config_dir()
# _loaded keeps track of the loaded YAML from
# the Juju data files so we don't need to load the same
# file many times.
diff --git a/juju/machine.py b/juju/machine.py
index 2067a21..1e46199 100644
--- a/juju/machine.py
+++ b/juju/machine.py
@@ -1,7 +1,6 @@
import asyncio
import ipaddress
import logging
-import os
import pyrfc3339
@@ -9,6 +8,7 @@ from . import model, tag
from .annotationhelper import _get_annotations, _set_annotations
from .client import client
from .errors import JujuError
+from juju.utils import juju_ssh_key_paths
log = logging.getLogger(__name__)
@@ -124,9 +124,10 @@ class Machine(model.ModelEntity):
""" Execute an scp command. Requires a fully qualified source and
destination.
"""
+ _, id_path = juju_ssh_key_paths()
cmd = [
'scp',
- '-i', os.path.expanduser('~/.local/share/juju/ssh/juju_id_rsa'),
+ '-i', id_path,
'-o', 'StrictHostKeyChecking=no',
'-q',
'-B'
@@ -153,9 +154,10 @@ class Machine(model.ModelEntity):
raise NotImplementedError('proxy option is not implemented')
address = self.dns_name
destination = "{}@{}".format(user, address)
+ _, id_path = juju_ssh_key_paths()
cmd = [
'ssh',
- '-i', os.path.expanduser('~/.local/share/juju/ssh/juju_id_rsa'),
+ '-i', id_path,
'-o', 'StrictHostKeyChecking=no',
'-q',
destination
diff --git a/juju/utils.py b/juju/utils.py
index 2321ffd..9fca71d 100644
--- a/juju/utils.py
+++ b/juju/utils.py
@@ -32,15 +32,50 @@ async def execute_process(*cmd, log=None, loop=None):
return p.returncode == 0
+def juju_config_dir():
+ """Resolves and returns the path string to the juju configuration
+ folder for the juju CLI tool. Of the following items, returns the
+ first option that works (top to bottom):
+
+ * $JUJU_DATA
+ * $XDG_DATA_HOME/juju
+ * ~/.local/share/juju
+
+ """
+ # Check $JUJU_DATA first
+ config_dir = os.environ.get('JUJU_DATA', None)
+
+ # Second option: $XDG_DATA_HOME for ~/.local/share
+ if not config_dir:
+ config_dir = os.environ.get('XDG_DATA_HOME', None)
+
+ # Third option: just set it to ~/.local/share/juju
+ if not config_dir:
+ config_dir = '~/.local/share/juju'
+
+ return os.path.abspath(os.path.expanduser(config_dir))
+
+
+def juju_ssh_key_paths():
+ """Resolves and returns the path strings for public and private ssh
+ keys for juju CLI.
+
+ """
+ config_dir = juju_config_dir()
+ public_key_path = os.path.join(config_dir, 'ssh', 'juju_id_rsa.pub')
+ private_key_path = os.path.join(config_dir, 'ssh', 'juju_id_rsa')
+
+ return public_key_path, private_key_path
+
+
def _read_ssh_key():
'''
Inner function for read_ssh_key, suitable for passing to our
Executor.
'''
- default_data_dir = Path(Path.home(), ".local", "share", "juju")
- juju_data = os.environ.get("JUJU_DATA", default_data_dir)
- ssh_key_path = Path(juju_data, 'ssh', 'juju_id_rsa.pub')
+ public_key_path_str, _ = juju_ssh_key_paths()
+ ssh_key_path = Path(public_key_path_str)
with ssh_key_path.open('r') as ssh_key_file:
ssh_key = ssh_key_file.readlines()[0].strip()
return ssh_key
|
juju/python-libjuju
|
8595b8335f31dde46f267411ce5456bca05a1225
|
diff --git a/tests/unit/test_utils.py b/tests/unit/test_utils.py
new file mode 100644
index 0000000..6a17339
--- /dev/null
+++ b/tests/unit/test_utils.py
@@ -0,0 +1,14 @@
+import unittest
+
+from juju.utils import juju_config_dir, juju_ssh_key_paths
+
+
+class TestDirResolve(unittest.TestCase):
+ def test_config_dir(self):
+ config_dir = juju_config_dir()
+ assert 'local/share/juju' in config_dir
+
+ def test_juju_ssh_key_paths(self):
+ public, private = juju_ssh_key_paths()
+ assert public.endswith('ssh/juju_id_rsa.pub')
+ assert private.endswith('ssh/juju_id_rsa')
|
Machine.ssh and Machine._scp do not use JUJU_DATA if set
|
0.0
|
8595b8335f31dde46f267411ce5456bca05a1225
|
[
"tests/unit/test_utils.py::TestDirResolve::test_config_dir",
"tests/unit/test_utils.py::TestDirResolve::test_juju_ssh_key_paths"
] |
[] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-10-05 17:49:00+00:00
|
apache-2.0
| 3,356 |
|
juju__python-libjuju-582
|
diff --git a/juju/constraints.py b/juju/constraints.py
index 42d26c2..3191f28 100644
--- a/juju/constraints.py
+++ b/juju/constraints.py
@@ -82,6 +82,11 @@ def normalize_value(value):
if value.isdigit():
return int(value)
+ if value.lower() == 'true':
+ return True
+ if value.lower() == 'false':
+ return False
+
return value
|
juju/python-libjuju
|
eee4fabe8b60119088097449f37f02b5a36cfe94
|
diff --git a/tests/unit/test_constraints.py b/tests/unit/test_constraints.py
index 4d5e26c..f76f516 100644
--- a/tests/unit/test_constraints.py
+++ b/tests/unit/test_constraints.py
@@ -33,6 +33,10 @@ class TestConstraints(unittest.TestCase):
self.assertEqual(_("10M"), 10)
self.assertEqual(_("10"), 10)
self.assertEqual(_("foo,bar"), "foo,bar")
+ self.assertEqual(_("false"), False)
+ self.assertEqual(_("true"), True)
+ self.assertEqual(_("FALSE"), False)
+ self.assertEqual(_("TRUE"), True)
def test_normalize_list_val(self):
_ = constraints.normalize_list_value
|
Unable to set allocate-public-ip constraint
### Summary
When using `model.deploy()` to deploy an application, including the `allocate-public-ip=true` constraint fails with the following error:
```
Traceback (most recent call last):
File "test_integration.py", line 60, in test_deploy_cluster
app = await ops_test.model.deploy(
File "/.tox_env/lib/python3.8/site-packages/juju/model.py", line 1662, in deploy
return await self._deploy(
File "/.tox_env/lib/python3.8/site-packages/juju/model.py", line 1897, in _deploy
app = client.ApplicationDeploy(
File "/.tox_env/lib/python3.8/site-packages/juju/client/_definitions.py", line 1806, in __init__
constraints_ = Value.from_json(constraints) if constraints else None
File "/.tox_env/lib/python3.8/site-packages/juju/client/facade.py", line 640, in from_json
return cls(**d)
File "/.tox_env/lib/python3.8/site-packages/juju/client/_definitions.py", line 27110, in __init__
raise Exception("Expected allocate_public_ip_ to be a bool, received: {}".format(type(allocate_public_ip_)))
Exception: Expected allocate_public_ip_ to be a bool, received: <class 'str'>
```
I believe the issue occurs due to https://github.com/juju/python-libjuju/blob/master/juju/constraints.py#L75-L85 not doing any handling for boolean values.
### Proposed Fix
Extend `normalize_value` with something along the lines of:
```python
if value in ['true', 'True']:
return True
if value in ['false', 'False']:
return False
```
I doubt this is going to break any other constraints.
|
0.0
|
eee4fabe8b60119088097449f37f02b5a36cfe94
|
[
"tests/unit/test_constraints.py::TestConstraints::test_normalize_val"
] |
[
"tests/unit/test_constraints.py::TestConstraints::test_mem_regex",
"tests/unit/test_constraints.py::TestConstraints::test_normalize_key",
"tests/unit/test_constraints.py::TestConstraints::test_normalize_list_val",
"tests/unit/test_constraints.py::TestConstraints::test_parse_constraints",
"tests/unit/test_constraints.py::TestConstraints::test_parse_device_constraint",
"tests/unit/test_constraints.py::TestConstraints::test_parse_storage_constraint"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2021-11-08 11:55:17+00:00
|
apache-2.0
| 3,357 |
|
juju__python-libjuju-666
|
diff --git a/juju/constraints.py b/juju/constraints.py
index 3191f28..5c141ed 100644
--- a/juju/constraints.py
+++ b/juju/constraints.py
@@ -32,6 +32,25 @@ FACTORS = {
"Y": 1024 ** 6
}
+# List of supported constraint keys, see
+# http://github.com/cderici/juju/blob/2.9/core/constraints/constraints.go#L20-L39
+SUPPORTED_KEYS = [
+ "arch",
+ "container",
+ "cpu_cores",
+ "cores",
+ "cpu_power",
+ "mem",
+ "root_disk",
+ "root_disk_source",
+ "tags",
+ "instance_role",
+ "instance_type",
+ "spaces",
+ "virt_type",
+ "zones",
+ "allocate_public_ip"]
+
LIST_KEYS = {'tags', 'spaces'}
SNAKE1 = re.compile(r'(.)([A-Z][a-z]+)')
@@ -51,17 +70,20 @@ def parse(constraints):
# Fowards compatibilty: already parsed
return constraints
- constraints = {
- normalize_key(k): (
- normalize_list_value(v) if k in LIST_KEYS else
- normalize_value(v)
- ) for k, v in [s.split("=") for s in constraints.split(" ")]}
+ normalized_constraints = {}
+ for s in constraints.split(" "):
+ if "=" not in s:
+ raise Exception("malformed constraint %s" % s)
+
+ k, v = s.split("=")
+ normalized_constraints[normalize_key(k)] = normalize_list_value(v) if\
+ k in LIST_KEYS else normalize_value(v)
- return constraints
+ return normalized_constraints
-def normalize_key(key):
- key = key.strip()
+def normalize_key(orig_key):
+ key = orig_key.strip()
key = key.replace("-", "_") # Our _client lib wants "_" in place of "-"
@@ -69,6 +91,8 @@ def normalize_key(key):
key = SNAKE1.sub(r'\1_\2', key)
key = SNAKE2.sub(r'\1_\2', key).lower()
+ if key not in SUPPORTED_KEYS:
+ raise Exception("unknown constraint in %s" % orig_key)
return key
|
juju/python-libjuju
|
7d2a423e3180230421ccfa16c309f3c2d0ac1cc2
|
diff --git a/tests/unit/test_constraints.py b/tests/unit/test_constraints.py
index f76f516..244883e 100644
--- a/tests/unit/test_constraints.py
+++ b/tests/unit/test_constraints.py
@@ -20,11 +20,13 @@ class TestConstraints(unittest.TestCase):
def test_normalize_key(self):
_ = constraints.normalize_key
- self.assertEqual(_("test-key"), "test_key")
- self.assertEqual(_("test-key "), "test_key")
- self.assertEqual(_(" test-key"), "test_key")
- self.assertEqual(_("TestKey"), "test_key")
- self.assertEqual(_("testKey"), "test_key")
+ self.assertEqual(_("root-disk"), "root_disk")
+ self.assertEqual(_("root-disk "), "root_disk")
+ self.assertEqual(_(" root-disk"), "root_disk")
+ self.assertEqual(_("RootDisk"), "root_disk")
+ self.assertEqual(_("rootDisk"), "root_disk")
+
+ self.assertRaises(Exception, lambda: _("not-one-of-the-supported-keys"))
def test_normalize_val(self):
_ = constraints.normalize_value
@@ -53,13 +55,16 @@ class TestConstraints(unittest.TestCase):
)
self.assertEqual(
- _("mem=10G foo=bar,baz tags=tag1 spaces=space1,space2"),
+ _("mem=10G zones=bar,baz tags=tag1 spaces=space1,space2"),
{"mem": 10 * 1024,
- "foo": "bar,baz",
+ "zones": "bar,baz",
"tags": ["tag1"],
"spaces": ["space1", "space2"]}
)
+ self.assertRaises(Exception, lambda: _("root-disk>16G"))
+ self.assertRaises(Exception, lambda: _("root-disk>=16G"))
+
def test_parse_storage_constraint(self):
_ = constraints.parse_storage_constraint
|
Inconsistent handling of contraints in juju cli and python-libjuju
When trying to limit a charm to only deploy to machines with a minimum amount of disk space, I noticed that juju command line and python-libjuju validate syntax of constraints differently. This happened in a (wrong) attempt of use a relational ">=".
In juju cli, we got the error as expected:
jenkins@juju-38dff2-0:~$ juju deploy ubuntu --constraints 'tags=scalebot-dev-controller arch=amd64 root-disk>=16G'
ERROR unknown constraint "root-disk>"
jenkins@juju-38dff2-0:~$ juju deploy ubuntu --constraints 'tags=scalebot-dev-controller arch=amd64 root-disk=16G'
Located charm "cs:ubuntu-18".
Deploying charm "cs:ubuntu-18".
jenkins@juju-38dff2-0:~$ juju deploy ubuntu --constraints 'tags=scalebot-dev-controller arch=amd64 root-disk>16G'
ERROR malformed constraint "root-disk>16G"
jenkins@juju-38dff2-0:~$
With python-libjuju 2.9.7:
Python 3.8.0 (default, Dec 9 2021, 17:53:27)
[GCC 8.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import juju
>>> import juju.constraints
>>> juju.constraints.parse('tags=scalebot-dev-controller arch=amd64 root-disk>=16G')
{'tags': ['scalebot-dev-controller'], 'arch': 'amd64', 'root_disk>': 16384}
>>>
If we try to deploy using the API with something similar to:
application = await model.deploy(
"ubuntu",
application_name="ubuntu",
series=str_series,
channel="stable",
constraints=constraints.parse(str_constraints),
)
... the invalid constraint 'root_disk>' will be sent to MAAS having not effect but also raising no exception. I only tested with MAAS, but other cloud providers may also fail to parse invalid constraints.
|
0.0
|
7d2a423e3180230421ccfa16c309f3c2d0ac1cc2
|
[
"tests/unit/test_constraints.py::TestConstraints::test_normalize_key",
"tests/unit/test_constraints.py::TestConstraints::test_parse_constraints"
] |
[
"tests/unit/test_constraints.py::TestConstraints::test_mem_regex",
"tests/unit/test_constraints.py::TestConstraints::test_normalize_list_val",
"tests/unit/test_constraints.py::TestConstraints::test_normalize_val",
"tests/unit/test_constraints.py::TestConstraints::test_parse_device_constraint",
"tests/unit/test_constraints.py::TestConstraints::test_parse_storage_constraint"
] |
{
"failed_lite_validators": [
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-04-12 21:50:47+00:00
|
apache-2.0
| 3,358 |
|
jupyter-server__jupyter_server-497
|
diff --git a/jupyter_server/services/contents/filemanager.py b/jupyter_server/services/contents/filemanager.py
index 6f465cf9e..516696942 100644
--- a/jupyter_server/services/contents/filemanager.py
+++ b/jupyter_server/services/contents/filemanager.py
@@ -273,7 +273,7 @@ class FileContentsManager(FileManagerMixin, ContentsManager):
# skip over broken symlinks in listing
if e.errno == errno.ENOENT:
self.log.warning("%s doesn't exist", os_path)
- else:
+ elif e.errno != errno.EACCES: # Don't provide clues about protected files
self.log.warning("Error stat-ing %s: %s", os_path, e)
continue
@@ -283,17 +283,25 @@ class FileContentsManager(FileManagerMixin, ContentsManager):
self.log.debug("%s not a regular file", os_path)
continue
- if self.should_list(name):
- if self.allow_hidden or not is_file_hidden(os_path, stat_res=st):
- contents.append(
+ try:
+ if self.should_list(name):
+ if self.allow_hidden or not is_file_hidden(os_path, stat_res=st):
+ contents.append(
self.get(path='%s/%s' % (path, name), content=False)
+ )
+ except OSError as e:
+ # ELOOP: recursive symlink, also don't show failure due to permissions
+ if e.errno not in [errno.ELOOP, errno.EACCES]:
+ self.log.warning(
+ "Unknown error checking if file %r is hidden",
+ os_path,
+ exc_info=True,
)
model['format'] = 'json'
return model
-
def _file_model(self, path, content=True, format=None):
"""Build a model for a file
@@ -585,7 +593,7 @@ class AsyncFileContentsManager(FileContentsManager, AsyncFileManagerMixin, Async
# skip over broken symlinks in listing
if e.errno == errno.ENOENT:
self.log.warning("%s doesn't exist", os_path)
- else:
+ elif e.errno != errno.EACCES: # Don't provide clues about protected files
self.log.warning("Error stat-ing %s: %s", os_path, e)
continue
@@ -595,10 +603,19 @@ class AsyncFileContentsManager(FileContentsManager, AsyncFileManagerMixin, Async
self.log.debug("%s not a regular file", os_path)
continue
- if self.should_list(name):
- if self.allow_hidden or not is_file_hidden(os_path, stat_res=st):
- contents.append(
- await self.get(path='%s/%s' % (path, name), content=False)
+ try:
+ if self.should_list(name):
+ if self.allow_hidden or not is_file_hidden(os_path, stat_res=st):
+ contents.append(
+ await self.get(path='%s/%s' % (path, name), content=False)
+ )
+ except OSError as e:
+ # ELOOP: recursive symlink, also don't show failure due to permissions
+ if e.errno not in [errno.ELOOP, errno.EACCES]:
+ self.log.warning(
+ "Unknown error checking if file %r is hidden",
+ os_path,
+ exc_info=True,
)
model['format'] = 'json'
|
jupyter-server/jupyter_server
|
7ceebda61765f99862be20edeab9002d1898dcb3
|
diff --git a/jupyter_server/tests/services/contents/test_manager.py b/jupyter_server/tests/services/contents/test_manager.py
index 27534dd8f..98f358645 100644
--- a/jupyter_server/tests/services/contents/test_manager.py
+++ b/jupyter_server/tests/services/contents/test_manager.py
@@ -2,18 +2,17 @@ import os
import sys
import time
import pytest
-import functools
from traitlets import TraitError
from tornado.web import HTTPError
from itertools import combinations
-
from nbformat import v4 as nbformat
from jupyter_server.services.contents.filemanager import AsyncFileContentsManager, FileContentsManager
from jupyter_server.utils import ensure_async
from ...utils import expected_http_error
+
@pytest.fixture(params=[(FileContentsManager, True),
(FileContentsManager, False),
(AsyncFileContentsManager, True),
@@ -29,6 +28,7 @@ def file_contents_manager_class(request, tmp_path):
# -------------- Functions ----------------------------
+
def _make_dir(jp_contents_manager, api_path):
"""
Make a directory.
@@ -99,6 +99,7 @@ async def check_populated_dir_files(jp_contents_manager, api_path):
# ----------------- Tests ----------------------------------
+
def test_root_dir(file_contents_manager_class, tmp_path):
fm = file_contents_manager_class(root_dir=str(tmp_path))
assert fm.root_dir == str(tmp_path)
@@ -116,6 +117,7 @@ def test_invalid_root_dir(file_contents_manager_class, tmp_path):
with pytest.raises(TraitError):
file_contents_manager_class(root_dir=str(temp_file))
+
def test_get_os_path(file_contents_manager_class, tmp_path):
fm = file_contents_manager_class(root_dir=str(tmp_path))
path = fm._get_os_path('/path/to/notebook/test.ipynb')
@@ -146,10 +148,6 @@ def test_checkpoint_subdir(file_contents_manager_class, tmp_path):
assert cp_dir == os.path.join(str(tmp_path), cpm.checkpoint_dir, cp_name)
[email protected](
- sys.platform == 'win32' and sys.version_info[0] < 3,
- reason="System platform is Windows, version < 3"
-)
async def test_bad_symlink(file_contents_manager_class, tmp_path):
td = str(tmp_path)
@@ -172,9 +170,31 @@ async def test_bad_symlink(file_contents_manager_class, tmp_path):
@pytest.mark.skipif(
- sys.platform == 'win32' and sys.version_info[0] < 3,
- reason="System platform is Windows, version < 3"
+ sys.platform.startswith('win'),
+ reason="Windows doesn't detect symlink loops"
)
+async def test_recursive_symlink(file_contents_manager_class, tmp_path):
+ td = str(tmp_path)
+
+ cm = file_contents_manager_class(root_dir=td)
+ path = 'test recursive symlink'
+ _make_dir(cm, path)
+
+ file_model = await ensure_async(cm.new_untitled(path=path, ext='.txt'))
+
+ # create recursive symlink
+ symlink(cm, '%s/%s' % (path, "recursive"), '%s/%s' % (path, "recursive"))
+ model = await ensure_async(cm.get(path))
+
+ contents = {
+ content['name']: content for content in model['content']
+ }
+ assert 'untitled.txt' in contents
+ assert contents['untitled.txt'] == file_model
+ # recursive symlinks should not be shown in the contents manager
+ assert 'recursive' not in contents
+
+
async def test_good_symlink(file_contents_manager_class, tmp_path):
td = str(tmp_path)
cm = file_contents_manager_class(root_dir=td)
@@ -213,6 +233,7 @@ async def test_403(file_contents_manager_class, tmp_path):
except HTTPError as e:
assert e.status_code == 403
+
async def test_escape_root(file_contents_manager_class, tmp_path):
td = str(tmp_path)
cm = file_contents_manager_class(root_dir=td)
|
Symlinks with inaccessible targets cause filemanager to not list anything in the same directory
## Description
It seems that in jupyter_core, in `is_file_hidden_posix()` an exception is raised if it comes across a symlink where the target path is not accessible to the user (PermissionError). This has the effect of stopping the file contents manager in JupyterLab 3 from displaying the contents of a directory containing such links.
The traceback looks like the following, where the symlink points to a directory that is not accessible to user1:
Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/tornado/web.py", line 1704, in _execute
result = await result
File "/usr/local/lib/python3.8/dist-packages/jupyter_server/services/contents/handlers.py", line 110, in get
model = await ensure_async(self.contents_manager.get(
File "/usr/local/lib/python3.8/dist-packages/jupyter_server/services/contents/filemanager.py", line 381, in get
model = self._dir_model(path, content=content)
File "/usr/local/lib/python3.8/dist-packages/jupyter_server/services/contents/filemanager.py", line 288, in _dir_model
if self.allow_hidden or not is_file_hidden(os_path, stat_res=st):
File "/usr/local/lib/python3.8/dist-packages/jupyter_core/paths.py", line 297, in is_file_hidden_posix
stat_res = os.stat(abs_path)
PermissionError: [Errno 13] Permission denied: '/home/user1/subdir/secret'
## Reproduce
1. Have user 1 create a directory that user 2 cannot see, and have user 2 link to the directory created by user 1
2. Have user 2 do something like `touch a b c` in the same directory as their symlink
2. Have user 2 start up JupyterLab 3 with jupyter_server
3. Browsing to the directory containing the symlink cause the file listing to freeze
4. Logs will show traceback similar to above
## Expected behavior
The file listing should just omit the disallowed link since but list everything else that can normally be listed.
I think this means that jupyter_server should handle the exception. See also jupyter/jupyter_core#224
## Context
- Operating System and version: ubuntu:focal
- Browser and version: Chrome 90.0.4430.93
- Jupyter Server version: 1.6.4
|
0.0
|
7ceebda61765f99862be20edeab9002d1898dcb3
|
[
"jupyter_server/tests/services/contents/test_manager.py::test_recursive_symlink[FileContentsManager]",
"jupyter_server/tests/services/contents/test_manager.py::test_recursive_symlink[AsyncFileContentsManager]"
] |
[
"jupyter_server/tests/services/contents/test_manager.py::test_root_dir[FileContentsManager]",
"jupyter_server/tests/services/contents/test_manager.py::test_root_dir[AsyncFileContentsManager]",
"jupyter_server/tests/services/contents/test_manager.py::test_missing_root_dir[FileContentsManager]",
"jupyter_server/tests/services/contents/test_manager.py::test_missing_root_dir[AsyncFileContentsManager]",
"jupyter_server/tests/services/contents/test_manager.py::test_invalid_root_dir[FileContentsManager]",
"jupyter_server/tests/services/contents/test_manager.py::test_invalid_root_dir[AsyncFileContentsManager]",
"jupyter_server/tests/services/contents/test_manager.py::test_get_os_path[FileContentsManager]",
"jupyter_server/tests/services/contents/test_manager.py::test_get_os_path[AsyncFileContentsManager]",
"jupyter_server/tests/services/contents/test_manager.py::test_checkpoint_subdir[FileContentsManager]",
"jupyter_server/tests/services/contents/test_manager.py::test_checkpoint_subdir[AsyncFileContentsManager]",
"jupyter_server/tests/services/contents/test_manager.py::test_bad_symlink[FileContentsManager]",
"jupyter_server/tests/services/contents/test_manager.py::test_bad_symlink[AsyncFileContentsManager]",
"jupyter_server/tests/services/contents/test_manager.py::test_good_symlink[FileContentsManager]",
"jupyter_server/tests/services/contents/test_manager.py::test_good_symlink[AsyncFileContentsManager]",
"jupyter_server/tests/services/contents/test_manager.py::test_escape_root[FileContentsManager]",
"jupyter_server/tests/services/contents/test_manager.py::test_escape_root[AsyncFileContentsManager]",
"jupyter_server/tests/services/contents/test_manager.py::test_new_untitled[jp_contents_manager0]",
"jupyter_server/tests/services/contents/test_manager.py::test_new_untitled[jp_contents_manager1]",
"jupyter_server/tests/services/contents/test_manager.py::test_new_untitled[jp_contents_manager2]",
"jupyter_server/tests/services/contents/test_manager.py::test_new_untitled[jp_contents_manager3]",
"jupyter_server/tests/services/contents/test_manager.py::test_modified_date[jp_contents_manager0]",
"jupyter_server/tests/services/contents/test_manager.py::test_modified_date[jp_contents_manager1]",
"jupyter_server/tests/services/contents/test_manager.py::test_modified_date[jp_contents_manager2]",
"jupyter_server/tests/services/contents/test_manager.py::test_modified_date[jp_contents_manager3]",
"jupyter_server/tests/services/contents/test_manager.py::test_get[jp_contents_manager0]",
"jupyter_server/tests/services/contents/test_manager.py::test_get[jp_contents_manager1]",
"jupyter_server/tests/services/contents/test_manager.py::test_get[jp_contents_manager2]",
"jupyter_server/tests/services/contents/test_manager.py::test_get[jp_contents_manager3]",
"jupyter_server/tests/services/contents/test_manager.py::test_update[jp_contents_manager0]",
"jupyter_server/tests/services/contents/test_manager.py::test_update[jp_contents_manager1]",
"jupyter_server/tests/services/contents/test_manager.py::test_update[jp_contents_manager2]",
"jupyter_server/tests/services/contents/test_manager.py::test_update[jp_contents_manager3]",
"jupyter_server/tests/services/contents/test_manager.py::test_save[jp_contents_manager0]",
"jupyter_server/tests/services/contents/test_manager.py::test_save[jp_contents_manager1]",
"jupyter_server/tests/services/contents/test_manager.py::test_save[jp_contents_manager2]",
"jupyter_server/tests/services/contents/test_manager.py::test_save[jp_contents_manager3]",
"jupyter_server/tests/services/contents/test_manager.py::test_delete[jp_contents_manager0]",
"jupyter_server/tests/services/contents/test_manager.py::test_delete[jp_contents_manager1]",
"jupyter_server/tests/services/contents/test_manager.py::test_delete[jp_contents_manager2]",
"jupyter_server/tests/services/contents/test_manager.py::test_delete[jp_contents_manager3]",
"jupyter_server/tests/services/contents/test_manager.py::test_rename[jp_contents_manager0]",
"jupyter_server/tests/services/contents/test_manager.py::test_rename[jp_contents_manager1]",
"jupyter_server/tests/services/contents/test_manager.py::test_rename[jp_contents_manager2]",
"jupyter_server/tests/services/contents/test_manager.py::test_rename[jp_contents_manager3]",
"jupyter_server/tests/services/contents/test_manager.py::test_delete_root[jp_contents_manager0]",
"jupyter_server/tests/services/contents/test_manager.py::test_delete_root[jp_contents_manager1]",
"jupyter_server/tests/services/contents/test_manager.py::test_delete_root[jp_contents_manager2]",
"jupyter_server/tests/services/contents/test_manager.py::test_delete_root[jp_contents_manager3]",
"jupyter_server/tests/services/contents/test_manager.py::test_copy[jp_contents_manager0]",
"jupyter_server/tests/services/contents/test_manager.py::test_copy[jp_contents_manager1]",
"jupyter_server/tests/services/contents/test_manager.py::test_copy[jp_contents_manager2]",
"jupyter_server/tests/services/contents/test_manager.py::test_copy[jp_contents_manager3]",
"jupyter_server/tests/services/contents/test_manager.py::test_mark_trusted_cells[jp_contents_manager0]",
"jupyter_server/tests/services/contents/test_manager.py::test_mark_trusted_cells[jp_contents_manager1]",
"jupyter_server/tests/services/contents/test_manager.py::test_mark_trusted_cells[jp_contents_manager2]",
"jupyter_server/tests/services/contents/test_manager.py::test_mark_trusted_cells[jp_contents_manager3]",
"jupyter_server/tests/services/contents/test_manager.py::test_check_and_sign[jp_contents_manager0]",
"jupyter_server/tests/services/contents/test_manager.py::test_check_and_sign[jp_contents_manager1]",
"jupyter_server/tests/services/contents/test_manager.py::test_check_and_sign[jp_contents_manager2]",
"jupyter_server/tests/services/contents/test_manager.py::test_check_and_sign[jp_contents_manager3]"
] |
{
"failed_lite_validators": [
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-04-30 15:40:55+00:00
|
bsd-3-clause
| 3,359 |
|
jupyter-server__jupyter_server-574
|
diff --git a/jupyter_server/services/contents/filemanager.py b/jupyter_server/services/contents/filemanager.py
index 376a8db62..54e2dca38 100644
--- a/jupyter_server/services/contents/filemanager.py
+++ b/jupyter_server/services/contents/filemanager.py
@@ -119,6 +119,16 @@ class FileContentsManager(FileManagerMixin, ContentsManager):
deleting files really deletes them.""",
)
+ always_delete_dir = Bool(
+ False,
+ config=True,
+ help="""If True, deleting a non-empty directory will always be allowed.
+ WARNING this may result in files being permanently removed; e.g. on Windows,
+ if the data size is too big for the trash/recycle bin the directory will be permanently
+ deleted. If False (default), the non-empty directory will be sent to the trash only
+ if safe. And if ``delete_to_trash`` is True, the directory won't be deleted.""",
+ )
+
@default("files_handler_class")
def _files_handler_class_default(self):
return AuthenticatedFileHandler
@@ -331,7 +341,10 @@ class FileContentsManager(FileManagerMixin, ContentsManager):
if content:
content, format = self._read_file(os_path, format)
if model["mimetype"] is None:
- default_mime = {"text": "text/plain", "base64": "application/octet-stream"}[format]
+ default_mime = {
+ "text": "text/plain",
+ "base64": "application/octet-stream",
+ }[format]
model["mimetype"] = default_mime
model.update(
@@ -391,7 +404,9 @@ class FileContentsManager(FileManagerMixin, ContentsManager):
if os.path.isdir(os_path):
if type not in (None, "directory"):
raise web.HTTPError(
- 400, u"%s is a directory, not a %s" % (path, type), reason="bad type"
+ 400,
+ u"%s is a directory, not a %s" % (path, type),
+ reason="bad type",
)
model = self._dir_model(path, content=content)
elif type == "notebook" or (type is None and path.endswith(".ipynb")):
@@ -494,7 +509,7 @@ class FileContentsManager(FileManagerMixin, ContentsManager):
return False
if self.delete_to_trash:
- if sys.platform == "win32" and is_non_empty_dir(os_path):
+ if not self.always_delete_dir and sys.platform == "win32" and is_non_empty_dir(os_path):
# send2trash can really delete files on Windows, so disallow
# deleting non-empty files. See Github issue 3631.
raise web.HTTPError(400, u"Directory %s not empty" % os_path)
@@ -507,12 +522,13 @@ class FileContentsManager(FileManagerMixin, ContentsManager):
return
else:
self.log.warning(
- "Skipping trash for %s, on different device " "to home directory", os_path
+ "Skipping trash for %s, on different device " "to home directory",
+ os_path,
)
if os.path.isdir(os_path):
# Don't permanently delete non-empty directories.
- if is_non_empty_dir(os_path):
+ if not self.always_delete_dir and is_non_empty_dir(os_path):
raise web.HTTPError(400, u"Directory %s not empty" % os_path)
self.log.debug("Removing directory %s", os_path)
with self.perm_to_403():
@@ -649,7 +665,10 @@ class AsyncFileContentsManager(FileContentsManager, AsyncFileManagerMixin, Async
if content:
content, format = await self._read_file(os_path, format)
if model["mimetype"] is None:
- default_mime = {"text": "text/plain", "base64": "application/octet-stream"}[format]
+ default_mime = {
+ "text": "text/plain",
+ "base64": "application/octet-stream",
+ }[format]
model["mimetype"] = default_mime
model.update(
@@ -709,7 +728,9 @@ class AsyncFileContentsManager(FileContentsManager, AsyncFileManagerMixin, Async
if os.path.isdir(os_path):
if type not in (None, "directory"):
raise web.HTTPError(
- 400, u"%s is a directory, not a %s" % (path, type), reason="bad type"
+ 400,
+ u"%s is a directory, not a %s" % (path, type),
+ reason="bad type",
)
model = await self._dir_model(path, content=content)
elif type == "notebook" or (type is None and path.endswith(".ipynb")):
@@ -813,7 +834,11 @@ class AsyncFileContentsManager(FileContentsManager, AsyncFileManagerMixin, Async
return False
if self.delete_to_trash:
- if sys.platform == "win32" and await is_non_empty_dir(os_path):
+ if (
+ not self.always_delete_dir
+ and sys.platform == "win32"
+ and await is_non_empty_dir(os_path)
+ ):
# send2trash can really delete files on Windows, so disallow
# deleting non-empty files. See Github issue 3631.
raise web.HTTPError(400, u"Directory %s not empty" % os_path)
@@ -826,12 +851,13 @@ class AsyncFileContentsManager(FileContentsManager, AsyncFileManagerMixin, Async
return
else:
self.log.warning(
- "Skipping trash for %s, on different device " "to home directory", os_path
+ "Skipping trash for %s, on different device " "to home directory",
+ os_path,
)
if os.path.isdir(os_path):
# Don't permanently delete non-empty directories.
- if await is_non_empty_dir(os_path):
+ if not self.always_delete_dir and await is_non_empty_dir(os_path):
raise web.HTTPError(400, u"Directory %s not empty" % os_path)
self.log.debug("Removing directory %s", os_path)
with self.perm_to_403():
|
jupyter-server/jupyter_server
|
90f619cf11eec842a27eec25692f9d65adccf169
|
diff --git a/jupyter_server/tests/services/contents/test_manager.py b/jupyter_server/tests/services/contents/test_manager.py
index 9063d2249..386d3ed60 100644
--- a/jupyter_server/tests/services/contents/test_manager.py
+++ b/jupyter_server/tests/services/contents/test_manager.py
@@ -513,6 +513,47 @@ async def test_delete(jp_contents_manager):
await ensure_async(cm.get(path))
[email protected](
+ "delete_to_trash, always_delete, error",
+ (
+ [True, True, False],
+ # on linux test folder may not be on home folder drive
+ # => if this is the case, _check_trash will be False
+ [True, False, None],
+ [False, True, False],
+ [False, False, True],
+ ),
+)
+async def test_delete_non_empty_folder(delete_to_trash, always_delete, error, jp_contents_manager):
+ cm = jp_contents_manager
+ cm.delete_to_trash = delete_to_trash
+ cm.always_delete_dir = always_delete
+
+ dir = "to_delete"
+
+ await make_populated_dir(cm, dir)
+ await check_populated_dir_files(cm, dir)
+
+ if error is None:
+ error = False
+ if sys.platform == "win32":
+ error = True
+ elif sys.platform == "linux":
+ file_dev = os.stat(cm.root_dir).st_dev
+ home_dev = os.stat(os.path.expanduser("~")).st_dev
+ error = file_dev != home_dev
+
+ if error:
+ with pytest.raises(
+ HTTPError,
+ match=r"HTTP 400: Bad Request \(Directory .*?to_delete not empty\)",
+ ):
+ await ensure_async(cm.delete_file(dir))
+ else:
+ await ensure_async(cm.delete_file(dir))
+ assert cm.dir_exists(dir) == False
+
+
async def test_rename(jp_contents_manager):
cm = jp_contents_manager
# Create a new notebook
|
Allow non-empty directory deletion for windows through settings
Hey would it be ok to allow non-empty directory deletion for windows through settings?
https://github.com/jupyter-server/jupyter_server/blob/f914126d173dde7d2b2f6a6d474648060c823419/jupyter_server/services/contents/filemanager.py#L492
|
0.0
|
90f619cf11eec842a27eec25692f9d65adccf169
|
[
"jupyter_server/tests/services/contents/test_manager.py::test_delete_non_empty_folder[jp_contents_manager0-False-True-False]",
"jupyter_server/tests/services/contents/test_manager.py::test_delete_non_empty_folder[jp_contents_manager1-False-True-False]",
"jupyter_server/tests/services/contents/test_manager.py::test_delete_non_empty_folder[jp_contents_manager2-False-True-False]",
"jupyter_server/tests/services/contents/test_manager.py::test_delete_non_empty_folder[jp_contents_manager3-False-True-False]"
] |
[
"jupyter_server/tests/services/contents/test_manager.py::test_root_dir[FileContentsManager]",
"jupyter_server/tests/services/contents/test_manager.py::test_root_dir[AsyncFileContentsManager]",
"jupyter_server/tests/services/contents/test_manager.py::test_missing_root_dir[FileContentsManager]",
"jupyter_server/tests/services/contents/test_manager.py::test_missing_root_dir[AsyncFileContentsManager]",
"jupyter_server/tests/services/contents/test_manager.py::test_invalid_root_dir[FileContentsManager]",
"jupyter_server/tests/services/contents/test_manager.py::test_invalid_root_dir[AsyncFileContentsManager]",
"jupyter_server/tests/services/contents/test_manager.py::test_get_os_path[FileContentsManager]",
"jupyter_server/tests/services/contents/test_manager.py::test_get_os_path[AsyncFileContentsManager]",
"jupyter_server/tests/services/contents/test_manager.py::test_checkpoint_subdir[FileContentsManager]",
"jupyter_server/tests/services/contents/test_manager.py::test_checkpoint_subdir[AsyncFileContentsManager]",
"jupyter_server/tests/services/contents/test_manager.py::test_bad_symlink[FileContentsManager]",
"jupyter_server/tests/services/contents/test_manager.py::test_bad_symlink[AsyncFileContentsManager]",
"jupyter_server/tests/services/contents/test_manager.py::test_recursive_symlink[FileContentsManager]",
"jupyter_server/tests/services/contents/test_manager.py::test_recursive_symlink[AsyncFileContentsManager]",
"jupyter_server/tests/services/contents/test_manager.py::test_good_symlink[FileContentsManager]",
"jupyter_server/tests/services/contents/test_manager.py::test_good_symlink[AsyncFileContentsManager]",
"jupyter_server/tests/services/contents/test_manager.py::test_escape_root[FileContentsManager]",
"jupyter_server/tests/services/contents/test_manager.py::test_escape_root[AsyncFileContentsManager]",
"jupyter_server/tests/services/contents/test_manager.py::test_new_untitled[jp_contents_manager0]",
"jupyter_server/tests/services/contents/test_manager.py::test_new_untitled[jp_contents_manager1]",
"jupyter_server/tests/services/contents/test_manager.py::test_new_untitled[jp_contents_manager2]",
"jupyter_server/tests/services/contents/test_manager.py::test_new_untitled[jp_contents_manager3]",
"jupyter_server/tests/services/contents/test_manager.py::test_modified_date[jp_contents_manager0]",
"jupyter_server/tests/services/contents/test_manager.py::test_modified_date[jp_contents_manager1]",
"jupyter_server/tests/services/contents/test_manager.py::test_modified_date[jp_contents_manager2]",
"jupyter_server/tests/services/contents/test_manager.py::test_modified_date[jp_contents_manager3]",
"jupyter_server/tests/services/contents/test_manager.py::test_get[jp_contents_manager0]",
"jupyter_server/tests/services/contents/test_manager.py::test_get[jp_contents_manager1]",
"jupyter_server/tests/services/contents/test_manager.py::test_get[jp_contents_manager2]",
"jupyter_server/tests/services/contents/test_manager.py::test_get[jp_contents_manager3]",
"jupyter_server/tests/services/contents/test_manager.py::test_update[jp_contents_manager0]",
"jupyter_server/tests/services/contents/test_manager.py::test_update[jp_contents_manager1]",
"jupyter_server/tests/services/contents/test_manager.py::test_update[jp_contents_manager2]",
"jupyter_server/tests/services/contents/test_manager.py::test_update[jp_contents_manager3]",
"jupyter_server/tests/services/contents/test_manager.py::test_save[jp_contents_manager0]",
"jupyter_server/tests/services/contents/test_manager.py::test_save[jp_contents_manager1]",
"jupyter_server/tests/services/contents/test_manager.py::test_save[jp_contents_manager2]",
"jupyter_server/tests/services/contents/test_manager.py::test_save[jp_contents_manager3]",
"jupyter_server/tests/services/contents/test_manager.py::test_delete[jp_contents_manager0]",
"jupyter_server/tests/services/contents/test_manager.py::test_delete[jp_contents_manager1]",
"jupyter_server/tests/services/contents/test_manager.py::test_delete[jp_contents_manager2]",
"jupyter_server/tests/services/contents/test_manager.py::test_delete[jp_contents_manager3]",
"jupyter_server/tests/services/contents/test_manager.py::test_delete_non_empty_folder[jp_contents_manager0-True-True-False]",
"jupyter_server/tests/services/contents/test_manager.py::test_delete_non_empty_folder[jp_contents_manager0-True-False-None]",
"jupyter_server/tests/services/contents/test_manager.py::test_delete_non_empty_folder[jp_contents_manager0-False-False-True]",
"jupyter_server/tests/services/contents/test_manager.py::test_delete_non_empty_folder[jp_contents_manager1-True-True-False]",
"jupyter_server/tests/services/contents/test_manager.py::test_delete_non_empty_folder[jp_contents_manager1-True-False-None]",
"jupyter_server/tests/services/contents/test_manager.py::test_delete_non_empty_folder[jp_contents_manager1-False-False-True]",
"jupyter_server/tests/services/contents/test_manager.py::test_delete_non_empty_folder[jp_contents_manager2-True-True-False]",
"jupyter_server/tests/services/contents/test_manager.py::test_delete_non_empty_folder[jp_contents_manager2-True-False-None]",
"jupyter_server/tests/services/contents/test_manager.py::test_delete_non_empty_folder[jp_contents_manager2-False-False-True]",
"jupyter_server/tests/services/contents/test_manager.py::test_delete_non_empty_folder[jp_contents_manager3-True-True-False]",
"jupyter_server/tests/services/contents/test_manager.py::test_delete_non_empty_folder[jp_contents_manager3-True-False-None]",
"jupyter_server/tests/services/contents/test_manager.py::test_delete_non_empty_folder[jp_contents_manager3-False-False-True]",
"jupyter_server/tests/services/contents/test_manager.py::test_rename[jp_contents_manager0]",
"jupyter_server/tests/services/contents/test_manager.py::test_rename[jp_contents_manager1]",
"jupyter_server/tests/services/contents/test_manager.py::test_rename[jp_contents_manager2]",
"jupyter_server/tests/services/contents/test_manager.py::test_rename[jp_contents_manager3]",
"jupyter_server/tests/services/contents/test_manager.py::test_delete_root[jp_contents_manager0]",
"jupyter_server/tests/services/contents/test_manager.py::test_delete_root[jp_contents_manager1]",
"jupyter_server/tests/services/contents/test_manager.py::test_delete_root[jp_contents_manager2]",
"jupyter_server/tests/services/contents/test_manager.py::test_delete_root[jp_contents_manager3]",
"jupyter_server/tests/services/contents/test_manager.py::test_copy[jp_contents_manager0]",
"jupyter_server/tests/services/contents/test_manager.py::test_copy[jp_contents_manager1]",
"jupyter_server/tests/services/contents/test_manager.py::test_copy[jp_contents_manager2]",
"jupyter_server/tests/services/contents/test_manager.py::test_copy[jp_contents_manager3]",
"jupyter_server/tests/services/contents/test_manager.py::test_mark_trusted_cells[jp_contents_manager0]",
"jupyter_server/tests/services/contents/test_manager.py::test_mark_trusted_cells[jp_contents_manager1]",
"jupyter_server/tests/services/contents/test_manager.py::test_mark_trusted_cells[jp_contents_manager2]",
"jupyter_server/tests/services/contents/test_manager.py::test_mark_trusted_cells[jp_contents_manager3]",
"jupyter_server/tests/services/contents/test_manager.py::test_check_and_sign[jp_contents_manager0]",
"jupyter_server/tests/services/contents/test_manager.py::test_check_and_sign[jp_contents_manager1]",
"jupyter_server/tests/services/contents/test_manager.py::test_check_and_sign[jp_contents_manager2]",
"jupyter_server/tests/services/contents/test_manager.py::test_check_and_sign[jp_contents_manager3]"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-08-20 09:57:24+00:00
|
bsd-3-clause
| 3,360 |
|
jupyter__nbformat-173
|
diff --git a/nbformat/__init__.py b/nbformat/__init__.py
index 7552e30..bb9c0fc 100644
--- a/nbformat/__init__.py
+++ b/nbformat/__init__.py
@@ -133,11 +133,12 @@ def read(fp, as_version, **kwargs):
nb : NotebookNode
The notebook that was read.
"""
- if isinstance(fp, (str, bytes)):
- with io.open(fp, encoding='utf-8') as f:
- return read(f, as_version, **kwargs)
- return reads(fp.read(), as_version, **kwargs)
+ try:
+ return reads(fp.read(), as_version, **kwargs)
+ except AttributeError:
+ with io.open(fp, encoding='utf-8') as f:
+ return reads(f.read(), as_version, **kwargs)
def write(nb, fp, version=NO_CONVERT, **kwargs):
@@ -158,13 +159,16 @@ def write(nb, fp, version=NO_CONVERT, **kwargs):
If unspecified, or specified as nbformat.NO_CONVERT,
the notebook's own version will be used and no conversion performed.
"""
- if isinstance(fp, (str, bytes)):
- with io.open(fp, 'w', encoding='utf-8') as f:
- return write(nb, f, version=version, **kwargs)
-
s = writes(nb, version, **kwargs)
if isinstance(s, bytes):
s = s.decode('utf8')
- fp.write(s)
- if not s.endswith(u'\n'):
- fp.write(u'\n')
+
+ try:
+ fp.write(s)
+ if not s.endswith(u'\n'):
+ fp.write(u'\n')
+ except AttributeError:
+ with io.open(fp, 'w', encoding='utf-8') as f:
+ f.write(s)
+ if not s.endswith(u'\n'):
+ f.write(u'\n')
|
jupyter/nbformat
|
2f20fd6ba7f7c06be9112ec555daf7838b9a58e4
|
diff --git a/nbformat/tests/test_api.py b/nbformat/tests/test_api.py
index f93f827..f991e2f 100644
--- a/nbformat/tests/test_api.py
+++ b/nbformat/tests/test_api.py
@@ -5,6 +5,9 @@
import json
import os
+import pathlib
+import sys
+import unittest
from .base import TestsBase
@@ -47,3 +50,17 @@ class TestAPI(TestsBase):
dest = os.path.join(td, 'echidna.ipynb')
write(nb, dest)
assert os.path.isfile(dest)
+
+ @unittest.skipIf(
+ sys.version_info < (3, 6, 0),
+ "python versions 3.5 and lower don't support opening pathlib.Path objects"
+ )
+ def test_read_write_pathlib_object(self):
+ """read() and write() take path-like objects such as pathlib objects"""
+ path = pathlib.Path(self._get_files_path()) / u'test4.ipynb'
+ nb = read(path, as_version=4)
+
+ with TemporaryDirectory() as td:
+ dest = pathlib.Path(td) / 'echidna.ipynb'
+ write(nb, dest)
+ assert os.path.isfile(dest)
|
Please support pathlib.Path objects
Could you please add support for `pathlib.Path` objects in `nbformat.read` and `nbformat.write`?
See [pathlib](https://docs.python.org/3/library/pathlib.html) and [PEP 519](https://www.python.org/dev/peps/pep-0519/).
```
>>> import nbformat
>>> from pathlib import Path
>>> path = Path("tests/test2.ipynb")
>>> nb = nbformat.read(Path("tests/test2.ipynb"), as_version=4)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/deil/anaconda3/lib/python3.7/site-packages/nbformat/__init__.py", line 141, in read
return reads(fp.read(), as_version, **kwargs)
AttributeError: 'PosixPath' object has no attribute 'read'
```
Looking at the implementation, it's clear why `pathlib.Path` isn't supported:
https://github.com/jupyter/nbformat/blob/b6b5a18e5a40d37f1cc0f71f65108288bdec9bb7/nbformat/__init__.py#L114-L141
But what is a good pattern to support `pathlib.Path` in addition?
Just an extra `if isinstance(fp, pathlib.Path)`, or is there a better way?
Note that the docstring still contains a caveat concerning Python 2, and `py3compat` is used. Probably that could be removed now.
I wanted to send a PR, but it wasn't clear to me how to write it. If you comment or point out an example how you do this in other places in the Jupyter codebase, I can take a shot at it.
|
0.0
|
2f20fd6ba7f7c06be9112ec555daf7838b9a58e4
|
[
"nbformat/tests/test_api.py::TestAPI::test_read_write_pathlib_object"
] |
[
"nbformat/tests/test_api.py::TestAPI::test_read",
"nbformat/tests/test_api.py::TestAPI::test_read_write_path",
"nbformat/tests/test_api.py::TestAPI::test_write_downgrade_2"
] |
{
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-03-30 21:20:33+00:00
|
bsd-3-clause
| 3,361 |
|
jupyter__nbformat-198
|
diff --git a/nbformat/json_compat.py b/nbformat/json_compat.py
index 936d3c8..2c4f81e 100644
--- a/nbformat/json_compat.py
+++ b/nbformat/json_compat.py
@@ -38,6 +38,7 @@ class FastJsonSchemaValidator(JsonSchemaValidator):
name = "fastjsonschema"
def __init__(self, schema):
+ super().__init__(schema)
self._validator = fastjsonschema.compile(schema)
def validate(self, data):
@@ -47,8 +48,11 @@ class FastJsonSchemaValidator(JsonSchemaValidator):
raise ValidationError(error.message, schema_path=error.path)
def iter_errors(self, data, schema=None):
+ if schema is not None:
+ return self._default_validator.iter_errors(data, schema)
+
errors = []
- validate_func = self._validator if schema is None else fastjsonschema.compile(schema)
+ validate_func = self._validator
try:
validate_func(data)
except _JsonSchemaException as error:
|
jupyter/nbformat
|
22396b8340d3bee7e666064560f4d904fece1d27
|
diff --git a/nbformat/tests/test_validator.py b/nbformat/tests/test_validator.py
index 7723dc9..1c7a1ee 100644
--- a/nbformat/tests/test_validator.py
+++ b/nbformat/tests/test_validator.py
@@ -197,3 +197,15 @@ def test_invalid_validator_raises_value_error_after_read():
set_validator("foobar")
with pytest.raises(ValueError):
validate(nb)
+
+
+def test_fallback_validator_with_iter_errors_using_ref():
+ """
+ Test that when creating a standalone object (code_cell etc)
+ the default validator is used as fallback.
+ """
+ import nbformat
+ set_validator("fastjsonschema")
+ nbformat.v4.new_code_cell()
+ nbformat.v4.new_markdown_cell()
+ nbformat.v4.new_raw_cell()
|
When using fastjsonschema, nbformat.v4.new_code_cell throws error
Reproducer -
`env NBFORMAT_VALIDATOR=fastjsonschema python3 -c 'import nbformat; nbformat.v4.new_code_cell()'`
Output-
```Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/Users/maharshi/Library/Python/3.7/lib/python/site-packages/nbformat/v4/nbbase.py", line 124, in new_code_cell
validate(cell, 'code_cell')
File "/Users/maharshi/Library/Python/3.7/lib/python/site-packages/nbformat/v4/nbbase.py", line 38, in validate
return validate(node, ref=ref, version=nbformat)
File "/Users/maharshi/Library/Python/3.7/lib/python/site-packages/nbformat/validator.py", line 262, in validate
relax_add_props=relax_add_props):
File "/Users/maharshi/Library/Python/3.7/lib/python/site-packages/nbformat/validator.py", line 292, in iter_validate
errors = validator.iter_errors(nbdict, {'$ref' : '#/definitions/%s' % ref})
File "/Users/maharshi/Library/Python/3.7/lib/python/site-packages/nbformat/json_compat.py", line 51, in iter_errors
validate_func = self._validator if schema is None else fastjsonschema.compile(schema)
File "/Users/maharshi/Library/Python/3.7/lib/python/site-packages/fastjsonschema/__init__.py", line 167, in compile
global_state = code_generator.global_state
File "/Users/maharshi/Library/Python/3.7/lib/python/site-packages/fastjsonschema/draft04.py", line 70, in global_state
res = super().global_state
File "/Users/maharshi/Library/Python/3.7/lib/python/site-packages/fastjsonschema/generator.py", line 80, in global_state
self._generate_func_code()
File "/Users/maharshi/Library/Python/3.7/lib/python/site-packages/fastjsonschema/generator.py", line 118, in _generate_func_code
self.generate_func_code()
File "/Users/maharshi/Library/Python/3.7/lib/python/site-packages/fastjsonschema/generator.py", line 132, in generate_func_code
self.generate_validation_function(uri, name)
File "/Users/maharshi/Library/Python/3.7/lib/python/site-packages/fastjsonschema/generator.py", line 140, in generate_validation_function
with self._resolver.resolving(uri) as definition:
File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/contextlib.py", line 112, in __enter__
return next(self.gen)
File "/Users/maharshi/Library/Python/3.7/lib/python/site-packages/fastjsonschema/ref_resolver.py", line 135, in resolving
yield resolve_path(schema, fragment)
File "/Users/maharshi/Library/Python/3.7/lib/python/site-packages/fastjsonschema/ref_resolver.py", line 41, in resolve_path
raise JsonSchemaDefinitionException('Unresolvable ref: {}'.format(part))
fastjsonschema.exceptions.JsonSchemaDefinitionException: Unresolvable ref: definitions```
|
0.0
|
22396b8340d3bee7e666064560f4d904fece1d27
|
[
"nbformat/tests/test_validator.py::test_fallback_validator_with_iter_errors_using_ref"
] |
[
"nbformat/tests/test_validator.py::test_nb2[fastjsonschema]",
"nbformat/tests/test_validator.py::test_nb2[jsonschema]",
"nbformat/tests/test_validator.py::test_nb3[fastjsonschema]",
"nbformat/tests/test_validator.py::test_nb3[jsonschema]",
"nbformat/tests/test_validator.py::test_nb4[fastjsonschema]",
"nbformat/tests/test_validator.py::test_nb4[jsonschema]",
"nbformat/tests/test_validator.py::test_nb4_document_info[fastjsonschema]",
"nbformat/tests/test_validator.py::test_nb4_document_info[jsonschema]",
"nbformat/tests/test_validator.py::test_nb4custom[fastjsonschema]",
"nbformat/tests/test_validator.py::test_nb4custom[jsonschema]",
"nbformat/tests/test_validator.py::test_nb4jupyter_metadata[fastjsonschema]",
"nbformat/tests/test_validator.py::test_nb4jupyter_metadata[jsonschema]",
"nbformat/tests/test_validator.py::test_nb4jupyter_metadata_timings[fastjsonschema]",
"nbformat/tests/test_validator.py::test_nb4jupyter_metadata_timings[jsonschema]",
"nbformat/tests/test_validator.py::test_invalid[fastjsonschema]",
"nbformat/tests/test_validator.py::test_invalid[jsonschema]",
"nbformat/tests/test_validator.py::test_validate_empty[fastjsonschema]",
"nbformat/tests/test_validator.py::test_validate_empty[jsonschema]",
"nbformat/tests/test_validator.py::test_future[fastjsonschema]",
"nbformat/tests/test_validator.py::test_future[jsonschema]",
"nbformat/tests/test_validator.py::test_validation_error[jsonschema]",
"nbformat/tests/test_validator.py::test_iter_validation_error[jsonschema]",
"nbformat/tests/test_validator.py::test_iter_validation_empty[fastjsonschema]",
"nbformat/tests/test_validator.py::test_iter_validation_empty[jsonschema]",
"nbformat/tests/test_validator.py::test_validation_no_version[fastjsonschema]",
"nbformat/tests/test_validator.py::test_validation_no_version[jsonschema]",
"nbformat/tests/test_validator.py::test_invalid_validator_raises_value_error",
"nbformat/tests/test_validator.py::test_invalid_validator_raises_value_error_after_read"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2020-11-16 16:12:41+00:00
|
bsd-3-clause
| 3,362 |
|
jupyterhub__binderhub-264
|
diff --git a/.travis.yml b/.travis.yml
index bab73d2..3f92a90 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -11,6 +11,7 @@ install:
| tar -xz -C bin --strip-components 1 linux-amd64/helm
- chmod +x bin/helm
- helm init --client-only
+- pip install .
script:
- |
if [[ "$TRAVIS_PULL_REQUEST" == "false" ]]; then
@@ -20,6 +21,8 @@ script:
cd -
fi
- "./helm-chart/build.py build --commit-range ${TRAVIS_COMMIT_RANGE} $PUSH"
+- pip install pytest
+- pytest -v
branches:
only:
- master
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index ca19102..78a0d6e 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -52,6 +52,12 @@ and run binderhub on the host system.
All features should work, including building and launching.
+9. Running unit tests
+
+ ```bash
+ python setup.py test
+ ```
+
## Pure HTML / CSS / JS development
If you do not want to set up minikube but just want to hack on the html / css / js,
diff --git a/binderhub/repoproviders.py b/binderhub/repoproviders.py
index 69e66f2..32dbdc7 100644
--- a/binderhub/repoproviders.py
+++ b/binderhub/repoproviders.py
@@ -21,6 +21,25 @@ from traitlets.config import LoggingConfigurable
GITHUB_RATE_LIMIT = Gauge('binderhub_github_rate_limit_remaining', 'GitHub rate limit remaining')
+
+def tokenize_spec(spec):
+ """Tokenize a Git Spec into parts, error if spec invalid."""
+
+ spec_parts = spec.split('/', 2) # allow ref to contain "/"
+ if len(spec_parts) != 3:
+ msg = 'Spec is not of the form "user/repo/ref", provided: "{spec}".'.format(spec=spec)
+ if len(spec_parts) == 2 and spec_parts[-1] != 'master':
+ msg += ' Did you mean "{spec}/master"?'.format(spec=spec)
+ raise ValueError(msg)
+
+ return spec_parts
+
+def strip_suffix(text, suffix):
+ if text.endswith(suffix):
+ text = text[:-(len(suffix))]
+ return text
+
+
class RepoProvider(LoggingConfigurable):
"""Base class for a repo provider"""
name = Unicode(
@@ -117,16 +136,8 @@ class GitHubRepoProvider(RepoProvider):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
- spec_parts = self.spec.split('/')
- if len(spec_parts) != 3:
- msg = 'Spec is not of the form "user/repo/ref", provided: "{spec}".'.format(spec=self.spec)
- if len(spec_parts) == 2 and spec_parts[-1] != 'master':
- msg += ' Did you mean "{spec}/master"?'.format(spec=self.spec)
- raise ValueError(msg)
-
- self.user, self.repo, self.unresolved_ref = spec_parts
- if self.repo.endswith('.git'):
- self.repo = self.repo[:len(self.repo) - 4]
+ self.user, self.repo, self.unresolved_ref = self.process_spec(self.spec)
+ self.repo = strip_suffix(self.repo, ".git")
def get_repo_url(self):
return "https://github.com/{user}/{repo}".format(user=self.user, repo=self.repo)
diff --git a/requirements.txt b/requirements.txt
new file mode 100644
index 0000000..1d38a43
--- /dev/null
+++ b/requirements.txt
@@ -0,0 +1,6 @@
+kubernetes==3.*
+tornado
+traitlets
+docker
+jinja2
+prometheus_client
diff --git a/setup.py b/setup.py
index d8e1470..2f6f031 100644
--- a/setup.py
+++ b/setup.py
@@ -1,20 +1,29 @@
from setuptools import setup, find_packages
+from pip.req import parse_requirements
+import uuid
+
+setup_requirements = [
+ 'pytest-runner'
+]
+
+test_requirements = [
+ 'pytest'
+]
+
+install_requirements = [str(ir.req) for ir in parse_requirements(
+ "requirements.txt", session=uuid.uuid1())]
setup(
name='binderhub',
- version='0.1',
- install_requires=[
- 'kubernetes==3.*',
- 'tornado',
- 'traitlets',
- 'docker',
- 'jinja2',
- 'prometheus_client'
- ],
+ version='0.1.1',
+ install_requires=install_requirements,
python_requires='>=3.5',
author='Project Jupyter Contributors',
author_email='[email protected]',
license='BSD',
packages=find_packages(),
include_package_data=True,
+ setup_requires=setup_requirements,
+ test_suite='tests',
+ tests_require=test_requirements
)
|
jupyterhub/binderhub
|
79c58127181ba9baadb47095014eeceb308148d8
|
diff --git a/binderhub/tests/__init__.py b/binderhub/tests/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/binderhub/tests/repoproviders_test.py b/binderhub/tests/repoproviders_test.py
new file mode 100644
index 0000000..01daca5
--- /dev/null
+++ b/binderhub/tests/repoproviders_test.py
@@ -0,0 +1,58 @@
+from unittest import TestCase
+
+import pytest
+
+from binderhub.repoproviders import tokenize_spec, strip_suffix
+
+
+# General string processing
[email protected](
+ 'raw_text, suffix, clean_text', [
+ ("foo.git", ".git", "foo"),
+ ("foo.bar", ".git", "foo.bar"),
+ ("foo.bar", ".bar", "foo")
+ ]
+)
+def test_string_strip(raw_text, suffix, clean_text):
+ assert strip_suffix(raw_text, suffix) == clean_text
+
+
+# user/repo/reference
[email protected](
+ 'spec, raw_user, raw_repo, raw_ref', [
+ ("user/repo/master", "user", "repo", "master"),
+ ("user/repo/hotfix/squash-bug", "user", "repo", "hotfix/squash-bug"),
+ ("user/repo/feature/save_world", "user", "repo", "feature/save_world")
+ ]
+)
+def test_spec_processing(spec, raw_user, raw_repo, raw_ref):
+ user, repo, unresolved_ref = tokenize_spec(spec)
+ assert raw_user == user
+ assert raw_repo == repo
+ assert raw_ref == unresolved_ref
+
+
+class TestSpecErrorHandling(TestCase):
+
+ def test_too_short_spec(self):
+ spec = "nothing_to_split"
+ with self.assertRaisesRegexp(ValueError, "Spec is not of the form"):
+ user, repo, unresolved_ref = tokenize_spec(spec)
+
+ def test_long_spec(self):
+ # No specification is too long, extra slashes go to the "ref" property
+ spec = "a/long/specification/with/many/slashes/to/split/on"
+ spec_parts = tokenize_spec(spec)
+ assert len(spec_parts) == 3
+
+ def test_spec_with_no_suggestion(self):
+ spec = "short/master"
+ error = "^((?!Did you mean).)*$".format(spec) # negative match
+ with self.assertRaisesRegexp(ValueError, error):
+ user, repo, unresolved_ref = tokenize_spec(spec)
+
+ def test_spec_with_suggestion(self):
+ spec = "short/suggestion"
+ error = "Did you mean \"{}/master\"?".format(spec)
+ with self.assertRaisesRegexp(ValueError, error):
+ user, repo, unresolved_ref = tokenize_spec(spec)
|
Setting build by branch won't work if name contains "/"
The git branch naming convention I've been using is something like `hotfix/name-of-issue` or `feature/name-of-issue`. However, I've been unable to build specific branches. I suspect that perhaps the branch reference is being split on `/`, and gets confused if the branch name contains this character.
For example, I've been unable to build my branch here `feature/add-requirements-file` on mybinder.org, so I've had to use the exact commit hash instead:
https://github.com/hydrosquall/pandas-cookbook/tree/feature/add-requirements-file
I get the following error message:
```bash
Spec is not of the form "user/repo/ref", provided: "hydrosquall/pandas-cookbook/feature/add-requi
rements-file".
```
|
0.0
|
79c58127181ba9baadb47095014eeceb308148d8
|
[
"binderhub/tests/repoproviders_test.py::test_string_strip[foo.git-.git-foo]",
"binderhub/tests/repoproviders_test.py::test_string_strip[foo.bar-.git-foo.bar]",
"binderhub/tests/repoproviders_test.py::test_string_strip[foo.bar-.bar-foo]",
"binderhub/tests/repoproviders_test.py::test_spec_processing[user/repo/master-user-repo-master]",
"binderhub/tests/repoproviders_test.py::test_spec_processing[user/repo/hotfix/squash-bug-user-repo-hotfix/squash-bug]",
"binderhub/tests/repoproviders_test.py::test_spec_processing[user/repo/feature/save_world-user-repo-feature/save_world]",
"binderhub/tests/repoproviders_test.py::TestSpecErrorHandling::test_long_spec",
"binderhub/tests/repoproviders_test.py::TestSpecErrorHandling::test_spec_with_no_suggestion",
"binderhub/tests/repoproviders_test.py::TestSpecErrorHandling::test_spec_with_suggestion",
"binderhub/tests/repoproviders_test.py::TestSpecErrorHandling::test_too_short_spec"
] |
[] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_added_files",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2017-11-11 18:54:57+00:00
|
bsd-3-clause
| 3,363 |
|
jupyterhub__chartpress-63
|
diff --git a/.travis.yml b/.travis.yml
index a47cf03..998bf51 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -5,11 +5,12 @@ cache: pip
install:
- set -e
- pip install --upgrade pip
- - pip install pyflakes .
+ - pip install pyflakes pytest .
script:
- chartpress --version
- chartpress --help
- pyflakes .
+ - pytest -v ./tests
# This is a workaround to an issue caused by the existence of a docker
# registrymirror in our CI environment. Without this fix that removes the
diff --git a/CHANGELOG.md b/CHANGELOG.md
index fdbd930..f6b591c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,23 @@
## 0.4
+### 0.4.3
+
+- Support `valuesPath` pointing to a single `image:tag` string in
+ addition to a dict with separate `repository` and `tag` keys.
+- Support lists in `valuesPath` by using integer indices,
+ e.g. `section.list.1.image` for the yaml:
+
+ ```yaml
+ section:
+ list:
+ - first: item
+ image: "not set"
+ - second: item
+ image: "image:tag" # <--sets this here
+ ```
+
+
### 0.4.2
- --long flag to always output build information in image tags and chart version [#57](https://github.com/jupyterhub/chartpress/pull/57) ([@consideRatio](https://github.com/consideRatio))
diff --git a/README.md b/README.md
index 7dbf6a9..6caa976 100644
--- a/README.md
+++ b/README.md
@@ -157,3 +157,19 @@ in your `.travis.yml`:
git:
depth: false
```
+
+## Development
+
+Testing of this python package can be done using [`pyflakes`](https://github.com/PyCQA/pyflakes) and [`pytest`](https://github.com/pytest-dev/pytest). There is also some additional testing that is only run as part of TravisCI, as declared in [`.travis.yml`](.travis.yml).
+
+```
+# install chartpress locally
+pip install -e .
+
+# install dev dependencies
+pip install pyflakes pytest
+
+# run tests
+pyflakes .
+pytest -v
+```
diff --git a/chartpress.py b/chartpress.py
index df0fb19..f6847da 100755
--- a/chartpress.py
+++ b/chartpress.py
@@ -10,6 +10,7 @@ from collections.abc import MutableMapping
from functools import lru_cache, partial
import os
import pipes
+import re
import shutil
import subprocess
from tempfile import TemporaryDirectory
@@ -55,29 +56,42 @@ def git_remote(git_repo):
return '[email protected]:{0}'.format(git_repo)
-def last_modified_commit(*paths, **kwargs):
- """Get the last commit to modify the given paths"""
- return check_output([
- 'git',
- 'log',
- '-n', '1',
- '--pretty=format:%h',
- '--',
- *paths
- ], **kwargs).decode('utf-8').strip()
+def latest_tag_or_mod_commit(*paths, **kwargs):
+ """
+ Get the latest of a) the latest tagged commit, or b) the latest modification
+ commit to provided path.
+ """
+ latest_modification_commit = check_output(
+ [
+ 'git', 'log',
+ '--max-count=1',
+ '--pretty=format:%h',
+ '--',
+ *paths,
+ ],
+ **kwargs,
+ ).decode('utf-8').strip()
+ git_describe_head = check_output(
+ [
+ 'git', 'describe', '--tags', '--long'
+ ],
+ **kwargs,
+ ).decode('utf-8').strip().rsplit("-", maxsplit=2)
+ latest_tagged_commit = git_describe_head[2][1:]
-def last_modified_date(*paths, **kwargs):
- """Return the last modified date (as a string) for the given paths"""
- return check_output([
- 'git',
- 'log',
- '-n', '1',
- '--pretty=format:%cd',
- '--date=iso',
- '--',
- *paths
- ], **kwargs).decode('utf-8').strip()
+ try:
+ check_call(
+ [
+ 'git', 'merge-base', '--is-ancestor', latest_tagged_commit, latest_modification_commit,
+ ],
+ **kwargs,
+ )
+ except subprocess.CalledProcessError:
+ # latest_tagged_commit was newer than latest_modification_commit
+ return latest_tagged_commit
+ else:
+ return latest_modification_commit
def render_build_args(image_options, ns):
@@ -179,7 +193,55 @@ def image_needs_building(image):
return image_needs_pushing(image)
-def build_images(prefix, images, tag=None, push=False, chart_tag=None, skip_build=False, long=False):
+def _get_identifier(tag, n_commits, commit, long):
+ """
+ Returns a chartpress formatted chart version or image tag (identifier) with
+ a build suffix.
+
+ This function should provide valid Helm chart versions, which means they
+ need to be valid SemVer 2 version strings. It also needs to return valid
+ image tags, which means they need to not contain `+` signs either.
+
+ Example:
+ tag="0.1.2", n_commits="5", commit="asdf1234", long=True,
+ should return "0.1.2-005.asdf1234".
+ """
+ n_commits = int(n_commits)
+
+ if n_commits > 0 or long:
+ if "-" in tag:
+ # append a pre-release tag, with a . separator
+ # 0.1.2-alpha.1 -> 0.1.2-alpha.1.n.sha
+ return f"{tag}.{n_commits:03d}.{commit}"
+ else:
+ # append a release tag, with a - separator
+ # 0.1.2 -> 0.1.2-n.sha
+ return f"{tag}-{n_commits:03d}.{commit}"
+ else:
+ return f"{tag}"
+
+
+def _strip_identifiers_build_suffix(identifier):
+ """
+ Return a stripped chart version or image tag (identifier) without its build
+ suffix (.005.asdf1234), leaving it to represent a Semver 2 release or
+ pre-release.
+
+ Example:
+ identifier: "0.1.2-005.asdf1234" returns: "0.1.2"
+ identifier: "0.1.2-alpha.1.005.asdf1234" returns: "0.1.2-alpha.1"
+ """
+ # split away official SemVer 2 build specifications if used
+ if "+" in identifier:
+ return identifier.split("+", maxsplit=1)[0]
+
+ # split away our custom build specification: something ending in either
+ # . or - followed by three or more digits, a dot, an commit sha of four
+ # or more alphanumeric characters.
+ return re.sub(r'[-\.]\d{3,}\.\w{4,}\Z', "", identifier)
+
+
+def build_images(prefix, images, tag=None, push=False, chart_version=None, skip_build=False, long=False):
"""Build a collection of docker images
Args:
@@ -191,9 +253,9 @@ def build_images(prefix, images, tag=None, push=False, chart_tag=None, skip_buil
to modify the image's files.
push (bool):
Whether to push the resulting images (default: False).
- chart_tag (str):
- The latest chart tag, included as a prefix on image tags
- if `tag` is not specified.
+ chart_version (str):
+ The latest chart version, trimmed from its build suffix, will be included
+ as a prefix on image tags if `tag` is not specified.
skip_build (bool):
Whether to skip the actual image build (only updates tags).
long (bool):
@@ -204,38 +266,35 @@ def build_images(prefix, images, tag=None, push=False, chart_tag=None, skip_buil
Example 1:
- long=False: 0.9.0
- - long=True: 0.9.0_000.asdf1234
+ - long=True: 0.9.0-000.asdf1234
Example 2:
- - long=False: 0.9.0_004.sdfg2345
- - long=True: 0.9.0_004.sdfg2345
+ - long=False: 0.9.0-004.sdfg2345
+ - long=True: 0.9.0-004.sdfg2345
"""
value_modifications = {}
for name, options in images.items():
image_path = options.get('contextPath', os.path.join('images', name))
image_tag = tag
+ chart_version = _strip_identifiers_build_suffix(chart_version)
# include chartpress.yaml itself as it can contain build args and
# similar that influence the image that would be built
paths = list(options.get('paths', [])) + [image_path, 'chartpress.yaml']
- last_image_commit = last_modified_commit(*paths)
- if tag is None:
- n_commits = int(check_output(
+ image_commit = latest_tag_or_mod_commit(*paths, echo=False)
+ if image_tag is None:
+ n_commits = check_output(
[
'git', 'rev-list', '--count',
- # Note that the 0.0.1 chart_tag may not exist as it was a
+ # Note that the 0.0.1 chart_version may not exist as it was a
# workaround to handle git histories with no tags in the
- # current branch. Also, if the chart_tag is a later git
- # reference than the last_image_commit, this command will
- # return 0.
- f'{chart_tag + ".." if chart_tag != "0.0.1" else ""}{last_image_commit}',
+ # current branch. Also, if the chart_version is a later git
+ # reference than the image_commit, this
+ # command will return 0.
+ f'{"" if chart_version == "0.0.1" else chart_version + ".."}{image_commit}',
],
echo=False,
- ).decode('utf-8').strip())
-
- if n_commits > 0 or long:
- image_tag = f"{chart_tag}_{int(n_commits):03d}-{last_image_commit}"
- else:
- image_tag = f"{chart_tag}"
+ ).decode('utf-8').strip()
+ image_tag = _get_identifier(chart_version, n_commits, image_commit, long)
image_name = prefix + name
image_spec = '{}:{}'.format(image_name, image_tag)
@@ -251,7 +310,7 @@ def build_images(prefix, images, tag=None, push=False, chart_tag=None, skip_buil
build_args = render_build_args(
options,
{
- 'LAST_COMMIT': last_image_commit,
+ 'LAST_COMMIT': image_commit,
'TAG': image_tag,
},
)
@@ -277,27 +336,49 @@ def build_values(name, values_mods):
values = yaml.load(f)
for key, value in values_mods.items():
+ if not isinstance(value, dict) or set(value.keys()) != {'repository', 'tag'}:
+ raise ValueError(f"I only understand image updates with 'repository', 'tag', not: {value!r}")
parts = key.split('.')
- mod_obj = values
+ mod_obj = parent = values
for p in parts:
+ if p.isdigit():
+ # integers are indices in lists
+ p = int(p)
+ parent = mod_obj
mod_obj = mod_obj[p]
- print(f"Updating {values_file}: {key}: {value}")
+ last_part = p
if isinstance(mod_obj, MutableMapping):
keys = IMAGE_REPOSITORY_KEYS & mod_obj.keys()
if keys:
- for key in keys:
- mod_obj[key] = value['repository']
+ for repo_key in keys:
+ before = mod_obj.get(repo_key, None)
+ if before != value['repository']:
+ print(f"Updating {values_file}: {key}.{repo_key}: {value}")
+ mod_obj[repo_key] = value['repository']
else:
possible_keys = ' or '.join(IMAGE_REPOSITORY_KEYS)
raise KeyError(
f'Could not find {possible_keys} in {values_file}:{key}'
)
+ before = mod_obj.get('tag', None)
+ if before != value['tag']:
+ print(f"Updating {values_file}: {key}.tag: {value}")
mod_obj['tag'] = value['tag']
+ elif isinstance(mod_obj, str):
+ # scalar image string, not dict with separate repository, tag keys
+ image = "{repository}:{tag}".format(**value)
+ try:
+ before = parent[last_part]
+ except (KeyError, IndexError):
+ before = None
+ if before != image:
+ print(f"Updating {values_file}: {key}: {image}")
+ parent[last_part] = image
else:
raise TypeError(
- f'The key {key} in {values_file} must be a mapping.'
+ f'The key {key} in {values_file} must be a mapping or string, not {type(mod_obj)}.'
)
@@ -315,34 +396,43 @@ def build_chart(name, version=None, paths=None, long=False):
Example versions constructed:
- 0.9.0-alpha.1
- - 0.9.0-alpha.1+000.asdf1234 (--long)
- - 0.9.0-alpha.1+005.sdfg2345
- - 0.9.0-alpha.1+005.sdfg2345 (--long)
+ - 0.9.0-alpha.1.000.asdf1234 (--long)
+ - 0.9.0-alpha.1.005.sdfg2345
+ - 0.9.0-alpha.1.005.sdfg2345 (--long)
+ - 0.9.0
+ - 0.9.0-002.dfgh3456
"""
chart_file = os.path.join(name, 'Chart.yaml')
with open(chart_file) as f:
chart = yaml.load(f)
- last_chart_commit = last_modified_commit(*paths)
-
if version is None:
+ chart_commit = latest_tag_or_mod_commit(*paths, echo=False)
+
try:
- git_describe = check_output(['git', 'describe', '--tags', '--long', last_chart_commit]).decode('utf8').strip()
+ git_describe = check_output(
+ [
+ 'git', 'describe', '--tags', '--long', chart_commit
+ ],
+ echo=False,
+ ).decode('utf8').strip()
latest_tag_in_branch, n_commits, sha = git_describe.rsplit('-', maxsplit=2)
-
- n_commits = int(n_commits)
- if n_commits > 0 or long:
- version = f"{latest_tag_in_branch}+{n_commits:03d}.{sha}"
- else:
- version = f"{latest_tag_in_branch}"
+ # remove "g" prefix output by the git describe command
+ # ref: https://git-scm.com/docs/git-describe#_examples
+ sha = sha[1:]
+ version = _get_identifier(latest_tag_in_branch, n_commits, sha, long)
except subprocess.CalledProcessError:
# no tags on branch: fallback to the SemVer 2 compliant version
- # 0.0.1+<n_comits>.<last_chart_commit>
- n_commits = int(check_output(
- ['git', 'rev-list', '--count', last_chart_commit],
+ # 0.0.1-<n_commits>.<chart_commit>
+ latest_tag_in_branch = "0.0.1"
+ n_commits = check_output(
+ [
+ 'git', 'rev-list', '--count', chart_commit
+ ],
echo=False,
- ).decode('utf-8').strip())
- version = f"0.0.1+{n_commits:03d}.{last_chart_commit}"
+ ).decode('utf-8').strip()
+
+ version = _get_identifier(latest_tag_in_branch, n_commits, chart_commit, long)
chart['version'] = version
@@ -510,10 +600,7 @@ def main():
images=chart['images'],
tag=args.tag if not args.reset else chart.get('resetTag', 'set-by-chartpress'),
push=args.push,
- # chart_tag will act as a image tag prefix, we can get it from
- # the chart_version by stripping away the build part of the
- # SemVer 2 compliant chart_version.
- chart_tag=chart_version.split('+')[0],
+ chart_version=chart_version,
skip_build=args.skip_build or args.reset,
long=args.long,
)
|
jupyterhub/chartpress
|
84df258b335fe19d56d3fc849a9241d9c4eb7afe
|
diff --git a/tests/test_regexp.py b/tests/test_regexp.py
new file mode 100644
index 0000000..b597655
--- /dev/null
+++ b/tests/test_regexp.py
@@ -0,0 +1,14 @@
+from chartpress import _strip_identifiers_build_suffix
+from chartpress import _get_identifier
+
+def test__strip_identifiers_build_suffix():
+ assert _strip_identifiers_build_suffix(identifier="0.1.2-005.asdf1234") == "0.1.2"
+ assert _strip_identifiers_build_suffix(identifier="0.1.2-alpha.1.005.asdf1234") == "0.1.2-alpha.1"
+
+def test__get_identifier():
+ assert _get_identifier(tag="0.1.2", n_commits="0", commit="asdf123", long=True) == "0.1.2-000.asdf123"
+ assert _get_identifier(tag="0.1.2", n_commits="0", commit="asdf123", long=False) == "0.1.2"
+ assert _get_identifier(tag="0.1.2", n_commits="5", commit="asdf123", long=False) == "0.1.2-005.asdf123"
+ assert _get_identifier(tag="0.1.2-alpha.1", n_commits="0", commit="asdf1234", long=True) == "0.1.2-alpha.1.000.asdf1234"
+ assert _get_identifier(tag="0.1.2-alpha.1", n_commits="0", commit="asdf1234", long=False) == "0.1.2-alpha.1"
+ assert _get_identifier(tag="0.1.2-alpha.1", n_commits="5", commit="asdf1234", long=False) == "0.1.2-alpha.1.005.asdf1234"
|
Support images defined as string
Add support for images defined as `<registry>/<repo>:<tag>`.
Possible solutions to keep compatibility with images defined as mapping:
1. check the image value in `values.yaml`
2. if it is mapping use current way of setting the dictionary;
3. else use formatted string `"{registry}/{repo}:{tag}".format(...)`
Please let me know what you think and I will send a PR.
|
0.0
|
84df258b335fe19d56d3fc849a9241d9c4eb7afe
|
[
"tests/test_regexp.py::test__strip_identifiers_build_suffix",
"tests/test_regexp.py::test__get_identifier"
] |
[] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-10-20 17:39:35+00:00
|
bsd-3-clause
| 3,364 |
|
jupyterhub__chartpress-64
|
diff --git a/.travis.yml b/.travis.yml
index a47cf03..998bf51 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -5,11 +5,12 @@ cache: pip
install:
- set -e
- pip install --upgrade pip
- - pip install pyflakes .
+ - pip install pyflakes pytest .
script:
- chartpress --version
- chartpress --help
- pyflakes .
+ - pytest -v ./tests
# This is a workaround to an issue caused by the existence of a docker
# registrymirror in our CI environment. Without this fix that removes the
diff --git a/README.md b/README.md
index 7dbf6a9..6caa976 100644
--- a/README.md
+++ b/README.md
@@ -157,3 +157,19 @@ in your `.travis.yml`:
git:
depth: false
```
+
+## Development
+
+Testing of this python package can be done using [`pyflakes`](https://github.com/PyCQA/pyflakes) and [`pytest`](https://github.com/pytest-dev/pytest). There is also some additional testing that is only run as part of TravisCI, as declared in [`.travis.yml`](.travis.yml).
+
+```
+# install chartpress locally
+pip install -e .
+
+# install dev dependencies
+pip install pyflakes pytest
+
+# run tests
+pyflakes .
+pytest -v
+```
diff --git a/chartpress.py b/chartpress.py
index df0fb19..1685946 100755
--- a/chartpress.py
+++ b/chartpress.py
@@ -10,6 +10,7 @@ from collections.abc import MutableMapping
from functools import lru_cache, partial
import os
import pipes
+import re
import shutil
import subprocess
from tempfile import TemporaryDirectory
@@ -55,29 +56,42 @@ def git_remote(git_repo):
return '[email protected]:{0}'.format(git_repo)
-def last_modified_commit(*paths, **kwargs):
- """Get the last commit to modify the given paths"""
- return check_output([
- 'git',
- 'log',
- '-n', '1',
- '--pretty=format:%h',
- '--',
- *paths
- ], **kwargs).decode('utf-8').strip()
+def latest_tag_or_mod_commit(*paths, **kwargs):
+ """
+ Get the latest of a) the latest tagged commit, or b) the latest modification
+ commit to provided path.
+ """
+ latest_modification_commit = check_output(
+ [
+ 'git', 'log',
+ '--max-count=1',
+ '--pretty=format:%h',
+ '--',
+ *paths,
+ ],
+ **kwargs,
+ ).decode('utf-8').strip()
+ git_describe_head = check_output(
+ [
+ 'git', 'describe', '--tags', '--long'
+ ],
+ **kwargs,
+ ).decode('utf-8').strip().rsplit("-", maxsplit=2)
+ latest_tagged_commit = git_describe_head[2][1:]
-def last_modified_date(*paths, **kwargs):
- """Return the last modified date (as a string) for the given paths"""
- return check_output([
- 'git',
- 'log',
- '-n', '1',
- '--pretty=format:%cd',
- '--date=iso',
- '--',
- *paths
- ], **kwargs).decode('utf-8').strip()
+ try:
+ check_call(
+ [
+ 'git', 'merge-base', '--is-ancestor', latest_tagged_commit, latest_modification_commit,
+ ],
+ **kwargs,
+ )
+ except subprocess.CalledProcessError:
+ # latest_tagged_commit was newer than latest_modification_commit
+ return latest_tagged_commit
+ else:
+ return latest_modification_commit
def render_build_args(image_options, ns):
@@ -179,7 +193,55 @@ def image_needs_building(image):
return image_needs_pushing(image)
-def build_images(prefix, images, tag=None, push=False, chart_tag=None, skip_build=False, long=False):
+def _get_identifier(tag, n_commits, commit, long):
+ """
+ Returns a chartpress formatted chart version or image tag (identifier) with
+ a build suffix.
+
+ This function should provide valid Helm chart versions, which means they
+ need to be valid SemVer 2 version strings. It also needs to return valid
+ image tags, which means they need to not contain `+` signs either.
+
+ Example:
+ tag="0.1.2", n_commits="5", commit="asdf1234", long=True,
+ should return "0.1.2-005.asdf1234".
+ """
+ n_commits = int(n_commits)
+
+ if n_commits > 0 or long:
+ if "-" in tag:
+ # append a pre-release tag, with a . separator
+ # 0.1.2-alpha.1 -> 0.1.2-alpha.1.n.sha
+ return f"{tag}.{n_commits:03d}.{commit}"
+ else:
+ # append a release tag, with a - separator
+ # 0.1.2 -> 0.1.2-n.sha
+ return f"{tag}-{n_commits:03d}.{commit}"
+ else:
+ return f"{tag}"
+
+
+def _strip_identifiers_build_suffix(identifier):
+ """
+ Return a stripped chart version or image tag (identifier) without its build
+ suffix (.005.asdf1234), leaving it to represent a Semver 2 release or
+ pre-release.
+
+ Example:
+ identifier: "0.1.2-005.asdf1234" returns: "0.1.2"
+ identifier: "0.1.2-alpha.1.005.asdf1234" returns: "0.1.2-alpha.1"
+ """
+ # split away official SemVer 2 build specifications if used
+ if "+" in identifier:
+ return identifier.split("+", maxsplit=1)[0]
+
+ # split away our custom build specification: something ending in either
+ # . or - followed by three or more digits, a dot, an commit sha of four
+ # or more alphanumeric characters.
+ return re.sub(r'[-\.]\d{3,}\.\w{4,}\Z', "", identifier)
+
+
+def build_images(prefix, images, tag=None, push=False, chart_version=None, skip_build=False, long=False):
"""Build a collection of docker images
Args:
@@ -191,9 +253,9 @@ def build_images(prefix, images, tag=None, push=False, chart_tag=None, skip_buil
to modify the image's files.
push (bool):
Whether to push the resulting images (default: False).
- chart_tag (str):
- The latest chart tag, included as a prefix on image tags
- if `tag` is not specified.
+ chart_version (str):
+ The latest chart version, trimmed from its build suffix, will be included
+ as a prefix on image tags if `tag` is not specified.
skip_build (bool):
Whether to skip the actual image build (only updates tags).
long (bool):
@@ -204,38 +266,35 @@ def build_images(prefix, images, tag=None, push=False, chart_tag=None, skip_buil
Example 1:
- long=False: 0.9.0
- - long=True: 0.9.0_000.asdf1234
+ - long=True: 0.9.0-000.asdf1234
Example 2:
- - long=False: 0.9.0_004.sdfg2345
- - long=True: 0.9.0_004.sdfg2345
+ - long=False: 0.9.0-004.sdfg2345
+ - long=True: 0.9.0-004.sdfg2345
"""
value_modifications = {}
for name, options in images.items():
image_path = options.get('contextPath', os.path.join('images', name))
image_tag = tag
+ chart_version = _strip_identifiers_build_suffix(chart_version)
# include chartpress.yaml itself as it can contain build args and
# similar that influence the image that would be built
paths = list(options.get('paths', [])) + [image_path, 'chartpress.yaml']
- last_image_commit = last_modified_commit(*paths)
- if tag is None:
- n_commits = int(check_output(
+ image_commit = latest_tag_or_mod_commit(*paths, echo=False)
+ if image_tag is None:
+ n_commits = check_output(
[
'git', 'rev-list', '--count',
- # Note that the 0.0.1 chart_tag may not exist as it was a
+ # Note that the 0.0.1 chart_version may not exist as it was a
# workaround to handle git histories with no tags in the
- # current branch. Also, if the chart_tag is a later git
- # reference than the last_image_commit, this command will
- # return 0.
- f'{chart_tag + ".." if chart_tag != "0.0.1" else ""}{last_image_commit}',
+ # current branch. Also, if the chart_version is a later git
+ # reference than the image_commit, this
+ # command will return 0.
+ f'{"" if chart_version == "0.0.1" else chart_version + ".."}{image_commit}',
],
echo=False,
- ).decode('utf-8').strip())
-
- if n_commits > 0 or long:
- image_tag = f"{chart_tag}_{int(n_commits):03d}-{last_image_commit}"
- else:
- image_tag = f"{chart_tag}"
+ ).decode('utf-8').strip()
+ image_tag = _get_identifier(chart_version, n_commits, image_commit, long)
image_name = prefix + name
image_spec = '{}:{}'.format(image_name, image_tag)
@@ -251,7 +310,7 @@ def build_images(prefix, images, tag=None, push=False, chart_tag=None, skip_buil
build_args = render_build_args(
options,
{
- 'LAST_COMMIT': last_image_commit,
+ 'LAST_COMMIT': image_commit,
'TAG': image_tag,
},
)
@@ -315,34 +374,43 @@ def build_chart(name, version=None, paths=None, long=False):
Example versions constructed:
- 0.9.0-alpha.1
- - 0.9.0-alpha.1+000.asdf1234 (--long)
- - 0.9.0-alpha.1+005.sdfg2345
- - 0.9.0-alpha.1+005.sdfg2345 (--long)
+ - 0.9.0-alpha.1.000.asdf1234 (--long)
+ - 0.9.0-alpha.1.005.sdfg2345
+ - 0.9.0-alpha.1.005.sdfg2345 (--long)
+ - 0.9.0
+ - 0.9.0-002.dfgh3456
"""
chart_file = os.path.join(name, 'Chart.yaml')
with open(chart_file) as f:
chart = yaml.load(f)
- last_chart_commit = last_modified_commit(*paths)
-
if version is None:
+ chart_commit = latest_tag_or_mod_commit(*paths, echo=False)
+
try:
- git_describe = check_output(['git', 'describe', '--tags', '--long', last_chart_commit]).decode('utf8').strip()
+ git_describe = check_output(
+ [
+ 'git', 'describe', '--tags', '--long', chart_commit
+ ],
+ echo=False,
+ ).decode('utf8').strip()
latest_tag_in_branch, n_commits, sha = git_describe.rsplit('-', maxsplit=2)
-
- n_commits = int(n_commits)
- if n_commits > 0 or long:
- version = f"{latest_tag_in_branch}+{n_commits:03d}.{sha}"
- else:
- version = f"{latest_tag_in_branch}"
+ # remove "g" prefix output by the git describe command
+ # ref: https://git-scm.com/docs/git-describe#_examples
+ sha = sha[1:]
+ version = _get_identifier(latest_tag_in_branch, n_commits, sha, long)
except subprocess.CalledProcessError:
# no tags on branch: fallback to the SemVer 2 compliant version
- # 0.0.1+<n_comits>.<last_chart_commit>
- n_commits = int(check_output(
- ['git', 'rev-list', '--count', last_chart_commit],
+ # 0.0.1-<n_commits>.<chart_commit>
+ latest_tag_in_branch = "0.0.1"
+ n_commits = check_output(
+ [
+ 'git', 'rev-list', '--count', chart_commit
+ ],
echo=False,
- ).decode('utf-8').strip())
- version = f"0.0.1+{n_commits:03d}.{last_chart_commit}"
+ ).decode('utf-8').strip()
+
+ version = _get_identifier(latest_tag_in_branch, n_commits, chart_commit, long)
chart['version'] = version
@@ -510,10 +578,7 @@ def main():
images=chart['images'],
tag=args.tag if not args.reset else chart.get('resetTag', 'set-by-chartpress'),
push=args.push,
- # chart_tag will act as a image tag prefix, we can get it from
- # the chart_version by stripping away the build part of the
- # SemVer 2 compliant chart_version.
- chart_tag=chart_version.split('+')[0],
+ chart_version=chart_version,
skip_build=args.skip_build or args.reset,
long=args.long,
)
|
jupyterhub/chartpress
|
84df258b335fe19d56d3fc849a9241d9c4eb7afe
|
diff --git a/tests/test_regexp.py b/tests/test_regexp.py
new file mode 100644
index 0000000..b597655
--- /dev/null
+++ b/tests/test_regexp.py
@@ -0,0 +1,14 @@
+from chartpress import _strip_identifiers_build_suffix
+from chartpress import _get_identifier
+
+def test__strip_identifiers_build_suffix():
+ assert _strip_identifiers_build_suffix(identifier="0.1.2-005.asdf1234") == "0.1.2"
+ assert _strip_identifiers_build_suffix(identifier="0.1.2-alpha.1.005.asdf1234") == "0.1.2-alpha.1"
+
+def test__get_identifier():
+ assert _get_identifier(tag="0.1.2", n_commits="0", commit="asdf123", long=True) == "0.1.2-000.asdf123"
+ assert _get_identifier(tag="0.1.2", n_commits="0", commit="asdf123", long=False) == "0.1.2"
+ assert _get_identifier(tag="0.1.2", n_commits="5", commit="asdf123", long=False) == "0.1.2-005.asdf123"
+ assert _get_identifier(tag="0.1.2-alpha.1", n_commits="0", commit="asdf1234", long=True) == "0.1.2-alpha.1.000.asdf1234"
+ assert _get_identifier(tag="0.1.2-alpha.1", n_commits="0", commit="asdf1234", long=False) == "0.1.2-alpha.1"
+ assert _get_identifier(tag="0.1.2-alpha.1", n_commits="5", commit="asdf1234", long=False) == "0.1.2-alpha.1.005.asdf1234"
|
Pre-release replaced by later builds
I've found a reproducible issue since #52 relating to the use of chartpress. Apparently, if we use chartpress to publish a tagged commit, like `0.9.0-alpha.1`, and later use chartpress to publish a later commit, it appears that Helm chart repository's `index.yaml` will get its entry about `0.9.0-alpha.1` replaced by `0.9.0-alpha.1+001.g152b8c9a`, instead of having it added alongside...
https://github.com/jupyterhub/helm-chart/commit/29f7cbe19f5eba8cc76f2fefaa57d70ce2668495#diff-43a27642790006c93fea79f384f23b4fL2858-R2859
## Reproduction
You need chartpress and helm, where helm is initialized with `helm init --client-only`.
```
pip install chartpress=0.4.2
```
```
rm -rf /tmp/{z2jh,helm-chart,index}
mkdir /tmp/{z2jh,helm-chart,index}
pushd /tmp/helm-chart
git clone https://github.com/jupyterhub/helm-chart . --no-checkout
git checkout 6c4de08
popd
pushd /tmp/index
git init
helm repo index . --merge /tmp/helm-chart/index.yaml --url https://jupyterhub.github.io/helm-chart
git add index.yaml
git commit -m "index.yaml initial state: with 0.9.0-alpha.1"
rm --interactive=never /tmp/index/*
popd
pushd /tmp/z2jh
git clone https://github.com/jupyterhub/zero-to-jupyterhub-k8s . --no-checkout
git checkout 83af061d
chartpress --skip-build
helm package ./jupyterhub --destination /tmp/index
mv /tmp/index/jupyterhub-0.9.0-alpha.1+001.g152b8c9.tgz /tmp/index/jupyterhub-0.9.0-alpha.1_001.g152b8c9.tgz
popd
pushd /tmp/index
helm repo index . --merge /tmp/helm-chart/index.yaml --url https://jupyterhub.github.io/helm-chart
git add index.yaml
git commit -m "merge with 0.9.0-alpha.1+n.sha overrode 0.9.0-alpha.1 entry"
cp /tmp/index/* /tmp/helm-chart/
rm --interactive=never /tmp/index/*
#rm /tmp/index/index.yaml
popd
pushd /tmp/z2jh
git checkout 0.9.0-alpha.1
chartpress --skip-build
helm package ./jupyterhub --destination /tmp/index
popd
pushd /tmp/index
helm repo index . --merge /tmp/helm-chart/index.yaml --url https://jupyterhub.github.io/helm-chart
rm --interactive=never /tmp/index/jupyterhub-*
git add index.yaml
git commit -m "Should not do anything."
```
## Reproduction results
```diff
- apiVersion: v1
appVersion: 1.0.1dev
- created: "2019-10-17T22:17:04.353205591Z"
+ created: "2019-10-19T20:01:39.379225412+02:00"
description: Multi-user Jupyter installation
- digest: 4835bf4b9d3130ad5747052a0eec50f1e5b2ef5133b9084d3a4e5a9f3602cc3e
+ digest: 9789053b0136b06fe3be4e429c1b57d69cc097faac80cdaf21239afa36f650a7
home: https://z2jh.jupyter.org
icon: https://jupyter.org/assets/hublogo.svg
kubeVersion: '>=1.11.0-0'
@@ -2847,8 +2847,8 @@ entries:
- https://github.com/jupyterhub/zero-to-jupyterhub-k8s
tillerVersion: '>=2.11.0-0'
urls:
- - https://jupyterhub.github.io/helm-chart/jupyterhub-0.9.0-alpha.1.tgz
- version: 0.9.0-alpha.1
+ - https://jupyterhub.github.io/helm-chart/jupyterhub-0.9.0-alpha.1+001.g152b8c9.tgz
+ version: 0.9.0-alpha.1+001.g152b8c9
```
|
0.0
|
84df258b335fe19d56d3fc849a9241d9c4eb7afe
|
[
"tests/test_regexp.py::test__strip_identifiers_build_suffix",
"tests/test_regexp.py::test__get_identifier"
] |
[] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_media",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-10-21 08:09:44+00:00
|
bsd-3-clause
| 3,365 |
|
jupyterhub__kubespawner-105
|
diff --git a/kubespawner/objects.py b/kubespawner/objects.py
index e2632b7..0f34a49 100644
--- a/kubespawner/objects.py
+++ b/kubespawner/objects.py
@@ -36,6 +36,7 @@ def make_pod(
volumes=[],
volume_mounts=[],
labels={},
+ annotations={},
cpu_limit=None,
cpu_guarantee=None,
mem_limit=None,
@@ -97,6 +98,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 +134,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()
diff --git a/kubespawner/spawner.py b/kubespawner/spawner.py
index c2bffd9..4f75887 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,
@@ -764,6 +781,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,6 +799,7 @@ 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,
|
jupyterhub/kubespawner
|
054f6d61cb23232983ca3db74177b2732f15de14
|
diff --git a/tests/test_objects.py b/tests/test_objects.py
index cc0bde8..c861b7a 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
|
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.
|
0.0
|
054f6d61cb23232983ca3db74177b2732f15de14
|
[
"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_pod_with_extra_resources",
"tests/test_objects.py::test_make_pvc_simple",
"tests/test_objects.py::test_make_resources_all"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2017-11-27 21:58:36+00:00
|
bsd-3-clause
| 3,366 |
|
jupyterhub__kubespawner-122
|
diff --git a/kubespawner/objects.py b/kubespawner/objects.py
index ae0d42e..f31af8e 100644
--- a/kubespawner/objects.py
+++ b/kubespawner/objects.py
@@ -170,7 +170,7 @@ def make_pod(
notebook_container.image_pull_policy = image_pull_policy
notebook_container.lifecycle = lifecycle_hooks
notebook_container.resources = V1ResourceRequirements()
-
+
if service_account is None:
# Add a hack to ensure that no service accounts are mounted in spawned pods
# This makes sure that we don"t accidentally give access to the whole
@@ -187,6 +187,9 @@ def make_pod(
hack_volume_mount.mount_path = "/var/run/secrets/kubernetes.io/serviceaccount"
hack_volume_mount.read_only = True
hack_volume_mounts = [hack_volume_mount]
+
+ # Non-hacky way of not mounting service accounts
+ pod.spec.automount_service_account_token = False
else:
hack_volumes = []
hack_volume_mounts = []
@@ -250,7 +253,8 @@ def make_pvc(
storage_class,
access_modes,
storage,
- labels
+ labels,
+ annotations={}
):
"""
Make a k8s pvc specification for running a user notebook.
@@ -272,9 +276,7 @@ def make_pvc(
pvc.api_version = "v1"
pvc.metadata = V1ObjectMeta()
pvc.metadata.name = name
- pvc.metadata.annotations = {}
- if storage_class:
- pvc.metadata.annotations.update({"volume.beta.kubernetes.io/storage-class": storage_class})
+ pvc.metadata.annotations = annotations
pvc.metadata.labels = {}
pvc.metadata.labels.update(labels)
pvc.spec = V1PersistentVolumeClaimSpec()
@@ -282,6 +284,10 @@ def make_pvc(
pvc.spec.resources = V1ResourceRequirements()
pvc.spec.resources.requests = {"storage": storage}
+ if storage_class:
+ pvc.metadata.annotations.update({"volume.beta.kubernetes.io/storage-class": storage_class})
+ pvc.spec.storage_class_name = storage_class
+
return pvc
def make_ingress(
diff --git a/kubespawner/spawner.py b/kubespawner/spawner.py
index e3da4d9..163303a 100644
--- a/kubespawner/spawner.py
+++ b/kubespawner/spawner.py
@@ -783,12 +783,8 @@ class KubeSpawner(Spawner):
labels = {
'heritage': 'jupyterhub',
'app': 'jupyterhub',
- 'hub.jupyter.org/username': escapism.escape(self.user.name)
}
- if self.name:
- # FIXME: Make sure this is dns safe?
- labels['hub.jupyter.org/servername'] = self.name
labels.update(extra_labels)
return labels
@@ -801,6 +797,17 @@ class KubeSpawner(Spawner):
labels.update(self.pod_reflector.labels)
return self._build_common_labels(labels)
+ def _build_common_annotations(self, extra_annotations):
+ # Annotations don't need to be escaped
+ annotations = {
+ 'hub.jupyter.org/username': self.user.name
+ }
+ if self.name:
+ annotations['hub.jupyter.org/servername'] = self.name
+
+ annotations.update(extra_annotations)
+ return annotations
+
@gen.coroutine
def get_pod_manifest(self):
"""
@@ -822,7 +829,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)
+ annotations = self._build_common_annotations(self._expand_all(self.singleuser_extra_annotations))
return make_pod(
name=self.pod_name,
@@ -861,12 +868,15 @@ class KubeSpawner(Spawner):
"""
labels = self._build_common_labels(self._expand_all(self.user_storage_extra_labels))
+ annotations = self._build_common_annotations({})
+
return make_pvc(
name=self.pvc_name,
storage_class=self.user_storage_class,
access_modes=self.user_storage_access_modes,
storage=self.user_storage_capacity,
- labels=labels
+ labels=labels,
+ annotations=annotations
)
def is_pod_running(self, pod):
|
jupyterhub/kubespawner
|
5c9bf38731e8f5b04b5001d78987b7408ed1ae00
|
diff --git a/tests/test_objects.py b/tests/test_objects.py
index a9f0311..8508723 100644
--- a/tests/test_objects.py
+++ b/tests/test_objects.py
@@ -24,6 +24,7 @@ def test_make_simplest_pod():
},
"spec": {
"securityContext": {},
+ 'automountServiceAccountToken': False,
"containers": [
{
"env": [],
@@ -66,6 +67,7 @@ def test_make_labeled_pod():
},
"spec": {
"securityContext": {},
+ 'automountServiceAccountToken': False,
"containers": [
{
"env": [],
@@ -109,6 +111,7 @@ def test_make_annotated_pod():
},
"spec": {
"securityContext": {},
+ 'automountServiceAccountToken': False,
"containers": [
{
"env": [],
@@ -151,6 +154,7 @@ def test_make_pod_with_image_pull_secrets():
},
"spec": {
"securityContext": {},
+ 'automountServiceAccountToken': False,
"imagePullSecrets": [
{'name': 'super-sekrit'}
],
@@ -201,6 +205,7 @@ def test_set_pod_uid_fs_gid():
"runAsUser": 1000,
"fsGroup": 1000
},
+ 'automountServiceAccountToken': False,
"containers": [
{
"env": [],
@@ -243,8 +248,9 @@ def test_run_privileged_container():
},
"spec": {
"securityContext": {},
+ 'automountServiceAccountToken': False,
"containers": [
- {
+ {
"env": [],
"name": "notebook",
"image": "jupyter/singleuser:latest",
@@ -293,6 +299,7 @@ def test_make_pod_resources_all():
},
"spec": {
"securityContext": {},
+ 'automountServiceAccountToken': False,
"imagePullSecrets": [{"name": "myregistrykey"}],
"nodeSelector": {"disk": "ssd"},
"containers": [
@@ -345,6 +352,7 @@ def test_make_pod_with_env():
"labels": {},
},
"spec": {
+ 'automountServiceAccountToken': False,
"securityContext": {},
"containers": [
{
@@ -396,6 +404,7 @@ def test_make_pod_with_lifecycle():
},
"spec": {
"securityContext": {},
+ 'automountServiceAccountToken': False,
"containers": [
{
"env": [],
@@ -458,6 +467,7 @@ def test_make_pod_with_init_containers():
"labels": {},
},
"spec": {
+ 'automountServiceAccountToken': False,
"securityContext": {},
"containers": [
{
@@ -524,6 +534,7 @@ def test_make_pod_with_extra_container_config():
"labels": {},
},
"spec": {
+ 'automountServiceAccountToken': False,
"securityContext": {},
"containers": [
{
@@ -584,6 +595,7 @@ def test_make_pod_with_extra_pod_config():
"labels": {},
},
"spec": {
+ 'automountServiceAccountToken': False,
"securityContext": {},
"containers": [
{
@@ -642,6 +654,7 @@ def test_make_pod_with_extra_containers():
"labels": {},
},
"spec": {
+ 'automountServiceAccountToken': False,
"securityContext": {},
"containers": [
{
@@ -698,6 +711,7 @@ def test_make_pod_with_extra_resources():
"labels": {},
},
"spec": {
+ 'automountServiceAccountToken': False,
"securityContext": {},
"imagePullSecrets": [{"name": "myregistrykey"}],
"nodeSelector": {"disk": "ssd"},
@@ -787,6 +801,7 @@ def test_make_resources_all():
}
},
'spec': {
+ 'storageClassName': 'gce-standard-storage',
'accessModes': ['ReadWriteOnce'],
'resources': {
'requests': {
|
Long user names used in pod and pvc labels not allowed by k8s
The `hub.jupyter.org/username` label in pod or pvc manifests (e.g. https://github.com/jupyterhub/kubespawner/blob/master/kubespawner/spawner.py#L663) when user name has more than 63 characters will make the creation of the pod fail with a error like this:
error: invalid label value: "hub.jupyter.org/username=notebook-a8e986f5974c1ee896fa7717cad98511be0388b3d667535d9af7fe18feab7e3d": must be no more than 63 characters
The username I'm using comes from an external OAuth2 IdP and has a fixed length of 64 characters so any pod creation will always fail. As a workaround I have changed the label to `hub.jupyter.org/userid` and use the id which should be small enough. However I'm not sure if that's the right approach.
|
0.0
|
5c9bf38731e8f5b04b5001d78987b7408ed1ae00
|
[
"tests/test_objects.py::test_make_simplest_pod",
"tests/test_objects.py::test_make_labeled_pod",
"tests/test_objects.py::test_make_annotated_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_pod_with_extra_resources",
"tests/test_objects.py::test_make_resources_all"
] |
[
"tests/test_objects.py::test_make_pvc_simple",
"tests/test_objects.py::test_make_pod_with_service_account"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-01-22 18:45:58+00:00
|
bsd-3-clause
| 3,367 |
|
jupyterhub__kubespawner-239
|
diff --git a/kubespawner/objects.py b/kubespawner/objects.py
index f29fe55..1c1944f 100644
--- a/kubespawner/objects.py
+++ b/kubespawner/objects.py
@@ -21,6 +21,9 @@ from kubernetes.client.models import (
V1beta1HTTPIngressRuleValue, V1beta1HTTPIngressPath,
V1beta1IngressBackend,
V1Toleration,
+ V1Affinity,
+ V1NodeAffinity, V1NodeSelector, V1NodeSelectorTerm, V1PreferredSchedulingTerm, V1NodeSelectorRequirement,
+ V1PodAffinity, V1PodAntiAffinity, V1WeightedPodAffinityTerm, V1PodAffinityTerm,
)
def make_pod(
@@ -56,6 +59,12 @@ def make_pod(
extra_containers=None,
scheduler_name=None,
tolerations=None,
+ node_affinity_preferred=None,
+ node_affinity_required=None,
+ pod_affinity_preferred=None,
+ pod_affinity_required=None,
+ pod_anti_affinity_preferred=None,
+ pod_anti_affinity_required=None,
priority_class_name=None,
logger=None,
):
@@ -156,6 +165,54 @@ def make_pod(
Pass this field an array of "Toleration" objects.*
* https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.10/#nodeselectorterm-v1-core
+ node_affinity_preferred:
+ Affinities describe where pods prefer or require to be scheduled, they
+ may prefer or require a node to have a certain label or be in proximity
+ / remoteness to another pod. To learn more visit
+ https://kubernetes.io/docs/concepts/configuration/assign-pod-node/
+
+ Pass this field an array of "PreferredSchedulingTerm" objects.*
+ * https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.10/#preferredschedulingterm-v1-core
+ node_affinity_required:
+ Affinities describe where pods prefer or require to be scheduled, they
+ may prefer or require a node to have a certain label or be in proximity
+ / remoteness to another pod. To learn more visit
+ https://kubernetes.io/docs/concepts/configuration/assign-pod-node/
+
+ Pass this field an array of "NodeSelectorTerm" objects.*
+ * https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.10/#nodeselectorterm-v1-core
+ pod_affinity_preferred:
+ Affinities describe where pods prefer or require to be scheduled, they
+ may prefer or require a node to have a certain label or be in proximity
+ / remoteness to another pod. To learn more visit
+ https://kubernetes.io/docs/concepts/configuration/assign-pod-node/
+
+ Pass this field an array of "WeightedPodAffinityTerm" objects.*
+ * https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.10/#weightedpodaffinityterm-v1-core
+ pod_affinity_required:
+ Affinities describe where pods prefer or require to be scheduled, they
+ may prefer or require a node to have a certain label or be in proximity
+ / remoteness to another pod. To learn more visit
+ https://kubernetes.io/docs/concepts/configuration/assign-pod-node/
+
+ Pass this field an array of "PodAffinityTerm" objects.*
+ * https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.10/#podaffinityterm-v1-core
+ pod_anti_affinity_preferred:
+ Affinities describe where pods prefer or require to be scheduled, they
+ may prefer or require a node to have a certain label or be in proximity
+ / remoteness to another pod. To learn more visit
+ https://kubernetes.io/docs/concepts/configuration/assign-pod-node/
+
+ Pass this field an array of "WeightedPodAffinityTerm" objects.*
+ * https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.10/#weightedpodaffinityterm-v1-core
+ pod_anti_affinity_required:
+ Affinities describe where pods prefer or require to be scheduled, they
+ may prefer or require a node to have a certain label or be in proximity
+ / remoteness to another pod. To learn more visit
+ https://kubernetes.io/docs/concepts/configuration/assign-pod-node/
+
+ Pass this field an array of "PodAffinityTerm" objects.*
+ * https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.10/#podaffinityterm-v1-core
priority_class_name:
The name of the PriorityClass to be assigned the pod. This feature is Beta available in K8s 1.11.
"""
@@ -260,8 +317,63 @@ def make_pod(
if scheduler_name:
pod.spec.scheduler_name = scheduler_name
+ node_affinity = None
+ if node_affinity_preferred or node_affinity_required:
+ node_selector = None
+ if node_affinity_required:
+ node_selector = V1NodeSelector(
+ node_selector_terms=[get_k8s_model(V1NodeSelectorTerm, obj) for obj in node_affinity_required],
+ )
+
+ preferred_scheduling_terms = None
+ if node_affinity_preferred:
+ preferred_scheduling_terms = [get_k8s_model(V1PreferredSchedulingTerm, obj) for obj in node_affinity_preferred]
+
+ node_affinity = V1NodeAffinity(
+ preferred_during_scheduling_ignored_during_execution=preferred_scheduling_terms,
+ required_during_scheduling_ignored_during_execution=node_selector,
+ )
+
+ pod_affinity = None
+ if pod_affinity_preferred or pod_affinity_required:
+ weighted_pod_affinity_terms = None
+ if pod_affinity_preferred:
+ weighted_pod_affinity_terms = [get_k8s_model(V1WeightedPodAffinityTerm, obj) for obj in pod_affinity_preferred]
+
+ pod_affinity_terms = None
+ if pod_affinity_required:
+ pod_affinity_terms = [get_k8s_model(V1PodAffinityTerm, obj) for obj in pod_affinity_required]
+ pod_affinity = V1PodAffinity(
+ preferred_during_scheduling_ignored_during_execution=weighted_pod_affinity_terms,
+ required_during_scheduling_ignored_during_execution=pod_affinity_terms,
+ )
+
+ pod_anti_affinity = None
+ if pod_anti_affinity_preferred or pod_anti_affinity_required:
+ weighted_pod_affinity_terms = None
+ if pod_anti_affinity_preferred:
+ weighted_pod_affinity_terms = [get_k8s_model(V1WeightedPodAffinityTerm, obj) for obj in pod_anti_affinity_preferred]
+
+ pod_affinity_terms = None
+ if pod_anti_affinity_required:
+ pod_affinity_terms = [get_k8s_model(V1PodAffinityTerm, obj) for obj in pod_anti_affinity_required]
+
+ pod_anti_affinity = V1PodAffinity(
+ preferred_during_scheduling_ignored_during_execution=weighted_pod_affinity_terms,
+ required_during_scheduling_ignored_during_execution=pod_affinity_terms,
+ )
+
+ affinity = None
+ if (node_affinity or pod_affinity or pod_anti_affinity):
+ affinity = V1Affinity(
+ node_affinity=node_affinity,
+ pod_affinity=pod_affinity,
+ pod_anti_affinity=pod_anti_affinity,
+ )
+ if affinity:
+ pod.spec.affinity = affinity
if priority_class_name:
pod.spec.priority_class_name = priority_class_name
diff --git a/kubespawner/spawner.py b/kubespawner/spawner.py
index fb7deaa..39adce9 100644
--- a/kubespawner/spawner.py
+++ b/kubespawner/spawner.py
@@ -900,6 +900,79 @@ class KubeSpawner(Spawner):
"""
)
+ node_affinity_preferred = List(
+ config=True,
+ help="""
+ Affinities describe where pods prefer or require to be scheduled, they
+ may prefer or require a node to have a certain label or be in proximity
+ / remoteness to another pod. To learn more visit
+ https://kubernetes.io/docs/concepts/configuration/assign-pod-node/
+
+ Pass this field an array of "PreferredSchedulingTerm" objects.*
+ * https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.11/#preferredschedulingterm-v1-core
+ """
+ )
+ node_affinity_required = List(
+ config=True,
+ help="""
+ Affinities describe where pods prefer or require to be scheduled, they
+ may prefer or require a node to have a certain label or be in proximity
+ / remoteness to another pod. To learn more visit
+ https://kubernetes.io/docs/concepts/configuration/assign-pod-node/
+
+ Pass this field an array of "NodeSelectorTerm" objects.*
+ * https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.11/#nodeselectorterm-v1-core
+ """
+ )
+ pod_affinity_preferred = List(
+ config=True,
+ help="""
+ Affinities describe where pods prefer or require to be scheduled, they
+ may prefer or require a node to have a certain label or be in proximity
+ / remoteness to another pod. To learn more visit
+ https://kubernetes.io/docs/concepts/configuration/assign-pod-node/
+
+ Pass this field an array of "WeightedPodAffinityTerm" objects.*
+ * https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.11/#weightedpodaffinityterm-v1-core
+ """
+ )
+ pod_affinity_required = List(
+ config=True,
+ help="""
+ Affinities describe where pods prefer or require to be scheduled, they
+ may prefer or require a node to have a certain label or be in proximity
+ / remoteness to another pod. To learn more visit
+ https://kubernetes.io/docs/concepts/configuration/assign-pod-node/
+
+ Pass this field an array of "PodAffinityTerm" objects.*
+ * https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.11/#podaffinityterm-v1-core
+ """
+ )
+ pod_anti_affinity_preferred = List(
+ config=True,
+ help="""
+ Affinities describe where pods prefer or require to be scheduled, they
+ may prefer or require a node to have a certain label or be in proximity
+ / remoteness to another pod. To learn more visit
+ https://kubernetes.io/docs/concepts/configuration/assign-pod-node/
+
+ Pass this field an array of "WeightedPodAffinityTerm" objects.*
+ * https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.11/#weightedpodaffinityterm-v1-core
+ """
+ )
+ pod_anti_affinity_required = List(
+ config=True,
+ help="""
+ Affinities describe where pods prefer or require to be scheduled, they
+ may prefer or require a node to have a certain label or be in proximity
+ / remoteness to another pod. To learn more visit
+ https://kubernetes.io/docs/concepts/configuration/assign-pod-node/
+
+ Pass this field an array of "PodAffinityTerm" objects.*
+ * https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.11/#podaffinityterm-v1-core
+ """
+ )
+
extra_resource_guarantees = Dict(
config=True,
help="""
@@ -1286,6 +1359,12 @@ class KubeSpawner(Spawner):
extra_containers=self.extra_containers,
scheduler_name=self.scheduler_name,
tolerations=self.tolerations,
+ node_affinity_preferred=self.node_affinity_preferred,
+ node_affinity_required=self.node_affinity_required,
+ pod_affinity_preferred=self.pod_affinity_preferred,
+ pod_affinity_required=self.pod_affinity_required,
+ pod_anti_affinity_preferred=self.pod_anti_affinity_preferred,
+ pod_anti_affinity_required=self.pod_anti_affinity_required,
priority_class_name=self.priority_class_name,
logger=self.log,
)
|
jupyterhub/kubespawner
|
99ef3b46c277e78da5c9f18ab581b0adce83f453
|
diff --git a/tests/test_objects.py b/tests/test_objects.py
index 53bcef9..5cb5326 100644
--- a/tests/test_objects.py
+++ b/tests/test_objects.py
@@ -1075,6 +1075,371 @@ def test_make_pod_with_tolerations():
}
+def test_make_pod_with_node_affinity_preferred():
+ """
+ Test specification of the simplest possible pod specification with non-empty node_affinity_preferred
+ """
+ node_affinity_preferred = [{
+ "weight": 1,
+ "preference": {
+ "matchExpressions": [{
+ "key": "hub.jupyter.org/node-purpose",
+ "operator": "In",
+ "values": ["user"],
+ }],
+ }
+ }]
+ assert api_client.sanitize_for_serialization(make_pod(
+ name='test',
+ image_spec='jupyter/singleuser:latest',
+ cmd=['jupyterhub-singleuser'],
+ port=8888,
+ image_pull_policy='IfNotPresent',
+ node_affinity_preferred=node_affinity_preferred
+ )) == {
+ "metadata": {
+ "name": "test",
+ "labels": {},
+ "annotations": {}
+ },
+ "spec": {
+ "automountServiceAccountToken": False,
+ "securityContext": {},
+ "containers": [
+ {
+ "env": [],
+ "name": "notebook",
+ "image": "jupyter/singleuser:latest",
+ "imagePullPolicy": "IfNotPresent",
+ "args": ["jupyterhub-singleuser"],
+ "ports": [{
+ "name": "notebook-port",
+ "containerPort": 8888
+ }],
+ 'volumeMounts': [],
+ "resources": {
+ "limits": {},
+ "requests": {}
+ }
+ }
+ ],
+ "volumes": [],
+ "affinity": {
+ "nodeAffinity": {
+ "preferredDuringSchedulingIgnoredDuringExecution": node_affinity_preferred
+ }
+ }
+ },
+ "kind": "Pod",
+ "apiVersion": "v1"
+ }
+
+
+def test_make_pod_with_node_affinity_required():
+ """
+ Test specification of the simplest possible pod specification with non-empty node_affinity_required
+ """
+ node_affinity_required = [{
+ "matchExpressions": [{
+ "key": "hub.jupyter.org/node-purpose",
+ "operator": "In",
+ "values": ["user"],
+ }]
+ }]
+ assert api_client.sanitize_for_serialization(make_pod(
+ name='test',
+ image_spec='jupyter/singleuser:latest',
+ cmd=['jupyterhub-singleuser'],
+ port=8888,
+ image_pull_policy='IfNotPresent',
+ node_affinity_required=node_affinity_required
+ )) == {
+ "metadata": {
+ "name": "test",
+ "labels": {},
+ "annotations": {}
+ },
+ "spec": {
+ "automountServiceAccountToken": False,
+ "securityContext": {},
+ "containers": [
+ {
+ "env": [],
+ "name": "notebook",
+ "image": "jupyter/singleuser:latest",
+ "imagePullPolicy": "IfNotPresent",
+ "args": ["jupyterhub-singleuser"],
+ "ports": [{
+ "name": "notebook-port",
+ "containerPort": 8888
+ }],
+ 'volumeMounts': [],
+ "resources": {
+ "limits": {},
+ "requests": {}
+ }
+ }
+ ],
+ "volumes": [],
+ "affinity": {
+ "nodeAffinity": {
+ "requiredDuringSchedulingIgnoredDuringExecution": {
+ "nodeSelectorTerms": node_affinity_required
+ }
+ }
+ }
+ },
+ "kind": "Pod",
+ "apiVersion": "v1"
+ }
+
+
+def test_make_pod_with_pod_affinity_preferred():
+ """
+ Test specification of the simplest possible pod specification with non-empty pod_affinity_preferred
+ """
+ pod_affinity_preferred = [{
+ "weight": 100,
+ "podAffinityTerm": {
+ "labelSelector": {
+ "matchExpressions": [{
+ "key": "hub.jupyter.org/pod-kind",
+ "operator": "In",
+ "values": ["user"],
+ }]
+ },
+ "topologyKey": "kubernetes.io/hostname"
+ }
+ }]
+ assert api_client.sanitize_for_serialization(make_pod(
+ name='test',
+ image_spec='jupyter/singleuser:latest',
+ cmd=['jupyterhub-singleuser'],
+ port=8888,
+ image_pull_policy='IfNotPresent',
+ pod_affinity_preferred=pod_affinity_preferred
+ )) == {
+ "metadata": {
+ "name": "test",
+ "labels": {},
+ "annotations": {}
+ },
+ "spec": {
+ "automountServiceAccountToken": False,
+ "securityContext": {},
+ "containers": [
+ {
+ "env": [],
+ "name": "notebook",
+ "image": "jupyter/singleuser:latest",
+ "imagePullPolicy": "IfNotPresent",
+ "args": ["jupyterhub-singleuser"],
+ "ports": [{
+ "name": "notebook-port",
+ "containerPort": 8888
+ }],
+ 'volumeMounts': [],
+ "resources": {
+ "limits": {},
+ "requests": {}
+ }
+ }
+ ],
+ "volumes": [],
+ "affinity": {
+ "podAffinity": {
+ "preferredDuringSchedulingIgnoredDuringExecution": pod_affinity_preferred
+ }
+ }
+ },
+ "kind": "Pod",
+ "apiVersion": "v1"
+ }
+
+
+def test_make_pod_with_pod_affinity_required():
+ """
+ Test specification of the simplest possible pod specification with non-empty pod_affinity_required
+ """
+ pod_affinity_required = [{
+ "labelSelector": {
+ "matchExpressions": [{
+ "key": "security",
+ "operator": "In",
+ "values": ["S1"],
+ }]
+ },
+ "topologyKey": "failure-domain.beta.kubernetes.io/zone"
+ }]
+ assert api_client.sanitize_for_serialization(make_pod(
+ name='test',
+ image_spec='jupyter/singleuser:latest',
+ cmd=['jupyterhub-singleuser'],
+ port=8888,
+ image_pull_policy='IfNotPresent',
+ pod_affinity_required=pod_affinity_required
+ )) == {
+ "metadata": {
+ "name": "test",
+ "labels": {},
+ "annotations": {}
+ },
+ "spec": {
+ "automountServiceAccountToken": False,
+ "securityContext": {},
+ "containers": [
+ {
+ "env": [],
+ "name": "notebook",
+ "image": "jupyter/singleuser:latest",
+ "imagePullPolicy": "IfNotPresent",
+ "args": ["jupyterhub-singleuser"],
+ "ports": [{
+ "name": "notebook-port",
+ "containerPort": 8888
+ }],
+ 'volumeMounts': [],
+ "resources": {
+ "limits": {},
+ "requests": {}
+ }
+ }
+ ],
+ "volumes": [],
+ "affinity": {
+ "podAffinity": {
+ "requiredDuringSchedulingIgnoredDuringExecution": pod_affinity_required
+ }
+ }
+ },
+ "kind": "Pod",
+ "apiVersion": "v1"
+ }
+
+
+def test_make_pod_with_pod_anti_affinity_preferred():
+ """
+ Test specification of the simplest possible pod specification with non-empty pod_anti_affinity_preferred
+ """
+ pod_anti_affinity_preferred = [{
+ "weight": 100,
+ "podAffinityTerm": {
+ "labelSelector": {
+ "matchExpressions": [{
+ "key": "hub.jupyter.org/pod-kind",
+ "operator": "In",
+ "values": ["user"],
+ }]
+ },
+ "topologyKey": "kubernetes.io/hostname"
+ }
+ }]
+ assert api_client.sanitize_for_serialization(make_pod(
+ name='test',
+ image_spec='jupyter/singleuser:latest',
+ cmd=['jupyterhub-singleuser'],
+ port=8888,
+ image_pull_policy='IfNotPresent',
+ pod_anti_affinity_preferred=pod_anti_affinity_preferred
+ )) == {
+ "metadata": {
+ "name": "test",
+ "labels": {},
+ "annotations": {}
+ },
+ "spec": {
+ "automountServiceAccountToken": False,
+ "securityContext": {},
+ "containers": [
+ {
+ "env": [],
+ "name": "notebook",
+ "image": "jupyter/singleuser:latest",
+ "imagePullPolicy": "IfNotPresent",
+ "args": ["jupyterhub-singleuser"],
+ "ports": [{
+ "name": "notebook-port",
+ "containerPort": 8888
+ }],
+ 'volumeMounts': [],
+ "resources": {
+ "limits": {},
+ "requests": {}
+ }
+ }
+ ],
+ "volumes": [],
+ "affinity": {
+ "podAntiAffinity": {
+ "preferredDuringSchedulingIgnoredDuringExecution": pod_anti_affinity_preferred
+ }
+ }
+ },
+ "kind": "Pod",
+ "apiVersion": "v1"
+ }
+
+
+def test_make_pod_with_pod_anti_affinity_required():
+ """
+ Test specification of the simplest possible pod specification with non-empty pod_anti_affinity_required
+ """
+ pod_anti_affinity_required = [{
+ "labelSelector": {
+ "matchExpressions": [{
+ "key": "security",
+ "operator": "In",
+ "values": ["S1"],
+ }]
+ },
+ "topologyKey": "failure-domain.beta.kubernetes.io/zone"
+ }]
+ assert api_client.sanitize_for_serialization(make_pod(
+ name='test',
+ image_spec='jupyter/singleuser:latest',
+ cmd=['jupyterhub-singleuser'],
+ port=8888,
+ image_pull_policy='IfNotPresent',
+ pod_anti_affinity_required=pod_anti_affinity_required
+ )) == {
+ "metadata": {
+ "name": "test",
+ "labels": {},
+ "annotations": {}
+ },
+ "spec": {
+ "automountServiceAccountToken": False,
+ "securityContext": {},
+ "containers": [
+ {
+ "env": [],
+ "name": "notebook",
+ "image": "jupyter/singleuser:latest",
+ "imagePullPolicy": "IfNotPresent",
+ "args": ["jupyterhub-singleuser"],
+ "ports": [{
+ "name": "notebook-port",
+ "containerPort": 8888
+ }],
+ 'volumeMounts': [],
+ "resources": {
+ "limits": {},
+ "requests": {}
+ }
+ }
+ ],
+ "volumes": [],
+ "affinity": {
+ "podAntiAffinity": {
+ "requiredDuringSchedulingIgnoredDuringExecution": pod_anti_affinity_required
+ }
+ }
+ },
+ "kind": "Pod",
+ "apiVersion": "v1"
+ }
+
+
def test_make_pod_with_priority_class_name():
"""
Test specification of the simplest possible pod specification with non-default priorityClassName set
|
Support setting affinity items
We should support setting nodeAffinity, podAffinity, podAntiAffinity, and preferred/required for each.
```yaml
affinity:
nodeAffinity:
requiredDuringSchedulingIgnoredDuringExecution: # nodeSelector
nodeSelectorTerms: #
# logical AND of the items below
- matchExpressions:
# local OR of the items below
- key: kubernetes.io/e2e-az-name
operator: In
values:
- e2e-az1
- e2e-az2
preferredDuringSchedulingIgnoredDuringExecution:
# fullfilled weights summed over and compared in between nodes
- weight: 1
preference:
matchExpressions:
# local OR of the items below
- key: another-node-label-key
operator: In
values:
- another-node-label-value
podAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
# logical AND of the items below
- labelSelector:
matchExpressions:
# logical OR of the items below
- key: security
operator: In
values:
- S1
topologyKey: failure-domain.beta.kubernetes.io/zone
preferredDuringSchedulingIgnoredDuringExecution:
# sum the weights for each node and compare
- weight: 100
podAffinityTerm:
labelSelector:
matchExpressions:
- key: security
operator: In
values:
- S2
topologyKey: kubernetes.io/hostname
# Exactly the same fields etc as podAffinity
podAntiAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchExpressions:
- key: app
operator: In
values:
- store
topologyKey: "kubernetes.io/hostname"
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 100
podAffinityTerm:
labelSelector:
matchExpressions:
- key: security
operator: In
values:
- S2
topologyKey: kubernetes.io/hostname
```
|
0.0
|
99ef3b46c277e78da5c9f18ab581b0adce83f453
|
[
"tests/test_objects.py::test_make_pod_with_node_affinity_preferred",
"tests/test_objects.py::test_make_pod_with_node_affinity_required",
"tests/test_objects.py::test_make_pod_with_pod_affinity_preferred",
"tests/test_objects.py::test_make_pod_with_pod_affinity_required",
"tests/test_objects.py::test_make_pod_with_pod_anti_affinity_preferred",
"tests/test_objects.py::test_make_pod_with_pod_anti_affinity_required"
] |
[
"tests/test_objects.py::test_make_simplest_pod",
"tests/test_objects.py::test_make_labeled_pod",
"tests/test_objects.py::test_make_annotated_pod",
"tests/test_objects.py::test_make_pod_with_image_pull_secrets",
"tests/test_objects.py::test_set_pod_uid_and_gid",
"tests/test_objects.py::test_set_pod_uid_fs_gid",
"tests/test_objects.py::test_set_pod_supplemental_gids",
"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_pod_with_extra_resources",
"tests/test_objects.py::test_make_pvc_simple",
"tests/test_objects.py::test_make_resources_all",
"tests/test_objects.py::test_make_pod_with_service_account",
"tests/test_objects.py::test_make_pod_with_scheduler_name",
"tests/test_objects.py::test_make_pod_with_tolerations",
"tests/test_objects.py::test_make_pod_with_priority_class_name"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-08-10 18:26:21+00:00
|
bsd-3-clause
| 3,368 |
|
jupyterhub__kubespawner-34
|
diff --git a/kubespawner/objects.py b/kubespawner/objects.py
index 0d35428..0564574 100644
--- a/kubespawner/objects.py
+++ b/kubespawner/objects.py
@@ -6,6 +6,8 @@ def make_pod_spec(
image_spec,
image_pull_policy,
image_pull_secret,
+ port,
+ cmd,
run_as_uid,
fs_gid,
env,
@@ -34,6 +36,10 @@ def make_pod_spec(
- image_pull_secret:
Image pull secret - Default is None -- set to your secret name to pull
from private docker registry.
+ - port:
+ Port the notebook server is going to be listening on
+ - cmd:
+ The command used to execute the singleuser server.
- run_as_uid:
The UID used to run single-user pods. The default is to run as the user
specified in the Dockerfile, if this is set to None.
@@ -87,9 +93,10 @@ def make_pod_spec(
{
'name': 'notebook',
'image': image_spec,
+ 'command': cmd,
'imagePullPolicy': image_pull_policy,
'ports': [{
- 'containerPort': 8888,
+ 'containerPort': port,
}],
'resources': {
'requests': {
diff --git a/kubespawner/spawner.py b/kubespawner/spawner.py
index a4e1919..d36f635 100644
--- a/kubespawner/spawner.py
+++ b/kubespawner/spawner.py
@@ -10,7 +10,7 @@ import string
from urllib.parse import urlparse, urlunparse
from tornado import gen
-from tornado.curl_httpclient import CurlAsyncHTTPClient
+from tornado.httpclient import AsyncHTTPClient
from tornado.httpclient import HTTPError
from traitlets import Unicode, List, Integer, Union
from jupyterhub.spawner import Spawner
@@ -28,8 +28,13 @@ class KubeSpawner(Spawner):
super().__init__(*args, **kwargs)
# By now, all the traitlets have been set, so we can use them to compute
# other attributes
- # FIXME: Make this param tuneable?
- self.httpclient = CurlAsyncHTTPClient(max_clients=64)
+ # Use curl HTTPClient if available, else fall back to Simple one
+ try:
+ from tornado.curl_httpclient import CurlAsyncHTTPClient
+ self.httpclient = CurlAsyncHTTPClient(max_clients=64)
+ except ImportError:
+ from tornado.simple_httpclient import SimpleAsyncHTTPClient
+ self.httpclient = SimpleAsyncHTTPClient(max_clients=64)
# FIXME: Support more than just kubeconfig
self.request = request_maker()
self.pod_name = self._expand_user_properties(self.pod_name_template)
@@ -44,6 +49,10 @@ class KubeSpawner(Spawner):
else:
self.accessible_hub_api_url = self.hub.api_url
+ if self.port == 0:
+ # Our default port is 8888
+ self.port = 8888
+
namespace = Unicode(
config=True,
help="""
@@ -67,6 +76,15 @@ class KubeSpawner(Spawner):
return f.read().strip()
return 'default'
+ ip = Unicode('0.0.0.0',
+ help="""
+ The IP address (or hostname) the single-user server should listen on.
+
+ We override this from the parent so we can set a more sane default for
+ the Kubernetes setup.
+ """
+ ).tag(config=True)
+
pod_name_template = Unicode(
'jupyter-{username}-{userid}',
config=True,
@@ -428,6 +446,8 @@ class KubeSpawner(Spawner):
self.singleuser_image_spec,
self.singleuser_image_pull_policy,
self.singleuser_image_pull_secrets,
+ self.port,
+ self.cmd + self.get_args(),
singleuser_uid,
singleuser_fs_gid,
self.get_env(),
@@ -576,9 +596,11 @@ class KubeSpawner(Spawner):
except HTTPError as e:
if e.code != 409:
# We only want to handle 409 conflict errors
+ self.log.exception("Failed for %s", json.dumps(pod_manifest))
raise
self.log.info('Found existing pod %s, attempting to kill', self.pod_name)
yield self.stop(True)
+
self.log.info('Killed pod %s, will try starting singleuser pod again', self.pod_name)
else:
raise Exception(
@@ -589,7 +611,7 @@ class KubeSpawner(Spawner):
if data is not None and self.is_pod_running(data):
break
yield gen.sleep(1)
- return (data['status']['podIP'], 8888)
+ return (data['status']['podIP'], self.port)
@gen.coroutine
def stop(self, now=False):
@@ -621,13 +643,19 @@ class KubeSpawner(Spawner):
def _env_keep_default(self):
return []
- def get_env(self):
- env = super(KubeSpawner, self).get_env()
- env.update({
- 'JPY_USER': self.user.name,
- 'JPY_COOKIE_NAME': self.user.server.cookie_name,
- 'JPY_BASE_URL': self.user.server.base_url,
- 'JPY_HUB_PREFIX': self.hub.server.base_url,
- 'JPY_HUB_API_URL': self.accessible_hub_api_url
- })
- return env
+ def get_args(self):
+ args = super(KubeSpawner, self).get_args()
+
+ # HACK: we wanna replace --hub-api-url=self.hub.api_url with
+ # self.accessible_hub_api_url. This is required in situations where
+ # the IP the hub is listening on (such as 0.0.0.0) is not the IP where
+ # it can be reached by the pods (such as the service IP used for the hub!)
+ # FIXME: Make this better?
+ print(args)
+ to_replace = '--hub-api-url="%s"' % (self.hub.api_url)
+ print(to_replace)
+ for i in range(len(args)):
+ if args[i] == to_replace:
+ args[i] = '--hub-api-url="%s"' % (self.accessible_hub_api_url)
+ break
+ return args
|
jupyterhub/kubespawner
|
dc41368f61d9916fa2972b6c0a944fc2a0a66b01
|
diff --git a/tests/test_objects.py b/tests/test_objects.py
index 4b09347..d8028a5 100644
--- a/tests/test_objects.py
+++ b/tests/test_objects.py
@@ -14,6 +14,8 @@ def test_make_simplest_pod():
env={},
volumes=[],
volume_mounts=[],
+ cmd=['jupyterhub-singleuser'],
+ port=8888,
cpu_limit=None,
cpu_guarantee=None,
mem_limit=None,
@@ -35,6 +37,7 @@ def test_make_simplest_pod():
"name": "notebook",
"image": "jupyter/singleuser:latest",
"imagePullPolicy": "IfNotPresent",
+ "command": ["jupyterhub-singleuser"],
"ports": [{
"containerPort": 8888
}],
@@ -68,6 +71,8 @@ def test_make_pod_with_image_pull_secrets():
env={},
volumes=[],
volume_mounts=[],
+ cmd=['jupyterhub-singleuser'],
+ port=8888,
cpu_limit=None,
cpu_guarantee=None,
mem_limit=None,
@@ -91,6 +96,7 @@ def test_make_pod_with_image_pull_secrets():
"name": "notebook",
"image": "jupyter/singleuser:latest",
"imagePullPolicy": "IfNotPresent",
+ "command": ["jupyterhub-singleuser"],
"ports": [{
"containerPort": 8888
}],
@@ -124,6 +130,8 @@ def test_set_pod_uid_fs_gid():
env={},
volumes=[],
volume_mounts=[],
+ cmd=['jupyterhub-singleuser'],
+ port=8888,
cpu_limit=None,
cpu_guarantee=None,
mem_limit=None,
@@ -148,6 +156,7 @@ def test_set_pod_uid_fs_gid():
"name": "notebook",
"image": "jupyter/singleuser:latest",
"imagePullPolicy": "IfNotPresent",
+ "command": ["jupyterhub-singleuser"],
"ports": [{
"containerPort": 8888
}],
@@ -183,6 +192,8 @@ def test_make_pod_resources_all():
volume_mounts=[],
cpu_limit=2,
cpu_guarantee=1,
+ cmd=['jupyterhub-singleuser'],
+ port=8888,
mem_limit='1Gi',
mem_guarantee='512Mi',
image_pull_policy='IfNotPresent',
@@ -202,6 +213,7 @@ def test_make_pod_resources_all():
"name": "notebook",
"image": "jupyter/singleuser:latest",
"imagePullPolicy": "IfNotPresent",
+ "command": ["jupyterhub-singleuser"],
"ports": [{
"containerPort": 8888
}],
@@ -237,6 +249,8 @@ def test_make_pod_with_env():
},
volumes=[],
volume_mounts=[],
+ cmd=['jupyterhub-singleuser'],
+ port=8888,
cpu_limit=None,
cpu_guarantee=None,
mem_limit=None,
@@ -258,6 +272,7 @@ def test_make_pod_with_env():
"name": "notebook",
"image": "jupyter/singleuser:latest",
"imagePullPolicy": "IfNotPresent",
+ "command": ["jupyterhub-singleuser"],
"ports": [{
"containerPort": 8888
}],
|
Specify container command
Is it possible to specify the container command via config? To use the docker stacks, command must be set to `/usr/local/bin/singleuser.sh`, but I can't see how to do it here. In DockerSpawner, it's passed to `docker.create`
|
0.0
|
dc41368f61d9916fa2972b6c0a944fc2a0a66b01
|
[
"tests/test_objects.py::test_make_simplest_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_make_pod_resources_all",
"tests/test_objects.py::test_make_pod_with_env"
] |
[
"tests/test_objects.py::test_make_pvc_simple",
"tests/test_objects.py::test_make_resources_all"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2017-03-19 01:06:56+00:00
|
bsd-3-clause
| 3,369 |
|
jupyterhub__kubespawner-38
|
diff --git a/kubespawner/objects.py b/kubespawner/objects.py
index c75e80c..16509e4 100644
--- a/kubespawner/objects.py
+++ b/kubespawner/objects.py
@@ -97,7 +97,7 @@ def make_pod_spec(
{
'name': 'notebook',
'image': image_spec,
- 'command': cmd,
+ 'args': cmd,
'imagePullPolicy': image_pull_policy,
'ports': [{
'containerPort': port,
|
jupyterhub/kubespawner
|
477b322b3bebd6d668185912c633eac2c1fee5dd
|
diff --git a/tests/test_objects.py b/tests/test_objects.py
index 11f2a55..a32a72b 100644
--- a/tests/test_objects.py
+++ b/tests/test_objects.py
@@ -39,7 +39,7 @@ def test_make_simplest_pod():
"name": "notebook",
"image": "jupyter/singleuser:latest",
"imagePullPolicy": "IfNotPresent",
- "command": ["jupyterhub-singleuser"],
+ "args": ["jupyterhub-singleuser"],
"ports": [{
"containerPort": 8888
}],
@@ -97,7 +97,7 @@ def test_make_labeled_pod():
"name": "notebook",
"image": "jupyter/singleuser:latest",
"imagePullPolicy": "IfNotPresent",
- "command": ["jupyterhub-singleuser"],
+ "args": ["jupyterhub-singleuser"],
"ports": [{
"containerPort": 8888
}],
@@ -157,7 +157,7 @@ def test_make_pod_with_image_pull_secrets():
"name": "notebook",
"image": "jupyter/singleuser:latest",
"imagePullPolicy": "IfNotPresent",
- "command": ["jupyterhub-singleuser"],
+ "args": ["jupyterhub-singleuser"],
"ports": [{
"containerPort": 8888
}],
@@ -219,7 +219,7 @@ def test_set_pod_uid_fs_gid():
"name": "notebook",
"image": "jupyter/singleuser:latest",
"imagePullPolicy": "IfNotPresent",
- "command": ["jupyterhub-singleuser"],
+ "args": ["jupyterhub-singleuser"],
"ports": [{
"containerPort": 8888
}],
@@ -278,7 +278,7 @@ def test_make_pod_resources_all():
"name": "notebook",
"image": "jupyter/singleuser:latest",
"imagePullPolicy": "IfNotPresent",
- "command": ["jupyterhub-singleuser"],
+ "args": ["jupyterhub-singleuser"],
"ports": [{
"containerPort": 8888
}],
@@ -339,7 +339,7 @@ def test_make_pod_with_env():
"name": "notebook",
"image": "jupyter/singleuser:latest",
"imagePullPolicy": "IfNotPresent",
- "command": ["jupyterhub-singleuser"],
+ "args": ["jupyterhub-singleuser"],
"ports": [{
"containerPort": 8888
}],
|
Specify container command
Is it possible to specify the container command via config? To use the docker stacks, command must be set to `/usr/local/bin/singleuser.sh`, but I can't see how to do it here. In DockerSpawner, it's passed to `docker.create`
|
0.0
|
477b322b3bebd6d668185912c633eac2c1fee5dd
|
[
"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_make_pod_resources_all",
"tests/test_objects.py::test_make_pod_with_env"
] |
[
"tests/test_objects.py::test_make_pvc_simple",
"tests/test_objects.py::test_make_resources_all"
] |
{
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false
}
|
2017-03-27 11:04:31+00:00
|
bsd-3-clause
| 3,370 |
|
jupyterhub__kubespawner-84
|
diff --git a/jupyterhub_config.py b/jupyterhub_config.py
index cce2c68..e59a17d 100644
--- a/jupyterhub_config.py
+++ b/jupyterhub_config.py
@@ -19,6 +19,7 @@ c.KubeSpawner.singleuser_image_spec = 'yuvipanda/simple-singleuser:v1'
# The spawned containers need to be able to talk to the hub through the proxy!
c.KubeSpawner.hub_connect_ip = os.environ['HUB_CONNECT_IP']
+c.KubeSpawner.singleuser_service_account = 'default'
# Do not use any authentication at all - any username / password will work.
c.JupyterHub.authenticator_class = 'dummyauthenticator.DummyAuthenticator'
diff --git a/kubespawner/objects.py b/kubespawner/objects.py
index 36ea5da..3848f2e 100644
--- a/kubespawner/objects.py
+++ b/kubespawner/objects.py
@@ -7,6 +7,8 @@ from kubernetes.client.models.v1_pod_spec import V1PodSpec
from kubernetes.client.models.v1_object_meta import V1ObjectMeta
from kubernetes.client.models.v1_pod_security_context import V1PodSecurityContext
from kubernetes.client.models.v1_local_object_reference import V1LocalObjectReference
+from kubernetes.client.models.v1_volume import V1Volume
+from kubernetes.client.models.v1_volume_mount import V1VolumeMount
from kubernetes.client.models.v1_container import V1Container
from kubernetes.client.models.v1_security_context import V1SecurityContext
@@ -40,6 +42,7 @@ def make_pod(
mem_guarantee,
lifecycle_hooks,
init_containers,
+ service_account,
):
"""
Make a k8s pod specification for running a user notebook.
@@ -106,6 +109,8 @@ def make_pod(
Dictionary of lifecycle hooks
- init_containers:
List of initialization containers belonging to the pod.
+ - service_account:
+ Service account to mount on the pod. None disables mounting
"""
pod = V1Pod()
@@ -150,6 +155,28 @@ def make_pod(
notebook_container.lifecycle = lifecycle_hooks
notebook_container.resources = V1ResourceRequirements()
+ if service_account is None:
+ # Add a hack to ensure that no service accounts are mounted in spawned pods
+ # This makes sure that we don"t accidentally give access to the whole
+ # kubernetes API to the users in the spawned pods.
+ # Note: We don't simply use `automountServiceAccountToken` here since we wanna be compatible
+ # with older kubernetes versions too for now.
+ hack_volume = V1Volume()
+ hack_volume.name = "no-api-access-please"
+ hack_volume.empty_dir = {}
+ hack_volumes = [hack_volume]
+
+ hack_volume_mount = V1VolumeMount()
+ hack_volume_mount.name = "no-api-access-please"
+ hack_volume_mount.mount_path = "/var/run/secrets/kubernetes.io/serviceaccount"
+ hack_volume_mount.read_only = True
+ hack_volume_mounts = [hack_volume_mount]
+ else:
+ hack_volumes = []
+ hack_volume_mounts = []
+
+ pod.service_account_name = service_account
+
if run_privileged:
container_security_context = V1SecurityContext()
container_security_context.privileged = True
@@ -167,11 +194,11 @@ def make_pod(
notebook_container.resources.limits['cpu'] = cpu_limit
if mem_limit:
notebook_container.resources.limits['memory'] = mem_limit
- notebook_container.volume_mounts = volume_mounts
+ notebook_container.volume_mounts = volume_mounts + hack_volume_mounts
pod.spec.containers.append(notebook_container)
pod.spec.init_containers = init_containers
- pod.spec.volumes = volumes
+ pod.spec.volumes = volumes + hack_volumes
return pod
diff --git a/kubespawner/spawner.py b/kubespawner/spawner.py
index 24a50e3..19e6c38 100644
--- a/kubespawner/spawner.py
+++ b/kubespawner/spawner.py
@@ -21,8 +21,6 @@ from traitlets.config import SingletonConfigurable
from traitlets import Type, Unicode, List, Integer, Union, Dict, Bool, Any
from jupyterhub.spawner import Spawner
from jupyterhub.traitlets import Command
-from kubernetes.client.models.v1_volume import V1Volume
-from kubernetes.client.models.v1_volume_mount import V1VolumeMount
from kubernetes.client.rest import ApiException
from kubernetes import client
import escapism
@@ -149,6 +147,24 @@ class KubeSpawner(Spawner):
"""
).tag(config=True)
+ singleuser_service_account = Unicode(
+ None,
+ allow_none=True,
+ config=True,
+ help="""
+ The service account to be mounted in the spawned user pod.
+
+ When set to None (the default), no service account is mounted, and the default service account
+ is explicitly disabled.
+
+ This serviceaccount must already exist in the namespace the user pod is being spawned in.
+
+ WARNING: Be careful with this configuration! Make sure the service account being mounted
+ has the minimal permissions needed, and nothing more. When misconfigured, this can easily
+ give arbitrary users root over your entire cluster.
+ """
+ )
+
pod_name_template = Unicode(
'jupyter-{username}',
config=True,
@@ -623,19 +639,6 @@ class KubeSpawner(Spawner):
else:
real_cmd = None
- # Add a hack to ensure that no service accounts are mounted in spawned pods
- # This makes sure that we don"t accidentally give access to the whole
- # kubernetes API to the users in the spawned pods.
- # See https://github.com/kubernetes/kubernetes/issues/16779#issuecomment-157460294
- hack_volume = V1Volume()
- hack_volume.name = "no-api-access-please"
- hack_volume.empty_dir = {}
-
- hack_volume_mount = V1VolumeMount()
- hack_volume_mount.name = "no-api-access-please"
- hack_volume_mount.mount_path = "/var/run/secrets/kubernetes.io/serviceaccount"
- hack_volume_mount.read_only = True
-
# Default set of labels, picked up from
# https://github.com/kubernetes/helm/blob/master/docs/chart_best_practices/labels.md
labels = {
@@ -659,8 +662,8 @@ class KubeSpawner(Spawner):
fs_gid=singleuser_fs_gid,
run_privileged=self.singleuser_privileged,
env=self.get_env(),
- volumes=self._expand_all(self.volumes) + [hack_volume],
- volume_mounts=self._expand_all(self.volume_mounts) + [hack_volume_mount],
+ volumes=self._expand_all(self.volumes),
+ volume_mounts=self._expand_all(self.volume_mounts),
working_dir=self.singleuser_working_dir,
labels=labels,
cpu_limit=self.cpu_limit,
@@ -669,6 +672,7 @@ class KubeSpawner(Spawner):
mem_guarantee=self.mem_guarantee,
lifecycle_hooks=self.singleuser_lifecycle_hooks,
init_containers=self.singleuser_init_containers,
+ service_account=self.singleuser_service_account
)
def get_pvc_manifest(self):
|
jupyterhub/kubespawner
|
ae1c6d6f58a45c2ba4b9e2fa81d50b16503f9874
|
diff --git a/tests/test_objects.py b/tests/test_objects.py
index a95ab56..5994de1 100644
--- a/tests/test_objects.py
+++ b/tests/test_objects.py
@@ -33,6 +33,7 @@ def test_make_simplest_pod():
labels={},
lifecycle_hooks=None,
init_containers=None,
+ service_account=None
)) == {
"metadata": {
"name": "test",
@@ -51,14 +52,14 @@ def test_make_simplest_pod():
"name": "notebook-port",
"containerPort": 8888
}],
- 'volumeMounts': [],
+ 'volumeMounts': [{'name': 'no-api-access-please', 'mountPath': '/var/run/secrets/kubernetes.io/serviceaccount', 'readOnly': True}],
"resources": {
"limits": {},
"requests": {}
}
}
],
- 'volumes': [],
+ 'volumes': [{'name': 'no-api-access-please', 'emptyDir': {}}],
},
"kind": "Pod",
"apiVersion": "v1"
@@ -90,6 +91,7 @@ def test_make_labeled_pod():
labels={"test": "true"},
lifecycle_hooks=None,
init_containers=None,
+ service_account=None
)) == {
"metadata": {
"name": "test",
@@ -108,14 +110,14 @@ def test_make_labeled_pod():
"name": "notebook-port",
"containerPort": 8888
}],
- 'volumeMounts': [],
+ 'volumeMounts': [{'name': 'no-api-access-please', 'mountPath': '/var/run/secrets/kubernetes.io/serviceaccount', 'readOnly': True}],
"resources": {
"limits": {},
"requests": {}
}
}
],
- 'volumes': [],
+ 'volumes': [{'name': 'no-api-access-please', 'emptyDir': {}}],
},
"kind": "Pod",
"apiVersion": "v1"
@@ -147,6 +149,7 @@ def test_make_pod_with_image_pull_secrets():
labels={},
lifecycle_hooks=None,
init_containers=None,
+ service_account=None
)) == {
"metadata": {
"name": "test",
@@ -168,14 +171,14 @@ def test_make_pod_with_image_pull_secrets():
"name": "notebook-port",
"containerPort": 8888
}],
- 'volumeMounts': [],
+ 'volumeMounts': [{'name': 'no-api-access-please', 'mountPath': '/var/run/secrets/kubernetes.io/serviceaccount', 'readOnly': True}],
"resources": {
"limits": {},
"requests": {}
}
}
],
- 'volumes': [],
+ 'volumes': [{'name': 'no-api-access-please', 'emptyDir': {}}],
},
"kind": "Pod",
"apiVersion": "v1"
@@ -208,6 +211,7 @@ def test_set_pod_uid_fs_gid():
labels={},
lifecycle_hooks=None,
init_containers=None,
+ service_account=None
)) == {
"metadata": {
"name": "test",
@@ -229,14 +233,14 @@ def test_set_pod_uid_fs_gid():
"name": "notebook-port",
"containerPort": 8888
}],
- 'volumeMounts': [],
+ 'volumeMounts': [{'name': 'no-api-access-please', 'mountPath': '/var/run/secrets/kubernetes.io/serviceaccount', 'readOnly': True}],
"resources": {
"limits": {},
"requests": {}
}
}
],
- 'volumes': [],
+ 'volumes': [{'name': 'no-api-access-please', 'emptyDir': {}}],
},
"kind": "Pod",
"apiVersion": "v1"
@@ -268,6 +272,7 @@ def test_run_privileged_container():
labels={},
lifecycle_hooks=None,
init_containers=None,
+ service_account=None
)) == {
"metadata": {
"name": "test",
@@ -293,10 +298,10 @@ def test_run_privileged_container():
"securityContext": {
"privileged": True,
},
- "volumeMounts": []
+ 'volumeMounts': [{'name': 'no-api-access-please', 'mountPath': '/var/run/secrets/kubernetes.io/serviceaccount', 'readOnly': True}],
}
],
- 'volumes': [],
+ 'volumes': [{'name': 'no-api-access-please', 'emptyDir': {}}],
},
"kind": "Pod",
"apiVersion": "v1"
@@ -328,6 +333,7 @@ def test_make_pod_resources_all():
labels={},
lifecycle_hooks=None,
init_containers=None,
+ service_account=None
)) == {
"metadata": {
"name": "test",
@@ -348,7 +354,7 @@ def test_make_pod_resources_all():
"name": "notebook-port",
"containerPort": 8888
}],
- 'volumeMounts': [],
+ 'volumeMounts': [{'name': 'no-api-access-please', 'mountPath': '/var/run/secrets/kubernetes.io/serviceaccount', 'readOnly': True}],
"resources": {
"limits": {
"cpu": 2,
@@ -361,7 +367,7 @@ def test_make_pod_resources_all():
}
}
],
- 'volumes': [],
+ 'volumes': [{'name': 'no-api-access-please', 'emptyDir': {}}],
},
"kind": "Pod",
"apiVersion": "v1"
@@ -396,6 +402,7 @@ def test_make_pod_with_env():
labels={},
lifecycle_hooks=None,
init_containers=None,
+ service_account=None
)) == {
"metadata": {
"name": "test",
@@ -414,7 +421,7 @@ def test_make_pod_with_env():
"name": "notebook-port",
"containerPort": 8888
}],
- 'volumeMounts': [],
+ 'volumeMounts': [{'name': 'no-api-access-please', 'mountPath': '/var/run/secrets/kubernetes.io/serviceaccount', 'readOnly': True}],
"resources": {
"limits": {
},
@@ -423,7 +430,7 @@ def test_make_pod_with_env():
}
}
],
- 'volumes': [],
+ 'volumes': [{'name': 'no-api-access-please', 'emptyDir': {}}],
},
"kind": "Pod",
"apiVersion": "v1"
@@ -461,6 +468,7 @@ def test_make_pod_with_lifecycle():
}
},
init_containers=None,
+ service_account=None
)) == {
"metadata": {
"name": "test",
@@ -479,7 +487,7 @@ def test_make_pod_with_lifecycle():
"name": "notebook-port",
"containerPort": 8888
}],
- 'volumeMounts': [],
+ 'volumeMounts': [{'name': 'no-api-access-please', 'mountPath': '/var/run/secrets/kubernetes.io/serviceaccount', 'readOnly': True}],
"resources": {
"limits": {
},
@@ -495,7 +503,7 @@ def test_make_pod_with_lifecycle():
}
}
],
- 'volumes': [],
+ 'volumes': [{'name': 'no-api-access-please', 'emptyDir': {}}],
},
"kind": "Pod",
"apiVersion": "v1"
@@ -539,6 +547,7 @@ def test_make_pod_with_init_containers():
'command': ['sh', '-c', 'until nslookup mydb; do echo waiting for mydb; sleep 2; done;']
}
],
+ service_account=None
)) == {
"metadata": {
"name": "test",
@@ -557,7 +566,7 @@ def test_make_pod_with_init_containers():
"name": "notebook-port",
"containerPort": 8888
}],
- 'volumeMounts': [],
+ 'volumeMounts': [{'name': 'no-api-access-please', 'mountPath': '/var/run/secrets/kubernetes.io/serviceaccount', 'readOnly': True}],
"resources": {
"limits": {
},
@@ -579,7 +588,7 @@ def test_make_pod_with_init_containers():
"command": ["sh", "-c", "until nslookup mydb; do echo waiting for mydb; sleep 2; done;"]
}
],
- 'volumes': [],
+ 'volumes': [{'name': 'no-api-access-please', 'emptyDir': {}}],
},
"kind": "Pod",
"apiVersion": "v1"
|
Add support for setting singleuser service account
Currently we disable all service account mounting from inside the pod.
We should allow people to:
1. Specify that the default serviceaccount needs to be mounted
2. Specify that an arbitrary service account should be created and then mounted.
The default would still be no sa, but would be something you can override. This would be great for people who wanna launch helm charts from inside the notebook.
|
0.0
|
ae1c6d6f58a45c2ba4b9e2fa81d50b16503f9874
|
[
"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_pvc_simple",
"tests/test_objects.py::test_make_resources_all"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2017-09-21 23:51:11+00:00
|
bsd-3-clause
| 3,371 |
|
jupyterhub__ltiauthenticator-43
|
diff --git a/ltiauthenticator/utils.py b/ltiauthenticator/utils.py
new file mode 100644
index 0000000..0f6bfb7
--- /dev/null
+++ b/ltiauthenticator/utils.py
@@ -0,0 +1,41 @@
+from tornado.log import app_log
+from tornado.web import RequestHandler
+
+
+def get_client_protocol(handler: RequestHandler) -> dict:
+ """
+ Gets first protocol from the x-forwarded-proto header that should
+ represent the client's original http/https request.
+
+ Args:
+ handler: a tornado.web.RequestHandler object
+
+ Returns:
+ A decoded dict with keys/values extracted from the request's arguments
+ """
+ if "x-forwarded-proto" in handler.request.headers:
+ hops = [
+ h.strip() for h in handler.request.headers["x-forwarded-proto"].split(",")
+ ]
+ protocol = hops[0]
+ else:
+ protocol = handler.request.protocol
+ app_log.debug("First protocol from x-forwarded-proto list: %s" % protocol)
+ return protocol
+
+
+def convert_request_to_dict(arguments: dict) -> dict:
+ """
+ Converts the arguments obtained from a request to a dict.
+
+ Args:
+ handler: a tornado.web.RequestHandler object
+
+ Returns:
+ A decoded dict with keys/values extracted from the request's arguments
+ """
+ args = {}
+ for k, values in arguments.items():
+ args[k] = values[0].decode()
+ app_log.debug("Request converted to dict: %s" % args)
+ return args
diff --git a/setup.py b/setup.py
index 4977b7d..92bb924 100644
--- a/setup.py
+++ b/setup.py
@@ -30,7 +30,7 @@ setup(
license="3 Clause BSD",
packages=find_packages(exclude="./tests"),
python_requires=">=3.6",
- install_requires=["jupyterhub>=0.8", "oauthlib>=3.1"],
+ install_requires=["jupyterhub>=0.8", "oauthlib>=3.1", "escapism>=1.0"],
package_data={
"": ["*.html"],
}, # noqa: E231
|
jupyterhub/ltiauthenticator
|
214840aedd3c59b41c14599331973c25ff1ac4f5
|
diff --git a/tests/test_utils.py b/tests/test_utils.py
new file mode 100644
index 0000000..4bfe494
--- /dev/null
+++ b/tests/test_utils.py
@@ -0,0 +1,42 @@
+from unittest.mock import Mock
+
+from tornado.web import RequestHandler
+
+from ltiauthenticator.utils import convert_request_to_dict
+from ltiauthenticator.utils import get_client_protocol
+
+
+def test_get_protocol_with_more_than_one_value():
+ """
+ Assert that the first (left-most) protocol value is correctly fetched from the x-forwarded-header.
+ """
+ handler = Mock(
+ spec=RequestHandler,
+ request=Mock(
+ headers={"x-forwarded-proto": "https,http,http"},
+ protocol="https",
+ ),
+ )
+ expected = "https"
+ protocol = get_client_protocol(handler)
+
+ assert expected == protocol
+
+
+def test_convert_request_arguments_with_encoded_items_to_dict():
+ """
+ Assert that a dict of k/v's is correctly created when receiving encoded values.
+ """
+ arguments = {
+ "key1": [b"value1"],
+ "key2": [b"value2"],
+ "key3": [b"value3"],
+ }
+ expected = {
+ "key1": "value1",
+ "key2": "value2",
+ "key3": "value3",
+ }
+ result = convert_request_to_dict(arguments)
+
+ assert expected == result
|
Update package with common utility functions
The LTI 1.1 and LTI 1.3 code (primarily the authenticators and the validators) have some common functions. Refactor the code so that these common tasks are encapsulated in functions to make them easier to document, test, and re-use.
Related to #38
|
0.0
|
214840aedd3c59b41c14599331973c25ff1ac4f5
|
[
"tests/test_utils.py::test_get_protocol_with_more_than_one_value",
"tests/test_utils.py::test_convert_request_arguments_with_encoded_items_to_dict"
] |
[] |
{
"failed_lite_validators": [
"has_issue_reference",
"has_added_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-04-13 12:56:04+00:00
|
bsd-3-clause
| 3,372 |
|
jupyterhub__ltiauthenticator-48
|
diff --git a/README.md b/README.md
index 585d09c..9bdde7a 100644
--- a/README.md
+++ b/README.md
@@ -43,7 +43,20 @@ pip install jupyterhub-ltiauthenticator
_Note_: Anyone with these two strings will be able to access your hub, so keep them secure!!
-4. Pick a name for edX to call your JupyterHub server. Then, along with the two random strings you generated in step 3, paste them together to create an _LTI Passport String_ in the following format:
+4. By default, the user's name will be the `custom_canvas_user_id` passed in by canvas. If you
+ would like to use some other bit of information from the LTI request, you can pick what should
+ be used as the user id.
+
+ ```python
+ # Set the user's email as their user id
+ c.LTIAuthenticator.username_key = 'lis_person_contact_email_primary'
+ ```
+
+ A [partial list of keys in an LTI request](https://www.edu-apps.org/code.html#params)
+ is available to help. Your LMS provider might also implement custom keys
+ you can use.
+
+5. Pick a name for edX to call your JupyterHub server. Then, along with the two random strings you generated in step 4, paste them together to create an _LTI Passport String_ in the following format:
```
your-hub-name:client-key:client-secret
diff --git a/ltiauthenticator/lti11/auth.py b/ltiauthenticator/lti11/auth.py
index 4e55788..016cfa6 100644
--- a/ltiauthenticator/lti11/auth.py
+++ b/ltiauthenticator/lti11/auth.py
@@ -3,7 +3,12 @@ from jupyterhub.auth import Authenticator
from jupyterhub.handlers import BaseHandler
from jupyterhub.utils import url_path_join
+from textwrap import dedent
+
+from tornado.web import HTTPError
+
from traitlets.config import Dict
+from traitlets.config import Unicode
from ltiauthenticator.lti11.handlers import LTI11AuthenticateHandler
from ltiauthenticator.lti11.validator import LTI11LaunchValidator
@@ -35,6 +40,31 @@ class LTI11Authenticator(Authenticator):
""",
)
+ username_key = Unicode(
+ "custom_canvas_user_id",
+ allow_none=True,
+ config=True,
+ help="""
+ Key present in LTI 1.1 launch request used to set the user's JupyterHub's username.
+ Some common examples include:
+ - User's email address: lis_person_contact_email_primary
+ - Canvas LMS custom user id: custom_canvas_user_id
+ Your LMS (Canvas / Open EdX / Moodle / others) may provide additional keys in the
+ LTI 1.1 launch request that you can use to set the username. In most cases these
+ are prefixed with `custom_`. You may also have the option of using variable substitutions
+ to fetch values that aren't provided with your vendor's standard LTI 1.1 launch request.
+ Reference the IMS LTI specification on variable substitutions:
+ https://www.imsglobal.org/specs/ltiv1p1p1/implementation-guide#toc-9.
+
+ Current default behavior:
+
+ To preserve legacy behavior, if custom_canvas_user_id is present in the LTI
+ request, it is used as the username. If not, user_id is used. In the future,
+ the default will be just user_id - if you want to use custom_canvas_user_id,
+ you must explicitly set username_key to custom_canvas_user_id.
+ """,
+ )
+
def get_handlers(self, app: JupyterHub) -> BaseHandler:
return [("/lti/launch", LTI11AuthenticateHandler)]
@@ -59,6 +89,15 @@ class LTI11Authenticator(Authenticator):
Raises:
HTTPError if the required values are not in the request
"""
+ # log deprecation warning when using the default custom_canvas_user_id setting
+ if self.username_key == "custom_canvas_user_id":
+ self.log.warning(
+ dedent(
+ """The default username_key 'custom_canvas_user_id' will be replaced by 'user_id' in a future release.
+ Set c.LTIAuthenticator.username_key to `custom_canvas_user_id` to preserve current behavior.
+ """
+ )
+ )
validator = LTI11LaunchValidator(self.consumers)
self.log.debug(
@@ -78,16 +117,32 @@ class LTI11Authenticator(Authenticator):
self.log.debug("Launch url is: %s" % launch_url)
if validator.validate_launch_request(launch_url, handler.request.headers, args):
- # get the lms vendor to implement optional logic for said vendor
- canvas_id = handler.get_body_argument("custom_canvas_user_id", default=None)
-
- if canvas_id is not None:
- user_id = handler.get_body_argument("custom_canvas_user_id")
- else:
- user_id = handler.get_body_argument("user_id")
+ # raise an http error if the username_key is not in the request's arguments.
+ if self.username_key not in args.keys():
+ raise HTTPError(
+ 400,
+ "%s did not match any of the launch request arguments."
+ % self.username_key,
+ )
+
+ # get the username_key. if empty, fetch the username from the request's user_id value.
+ username = args.get(self.username_key)
+ if not username:
+ username = args.get("user_id")
+
+ # if username is still empty or none, raise an http error.
+ if not username:
+ raise HTTPError(
+ 400,
+ "The %s value in the launch request is empty or None."
+ % self.username_key,
+ )
+
+ # return standard authentication where all launch request arguments are added to the auth_state key
+ # except for the oauth_* arguments.
return {
- "name": user_id,
+ "name": username,
"auth_state": {
k: v for k, v in args.items() if not k.startswith("oauth_")
},
|
jupyterhub/ltiauthenticator
|
98fe61a0768fd5083c2137bb251ced7909f0ab68
|
diff --git a/tests/conftest.py b/tests/conftest.py
index cbe8665..5daf4db 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -1,3 +1,4 @@
+import os
import secrets
import time
@@ -7,26 +8,75 @@ import pytest
from typing import Dict
+from tornado.web import Application
+from tornado.web import RequestHandler
+from tornado.httputil import HTTPServerRequest
+
+from unittest.mock import Mock
+
+
[email protected](scope="function")
+def user_model(username: str, **kwargs) -> dict:
+ """Return a user model"""
+ user = {
+ "username": username,
+ "auth_state": {k: v for k, v in kwargs.items() if not k.startswith("oauth_")},
+ }
+ user.update(kwargs)
+ return user
+
@pytest.fixture(scope="function")
def make_lti11_basic_launch_request_args() -> Dict[str, str]:
def _make_lti11_basic_launch_args(
+ roles: str = "Instructor",
+ ext_roles: str = "urn:lti:instrole:ims/lis/Instructor",
+ lms_vendor: str = "canvas",
oauth_consumer_key: str = "my_consumer_key",
oauth_consumer_secret: str = "my_shared_secret",
):
oauth_timestamp = str(int(time.time()))
oauth_nonce = secrets.token_urlsafe(32)
args = {
- "lti_message_type": "basic-lti-launch-request",
- "lti_version": "LTI-1p0".encode(),
- "resource_link_id": "88391-e1919-bb3456",
+ "oauth_callback": "about:blank",
"oauth_consumer_key": oauth_consumer_key,
"oauth_timestamp": str(int(oauth_timestamp)),
"oauth_nonce": str(oauth_nonce),
"oauth_signature_method": "HMAC-SHA1",
- "oauth_callback": "about:blank",
"oauth_version": "1.0",
- "user_id": "123123123",
+ "context_id": "888efe72d4bbbdf90619353bb8ab5965ccbe9b3f",
+ "context_label": "Introduction to Data Science",
+ "context_title": "Introduction101",
+ "course_lineitems": "https://canvas.instructure.com/api/lti/courses/1/line_items",
+ "custom_canvas_assignment_title": "test-assignment",
+ "custom_canvas_course_id": "616",
+ "custom_canvas_enrollment_state": "active",
+ "custom_canvas_user_id": "1091",
+ "custom_canvas_user_login_id": "[email protected]",
+ "ext_roles": ext_roles,
+ "launch_presentation_document_target": "iframe",
+ "launch_presentation_height": "1000",
+ "launch_presentation_locale": "en",
+ "launch_presentation_return_url": "https://canvas.instructure.com/courses/161/external_content/success/external_tool_redirect",
+ "launch_presentation_width": "1000",
+ "lis_outcome_service_url": "http://www.imsglobal.org/developers/LTI/test/v1p1/common/tool_consumer_outcome.php?b64=MTIzNDU6OjpzZWNyZXQ=",
+ "lis_person_contact_email_primary": "[email protected]",
+ "lis_person_name_family": "Bar",
+ "lis_person_name_full": "Foo Bar",
+ "lis_person_name_given": "Foo",
+ "lti_message_type": "basic-lti-launch-request",
+ "lis_result_sourcedid": "feb-123-456-2929::28883",
+ "lti_version": "LTI-1p0",
+ "resource_link_id": "888efe72d4bbbdf90619353bb8ab5965ccbe9b3f",
+ "resource_link_title": "Test-Assignment",
+ "roles": roles,
+ "tool_consumer_info_product_family_code": lms_vendor,
+ "tool_consumer_info_version": "cloud",
+ "tool_consumer_instance_contact_email": "[email protected]",
+ "tool_consumer_instance_guid": "srnuz6h1U8kOMmETzoqZTJiPWzbPXIYkAUnnAJ4u:test-lms",
+ "tool_consumer_instance_name": "myedutool",
+ "user_id": "185d6c59731a553009ca9b59ca3a885100000",
+ "user_image": "https://lms.example.com/avatar-50.png",
}
extra_args = {"my_key": "this_value"}
headers = {"Content-Type": "application/x-www-form-urlencoded"}
@@ -48,3 +98,108 @@ def make_lti11_basic_launch_request_args() -> Dict[str, str]:
return args
return _make_lti11_basic_launch_args
+
+
[email protected](scope="function")
+def make_lti11_success_authentication_request_args():
+ def _make_lti11_success_authentication_request_args(
+ roles: str = "Instructor",
+ ext_roles: str = "urn:lti:instrole:ims/lis/Instructor",
+ lms_vendor: str = "canvas",
+ oauth_consumer_key: str = "my_consumer_key",
+ ):
+ """
+ Return a valid request arguments make from LMS to our tool (when authentication steps were success)
+ """
+ args = {
+ "oauth_callback": ["about:blank".encode()],
+ "oauth_consumer_key": [oauth_consumer_key.encode()],
+ "oauth_signature_method": ["HMAC-SHA1".encode()],
+ "oauth_timestamp": ["1585947271".encode()],
+ "oauth_nonce": ["01fy8HKIASKuD9gK9vWUcBj9fql1nOCWfOLPzeylsmg".encode()],
+ "oauth_signature": ["abc123".encode()],
+ "oauth_version": ["1.0".encode()],
+ "context_id": ["888efe72d4bbbdf90619353bb8ab5965ccbe9b3f".encode()],
+ "context_label": ["intro101".encode()],
+ "context_title": ["intro101".encode()],
+ "course_lineitems": [
+ "my.platform.com/api/lti/courses/1/line_items".encode()
+ ],
+ "custom_canvas_assignment_title": ["test-assignment".encode()],
+ "custom_canvas_course_id": ["616".encode()],
+ "custom_canvas_enrollment_state": ["active".encode()],
+ "custom_canvas_user_id": ["1091".encode()],
+ "custom_canvas_user_login_id": ["[email protected]".encode()],
+ "ext_roles": [ext_roles.encode()],
+ "launch_presentation_document_target": ["iframe".encode()],
+ "launch_presentation_height": ["1000".encode()],
+ "launch_presentation_locale": ["en".encode()],
+ "launch_presentation_return_url": [
+ "https: //illumidesk.instructure.com/courses/161/external_content/success/external_tool_redirect".encode()
+ ],
+ "launch_presentation_width": ["1000".encode()],
+ "lis_outcome_service_url": [
+ "http://www.imsglobal.org/developers/LTI/test/v1p1/common/tool_consumer_outcome.php?b64=MTIzNDU6OjpzZWNyZXQ=".encode()
+ ],
+ "lis_person_contact_email_primary": ["[email protected]".encode()],
+ "lis_person_name_family": ["Bar".encode()],
+ "lis_person_name_full": ["Foo Bar".encode()],
+ "lis_person_name_given": ["Foo".encode()],
+ "lti_message_type": ["basic-lti-launch-request".encode()],
+ "lis_result_sourcedid": ["feb-123-456-2929::28883".encode()],
+ "lti_version": ["LTI-1p0".encode()],
+ "resource_link_id": ["888efe72d4bbbdf90619353bb8ab5965ccbe9b3f".encode()],
+ "resource_link_title": ["Test-Assignment-Another-LMS".encode()],
+ "roles": [roles.encode()],
+ "tool_consumer_info_product_family_code": [lms_vendor.encode()],
+ "tool_consumer_info_version": ["cloud".encode()],
+ "tool_consumer_instance_contact_email": [
+ "[email protected]".encode()
+ ],
+ "tool_consumer_instance_guid": [
+ "srnuz6h1U8kOMmETzoqZTJiPWzbPXIYkAUnnAJ4u:test-lms".encode()
+ ],
+ "tool_consumer_instance_name": ["myorg".encode()],
+ "user_id": ["185d6c59731a553009ca9b59ca3a885100000".encode()],
+ "user_image": ["https://lms.example.com/avatar-50.png".encode()],
+ }
+ return args
+
+ return _make_lti11_success_authentication_request_args
+
+
[email protected](scope="function")
+def make_lti11_mock_request_handler() -> RequestHandler:
+ """
+ Sourced from https://github.com/jupyterhub/oauthenticator/blob/master/oauthenticator/tests/mocks.py
+ """
+
+ def _make_lti11_mock_request_handler(
+ handler: RequestHandler,
+ uri: str = "https://hub.example.com",
+ method: str = "POST",
+ **settings: dict,
+ ) -> RequestHandler:
+ """Instantiate a Handler in a mock application"""
+ application = Application(
+ hub=Mock(
+ base_url="/hub/",
+ server=Mock(base_url="/hub/"),
+ ),
+ cookie_secret=os.urandom(32),
+ db=Mock(rollback=Mock(return_value=None)),
+ **settings,
+ )
+ request = HTTPServerRequest(
+ method=method,
+ uri=uri,
+ connection=Mock(),
+ )
+ handler = RequestHandler(
+ application=application,
+ request=request,
+ )
+ handler._transforms = []
+ return handler
+
+ return _make_lti11_mock_request_handler
diff --git a/tests/test_lti11_authenticator.py b/tests/test_lti11_authenticator.py
index 0b62ca9..267ceac 100644
--- a/tests/test_lti11_authenticator.py
+++ b/tests/test_lti11_authenticator.py
@@ -1,143 +1,131 @@
-import pytest
-
-from tornado import web
-
-from ltiauthenticator.lti11.validator import LTI11LaunchValidator
-
-
-def test_launch(make_lti11_basic_launch_request_args):
- """Test a basic launch request"""
- oauth_consumer_key = "my_consumer_key"
- oauth_consumer_secret = "my_shared_secret"
- launch_url = "http://jupyterhub/hub/lti/launch"
- headers = {"Content-Type": "application/x-www-form-urlencoded"}
-
- args = make_lti11_basic_launch_request_args(
- oauth_consumer_key,
- oauth_consumer_secret,
- )
-
- validator = LTI11LaunchValidator({oauth_consumer_key: oauth_consumer_secret})
-
- assert validator.validate_launch_request(launch_url, headers, args)
-
-
-def test_wrong_key(make_lti11_basic_launch_request_args):
- """Test that the request is rejected when receiving the wrong consumer key."""
- oauth_consumer_key = "my_consumer_key"
- oauth_consumer_secret = "my_shared_secret"
- launch_url = "http://jupyterhub/hub/lti/launch"
- headers = {"Content-Type": "application/x-www-form-urlencoded"}
-
- args = make_lti11_basic_launch_request_args(
- oauth_consumer_key,
- oauth_consumer_secret,
- )
-
- validator = LTI11LaunchValidator({"wrongkey": oauth_consumer_secret})
-
- with pytest.raises(web.HTTPError):
- assert validator.validate_launch_request(launch_url, headers, args)
-
-
-def test_wrong_secret(make_lti11_basic_launch_request_args):
- """Test that a request is rejected when the signature is created with the wrong secret."""
- oauth_consumer_key = "my_consumer_key"
- oauth_consumer_secret = "my_shared_secret"
- launch_url = "http://jupyterhub/hub/lti/launch"
- headers = {"Content-Type": "application/x-www-form-urlencoded"}
-
- args = make_lti11_basic_launch_request_args(
- oauth_consumer_key,
- oauth_consumer_secret,
- )
-
- validator = LTI11LaunchValidator({oauth_consumer_key: "wrongsecret"})
-
- with pytest.raises(web.HTTPError):
- validator.validate_launch_request(launch_url, headers, args)
-
-
-def test_full_replay(make_lti11_basic_launch_request_args):
- """Ensure that an oauth timestamp/nonce replay raises an HTTPError"""
+import json
- oauth_consumer_key = "my_consumer_key"
- oauth_consumer_secret = "my_shared_secret"
- launch_url = "http://jupyterhub/hub/lti/launch"
- headers = {"Content-Type": "application/x-www-form-urlencoded"}
+from unittest.mock import Mock
+from unittest.mock import patch
- args = make_lti11_basic_launch_request_args(
- oauth_consumer_key,
- oauth_consumer_secret,
- )
-
- validator = LTI11LaunchValidator({oauth_consumer_key: oauth_consumer_secret})
-
- assert validator.validate_launch_request(launch_url, headers, args)
-
- with pytest.raises(web.HTTPError):
- validator.validate_launch_request(launch_url, headers, args)
-
-
-def test_partial_replay_timestamp(make_lti11_basic_launch_request_args):
- """Test that a partial timestamp replay raises an HTTPError."""
-
- oauth_consumer_key = "my_consumer_key"
- oauth_consumer_secret = "my_shared_secret"
- launch_url = "http://jupyterhub/hub/lti/launch"
- headers = {"Content-Type": "application/x-www-form-urlencoded"}
-
- args = make_lti11_basic_launch_request_args(
- oauth_consumer_key,
- oauth_consumer_secret,
- )
-
- validator = LTI11LaunchValidator({oauth_consumer_key: oauth_consumer_secret})
-
- assert validator.validate_launch_request(launch_url, headers, args)
-
- args["oauth_timestamp"] = str(int(float(args["oauth_timestamp"])) - 1)
- with pytest.raises(web.HTTPError):
- validator.validate_launch_request(launch_url, headers, args)
-
-
-def test_partial_replay_nonce(make_lti11_basic_launch_request_args):
- """Test that a partial nonce replay raises an HTTPError"""
- oauth_consumer_key = "my_consumer_key"
- oauth_consumer_secret = "my_shared_secret"
- launch_url = "http://jupyterhub/hub/lti/launch"
- headers = {"Content-Type": "application/x-www-form-urlencoded"}
-
- args = make_lti11_basic_launch_request_args(
- oauth_consumer_key,
- oauth_consumer_secret,
- )
-
- validator = LTI11LaunchValidator({oauth_consumer_key: oauth_consumer_secret})
-
- assert validator.validate_launch_request(launch_url, headers, args)
-
- args["oauth_nonce"] = args["oauth_nonce"] + "1"
- with pytest.raises(web.HTTPError):
- validator.validate_launch_request(launch_url, headers, args)
-
-
-def test_dubious_extra_args(make_lti11_basic_launch_request_args):
- """Ensure that dubious extra args are rejected"""
- oauth_consumer_key = "my_consumer_key"
- oauth_consumer_secret = "my_shared_secret"
- launch_url = "http://jupyterhub/hub/lti/launch"
- headers = {"Content-Type": "application/x-www-form-urlencoded"}
+import pytest
- args = make_lti11_basic_launch_request_args(
- oauth_consumer_key,
- oauth_consumer_secret,
- )
+from tornado.web import HTTPError
+from tornado.httputil import HTTPServerRequest
+from tornado.web import RequestHandler
- validator = LTI11LaunchValidator({oauth_consumer_key: oauth_consumer_secret})
+from ltiauthenticator.lti11.auth import LTI11Authenticator
+from ltiauthenticator.lti11.validator import LTI11LaunchValidator
- assert validator.validate_launch_request(launch_url, headers, args)
- args["extra_credential"] = "i have admin powers"
- with pytest.raises(web.HTTPError):
- validator.validate_launch_request(launch_url, headers, args)
[email protected]
+async def test_authenticator_uses_lti11validator(
+ make_lti11_success_authentication_request_args,
+):
+ """
+ Ensure that we call the LTI11Validator from the LTI11Authenticator.
+ """
+ with patch.object(
+ LTI11LaunchValidator, "validate_launch_request", return_value=True
+ ) as mock_validator:
+
+ authenticator = LTI11Authenticator()
+ handler = Mock(spec=RequestHandler)
+ request = HTTPServerRequest(
+ method="POST",
+ connection=Mock(),
+ )
+ handler.request = request
+
+ handler.request.arguments = make_lti11_success_authentication_request_args(
+ "lmsvendor"
+ )
+ handler.request.get_argument = (
+ lambda x, strip=True: make_lti11_success_authentication_request_args(
+ "lmsvendor"
+ )[x][0].decode()
+ )
+
+ _ = await authenticator.authenticate(handler, None)
+ assert mock_validator.called
+
+
[email protected]
+async def test_authenticator_returns_auth_dict_when_custom_canvas_user_id_is_empty(
+ make_lti11_success_authentication_request_args,
+):
+ """
+ Do we get a valid username when the custom_canvas_user_id is empty?
+ """
+ local_args = make_lti11_success_authentication_request_args()
+ local_args["custom_canvas_user_id"] = ["".encode()]
+ with patch.object(
+ LTI11LaunchValidator, "validate_launch_request", return_value=True
+ ):
+ authenticator = LTI11Authenticator()
+ handler = Mock(
+ spec=RequestHandler,
+ get_secure_cookie=Mock(return_value=json.dumps(["key", "secret"])),
+ request=Mock(
+ arguments=local_args,
+ headers={},
+ items=[],
+ ),
+ )
+ result = await authenticator.authenticate(handler, None)
+ expected = {
+ "name": "185d6c59731a553009ca9b59ca3a885100000",
+ }
+ assert result["name"] == expected["name"]
+
+
[email protected]
+async def test_authenticator_returns_correct_username_when_using_lis_person_contact_email_primary(
+ make_lti11_success_authentication_request_args,
+):
+ """
+ Do we get a valid username with lms vendors other than canvas?
+ """
+ local_args = make_lti11_success_authentication_request_args()
+ local_authenticator = LTI11Authenticator()
+ local_authenticator.username_key = "lis_person_contact_email_primary"
+ with patch.object(
+ LTI11LaunchValidator, "validate_launch_request", return_value=True
+ ):
+ authenticator = local_authenticator
+ handler = Mock(
+ spec=RequestHandler,
+ get_secure_cookie=Mock(return_value=json.dumps(["key", "secret"])),
+ request=Mock(
+ arguments=local_args,
+ headers={},
+ items=[],
+ ),
+ )
+ result = await authenticator.authenticate(handler, None)
+ expected = {
+ "name": "[email protected]",
+ }
+ assert result["name"] == expected["name"]
+
+
[email protected]
+async def test_empty_username_raises_http_error(
+ make_lti11_success_authentication_request_args,
+):
+ """Does an empty username value raise the correct 400 HTTPError?"""
+ local_args = make_lti11_success_authentication_request_args()
+ local_authenticator = LTI11Authenticator()
+ local_args["custom_canvas_user_id"] = ["".encode()]
+ local_args["user_id"] = ["".encode()]
+
+ with patch.object(
+ LTI11LaunchValidator, "validate_launch_request", return_value=True
+ ):
+ authenticator = local_authenticator
+ handler = Mock(
+ spec=RequestHandler,
+ get_secure_cookie=Mock(return_value=json.dumps(["key", "secret"])),
+ request=Mock(
+ arguments=local_args,
+ headers={},
+ items=[],
+ ),
+ )
+ with pytest.raises(HTTPError):
+ _ = await authenticator.authenticate(handler, None)
diff --git a/tests/test_lti11_handlers.py b/tests/test_lti11_handlers.py
new file mode 100644
index 0000000..4719200
--- /dev/null
+++ b/tests/test_lti11_handlers.py
@@ -0,0 +1,41 @@
+from unittest.mock import patch
+
+import pytest
+
+from ltiauthenticator.lti11.handlers import LTI11AuthenticateHandler
+
+
[email protected]
+async def test_lti_11_authenticate_handler_invokes_redirect_method(
+ make_lti11_mock_request_handler,
+):
+ """
+ Does the LTI11AuthenticateHandler call the redirect function?
+ """
+ local_handler = make_lti11_mock_request_handler(LTI11AuthenticateHandler)
+ with patch.object(
+ LTI11AuthenticateHandler, "redirect", return_value=None
+ ) as mock_redirect:
+ with patch.object(LTI11AuthenticateHandler, "login_user", return_value=None):
+ await LTI11AuthenticateHandler(
+ local_handler.application, local_handler.request
+ ).post()
+ assert mock_redirect.called
+
+
[email protected]
+async def test_lti_11_authenticate_handler_invokes_login_user_method(
+ make_lti11_mock_request_handler,
+):
+ """
+ Does the LTI11AuthenticateHandler call the login_user function?
+ """
+ local_handler = make_lti11_mock_request_handler(LTI11AuthenticateHandler)
+ with patch.object(LTI11AuthenticateHandler, "redirect", return_value=None):
+ with patch.object(
+ LTI11AuthenticateHandler, "login_user", return_value=None
+ ) as mock_login_user:
+ await LTI11AuthenticateHandler(
+ local_handler.application, local_handler.request
+ ).post()
+ assert mock_login_user.called
|
Use usernames instead of user IDs
I'm currently using LTI authentication with Moodle. By default, the user IDs are used to create the JHub users. Is it possible to use the Moodle usernames (or first/last names) instead?
Help is appreciated. Thanks!
|
0.0
|
98fe61a0768fd5083c2137bb251ced7909f0ab68
|
[
"tests/test_lti11_authenticator.py::test_authenticator_returns_auth_dict_when_custom_canvas_user_id_is_empty",
"tests/test_lti11_authenticator.py::test_authenticator_returns_correct_username_when_using_lis_person_contact_email_primary",
"tests/test_lti11_authenticator.py::test_empty_username_raises_http_error"
] |
[
"tests/test_lti11_authenticator.py::test_authenticator_uses_lti11validator",
"tests/test_lti11_handlers.py::test_lti_11_authenticate_handler_invokes_redirect_method",
"tests/test_lti11_handlers.py::test_lti_11_authenticate_handler_invokes_login_user_method"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-06-02 23:50:26+00:00
|
bsd-3-clause
| 3,373 |
|
jupyterhub__ltiauthenticator-51
|
diff --git a/ltiauthenticator/lti11/auth.py b/ltiauthenticator/lti11/auth.py
index 016cfa6..641b17d 100644
--- a/ltiauthenticator/lti11/auth.py
+++ b/ltiauthenticator/lti11/auth.py
@@ -120,10 +120,8 @@ class LTI11Authenticator(Authenticator):
# raise an http error if the username_key is not in the request's arguments.
if self.username_key not in args.keys():
- raise HTTPError(
- 400,
- "%s did not match any of the launch request arguments."
- % self.username_key,
+ self.log.warning(
+ "%s the specified username_key did not match any of the launch request arguments."
)
# get the username_key. if empty, fetch the username from the request's user_id value.
|
jupyterhub/ltiauthenticator
|
01009c50834771acf124b505cf9ba5269f75238a
|
diff --git a/tests/test_lti11_authenticator.py b/tests/test_lti11_authenticator.py
index 267ceac..db45300 100644
--- a/tests/test_lti11_authenticator.py
+++ b/tests/test_lti11_authenticator.py
@@ -74,6 +74,35 @@ async def test_authenticator_returns_auth_dict_when_custom_canvas_user_id_is_emp
assert result["name"] == expected["name"]
[email protected]
+async def test_authenticator_returns_auth_dict_when_custom_canvas_user_id_does_not_exist(
+ make_lti11_success_authentication_request_args,
+):
+ """
+ Do we get a valid username when the custom_canvas_user_id parameter does not exist in the launch request?
+ """
+ local_args = make_lti11_success_authentication_request_args()
+ del local_args["custom_canvas_user_id"]
+ with patch.object(
+ LTI11LaunchValidator, "validate_launch_request", return_value=True
+ ):
+ authenticator = LTI11Authenticator()
+ handler = Mock(
+ spec=RequestHandler,
+ get_secure_cookie=Mock(return_value=json.dumps(["key", "secret"])),
+ request=Mock(
+ arguments=local_args,
+ headers={},
+ items=[],
+ ),
+ )
+ result = await authenticator.authenticate(handler, None)
+ expected = {
+ "name": "185d6c59731a553009ca9b59ca3a885100000",
+ }
+ assert result["name"] == expected["name"]
+
+
@pytest.mark.asyncio
async def test_authenticator_returns_correct_username_when_using_lis_person_contact_email_primary(
make_lti11_success_authentication_request_args,
|
Configured oauth_consumer_key not known
<!-- Thank you for contributing. These HTML comments will not render in the issue, but you can delete them once you've read them if you prefer! -->
### Bug description
I am testing PR #48 with Helm chart zero-to-jupyterhub-k8s 1.1.1 as follows:
1. I use the Docker image jupyterhub/k8s-hub:1.1.1 as base. This is working fine with the configuration below.
2. install the latest ltiauthenticator
3. configure the authenticator in values.yml
```
hub:
config:
LTIAuthenticator:
consumers: {
"aaaaaaaaaaaaaaaaaaaaaaa": "bbbbbbbbbbbbbbbbb"
}
JupyterHub:
authenticator_class: ltiauthenticator.LTIAuthenticator
```
#### Expected behaviour
<!-- Tell us what you thought would happen. -->
Authentication is working as with ltiauthenticator 1.0.0
#### Actual behaviour
<!-- Tell us what actually happens. -->
Authentication fails. The issue raises here:
```
if args["oauth_consumer_key"] not in self.consumers:
raise HTTPError(401, "unknown oauth_consumer_key")
```
I think the LTI11Authenticator does not get the configuration items from the values.yml (content is `{}` at initialization); the attribute `args["oauth_consumer_key"]` contains the correct value.
I tried then to find where the configuration values are read, but I could not find that piece of code here or in JupyterHub.
### Your personal set up
<!--
Tell us a little about the system you're using.
Please include information about how you installed,
e.g. are you using a distribution such as zero-to-jupyterhub or the-littlest-jupyterhub.
-->
Kubernetes setup is straight forward. For testing, my Dockerfile to build the test environment looks like (forked the repo to add additional debugging output only):
```
FROM jupyterhub/k8s-hub:1.1.1
USER 0
RUN git clone https://github.com/bengig/ltiauthenticator.git && cd ltiauthenticator && git checkout jhub-integration && pip3 install .
USER 1000
CMD ["jupyterhub", "--config", "/usr/local/etc/jupyterhub/jupyterhub_config.py"]
```
|
0.0
|
01009c50834771acf124b505cf9ba5269f75238a
|
[
"tests/test_lti11_authenticator.py::test_authenticator_returns_auth_dict_when_custom_canvas_user_id_does_not_exist"
] |
[
"tests/test_lti11_authenticator.py::test_authenticator_uses_lti11validator",
"tests/test_lti11_authenticator.py::test_authenticator_returns_auth_dict_when_custom_canvas_user_id_is_empty",
"tests/test_lti11_authenticator.py::test_authenticator_returns_correct_username_when_using_lis_person_contact_email_primary",
"tests/test_lti11_authenticator.py::test_empty_username_raises_http_error"
] |
{
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-07-23 23:46:58+00:00
|
bsd-3-clause
| 3,374 |
|
jupyterhub__nativeauthenticator-49
|
diff --git a/nativeauthenticator/nativeauthenticator.py b/nativeauthenticator/nativeauthenticator.py
index f0e7207..2cff990 100644
--- a/nativeauthenticator/nativeauthenticator.py
+++ b/nativeauthenticator/nativeauthenticator.py
@@ -2,6 +2,7 @@ import bcrypt
import os
from datetime import datetime
from jupyterhub.auth import Authenticator
+from jupyterhub.orm import User
from sqlalchemy import inspect
from tornado import gen
@@ -149,7 +150,11 @@ class NativeAuthenticator(Authenticator):
infos.update({'is_authorized': True})
user_info = UserInfo(**infos)
- self.db.add(user_info)
+ user = User(name=username)
+
+ self.db.add_all([user_info, user])
+ self.db.commit()
+
return user_info
def change_password(self, username, new_password):
@@ -171,3 +176,9 @@ class NativeAuthenticator(Authenticator):
(r'/change-password', ChangePasswordHandler),
]
return super().get_handlers(app) + native_handlers
+
+ def delete_user(self, user):
+ user_info = UserInfo.find(self.db, user.name)
+ self.db.delete(user_info)
+ self.db.commit()
+ return super().delete_user(user)
|
jupyterhub/nativeauthenticator
|
7b0953c83b4b7d725561808cfa3ab5dbdd97b9a5
|
diff --git a/nativeauthenticator/tests/test_authenticator.py b/nativeauthenticator/tests/test_authenticator.py
index c5f55ce..5475409 100644
--- a/nativeauthenticator/tests/test_authenticator.py
+++ b/nativeauthenticator/tests/test_authenticator.py
@@ -1,5 +1,6 @@
import pytest
import time
+from jupyterhub.orm import User
from jupyterhub.tests.mocking import MockHub
from nativeauthenticator import NativeAuthenticator
@@ -40,9 +41,11 @@ async def test_create_user(is_admin, open_signup, expected_authorization,
auth.open_signup = True
auth.get_or_create_user('johnsnow', 'password')
- user = UserInfo.find(app.db, 'johnsnow')
- assert user.username == 'johnsnow'
- assert user.is_authorized == expected_authorization
+ user_info = UserInfo.find(app.db, 'johnsnow')
+ user = User.find(app.db, 'johnsnow')
+ assert user_info.username == 'johnsnow'
+ assert user.name == 'johnsnow'
+ assert user_info.is_authorized == expected_authorization
async def test_create_user_bas_characters(tmpcwd, app):
@@ -154,3 +157,14 @@ async def test_change_password(tmpcwd, app):
auth.change_password('johnsnow', 'newpassword')
assert not user.is_valid_password('password')
assert user.is_valid_password('newpassword')
+
+
+async def test_delete_user(tmpcwd, app):
+ auth = NativeAuthenticator(db=app.db)
+ auth.get_or_create_user('johnsnow', 'password')
+
+ user = User.find(app.db, 'johnsnow')
+ auth.delete_user(user)
+
+ user_info = UserInfo.find(app.db, 'johnsnow')
+ assert not user_info
|
Make delete_user method delete UserInfo as well
As explained on #44 we should overwrite the `delete_user` method to delete a User on UserInfo table as well.
|
0.0
|
7b0953c83b4b7d725561808cfa3ab5dbdd97b9a5
|
[
"nativeauthenticator/tests/test_authenticator.py::test_create_user[False-False-False]",
"nativeauthenticator/tests/test_authenticator.py::test_create_user[True-False-True]",
"nativeauthenticator/tests/test_authenticator.py::test_create_user[False-True-True]",
"nativeauthenticator/tests/test_authenticator.py::test_delete_user"
] |
[
"nativeauthenticator/tests/test_authenticator.py::test_create_user_bas_characters",
"nativeauthenticator/tests/test_authenticator.py::test_create_user_with_strong_passwords[qwerty-1-False]",
"nativeauthenticator/tests/test_authenticator.py::test_create_user_with_strong_passwords[agameofthrones-1-True]",
"nativeauthenticator/tests/test_authenticator.py::test_create_user_with_strong_passwords[agameofthrones-15-False]",
"nativeauthenticator/tests/test_authenticator.py::test_create_user_with_strong_passwords[averyveryverylongpassword-15-True]",
"nativeauthenticator/tests/test_authenticator.py::test_authentication[name-123-False-False]",
"nativeauthenticator/tests/test_authenticator.py::test_authentication[johnsnow-123-True-False]",
"nativeauthenticator/tests/test_authenticator.py::test_authentication[Snow-password-True-False]",
"nativeauthenticator/tests/test_authenticator.py::test_authentication[johnsnow-password-False-False]",
"nativeauthenticator/tests/test_authenticator.py::test_authentication[johnsnow-password-True-True]",
"nativeauthenticator/tests/test_authenticator.py::test_handlers",
"nativeauthenticator/tests/test_authenticator.py::test_add_new_attempt_of_login",
"nativeauthenticator/tests/test_authenticator.py::test_authentication_login_count",
"nativeauthenticator/tests/test_authenticator.py::test_authentication_with_exceed_atempts_of_login",
"nativeauthenticator/tests/test_authenticator.py::test_change_password"
] |
{
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-02-07 18:29:39+00:00
|
bsd-3-clause
| 3,375 |
|
jupyterhub__oauthenticator-449
|
diff --git a/docs/source/github.md b/docs/source/github.md
index d5e2663..170b51e 100644
--- a/docs/source/github.md
+++ b/docs/source/github.md
@@ -39,3 +39,33 @@ To use this expanded user information, you will need to subclass your
current spawner and modify the subclass to read these fields from
`auth_state` and then use this information to provision your Notebook or
Lab user.
+
+## Restricting access
+
+### Organizations
+
+If you would like to restrict access to members of specific GitHub organizations
+you can pass a list of organization names to `allowed_organizations`.
+
+For example, the below will ensure that only members of `org_a` or
+`org_b` will be authorized to access.
+
+`c.GitHubOAuthenticator.allowed_organizations = ["org_a", "org_b"]`
+
+### Teams
+
+It is also possible to restrict access to members of specific teams within
+organizations using the syntax: `<organization>:<team-name>`.
+
+For example, the below will only allow members of `org_a`, or
+`team_1` in `org_b` access. Members of `org_b` but not `team_1` will be
+unauthorized to access.
+
+`c.GitHubOAuthenticator.allowed_organizations = ["org_a", "org_b:team_1"]`
+
+### Notes
+
+- Restricting access by either organization or team requires the `read:org`
+ scope
+- Ensure you use the organization/team name as it appears in the GitHub url
+ - E.g. Use `jupyter` instead of `Project Jupyter`
diff --git a/oauthenticator/github.py b/oauthenticator/github.py
index e29777d..9526b1f 100644
--- a/oauthenticator/github.py
+++ b/oauthenticator/github.py
@@ -225,13 +225,13 @@ class GitHubOAuthenticator(OAuthenticator):
headers = _api_headers(access_token)
# Check membership of user `username` for organization `org` via api [check-membership](https://developer.github.com/v3/orgs/members/#check-membership)
# With empty scope (even if authenticated by an org member), this
- # will only await public org members. You want 'read:org' in order
- # to be able to iterate through all members.
- check_membership_url = "%s/orgs/%s/members/%s" % (
- self.github_api,
- org,
- username,
- )
+ # will only await public org members. You want 'read:org' in order
+ # to be able to iterate through all members. If you would only like to
+ # allow certain teams within an organisation, specify
+ # allowed_organisations = {org_name:team_name}
+
+ check_membership_url = self._build_check_membership_url(org, username)
+
req = HTTPRequest(
check_membership_url,
method="GET",
@@ -260,6 +260,13 @@ class GitHubOAuthenticator(OAuthenticator):
)
return False
+ def _build_check_membership_url(self, org: str, username: str) -> str:
+ if ":" in org:
+ org, team = org.split(":")
+ return f"{self.github_api}/orgs/{org}/teams/{team}/members/{username}"
+ else:
+ return f"{self.github_api}/orgs/{org}/members/{username}"
+
class LocalGitHubOAuthenticator(LocalAuthenticator, GitHubOAuthenticator):
|
jupyterhub/oauthenticator
|
d8ea0b6f11dbc3dac35aada9d17aef6ccd2da6a4
|
diff --git a/oauthenticator/tests/test_github.py b/oauthenticator/tests/test_github.py
index 0211cd4..16c04c9 100644
--- a/oauthenticator/tests/test_github.py
+++ b/oauthenticator/tests/test_github.py
@@ -7,6 +7,7 @@ from urllib.parse import parse_qs
from urllib.parse import urlparse
from pytest import fixture
+from pytest import mark
from tornado.httpclient import HTTPResponse
from tornado.httputil import HTTPHeaders
from traitlets.config import Config
@@ -71,40 +72,42 @@ async def test_allowed_org_membership(github_client):
## Mock Github API
- teams = {
+ orgs = {
'red': ['grif', 'simmons', 'donut', 'sarge', 'lopez'],
'blue': ['tucker', 'caboose', 'burns', 'sheila', 'texas'],
}
+ org_teams = {'blue': {'alpha': ['tucker', 'caboose', 'burns']}}
+
member_regex = re.compile(r'/orgs/(.*)/members')
- def team_members(paginate, request):
+ def org_members(paginate, request):
urlinfo = urlparse(request.url)
- team = member_regex.match(urlinfo.path).group(1)
+ org = member_regex.match(urlinfo.path).group(1)
- if team not in teams:
+ if org not in orgs:
return HTTPResponse(request, 404)
if not paginate:
- return [user_model(m) for m in teams[team]]
+ return [user_model(m) for m in orgs[org]]
else:
page = parse_qs(urlinfo.query).get('page', ['1'])
page = int(page[0])
- return team_members_paginated(
- team, page, urlinfo, functools.partial(HTTPResponse, request)
+ return org_members_paginated(
+ org, page, urlinfo, functools.partial(HTTPResponse, request)
)
- def team_members_paginated(team, page, urlinfo, response):
- if page < len(teams[team]):
+ def org_members_paginated(org, page, urlinfo, response):
+ if page < len(orgs[org]):
headers = make_link_header(urlinfo, page + 1)
- elif page == len(teams[team]):
+ elif page == len(orgs[org]):
headers = {}
else:
return response(400)
headers.update({'Content-Type': 'application/json'})
- ret = [user_model(teams[team][page - 1])]
+ ret = [user_model(orgs[org][page - 1])]
return response(
200,
@@ -112,19 +115,42 @@ async def test_allowed_org_membership(github_client):
buffer=BytesIO(json.dumps(ret).encode('utf-8')),
)
- membership_regex = re.compile(r'/orgs/(.*)/members/(.*)')
+ org_membership_regex = re.compile(r'/orgs/(.*)/members/(.*)')
- def team_membership(request):
+ def org_membership(request):
urlinfo = urlparse(request.url)
- urlmatch = membership_regex.match(urlinfo.path)
- team = urlmatch.group(1)
+ urlmatch = org_membership_regex.match(urlinfo.path)
+ org = urlmatch.group(1)
username = urlmatch.group(2)
- print('Request team = %s, username = %s' % (team, username))
- if team not in teams:
- print('Team not found: team = %s' % (team))
+ print('Request org = %s, username = %s' % (org, username))
+ if org not in orgs:
+ print('Org not found: org = %s' % (org))
+ return HTTPResponse(request, 404)
+ if username not in orgs[org]:
+ print('Member not found: org = %s, username = %s' % (org, username))
return HTTPResponse(request, 404)
- if username not in teams[team]:
- print('Member not found: team = %s, username = %s' % (team, username))
+ return HTTPResponse(request, 204)
+
+ team_membership_regex = re.compile(r'/orgs/(.*)/teams/(.*)/members/(.*)')
+
+ def team_membership(request):
+ urlinfo = urlparse(request.url)
+ urlmatch = team_membership_regex.match(urlinfo.path)
+ org = urlmatch.group(1)
+ team = urlmatch.group(2)
+ username = urlmatch.group(3)
+ print('Request org = %s, team = %s username = %s' % (org, team, username))
+ if org not in orgs:
+ print('Org not found: org = %s' % (org))
+ return HTTPResponse(request, 404)
+ if team not in org_teams[org]:
+ print('Team not found in org: team = %s, org = %s' % (team, org))
+ return HTTPResponse(request, 404)
+ if username not in org_teams[org][team]:
+ print(
+ 'Member not found: org = %s, team = %s, username = %s'
+ % (org, team, username)
+ )
return HTTPResponse(request, 404)
return HTTPResponse(request, 204)
@@ -132,8 +158,9 @@ async def test_allowed_org_membership(github_client):
for paginate in (False, True):
client_hosts = client.hosts['api.github.com']
- client_hosts.append((membership_regex, team_membership))
- client_hosts.append((member_regex, functools.partial(team_members, paginate)))
+ client_hosts.append((team_membership_regex, team_membership))
+ client_hosts.append((org_membership_regex, org_membership))
+ client_hosts.append((member_regex, functools.partial(org_members, paginate)))
authenticator.allowed_organizations = ['blue']
@@ -156,10 +183,42 @@ async def test_allowed_org_membership(github_client):
user = await authenticator.authenticate(handler)
assert user['name'] == 'donut'
+ # test team membership
+ authenticator.allowed_organizations = ['blue:alpha', 'red']
+
+ handler = client.handler_for_user(user_model('tucker'))
+ user = await authenticator.authenticate(handler)
+ assert user['name'] == 'tucker'
+
+ handler = client.handler_for_user(user_model('grif'))
+ user = await authenticator.authenticate(handler)
+ assert user['name'] == 'grif'
+
+ handler = client.handler_for_user(user_model('texas'))
+ user = await authenticator.authenticate(handler)
+ assert user is None
+
client_hosts.pop()
client_hosts.pop()
[email protected](
+ "org, username, expected",
+ [
+ ("blue", "texas", "https://api.github.com/orgs/blue/members/texas"),
+ (
+ "blue:alpha",
+ "tucker",
+ "https://api.github.com/orgs/blue/teams/alpha/members/tucker",
+ ),
+ ("red", "grif", "https://api.github.com/orgs/red/members/grif"),
+ ],
+)
+def test_build_check_membership_url(org, username, expected):
+ output = GitHubOAuthenticator()._build_check_membership_url(org, username)
+ assert output == expected
+
+
def test_deprecated_config(caplog):
cfg = Config()
cfg.GitHubOAuthenticator.github_organization_whitelist = ["jupy"]
|
[GitHub] We can authorize organizations, but what about teams within them?
Currently GitHub authentication is setup to whitelist individual users or entire organizations:
https://github.com/jupyterhub/oauthenticator/blob/master/oauthenticator/github.py
See here for the implementation:
https://zero-to-jupyterhub.readthedocs.io/en/latest/authentication.html?highlight=auth#github
It would be great to be able to whitelist Teams within a given organization:
https://developer.github.com/v3/teams/members/#get-team-membership
We are currently creating many new organizations on github for week-long tutorials to grant time-limited access to hubs. Having team-based authentication could help with a few scenarios:
1) medium/large github organizations with application-specific hubs (https://github.com/pangeo-data)
2) could also be a really useful feature for resource access based on team membership within a hub (for example, mapping team name to group id)?
|
0.0
|
d8ea0b6f11dbc3dac35aada9d17aef6ccd2da6a4
|
[
"oauthenticator/tests/test_github.py::test_build_check_membership_url[blue-texas-https://api.github.com/orgs/blue/members/texas]",
"oauthenticator/tests/test_github.py::test_build_check_membership_url[blue:alpha-tucker-https://api.github.com/orgs/blue/teams/alpha/members/tucker]",
"oauthenticator/tests/test_github.py::test_build_check_membership_url[red-grif-https://api.github.com/orgs/red/members/grif]"
] |
[
"oauthenticator/tests/test_github.py::test_deprecated_config"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-08-04 15:03:45+00:00
|
bsd-3-clause
| 3,376 |
|
just-work__fffw-100
|
diff --git a/fffw/encoding/filters.py b/fffw/encoding/filters.py
index 194424c..1f49262 100644
--- a/fffw/encoding/filters.py
+++ b/fffw/encoding/filters.py
@@ -261,6 +261,8 @@ class Trim(AutoFilter):
meta = metadata[0]
scenes = []
streams: List[str] = []
+ start = self.start or TS(0)
+ end = min(meta.duration, self.end or TS(0))
for scene in meta.scenes:
if scene.stream and (not streams or streams[0] != scene.stream):
# Adding an input stream without contiguous duplicates.
@@ -279,12 +281,12 @@ class Trim(AutoFilter):
duration=end - start))
kwargs = {
- 'start': self.start,
- 'duration': self.end,
+ 'start': start,
+ 'duration': end,
'scenes': scenes,
'streams': streams
}
- interval = cast(TS, self.end) - cast(TS, self.start)
+ interval = cast(TS, end) - cast(TS, start)
if isinstance(meta, AudioMeta):
kwargs['samples'] = round(meta.sampling_rate * interval)
if isinstance(meta, VideoMeta):
|
just-work/fffw
|
660e60664812b377a9ac43c0a6b9bb807bc7e394
|
diff --git a/tests/test_graph.py b/tests/test_graph.py
index ecf7948..c7db0fd 100644
--- a/tests/test_graph.py
+++ b/tests/test_graph.py
@@ -316,6 +316,15 @@ class FilterGraphTestCase(TestCase):
self.assertEqual(vm.duration, TS(4.0))
self.assertEqual(vm.frames, 1.0 * vm.frame_rate)
+ def test_video_trim_end_of_stream(self):
+ """
+ If Trim ends after stream end, duration is set to min value.
+ """
+ f = self.source | Trim(VIDEO, start=5.0, end=400.0) | SetPTS(VIDEO)
+ f > self.output
+ vm = cast(VideoMeta, self.output.codecs[0].get_meta_data())
+ self.assertEqual(vm.duration, TS(295.0))
+
def test_audio_trim_metadata(self):
"""
Trim filter sets start and changes stream duration.
|
Trim sets incorrect duration
If Trim end is after EOF, stream output duration is greater than expected.
|
0.0
|
660e60664812b377a9ac43c0a6b9bb807bc7e394
|
[
"tests/test_graph.py::FilterGraphTestCase::test_video_trim_end_of_stream"
] |
[
"tests/test_graph.py::FilterGraphTestCase::test_any_hardware_filter",
"tests/test_graph.py::FilterGraphTestCase::test_audio_trim_metadata",
"tests/test_graph.py::FilterGraphTestCase::test_codec_metadata_transform",
"tests/test_graph.py::FilterGraphTestCase::test_concat_audio_metadata",
"tests/test_graph.py::FilterGraphTestCase::test_concat_video_metadata",
"tests/test_graph.py::FilterGraphTestCase::test_disabled_filters",
"tests/test_graph.py::FilterGraphTestCase::test_ensure_audio",
"tests/test_graph.py::FilterGraphTestCase::test_ensure_video",
"tests/test_graph.py::FilterGraphTestCase::test_filter_graph",
"tests/test_graph.py::FilterGraphTestCase::test_filter_validates_hardware_device",
"tests/test_graph.py::FilterGraphTestCase::test_filter_validates_stream_kind",
"tests/test_graph.py::FilterGraphTestCase::test_overlay_metadata",
"tests/test_graph.py::FilterGraphTestCase::test_scale_changes_metadata",
"tests/test_graph.py::FilterGraphTestCase::test_setpts_metadata",
"tests/test_graph.py::FilterGraphTestCase::test_skip_not_connected_sources",
"tests/test_graph.py::FilterGraphTestCase::test_video_trim_metadata"
] |
{
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-01-30 14:37:24+00:00
|
mit
| 3,377 |
|
just-work__fffw-106
|
diff --git a/fffw/encoding/filters.py b/fffw/encoding/filters.py
index 1f49262..70c8d93 100644
--- a/fffw/encoding/filters.py
+++ b/fffw/encoding/filters.py
@@ -269,16 +269,20 @@ class Trim(AutoFilter):
streams.append(scene.stream)
# intersect scene with trim interval
- start = cast(TS, max(self.start, scene.start))
- end = cast(TS, min(self.end, scene.end))
+ start = cast(TS, max(self.start, scene.position))
+ end = cast(TS, min(self.end, scene.position + scene.duration))
if start < end:
# If intersection is not empty, add intersection to resulting
# scenes list.
# This will allow to detect buffering when multiple scenes are
# reordered in same file: input[3:4] + input[1:2]
- scenes.append(Scene(stream=scene.stream, start=start,
- duration=end - start))
+ offset = start - scene.position
+ scenes.append(Scene(
+ stream=scene.stream,
+ start=scene.start + offset,
+ position=scene.position + offset,
+ duration=end - start))
kwargs = {
'start': start,
@@ -367,8 +371,14 @@ class Concat(Filter):
streams: List[str] = []
frames: int = 0
for meta in metadata:
+ for scene in meta.scenes:
+ scenes.append(Scene(
+ stream=scene.stream,
+ duration=scene.duration,
+ start=scene.start,
+ position=scene.position + duration,
+ ))
duration += meta.duration
- scenes.extend(meta.scenes)
for stream in meta.streams:
if not streams or streams[-1] != stream:
# Add all streams for each concatenated metadata and remove
@@ -422,6 +432,12 @@ class Upload(VideoFilter):
extra_hw_frames: int = param(default=64, init=False)
device: Device = param(skip=True)
+ def __post_init__(self) -> None:
+ if isinstance(self.device, dict):
+ # deserialize back after filter cloning
+ self.device = Device(**self.device)
+ super().__post_init__()
+
def transform(self, *metadata: Meta) -> VideoMeta:
""" Marks a stream as uploaded to a device."""
meta = ensure_video(*metadata)
diff --git a/fffw/graph/meta.py b/fffw/graph/meta.py
index 29beac6..5ed0f15 100644
--- a/fffw/graph/meta.py
+++ b/fffw/graph/meta.py
@@ -143,6 +143,7 @@ class TS(float):
value = seconds + fractional
return super().__new__(cls, value) # type: ignore
+ __hash__ = float.__hash__
__add__ = ts(float.__add__)
__radd__ = ts(float.__radd__)
__sub__ = ts(float.__sub__)
@@ -264,7 +265,9 @@ class Scene:
duration: TS
""" Stream duration."""
start: TS
- """ First frame/sample timestamp for stream."""
+ """ First frame/sample timestamp in source stream."""
+ position: TS
+ """ Position of scene in current stream."""
@property
def end(self) -> TS:
@@ -386,6 +389,7 @@ def audio_meta_data(**kwargs: Any) -> AudioMeta:
stream=stream,
duration=duration,
start=start,
+ position=start,
)
return AudioMeta(
@@ -425,8 +429,9 @@ def video_meta_data(**kwargs: Any) -> VideoMeta:
start = TS(kwargs.get('start', 0))
scene = Scene(
stream=stream,
- start=start,
duration=duration,
+ start=start,
+ position=start,
)
return VideoMeta(
scenes=[scene],
|
just-work/fffw
|
0b9d1fc797ccced2230bbb429d3c351c1484414e
|
diff --git a/tests/test_graph.py b/tests/test_graph.py
index c7db0fd..bed22b0 100644
--- a/tests/test_graph.py
+++ b/tests/test_graph.py
@@ -1,3 +1,4 @@
+from copy import deepcopy
from dataclasses import dataclass, replace
from typing import cast
from unittest import TestCase
@@ -302,6 +303,33 @@ class FilterGraphTestCase(TestCase):
self.assertEqual(round(am.duration * audio_meta.sampling_rate),
am.samples)
+ def test_concat_scenes(self):
+ """
+ Concat shifts scenes start/end timestamps.
+ """
+ video_meta = video_meta_data(duration=1000.0,
+ frame_count=10000,
+ frame_rate=10.0)
+ vs1 = inputs.Stream(VIDEO, meta=video_meta)
+ vs2 = inputs.Stream(VIDEO, meta=video_meta)
+ vs3 = inputs.Stream(VIDEO, meta=video_meta)
+
+ c = Concat(VIDEO, input_count=3)
+ vs1 | c
+ vs2 | c
+ vs3 | c
+ expected = (
+ deepcopy(vs1.meta.scenes) +
+ deepcopy(vs2.meta.scenes) +
+ deepcopy(vs3.meta.scenes)
+ )
+ assert len(expected) == 3
+ current_duration = TS(0)
+ for scene in expected:
+ scene.position += current_duration
+ current_duration += scene.duration
+ self.assertListEqual(c.meta.scenes, expected)
+
def test_video_trim_metadata(self):
"""
Trim filter sets start and changes stream duration.
@@ -389,6 +417,15 @@ class FilterGraphTestCase(TestCase):
except ValueError: # pragma: no cover
self.fail("hardware validation unexpectedly failed")
+ def test_upload_filter_clone(self):
+ """ While cloning Upload filter should preserve Device instance."""
+ cuda = meta.Device(hardware='cuda', name='foo')
+ upload = self.source.video | Upload(device=cuda)
+
+ upload = upload.clone(2)[1]
+ vm = cast(VideoMeta, upload.meta)
+ self.assertEqual(vm.device, cuda)
+
def test_codec_metadata_transform(self):
"""
Codecs parameters applied to stream metadata when using transform.
diff --git a/tests/test_meta_data.py b/tests/test_meta_data.py
index 801af85..d8fed7f 100644
--- a/tests/test_meta_data.py
+++ b/tests/test_meta_data.py
@@ -217,7 +217,8 @@ class MetaDataTestCase(TestCase):
self.assertIsInstance(video, meta.VideoMeta)
scene = meta.Scene(stream=None,
start=meta.TS(0),
- duration=meta.TS(6.740))
+ duration=meta.TS(6.740),
+ position=meta.TS(0))
expected = meta.VideoMeta(
scenes=[scene],
streams=[],
@@ -237,7 +238,8 @@ class MetaDataTestCase(TestCase):
self.assertIsInstance(audio, meta.AudioMeta)
scene = meta.Scene(stream=None,
start=meta.TS(0),
- duration=meta.TS(6.742))
+ duration=meta.TS(6.742),
+ position=meta.TS(0))
expected = meta.AudioMeta(
scenes=[scene],
streams=[],
@@ -301,6 +303,11 @@ class TimeStampTestCase(TestCase):
self.assertIsInstance(ts, meta.TS)
self.assertAlmostEqual(ts.total_seconds(), expected, places=4)
+ def test_ts_hashable(self):
+ marker = object()
+ data = {float(self.ts): marker}
+ self.assertIs(data.get(self.ts), marker)
+
def test_ts_float(self):
self.assertEqual(float(self.ts), self.td.total_seconds())
|
Filter._clone changes attribute types
`Upload._clone()` method changes `device` type from `Device` to `dict`. After that upload instance become unusable.
|
0.0
|
0b9d1fc797ccced2230bbb429d3c351c1484414e
|
[
"tests/test_graph.py::FilterGraphTestCase::test_concat_scenes",
"tests/test_graph.py::FilterGraphTestCase::test_upload_filter_clone",
"tests/test_meta_data.py::MetaDataTestCase::test_parse_streams",
"tests/test_meta_data.py::TimeStampTestCase::test_ts_hashable"
] |
[
"tests/test_graph.py::FilterGraphTestCase::test_any_hardware_filter",
"tests/test_graph.py::FilterGraphTestCase::test_audio_trim_metadata",
"tests/test_graph.py::FilterGraphTestCase::test_codec_metadata_transform",
"tests/test_graph.py::FilterGraphTestCase::test_concat_audio_metadata",
"tests/test_graph.py::FilterGraphTestCase::test_concat_video_metadata",
"tests/test_graph.py::FilterGraphTestCase::test_disabled_filters",
"tests/test_graph.py::FilterGraphTestCase::test_ensure_audio",
"tests/test_graph.py::FilterGraphTestCase::test_ensure_video",
"tests/test_graph.py::FilterGraphTestCase::test_filter_graph",
"tests/test_graph.py::FilterGraphTestCase::test_filter_validates_hardware_device",
"tests/test_graph.py::FilterGraphTestCase::test_filter_validates_stream_kind",
"tests/test_graph.py::FilterGraphTestCase::test_overlay_metadata",
"tests/test_graph.py::FilterGraphTestCase::test_scale_changes_metadata",
"tests/test_graph.py::FilterGraphTestCase::test_setpts_metadata",
"tests/test_graph.py::FilterGraphTestCase::test_skip_not_connected_sources",
"tests/test_graph.py::FilterGraphTestCase::test_video_trim_end_of_stream",
"tests/test_graph.py::FilterGraphTestCase::test_video_trim_metadata",
"tests/test_meta_data.py::MetaDataTestCase::test_subclassing_audio_meta",
"tests/test_meta_data.py::MetaDataTestCase::test_subclassing_video_meta",
"tests/test_meta_data.py::TimeStampTestCase::test_addition",
"tests/test_meta_data.py::TimeStampTestCase::test_compare",
"tests/test_meta_data.py::TimeStampTestCase::test_divmod",
"tests/test_meta_data.py::TimeStampTestCase::test_fields",
"tests/test_meta_data.py::TimeStampTestCase::test_floordiv",
"tests/test_meta_data.py::TimeStampTestCase::test_json_serializable",
"tests/test_meta_data.py::TimeStampTestCase::test_multiplication",
"tests/test_meta_data.py::TimeStampTestCase::test_negate_abs",
"tests/test_meta_data.py::TimeStampTestCase::test_repr",
"tests/test_meta_data.py::TimeStampTestCase::test_str",
"tests/test_meta_data.py::TimeStampTestCase::test_substraction",
"tests/test_meta_data.py::TimeStampTestCase::test_total_seconds",
"tests/test_meta_data.py::TimeStampTestCase::test_truediv",
"tests/test_meta_data.py::TimeStampTestCase::test_ts_deconstruction",
"tests/test_meta_data.py::TimeStampTestCase::test_ts_float",
"tests/test_meta_data.py::TimeStampTestCase::test_ts_init",
"tests/test_meta_data.py::TimeStampTestCase::test_ts_int"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-02-22 11:42:16+00:00
|
mit
| 3,378 |
|
just-work__fffw-122
|
diff --git a/fffw/graph/meta.py b/fffw/graph/meta.py
index 5ed0f15..328d1f0 100644
--- a/fffw/graph/meta.py
+++ b/fffw/graph/meta.py
@@ -381,9 +381,28 @@ class AudioMeta(Meta):
assert abs(self.samples - interval * self.sampling_rate) <= 1
+def maybe_parse_duration(value: Union[str, float, int, None]) -> TS:
+ """
+ Parses duration from mediainfo output, if necessary.
+
+ Some containers store float value and some int, but in both cases (which is different from ffmpeg) value is
+ counted in milliseconds.
+ """
+ if value is None:
+ return TS(0)
+ if isinstance(value, str):
+ try:
+ value = int(value)
+ except ValueError:
+ # prepare seconds for TS constructor
+ value = float(value) / 1000
+ return TS(value)
+
+
def audio_meta_data(**kwargs: Any) -> AudioMeta:
+ duration = maybe_parse_duration(kwargs.get('duration'))
+
stream = kwargs.get('stream')
- duration = TS(kwargs.get('duration', 0))
start = TS(kwargs.get('start', 0))
scene = Scene(
stream=stream,
@@ -405,7 +424,7 @@ def audio_meta_data(**kwargs: Any) -> AudioMeta:
def video_meta_data(**kwargs: Any) -> VideoMeta:
- duration = TS(kwargs.get('duration', 0))
+ duration = maybe_parse_duration(kwargs.get('duration'))
width = int(kwargs.get('width', 0))
height = int(kwargs.get('height', 0))
par = float(kwargs.get('pixel_aspect_ratio', 1.0))
|
just-work/fffw
|
614b9148e11e1ee1d7255fd9b138bf07f2628b0b
|
diff --git a/tests/test_meta_data.py b/tests/test_meta_data.py
index d8fed7f..6ad882b 100644
--- a/tests/test_meta_data.py
+++ b/tests/test_meta_data.py
@@ -2,9 +2,10 @@ import json
from copy import deepcopy
from dataclasses import dataclass, fields
from datetime import timedelta
+from itertools import product
from typing import Iterable, Tuple, Any
from unittest import TestCase
-from itertools import product
+
from pymediainfo import MediaInfo # type: ignore
from fffw.graph import meta
@@ -268,6 +269,17 @@ class MetaDataTestCase(TestCase):
self.assertTrue(fields(ExtendedVideoMeta))
+ def test_mkv_stream_duration(self):
+ """ MKV duration is stored as float and this is a problem for TS constuctor."""
+ original = meta.from_media_info(self.media_info)
+ s = SAMPLE
+ s = s.replace('<Duration>6742</Duration>', '<Duration>6742.000000</Duration>')
+ s = s.replace('<Duration>6740</Duration>', '<Duration>6740.000000</Duration>')
+ streams = meta.from_media_info(MediaInfo(s))
+ self.assertEqual(len(original), len(streams))
+ for s, o in zip(streams, original):
+ self.assertEqual(s.duration, o.duration)
+
class TimeStampTestCase(TestCase):
td: timedelta
|
Wrong MKV duration
In MKV container duration field contains float milliseconds value and in MP4 container it's int.
TS implementation parses int as milliseconds and float as seconds (because of ffmpeg duration meanings).
media info normalizer should perform duration rounding.
|
0.0
|
614b9148e11e1ee1d7255fd9b138bf07f2628b0b
|
[
"tests/test_meta_data.py::MetaDataTestCase::test_mkv_stream_duration"
] |
[
"tests/test_meta_data.py::MetaDataTestCase::test_parse_streams",
"tests/test_meta_data.py::MetaDataTestCase::test_subclassing_audio_meta",
"tests/test_meta_data.py::MetaDataTestCase::test_subclassing_video_meta",
"tests/test_meta_data.py::TimeStampTestCase::test_addition",
"tests/test_meta_data.py::TimeStampTestCase::test_compare",
"tests/test_meta_data.py::TimeStampTestCase::test_divmod",
"tests/test_meta_data.py::TimeStampTestCase::test_fields",
"tests/test_meta_data.py::TimeStampTestCase::test_floordiv",
"tests/test_meta_data.py::TimeStampTestCase::test_json_serializable",
"tests/test_meta_data.py::TimeStampTestCase::test_multiplication",
"tests/test_meta_data.py::TimeStampTestCase::test_negate_abs",
"tests/test_meta_data.py::TimeStampTestCase::test_repr",
"tests/test_meta_data.py::TimeStampTestCase::test_str",
"tests/test_meta_data.py::TimeStampTestCase::test_substraction",
"tests/test_meta_data.py::TimeStampTestCase::test_total_seconds",
"tests/test_meta_data.py::TimeStampTestCase::test_truediv",
"tests/test_meta_data.py::TimeStampTestCase::test_ts_deconstruction",
"tests/test_meta_data.py::TimeStampTestCase::test_ts_float",
"tests/test_meta_data.py::TimeStampTestCase::test_ts_hashable",
"tests/test_meta_data.py::TimeStampTestCase::test_ts_init",
"tests/test_meta_data.py::TimeStampTestCase::test_ts_int"
] |
{
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-08-19 14:30:31+00:00
|
mit
| 3,379 |
|
just-work__fffw-136
|
diff --git a/fffw/encoding/codecs.py b/fffw/encoding/codecs.py
index cfe68f9..4857c38 100644
--- a/fffw/encoding/codecs.py
+++ b/fffw/encoding/codecs.py
@@ -82,6 +82,53 @@ class Copy(outputs.Codec):
:returns: edge pointing to an input stream
"""
+ # Running parent method for side effects like stream validation, like if
+ # Copy is compatible with filter graph.
+ super().connect_edge(edge)
+
+ # Ensure that between source stream and copy codec there is no
+ # processing filters. Only split filter is allowed.
+ src = self._validate_filter_chain(edge)
+
+ if edge.input is src:
+ # Copy codec is being connected directly to Source, no more actions
+ # are needed.
+ return edge
+
+ # There are some Splits between Source and Copy. Current edge is not
+ # needed anymore because new Edge will be added directly to the Source.
+ # Recursively removing it from Splits chain.
+ self._remove_edge(edge)
+ # Connecting Copy to a Source directly using new node.
+ src.connect_dest(self)
+ return self.edge
+
+ def _remove_edge(self, edge: base.Edge) -> None:
+ """
+ Remove edge mentions from graph and current instance like it never
+ existed.
+
+ This method is used for reconnecting Copy codec from an end of Split
+ filter chain directly to Source.
+ """
+ # Remove and edge from existing Split filter chain
+ split = edge.input
+ if not isinstance(split, filters.Split): # pragma: no cover
+ # Method is only called from connect_edge() in case of split
+ # filter presence.
+ raise TypeError("Can't disconnect and edge from real filter")
+ split.disconnect(edge)
+ # As the Edge is thrown away, forgot about it.
+ self._edge = None
+
+ @staticmethod
+ def _validate_filter_chain(edge: base.Edge) -> base.Source:
+ """
+ Ensures that Copy codec is being connected to a filter chain that
+ contains only Split filters.
+
+ :returns: Source stream passed to Copy codec.
+ """
src = edge.input
# Ensure that edge is connected to a source with only split filters
# in between.
@@ -89,8 +136,4 @@ class Copy(outputs.Codec):
src = src.input.input
if not isinstance(src, base.Source):
raise ValueError('copy codec can be connected only to source')
- src = edge.input
- if isinstance(src, filters.Split):
- # Remove current edge from filter graph
- edge = src.disconnect(edge)
- return super().connect_edge(edge)
+ return src
diff --git a/fffw/graph/base.py b/fffw/graph/base.py
index fe5b40d..6881fde 100644
--- a/fffw/graph/base.py
+++ b/fffw/graph/base.py
@@ -93,9 +93,11 @@ class Dest(Traversable):
:return Edge: connected edge
"""
if not isinstance(edge, Edge):
- raise ValueError("Only edge allowed")
+ raise TypeError("Only edge allowed")
if self._edge is not None:
- raise RuntimeError("Dest is already connected to %s" % self._edge)
+ raise RuntimeError("Dest input edge is already connected")
+ if edge.output is not self:
+ raise ValueError("Edge output is connected to another dest")
self._edge = edge
return edge
@@ -392,7 +394,9 @@ class Node(Traversable, abc.ABC):
:returns: connected edge
"""
if not isinstance(edge, Edge):
- raise ValueError("only edge allowed")
+ raise TypeError("only edge allowed")
+ if edge.output is not self:
+ raise ValueError("Edge output is connected to another node")
self.inputs[self.inputs.index(None)] = edge
return edge
|
just-work/fffw
|
19f969ee55c1ed08a228af38eab116db2d9aea81
|
diff --git a/tests/test_graph.py b/tests/test_graph.py
index c6edf1b..983a7e2 100644
--- a/tests/test_graph.py
+++ b/tests/test_graph.py
@@ -7,6 +7,7 @@ from fffw.encoding import inputs, outputs, codecs
from fffw.encoding.complex import FilterComplex
from fffw.encoding.filters import *
from fffw.graph import *
+from fffw.graph import base
from fffw.wrapper import param
@@ -35,6 +36,71 @@ class FdkAAC(codecs.AudioCodec):
return replace(ensure_audio(*metadata), bitrate=self.bitrate)
+class SourceImpl(base.Source):
+
+ @property
+ def name(self) -> str: # pragma: no cover
+ return ''
+
+
+class NodeImpl(base.Node):
+
+ @property
+ def args(self) -> str: # pragma: no cover
+ return ''
+
+
+class DestImpl(base.Dest):
+ pass
+
+
+class GraphBaseTestCase(TestCase):
+ def setUp(self) -> None:
+ super().setUp()
+ self.source = SourceImpl(VIDEO)
+ self.node = NodeImpl()
+ self.another = NodeImpl()
+ self.dest = DestImpl()
+ self.source_edge = base.Edge(self.source, self.node)
+ self.inter_edge = base.Edge(self.node, self.another)
+ self.dest_edge = base.Edge(self.another, self.dest)
+
+ def test_node_connect_edge_validation(self):
+ """
+ Checks edge validation for Node.
+ """
+
+ with self.subTest("only edge allowed"):
+ with self.assertRaises(TypeError):
+ self.node.connect_edge(object()) # type: ignore
+
+ with self.subTest("edge output cross-link"):
+ with self.assertRaises(ValueError):
+ self.node.connect_edge(self.dest_edge)
+
+ with self.subTest("success"):
+ self.node.connect_edge(self.source_edge)
+
+ def test_dest_connect_edge_validation(self):
+ """
+ Checks edge validation for Dest.
+ """
+ with self.subTest("only edge allowed"):
+ with self.assertRaises(TypeError):
+ self.dest.connect_edge(object()) # type: ignore
+
+ with self.subTest("edge output cross-link"):
+ with self.assertRaises(ValueError):
+ self.dest.connect_edge(self.source_edge)
+
+ with self.subTest("success"):
+ self.dest.connect_edge(self.dest_edge)
+
+ with self.subTest("slot is busy"):
+ with self.assertRaises(RuntimeError):
+ self.dest.connect_edge(self.dest_edge)
+
+
class FilterGraphBaseTestCase(TestCase):
def setUp(self) -> None:
@@ -322,9 +388,9 @@ class FilterGraphTestCase(FilterGraphBaseTestCase):
vs2 | c
vs3 | c
expected = (
- deepcopy(vs1.meta.scenes) +
- deepcopy(vs2.meta.scenes) +
- deepcopy(vs3.meta.scenes)
+ deepcopy(vs1.meta.scenes) +
+ deepcopy(vs2.meta.scenes) +
+ deepcopy(vs3.meta.scenes)
)
assert len(expected) == 3
current_duration = TS(0)
@@ -523,12 +589,41 @@ class CopyCodecTestCase(FilterGraphBaseTestCase):
s1 = split
s2 = split | Scale(1920, 1080)
- s1 > codecs.Copy(kind=VIDEO)
+ copy = s1 > codecs.Copy(kind=VIDEO)
# one output left
self.assertListEqual(split.outputs, [s2.input])
# split is disabled because of single output
self.assertFalse(split.enabled)
+ # copy codec is connected to source
+ self.assertIs(copy.edge.input, self.source.video)
+
+ def test_split_disconnect_transient(self):
+ """
+ With multiple splits, copy codec is being disconnected from all of them.
+ """
+ video = self.source.video
+ inter = video | Split(VIDEO, output_count=1)
+ split = inter | Split(VIDEO, output_count=2)
+ s1 = split
+ s2 = split | Scale(1920, 1080)
+
+ copy = s1 > codecs.Copy(kind=VIDEO)
+
+ # one output left
+ self.assertListEqual(split.outputs, [s2.input])
+ # split is disabled because of single output
+ self.assertFalse(split.enabled)
+
+ # intermediate split is still connected to another split
+ self.assertIs(inter.output.output, split)
+ # copy codec is connected to source
+ self.assertIs(copy.edge.input, video)
+ # source is still connected to split
+ edges = video._outputs
+ expected = [copy.edge, inter.input]
+ self.assertEqual(len(edges), 2)
+ self.assertSetEqual(set(edges), set(expected))
def test_split_disconnect_on_single_output(self):
"""
|
Copy codec bug
```
source - split(1) - split(3) - Copy x 3
```
In this case Copy codec is connected to split(1) instead of source, followed by some errors.
```
src = edge.input
# Ensure that edge is connected to a source with only split filters
# in between.
source_edge = edge
while isinstance(src, filters.Split):
source_edge = src.input
src = source_edge.input
if not isinstance(src, base.Source):
raise ValueError('copy codec can be connected only to source')
src = edge.input
if isinstance(src, filters.Split):
# Remove current edge from filter graph
src.disconnect(edge)
return super().connect_edge(source_edge)
```
Source edge must be used instead of current one.
|
0.0
|
19f969ee55c1ed08a228af38eab116db2d9aea81
|
[
"tests/test_graph.py::GraphBaseTestCase::test_dest_connect_edge_validation",
"tests/test_graph.py::GraphBaseTestCase::test_node_connect_edge_validation",
"tests/test_graph.py::CopyCodecTestCase::test_split_disconnect_transient"
] |
[
"tests/test_graph.py::FilterGraphTestCase::test_any_hardware_filter",
"tests/test_graph.py::FilterGraphTestCase::test_audio_trim_metadata",
"tests/test_graph.py::FilterGraphTestCase::test_codec_metadata_transform",
"tests/test_graph.py::FilterGraphTestCase::test_concat_audio_metadata",
"tests/test_graph.py::FilterGraphTestCase::test_concat_scenes",
"tests/test_graph.py::FilterGraphTestCase::test_concat_video_metadata",
"tests/test_graph.py::FilterGraphTestCase::test_disabled_filters",
"tests/test_graph.py::FilterGraphTestCase::test_ensure_audio",
"tests/test_graph.py::FilterGraphTestCase::test_ensure_video",
"tests/test_graph.py::FilterGraphTestCase::test_filter_graph",
"tests/test_graph.py::FilterGraphTestCase::test_filter_validates_hardware_device",
"tests/test_graph.py::FilterGraphTestCase::test_filter_validates_stream_kind",
"tests/test_graph.py::FilterGraphTestCase::test_overlay_metadata",
"tests/test_graph.py::FilterGraphTestCase::test_scale_changes_metadata",
"tests/test_graph.py::FilterGraphTestCase::test_setpts_metadata",
"tests/test_graph.py::FilterGraphTestCase::test_skip_not_connected_sources",
"tests/test_graph.py::FilterGraphTestCase::test_split_args",
"tests/test_graph.py::FilterGraphTestCase::test_split_enable",
"tests/test_graph.py::FilterGraphTestCase::test_upload_filter_clone",
"tests/test_graph.py::FilterGraphTestCase::test_video_trim_end_of_stream",
"tests/test_graph.py::FilterGraphTestCase::test_video_trim_metadata",
"tests/test_graph.py::CopyCodecTestCase::test_copy_codec_filter_forbidden",
"tests/test_graph.py::CopyCodecTestCase::test_copy_codec_kind_required",
"tests/test_graph.py::CopyCodecTestCase::test_copy_codec_transient_filter_forbidden",
"tests/test_graph.py::CopyCodecTestCase::test_deny_disconnect_from_other_filters",
"tests/test_graph.py::CopyCodecTestCase::test_disconnect_split_without_parent",
"tests/test_graph.py::CopyCodecTestCase::test_end_disconnect_on_source",
"tests/test_graph.py::CopyCodecTestCase::test_split_disconnect_on_copy_codec",
"tests/test_graph.py::CopyCodecTestCase::test_split_disconnect_on_single_output"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-02-28 10:22:38+00:00
|
mit
| 3,380 |
|
just-work__fffw-174
|
diff --git a/docs/requirements.txt b/docs/requirements.txt
index d089081..01475f4 100644
--- a/docs/requirements.txt
+++ b/docs/requirements.txt
@@ -1,4 +1,4 @@
-sphinx==5.1.1
+sphinx==7.1.2
sphinxcontrib-blockdiag==3.0.0
-pymediainfo==5.1.0
+pymediainfo==6.0.1
funcparserlib==1.0.1
diff --git a/fffw/encoding/outputs.py b/fffw/encoding/outputs.py
index 968db2f..92e0ba0 100644
--- a/fffw/encoding/outputs.py
+++ b/fffw/encoding/outputs.py
@@ -1,11 +1,12 @@
+from collections import defaultdict
from dataclasses import dataclass
-from itertools import chain
-from typing import List, cast, Optional, Iterable, Any
+from typing import List, cast, Optional, Iterable, Any, Tuple, Dict
-from fffw.graph.meta import AUDIO, VIDEO, StreamType
+from fffw.encoding import mixins
from fffw.graph import base
+from fffw.graph.meta import AUDIO, VIDEO, StreamType
from fffw.wrapper import BaseWrapper, ensure_binary, param
-from fffw.encoding import mixins
+
__all__ = [
'Codec',
'Output',
@@ -57,9 +58,22 @@ class Codec(mixins.StreamValidationMixin, base.Dest, BaseWrapper):
return bool(self.edge)
def get_args(self) -> List[bytes]:
+ """
+ Insert map argument before all rest codec params.
+ """
args = ['-map', self.map]
return ensure_binary(args) + super().get_args()
+ def as_pairs(self) -> List[Tuple[Optional[str], Optional[str]]]:
+ """
+ Add stream index suffix to all named params
+ """
+ pairs = super().as_pairs()
+ result = []
+ for p, v in pairs:
+ result.append((p and f'{p}:{self.index}', v))
+ return result
+
def clone(self, count: int = 1) -> List["Codec"]:
"""
Creates multiple copies of self to reuse it as output node for multiple
@@ -202,8 +216,6 @@ class OutputList(list):
:param outputs: list of output files
"""
super().__init__()
- self.__video_index = 0
- self.__audio_index = 0
self.extend(outputs)
@property
@@ -219,8 +231,7 @@ class OutputList(list):
:param output: output file
"""
- for codec in output.codecs:
- self.__set_index(codec)
+ self.__set_index(output)
super().append(output)
def extend(self, outputs: Iterable[Output]) -> None:
@@ -229,20 +240,25 @@ class OutputList(list):
:param outputs: list of output files
"""
- for codec in chain(*map(lambda output: output.codecs, outputs)):
- self.__set_index(codec)
+ for output in outputs:
+ self.__set_index(output)
super().extend(outputs)
def get_args(self) -> List[bytes]:
+ """
+ Combine all output params together
+ """
result: List[bytes] = []
- for source in self:
- result.extend(source.get_args())
+ for output in self:
+ result.extend(output.get_args())
return result
- def __set_index(self, codec: Codec) -> None:
- if codec.kind == VIDEO:
- codec.index = self.__video_index
- self.__video_index += 1
- else:
- codec.index = self.__audio_index
- self.__audio_index += 1
+ @staticmethod
+ def __set_index(output: Output) -> None:
+ """
+ Enumerate codecs in output with a stream index in this output
+ """
+ indices: Dict[StreamType, int] = defaultdict(lambda: 0)
+ for codec in output.codecs:
+ codec.index = indices[codec.kind]
+ indices[codec.kind] += 1
diff --git a/requirements.txt b/requirements.txt
index 13c8d11..b67db88 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -1,1 +1,1 @@
-pymediainfo==5.1.0
+pymediainfo==6.0.1
|
just-work/fffw
|
ee8cf9ba7fd07313aca7dfab0155d0982f65cfa9
|
diff --git a/tests/test_ffmpeg.py b/tests/test_ffmpeg.py
index 9408ae8..36ce86b 100644
--- a/tests/test_ffmpeg.py
+++ b/tests/test_ffmpeg.py
@@ -109,12 +109,12 @@ class FFMPEGTestCase(BaseTestCase):
'-filter_complex',
'[0:v:0]scale=w=640:h=360[vout0];[0:a:0]asplit[aout0][aout1]',
- '-map', '[vout0]', '-c:v', 'libx264', '-b:v', '3600000',
- '-map', '[aout0]', '-c:a', 'aac', '-b:a', '192000',
+ '-map', '[vout0]', '-c:v:0', 'libx264', '-b:v:0', '3600000',
+ '-map', '[aout0]', '-c:a:0', 'aac', '-b:a:0', '192000',
'output.mp4',
- '-map', '[aout1]', '-c:a', 'libmp3lame', '-b:a', '394000',
+ '-map', '[aout1]', '-c:a:0', 'libmp3lame', '-b:a:0', '394000',
'-vn',
'/tmp/out.mp3'
)
@@ -164,11 +164,47 @@ class FFMPEGTestCase(BaseTestCase):
'-i', 'source.mp4',
'-filter_complex',
'[0:v:0]scale=w=640:h=360[vout0]',
- '-map', '[vout0]', '-c:v', 'libx264', '-b:v', '3600000',
- '-map', '0:a:0', '-c:a', 'aac', '-b:a', '192000',
+ '-map', '[vout0]', '-c:v:0', 'libx264', '-b:v:0', '3600000',
+ '-map', '0:a:0', '-c:a:0', 'aac', '-b:a:0', '192000',
'output.mp4'
)
+ def test_set_stream_index_for_codec_params(self):
+ """ Codec params in same file should be properly indexed."""
+ ff = self.ffmpeg
+ ff < self.source
+
+ split = ff.video | filters.Scale(640, 360) | filters.Split(VIDEO, 4)
+ split > self.video_codec
+ vc1 = X264(bitrate=1800000)
+ vc2 = X264(bitrate=900000)
+ vc3 = X264(bitrate=450000)
+
+ split > vc1
+ split > vc2
+ split > vc3
+
+ output1 = outputs.output_file('first.mp4', self.video_codec, vc1)
+ output2 = outputs.output_file('second.mp4', vc2, vc3)
+
+ ff > output1
+ ff > output2
+
+ self.assert_ffmpeg_args(
+ '-i', 'source.mp4',
+ '-filter_complex',
+ '[0:v:0]scale=w=640:h=360[v:scale0];'
+ '[v:scale0]split=4[vout0][vout1][vout2][vout3]',
+ '-map', '[vout0]', '-c:v:0', 'libx264', '-b:v:0', '3600000',
+ '-map', '[vout1]', '-c:v:1', 'libx264', '-b:v:1', '1800000',
+ '-an',
+ 'first.mp4',
+ '-map', '[vout2]', '-c:v:0', 'libx264', '-b:v:0', '900000',
+ '-map', '[vout3]', '-c:v:1', 'libx264', '-b:v:1', '450000',
+ '-an',
+ 'second.mp4'
+ )
+
def test_bypass_disabled_filter(self):
""" Audio stream bypass mode."""
ff = self.ffmpeg
@@ -182,8 +218,8 @@ class FFMPEGTestCase(BaseTestCase):
self.assert_ffmpeg_args(
'-i', 'source.mp4',
- '-map', '0:v:0', '-c:v', 'libx264', '-b:v', '3600000',
- '-map', '0:a:0', '-c:a', 'aac', '-b:a', '192000',
+ '-map', '0:v:0', '-c:v:0', 'libx264', '-b:v:0', '3600000',
+ '-map', '0:a:0', '-c:a:0', 'aac', '-b:a:0', '192000',
'output.mp4'
)
@@ -200,7 +236,7 @@ class FFMPEGTestCase(BaseTestCase):
'-i', 'source.mp4',
'-filter_complex',
'[0:v:0]scale=w=640:h=360[vout0]',
- '-map', '[vout0]', '-c:v', 'libx264',
+ '-map', '[vout0]', '-c:v:0', 'libx264',
'-an',
'out.mp4'
)
@@ -213,8 +249,8 @@ class FFMPEGTestCase(BaseTestCase):
self.assert_ffmpeg_args(
'-i', 'source.mp4',
- '-map', '0:v:0', '-c:v', 'libx264', '-b:v', '3600000',
- '-map', '0:a:0', '-c:a', 'aac', '-b:a', '192000',
+ '-map', '0:v:0', '-c:v:0', 'libx264', '-b:v:0', '3600000',
+ '-map', '0:a:0', '-c:a:0', 'aac', '-b:a:0', '192000',
'output.mp4'
)
@@ -244,8 +280,8 @@ class FFMPEGTestCase(BaseTestCase):
'[v:scale0][v:scale1]overlay[vout0];'
'[1:v:0]scale=w=1280:h=720[v:scale1];'
'[1:a:0]volume=-20.00[aout0]',
- '-map', '[vout0]', '-c:v', 'libx264', '-b:v', '3600000',
- '-map', '[aout0]', '-c:a', 'aac', '-b:a', '192000',
+ '-map', '[vout0]', '-c:v:0', 'libx264', '-b:v:0', '3600000',
+ '-map', '[aout0]', '-c:a:0', 'aac', '-b:a:0', '192000',
'output.mp4'
)
@@ -265,9 +301,9 @@ class FFMPEGTestCase(BaseTestCase):
'-filter_complex',
'[0:a:0]volume=20.00[aout0]',
'-map', '0:v:0',
- '-c:v', 'copy',
+ '-c:v:0', 'copy',
'-map', '[aout0]',
- '-c:a', 'aac', '-b:a', '128000',
+ '-c:a:0', 'aac', '-b:a:0', '128000',
'/tmp/out.flv'
)
@@ -289,14 +325,14 @@ class FFMPEGTestCase(BaseTestCase):
self.assert_ffmpeg_args(
'-i', 'source.mp4',
'-map', '0:v:0',
- '-c:v', 'libx264', '-b:v', '3600000',
+ '-c:v:0', 'libx264', '-b:v:0', '3600000',
'-map', '0:a:0',
- '-c:a', 'aac', '-b:a', '192000',
+ '-c:a:0', 'aac', '-b:a:0', '192000',
'output.mp4',
'-map', '0:v:0',
- '-c:v', 'copy',
+ '-c:v:0', 'copy',
'-map', '0:a:0',
- '-c:a', 'copy',
+ '-c:a:0', 'copy',
'/tmp/out1.flv',
)
@@ -321,14 +357,14 @@ class FFMPEGTestCase(BaseTestCase):
'-filter_complex',
'[0:v:0]scale=w=640:h=360[vout0]',
'-map', '0:v:0',
- '-c:v', 'copy',
+ '-c:v:0', 'copy',
'-map', '0:a:0',
- '-c:a', 'copy',
+ '-c:a:0', 'copy',
'/tmp/copy.flv',
'-map', '[vout0]',
- '-c:v', 'libx264',
+ '-c:v:0', 'libx264',
'-map', '0:a:0',
- '-c:a', 'aac',
+ '-c:a:0', 'aac',
'/tmp/out.flv')
def test_transcoding_without_graph(self):
@@ -361,9 +397,9 @@ class FFMPEGTestCase(BaseTestCase):
'ffmpeg',
'-i', '/tmp/input.mp4',
'-map', '0:v:0',
- '-c:v', 'libx264',
+ '-c:v:0', 'libx264',
'-map', '0:a:0',
- '-c:a', 'aac',
+ '-c:a:0', 'aac',
'-f', 'tee',
'[f=hls:hls_time=2]http://ya.ru/1.m3u8|'
'[f=hls:hls_list_size=5]http://ya.ru/2.m3u8'
@@ -398,8 +434,8 @@ class FFMPEGTestCase(BaseTestCase):
"[v:scale0]setsar=1[v:setsar0];"
"[v:setsar0][1:v:0]concat[vout0];"
"[0:a:0][1:a:0]concat=v=0:a=1:n=2[aout0]",
- '-map', '[vout0]', '-c:v', 'libx264', '-b:v', '3600000',
- '-map', '[aout0]', '-c:a', 'aac', '-b:a', '192000',
+ '-map', '[vout0]', '-c:v:0', 'libx264', '-b:v:0', '3600000',
+ '-map', '[aout0]', '-c:a:0', 'aac', '-b:a:0', '192000',
'output.mp4'
)
diff --git a/tests/test_vector.py b/tests/test_vector.py
index 57047bf..b950d50 100644
--- a/tests/test_vector.py
+++ b/tests/test_vector.py
@@ -125,11 +125,11 @@ class VectorTestCase(BaseTestCase):
""" Checks that vector works correctly without filter graph."""
self.assert_simd_args(
'-i', 'input.mp4',
- '-map', '0:v:0', '-c:v', 'libx264',
- '-map', '0:a:0', '-c:a', 'aac', '-b:a', '64000',
+ '-map', '0:v:0', '-c:v:0', 'libx264',
+ '-map', '0:a:0', '-c:a:0', 'aac', '-b:a:0', '64000',
'output1.mp4',
- '-map', '0:v:0', '-c:v', 'libx265',
- '-map', '0:a:0', '-c:a', 'libfdk_aac',
+ '-map', '0:v:0', '-c:v:0', 'libx265',
+ '-map', '0:a:0', '-c:a:0', 'libfdk_aac',
'output2.mp5')
def test_filter_graph_pass_through(self):
@@ -139,11 +139,11 @@ class VectorTestCase(BaseTestCase):
self.assert_simd_args(
'-i', 'input.mp4',
- '-map', '0:v:0', '-c:v', 'libx264',
- '-map', '0:a:0', '-c:a', 'aac', '-b:a', '64000',
+ '-map', '0:v:0', '-c:v:0', 'libx264',
+ '-map', '0:a:0', '-c:a:0', 'aac', '-b:a:0', '64000',
'output1.mp4',
- '-map', '0:v:0', '-c:v', 'libx265',
- '-map', '0:a:0', '-c:a', 'libfdk_aac',
+ '-map', '0:v:0', '-c:v:0', 'libx265',
+ '-map', '0:a:0', '-c:a:0', 'libfdk_aac',
'output2.mp5')
def test_single_quality_copy_pass_through(self):
@@ -161,11 +161,11 @@ class VectorTestCase(BaseTestCase):
'-i', 'input.mp4',
'-filter_complex',
'[0:v:0]scale=w=1920:h=1080[vout0]',
- '-map', '[vout0]', '-c:v', 'libx264',
- '-map', '0:a:0', '-c:a', 'aac', '-b:a', '64000',
+ '-map', '[vout0]', '-c:v:0', 'libx264',
+ '-map', '0:a:0', '-c:a:0', 'aac', '-b:a:0', '64000',
'output1.mp4',
- '-map', '0:v:0', '-c:v', 'copy',
- '-map', '0:a:0', '-c:a', 'libfdk_aac',
+ '-map', '0:v:0', '-c:v:0', 'copy',
+ '-map', '0:a:0', '-c:a:0', 'libfdk_aac',
'output2.mp5')
def test_same_filter_for_all_streams(self):
@@ -178,11 +178,11 @@ class VectorTestCase(BaseTestCase):
'-filter_complex',
'[0:a:0]volume=30.00[a:volume0];'
'[a:volume0]asplit[aout0][aout1]',
- '-map', '0:v:0', '-c:v', 'libx264',
- '-map', '[aout0]', '-c:a', 'aac', '-b:a', '64000',
+ '-map', '0:v:0', '-c:v:0', 'libx264',
+ '-map', '[aout0]', '-c:a:0', 'aac', '-b:a:0', '64000',
'output1.mp4',
- '-map', '0:v:0', '-c:v', 'libx265',
- '-map', '[aout1]', '-c:a', 'libfdk_aac',
+ '-map', '0:v:0', '-c:v:0', 'libx265',
+ '-map', '[aout1]', '-c:a:0', 'libfdk_aac',
'output2.mp5')
def test_same_filter_with_mask(self):
@@ -195,11 +195,11 @@ class VectorTestCase(BaseTestCase):
'-filter_complex',
'[0:a:0]asplit[a:asplit0][aout0];'
'[a:asplit0]volume=30.00[aout1]',
- '-map', '0:v:0', '-c:v', 'libx264',
- '-map', '[aout0]', '-c:a', 'aac', '-b:a', '64000',
+ '-map', '0:v:0', '-c:v:0', 'libx264',
+ '-map', '[aout0]', '-c:a:0', 'aac', '-b:a:0', '64000',
'output1.mp4',
- '-map', '0:v:0', '-c:v', 'libx265',
- '-map', '[aout1]', '-c:a', 'libfdk_aac',
+ '-map', '0:v:0', '-c:v:0', 'libx265',
+ '-map', '[aout1]', '-c:a:0', 'libfdk_aac',
'output2.mp5')
def test_multiple_disabled_filters(self):
@@ -210,11 +210,11 @@ class VectorTestCase(BaseTestCase):
'input.mp4',
'-filter_complex',
'[0:a:0]asplit[aout0][aout1]',
- '-map', '0:v:0', '-c:v', 'libx264',
- '-map', '[aout0]', '-c:a', 'aac', '-b:a', '64000',
+ '-map', '0:v:0', '-c:v:0', 'libx264',
+ '-map', '[aout0]', '-c:a:0', 'aac', '-b:a:0', '64000',
'output1.mp4',
- '-map', '0:v:0', '-c:v', 'libx265',
- '-map', '[aout1]', '-c:a', 'libfdk_aac',
+ '-map', '0:v:0', '-c:v:0', 'libx265',
+ '-map', '[aout1]', '-c:a:0', 'libfdk_aac',
'output2.mp5')
def test_apply_filter_with_params_vector(self):
@@ -227,11 +227,11 @@ class VectorTestCase(BaseTestCase):
'[0:a:0]asplit[a:asplit0][a:asplit1];'
'[a:asplit0]volume=20.00[aout0];'
'[a:asplit1]volume=30.00[aout1]',
- '-map', '0:v:0', '-c:v', 'libx264',
- '-map', '[aout0]', '-c:a', 'aac', '-b:a', '64000',
+ '-map', '0:v:0', '-c:v:0', 'libx264',
+ '-map', '[aout0]', '-c:a:0', 'aac', '-b:a:0', '64000',
'output1.mp4',
- '-map', '0:v:0', '-c:v', 'libx265',
- '-map', '[aout1]', '-c:a', 'libfdk_aac',
+ '-map', '0:v:0', '-c:v:0', 'libx265',
+ '-map', '[aout1]', '-c:a:0', 'libfdk_aac',
'output2.mp5')
def test_apply_filter_with_equal_params(self):
@@ -243,11 +243,11 @@ class VectorTestCase(BaseTestCase):
'-filter_complex',
'[0:a:0]volume=30.00[a:volume0];'
'[a:volume0]asplit[aout0][aout1]',
- '-map', '0:v:0', '-c:v', 'libx264',
- '-map', '[aout0]', '-c:a', 'aac', '-b:a', '64000',
+ '-map', '0:v:0', '-c:v:0', 'libx264',
+ '-map', '[aout0]', '-c:a:0', 'aac', '-b:a:0', '64000',
'output1.mp4',
- '-map', '0:v:0', '-c:v', 'libx265',
- '-map', '[aout1]', '-c:a', 'libfdk_aac',
+ '-map', '0:v:0', '-c:v:0', 'libx265',
+ '-map', '[aout1]', '-c:a:0', 'libfdk_aac',
'output2.mp5')
def test_split_filter_if_vector_differs(self):
@@ -266,11 +266,11 @@ class VectorTestCase(BaseTestCase):
'[a:volume0]stub[aout0];'
'[a:asplit1]volume=30.00[a:volume1];'
'[a:volume1]stub[aout1]',
- '-map', '0:v:0', '-c:v', 'libx264',
- '-map', '[aout0]', '-c:a', 'aac', '-b:a', '64000',
+ '-map', '0:v:0', '-c:v:0', 'libx264',
+ '-map', '[aout0]', '-c:a:0', 'aac', '-b:a:0', '64000',
'output1.mp4',
- '-map', '0:v:0', '-c:v', 'libx265',
- '-map', '[aout1]', '-c:a', 'libfdk_aac',
+ '-map', '0:v:0', '-c:v:0', 'libx265',
+ '-map', '[aout1]', '-c:a:0', 'libfdk_aac',
'output2.mp5')
def test_clone_inputs_for_destination_filter(self):
@@ -300,11 +300,11 @@ class VectorTestCase(BaseTestCase):
'[v:another0]split[v:split4][v:split5];'
'[v:split4][v:scale0]overlay[vout0];'
'[v:split5][v:scale1]overlay[vout1]',
- '-map', '[vout0]', '-c:v', 'libx264',
- '-map', '0:a:0', '-c:a', 'aac', '-b:a', '64000',
+ '-map', '[vout0]', '-c:v:0', 'libx264',
+ '-map', '0:a:0', '-c:a:0', 'aac', '-b:a:0', '64000',
'output1.mp4',
- '-map', '[vout1]', '-c:v', 'libx265',
- '-map', '0:a:0', '-c:a', 'libfdk_aac',
+ '-map', '[vout1]', '-c:v:0', 'libx265',
+ '-map', '0:a:0', '-c:a:0', 'libfdk_aac',
'output2.mp5')
def test_clone_streams(self):
@@ -328,11 +328,11 @@ class VectorTestCase(BaseTestCase):
'[v:split1]scale=w=640:h=360[v:scale1];'
'[v:split2][v:scale0]overlay[vout0];'
'[v:split3][v:scale1]overlay[vout1]',
- '-map', '[vout0]', '-c:v', 'libx264',
- '-map', '0:a:0', '-c:a', 'aac', '-b:a', '64000',
+ '-map', '[vout0]', '-c:v:0', 'libx264',
+ '-map', '0:a:0', '-c:a:0', 'aac', '-b:a:0', '64000',
'output1.mp4',
- '-map', '[vout1]', '-c:v', 'libx265',
- '-map', '0:a:0', '-c:a', 'libfdk_aac',
+ '-map', '[vout1]', '-c:v:0', 'libx265',
+ '-map', '0:a:0', '-c:a:0', 'libfdk_aac',
'output2.mp5'
)
@@ -352,11 +352,11 @@ class VectorTestCase(BaseTestCase):
'-filter_complex',
'[0:v:0]split[v:split0][vout0];'
'[1:v:0][v:split0]overlay[vout1]',
- '-map', '[vout1]', '-c:v', 'libx264',
- '-map', '0:a:0', '-c:a', 'aac', '-b:a', '64000',
+ '-map', '[vout1]', '-c:v:0', 'libx264',
+ '-map', '0:a:0', '-c:a:0', 'aac', '-b:a:0', '64000',
'output1.mp4',
- '-map', '[vout0]', '-c:v', 'libx265',
- '-map', '0:a:0', '-c:a', 'libfdk_aac',
+ '-map', '[vout0]', '-c:v:0', 'libx265',
+ '-map', '0:a:0', '-c:a:0', 'libfdk_aac',
'output2.mp5'
)
@@ -383,11 +383,11 @@ class VectorTestCase(BaseTestCase):
'[0:a:0]asplit[a:asplit0][aout0];'
'[1:v:0][v:split0]concat[vout1];'
'[1:a:0][a:asplit0]concat=v=0:a=1:n=2[aout1]',
- '-map', '[vout1]', '-c:v', 'libx264',
- '-map', '[aout1]', '-c:a', 'aac', '-b:a', '64000',
+ '-map', '[vout1]', '-c:v:0', 'libx264',
+ '-map', '[aout1]', '-c:a:0', 'aac', '-b:a:0', '64000',
'output1.mp4',
- '-map', '[vout0]', '-c:v', 'libx265',
- '-map', '[aout0]', '-c:a', 'libfdk_aac',
+ '-map', '[vout0]', '-c:v:0', 'libx265',
+ '-map', '[aout0]', '-c:a:0', 'libfdk_aac',
'output2.mp5')
def test_connect_filter_to_a_vector(self):
@@ -406,11 +406,11 @@ class VectorTestCase(BaseTestCase):
'[v:overlay0]split[vout0][vout1];'
'[1:v:0]scale=w=120:h=120[v:scale0];'
'[0:v:0][v:scale0]overlay[v:overlay0]',
- '-map', '[vout0]', '-c:v', 'libx264',
- '-map', '0:a:0', '-c:a', 'aac', '-b:a', '64000',
+ '-map', '[vout0]', '-c:v:0', 'libx264',
+ '-map', '0:a:0', '-c:a:0', 'aac', '-b:a:0', '64000',
'output1.mp4',
- '-map', '[vout1]', '-c:v', 'libx265',
- '-map', '0:a:0', '-c:a', 'libfdk_aac',
+ '-map', '[vout1]', '-c:v:0', 'libx265',
+ '-map', '0:a:0', '-c:a:0', 'libfdk_aac',
'output2.mp5'
)
@@ -437,14 +437,14 @@ class VectorTestCase(BaseTestCase):
'[v:concat0]scale=w=1820:h=720[v:scale0];'
'[1:v:0][1:v:0]concat[v:concat0]',
'-map', '[vout0]',
- '-c:v', 'libx264',
+ '-c:v:0', 'libx264',
'-map', '[aout0]',
- '-c:a', 'aac', '-b:a', '64000',
+ '-c:a:0', 'aac', '-b:a:0', '64000',
'output1.mp4',
'-map', '[vout1]',
- '-c:v', 'libx265',
+ '-c:v:0', 'libx265',
'-map', '[aout1]',
- '-c:a', 'libfdk_aac',
+ '-c:a:0', 'libfdk_aac',
'output2.mp5'
)
|
Multiple options specified for stream
```
Multiple -c, -codec, -acodec, -vcodec, -scodec or -dcodec options specified for stream 0, only the last option '-c:v libx264' will be used.
```
since ffmpeg-4.4 (or even earlier) to set different options for different streams in same file, output stream index suffix should be used (like '-c:v:0 libx264')
|
0.0
|
ee8cf9ba7fd07313aca7dfab0155d0982f65cfa9
|
[
"tests/test_ffmpeg.py::FFMPEGTestCase::test_bypass_disabled_filter",
"tests/test_ffmpeg.py::FFMPEGTestCase::test_bypass_with_filter_complex",
"tests/test_ffmpeg.py::FFMPEGTestCase::test_bypass_without_filter_complex",
"tests/test_ffmpeg.py::FFMPEGTestCase::test_concat",
"tests/test_ffmpeg.py::FFMPEGTestCase::test_ffmpeg",
"tests/test_ffmpeg.py::FFMPEGTestCase::test_handle_codec_copy",
"tests/test_ffmpeg.py::FFMPEGTestCase::test_handle_codec_copy_with_other_filters",
"tests/test_ffmpeg.py::FFMPEGTestCase::test_input_stream_naming",
"tests/test_ffmpeg.py::FFMPEGTestCase::test_no_audio_if_no_codecs_found",
"tests/test_ffmpeg.py::FFMPEGTestCase::test_reuse_input_files",
"tests/test_ffmpeg.py::FFMPEGTestCase::test_set_stream_index_for_codec_params",
"tests/test_vector.py::VectorTestCase::test_apply_filter_with_equal_params",
"tests/test_vector.py::VectorTestCase::test_apply_filter_with_params_vector",
"tests/test_vector.py::VectorTestCase::test_clone_inputs_for_destination_filter",
"tests/test_vector.py::VectorTestCase::test_clone_streams",
"tests/test_vector.py::VectorTestCase::test_connect_filter_to_a_vector",
"tests/test_vector.py::VectorTestCase::test_connect_stream_to_simd",
"tests/test_vector.py::VectorTestCase::test_filter_graph_pass_through",
"tests/test_vector.py::VectorTestCase::test_multiple_disabled_filters",
"tests/test_vector.py::VectorTestCase::test_no_filter_graph",
"tests/test_vector.py::VectorTestCase::test_overlay_with_mask",
"tests/test_vector.py::VectorTestCase::test_preroll_with_mask",
"tests/test_vector.py::VectorTestCase::test_same_filter_for_all_streams",
"tests/test_vector.py::VectorTestCase::test_same_filter_with_mask",
"tests/test_vector.py::VectorTestCase::test_single_quality_copy_pass_through",
"tests/test_vector.py::VectorTestCase::test_split_filter_if_vector_differs"
] |
[
"tests/test_ffmpeg.py::FFMPEGTestCase::test_detect_concat_buffering",
"tests/test_ffmpeg.py::FFMPEGTestCase::test_detect_trim_buffering",
"tests/test_ffmpeg.py::FFMPEGTestCase::test_filter_device_helper",
"tests/test_ffmpeg.py::FFMPEGTestCase::test_fix_preroll_buffering_with_trim",
"tests/test_ffmpeg.py::FFMPEGTestCase::test_fix_trim_buffering",
"tests/test_ffmpeg.py::FFMPEGTestCase::test_inputs_property",
"tests/test_ffmpeg.py::FFMPEGTestCase::test_outputs_property",
"tests/test_ffmpeg.py::FFMPEGTestCase::test_shortcut_outputs_with_codec",
"tests/test_ffmpeg.py::FFMPEGTestCase::test_transcoding_without_graph",
"tests/test_vector.py::VectorTestCase::test_clone_filter_with_skipped_params",
"tests/test_vector.py::VectorTestCase::test_vector_dimensions",
"tests/test_vector.py::VectorTestCase::test_vector_kind",
"tests/test_vector.py::VectorTestCase::test_vector_metadata",
"tests/test_vector.py::VectorTestCase::test_vector_metadata_for_multiple_streams"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-08-09 13:29:15+00:00
|
mit
| 3,381 |
|
just-work__fffw-47
|
diff --git a/examples/overlay.py b/examples/overlay.py
index 800fa90..a7926c7 100644
--- a/examples/overlay.py
+++ b/examples/overlay.py
@@ -11,7 +11,7 @@ overlay = ff.video | Overlay(x=1720, y=100)
# scale logo to 100x100 and pass as top layer to overlay filter
logo | Scale(width=100, height=100) | overlay
-# tell ffmpeg that it'll output something to destination file
-output = ff > output_file('output.mp4')
# output video with logo to destination file
-overlay > output
+output = overlay > output_file('output.mp4', VideoCodec('libx264'))
+# tell ffmpeg that it'll output something to destination file
+ff > output
diff --git a/fffw/encoding/outputs.py b/fffw/encoding/outputs.py
index 267c59d..4d0e471 100644
--- a/fffw/encoding/outputs.py
+++ b/fffw/encoding/outputs.py
@@ -110,7 +110,7 @@ class Output(BaseWrapper):
format: str = param(name="f")
output_file: str = param(name="", skip=True)
- def __lt__(self, other: base.InputType) -> Codec:
+ def __lt__(self, other: base.InputType) -> "Output":
"""
Connects a source or a filter to a first free codec.
@@ -118,7 +118,7 @@ class Output(BaseWrapper):
"""
codec = self.get_free_codec(other.kind)
other.connect_dest(codec)
- return codec
+ return self
@property
def video(self) -> Codec:
|
just-work/fffw
|
bb6d4bc134f17b0813d82eac027b6eb82a8ccbe3
|
diff --git a/tests/test_ffmpeg.py b/tests/test_ffmpeg.py
index dcb2105..10e52e3 100644
--- a/tests/test_ffmpeg.py
+++ b/tests/test_ffmpeg.py
@@ -493,3 +493,19 @@ class FFMPEGTestCase(BaseTestCase):
ff > output
ff.check_buffering()
+
+ def test_shortcut_outputs_with_codec(self):
+ """ Check ff > output shortcut if codecs list specified."""
+ ff = FFMPEG(input=inputs.input_file("input.mp4"))
+ scaled = ff.video | filters.Scale(width=1280, height=720)
+
+ with self.assertRaises(RuntimeError):
+ codec = codecs.VideoCodec("libx264")
+ out = ff > outputs.output_file("output.mp4", codec)
+ # at this moment codec is connected to ffmpeg input stream directly
+ # so scaled video stream could not be connected to output
+ scaled > out
+
+ codec = codecs.VideoCodec("libx264")
+ out = scaled > outputs.output_file("output.mp4", codec)
+ ff > out
|
FFMPEG.add_output shortcuts imisbehaving
```
output = ff > output_file('output.mp4', VideoCodec('libx264'))
stream > output
```
The code above does not work because second line raises "no free codecs" error.
Relates to #43
|
0.0
|
bb6d4bc134f17b0813d82eac027b6eb82a8ccbe3
|
[
"tests/test_ffmpeg.py::FFMPEGTestCase::test_shortcut_outputs_with_codec"
] |
[
"tests/test_ffmpeg.py::FFMPEGTestCase::test_bypass_with_filter_complex",
"tests/test_ffmpeg.py::FFMPEGTestCase::test_bypass_without_filter_complex",
"tests/test_ffmpeg.py::FFMPEGTestCase::test_concat",
"tests/test_ffmpeg.py::FFMPEGTestCase::test_detect_concat_buffering",
"tests/test_ffmpeg.py::FFMPEGTestCase::test_detect_trim_buffering",
"tests/test_ffmpeg.py::FFMPEGTestCase::test_ffmpeg",
"tests/test_ffmpeg.py::FFMPEGTestCase::test_fix_preroll_buffering_with_trim",
"tests/test_ffmpeg.py::FFMPEGTestCase::test_handle_codec_copy",
"tests/test_ffmpeg.py::FFMPEGTestCase::test_handle_codec_copy_with_other_filters",
"tests/test_ffmpeg.py::FFMPEGTestCase::test_input_stream_naming",
"tests/test_ffmpeg.py::FFMPEGTestCase::test_no_audio_if_no_codecs_found",
"tests/test_ffmpeg.py::FFMPEGTestCase::test_reuse_input_files",
"tests/test_ffmpeg.py::FFMPEGTestCase::test_transcoding_without_graph"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_issue_reference",
"has_media",
"has_many_modified_files",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-08-28 13:29:32+00:00
|
mit
| 3,382 |
|
just-work__fffw-56
|
diff --git a/fffw/graph/meta.py b/fffw/graph/meta.py
index ea0db03..93c0230 100644
--- a/fffw/graph/meta.py
+++ b/fffw/graph/meta.py
@@ -1,8 +1,13 @@
-import abc
from dataclasses import dataclass
from datetime import timedelta
from enum import Enum
-from typing import List, Union, Any, Optional
+from functools import wraps
+from typing import List, Union, Any, Optional, Callable, overload, Tuple, cast
+
+try:
+ from typing import Literal
+except ImportError: # pragma: no cover
+ from typing_extensions import Literal # type: ignore
from pymediainfo import MediaInfo # type: ignore
@@ -29,8 +34,88 @@ class StreamType(Enum):
VIDEO = StreamType.VIDEO
AUDIO = StreamType.AUDIO
-
-class TS(timedelta):
+BinaryOp = Callable[[Any, Any], Any]
+BinaryTS = Callable[[Any, Any], "TS"]
+UnaryOp = Callable[[Any], Any]
+UnaryTS = Callable[[Any], "TS"]
+
+
+@overload
+def ts(func: BinaryOp,
+ *,
+ arg: bool = True,
+ res: Literal[True] = True,
+ noarg: Literal[False] = False
+ ) -> BinaryTS:
+ ...
+
+
+@overload
+def ts(func: BinaryOp,
+ *,
+ arg: bool = True,
+ res: Literal[False],
+ noarg: Literal[False] = False
+ ) -> BinaryOp:
+ ...
+
+
+@overload
+def ts(func: UnaryOp,
+ *,
+ arg: bool = True,
+ res: Literal[True] = True,
+ noarg: Literal[True]
+ ) -> UnaryTS:
+ ...
+
+
+@overload
+def ts(func: UnaryOp,
+ *,
+ arg: bool = True,
+ res: Literal[False],
+ noarg: Literal[True]
+ ) -> UnaryOp:
+ ...
+
+
+def ts(func: Union[BinaryOp, UnaryOp], *,
+ arg: bool = True, res: bool = True, noarg: bool = False
+ ) -> Union[BinaryOp, UnaryOp]:
+ """
+ Decorates functions to automatically cast first argument and result to TS.
+ """
+ if arg and res:
+ if noarg:
+ @wraps(func)
+ def wrapper(self: "TS") -> "TS":
+ return TS(cast(UnaryOp, func)(self)) # noqa
+ else:
+ @wraps(func)
+ def wrapper(self: "TS", value: Any) -> "TS":
+ if value is None:
+ res = cast(BinaryOp, func)(self, value) # noqa
+ else:
+ res = cast(BinaryOp, func)(self, TS(value)) # noqa
+ return TS(res)
+ elif arg:
+ @wraps(func)
+ def wrapper(self: "TS", value: Any) -> Any:
+ if value is None:
+ return cast(BinaryOp, func)(self, value) # noqa
+ return cast(BinaryOp, func)(self, TS(value)) # noqa
+ elif res:
+ @wraps(func)
+ def wrapper(self: "TS", value: Any) -> "TS":
+ return TS(cast(BinaryOp, func)(self, value)) # noqa
+ else:
+ return func
+
+ return wrapper
+
+
+class TS(float):
"""
Timestamp data type.
@@ -38,18 +123,15 @@ class TS(timedelta):
Integer values are parsed as milliseconds.
"""
- def __new__(cls, value: Union[int, float, str], *args: int) -> "TS":
+ def __new__(cls, value: Union[int, float, str, timedelta]) -> "TS":
"""
:param value: integer duration in milliseconds, float duration in
seconds or string ffmpeg interval definition (123:59:59.999).
:returns new timestamp from value.
"""
- if args:
- # from deconstruction
- if not isinstance(value, int):
- raise ValueError(value)
- value = timedelta(value, *args).total_seconds()
- if isinstance(value, int):
+ if isinstance(value, timedelta):
+ value = value.total_seconds()
+ elif isinstance(value, int):
value = value / 1000.0
elif isinstance(value, str):
if '.' in value:
@@ -62,13 +144,86 @@ class TS(timedelta):
seconds *= 60
seconds += part
value = seconds + fractional
- return super().__new__(cls, seconds=value) # type: ignore
+ return super().__new__(cls, value) # type: ignore
+
+ __add__ = ts(float.__add__)
+ __radd__ = ts(float.__radd__)
+ __sub__ = ts(float.__sub__)
+ __rsub__ = ts(float.__rsub__)
+ __mul__ = ts(float.__mul__, arg=False)
+ __rmul__ = ts(float.__rmul__, arg=False)
+ __neg__ = ts(float.__neg__, noarg=True)
+ __abs__ = ts(float.__abs__, noarg=True)
+ __eq__ = ts(float.__eq__, res=False)
+ __ne__ = ts(float.__ne__, res=False)
+ __gt__ = ts(float.__gt__, res=False)
+ __ge__ = ts(float.__ge__, res=False)
+ __lt__ = ts(float.__lt__, res=False)
+ __le__ = ts(float.__le__, res=False)
+
+ @overload # type: ignore
+ def __floordiv__(self, other: "TS") -> int:
+ ...
+
+ @overload # type: ignore
+ def __floordiv__(self, other: int) -> "TS":
+ ...
+
+ def __floordiv__(self, other: Union["TS", float, int]) -> Union[int, "TS"]:
+ """
+ Division behavior from timedelta (rounds to microseconds)
+
+ >>> TS(10.0) // TS(3.0)
+ 3
+ >>> TS(10.0) // 3
+ TS(3.333333)
+ >>> TS(10.0) // 3.0
+ TS(3.333333)
+ """
+ value = (float(self * 1000000.0) // other) / 1000000.0
+ if isinstance(other, TS):
+ return int(value)
+ return TS(value)
+
+ @overload
+ def __truediv__(self, other: "TS") -> float: # type: ignore
+ ...
+
+ @overload
+ def __truediv__(self, other: Union[float, int]) -> "TS": # type: ignore
+ ...
- def __float__(self) -> float:
+ def __truediv__(self, other: Union["TS", float, int]) -> Union[float, "TS"]:
"""
- :returns: duration in seconds.
+ Division behavior from timedelta
+
+ >>> TS(10.0) / TS(2.125)
+ 4.705882352941177
+ >>> TS(10.0) / 2.125
+ TS(4.705882352941177)
+ >>> TS(10.0) / 2
+ TS(5.0)
+ """
+ value = super().__truediv__(other)
+ if isinstance(other, TS):
+ return value
+ return TS(value)
+
+ def __divmod__(self, other: float) -> Tuple[int, "TS"]:
"""
- return self.total_seconds()
+ Div/mod behavior from timedelta
+
+ >>> divmod(TS(10.0), TS(2.125))
+ (4, TS(1.5))
+ """
+ div, mod = super().__divmod__(other)
+ return int(div), TS(mod)
+
+ def __int__(self) -> int:
+ """
+ :return: duration in milliseconds.
+ """
+ return int(float(self * 1000))
def __str__(self) -> str:
"""
@@ -76,25 +231,30 @@ class TS(timedelta):
:returns: ffmpeg seconds definition (123456.999).
"""
- v = str(self.total_seconds())
+ v = super().__repr__()
if '.' in v:
v = v.rstrip('0')
+ if v.endswith('.'):
+ v += '0'
return v
- def __add__(self, other: timedelta) -> "TS":
- if not isinstance(other, timedelta):
- return NotImplemented
- return TS(self.total_seconds() + other.total_seconds())
+ def __repr__(self) -> str:
+ return f'TS({super().__repr__()})'
- def __sub__(self, other: timedelta) -> "TS":
- if not isinstance(other, timedelta):
- return NotImplemented
- return TS(self.total_seconds() - other.total_seconds())
+ def total_seconds(self) -> float:
+ return float(self)
- def __lt__(self, other: Union[int, float, str, timedelta, "TS"]) -> bool:
- if not isinstance(other, timedelta):
- other = TS(other)
- return self.total_seconds() < other.total_seconds()
+ @property
+ def days(self) -> int:
+ return int(float(self / (24 * 3600)))
+
+ @property
+ def seconds(self) -> int:
+ return int(float(self) % (24 * 3600))
+
+ @property
+ def microseconds(self) -> int:
+ return int(float(self * 1000000) % 1000000)
@dataclass
|
just-work/fffw
|
dbeea7af44b21564453782ab9725ac3d0d1b665d
|
diff --git a/tests/test_meta_data.py b/tests/test_meta_data.py
index 0e00b0d..c6087db 100644
--- a/tests/test_meta_data.py
+++ b/tests/test_meta_data.py
@@ -1,6 +1,9 @@
+import json
from copy import deepcopy
+from datetime import timedelta
+from typing import Iterable, Tuple, Any
from unittest import TestCase
-
+from itertools import product
from pymediainfo import MediaInfo # type: ignore
from fffw.graph import meta
@@ -206,23 +209,6 @@ class MetaDataTestCase(TestCase):
def setUp(self) -> None:
self.media_info = MediaInfo(SAMPLE)
- def test_ts_deconstruction(self):
- ts = meta.TS(3600 * 24 * 2 + 3600 * 4 + 0.123)
- self.assertEqual(ts, deepcopy(ts))
-
- def test_ts_init(self):
- self.assertEqual(float(meta.TS(1.23)), 1.23)
- self.assertEqual(float(meta.TS(1)), 0.001)
- self.assertEqual(float(meta.TS('01:02:03.04')),
- 1 * 3600 + 2 * 60 + 3 + 0.04)
- self.assertEqual(float(meta.TS(1, 2, 3)),
- 1 * 24 * 3600 + 2 + 0.000003)
- self.assertRaises(ValueError, meta.TS, 1.1, 2, 3)
-
- def test_ts_float(self):
- ts = meta.TS(3600 * 24 * 2 + 3600 * 4 + 0.123)
- self.assertEqual(float(ts), ts.total_seconds())
-
def test_parse_streams(self):
streams = meta.from_media_info(self.media_info)
self.assertEqual(len(streams), 2)
@@ -260,3 +246,169 @@ class MetaDataTestCase(TestCase):
samples=323616,
)
self.assertEqual(expected, audio)
+
+
+class TimeStampTestCase(TestCase):
+ td: timedelta
+ ts: meta.TS
+ binary_cases: Iterable[Tuple[Any, Any]]
+
+ @classmethod
+ def setUpClass(cls) -> None:
+ cls.td = timedelta(
+ days=10,
+ hours=12,
+ minutes=34,
+ seconds=56,
+ microseconds=789000)
+ cls.ts = meta.TS(cls.td.total_seconds())
+
+ ms = int(cls.td.total_seconds() * 1000)
+ seconds = cls.td.total_seconds()
+ string = '252:34:56.789000'
+ cls.binary_cases = (
+ (cls.ts, cls.ts),
+ (cls.ts, cls.td),
+ (cls.ts, ms),
+ (cls.ts, seconds),
+ (cls.ts, string),
+ (cls.td, cls.ts),
+ (ms, cls.ts),
+ (seconds, cls.ts),
+ (string, cls.ts),
+ )
+
+ def assert_ts_equal(self, ts: meta.TS, expected: float):
+ self.assertIsInstance(ts, meta.TS)
+ self.assertAlmostEqual(ts.total_seconds(), expected, places=4)
+
+ def test_ts_float(self):
+ self.assertEqual(float(self.ts), self.td.total_seconds())
+
+ def test_ts_int(self):
+ self.assertEqual(int(self.ts), int(self.td.total_seconds() * 1000))
+
+ def test_ts_deconstruction(self):
+ self.assertEqual(self.ts, deepcopy(self.ts))
+
+ def test_ts_init(self):
+ cases = (
+ # from float seconds
+ self.td.total_seconds(),
+ # from in milliseconds
+ int(self.td.total_seconds() * 1000),
+ # from string
+ '252:34:56.789000',
+ )
+ for v in cases:
+ with self.subTest(v):
+ self.assertEqual(self.ts, meta.TS(v))
+
+ def test_addition(self):
+ for case in self.binary_cases:
+ with self.subTest(case):
+ first, second = case
+ ts = first + second
+ self.assert_ts_equal(ts, 2 * self.td.total_seconds())
+
+ def test_substraction(self):
+ for case in self.binary_cases:
+ with self.subTest(case):
+ first, second = case
+ ts = first - second
+ self.assert_ts_equal(ts, 0.0)
+
+ def test_multiplication(self):
+ cases = (
+ 2.0,
+ 2,
+ )
+ for case in product(cases, (True, False)):
+ with self.subTest(case):
+ v, rev = case
+ if rev:
+ ts = v * self.ts
+ else:
+ ts = self.ts * v
+ self.assert_ts_equal(ts, 2 * self.td.total_seconds())
+
+ def test_divmod(self):
+ """ Test timedelta.__divmod__ behavior."""
+ # noinspection PyTypeChecker
+ div, mod = divmod(self.ts, self.ts)
+ self.assert_ts_equal(mod, 0.0)
+ self.assertIsInstance(div, int)
+ self.assertEqual(div, 1)
+
+ def test_floordiv(self):
+ """ Test timedelta.__floordiv__ behavior."""
+ ts = (self.ts + 0.000001) // 2
+ expected = int(self.td.total_seconds() * 1000000) / 2000000.0
+ self.assert_ts_equal(ts, expected)
+
+ ts = (self.ts + 0.000001) // meta.TS(2.0)
+ expected = int(self.td.total_seconds() * 1000000) // 2000000
+ self.assertIsInstance(ts, int)
+ self.assertEqual(ts, expected)
+
+ def test_truediv(self):
+ ts = (self.ts + 0.000001) / 2
+ expected = int(self.td.total_seconds() * 1000000) / 2000000.0
+ self.assert_ts_equal(ts, expected)
+
+ ts = (self.ts + 0.000001) / 2.0
+ expected = int(self.td.total_seconds() * 1000000) / 2000000.0
+ self.assert_ts_equal(ts, expected)
+
+ ts = (self.ts + 0.000001) / meta.TS(2.0)
+ expected = int(self.td.total_seconds() * 1000000) / 2000000.0
+ self.assertIsInstance(ts, float)
+ self.assertAlmostEqual(ts, expected, places=5)
+
+ def test_negate_abs(self):
+ ts = -self.ts
+ self.assert_ts_equal(ts, -self.td.total_seconds())
+ self.assert_ts_equal(abs(ts), self.td.total_seconds())
+
+ def test_compare(self):
+ v = self.ts + 0.001
+ cases = (
+ v,
+ v.total_seconds(),
+ int(v.total_seconds() * 1000),
+ )
+ for v in cases:
+ with self.subTest(v):
+ self.assertTrue(v > self.ts)
+ self.assertTrue(v >= self.ts)
+ self.assertFalse(v < self.ts)
+ self.assertTrue(self.ts < v)
+ self.assertTrue(self.ts <= v)
+ self.assertFalse(self.ts > v)
+ self.assertFalse(self.ts == v)
+ self.assertFalse(v == self.ts)
+ self.assertTrue(v != self.ts)
+ self.assertTrue(self.ts != v)
+
+ self.assertFalse(self.ts == None) # noqa
+ self.assertTrue(self.ts != None) # noqa
+ self.assertFalse(self.ts is None)
+ self.assertTrue(self.ts is not None)
+
+ def test_total_seconds(self):
+ self.assertEqual(self.ts.total_seconds(), self.td.total_seconds())
+
+ def test_fields(self):
+ self.assertEqual(self.ts.days, self.td.days)
+ self.assertEqual(self.ts.seconds, self.td.seconds)
+ self.assertEqual(self.ts.microseconds, self.td.microseconds)
+
+ def test_json_serializable(self):
+ self.assertEqual(json.dumps(self.ts),
+ json.dumps(self.td.total_seconds()))
+
+ def test_str(self):
+ self.assertEqual(str(self.ts), str(self.td.total_seconds()))
+
+ def test_repr(self):
+ self.assertEqual(repr(self.ts), f'TS({repr(self.td.total_seconds())})')
|
TS: base class and magic methods
`TS` instance based on `timedelta` is not json serializable, what leads to complicated Celery setup.
1. TS may be based on float and implement datetime/timedelta support via `__sub__`/`__add__` methods
2. TS should also define __repr__ method
|
0.0
|
dbeea7af44b21564453782ab9725ac3d0d1b665d
|
[
"tests/test_meta_data.py::TimeStampTestCase::test_addition",
"tests/test_meta_data.py::TimeStampTestCase::test_compare",
"tests/test_meta_data.py::TimeStampTestCase::test_divmod",
"tests/test_meta_data.py::TimeStampTestCase::test_floordiv",
"tests/test_meta_data.py::TimeStampTestCase::test_json_serializable",
"tests/test_meta_data.py::TimeStampTestCase::test_multiplication",
"tests/test_meta_data.py::TimeStampTestCase::test_negate_abs",
"tests/test_meta_data.py::TimeStampTestCase::test_repr",
"tests/test_meta_data.py::TimeStampTestCase::test_substraction",
"tests/test_meta_data.py::TimeStampTestCase::test_truediv",
"tests/test_meta_data.py::TimeStampTestCase::test_ts_int"
] |
[
"tests/test_meta_data.py::MetaDataTestCase::test_parse_streams",
"tests/test_meta_data.py::TimeStampTestCase::test_fields",
"tests/test_meta_data.py::TimeStampTestCase::test_str",
"tests/test_meta_data.py::TimeStampTestCase::test_total_seconds",
"tests/test_meta_data.py::TimeStampTestCase::test_ts_deconstruction",
"tests/test_meta_data.py::TimeStampTestCase::test_ts_float",
"tests/test_meta_data.py::TimeStampTestCase::test_ts_init"
] |
{
"failed_lite_validators": [
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-09-23 10:32:16+00:00
|
mit
| 3,383 |
|
just-work__fffw-64
|
diff --git a/fffw/encoding/filters.py b/fffw/encoding/filters.py
index bd06ae6..ff1baa2 100644
--- a/fffw/encoding/filters.py
+++ b/fffw/encoding/filters.py
@@ -1,4 +1,4 @@
-from dataclasses import dataclass, replace, asdict, field
+from dataclasses import dataclass, replace, asdict, field, fields
from typing import Union, List, cast
from fffw.graph import base
@@ -91,7 +91,8 @@ class Filter(mixins.StreamValidationMixin, base.Node, Params):
Inputs and outputs are not copied.
"""
- kwargs = asdict(self)
+ skip = [f.name for f in fields(self) if not f.init]
+ kwargs = {k: v for k, v in asdict(self).items() if k not in skip}
# noinspection PyArgumentList
return type(self)(**kwargs) # type: ignore
|
just-work/fffw
|
fefda959ec043f1869b38026fc3c8a9679bf45bc
|
diff --git a/tests/test_vector.py b/tests/test_vector.py
index 50794cd..bc4e8c8 100644
--- a/tests/test_vector.py
+++ b/tests/test_vector.py
@@ -1,4 +1,4 @@
-from dataclasses import dataclass, replace
+from dataclasses import dataclass, replace, asdict
from typing import cast, Tuple
from fffw.encoding import *
@@ -373,3 +373,17 @@ class VectorTestCase(BaseTestCase):
'-c:a', 'libfdk_aac',
'output2.mp5'
)
+
+ def test_clone_filter_with_skipped_params(self):
+ """
+ A filter with `init=False` param is cloned correctly.
+ """
+ @dataclass
+ class MyFilter(filters.VideoFilter):
+ my_flag: bool = param(init=False, default=True)
+
+ f = MyFilter()
+
+ cloned = f._clone()
+
+ self.assertTrue(asdict(cloned)['my_flag'])
|
Filter with skipped params could not be cloned
`TypeError: __init__() got an unexpected keyword argument 'extra_hw_frames'`
|
0.0
|
fefda959ec043f1869b38026fc3c8a9679bf45bc
|
[
"tests/test_vector.py::VectorTestCase::test_clone_filter_with_skipped_params"
] |
[
"tests/test_vector.py::VectorTestCase::test_apply_filter_with_equal_params",
"tests/test_vector.py::VectorTestCase::test_apply_filter_with_params_vector",
"tests/test_vector.py::VectorTestCase::test_clone_inputs_for_destination_filter",
"tests/test_vector.py::VectorTestCase::test_clone_streams",
"tests/test_vector.py::VectorTestCase::test_connect_filter_to_a_vector",
"tests/test_vector.py::VectorTestCase::test_connect_stream_to_simd",
"tests/test_vector.py::VectorTestCase::test_multiple_disabled_filters",
"tests/test_vector.py::VectorTestCase::test_no_filter_graph",
"tests/test_vector.py::VectorTestCase::test_overlay_with_mask",
"tests/test_vector.py::VectorTestCase::test_preroll_with_mask",
"tests/test_vector.py::VectorTestCase::test_same_filter_for_all_streams",
"tests/test_vector.py::VectorTestCase::test_same_filter_with_mask",
"tests/test_vector.py::VectorTestCase::test_split_filter_if_vector_differs",
"tests/test_vector.py::VectorTestCase::test_vector_kind",
"tests/test_vector.py::VectorTestCase::test_vector_metadata",
"tests/test_vector.py::VectorTestCase::test_vector_metadata_for_multiple_streams"
] |
{
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-10-15 13:31:45+00:00
|
mit
| 3,384 |
|
just-work__fffw-68
|
diff --git a/fffw/encoding/filters.py b/fffw/encoding/filters.py
index ff1baa2..1ef1505 100644
--- a/fffw/encoding/filters.py
+++ b/fffw/encoding/filters.py
@@ -3,7 +3,7 @@ from typing import Union, List, cast
from fffw.graph import base
from fffw.encoding import mixins
-from fffw.graph.meta import Meta, VideoMeta, TS, Scene, VIDEO, AUDIO
+from fffw.graph.meta import Meta, VideoMeta, TS, Scene, VIDEO, AUDIO, AudioMeta
from fffw.graph.meta import StreamType, Device
from fffw.wrapper.params import Params, param
@@ -330,16 +330,26 @@ class Concat(Filter):
duration = TS(0)
scenes = []
streams: List[str] = []
+ samples = 0
+ sampling_rate = None
for meta in metadata:
duration += meta.duration
+ if isinstance(meta, AudioMeta):
+ samples += meta.samples
+ if sampling_rate is None:
+ sampling_rate = meta.sampling_rate
+ else:
+ assert sampling_rate == meta.sampling_rate
scenes.extend(meta.scenes)
for stream in meta.streams:
if not streams or streams[-1] != stream:
# Add all streams for each concatenated metadata and remove
# contiguous duplicates.
streams.append(stream)
- return replace(metadata[0], duration=duration,
- scenes=scenes, streams=streams)
+ kwargs = dict(duration=duration, scenes=scenes, streams=streams)
+ if samples != 0:
+ kwargs['samples'] = samples
+ return replace(metadata[0], **kwargs)
@dataclass
|
just-work/fffw
|
ec1451b6347ac0c9a8da3947651d7b15ebf0212d
|
diff --git a/tests/test_graph.py b/tests/test_graph.py
index 5e82f6e..905464c 100644
--- a/tests/test_graph.py
+++ b/tests/test_graph.py
@@ -35,7 +35,10 @@ class FilterGraphTestCase(TestCase):
par=1.0,
duration=300.0,
)
- self.audio_metadata = audio_meta_data()
+ self.audio_metadata = audio_meta_data(
+ duration=200.0,
+ sampling_rate=48000,
+ samples_count=200*48000)
self.source = inputs.Input(
input_file='input.mp4',
@@ -239,6 +242,25 @@ class FilterGraphTestCase(TestCase):
self.assertEqual(self.video_metadata.duration + vs.meta.duration,
vm.duration)
+ def test_concat_audio_metadata(self):
+ """
+ Concat filter sums samples count for audio streams.
+ """
+ audio_meta = audio_meta_data(duration=1000.0, sampling_rate=48000,
+ samples_count=48000 * 1000)
+ a = inputs.Stream(AUDIO, meta=audio_meta)
+ self.input_list.append(inputs.input_file('second.mp4', a))
+ concat = a | Concat(AUDIO)
+ self.source | concat
+
+ concat > self.output
+
+ am = cast(AudioMeta, self.output.codecs[-1].get_meta_data())
+ self.assertEqual(self.audio_metadata.duration + audio_meta.duration,
+ am.duration)
+ self.assertEqual(self.audio_metadata.samples + audio_meta.samples,
+ am.samples)
+
def test_trim_metadata(self):
"""
Trim filter sets start and changes stream duration.
|
Concat audio fails validation
Samples count is not summed while concatenating audio.
Looks like concatenating video doesn't sum frames count.
|
0.0
|
ec1451b6347ac0c9a8da3947651d7b15ebf0212d
|
[
"tests/test_graph.py::FilterGraphTestCase::test_concat_audio_metadata"
] |
[
"tests/test_graph.py::FilterGraphTestCase::test_concat_metadata",
"tests/test_graph.py::FilterGraphTestCase::test_disabled_filters",
"tests/test_graph.py::FilterGraphTestCase::test_filter_graph",
"tests/test_graph.py::FilterGraphTestCase::test_filter_validates_hardware_device",
"tests/test_graph.py::FilterGraphTestCase::test_filter_validates_stream_kind",
"tests/test_graph.py::FilterGraphTestCase::test_overlay_metadata",
"tests/test_graph.py::FilterGraphTestCase::test_scale_changes_metadata",
"tests/test_graph.py::FilterGraphTestCase::test_setpts_metadata",
"tests/test_graph.py::FilterGraphTestCase::test_skip_not_connected_sources",
"tests/test_graph.py::FilterGraphTestCase::test_trim_metadata"
] |
{
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-10-15 14:18:30+00:00
|
mit
| 3,385 |
|
just-work__fffw-70
|
diff --git a/fffw/encoding/filters.py b/fffw/encoding/filters.py
index 1ef1505..43ed444 100644
--- a/fffw/encoding/filters.py
+++ b/fffw/encoding/filters.py
@@ -202,6 +202,10 @@ class Split(AutoFilter):
return ''
return str(self.output_count)
+ def validate_edge_device(self, edge: base.Edge) -> None:
+ # Any device is supported
+ return
+
@dataclass
class Trim(AutoFilter):
@@ -351,6 +355,10 @@ class Concat(Filter):
kwargs['samples'] = samples
return replace(metadata[0], **kwargs)
+ def validate_edge_device(self, edge: base.Edge) -> None:
+ # Any device is supported
+ return
+
@dataclass
class Overlay(VideoFilter):
|
just-work/fffw
|
448ed0a0b1dee4640a86e0ecce056f5fb1505c3b
|
diff --git a/tests/test_graph.py b/tests/test_graph.py
index 905464c..6b9bb4c 100644
--- a/tests/test_graph.py
+++ b/tests/test_graph.py
@@ -305,3 +305,17 @@ class FilterGraphTestCase(TestCase):
cuda = meta.Device(hardware='cuda', name='foo')
self.source.video | Upload(device=cuda) | ScaleCuda(640, 360)
+
+ def test_concat_split_allows_any_hardware(self):
+ """
+ Concat and split filters allow any hardware acceleration.
+ """
+ try:
+ cuda = meta.Device(hardware='cuda', name='foo')
+ hw = self.source.video | Upload(device=cuda)
+ split = hw | Split(VIDEO, output_count=2)
+ concat = Concat(VIDEO, input_count=2)
+ split | concat
+ split | concat
+ except ValueError: # pragma: no cover
+ self.fail("hardware validation unexpectedly failed")
|
Split and concat should validate against any hardware
splitting and concatenation is supported in every hardware acceleration
|
0.0
|
448ed0a0b1dee4640a86e0ecce056f5fb1505c3b
|
[
"tests/test_graph.py::FilterGraphTestCase::test_concat_split_allows_any_hardware"
] |
[
"tests/test_graph.py::FilterGraphTestCase::test_concat_audio_metadata",
"tests/test_graph.py::FilterGraphTestCase::test_concat_metadata",
"tests/test_graph.py::FilterGraphTestCase::test_disabled_filters",
"tests/test_graph.py::FilterGraphTestCase::test_filter_graph",
"tests/test_graph.py::FilterGraphTestCase::test_filter_validates_hardware_device",
"tests/test_graph.py::FilterGraphTestCase::test_filter_validates_stream_kind",
"tests/test_graph.py::FilterGraphTestCase::test_overlay_metadata",
"tests/test_graph.py::FilterGraphTestCase::test_scale_changes_metadata",
"tests/test_graph.py::FilterGraphTestCase::test_setpts_metadata",
"tests/test_graph.py::FilterGraphTestCase::test_skip_not_connected_sources",
"tests/test_graph.py::FilterGraphTestCase::test_trim_metadata"
] |
{
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-10-15 16:10:40+00:00
|
mit
| 3,386 |
|
just-work__fffw-71
|
diff --git a/fffw/encoding/filters.py b/fffw/encoding/filters.py
index 43ed444..2564388 100644
--- a/fffw/encoding/filters.py
+++ b/fffw/encoding/filters.py
@@ -157,6 +157,7 @@ class Scale(VideoFilter):
:arg height: resulting video height
"""
filter = "scale"
+ hardware = None # cpu only
width: int = param(name='w')
height: int = param(name='h')
@@ -202,10 +203,6 @@ class Split(AutoFilter):
return ''
return str(self.output_count)
- def validate_edge_device(self, edge: base.Edge) -> None:
- # Any device is supported
- return
-
@dataclass
class Trim(AutoFilter):
@@ -355,10 +352,6 @@ class Concat(Filter):
kwargs['samples'] = samples
return replace(metadata[0], **kwargs)
- def validate_edge_device(self, edge: base.Edge) -> None:
- # Any device is supported
- return
-
@dataclass
class Overlay(VideoFilter):
diff --git a/fffw/encoding/mixins.py b/fffw/encoding/mixins.py
index e74310c..a0e4a2d 100644
--- a/fffw/encoding/mixins.py
+++ b/fffw/encoding/mixins.py
@@ -1,4 +1,4 @@
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, Optional
from fffw.graph import base, VIDEO
@@ -9,7 +9,7 @@ else:
class StreamValidationMixin(StreamValidationTarget):
- hardware: str
+ hardware: Optional[str]
def connect_edge(self, edge: base.Edge) -> base.Edge:
self.validate_edge_kind(edge)
@@ -30,7 +30,11 @@ class StreamValidationMixin(StreamValidationTarget):
meta = edge.get_meta_data(self)
if meta is None:
return
- filter_hardware = getattr(self, 'hardware', None)
+ try:
+ filter_hardware = getattr(self, 'hardware')
+ except AttributeError:
+ # no hardware restrictions for filter/codec
+ return
device = getattr(meta, 'device', None)
edge_hardware = None if device is None else device.hardware
if filter_hardware != edge_hardware:
|
just-work/fffw
|
a5b5cacad54b502e9ee0ccd539e9dfcd7bf60eec
|
diff --git a/tests/test_encoding.py b/tests/test_encoding.py
index 005be16..959746a 100644
--- a/tests/test_encoding.py
+++ b/tests/test_encoding.py
@@ -1,3 +1,4 @@
+from dataclasses import dataclass
from unittest import TestCase
from fffw.graph import StreamType, VIDEO, AUDIO, video_meta_data
@@ -81,8 +82,13 @@ class InputsTestCase(TestCase):
hardware='cuda',
device='foo')
+ @dataclass
+ class X264(VideoCodec):
+ codec = 'libx264'
+ hardware = None # cpu only
+
with self.assertRaises(ValueError):
- src.video > VideoCodec('libx264')
+ src.video > X264()
with self.assertRaises(ValueError):
src.video | filters.Scale(640, 360)
diff --git a/tests/test_graph.py b/tests/test_graph.py
index 6b9bb4c..dd68ec9 100644
--- a/tests/test_graph.py
+++ b/tests/test_graph.py
@@ -306,16 +306,20 @@ class FilterGraphTestCase(TestCase):
cuda = meta.Device(hardware='cuda', name='foo')
self.source.video | Upload(device=cuda) | ScaleCuda(640, 360)
- def test_concat_split_allows_any_hardware(self):
+ def test_any_hardware_filter(self):
"""
- Concat and split filters allow any hardware acceleration.
+ A filter may be defined that allows to be ran on any hardware
"""
+
+ @dataclass
+ class UniversalFilter(VideoFilter):
+ filter = 'filter'
+ # not setting hardware - universal filter
+
try:
cuda = meta.Device(hardware='cuda', name='foo')
- hw = self.source.video | Upload(device=cuda)
- split = hw | Split(VIDEO, output_count=2)
- concat = Concat(VIDEO, input_count=2)
- split | concat
- split | concat
+ s = self.source.video | Split(VIDEO)
+ s | UniversalFilter()
+ s | Upload(device=cuda) | UniversalFilter()
except ValueError: # pragma: no cover
self.fail("hardware validation unexpectedly failed")
|
Split and concat should validate against any hardware
splitting and concatenation is supported in every hardware acceleration
|
0.0
|
a5b5cacad54b502e9ee0ccd539e9dfcd7bf60eec
|
[
"tests/test_graph.py::FilterGraphTestCase::test_any_hardware_filter"
] |
[
"tests/test_encoding.py::InputsTestCase::test_append_source",
"tests/test_encoding.py::InputsTestCase::test_default_input",
"tests/test_encoding.py::InputsTestCase::test_input_list",
"tests/test_encoding.py::InputsTestCase::test_validate_input_hardware",
"tests/test_encoding.py::InputsTestCase::test_validate_stream_kind",
"tests/test_encoding.py::OutputsTestCase::test_codec_validates_hardware_device",
"tests/test_encoding.py::OutputsTestCase::test_codec_validates_stream_kind",
"tests/test_graph.py::FilterGraphTestCase::test_concat_audio_metadata",
"tests/test_graph.py::FilterGraphTestCase::test_concat_metadata",
"tests/test_graph.py::FilterGraphTestCase::test_disabled_filters",
"tests/test_graph.py::FilterGraphTestCase::test_filter_graph",
"tests/test_graph.py::FilterGraphTestCase::test_filter_validates_hardware_device",
"tests/test_graph.py::FilterGraphTestCase::test_filter_validates_stream_kind",
"tests/test_graph.py::FilterGraphTestCase::test_overlay_metadata",
"tests/test_graph.py::FilterGraphTestCase::test_scale_changes_metadata",
"tests/test_graph.py::FilterGraphTestCase::test_setpts_metadata",
"tests/test_graph.py::FilterGraphTestCase::test_skip_not_connected_sources",
"tests/test_graph.py::FilterGraphTestCase::test_trim_metadata"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-10-15 16:25:01+00:00
|
mit
| 3,387 |
|
just-work__fffw-75
|
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index a23163e..b69d937 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -8,7 +8,7 @@ jobs:
strategy:
max-parallel: 4
matrix:
- python-version: [3.6, 3.7, 3.8]
+ python-version: [3.6, 3.7, 3.8, 3.9]
steps:
- uses: actions/checkout@v2
diff --git a/.github/workflows/codecov.yml b/.github/workflows/codecov.yml
index 5c6a729..1266714 100644
--- a/.github/workflows/codecov.yml
+++ b/.github/workflows/codecov.yml
@@ -8,7 +8,7 @@ jobs:
- name: Setup Python
uses: actions/setup-python@master
with:
- python-version: 3.8
+ python-version: 3.9
- name: Generate coverage report
run: |
pip install coverage
diff --git a/SECURITY.md b/SECURITY.md
index 6d5c5da..1a3963c 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -2,11 +2,12 @@
## Supported Versions
-Currently only 2.0.x branch has full support, 1.0.x branch is shut down.
+Currently only 2.x/3x branches has full support, 1.0.x branch is shut down.
| Version | Supported |
| ------- | ------------------ |
-| 2.0.x | :white_check_mark: |
+| 3.x | :white_check_mark: |
+| 2.x | :white_check_mark: |
| 1.0.x | :x: |
diff --git a/fffw/encoding/filters.py b/fffw/encoding/filters.py
index 2564388..f42e5b2 100644
--- a/fffw/encoding/filters.py
+++ b/fffw/encoding/filters.py
@@ -19,9 +19,33 @@ __all__ = [
'Split',
'Trim',
'Upload',
+ 'ensure_video',
+ 'ensure_audio',
]
+def ensure_video(meta: Meta, *_: Meta) -> VideoMeta:
+ """
+ Checks that first passed stream is a video stream
+
+ :returns: first passed stream
+ """
+ if not isinstance(meta, VideoMeta):
+ raise TypeError(meta)
+ return meta
+
+
+def ensure_audio(meta: Meta, *_: Meta) -> AudioMeta:
+ """
+ Checks that first passed stream is a audio stream
+
+ :returns: first passed stream
+ """
+ if not isinstance(meta, AudioMeta):
+ raise TypeError(meta)
+ return meta
+
+
@dataclass
class Filter(mixins.StreamValidationMixin, base.Node, Params):
"""
@@ -163,9 +187,7 @@ class Scale(VideoFilter):
height: int = param(name='h')
def transform(self, *metadata: Meta) -> Meta:
- meta = metadata[0]
- if not isinstance(meta, VideoMeta):
- raise TypeError(meta)
+ meta = ensure_video(*metadata)
par = meta.dar / (self.width / self.height)
return replace(meta, width=self.width, height=self.height, par=par)
@@ -331,16 +353,8 @@ class Concat(Filter):
duration = TS(0)
scenes = []
streams: List[str] = []
- samples = 0
- sampling_rate = None
for meta in metadata:
duration += meta.duration
- if isinstance(meta, AudioMeta):
- samples += meta.samples
- if sampling_rate is None:
- sampling_rate = meta.sampling_rate
- else:
- assert sampling_rate == meta.sampling_rate
scenes.extend(meta.scenes)
for stream in meta.streams:
if not streams or streams[-1] != stream:
@@ -348,8 +362,11 @@ class Concat(Filter):
# contiguous duplicates.
streams.append(stream)
kwargs = dict(duration=duration, scenes=scenes, streams=streams)
- if samples != 0:
- kwargs['samples'] = samples
+ meta = metadata[0]
+ if isinstance(meta, AudioMeta):
+ # Recompute samples and sampling rate: sampling rate from first
+ # input, samples count corresponds duration.
+ kwargs['samples'] = round(meta.sampling_rate * duration)
return replace(metadata[0], **kwargs)
@@ -389,7 +406,5 @@ class Upload(VideoFilter):
def transform(self, *metadata: Meta) -> VideoMeta:
""" Marks a stream as uploaded to a device."""
- meta = super().transform(*metadata)
- if not isinstance(meta, VideoMeta):
- raise ValueError(meta)
+ meta = ensure_video(*metadata)
return replace(meta, device=self.device)
diff --git a/fffw/wrapper/base.py b/fffw/wrapper/base.py
index b595a09..d8326b8 100644
--- a/fffw/wrapper/base.py
+++ b/fffw/wrapper/base.py
@@ -5,13 +5,78 @@ from asyncio.subprocess import Process
from dataclasses import dataclass
from logging import getLogger
from types import TracebackType
-from typing import Tuple, List, Any, Optional, cast, Callable, Union, TextIO, \
- Type
+from typing import Tuple, List, Any, Optional, cast, Callable, Union, TextIO
+from typing import Type, AsyncIterator
from fffw.wrapper.helpers import quote, ensure_binary, ensure_text
from fffw.wrapper.params import Params
+class UniversalLineReader:
+ """
+ Reads bytes from asyncio.StreamReader and splits it to lines with either
+ CR or LF, or even CRLF.
+
+ https://docs.python.org/3/glossary.html#term-universal-newlines
+
+ >>> # noinspection PyUnresolvedReferences
+ ... line_iter = UniversalLineReader(process.stderr)
+ >>> async for line in line_iter:
+ ... print(line)
+
+ """
+
+ def __init__(self,
+ reader: asyncio.StreamReader,
+ bufsize: int = 10 * io.DEFAULT_BUFFER_SIZE,
+ blocksize: int = io.DEFAULT_BUFFER_SIZE,
+ encoding: str = 'utf8') -> None:
+ """
+ :param reader: asynchronous stream reader, i.e. stdout/stderr of
+ asyncio Process instance.
+ :param bufsize: max buffer size
+ :param blocksize: read block size
+ :param encoding: text encoding
+ """
+ self.blocksize = blocksize
+ self.reader = reader
+ self.bufsize = bufsize
+ self.buffer = b''
+ self.encoding = encoding
+ self.at_eof = False
+
+ def __aiter__(self) -> AsyncIterator[str]:
+ return self.readlines()
+
+ async def readlines(self) -> AsyncIterator[str]:
+ while not self.at_eof:
+ # StreamReader supports only LF line separator. This leads to buffer
+ # overrun when it contains only CR-terminated lines. Thus, we read
+ # blocks manually and then split it to lines with universal line
+ # separator.
+ block = await self.reader.read(self.blocksize)
+ # empty read means that stream is closed
+ self.at_eof = len(block) == 0
+
+ # checking max buffer size
+ buffered = len(self.buffer) + len(block)
+ if buffered > self.bufsize:
+ raise asyncio.LimitOverrunError("buffer overrun", buffered)
+
+ self.buffer += block
+ if self.buffer:
+ # Split buffer to line with any of CR, LF of CRLF separators
+ # Last line is buffered to handle the case when CRLF sequence is
+ # being split to subsequent reads.
+ [*lines, self.buffer] = self.buffer.splitlines(keepends=True)
+ for line in lines:
+ yield line.decode(self.encoding)
+ # We always leave one non-empty line above, but stream may be empty. In
+ # this case we don't want to yield empty line.
+ if self.buffer:
+ yield self.buffer.decode(self.encoding)
+
+
class Runner:
""" Wrapper for Popen process for non-blocking streams handling."""
@@ -69,7 +134,7 @@ class Runner:
"""
Handles read from stdout/stderr.
- Reads lines from reader and feeds it to callback. Values, filtered by
+ Reads lines from stream and feeds it to callback. Values, filtered by
callback, are written to output buffer.
:param reader: Process.stdout or Process.stderr instance
@@ -78,14 +143,10 @@ class Runner:
"""
if callback is None or reader is None:
return
- while True:
- line = await reader.readline()
- if line:
- data = callback(line.decode())
- if data:
- output.write(data)
- else:
- break
+ async for line in UniversalLineReader(reader):
+ data = callback(line)
+ if data:
+ output.write(data)
@staticmethod
async def write(writer: Optional[asyncio.StreamWriter],
diff --git a/setup.py b/setup.py
index 95909f1..a4ad5a9 100644
--- a/setup.py
+++ b/setup.py
@@ -85,6 +85,7 @@ setup(
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
+ 'Programming Language :: Python :: 3.9',
'Topic :: Multimedia :: Video :: Conversion',
]
|
just-work/fffw
|
69fae959dae793a05ae4a4914cbf4e8d5e32af16
|
diff --git a/tests/test_graph.py b/tests/test_graph.py
index dd68ec9..e8c25d9 100644
--- a/tests/test_graph.py
+++ b/tests/test_graph.py
@@ -49,6 +49,18 @@ class FilterGraphTestCase(TestCase):
self.output_list = outputs.OutputList((self.output,))
self.fc = FilterComplex(self.input_list, self.output_list)
+ def test_ensure_video(self):
+ """ Test video stream type assertion helper."""
+ with self.assertRaises(TypeError):
+ ensure_video(self.audio_metadata)
+ self.assertIs(ensure_video(self.video_metadata), self.video_metadata)
+
+ def test_ensure_audio(self):
+ """ Test audio stream type assertion helper."""
+ with self.assertRaises(TypeError):
+ ensure_audio(self.video_metadata)
+ self.assertIs(ensure_audio(self.audio_metadata), self.audio_metadata)
+
def test_filter_graph(self):
""" Filter complex smoke test and features demo.
@@ -246,8 +258,8 @@ class FilterGraphTestCase(TestCase):
"""
Concat filter sums samples count for audio streams.
"""
- audio_meta = audio_meta_data(duration=1000.0, sampling_rate=48000,
- samples_count=48000 * 1000)
+ audio_meta = audio_meta_data(duration=1000.0, sampling_rate=24000,
+ samples_count=24000 * 1000)
a = inputs.Stream(AUDIO, meta=audio_meta)
self.input_list.append(inputs.input_file('second.mp4', a))
concat = a | Concat(AUDIO)
@@ -258,7 +270,7 @@ class FilterGraphTestCase(TestCase):
am = cast(AudioMeta, self.output.codecs[-1].get_meta_data())
self.assertEqual(self.audio_metadata.duration + audio_meta.duration,
am.duration)
- self.assertEqual(self.audio_metadata.samples + audio_meta.samples,
+ self.assertEqual(round(am.duration * audio_meta.sampling_rate),
am.samples)
def test_trim_metadata(self):
diff --git a/tests/test_wrapper.py b/tests/test_wrapper.py
new file mode 100644
index 0000000..ba68852
--- /dev/null
+++ b/tests/test_wrapper.py
@@ -0,0 +1,121 @@
+import asyncio
+import io
+import random
+import sys
+import time
+from dataclasses import dataclass
+from typing import List
+from unittest import TestCase, mock
+
+from fffw.wrapper import param
+from fffw.wrapper.base import UniversalLineReader, BaseWrapper
+
+
+@dataclass
+class Python(BaseWrapper):
+ command = 'python'
+ module: str = param(name='m')
+
+
+def script():
+ line = input()
+ sys.stdout.write(f'stdout: {line}\n')
+ sys.stderr.write(f'stderr: {line}\n')
+ time.sleep(int(line) // 100)
+ return int(line)
+
+
+if __name__ == '__main__':
+ sys.exit(script())
+
+
+class WrapperTestCase(TestCase):
+
+ def test_run_child_process(self):
+ p = Python(module='tests.test_wrapper')
+ ret, out, err = p.run('1')
+ self.assertEqual(ret, 1)
+ self.assertEqual(out, 'stdout: 1\n')
+ self.assertEqual(err, 'stderr: 1\n')
+
+ def test_child_timeout(self):
+ p = Python(module='tests.test_wrapper')
+ ret, out, err = p.run('100', timeout=0.01)
+ self.assertEqual(ret, -9)
+
+
+class UniversalLineReaderTestCase(TestCase):
+ def setUp(self) -> None:
+ self.data = io.BytesIO()
+ self.stream = mock.MagicMock(read=self.read)
+ self.reader = UniversalLineReader(self.stream, bufsize=100, blocksize=5)
+
+ async def read(self, n=-1):
+ return self.data.read(n)
+
+ async def iterate(self) -> List[str]:
+ result = []
+ async for line in self.reader:
+ result.append(line)
+ return result
+
+ def assert_lines(self, lines: List[str]):
+ for line in lines:
+ self.data.write(line.encode('utf-8'))
+ self.data.seek(0)
+ result = asyncio.get_event_loop().run_until_complete(self.iterate())
+ self.assertListEqual(lines, result)
+
+ def test_read_lf(self):
+ lines = []
+ for c in 'abcdefghijklmnopqrstuvwxyz':
+ length = random.randint(0, 15)
+ lines.append(c * length + '\n')
+ for line in lines:
+ self.data.write(line.encode('utf-8'))
+ self.data.seek(0)
+
+ self.assert_lines(lines)
+
+ def test_read_cr(self):
+ lines = []
+ for c in 'abcdefghijklmnopqrstuvwxyz':
+ length = random.randint(0, 15)
+ lines.append(c * length + '\r')
+
+ self.assert_lines(lines)
+
+ def test_read_crlf(self):
+ lines = []
+ for c in 'abcdefghijklmnopqrstuvwxyz':
+ length = random.randint(0, 15)
+ lines.append(c * length + '\r\n')
+
+ self.assert_lines(lines)
+
+ def test_empty_lines(self):
+ lines = [
+ 'a\n',
+ '\n',
+ 'b\n'
+ ]
+
+ self.assert_lines(lines)
+
+ def test_last_incomplete_line(self):
+ lines = [
+ 'aaaaa\n',
+ 'b'
+ ]
+
+ self.assert_lines(lines)
+
+ def test_empty_stream(self):
+ self.assert_lines([])
+
+ def test_buffer_overrun(self):
+ max_line = 'a' * self.reader.bufsize
+ lines = [max_line + '\n']
+
+ with self.assertRaises(asyncio.LimitOverrunError):
+ self.assert_lines(lines)
|
Separator is not found, and chunk exceed the limit
I am trying to transcode using `django-video-transcoding` which uses fffw library, and for a few streams I am getting `Separator is not found, and chunk exceed the limit`. I tried running ffmpeg with the exact command which`django-video-transcoding` logs and it works fine.
|
0.0
|
69fae959dae793a05ae4a4914cbf4e8d5e32af16
|
[
"tests/test_graph.py::FilterGraphTestCase::test_any_hardware_filter",
"tests/test_graph.py::FilterGraphTestCase::test_concat_audio_metadata",
"tests/test_graph.py::FilterGraphTestCase::test_concat_metadata",
"tests/test_graph.py::FilterGraphTestCase::test_disabled_filters",
"tests/test_graph.py::FilterGraphTestCase::test_ensure_audio",
"tests/test_graph.py::FilterGraphTestCase::test_ensure_video",
"tests/test_graph.py::FilterGraphTestCase::test_filter_graph",
"tests/test_graph.py::FilterGraphTestCase::test_filter_validates_hardware_device",
"tests/test_graph.py::FilterGraphTestCase::test_filter_validates_stream_kind",
"tests/test_graph.py::FilterGraphTestCase::test_overlay_metadata",
"tests/test_graph.py::FilterGraphTestCase::test_scale_changes_metadata",
"tests/test_graph.py::FilterGraphTestCase::test_setpts_metadata",
"tests/test_graph.py::FilterGraphTestCase::test_skip_not_connected_sources",
"tests/test_graph.py::FilterGraphTestCase::test_trim_metadata",
"tests/test_wrapper.py::WrapperTestCase::test_child_timeout",
"tests/test_wrapper.py::WrapperTestCase::test_run_child_process",
"tests/test_wrapper.py::UniversalLineReaderTestCase::test_buffer_overrun",
"tests/test_wrapper.py::UniversalLineReaderTestCase::test_empty_lines",
"tests/test_wrapper.py::UniversalLineReaderTestCase::test_empty_stream",
"tests/test_wrapper.py::UniversalLineReaderTestCase::test_last_incomplete_line",
"tests/test_wrapper.py::UniversalLineReaderTestCase::test_read_cr",
"tests/test_wrapper.py::UniversalLineReaderTestCase::test_read_crlf",
"tests/test_wrapper.py::UniversalLineReaderTestCase::test_read_lf"
] |
[] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-10-30 09:18:13+00:00
|
mit
| 3,388 |
|
just-work__fffw-80
|
diff --git a/fffw/encoding/filters.py b/fffw/encoding/filters.py
index f42e5b2..194424c 100644
--- a/fffw/encoding/filters.py
+++ b/fffw/encoding/filters.py
@@ -278,8 +278,18 @@ class Trim(AutoFilter):
scenes.append(Scene(stream=scene.stream, start=start,
duration=end - start))
- return replace(meta, start=self.start, duration=self.end,
- scenes=scenes, streams=streams)
+ kwargs = {
+ 'start': self.start,
+ 'duration': self.end,
+ 'scenes': scenes,
+ 'streams': streams
+ }
+ interval = cast(TS, self.end) - cast(TS, self.start)
+ if isinstance(meta, AudioMeta):
+ kwargs['samples'] = round(meta.sampling_rate * interval)
+ if isinstance(meta, VideoMeta):
+ kwargs['frames'] = round(meta.frame_rate * interval)
+ return replace(meta, **kwargs)
@dataclass
@@ -353,6 +363,7 @@ class Concat(Filter):
duration = TS(0)
scenes = []
streams: List[str] = []
+ frames: int = 0
for meta in metadata:
duration += meta.duration
scenes.extend(meta.scenes)
@@ -361,12 +372,17 @@ class Concat(Filter):
# Add all streams for each concatenated metadata and remove
# contiguous duplicates.
streams.append(stream)
+ if isinstance(meta, VideoMeta):
+ frames += meta.frames
kwargs = dict(duration=duration, scenes=scenes, streams=streams)
meta = metadata[0]
if isinstance(meta, AudioMeta):
# Recompute samples and sampling rate: sampling rate from first
# input, samples count corresponds duration.
kwargs['samples'] = round(meta.sampling_rate * duration)
+ if isinstance(meta, VideoMeta):
+ # Sum frames count from all input streams
+ kwargs['frames'] = frames
return replace(metadata[0], **kwargs)
diff --git a/fffw/graph/meta.py b/fffw/graph/meta.py
index c767955..29beac6 100644
--- a/fffw/graph/meta.py
+++ b/fffw/graph/meta.py
@@ -330,6 +330,8 @@ class VideoMeta(Meta):
""" Display aspect ratio."""
frame_rate: float
""" Frames per second."""
+ frames: int
+ """ Number of frames."""
device: Optional[Device]
""" Hardware device asociated with current stream."""
@@ -346,6 +348,9 @@ class VideoMeta(Meta):
else:
assert str(self.dar) == 'nan'
+ interval = float(self.duration - self.start)
+ assert abs(self.frames - interval * self.frame_rate) <= 1
+
@dataclass
class AudioMeta(Meta):
@@ -369,11 +374,8 @@ class AudioMeta(Meta):
return AUDIO
def validate(self) -> None:
- duration = self.duration.total_seconds()
- if duration != 0:
- assert abs(self.sampling_rate - self.samples / duration) < 0.001
- else:
- assert self.sampling_rate == 0
+ interval = float(self.duration - self.start)
+ assert abs(self.samples - interval * self.sampling_rate) <= 1
def audio_meta_data(**kwargs: Any) -> AudioMeta:
@@ -437,6 +439,7 @@ def video_meta_data(**kwargs: Any) -> VideoMeta:
par=par,
dar=dar,
frame_rate=frame_rate,
+ frames=frames,
device=None,
)
diff --git a/fffw/wrapper/base.py b/fffw/wrapper/base.py
index b595a09..d8326b8 100644
--- a/fffw/wrapper/base.py
+++ b/fffw/wrapper/base.py
@@ -5,13 +5,78 @@ from asyncio.subprocess import Process
from dataclasses import dataclass
from logging import getLogger
from types import TracebackType
-from typing import Tuple, List, Any, Optional, cast, Callable, Union, TextIO, \
- Type
+from typing import Tuple, List, Any, Optional, cast, Callable, Union, TextIO
+from typing import Type, AsyncIterator
from fffw.wrapper.helpers import quote, ensure_binary, ensure_text
from fffw.wrapper.params import Params
+class UniversalLineReader:
+ """
+ Reads bytes from asyncio.StreamReader and splits it to lines with either
+ CR or LF, or even CRLF.
+
+ https://docs.python.org/3/glossary.html#term-universal-newlines
+
+ >>> # noinspection PyUnresolvedReferences
+ ... line_iter = UniversalLineReader(process.stderr)
+ >>> async for line in line_iter:
+ ... print(line)
+
+ """
+
+ def __init__(self,
+ reader: asyncio.StreamReader,
+ bufsize: int = 10 * io.DEFAULT_BUFFER_SIZE,
+ blocksize: int = io.DEFAULT_BUFFER_SIZE,
+ encoding: str = 'utf8') -> None:
+ """
+ :param reader: asynchronous stream reader, i.e. stdout/stderr of
+ asyncio Process instance.
+ :param bufsize: max buffer size
+ :param blocksize: read block size
+ :param encoding: text encoding
+ """
+ self.blocksize = blocksize
+ self.reader = reader
+ self.bufsize = bufsize
+ self.buffer = b''
+ self.encoding = encoding
+ self.at_eof = False
+
+ def __aiter__(self) -> AsyncIterator[str]:
+ return self.readlines()
+
+ async def readlines(self) -> AsyncIterator[str]:
+ while not self.at_eof:
+ # StreamReader supports only LF line separator. This leads to buffer
+ # overrun when it contains only CR-terminated lines. Thus, we read
+ # blocks manually and then split it to lines with universal line
+ # separator.
+ block = await self.reader.read(self.blocksize)
+ # empty read means that stream is closed
+ self.at_eof = len(block) == 0
+
+ # checking max buffer size
+ buffered = len(self.buffer) + len(block)
+ if buffered > self.bufsize:
+ raise asyncio.LimitOverrunError("buffer overrun", buffered)
+
+ self.buffer += block
+ if self.buffer:
+ # Split buffer to line with any of CR, LF of CRLF separators
+ # Last line is buffered to handle the case when CRLF sequence is
+ # being split to subsequent reads.
+ [*lines, self.buffer] = self.buffer.splitlines(keepends=True)
+ for line in lines:
+ yield line.decode(self.encoding)
+ # We always leave one non-empty line above, but stream may be empty. In
+ # this case we don't want to yield empty line.
+ if self.buffer:
+ yield self.buffer.decode(self.encoding)
+
+
class Runner:
""" Wrapper for Popen process for non-blocking streams handling."""
@@ -69,7 +134,7 @@ class Runner:
"""
Handles read from stdout/stderr.
- Reads lines from reader and feeds it to callback. Values, filtered by
+ Reads lines from stream and feeds it to callback. Values, filtered by
callback, are written to output buffer.
:param reader: Process.stdout or Process.stderr instance
@@ -78,14 +143,10 @@ class Runner:
"""
if callback is None or reader is None:
return
- while True:
- line = await reader.readline()
- if line:
- data = callback(line.decode())
- if data:
- output.write(data)
- else:
- break
+ async for line in UniversalLineReader(reader):
+ data = callback(line)
+ if data:
+ output.write(data)
@staticmethod
async def write(writer: Optional[asyncio.StreamWriter],
|
just-work/fffw
|
d839c61a6d8db8e4d79474125e203df496a46a43
|
diff --git a/tests/test_graph.py b/tests/test_graph.py
index e8c25d9..b85e73b 100644
--- a/tests/test_graph.py
+++ b/tests/test_graph.py
@@ -2,7 +2,7 @@ from dataclasses import dataclass
from typing import cast
from unittest import TestCase
-from fffw.encoding import inputs, outputs
+from fffw.encoding import inputs, outputs, codecs
from fffw.encoding.complex import FilterComplex
from fffw.encoding.filters import *
from fffw.graph import *
@@ -34,17 +34,22 @@ class FilterGraphTestCase(TestCase):
dar=1.777777778,
par=1.0,
duration=300.0,
+ frame_rate=10.0,
+ frame_count=3000
)
self.audio_metadata = audio_meta_data(
duration=200.0,
sampling_rate=48000,
- samples_count=200*48000)
+ samples_count=200 * 48000)
self.source = inputs.Input(
input_file='input.mp4',
streams=(inputs.Stream(VIDEO, meta=self.video_metadata),
inputs.Stream(AUDIO, meta=self.audio_metadata)))
- self.output = outputs.output_file('output.mp4')
+ self.output = outputs.output_file(
+ 'output.mp4',
+ codecs.VideoCodec('libx264'),
+ codecs.AudioCodec('libfdk_aac'))
self.input_list = inputs.InputList((self.source,))
self.output_list = outputs.OutputList((self.output,))
self.fc = FilterComplex(self.input_list, self.output_list)
@@ -237,13 +242,16 @@ class FilterGraphTestCase(TestCase):
self.assertEqual(vm.width, self.video_metadata.width)
self.assertEqual(vm.height, self.video_metadata.height)
- def test_concat_metadata(self):
+ def test_concat_video_metadata(self):
"""
Concat filter sums stream duration
$ ffmpeg -y -i first.mp4 -i second.mp4 -filter_complex concat test.mp4
"""
- vs = inputs.Stream(VIDEO, meta=video_meta_data(duration=1000.0))
+ video_meta = video_meta_data(duration=1000.0,
+ frame_count=10000,
+ frame_rate=10.0)
+ vs = inputs.Stream(VIDEO, meta=video_meta)
self.input_list.append(inputs.input_file('second.mp4', vs))
concat = vs | Concat(VIDEO)
self.source | concat
@@ -253,12 +261,15 @@ class FilterGraphTestCase(TestCase):
vm = cast(VideoMeta, self.output.codecs[0].get_meta_data())
self.assertEqual(self.video_metadata.duration + vs.meta.duration,
vm.duration)
+ self.assertEqual(self.video_metadata.frames + video_meta.frames,
+ vm.frames)
def test_concat_audio_metadata(self):
"""
Concat filter sums samples count for audio streams.
"""
- audio_meta = audio_meta_data(duration=1000.0, sampling_rate=24000,
+ audio_meta = audio_meta_data(duration=1000.0,
+ sampling_rate=24000,
samples_count=24000 * 1000)
a = inputs.Stream(AUDIO, meta=audio_meta)
self.input_list.append(inputs.input_file('second.mp4', a))
@@ -273,7 +284,7 @@ class FilterGraphTestCase(TestCase):
self.assertEqual(round(am.duration * audio_meta.sampling_rate),
am.samples)
- def test_trim_metadata(self):
+ def test_video_trim_metadata(self):
"""
Trim filter sets start and changes stream duration.
$ ffmpeg -y -i source.mp4 -vf trim=start=3:end=4 -an test.mp4
@@ -285,6 +296,21 @@ class FilterGraphTestCase(TestCase):
vm = cast(VideoMeta, self.output.codecs[0].get_meta_data())
self.assertEqual(vm.start, TS(3.0))
self.assertEqual(vm.duration, TS(4.0))
+ self.assertEqual(vm.frames, 1.0 * vm.frame_rate)
+
+ def test_audio_trim_metadata(self):
+ """
+ Trim filter sets start and changes stream duration.
+ $ ffmpeg -y -i source.mp4 -af atrim=start=3:end=4 -vn test.mp4
+
+ Note that resulting video has 3 seconds of frozen frame at 00:00:03.000,
+ total duration is 4.
+ """
+ self.source | Trim(AUDIO, start=3.0, end=4.0) > self.output
+ am = cast(AudioMeta, self.output.codecs[1].get_meta_data())
+ self.assertEqual(am.start, TS(3.0))
+ self.assertEqual(am.duration, TS(4.0))
+ self.assertEqual(am.samples, 1.0 * am.sampling_rate)
def test_setpts_metadata(self):
"""
diff --git a/tests/test_meta_data.py b/tests/test_meta_data.py
index 8f63ce8..801af85 100644
--- a/tests/test_meta_data.py
+++ b/tests/test_meta_data.py
@@ -229,6 +229,7 @@ class MetaDataTestCase(TestCase):
par=1.0,
dar=1.778,
frame_rate=50.0,
+ frames=337,
device=None,
)
self.assertEqual(expected, video)
@@ -266,7 +267,6 @@ class MetaDataTestCase(TestCase):
self.assertTrue(fields(ExtendedVideoMeta))
-
class TimeStampTestCase(TestCase):
td: timedelta
ts: meta.TS
diff --git a/tests/test_wrapper.py b/tests/test_wrapper.py
new file mode 100644
index 0000000..ba68852
--- /dev/null
+++ b/tests/test_wrapper.py
@@ -0,0 +1,121 @@
+import asyncio
+import io
+import random
+import sys
+import time
+from dataclasses import dataclass
+from typing import List
+from unittest import TestCase, mock
+
+from fffw.wrapper import param
+from fffw.wrapper.base import UniversalLineReader, BaseWrapper
+
+
+@dataclass
+class Python(BaseWrapper):
+ command = 'python'
+ module: str = param(name='m')
+
+
+def script():
+ line = input()
+ sys.stdout.write(f'stdout: {line}\n')
+ sys.stderr.write(f'stderr: {line}\n')
+ time.sleep(int(line) // 100)
+ return int(line)
+
+
+if __name__ == '__main__':
+ sys.exit(script())
+
+
+class WrapperTestCase(TestCase):
+
+ def test_run_child_process(self):
+ p = Python(module='tests.test_wrapper')
+ ret, out, err = p.run('1')
+ self.assertEqual(ret, 1)
+ self.assertEqual(out, 'stdout: 1\n')
+ self.assertEqual(err, 'stderr: 1\n')
+
+ def test_child_timeout(self):
+ p = Python(module='tests.test_wrapper')
+ ret, out, err = p.run('100', timeout=0.01)
+ self.assertEqual(ret, -9)
+
+
+class UniversalLineReaderTestCase(TestCase):
+ def setUp(self) -> None:
+ self.data = io.BytesIO()
+ self.stream = mock.MagicMock(read=self.read)
+ self.reader = UniversalLineReader(self.stream, bufsize=100, blocksize=5)
+
+ async def read(self, n=-1):
+ return self.data.read(n)
+
+ async def iterate(self) -> List[str]:
+ result = []
+ async for line in self.reader:
+ result.append(line)
+ return result
+
+ def assert_lines(self, lines: List[str]):
+ for line in lines:
+ self.data.write(line.encode('utf-8'))
+ self.data.seek(0)
+ result = asyncio.get_event_loop().run_until_complete(self.iterate())
+ self.assertListEqual(lines, result)
+
+ def test_read_lf(self):
+ lines = []
+ for c in 'abcdefghijklmnopqrstuvwxyz':
+ length = random.randint(0, 15)
+ lines.append(c * length + '\n')
+ for line in lines:
+ self.data.write(line.encode('utf-8'))
+ self.data.seek(0)
+
+ self.assert_lines(lines)
+
+ def test_read_cr(self):
+ lines = []
+ for c in 'abcdefghijklmnopqrstuvwxyz':
+ length = random.randint(0, 15)
+ lines.append(c * length + '\r')
+
+ self.assert_lines(lines)
+
+ def test_read_crlf(self):
+ lines = []
+ for c in 'abcdefghijklmnopqrstuvwxyz':
+ length = random.randint(0, 15)
+ lines.append(c * length + '\r\n')
+
+ self.assert_lines(lines)
+
+ def test_empty_lines(self):
+ lines = [
+ 'a\n',
+ '\n',
+ 'b\n'
+ ]
+
+ self.assert_lines(lines)
+
+ def test_last_incomplete_line(self):
+ lines = [
+ 'aaaaa\n',
+ 'b'
+ ]
+
+ self.assert_lines(lines)
+
+ def test_empty_stream(self):
+ self.assert_lines([])
+
+ def test_buffer_overrun(self):
+ max_line = 'a' * self.reader.bufsize
+ lines = [max_line + '\n']
+
+ with self.assertRaises(asyncio.LimitOverrunError):
+ self.assert_lines(lines)
|
Support computing frames count for video metadata
It's useful to track encoding progress and to restore partial video metadata
|
0.0
|
d839c61a6d8db8e4d79474125e203df496a46a43
|
[
"tests/test_graph.py::FilterGraphTestCase::test_any_hardware_filter",
"tests/test_graph.py::FilterGraphTestCase::test_audio_trim_metadata",
"tests/test_graph.py::FilterGraphTestCase::test_concat_audio_metadata",
"tests/test_graph.py::FilterGraphTestCase::test_concat_video_metadata",
"tests/test_graph.py::FilterGraphTestCase::test_disabled_filters",
"tests/test_graph.py::FilterGraphTestCase::test_ensure_audio",
"tests/test_graph.py::FilterGraphTestCase::test_ensure_video",
"tests/test_graph.py::FilterGraphTestCase::test_filter_graph",
"tests/test_graph.py::FilterGraphTestCase::test_filter_validates_hardware_device",
"tests/test_graph.py::FilterGraphTestCase::test_filter_validates_stream_kind",
"tests/test_graph.py::FilterGraphTestCase::test_overlay_metadata",
"tests/test_graph.py::FilterGraphTestCase::test_scale_changes_metadata",
"tests/test_graph.py::FilterGraphTestCase::test_setpts_metadata",
"tests/test_graph.py::FilterGraphTestCase::test_skip_not_connected_sources",
"tests/test_graph.py::FilterGraphTestCase::test_video_trim_metadata",
"tests/test_meta_data.py::MetaDataTestCase::test_parse_streams",
"tests/test_meta_data.py::MetaDataTestCase::test_subclassing_audio_meta",
"tests/test_meta_data.py::MetaDataTestCase::test_subclassing_video_meta",
"tests/test_meta_data.py::TimeStampTestCase::test_addition",
"tests/test_meta_data.py::TimeStampTestCase::test_compare",
"tests/test_meta_data.py::TimeStampTestCase::test_divmod",
"tests/test_meta_data.py::TimeStampTestCase::test_fields",
"tests/test_meta_data.py::TimeStampTestCase::test_floordiv",
"tests/test_meta_data.py::TimeStampTestCase::test_json_serializable",
"tests/test_meta_data.py::TimeStampTestCase::test_multiplication",
"tests/test_meta_data.py::TimeStampTestCase::test_negate_abs",
"tests/test_meta_data.py::TimeStampTestCase::test_repr",
"tests/test_meta_data.py::TimeStampTestCase::test_str",
"tests/test_meta_data.py::TimeStampTestCase::test_substraction",
"tests/test_meta_data.py::TimeStampTestCase::test_total_seconds",
"tests/test_meta_data.py::TimeStampTestCase::test_truediv",
"tests/test_meta_data.py::TimeStampTestCase::test_ts_deconstruction",
"tests/test_meta_data.py::TimeStampTestCase::test_ts_float",
"tests/test_meta_data.py::TimeStampTestCase::test_ts_init",
"tests/test_meta_data.py::TimeStampTestCase::test_ts_int",
"tests/test_wrapper.py::WrapperTestCase::test_child_timeout",
"tests/test_wrapper.py::WrapperTestCase::test_run_child_process",
"tests/test_wrapper.py::UniversalLineReaderTestCase::test_buffer_overrun",
"tests/test_wrapper.py::UniversalLineReaderTestCase::test_empty_lines",
"tests/test_wrapper.py::UniversalLineReaderTestCase::test_empty_stream",
"tests/test_wrapper.py::UniversalLineReaderTestCase::test_last_incomplete_line",
"tests/test_wrapper.py::UniversalLineReaderTestCase::test_read_cr",
"tests/test_wrapper.py::UniversalLineReaderTestCase::test_read_crlf",
"tests/test_wrapper.py::UniversalLineReaderTestCase::test_read_lf"
] |
[] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-11-02 05:12:05+00:00
|
mit
| 3,389 |
|
just-work__fffw-89
|
diff --git a/fffw/wrapper/params.py b/fffw/wrapper/params.py
index 11dc74a..a509f88 100644
--- a/fffw/wrapper/params.py
+++ b/fffw/wrapper/params.py
@@ -1,4 +1,4 @@
-from dataclasses import field, dataclass, Field, fields
+from dataclasses import field, dataclass, Field, fields, MISSING
from typing import Any, Optional, Tuple, cast, List, Callable
@@ -89,7 +89,7 @@ class Params:
for f in self._fields: # type: Field
key = f.name
value = getattr(self, key)
- if f.default == value and f.init:
+ if f.default is not MISSING and f.default == value and f.init:
# if field value has default value and is configurable via
# __init__, we omit this field
continue
|
just-work/fffw
|
05f7e819b81f44bb6b95c970e871d956e5098c07
|
diff --git a/tests/test_wrapper.py b/tests/test_wrapper.py
index ba68852..d6e4ea4 100644
--- a/tests/test_wrapper.py
+++ b/tests/test_wrapper.py
@@ -7,8 +7,10 @@ from dataclasses import dataclass
from typing import List
from unittest import TestCase, mock
+from fffw.graph import TS
from fffw.wrapper import param
from fffw.wrapper.base import UniversalLineReader, BaseWrapper
+from fffw.wrapper.params import Params
@dataclass
@@ -119,3 +121,20 @@ class UniversalLineReaderTestCase(TestCase):
with self.assertRaises(asyncio.LimitOverrunError):
self.assert_lines(lines)
+
+
+@dataclass
+class Wrapper(Params):
+ field: TS # no default and TS instance
+
+
+class ParamsTestCase(TestCase):
+ """ Check command line parameters rendering."""
+
+ def test_as_pairs_if_default_is_missing(self):
+ """
+ Checks that missing default does not checks value for equality with
+ dataclasses.MISSING.
+ """
+ w = Wrapper(TS(42.0))
+ self.assertEqual(w.as_pairs(), [('field', '42.0')])
|
Incorrect as_pairs behavior if default is not set
```python
File "/data/encoder/virtualenv/lib/python3.6/site-packages/fffw/wrapper/params.py", line 92, in as_pairs
if f.default == value and f.init:
File "/data/encoder/virtualenv/lib/python3.6/site-packages/fffw/graph/meta.py", line 104, in wrapper
return cast(BinaryOp, func)(self, TS(value)) # noqa
File "/data/encoder/virtualenv/lib/python3.6/site-packages/fffw/graph/meta.py", line 144, in __new__
return super().__new__(cls, value) # type: ignore
TypeError: float() argument must be a string or a number, not '_MISSING_TYPE'
```
There should be a MISSING check
|
0.0
|
05f7e819b81f44bb6b95c970e871d956e5098c07
|
[
"tests/test_wrapper.py::ParamsTestCase::test_as_pairs_if_default_is_missing"
] |
[
"tests/test_wrapper.py::WrapperTestCase::test_child_timeout",
"tests/test_wrapper.py::WrapperTestCase::test_run_child_process",
"tests/test_wrapper.py::UniversalLineReaderTestCase::test_buffer_overrun",
"tests/test_wrapper.py::UniversalLineReaderTestCase::test_empty_lines",
"tests/test_wrapper.py::UniversalLineReaderTestCase::test_empty_stream",
"tests/test_wrapper.py::UniversalLineReaderTestCase::test_last_incomplete_line",
"tests/test_wrapper.py::UniversalLineReaderTestCase::test_read_cr",
"tests/test_wrapper.py::UniversalLineReaderTestCase::test_read_crlf",
"tests/test_wrapper.py::UniversalLineReaderTestCase::test_read_lf"
] |
{
"failed_lite_validators": [
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-11-27 12:30:37+00:00
|
mit
| 3,390 |
|
just-work__fffw-93
|
diff --git a/fffw/graph/base.py b/fffw/graph/base.py
index e3e9d8b..45dac19 100644
--- a/fffw/graph/base.py
+++ b/fffw/graph/base.py
@@ -59,7 +59,14 @@ class Dest(Traversable):
@property
def meta(self) -> Optional[Meta]:
- return self.get_meta_data(self)
+ metadata = self.get_meta_data(self)
+ if metadata is None:
+ return None
+ return self.transform(metadata)
+
+ def transform(self, *metadata: Meta) -> Meta:
+ """ Apply codec changes to stream metadata."""
+ return metadata[0]
@property
def edge(self) -> Optional["Edge"]:
|
just-work/fffw
|
8e5e9c2ff766f31a90bf55dcfec2e6ac732b0478
|
diff --git a/tests/test_graph.py b/tests/test_graph.py
index b85e73b..ecf7948 100644
--- a/tests/test_graph.py
+++ b/tests/test_graph.py
@@ -1,4 +1,4 @@
-from dataclasses import dataclass
+from dataclasses import dataclass, replace
from typing import cast
from unittest import TestCase
@@ -6,6 +6,7 @@ from fffw.encoding import inputs, outputs, codecs
from fffw.encoding.complex import FilterComplex
from fffw.encoding.filters import *
from fffw.graph import *
+from fffw.wrapper import param
@dataclass
@@ -24,6 +25,15 @@ class ScaleCuda(Scale):
hardware = 'cuda'
+@dataclass
+class FdkAAC(codecs.AudioCodec):
+ codec = 'libfdk_aac'
+ bitrate: int = param(name='b', stream_suffix=True)
+
+ def transform(self, metadata: Meta) -> Meta:
+ return replace(metadata, bitrate=self.bitrate)
+
+
class FilterGraphTestCase(TestCase):
def setUp(self) -> None:
@@ -37,10 +47,18 @@ class FilterGraphTestCase(TestCase):
frame_rate=10.0,
frame_count=3000
)
+ self.source_audio_duration = 200.0
+ self.source_sampling_rate = 48000
+ self.source_samples_count = (self.source_audio_duration *
+ self.source_sampling_rate)
+ self.source_audio_bitrate = 128000
self.audio_metadata = audio_meta_data(
- duration=200.0,
- sampling_rate=48000,
- samples_count=200 * 48000)
+ duration=self.source_audio_duration,
+ sampling_rate=self.source_sampling_rate,
+ samples_count=self.source_samples_count,
+ bit_rate=self.source_audio_bitrate,
+ )
+ self.target_audio_bitrate = 64000
self.source = inputs.Input(
input_file='input.mp4',
@@ -49,7 +67,7 @@ class FilterGraphTestCase(TestCase):
self.output = outputs.output_file(
'output.mp4',
codecs.VideoCodec('libx264'),
- codecs.AudioCodec('libfdk_aac'))
+ FdkAAC(bitrate=self.target_audio_bitrate))
self.input_list = inputs.InputList((self.source,))
self.output_list = outputs.OutputList((self.output,))
self.fc = FilterComplex(self.input_list, self.output_list)
@@ -361,3 +379,26 @@ class FilterGraphTestCase(TestCase):
s | Upload(device=cuda) | UniversalFilter()
except ValueError: # pragma: no cover
self.fail("hardware validation unexpectedly failed")
+
+ def test_codec_metadata_transform(self):
+ """
+ Codecs parameters applied to stream metadata when using transform.
+ """
+ with self.subTest('codec with transform'):
+ self.source.audio > self.output
+ am = cast(AudioMeta, self.output.codecs[1].meta)
+ self.assertEqual(am.bitrate, self.target_audio_bitrate)
+
+ with self.subTest('no input metadata'):
+ no_meta_input = inputs.input_file('input.mp4')
+ output = outputs.output_file('output.mp4',
+ codecs.AudioCodec('aac'))
+ no_meta_input.audio > output.audio
+ self.assertIsNone(output.codecs[0].meta)
+
+ with self.subTest('no transform'):
+ output = outputs.output_file('output.mp4',
+ codecs.AudioCodec('aac'))
+ self.source.audio > output.audio
+ am = cast(AudioMeta, output.codecs[0].meta)
+ self.assertEqual(am.bitrate, self.audio_metadata.bitrate)
diff --git a/tests/test_vector.py b/tests/test_vector.py
index bc4e8c8..3f74cf0 100644
--- a/tests/test_vector.py
+++ b/tests/test_vector.py
@@ -9,6 +9,15 @@ from tests.base import BaseTestCase
from tests.test_ffmpeg import Volume
+@dataclass
+class AAC(AudioCodec):
+ codec = 'aac'
+ bitrate: int = param(name='b', stream_suffix=True)
+
+ def transform(self, metadata: Meta) -> Meta:
+ return replace(metadata, bitrate=self.bitrate)
+
+
@dataclass
class StubFilter(AudioFilter):
filter = 'stub'
@@ -30,13 +39,14 @@ class VectorTestCase(BaseTestCase):
def setUp(self) -> None:
super().setUp()
self.video_meta = video_meta_data(width=1920, height=1080)
- self.audio_meta = audio_meta_data()
+ self.audio_meta = audio_meta_data(bit_rate=128000)
+ self.audio_bitrate = 64000
self.source = input_file('input.mp4',
Stream(VIDEO, self.video_meta),
Stream(AUDIO, self.audio_meta))
self.output1 = output_file('output1.mp4',
VideoCodec('libx264'),
- AudioCodec('aac'))
+ AAC(bitrate=self.audio_bitrate))
self.output2 = output_file('output2.mp5',
VideoCodec('libx265'),
AudioCodec('libfdk_aac'))
@@ -63,7 +73,9 @@ class VectorTestCase(BaseTestCase):
"""
with self.subTest("input meta"):
v = self.simd.video
+ a = self.simd.audio
self.assertEqual(v.meta, self.video_meta)
+ self.assertEqual(a.meta, self.audio_meta)
with self.subTest("filter meta"):
v = v | Scale(1280, 720)
@@ -71,9 +83,10 @@ class VectorTestCase(BaseTestCase):
self.assertEqual(v.meta, expected)
with self.subTest("codec meta"):
+ expected = replace(self.audio_meta, bitrate=self.audio_bitrate)
simd = SIMD(self.source, self.output1)
- x = v > simd
- self.assertEqual(x.meta, expected)
+ a = a > simd
+ self.assertEqual(a.meta, expected)
def test_vector_metadata_for_multiple_streams(self):
"""
@@ -88,7 +101,7 @@ class VectorTestCase(BaseTestCase):
self.assert_simd_args(
'-i', 'input.mp4',
'-map', '0:v', '-c:v', 'libx264',
- '-map', '0:a', '-c:a', 'aac',
+ '-map', '0:a', '-c:a', 'aac', '-b:a', '64000',
'output1.mp4',
'-map', '0:v', '-c:v', 'libx265',
'-map', '0:a', '-c:a', 'libfdk_aac',
@@ -105,7 +118,7 @@ class VectorTestCase(BaseTestCase):
'[0:a]volume=30.00[a:volume0];'
'[a:volume0]asplit[aout0][aout1]',
'-map', '0:v', '-c:v', 'libx264',
- '-map', '[aout0]', '-c:a', 'aac',
+ '-map', '[aout0]', '-c:a', 'aac', '-b:a', '64000',
'output1.mp4',
'-map', '0:v', '-c:v', 'libx265',
'-map', '[aout1]', '-c:a', 'libfdk_aac',
@@ -122,7 +135,7 @@ class VectorTestCase(BaseTestCase):
'[0:a]asplit[a:asplit0][aout0];'
'[a:asplit0]volume=30.00[aout1]',
'-map', '0:v', '-c:v', 'libx264',
- '-map', '[aout0]', '-c:a', 'aac',
+ '-map', '[aout0]', '-c:a', 'aac', '-b:a', '64000',
'output1.mp4',
'-map', '0:v', '-c:v', 'libx265',
'-map', '[aout1]', '-c:a', 'libfdk_aac',
@@ -137,7 +150,7 @@ class VectorTestCase(BaseTestCase):
'-filter_complex',
'[0:a]asplit[aout0][aout1]',
'-map', '0:v', '-c:v', 'libx264',
- '-map', '[aout0]', '-c:a', 'aac',
+ '-map', '[aout0]', '-c:a', 'aac', '-b:a', '64000',
'output1.mp4',
'-map', '0:v', '-c:v', 'libx265',
'-map', '[aout1]', '-c:a', 'libfdk_aac',
@@ -154,7 +167,7 @@ class VectorTestCase(BaseTestCase):
'[a:asplit0]volume=20.00[aout0];'
'[a:asplit1]volume=30.00[aout1]',
'-map', '0:v', '-c:v', 'libx264',
- '-map', '[aout0]', '-c:a', 'aac',
+ '-map', '[aout0]', '-c:a', 'aac', '-b:a', '64000',
'output1.mp4',
'-map', '0:v', '-c:v', 'libx265',
'-map', '[aout1]', '-c:a', 'libfdk_aac',
@@ -170,7 +183,7 @@ class VectorTestCase(BaseTestCase):
'[0:a]volume=30.00[a:volume0];'
'[a:volume0]asplit[aout0][aout1]',
'-map', '0:v', '-c:v', 'libx264',
- '-map', '[aout0]', '-c:a', 'aac',
+ '-map', '[aout0]', '-c:a', 'aac', '-b:a', '64000',
'output1.mp4',
'-map', '0:v', '-c:v', 'libx265',
'-map', '[aout1]', '-c:a', 'libfdk_aac',
@@ -193,7 +206,7 @@ class VectorTestCase(BaseTestCase):
'[a:asplit1]volume=30.00[a:volume1];'
'[a:volume1]stub[aout1]',
'-map', '0:v', '-c:v', 'libx264',
- '-map', '[aout0]', '-c:a', 'aac',
+ '-map', '[aout0]', '-c:a', 'aac', '-b:a', '64000',
'output1.mp4',
'-map', '0:v', '-c:v', 'libx265',
'-map', '[aout1]', '-c:a', 'libfdk_aac',
@@ -227,7 +240,7 @@ class VectorTestCase(BaseTestCase):
'[v:split4][v:scale0]overlay[vout0];'
'[v:split5][v:scale1]overlay[vout1]',
'-map', '[vout0]', '-c:v', 'libx264',
- '-map', '0:a', '-c:a', 'aac',
+ '-map', '0:a', '-c:a', 'aac', '-b:a', '64000',
'output1.mp4',
'-map', '[vout1]', '-c:v', 'libx265',
'-map', '0:a', '-c:a', 'libfdk_aac',
@@ -255,7 +268,7 @@ class VectorTestCase(BaseTestCase):
'[v:split2][v:scale0]overlay[vout0];'
'[v:split3][v:scale1]overlay[vout1]',
'-map', '[vout0]', '-c:v', 'libx264',
- '-map', '0:a', '-c:a', 'aac',
+ '-map', '0:a', '-c:a', 'aac', '-b:a', '64000',
'output1.mp4',
'-map', '[vout1]', '-c:v', 'libx265',
'-map', '0:a', '-c:a', 'libfdk_aac',
@@ -279,7 +292,7 @@ class VectorTestCase(BaseTestCase):
'[0:v]split[v:split0][vout0];'
'[1:v][v:split0]overlay[vout1]',
'-map', '[vout1]', '-c:v', 'libx264',
- '-map', '0:a', '-c:a', 'aac',
+ '-map', '0:a', '-c:a', 'aac', '-b:a', '64000',
'output1.mp4',
'-map', '[vout0]', '-c:v', 'libx265',
'-map', '0:a', '-c:a', 'libfdk_aac',
@@ -310,7 +323,7 @@ class VectorTestCase(BaseTestCase):
'[1:v][v:split0]concat[vout1];'
'[1:a][a:asplit0]concat=v=0:a=1:n=2[aout1]',
'-map', '[vout1]', '-c:v', 'libx264',
- '-map', '[aout1]', '-c:a', 'aac',
+ '-map', '[aout1]', '-c:a', 'aac', '-b:a', '64000',
'output1.mp4',
'-map', '[vout0]', '-c:v', 'libx265',
'-map', '[aout0]', '-c:a', 'libfdk_aac',
@@ -333,7 +346,7 @@ class VectorTestCase(BaseTestCase):
'[1:v]scale=w=120:h=120[v:scale0];'
'[0:v][v:scale0]overlay[v:overlay0]',
'-map', '[vout0]', '-c:v', 'libx264',
- '-map', '0:a', '-c:a', 'aac',
+ '-map', '0:a', '-c:a', 'aac', '-b:a', '64000',
'output1.mp4',
'-map', '[vout1]', '-c:v', 'libx265',
'-map', '0:a', '-c:a', 'libfdk_aac',
@@ -365,7 +378,7 @@ class VectorTestCase(BaseTestCase):
'-map', '[vout0]',
'-c:v', 'libx264',
'-map', '[aout0]',
- '-c:a', 'aac',
+ '-c:a', 'aac', '-b:a', '64000',
'output1.mp4',
'-map', '[vout1]',
'-c:v', 'libx265',
|
Codecs should transform meta
I.e. AudioCodec: when changing sampling rate, it should also change samples count.
For VideoCodec frame rate could be changed and frames count (#66) will also change.
|
0.0
|
8e5e9c2ff766f31a90bf55dcfec2e6ac732b0478
|
[
"tests/test_graph.py::FilterGraphTestCase::test_codec_metadata_transform",
"tests/test_vector.py::VectorTestCase::test_vector_metadata"
] |
[
"tests/test_graph.py::FilterGraphTestCase::test_any_hardware_filter",
"tests/test_graph.py::FilterGraphTestCase::test_audio_trim_metadata",
"tests/test_graph.py::FilterGraphTestCase::test_concat_audio_metadata",
"tests/test_graph.py::FilterGraphTestCase::test_concat_video_metadata",
"tests/test_graph.py::FilterGraphTestCase::test_disabled_filters",
"tests/test_graph.py::FilterGraphTestCase::test_ensure_audio",
"tests/test_graph.py::FilterGraphTestCase::test_ensure_video",
"tests/test_graph.py::FilterGraphTestCase::test_filter_graph",
"tests/test_graph.py::FilterGraphTestCase::test_filter_validates_hardware_device",
"tests/test_graph.py::FilterGraphTestCase::test_filter_validates_stream_kind",
"tests/test_graph.py::FilterGraphTestCase::test_overlay_metadata",
"tests/test_graph.py::FilterGraphTestCase::test_scale_changes_metadata",
"tests/test_graph.py::FilterGraphTestCase::test_setpts_metadata",
"tests/test_graph.py::FilterGraphTestCase::test_skip_not_connected_sources",
"tests/test_graph.py::FilterGraphTestCase::test_video_trim_metadata",
"tests/test_vector.py::VectorTestCase::test_apply_filter_with_equal_params",
"tests/test_vector.py::VectorTestCase::test_apply_filter_with_params_vector",
"tests/test_vector.py::VectorTestCase::test_clone_filter_with_skipped_params",
"tests/test_vector.py::VectorTestCase::test_clone_inputs_for_destination_filter",
"tests/test_vector.py::VectorTestCase::test_clone_streams",
"tests/test_vector.py::VectorTestCase::test_connect_filter_to_a_vector",
"tests/test_vector.py::VectorTestCase::test_connect_stream_to_simd",
"tests/test_vector.py::VectorTestCase::test_multiple_disabled_filters",
"tests/test_vector.py::VectorTestCase::test_no_filter_graph",
"tests/test_vector.py::VectorTestCase::test_overlay_with_mask",
"tests/test_vector.py::VectorTestCase::test_preroll_with_mask",
"tests/test_vector.py::VectorTestCase::test_same_filter_for_all_streams",
"tests/test_vector.py::VectorTestCase::test_same_filter_with_mask",
"tests/test_vector.py::VectorTestCase::test_split_filter_if_vector_differs",
"tests/test_vector.py::VectorTestCase::test_vector_kind",
"tests/test_vector.py::VectorTestCase::test_vector_metadata_for_multiple_streams"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_issue_reference"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-12-21 14:03:27+00:00
|
mit
| 3,391 |
|
jwplayer__jwplatform-py-20
|
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())
|
jwplayer/jwplatform-py
|
be9d31a94f85b8846c8517b5fe2b065c5d7bfad9
|
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__)
|
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
```
|
0.0
|
be9d31a94f85b8846c8517b5fe2b065c5d7bfad9
|
[
"tests/test_init.py::test_custom_initialization_empty_kwargs"
] |
[
"tests/test_init.py::test_default_initialization",
"tests/test_init.py::test_custom_initialization"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2017-11-17 21:41:54+00:00
|
mit
| 3,392 |
|
kaizendorks__pymongo_inmemory-91
|
diff --git a/README.md b/README.md
index 1e6b132..18ef7ba 100644
--- a/README.md
+++ b/README.md
@@ -7,6 +7,7 @@ A mongo mocking library with an ephemeral MongoDB running in memory.
## What's new?
### v0.4.0-pre
+
- Tooling enhancements. [[PR #90](https://github.com/kaizendorks/pymongo_inmemory/pull/90)]
### v0.3.1
@@ -60,18 +61,19 @@ with MongoClient() as client:
## Configuration
-| Config param | Description | Optional? | Default |
-| ------------------ | ---------------------------------------------------------------------------------------------------------- | --------- | -------------------------------------------------------------------------------------------------------------------------- |
-| `mongo_version` | Which MongoD version to download and use. | Yes | Latest for the OS |
-| `mongod_port` | Override port preference. | Yes | Automatically picked between `27017` and `28000` after testing availability |
-| `operating_system` | This makes sense for Linux setting, where there are several flavours | Yes | Automatically determined (Generic for Linux)\* |
-| `os_version` | If an operating system has several versions use this parameter to select one | Yes | Latest version of the OS will be selected from the list |
-| `download_url` | If set, it won't attempt to determine which MongoDB to download. However there won't be a fallback either. | Yes | Automatically determined from given parameters and using [internal URL bank](pymongo_inmemory/downloader/_patterns.py)\*\* |
-| `ignore_cache` | Even if there is a downloaded version in the cache, download it again. | Yes | False |
-| `use_local_mongod` | If set, it will try to use a local mongod instance instead of downloading one. | Yes | False |
-| `download_folder` | Override the default download location. | Yes | pymongo_inmemory/.cache/download |
-| `extract_folder` | Override the default extraction location. | Yes | pymongo_inmemory/.cache/extract |
-| | | |
+| | Config parameter | Description Default |
+| ------- | -------------------- | ---------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
+| | `mongo_version` | Which MongoD version to download and use. | Latest for the OS |
+| | `mongod_port` | Override port preference. | Automatically picked between `27017` and `28000` after testing availability |
+| | `operating_system` | This makes sense for Linux setting, where there are several flavours | Automatically determined (Generic for Linux)\* |
+| | `os_version` | If an operating system has several versions use this parameter to select one | Latest version of the OS will be selected from the list |
+| | `download_url` | If set, it won't attempt to determine which MongoDB to download. However there won't be a fallback either. | Automatically determined from given parameters and using [internal URL bank](pymongo_inmemory/downloader/_patterns.py)\*\* |
+| | `ignore_cache` | Even if there is a downloaded version in the cache, download it again. | False |
+| | `use_local_mongod` | If set, it will try to use a local mongod instance instead of downloading one. | False |
+| | `download_folder` | Override the default download location. | pymongo_inmemory/.cache/download |
+| | `extract_folder` | Override the default extraction location. | pymongo_inmemory/.cache/extract |
+| **NEW** | `mongod_data_folder` | Provide a data folder to be used by MongoD. | A `TemporaryDirectory` will be used |
+| | | |
- \***_Note 1:_** Generic Linux version offering for MongoDB ends with version **4.0.23**. If the operating system is just `linux` and if selected MongoDB version is higher, it will default to `4.0.23`.
- **\***Note 2:\*\*\* URL bank is filled with URLs collected from [release list](https://www.mongodb.com/download-center/community/releases) and [archived released list](https://www.mongodb.com/download-center/community/releases/archive), so if a version is not in the bank you can use the same list to provide an official download link.
diff --git a/pymongo_inmemory/context.py b/pymongo_inmemory/context.py
index 00f6e57..e52083c 100644
--- a/pymongo_inmemory/context.py
+++ b/pymongo_inmemory/context.py
@@ -103,6 +103,7 @@ class Context:
) -> None:
self.mongo_version = conf("mongo_version", version)
self.mongod_port = conf("mongod_port", None, coerce_with=int)
+ self.mongod_data_folder = conf("mongod_data_folder", None)
self.operating_system = self._build_operating_system_info(os_name)
self.os_version = conf("os_version", os_ver)
@@ -129,6 +130,7 @@ class Context:
return (
f"Mongo Version {self.mongo_version}\n"
f"MongoD Port {self.mongod_port}\n"
+ f"MongoD Data Folder {self.mongod_data_folder}\n"
f"OS Name {self.operating_system}\n"
f"OS Version {self.os_version}\n"
f"Download URL {self.download_url}\n"
diff --git a/pymongo_inmemory/mongod.py b/pymongo_inmemory/mongod.py
index c09ce6f..6b0fc58 100644
--- a/pymongo_inmemory/mongod.py
+++ b/pymongo_inmemory/mongod.py
@@ -87,7 +87,10 @@ class Mongod:
self._connection_string = None
self.config = MongodConfig(self._pim_context)
- self.data_folder = TemporaryDirectory(prefix="pymongoim")
+
+ self._temp_data_folder = TemporaryDirectory(prefix="pymongoim")
+ self._using_tmp_folder = self._pim_context.mongod_data_folder is None
+
self._client = pymongo.MongoClient(self.connection_string)
def __enter__(self):
@@ -98,22 +101,14 @@ class Mongod:
self.stop()
def start(self):
- while self.is_locked:
- logger.warning(
- (
- "Lock file found, possibly another mock server is running. "
- "Changing the data folder."
- )
- )
- self.data_folder = TemporaryDirectory(prefix="pymongoim")
-
- self.log_path = os.path.join(self.data_folder.name, "mongod.log")
+ self._check_lock()
+ self.log_path = os.path.join(self.data_folder, "mongod.log")
logger.info("Starting mongod with {cs}...".format(cs=self.connection_string))
boot_command = [
os.path.join(self._bin_folder, "mongod"),
"--dbpath",
- self.data_folder.name,
+ self.data_folder,
"--logpath",
self.log_path,
"--port",
@@ -137,7 +132,14 @@ class Mongod:
while self._proc.poll() is None:
logger.debug("Waiting for MongoD shutdown.")
time.sleep(1)
- self.data_folder.cleanup()
+ self._clean_up()
+
+ @property
+ def data_folder(self):
+ if self._using_tmp_folder:
+ return self._temp_data_folder.name
+ else:
+ return self._pim_context.mongod_data_folder
@property
def connection_string(self):
@@ -155,7 +157,7 @@ class Mongod:
@property
def is_locked(self):
- return os.path.exists(os.path.join(self.data_folder.name, "mongod.lock"))
+ return os.path.exists(os.path.join(self.data_folder, "mongod.lock"))
@property
def is_healthy(self):
@@ -199,6 +201,27 @@ class Mongod:
with open(self.log_path, "r") as logfile:
return logfile.readlines()
+ def _clean_up(self):
+ if self._using_tmp_folder:
+ self._temp_data_folder.cleanup()
+
+ def _check_lock(self):
+ while self.is_locked:
+ if self._using_tmp_folder:
+ raise RuntimeError(
+ (
+ "There is a lock file in the provided data folder. "
+ "Make sure that no other MongoDB is running."
+ )
+ )
+ logger.warning(
+ (
+ "Lock file found, possibly another mock server is running. "
+ "Changing the data folder."
+ )
+ )
+ self._temp_data_folder = TemporaryDirectory(prefix="pymongoim")
+
if __name__ == "__main__":
# This part is used for integrity tests too.
|
kaizendorks/pymongo_inmemory
|
d20eba3ffc53e21040e6b899bc3dc90092ce324d
|
diff --git a/tests/unit/test_mongod.py b/tests/unit/test_mongod.py
new file mode 100644
index 0000000..986c7be
--- /dev/null
+++ b/tests/unit/test_mongod.py
@@ -0,0 +1,37 @@
+import subprocess
+
+from pymongo_inmemory.mongod import Mongod
+import pymongo_inmemory.downloader as downloader
+from pymongo_inmemory.context import Context
+
+
+class Popen:
+ def __init__(self, cmd):
+ self.cmd = cmd
+ self.terminated = False
+
+ def terminate(self):
+ self.terminated = True
+
+ def poll(self):
+ return True
+
+
+def returns_true():
+ return True
+
+
+def download():
+ return ""
+
+
+def test_mongod(monkeypatch):
+ monkeypatch.setattr(subprocess, "Popen", Popen)
+ monkeypatch.setattr(Mongod, "is_healthy", returns_true)
+ monkeypatch.setattr(downloader, "download", download)
+
+ context = Context()
+ context.mongod_data_folder = "TEST"
+
+ with Mongod(context) as md:
+ assert md.data_folder == "TEST"
|
pymongo_inmemory does not work in a docker container when /tmp directory is mounted. No bypass available.
**Describe the bug**
I have a complicated CLI docker container that I share with my developers. In it, I have created a kubernetes plugin, `kubectl query` which allows us to load internal data into an in-memory and search it. It works great and as expected when running on MacOS.
When packaged and launched our docker container, we mount the `/tmp` directory as a method of porting data inbetween the Mac and the Ubuntu container. This allows us to easily transfer our scratch data between the OS in Ubuntu and Mac. This is often used for other kubectl plugins that we have written.
The fact that we are mounting the `/tmp` directory is not playing well with `pymongo_inmemory`. I have discovered that if we opt not to mount the `/tmp` directory, then `pymongo_inmemory` correctly starts. Only when we mount the `/tmp` directory, does `pymongo_inmemory` fail to connect. *This is reproducible with the code below*.
I have attempted furthermore to bypass this issue by setting the `TMPDIR`, `TEMP`, and `TMP` directories, so that the `tempfile` package ignores the volume mounting. However, I am still exhibiting this problem.
**To Reproduce**
Steps to reproduce the behavior:
1. Create a Dockerfile:
```
FROM ubuntu:20.04
RUN apt-get update && apt-get -y install \
bash \
bash-completion \
bash-doc \
python3 \
python3-dev \
python3-pip
RUN pip3 install --upgrade pymongo_inmemory==0.3.0
RUN echo '\n\
from pymongo_inmemory import MongoClient \n\
client = MongoClient() \n\
db = client["testdb"] \n\
collection = db["test-collection"] \n\
# etc., etc. \n\
client.close() \n'\
> /query.py
CMD /bin/bash
```
2. Build Dockerfile
```
docker build ./ -t temp --platform=linux/x86_64
```
3. Run Docker file, everything will be OK:
```
docker run --platform=linux/x86_64 -it temp python3 query.py
```
4. Run Docker file, override mount, this will fail:
```
docker run -v /tmp:/tmp --platform=linux/x86_64 -it temp python3 query.py
```
5. Attempt patching with different tempdir, Run Docker file, override mount, this will fail:
```
docker run -e TMPDIR=/pytemp -v /tmp:/tmp --platform=linux/x86_64 -it temp python3 query.py
```
*Full Error*
```
$ docker run -e TMPDIR=/pytemp -v /tmp:/tmp --platform=linux/x86_64 -it temp python3 query.py
Starting from MongoDB 4.0.23 there isn't a generic Linux version of MongoDB
Traceback (most recent call last):
File "query.py", line 3, in <module>
client = MongoClient()
File "/usr/local/lib/python3.8/dist-packages/pymongo_inmemory/_pim.py", line 11, in __init__
self._mongod.start()
File "/usr/local/lib/python3.8/dist-packages/pymongo_inmemory/mongod.py", line 130, in start
while not self.is_healthy:
File "/usr/local/lib/python3.8/dist-packages/pymongo_inmemory/mongod.py", line 164, in is_healthy
status = db.command("serverStatus")
File "/usr/local/lib/python3.8/dist-packages/pymongo/_csot.py", line 108, in csot_wrapper
return func(self, *args, **kwargs)
File "/usr/local/lib/python3.8/dist-packages/pymongo/database.py", line 892, in command
with self.__client._conn_for_reads(read_preference, session) as (
File "/usr/local/lib/python3.8/dist-packages/pymongo/mongo_client.py", line 1340, in _conn_for_reads
server = self._select_server(read_preference, session)
File "/usr/local/lib/python3.8/dist-packages/pymongo/mongo_client.py", line 1297, in _select_server
server = topology.select_server(server_selector)
File "/usr/local/lib/python3.8/dist-packages/pymongo/topology.py", line 312, in select_server
server = self._select_server(selector, server_selection_timeout, address)
File "/usr/local/lib/python3.8/dist-packages/pymongo/topology.py", line 296, in _select_server
servers = self.select_servers(selector, server_selection_timeout, address)
File "/usr/local/lib/python3.8/dist-packages/pymongo/topology.py", line 247, in select_servers
server_descriptions = self._select_servers_loop(selector, server_timeout, address)
File "/usr/local/lib/python3.8/dist-packages/pymongo/topology.py", line 269, in _select_servers_loop
raise ServerSelectionTimeoutError(
pymongo.errors.ServerSelectionTimeoutError: 127.0.0.1:27017: [Errno 111] Connection refused, Timeout: 30s, Topology Description: <TopologyDescription id: 650b42c35fed3c72b372d834, topology_type: Unknown, servers: [<ServerDescription ('127.0.0.1', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('127.0.0.1:27017: [Errno 111] Connection refused')>]>
```
**Expected behavior**
I was expecting successful startup of Mongo DB:
```
$ docker run --platform=linux/x86_64 -it temp python3 query.py
Starting from MongoDB 4.0.23 there isn't a generic Linux version of MongoDB
```
In the event that MongoDB can't share the `/tmp` directory with MacOS, I was expecting `TMPDIR` to get the system working. *NOTE:* `pymongo_inmemory` *is* respecting the `TMPDIR` environment variable, it just isn't starting Mongodb, and I'm not sure why.
**Logs**
See above error.
**Screenshots**
N/A
**Context:**
- OS: Apple M1 Pro, Ventura 13.4.1 w/ Docker Container ubuntu:20.04
- Version of pymongo_inmemory: 0.3.0
- Version of mongo you are downloading: 4.0.23
- Version of Docker: 4.20.1 (110738)
- Any other additional information about context
Workarounds instead of direct fixes are acceptable to me.
|
0.0
|
d20eba3ffc53e21040e6b899bc3dc90092ce324d
|
[
"tests/unit/test_mongod.py::test_mongod"
] |
[] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-09-30 14:16:58+00:00
|
mit
| 3,393 |
|
kangasta__fdbk-51
|
diff --git a/fdbk/_db_connection.py b/fdbk/_db_connection.py
index 5a4f371..4769179 100644
--- a/fdbk/_db_connection.py
+++ b/fdbk/_db_connection.py
@@ -106,7 +106,14 @@ class DBConnection:
'''
return self.get_data(topic_id)[-1]
- def get_summary(self, topic_id, since=None, until=None, limit=None):
+ def get_summary(
+ self,
+ topic_id,
+ since=None,
+ until=None,
+ limit=None,
+ aggregate_to=None,
+ aggregate_with=None):
'''Get summary of the topic data
Args:
@@ -114,6 +121,8 @@ class DBConnection:
since: Datetime of the earliest entry to include
until: Datetime of the most recent entry to include
limit: Number of entries to include from the most recent
+ aggregate_to: Aggregate data into specified number of data points
+ aggregate_with: Aggregate data with speficied function
Returns:
Dictionary with summary of the topic
@@ -133,7 +142,8 @@ class DBConnection:
"warnings": []
}
- results, warnings = run_data_tools(topic_d, data_d)
+ results, warnings = run_data_tools(
+ topic_d, data_d, aggregate_to, aggregate_with)
summary_d["warnings"].extend(warnings)
results, warnings = post_process(results)
@@ -147,7 +157,9 @@ class DBConnection:
type_=None,
since=None,
until=None,
- limit=None):
+ limit=None,
+ aggregate_to=None,
+ aggregate_with=None):
if not topic_ids:
# TODO: only fetch topics list once in this function
topic_ids = [topic["id"] for topic in self.get_topics(type_)]
@@ -168,7 +180,8 @@ class DBConnection:
result_d["topic_names"].append(topic_d["name"])
result_d["fields"].extend(topic_d["fields"])
- new_results, warnings = run_data_tools(topic_d, data_d)
+ new_results, warnings = run_data_tools(
+ topic_d, data_d, aggregate_to, aggregate_with)
results.extend(new_results)
result_d["warnings"].extend(warnings)
@@ -192,7 +205,9 @@ class DBConnection:
type_=None,
since=None,
until=None,
- limit=None):
+ limit=None,
+ aggregate_to=None,
+ aggregate_with=None):
'''Get overview of the data
Args:
@@ -203,6 +218,8 @@ class DBConnection:
since: Datetime of the earliest entry to include
until: Datetime of the most recent entry to include
limit: Number of entries to include from the most recent
+ aggregate_to: Aggregate data into specified number of data points
+ aggregate_with: Aggregate data with speficied function
Returns:
Dictionary with overview of the topics data
@@ -215,7 +232,9 @@ class DBConnection:
type_=type_,
since=since,
until=until,
- limit=limit)
+ limit=limit,
+ aggregate_to=aggregate_to,
+ aggregate_with=aggregate_with)
ConnectionClass = DBConnection
diff --git a/fdbk/data_tools/__init__.py b/fdbk/data_tools/__init__.py
index a60d0f6..0096656 100644
--- a/fdbk/data_tools/__init__.py
+++ b/fdbk/data_tools/__init__.py
@@ -5,4 +5,5 @@ Functions to ease the simple data analysis done by the DBConnection.
'''
from .functions import *
+from ._aggregate import *
from ._utils import *
diff --git a/fdbk/data_tools/_aggregate.py b/fdbk/data_tools/_aggregate.py
new file mode 100644
index 0000000..007d604
--- /dev/null
+++ b/fdbk/data_tools/_aggregate.py
@@ -0,0 +1,66 @@
+from datetime import timezone
+from dateutil.parser import isoparse
+
+from fdbk.utils import timestamp_as_str
+from fdbk.utils.messages import (
+ method_not_supported)
+
+from .functions import functions as data_functions, VALUE_FUNCS
+
+
+def _dt_timestamp(data_point):
+ return isoparse(data_point.get('timestamp'))
+
+
+def _as_naive_utc(dt_timestamp):
+ return dt_timestamp.astimezone(timezone.utc).replace(tzinfo=None)
+
+
+def _get_keys(data_point):
+ return [key for key in data_point if key != 'timestamp']
+
+
+def aggregate(data, aggregate_to, aggregate_with=None):
+ if not aggregate_with:
+ aggregate_with = 'average'
+
+ warnings = []
+ aggregated = []
+
+ if aggregate_with not in VALUE_FUNCS:
+ warnings.append(method_not_supported(aggregate_with))
+ return ([], warnings,)
+
+ start = _dt_timestamp(data[0])
+ end = _dt_timestamp(data[-1])
+ window = (end - start) / aggregate_to
+
+ keys = _get_keys(data[0])
+ remaining = data
+ for i in range(aggregate_to):
+ try:
+ last = next(j for j, a in enumerate(remaining)
+ if _dt_timestamp(a) > start + (i + 1) * window)
+ current = remaining[:last]
+ if not current:
+ continue
+ remaining = remaining[last:]
+ except StopIteration:
+ if i == (aggregate_to - 1):
+ current = remaining
+ else:
+ continue
+
+ aggregated_point = dict(
+ timestamp=timestamp_as_str(
+ _as_naive_utc(
+ start + i * window)))
+ for key in keys:
+ try:
+ aggregated_point[key] = data_functions[aggregate_with](
+ current, key, None).get('payload').get('value')
+ except BaseException:
+ aggregated_point[key] = None
+ aggregated.append(aggregated_point)
+
+ return (aggregated, warnings,)
diff --git a/fdbk/data_tools/_utils.py b/fdbk/data_tools/_utils.py
index 0b5dea2..1158389 100644
--- a/fdbk/data_tools/_utils.py
+++ b/fdbk/data_tools/_utils.py
@@ -1,8 +1,9 @@
from fdbk.utils.messages import (
method_not_supported, field_is_undefined, collection_name_is_undefined)
-from .functions import functions as data_functions
+from .functions import functions as data_functions, CHART_FUNCS
from .functions.utils import chart_dict, statistics_dict
+from ._aggregate import aggregate
def _create_chart(type_, field):
@@ -180,10 +181,17 @@ def post_process(statistics):
return _process(funcs, statistics)
-def run_data_tools(topic_d, data):
+def run_data_tools(topic_d, data, aggregate_to=None, aggregate_with=None):
results = []
warnings = []
+ if aggregate_to:
+ chart_data, aggregate_warnings = aggregate(
+ data, aggregate_to, aggregate_with)
+ warnings.extend(aggregate_warnings)
+ else:
+ chart_data = data
+
for instruction in topic_d['data_tools']:
if instruction["method"] not in data_functions:
warnings.append(method_not_supported(instruction["method"]))
@@ -191,9 +199,12 @@ def run_data_tools(topic_d, data):
if instruction["field"] not in topic_d["fields"]:
warnings.append(field_is_undefined(instruction["field"]))
continue
+ is_chart = instruction["method"] in CHART_FUNCS
result = data_functions[instruction.get("method")](
- data, instruction.get("field"), instruction.get("parameters")
+ data if not is_chart else chart_data,
+ instruction.get("field"),
+ instruction.get("parameters")
)
if result is not None:
result["payload"]["topic_name"] = topic_d["name"]
diff --git a/fdbk/server/_server_handlers.py b/fdbk/server/_server_handlers.py
index a651cc3..b80865a 100644
--- a/fdbk/server/_server_handlers.py
+++ b/fdbk/server/_server_handlers.py
@@ -11,13 +11,23 @@ def _parse_param(param, parser):
return None
-def parse_filter_parameters(args):
- return dict(
+def parse_filter_parameters(args, include_aggregate=False):
+ query = dict(
since=_parse_param(args.get('since'), isoparse),
until=_parse_param(args.get('until'), isoparse),
- limit=_parse_param(args.get('limit'), int),
+ limit=_parse_param(args.get('limit'), int)
)
+ if not include_aggregate:
+ return query
+
+ aggregate = dict(
+ aggregate_to=_parse_param(args.get('aggregate_to'), int),
+ aggregate_with=args.get('aggregate_with')
+ )
+
+ return {**aggregate, **query}
+
def _get_response_or_not_found(function, args, kwargs=None):
if not kwargs:
@@ -94,7 +104,7 @@ class ServerHandlers:
return _get_response_or_not_found(
self._db_connection.get_summary,
(topic_id,),
- parse_filter_parameters(query_args))
+ parse_filter_parameters(query_args, include_aggregate=True))
def get_comparison(self, topic_ids=None, query_args=None):
topic_ids_a = topic_ids.split(',') if topic_ids else None
@@ -102,8 +112,10 @@ class ServerHandlers:
query_args = {}
try:
+ params = parse_filter_parameters(
+ query_args, include_aggregate=True)
data = self._db_connection.get_comparison(
- topic_ids_a, **parse_filter_parameters(query_args))
+ topic_ids_a, **params)
return data, 200
except KeyError as error:
return {
@@ -115,8 +127,10 @@ class ServerHandlers:
query_args = {}
try:
+ params = parse_filter_parameters(
+ query_args, include_aggregate=True)
data = self._db_connection.get_overview(
- type_=type_, **parse_filter_parameters(query_args))
+ type_=type_, **params)
return data, 200
except KeyError as error:
return {
diff --git a/setup.py b/setup.py
index d66ef0a..d4ca26c 100644
--- a/setup.py
+++ b/setup.py
@@ -30,6 +30,7 @@ setuptools.setup(
"importlib_resources; python_version<'3.7'",
"jsonschema",
"flask",
+ "python-dateutil",
"requests"
],
python_requires='>=3.6',
|
kangasta/fdbk
|
61edb0c86488a0dc9d74247ccee3f792d9bde077
|
diff --git a/tst/test_data_tools.py b/tst/test_data_tools.py
index d35e951..c253a03 100644
--- a/tst/test_data_tools.py
+++ b/tst/test_data_tools.py
@@ -1,10 +1,14 @@
from unittest import TestCase
from unittest.mock import Mock, patch
-from fdbk.data_tools import functions
+from fdbk.data_tools import aggregate, functions
+from fdbk.utils.messages import method_not_supported
-def generate_test_numbers(N=10):
- return [dict(number=i) for i in range(N)]
+def _test_timestamp(i):
+ return f'2020-08-23T00:{i // 60:02}:{i % 60:02}Z'
+
+def generate_test_data(N=10):
+ return [dict(number=i, number2=i*2, letter=chr(ord('A') + i), timestamp=_test_timestamp(i)) for i in range(N)]
class DataToolsTest(TestCase):
def test_summary_funcs_return_none_on_empty_data(self):
@@ -12,7 +16,7 @@ class DataToolsTest(TestCase):
self.assertIsNone(fn([], 'field'))
def test_value_functions(self):
- data = generate_test_numbers()
+ data = generate_test_data()
tests = [
('average', 4.5,),
@@ -27,4 +31,40 @@ class DataToolsTest(TestCase):
result = functions.get(type_)(data, 'number')
self.assertEqual(result.get('payload').get('type'), type_)
- self.assertEqual(result.get('payload').get('value'), value)
\ No newline at end of file
+ self.assertEqual(result.get('payload').get('value'), value)
+
+ def test_aggregate(self):
+ data = generate_test_data(51)
+ aggregated, warnings = aggregate(data, 5)
+
+ for i in range(1,5):
+ self.assertEqual(aggregated[i].get('timestamp'), _test_timestamp(i*10))
+ num = 5.5 + 10 * i
+ self.assertEqual(aggregated[i].get('number'), num)
+ self.assertEqual(aggregated[i].get('number2'), num * 2)
+
+ def test_aggregate_min(self):
+ data = generate_test_data(51)
+ aggregated, warnings = aggregate(data, 5, 'min')
+
+ for i in range(1,5):
+ self.assertEqual(aggregated[i].get('timestamp'), _test_timestamp(i*10))
+ num = 1 + 10 * i
+ self.assertEqual(aggregated[i].get('number'), num)
+ self.assertEqual(aggregated[i].get('number2'), num * 2)
+
+ def test_aggregate_empty_window(self):
+ data = generate_test_data(5)
+ aggregated, warnings = aggregate(data, 10, 'max')
+
+ for i in range(1, 5):
+ self.assertNotEqual(aggregated[i].get('timestamp'), _test_timestamp(i))
+ self.assertEqual(aggregated[i].get('number'), i)
+ self.assertEqual(aggregated[i].get('number2'), i * 2)
+
+ def test_aggregate_unknown_data_tool(self):
+ data = generate_test_data(5)
+ aggregated, warnings = aggregate(data, 10, 'horse')
+
+ self.assertEqual(aggregated, [])
+ self.assertEqual(warnings, [method_not_supported('horse')])
diff --git a/tst/test_db_connection.py b/tst/test_db_connection.py
index 187b103..9f30c96 100644
--- a/tst/test_db_connection.py
+++ b/tst/test_db_connection.py
@@ -271,4 +271,30 @@ class DBConnectionTest(TestCase):
self.assertEqual(overview["fields"], ["number"])
self.assertEqual(len(overview["statistics"]), 3)
- self.assertEqual(overview["statistics"][0]["payload"]["unit"], "scalar")
\ No newline at end of file
+ self.assertEqual(overview["statistics"][0]["payload"]["unit"], "scalar")
+
+ def test_summary_overview_aggregate(self):
+ data_tools = [
+ {"field":"number", "method":"line"},
+ ]
+
+ units_d = {"field":"number", "unit":"scalar"}
+
+ C = DictConnection()
+ topic_id = C.add_topic(
+ "topic",
+ description="description",
+ fields=["number"],
+ data_tools=data_tools,
+ units=[units_d]
+ )
+ for i in range(10):
+ C.add_data(topic_id, {"number": i})
+
+ result = C.get_overview(aggregate_to=3)
+ data = result["statistics"][0]["payload"]["data"]["datasets"][0]["data"]
+ self.assertEqual(len(data), 3)
+
+ result = C.get_summary(topic_id, aggregate_to=3)
+ data = result["statistics"][0]["payload"]["data"]["datasets"][0]["data"]
+ self.assertEqual(len(data), 3)
diff --git a/tst/test_server_handlers.py b/tst/test_server_handlers.py
index 2d3dfc3..cc3f550 100644
--- a/tst/test_server_handlers.py
+++ b/tst/test_server_handlers.py
@@ -10,7 +10,7 @@ from fdbk.server import parse_filter_parameters, ServerHandlers
class ServerHandlersTest(TestCase):
def _assert_status(self, expected_status, function, *args, **kwargs):
data, status = function(*args, **kwargs)
- self.assertEqual(status, expected_status)
+ self.assertEqual(status, expected_status, f'data={str(data)}')
return data
def _create_topic(self, server_handlers, topic):
@@ -22,14 +22,23 @@ class ServerHandlersTest(TestCase):
since="2020-04-26T19:18:14.123456Z",
until="2020-04-26T19:18:14.123456Z",
limit="123",
+ aggregate_to="25",
+ aggregate_with="min",
asd="asd"
)
- parsed = parse_filter_parameters(params)
- self.assertEqual(parsed.get("since"), datetime(2020,4,26,19,18,14,123456, tzutc()))
- self.assertEqual(parsed.get("until"), datetime(2020,4,26,19,18,14,123456, tzutc()))
- self.assertEqual(parsed.get("limit"), 123)
- self.assertIsNone(parsed.get("asd"))
+ for include_aggretate in (True, False):
+ parsed = parse_filter_parameters(params, include_aggretate)
+ self.assertEqual(parsed.get("since"), datetime(2020,4,26,19,18,14,123456, tzutc()))
+ self.assertEqual(parsed.get("until"), datetime(2020,4,26,19,18,14,123456, tzutc()))
+ self.assertEqual(parsed.get("limit"), 123)
+ if include_aggretate:
+ self.assertEqual(parsed.get("aggregate_to"), 25)
+ self.assertEqual(parsed.get("aggregate_with"), "min")
+ else:
+ self.assertIsNone(parsed.get("aggregate_to"))
+ self.assertIsNone(parsed.get("aggregate_with"))
+ self.assertIsNone(parsed.get("asd"))
def test_parse_filter_parameters_catches_parsing_error(self):
parsed = parse_filter_parameters(dict(limit="cow"))
@@ -47,12 +56,15 @@ class ServerHandlersTest(TestCase):
s = ServerHandlers(DictConnection())
self._assert_status(200, s.add_topic, dict(name="topic"))
- def test_add_data_get_data_and_get_latest_and_get_summary(self):
+ def test_add_data_get_data_and_get_latest_and_get_summary_get_overview(self):
s = ServerHandlers(DictConnection())
self._assert_status(404, s.get_latest, None)
- topic_id = self._create_topic(s, dict(name="topic", fields=["number"]))
+ data_tools = [
+ {"field":"number", "method":"line"},
+ ]
+ topic_id = self._create_topic(s, dict(name="topic", fields=["number"], data_tools=data_tools))
self._assert_status(404, s.get_latest, topic_id)
@@ -71,6 +83,14 @@ class ServerHandlersTest(TestCase):
self._assert_status(200, s.get_summary, topic_id, {})
+ for i in range(5):
+ self._assert_status(200, s.add_data, topic_id, dict(number=i))
+
+ response = self._assert_status(200, s.get_overview, None, dict(aggregate_to=3))
+ data = response["statistics"][0]["payload"]["data"]["datasets"][0]["data"]
+ self.assertLessEqual(len(data), 3)
+
+
def test_add_data_validations(self):
s = ServerHandlers(DictConnection())
|
Data tools should allow aggregating data
|
0.0
|
61edb0c86488a0dc9d74247ccee3f792d9bde077
|
[
"tst/test_data_tools.py::DataToolsTest::test_aggregate",
"tst/test_data_tools.py::DataToolsTest::test_aggregate_empty_window",
"tst/test_data_tools.py::DataToolsTest::test_aggregate_min",
"tst/test_data_tools.py::DataToolsTest::test_aggregate_unknown_data_tool",
"tst/test_data_tools.py::DataToolsTest::test_summary_funcs_return_none_on_empty_data",
"tst/test_data_tools.py::DataToolsTest::test_value_functions",
"tst/test_db_connection.py::DBConnectionTest::test_abstract_methods_raise_not_implemented_error",
"tst/test_db_connection.py::DBConnectionTest::test_get_comparison_produces_comparison",
"tst/test_db_connection.py::DBConnectionTest::test_get_latest_handles_empty_list",
"tst/test_db_connection.py::DBConnectionTest::test_get_latest_returns_latest_data_element_for_topic",
"tst/test_db_connection.py::DBConnectionTest::test_get_overview_combines_list_items_to_list",
"tst/test_db_connection.py::DBConnectionTest::test_get_overview_combines_table_items_to_table",
"tst/test_db_connection.py::DBConnectionTest::test_get_overview_produces_overview",
"tst/test_db_connection.py::DBConnectionTest::test_get_summary_average_ignores_invalid_values",
"tst/test_db_connection.py::DBConnectionTest::test_get_summary_ignores_invalid_fields",
"tst/test_db_connection.py::DBConnectionTest::test_get_summary_produces_summary",
"tst/test_db_connection.py::DBConnectionTest::test_get_summary_writes_warning_to_output_when_unsupported_method_requested",
"tst/test_db_connection.py::DBConnectionTest::test_last_truthy_falsy_summary_returns_correct_timestamp",
"tst/test_db_connection.py::DBConnectionTest::test_latest_summary_returns_latest_item",
"tst/test_db_connection.py::DBConnectionTest::test_line_visualization_gives_timestamps_in_utc",
"tst/test_db_connection.py::DBConnectionTest::test_overview_and_comparison_include_units",
"tst/test_db_connection.py::DBConnectionTest::test_process_list_ignores_instruction_without_parameters",
"tst/test_db_connection.py::DBConnectionTest::test_summary_overview_aggregate",
"tst/test_db_connection.py::DBConnectionTest::test_topic_is_validated_on_creation",
"tst/test_server_handlers.py::ServerHandlersTest::test_add_data_get_data_and_get_latest_and_get_summary_get_overview",
"tst/test_server_handlers.py::ServerHandlersTest::test_add_data_validations",
"tst/test_server_handlers.py::ServerHandlersTest::test_add_topic_returns_200_on_success",
"tst/test_server_handlers.py::ServerHandlersTest::test_add_topic_returns_400_when_topic_data_is_invalid",
"tst/test_server_handlers.py::ServerHandlersTest::test_add_topic_returns_400_when_topic_name_missing",
"tst/test_server_handlers.py::ServerHandlersTest::test_get_topic",
"tst/test_server_handlers.py::ServerHandlersTest::test_parse_filter_parameters",
"tst/test_server_handlers.py::ServerHandlersTest::test_parse_filter_parameters_catches_parsing_error"
] |
[] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-08-23 21:33:23+00:00
|
mit
| 3,394 |
|
kangasta__fdbk-55
|
diff --git a/fdbk/data_tools/_aggregate.py b/fdbk/data_tools/_aggregate.py
index 007d604..2283bbe 100644
--- a/fdbk/data_tools/_aggregate.py
+++ b/fdbk/data_tools/_aggregate.py
@@ -3,7 +3,8 @@ from dateutil.parser import isoparse
from fdbk.utils import timestamp_as_str
from fdbk.utils.messages import (
- method_not_supported)
+ method_not_supported,
+ no_data)
from .functions import functions as data_functions, VALUE_FUNCS
@@ -27,6 +28,10 @@ def aggregate(data, aggregate_to, aggregate_with=None):
warnings = []
aggregated = []
+ if not data:
+ warnings.append(no_data())
+ return ([], warnings,)
+
if aggregate_with not in VALUE_FUNCS:
warnings.append(method_not_supported(aggregate_with))
return ([], warnings,)
diff --git a/fdbk/data_tools/_utils.py b/fdbk/data_tools/_utils.py
index 1158389..d55fe52 100644
--- a/fdbk/data_tools/_utils.py
+++ b/fdbk/data_tools/_utils.py
@@ -1,5 +1,8 @@
from fdbk.utils.messages import (
- method_not_supported, field_is_undefined, collection_name_is_undefined)
+ method_not_supported,
+ field_is_undefined,
+ collection_name_is_undefined,
+ no_data)
from .functions import functions as data_functions, CHART_FUNCS
from .functions.utils import chart_dict, statistics_dict
@@ -185,6 +188,10 @@ def run_data_tools(topic_d, data, aggregate_to=None, aggregate_with=None):
results = []
warnings = []
+ if not data:
+ warnings.append(no_data(topic_d))
+ return ([], warnings,)
+
if aggregate_to:
chart_data, aggregate_warnings = aggregate(
data, aggregate_to, aggregate_with)
diff --git a/fdbk/utils/messages.py b/fdbk/utils/messages.py
index 533c2f2..6814c52 100644
--- a/fdbk/utils/messages.py
+++ b/fdbk/utils/messages.py
@@ -1,14 +1,22 @@
-def topic_not_found(id_):
- return f'Topic ID "{id_}" not found from database'
+def collection_name_is_undefined(method, field):
+ return f'No target list name specified for {method} {field}.'
+
+
+def field_is_undefined(field):
+ return f'The requested field "{field}" is undefined.'
def method_not_supported(method):
return f'The requested method "{method}" is not supported.'
-def field_is_undefined(field):
- return f'The requested field "{field}" is undefined.'
+def no_data(topic_d=None):
+ if topic_d:
+ topic_details = f' for topic {topic_d["name"]} ({topic_d["id"]})'
+ else:
+ topic_details = ''
+ return f'No data found{topic_details}.'
-def collection_name_is_undefined(method, field):
- return f'No target list name specified for {method} {field}.'
+def topic_not_found(id_):
+ return f'Topic ID "{id_}" not found from database'
|
kangasta/fdbk
|
9a448db20ccd536a0c23ced7df7c843b399bc306
|
diff --git a/tst/test_data_tools.py b/tst/test_data_tools.py
index c253a03..0f3f273 100644
--- a/tst/test_data_tools.py
+++ b/tst/test_data_tools.py
@@ -1,8 +1,8 @@
from unittest import TestCase
from unittest.mock import Mock, patch
-from fdbk.data_tools import aggregate, functions
-from fdbk.utils.messages import method_not_supported
+from fdbk.data_tools import aggregate, functions, run_data_tools
+from fdbk.utils.messages import method_not_supported, no_data
def _test_timestamp(i):
return f'2020-08-23T00:{i // 60:02}:{i % 60:02}Z'
@@ -15,6 +15,23 @@ class DataToolsTest(TestCase):
for fn in functions.values():
self.assertIsNone(fn([], 'field'))
+ def test_run_data_tools_empty_data(self):
+ topic_d = dict(id='test_id', name='Test name')
+ data = []
+
+ def _check_results(results, warnings, topic_d=None):
+ self.assertEqual(result, [])
+ self.assertEqual(
+ warnings[0],
+ no_data(topic_d))
+
+ result, warnings = aggregate(data, 3)
+ _check_results(result, warnings)
+
+ result, warnings = run_data_tools(topic_d, data)
+ _check_results(result, warnings, topic_d)
+
+
def test_value_functions(self):
data = generate_test_data()
|
Data tools aggregation raises error on empty data
|
0.0
|
9a448db20ccd536a0c23ced7df7c843b399bc306
|
[
"tst/test_data_tools.py::DataToolsTest::test_aggregate",
"tst/test_data_tools.py::DataToolsTest::test_aggregate_empty_window",
"tst/test_data_tools.py::DataToolsTest::test_aggregate_min",
"tst/test_data_tools.py::DataToolsTest::test_aggregate_unknown_data_tool",
"tst/test_data_tools.py::DataToolsTest::test_run_data_tools_empty_data",
"tst/test_data_tools.py::DataToolsTest::test_summary_funcs_return_none_on_empty_data",
"tst/test_data_tools.py::DataToolsTest::test_value_functions"
] |
[] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-08-30 18:07:43+00:00
|
mit
| 3,395 |
|
kangasta__fdbk-58
|
diff --git a/fdbk/_client_connection.py b/fdbk/_client_connection.py
index d691355..eae4135 100644
--- a/fdbk/_client_connection.py
+++ b/fdbk/_client_connection.py
@@ -36,9 +36,14 @@ class ClientConnection(DBConnection):
if not response.ok:
raise RuntimeError(json.dumps(response.json()))
- def get_topics(self, type_=None):
+ def get_topics(self, type_=None, template=None):
# TODO: Error handling
- query = f"type={type_}" if type_ else ""
+ query = []
+ if type_:
+ query.append(f"type={type_}")
+ if template:
+ query.append(f"template={template}")
+ query = '&'.join(query)
query = f"?{query}" if query else ""
response = requests.get(f"{self.__url}/topics{query}")
diff --git a/fdbk/_db_connection.py b/fdbk/_db_connection.py
index b86c670..e29227c 100644
--- a/fdbk/_db_connection.py
+++ b/fdbk/_db_connection.py
@@ -11,6 +11,27 @@ class DBConnection:
'''Base class for DB connections.
'''
+ def validate_template(self, topic_d):
+ ''' Validate that topics template is a template topic
+
+ Args:
+ topic_d: Topic dict which template is validated
+
+ Returns:
+ None
+
+ Raises:
+ AssertionError: Template is not a valid template
+ KeyError: Template not found from DB
+ '''
+ template = topic_d.get('template')
+ if not template:
+ return
+
+ template_d = self.get_topic(template)
+ if template_d.get('type') != 'template':
+ raise AssertionError('Templates type is not template.')
+
def add_topic(self, name, **kwargs):
'''Adds new topic to DB.
@@ -21,7 +42,8 @@ class DBConnection:
Topic ID of the newly created topic
Raises:
- KeyError: Topic already exists in DB
+ KeyError: Topic already exists in DB or topics template does not
+ exist in DB.
'''
raise NotImplementedError(
"Functionality not implemented by selected DB connection")
@@ -38,26 +60,90 @@ class DBConnection:
None
Raises:
+ AssertionError: Topic is a template topic
KeyError: Topic does not exist in DB
ValueError: Values do not match those defined for the topic
'''
raise NotImplementedError(
"Functionality not implemented by selected DB connection")
- def get_topics(self, type_=None):
- '''Gets list of topic dicts
+ def get_topics_without_templates(self, type_=None, template=None):
+ '''Gets list of topic dicts without resolving templates
+
+ Fetches all topics by default.
Args:
- type_: Type of topics to fetch. By default all topics are fetched.
+ type_: Type of topics to fetch
+ template: Template of topics to fetch.
+
+ Returns:
+ List of topic dicts without fields from possible templates
+ '''
+ raise NotImplementedError(
+ "Functionality not implemented by selected DB connection")
+
+ @staticmethod
+ def _remove_empty(obj):
+ ret = {}
+ for key, value in obj.items():
+ if value:
+ ret[key] = value
+ return ret
+
+ @staticmethod
+ def _with_templates(topic_d, templates):
+ template = topic_d.get('template')
+ if template:
+ try:
+ template_d = next(
+ i for i in templates if i.get('id') == template)
+ except StopIteration:
+ raise KeyError(topic_not_found(template))
+ return {
+ **DBConnection._with_templates(
+ template_d,
+ templates),
+ **DBConnection._remove_empty(topic_d)}
+ else:
+ return topic_d
+
+ def get_topics(self, type_=None, template=None):
+ '''Gets list of topic dicts with values from templates
+
+ Fetches all topics by default.
+
+ Args:
+ type_: Type of topics to fetch
+ template: Template of topics to fetch.
Returns:
List of topic dicts
+
+ Raises:
+ KeyError: Template of a topic not found from the DB
+ '''
+ topics = self.get_topics_without_templates(type_, template=template)
+ templates = self.get_topics_without_templates(type_='template')
+
+ return [self._with_templates(topic, templates) for topic in topics]
+
+ def get_topic_without_templates(self, topic_id):
+ '''Get topic dict by ID without resolving templates
+
+ Args:
+ topic_id: ID of the topic to find
+
+ Returns:
+ Topic dictionary without fields from possible templates
+
+ Raises:
+ KeyError: Topic does not exist in DB
'''
raise NotImplementedError(
"Functionality not implemented by selected DB connection")
def get_topic(self, topic_id):
- '''Get topic dict by ID
+ '''Get topic dict by ID with values from templates
Args:
topic_id: ID of the topic to find
@@ -68,8 +154,12 @@ class DBConnection:
Raises:
KeyError: Topic does not exist in DB
'''
- raise NotImplementedError(
- "Functionality not implemented by selected DB connection")
+ topic_d = self.get_topic_without_templates(topic_id)
+ template = topic_d.get('template')
+ if template:
+ return {**self.get_topic(template), **self._remove_empty(topic_d)}
+ else:
+ return topic_d
def get_data(self, topic_id, since=None, until=None, limit=None):
'''Get all data under given topic
@@ -168,7 +258,7 @@ class DBConnection:
def _run_data_tools_for_many(self,
topic_ids=None,
- type_=None,
+ template=None,
since=None,
until=None,
limit=None,
@@ -185,7 +275,8 @@ class DBConnection:
except KeyError as e:
warnings.append(topic_not_found(topic_id))
else:
- topics = {topic["id"]: topic for topic in self.get_topics(type_)}
+ topics = {
+ topic["id"]: topic for topic in self.get_topics(template)}
result_d = {
"topic_names": [],
@@ -219,17 +310,10 @@ class DBConnection:
result_d["fields"] = list(set(result_d["fields"]))
return result_d
- def get_comparison(self, topic_ids=None, **kwargs):
- '''Get comparison of the data of the given topic IDs
-
- See get_overview.
- '''
- return self._run_data_tools_for_many(topic_ids, **kwargs)
-
def get_overview(
self,
topic_ids=None,
- type_=None,
+ template=None,
since=None,
until=None,
limit=None,
@@ -240,8 +324,8 @@ class DBConnection:
Args:
topic_ids: List of topic IDs to overview. By default all topics are
included.
- type_: Type of topics to include. Only has effect is topic_ids is
- empty. By default all topics are included.
+ template: Template of topics to include. Only has effect if
+ topic_ids is empty. By default all topics are included.
since: Datetime of the earliest entry to include
until: Datetime of the most recent entry to include
limit: Number of entries to include from the most recent
@@ -256,7 +340,7 @@ class DBConnection:
'''
return self._run_data_tools_for_many(
topic_ids=topic_ids,
- type_=type_,
+ template=template,
since=since,
until=until,
limit=limit,
diff --git a/fdbk/_dict_connection.py b/fdbk/_dict_connection.py
index 5492f32..7ceb9a4 100644
--- a/fdbk/_dict_connection.py
+++ b/fdbk/_dict_connection.py
@@ -35,6 +35,7 @@ class DictConnection(DBConnection):
def add_topic(self, name, **kwargs):
topic_d = generate_topic_dict(name, add_id=True, **kwargs)
+ self.validate_template(topic_d)
self._dict["topics"].append(topic_d)
self._dict[topic_d["id"]] = []
@@ -47,15 +48,19 @@ class DictConnection(DBConnection):
def add_data(self, topic_id, values):
topic_d = self._get_topic_dict(topic_id)
+ if topic_d.get('type') == 'template':
+ raise AssertionError('Cannot add data to template topic.')
fields = topic_d["fields"]
data = generate_data_entry(topic_id, fields, values)
self._dict[topic_id].append(data)
- def get_topics(self, type_=None):
+ def get_topics_without_templates(self, type_=None, template=None):
topics = self._dict["topics"]
if type_:
topics = [i for i in topics if i.get('type') == type_]
+ if template:
+ topics = [i for i in topics if i.get('template') == template]
return generate_topics_list(topics)
@@ -66,7 +71,7 @@ class DictConnection(DBConnection):
except StopIteration:
raise KeyError(topic_not_found(topic_id))
- def get_topic(self, topic_id):
+ def get_topic_without_templates(self, topic_id):
return generate_topic_response(self._get_topic_dict(topic_id))
def get_data(self, topic_id, since=None, until=None, limit=None):
diff --git a/fdbk/schemas/topic-in.json b/fdbk/schemas/topic-in.json
index 81ac4c6..aba4e4c 100644
--- a/fdbk/schemas/topic-in.json
+++ b/fdbk/schemas/topic-in.json
@@ -24,7 +24,8 @@
"properties": {
"id": {"type": "string"},
"name": {"type": "string"},
- "type": {
+ "type": { "enum": ["topic", "template"]},
+ "template": {
"oneOf": [
{"type": "string"},
{"type": "null"}
@@ -50,6 +51,6 @@
},
"metadata": {"type": "object"}
},
- "required": ["name", "fields"],
+ "required": ["name"],
"additionalProperties": false
}
diff --git a/fdbk/server/_server_handlers.py b/fdbk/server/_server_handlers.py
index b80865a..900337c 100644
--- a/fdbk/server/_server_handlers.py
+++ b/fdbk/server/_server_handlers.py
@@ -114,7 +114,7 @@ class ServerHandlers:
try:
params = parse_filter_parameters(
query_args, include_aggregate=True)
- data = self._db_connection.get_comparison(
+ data = self._db_connection.get_overview(
topic_ids_a, **params)
return data, 200
except KeyError as error:
@@ -122,7 +122,7 @@ class ServerHandlers:
"error": str(error)
}, 404
- def get_overview(self, type_=None, query_args=None):
+ def get_overview(self, template=None, query_args=None):
if not query_args:
query_args = {}
@@ -130,7 +130,7 @@ class ServerHandlers:
params = parse_filter_parameters(
query_args, include_aggregate=True)
data = self._db_connection.get_overview(
- type_=type_, **params)
+ template=template, **params)
return data, 200
except KeyError as error:
return {
diff --git a/fdbk/utils/_format.py b/fdbk/utils/_format.py
index 6562697..e3d343f 100644
--- a/fdbk/utils/_format.py
+++ b/fdbk/utils/_format.py
@@ -7,6 +7,7 @@ TOPIC_FIELDS = [
"name",
"id",
"type",
+ "template",
"description",
"fields",
"units",
@@ -86,6 +87,7 @@ def generate_data_response(data, fields):
def generate_topic_dict(
name,
type_str=None,
+ template=None,
description=None,
fields=None,
units=None,
@@ -96,7 +98,8 @@ def generate_topic_dict(
Args:
name: Name of the topic.
- type_str: Type of the topic, for example 'form' or 'sensor'.
+ type_str: Type of the topic, 'topic' or 'template'.
+ template: Template to inherit values from.
description: Description of the topic.
fields: List of data field names included in the topic.
units: List of units for field.
@@ -107,11 +110,11 @@ def generate_topic_dict(
Returns:
Generated topic dict
-
'''
topic_d = {
"name": name,
- "type": type_str,
+ "type": type_str if type_str is not None else "topic",
+ "template": template,
"description": description,
"fields": fields if fields is not None else [],
"units": units if units is not None else [],
@@ -120,7 +123,10 @@ def generate_topic_dict(
}
if add_id:
- topic_d["id"] = str(uuid4())
+ if type_str == 'template':
+ topic_d["id"] = name
+ else:
+ topic_d["id"] = str(uuid4())
validate_topic_dict(topic_d)
diff --git a/fdbk/utils/messages.py b/fdbk/utils/messages.py
index 6814c52..6e1a37f 100644
--- a/fdbk/utils/messages.py
+++ b/fdbk/utils/messages.py
@@ -19,4 +19,4 @@ def no_data(topic_d=None):
def topic_not_found(id_):
- return f'Topic ID "{id_}" not found from database'
+ return f'Topic ID "{id_}" not found from database.'
|
kangasta/fdbk
|
b591821a2cb507fd7fc1f4b86058e600c2dfee58
|
diff --git a/fdbk/utils/_common_tests.py b/fdbk/utils/_common_tests.py
index 772beb7..c90bc56 100644
--- a/fdbk/utils/_common_tests.py
+++ b/fdbk/utils/_common_tests.py
@@ -19,6 +19,32 @@ class CommonTest:
with self.assertRaises(KeyError):
self.C.add_data("topic_id", {"key": "value"})
+ def test_template_topics(self):
+ template_id = self.C.add_topic(
+ "test_template",
+ type_str='template',
+ fields=['number'])
+ self.assertEqual(template_id, "test_template")
+
+ topic_id = self.C.add_topic('topic', template=template_id)
+ topic_d = self.C.get_topic(topic_id)
+ self.assertEqual(topic_d.get('fields'), ['number'])
+
+ topics = self.C.get_topics()
+ self.assertEqual(len(topics), 2)
+ for topic in topics:
+ self.assertEqual(topic.get('fields'), ['number'])
+
+ def test_cannot_add_topic_with_invalid_template(self):
+ with self.assertRaises(KeyError):
+ self.C.add_topic('topic1', template='test_template')
+
+ self.C.add_topic("test_template", type_str='template')
+ topic_id = self.C.add_topic('topic2', template='test_template')
+
+ with self.assertRaises(AssertionError):
+ self.C.add_topic('topic3', template=topic_id)
+
def test_cannot_add_data_with_non_matching_number_of_fields(self):
topic_id = self.C.add_topic(
"topic",
@@ -35,6 +61,14 @@ class CommonTest:
with self.assertRaises(ValueError):
self.C.add_data(topic_id, {"key": "value"})
+ def test_cannot_add_data_to_template(self):
+ topic_id = self.C.add_topic(
+ "topic",
+ type_str="template",
+ fields=["number"])
+ with self.assertRaises(AssertionError):
+ self.C.add_data(topic_id, {"number": 3})
+
def test_add_data_affects_get_data_output(self):
topic_id = self.C.add_topic(
"topic",
@@ -110,22 +144,33 @@ class CommonTest:
self.assertEqual(dataset["data"][0]["x"], '2020-01-01T01:03:00Z')
self.assertEqual(dataset["data"][-1]["x"], '2020-01-01T01:07:00Z')
- def test_can_get_topics_type(self):
+ def test_can_get_topics_type_and_template(self):
self.C.add_topic(
- "1",
- type_str="a",
+ "te1",
+ type_str="template",
fields=["number"])
+ self.C.add_topic(
+ "te2",
+ type_str="template",
+ fields=["letter"])
+ self.C.add_topic(
+ "1",
+ template="te1")
self.C.add_topic(
"2",
- type_str="a",
- fields=["number"])
+ template="te1")
self.C.add_topic(
"3",
- type_str="b",
- fields=["letter"])
+ template="te2")
+
+ topics = self.C.get_topics('template')
+ self.assertEqual(len(topics), 2)
+
+ topics = self.C.get_topics('topic')
+ self.assertEqual(len(topics), 3)
- topics = self.C.get_topics('a')
+ topics = self.C.get_topics(template='te1')
self.assertEqual(len(topics), 2)
- topics = self.C.get_topics('b')
+ topics = self.C.get_topics(template='te2')
self.assertEqual(len(topics), 1)
diff --git a/tst/test_client_connection.py b/tst/test_client_connection.py
index 600e1bf..e47fb2c 100644
--- a/tst/test_client_connection.py
+++ b/tst/test_client_connection.py
@@ -57,8 +57,8 @@ class ClientConnectionTest(TestCase):
def test_add_topic_triggers_correct_call(self):
c = ClientConnection("")
with patch('requests.post', side_effect=self.mock_requests_post), patch('fdbk.DictConnection.add_topic', return_value="topic_id") as add_topic:
- c.add_topic("topic", type_str="test")
- add_topic.assert_called_with("topic", type_str="test", description=None, fields=[], units=[], data_tools=[], metadata={})
+ c.add_topic("topic", type_str="template")
+ add_topic.assert_called_with("topic", type_str="template", description=None, fields=[], units=[], data_tools=[], metadata={}, template=None)
def test_add_data_triggers_correct_call(self):
c = ClientConnection("")
diff --git a/tst/test_db_connection.py b/tst/test_db_connection.py
index 6f5a0d5..d4c1b8a 100644
--- a/tst/test_db_connection.py
+++ b/tst/test_db_connection.py
@@ -198,7 +198,7 @@ class DBConnectionTest(TestCase):
C.add_data(topic_ids[-1], {"number": 4})
C.add_data(topic_ids[-1], {"number": 2})
if fn == "get_comparison":
- result = C.get_comparison(topic_ids)
+ result = C.get_overview(topic_ids)
elif fn == "get_overview":
result = C.get_overview()
self.assertEqual(result["topic_names"], ["topic_0", "topic_1", "topic_2"])
diff --git a/tst/test_dict_connection.py b/tst/test_dict_connection.py
index eb8ec6a..b0bca0d 100644
--- a/tst/test_dict_connection.py
+++ b/tst/test_dict_connection.py
@@ -1,5 +1,6 @@
import os
from unittest import TestCase
+from uuid import uuid4
try:
from unittest.mock import Mock, patch
@@ -15,13 +16,25 @@ class DictConnectionCommonTest(CommonTest, TestCase):
class DictConnectionTest(TestCase):
def test_topics_backup_saves_dict_to_file(self):
- C1 = DictConnection('/tmp/asd.json')
+ filename = f'{uuid4()}.json'
+ C1 = DictConnection(f'/tmp/{filename}')
C1.add_topic('Test topic 1')
C1.add_topic('Test topic 2')
- C2 = DictConnection('/tmp/asd.json')
+ C2 = DictConnection(f'/tmp/{filename}')
topics = C2.get_topics()
- os.remove('/tmp/asd.json')
+ os.remove(f'/tmp/{filename}')
self.assertEqual(len(topics), 2)
+
+ def test_get_topics_raises_keyerror_on_template_not_found(self):
+ C = DictConnection()
+ C.add_topic('test_template', type_str='template')
+ C.add_topic('topic', template='test_template')
+
+ C.get_topics()
+
+ C._dict['topics'] = C._dict['topics'][1:]
+ with self.assertRaises(KeyError):
+ C.get_topics()
|
DB connection should support template topics
|
0.0
|
b591821a2cb507fd7fc1f4b86058e600c2dfee58
|
[
"tst/test_client_connection.py::ClientConnectionTest::test_add_topic_triggers_correct_call",
"tst/test_dict_connection.py::DictConnectionCommonTest::test_can_get_topics_type_and_template",
"tst/test_dict_connection.py::DictConnectionCommonTest::test_cannot_add_data_to_template",
"tst/test_dict_connection.py::DictConnectionCommonTest::test_cannot_add_topic_with_invalid_template",
"tst/test_dict_connection.py::DictConnectionCommonTest::test_template_topics",
"tst/test_dict_connection.py::DictConnectionTest::test_get_topics_raises_keyerror_on_template_not_found"
] |
[
"tst/test_client_connection.py::ClientConnectionTest::test_add_data_triggers_correct_call",
"tst/test_client_connection.py::ClientConnectionTest::test_failing_add_calls_should_raise_RuntimeError",
"tst/test_client_connection.py::ClientConnectionTest::test_fresh_server_returns_empty_response_or_error",
"tst/test_db_connection.py::DBConnectionTest::test_abstract_methods_raise_not_implemented_error",
"tst/test_db_connection.py::DBConnectionTest::test_get_comparison_produces_comparison",
"tst/test_db_connection.py::DBConnectionTest::test_get_latest_handles_empty_list",
"tst/test_db_connection.py::DBConnectionTest::test_get_latest_returns_latest_data_element_for_topic",
"tst/test_db_connection.py::DBConnectionTest::test_get_overview_combines_list_items_to_list",
"tst/test_db_connection.py::DBConnectionTest::test_get_overview_combines_table_items_to_table",
"tst/test_db_connection.py::DBConnectionTest::test_get_overview_produces_overview",
"tst/test_db_connection.py::DBConnectionTest::test_get_summary_average_ignores_invalid_values",
"tst/test_db_connection.py::DBConnectionTest::test_get_summary_ignores_invalid_fields",
"tst/test_db_connection.py::DBConnectionTest::test_get_summary_produces_summary",
"tst/test_db_connection.py::DBConnectionTest::test_get_summary_writes_warning_to_output_when_unsupported_method_requested",
"tst/test_db_connection.py::DBConnectionTest::test_last_truthy_falsy_summary_returns_correct_timestamp",
"tst/test_db_connection.py::DBConnectionTest::test_latest_summary_returns_latest_item",
"tst/test_db_connection.py::DBConnectionTest::test_line_visualization_gives_timestamps_in_utc",
"tst/test_db_connection.py::DBConnectionTest::test_overview_and_comparison_include_units",
"tst/test_db_connection.py::DBConnectionTest::test_process_list_ignores_instruction_without_parameters",
"tst/test_db_connection.py::DBConnectionTest::test_run_data_tools_topic_not_found",
"tst/test_db_connection.py::DBConnectionTest::test_summary_overview_aggregate",
"tst/test_db_connection.py::DBConnectionTest::test_topic_is_validated_on_creation",
"tst/test_dict_connection.py::DictConnectionCommonTest::test_add_data_affects_get_data_output",
"tst/test_dict_connection.py::DictConnectionCommonTest::test_add_topic_affects_get_topic_output",
"tst/test_dict_connection.py::DictConnectionCommonTest::test_can_get_data_limit",
"tst/test_dict_connection.py::DictConnectionCommonTest::test_can_get_data_since",
"tst/test_dict_connection.py::DictConnectionCommonTest::test_can_get_data_until",
"tst/test_dict_connection.py::DictConnectionCommonTest::test_can_get_overview_since_until_limit",
"tst/test_dict_connection.py::DictConnectionCommonTest::test_can_get_summary_since_until_limit",
"tst/test_dict_connection.py::DictConnectionCommonTest::test_cannot_add_data_to_undefined_topic",
"tst/test_dict_connection.py::DictConnectionCommonTest::test_cannot_add_data_with_non_matching_fields",
"tst/test_dict_connection.py::DictConnectionCommonTest::test_cannot_add_data_with_non_matching_number_of_fields",
"tst/test_dict_connection.py::DictConnectionCommonTest::test_cannot_get_data_of_undefined_topic",
"tst/test_dict_connection.py::DictConnectionCommonTest::test_cannot_get_undefined_topic",
"tst/test_dict_connection.py::DictConnectionTest::test_topics_backup_saves_dict_to_file"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-09-05 23:23:13+00:00
|
mit
| 3,396 |
|
kangasta__fdbk-63
|
diff --git a/examples/net_status/net_status.py b/examples/net_status/net_status.py
index 6221aaf..8844052 100644
--- a/examples/net_status/net_status.py
+++ b/examples/net_status/net_status.py
@@ -18,13 +18,11 @@ class NetStatus(object):
self._target = target
self._timeout = timeout
- # TODO #62: add netstatus template
-
@property
- def topic(self):
+ def template(self):
return {
- "name": self._target.get('name'),
- "type_str": "topic",
+ "name": "netstatus",
+ "type_str": "template",
"description": "Network connection status monitor.",
"fields": ['elapsed', 'status_code'],
"units": [{
@@ -40,6 +38,15 @@ class NetStatus(object):
}],
}
+ @property
+ def topic(self):
+ return {
+ "name": self._target.get('name'),
+ "template": "netstatus",
+ "type_str": "topic",
+ "metadata": {"url": self._target.get('url')},
+ }
+
@property
def data(self):
data = {}
diff --git a/examples/sys_status/sys_status.py b/examples/sys_status/sys_status.py
index 03b3792..79c7a4a 100644
--- a/examples/sys_status/sys_status.py
+++ b/examples/sys_status/sys_status.py
@@ -9,18 +9,16 @@ class SysStatus(object):
def __init__(self, topic_name='System status'):
self.__topic_name = topic_name
- # TODO #62: add sysstatus template
-
@property
- def topic(self):
+ def template(self):
fields = ['CPU_usage', 'memory_usage', 'disk_usage']
units = (
list(map(lambda field: {'field': field, 'unit': 'percent'}, fields))
)
return {
- "name": self.__topic_name,
- "type_str": "topic",
+ "name": "sysstatus",
+ "type_str": "template",
"description": "System status monitor.",
"fields": fields,
"units": units,
@@ -33,6 +31,14 @@ class SysStatus(object):
}, fields))
}
+ @property
+ def topic(self):
+ return {
+ "name": self.__topic_name,
+ "template": "sysstatus",
+ "type_str": "topic",
+ }
+
@property
def data(self):
data = {
diff --git a/fdbk/reporter.py b/fdbk/reporter.py
index 0e4fe3e..d55fc2d 100644
--- a/fdbk/reporter.py
+++ b/fdbk/reporter.py
@@ -160,11 +160,17 @@ class Reporter:
if not self._data_source:
raise ValueError('Cannot create new topic without data source')
- topic_d = self._data_source.topic
+ try:
+ template_d = self._data_source.template
+ template_id = self._client.add_topic(**template_d)
+ self._print(created_topic(template_d, template_id))
+ except (AttributeError, KeyError, RuntimeError):
+ pass
- self._print(f"Creating topic '{topic_d['name']}' to fdbk")
+ topic_d = self._data_source.topic
self._topic_id = self._client.add_topic(**topic_d)
+ self._print(created_topic(topic_d, self._topic_id))
def _print(self, *args, **kwargs):
if self._verbose:
diff --git a/fdbk/utils/messages.py b/fdbk/utils/messages.py
index 4699ceb..c756b1d 100644
--- a/fdbk/utils/messages.py
+++ b/fdbk/utils/messages.py
@@ -1,11 +1,18 @@
def _topic_str(topic_d):
- return f'{topic_d["name"]} ({topic_d["id"]})'
+ type_ = topic_d.get("type") or topic_d.get("type_str", "topic")
+ type_str = f', {type_}' if type_ != 'topic' else ''
+ return f'{topic_d["name"]} ({topic_d["id"]}{type_str})'
def created_connection(plugin, parameters):
return (
- f"Created fdbk DB connection of type '{plugin}' with parameters"
- f"{str(parameters)}")
+ f"Created fdbk DB connection of type '{plugin}' with parameters "
+ f"{str(parameters)}.")
+
+
+def created_topic(topic_d, id_):
+ topic_d = {**topic_d, "id": id_}
+ return (f"Created topic '{_topic_str(topic_d)}' to the database.")
def collection_name_is_undefined(method, field):
|
kangasta/fdbk
|
ab1162ae05fa38d089e698c337da0dbb11e9c8c6
|
diff --git a/tst/test_reporter.py b/tst/test_reporter.py
index 1d94b12..7386ef9 100644
--- a/tst/test_reporter.py
+++ b/tst/test_reporter.py
@@ -1,4 +1,5 @@
from datetime import datetime
+from random import randrange
from unittest import TestCase
from unittest.mock import Mock, patch
@@ -7,7 +8,7 @@ from freezegun import freeze_time
from fdbk import Reporter, DictConnection
from fdbk.reporter import _add, _div, _obj_add, _Data
-class TestDataSource(object):
+class TestDataSource:
def __init__(self, pattern, n):
self._pattern = pattern
self._i = 0
@@ -37,6 +38,29 @@ class TestDataSource(object):
"number": num
}
+class TestDataSourceWithTemplate:
+ @property
+ def template(self):
+ return {
+ "name": "random",
+ "description": "Random numbers from randrange(10)",
+ "type_str": "template",
+ "fields": [ "number" ]
+ }
+
+ @property
+ def topic(self):
+ return {
+ "name": "topic",
+ "template": "random",
+ }
+
+ @property
+ def data(self):
+ return {
+ "number": randrange(10)
+ }
+
class ReporterUtilsTest(TestCase):
def test_add_and_div_returns_none_on_error(self):
self.assertIsNone(_add(1, None))
@@ -86,6 +110,16 @@ class ReporterTest(TestCase):
self.assertEqual(C.get_topic(R.topic_id)["name"], "topic")
self.assertEqual(C.get_topic(R.topic_id)["fields"], ["number"])
+ def test_creates_template_on_init(self):
+ DS = TestDataSourceWithTemplate()
+ R = Reporter(DS, db_plugin='DictConnection')
+ C = R.connection
+ self.assertEqual(len(C.get_topics()), 2)
+ self.assertEqual(C.get_topics()[0]["type"], "template")
+
+ R = Reporter(DS, db_connection=C)
+ self.assertEqual(len(C.get_topics()), 3)
+
def test_can_use_existing_connection(self):
DS = TestDataSource([1,2,3], 3)
C = DictConnection()
|
Reporter data source should support template topics
In addition to topic property, reporter should read template property.
|
0.0
|
ab1162ae05fa38d089e698c337da0dbb11e9c8c6
|
[
"tst/test_reporter.py::ReporterTest::test_creates_template_on_init"
] |
[
"tst/test_reporter.py::ReporterUtilsTest::test_add_and_div_returns_none_on_error",
"tst/test_reporter.py::ReporterUtilsTest::test_data_add_raises_value_error_on_non_matching_data",
"tst/test_reporter.py::ReporterUtilsTest::test_data_averaged_return_none_on_empty_data",
"tst/test_reporter.py::ReporterUtilsTest::test_data_has_age_property",
"tst/test_reporter.py::ReporterUtilsTest::test_data_has_reset_method",
"tst/test_reporter.py::ReporterUtilsTest::test_obj_add_raises_value_error_on_non_matching_dicts",
"tst/test_reporter.py::ReporterTest::test_allows_custom_print_fn",
"tst/test_reporter.py::ReporterTest::test_averaging_ignores_samples_with_none",
"tst/test_reporter.py::ReporterTest::test_averaging_wont_pass_through_exception_on_failed_push",
"tst/test_reporter.py::ReporterTest::test_averaging_wont_push_if_no_valid_samples",
"tst/test_reporter.py::ReporterTest::test_can_use_existing_connection",
"tst/test_reporter.py::ReporterTest::test_creates_topic_on_init",
"tst/test_reporter.py::ReporterTest::test_data_can_be_pushed_to_existing_topic",
"tst/test_reporter.py::ReporterTest::test_data_collection_fails_without_data_source",
"tst/test_reporter.py::ReporterTest::test_provides_averaging_over_push_interval",
"tst/test_reporter.py::ReporterTest::test_provides_push_method",
"tst/test_reporter.py::ReporterTest::test_push_automatically_on_report_for_interval",
"tst/test_reporter.py::ReporterTest::test_push_automatically_on_report_for_num_samples",
"tst/test_reporter.py::ReporterTest::test_push_is_skipped_on_empty_data",
"tst/test_reporter.py::ReporterTest::test_raises_error_with_invalid_db_connection",
"tst/test_reporter.py::ReporterTest::test_reports_data_until_None",
"tst/test_reporter.py::ReporterTest::test_start_method_catches_ctrl_c",
"tst/test_reporter.py::ReporterTest::test_start_supports_non_numeric_values",
"tst/test_reporter.py::ReporterTest::test_topic_creation_fails_without_data_source"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-09-07 21:24:48+00:00
|
mit
| 3,397 |
|
kangasta__fdbk-69
|
diff --git a/fdbk/_db_connection.py b/fdbk/_db_connection.py
index a92fd00..af155fe 100644
--- a/fdbk/_db_connection.py
+++ b/fdbk/_db_connection.py
@@ -212,7 +212,8 @@ class DBConnection:
until=None,
limit=None,
aggregate_to=None,
- aggregate_with=None):
+ aggregate_with=None,
+ aggregate_always=False):
'''Get summary of the topic data
Args:
@@ -222,6 +223,8 @@ class DBConnection:
limit: Number of entries to include from the most recent
aggregate_to: Aggregate data into specified number of data points
aggregate_with: Aggregate data with speficied function
+ aggregate_always: Aggregate data even if datas length is
+ shorter than aggregate_to value. Disabled by default.
Returns:
Dictionary with summary of the topic
@@ -242,7 +245,7 @@ class DBConnection:
}
results, warnings = run_data_tools(
- topic_d, data_d, aggregate_to, aggregate_with)
+ topic_d, data_d, aggregate_to, aggregate_with, aggregate_always,)
summary_d["warnings"].extend(warnings)
results, warnings = post_process(results)
@@ -258,9 +261,15 @@ class DBConnection:
until=None,
limit=None,
aggregate_to=None,
- aggregate_with=None):
+ aggregate_with=None,
+ aggregate_always=False):
data_d = self.get_data(topic_d.get("id"), since, until, limit)
- return run_data_tools(topic_d, data_d, aggregate_to, aggregate_with)
+ return run_data_tools(
+ topic_d,
+ data_d,
+ aggregate_to,
+ aggregate_with,
+ aggregate_always)
def _run_data_tools_for_many(self,
topic_ids=None,
@@ -269,7 +278,8 @@ class DBConnection:
until=None,
limit=None,
aggregate_to=None,
- aggregate_with=None):
+ aggregate_with=None,
+ aggregate_always=False):
executor = ThreadPoolExecutor()
warnings = []
@@ -293,7 +303,14 @@ class DBConnection:
}
jobs = []
- params = (since, until, limit, aggregate_to, aggregate_with,)
+ params = (
+ since,
+ until,
+ limit,
+ aggregate_to,
+ aggregate_with,
+ aggregate_always,
+ )
for topic_d in topics.values():
jobs.append(
executor.submit(
@@ -324,7 +341,8 @@ class DBConnection:
until=None,
limit=None,
aggregate_to=None,
- aggregate_with=None):
+ aggregate_with=None,
+ aggregate_always=False):
'''Get overview of the data
Args:
@@ -337,6 +355,8 @@ class DBConnection:
limit: Number of entries to include from the most recent
aggregate_to: Aggregate data into specified number of data points
aggregate_with: Aggregate data with speficied function
+ aggregate_always: Aggregate data even if datas length is
+ shorter than aggregate_to value. Disabled by default.
Returns:
Dictionary with overview of the topics data
@@ -351,7 +371,8 @@ class DBConnection:
until=until,
limit=limit,
aggregate_to=aggregate_to,
- aggregate_with=aggregate_with)
+ aggregate_with=aggregate_with,
+ aggregate_always=aggregate_always)
ConnectionClass = DBConnection
diff --git a/fdbk/data_tools/_aggregate.py b/fdbk/data_tools/_aggregate.py
index 2283bbe..861cbe5 100644
--- a/fdbk/data_tools/_aggregate.py
+++ b/fdbk/data_tools/_aggregate.py
@@ -21,7 +21,20 @@ def _get_keys(data_point):
return [key for key in data_point if key != 'timestamp']
-def aggregate(data, aggregate_to, aggregate_with=None):
+def aggregate(data, aggregate_to, aggregate_with=None, aggregate_always=False):
+ '''Aggregate data to less data points
+
+ Args:
+ data: Data before aggregation
+ aggregate_to: Number of data points to aggregate data to.
+ aggregate_with: Value function to use to when combining data-points.
+ Defaults to average.
+ aggregate_always: If true, data is aggregated even if datas length is
+ shorter than aggregate_to value. Disabled by default.
+
+ Returns:
+ List of aggregated data-points
+ '''
if not aggregate_with:
aggregate_with = 'average'
@@ -32,6 +45,9 @@ def aggregate(data, aggregate_to, aggregate_with=None):
warnings.append(no_data())
return ([], warnings,)
+ if len(data) <= aggregate_to and not aggregate_always:
+ return (data, warnings,)
+
if aggregate_with not in VALUE_FUNCS:
warnings.append(method_not_supported(aggregate_with))
return ([], warnings,)
diff --git a/fdbk/data_tools/_utils.py b/fdbk/data_tools/_utils.py
index d55fe52..97b0b85 100644
--- a/fdbk/data_tools/_utils.py
+++ b/fdbk/data_tools/_utils.py
@@ -184,7 +184,12 @@ def post_process(statistics):
return _process(funcs, statistics)
-def run_data_tools(topic_d, data, aggregate_to=None, aggregate_with=None):
+def run_data_tools(
+ topic_d,
+ data,
+ aggregate_to=None,
+ aggregate_with=None,
+ aggregate_always=False):
results = []
warnings = []
@@ -194,7 +199,7 @@ def run_data_tools(topic_d, data, aggregate_to=None, aggregate_with=None):
if aggregate_to:
chart_data, aggregate_warnings = aggregate(
- data, aggregate_to, aggregate_with)
+ data, aggregate_to, aggregate_with, aggregate_always)
warnings.extend(aggregate_warnings)
else:
chart_data = data
diff --git a/fdbk/server/_server_handlers.py b/fdbk/server/_server_handlers.py
index 2bd815a..32a3538 100644
--- a/fdbk/server/_server_handlers.py
+++ b/fdbk/server/_server_handlers.py
@@ -4,6 +4,10 @@
from dateutil.parser import isoparse
+def _parse_boolean(param):
+ return str(param).lower() == 'true'
+
+
def _parse_param(param, parser):
try:
return parser(param)
@@ -22,8 +26,13 @@ def parse_filter_parameters(args, include_aggregate=False):
return query
aggregate = dict(
- aggregate_to=_parse_param(args.get('aggregate_to'), int),
- aggregate_with=args.get('aggregate_with')
+ aggregate_to=_parse_param(
+ args.get('aggregate_to'),
+ int),
+ aggregate_with=args.get('aggregate_with'),
+ aggregate_always=_parse_param(
+ args.get('aggregate_always'),
+ _parse_boolean),
)
return {**aggregate, **query}
|
kangasta/fdbk
|
010f8e8551468608f33e0b939e677104bc147508
|
diff --git a/tst/test_data_tools.py b/tst/test_data_tools.py
index 0f3f273..08470b7 100644
--- a/tst/test_data_tools.py
+++ b/tst/test_data_tools.py
@@ -4,11 +4,23 @@ from unittest.mock import Mock, patch
from fdbk.data_tools import aggregate, functions, run_data_tools
from fdbk.utils.messages import method_not_supported, no_data
-def _test_timestamp(i):
+def _test_timestamp(i, timestamps=None):
+ if timestamps:
+ return timestamps[i]
return f'2020-08-23T00:{i // 60:02}:{i % 60:02}Z'
-def generate_test_data(N=10):
- return [dict(number=i, number2=i*2, letter=chr(ord('A') + i), timestamp=_test_timestamp(i)) for i in range(N)]
+def generate_test_data(N=10, timestamps=None):
+ return [dict(number=i, number2=i*2, letter=chr(ord('A') + i), timestamp=_test_timestamp(i, timestamps)) for i in range(N)]
+
+AGGREGATE_ALWAYS_TOPIC = dict(
+ name="Aggregate test",
+ fields=["number", "number2", "letter"],
+ data_tools=[{"field":"number", "method":"line"},])
+AGGREGATE_ALWAYS_DATA = generate_test_data(4, [
+ '2020-09-12T00:00:00Z',
+ '2020-09-12T00:00:01Z',
+ '2020-09-12T00:00:02Z',
+ '2020-09-13T00:00:00Z',])
class DataToolsTest(TestCase):
def test_summary_funcs_return_none_on_empty_data(self):
@@ -72,7 +84,7 @@ class DataToolsTest(TestCase):
def test_aggregate_empty_window(self):
data = generate_test_data(5)
- aggregated, warnings = aggregate(data, 10, 'max')
+ aggregated, warnings = aggregate(data, 10, 'max', aggregate_always=True)
for i in range(1, 5):
self.assertNotEqual(aggregated[i].get('timestamp'), _test_timestamp(i))
@@ -80,8 +92,22 @@ class DataToolsTest(TestCase):
self.assertEqual(aggregated[i].get('number2'), i * 2)
def test_aggregate_unknown_data_tool(self):
- data = generate_test_data(5)
+ data = generate_test_data(15)
aggregated, warnings = aggregate(data, 10, 'horse')
self.assertEqual(aggregated, [])
self.assertEqual(warnings, [method_not_supported('horse')])
+
+ def test_aggregate_always(self):
+ data = AGGREGATE_ALWAYS_DATA
+ aggregated, warnings = aggregate(data, 5)
+
+ self.assertEqual(aggregated, data)
+ self.assertEqual(warnings, [])
+
+ aggregated, warnings = aggregate(data, 5, aggregate_always=True)
+
+ self.assertEqual(len(aggregated), 2)
+ self.assertEqual(aggregated[0]["number"], 1)
+ self.assertEqual(aggregated[1]["number"], 3)
+ self.assertEqual(warnings, [])
diff --git a/tst/test_server_handlers.py b/tst/test_server_handlers.py
index c247bfd..9cc773d 100644
--- a/tst/test_server_handlers.py
+++ b/tst/test_server_handlers.py
@@ -1,4 +1,5 @@
from datetime import datetime
+from dateutil.parser import isoparse
from dateutil.tz import tzutc
from unittest import TestCase
@@ -8,6 +9,8 @@ from fdbk import DictConnection
from fdbk.server import parse_filter_parameters, ServerHandlers, generate_app
from fdbk.server._server_handlers import _get_overwrite
+from test_data_tools import AGGREGATE_ALWAYS_DATA, AGGREGATE_ALWAYS_TOPIC
+
class ServerHandlersTest(TestCase):
def _assert_status(self, expected_status, function, *args, **kwargs):
data, status = function(*args, **kwargs)
@@ -100,7 +103,6 @@ class ServerHandlersTest(TestCase):
data = response["statistics"][0]["payload"]["data"]["datasets"][0]["data"]
self.assertLessEqual(len(data), 3)
-
def test_add_data_validations(self):
s = ServerHandlers(DictConnection())
@@ -115,3 +117,22 @@ class ServerHandlersTest(TestCase):
self._assert_status(404, s.get_topic, None)
topic_id = self._create_topic(s, dict(name="topic", fields=["number"]))
self._assert_status(200, s.get_topic, topic_id)
+
+ def test_aggregate(self):
+ s = ServerHandlers(DictConnection())
+ topic_id = self._create_topic(s, AGGREGATE_ALWAYS_TOPIC)
+ for data in AGGREGATE_ALWAYS_DATA:
+ data['timestamp'] = isoparse(data['timestamp']).replace(tzinfo=None)
+ self._assert_status(200, s.add_data, topic_id, data)
+
+ tests = [
+ (s.get_summary, (topic_id, dict(aggregate_to="5", aggregate_with='sum')), 4),
+ (s.get_summary, (topic_id, dict(aggregate_to="5", aggregate_with='sum', aggregate_always="tRuE")), 2),
+ (s.get_overview, (None, dict(aggregate_to="5", aggregate_with='sum')), 4),
+ (s.get_overview, (None, dict(aggregate_to="5", aggregate_with='sum', aggregate_always="True")), 2),
+ ]
+
+ for fn, params, count in tests:
+ data = self._assert_status(200, fn, *params)
+ aggregated = data['statistics'][0]['payload']['data']['datasets'][0]['data']
+ self.assertEqual(len(aggregated), count)
|
Data tools should not aggregate data if len(data) < aggregate_to
|
0.0
|
010f8e8551468608f33e0b939e677104bc147508
|
[
"tst/test_data_tools.py::DataToolsTest::test_aggregate_always",
"tst/test_data_tools.py::DataToolsTest::test_aggregate_empty_window",
"tst/test_server_handlers.py::ServerHandlersTest::test_aggregate"
] |
[
"tst/test_data_tools.py::DataToolsTest::test_aggregate",
"tst/test_data_tools.py::DataToolsTest::test_aggregate_min",
"tst/test_data_tools.py::DataToolsTest::test_aggregate_unknown_data_tool",
"tst/test_data_tools.py::DataToolsTest::test_run_data_tools_empty_data",
"tst/test_data_tools.py::DataToolsTest::test_summary_funcs_return_none_on_empty_data",
"tst/test_data_tools.py::DataToolsTest::test_value_functions",
"tst/test_server_handlers.py::ServerHandlersTest::test_add_data_get_data_and_get_latest_and_get_summary_get_overview",
"tst/test_server_handlers.py::ServerHandlersTest::test_add_data_validations",
"tst/test_server_handlers.py::ServerHandlersTest::test_add_topic_returns_200_on_success",
"tst/test_server_handlers.py::ServerHandlersTest::test_add_topic_returns_400_when_topic_data_is_invalid",
"tst/test_server_handlers.py::ServerHandlersTest::test_add_topic_returns_400_when_topic_name_missing",
"tst/test_server_handlers.py::ServerHandlersTest::test_get_overwrite",
"tst/test_server_handlers.py::ServerHandlersTest::test_get_topic",
"tst/test_server_handlers.py::ServerHandlersTest::test_parse_filter_parameters",
"tst/test_server_handlers.py::ServerHandlersTest::test_parse_filter_parameters_catches_parsing_error",
"tst/test_server_handlers.py::ServerHandlersTest::test_server_from_plugin_name"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-09-11 22:44:50+00:00
|
mit
| 3,398 |
|
kangasta__fdbk-72
|
diff --git a/fdbk/_db_connection.py b/fdbk/_db_connection.py
index af155fe..66bcf62 100644
--- a/fdbk/_db_connection.py
+++ b/fdbk/_db_connection.py
@@ -312,6 +312,9 @@ class DBConnection:
aggregate_always,
)
for topic_d in topics.values():
+ if topic_d["type"] == "template":
+ continue
+
jobs.append(
executor.submit(
self._get_topic_statistics, topic_d, *params))
|
kangasta/fdbk
|
2bb2f886a860d85c74284053124d92c0d4dd9d07
|
diff --git a/tst/test_db_connection.py b/tst/test_db_connection.py
index d4c1b8a..f368696 100644
--- a/tst/test_db_connection.py
+++ b/tst/test_db_connection.py
@@ -308,3 +308,18 @@ class DBConnectionTest(TestCase):
result = C.get_summary(topic_id, aggregate_to=3)
data = result["statistics"][0]["payload"]["data"]["datasets"][0]["data"]
self.assertEqual(len(data), 3)
+
+ def test_overview_ignores_templates(self):
+ data_tools = [
+ {"field":"number", "method":"line"},
+ ]
+
+ units_d = {"field":"number", "unit":"scalar"}
+
+ C = DictConnection()
+ C.add_topic("Test template", type_str="template", fields=['number'], units=[units_d], data_tools=data_tools)
+ C.add_topic("Test topic", template="Test template")
+
+ data = C.get_overview()
+ self.assertEqual(len(data["warnings"]), 1)
+ self.assertNotIn(data["warnings"][0], "template")
|
Data tools should ignore template topics
Do not add warning for missing data if topic is template topic.
|
0.0
|
2bb2f886a860d85c74284053124d92c0d4dd9d07
|
[
"tst/test_db_connection.py::DBConnectionTest::test_overview_ignores_templates"
] |
[
"tst/test_db_connection.py::DBConnectionTest::test_abstract_methods_raise_not_implemented_error",
"tst/test_db_connection.py::DBConnectionTest::test_get_comparison_produces_comparison",
"tst/test_db_connection.py::DBConnectionTest::test_get_latest_handles_empty_list",
"tst/test_db_connection.py::DBConnectionTest::test_get_latest_returns_latest_data_element_for_topic",
"tst/test_db_connection.py::DBConnectionTest::test_get_overview_combines_list_items_to_list",
"tst/test_db_connection.py::DBConnectionTest::test_get_overview_combines_table_items_to_table",
"tst/test_db_connection.py::DBConnectionTest::test_get_overview_produces_overview",
"tst/test_db_connection.py::DBConnectionTest::test_get_summary_average_ignores_invalid_values",
"tst/test_db_connection.py::DBConnectionTest::test_get_summary_ignores_invalid_fields",
"tst/test_db_connection.py::DBConnectionTest::test_get_summary_produces_summary",
"tst/test_db_connection.py::DBConnectionTest::test_get_summary_writes_warning_to_output_when_unsupported_method_requested",
"tst/test_db_connection.py::DBConnectionTest::test_last_truthy_falsy_summary_returns_correct_timestamp",
"tst/test_db_connection.py::DBConnectionTest::test_latest_summary_returns_latest_item",
"tst/test_db_connection.py::DBConnectionTest::test_line_visualization_gives_timestamps_in_utc",
"tst/test_db_connection.py::DBConnectionTest::test_overview_and_comparison_include_units",
"tst/test_db_connection.py::DBConnectionTest::test_process_list_ignores_instruction_without_parameters",
"tst/test_db_connection.py::DBConnectionTest::test_run_data_tools_topic_not_found",
"tst/test_db_connection.py::DBConnectionTest::test_summary_overview_aggregate",
"tst/test_db_connection.py::DBConnectionTest::test_topic_is_validated_on_creation"
] |
{
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-09-12 22:42:46+00:00
|
mit
| 3,399 |
|
kangasta__fdbk-77
|
diff --git a/fdbk/data_tools/_utils.py b/fdbk/data_tools/_utils.py
index 702e1dd..3b3f201 100644
--- a/fdbk/data_tools/_utils.py
+++ b/fdbk/data_tools/_utils.py
@@ -103,6 +103,12 @@ def _get_clean_payload(statistic):
topic_name = payload.pop("topic_name")
payload["payload"]["topic_name"] = topic_name
+ try:
+ unit = payload.pop("unit")
+ payload["payload"]["unit"] = unit
+ except KeyError:
+ pass
+
return payload
diff --git a/fdbk/schemas/statistics-out.json b/fdbk/schemas/statistics-out.json
index d99aeef..e2a096b 100644
--- a/fdbk/schemas/statistics-out.json
+++ b/fdbk/schemas/statistics-out.json
@@ -18,6 +18,9 @@
},
"topic_name": {
"type": "string"
+ },
+ "unit": {
+ "type": "string"
}
},
"required": [
|
kangasta/fdbk
|
6f5506f24efbf04c5cc0c1740152d8bab2921f5e
|
diff --git a/tst/test_data_tools.py b/tst/test_data_tools.py
index 25e8968..bdd1200 100644
--- a/tst/test_data_tools.py
+++ b/tst/test_data_tools.py
@@ -15,7 +15,7 @@ def _test_timestamp(i, timestamps=None):
def generate_test_data(N=10, timestamps=None):
return [dict(number=i, number2=i*2, letter=chr(ord('A') + i), timestamp=_test_timestamp(i, timestamps)) for i in range(N)]
-STATUS_TOPIC = dict(name='Test status', fields=["number", "number2", "letter"], units=[], data_tools=[])
+STATUS_TOPIC = dict(name='Test status', fields=["number", "number2", "letter"], units=[dict(field="number", unit="scalar")], data_tools=[])
AGGREGATE_ALWAYS_TOPIC = dict(
name="Aggregate test",
fields=["number", "number2", "letter"],
@@ -66,6 +66,38 @@ class DataToolsTest(TestCase):
self.assertEqual(result.get('payload').get('type'), type_)
self.assertEqual(result.get('payload').get('value'), value)
+ def test_collection_functions_unit(self):
+ topic_d = STATUS_TOPIC
+ data = generate_test_data()
+
+ topic_d['data_tools'] = [
+ dict(field='number', method="average"),
+ dict(field='number', method='list_item', parameters=dict(
+ name="test_list", method="average")),
+ dict(field='number', method='table_item', parameters=dict(
+ name="test_table", method="average")),
+ ]
+
+ results, warnings = run_data_tools(topic_d, data)
+ self.assertEqual(len(warnings), 0)
+
+ results, warnings = post_process(results)
+ self.assertEqual(len(warnings), 0)
+ validate_statistics_array(results)
+
+ self.assertEqual(len(results), 3)
+
+ value = next(i for i in results if i["type"] == "value")
+ self.assertEqual(
+ value["payload"]["unit"], "scalar")
+ list_ = next(i for i in results if i["type"] == "list")
+ self.assertEqual(
+ list_["payload"]["data"][0]["payload"]["unit"], "scalar")
+ table = next(i for i in results if i["type"] == "table")
+ self.assertEqual(
+ table["payload"]["data"][0]["data"][0]["payload"]["unit"], "scalar")
+
+
def test_status_functions(self):
topic_d = STATUS_TOPIC
data = generate_test_data()
|
Data tools should add unit inside value payload instead next to it
Currently seems to work as expected for values when value is not in table.
|
0.0
|
6f5506f24efbf04c5cc0c1740152d8bab2921f5e
|
[
"tst/test_data_tools.py::DataToolsTest::test_collection_functions_unit"
] |
[
"tst/test_data_tools.py::DataToolsTest::test_aggregate",
"tst/test_data_tools.py::DataToolsTest::test_aggregate_always",
"tst/test_data_tools.py::DataToolsTest::test_aggregate_empty_window",
"tst/test_data_tools.py::DataToolsTest::test_aggregate_min",
"tst/test_data_tools.py::DataToolsTest::test_aggregate_unknown_data_tool",
"tst/test_data_tools.py::DataToolsTest::test_invalid_functions_in_collection",
"tst/test_data_tools.py::DataToolsTest::test_run_data_tools_empty_data",
"tst/test_data_tools.py::DataToolsTest::test_status_functions",
"tst/test_data_tools.py::DataToolsTest::test_status_functions_in_collection",
"tst/test_data_tools.py::DataToolsTest::test_status_functions_warnings",
"tst/test_data_tools.py::DataToolsTest::test_summary_funcs_return_none_on_empty_data",
"tst/test_data_tools.py::DataToolsTest::test_value_functions"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-09-25 15:23:00+00:00
|
mit
| 3,400 |
|
kangasta__fdbk-90
|
diff --git a/fdbk/data_tools/_run.py b/fdbk/data_tools/_run.py
index 442a1ef..7e7ec06 100644
--- a/fdbk/data_tools/_run.py
+++ b/fdbk/data_tools/_run.py
@@ -94,7 +94,7 @@ def run_data_tools(
instruction.get("field"),
instruction.get("parameters")
)
- except ValueError as error:
+ except (AssertionError, ValueError) as error:
warnings.append(str(error))
result = None
diff --git a/fdbk/data_tools/functions/_status_funcs.py b/fdbk/data_tools/functions/_status_funcs.py
index 3756fc4..6a49fd5 100644
--- a/fdbk/data_tools/functions/_status_funcs.py
+++ b/fdbk/data_tools/functions/_status_funcs.py
@@ -21,11 +21,14 @@ OPERATORS = {
def _get_value(method, data, field, parameters=None):
+ if method not in functions:
+ raise ValueError(method_not_supported(method))
+
value_d = functions.get(method)(data, field, parameters)
return value_d.get("payload", {}).get("value")
-def _get_parameters(parameters=None):
+def _get_status_parameters(parameters=None):
default = parameters.get("default")
checks = parameters.get("checks", [])
short_circuit = parameters.get("short_circuit", False)
@@ -34,6 +37,14 @@ def _get_parameters(parameters=None):
return default, checks, short_circuit, method
+def _get_warning_parameters(parameters=None):
+ check = parameters.get("check")
+ message = parameters.get("message")
+ method = parameters.get("method", "latest")
+
+ return check, message, method
+
+
def _run_assertion(assertion, value, other):
if assertion not in ASSERTIONS: # pragma: no cover
raise RuntimeError(f"Assertion {assertion} was not recognized")
@@ -45,7 +56,7 @@ def _run_assertion(assertion, value, other):
def _run_check(value, check):
- status = check.get("status")
+ status = check.get("status", 'WARNING')
operator = str(check.get("operator", 'or')).lower()
result = False if operator == 'or' else True
@@ -72,13 +83,11 @@ def status(data, field, parameters=None):
warnings = []
try:
- default, checks, short_circuit, method = _get_parameters(parameters)
+ default, checks, short_circuit, method = _get_status_parameters(
+ parameters)
except BaseException:
return None
- if method not in functions:
- raise ValueError(method_not_supported(method))
-
value = _get_value(method, data, field, parameters)
status_d = dict(field=field, status=default, reason=None)
@@ -104,6 +113,26 @@ def status(data, field, parameters=None):
return status_dict(**status_d)
+def warning(data, field, parameters=None):
+ if not len(data):
+ return None
+
+ try:
+ check, message, method = _get_warning_parameters(parameters)
+ except BaseException:
+ return None
+
+ if not check or not message:
+ return None
+
+ value = _get_value(method, data, field, parameters)
+ warning = _run_check(value, check)
+
+ if warning:
+ raise AssertionError(message)
+
+
STATUS_FUNCS = dict(
- status=status
+ status=status,
+ warning=warning,
)
|
kangasta/fdbk
|
a955ad766618af5f21e475a603ca8513d90ef1ab
|
diff --git a/tst/test_data_tools.py b/tst/test_data_tools.py
index bdd1200..3fc8b96 100644
--- a/tst/test_data_tools.py
+++ b/tst/test_data_tools.py
@@ -217,3 +217,29 @@ class DataToolsTest(TestCase):
self.assertEqual(aggregated[0]["number"], 1)
self.assertEqual(aggregated[1]["number"], 3)
self.assertEqual(warnings, [])
+
+ def test_warning_functions(self):
+ topic_d = STATUS_TOPIC
+ data = generate_test_data()
+
+ for check, expected in [
+ (dict(operator='and', gte=4, lte=6), ["Test warning"]),
+ (dict(operator='and', gte=6, lte=4), []),
+ ]:
+ parameters=dict(
+ method="average",
+ message="Test warning",
+ check=check,
+ )
+
+ topic_d['data_tools'] = [
+ dict(field='number', method="warning", parameters=parameters),
+ ]
+
+ results, warnings = run_data_tools(topic_d, data)
+
+ self.assertEqual(len(results), 0)
+ self.assertEqual(len(warnings), len(expected))
+
+ if expected:
+ self.assertEqual(warnings[0], "Test warning")
|
Data tools should support custom warnings
Forked from #45.
Add option to status data tool to show warning instead of updating status. This could be a separate `warning` function.
|
0.0
|
a955ad766618af5f21e475a603ca8513d90ef1ab
|
[
"tst/test_data_tools.py::DataToolsTest::test_warning_functions"
] |
[
"tst/test_data_tools.py::DataToolsTest::test_aggregate",
"tst/test_data_tools.py::DataToolsTest::test_aggregate_always",
"tst/test_data_tools.py::DataToolsTest::test_aggregate_empty_window",
"tst/test_data_tools.py::DataToolsTest::test_aggregate_min",
"tst/test_data_tools.py::DataToolsTest::test_aggregate_unknown_data_tool",
"tst/test_data_tools.py::DataToolsTest::test_collection_functions_unit",
"tst/test_data_tools.py::DataToolsTest::test_invalid_functions_in_collection",
"tst/test_data_tools.py::DataToolsTest::test_run_data_tools_empty_data",
"tst/test_data_tools.py::DataToolsTest::test_status_functions",
"tst/test_data_tools.py::DataToolsTest::test_status_functions_in_collection",
"tst/test_data_tools.py::DataToolsTest::test_status_functions_warnings",
"tst/test_data_tools.py::DataToolsTest::test_summary_funcs_return_none_on_empty_data",
"tst/test_data_tools.py::DataToolsTest::test_value_functions"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_issue_reference",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-12-20 01:24:41+00:00
|
mit
| 3,401 |
|
kangasta__pullnrun-11
|
diff --git a/pullnrun/_log.py b/pullnrun/_log.py
index 89198bd..02bf8c3 100644
--- a/pullnrun/_log.py
+++ b/pullnrun/_log.py
@@ -1,18 +1,47 @@
+def _http_details(output_dict):
+ type_ = output_dict.get('type', '')
+ status = str(output_dict.get('data', {}).get('status', '')).rjust(4)
+
+ file_ = output_dict.get('data', {}).get('file', '')
+ direction = 'to' if 'push' in type_ else 'from'
+ url = output_dict.get('data', {}).get('url', '')
+
+ detail = f'{file_} {direction} {url}'
+
+ return (status, detail, )
+
+def _s3_details(output_dict):
+ type_ = output_dict.get('type', '')
+
+ filename = output_dict.get('data', {}).get('filename', '')
+ bucket = output_dict.get('data', {}).get('bucket', '')
+ object_name = output_dict.get('data', {}).get('object_name', '')
+
+ if 'push' in type_:
+ direction = 'to'
+ source, target = filename, object_name
+ else:
+ direction = 'from'
+ source, target = object_name, filename
+
+ target = f' as {target}' if source != target else ''
+ detail = f'{source} {direction} S3 bucket {bucket}{target}'
+
+ return detail
+
def log_to_console(output_dict):
ok = '\u2714' if output_dict.get('ok') else '\u2718'
type_ = output_dict.get('type', '')
- stage = type_.upper().ljust(4)
+ stage = type_.upper()[:4].ljust(4)
status = ''.rjust(4)
detail = ''
output = None
if type_ in ('pull_http', 'push_http'):
- status = str(output_dict.get('data', {}).get('status', '')).rjust(4)
- file_ = output_dict.get('data', {}).get('file', '')
- url = output_dict.get('data', {}).get('url', '')
- direction = 'to' if 'push' in type_ else 'from'
- detail = f'{file_} {direction} {url}'
+ status, detail = _http_details(output_dict)
+ elif type_ in ('pull_s3', 'push_s3'):
+ detail = _s3_details(output_dict)
elif type_ == 'run':
status = str(output_dict.get('data', {}).get('exit_code', '')).rjust(4)
detail = ' '.join(output_dict.get('data', {}).get('command', []))
|
kangasta/pullnrun
|
e5a9e4f337915ad48f0aaaac04956c56220a4d56
|
diff --git a/tst/test_log.py b/tst/test_log.py
index 596d35c..ed94950 100644
--- a/tst/test_log.py
+++ b/tst/test_log.py
@@ -10,18 +10,45 @@ class LogTest(TestCase):
print_mock.assert_called()
@patch('builtins.print')
- def test_log_to_console_prints_type_and_status(self, print_mock):
+ def test_log_to_console_prints_logs_as_specified(self, print_mock):
+ url = 'example.com'
+ f = 'filename'
+
testdata = [
- ({'type': 'pull_http', 'ok': True, 'data': {'status': 200}}, ['\u2714', '200', 'PULL']),
- ({'type': 'run', 'ok': False, 'data': {'exit_code': 200}}, ['\u2718', '200', 'RUN']),
+ # Type and status
+ ({'type': 'pull_http', 'data': {
+ 'file': f,
+ 'url': url,
+ }}, [f, 'from', url], []),
+ ({'type': 'push_http', 'data': {
+ 'file': f,
+ 'url': url,
+ }}, [f, 'to', url], []),
+ # HTTP details
+ ({'type': 'pull_http', 'ok': True, 'data': {'status': 200}}, ['\u2714', '200', 'PULL'], ['_HTTP']),
+ ({'type': 'run', 'ok': False, 'data': {'exit_code': 200}}, ['\u2718', '200', 'RUN'], ['_HTTP']),
+ # S3 details
+ ({'type': 'pull_s3', 'data': {
+ 'bucket': 'b',
+ 'object_name': 'a',
+ 'filename': 'c',
+ }}, ['PULL', 'a from S3 bucket b as c'], ['_S3']),
+ ({'type': 'push_s3', 'data': {
+ 'bucket': 'b',
+ 'object_name': 'a',
+ 'filename': 'a',
+ }}, ['PUSH', 'a to S3 bucket b'], ['as a', '_S3']),
]
- for data, results in testdata:
+ for data, p_results, n_results in testdata:
log_to_console(data)
output = print_mock.call_args[-2][0]
- for result in results:
+ for result in p_results:
self.assertIn(result, output)
+ for result in n_results:
+ self.assertNotIn(result, output)
+
@patch('builtins.print')
def test_log_to_console_prints_run_output(self, print_mock):
@@ -32,20 +59,3 @@ class LogTest(TestCase):
output = print_mock.call_args[-2][0]
self.assertIn(result, output)
-
- @patch('builtins.print')
- def test_log_to_console_prints_pull_and_push_url(self, print_mock):
- url = 'example.com'
- f = 'filename'
-
- testdata = [
- ({'type': 'pull_http', 'data': {'file': f, 'url': url}}, [f, 'from', url]),
- ({'type': 'push_http', 'data': {'file': f, 'url': url}}, [f, 'to', url]),
- ]
-
- for data, results in testdata:
- log_to_console(data)
- output = print_mock.call_args[-2][0]
-
- for result in results:
- self.assertIn(result, output)
|
Add details logging for S3 pull and push
|
0.0
|
e5a9e4f337915ad48f0aaaac04956c56220a4d56
|
[
"tst/test_log.py::LogTest::test_log_to_console_prints_logs_as_specified"
] |
[
"tst/test_log.py::LogTest::test_log_to_console_does_not_crash_on_empty_input",
"tst/test_log.py::LogTest::test_log_to_console_prints_run_output"
] |
{
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-12-09 21:42:15+00:00
|
mit
| 3,402 |
|
kangasta__pullnrun-16
|
diff --git a/pullnrun/_log.py b/pullnrun/_log.py
index 3a9533f..df25bfa 100644
--- a/pullnrun/_log.py
+++ b/pullnrun/_log.py
@@ -1,3 +1,8 @@
+from os import getenv
+from uuid import uuid4
+
+from pullnrun._utils import get_log_entry, timestamp
+
def _status(output_dict):
status = output_dict.get('status')
if status == 'SUCCESS':
@@ -8,6 +13,31 @@ def _status(output_dict):
return '\u25B6'
return ' '
+def _duration(output_dict):
+ start = output_dict.get('meta', {}).get('start')
+ end = output_dict.get('meta', {}).get('end')
+
+ if not start or not end:
+ return ''
+
+ duration = end - start
+
+ if duration >= 1000:
+ return f'{duration/1000:.3f} s'
+ return f'{duration} ms'
+
+def _main_text(output_dict):
+ if output_dict.get('status') == 'STARTED':
+ id_ = output_dict.get('data', {}).get('id')
+ return f'Started pullnrun execution with id {id_}'
+
+ if output_dict.get('status') in ('SUCCESS', 'ERROR'):
+ success = output_dict.get('data', {}).get('success')
+ fail = output_dict.get('data', {}).get('fail')
+ duration = _duration(output_dict)
+
+ return f'Finished pullnrun execution in {duration}: {success} out of {success + fail} actions succeeded.'
+
def _http_details(output_dict):
type_ = output_dict.get('type', '')
status_code = str(output_dict.get('data', {}).get('status_code', '')).rjust(4)
@@ -39,22 +69,13 @@ def _s3_details(output_dict):
return detail
-def _duration(output_dict):
- start = output_dict.get('meta', {}).get('start')
- end = output_dict.get('meta', {}).get('end')
-
- if not start or not end:
- return ''
-
- duration = end - start
-
- if duration >= 1000:
- return f'({duration/1000:.3f} s)'
- return f'({duration} ms)'
-
def log_to_console(output_dict):
- status = _status(output_dict)
type_ = output_dict.get('type', '')
+ if type_ == 'main':
+ print(_main_text(output_dict))
+ return
+
+ status = _status(output_dict)
stage = type_.upper()[:4].ljust(4)
status_code = ''.rjust(4)
@@ -71,9 +92,32 @@ def log_to_console(output_dict):
output = output_dict.get('data', {}).get('output')
duration = _duration(output_dict)
+ duration = f'({duration})' if duration else ''
print(f'{status} {status_code} {stage} {detail} {duration}')
if output:
end = '\n' if output[-1] != '\n' else ''
- print(f'\n{output}{end}')
\ No newline at end of file
+ print(f'\n{output}{end}')
+
+class Log:
+ def __init__(self, quiet=False):
+ self._start = None
+ self._end = None
+ self._id = getenv('PULLNRUN_ID', str(uuid4()))
+ self._to_console = not quiet
+
+ def __call__(self, log_entry):
+ if self._to_console:
+ log_to_console(log_entry)
+
+ def start(self):
+ self._start = timestamp()
+ if self._to_console:
+ log_to_console(get_log_entry('main', 'STARTED', start=self._start, id=self._id))
+
+ def end(self, success, fail):
+ self._end = timestamp()
+ status = 'SUCCESS' if success > 0 and fail == 0 else 'ERROR'
+ if self._to_console:
+ log_to_console(get_log_entry('main', status, start=self._start, end=self._end, success=success, fail=fail))
diff --git a/pullnrun/_main.py b/pullnrun/_main.py
index 06a6605..d9ec3d4 100644
--- a/pullnrun/_main.py
+++ b/pullnrun/_main.py
@@ -8,7 +8,7 @@ except ImportError:
from jsonschema import validate
from ._utils import as_list
-from ._log import log_to_console
+from ._log import Log
from ._pull import pull
from ._push import push
@@ -24,8 +24,12 @@ def _validate(input_dict):
schema = json.loads(resources.read_text('pullnrun', 'schema.json'))
validate(instance=input_dict, schema=schema)
-def main(input_dict, log=log_to_console):
+def main(input_dict, quiet=False):
_validate(input_dict)
+
+ log = Log(quiet)
+ log.start()
+
success, error = (0, 0, )
for stage, function in FUNCTION_MAPPINGS.items():
@@ -36,4 +40,5 @@ def main(input_dict, log=log_to_console):
else:
error += 1
+ log.end(success, error)
return (success, error, )
|
kangasta/pullnrun
|
eeb04490fa6346d7134c58f4713f9a9567993a30
|
diff --git a/tst/test_log.py b/tst/test_log.py
index 54a1d74..5db69da 100644
--- a/tst/test_log.py
+++ b/tst/test_log.py
@@ -1,7 +1,7 @@
from unittest import TestCase
from unittest.mock import patch
-from pullnrun._log import log_to_console, _duration
+from pullnrun._log import Log, log_to_console, _duration
class LogTest(TestCase):
def test_duration_is_logged_correctly(self):
@@ -9,8 +9,8 @@ class LogTest(TestCase):
({'meta': {'start': 0, 'end': 1, }}, ''),
({'meta': {'start': 1, }}, ''),
({'meta': {'start': 0, }}, ''),
- ({'meta': {'start': 3, 'end': 53, }}, '(50 ms)'),
- ({'meta': {'start': 3, 'end': 5003, }}, '(5.000 s)'),
+ ({'meta': {'start': 3, 'end': 53, }}, '50 ms'),
+ ({'meta': {'start': 3, 'end': 5003, }}, '5.000 s'),
]
for data, output in testdata:
@@ -52,6 +52,9 @@ class LogTest(TestCase):
'object_name': 'a',
'filename': 'a',
}}, ['PUSH', 'a to S3 bucket b'], ['as a', '_S3']),
+ # Main function start and end
+ ({'type': 'main', 'status': 'STARTED'}, ['Started pullnrun execution with id'], ['\u25B6']),
+ ({'type': 'main', 'status': 'SUCCESS', 'data': {'success': 3, 'fail': 5}}, ['Finished pullnrun execution in', '3 out of 8 actions succeeded.'], ['\u2714', '\u2718']),
]
for data, p_results, n_results in testdata:
@@ -63,7 +66,6 @@ class LogTest(TestCase):
for result in n_results:
self.assertNotIn(result, output)
-
@patch('builtins.print')
def test_log_to_console_prints_run_output(self, print_mock):
data = {'type': 'run', 'data': {'output': 'banana'}}
@@ -73,3 +75,18 @@ class LogTest(TestCase):
output = print_mock.call_args[-2][0]
self.assertIn(result, output)
+
+ @patch('builtins.print')
+ def test_log_class_prints_actions(self, print_mock):
+ log = Log()
+ testdata = [
+ (log, ({'type': 'run', 'status': 'STARTED'}, ), '\u25B6'),
+ (log.start, [], 'Started pullnrun execution'),
+ (log.end, (1,2,), 'Finished pullnrun execution'),
+ ]
+
+ for fn, args, result in testdata:
+ fn(*args)
+ output = print_mock.call_args[-2][0]
+
+ self.assertIn(result, output)
|
Each pullnrun execution should have uuid
|
0.0
|
eeb04490fa6346d7134c58f4713f9a9567993a30
|
[
"tst/test_log.py::LogTest::test_duration_is_logged_correctly",
"tst/test_log.py::LogTest::test_log_class_prints_actions",
"tst/test_log.py::LogTest::test_log_to_console_does_not_crash_on_empty_input",
"tst/test_log.py::LogTest::test_log_to_console_prints_logs_as_specified",
"tst/test_log.py::LogTest::test_log_to_console_prints_run_output"
] |
[] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-12-13 22:25:31+00:00
|
mit
| 3,403 |
|
karlicoss__promnesia-277
|
diff --git a/src/promnesia/cannon.py b/src/promnesia/cannon.py
index a3a303f..b76cb9f 100755
--- a/src/promnesia/cannon.py
+++ b/src/promnesia/cannon.py
@@ -105,11 +105,13 @@ default_qkeep = [
# TODO perhaps, decide if fragment is meaningful (e.g. wiki) or random sequence of letters?
class Spec(NamedTuple):
- qkeep : Optional[Collection[str]] = None
+ qkeep : Optional[Union[Collection[str], bool]] = None
qremove: Optional[Set[str]] = None
fkeep : bool = False
def keep_query(self, q: str) -> Optional[int]: # returns order
+ if self.qkeep is True:
+ return 1
qkeep = {
q: i for i, q in enumerate(chain(default_qkeep, self.qkeep or []))
}
@@ -183,6 +185,7 @@ specs: Dict[str, Spec] = {
'ycombinator.com' : S(qkeep={'id'}), # todo just keep id by default?
'play.google.com' : S(qkeep={'id'}),
'answers.yahoo.com' : S(qkeep={'qid'}),
+ 'isfdb.org': S(qkeep=True),
}
_def_spec = S()
@@ -271,7 +274,7 @@ def transform_split(split: SplitResult):
netloc = canonify_domain(split.netloc)
path = split.path
- qparts = parse_qsl(split.query)
+ qparts = parse_qsl(split.query, keep_blank_values=True)
fragment = split.fragment
@@ -319,7 +322,7 @@ def transform_split(split: SplitResult):
to = to + ('', )
(netloc, path, qq) = [t.format(**gd) for t in to]
- qparts.extend(parse_qsl(qq)) # TODO hacky..
+ qparts.extend(parse_qsl(qq, keep_blank_values=True)) # TODO hacky..
# TODO eh, qparts should really be a map or something...
break
|
karlicoss/promnesia
|
90ba0d15ac7d04b365363821adb0f722534086f3
|
diff --git a/tests/cannon.py b/tests/cannon.py
index d76693b..5cd6ef5 100644
--- a/tests/cannon.py
+++ b/tests/cannon.py
@@ -294,3 +294,19 @@ def test_error():
with pytest.raises(CanonifyException):
# borrowed from https://bugs.mageia.org/show_bug.cgi?id=24640#c7
canonify('https://example.com\[email protected]')
+
[email protected]("url,expected", [
+ ('https://news.ycombinator.com/item?id=', 'news.ycombinator.com/item?id='),
+ ('https://www.youtube.com/watch?v=hvoQiF0kBI8&list&index=2',
+ 'youtube.com/watch?v=hvoQiF0kBI8&list='),
+])
+def test_empty_query_parameter(url, expected):
+ assert canonify(url) == expected
+
[email protected]("url,expected", [
+ ('http://www.isfdb.org/cgi-bin/title.cgi?2172', 'isfdb.org/cgi-bin/title.cgi?2172='),
+ ('http://www.isfdb.org/cgi-bin/title.cgi?2172+1', 'isfdb.org/cgi-bin/title.cgi?2172%201='),
+ ('http://www.isfdb.org/cgi-bin/title.cgi?2172&foo=bar&baz&quux', 'isfdb.org/cgi-bin/title.cgi?2172=&baz=&foo=bar&quux='),
+])
+def test_qkeep_true(url, expected):
+ assert canonify(url) == expected
|
Handle query parameters without values
Right now, pages on isfdb like `http://www.isfdb.org/cgi-bin/title.cgi?2172` are canonicalized to `http://www.isfdb.org/cgi-bin/title.cgi`, which removes important info from the URL.
I made a somewhat hacky solution, but there is perhaps a more elegant way. The solution is in two parts:
First, modify `Spec` to accept `qkeep=True`, which is taken to mean "retain all query parameters", and have isfdb.org use that option.
```
@@ -105,11 +105,13 @@ default_qkeep = [
# TODO perhaps, decide if fragment is meaningful (e.g. wiki) or random sequence of letters?
class Spec(NamedTuple):
- qkeep : Optional[Collection[str]] = None
+ qkeep : Optional[Union[Collection[str], bool]] = None
qremove: Optional[Set[str]] = None
fkeep : bool = False
def keep_query(self, q: str) -> Optional[int]: # returns order
+ if self.qkeep is True:
+ return 1
qkeep = {
q: i for i, q in enumerate(chain(default_qkeep, self.qkeep or []))
}
@@ -183,6 +185,7 @@ specs: Dict[str, Spec] = {
'ycombinator.com' : S(qkeep={'id'}), # todo just keep id by default?
'play.google.com' : S(qkeep={'id'}),
'answers.yahoo.com' : S(qkeep={'qid'}),
+ 'isfdb.org': S(qkeep=True),
}
_def_spec = S()
```
Second, pass, `keep_blank_values=True` to `parse_qsl`.
```
@@ -271,7 +274,7 @@ def transform_split(split: SplitResult):
netloc = canonify_domain(split.netloc)
path = split.path
- qparts = parse_qsl(split.query)
+ qparts = parse_qsl(split.query, keep_blank_values=True)
fragment = split.fragment
@@ -319,7 +322,7 @@ def transform_split(split: SplitResult):
to = to + ('', )
(netloc, path, qq) = [t.format(**gd) for t in to]
- qparts.extend(parse_qsl(qq)) # TODO hacky..
+ qparts.extend(parse_qsl(qq, keep_blank_values=True)) # TODO hacky..
# TODO eh, qparts should really be a map or something...
break
```
This achieves the desired result, but it's unpleasantly hacky.
First problem: this will not guarantee the order of query parameters. But is that important? Why doesn't the code just always alphabetize them? There's a note for youtube that "order matters here", but it seems to me that youtube doesn't care what order the parameters are in.
Second problem: maybe you usually don't want empty parameters kept. It could complicate things to add logic around this, but maybe something like a `keep_blank_values` property on Spec would do the job.
Third problem: it's not great to have to dig around in the program code to fix this behavior. Maybe it could be patched in from my `config.py`, once the supporting code is in place, which something like:
```python
from promnesia.cannon import specs, S
specs['isfdb.org'] = S(qkeep=True)
```
Really, all of `cannon.py` is a bit intimidating to modify (and, incidentally, shouldn't it be `canon.py`?). I'm not sure what's the right direction to go.
|
0.0
|
90ba0d15ac7d04b365363821adb0f722534086f3
|
[
"tests/cannon.py::test_qkeep_true[http://www.isfdb.org/cgi-bin/title.cgi?2172-isfdb.org/cgi-bin/title.cgi?2172=]",
"tests/cannon.py::test_empty_query_parameter[https://news.ycombinator.com/item?id=-news.ycombinator.com/item?id=]",
"tests/cannon.py::test_qkeep_true[http://www.isfdb.org/cgi-bin/title.cgi?2172&foo=bar&baz&quux-isfdb.org/cgi-bin/title.cgi?2172=&baz=&foo=bar&quux=]",
"tests/cannon.py::test_qkeep_true[http://www.isfdb.org/cgi-bin/title.cgi?2172+1-isfdb.org/cgi-bin/title.cgi?2172%201=]",
"tests/cannon.py::test_empty_query_parameter[https://www.youtube.com/watch?v=hvoQiF0kBI8&list&index=2-youtube.com/watch?v=hvoQiF0kBI8&list=]"
] |
[
"tests/cannon.py::test_youtube[youtube.com/watch?v=wHrCkyoe72U&feature=share&time_continue=6-youtube.com/watch?v=wHrCkyoe72U]",
"tests/cannon.py::test[https://news.ycombinator.com/item?id=12172351-news.ycombinator.com/item?id=12172351]",
"tests/cannon.py::test[https://www.youtube.com/watch?v=hvoQiF0kBI8&list=WL&index=2-youtube.com/watch?v=hvoQiF0kBI8&list=WL]",
"tests/cannon.py::test_reddit[https://www.reddit.com/r/selfhosted/comments/8j8mo3/what_are_you_self_hosting/dz19gh9/?utm_content=permalink&utm_medium=user&utm_source=reddit&utm_name=u_karlicoss-reddit.com/r/selfhosted/comments/8j8mo3/what_are_you_self_hosting/dz19gh9]",
"tests/cannon.py::test[https://ubuntuforums.org/showthread.php?t=1403470&s=0dd67bdb12559c22e73a220752db50c7&p=8806195#post8806195-ubuntuforums.org/showthread.php?t=1403470&p=8806195]",
"tests/cannon.py::test[withouthspec.co.uk/rooms/16867952?guests=2&adults=2&location=Berlin%2C+Germany&check_in=2017-08-16&check_out=2017-08-20-withouthspec.co.uk/rooms/16867952]",
"tests/cannon.py::test_youtube[m.youtube.com/watch?v=Zn6gV2sdl38-youtube.com/watch?v=Zn6gV2sdl38]",
"tests/cannon.py::test_same_norm[urls0]",
"tests/cannon.py::test_hackernews[https://news.ycombinator.com/from?site=jacopo.io-jacopo.io]",
"tests/cannon.py::test_youtube[youtube.com/embed/nyc6RJEEe0U?feature=oembed-youtube.com/watch?v=nyc6RJEEe0U]",
"tests/cannon.py::test[https://answers.yahoo.com/question/index?qid=20071101131442AAk9bGp-answers.yahoo.com/question/index?qid=20071101131442AAk9bGp]",
"tests/cannon.py::test[zoopla.co.uk/to-rent/details/42756337#D0zlBWeD4X85odsR.97-zoopla.co.uk/to-rent/details/42756337]",
"tests/cannon.py::test_error",
"tests/cannon.py::test_hackernews[https://news.ycombinator.com/item?id=25099862-news.ycombinator.com/item?id=25099862]",
"tests/cannon.py::test_reddit[https://www.reddit.com/r/firefox/comments/bbugc5/firefox_bans_free_speech_commenting_plugin/?ref=readnext-reddit.com/r/firefox/comments/bbugc5/firefox_bans_free_speech_commenting_plugin]",
"tests/cannon.py::test[https://www.facebook.com/photo.php?fbid=24147689823424326&set=pcb.2414778905423667&type=3&theater-facebook.com/photo.php?fbid=24147689823424326]",
"tests/cannon.py::test[https://play.google.com/store/apps/details?id=com.faultexception.reader&hl=en-play.google.com/store/apps/details?id=com.faultexception.reader]",
"tests/cannon.py::test[flowingdata.com/2010/12/14/10-best-data-visualization-projects-of-the-year-%e2%80%93-2010-flowingdata.com/2010/12/14/10-best-data-visualization-projects-of-the-year-%E2%80%93-2010]",
"tests/cannon.py::test[https://github.com/search?o=asc&q=track&s=stars&type=Repositories-github.com/search?q=track]",
"tests/cannon.py::test_youtube[https://youtu.be/iCvmsMzlF7o?list=WL-youtube.com/watch?v=iCvmsMzlF7o&list=WL]",
"tests/cannon.py::test_same_norm[urls1]",
"tests/cannon.py::test[https://urbandictionary.com/define.php?term=Belgian%20Whistle-urbandictionary.com/define.php?term=Belgian%20Whistle]",
"tests/cannon.py::test[https://en.wikipedia.org/wiki/Dinic%27s_algorithm-en.wikipedia.org/wiki/Dinic%27s_algorithm]",
"tests/cannon.py::test_archiveorg[https://web.archive.org/web/20090902224414/http://reason.com/news/show/119237.html-reason.com/news/show/119237.html]",
"tests/cannon.py::test[https://80000hours.org/career-decision/article/?utm_source=The+EA+Newsletter&utm_campaign=04ca3c2244-EMAIL_CAMPAIGN_2019_04_03_04_26&utm_medium=email&utm_term=0_51c1df13ac-04ca3c2244-318697649-80000hours.org/career-decision/article]",
"tests/cannon.py::test[https://www.youtube.com/watch?list=WL&v=hvoQiF0kBI8&index=2-youtube.com/watch?v=hvoQiF0kBI8&list=WL]",
"tests/cannon.py::test[flowingdata.com/2010/12/14/10-best-data-visualization-projects-of-the-year-\\u2013-2010-flowingdata.com/2010/12/14/10-best-data-visualization-projects-of-the-year-%E2%80%93-2010]",
"tests/cannon.py::test[https://bbs.archlinux.org/viewtopic.php?id=212740-bbs.archlinux.org/viewtopic.php?id=212740]",
"tests/cannon.py::test[https://google.co.uk/amp/s/amp.reddit.com/r/androidapps/comments/757e2t/swiftkey_or_gboard-reddit.com/r/androidapps/comments/757e2t/swiftkey_or_gboard]",
"tests/cannon.py::test_youtube[https://www.youtube.com/watch?t=491s&v=1NHbPN9pNPM&index=63&list=WL-youtube.com/watch?v=1NHbPN9pNPM&t=491s&list=WL]",
"tests/cannon.py::test[amp.theguardian.com/technology/2017/oct/09/mark-zuckerberg-facebook-puerto-rico-virtual-reality-theguardian.com/technology/2017/oct/09/mark-zuckerberg-facebook-puerto-rico-virtual-reality]",
"tests/cannon.py::test[https://arstechnica.com/?p=1371299-arstechnica.com/?p=1371299]",
"tests/cannon.py::test[https://spoonuniversity.com/lifestyle/marmite-ways-to-eat-it&usg=AFQjCNH4s1SOEjlpENlfPV5nuvADZpSdow-spoonuniversity.com/lifestyle/marmite-ways-to-eat-it]"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-03-05 03:44:19+00:00
|
mit
| 3,404 |
|
kaste__mockito-python-34
|
diff --git a/mockito/mocking.py b/mockito/mocking.py
index 82be9b2..0955e19 100644
--- a/mockito/mocking.py
+++ b/mockito/mocking.py
@@ -18,17 +18,14 @@
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
-from collections import deque
-import inspect
import functools
+import inspect
import operator
+from collections import deque
-from . import invocation
-from . import signature
-from . import utils
+from . import invocation, signature, utils
from .mock_registry import mock_registry
-
__all__ = ['mock']
__tracebackhide__ = operator.methodcaller(
@@ -75,13 +72,24 @@ class Mock(object):
# STUBBING
def get_original_method(self, method_name):
+ """
+ Looks up the original method on the `spec` object and returns it
+ together with an indication of whether the method is found
+ "directly" on the `spec` object.
+
+ This is used to decide whether the method should be stored as an
+ original_method and should therefore be replaced when unstubbing.
+ """
if self.spec is None:
- return None
+ return None, False
try:
- return self.spec.__dict__.get(method_name)
- except AttributeError:
- return getattr(self.spec, method_name, None)
+ return self.spec.__dict__[method_name], True
+ except (AttributeError, KeyError):
+ # Classes with defined `__slots__` and then no `__dict__` are not
+ # patchable but if we catch the `AttributeError` here, we get
+ # the better error message for the user.
+ return getattr(self.spec, method_name, None), False
def set_method(self, method_name, new_method):
setattr(self.mocked_obj, method_name, new_method)
@@ -130,8 +138,14 @@ class Mock(object):
try:
self.original_methods[method_name]
except KeyError:
- original_method = self.get_original_method(method_name)
- self.original_methods[method_name] = original_method
+ original_method, was_in_spec = self.get_original_method(
+ method_name)
+ if was_in_spec:
+ # This indicates the original method was found directly on
+ # the spec object and should therefore be restored by unstub
+ self.original_methods[method_name] = original_method
+ else:
+ self.original_methods[method_name] = None
self.replace_method(method_name, original_method)
diff --git a/mockito/utils.py b/mockito/utils.py
index ed8e7c3..52e8be4 100644
--- a/mockito/utils.py
+++ b/mockito/utils.py
@@ -14,10 +14,7 @@ def contains_strict(seq, element):
def newmethod(fn, obj):
- if PY3:
- return types.MethodType(fn, obj)
- else:
- return types.MethodType(fn, obj, obj.__class__)
+ return types.MethodType(fn, obj)
def get_function_host(fn):
|
kaste/mockito-python
|
79ae4340635c8298a79b1d6afc8e6b0b5ce26f88
|
diff --git a/tests/classmethods_test.py b/tests/classmethods_test.py
index 69d8cf7..0dc15bd 100644
--- a/tests/classmethods_test.py
+++ b/tests/classmethods_test.py
@@ -18,10 +18,12 @@
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
-from .test_base import TestBase
-from mockito import when, unstub, verify
+from mockito import unstub, verify, when
from mockito.verification import VerificationError
+from .test_base import TestBase
+
+
class Dog:
@classmethod
def bark(cls):
@@ -105,3 +107,122 @@ class ClassMethodsTest(TestBase):
self.assertEqual("Cat foo", Cat.meow("foo"))
+class Retriever:
+ @classmethod
+ def retrieve(cls, item):
+ return item
+
+
+class TrickDog(Dog, Retriever):
+ pass
+
+
+class InheritedClassMethodsTest(TestBase):
+
+ def tearDown(self):
+ unstub()
+
+ def testUnstubs(self):
+ when(TrickDog).bark().thenReturn("miau!")
+ when(TrickDog).retrieve("stick").thenReturn("ball")
+ unstub()
+ self.assertEqual("woof!", TrickDog.bark())
+ self.assertEqual("stick", TrickDog.retrieve("stick"))
+
+ def testStubs(self):
+ self.assertEqual("woof!", TrickDog.bark())
+ self.assertEqual("stick", TrickDog.retrieve("stick"))
+
+ when(TrickDog).bark().thenReturn("miau!")
+ when(TrickDog).retrieve("stick").thenReturn("ball")
+
+ self.assertEqual("miau!", TrickDog.bark())
+ self.assertEqual("ball", TrickDog.retrieve("stick"))
+
+ def testVerifiesMultipleCallsOnClassmethod(self):
+ when(TrickDog).bark().thenReturn("miau!")
+ when(TrickDog).retrieve("stick").thenReturn("ball")
+
+ TrickDog.bark()
+ TrickDog.bark()
+
+ TrickDog.retrieve("stick")
+ TrickDog.retrieve("stick")
+
+ verify(TrickDog, times=2).bark()
+ verify(TrickDog, times=2).retrieve("stick")
+
+ def testFailsVerificationOfMultipleCallsOnClassmethod(self):
+ when(TrickDog).bark().thenReturn("miau!")
+ when(TrickDog).retrieve("stick").thenReturn("bark")
+
+ TrickDog.bark()
+ TrickDog.retrieve("stick")
+
+ self.assertRaises(VerificationError, verify(TrickDog, times=2).bark)
+ self.assertRaises(VerificationError, verify(TrickDog,
+ times=2).retrieve)
+
+ def testStubsAndVerifiesClassmethod(self):
+ when(TrickDog).bark().thenReturn("miau!")
+ when(TrickDog).retrieve("stick").thenReturn("ball")
+
+ self.assertEqual("miau!", TrickDog.bark())
+ self.assertEqual("ball", TrickDog.retrieve("stick"))
+
+ verify(TrickDog).bark()
+ verify(TrickDog).retrieve("stick")
+
+ def testPreservesSuperClassClassMethodWhenStubbed(self):
+ self.assertEqual("woof!", Dog.bark())
+ self.assertEqual("stick", Retriever.retrieve("stick"))
+
+ self.assertEqual("woof!", TrickDog.bark())
+ self.assertEqual("stick", TrickDog.retrieve("stick"))
+
+ when(TrickDog).bark().thenReturn("miau!")
+ when(TrickDog).retrieve("stick").thenReturn("ball")
+
+ self.assertEqual("miau!", TrickDog.bark())
+ self.assertEqual("ball", TrickDog.retrieve("stick"))
+
+ self.assertEqual("woof!", Dog.bark())
+ self.assertEqual("stick", Retriever.retrieve("stick"))
+
+ def testDoubleStubStubWorksAfterUnstub(self):
+ when(TrickDog).retrieve("stick").thenReturn("ball")
+ when(TrickDog).retrieve("stick").thenReturn("cat")
+ unstub()
+ self.assertEqual("stick", TrickDog.retrieve("stick"))
+
+ def testUnStubWorksOnClassAndSuperClass(self):
+ self.assertEqual("stick", Retriever.retrieve("stick"))
+ self.assertEqual("stick", TrickDog.retrieve("stick"))
+
+ when(Retriever).retrieve("stick").thenReturn("ball")
+ self.assertEqual("ball", Retriever.retrieve("stick"))
+ self.assertEqual("ball", TrickDog.retrieve("stick"))
+
+ when(TrickDog).retrieve("stick").thenReturn("cat")
+ self.assertEqual("ball", Retriever.retrieve("stick"))
+ self.assertEqual("cat", TrickDog.retrieve("stick"))
+
+ unstub(TrickDog)
+ self.assertEqual("ball", Retriever.retrieve("stick"))
+ self.assertEqual("ball", TrickDog.retrieve("stick"))
+
+ unstub(Retriever)
+ self.assertEqual("stick", Retriever.retrieve("stick"))
+ self.assertEqual("stick", TrickDog.retrieve("stick"))
+
+ def testReverseOrderWhenUnstubbing(self):
+ when(Retriever).retrieve("stick").thenReturn("ball")
+ when(TrickDog).retrieve("stick").thenReturn("cat")
+
+ unstub(Retriever)
+ self.assertEqual("stick", Retriever.retrieve("stick"))
+ self.assertEqual("cat", TrickDog.retrieve("stick"))
+
+ unstub(TrickDog)
+ self.assertEqual("stick", Retriever.retrieve("stick"))
+ self.assertEqual("stick", TrickDog.retrieve("stick"))
|
Invocation of mocked @classmethod defined in super classes fails.
I recently tried mocking a class method and saw my test failing with a cryptic message
`Fail: TypeError: missing a required argument: 'id'` and an exception somewhere in the python library code.
I grabbed the mockito-python code, did some digging and found that the only thing that set my case apart from what mockito-python supports (and has tests for 👍) is that in my case, the class method I tried mocking, was defined on a super class of the object in `when()`.
Here's a little example that replicates the issue:
```python
class LoudBarker:
@classmethod
def loud_bark(cls, bark):
return bark
class Dog(LoudBarker):
@classmethod
def bark(cls):
return "woof!"
class LoudBarkerTest(TestBase):
def test_loud_dog(self):
when(Dog).loud_bark("woof!").thenReturn("WOOOOF!")
self.assertEqual(Dog.loud_bark("woof!"), "WOOOOF!") #fails with TypeError
```
Here, `Dog.loud_bark("woof!")` will fail with `Fail: TypeError: missing a required argument: 'bark'`.
If we write the mocking statement based on the class where the class method is defined, everything works as expected:
```python
def test_loud_bark__in_loud_barker(self):
when(LoudBarker).loud_bark("woof!").thenReturn("WOOOOF!")
self.assertEqual(Dog.loud_bark("woof!"), "WOOOOF!") #passes
```
In practice, this way of defining `when()` may be difficult because libraries do not always exactly expose in what class a class method is defined and source code may not always be available to find the answer.
|
0.0
|
79ae4340635c8298a79b1d6afc8e6b0b5ce26f88
|
[
"tests/classmethods_test.py::InheritedClassMethodsTest::testFailsVerificationOfMultipleCallsOnClassmethod",
"tests/classmethods_test.py::InheritedClassMethodsTest::testPreservesSuperClassClassMethodWhenStubbed",
"tests/classmethods_test.py::InheritedClassMethodsTest::testReverseOrderWhenUnstubbing",
"tests/classmethods_test.py::InheritedClassMethodsTest::testStubs",
"tests/classmethods_test.py::InheritedClassMethodsTest::testStubsAndVerifiesClassmethod",
"tests/classmethods_test.py::InheritedClassMethodsTest::testUnStubWorksOnClassAndSuperClass",
"tests/classmethods_test.py::InheritedClassMethodsTest::testVerifiesMultipleCallsOnClassmethod"
] |
[
"tests/classmethods_test.py::ClassMethodsTest::testFailsVerificationOfMultipleCallsOnClassmethod",
"tests/classmethods_test.py::ClassMethodsTest::testPreservesClassArgumentAfterUnstub",
"tests/classmethods_test.py::ClassMethodsTest::testStubs",
"tests/classmethods_test.py::ClassMethodsTest::testStubsAndVerifiesClassmethod",
"tests/classmethods_test.py::ClassMethodsTest::testStubsClassesDerivedFromTheObjectClass",
"tests/classmethods_test.py::ClassMethodsTest::testUnstubShouldPreserveMethodType",
"tests/classmethods_test.py::ClassMethodsTest::testUnstubs",
"tests/classmethods_test.py::ClassMethodsTest::testVerifiesMultipleCallsOnClassmethod",
"tests/classmethods_test.py::InheritedClassMethodsTest::testDoubleStubStubWorksAfterUnstub",
"tests/classmethods_test.py::InheritedClassMethodsTest::testUnstubs"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-02-16 17:36:48+00:00
|
mit
| 3,405 |
|
kaste__mockito-python-44
|
diff --git a/mockito/matchers.py b/mockito/matchers.py
index 9a44584..36c3815 100644
--- a/mockito/matchers.py
+++ b/mockito/matchers.py
@@ -61,7 +61,6 @@ The one usage you should not care about is a loose signature when using
import re
-
__all__ = [
'and_', 'or_', 'not_',
'eq', 'neq',
@@ -77,6 +76,7 @@ __all__ = [
'kwargs', 'KWARGS'
]
+
class _ArgsSentinel(object):
def __repr__(self):
return '*args'
@@ -106,6 +106,13 @@ KWARGS = kwargs = {KWARGS_SENTINEL: '_'}
# """
+
+class MatcherError(RuntimeError):
+ '''Indicates generic runtime error raised by mockito-python matchers
+ '''
+ pass
+
+
class Matcher:
def matches(self, arg):
pass
@@ -246,18 +253,24 @@ class Matches(Matcher):
class ArgumentCaptor(Matcher):
def __init__(self, matcher=None):
self.matcher = matcher or Any()
- self.value = None
+ self.all_values = []
def matches(self, arg):
result = self.matcher.matches(arg)
if not result:
return
- self.value = arg
+ self.all_values.append(arg)
return True
+ @property
+ def value(self):
+ if not self.all_values:
+ raise MatcherError("No argument value was captured!")
+ return self.all_values[-1]
+
def __repr__(self):
- return "<ArgumentCaptor: matcher=%s value=%s>" % (
- repr(self.matcher), self.value,
+ return "<ArgumentCaptor: matcher=%s values=%s>" % (
+ repr(self.matcher), self.all_values,
)
diff --git a/mockito/verification.py b/mockito/verification.py
index e7f766e..c36241b 100644
--- a/mockito/verification.py
+++ b/mockito/verification.py
@@ -22,6 +22,7 @@ import operator
__all__ = ['never', 'VerificationError']
+
class VerificationError(AssertionError):
'''Indicates error during verification of invocations.
|
kaste/mockito-python
|
ddab8c7cb556dc54a4fc5f65bc3f9d33dba356ad
|
diff --git a/tests/matchers_test.py b/tests/matchers_test.py
index 0ffcbc3..c7c0445 100644
--- a/tests/matchers_test.py
+++ b/tests/matchers_test.py
@@ -17,7 +17,7 @@
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
-
+from mockito.matchers import MatcherError
from .test_base import TestBase
from mockito import mock, verify
from mockito.matchers import and_, or_, not_, eq, neq, lt, lte, gt, gte, \
@@ -211,30 +211,38 @@ class ArgumentCaptorTest(TestBase):
def testShouldSatisfyIfInnerMatcherIsSatisfied(self):
c = captor(contains("foo"))
self.assertTrue(c.matches("foobar"))
+ self.assertListEqual(["foobar", ], c.all_values)
def testShouldNotSatisfyIfInnerMatcherIsNotSatisfied(self):
c = captor(contains("foo"))
self.assertFalse(c.matches("barbam"))
+ self.assertListEqual([], c.all_values)
def testShouldReturnNoneValueByDefault(self):
c = captor(contains("foo"))
- self.assertEqual(None, c.value)
+ self.assertListEqual([], c.all_values)
+ with self.assertRaises(MatcherError):
+ _ = c.value
def testShouldReturnNoneValueIfDidntMatch(self):
c = captor(contains("foo"))
c.matches("bar")
- self.assertEqual(None, c.value)
+ self.assertListEqual([], c.all_values)
+ with self.assertRaises(MatcherError):
+ _ = c.value
def testShouldReturnLastMatchedValue(self):
c = captor(contains("foo"))
c.matches("foobar")
c.matches("foobam")
c.matches("bambaz")
+ self.assertListEqual(["foobar", "foobam"], c.all_values)
self.assertEqual("foobam", c.value)
def testShouldDefaultMatcherToAny(self):
c = captor()
c.matches("foo")
c.matches(123)
+ self.assertListEqual(["foo", 123], c.all_values)
self.assertEqual(123, c.value)
|
Add support for capturing all the arguments when there are multiple invocations
Hi @kaste
First of all, Thank you for this project. I have been using mockito-python for a while now and really like its features (and its similarity with Java framework).
I went through the issues in the repo and could not find one that is related to what my ask is. So creating this issue. If this was discussed before, please feel free to close it and link it as duplicate tagging the older issue.
### Issue
Currently the `ArgumentCaptor` available in the `matchers` module allows capturing the method arguments. The limitation of this is that it just captures the last value when there are multiple invocations. For a usecase when a particular method is called multiple times with different values, its good to verify that the invocations were done with the correct arguments
### Solution
There are 2 solutions I think of after going through the repo
1. Add a new class called `MultipleInvocationsArgumentCaptor` that does this job. I also have an implementation ready (along with tests) for the same in this [branch](https://github.com/kaste/mockito-python/compare/master...shashankrnr32:multicaptor?expand=1). I am happy to raise this as a PR. (_Also, feel free to choose a new name for this class if its too long._ 😄 )
2. Modify the current `ArgumentCaptor` to take in multiple matchers and change certain aspects with this. This would be a backward incompatible change and I personally go with the 1st option keeping the current code as it is. But I added this option in case you want to maintain close similarity with Java framework, then this would be the preferred option.
As I said, I already have changes ready for the 1st solution I added([See branch](https://github.com/kaste/mockito-python/compare/master...shashankrnr32:multicaptor?expand=1)). I will raise the PR once I get your response on the 1st solution. If you opt to go with the other option, I will be happy to work on it in my free time and raise a PR in a couple of days.
Thank you!
|
0.0
|
ddab8c7cb556dc54a4fc5f65bc3f9d33dba356ad
|
[
"tests/matchers_test.py::TestConvenienceMatchers::testBuiltinAnyStandsForOurAny",
"tests/matchers_test.py::TestConvenienceMatchers::testOurAnyCanBeUsedAsAType",
"tests/matchers_test.py::TestAliases::testANY",
"tests/matchers_test.py::TestAliases::testARGS",
"tests/matchers_test.py::TestAliases::testKWARGS",
"tests/matchers_test.py::MatchersTest::testVerifiesUsingContainsMatcher",
"tests/matchers_test.py::AndMatcherTest::testShouldNotSatisfyIfOneOfMatchersIsNotSatisfied",
"tests/matchers_test.py::AndMatcherTest::testShouldSatisfyIfAllMatchersAreSatisfied",
"tests/matchers_test.py::AndMatcherTest::testShouldTreatNonMatchersAsEqMatcher",
"tests/matchers_test.py::OrMatcherTest::testShouldNotSatisfyIfAllOfMatchersAreNotSatisfied",
"tests/matchers_test.py::OrMatcherTest::testShouldSatisfyIfAnyOfMatchersIsSatisfied",
"tests/matchers_test.py::OrMatcherTest::testShouldTreatNonMatchersAsEqMatcher",
"tests/matchers_test.py::NotMatcherTest::testShouldNotSatisfyIfInnerMatcherIsSatisfied",
"tests/matchers_test.py::NotMatcherTest::testShouldSatisfyIfInnerMatcherIsNotSatisfied",
"tests/matchers_test.py::NotMatcherTest::testShouldTreatNonMatchersAsEqMatcher",
"tests/matchers_test.py::EqMatcherTest::testShouldNotSatisfyIfArgDoesNotMatchGivenValue",
"tests/matchers_test.py::EqMatcherTest::testShouldSatisfyIfArgMatchesGivenValue",
"tests/matchers_test.py::NeqMatcherTest::testShouldNotSatisfyIfArgMatchesGivenValue",
"tests/matchers_test.py::NeqMatcherTest::testShouldSatisfyIfArgDoesNotMatchGivenValue",
"tests/matchers_test.py::LtMatcherTest::testShouldNotSatisfyIfArgIsEqualToGivenValue",
"tests/matchers_test.py::LtMatcherTest::testShouldNotSatisfyIfArgIsGreaterThanGivenValue",
"tests/matchers_test.py::LtMatcherTest::testShouldSatisfyIfArgIsLessThanGivenValue",
"tests/matchers_test.py::LteMatcherTest::testShouldNotSatisfyIfArgIsGreaterThanGivenValue",
"tests/matchers_test.py::LteMatcherTest::testShouldSatisfyIfArgIsEqualToGivenValue",
"tests/matchers_test.py::LteMatcherTest::testShouldSatisfyIfArgIsLessThanGivenValue",
"tests/matchers_test.py::GtMatcherTest::testShouldNotSatisfyIfArgIsEqualToGivenValue",
"tests/matchers_test.py::GtMatcherTest::testShouldNotSatisfyIfArgIsLessThanGivenValue",
"tests/matchers_test.py::GtMatcherTest::testShouldSatisfyIfArgIsGreaterThanGivenValue",
"tests/matchers_test.py::GteMatcherTest::testShouldNotSatisfyIfArgIsLessThanGivenValue",
"tests/matchers_test.py::GteMatcherTest::testShouldSatisfyIfArgIsEqualToGivenValue",
"tests/matchers_test.py::GteMatcherTest::testShouldSatisfyIfArgIsGreaterThanGivenValue",
"tests/matchers_test.py::ArgThatMatcherTest::testShouldNotSatisfyIfPredicateReturnsFalse",
"tests/matchers_test.py::ArgThatMatcherTest::testShouldSatisfyIfPredicateReturnsTrue",
"tests/matchers_test.py::ContainsMatcherTest::testShouldNotSatisfiyEmptyString",
"tests/matchers_test.py::ContainsMatcherTest::testShouldNotSatisfiyNone",
"tests/matchers_test.py::ContainsMatcherTest::testShouldNotSatisfiyStringWhichIsNotSubstringOfGivenString",
"tests/matchers_test.py::ContainsMatcherTest::testShouldSatisfiySubstringOfGivenString",
"tests/matchers_test.py::ContainsMatcherTest::testShouldSatisfySameString",
"tests/matchers_test.py::MatchesMatcherTest::testShouldAllowSpecifyingRegexFlags",
"tests/matchers_test.py::MatchesMatcherTest::testShouldNotSatisfyIfRegexIsNotMatchedByGivenString",
"tests/matchers_test.py::MatchesMatcherTest::testShouldSatisfyIfRegexMatchesGivenString",
"tests/matchers_test.py::ArgumentCaptorTest::testShouldDefaultMatcherToAny",
"tests/matchers_test.py::ArgumentCaptorTest::testShouldNotSatisfyIfInnerMatcherIsNotSatisfied",
"tests/matchers_test.py::ArgumentCaptorTest::testShouldReturnLastMatchedValue",
"tests/matchers_test.py::ArgumentCaptorTest::testShouldReturnNoneValueByDefault",
"tests/matchers_test.py::ArgumentCaptorTest::testShouldReturnNoneValueIfDidntMatch",
"tests/matchers_test.py::ArgumentCaptorTest::testShouldSatisfyIfInnerMatcherIsSatisfied"
] |
[] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-12-02 03:43:46+00:00
|
mit
| 3,406 |
|
kaste__mockito-python-54
|
diff --git a/mockito/mocking.py b/mockito/mocking.py
index e52db5e..7ac5c8c 100644
--- a/mockito/mocking.py
+++ b/mockito/mocking.py
@@ -180,8 +180,11 @@ class Mock(object):
# the one on its class, so we delete as well.
if (
not original_method
- or not inspect.isclass(self.mocked_obj)
- and inspect.ismethod(original_method)
+ or (
+ inspect.ismethod(original_method)
+ and not inspect.isclass(self.mocked_obj)
+ and not inspect.ismodule(self.mocked_obj)
+ )
):
delattr(self.mocked_obj, method_name)
else:
|
kaste/mockito-python
|
699294f903025623a241a0259cf4c770614c61f2
|
diff --git a/tests/modulefunctions_test.py b/tests/modulefunctions_test.py
index 6d8728f..d1429e1 100644
--- a/tests/modulefunctions_test.py
+++ b/tests/modulefunctions_test.py
@@ -98,3 +98,10 @@ class ModuleFunctionsTest(TestBase):
from . import module
when(module).Foo().thenReturn('mocked')
assert module.Foo() == 'mocked'
+
+ def testUnstubFunctionOnModuleWhichIsActuallyAMethod_issue_53(self):
+ import random
+ when(random).randint(...).thenReturn("mocked")
+ assert random.randint(1, 10) == "mocked"
+ unstub(random)
+ assert random.randint(1, 10) != "mocked"
|
Issue unstubbing random.randint
When trying to monkeypatch random.randint and then later unstubbing the original method does not get reinstated. Example:
```
import sys
sys.version
Out[3]: '3.10.4 (main, Mar 31 2022, 03:38:35) [Clang 12.0.0 ]'
import random
import mockito
mockito.__version__
Out[6]: '1.2.2'
random.randint(1, 10)
Out[7]: 6
mockito.when(random).randint(...).thenReturn("Mocked!")
Out[8]: <mockito.invocation.AnswerSelector at 0x7ff076012c80>
random.randint(1, 10)
Out[9]: 'Mocked!'
mockito.unstub()
random.randint(1, 10)
Traceback (most recent call last):
...
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-11-a5705e42ffa6>", line 1, in <cell line: 1>
random.randint(1, 10)
AttributeError: module 'random' has no attribute 'randint'`
```
This seems to be because:
not inspect.isclass(self.mocked_obj) and inspect.ismethod(original_method)
in the method restore_method within mocking returns True when it should be False.
|
0.0
|
699294f903025623a241a0259cf4c770614c61f2
|
[
"tests/modulefunctions_test.py::ModuleFunctionsTest::testUnstubFunctionOnModuleWhichIsActuallyAMethod_issue_53"
] |
[
"tests/modulefunctions_test.py::ModuleFunctionsTest::testEnsureWeCanMockTheClassOnAModule",
"tests/modulefunctions_test.py::ModuleFunctionsTest::testFailsOnNumberOfCalls",
"tests/modulefunctions_test.py::ModuleFunctionsTest::testFailsVerification",
"tests/modulefunctions_test.py::ModuleFunctionsTest::testShouldThrowIfWeStubAFunctionNotDefinedInTheModule",
"tests/modulefunctions_test.py::ModuleFunctionsTest::testStubs",
"tests/modulefunctions_test.py::ModuleFunctionsTest::testStubsConsecutiveCalls",
"tests/modulefunctions_test.py::ModuleFunctionsTest::testStubsMultipleClasses",
"tests/modulefunctions_test.py::ModuleFunctionsTest::testStubsTwiceAndUnstubs",
"tests/modulefunctions_test.py::ModuleFunctionsTest::testStubsTwiceWithDifferentArguments",
"tests/modulefunctions_test.py::ModuleFunctionsTest::testUnstubs",
"tests/modulefunctions_test.py::ModuleFunctionsTest::testVerifiesSuccesfully"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2022-06-23 14:43:38+00:00
|
mit
| 3,407 |
|
kblin__ncbi-genome-download-25
|
diff --git a/ncbi_genome_download/core.py b/ncbi_genome_download/core.py
index 2a47d97..f2389df 100644
--- a/ncbi_genome_download/core.py
+++ b/ncbi_genome_download/core.py
@@ -286,6 +286,8 @@ def save_and_check(response, local_file, expected_checksum, symlink_path):
return False
if symlink_path is not None:
+ if os.path.lexists(symlink_path):
+ os.unlink(symlink_path)
os.symlink(os.path.abspath(local_file), symlink_path)
return True
|
kblin/ncbi-genome-download
|
07b61f5086322e87b4412480e2bd99bdadc57421
|
diff --git a/tests/test_core.py b/tests/test_core.py
index d372c91..3c17e9a 100644
--- a/tests/test_core.py
+++ b/tests/test_core.py
@@ -1,3 +1,4 @@
+import os
import pytest
import requests_mock
from argparse import Namespace
@@ -508,6 +509,21 @@ def test_download_file_symlink_path(req, tmpdir):
symlink = symlink_dir.join('fake_genomic.gbff.gz')
assert symlink.check()
+def test_download_file_symlink_path_existed(req, tmpdir):
+ entry = {'ftp_path': 'ftp://fake/path'}
+ fake_file = tmpdir.join('fake_genomic.gbff.gz')
+ fake_file.write('foo')
+ assert fake_file.check()
+ checksum = core.md5sum(str(fake_file))
+ checksums = [{'checksum': checksum, 'file': fake_file.basename}]
+ dl_dir = tmpdir.mkdir('download')
+ symlink_dir = tmpdir.mkdir('symlink')
+ symlink = symlink_dir.join('fake_genomic.gbff.gz')
+ os.symlink("/foo/bar", str(symlink))
+ req.get('https://fake/path/fake_genomic.gbff.gz', text=fake_file.read())
+
+ assert core.worker(core.download_file(entry, str(dl_dir), checksums, symlink_path=str(symlink_dir)))
+ assert symlink.check()
def test_get_genus_label():
fake_entry = {'organism_name': 'Example species ABC 1234'}
|
OSError: [Errno 17] File exists
Been getting this a bit when I restart jobs that failed due to unreachable network:
```
NFO: Starting new HTTPS connection (1): ftp.ncbi.nlm.nih.gov
DEBUG: "GET /genomes/all/GCA_001443705.1_ASM144370v1/GCA_001443705.1_ASM144370v1_genomic.gbff.gz HTTP/1.1" 200 185238057
Traceback (most recent call last):
File "/home/linuxbrew/.linuxbrew/bin/ncbi-genome-download", line 11, in <module>
sys.exit(main())
File "/home/linuxbrew/.linuxbrew/Cellar/python/2.7.12_1/lib/python2.7/site-packages/ncbi_genome_download/__main__.py", line 78, in main
INFO: Starting new HTTPS connection (1): ftp.ncbi.nlm.nih.gov
ret = ncbi_genome_download.download(args)
File "/home/linuxbrew/.linuxbrew/Cellar/python/2.7.12_1/lib/python2.7/site-packages/ncbi_genome_download/core.py", line 60, in download
args.taxid, args.human_readable, args.parallel)
File "/home/linuxbrew/.linuxbrew/Cellar/python/2.7.12_1/lib/python2.7/site-packages/ncbi_genome_download/core.py", line 94, in _download
pool.map(worker, download_jobs)
File "/home/linuxbrew/.linuxbrew/Cellar/python/2.7.12_1/lib/python2.7/multiprocessing/pool.py", line 251, in map
return self.map_async(func, iterable, chunksize).get()
File "/home/linuxbrew/.linuxbrew/Cellar/python/2.7.12_1/lib/python2.7/multiprocessing/pool.py", line 567, in get
raise self._value
OSError: [Errno 17] File exists
```
|
0.0
|
07b61f5086322e87b4412480e2bd99bdadc57421
|
[
"tests/test_core.py::test_download_file_symlink_path_existed"
] |
[
"tests/test_core.py::test_download_one",
"tests/test_core.py::test_download_all",
"tests/test_core.py::test_download_connection_err",
"tests/test_core.py::test__download",
"tests/test_core.py::test__download_complete",
"tests/test_core.py::test__download_chromosome",
"tests/test_core.py::test__download_scaffold",
"tests/test_core.py::test__download_contig",
"tests/test_core.py::test__download_genus",
"tests/test_core.py::test__download_genus_lowercase",
"tests/test_core.py::test__download_taxid",
"tests/test_core.py::test__download_species_taxid",
"tests/test_core.py::test_get_summary",
"tests/test_core.py::test_parse_summary",
"tests/test_core.py::test_download_entry_genbank",
"tests/test_core.py::test_download_entry_all",
"tests/test_core.py::test_download_entry_missing",
"tests/test_core.py::test_download_entry_human_readable",
"tests/test_core.py::test_create_dir",
"tests/test_core.py::test_create_dir_exists",
"tests/test_core.py::test_create_dir_isfile",
"tests/test_core.py::test_create_readable_dir",
"tests/test_core.py::test_create_readable_dir_exists",
"tests/test_core.py::test_create_readable_dir_isfile",
"tests/test_core.py::test_create_readable_dir_virus",
"tests/test_core.py::test_grab_checksums_file",
"tests/test_core.py::test_parse_checksums",
"tests/test_core.py::test_has_file_changed_no_file",
"tests/test_core.py::test_has_file_changed",
"tests/test_core.py::test_has_file_changed_unchanged",
"tests/test_core.py::test_md5sum",
"tests/test_core.py::test_download_file_genbank",
"tests/test_core.py::test_download_file_genbank_mismatch",
"tests/test_core.py::test_download_file_fasta",
"tests/test_core.py::test_download_file_cds_fasta",
"tests/test_core.py::test_download_file_rna_fasta",
"tests/test_core.py::test_download_file_symlink_path",
"tests/test_core.py::test_get_genus_label",
"tests/test_core.py::test_get_species_label",
"tests/test_core.py::test_get_strain_label"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2016-12-22 23:47:34+00:00
|
apache-2.0
| 3,408 |
|
kdunee__pyembeddedfhir-19
|
diff --git a/HISTORY.rst b/HISTORY.rst
index 6220350..3518afd 100755
--- a/HISTORY.rst
+++ b/HISTORY.rst
@@ -2,6 +2,8 @@
History
=======
+#11 Improved error handling.
+
1.1.2 (2021-11-07)
------------------
diff --git a/pyembeddedfhir/fhir_runner.py b/pyembeddedfhir/fhir_runner.py
index 46cdef0..44ed6f0 100644
--- a/pyembeddedfhir/fhir_runner.py
+++ b/pyembeddedfhir/fhir_runner.py
@@ -2,6 +2,7 @@ import logging
from typing import Optional
import docker # type: ignore[import]
+from docker.client import DockerClient # type: ignore[import]
from docker.models.networks import Network # type: ignore[import]
from docker.errors import APIError # type: ignore[import]
import psutil # type: ignore[import]
@@ -18,7 +19,7 @@ from .models import Configuration, FHIRFlavor, RunningFHIR
LOGGER = logging.getLogger(__name__)
-def _kill_orphaned_containers(docker_client: docker.DockerClient):
+def _kill_orphaned_containers(docker_client: DockerClient):
containers = docker_client.containers.list(
filters={
"label": DOCKER_LABEL_KEY,
@@ -34,7 +35,7 @@ def _kill_orphaned_containers(docker_client: docker.DockerClient):
container.kill()
-def _kill_orphaned_networks(docker_client: docker.DockerClient):
+def _kill_orphaned_networks(docker_client: DockerClient):
networks = docker_client.networks.list(
filters={
"label": DOCKER_LABEL_KEY,
@@ -82,7 +83,7 @@ class FHIRRunner(object):
:type startup_timeout: float, optional
:param docker_client: A Docker client, will be created
using ``docker.from_env()`` if not set, defaults to None
- :type docker_client: Optional[docker.DockerClient], optional
+ :type docker_client: Optional[DockerClient], optional
:ivar running_fhir: Descriptor of the running FHIR server.
:vartype running_fhir: RunningFHIR
:raises NotImplementedError: Selected implementation is not supported.
@@ -104,7 +105,7 @@ class FHIRRunner(object):
kill_orphans: bool = True,
network_id: Optional[str] = None,
startup_timeout: float = 120,
- docker_client: Optional[docker.DockerClient] = None,
+ docker_client: Optional[DockerClient] = None,
) -> None:
"""A constructor of ``RunningFHIR``."""
self._configuration = Configuration(
@@ -131,7 +132,8 @@ class FHIRRunner(object):
_kill_orphaned_containers(docker_client)
_kill_orphaned_networks(docker_client)
- if configuration.network_id is None:
+ new_network_created = configuration.network_id is None
+ if new_network_created:
network = docker_client.networks.create(
name="pyembeddedfhir",
driver="bridge",
@@ -141,11 +143,16 @@ class FHIRRunner(object):
network = docker_client.networks.get(configuration.network_id)
self._network = network
- return self._implementation.start(
- docker_client,
- configuration,
- network,
- )
+ try:
+ return self._implementation.start(
+ docker_client,
+ configuration,
+ network,
+ )
+ except: # noqa: E722 (intentionally using bare except)
+ if new_network_created:
+ network.remove()
+ raise
except APIError as e:
raise ContainerRuntimeError(e)
@@ -167,12 +174,10 @@ class FHIRRunner(object):
:raises ContainerRuntimeError: An error related to container runtime.
:raises AlreadyStoppedError: If the runner was already stopped.
"""
- # TODO: handle errors
self._stop()
def __enter__(self) -> RunningFHIR:
return self.running_fhir
def __exit__(self, exc_type, exc_val, exc_tb) -> None:
- # TODO: handle errors (wrap exc_val if needed)
self._stop()
diff --git a/pyembeddedfhir/implementations.py b/pyembeddedfhir/implementations.py
index 22eb239..c8008e0 100644
--- a/pyembeddedfhir/implementations.py
+++ b/pyembeddedfhir/implementations.py
@@ -136,6 +136,11 @@ class FHIRImplementation(ABC):
class HAPIFHIRImplementation(FHIRImplementation):
_CONTAINER_PORT = 8080
+ _containers: List[Container]
+
+ def __init__(self):
+ super().__init__()
+ self._containers = []
def _pull_image(self, docker_client: DockerClient) -> Image:
LOGGER.info("Pulling HAPI FHIR image...")
@@ -162,7 +167,7 @@ class HAPIFHIRImplementation(FHIRImplementation):
network=network.id,
labels={DOCKER_LABEL_KEY: get_docker_label_value()},
)
- self._container = container
+ self._containers.append(container)
container.reload()
return container
@@ -172,35 +177,44 @@ class HAPIFHIRImplementation(FHIRImplementation):
configuration: Configuration,
network: Network,
) -> RunningFHIR:
- image = self._pull_image(docker_client)
- ports_config = _prepare_ports_config(
- configuration.host_ip, HAPIFHIRImplementation._CONTAINER_PORT
- )
- container = self._run_container(
- docker_client,
- network,
- image,
- ports_config,
- )
+ try:
+ image = self._pull_image(docker_client)
+ ports_config = _prepare_ports_config(
+ configuration.host_ip, HAPIFHIRImplementation._CONTAINER_PORT
+ )
+ container = self._run_container(
+ docker_client,
+ network,
+ image,
+ ports_config,
+ )
- return _create_running_fhir_from_container(
- docker_client=docker_client,
- configuration=configuration,
- network=network,
- container=container,
- base_path="/fhir/",
- port=HAPIFHIRImplementation._CONTAINER_PORT,
- )
+ return _create_running_fhir_from_container(
+ docker_client=docker_client,
+ configuration=configuration,
+ network=network,
+ container=container,
+ base_path="/fhir/",
+ port=HAPIFHIRImplementation._CONTAINER_PORT,
+ )
+ except: # noqa: E722 (intentionally using bare except)
+ self.stop()
+ raise
def stop(self) -> None:
- self._container.kill()
+ for container in self._containers:
+ container.kill()
class MicrosoftFHIRImplemention(FHIRImplementation):
_SAPASSWORD = "wW89*XK6aedjMSz9s"
_CONTAINER_PORT = 8080
- _containers: List[Container] = []
+ _containers: List[Container]
+
+ def __init__(self):
+ super().__init__()
+ self._containers = []
def _pull_mssql_image(self, docker_client: DockerClient) -> Image:
LOGGER.info("Pulling MSSQL image...")
@@ -306,31 +320,43 @@ class MicrosoftFHIRImplemention(FHIRImplementation):
configuration: Configuration,
network: Network,
) -> RunningFHIR:
- mssql_image = self._pull_mssql_image(docker_client)
- mssql_container = self._run_mssql(mssql_image, docker_client, network)
- self._wait_for_mssql(mssql_container, configuration.startup_timeout)
- mssql_network_settings = mssql_container.attrs["NetworkSettings"]
- mssql_network = _select_container_network_by_id(
- network.id, mssql_network_settings["Networks"].values()
- )
- mssql_host = mssql_network["IPAddress"]
+ try:
+ mssql_image = self._pull_mssql_image(docker_client)
+ mssql_container = self._run_mssql(
+ mssql_image,
+ docker_client,
+ network,
+ )
+ self._wait_for_mssql(
+ mssql_container,
+ configuration.startup_timeout,
+ )
+ mssql_network_settings = mssql_container.attrs["NetworkSettings"]
+ mssql_network = _select_container_network_by_id(
+ network.id, mssql_network_settings["Networks"].values()
+ )
+ mssql_host = mssql_network["IPAddress"]
- ports_config = _prepare_ports_config(
- configuration.host_ip, MicrosoftFHIRImplemention._CONTAINER_PORT
- )
- fhir_image = self._pull_fhir_server(docker_client)
- fhir_container = self._run_fhir_server(
- fhir_image, docker_client, network, mssql_host, ports_config
- )
+ ports_config = _prepare_ports_config(
+ configuration.host_ip,
+ MicrosoftFHIRImplemention._CONTAINER_PORT,
+ )
+ fhir_image = self._pull_fhir_server(docker_client)
+ fhir_container = self._run_fhir_server(
+ fhir_image, docker_client, network, mssql_host, ports_config
+ )
- return _create_running_fhir_from_container(
- docker_client=docker_client,
- configuration=configuration,
- network=network,
- container=fhir_container,
- base_path="/",
- port=MicrosoftFHIRImplemention._CONTAINER_PORT,
- )
+ return _create_running_fhir_from_container(
+ docker_client=docker_client,
+ configuration=configuration,
+ network=network,
+ container=fhir_container,
+ base_path="/",
+ port=MicrosoftFHIRImplemention._CONTAINER_PORT,
+ )
+ except: # noqa: E722 (intentionally using bare except)
+ self.stop()
+ raise
def stop(self) -> None:
for container in self._containers:
|
kdunee/pyembeddedfhir
|
e397c352453b9b910e807037826ff3c03ca3c413
|
diff --git a/tests/unit/test_fhir_runner.py b/tests/unit/test_fhir_runner.py
new file mode 100644
index 0000000..ac71256
--- /dev/null
+++ b/tests/unit/test_fhir_runner.py
@@ -0,0 +1,99 @@
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from pyembeddedfhir.fhir_runner import FHIRRunner
+from pyembeddedfhir.models import FHIRFlavor
+
+
[email protected]
+def network_mock():
+ return MagicMock()
+
+
[email protected]
+def docker_client_mock(network_mock):
+ mock = MagicMock()
+ mock.networks.create.return_value = network_mock
+ return mock
+
+
+class SomeUnexpectedError(Exception):
+ pass
+
+
[email protected]
+def implementation_constructor_mock():
+ return MagicMock()
+
+
[email protected]
+def patched_hapi_fhir_implementation(implementation_constructor_mock):
+ with patch(
+ "pyembeddedfhir.fhir_runner.HAPIFHIRImplementation",
+ implementation_constructor_mock,
+ ):
+ yield implementation_constructor_mock
+
+
+class TestNetworkRemoval:
+ def test_network_removal_when_failure(
+ self,
+ docker_client_mock,
+ patched_hapi_fhir_implementation,
+ network_mock,
+ ):
+ """When faced with any error in the implementation,
+ FHIRRunner should delete created network."""
+ implementation = patched_hapi_fhir_implementation.return_value
+ implementation.start.side_effect = SomeUnexpectedError()
+ with pytest.raises(SomeUnexpectedError):
+ FHIRRunner(
+ FHIRFlavor.HAPI,
+ docker_client=docker_client_mock,
+ )
+ network_mock.remove.assert_called_once()
+
+ def test_when_success(
+ self,
+ docker_client_mock,
+ patched_hapi_fhir_implementation,
+ network_mock,
+ ):
+ """When the implementation succeeds,
+ FHIRRunner should not delete created network."""
+ FHIRRunner(
+ FHIRFlavor.HAPI,
+ docker_client=docker_client_mock,
+ )
+ network_mock.remove.assert_not_called()
+
+ def test_when_context_manager(
+ self,
+ docker_client_mock,
+ patched_hapi_fhir_implementation,
+ network_mock,
+ ):
+ """When FHIRRunner is used as context manager,
+ it should delete created network."""
+ with FHIRRunner(
+ FHIRFlavor.HAPI,
+ docker_client=docker_client_mock,
+ ):
+ pass
+ network_mock.remove.assert_called_once()
+
+ def test_when_stop(
+ self,
+ docker_client_mock,
+ patched_hapi_fhir_implementation,
+ network_mock,
+ ):
+ """When stop() is explicitly called,
+ FHIRRunner should delete created network."""
+ runner = FHIRRunner(
+ FHIRFlavor.HAPI,
+ docker_client=docker_client_mock,
+ )
+ runner.stop()
+ network_mock.remove.assert_called_once()
diff --git a/tests/unit/test_implementations.py b/tests/unit/test_implementations.py
new file mode 100644
index 0000000..c588840
--- /dev/null
+++ b/tests/unit/test_implementations.py
@@ -0,0 +1,113 @@
+from unittest.mock import MagicMock
+import pytest
+
+from pyembeddedfhir.implementations import (
+ HAPIFHIRImplementation,
+ MicrosoftFHIRImplemention,
+)
+from pyembeddedfhir.models import Configuration
+
+
[email protected]
+def network_mock():
+ return MagicMock()
+
+
[email protected]
+def container_mock(network_mock):
+ mock = MagicMock()
+ mock.exec_run.return_value = (0, None)
+ mock.attrs = {
+ "NetworkSettings": {
+ "Networks": {
+ "a": {
+ "NetworkID": network_mock.id,
+ "IPAddress": "127.0.0.1",
+ },
+ },
+ },
+ }
+ mock.wait.return_value = {"StatusCode": 0}
+ return mock
+
+
[email protected]
+def docker_client_mock(container_mock):
+ mock = MagicMock()
+ mock.containers.run.return_value = container_mock
+ return mock
+
+
[email protected]
+def sample_configuration(docker_client_mock):
+ return Configuration(docker_client=docker_client_mock)
+
+
+class SomeError(Exception):
+ pass
+
+
+class TestContainerRemoval:
+ def test_microsoft_kills_both_containers_when_failure(
+ self,
+ docker_client_mock,
+ network_mock,
+ sample_configuration,
+ container_mock,
+ ):
+ container_mock.wait.side_effect = SomeError()
+ implementation = MicrosoftFHIRImplemention()
+ with pytest.raises(SomeError):
+ implementation.start(
+ docker_client_mock,
+ sample_configuration,
+ network_mock,
+ )
+ assert container_mock.kill.call_count == 2
+
+ def test_microsoft_kills_no_containers_when_success(
+ self,
+ docker_client_mock,
+ network_mock,
+ sample_configuration,
+ container_mock,
+ ):
+ implementation = MicrosoftFHIRImplemention()
+ implementation.start(
+ docker_client_mock,
+ sample_configuration,
+ network_mock,
+ )
+ assert container_mock.kill.call_count == 0
+
+ def test_hapi_kills_container_when_failure(
+ self,
+ docker_client_mock,
+ network_mock,
+ sample_configuration,
+ container_mock,
+ ):
+ container_mock.wait.side_effect = SomeError()
+ implementation = HAPIFHIRImplementation()
+ with pytest.raises(SomeError):
+ implementation.start(
+ docker_client_mock,
+ sample_configuration,
+ network_mock,
+ )
+ assert container_mock.kill.call_count == 1
+
+ def test_hapi_kills_no_containers_when_success(
+ self,
+ docker_client_mock,
+ network_mock,
+ sample_configuration,
+ container_mock,
+ ):
+ implementation = HAPIFHIRImplementation()
+ implementation.start(
+ docker_client_mock,
+ sample_configuration,
+ network_mock,
+ )
+ assert container_mock.kill.call_count == 0
|
Resolve outstanding TODOs related to error handling
|
0.0
|
e397c352453b9b910e807037826ff3c03ca3c413
|
[
"tests/unit/test_fhir_runner.py::TestNetworkRemoval::test_network_removal_when_failure",
"tests/unit/test_implementations.py::TestContainerRemoval::test_microsoft_kills_both_containers_when_failure",
"tests/unit/test_implementations.py::TestContainerRemoval::test_hapi_kills_container_when_failure"
] |
[
"tests/unit/test_fhir_runner.py::TestNetworkRemoval::test_when_success",
"tests/unit/test_fhir_runner.py::TestNetworkRemoval::test_when_context_manager",
"tests/unit/test_fhir_runner.py::TestNetworkRemoval::test_when_stop",
"tests/unit/test_implementations.py::TestContainerRemoval::test_microsoft_kills_no_containers_when_success",
"tests/unit/test_implementations.py::TestContainerRemoval::test_hapi_kills_no_containers_when_success"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-11-09 20:26:40+00:00
|
mit
| 3,409 |
|
kecorbin__virlutils-36
|
diff --git a/virl/cli/pull/commands.py b/virl/cli/pull/commands.py
index debc4c6..99c5423 100644
--- a/virl/cli/pull/commands.py
+++ b/virl/cli/pull/commands.py
@@ -12,7 +12,10 @@ def pull(repo, **kwargs):
url = "https://raw.githubusercontent.com/"
url = url + "{}/master/topology.virl".format(repo)
resp = requests.get(url)
-
- with open('topology.virl', 'w') as fh:
- fh.write(resp.text)
- click.secho("Saved topology as topology.virl", fg="green")
+ if resp.ok:
+ with open('topology.virl', 'w') as fh:
+ fh.write(resp.text)
+ click.secho("Saved topology as topology.virl", fg="green")
+ else:
+ click.secho("Error pulling {} - repo not found".format(repo),
+ fg="red")
|
kecorbin/virlutils
|
2af0696d84fa86568d0228fbd63ac543934fd153
|
diff --git a/tests/pull.py b/tests/pull.py
index 05c8204..2f060be 100644
--- a/tests/pull.py
+++ b/tests/pull.py
@@ -17,3 +17,16 @@ class Tests(BaseTest):
runner = CliRunner()
result = runner.invoke(virl, ["pull", "foo/bar"])
self.assertEqual(0, result.exit_code)
+
+ def test_virl_pull_invalid_repo(self):
+ with requests_mock.mock() as m:
+ # Mock the request to return what we expect from the API.
+
+ topo_url = 'https://raw.githubusercontent.com/'
+ topo_url += 'doesnt/exist/master/topology.virl'
+ m.get(topo_url, status_code=400)
+ runner = CliRunner()
+ result = runner.invoke(virl, ["pull", "doesnt/exist"])
+ expected = "Pulling from doesnt/exist\nError pulling " \
+ "doesnt/exist - repo not found\n"
+ self.assertEqual(result.output, expected)
|
need error handling on `virl pull`
## Example
This workflow should provide an error back to the user
```
[root@localhost test2]# virl pull foo
Pulling from foo
Saved topology as topology.virl
You have new mail in /var/spool/mail/root
[root@localhost test2]# cat topology.virl
400: Invalid request
```
|
0.0
|
2af0696d84fa86568d0228fbd63ac543934fd153
|
[
"tests/pull.py::Tests::test_virl_pull_invalid_repo"
] |
[
"tests/pull.py::Tests::test_virl_pull"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2018-05-02 16:20:48+00:00
|
mit
| 3,410 |
|
kedro-org__kedro-3272
|
diff --git a/RELEASE.md b/RELEASE.md
index 90b8adf1..33dc1c28 100644
--- a/RELEASE.md
+++ b/RELEASE.md
@@ -6,6 +6,7 @@
* The new spaceflights starters, `spaceflights-pandas`, `spaceflights-pandas-viz`, `spaceflights-pyspark`, and `spaceflights-pyspark-viz` can be used with the `kedro new` command with the `--starter` flag.
* Added the `--conf-source` option to `%reload_kedro`, allowing users to specify a source for project configuration.
* Added the functionality to choose a merging strategy for config files loaded with `OmegaConfigLoader`.
+* Modified the mechanism of importing datasets, raise more explicit error when dependencies are missing.
## Bug fixes and other changes
diff --git a/kedro/io/core.py b/kedro/io/core.py
index e620d15f..f605c272 100644
--- a/kedro/io/core.py
+++ b/kedro/io/core.py
@@ -376,14 +376,14 @@ def parse_dataset_definition(
if "type" not in config:
raise DatasetError("'type' is missing from dataset catalog configuration")
- class_obj = config.pop("type")
- if isinstance(class_obj, str):
- if len(class_obj.strip(".")) != len(class_obj):
+ dataset_type = config.pop("type")
+ if isinstance(dataset_type, str):
+ if len(dataset_type.strip(".")) != len(dataset_type):
raise DatasetError(
"'type' class path does not support relative "
"paths or paths ending with a dot."
)
- class_paths = (prefix + class_obj for prefix in _DEFAULT_PACKAGES)
+ class_paths = (prefix + dataset_type for prefix in _DEFAULT_PACKAGES)
for class_path in class_paths:
tmp = _load_obj(class_path)
@@ -391,10 +391,7 @@ def parse_dataset_definition(
class_obj = tmp
break
else:
- raise DatasetError(
- f"Class '{class_obj}' not found or one of its dependencies "
- f"has not been installed."
- )
+ raise DatasetError(f"Class '{dataset_type}' not found, is this a typo?")
if not issubclass(class_obj, AbstractDataset):
raise DatasetError(
@@ -422,8 +419,9 @@ def parse_dataset_definition(
return class_obj, config
-def _load_obj(class_path: str) -> object | None:
+def _load_obj(class_path: str) -> Any | None:
mod_path, _, class_name = class_path.rpartition(".")
+ # Check if the module exists
try:
available_classes = load_obj(f"{mod_path}.__all__")
# ModuleNotFoundError: When `load_obj` can't find `mod_path` (e.g `kedro.io.pandas`)
@@ -432,18 +430,16 @@ def _load_obj(class_path: str) -> object | None:
# `__all__` attribute -- either because it's a custom or a kedro.io dataset
except (ModuleNotFoundError, AttributeError, ValueError):
available_classes = None
-
try:
class_obj = load_obj(class_path)
- except (ModuleNotFoundError, ValueError):
- return None
- except AttributeError as exc:
+ except (ModuleNotFoundError, ValueError, AttributeError) as exc:
+ # If it's available, module exist but dependencies are missing
if available_classes and class_name in available_classes:
raise DatasetError(
- f"{exc} Please see the documentation on how to "
+ f"{exc}. Please see the documentation on how to "
f"install relevant dependencies for {class_path}:\n"
- f"https://kedro.readthedocs.io/en/stable/"
- f"kedro_project_setup/dependencies.html"
+ f"https://docs.kedro.org/en/stable/kedro_project_setup/"
+ f"dependencies.html#install-dependencies-related-to-the-data-catalog"
) from exc
return None
diff --git a/kedro/utils.py b/kedro/utils.py
index 6067d96b..f527b909 100644
--- a/kedro/utils.py
+++ b/kedro/utils.py
@@ -23,6 +23,4 @@ def load_obj(obj_path: str, default_obj_path: str = "") -> Any:
obj_path = obj_path_list.pop(0) if len(obj_path_list) > 1 else default_obj_path
obj_name = obj_path_list[0]
module_obj = importlib.import_module(obj_path)
- if not hasattr(module_obj, obj_name):
- raise AttributeError(f"Object '{obj_name}' cannot be loaded from '{obj_path}'.")
return getattr(module_obj, obj_name)
|
kedro-org/kedro
|
6f4119f8912a4ba7b9f14980ff18a89a0dda9abd
|
diff --git a/tests/io/test_core.py b/tests/io/test_core.py
index dcf2f30a..1cbea798 100644
--- a/tests/io/test_core.py
+++ b/tests/io/test_core.py
@@ -19,6 +19,7 @@ from kedro.io.core import (
generate_timestamp,
get_filepath_str,
get_protocol_and_path,
+ parse_dataset_definition,
validate_on_forbidden_chars,
)
@@ -265,6 +266,32 @@ class TestCoreFunctions:
with pytest.raises(DatasetError, match=expected_error_message):
validate_on_forbidden_chars(**input)
+ def test_dataset_name_typo(self, mocker):
+ # If the module doesn't exist, it return None instead ModuleNotFoundError
+ mocker.patch("kedro.io.core.load_obj", return_value=None)
+ dataset_name = "lAmbDaDaTAsET"
+
+ with pytest.raises(
+ DatasetError, match=f"Class '{dataset_name}' not found, is this a typo?"
+ ):
+ parse_dataset_definition({"type": dataset_name})
+
+ def test_dataset_missing_dependencies(self, mocker):
+ # If the module is found but import the dataset trigger ModuleNotFoundError
+ dataset_name = "LambdaDataset"
+
+ def side_effect_function(value):
+ if "__all__" in value:
+ return [dataset_name]
+ else:
+ raise ModuleNotFoundError
+
+ mocker.patch("kedro.io.core.load_obj", side_effect=side_effect_function)
+
+ pattern = "Please see the documentation on how to install relevant dependencies"
+ with pytest.raises(DatasetError, match=pattern):
+ parse_dataset_definition({"type": dataset_name})
+
class TestAbstractVersionedDataset:
def test_version_str_repr(self, load_version, save_version):
diff --git a/tests/test_utils.py b/tests/test_utils.py
index 1ca93067..34704513 100644
--- a/tests/test_utils.py
+++ b/tests/test_utils.py
@@ -18,12 +18,6 @@ class TestExtractObject:
extracted_obj = load_obj("DummyClass", "tests.test_utils")
assert extracted_obj is DummyClass
- def test_load_obj_invalid_attribute(self):
- with pytest.raises(
- AttributeError, match=r"Object 'InvalidClass' cannot be loaded"
- ):
- load_obj("InvalidClass", "tests.test_utils")
-
def test_load_obj_invalid_module(self):
with pytest.raises(ImportError, match=r"No module named 'missing_path'"):
load_obj("InvalidClass", "missing_path")
|
Make import failures in `kedro-datasets` clearer
## Description
Disambiguate the "module does not exist" error from the `ImportError` in messages like:
```
DatasetError: An exception occurred when parsing config for dataset 'companies':
Class 'polars.CSVDataSet' not found or one of its dependencies has not been installed.
```
This task will require investigation into how the error messages are swallowed, which will inform the proper implementation. Probably change: https://github.com/kedro-org/kedro/blob/4194fbd16a992af0320a395c0060aaaea356efb2/kedro/io/core.py#L433
## Context
This week I've been battling some puzzling documentation errors and after a while I noticed that, if the dependencies of a particular dataset are not present, the `ImportError` is swallowed silently. Examples:
https://github.com/kedro-org/kedro-plugins/blob/b8881d113f8082ff03e0233db3ae4557a4c32547/kedro-datasets/kedro_datasets/biosequence/__init__.py#L7-L8
https://github.com/kedro-org/kedro-plugins/blob/b8881d113f8082ff03e0233db3ae4557a4c32547/kedro-datasets/kedro_datasets/networkx/__init__.py#L8-L15
This was done in https://github.com/quantumblacklabs/private-kedro/pull/575 to solve https://github.com/quantumblacklabs/private-kedro/issues/563 at the same time dependencies were moved to `extras_require`.
I see how _not_ suppressing these errors could be extremely annoying back then, because `kedro.io` used to re-export all the datasets in its `__init__.py`:
https://github.com/quantumblacklabs/private-kedro/blob/f7dd2478aec4de1b46afbaded9bce3c69bff6304/kedro/io/__init__.py#L29-L47
```python
# kedro/io/__init__.py
"""``kedro.io`` provides functionality to read and write to a
number of data sets. At core of the library is ``AbstractDataSet``
which allows implementation of various ``AbstractDataSet``s.
"""
from .cached_dataset import CachedDataSet # NOQA
from .core import AbstractDataSet # NOQA
from .core import AbstractVersionedDataSet # NOQA
from .core import DataSetAlreadyExistsError # NOQA
from .core import DataSetError # NOQA
from .core import DataSetNotFoundError # NOQA
from .core import Version # NOQA
from .data_catalog import DataCatalog # NOQA
from .data_catalog_with_default import DataCatalogWithDefault # NOQA
from .lambda_data_set import LambdaDataSet # NOQA
from .memory_data_set import MemoryDataSet # NOQA
from .partitioned_data_set import IncrementalDataSet # NOQA
from .partitioned_data_set import PartitionedDataSet # NOQA
from .transformers import AbstractTransformer # NOQA
```
However, now our `__init__.py` is empty and datasets are meant to be imported separately:
https://github.com/kedro-org/kedro-plugins/blob/b8881d113f8082ff03e0233db3ae4557a4c32547/kedro-datasets/kedro_datasets/__init__.py#L1-L3
So I think it would be much better if we did _not_ silence those import errors.
## More context
If one dependency is missing, the user would get an unhelpful "module X has no attribute Y" when trying to import a dataset rather than an actual error:
```
> pip uninstall biopython (kedro-dev)
Found existing installation: biopython 1.81
Uninstalling biopython-1.81:
Would remove:
/Users/juan_cano/.micromamba/envs/kedro-dev/lib/python3.10/site-packages/Bio/*
/Users/juan_cano/.micromamba/envs/kedro-dev/lib/python3.10/site-packages/BioSQL/*
/Users/juan_cano/.micromamba/envs/kedro-dev/lib/python3.10/site-packages/biopython-1.81.dist-info/*
Proceed (Y/n)? y
Successfully uninstalled biopython-1.81
> python (kedro-dev)
Python 3.10.9 | packaged by conda-forge | (main, Feb 2 2023, 20:26:08) [Clang 14.0.6 ] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from kedro_datasets.biosequence import BioSequenceDataSet
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: cannot import name 'BioSequenceDataSet' from 'kedro_datasets.biosequence' (/Users/juan_cano/.micromamba/envs/kedro-dev/lib/python3.10/site-packages/kedro_datasets/biosequence/__init__.py)
```
|
0.0
|
6f4119f8912a4ba7b9f14980ff18a89a0dda9abd
|
[
"tests/io/test_core.py::TestCoreFunctions::test_dataset_name_typo",
"tests/io/test_core.py::TestCoreFunctions::test_dataset_missing_dependencies"
] |
[
"tests/io/test_core.py::TestCoreFunctions::test_str_representation[1]",
"tests/io/test_core.py::TestCoreFunctions::test_str_representation[True]",
"tests/io/test_core.py::TestCoreFunctions::test_str_representation[False]",
"tests/io/test_core.py::TestCoreFunctions::test_str_representation[0]",
"tests/io/test_core.py::TestCoreFunctions::test_str_representation[0.0]",
"tests/io/test_core.py::TestCoreFunctions::test_str_representation[0j]",
"tests/io/test_core.py::TestCoreFunctions::test_str_representation[var6]",
"tests/io/test_core.py::TestCoreFunctions::test_str_representation[var7]",
"tests/io/test_core.py::TestCoreFunctions::test_str_representation[]",
"tests/io/test_core.py::TestCoreFunctions::test_str_representation[var9]",
"tests/io/test_core.py::TestCoreFunctions::test_str_representation[var10]",
"tests/io/test_core.py::TestCoreFunctions::test_str_representation[var11]",
"tests/io/test_core.py::TestCoreFunctions::test_str_representation[var12]",
"tests/io/test_core.py::TestCoreFunctions::test_str_representation[var13]",
"tests/io/test_core.py::TestCoreFunctions::test_str_representation_none",
"tests/io/test_core.py::TestCoreFunctions::test_get_filepath_str",
"tests/io/test_core.py::TestCoreFunctions::test_get_protocol_and_path[s3://bucket/file.txt-expected_result0]",
"tests/io/test_core.py::TestCoreFunctions::test_get_protocol_and_path[s3://user@BUCKET/file.txt-expected_result1]",
"tests/io/test_core.py::TestCoreFunctions::test_get_protocol_and_path[gcs://bucket/file.txt-expected_result2]",
"tests/io/test_core.py::TestCoreFunctions::test_get_protocol_and_path[gs://bucket/file.txt-expected_result3]",
"tests/io/test_core.py::TestCoreFunctions::test_get_protocol_and_path[adl://bucket/file.txt-expected_result4]",
"tests/io/test_core.py::TestCoreFunctions::test_get_protocol_and_path[abfs://bucket/file.txt-expected_result5]",
"tests/io/test_core.py::TestCoreFunctions::test_get_protocol_and_path[abfss://bucket/file.txt-expected_result6]",
"tests/io/test_core.py::TestCoreFunctions::test_get_protocol_and_path[abfss://[email protected]/mypath-expected_result7]",
"tests/io/test_core.py::TestCoreFunctions::test_get_protocol_and_path[hdfs://namenode:8020/file.txt-expected_result8]",
"tests/io/test_core.py::TestCoreFunctions::test_get_protocol_and_path[file:///tmp/file.txt-expected_result9]",
"tests/io/test_core.py::TestCoreFunctions::test_get_protocol_and_path[/tmp/file.txt-expected_result10]",
"tests/io/test_core.py::TestCoreFunctions::test_get_protocol_and_path[C:\\\\Projects\\\\file.txt-expected_result11]",
"tests/io/test_core.py::TestCoreFunctions::test_get_protocol_and_path[file:///C:\\\\Projects\\\\file.txt-expected_result12]",
"tests/io/test_core.py::TestCoreFunctions::test_get_protocol_and_path[https://example.com/file.txt-expected_result13]",
"tests/io/test_core.py::TestCoreFunctions::test_get_protocol_and_path[http://example.com/file.txt-expected_result14]",
"tests/io/test_core.py::TestCoreFunctions::test_get_protocol_and_path_http_with_version[http://example.com/file.txt]",
"tests/io/test_core.py::TestCoreFunctions::test_get_protocol_and_path_http_with_version[https://example.com/file.txt]",
"tests/io/test_core.py::TestCoreFunctions::test_validate_forbidden_chars[input0]",
"tests/io/test_core.py::TestCoreFunctions::test_validate_forbidden_chars[input1]",
"tests/io/test_core.py::TestAbstractVersionedDataset::test_version_str_repr[None-None]",
"tests/io/test_core.py::TestAbstractVersionedDataset::test_save_and_load[None-None]",
"tests/io/test_core.py::TestAbstractVersionedDataset::test_resolve_save_version",
"tests/io/test_core.py::TestAbstractVersionedDataset::test_no_versions[None-None]",
"tests/io/test_core.py::TestAbstractVersionedDataset::test_local_exists",
"tests/io/test_core.py::TestAbstractVersionedDataset::test_exists_general_exception",
"tests/io/test_core.py::TestAbstractVersionedDataset::test_exists[None-None]",
"tests/io/test_core.py::TestAbstractVersionedDataset::test_prevent_overwrite[None-None]",
"tests/io/test_core.py::TestAbstractVersionedDataset::test_save_version_warning[2019-01-02T00.00.00.000Z-2019-01-01T23.59.59.999Z]",
"tests/io/test_core.py::TestAbstractVersionedDataset::test_versioning_existing_dataset[None-None-None-None]",
"tests/io/test_core.py::TestAbstractVersionedDataset::test_cache_release[None-None]",
"tests/test_utils.py::TestExtractObject::test_load_obj",
"tests/test_utils.py::TestExtractObject::test_load_obj_default_path",
"tests/test_utils.py::TestExtractObject::test_load_obj_invalid_module"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-11-06 05:14:09+00:00
|
apache-2.0
| 3,411 |
|
keleshev__schema-174
|
diff --git a/README.rst b/README.rst
index 0d1855c..28186f8 100644
--- a/README.rst
+++ b/README.rst
@@ -298,6 +298,18 @@ for the same data:
>>> Schema(And(Or(int, float), lambda x: x > 0)).validate(3.1415)
3.1415
+In a dictionary, you can also combine two keys in a "one or the other" manner. To do
+so, use the `Or` class as a key:
+
+.. code:: python
+ from schema import Or, Schema
+ schema = Schema({
+ Or("key1", "key2", only_one=True): str
+ })
+
+ schema.validate({"key1": "test"}) # Ok
+ schema.validate({"key1": "test", "key2": "test"}) # SchemaWrongKeyError
+
Hooks
~~~~~~~~~~
You can define hooks which are functions that are executed whenever a valid key:value is found.
diff --git a/schema.py b/schema.py
index 03e6909..cfae8b9 100644
--- a/schema.py
+++ b/schema.py
@@ -71,6 +71,7 @@ class And(object):
"""
Utility function to combine validation directives in AND Boolean fashion.
"""
+
def __init__(self, *args, **kw):
self._args = args
if not set(kw).issubset({'error', 'schema', 'ignore_extra_keys'}):
@@ -102,6 +103,15 @@ class And(object):
class Or(And):
"""Utility function to combine validation directives in a OR Boolean
fashion."""
+
+ def __init__(self, *args, **kwargs):
+ self.only_one = kwargs.pop('only_one', False)
+ self.reset()
+ super(Or, self).__init__(*args, **kwargs)
+
+ def reset(self):
+ self.got_one = False
+
def validate(self, data):
"""
Validate data using sub defined schema/expressions ensuring at least
@@ -114,7 +124,11 @@ class Or(And):
ignore_extra_keys=self._ignore_extra_keys)
for s in self._args]:
try:
- return s.validate(data)
+ validation = s.validate(data)
+ if self.got_one and self.only_one:
+ break
+ self.got_one = True
+ return validation
except SchemaError as _x:
autos, errors = _x.autos, _x.errors
raise SchemaError(['%r did not validate %r' % (self, data)] + autos,
@@ -170,6 +184,7 @@ class Use(object):
For more general use cases, you can use the Use class to transform
the data while it is being validate.
"""
+
def __init__(self, callable_, error=None):
if not callable(callable_):
raise TypeError('Expected a callable, not %r' % callable_)
@@ -217,6 +232,7 @@ class Schema(object):
Entry point of the library, use this class to instantiate validation
schema for the data that will be validated.
"""
+
def __init__(self, schema, error=None, ignore_extra_keys=False):
self._schema = schema
self._error = error
@@ -266,6 +282,10 @@ class Schema(object):
coverage = set() # matched schema keys
# for each key and value find a schema entry matching them, if any
sorted_skeys = sorted(s, key=self._dict_key_priority)
+ for skey in sorted_skeys:
+ if isinstance(skey, Or):
+ skey.reset()
+
for key, value in data.items():
for skey in sorted_skeys:
svalue = s[skey]
|
keleshev/schema
|
f463ab62d4d5078484e97fec071bac6876b9beef
|
diff --git a/test_schema.py b/test_schema.py
index 553e841..e230ba1 100644
--- a/test_schema.py
+++ b/test_schema.py
@@ -81,6 +81,16 @@ def test_or():
with SE: Or().validate(2)
+def test_or_only_one():
+ schema = Schema({
+ Or("test1", "test2", only_one=True): str
+ })
+ assert schema.validate({"test1": "value"})
+ assert schema.validate({"test2": "other_value"})
+ with SE: schema.validate({"test1": "value", "test2": "other_value"})
+ with SE: schema.validate({"othertest": "value"})
+
+
def test_test():
def unique_list(_list):
return len(_list) == len(set(_list))
|
XOr implementation
First of all, this library is awesome.
I've implemented a `XOr` class for exclusive schemas (shamelessly copying from the `Or` class). Maybe this is naively wrong, but so far this has worked as expected.
``` python
class XOr(And):
def validate(self, data):
accepted = False
x = SchemaError([], [])
for s in [Schema(s, error=self._error) for s in self._args]:
try:
validated = s.validate(data)
if accepted:
raise SchemaError(['%r did not validate %r' % (self, data)],
[self._error])
accepted = True
except SchemaError as _x:
x = _x
if not accepted:
raise SchemaError(['%r did not validate %r' % (self, data)] + x.autos,
[self._error] + x.errors)
return validated
```
If you are interested in this, I can open a PR.
|
0.0
|
f463ab62d4d5078484e97fec071bac6876b9beef
|
[
"test_schema.py::test_or_only_one"
] |
[
"test_schema.py::test_and_error_handling",
"test_schema.py::test_exception_handling_with_bad_validators",
"test_schema.py::test_error_reporting",
"test_schema.py::test_optional_key_convert_failed_randomly_while_with_another_optional_object",
"test_schema.py::test_nice_errors",
"test_schema.py::test_and",
"test_schema.py::test_issue_83_iterable_validation_return_type",
"test_schema.py::test_dict",
"test_schema.py::test_or",
"test_schema.py::test_ignore_extra_keys",
"test_schema.py::test_issue_9_prioritized_key_comparison",
"test_schema.py::test_copy",
"test_schema.py::test_regex",
"test_schema.py::test_use_error_handling",
"test_schema.py::test_validate_file",
"test_schema.py::test_missing_keys_exception_with_non_str_dict_keys",
"test_schema.py::test_validate_list",
"test_schema.py::test_dict_key_error",
"test_schema.py::test_schema",
"test_schema.py::test_dict_optional_defaults",
"test_schema.py::test_dict_keys",
"test_schema.py::test_dict_forbidden_keys",
"test_schema.py::test_complex",
"test_schema.py::test_ignore_extra_keys_validation_and_return_keys",
"test_schema.py::test_dict_subtypes",
"test_schema.py::test_dict_hook",
"test_schema.py::test_use_json",
"test_schema.py::test_test",
"test_schema.py::test_schema_repr",
"test_schema.py::test_list_tuple_set_frozenset",
"test_schema.py::test_validate_object",
"test_schema.py::test_strictly",
"test_schema.py::test_schema_error_handling",
"test_schema.py::test_issue_9_prioritized_key_comparison_in_dicts",
"test_schema.py::test_dict_optional_keys",
"test_schema.py::test_inheritance",
"test_schema.py::test_or_error_handling",
"test_schema.py::test_issue_56_cant_rely_on_callables_to_have_name"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-10-17 18:37:36+00:00
|
mit
| 3,412 |
|
keleshev__schema-247
|
diff --git a/schema.py b/schema.py
index ef5dede..a1ada98 100644
--- a/schema.py
+++ b/schema.py
@@ -220,7 +220,7 @@ class Regex(object):
if self._pattern.search(data):
return data
else:
- raise SchemaError("%r does not match %r" % (self, data), e)
+ raise SchemaError("%r does not match %r" % (self, data), e.format(data) if e else None)
except TypeError:
raise SchemaError("%r is not string nor buffer" % data, e)
@@ -344,7 +344,7 @@ class Schema(object):
def validate(self, data):
Schema = self.__class__
s = self._schema
- e = self._error.format(data) if self._error else None
+ e = self._error
i = self._ignore_extra_keys
if isinstance(s, Literal):
@@ -397,7 +397,7 @@ class Schema(object):
except SchemaError as x:
k = "Key '%s' error:" % nkey
message = self._prepend_schema_name(k)
- raise SchemaError([message] + x.autos, [e] + x.errors)
+ raise SchemaError([message] + x.autos, [e.format(data) if e else None] + x.errors)
else:
new[nkey] = nvalue
coverage.add(skey)
@@ -408,13 +408,13 @@ class Schema(object):
s_missing_keys = ", ".join(repr(k) for k in sorted(missing_keys, key=repr))
message = "Missing key%s: %s" % (_plural_s(missing_keys), s_missing_keys)
message = self._prepend_schema_name(message)
- raise SchemaMissingKeyError(message, e)
+ raise SchemaMissingKeyError(message, e.format(data) if e else None)
if not self._ignore_extra_keys and (len(new) != len(data)):
wrong_keys = set(data.keys()) - set(new.keys())
s_wrong_keys = ", ".join(repr(k) for k in sorted(wrong_keys, key=repr))
message = "Wrong key%s %s in %r" % (_plural_s(wrong_keys), s_wrong_keys, data)
message = self._prepend_schema_name(message)
- raise SchemaWrongKeyError(message, e)
+ raise SchemaWrongKeyError(message, e.format(data) if e else None)
# Apply default-having optionals that haven't been used:
defaults = set(k for k in s if type(k) is Optional and hasattr(k, "default")) - coverage
@@ -428,36 +428,36 @@ class Schema(object):
else:
message = "%r should be instance of %r" % (data, s.__name__)
message = self._prepend_schema_name(message)
- raise SchemaUnexpectedTypeError(message, e)
+ raise SchemaUnexpectedTypeError(message, e.format(data) if e else None)
if flavor == VALIDATOR:
try:
return s.validate(data)
except SchemaError as x:
- raise SchemaError([None] + x.autos, [e] + x.errors)
+ raise SchemaError([None] + x.autos, [e.format(data) if e else None] + x.errors)
except BaseException as x:
message = "%r.validate(%r) raised %r" % (s, data, x)
message = self._prepend_schema_name(message)
- raise SchemaError(message, e)
+ raise SchemaError(message, e.format(data) if e else None)
if flavor == CALLABLE:
f = _callable_str(s)
try:
if s(data):
return data
except SchemaError as x:
- raise SchemaError([None] + x.autos, [e] + x.errors)
+ raise SchemaError([None] + x.autos, [e.format(data) if e else None] + x.errors)
except BaseException as x:
message = "%s(%r) raised %r" % (f, data, x)
message = self._prepend_schema_name(message)
- raise SchemaError(message, e)
+ raise SchemaError(message, e.format(data) if e else None)
message = "%s(%r) should evaluate to True" % (f, data)
message = self._prepend_schema_name(message)
- raise SchemaError(message, e)
+ raise SchemaError(message, e.format(data) if e else None)
if s == data:
return data
else:
message = "%r does not match %r" % (s, data)
message = self._prepend_schema_name(message)
- raise SchemaError(message, e)
+ raise SchemaError(message, e.format(data) if e else None)
def json_schema(self, schema_id, use_refs=False):
"""Generate a draft-07 JSON schema dict representing the Schema.
|
keleshev/schema
|
a600fb465bdf2f4d4896df7d411ad3e57a4713bf
|
diff --git a/test_schema.py b/test_schema.py
index fb7a59f..d8af5e0 100644
--- a/test_schema.py
+++ b/test_schema.py
@@ -1600,3 +1600,18 @@ def test_prepend_schema_name():
Schema(int, name="custom_schemaname").validate("a")
except SchemaUnexpectedTypeError as e:
assert str(e) == "'custom_schemaname' 'a' should be instance of 'int'"
+
+
+def test_dict_literal_error_string():
+ # this is a simplified regression test of the bug in github issue #240
+ assert Schema(Or({"a": 1}, error="error: {}")).is_valid(dict(a=1))
+
+
+def test_callable_error():
+ # this tests for the behavior desired in github pull request #238
+ e = None
+ try:
+ Schema(lambda d: False, error="{}").validate("This is the error message")
+ except SchemaError as ex:
+ e = ex
+ assert e.errors == ["This is the error message"]
|
Formatting error when supplying raw dict as schema to `Or`
I'm not sure if this is valid Schema usage, but I wanted to drop my reproduction here just in case.
I have a schema that looks like this:
```python
import schema as s
test1 = s.Or(str, {
s.Optional("gpu"): str,
s.Optional("cpu"): str
},
error="Got '{}'")
test1.validate({"cpu": "face", "gpu": "cake"})
```
Trying to run that code throws this error:
```python
self = Schema(<class 'dict'>), data = {'cpu': 'face', 'gpu': 'cake'}
def validate(self, data):
Schema = self.__class__
s = self._schema
> e = self._error.format(data) if self._error else None
E KeyError: "'cpu'"
env/lib/python3.6/site-packages/schema.py:372: KeyError
```
When I trace, it looks like what's happening is that `self._error` on the `Or` schema is getting set to the FILLED schema, on this line:
https://github.com/keleshev/schema/blob/master/schema.py#L345
ie, when I insert `print(self._error)` there, I see:
```python
Got '{}'
Got '{'cpu': 'face', 'gpu': 'cake'}'
```
Which creates this case:
```python
>>> "Got '{'cpu': 'face', 'gpu': 'cake'}'".format({'cpu': 'face', 'gpu': 'cake'})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: "'cpu'"
```
The issue's solved if I wrap the dictionary in `s.Schema`... but it might be worth having `Or`, `And` etc do the wrapping for us if it sees a raw dict to prevent this issue.
Hope this helps!
|
0.0
|
a600fb465bdf2f4d4896df7d411ad3e57a4713bf
|
[
"test_schema.py::test_dict_literal_error_string"
] |
[
"test_schema.py::test_copy",
"test_schema.py::test_json_schema",
"test_schema.py::test_json_schema_title_and_description",
"test_schema.py::test_nice_errors",
"test_schema.py::test_json_schema_root_not_dict[input_schema6-enum-expected_value6]",
"test_schema.py::test_json_schema_description_nested",
"test_schema.py::test_or",
"test_schema.py::test_strictly",
"test_schema.py::test_json_schema_and_types",
"test_schema.py::test_json_schema_nested",
"test_schema.py::test_json_schema_root_not_dict[list-type-array]",
"test_schema.py::test_literal_repr",
"test_schema.py::test_json_schema_root_not_dict[input_schema8-allOf-expected_value8]",
"test_schema.py::test_json_schema_types",
"test_schema.py::test_json_schema_additional_properties[input_schema2-False-True]",
"test_schema.py::test_test",
"test_schema.py::test_dict_hook",
"test_schema.py::test_callable_error",
"test_schema.py::test_json_schema_array[input_schema2-type-string]",
"test_schema.py::test_json_schema_default_is_tuple",
"test_schema.py::test_json_schema_or_only_one",
"test_schema.py::test_json_schema_array[input_schema1-const-1]",
"test_schema.py::test_json_schema_object_or_array_of_object",
"test_schema.py::test_json_schema_additional_properties[input_schema4-True-True]",
"test_schema.py::test_json_schema_definitions",
"test_schema.py::test_json_schema_or_values",
"test_schema.py::test_json_schema_array[input_schema0-enum-expected_value0]",
"test_schema.py::test_json_schema_dict_type",
"test_schema.py::test_description_with_default",
"test_schema.py::test_json_schema_root_not_dict[input_schema7-anyOf-expected_value7]",
"test_schema.py::test_ignore_extra_keys_validation_and_return_keys",
"test_schema.py::test_json_schema_optional_key",
"test_schema.py::test_json_schema_and_list",
"test_schema.py::test_or_error_handling",
"test_schema.py::test_json_schema_forbidden_key_ignored",
"test_schema.py::test_json_schema_other_types",
"test_schema.py::test_json_schema_definitions_recursive",
"test_schema.py::test_inheritance",
"test_schema.py::test_list_tuple_set_frozenset",
"test_schema.py::test_json_schema_const_is_none",
"test_schema.py::test_use_json",
"test_schema.py::test_json_schema_with_title",
"test_schema.py::test_use_error_handling",
"test_schema.py::test_json_schema_default_value",
"test_schema.py::test_validate_list",
"test_schema.py::test_description",
"test_schema.py::test_json_schema_additional_properties[input_schema0-False-False]",
"test_schema.py::test_json_schema_nested_schema",
"test_schema.py::test_json_schema_default_value_with_literal",
"test_schema.py::test_json_schema_additional_properties[input_schema3-False-True]",
"test_schema.py::test_json_schema_additional_properties[input_schema1-False-True]",
"test_schema.py::test_prepend_schema_name",
"test_schema.py::test_regex",
"test_schema.py::test_json_schema_default_is_none",
"test_schema.py::test_json_schema_default_is_custom_type",
"test_schema.py::test_validate_file",
"test_schema.py::test_dict_subtypes",
"test_schema.py::test_json_schema_definitions_and_literals",
"test_schema.py::test_json_schema_refs",
"test_schema.py::test_json_schema_refs_no_missing",
"test_schema.py::test_dict_keys",
"test_schema.py::test_json_schema_description_and_nested",
"test_schema.py::test_issue_56_cant_rely_on_callables_to_have_name",
"test_schema.py::test_error_reporting",
"test_schema.py::test_issue_9_prioritized_key_comparison",
"test_schema.py::test_schema_error_handling",
"test_schema.py::test_ignore_extra_keys",
"test_schema.py::test_json_schema_optional_key_nested",
"test_schema.py::test_json_schema_default_is_literal",
"test_schema.py::test_json_schema_root_not_dict[dict-type-object]",
"test_schema.py::test_json_schema_const_is_custom_type",
"test_schema.py::test_and_error_handling",
"test_schema.py::test_json_schema_or_key",
"test_schema.py::test_validate_object",
"test_schema.py::test_issue_9_prioritized_key_comparison_in_dicts",
"test_schema.py::test_missing_keys_exception_with_non_str_dict_keys",
"test_schema.py::test_optional_key_convert_failed_randomly_while_with_another_optional_object",
"test_schema.py::test_json_schema_additional_properties_multiple",
"test_schema.py::test_json_schema_description_or_nested",
"test_schema.py::test_or_only_one",
"test_schema.py::test_json_schema_const_is_callable",
"test_schema.py::test_json_schema_regex_root",
"test_schema.py::test_dict_key_error",
"test_schema.py::test_and",
"test_schema.py::test_dict",
"test_schema.py::test_json_schema_or_values_nested",
"test_schema.py::test_json_schema_root_not_dict[float-type-number]",
"test_schema.py::test_dict_optional_keys",
"test_schema.py::test_issue_83_iterable_validation_return_type",
"test_schema.py::test_dict_optional_defaults",
"test_schema.py::test_dict_forbidden_keys",
"test_schema.py::test_json_schema_root_not_dict[int-type-integer]",
"test_schema.py::test_json_schema_and_simple",
"test_schema.py::test_json_schema_ref_in_list",
"test_schema.py::test_complex",
"test_schema.py::test_json_schema_definitions_invalid",
"test_schema.py::test_schema",
"test_schema.py::test_json_schema_or_one_value",
"test_schema.py::test_schema_repr",
"test_schema.py::test_json_schema_root_not_dict[bool-type-boolean]",
"test_schema.py::test_json_schema_refs_is_smaller",
"test_schema.py::test_json_schema_regex",
"test_schema.py::test_json_schema_definitions_nested",
"test_schema.py::test_exception_handling_with_bad_validators",
"test_schema.py::test_json_schema_literal_with_enum",
"test_schema.py::test_json_schema_or_values_with_optional",
"test_schema.py::test_json_schema_root_not_dict[test-const-test]",
"test_schema.py::test_json_schema_or_types"
] |
{
"failed_lite_validators": [
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-11-25 07:01:13+00:00
|
mit
| 3,413 |
|
kennethreitz__records-118
|
diff --git a/records.py b/records.py
index 2a9bb56..0fe09ca 100644
--- a/records.py
+++ b/records.py
@@ -52,6 +52,8 @@ class Record(object):
# Support for string-based lookup.
if key in self.keys():
i = self.keys().index(key)
+ if self.keys().count(key) > 1:
+ raise KeyError("Record contains multiple '{}' fields.".format(key))
return self.values()[i]
raise KeyError("Record contains no '{}' field.".format(key))
@@ -296,7 +298,7 @@ class Database(object):
# If path doesn't exists
if not os.path.exists(path):
- raise IOError("File '{}'' not found!".format(path))
+ raise IOError("File '{}' not found!".format(path))
# If it's a directory
if os.path.isdir(path):
|
kennethreitz/records
|
fcd41c36c93c1fcac43557da46f62435b1c44716
|
diff --git a/tests/test_records.py b/tests/test_records.py
index 722591f..7e42731 100644
--- a/tests/test_records.py
+++ b/tests/test_records.py
@@ -97,3 +97,9 @@ class TestRecord:
assert key in _dir
for key in dir(object):
assert key in _dir
+
+ def test_record_duplicate_column(self):
+ keys, values = ['id', 'name', 'email', 'email'], [1, '', '', '']
+ record = records.Record(keys, values)
+ with raises(KeyError):
+ record['email']
|
Records silently ignores duplicate field name in joined tables.
In an SQL query I had joined to tables that happened to have a field with the same name (with different content). Records selected one of the fields without complaining; it just happened to be the wrong one.
```sql
SELECT *
FROM A LEFT OUTER JOIN B on A.somekey=B.somekey
WHERE .....
```
If A and B contain a field with the same name, just one is returned. Usually the table name is prefixed to distinguish them, but I assume Records just uses the fieldname without prefix. That is usually convenient but not in this case. I think I'd prefer an error message.
|
0.0
|
fcd41c36c93c1fcac43557da46f62435b1c44716
|
[
"tests/test_records.py::TestRecord::test_record_duplicate_column"
] |
[
"tests/test_records.py::TestRecordCollection::test_iter",
"tests/test_records.py::TestRecordCollection::test_next",
"tests/test_records.py::TestRecordCollection::test_iter_and_next",
"tests/test_records.py::TestRecordCollection::test_multiple_iter",
"tests/test_records.py::TestRecordCollection::test_slice_iter",
"tests/test_records.py::TestRecordCollection::test_all_returns_a_list_of_records",
"tests/test_records.py::TestRecordCollection::test_first_returns_a_single_record",
"tests/test_records.py::TestRecordCollection::test_first_defaults_to_None",
"tests/test_records.py::TestRecordCollection::test_first_default_is_overridable",
"tests/test_records.py::TestRecordCollection::test_first_raises_when_more_than_first",
"tests/test_records.py::TestRecordCollection::test_first_raises_default_if_its_an_exception_subclass",
"tests/test_records.py::TestRecordCollection::test_first_raises_default_if_its_an_exception_instance",
"tests/test_records.py::TestRecord::test_record_dir"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2017-12-07 16:49:26+00:00
|
isc
| 3,414 |
|
keras-team__keras-autodoc-32
|
diff --git a/keras_autodoc/autogen.py b/keras_autodoc/autogen.py
index 7f8e379..0318aca 100644
--- a/keras_autodoc/autogen.py
+++ b/keras_autodoc/autogen.py
@@ -1,6 +1,6 @@
import shutil
import pathlib
-from inspect import isclass, isfunction
+from inspect import isclass, isfunction, getdoc
from typing import Dict, Union
from .docstring import process_docstring
@@ -78,10 +78,10 @@ class DocumentationGenerator:
signature = get_class_signature(cls, signature_override)
signature = self.process_signature(signature)
subblocks.append(utils.code_snippet(signature))
- docstring = cls.__doc__
+ docstring = getdoc(cls)
if docstring:
subblocks.append(self.process_class_docstring(docstring, cls))
- return '\n'.join(subblocks) + '\n----\n\n'
+ return '\n'.join(subblocks) + '\n\n----\n\n'
def _render_method(self, method, signature_override=None):
subblocks = []
@@ -90,11 +90,11 @@ class DocumentationGenerator:
subblocks.append(f"### {method.__name__} method:\n")
subblocks.append(utils.code_snippet(signature))
- docstring = method.__doc__
+ docstring = getdoc(method)
if docstring:
docstring = self.process_method_docstring(docstring, method)
subblocks.append(docstring)
- return "\n\n".join(subblocks) + '\n----\n\n'
+ return "\n\n".join(subblocks) + '\n\n----\n\n'
def _render_function(self, function, signature_override=None):
subblocks = []
@@ -103,8 +103,8 @@ class DocumentationGenerator:
subblocks.append(f"### {function.__name__} function:\n")
subblocks.append(utils.code_snippet(signature))
- docstring = function.__doc__
+ docstring = getdoc(function)
if docstring:
docstring = self.process_function_docstring(docstring, function)
subblocks.append(docstring)
- return "\n\n".join(subblocks) + '\n----\n\n'
+ return "\n\n".join(subblocks) + '\n\n----\n\n'
diff --git a/keras_autodoc/docstring.py b/keras_autodoc/docstring.py
index 5d71d4f..20cfc33 100644
--- a/keras_autodoc/docstring.py
+++ b/keras_autodoc/docstring.py
@@ -97,7 +97,7 @@ def get_code_blocks(docstring):
def get_sections(docstring):
# Format docstring lists.
- section_regex = r"\n( +)# (.*)\n"
+ section_regex = r"\n( *)# (.*)\n"
section_idx = re.search(section_regex, docstring)
shift = 0
sections = {}
|
keras-team/keras-autodoc
|
cd500b1351d6c71f5825bb5d97f86f3058f00456
|
diff --git a/tests/dummy_package/dummy_module.py b/tests/dummy_package/dummy_module.py
index 73e8f4b..58a028d 100644
--- a/tests/dummy_package/dummy_module.py
+++ b/tests/dummy_package/dummy_module.py
@@ -188,7 +188,9 @@ class ImageDataGenerator:
interpolation_order: int, order to use for
the spline interpolation. Higher is slower.
dtype: Dtype to use for the generated arrays.
+
# Examples
+
Example of using `.flow(x, y)`:
```python
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
diff --git a/tests/dummy_package/expected.md b/tests/dummy_package/expected.md
index ba981ed..a764c49 100644
--- a/tests/dummy_package/expected.md
+++ b/tests/dummy_package/expected.md
@@ -69,7 +69,7 @@ __Output shape__
nD tensor with shape: `(batch_size, ..., units)`.
For instance, for a 2D input with shape `(batch_size, input_dim)`,
the output would have shape `(batch_size, units)`.
-
+
----
<span style="float:right;">[[source]](www.dummy.com/my_project/tests/dummy_package/dummy_module.py#L113)</span>
@@ -157,8 +157,10 @@ __Arguments__
- __interpolation_order__: int, order to use for
the spline interpolation. Higher is slower.
- __dtype__: Dtype to use for the generated arrays.
+
__Examples__
+
Example of using `.flow(x, y)`:
```python
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
@@ -278,7 +280,7 @@ model.fit_generator(
validation_data=validation_generator,
validation_steps=800)
```
-
+
----
### flow method:
@@ -332,7 +334,7 @@ An `Iterator` yielding tuples of `(x, y)`
of corresponding labels. If 'sample_weight' is not None,
the yielded tuples are of the form `(x, y, sample_weight)`.
If `y` is None, only the numpy array `x` is returned.
-
+
----
### flow_from_directory method:
@@ -418,7 +420,7 @@ A `DirectoryIterator` yielding tuples of `(x, y)`
where `x` is a numpy array containing a batch
of images with shape `(batch_size, *target_size, channels)`
and `y` is a numpy array of corresponding labels.
-
+
----
### to_categorical function:
@@ -463,6 +465,6 @@ array([[ 1., 0., 0.],
[ 0., 0., 1.],
[ 1., 0., 0.]], dtype=float32)
```
-
+
----
diff --git a/tests/test_autogen.py b/tests/test_autogen.py
index 327bd00..85dc003 100644
--- a/tests/test_autogen.py
+++ b/tests/test_autogen.py
@@ -8,156 +8,156 @@ from .dummy_package import dummy_module
test_doc1 = {
"doc": """Base class for recurrent layers.
- # Arguments
- cell: A RNN cell instance. A RNN cell is a class that has:
- - a `call(input_at_t, states_at_t)` method, returning
- `(output_at_t, states_at_t_plus_1)`. The call method of the
- cell can also take the optional argument `constants`, see
- section "Note on passing external constants" below.
- - a `state_size` attribute. This can be a single integer
- (single state) in which case it is
- the size of the recurrent state
- (which should be the same as the size of the cell output).
- This can also be a list/tuple of integers
- (one size per state). In this case, the first entry
- (`state_size[0]`) should be the same as
- the size of the cell output.
- It is also possible for `cell` to be a list of RNN cell instances,
- in which cases the cells get stacked on after the other in the RNN,
- implementing an efficient stacked RNN.
- return_sequences: Boolean. Whether to return the last output
- in the output sequence, or the full sequence.
- return_state: Boolean. Whether to return the last state
- in addition to the output.
- go_backwards: Boolean (default False).
- If True, process the input sequence backwards and return the
- reversed sequence.
- stateful: Boolean (default False). If True, the last state
- for each sample at index i in a batch will be used as initial
- state for the sample of index i in the following batch.
- unroll: Boolean (default False).
- If True, the network will be unrolled,
- else a symbolic loop will be used.
- Unrolling can speed-up a RNN,
- although it tends to be more memory-intensive.
- Unrolling is only suitable for short sequences.
- input_dim: dimensionality of the input (integer).
- This argument (or alternatively,
- the keyword argument `input_shape`)
- is required when using this layer as the first layer in a model.
- input_length: Length of input sequences, to be specified
- when it is constant.
- This argument is required if you are going to connect
- `Flatten` then `Dense` layers upstream
- (without it, the shape of the dense outputs cannot be computed).
- Note that if the recurrent layer is not the first layer
- in your model, you would need to specify the input length
- at the level of the first layer
- (e.g. via the `input_shape` argument)
-
- # Input shape
- 3D tensor with shape `(batch_size, timesteps, input_dim)`.
-
- # Output shape
- - if `return_state`: a list of tensors. The first tensor is
- the output. The remaining tensors are the last states,
- each with shape `(batch_size, units)`.
- - if `return_sequences`: 3D tensor with shape
- `(batch_size, timesteps, units)`.
- - else, 2D tensor with shape `(batch_size, units)`.
-
- # Masking
- This layer supports masking for input data with a variable number
- of timesteps. To introduce masks to your data,
- use an [Embedding](embeddings.md) layer with the `mask_zero` parameter
- set to `True`.
-
- # Note on using statefulness in RNNs
- You can set RNN layers to be 'stateful', which means that the states
- computed for the samples in one batch will be reused as initial states
- for the samples in the next batch. This assumes a one-to-one mapping
- between samples in different successive batches.
-
- To enable statefulness:
- - specify `stateful=True` in the layer constructor.
- - specify a fixed batch size for your model, by passing
- if sequential model:
- `batch_input_shape=(...)` to the first layer in your model.
- else for functional model with 1 or more Input layers:
- `batch_shape=(...)` to all the first layers in your model.
- This is the expected shape of your inputs
- *including the batch size*.
- It should be a tuple of integers, e.g. `(32, 10, 100)`.
- - specify `shuffle=False` when calling fit().
-
- To reset the states of your model, call `.reset_states()` on either
- a specific layer, or on your entire model.
-
- # Note on specifying the initial state of RNNs
- Note: that
- One: You can specify the initial state of RNN layers symbolically by
- calling them with the keyword argument `initial_state`.
- Two: The value of `initial_state` should be a tensor or list of
- tensors representing
- the initial state of the RNN layer.
- You can specify the initial state of RNN layers numerically by:
- One: calling `reset_states`
- - With the keyword argument `states`.
- - The value of
- `states` should be a numpy array or
- list of numpy arrays representing
+# Arguments
+ cell: A RNN cell instance. A RNN cell is a class that has:
+ - a `call(input_at_t, states_at_t)` method, returning
+ `(output_at_t, states_at_t_plus_1)`. The call method of the
+ cell can also take the optional argument `constants`, see
+ section "Note on passing external constants" below.
+ - a `state_size` attribute. This can be a single integer
+ (single state) in which case it is
+ the size of the recurrent state
+ (which should be the same as the size of the cell output).
+ This can also be a list/tuple of integers
+ (one size per state). In this case, the first entry
+ (`state_size[0]`) should be the same as
+ the size of the cell output.
+ It is also possible for `cell` to be a list of RNN cell instances,
+ in which cases the cells get stacked on after the other in the RNN,
+ implementing an efficient stacked RNN.
+ return_sequences: Boolean. Whether to return the last output
+ in the output sequence, or the full sequence.
+ return_state: Boolean. Whether to return the last state
+ in addition to the output.
+ go_backwards: Boolean (default False).
+ If True, process the input sequence backwards and return the
+ reversed sequence.
+ stateful: Boolean (default False). If True, the last state
+ for each sample at index i in a batch will be used as initial
+ state for the sample of index i in the following batch.
+ unroll: Boolean (default False).
+ If True, the network will be unrolled,
+ else a symbolic loop will be used.
+ Unrolling can speed-up a RNN,
+ although it tends to be more memory-intensive.
+ Unrolling is only suitable for short sequences.
+ input_dim: dimensionality of the input (integer).
+ This argument (or alternatively,
+ the keyword argument `input_shape`)
+ is required when using this layer as the first layer in a model.
+ input_length: Length of input sequences, to be specified
+ when it is constant.
+ This argument is required if you are going to connect
+ `Flatten` then `Dense` layers upstream
+ (without it, the shape of the dense outputs cannot be computed).
+ Note that if the recurrent layer is not the first layer
+ in your model, you would need to specify the input length
+ at the level of the first layer
+ (e.g. via the `input_shape` argument)
+
+# Input shape
+ 3D tensor with shape `(batch_size, timesteps, input_dim)`.
+
+# Output shape
+ - if `return_state`: a list of tensors. The first tensor is
+ the output. The remaining tensors are the last states,
+ each with shape `(batch_size, units)`.
+ - if `return_sequences`: 3D tensor with shape
+ `(batch_size, timesteps, units)`.
+ - else, 2D tensor with shape `(batch_size, units)`.
+
+# Masking
+ This layer supports masking for input data with a variable number
+ of timesteps. To introduce masks to your data,
+ use an [Embedding](embeddings.md) layer with the `mask_zero` parameter
+ set to `True`.
+
+# Note on using statefulness in RNNs
+ You can set RNN layers to be 'stateful', which means that the states
+ computed for the samples in one batch will be reused as initial states
+ for the samples in the next batch. This assumes a one-to-one mapping
+ between samples in different successive batches.
+
+ To enable statefulness:
+ - specify `stateful=True` in the layer constructor.
+ - specify a fixed batch size for your model, by passing
+ if sequential model:
+ `batch_input_shape=(...)` to the first layer in your model.
+ else for functional model with 1 or more Input layers:
+ `batch_shape=(...)` to all the first layers in your model.
+ This is the expected shape of your inputs
+ *including the batch size*.
+ It should be a tuple of integers, e.g. `(32, 10, 100)`.
+ - specify `shuffle=False` when calling fit().
+
+ To reset the states of your model, call `.reset_states()` on either
+ a specific layer, or on your entire model.
+
+# Note on specifying the initial state of RNNs
+Note: that
+ One: You can specify the initial state of RNN layers symbolically by
+ calling them with the keyword argument `initial_state`.
+ Two: The value of `initial_state` should be a tensor or list of
+ tensors representing
the initial state of the RNN layer.
+ You can specify the initial state of RNN layers numerically by:
+ One: calling `reset_states`
+ - With the keyword argument `states`.
+ - The value of
+ `states` should be a numpy array or
+ list of numpy arrays representing
+ the initial state of the RNN layer.
+
+# Note on passing external constants to RNNs
+ You can pass "external" constants to the cell using the `constants`
+ keyword: argument of `RNN.__call__` (as well as `RNN.call`) method.
+ This: requires that the `cell.call` method accepts the same keyword argument
+ `constants`. Such constants can be used to condition the cell
+ transformation on additional static inputs (not changing over time),
+ a.k.a. an attention mechanism.
- # Note on passing external constants to RNNs
- You can pass "external" constants to the cell using the `constants`
- keyword: argument of `RNN.__call__` (as well as `RNN.call`) method.
- This: requires that the `cell.call` method accepts the same keyword argument
- `constants`. Such constants can be used to condition the cell
- transformation on additional static inputs (not changing over time),
- a.k.a. an attention mechanism.
-
- # Examples
-
- ```python
- # First, let's define a RNN Cell, as a layer subclass.
-
- class MinimalRNNCell(keras.layers.Layer):
-
- def __init__(self, units, **kwargs):
- self.units = units
- self.state_size = units
- super(MinimalRNNCell, self).__init__(**kwargs)
-
- def build(self, input_shape):
- self.kernel = self.add_weight(shape=(input_shape[-1], self.units),
- initializer='uniform',
- name='kernel')
- self.recurrent_kernel = self.add_weight(
- shape=(self.units, self.units),
- initializer='uniform',
- name='recurrent_kernel')
- self.built = True
-
- def call(self, inputs, states):
- prev_output = states[0]
- h = K.dot(inputs, self.kernel)
- output = h + K.dot(prev_output, self.recurrent_kernel)
- return output, [output]
-
- # Let's use this cell in a RNN layer:
-
- cell = MinimalRNNCell(32)
- x = keras.Input((None, 5))
- layer = RNN(cell)
- y = layer(x)
-
- # Here's how to use the cell to build a stacked RNN:
-
- cells = [MinimalRNNCell(32), MinimalRNNCell(64)]
- x = keras.Input((None, 5))
- layer = RNN(cells)
- y = layer(x)
- ```
+# Examples
+
+```python
+ # First, let's define a RNN Cell, as a layer subclass.
+
+ class MinimalRNNCell(keras.layers.Layer):
+
+ def __init__(self, units, **kwargs):
+ self.units = units
+ self.state_size = units
+ super(MinimalRNNCell, self).__init__(**kwargs)
+
+ def build(self, input_shape):
+ self.kernel = self.add_weight(shape=(input_shape[-1], self.units),
+ initializer='uniform',
+ name='kernel')
+ self.recurrent_kernel = self.add_weight(
+ shape=(self.units, self.units),
+ initializer='uniform',
+ name='recurrent_kernel')
+ self.built = True
+
+ def call(self, inputs, states):
+ prev_output = states[0]
+ h = K.dot(inputs, self.kernel)
+ output = h + K.dot(prev_output, self.recurrent_kernel)
+ return output, [output]
+
+ # Let's use this cell in a RNN layer:
+
+ cell = MinimalRNNCell(32)
+ x = keras.Input((None, 5))
+ layer = RNN(cell)
+ y = layer(x)
+
+ # Here's how to use the cell to build a stacked RNN:
+
+ cells = [MinimalRNNCell(32), MinimalRNNCell(64)]
+ x = keras.Input((None, 5))
+ layer = RNN(cells)
+ y = layer(x)
+```
""",
"result": """Base class for recurrent layers.
@@ -332,11 +332,11 @@ y = layer(x)
test_doc_with_arguments_as_last_block = {
"doc": """Base class for recurrent layers.
- # Arguments
- return_sequences: Boolean. Whether to return the last output
- in the output sequence, or the full sequence.
- return_state: Boolean. Whether to return the last state
- in addition to the output.
+# Arguments
+ return_sequences: Boolean. Whether to return the last output
+ in the output sequence, or the full sequence.
+ return_state: Boolean. Whether to return the last state
+ in addition to the output.
""",
"result": """Base class for recurrent layers.
@@ -351,7 +351,7 @@ __Arguments__
@pytest.mark.parametrize(
- "docs_descriptor", [test_doc1, test_doc_with_arguments_as_last_block]
+ "docs_descriptor", [test_doc_with_arguments_as_last_block, test_doc1]
)
def test_doc_lists(docs_descriptor):
docstring = autogen.process_docstring(docs_descriptor["doc"])
@@ -360,25 +360,25 @@ def test_doc_lists(docs_descriptor):
dummy_docstring = """Multiplies 2 tensors (and/or variables) and returns a *tensor*.
- When attempting to multiply a nD tensor
- with a nD tensor, it reproduces the Theano behavior.
- (e.g. `(2, 3) * (4, 3, 5) -> (2, 4, 5)`)
-
- # Examples
- ```python
- # Theano-like behavior example
- >>> x = K.random_uniform_variable(shape=(2, 3), low=0, high=1)
- >>> y = K.ones((4, 3, 5))
- >>> xy = K.dot(x, y)
- >>> K.int_shape(xy)
- (2, 4, 5)
- ```
-
- # Numpy implementation
- ```python
- def dot(x, y):
- return dot(x, y)
- ```
+When attempting to multiply a nD tensor
+with a nD tensor, it reproduces the Theano behavior.
+(e.g. `(2, 3) * (4, 3, 5) -> (2, 4, 5)`)
+
+# Examples
+```python
+ # Theano-like behavior example
+ >>> x = K.random_uniform_variable(shape=(2, 3), low=0, high=1)
+ >>> y = K.ones((4, 3, 5))
+ >>> xy = K.dot(x, y)
+ >>> K.int_shape(xy)
+ (2, 4, 5)
+```
+
+# Numpy implementation
+```python
+ def dot(x, y):
+ return dot(x, y)
+```
"""
@@ -445,5 +445,21 @@ def test_aliases_methods(element, expected):
assert expected in computed
+class A:
+ def dodo(self):
+ """Some docstring."""
+ pass
+
+
+class B(A):
+ def dodo(self):
+ pass
+
+
+def test_get_docstring_of_super_class():
+ computed = autogen.DocumentationGenerator()._render(B.dodo)
+ assert 'Some docstring' in computed
+
+
if __name__ == "__main__":
pytest.main([__file__])
|
Docstring of super class doesn't show
@gabrieldemarmiesse
I'm seeing an issue where if a docstring exists in the super class but not in the subclass method then it is not showing up at all
|
0.0
|
cd500b1351d6c71f5825bb5d97f86f3058f00456
|
[
"tests/test_autogen.py::test_doc_lists[docs_descriptor0]",
"tests/test_autogen.py::test_doc_lists[docs_descriptor1]"
] |
[
"tests/test_autogen.py::test_doc_multiple_sections_code"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-10-27 16:04:55+00:00
|
apache-2.0
| 3,415 |
|
keras-team__keras-nlp-131
|
diff --git a/keras_nlp/layers/preprocessing/mlm_mask_generator.py b/keras_nlp/layers/preprocessing/mlm_mask_generator.py
index 19c6dfc..3c2bbd6 100644
--- a/keras_nlp/layers/preprocessing/mlm_mask_generator.py
+++ b/keras_nlp/layers/preprocessing/mlm_mask_generator.py
@@ -129,7 +129,7 @@ class MLMMaskGenerator(keras.layers.Layer):
def call(self, inputs):
input_is_ragged = isinstance(inputs, tf.RaggedTensor)
- input_is_1d = tf.rank(inputs) == 1
+ input_is_1d = inputs.shape.rank == 1
if input_is_1d:
# If inputs is of rank 1, we manually add the batch axis.
inputs = inputs[tf.newaxis, :]
@@ -137,6 +137,7 @@ class MLMMaskGenerator(keras.layers.Layer):
# `tf_text.mask_language_model` requires a ragged tensor, so
# convert dense to ragged.
inputs = tf.RaggedTensor.from_tensor(inputs)
+
(tokens, mask_positions, mask_ids,) = tf_text.mask_language_model(
inputs,
item_selector=self._random_selector,
|
keras-team/keras-nlp
|
80709ae68daf20514a39cd580d2c2e1d98308d07
|
diff --git a/keras_nlp/layers/preprocessing/mlm_mask_generator_test.py b/keras_nlp/layers/preprocessing/mlm_mask_generator_test.py
index 6654798..492a271 100644
--- a/keras_nlp/layers/preprocessing/mlm_mask_generator_test.py
+++ b/keras_nlp/layers/preprocessing/mlm_mask_generator_test.py
@@ -202,7 +202,7 @@ class MLMMaskGeneratorTest(tf.test.TestCase):
mask_token_rate=1,
random_token_rate=0,
)
- inputs = [unselectable_token_ids]
+ inputs = tf.convert_to_tensor([unselectable_token_ids])
outputs = mlm_masker(inputs)
# Verify that no token is masked out.
self.assertEqual(tf.reduce_sum(outputs["mask_positions"]), 0)
@@ -232,3 +232,36 @@ class MLMMaskGeneratorTest(tf.test.TestCase):
[[0, 1, 2], [0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4]]
)
cloned_mlm_masker(inputs)
+
+ def test_graph_mode_execution(self):
+ mlm_masker = MLMMaskGenerator(
+ vocabulary_size=self.vocabulary_size,
+ mask_selection_rate=0.5,
+ mask_token_id=self.mask_token_id,
+ mask_selection_length=5,
+ )
+
+ @tf.function
+ def masker(inputs):
+ return mlm_masker(inputs)
+
+ masker(tf.constant([1, 2, 3]))
+ masker(tf.constant([[1, 2, 3], [1, 2, 3]]))
+ masker(tf.ragged.constant([[3, 5, 7, 7], [4, 6, 7, 5]]))
+
+ def test_with_tf_data(self):
+ ds = tf.data.Dataset.from_tensor_slices(
+ tf.ones((100, 10), dtype="int32")
+ )
+ mlm_masker = MLMMaskGenerator(
+ vocabulary_size=self.vocabulary_size,
+ mask_selection_rate=0.5,
+ mask_token_id=self.mask_token_id,
+ mask_selection_length=5,
+ )
+ batch_first = ds.batch(8).map(mlm_masker)
+ batch_second = ds.map(mlm_masker).batch(8)
+ self.assertEqual(
+ batch_first.take(1).get_single_element()["tokens"].shape,
+ batch_second.take(1).get_single_element()["tokens"].shape,
+ )
|
Error with tf.data and MLMMaskGenerator for dense inputs
When using the MLMMaskGenerator for to map over dense, batched inputs in a tf.data.Dataset, we get the following error...
`TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'`
This colab has a reproduction https://colab.research.google.com/gist/mattdangerw/4596df85105ff6e6731128fc79d16bf3/mlmmaskgenerator-bug.ipynb
tf.data + dense, batched inputs might be the most common use case for this layer, so this is an important one to fix.
|
0.0
|
80709ae68daf20514a39cd580d2c2e1d98308d07
|
[
"keras_nlp/layers/preprocessing/mlm_mask_generator_test.py::MLMMaskGeneratorTest::test_graph_mode_execution",
"keras_nlp/layers/preprocessing/mlm_mask_generator_test.py::MLMMaskGeneratorTest::test_with_tf_data"
] |
[
"keras_nlp/layers/preprocessing/mlm_mask_generator_test.py::MLMMaskGeneratorTest::test_apply_random_token_not_mask",
"keras_nlp/layers/preprocessing/mlm_mask_generator_test.py::MLMMaskGeneratorTest::test_config",
"keras_nlp/layers/preprocessing/mlm_mask_generator_test.py::MLMMaskGeneratorTest::test_invalid_mask_token",
"keras_nlp/layers/preprocessing/mlm_mask_generator_test.py::MLMMaskGeneratorTest::test_mask_1d_input",
"keras_nlp/layers/preprocessing/mlm_mask_generator_test.py::MLMMaskGeneratorTest::test_mask_ragged_tensor",
"keras_nlp/layers/preprocessing/mlm_mask_generator_test.py::MLMMaskGeneratorTest::test_mask_tensor",
"keras_nlp/layers/preprocessing/mlm_mask_generator_test.py::MLMMaskGeneratorTest::test_number_of_masked_position_as_expected",
"keras_nlp/layers/preprocessing/mlm_mask_generator_test.py::MLMMaskGeneratorTest::test_unselectable_tokens"
] |
{
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-04-18 22:41:12+00:00
|
apache-2.0
| 3,416 |
|
keras-team__keras-nlp-951
|
diff --git a/keras_nlp/models/gpt2/gpt2_causal_lm.py b/keras_nlp/models/gpt2/gpt2_causal_lm.py
index e674d54..09c2962 100644
--- a/keras_nlp/models/gpt2/gpt2_causal_lm.py
+++ b/keras_nlp/models/gpt2/gpt2_causal_lm.py
@@ -28,6 +28,7 @@ from keras_nlp.models.task import Task
from keras_nlp.samplers.serialization import get as get_sampler
from keras_nlp.utils.keras_utils import is_xla_compatible
from keras_nlp.utils.python_utils import classproperty
+from keras_nlp.utils.tf_utils import tensor_to_string_list
from keras_nlp.utils.tf_utils import truncate_at_token
@@ -447,4 +448,9 @@ class GPT2CausalLM(Task):
outputs.append(output)
outputs = tf.concat(outputs, axis=0)
- return tf.squeeze(outputs, 0) if input_is_scalar else outputs
+ outputs = tf.squeeze(outputs, 0) if input_is_scalar else outputs
+ # Convert outputs to a friendly pythonic type. For numerical outputs
+ # that is numpy, for string outputs that is `list` and `str`.
+ if outputs.dtype == tf.string:
+ return tensor_to_string_list(outputs)
+ return outputs.numpy()
diff --git a/keras_nlp/samplers/beam_sampler.py b/keras_nlp/samplers/beam_sampler.py
index cbb6b73..2830640 100644
--- a/keras_nlp/samplers/beam_sampler.py
+++ b/keras_nlp/samplers/beam_sampler.py
@@ -97,8 +97,9 @@ class BeamSampler(Sampler):
self,
num_beams=5,
return_all_beams=False,
+ **kwargs,
):
- super().__init__()
+ super().__init__(**kwargs)
self.num_beams = num_beams
self.return_all_beams = return_all_beams
@@ -156,7 +157,7 @@ class BeamSampler(Sampler):
# Compute the softmax distribution for the next token.
logits, _, cache = next(prompt, cache, index)
vocab_size = tf.shape(logits)[-1]
- probs = keras.activations.softmax(logits)
+ probs = keras.activations.softmax(logits / self.temperature)
# Compute the running log-likelihood of each new candidate.
next_log_probs = tf.math.log(probs) + log_probs[..., tf.newaxis]
diff --git a/keras_nlp/samplers/greedy_sampler.py b/keras_nlp/samplers/greedy_sampler.py
index 9d4cf73..6064270 100644
--- a/keras_nlp/samplers/greedy_sampler.py
+++ b/keras_nlp/samplers/greedy_sampler.py
@@ -55,8 +55,11 @@ class GreedySampler(Sampler):
```
"""
- def __init__(self):
- super().__init__()
+ def __init__(
+ self,
+ **kwargs,
+ ):
+ super().__init__(**kwargs)
def get_next_token(self, probabilities):
return tf.argmax(probabilities, axis=-1)
diff --git a/keras_nlp/samplers/random_sampler.py b/keras_nlp/samplers/random_sampler.py
index 9d2c731..a0a945c 100644
--- a/keras_nlp/samplers/random_sampler.py
+++ b/keras_nlp/samplers/random_sampler.py
@@ -62,8 +62,9 @@ class RandomSampler(Sampler):
def __init__(
self,
seed=None,
+ **kwargs,
):
- super().__init__()
+ super().__init__(**kwargs)
self.seed = seed
def get_next_token(self, probabilities):
diff --git a/keras_nlp/samplers/sampler.py b/keras_nlp/samplers/sampler.py
index 7ccb35b..e1c5ae5 100644
--- a/keras_nlp/samplers/sampler.py
+++ b/keras_nlp/samplers/sampler.py
@@ -48,6 +48,11 @@ call_args_docstring = """
class Sampler:
"""Base sampler class.
+ Args:
+ temperature: float. optional. defaults to '1.0'. Used to control the
+ randomness of the sampling. The higher the temperature, the
+ more diverse the samples.
+
Call Args:
{{call_args}}
@@ -84,6 +89,12 @@ class Sampler:
```
"""
+ def __init__(
+ self,
+ temperature=1.0,
+ ):
+ self.temperature = temperature
+
def __call__(
self,
next,
@@ -115,7 +126,7 @@ class Sampler:
def body(prompt, cache, index):
# Compute the softmax distribution for the next token.
logits, _, cache = next(prompt, cache, index)
- probabilities = keras.activations.softmax(logits)
+ probabilities = keras.activations.softmax(logits / self.temperature)
# Compute the next token.
next_token = self.get_next_token(probabilities)
# Don't overwrite anywhere mask is True.
@@ -140,11 +151,9 @@ class Sampler:
def get_next_token(self, probabilities):
"""Get the next token.
-
Args:
probabilities: a Tensor, the probability distribution for next
token over all vocab tokens.
-
Get the next token based on given probability distribution over tokens.
Subclasses must implement this method.
"""
@@ -155,4 +164,4 @@ class Sampler:
return cls(**config)
def get_config(self):
- return {}
+ return {"temperature": self.temperature}
diff --git a/keras_nlp/samplers/top_k_sampler.py b/keras_nlp/samplers/top_k_sampler.py
index 68f369a..a3369c4 100644
--- a/keras_nlp/samplers/top_k_sampler.py
+++ b/keras_nlp/samplers/top_k_sampler.py
@@ -64,8 +64,9 @@ class TopKSampler(Sampler):
self,
k=5,
seed=None,
+ **kwargs,
):
- super().__init__()
+ super().__init__(**kwargs)
self.k = k
self.seed = seed
diff --git a/keras_nlp/samplers/top_p_sampler.py b/keras_nlp/samplers/top_p_sampler.py
index ec5c4be..2ef90d3 100644
--- a/keras_nlp/samplers/top_p_sampler.py
+++ b/keras_nlp/samplers/top_p_sampler.py
@@ -73,8 +73,9 @@ class TopPSampler(Sampler):
p=0.1,
k=None,
seed=None,
+ **kwargs,
):
- super().__init__()
+ super().__init__(**kwargs)
self.p = p
self.k = k
self.seed = seed
|
keras-team/keras-nlp
|
08351c09a44f63c227528d462a9b8f0583b2f5d3
|
diff --git a/keras_nlp/models/gpt2/gpt2_causal_lm_test.py b/keras_nlp/models/gpt2/gpt2_causal_lm_test.py
index 9162977..5f210a0 100644
--- a/keras_nlp/models/gpt2/gpt2_causal_lm_test.py
+++ b/keras_nlp/models/gpt2/gpt2_causal_lm_test.py
@@ -96,15 +96,11 @@ class GPT2CausalLMTest(tf.test.TestCase, parameterized.TestCase):
# String input.
prompt = " airplane"
output = self.causal_lm.generate(" airplane")
- self.assertTrue(prompt in output.numpy().decode("utf-8"))
+ self.assertTrue(prompt in output)
# String tensor input.
- self.assertDTypeEqual(
- self.causal_lm.generate(self.raw_batch), tf.string
- )
+ self.assertIsInstance(self.causal_lm.generate(self.raw_batch)[0], str)
# String dataset input.
- self.assertDTypeEqual(
- self.causal_lm.generate(self.raw_dataset), tf.string
- )
+ self.assertIsInstance(self.causal_lm.generate(self.raw_dataset)[0], str)
# Int tensor input.
self.causal_lm.preprocessor = None
self.assertDTypeEqual(
diff --git a/keras_nlp/samplers/beam_sampler_test.py b/keras_nlp/samplers/beam_sampler_test.py
index ff0d671..979a300 100644
--- a/keras_nlp/samplers/beam_sampler_test.py
+++ b/keras_nlp/samplers/beam_sampler_test.py
@@ -38,7 +38,7 @@ class BeamSamplerTest(tf.test.TestCase, parameterized.TestCase):
return logits, hidden_states, cache
self.next = next
- self.sampler = BeamSampler(num_beams=5)
+ self.sampler = BeamSampler(num_beams=5, temperature=1.0)
self.sampler_all_beams = BeamSampler(num_beams=5, return_all_beams=True)
def join_as_string(self, x):
diff --git a/keras_nlp/samplers/greedy_sampler_test.py b/keras_nlp/samplers/greedy_sampler_test.py
index f45902f..e612277 100644
--- a/keras_nlp/samplers/greedy_sampler_test.py
+++ b/keras_nlp/samplers/greedy_sampler_test.py
@@ -37,7 +37,7 @@ class GreedySamplerTest(tf.test.TestCase, parameterized.TestCase):
return logits, hidden_states, cache
self.next = next
- self.sampler = GreedySampler()
+ self.sampler = GreedySampler(temperature=1.0)
def join_as_string(self, x):
return ["".join([self.int_lookup[i] for i in s]) for s in x.numpy()]
diff --git a/keras_nlp/samplers/random_sampler_test.py b/keras_nlp/samplers/random_sampler_test.py
index 2c08b09..7ae739f 100644
--- a/keras_nlp/samplers/random_sampler_test.py
+++ b/keras_nlp/samplers/random_sampler_test.py
@@ -38,7 +38,7 @@ class RandomSamplerTest(tf.test.TestCase, parameterized.TestCase):
return logits, hidden_states, cache
self.next = next
- self.sampler = RandomSampler()
+ self.sampler = RandomSampler(temperature=1.0)
def join_as_string(self, x):
return ["".join([self.int_lookup[i] for i in s]) for s in x.numpy()]
@@ -71,6 +71,22 @@ class RandomSamplerTest(tf.test.TestCase, parameterized.TestCase):
)
self.assertEqual(self.join_as_string(output), ["sequentially"])
+ def test_temperature(self):
+ def next(prompt, cache, index):
+ # Dummy hidden states.
+ hidden_states = tf.ones([self.batch_size, 5])
+ logits = tf.range(self.vocab_size, 0, -1, dtype=tf.float32)
+ logits = tf.reshape(logits[tf.newaxis, :], (self.batch_size, -1))
+ return tf.constant(logits), hidden_states, cache
+
+ prompt = tf.fill((self.batch_size, self.length), self.char_lookup["z"])
+
+ output = RandomSampler(temperature=1e-5)(
+ next=next,
+ prompt=prompt,
+ )
+ self.assertAllEqual(output, tf.zeros_like(output))
+
def test_early_stopping(self):
cache_chars = list("sequentially")
cache = tf.constant([[self.char_lookup[c] for c in cache_chars]])
diff --git a/keras_nlp/samplers/top_k_sampler_test.py b/keras_nlp/samplers/top_k_sampler_test.py
index 10ce77b..8f4fe8b 100644
--- a/keras_nlp/samplers/top_k_sampler_test.py
+++ b/keras_nlp/samplers/top_k_sampler_test.py
@@ -37,7 +37,7 @@ class TopKSamplerTest(tf.test.TestCase, parameterized.TestCase):
return logits, hidden_states, cache
self.next = next
- self.sampler = TopKSampler(k=5)
+ self.sampler = TopKSampler(k=5, temperature=1.0)
def join_as_string(self, x):
return ["".join([self.int_lookup[i] for i in s]) for s in x.numpy()]
diff --git a/keras_nlp/samplers/top_p_sampler_test.py b/keras_nlp/samplers/top_p_sampler_test.py
index f06563a..728d9a6 100644
--- a/keras_nlp/samplers/top_p_sampler_test.py
+++ b/keras_nlp/samplers/top_p_sampler_test.py
@@ -122,6 +122,22 @@ class TopPSamplerTest(tf.test.TestCase, parameterized.TestCase):
output_ids = set(output[0].numpy())
self.assertContainsSubset(output_ids, range(3))
+ def test_temperature(self):
+ def next(prompt, cache, index):
+ # Dummy hidden states.
+ hidden_states = tf.ones([self.batch_size, 5])
+ logits = tf.range(self.vocab_size, 0, -1, dtype=tf.float32)
+ logits = tf.reshape(logits[tf.newaxis, :], (self.batch_size, -1))
+ return tf.constant(logits), hidden_states, cache
+
+ prompt = tf.fill((self.batch_size, self.length), self.char_lookup["z"])
+
+ output = TopPSampler(p=0.5, temperature=1e-9)(
+ next=next,
+ prompt=prompt,
+ )
+ self.assertAllEqual(output, tf.zeros_like(output))
+
@parameterized.named_parameters(
("jit_compile_false", False), ("jit_compile_true", True)
)
|
Add a temperature argument to the base sampler class
We would like our samplers to support a [temperature](https://medium.com/mlearning-ai/softmax-temperature-5492e4007f71) argument that allows tightening or loosening the probability distribution.
We can add this pretty simply in the base class by dividing our logits by a temperature parameter [here](https://github.com/keras-team/keras-nlp/blob/master/keras_nlp/samplers/sampler.py#L111-L112) before applying the softmax.
Checklist:
- [ ] Sampler takes in a `temperature` argument in `__init__`, adds it to `self`, and populates it in `get_config()`.
- [ ] In `__call__`, use `self.temperature` to scale the logits.
- [ ] Beam sampler will need to do the same (as it overrides call).
- [ ] Add unit tests. E.g. [this test](https://github.com/keras-team/keras-nlp/blob/794c4b18084a1fdf04cea0a2cae4889dbadd8516/keras_nlp/samplers/top_k_sampler_test.py#L82-L95 ) could be adapted to run with a very low temperature, and assert that all output ids are zero.
|
0.0
|
08351c09a44f63c227528d462a9b8f0583b2f5d3
|
[
"keras_nlp/samplers/beam_sampler_test.py::BeamSamplerTest::test_compilation_jit_compile_false",
"keras_nlp/samplers/beam_sampler_test.py::BeamSamplerTest::test_compilation_jit_compile_true",
"keras_nlp/samplers/beam_sampler_test.py::BeamSamplerTest::test_early_stopping",
"keras_nlp/samplers/beam_sampler_test.py::BeamSamplerTest::test_return_all_beams",
"keras_nlp/samplers/beam_sampler_test.py::BeamSamplerTest::test_stateful_call",
"keras_nlp/samplers/beam_sampler_test.py::BeamSamplerTest::test_stateless_call",
"keras_nlp/samplers/greedy_sampler_test.py::GreedySamplerTest::test_compilation_jit_compile_false",
"keras_nlp/samplers/greedy_sampler_test.py::GreedySamplerTest::test_compilation_jit_compile_true",
"keras_nlp/samplers/greedy_sampler_test.py::GreedySamplerTest::test_early_stopping",
"keras_nlp/samplers/greedy_sampler_test.py::GreedySamplerTest::test_is_greedy",
"keras_nlp/samplers/greedy_sampler_test.py::GreedySamplerTest::test_stateful_call",
"keras_nlp/samplers/greedy_sampler_test.py::GreedySamplerTest::test_stateless_call",
"keras_nlp/samplers/random_sampler_test.py::RandomSamplerTest::test_compilation_jit_compile_false",
"keras_nlp/samplers/random_sampler_test.py::RandomSamplerTest::test_compilation_jit_compile_true",
"keras_nlp/samplers/random_sampler_test.py::RandomSamplerTest::test_early_stopping",
"keras_nlp/samplers/random_sampler_test.py::RandomSamplerTest::test_stateful_call",
"keras_nlp/samplers/random_sampler_test.py::RandomSamplerTest::test_stateless_call",
"keras_nlp/samplers/random_sampler_test.py::RandomSamplerTest::test_temperature",
"keras_nlp/samplers/top_k_sampler_test.py::TopKSamplerTest::test_compilation_jit_compile_false",
"keras_nlp/samplers/top_k_sampler_test.py::TopKSamplerTest::test_compilation_jit_compile_true",
"keras_nlp/samplers/top_k_sampler_test.py::TopKSamplerTest::test_early_stopping",
"keras_nlp/samplers/top_k_sampler_test.py::TopKSamplerTest::test_outputs_in_top_k",
"keras_nlp/samplers/top_k_sampler_test.py::TopKSamplerTest::test_stateful_call",
"keras_nlp/samplers/top_k_sampler_test.py::TopKSamplerTest::test_stateless_call",
"keras_nlp/samplers/top_p_sampler_test.py::TopPSamplerTest::test_temperature"
] |
[
"keras_nlp/samplers/top_p_sampler_test.py::TopPSamplerTest::test_compilation_jit_compile_false",
"keras_nlp/samplers/top_p_sampler_test.py::TopPSamplerTest::test_compilation_jit_compile_true",
"keras_nlp/samplers/top_p_sampler_test.py::TopPSamplerTest::test_early_stopping",
"keras_nlp/samplers/top_p_sampler_test.py::TopPSamplerTest::test_only_sample_from_top_k_tokens",
"keras_nlp/samplers/top_p_sampler_test.py::TopPSamplerTest::test_outputs_in_top_p",
"keras_nlp/samplers/top_p_sampler_test.py::TopPSamplerTest::test_stateful_call",
"keras_nlp/samplers/top_p_sampler_test.py::TopPSamplerTest::test_stateless_call"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-03-31 21:13:46+00:00
|
apache-2.0
| 3,417 |
|
kerrickstaley__genanki-89
|
diff --git a/genanki/note.py b/genanki/note.py
index 0ffcd98..42609be 100644
--- a/genanki/note.py
+++ b/genanki/note.py
@@ -47,7 +47,7 @@ class _TagList(list):
class Note:
- _INVALID_HTML_TAG_RE = re.compile(r'<(?!/?[a-z0-9]+(?: .*|/?)>)(?:.|\n)*?>')
+ _INVALID_HTML_TAG_RE = re.compile(r'<(?!/?[a-zA-Z0-9]+(?: .*|/?)>)(?:.|\n)*?>')
def __init__(self, model=None, fields=None, sort_field=None, tags=None, guid=None, due=0):
self.model = model
|
kerrickstaley/genanki
|
6ceffc1b707ad67efa2adf4534d143a142487df8
|
diff --git a/tests/test_note.py b/tests/test_note.py
index ede19f3..f654e30 100644
--- a/tests/test_note.py
+++ b/tests/test_note.py
@@ -172,6 +172,9 @@ class TestFindInvalidHtmlTagsInField:
def test_ok_attrs(self):
assert genanki.Note._find_invalid_html_tags_in_field('<h1 style="color: red">STOP</h1>') == []
+
+ def test_ok_uppercase(self):
+ assert genanki.Note._find_invalid_html_tags_in_field('<TD></Td>') == []
def test_ng_empty(self):
assert genanki.Note._find_invalid_html_tags_in_field(' hello <> goodbye') == ['<>']
|
HTML tags are not case sensitive
`_INVALID_HTML_TAG_RE` is case sensitive, so I'm getting false positive warnings on tags like `<TABLE>, `<TD>`, etc.
|
0.0
|
6ceffc1b707ad67efa2adf4534d143a142487df8
|
[
"tests/test_note.py::TestFindInvalidHtmlTagsInField::test_ok_uppercase"
] |
[
"tests/test_note.py::TestTags::test_init",
"tests/test_note.py::TestTags::test_assign",
"tests/test_note.py::TestTags::test_assign_element",
"tests/test_note.py::TestTags::test_assign_slice",
"tests/test_note.py::TestTags::test_append",
"tests/test_note.py::TestTags::test_extend",
"tests/test_note.py::TestTags::test_insert",
"tests/test_note.py::test_num_fields_equals_model_ok",
"tests/test_note.py::test_num_fields_less_than_model_raises",
"tests/test_note.py::test_num_fields_more_than_model_raises",
"tests/test_note.py::TestFindInvalidHtmlTagsInField::test_ok",
"tests/test_note.py::TestFindInvalidHtmlTagsInField::test_ok_with_space",
"tests/test_note.py::TestFindInvalidHtmlTagsInField::test_ok_multiple",
"tests/test_note.py::TestFindInvalidHtmlTagsInField::test_ok_br",
"tests/test_note.py::TestFindInvalidHtmlTagsInField::test_ok_br2",
"tests/test_note.py::TestFindInvalidHtmlTagsInField::test_ok_br3",
"tests/test_note.py::TestFindInvalidHtmlTagsInField::test_ok_attrs",
"tests/test_note.py::TestFindInvalidHtmlTagsInField::test_ng_empty",
"tests/test_note.py::TestFindInvalidHtmlTagsInField::test_ng_empty_space",
"tests/test_note.py::TestFindInvalidHtmlTagsInField::test_ng_invalid_characters",
"tests/test_note.py::TestFindInvalidHtmlTagsInField::test_ng_invalid_characters_end",
"tests/test_note.py::TestFindInvalidHtmlTagsInField::test_ng_issue_28",
"tests/test_note.py::test_warns_on_invalid_html_tags"
] |
{
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-08-05 13:53:30+00:00
|
mit
| 3,418 |
|
kevin1024__vcrpy-278
|
diff --git a/vcr/matchers.py b/vcr/matchers.py
index b54ed2f..8fe334e 100644
--- a/vcr/matchers.py
+++ b/vcr/matchers.py
@@ -49,7 +49,8 @@ def _transform_json(body):
# Request body is always a byte string, but json.loads() wants a text
# string. RFC 7159 says the default encoding is UTF-8 (although UTF-16
# and UTF-32 are also allowed: hmmmmm).
- return json.loads(body.decode('utf-8'))
+ if body:
+ return json.loads(body.decode('utf-8'))
_xml_header_checker = _header_checker('text/xml')
diff --git a/vcr/serializers/compat.py b/vcr/serializers/compat.py
index 0fcc583..8364997 100644
--- a/vcr/serializers/compat.py
+++ b/vcr/serializers/compat.py
@@ -24,7 +24,7 @@ def convert_body_to_bytes(resp):
http://pyyaml.org/wiki/PyYAMLDocumentation#Python3support
"""
try:
- if not isinstance(resp['body']['string'], six.binary_type):
+ if resp['body']['string'] is not None and not isinstance(resp['body']['string'], six.binary_type):
resp['body']['string'] = resp['body']['string'].encode('utf-8')
except (KeyError, TypeError, UnicodeEncodeError):
# The thing we were converting either wasn't a dictionary or didn't
diff --git a/vcr/stubs/aiohttp_stubs/__init__.py b/vcr/stubs/aiohttp_stubs/__init__.py
index a19be69..5730d3b 100644
--- a/vcr/stubs/aiohttp_stubs/__init__.py
+++ b/vcr/stubs/aiohttp_stubs/__init__.py
@@ -4,8 +4,9 @@ from __future__ import absolute_import
import asyncio
import functools
import json
+import urllib
-from aiohttp import ClientResponse
+from aiohttp import ClientResponse, helpers
from vcr.request import Request
@@ -26,15 +27,38 @@ class MockClientResponse(ClientResponse):
def vcr_request(cassette, real_request):
-
@functools.wraps(real_request)
@asyncio.coroutine
def new_request(self, method, url, **kwargs):
headers = kwargs.get('headers')
headers = self._prepare_headers(headers)
data = kwargs.get('data')
-
- vcr_request = Request(method, url, data, headers)
+ params = kwargs.get('params')
+
+ # INFO: Query join logic from
+ # https://github.com/KeepSafe/aiohttp/blob/b3eeedbc2f515ec2aa6e87ba129524c17b6fe4e3/aiohttp/client_reqrep.py#L167-L188
+ scheme, netloc, path, query, fragment = urllib.parse.urlsplit(url)
+ if not path:
+ path = '/'
+
+ # NOTICE: Not sure this is applicable here:
+ # if isinstance(params, collections.Mapping):
+ # params = list(params.items())
+
+ if params:
+ if not isinstance(params, str):
+ params = urllib.parse.urlencode(params)
+ if query:
+ query = '%s&%s' % (query, params)
+ else:
+ query = params
+
+ request_path = urllib.parse.urlunsplit(('', '', helpers.requote_uri(path),
+ query, fragment))
+ request_url = urllib.parse.urlunsplit(
+ (scheme, netloc, request_path, '', ''))
+
+ vcr_request = Request(method, request_url, data, headers)
if cassette.can_play_response_for(vcr_request):
vcr_response = cassette.play_response(vcr_request)
|
kevin1024/vcrpy
|
ecbc192fc445d3bd91aba43d1a34dd6d9ccb1976
|
diff --git a/tests/integration/test_aiohttp.py b/tests/integration/test_aiohttp.py
index 1aa9c05..82957ff 100644
--- a/tests/integration/test_aiohttp.py
+++ b/tests/integration/test_aiohttp.py
@@ -85,3 +85,33 @@ def test_post(tmpdir, scheme):
_, cassette_response_json = post(url, data=data)
assert cassette_response_json == response_json
assert cassette.play_count == 1
+
+
+def test_params(tmpdir, scheme):
+ url = scheme + '://httpbin.org/get'
+ params = {'a': 1, 'b': False, 'c': 'c'}
+ with vcr.use_cassette(str(tmpdir.join('get.yaml'))) as cassette:
+ _, response_json = get(url, as_text=False, params=params)
+
+ with vcr.use_cassette(str(tmpdir.join('get.yaml'))) as cassette:
+ _, cassette_response_json = get(url, as_text=False, params=params)
+ assert cassette_response_json == response_json
+ assert cassette.play_count == 1
+
+
+def test_params_same_url_distinct_params(tmpdir, scheme):
+ url = scheme + '://httpbin.org/get'
+ params = {'a': 1, 'b': False, 'c': 'c'}
+ with vcr.use_cassette(str(tmpdir.join('get.yaml'))) as cassette:
+ _, response_json = get(url, as_text=False, params=params)
+
+ with vcr.use_cassette(str(tmpdir.join('get.yaml'))) as cassette:
+ _, cassette_response_json = get(url, as_text=False, params=params)
+ assert cassette_response_json == response_json
+ assert cassette.play_count == 1
+
+ other_params = {'other': 'params'}
+ with vcr.use_cassette(str(tmpdir.join('get.yaml'))) as cassette:
+ response, cassette_response_text = get(url, as_text=True, params=other_params)
+ assert 'No match for the request' in cassette_response_text
+ assert response.status == 599
diff --git a/tests/integration/test_requests.py b/tests/integration/test_requests.py
index 84a992b..804ab2e 100644
--- a/tests/integration/test_requests.py
+++ b/tests/integration/test_requests.py
@@ -38,6 +38,18 @@ def test_body(tmpdir, httpbin_both):
assert content == requests.get(url).content
+def test_get_empty_content_type_json(tmpdir, httpbin_both):
+ '''Ensure GET with application/json content-type and empty request body doesn't crash'''
+ url = httpbin_both + '/status/200'
+ headers = {'Content-Type': 'application/json'}
+
+ with vcr.use_cassette(str(tmpdir.join('get_empty_json.yaml')), match_on=('body',)):
+ status = requests.get(url, headers=headers).status_code
+
+ with vcr.use_cassette(str(tmpdir.join('get_empty_json.yaml')), match_on=('body',)):
+ assert status == requests.get(url, headers=headers).status_code
+
+
def test_effective_url(tmpdir, httpbin_both):
'''Ensure that the effective_url is captured'''
url = httpbin_both.url + '/redirect-to?url=/html'
diff --git a/tests/unit/test_serialize.py b/tests/unit/test_serialize.py
index cf3f0a8..6555cca 100644
--- a/tests/unit/test_serialize.py
+++ b/tests/unit/test_serialize.py
@@ -4,7 +4,7 @@ import pytest
from vcr.compat import mock
from vcr.request import Request
from vcr.serialize import deserialize, serialize
-from vcr.serializers import yamlserializer, jsonserializer
+from vcr.serializers import yamlserializer, jsonserializer, compat
def test_deserialize_old_yaml_cassette():
@@ -131,3 +131,9 @@ def test_serialize_binary_request():
)
except (UnicodeDecodeError, TypeError) as exc:
assert msg in str(exc)
+
+
+def test_deserialize_no_body_string():
+ data = {'body': {'string': None}}
+ output = compat.convert_to_bytes(data)
+ assert data == output
|
AttributeError: 'NoneType' object has no attribute 'decode' when 'body' in match_on, fixed with 'raw_body'
When using vcr with the following configuration with 'body', there are errors with loading the JSON response -- it could be due to a blank response or blank payload. When I use 'raw_body' it works perfectly. Here's the stack trace (relevant sections):
```bash
File "/home/vagrant/venv/local/lib/python2.7/site-packages/requests/sessions.py", line 473, in get
return self.request('GET', url, **kwargs)
File "/home/vagrant/venv/local/lib/python2.7/site-packages/requests/sessions.py", line 461, in request
resp = self.send(prep, **send_kwargs)
File "/home/vagrant/venv/local/lib/python2.7/site-packages/requests/sessions.py", line 573, in send
r = adapter.send(request, **kwargs)
File "/home/vagrant/venv/local/lib/python2.7/site-packages/requests/adapters.py", line 370, in send
timeout=timeout
File "/home/vagrant/venv/local/lib/python2.7/site-packages/requests/packages/urllib3/connectionpool.py", line 518, in urlopen
body=body, headers=headers)
File "/home/vagrant/venv/local/lib/python2.7/site-packages/requests/packages/urllib3/connectionpool.py", line 353, in _make_request
httplib_response = conn.getresponse(buffering=True)
File "/home/vagrant/venv/local/lib/python2.7/site-packages/vcr/stubs/__init__.py", line 219, in getresponse
if self.cassette.can_play_response_for(self._vcr_request):
File "/home/vagrant/venv/local/lib/python2.7/site-packages/vcr/cassette.py", line 232, in can_play_response_for
return request and request in self and \
File "/home/vagrant/venv/local/lib/python2.7/site-packages/vcr/cassette.py", line 303, in __contains__
for index, response in self._responses(request):
File "/home/vagrant/venv/local/lib/python2.7/site-packages/vcr/cassette.py", line 227, in _responses
if requests_match(request, stored_request, self._match_on):
File "/home/vagrant/venv/local/lib/python2.7/site-packages/vcr/matchers.py", line 97, in requests_match
matches = [(m(r1, r2), m) for m in matchers]
File "/home/vagrant/venv/local/lib/python2.7/site-packages/vcr/matchers.py", line 80, in body
return transformer(read_body(r1)) == transformer(read_body(r2))
File "/home/vagrant/venv/local/lib/python2.7/site-packages/vcr/matchers.py", line 52, in _transform_json
return json.loads(body.decode('utf-8'))
AttributeError: 'NoneType' object has no attribute 'decode'
```
|
0.0
|
ecbc192fc445d3bd91aba43d1a34dd6d9ccb1976
|
[
"tests/unit/test_serialize.py::test_deserialize_no_body_string"
] |
[
"tests/unit/test_serialize.py::test_deserialize_old_yaml_cassette",
"tests/unit/test_serialize.py::test_deserialize_old_json_cassette",
"tests/unit/test_serialize.py::test_deserialize_new_yaml_cassette",
"tests/unit/test_serialize.py::test_deserialize_new_json_cassette",
"tests/unit/test_serialize.py::test_deserialize_py2py3_yaml_cassette[x=5&y=2-x=5&y=2]",
"tests/unit/test_serialize.py::test_deserialize_py2py3_yaml_cassette[!!binary",
"tests/unit/test_serialize.py::test_deserialize_py2py3_yaml_cassette[!!python/str",
"tests/unit/test_serialize.py::test_serialize_constructs_UnicodeDecodeError",
"tests/unit/test_serialize.py::test_serialize_empty_request",
"tests/unit/test_serialize.py::test_serialize_json_request",
"tests/unit/test_serialize.py::test_serialize_binary_request"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2016-10-02 20:25:36+00:00
|
mit
| 3,419 |
|
kevin1024__vcrpy-415
|
diff --git a/vcr/request.py b/vcr/request.py
index 09c83f4..b4b3f71 100644
--- a/vcr/request.py
+++ b/vcr/request.py
@@ -58,7 +58,10 @@ class Request(object):
parse_uri = urlparse(self.uri)
port = parse_uri.port
if port is None:
- port = {'https': 443, 'http': 80}[parse_uri.scheme]
+ try:
+ port = {'https': 443, 'http': 80}[parse_uri.scheme]
+ except KeyError:
+ pass
return port
@property
|
kevin1024/vcrpy
|
9039eab91606ea39ac664450c64e2694b36caa37
|
diff --git a/tests/unit/test_request.py b/tests/unit/test_request.py
index dfd68d7..00793f8 100644
--- a/tests/unit/test_request.py
+++ b/tests/unit/test_request.py
@@ -3,9 +3,13 @@ import pytest
from vcr.request import Request, HeadersDict
-def test_str():
- req = Request('GET', 'http://www.google.com/', '', {})
- str(req) == '<Request (GET) http://www.google.com/>'
[email protected]("method, uri, expected_str", [
+ ('GET', 'http://www.google.com/', '<Request (GET) http://www.google.com/>'),
+ ('OPTIONS', '*', '<Request (OPTIONS) *>'),
+ ('CONNECT', 'host.some.where:1234', '<Request (CONNECT) host.some.where:1234>')
+])
+def test_str(method, uri, expected_str):
+ assert str(Request(method, uri, '', {})) == expected_str
def test_headers():
@@ -29,18 +33,21 @@ def test_add_header_deprecated():
('https://go.com/', 443),
('https://go.com:443/', 443),
('https://go.com:3000/', 3000),
+ ('*', None)
])
def test_port(uri, expected_port):
req = Request('GET', uri, '', {})
assert req.port == expected_port
-def test_uri():
- req = Request('GET', 'http://go.com/', '', {})
- assert req.uri == 'http://go.com/'
-
- req = Request('GET', 'http://go.com:80/', '', {})
- assert req.uri == 'http://go.com:80/'
[email protected]("method, uri", [
+ ('GET', 'http://go.com/'),
+ ('GET', 'http://go.com:80/'),
+ ('CONNECT', 'localhost:1234'),
+ ('OPTIONS', '*')
+])
+def test_uri(method, uri):
+ assert Request(method, uri, '', {}).uri == uri
def test_HeadersDict():
|
Proxy tunnel connect was broken by #389
In #389 there was a change in the stubs __init__.py:
https://github.com/kevin1024/vcrpy/pull/389/files#diff-06abc5fc1e45f59da669d9294b92a168R139
This change has broken tunnel CONNECT processing.
The client code that calls this (from pyvmomi) is:
```
/home/jking/pyvmomi/pyVmomi/SoapAdapter.py(1087)__call__()
1086 tunnel = http_client.HTTPConnection(path, **tmpKwargs)
-> 1087 tunnel.request('CONNECT', self.proxyPath)
1088 resp = tunnel.getresponse()
ipdb> p path
'vcsa:80'
ipdb> p self.proxyPath
'sdkTunnel:8089'
```
It is acceptable to issue a CONNECT request with a string of "host:port":
https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/CONNECT
Now in the cassette file you get something that looks like this:
```
jking@dvm:~/pyvmomi$ cat tests/fixtures/ssl_tunnel.yaml
interactions:
- request:
body: null
headers: {}
method: CONNECT
uri: sdkTunnel:8089
response:
...
```
When the cassette player tries to match the requests in the cassette to what's happening on replay, it fails:
```
Traceback (most recent call last):
File "/home/jking/pyvmomi/.eggs/vcrpy-2.0.1-py3.6.egg/vcr/cassette.py", line 109, in __call__
function, args, kwargs
File "/home/jking/pyvmomi/.eggs/vcrpy-2.0.1-py3.6.egg/vcr/cassette.py", line 124, in _execute_function
return self._handle_function(fn=handle_function)
File "/home/jking/pyvmomi/.eggs/vcrpy-2.0.1-py3.6.egg/vcr/cassette.py", line 148, in _handle_function
return fn(cassette)
File "/home/jking/pyvmomi/.eggs/vcrpy-2.0.1-py3.6.egg/vcr/cassette.py", line 117, in handle_function
return function(*args, **kwargs)
File "/home/jking/pyvmomi/tests/test_connect.py", line 99, in test_ssl_tunnel_http_failure
self.assertRaises(http_client.HTTPException, should_fail)
File "/usr/lib/python3.6/unittest/case.py", line 733, in assertRaises
return context.handle('assertRaises', args, kwargs)
File "/usr/lib/python3.6/unittest/case.py", line 178, in handle
callable_obj(*args, **kwargs)
File "/home/jking/pyvmomi/tests/test_connect.py", line 98, in should_fail
connect.SoapStubAdapter('sdkTunnel', 8089, httpProxyHost='localhost', httpProxyPort=8899).GetConnection()
File "/home/jking/pyvmomi/pyVmomi/SoapAdapter.py", line 1405, in GetConnection
result = self.scheme(self.host, **self.schemeArgs)
File "/home/jking/pyvmomi/pyVmomi/SoapAdapter.py", line 1088, in __call__
resp = tunnel.getresponse()
File "/home/jking/pyvmomi/.eggs/vcrpy-2.0.1-py3.6.egg/vcr/stubs/__init__.py", line 220, in getresponse
if self.cassette.can_play_response_for(self._vcr_request):
File "/home/jking/pyvmomi/.eggs/vcrpy-2.0.1-py3.6.egg/vcr/cassette.py", line 255, in can_play_response_for
return request and request in self and \
File "/home/jking/pyvmomi/.eggs/vcrpy-2.0.1-py3.6.egg/vcr/cassette.py", line 326, in __contains__
for index, response in self._responses(request):
File "/home/jking/pyvmomi/.eggs/vcrpy-2.0.1-py3.6.egg/vcr/cassette.py", line 250, in _responses
if requests_match(request, stored_request, self._match_on):
File "/home/jking/pyvmomi/.eggs/vcrpy-2.0.1-py3.6.egg/vcr/matchers.py", line 99, in requests_match
matches = [(m(r1, r2), m) for m in matchers]
File "/home/jking/pyvmomi/.eggs/vcrpy-2.0.1-py3.6.egg/vcr/matchers.py", line 99, in <listcomp>
matches = [(m(r1, r2), m) for m in matchers]
File "/home/jking/pyvmomi/.eggs/vcrpy-2.0.1-py3.6.egg/vcr/matchers.py", line 27, in port
return r1.port == r2.port
File "/home/jking/pyvmomi/.eggs/vcrpy-2.0.1-py3.6.egg/vcr/request.py", line 61, in port
port = {'https': 443, 'http': 80}[parse_uri.scheme]
KeyError: ''
```
The uri that goes into the cassette is no longer a valid URI. I would assume that the URI would have to be in this case:
```
...
method: CONNECT
uri: http://vcsa:80/sdkTunnel:8089
```
Here's what it was in vcrpy 1.13 and earlier:
```
uri: http://vcsasdkTunnel:8089
```
So I think the fix in #389 was wrong; instead of returning the URL if the path does not start with slash, it should insert the slash when the method is CONNECT.
Thoughts?
|
0.0
|
9039eab91606ea39ac664450c64e2694b36caa37
|
[
"tests/unit/test_request.py::test_port[*-None]"
] |
[
"tests/unit/test_request.py::test_str[GET-http://www.google.com/-<Request",
"tests/unit/test_request.py::test_str[OPTIONS-*-<Request",
"tests/unit/test_request.py::test_str[CONNECT-host.some.where:1234-<Request",
"tests/unit/test_request.py::test_headers",
"tests/unit/test_request.py::test_add_header_deprecated",
"tests/unit/test_request.py::test_port[http://go.com/-80]",
"tests/unit/test_request.py::test_port[http://go.com:80/-80]",
"tests/unit/test_request.py::test_port[http://go.com:3000/-3000]",
"tests/unit/test_request.py::test_port[https://go.com/-443]",
"tests/unit/test_request.py::test_port[https://go.com:443/-443]",
"tests/unit/test_request.py::test_port[https://go.com:3000/-3000]",
"tests/unit/test_request.py::test_uri[GET-http://go.com/]",
"tests/unit/test_request.py::test_uri[GET-http://go.com:80/]",
"tests/unit/test_request.py::test_uri[CONNECT-localhost:1234]",
"tests/unit/test_request.py::test_uri[OPTIONS-*]",
"tests/unit/test_request.py::test_HeadersDict"
] |
{
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-12-22 17:29:43+00:00
|
mit
| 3,420 |
|
kevin1024__vcrpy-488
|
diff --git a/docs/changelog.rst b/docs/changelog.rst
index e728107..bda16ba 100644
--- a/docs/changelog.rst
+++ b/docs/changelog.rst
@@ -7,6 +7,7 @@ Changelog
- Fix exception when body is empty (@keithprickett)
- Add `pytest-recording` to the documentation as an alternative Pytest plugin (@Stranger6667)
- Fix yarl and python3.5 version issue (@neozenith)
+ - Fix header matcher for boto3 - fixes #474 (@simahawk)
- 2.1.0 - Add a `rewind` method to reset a cassette (thanks @khamidou)
New error message with more details on why the cassette failed to play a request (thanks @arthurHamon2, @neozenith)
Handle connect tunnel URI (thanks @jeking3)
diff --git a/vcr/matchers.py b/vcr/matchers.py
index 7a969f4..eabd61f 100644
--- a/vcr/matchers.py
+++ b/vcr/matchers.py
@@ -53,7 +53,10 @@ def headers(r1, r2):
def _header_checker(value, header="Content-Type"):
def checker(headers):
- return value in headers.get(header, "").lower()
+ _header = headers.get(header, "")
+ if isinstance(_header, bytes):
+ _header = _header.decode("utf-8")
+ return value in _header.lower()
return checker
|
kevin1024/vcrpy
|
d843d2a6c1f26aad83bc35fb2f6dcb8d2d3c4989
|
diff --git a/tests/unit/test_matchers.py b/tests/unit/test_matchers.py
index 4d161ca..34eadd3 100644
--- a/tests/unit/test_matchers.py
+++ b/tests/unit/test_matchers.py
@@ -54,6 +54,16 @@ req2_body = (
b"<member><name>a</name><value><string>1</string></value></member>"
b"</struct></value></data></array></value></param></params></methodCall>"
)
+boto3_bytes_headers = {
+ "X-Amz-Content-SHA256": b"UNSIGNED-PAYLOAD",
+ "Cache-Control": b"max-age=31536000, public",
+ "X-Amz-Date": b"20191102T143910Z",
+ "User-Agent": b"Boto3/1.9.102 Python/3.5.3 Linux/4.15.0-54-generic Botocore/1.12.253 Resource",
+ "Content-MD5": b"GQqjEXsRqrPyxfTl99nkAg==",
+ "Content-Type": b"text/plain",
+ "Expect": b"100-continue",
+ "Content-Length": "21",
+}
@pytest.mark.parametrize(
@@ -110,6 +120,11 @@ req2_body = (
"POST", "http://host.com/", '{"b": 2, "a": 1}', {"content-type": "application/json"}
),
),
+ (
+ # special case for boto3 bytes headers
+ request.Request("POST", "http://aws.custom.com/", b"123", boto3_bytes_headers),
+ request.Request("POST", "http://aws.custom.com/", b"123", boto3_bytes_headers),
+ ),
],
)
def test_body_matcher_does_match(r1, r2):
|
TypeError: a bytes-like object is required, not 'str' when processing header object
```
headers = {'X-Amz-Target': b'<target>', 'Content-Type': b'<content-type>', 'User-Agent': b'<user-agent>', Signature=b'<sig>', 'Content-Length': '<len>'}
def checker(headers):
> return value in headers.get(header, '').lower()
E TypeError: a bytes-like object is required, not 'str'
.venv/lib/python3.6/site-packages/vcr/matchers.py:56: TypeError
```
The code on line 56 in matchers fails unexpectedly. The content type return as a bytes like object but the code still fails. When we convert the bytes object to a string it works. Replacing the current function at https://github.com/kevin1024/vcrpy/blob/master/vcr/matchers.py#L54-L57:
```
def _header_checker(value, header='Content-Type'):
def checker(headers):
return value in headers.get(header, '').lower()
return checker
```
with
```
def _header_checker(value, header='Content-Type'):
def checker(headers):
return value in headers.get(header, '').decode('utf-8').lower()
return checker
```
fixes this issue especially with boto3 requests.
Would there be any risk with making this change?
|
0.0
|
d843d2a6c1f26aad83bc35fb2f6dcb8d2d3c4989
|
[
"tests/unit/test_matchers.py::test_body_matcher_does_match[r17-r27]"
] |
[
"tests/unit/test_matchers.py::test_uri_matcher",
"tests/unit/test_matchers.py::test_body_matcher_does_match[r10-r20]",
"tests/unit/test_matchers.py::test_body_matcher_does_match[r11-r21]",
"tests/unit/test_matchers.py::test_body_matcher_does_match[r12-r22]",
"tests/unit/test_matchers.py::test_body_matcher_does_match[r13-r23]",
"tests/unit/test_matchers.py::test_body_matcher_does_match[r14-r24]",
"tests/unit/test_matchers.py::test_body_matcher_does_match[r15-r25]",
"tests/unit/test_matchers.py::test_body_matcher_does_match[r16-r26]",
"tests/unit/test_matchers.py::test_body_match_does_not_match[r10-r20]",
"tests/unit/test_matchers.py::test_body_match_does_not_match[r11-r21]",
"tests/unit/test_matchers.py::test_body_match_does_not_match[r12-r22]",
"tests/unit/test_matchers.py::test_query_matcher",
"tests/unit/test_matchers.py::test_matchers",
"tests/unit/test_matchers.py::test_evaluate_matcher_does_match",
"tests/unit/test_matchers.py::test_evaluate_matcher_does_not_match",
"tests/unit/test_matchers.py::test_evaluate_matcher_does_not_match_with_assert_message",
"tests/unit/test_matchers.py::test_get_assertion_message",
"tests/unit/test_matchers.py::test_get_assertion_message_with_details",
"tests/unit/test_matchers.py::test_get_matchers_results[r10-r20-expected_successes0-expected_failures0]",
"tests/unit/test_matchers.py::test_get_matchers_results[r11-r21-expected_successes1-expected_failures1]",
"tests/unit/test_matchers.py::test_get_matchers_results[r12-r22-expected_successes2-expected_failures2]",
"tests/unit/test_matchers.py::test_requests_match[successes0-failures0-True]",
"tests/unit/test_matchers.py::test_requests_match[successes1-failures1-False]",
"tests/unit/test_matchers.py::test_requests_match[successes2-failures2-False]"
] |
{
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-11-02 14:50:45+00:00
|
mit
| 3,421 |
|
kevin1024__vcrpy-505
|
diff --git a/docs/changelog.rst b/docs/changelog.rst
index 17e90db..f149199 100644
--- a/docs/changelog.rst
+++ b/docs/changelog.rst
@@ -9,8 +9,10 @@ All help in providing PRs to close out bug issues is appreciated. Even if that i
- UNRELEASED
- ...
-
-
+- 4.0.2
+ - Fix mock imports as reported in #504 by @llybin. Thank you.
+- 4.0.1
+ - Fix logo alignment for PyPI
- 4.0.0
- Remove Python2 support (@hugovk)
- Add Python 3.8 TravisCI support (@neozenith)
diff --git a/tox.ini b/tox.ini
index e73f477..20c4b73 100644
--- a/tox.ini
+++ b/tox.ini
@@ -63,7 +63,6 @@ commands =
./runtests.sh --cov=./vcr --cov-branch --cov-report=xml --cov-append {posargs}
deps =
Flask
- mock
pytest
pytest-httpbin
pytest-cov
diff --git a/vcr/__init__.py b/vcr/__init__.py
index 02b6fb1..070d3e9 100644
--- a/vcr/__init__.py
+++ b/vcr/__init__.py
@@ -2,7 +2,7 @@ import logging
from .config import VCR
from logging import NullHandler
-__version__ = "4.0.1"
+__version__ = "4.0.2"
logging.getLogger(__name__).addHandler(NullHandler())
diff --git a/vcr/patch.py b/vcr/patch.py
index 40b462a..3b30407 100644
--- a/vcr/patch.py
+++ b/vcr/patch.py
@@ -2,7 +2,7 @@
import contextlib
import functools
import itertools
-import mock
+from unittest import mock
from .stubs import VCRHTTPConnection, VCRHTTPSConnection
import http.client as httplib
|
kevin1024/vcrpy
|
f07083e7cc8234bfc232c04f5a177aecec7ad805
|
diff --git a/tests/unit/test_cassettes.py b/tests/unit/test_cassettes.py
index 915f235..90a05c7 100644
--- a/tests/unit/test_cassettes.py
+++ b/tests/unit/test_cassettes.py
@@ -1,13 +1,12 @@
import contextlib
import copy
+import http.client as httplib
import inspect
-import mock
import os
+from unittest import mock
-import http.client as httplib
import pytest
import yaml
-
from vcr.cassette import Cassette
from vcr.errors import UnhandledHTTPRequestError
from vcr.patch import force_reset
diff --git a/tests/unit/test_errors.py b/tests/unit/test_errors.py
index fe79253..62c622a 100644
--- a/tests/unit/test_errors.py
+++ b/tests/unit/test_errors.py
@@ -1,4 +1,4 @@
-import mock
+from unittest import mock
import pytest
diff --git a/tests/unit/test_filters.py b/tests/unit/test_filters.py
index d40bb0c..69d26bf 100644
--- a/tests/unit/test_filters.py
+++ b/tests/unit/test_filters.py
@@ -11,7 +11,7 @@ from vcr.filters import (
from vcr.request import Request
import gzip
import json
-import mock
+from unittest import mock
import zlib
diff --git a/tests/unit/test_matchers.py b/tests/unit/test_matchers.py
index 6c2bd4a..5e45ab6 100644
--- a/tests/unit/test_matchers.py
+++ b/tests/unit/test_matchers.py
@@ -1,5 +1,5 @@
import itertools
-import mock
+from unittest import mock
import pytest
diff --git a/tests/unit/test_serialize.py b/tests/unit/test_serialize.py
index a7efb77..c06d6d3 100644
--- a/tests/unit/test_serialize.py
+++ b/tests/unit/test_serialize.py
@@ -1,5 +1,5 @@
# -*- encoding: utf-8 -*-
-import mock
+from unittest import mock
import pytest
diff --git a/tests/unit/test_stubs.py b/tests/unit/test_stubs.py
index 07d15c1..ee05134 100644
--- a/tests/unit/test_stubs.py
+++ b/tests/unit/test_stubs.py
@@ -1,4 +1,4 @@
-import mock
+from unittest import mock
from vcr.stubs import VCRHTTPSConnection
from vcr.cassette import Cassette
diff --git a/tests/unit/test_vcr.py b/tests/unit/test_vcr.py
index 49e9000..c49a4b9 100644
--- a/tests/unit/test_vcr.py
+++ b/tests/unit/test_vcr.py
@@ -1,4 +1,4 @@
-import mock
+from unittest import mock
import os
import pytest
|
python 3.8 vcrpy 4.0.1 No module named 'mock'
```
python3.8/site-packages/vcr/patch.py", line 5, in <module>
import mock
ModuleNotFoundError: No module named 'mock'
```
my suggestion: everywhere in projects change:
import mock -> from unittest import mock
|
0.0
|
f07083e7cc8234bfc232c04f5a177aecec7ad805
|
[
"tests/unit/test_cassettes.py::test_cassette_load",
"tests/unit/test_cassettes.py::test_cassette_not_played",
"tests/unit/test_cassettes.py::test_cassette_append",
"tests/unit/test_cassettes.py::test_cassette_len",
"tests/unit/test_cassettes.py::test_cassette_contains",
"tests/unit/test_cassettes.py::test_cassette_responses_of",
"tests/unit/test_cassettes.py::test_cassette_get_missing_response",
"tests/unit/test_cassettes.py::test_cassette_cant_read_same_request_twice",
"tests/unit/test_cassettes.py::test_function_decorated_with_use_cassette_can_be_invoked_multiple_times",
"tests/unit/test_cassettes.py::test_arg_getter_functionality",
"tests/unit/test_cassettes.py::test_cassette_not_all_played",
"tests/unit/test_cassettes.py::test_cassette_all_played",
"tests/unit/test_cassettes.py::test_cassette_rewound",
"tests/unit/test_cassettes.py::test_before_record_response",
"tests/unit/test_cassettes.py::test_nesting_cassette_context_managers",
"tests/unit/test_cassettes.py::test_nesting_context_managers_by_checking_references_of_http_connection",
"tests/unit/test_cassettes.py::test_custom_patchers",
"tests/unit/test_cassettes.py::test_decorated_functions_are_reentrant",
"tests/unit/test_cassettes.py::test_cassette_use_called_without_path_uses_function_to_generate_path",
"tests/unit/test_cassettes.py::test_path_transformer_with_function_path",
"tests/unit/test_cassettes.py::test_path_transformer_with_context_manager",
"tests/unit/test_cassettes.py::test_path_transformer_None",
"tests/unit/test_cassettes.py::test_func_path_generator",
"tests/unit/test_cassettes.py::test_use_as_decorator_on_coroutine",
"tests/unit/test_cassettes.py::test_use_as_decorator_on_generator",
"tests/unit/test_cassettes.py::test_find_requests_with_most_matches_one_similar_request",
"tests/unit/test_cassettes.py::test_find_requests_with_most_matches_no_similar_requests",
"tests/unit/test_cassettes.py::test_find_requests_with_most_matches_many_similar_requests",
"tests/unit/test_errors.py::test_CannotOverwriteExistingCassetteException_get_message[most_matches0-No",
"tests/unit/test_errors.py::test_CannotOverwriteExistingCassetteException_get_message[most_matches1-Found",
"tests/unit/test_errors.py::test_CannotOverwriteExistingCassetteException_get_message[most_matches2-Found",
"tests/unit/test_errors.py::test_CannotOverwriteExistingCassetteException_get_message[most_matches3-Found",
"tests/unit/test_filters.py::test_replace_headers",
"tests/unit/test_filters.py::test_replace_headers_empty",
"tests/unit/test_filters.py::test_replace_headers_callable",
"tests/unit/test_filters.py::test_remove_headers",
"tests/unit/test_filters.py::test_replace_query_parameters",
"tests/unit/test_filters.py::test_remove_all_query_parameters",
"tests/unit/test_filters.py::test_replace_query_parameters_callable",
"tests/unit/test_filters.py::test_remove_query_parameters",
"tests/unit/test_filters.py::test_replace_post_data_parameters",
"tests/unit/test_filters.py::test_replace_post_data_parameters_empty_body",
"tests/unit/test_filters.py::test_remove_post_data_parameters",
"tests/unit/test_filters.py::test_preserve_multiple_post_data_parameters",
"tests/unit/test_filters.py::test_remove_all_post_data_parameters",
"tests/unit/test_filters.py::test_replace_json_post_data_parameters",
"tests/unit/test_filters.py::test_remove_json_post_data_parameters",
"tests/unit/test_filters.py::test_remove_all_json_post_data_parameters",
"tests/unit/test_filters.py::test_decode_response_uncompressed",
"tests/unit/test_filters.py::test_decode_response_deflate",
"tests/unit/test_filters.py::test_decode_response_gzip",
"tests/unit/test_matchers.py::test_uri_matcher",
"tests/unit/test_matchers.py::test_body_matcher_does_match[r10-r20]",
"tests/unit/test_matchers.py::test_body_matcher_does_match[r11-r21]",
"tests/unit/test_matchers.py::test_body_matcher_does_match[r12-r22]",
"tests/unit/test_matchers.py::test_body_matcher_does_match[r13-r23]",
"tests/unit/test_matchers.py::test_body_matcher_does_match[r14-r24]",
"tests/unit/test_matchers.py::test_body_matcher_does_match[r15-r25]",
"tests/unit/test_matchers.py::test_body_matcher_does_match[r16-r26]",
"tests/unit/test_matchers.py::test_body_matcher_does_match[r17-r27]",
"tests/unit/test_matchers.py::test_body_match_does_not_match[r10-r20]",
"tests/unit/test_matchers.py::test_body_match_does_not_match[r11-r21]",
"tests/unit/test_matchers.py::test_body_match_does_not_match[r12-r22]",
"tests/unit/test_matchers.py::test_query_matcher",
"tests/unit/test_matchers.py::test_matchers",
"tests/unit/test_matchers.py::test_evaluate_matcher_does_match",
"tests/unit/test_matchers.py::test_evaluate_matcher_does_not_match",
"tests/unit/test_matchers.py::test_evaluate_matcher_does_not_match_with_assert_message",
"tests/unit/test_matchers.py::test_get_assertion_message",
"tests/unit/test_matchers.py::test_get_assertion_message_with_details",
"tests/unit/test_matchers.py::test_get_matchers_results[r10-r20-expected_successes0-expected_failures0]",
"tests/unit/test_matchers.py::test_get_matchers_results[r11-r21-expected_successes1-expected_failures1]",
"tests/unit/test_matchers.py::test_get_matchers_results[r12-r22-expected_successes2-expected_failures2]",
"tests/unit/test_matchers.py::test_requests_match[successes0-failures0-True]",
"tests/unit/test_matchers.py::test_requests_match[successes1-failures1-False]",
"tests/unit/test_matchers.py::test_requests_match[successes2-failures2-False]",
"tests/unit/test_serialize.py::test_deserialize_old_yaml_cassette",
"tests/unit/test_serialize.py::test_deserialize_old_json_cassette",
"tests/unit/test_serialize.py::test_deserialize_new_yaml_cassette",
"tests/unit/test_serialize.py::test_deserialize_new_json_cassette",
"tests/unit/test_serialize.py::test_deserialize_py2py3_yaml_cassette[x=5&y=2-x=5&y=2]",
"tests/unit/test_serialize.py::test_deserialize_py2py3_yaml_cassette[!!binary",
"tests/unit/test_serialize.py::test_deserialize_py2py3_yaml_cassette[!!python/str",
"tests/unit/test_serialize.py::test_serialize_constructs_UnicodeDecodeError",
"tests/unit/test_serialize.py::test_serialize_empty_request",
"tests/unit/test_serialize.py::test_serialize_json_request",
"tests/unit/test_serialize.py::test_serialize_binary_request",
"tests/unit/test_serialize.py::test_deserialize_no_body_string",
"tests/unit/test_stubs.py::TestVCRConnection::test_setting_of_attributes_get_propogated_to_real_connection",
"tests/unit/test_stubs.py::TestVCRConnection::testing_connect",
"tests/unit/test_vcr.py::test_vcr_use_cassette",
"tests/unit/test_vcr.py::test_vcr_before_record_request_params",
"tests/unit/test_vcr.py::test_vcr_before_record_response_iterable",
"tests/unit/test_vcr.py::test_before_record_response_as_filter",
"tests/unit/test_vcr.py::test_vcr_path_transformer",
"tests/unit/test_vcr.py::test_fixtures_with_use_cassette",
"tests/unit/test_vcr.py::test_custom_patchers",
"tests/unit/test_vcr.py::test_inject_cassette",
"tests/unit/test_vcr.py::test_with_current_defaults",
"tests/unit/test_vcr.py::test_cassette_library_dir_with_decoration_and_no_explicit_path",
"tests/unit/test_vcr.py::test_cassette_library_dir_with_decoration_and_explicit_path",
"tests/unit/test_vcr.py::test_cassette_library_dir_with_decoration_and_super_explicit_path",
"tests/unit/test_vcr.py::test_cassette_library_dir_with_path_transformer",
"tests/unit/test_vcr.py::test_use_cassette_with_no_extra_invocation",
"tests/unit/test_vcr.py::test_path_transformer",
"tests/unit/test_vcr.py::test_cassette_name_generator_defaults_to_using_module_function_defined_in",
"tests/unit/test_vcr.py::test_ensure_suffix",
"tests/unit/test_vcr.py::test_additional_matchers",
"tests/unit/test_vcr.py::test_decoration_should_respect_function_return_value",
"tests/unit/test_vcr.py::TestVCRClass::test_one",
"tests/unit/test_vcr.py::TestVCRClass::test_two",
"tests/unit/test_vcr.py::TestVCRClass::test_dynamically_added"
] |
[] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-12-20 09:50:27+00:00
|
mit
| 3,422 |
|
kevin1024__vcrpy-541
|
diff --git a/docs/advanced.rst b/docs/advanced.rst
index 5536055..b16710b 100644
--- a/docs/advanced.rst
+++ b/docs/advanced.rst
@@ -33,6 +33,8 @@ consider part of the API. The fields are as follows:
been played back.
- ``responses_of(request)``: Access the responses that match a given
request
+- ``allow_playback_repeats``: A boolean indicating whether responses
+ can be played back more than once.
The ``Request`` object has the following properties:
@@ -386,3 +388,19 @@ VCR.py allows to rewind a cassette in order to replay it inside the same functio
assert cass.all_played
cass.rewind()
assert not cass.all_played
+
+Playback Repeats
+----------------
+
+By default, each response in a cassette can only be matched and played back
+once while the cassette is in use, unless the cassette is rewound.
+
+If you want to allow playback repeats without rewinding the cassette, use
+the Cassette ``allow_playback_repeats`` option.
+
+.. code:: python
+
+ with vcr.use_cassette('fixtures/vcr_cassettes/synopsis.yaml', allow_playback_repeats=True) as cass:
+ for x in range(10):
+ response = urllib2.urlopen('http://www.zombo.com/').read()
+ assert cass.all_played
diff --git a/vcr/cassette.py b/vcr/cassette.py
index 826a68b..9122b4a 100644
--- a/vcr/cassette.py
+++ b/vcr/cassette.py
@@ -182,6 +182,7 @@ class Cassette:
before_record_response=None,
custom_patches=(),
inject=False,
+ allow_playback_repeats=False,
):
self._persister = persister or FilesystemPersister
self._path = path
@@ -193,6 +194,7 @@ class Cassette:
self.inject = inject
self.record_mode = record_mode
self.custom_patches = custom_patches
+ self.allow_playback_repeats = allow_playback_repeats
# self.data is the list of (req, resp) tuples
self.data = []
@@ -207,7 +209,7 @@ class Cassette:
@property
def all_played(self):
"""Returns True if all responses have been played, False otherwise."""
- return self.play_count == len(self)
+ return len(self.play_counts.values()) == len(self)
@property
def requests(self):
@@ -259,7 +261,7 @@ class Cassette:
hasn't been played back before, and mark it as played
"""
for index, response in self._responses(request):
- if self.play_counts[index] == 0:
+ if self.play_counts[index] == 0 or self.allow_playback_repeats:
self.play_counts[index] += 1
return response
# The cassette doesn't contain the request asked for.
@@ -349,6 +351,6 @@ class Cassette:
def __contains__(self, request):
"""Return whether or not a request has been stored"""
for index, response in self._responses(request):
- if self.play_counts[index] == 0:
+ if self.play_counts[index] == 0 or self.allow_playback_repeats:
return True
return False
diff --git a/vcr/config.py b/vcr/config.py
index 7dfd1a8..e95908c 100644
--- a/vcr/config.py
+++ b/vcr/config.py
@@ -149,6 +149,7 @@ class VCR:
"inject": kwargs.get("inject_cassette", self.inject_cassette),
"path_transformer": path_transformer,
"func_path_generator": func_path_generator,
+ "allow_playback_repeats": kwargs.get("allow_playback_repeats", False),
}
path = kwargs.get("path")
if path:
|
kevin1024/vcrpy
|
a249781b977ce1ae4e9a6d098a7b093dfdbeaf4a
|
diff --git a/tests/unit/test_cassettes.py b/tests/unit/test_cassettes.py
index 90a05c7..adbc77a 100644
--- a/tests/unit/test_cassettes.py
+++ b/tests/unit/test_cassettes.py
@@ -137,6 +137,31 @@ def test_cassette_all_played():
assert a.all_played
[email protected]("vcr.cassette.requests_match", _mock_requests_match)
+def test_cassette_allow_playback_repeats():
+ a = Cassette("test", allow_playback_repeats=True)
+ a.append("foo", "bar")
+ a.append("other", "resp")
+ for x in range(10):
+ assert a.play_response("foo") == "bar"
+ assert a.play_count == 10
+ assert a.all_played is False
+ assert a.play_response("other") == "resp"
+ assert a.play_count == 11
+ assert a.all_played
+
+ a.allow_playback_repeats = False
+ with pytest.raises(UnhandledHTTPRequestError) as e:
+ a.play_response("foo")
+ assert str(e.value) == "\"The cassette ('test') doesn't contain the request ('foo') asked for\""
+ a.rewind()
+ assert a.all_played is False
+ assert a.play_response("foo") == "bar"
+ assert a.all_played is False
+ assert a.play_response("other") == "resp"
+ assert a.all_played
+
+
@mock.patch("vcr.cassette.requests_match", _mock_requests_match)
def test_cassette_rewound():
a = Cassette("test")
|
allow_playback_repeats
Ruby VCR has a Cassette option [allow_playback_repeats](https://relishapp.com/vcr/vcr/docs/request-matching/playback-repeats). Any chance this can be added to vcrpy?
|
0.0
|
a249781b977ce1ae4e9a6d098a7b093dfdbeaf4a
|
[
"tests/unit/test_cassettes.py::test_cassette_allow_playback_repeats"
] |
[
"tests/unit/test_cassettes.py::test_cassette_load",
"tests/unit/test_cassettes.py::test_cassette_not_played",
"tests/unit/test_cassettes.py::test_cassette_append",
"tests/unit/test_cassettes.py::test_cassette_len",
"tests/unit/test_cassettes.py::test_cassette_contains",
"tests/unit/test_cassettes.py::test_cassette_responses_of",
"tests/unit/test_cassettes.py::test_cassette_get_missing_response",
"tests/unit/test_cassettes.py::test_cassette_cant_read_same_request_twice",
"tests/unit/test_cassettes.py::test_function_decorated_with_use_cassette_can_be_invoked_multiple_times",
"tests/unit/test_cassettes.py::test_arg_getter_functionality",
"tests/unit/test_cassettes.py::test_cassette_not_all_played",
"tests/unit/test_cassettes.py::test_cassette_all_played",
"tests/unit/test_cassettes.py::test_cassette_rewound",
"tests/unit/test_cassettes.py::test_before_record_response",
"tests/unit/test_cassettes.py::test_nesting_cassette_context_managers",
"tests/unit/test_cassettes.py::test_nesting_context_managers_by_checking_references_of_http_connection",
"tests/unit/test_cassettes.py::test_custom_patchers",
"tests/unit/test_cassettes.py::test_decorated_functions_are_reentrant",
"tests/unit/test_cassettes.py::test_cassette_use_called_without_path_uses_function_to_generate_path",
"tests/unit/test_cassettes.py::test_path_transformer_with_function_path",
"tests/unit/test_cassettes.py::test_path_transformer_with_context_manager",
"tests/unit/test_cassettes.py::test_path_transformer_None",
"tests/unit/test_cassettes.py::test_func_path_generator",
"tests/unit/test_cassettes.py::test_use_as_decorator_on_coroutine",
"tests/unit/test_cassettes.py::test_use_as_decorator_on_generator",
"tests/unit/test_cassettes.py::test_find_requests_with_most_matches_one_similar_request",
"tests/unit/test_cassettes.py::test_find_requests_with_most_matches_no_similar_requests",
"tests/unit/test_cassettes.py::test_find_requests_with_most_matches_many_similar_requests"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-07-02 17:07:00+00:00
|
mit
| 3,423 |
|
kevin1024__vcrpy-668
|
diff --git a/docs/advanced.rst b/docs/advanced.rst
index f3eb68c..fb287fa 100644
--- a/docs/advanced.rst
+++ b/docs/advanced.rst
@@ -404,3 +404,25 @@ the Cassette ``allow_playback_repeats`` option.
for x in range(10):
response = urllib2.urlopen('http://www.zombo.com/').read()
assert cass.all_played
+
+Discards Cassette on Errors
+---------------------------
+
+By default VCR will save the cassette file even when there is any error inside
+the enclosing context/test.
+
+If you want to save the cassette only when the test succeedes, set the Cassette
+``record_on_exception`` option to ``False``.
+
+.. code:: python
+
+ try:
+ my_vcr = VCR(record_on_exception=False)
+ with my_vcr.use_cassette('fixtures/vcr_cassettes/synopsis.yaml') as cass:
+ response = urllib2.urlopen('http://www.zombo.com/').read()
+ raise RuntimeError("Oops, something happened")
+ except RuntimeError:
+ pass
+
+ # Since there was an exception, the cassette file hasn't been created.
+ assert not os.path.exists('fixtures/vcr_cassettes/synopsis.yaml')
diff --git a/docs/conf.py b/docs/conf.py
index 94e6d8a..a3ffd5e 100644
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -94,7 +94,7 @@ version = release = find_version("..", "vcr", "__init__.py")
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
-language = None
+language = "en"
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
diff --git a/vcr/cassette.py b/vcr/cassette.py
index 901b7fb..5822afa 100644
--- a/vcr/cassette.py
+++ b/vcr/cassette.py
@@ -45,7 +45,11 @@ class CassetteContextDecorator:
this class as a context manager in ``__exit__``.
"""
- _non_cassette_arguments = ("path_transformer", "func_path_generator")
+ _non_cassette_arguments = (
+ "path_transformer",
+ "func_path_generator",
+ "record_on_exception",
+ )
@classmethod
def from_args(cls, cassette_class, **kwargs):
@@ -55,6 +59,7 @@ class CassetteContextDecorator:
self.cls = cls
self._args_getter = args_getter
self.__finish = None
+ self.__cassette = None
def _patch_generator(self, cassette):
with contextlib.ExitStack() as exit_stack:
@@ -64,9 +69,6 @@ class CassetteContextDecorator:
log.debug(log_format.format(action="Entering", path=cassette._path))
yield cassette
log.debug(log_format.format(action="Exiting", path=cassette._path))
- # TODO(@IvanMalison): Hmmm. it kind of feels like this should be
- # somewhere else.
- cassette._save()
def __enter__(self):
# This assertion is here to prevent the dangerous behavior
@@ -84,10 +86,22 @@ class CassetteContextDecorator:
if other_kwargs.get("path_transformer"):
transformer = other_kwargs["path_transformer"]
cassette_kwargs["path"] = transformer(cassette_kwargs["path"])
- self.__finish = self._patch_generator(self.cls.load(**cassette_kwargs))
+ self.__cassette = self.cls.load(**cassette_kwargs)
+ self.__finish = self._patch_generator(self.__cassette)
return next(self.__finish)
- def __exit__(self, *args):
+ def __exit__(self, *exc_info):
+ exception_was_raised = any(exc_info)
+ record_on_exception = self._args_getter().get("record_on_exception", True)
+ if record_on_exception or not exception_was_raised:
+ self.__cassette._save()
+ self.__cassette = None
+ # Fellow programmer, don't remove this `next`, if `self.__finish` is
+ # not consumed the unpatcher functions accumulated in the `exit_stack`
+ # object created in `_patch_generator` will not be called until
+ # `exit_stack` is not garbage collected.
+ # This works in CPython but not in Pypy, where the unpatchers will not
+ # be called until much later.
next(self.__finish, None)
self.__finish = None
diff --git a/vcr/config.py b/vcr/config.py
index 45412e3..a991c95 100644
--- a/vcr/config.py
+++ b/vcr/config.py
@@ -49,6 +49,7 @@ class VCR:
cassette_library_dir=None,
func_path_generator=None,
decode_compressed_response=False,
+ record_on_exception=True,
):
self.serializer = serializer
self.match_on = match_on
@@ -80,6 +81,7 @@ class VCR:
self.path_transformer = path_transformer
self.func_path_generator = func_path_generator
self.decode_compressed_response = decode_compressed_response
+ self.record_on_exception = record_on_exception
self._custom_patches = tuple(custom_patches)
def _get_serializer(self, serializer_name):
@@ -123,6 +125,7 @@ class VCR:
func_path_generator = kwargs.get("func_path_generator", self.func_path_generator)
cassette_library_dir = kwargs.get("cassette_library_dir", self.cassette_library_dir)
additional_matchers = kwargs.get("additional_matchers", ())
+ record_on_exception = kwargs.get("record_on_exception", self.record_on_exception)
if cassette_library_dir:
@@ -149,6 +152,7 @@ class VCR:
"path_transformer": path_transformer,
"func_path_generator": func_path_generator,
"allow_playback_repeats": kwargs.get("allow_playback_repeats", False),
+ "record_on_exception": record_on_exception,
}
path = kwargs.get("path")
if path:
|
kevin1024/vcrpy
|
423ccaa40b94439645933d920ebd51b893faf9d2
|
diff --git a/tests/integration/test_config.py b/tests/integration/test_config.py
index c6da8e8..013f849 100644
--- a/tests/integration/test_config.py
+++ b/tests/integration/test_config.py
@@ -60,3 +60,23 @@ def test_missing_matcher():
with pytest.raises(KeyError):
with my_vcr.use_cassette("test.yaml", match_on=["notawesome"]):
pass
+
+
+def test_dont_record_on_exception(tmpdir):
+ my_vcr = vcr.VCR(record_on_exception=False)
+
+ @my_vcr.use_cassette(str(tmpdir.join("dontsave.yml")))
+ def some_test():
+ assert b"Not in content" in urlopen("http://httpbin.org/get")
+
+ with pytest.raises(AssertionError):
+ some_test()
+
+ assert not os.path.exists(str(tmpdir.join("dontsave.yml")))
+
+ # Make sure context decorator has the same behavior
+ with pytest.raises(AssertionError):
+ with my_vcr.use_cassette(str(tmpdir.join("dontsave2.yml"))):
+ assert b"Not in content" in urlopen("http://httpbin.org/get").read()
+
+ assert not os.path.exists(str(tmpdir.join("dontsave2.yml")))
|
Don't save requests from decorated tests if decorated test fails
As the title says: Don't save requests from decorated tests if decorated test fails
Does VCR already do this? If so awesome, and you guys should definitely say so in the README somewhere. Otherwise this seems like a solid feature. We have one test in particular where our 3rd party goes down more often than I'd care to admit, and if that bad response gets saved that will be quite aggravating.
|
0.0
|
423ccaa40b94439645933d920ebd51b893faf9d2
|
[
"tests/integration/test_config.py::test_dont_record_on_exception"
] |
[
"tests/integration/test_config.py::test_missing_matcher"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-10-30 19:32:18+00:00
|
mit
| 3,424 |
|
kgaughan__komorebi-11
|
diff --git a/Makefile b/Makefile
index c9ef6f9..89313eb 100644
--- a/Makefile
+++ b/Makefile
@@ -26,4 +26,7 @@ lint:
poetry run flake8 --max-line-length=105 --ignore=E203 --per-file-ignores="komorebi/oembed.py:N802" komorebi
poetry run pylint komorebi
-.PHONY: clean develop run build tidy lint
+test:
+ poetry run python -m unittest discover -bf tests
+
+.PHONY: clean develop run build tidy lint test
diff --git a/komorebi/blog.py b/komorebi/blog.py
index 75168d0..21bf6ab 100644
--- a/komorebi/blog.py
+++ b/komorebi/blog.py
@@ -16,7 +16,7 @@ from flask_httpauth import HTTPBasicAuth
import markdown
from passlib.apache import HtpasswdFile
-from . import db, forms, oembed, time, xmlutils
+from . import db, forms, futz, oembed, time, xmlutils
blog = Blueprint("blog", __name__)
blog.add_app_template_filter(time.to_iso_date)
@@ -51,14 +51,22 @@ def process_archive(records):
if record["year"] != year:
if last_month != 0:
for i in range(1, 13 - last_month):
- yield {"n": 0, "year": year, "month": last_month + i}
+ yield {
+ "n": 0,
+ "year": year,
+ "month": last_month + i,
+ }
year = record["year"]
last_month = 0
# Pad out between months in a year.
if record["month"] - 1 != last_month:
for i in range(1, record["month"] - last_month):
- yield {"n": 0, "year": record["year"], "month": last_month + i}
+ yield {
+ "n": 0,
+ "year": record["year"],
+ "month": last_month + i,
+ }
yield record
last_month = record["month"]
@@ -161,13 +169,22 @@ def add_entry():
try:
entry_id = db.add_entry(
- link=form.link.data, title=title, via=form.via.data, note=form.note.data
+ link=form.link.data,
+ title=title,
+ via=form.via.data,
+ note=form.note.data,
)
except IntegrityError:
flash("That links already exists", "error")
else:
if data:
- db.add_oembed(entry_id, data["html"], data["width"], data["height"])
+ futzed, width, height = futz.futz(data["html"])
+ db.add_oembed(
+ entry_id,
+ futz.futz(data["html"]),
+ width,
+ height,
+ )
return redirect(url_for(".entry", entry_id=entry_id))
return render_template("entry_edit.html", form=form)
@@ -212,3 +229,9 @@ def md(text):
@blog.app_template_filter()
def extract_hostname(url):
return parse.urlparse(url).netloc
+
+
[email protected]_template_filter("futz")
+def futz_markup(markup):
+ futzed, _, _ = futz.futz(markup)
+ return futzed
diff --git a/komorebi/futz.py b/komorebi/futz.py
new file mode 100644
index 0000000..87e0afd
--- /dev/null
+++ b/komorebi/futz.py
@@ -0,0 +1,131 @@
+"""
+Futz with OEmbed data to fix it up.
+"""
+
+import dataclasses
+import html
+from html.parser import HTMLParser
+import io
+
+# See: https://html.spec.whatwg.org/multipage/syntax.html#void-elements
+SELF_CLOSING = {
+ "area",
+ "base",
+ "br",
+ "col",
+ "command",
+ "embed",
+ "hr",
+ "img",
+ "input",
+ "keygen",
+ "link",
+ "meta",
+ "param",
+ "source",
+ "track",
+ "wbr",
+}
+
+
[email protected]
+class Element:
+ tag: str
+ attrs: dict = dataclasses.field(default_factory=dict)
+ children: list = dataclasses.field(default_factory=list)
+
+ def __getitem__(self, i):
+ return self.children[i]
+
+ def __len__(self):
+ return len(self.children)
+
+ def __iter__(self):
+ return iter(self.children)
+
+ def serialize(self, dest=None) -> io.TextIOBase:
+ if dest is None:
+ dest = io.StringIO()
+ if self.tag is not None:
+ dest.write("<" + self.tag)
+ for key, value in self.attrs.items():
+ dest.write(" " + key)
+ if value is not None:
+ dest.write('="' + html.escape(value, quote=True) + '"')
+ dest.write(">")
+ for child in self.children:
+ if isinstance(child, str):
+ dest.write(html.escape(child, quote=False))
+ elif isinstance(child, Element):
+ child.serialize(dest)
+ if self.tag is not None and self.tag not in SELF_CLOSING:
+ dest.write("</" + self.tag + ">")
+
+ return dest
+
+
+class Parser(HTMLParser):
+ """
+ Parses a HTML document into
+ """
+
+ def __init__(self):
+ super().__init__()
+ self.root = Element(tag=None)
+ self.stack = [self.root]
+
+ def close(self):
+ super().close()
+
+ @property
+ def top(self):
+ return self.stack[-1]
+
+ def handle_starttag(self, tag, attrs):
+ elem = Element(tag=tag, attrs=dict(attrs))
+ self.top.children.append(elem)
+ if tag not in SELF_CLOSING:
+ self.stack.append(elem)
+
+ def handle_startendtag(self, tag, attrs):
+ elem = Element(tag=tag, attrs=attrs)
+ self.top.children.append(elem)
+
+ def handle_endtag(self, tag):
+ if tag not in SELF_CLOSING:
+ while len(self.stack) > 1:
+ self.stack.pop()
+ if tag == self.top.tag:
+ break
+
+ def handle_data(self, data):
+ if data != "":
+ self.top.children.append(data)
+
+
+def futz(markup):
+ """
+ Performs various kinds of cleanup on OEmbed data
+ """
+ parser = Parser()
+ parser.feed(markup)
+
+ width = 0
+ height = 0
+ for elem in parser.root:
+ if isinstance(elem, str) or elem.tag != "iframe":
+ continue
+ elem.attrs["loading"] = "lazy"
+ del elem.attrs["allowfullscreen"]
+ width = max(1, int(elem.attrs.get("width", "1")))
+ # Fix undersized YT embeds
+ if width < 560:
+ height = max(1, int(elem.attrs.get("height", "1")))
+ height = int(height * 560.0 / width)
+ elem.attrs["height"] = str(height)
+ width = 560
+ elem.attrs["width"] = "560"
+
+ with io.StringIO() as fo:
+ parser.root.serialize(fo)
+ return fo.getvalue(), width, height
diff --git a/komorebi/templates/macros.html b/komorebi/templates/macros.html
index ca118b9..6021dc1 100644
--- a/komorebi/templates/macros.html
+++ b/komorebi/templates/macros.html
@@ -21,7 +21,7 @@
</div>
</header>
- {% if entry.html %}<div class="oembed">{{ entry.html | safe}}</div>{% endif %}
+ {% if entry.html %}<div class="oembed">{{ entry.html | futz | safe }}</div>{% endif %}
{{ entry.note | markdown | safe }}
</article>
{%- endmacro %}
|
kgaughan/komorebi
|
004e099ca7e906680e6be41957a0b44a5c4f22af
|
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
new file mode 100644
index 0000000..594b206
--- /dev/null
+++ b/.github/workflows/tests.yml
@@ -0,0 +1,17 @@
+---
+name: Tests
+on:
+ push:
+ branches: [ master ]
+ pull_request:
+ branches: [ master ]
+
+ workflow_dispatch:
+
+jobs:
+ build:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v2
+ - name: Run tests
+ run: make test
diff --git a/tests/test_futz.py b/tests/test_futz.py
new file mode 100644
index 0000000..14e3ffa
--- /dev/null
+++ b/tests/test_futz.py
@@ -0,0 +1,83 @@
+import io
+import unittest
+
+from komorebi import futz
+
+
+def parse(fixture):
+ parser = futz.Parser()
+ parser.feed(fixture)
+ parser.close()
+ return parser.root
+
+
+class TestParser(unittest.TestCase):
+ def test_empty(self):
+ root = parse("")
+ self.assertEqual(len(root), 0)
+ self.assertDictEqual(root.attrs, {})
+
+ def test_simple(self):
+ root = parse("<a>")
+ self.assertEqual(len(root), 1)
+ self.assertEqual(root[0].tag, "a")
+
+ def test_simple_nesting(self):
+ root = parse("<b><a>")
+ self.assertEqual(len(root), 1)
+ self.assertEqual(root[0].tag, "b")
+ self.assertEqual(root[0][0].tag, "a")
+
+ def test_self_closing(self):
+ root = parse("<br><hr>")
+ self.assertEqual(len(root), 2)
+ self.assertEqual(root[0].tag, "br")
+ self.assertEqual(root[1].tag, "hr")
+
+ def test_text_embedding(self):
+ root = parse("a<br>b<hr>c")
+ self.assertEqual(len(root), 5)
+ self.assertIsInstance(root[0], str)
+ self.assertEqual(root[0], "a")
+ self.assertIsInstance(root[1], futz.Element)
+ self.assertEqual(root[1].tag, "br")
+ self.assertIsInstance(root[2], str)
+ self.assertEqual(root[2], "b")
+ self.assertIsInstance(root[3], futz.Element)
+ self.assertEqual(root[3].tag, "hr")
+ self.assertIsInstance(root[4], str)
+ self.assertEqual(root[4], "c")
+
+
+class TestElement(unittest.TestCase):
+ def assert_html(self, a, b):
+ with io.StringIO() as fo:
+ parse(a).serialize(fo)
+ self.assertEqual(fo.getvalue(), b)
+
+ def test_simple(self):
+ self.assert_html("", "")
+ self.assert_html("<a>", "<a></a>")
+ self.assert_html("<br>", "<br>")
+
+ def test_attrs(self):
+ self.assert_html(
+ '<a href="foo">bar</a>',
+ '<a href="foo">bar</a>',
+ )
+ self.assert_html(
+ "<a name>bar</a>",
+ "<a name>bar</a>",
+ )
+
+
+class TestFutz(unittest.TestCase):
+ def test_futz(self):
+ fixture = """\
+<iframe src="https://www.youtube.com/embed/W9qsxhhNUoU?feature=oembed" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" width="200" height="113" frameborder="0"></iframe>
+"""
+ result, width, height = futz.futz(fixture)
+ self.assertEquals(width, 560)
+ self.assertEquals(height, 316)
+ self.assertIn('loading="lazy"', result)
+ self.assertNotIn(" allowfullscreen", result)
|
Embed scaling
YouTube recently started making its embeds _tiny_. Here's an example:
```html
<iframe
width="200"
height="113"
src="https://www.youtube.com/embed/1234567890a?feature=oembed"
frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen></iframe>
```
This is very, very small. I think I need a way to rescale things like these.
|
0.0
|
004e099ca7e906680e6be41957a0b44a5c4f22af
|
[
"tests/test_futz.py::TestParser::test_empty",
"tests/test_futz.py::TestParser::test_self_closing",
"tests/test_futz.py::TestParser::test_simple",
"tests/test_futz.py::TestParser::test_simple_nesting",
"tests/test_futz.py::TestParser::test_text_embedding",
"tests/test_futz.py::TestElement::test_attrs",
"tests/test_futz.py::TestElement::test_simple",
"tests/test_futz.py::TestFutz::test_futz"
] |
[] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-06-05 19:09:28+00:00
|
mit
| 3,425 |
|
kidosoft__Morelia-125
|
diff --git a/CHANGES.rst b/CHANGES.rst
index b0066c2..e8bd1aa 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -10,6 +10,10 @@ and this project adheres to `Semantic Versioning <http://semver.org/>`_.
Version: Unreleased
===============================================================================
+FIXED
+-----
+
+ * matching steps with augmented predicate (#123)
Version: 0.7.1 (2019-01-15)
===============================================================================
diff --git a/morelia/visitors.py b/morelia/visitors.py
index 8d25552..c55b9c9 100644
--- a/morelia/visitors.py
+++ b/morelia/visitors.py
@@ -184,3 +184,6 @@ class StepMatcherVisitor(IVisitor):
if suggest:
diagnostic = u'Cannot match steps:\n\n{}'.format(suggest)
self._suite.fail(to_docstring(diagnostic))
+
+ def permute_schedule(self, node):
+ return node.permute_schedule()
|
kidosoft/Morelia
|
912b0ec21310b8bbf3b346dcf7cc10123bc5ebc8
|
diff --git a/example/test_acceptance.py b/example/test_acceptance.py
index dbf8272..3131e82 100644
--- a/example/test_acceptance.py
+++ b/example/test_acceptance.py
@@ -31,7 +31,7 @@ class CalculatorTestCase(unittest.TestCase):
self.calculator.on()
def step_I_enter_a_number_into_the_calculator(self, number):
- r'I enter "(.+)" into the calculator' # match by regexp
+ r'I enter "(\d+)" into the calculator' # match by regexp
self.calculator.push(int(number))
def step_I_press_add(self): # matched by method name
|
initial step matching is done with non-augmented predicates when show_all_missing=True
* Morelia version: 0.7.1
* Python version: 2.7
### Description
`show_all_missing=True` does an initial matching pass where the `augmented_predicate` is not augmented yet
this prevents using a regex like `(\d+)` to match steps which have numeric variable substitutions because the regex needs to match `<variable_name>` instead
if I set `show_all_missing=False` then I can regex match on augmented predicates like I wanted
|
0.0
|
912b0ec21310b8bbf3b346dcf7cc10123bc5ebc8
|
[
"example/test_acceptance.py::CalculatorTestCase::test_addition"
] |
[] |
{
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-07-09 20:25:23+00:00
|
mit
| 3,426 |
|
kinegratii__borax-21
|
diff --git a/borax/calendars/lunardate.py b/borax/calendars/lunardate.py
index 1ff9b59..b7adda7 100644
--- a/borax/calendars/lunardate.py
+++ b/borax/calendars/lunardate.py
@@ -456,7 +456,10 @@ class LunarDate(EncoderMixin):
@property
def cn_day_calendar(self) -> str:
if self.day == 1:
- return self.cn_month
+ if self.leap:
+ return '闰{}'.format(self.cn_month)
+ else:
+ return '{}月'.format(self.cn_month)
else:
return self.cn_day
|
kinegratii/borax
|
f9e51116e04eb9539e54e0db1e321b6e40200903
|
diff --git a/tests/test_lunardate.py b/tests/test_lunardate.py
index 3d1d7a1..86417c7 100644
--- a/tests/test_lunardate.py
+++ b/tests/test_lunardate.py
@@ -127,6 +127,7 @@ class FormatterTestCase(unittest.TestCase):
ld2 = LunarDate(2018, 11, 23)
self.assertEqual('二〇一八/冬/廿三', ld2.strftime('%Y/%M/%D'))
self.assertEqual('二〇一八/十一/廿三', ld2.strftime('%Y/%N/%D'))
+ self.assertEqual('廿三', ld2.strftime('%F'))
ld3 = LunarDate(2017, 6, 3, 1)
self.assertEqual('61', ld3.strftime('%m%l'))
@@ -143,6 +144,12 @@ class FormatterTestCase(unittest.TestCase):
ld = LunarDate(2020, 3, 23)
self.assertEqual('tem:-', ld.strftime('tem:%t'))
+ def test_cn_calendar_day(self):
+ ld = LunarDate(2017, 6, 1, 1)
+ self.assertEqual('闰六', ld.strftime('%F'))
+ ld1 = LunarDate(2017, 11, 1, 0)
+ self.assertEqual('冬月', ld1.strftime('%F'))
+
class LCalendarTestCase(unittest.TestCase):
def test_ndays(self):
|
农历:LunarDate.cn_day_calendar 计算错误%F 描述符缺少“月”后缀
## 问题类型
- [X] BUG
- [ ] 新功能
- [ ] 功能优化
## 问题
LunarDate.cn_day_calendar 计算错误,同时 '%F' 描述符计算错误。
## 代码
```python
from borax.calendars import LunarDate, LCalendars
print([LunarDate(year=2017, month=month, day=1, leap=leap).cn_day_calendar for month, days, leap in LCalendars.iter_year_month(2017)])
```
结果为
```
['正', '二', '三', '四', '五', '六', '六', '七', '八', '九', '十', '冬', '腊']
```
正确结果为
```
```
['正月', '二月', '三月', '四月', '五月', '六月', '闰六', '七月', '八月', '九月', '十月', '冬月', '腊月']
```
```
|
0.0
|
f9e51116e04eb9539e54e0db1e321b6e40200903
|
[
"tests/test_lunardate.py::FormatterTestCase::test_cn_calendar_day"
] |
[
"tests/test_lunardate.py::LunarDateTestCase::test_comparison",
"tests/test_lunardate.py::LunarDateTestCase::test_convert_datetime",
"tests/test_lunardate.py::LunarDateTestCase::test_create_date",
"tests/test_lunardate.py::LunarDateTestCase::test_create_specific_dates",
"tests/test_lunardate.py::LunarDateTestCase::test_immutable_feature",
"tests/test_lunardate.py::LunarDateTestCase::test_new_date",
"tests/test_lunardate.py::LunarDateTestCase::test_solar_and_lunar",
"tests/test_lunardate.py::LunarDateTestCase::test_term_ganzhi_feature",
"tests/test_lunardate.py::LunarDateTestCase::test_timedelta",
"tests/test_lunardate.py::PrivateMethodsTestCase::test_year_info",
"tests/test_lunardate.py::FormatterTestCase::test_term",
"tests/test_lunardate.py::FormatterTestCase::test_valid_format",
"tests/test_lunardate.py::LCalendarTestCase::test_delta",
"tests/test_lunardate.py::LCalendarTestCase::test_leap_check",
"tests/test_lunardate.py::LCalendarTestCase::test_ndays"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2020-11-19 01:24:37+00:00
|
mit
| 3,427 |
|
kinegratii__borax-23
|
diff --git a/borax/calendars/lunardate.py b/borax/calendars/lunardate.py
index b7adda7..6e37c33 100644
--- a/borax/calendars/lunardate.py
+++ b/borax/calendars/lunardate.py
@@ -352,9 +352,10 @@ class TextUtils:
def day_cn(day: int) -> str:
a, b = divmod(day, 10)
if b == 0: # 10,20,30
- b = 10
- if a == 1: # 10
- a = 0
+ if a == 1:
+ return TextUtils.TENS[0] + TextUtils.DAYS_CN[10]
+ else:
+ return TextUtils.DAYS_CN[a] + TextUtils.DAYS_CN[10]
return TextUtils.TENS[a] + TextUtils.DAYS_CN[b]
@staticmethod
|
kinegratii/borax
|
c7741cdfcd1b04476e2f140e86c96160227b1207
|
diff --git a/tests/test_lunardate.py b/tests/test_lunardate.py
index 86417c7..092c2c9 100644
--- a/tests/test_lunardate.py
+++ b/tests/test_lunardate.py
@@ -4,7 +4,22 @@ import datetime
import unittest
from datetime import date, timedelta
-from borax.calendars.lunardate import LunarDate, parse_year_days, LCalendars, InvalidLunarDateError
+from borax.calendars.lunardate import LunarDate, parse_year_days, LCalendars, InvalidLunarDateError, TextUtils
+
+
+class TextUtilsTestCase(unittest.TestCase):
+ def test_cn_day_text(self):
+ data = [
+ (1, '初一'),
+ (10, '初十'),
+ (14, '十四'),
+ (20, '二十'),
+ (23, '廿三'),
+ (30, '三十')
+ ]
+ for value, text in data:
+ with self.subTest(value=value, text=text):
+ self.assertEqual(text, TextUtils.day_cn(value))
class LunarDateTestCase(unittest.TestCase):
|
农历日“二十”“三十”中文名称错误
## 发现版本
v3.4.0
## 问题描述
“廿十”、“卅十” 是不正确的用法,因为“廿”、“卅” 本身就是二十、三十的意思了,正确的应该为“二十”、“三十”。
## 代码示例
```python
from borax.calendars.lunardate import LunarDate, TextUtils
print(TextUtils.day_cn(20)) # “廿十”
ld = LunarDate(2020, 10, 20, 0)
print(ld.cn_day) # “廿十”
print(ld.cn_day_calendar) # “廿十”
print(ld.cn_str()) # “廿十”
```
## 建议方案
只需要修改 `TextUtils.day_cn` 逻辑即可,其他函数均是调用该函数。
|
0.0
|
c7741cdfcd1b04476e2f140e86c96160227b1207
|
[
"tests/test_lunardate.py::TextUtilsTestCase::test_cn_day_text"
] |
[
"tests/test_lunardate.py::LunarDateTestCase::test_comparison",
"tests/test_lunardate.py::LunarDateTestCase::test_convert_datetime",
"tests/test_lunardate.py::LunarDateTestCase::test_create_date",
"tests/test_lunardate.py::LunarDateTestCase::test_create_specific_dates",
"tests/test_lunardate.py::LunarDateTestCase::test_immutable_feature",
"tests/test_lunardate.py::LunarDateTestCase::test_new_date",
"tests/test_lunardate.py::LunarDateTestCase::test_solar_and_lunar",
"tests/test_lunardate.py::LunarDateTestCase::test_term_ganzhi_feature",
"tests/test_lunardate.py::LunarDateTestCase::test_timedelta",
"tests/test_lunardate.py::PrivateMethodsTestCase::test_year_info",
"tests/test_lunardate.py::FormatterTestCase::test_cn_calendar_day",
"tests/test_lunardate.py::FormatterTestCase::test_term",
"tests/test_lunardate.py::FormatterTestCase::test_valid_format",
"tests/test_lunardate.py::LCalendarTestCase::test_delta",
"tests/test_lunardate.py::LCalendarTestCase::test_leap_check",
"tests/test_lunardate.py::LCalendarTestCase::test_ndays"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2020-11-21 13:56:45+00:00
|
mit
| 3,428 |
|
kinnala__scikit-fem-1050
|
diff --git a/README.md b/README.md
index ad604d7b..05d8e302 100644
--- a/README.md
+++ b/README.md
@@ -212,6 +212,11 @@ with respect to documented and/or tested features.
### Unreleased
- Removed: Python 3.7 support
+- Added: `Mesh.load` supports new keyword arguments
+ `ignore_orientation=True` and `ignore_interior_facets=True` which
+ will both speed up the loading of larger three-dimensional meshes by
+ ignoring facet orientation and all tags not on the boundary,
+ respectively.
- Fixed: `MeshTet` uniform refine was reindexing subdomains incorrectly
## [8.1.0] - 2023-06-16
diff --git a/skfem/io/meshio.py b/skfem/io/meshio.py
index a058cfeb..b3ee2a78 100644
--- a/skfem/io/meshio.py
+++ b/skfem/io/meshio.py
@@ -50,7 +50,9 @@ INV_HEX_MAPPING = [HEX_MAPPING.index(i)
def from_meshio(m,
out=None,
int_data_to_sets=False,
- force_meshio_type=None):
+ force_meshio_type=None,
+ ignore_orientation=False,
+ ignore_interior_facets=False):
cells = m.cells_dict
meshio_type = None
@@ -126,37 +128,49 @@ def from_meshio(m,
}
sorted_facets = {k: [tuple(np.sort(f)) for f in v]
for k, v in oriented_facets.items()}
-
for k, v in oriented_facets.items():
- indices = []
- oris = []
- for i, f in enumerate(map(tuple, mtmp.facets.T)):
- if f in sorted_facets[k]:
- indices.append(i)
- ix = sorted_facets[k].index(f)
- facet = v[ix]
- t1, t2 = mtmp.f2t[:, i]
- if t2 == -1:
- # orientation on boundary is 0
- oris.append(0)
- continue
- if len(f) == 2:
- # rotate tangent to find normal
- tangent = mtmp.p[:, facet[1]] - mtmp.p[:, facet[0]]
- normal = np.array([-tangent[1], tangent[0]])
- elif len(f) == 3:
- # cross product to find normal
- tangent1 = mtmp.p[:, facet[1]] - mtmp.p[:, facet[0]]
- tangent2 = mtmp.p[:, facet[2]] - mtmp.p[:, facet[0]]
- normal = -np.cross(tangent1, tangent2)
- else:
- raise NotImplementedError
- # find another vector using node outside of boundary
- third = np.setdiff1d(mtmp.t[:, t1],
- np.array(f))[0]
- outplane = mtmp.p[:, f[0]] - mtmp.p[:, third]
- oris.append(1 if np.dot(normal, outplane) > 0 else 0)
- boundaries[k] = OrientedBoundary(indices, oris)
+ if ignore_orientation or ignore_interior_facets:
+ a = np.array(sorted_facets[k])
+ if ignore_interior_facets:
+ b = mtmp.facets[:, mtmp.boundary_facets()].T
+ else:
+ b = mtmp.facets.T
+ boundaries[k] = np.nonzero((a == b[:, None])
+ .all(axis=2)
+ .any(axis=1))[0]
+ else:
+ indices = []
+ oris = []
+ for i, f in enumerate(map(tuple, mtmp.facets.T)):
+ if f in sorted_facets[k]:
+ indices.append(i)
+ ix = sorted_facets[k].index(f)
+ facet = v[ix]
+ t1, t2 = mtmp.f2t[:, i]
+ if t2 == -1:
+ # orientation on boundary is 0
+ oris.append(0)
+ continue
+ if len(f) == 2:
+ # rotate tangent to find normal
+ tangent = (mtmp.p[:, facet[1]]
+ - mtmp.p[:, facet[0]])
+ normal = np.array([-tangent[1], tangent[0]])
+ elif len(f) == 3:
+ # cross product to find normal
+ tangent1 = (mtmp.p[:, facet[1]]
+ - mtmp.p[:, facet[0]])
+ tangent2 = (mtmp.p[:, facet[2]]
+ - mtmp.p[:, facet[0]])
+ normal = -np.cross(tangent1, tangent2)
+ else:
+ raise NotImplementedError
+ # find another vector using node outside of boundary
+ third = np.setdiff1d(mtmp.t[:, t1],
+ np.array(f))[0]
+ outplane = mtmp.p[:, f[0]] - mtmp.p[:, third]
+ oris.append(1 if np.dot(normal, outplane) > 0 else 0)
+ boundaries[k] = OrientedBoundary(indices, oris)
# MSH 2.2 tag parsing
if len(boundaries) == 0 and m.cell_data and m.field_data:
diff --git a/skfem/visuals/matplotlib.py b/skfem/visuals/matplotlib.py
index 1421a09e..4c7b49d5 100644
--- a/skfem/visuals/matplotlib.py
+++ b/skfem/visuals/matplotlib.py
@@ -1,3 +1,4 @@
+# type: ignore
"""Drawing meshes and solutions using matplotlib."""
from functools import singledispatch
|
kinnala/scikit-fem
|
29ac66cac6c60cbf9ed328d8976794ed1b343f49
|
diff --git a/tests/test_mesh.py b/tests/test_mesh.py
index 2fd3aeda..5f862a9a 100644
--- a/tests/test_mesh.py
+++ b/tests/test_mesh.py
@@ -571,7 +571,21 @@ def test_saveload_cycle_vtk(m):
MeshTet(),
]
)
-def test_saveload_cycle_tags(fmt, kwargs, m):
[email protected](
+ "ignore_orientation",
+ [
+ True,
+ False,
+ ]
+)
[email protected](
+ "ignore_interior_facets",
+ [
+ True,
+ False,
+ ]
+)
+def test_saveload_cycle_tags(fmt, kwargs, m, ignore_orientation, ignore_interior_facets):
m = (m
.refined(2)
@@ -582,7 +596,10 @@ def test_saveload_cycle_tags(fmt, kwargs, m):
with NamedTemporaryFile(suffix=fmt) as f:
m.save(f.name, point_data={'foo': m.p[0]}, **kwargs)
out = ['point_data', 'cells_dict']
- m2 = Mesh.load(f.name, out=out)
+ m2 = Mesh.load(f.name,
+ out=out,
+ ignore_orientation=ignore_orientation,
+ ignore_interior_facets=ignore_interior_facets)
assert_array_equal(m.p, m2.p)
|
slow to build meshes with labeled subdomains
# The problem, with labelled subdomains:
```python
gmsh.initialize()
try:
gmsh.option.setNumber("General.Verbosity", 3)
gmsh.option.setNumber("Mesh.MeshSizeFactor", .5)
gmsh.model.occ.add_box(0, 0, 0, 1, 1, 1)
gmsh.model.occ.synchronize()
for e in gmsh.model.getEntities():
if e[0] > 1:
name=f"{e[0]}{e[1]:02d}"
gmsh.model.add_physical_group(e[0], [e[1]], name=name)
gmsh.model.occ.synchronize()
gmsh.model.mesh.generate(_3D)
gmsh.write(str(mesh_file))
finally:
gmsh.clear()
gmsh.finalize()
%time mesh_data = meshio.read(mesh_file)
%time mesh = skfem.io.from_meshio(mesh_data)
```
```
CPU times: total: 31.2 ms
Wall time: 37 ms
CPU times: total: 3.45 s <-------------- 3 seconds on a trivial mesh!!
Wall time: 3.46 s
```
# Compare to the same mesh with no labels:
```python
gmsh.initialize()
try:
gmsh.option.setNumber("General.Verbosity", 3)
gmsh.option.setNumber("Mesh.MeshSizeFactor", .5)
gmsh.model.occ.add_box(0, 0, 0, 1, 1, 1)
gmsh.model.occ.synchronize()
# for e in gmsh.model.getEntities():
# if e[0] > 1:
# name=f"{e[0]}{e[1]:02d}"
# gmsh.model.add_physical_group(e[0], [e[1]], name=name)
gmsh.model.occ.synchronize()
gmsh.model.mesh.generate(_3D)
gmsh.write(str(mesh_file))
finally:
gmsh.clear()
gmsh.finalize()
%time mesh_data = meshio.read(mesh_file)
%time mesh = skfem.io.from_meshio(mesh_data)
```
```
CPU times: total: 31.2 ms
Wall time: 39 ms
CPU times: total: 0 ns <---------------------- 0 seconds when no labels present
Wall time: 0 ns
```
Edit: Attached mesh files.
[meshes.zip](https://github.com/kinnala/scikit-fem/files/12303340/meshes.zip)
|
0.0
|
29ac66cac6c60cbf9ed328d8976794ed1b343f49
|
[
"tests/test_mesh.py::test_saveload_cycle_tags[True-True-m0-.msh-kwargs0]",
"tests/test_mesh.py::test_saveload_cycle_tags[True-True-m0-.msh-kwargs1]",
"tests/test_mesh.py::test_saveload_cycle_tags[True-True-m0-.vtk-kwargs2]",
"tests/test_mesh.py::test_saveload_cycle_tags[True-True-m0-.vtu-kwargs3]",
"tests/test_mesh.py::test_saveload_cycle_tags[True-True-m1-.msh-kwargs0]",
"tests/test_mesh.py::test_saveload_cycle_tags[True-True-m1-.msh-kwargs1]",
"tests/test_mesh.py::test_saveload_cycle_tags[True-True-m1-.vtk-kwargs2]",
"tests/test_mesh.py::test_saveload_cycle_tags[True-True-m1-.vtu-kwargs3]",
"tests/test_mesh.py::test_saveload_cycle_tags[True-True-m2-.msh-kwargs0]",
"tests/test_mesh.py::test_saveload_cycle_tags[True-True-m2-.msh-kwargs1]",
"tests/test_mesh.py::test_saveload_cycle_tags[True-True-m2-.vtk-kwargs2]",
"tests/test_mesh.py::test_saveload_cycle_tags[True-True-m2-.vtu-kwargs3]",
"tests/test_mesh.py::test_saveload_cycle_tags[True-True-m3-.msh-kwargs0]",
"tests/test_mesh.py::test_saveload_cycle_tags[True-True-m3-.msh-kwargs1]",
"tests/test_mesh.py::test_saveload_cycle_tags[True-True-m3-.vtk-kwargs2]",
"tests/test_mesh.py::test_saveload_cycle_tags[True-True-m3-.vtu-kwargs3]",
"tests/test_mesh.py::test_saveload_cycle_tags[True-False-m0-.msh-kwargs0]",
"tests/test_mesh.py::test_saveload_cycle_tags[True-False-m0-.msh-kwargs1]",
"tests/test_mesh.py::test_saveload_cycle_tags[True-False-m0-.vtk-kwargs2]",
"tests/test_mesh.py::test_saveload_cycle_tags[True-False-m0-.vtu-kwargs3]",
"tests/test_mesh.py::test_saveload_cycle_tags[True-False-m1-.msh-kwargs0]",
"tests/test_mesh.py::test_saveload_cycle_tags[True-False-m1-.msh-kwargs1]",
"tests/test_mesh.py::test_saveload_cycle_tags[True-False-m1-.vtk-kwargs2]",
"tests/test_mesh.py::test_saveload_cycle_tags[True-False-m1-.vtu-kwargs3]",
"tests/test_mesh.py::test_saveload_cycle_tags[True-False-m2-.msh-kwargs0]",
"tests/test_mesh.py::test_saveload_cycle_tags[True-False-m2-.msh-kwargs1]",
"tests/test_mesh.py::test_saveload_cycle_tags[True-False-m2-.vtk-kwargs2]",
"tests/test_mesh.py::test_saveload_cycle_tags[True-False-m2-.vtu-kwargs3]",
"tests/test_mesh.py::test_saveload_cycle_tags[True-False-m3-.msh-kwargs0]",
"tests/test_mesh.py::test_saveload_cycle_tags[True-False-m3-.msh-kwargs1]",
"tests/test_mesh.py::test_saveload_cycle_tags[True-False-m3-.vtk-kwargs2]",
"tests/test_mesh.py::test_saveload_cycle_tags[True-False-m3-.vtu-kwargs3]",
"tests/test_mesh.py::test_saveload_cycle_tags[False-True-m0-.msh-kwargs0]",
"tests/test_mesh.py::test_saveload_cycle_tags[False-True-m0-.msh-kwargs1]",
"tests/test_mesh.py::test_saveload_cycle_tags[False-True-m0-.vtk-kwargs2]",
"tests/test_mesh.py::test_saveload_cycle_tags[False-True-m0-.vtu-kwargs3]",
"tests/test_mesh.py::test_saveload_cycle_tags[False-True-m1-.msh-kwargs0]",
"tests/test_mesh.py::test_saveload_cycle_tags[False-True-m1-.msh-kwargs1]",
"tests/test_mesh.py::test_saveload_cycle_tags[False-True-m1-.vtk-kwargs2]",
"tests/test_mesh.py::test_saveload_cycle_tags[False-True-m1-.vtu-kwargs3]",
"tests/test_mesh.py::test_saveload_cycle_tags[False-True-m2-.msh-kwargs0]",
"tests/test_mesh.py::test_saveload_cycle_tags[False-True-m2-.msh-kwargs1]",
"tests/test_mesh.py::test_saveload_cycle_tags[False-True-m2-.vtk-kwargs2]",
"tests/test_mesh.py::test_saveload_cycle_tags[False-True-m2-.vtu-kwargs3]",
"tests/test_mesh.py::test_saveload_cycle_tags[False-True-m3-.msh-kwargs0]",
"tests/test_mesh.py::test_saveload_cycle_tags[False-True-m3-.msh-kwargs1]",
"tests/test_mesh.py::test_saveload_cycle_tags[False-True-m3-.vtk-kwargs2]",
"tests/test_mesh.py::test_saveload_cycle_tags[False-True-m3-.vtu-kwargs3]",
"tests/test_mesh.py::test_saveload_cycle_tags[False-False-m0-.msh-kwargs0]",
"tests/test_mesh.py::test_saveload_cycle_tags[False-False-m0-.msh-kwargs1]",
"tests/test_mesh.py::test_saveload_cycle_tags[False-False-m0-.vtk-kwargs2]",
"tests/test_mesh.py::test_saveload_cycle_tags[False-False-m0-.vtu-kwargs3]",
"tests/test_mesh.py::test_saveload_cycle_tags[False-False-m1-.msh-kwargs0]",
"tests/test_mesh.py::test_saveload_cycle_tags[False-False-m1-.msh-kwargs1]",
"tests/test_mesh.py::test_saveload_cycle_tags[False-False-m1-.vtk-kwargs2]",
"tests/test_mesh.py::test_saveload_cycle_tags[False-False-m1-.vtu-kwargs3]",
"tests/test_mesh.py::test_saveload_cycle_tags[False-False-m2-.msh-kwargs0]",
"tests/test_mesh.py::test_saveload_cycle_tags[False-False-m2-.msh-kwargs1]",
"tests/test_mesh.py::test_saveload_cycle_tags[False-False-m2-.vtk-kwargs2]",
"tests/test_mesh.py::test_saveload_cycle_tags[False-False-m2-.vtu-kwargs3]",
"tests/test_mesh.py::test_saveload_cycle_tags[False-False-m3-.msh-kwargs0]",
"tests/test_mesh.py::test_saveload_cycle_tags[False-False-m3-.msh-kwargs1]",
"tests/test_mesh.py::test_saveload_cycle_tags[False-False-m3-.vtk-kwargs2]",
"tests/test_mesh.py::test_saveload_cycle_tags[False-False-m3-.vtu-kwargs3]"
] |
[
"tests/test_mesh.py::MeshTests::runTest",
"tests/test_mesh.py::Loading::runTest",
"tests/test_mesh.py::SerializeUnserializeCycle::runTest",
"tests/test_mesh.py::TestBoundaryEdges::runTest",
"tests/test_mesh.py::TestBoundaryEdges2::runTest",
"tests/test_mesh.py::TestMeshAddition::runTest",
"tests/test_mesh.py::TestMeshQuadSplit::runTest",
"tests/test_mesh.py::TestAdaptiveSplitting1D::runTest",
"tests/test_mesh.py::TestAdaptiveSplitting2D::runTest",
"tests/test_mesh.py::test_adaptive_splitting_3d",
"tests/test_mesh.py::test_adaptive_splitting_3d_0",
"tests/test_mesh.py::test_adaptive_splitting_3d_1",
"tests/test_mesh.py::test_adaptive_splitting_3d_2",
"tests/test_mesh.py::test_adaptive_splitting_3d_3",
"tests/test_mesh.py::test_adaptive_splitting_3d_4",
"tests/test_mesh.py::test_adaptive_splitting_3d_5",
"tests/test_mesh.py::test_adaptive_random_splitting[m0-0]",
"tests/test_mesh.py::test_adaptive_random_splitting[m1-1]",
"tests/test_mesh.py::test_adaptive_random_splitting[m2-2]",
"tests/test_mesh.py::test_adaptive_random_splitting[m3-3]",
"tests/test_mesh.py::test_adaptive_random_splitting[m4-10]",
"tests/test_mesh.py::TestFinder1DRefined::runTest",
"tests/test_mesh.py::TestFinder1DLinspaced::runTest",
"tests/test_mesh.py::test_smoothed[m0]",
"tests/test_mesh.py::test_smoothed[m1]",
"tests/test_mesh.py::test_smoothed[m2]",
"tests/test_mesh.py::test_smoothed[m3]",
"tests/test_mesh.py::test_oriented[m0]",
"tests/test_mesh.py::test_oriented[m1]",
"tests/test_mesh.py::test_finder_simplex[m0-0]",
"tests/test_mesh.py::test_finder_simplex[m1-1]",
"tests/test_mesh.py::test_finder_simplex[m2-2]",
"tests/test_mesh.py::test_finder_simplex[m3-0]",
"tests/test_mesh.py::test_finder_simplex[m4-1]",
"tests/test_mesh.py::test_finder_simplex[m5-2]",
"tests/test_mesh.py::test_finder_simplex[m6-10]",
"tests/test_mesh.py::test_meshio_cycle[m0]",
"tests/test_mesh.py::test_meshio_cycle[m1]",
"tests/test_mesh.py::test_meshio_cycle[m2]",
"tests/test_mesh.py::test_meshio_cycle[m3]",
"tests/test_mesh.py::test_meshio_cycle[m4]",
"tests/test_mesh.py::test_meshio_cycle[m5]",
"tests/test_mesh.py::test_meshio_cycle[m6]",
"tests/test_mesh.py::test_meshio_cycle[m7]",
"tests/test_mesh.py::test_meshio_cycle[m8]",
"tests/test_mesh.py::test_meshio_cycle_boundaries[m0-True]",
"tests/test_mesh.py::test_meshio_cycle_boundaries[m0-False]",
"tests/test_mesh.py::test_meshio_cycle_boundaries[m1-True]",
"tests/test_mesh.py::test_meshio_cycle_boundaries[m1-False]",
"tests/test_mesh.py::test_meshio_cycle_boundaries[m2-True]",
"tests/test_mesh.py::test_meshio_cycle_boundaries[m2-False]",
"tests/test_mesh.py::test_meshio_cycle_boundaries[m3-True]",
"tests/test_mesh.py::test_meshio_cycle_boundaries[m3-False]",
"tests/test_mesh.py::test_meshio_cycle_boundaries[m4-True]",
"tests/test_mesh.py::test_meshio_cycle_boundaries[m4-False]",
"tests/test_mesh.py::test_meshio_cycle_boundaries[m5-True]",
"tests/test_mesh.py::test_meshio_cycle_boundaries[m5-False]",
"tests/test_mesh.py::test_meshio_cycle_boundaries[m6-True]",
"tests/test_mesh.py::test_meshio_cycle_boundaries[m6-False]",
"tests/test_mesh.py::test_meshio_cycle_boundaries[m7-True]",
"tests/test_mesh.py::test_meshio_cycle_boundaries[m7-False]",
"tests/test_mesh.py::test_meshio_cycle_subdomains[m0]",
"tests/test_mesh.py::test_meshio_cycle_subdomains[m1]",
"tests/test_mesh.py::test_meshio_cycle_subdomains[m2]",
"tests/test_mesh.py::test_meshio_cycle_subdomains[m3]",
"tests/test_mesh.py::test_saveload_cycle_vtk[m0]",
"tests/test_mesh.py::test_saveload_cycle_vtk[m1]",
"tests/test_mesh.py::test_saveload_cycle_vtk[m2]",
"tests/test_mesh.py::test_saveload_cycle_vtk[m3]",
"tests/test_mesh.py::test_periodic_failure",
"tests/test_mesh.py::test_init_refdom[MeshTri1]",
"tests/test_mesh.py::test_init_refdom[MeshQuad1]",
"tests/test_mesh.py::test_init_refdom[MeshHex1]",
"tests/test_mesh.py::test_init_refdom[MeshTet1]",
"tests/test_mesh.py::test_init_refdom[MeshLine1]",
"tests/test_mesh.py::test_refine_boundaries[MeshTri1]",
"tests/test_mesh.py::test_refine_boundaries[MeshQuad1]",
"tests/test_mesh.py::test_refine_boundaries[MeshLine1]",
"tests/test_mesh.py::test_point_outside_mesh",
"tests/test_mesh.py::test_refine_subdomains_adaptive",
"tests/test_mesh.py::test_refine_subdomains_uniform",
"tests/test_mesh.py::test_refine_subdomains_uniform_tets",
"tests/test_mesh.py::test_refine_subdomains_uniform_hexs"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-08-17 09:31:28+00:00
|
bsd-3-clause
| 3,429 |
|
kinnala__scikit-fem-622
|
diff --git a/skfem/utils.py b/skfem/utils.py
index 315b5a80..e31e68af 100644
--- a/skfem/utils.py
+++ b/skfem/utils.py
@@ -22,12 +22,10 @@ from skfem.element import ElementVector
Solution = Union[ndarray, Tuple[ndarray, ndarray]]
LinearSolver = Callable[..., ndarray]
EigenSolver = Callable[..., Tuple[ndarray, ndarray]]
-EnforcedSystem = Union[spmatrix,
- Tuple[spmatrix, ndarray],
- Tuple[spmatrix, spmatrix]]
-CondensedSystem = Union[spmatrix,
- Tuple[spmatrix, ndarray],
- Tuple[spmatrix, spmatrix],
+LinearSystem = Union[spmatrix,
+ Tuple[spmatrix, ndarray],
+ Tuple[spmatrix, spmatrix]]
+CondensedSystem = Union[LinearSystem,
Tuple[spmatrix, ndarray, ndarray],
Tuple[spmatrix, ndarray, ndarray, ndarray],
Tuple[spmatrix, spmatrix, ndarray, ndarray]]
@@ -248,7 +246,7 @@ def _flatten_dofs(S: Optional[DofsCollection]) -> Optional[ndarray]:
def _init_bc(A: spmatrix,
- b: Optional[ndarray] = None,
+ b: Optional[Union[ndarray, spmatrix]] = None,
x: Optional[ndarray] = None,
I: Optional[DofsCollection] = None,
D: Optional[DofsCollection] = None) -> Tuple[Optional[ndarray],
@@ -284,7 +282,8 @@ def enforce(A: spmatrix,
x: Optional[ndarray] = None,
I: Optional[DofsCollection] = None,
D: Optional[DofsCollection] = None,
- diag: float = 1.) -> EnforcedSystem:
+ diag: float = 1.,
+ overwrite: bool = False) -> LinearSystem:
r"""Enforce degrees-of-freedom of a linear system.
.. note::
@@ -307,39 +306,46 @@ def enforce(A: spmatrix,
D
Specify either this or ``I``: The set of degree-of-freedom indices to
enforce (rows/diagonal set to zero/one).
+ overwrite
+ Optionally, the original system is both modified (for performance) and
+ returned (for compatibility with :func:`skfem.utils.solve`). By
+ default, ``False``.
Returns
-------
- EnforcedSystem
+ LinearSystem
A linear system with the enforced rows/diagonals set to zero/one.
"""
b, x, I, D = _init_bc(A, b, x, I, D)
+ Aout = A if overwrite else A.copy()
+
# set rows on lhs to zero
- start = A.indptr[D]
- stop = A.indptr[D + 1]
+ start = Aout.indptr[D]
+ stop = Aout.indptr[D + 1]
count = stop - start
idx = np.ones(count.sum(), dtype=np.int64)
idx[np.cumsum(count)[:-1]] -= count[:-1]
idx = np.repeat(start, count) + np.cumsum(idx) - 1
- A.data[idx] = 0.
+ Aout.data[idx] = 0.
# set diagonal value
- d = A.diagonal()
+ d = Aout.diagonal()
d[D] = diag
- A.setdiag(d)
+ Aout.setdiag(d)
if b is not None:
if isinstance(b, spmatrix):
- # eigenvalue problem
- b = enforce(b, D=D, diag=0.)
+ # mass matrix (eigen- or initial value problem)
+ bout = enforce(b, D=D, diag=0., overwrite=overwrite)
else:
# set rhs to the given value
- b[D] = x[D]
- return A, b
+ bout = b if overwrite else b.copy()
+ bout[D] = x[D]
+ return Aout, bout
- return A
+ return Aout
def condense(A: spmatrix,
|
kinnala/scikit-fem
|
13f5630bd0077a1484a6ee392c219b4570dcb591
|
diff --git a/tests/test_utils.py b/tests/test_utils.py
index 48dcb86a..f5c11c27 100644
--- a/tests/test_utils.py
+++ b/tests/test_utils.py
@@ -44,10 +44,13 @@ class TestEnforce(TestCase):
M = mass.assemble(basis)
D = m.boundary_nodes()
- assert_almost_equal(enforce(A, D=D).todense(), np.eye(A.shape[0]))
- assert_almost_equal(enforce(M, D=D, diag=0.).todense(),
+ assert_almost_equal(enforce(A, D=D).toarray(), np.eye(A.shape[0]))
+ assert_almost_equal(enforce(M, D=D, diag=0.).toarray(),
np.zeros(M.shape))
+ enforce(A, D=D, overwrite=True)
+ assert_almost_equal(A.toarray(), np.eye(A.shape[0]))
+
if __name__ == '__main__':
unittest.main()
|
overwrite_a: bool = False
In investigating the behaviour of the new #596 `skfem.utils.enforce` function [at the end of last week](https://github.com/kinnala/scikit-fem/issues/591#issuecomment-816408235), I wasted a couple of hours tracking down discrepancies with condensing and penalizing Dirichlet conditions because of not realizing that in a call like
```python
L0, M0 = enforce(L, M, D=basis.find_dofs())
```
`L` and `M` would also be mutated, though I do now read that
https://github.com/kinnala/scikit-fem/blob/13f5630bd0077a1484a6ee392c219b4570dcb591/skfem/utils.py#L290-L293
I had been assuming that as discussed in #591 on [2021-03-25](https://github.com/kinnala/scikit-fem/issues/591#issuecomment-806409380)
> it should have the same signature as `condense`
I understand that ([ibid](https://github.com/kinnala/scikit-fem/issues/591#issue-840495893))
> Advantages of this approach include the fact that neither `A` nor `b` need to be rewritten in memory.
but I don't think any of the NumPy and SciPy routines that scikit-fem is built on mutate their arguments, and other functions from those libraries that do, for example, the dense [`scipy.linalg.solve`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.solve.html#scipy.linalg.solve) only does so if `overwrite_a` or `overwrite_b` is `True` and both are `False` by default.
I think it does happen fairly often that an assembled finite element matrix is reused for the different things. Of course mutation can be avoided in such cases by copying first, but only if one realizes that there is a threat of mutation. Would it be safer to introduce overwrite-flags that are `False` by default?
I had a quick look at the implementation of `skfem.utils.enforce` and it doesn't look as though this would be too intrusive.
https://github.com/kinnala/scikit-fem/blob/13f5630bd0077a1484a6ee392c219b4570dcb591/skfem/utils.py#L326-L331
I think the assembly of `idx` and `d` would be the same but one only modifies `A` if `overwrite_A` and otherwise returns a fresh matrix with the condition enforced.
|
0.0
|
13f5630bd0077a1484a6ee392c219b4570dcb591
|
[
"tests/test_utils.py::TestEnforce::runTest"
] |
[
"tests/test_utils.py::InitializeScalarField::runTest"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_issue_reference",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-04-12 11:38:07+00:00
|
bsd-3-clause
| 3,430 |
|
kinnala__scikit-fem-634
|
diff --git a/skfem/mesh/mesh.py b/skfem/mesh/mesh.py
index 926eada4..8a275483 100644
--- a/skfem/mesh/mesh.py
+++ b/skfem/mesh/mesh.py
@@ -1315,13 +1315,15 @@ class MeshLine1(Mesh):
return np.max(np.abs(self.p[0, self.t[1]] - self.p[0, self.t[0]]))
def element_finder(self, mapping=None):
- ix = np.argsort(self.p)
+ ix = np.argsort(self.p[0])
+ maxt = self.t[np.argmax(self.p[0, self.t], 0),
+ np.arange(self.t.shape[1])]
def finder(x):
- maxix = (x == np.max(self.p))
- x[maxix] = x[maxix] - 1e-10 # special case in np.digitize
- return np.argmax(np.digitize(x, self.p[0, ix[0]])[:, None]
- == self.t[1], axis=1)
+ xin = x.copy() # bring endpoint inside for np.digitize
+ xin[x == self.p[0, ix[-1]]] = self.p[0, ix[-2:]].mean()
+ return np.nonzero(ix[np.digitize(xin, self.p[0, ix])][:, None]
+ == maxt)[1]
return finder
|
kinnala/scikit-fem
|
13b5d697d41d96417abb3288fa524bb4f02290b9
|
diff --git a/tests/test_mesh.py b/tests/test_mesh.py
index 0b3e8c0b..adc57791 100644
--- a/tests/test_mesh.py
+++ b/tests/test_mesh.py
@@ -1,4 +1,4 @@
-import unittest
+from unittest import TestCase
from pathlib import Path
import numpy as np
@@ -6,7 +6,7 @@ import numpy as np
from skfem.mesh import Mesh, MeshHex, MeshLine, MeshQuad, MeshTet, MeshTri
-class MeshTests(unittest.TestCase):
+class MeshTests(TestCase):
"""Test some of the methods in mesh classes
that are not tested elsewhere."""
@@ -29,7 +29,7 @@ class MeshTests(unittest.TestCase):
self.assertEqual(len(m.facets_satisfying(lambda x: x[0] == 0.5)), 1)
-class FaultyInputs(unittest.TestCase):
+class FaultyInputs(TestCase):
"""Check that faulty meshes are detected by the constructors."""
def _runTest(self): # disabled
@@ -51,7 +51,7 @@ class FaultyInputs(unittest.TestCase):
np.array([[0.0, 1.0, 2.0], [1.0, 2.0, 3.0]]).T)
-class Loading(unittest.TestCase):
+class Loading(TestCase):
"""Check that Mesh.load works properly."""
def runTest(self):
@@ -73,7 +73,7 @@ class Loading(unittest.TestCase):
== m.facets_satisfying(lambda x: x[0] == 1)).all())
-class SaveLoadCycle(unittest.TestCase):
+class SaveLoadCycle(TestCase):
"""Save to temporary file and check import/export cycles."""
cls = MeshTet
@@ -93,7 +93,7 @@ class SaveLoadCycleHex(SaveLoadCycle):
cls = MeshHex
-class SerializeUnserializeCycle(unittest.TestCase):
+class SerializeUnserializeCycle(TestCase):
"""Check to_dict/initialize cycles."""
clss = [MeshTet,
@@ -116,7 +116,7 @@ class SerializeUnserializeCycle(unittest.TestCase):
self.assertTrue((m.subdomains[k] == M.subdomains[k]).all())
-class TestBoundaryEdges(unittest.TestCase):
+class TestBoundaryEdges(TestCase):
def runTest(self):
m = MeshTet()
@@ -129,7 +129,7 @@ class TestBoundaryEdges(unittest.TestCase):
self.assertTrue(len(m.refined().boundary_edges()) == 72)
-class TestBoundaryEdges2(unittest.TestCase):
+class TestBoundaryEdges2(TestCase):
def runTest(self):
m = MeshHex()
@@ -142,7 +142,7 @@ class TestBoundaryEdges2(unittest.TestCase):
self.assertEqual(len(m.refined().boundary_edges()), 48)
-class TestMeshAddition(unittest.TestCase):
+class TestMeshAddition(TestCase):
def runTest(self):
m = MeshTri()
@@ -152,7 +152,7 @@ class TestMeshAddition(unittest.TestCase):
self.assertTrue(mesh.t.shape[1] == 4)
-class TestMeshQuadSplit(unittest.TestCase):
+class TestMeshQuadSplit(TestCase):
def runTest(self):
from docs.examples.ex17 import mesh
@@ -178,7 +178,7 @@ class TestMeshQuadSplit(unittest.TestCase):
for m in [mesh, mesh_tri]])
-class TestAdaptiveSplitting1D(unittest.TestCase):
+class TestAdaptiveSplitting1D(TestCase):
def runTest(self):
@@ -194,7 +194,7 @@ class TestAdaptiveSplitting1D(unittest.TestCase):
self.assertEqual(prev_p_size, m.p.shape[1] - 1)
-class TestAdaptiveSplitting2D(unittest.TestCase):
+class TestAdaptiveSplitting2D(TestCase):
def runTest(self):
@@ -213,7 +213,7 @@ class TestAdaptiveSplitting2D(unittest.TestCase):
self.assertEqual(prev_p_size, m.p.shape[1] - 3)
-class TestMirrored(unittest.TestCase):
+class TestMirrored(TestCase):
def runTest(self):
@@ -227,5 +227,27 @@ class TestMirrored(unittest.TestCase):
self.assertEqual(m.nelements, 20)
+class TestFinder1DRefined(TestCase):
+
+ def runTest(self):
+
+ for itr in range(5):
+ finder = MeshLine().refined(itr).element_finder()
+ self.assertEqual(finder(np.array([0.001]))[0], 0)
+ self.assertEqual(finder(np.array([0.999]))[0], 2 ** itr - 1)
+
+
+class TestFinder1DLinspaced(TestCase):
+
+ def runTest(self):
+
+ for itr in range(5):
+ finder = (
+ MeshLine(np.linspace(0, 1, 2 ** itr + 1)).element_finder()
+ )
+ self.assertEqual(finder(np.array([0.999]))[0], 2 ** itr - 1)
+ self.assertEqual(finder(np.array([0.001]))[0], 0)
+
+
if __name__ == '__main__':
- unittest.main()
+ main()
|
MeshLine.refine
While working on the point source #632, trouble was encountered with `MeshLine().refined()` and this was traced to `element_finder`:
```python
>>> m = MeshLine().refined()
>>> m.element_finder()(np.array([.7]))
array([0])
>>> MeshLine(m.p[0]).element_finder()(np.array([.7]))
array([1])
```
I'm not sure which of these is right. I mean the first is wrong since 0.7 is definitely in the second element, but I'm not sure about the second. Are the points passed to the constructed assumed increasing?
|
0.0
|
13b5d697d41d96417abb3288fa524bb4f02290b9
|
[
"tests/test_mesh.py::TestFinder1DRefined::runTest"
] |
[
"tests/test_mesh.py::MeshTests::runTest",
"tests/test_mesh.py::Loading::runTest",
"tests/test_mesh.py::SaveLoadCycle::runTest",
"tests/test_mesh.py::SaveLoadCycleHex::runTest",
"tests/test_mesh.py::SerializeUnserializeCycle::runTest",
"tests/test_mesh.py::TestBoundaryEdges::runTest",
"tests/test_mesh.py::TestBoundaryEdges2::runTest",
"tests/test_mesh.py::TestMeshAddition::runTest",
"tests/test_mesh.py::TestMeshQuadSplit::runTest",
"tests/test_mesh.py::TestAdaptiveSplitting1D::runTest",
"tests/test_mesh.py::TestAdaptiveSplitting2D::runTest",
"tests/test_mesh.py::TestFinder1DLinspaced::runTest"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2021-04-22 07:10:51+00:00
|
bsd-3-clause
| 3,431 |
|
kinnala__scikit-fem-637
|
diff --git a/README.md b/README.md
index 1c4ad3ae..4f0400a4 100644
--- a/README.md
+++ b/README.md
@@ -212,6 +212,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Unreleased
+- Added: `utils.penalize`, an alternative to `condense` and `enforce` for
+ essential boundary conditions
- Added: `InteriorBasis.point_source`, with `ex38`
- Fixed: `MeshLine1.element_finder`
diff --git a/docs/examples/ex19.py b/docs/examples/ex19.py
index 1440373c..1777fd74 100644
--- a/docs/examples/ex19.py
+++ b/docs/examples/ex19.py
@@ -63,33 +63,21 @@ M = asm(mass, basis)
dt = .01
print('dt =', dt)
theta = 0.5 # Crank–Nicolson
-A = M + theta * L * dt
-B = M - (1 - theta) * L * dt
+L0, M0 = penalize(L, M, D=basis.find_dofs())
+A = M0 + theta * L0 * dt
+B = M0 - (1 - theta) * L0 * dt
-boundary = basis.find_dofs()
-interior = basis.complement_dofs(boundary)
-
-# transpose as splu prefers CSC
-backsolve = splu(condense(A, D=boundary, expand=False).T).solve
+backsolve = splu(A.T).solve # .T as splu prefers CSC
u_init = (np.cos(np.pi * mesh.p[0, :] / 2 / halfwidth[0])
* np.cos(np.pi * mesh.p[1, :] / 2 / halfwidth[1]))
-def step(t: float,
- u: np.ndarray) -> Tuple[float, np.ndarray]:
- u_new = np.zeros_like(u) # zero Dirichlet conditions
- _, b1 = condense(csr_matrix(A.shape), # ignore condensed matrix
- B @ u, u_new, D=boundary, expand=False)
- u_new[interior] = backsolve(b1)
- return t + dt, u_new
-
-
def evolve(t: float,
u: np.ndarray) -> Iterator[Tuple[float, np.ndarray]]:
while np.linalg.norm(u, np.inf) > 2**-3:
- t, u = step(t, u)
+ t, u = t + dt, backsolve(B @ u)
yield t, u
diff --git a/skfem/__init__.py b/skfem/__init__.py
index 60af8049..5cad2124 100644
--- a/skfem/__init__.py
+++ b/skfem/__init__.py
@@ -20,6 +20,7 @@ __all__ = all_mesh + all_assembly + all_element + [ # noqa
'build_pc_diag',
'condense',
'enforce',
+ 'penalize',
'project',
'projection',
'solve',
diff --git a/skfem/utils.py b/skfem/utils.py
index e31e68af..8c5343a1 100644
--- a/skfem/utils.py
+++ b/skfem/utils.py
@@ -288,8 +288,9 @@ def enforce(A: spmatrix,
.. note::
- The original system is both modified (for performance) and returned
- (for compatibility with :func:`skfem.utils.solve`).
+ The original system is both returned
+ (for compatibility with :func:`skfem.utils.solve`) and optionally (if
+ `overwrite`) modified (for performance).
Parameters
----------
@@ -348,6 +349,65 @@ def enforce(A: spmatrix,
return Aout
+def penalize(A: spmatrix,
+ b: Optional[Union[ndarray, spmatrix]] = None,
+ x: Optional[ndarray] = None,
+ I: Optional[DofsCollection] = None,
+ D: Optional[DofsCollection] = None,
+ epsilon: Optional[float] = None,
+ overwrite: bool = False) -> LinearSystem:
+ r"""Penalize degrees-of-freedom of a linear system.
+
+ Parameters
+ ----------
+ A
+ The system matrix
+ b
+ Optionally, the right hand side vector.
+ x
+ The values of the penalized degrees-of-freedom. If not given, assumed
+ to be zero.
+ I
+ Specify either this or ``D``: The set of degree-of-freedom indices to
+ solve for.
+ D
+ Specify either this or ``I``: The set of degree-of-freedom indices to
+ enforce (rows/diagonal set to zero/one).
+ epsilon
+ Very small value, the reciprocal of which penalizes deviations from
+ the Dirichlet condition
+ overwrite
+ Optionally, the original system is both modified (for performance) and
+ returned (for compatibility with :func:`skfem.utils.solve`). By
+ default, ``False``.
+
+ Returns
+ -------
+ LinearSystem
+ A linear system with the penalized diagonal and RHS entries set to
+ very large values, 1/epsilon and x/epsilon, respectively.
+
+ """
+ b, x, I, D = _init_bc(A, b, x, I, D)
+
+ Aout = A if overwrite else A.copy()
+
+ d = Aout.diagonal()
+ if epsilon is None:
+ epsilon = 1e-10 / np.linalg.norm(d[D], np.inf)
+ d[D] = 1/epsilon
+ Aout.setdiag(d)
+
+ if b is None:
+ return Aout
+
+ bout = b if overwrite else b.copy()
+ # Nothing needs doing for mass matrix, but RHS vector needs penalty factor
+ if not isinstance(b, spmatrix):
+ bout[D] = x[D] / epsilon
+ return Aout, bout
+
+
def condense(A: spmatrix,
b: Optional[Union[ndarray, spmatrix]] = None,
x: Optional[ndarray] = None,
|
kinnala/scikit-fem
|
4210dfc9eb4f9a35e69f4c5972e59636e384b4f4
|
diff --git a/tests/test_manufactured.py b/tests/test_manufactured.py
index 0eeb4c4a..1e0a90d2 100644
--- a/tests/test_manufactured.py
+++ b/tests/test_manufactured.py
@@ -1,8 +1,11 @@
"""Solve problems that have manufactured solutions."""
+from skfem.utils import penalize
from unittest import TestCase
from pathlib import Path
+import pytest
+
import numpy as np
from skfem import (LinearForm, Functional, asm, condense, solve, projection,
enforce)
@@ -283,12 +286,6 @@ class SolveCirclePoissonTet(SolveCirclePoisson):
return self.mesh_type.init_ball().scaled(0.5)
-class SolveCirclePoissonTet2(SolveCirclePoissonTet):
-
- mesh_type = MeshTet2
- element_type = ElementTetP2
-
-
class SolveCirclePoissonTet2(SolveCirclePoisson):
mesh_type = MeshTet2
@@ -297,49 +294,47 @@ class SolveCirclePoissonTet2(SolveCirclePoisson):
maxval = 0.0405901240018571
-class SolveInhomogeneousLaplace(TestCase):
[email protected](
+ "mesh_elem", [(MeshTri, ElementTriP2()), (MeshQuad, ElementQuad2())]
+)
[email protected]("impose", [enforce, penalize])
+def test_solving_inhomogeneous_laplace(mesh_elem, impose):
"""Adapted from example 14."""
- mesh = MeshTri
- elem = ElementTriP2()
-
- def runTest(self):
- m = self.mesh().refined(4)
- basis = InteriorBasis(m, self.elem)
- boundary_basis = FacetBasis(m, self.elem)
- boundary_dofs = boundary_basis.get_dofs().flatten()
-
+ mesh, elem = mesh_elem
- def dirichlet(x):
- """return a harmonic function"""
- return ((x[0] + 1.j * x[1]) ** 2).real
+ m = mesh().refined(4)
+ basis = InteriorBasis(m, elem)
+ boundary_basis = FacetBasis(m, elem)
+ boundary_dofs = boundary_basis.get_dofs().flatten()
+ def dirichlet(x):
+ """return a harmonic function"""
+ return ((x[0] + 1.j * x[1]) ** 2).real
- u = basis.zeros()
- A = laplace.assemble(basis)
- u[boundary_dofs] = projection(dirichlet,
- boundary_basis,
- I=boundary_dofs)
- u = solve(*enforce(A, x=u, D=boundary_dofs))
+ u = basis.zeros()
+ A = laplace.assemble(basis)
+ u[boundary_dofs] = projection(dirichlet,
+ boundary_basis,
+ I=boundary_dofs)
+ u = solve(*impose(A, x=u, D=boundary_dofs))
- @Functional
- def gradu(w):
- gradu = w['sol'].grad
- return dot(gradu, gradu)
+ @Functional
+ def gradu(w):
+ gradu = w['sol'].grad
+ return dot(gradu, gradu)
- self.assertAlmostEqual(
- gradu.assemble(basis, sol=basis.interpolate(u)),
- 8 / 3,
- delta=1e-10,
- )
+ np.testing.assert_almost_equal(
+ gradu.assemble(basis, sol=basis.interpolate(u)),
+ 8 / 3,
+ decimal=9
+ )
-class SolveInhomogeneousLaplaceQuad(SolveInhomogeneousLaplace):
-
- mesh = MeshQuad
- elem = ElementQuad2()
-
+if __name__ == "__main__":
+ import pytest
+ import unittest
-if __name__ == '__main__':
- main()
+ unittest.main()
+ pytest.main()
|
penalizing Dirichlet conditions
Following the introduction of `skfem.utils.enforce` in #591 and #596 and subsequent investigation which involved the penalty method ([2021-04-09](https://github.com/kinnala/scikit-fem/issues/591#issuecomment-816408235)) for a very special example, I realized that an implementation of the `skfem.utils.penalize` function would be quite similar. It would add a large positive number to the diagonal elements of the stiffness matrix corresponding to the Dirichlet degrees of freedom and in the static case multiply the corresponding entries of the right-hand side vector by the same factor. The mass matrix would be left untouched in the unsteady or eigenvalue cases.
Possibly applications of this besides pedagogical might follow from the feature that it would act very like `enforce` but not destroy symmetry; e.g. as Ern & Guermond (2004, §8.4.4 ‘Penalty method’) put it:
> This technique, which is very simple to implement, is useful when one wishes to utilize a direct solution method based on the symmetry of the matrix such as the Choleski or the LDL<sup>T</sup> factorization
Though I don't think we have access to the latter and haven't used the former since `sksparse.cholmod` was dumped #447.
I'll take a stab at this, probably with overwriting turned off by default. #620
|
0.0
|
4210dfc9eb4f9a35e69f4c5972e59636e384b4f4
|
[
"tests/test_manufactured.py::Line1D::runTest",
"tests/test_manufactured.py::Line1DP2::runTest",
"tests/test_manufactured.py::Line1DMini::runTest",
"tests/test_manufactured.py::LineNegative1D::runTest",
"tests/test_manufactured.py::LineNegative1DP2::runTest",
"tests/test_manufactured.py::LineNegative1DMini::runTest",
"tests/test_manufactured.py::LineNeumann1D::runTest",
"tests/test_manufactured.py::LineNeumann1DP2::runTest",
"tests/test_manufactured.py::LineNeumann1DMini::runTest",
"tests/test_manufactured.py::TestExactHexElement::runTest",
"tests/test_manufactured.py::TestExactHexS2::runTest",
"tests/test_manufactured.py::TestExactHex2::runTest",
"tests/test_manufactured.py::TestExactQuadElement::runTest",
"tests/test_manufactured.py::TestExactTetElement::runTest",
"tests/test_manufactured.py::TestExactTriElementP2::runTest",
"tests/test_manufactured.py::TestExactQuadElement2::runTest",
"tests/test_manufactured.py::SolveCirclePoisson::runTest",
"tests/test_manufactured.py::SolveCirclePoissonQuad::runTest",
"tests/test_manufactured.py::SolveCirclePoissonQuad2::runTest",
"tests/test_manufactured.py::SolveCirclePoissonTri2::runTest",
"tests/test_manufactured.py::SolveCirclePoissonTri2Init::runTest",
"tests/test_manufactured.py::SolveCirclePoissonTet::runTest",
"tests/test_manufactured.py::SolveCirclePoissonTet2::runTest",
"tests/test_manufactured.py::test_solving_inhomogeneous_laplace[enforce-mesh_elem0]",
"tests/test_manufactured.py::test_solving_inhomogeneous_laplace[enforce-mesh_elem1]",
"tests/test_manufactured.py::test_solving_inhomogeneous_laplace[penalize-mesh_elem0]",
"tests/test_manufactured.py::test_solving_inhomogeneous_laplace[penalize-mesh_elem1]"
] |
[] |
{
"failed_lite_validators": [
"has_issue_reference",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-04-30 07:05:39+00:00
|
bsd-3-clause
| 3,432 |
|
kinnala__scikit-fem-667
|
diff --git a/README.md b/README.md
index ec13b5ff..453498ed 100644
--- a/README.md
+++ b/README.md
@@ -257,6 +257,9 @@ with respect to documented and/or tested features.
- Added: `ElementTriCCR` and `ElementTetCCR`, conforming Crouzeix-Raviart finite elements
- Fixed: `Mesh.mirrored` returned a wrong mesh when a point other than the origin was used
- Fixed: `MeshLine` constructor accepted only NumPy arrays and not plain Python lists
+- Fixed: `Mesh.element_finder` (and `CellBasis.probes`, `CellBasis.interpolator`) was not working properly for a small number of elements (<5) or a large number of input points (>1000)
+- Fixed: `MeshTet` and `MeshTri.element_finder` is are now more robust against degenerate elements
+- Fixed: `Mesh.element_finder` (and `CellBasis.probes`, `CellBasis.interpolator`) raises exception if the query point is outside of the domain
### [3.1.0] - 2021-06-18
diff --git a/docs/examples/ex28.py b/docs/examples/ex28.py
index 5c526815..987ce837 100644
--- a/docs/examples/ex28.py
+++ b/docs/examples/ex28.py
@@ -88,15 +88,7 @@ import numpy as np
import pygmsh
-if version.parse(pygmsh.__version__) < version.parse('7.0.0'):
- class NullContextManager():
- def __enter__(self):
- return None
- def __exit__(self, *args):
- pass
- geometrycontext = NullContextManager()
-else:
- geometrycontext = pygmsh.geo.Geometry()
+geometrycontext = pygmsh.geo.Geometry()
halfheight = 1.
length = 10.
@@ -110,17 +102,12 @@ peclet = 357.
def make_mesh(halfheight: float, # mm
length: float,
thickness: float) -> MeshTri:
- with geometrycontext as g:
- if version.parse(pygmsh.__version__) < version.parse('7.0.0'):
- geom = pygmsh.built_in.Geometry()
- geom.add_curve_loop = geom.add_line_loop
- else:
- geom = g
+ with geometrycontext as geom:
points = []
lines = []
- lcar = halfheight / 2**2
+ lcar = halfheight / 2 ** 2
for xy in [(0., halfheight),
(0., -halfheight),
@@ -155,10 +142,7 @@ def make_mesh(halfheight: float, # mm
geom.add_physical(geom.add_plane_surface(geom.add_curve_loop(
[*lines[-3:], -lines[1]])), 'solid')
- if version.parse(pygmsh.__version__) < version.parse('7.0.0'):
- return from_meshio(pygmsh.generate_mesh(geom, dim=2))
- else:
- return from_meshio(geom.generate_mesh(dim=2))
+ return from_meshio(geom.generate_mesh(dim=2))
mesh = from_file(Path(__file__).parent / 'meshes' / 'ex28.json')
element = ElementTriP1()
diff --git a/skfem/mesh/mesh_line_1.py b/skfem/mesh/mesh_line_1.py
index ef85502c..e04afbda 100644
--- a/skfem/mesh/mesh_line_1.py
+++ b/skfem/mesh/mesh_line_1.py
@@ -74,6 +74,7 @@ class MeshLine1(Mesh):
return np.max(np.abs(self.p[0, self.t[1]] - self.p[0, self.t[0]]))
def element_finder(self, mapping=None):
+
ix = np.argsort(self.p[0])
maxt = self.t[np.argmax(self.p[0, self.t], 0),
np.arange(self.t.shape[1])]
@@ -81,8 +82,11 @@ class MeshLine1(Mesh):
def finder(x):
xin = x.copy() # bring endpoint inside for np.digitize
xin[x == self.p[0, ix[-1]]] = self.p[0, ix[-2:]].mean()
- return np.nonzero(ix[np.digitize(xin, self.p[0, ix])][:, None]
- == maxt)[1]
+ elems = np.nonzero(ix[np.digitize(xin, self.p[0, ix])][:, None]
+ == maxt)[1]
+ if len(elems) < len(x):
+ raise ValueError("Point is outside of the mesh.")
+ return elems
return finder
diff --git a/skfem/mesh/mesh_tet_1.py b/skfem/mesh/mesh_tet_1.py
index a0ef8361..f7f75bbd 100644
--- a/skfem/mesh/mesh_tet_1.py
+++ b/skfem/mesh/mesh_tet_1.py
@@ -34,18 +34,34 @@ class MeshTet1(Mesh3D):
if mapping is None:
mapping = self._mapping()
- tree = cKDTree(np.mean(self.p[:, self.t], axis=1).T)
+ if not hasattr(self, '_cached_tree'):
+ self._cached_tree = cKDTree(np.mean(self.p[:, self.t], axis=1).T)
+
+ tree = self._cached_tree
+ nelems = self.t.shape[1]
+
+ def finder(x, y, z, _search_all=False):
+
+ if not _search_all:
+ ix = tree.query(np.array([x, y, z]).T,
+ min(10, nelems))[1].flatten()
+ _, ix_ind = np.unique(ix, return_index=True)
+ ix = ix[np.sort(ix_ind)]
+ else:
+ ix = np.arange(nelems, dtype=np.int64)
- def finder(x, y, z):
- ix = tree.query(np.array([x, y, z]).T, 5)[1].flatten()
X = mapping.invF(np.array([x, y, z])[:, None], ix)
- inside = (
- (X[0] >= 0) *
- (X[1] >= 0) *
- (X[2] >= 0) *
- (1 - X[0] - X[1] - X[2] >= 0)
- )
- return np.array([ix[np.argmax(inside, axis=0)]]).flatten()
+ inside = ((X[0] >= 0) *
+ (X[1] >= 0) *
+ (X[2] >= 0) *
+ (1 - X[0] - X[1] - X[2] >= 0))
+
+ if not inside.max(axis=0).all():
+ if _search_all:
+ raise ValueError("Point is outside of the mesh.")
+ return finder(x, y, z, _search_all=True)
+
+ return np.array([ix[inside.argmax(axis=0)]]).flatten()
return finder
diff --git a/skfem/mesh/mesh_tri_1.py b/skfem/mesh/mesh_tri_1.py
index 055b758a..4b1a087d 100644
--- a/skfem/mesh/mesh_tri_1.py
+++ b/skfem/mesh/mesh_tri_1.py
@@ -325,16 +325,32 @@ class MeshTri1(Mesh2D):
if mapping is None:
mapping = self._mapping()
- tree = cKDTree(np.mean(self.p[:, self.t], axis=1).T)
+ if not hasattr(self, '_cached_tree'):
+ self._cached_tree = cKDTree(np.mean(self.p[:, self.t], axis=1).T)
+
+ tree = self._cached_tree
+ nelems = self.t.shape[1]
+
+ def finder(x, y, _search_all=False):
+
+ if not _search_all:
+ ix = tree.query(np.array([x, y]).T,
+ min(5, nelems))[1].flatten()
+ _, ix_ind = np.unique(ix, return_index=True)
+ ix = ix[np.sort(ix_ind)]
+ else:
+ ix = np.arange(nelems, dtype=np.int64)
- def finder(x, y):
- ix = tree.query(np.array([x, y]).T, 5)[1].flatten()
X = mapping.invF(np.array([x, y])[:, None], ix)
- inside = (
- (X[0] >= 0) *
- (X[1] >= 0) *
- (1 - X[0] - X[1] >= 0)
- )
- return np.array([ix[np.argmax(inside, axis=0)]]).flatten()
+ inside = ((X[0] >= 0) *
+ (X[1] >= 0) *
+ (1 - X[0] - X[1] >= 0))
+
+ if not inside.max(axis=0).all():
+ if _search_all:
+ raise ValueError("Point is outside of the mesh.")
+ return finder(x, y, _search_all=True)
+
+ return np.array([ix[inside.argmax(axis=0)]]).flatten()
return finder
|
kinnala/scikit-fem
|
d08af2a3f4607e28023656b1b6ad025b1a530aa1
|
diff --git a/tests/test_basis.py b/tests/test_basis.py
index 45676969..9116e431 100644
--- a/tests/test_basis.py
+++ b/tests/test_basis.py
@@ -6,7 +6,7 @@ from numpy.testing import assert_allclose, assert_almost_equal
from skfem import BilinearForm, asm, solve, condense, projection
from skfem.mesh import MeshTri, MeshTet, MeshHex, MeshQuad, MeshLine
-from skfem.assembly import InteriorBasis, FacetBasis, Dofs, Functional
+from skfem.assembly import CellBasis, FacetBasis, Dofs, Functional
from skfem.element import (ElementVectorH1, ElementTriP2, ElementTriP1,
ElementTetP2, ElementHexS2, ElementHex2,
ElementQuad2, ElementLineP2, ElementTriP0,
@@ -28,7 +28,7 @@ class TestCompositeSplitting(TestCase):
e = ElementVectorH1(ElementTriP2()) * ElementTriP1()
- basis = InteriorBasis(m, e)
+ basis = CellBasis(m, e)
@BilinearForm
def bilinf(u, p, v, q, w):
@@ -93,7 +93,7 @@ class TestFacetExpansion(TestCase):
m = self.mesh_type().refined(2)
- basis = InteriorBasis(m, self.elem_type())
+ basis = CellBasis(m, self.elem_type())
for fun in [lambda x: x[0] == 0,
lambda x: x[0] == 1,
@@ -128,7 +128,7 @@ class TestInterpolatorTet(TestCase):
def runTest(self):
m = self.mesh_type().refined(self.nrefs)
- basis = InteriorBasis(m, self.element_type())
+ basis = CellBasis(m, self.element_type())
x = projection(lambda x: x[0] ** 2, basis)
fun = basis.interpolator(x)
X = np.linspace(0, 1, 10)
@@ -187,7 +187,38 @@ class TestIncompatibleMeshElement(TestCase):
with self.assertRaises(ValueError):
m = MeshTri()
e = ElementTetP2()
- basis = InteriorBasis(m, e)
+ basis = CellBasis(m, e)
+
+
[email protected](
+ "mtype,e,nrefs,npoints",
+ [
+ (MeshTri, ElementTriP1(), 0, 10),
+ (MeshTri, ElementTriP2(), 1, 10),
+ (MeshTri, ElementTriP1(), 5, 10),
+ (MeshTri, ElementTriP1(), 1, 3e5),
+ (MeshTet, ElementTetP2(), 1, 10),
+ (MeshTet, ElementTetP1(), 5, 10),
+ (MeshTet, ElementTetP1(), 1, 3e5),
+ (MeshQuad, ElementQuad1(), 1, 10),
+ (MeshQuad, ElementQuad1(), 1, 3e5),
+ (MeshHex, ElementHex1(), 1, 1e5),
+ ]
+)
+def test_interpolator_probes(mtype, e, nrefs, npoints):
+
+ m = mtype().refined(nrefs)
+
+ np.random.seed(0)
+ X = np.random.rand(m.p.shape[0], int(npoints))
+
+ basis = CellBasis(m, e)
+
+ y = projection(lambda x: x[0] ** 2, basis)
+
+ assert_allclose(basis.probes(X) @ y, basis.interpolator(y)(X))
+ atol = 1e-1 if nrefs <= 1 else 1e-3
+ assert_allclose(basis.probes(X) @ y, X[0] ** 2, atol=atol)
@pytest.mark.parametrize(
@@ -215,7 +246,7 @@ def test_trace(mtype, e1, e2):
# use the boundary where last coordinate is zero
basis = FacetBasis(m, e1,
facets=m.facets_satisfying(lambda x: x[x.shape[0] - 1] == 0.0))
- xfun = projection(lambda x: x[0], InteriorBasis(m, e1))
+ xfun = projection(lambda x: x[0], CellBasis(m, e1))
nbasis, y = basis.trace(xfun, lambda p: p[0:(p.shape[0] - 1)], target_elem=e2)
@Functional
@@ -235,8 +266,8 @@ def test_point_source(etype):
from skfem.models.poisson import laplace
mesh = MeshLine().refined()
- basis = InteriorBasis(mesh, etype())
+ basis = CellBasis(mesh, etype())
source = np.array([0.7])
u = solve(*condense(asm(laplace, basis), basis.point_source(source), D=basis.find_dofs()))
exact = np.stack([(1 - source) * mesh.p, (1 - mesh.p) * source]).min(0)
- assert_almost_equal(u[basis.nodal_dofs], exact)
\ No newline at end of file
+ assert_almost_equal(u[basis.nodal_dofs], exact)
diff --git a/tests/test_mesh.py b/tests/test_mesh.py
index 611285ef..12380427 100644
--- a/tests/test_mesh.py
+++ b/tests/test_mesh.py
@@ -2,10 +2,12 @@ from unittest import TestCase
from pathlib import Path
import numpy as np
-from numpy.testing import assert_array_equal
import pytest
+from scipy.spatial import Delaunay
+from numpy.testing import assert_array_equal
-from skfem.mesh import Mesh, MeshHex, MeshLine, MeshQuad, MeshTet, MeshTri, MeshTri2, MeshQuad2, MeshTet2, MeshHex2
+from skfem.mesh import (Mesh, MeshHex, MeshLine, MeshQuad, MeshTet, MeshTri,
+ MeshTri2, MeshQuad2, MeshTet2, MeshHex2)
from skfem.io.meshio import to_meshio, from_meshio
@@ -241,6 +243,34 @@ class TestFinder1DLinspaced(TestCase):
self.assertEqual(finder(np.array([0.001]))[0], 0)
+
[email protected](
+ "m,seed",
+ [
+ (MeshTri(), 0),
+ (MeshTri(), 1),
+ (MeshTri(), 2),
+ (MeshTet(), 0),
+ (MeshTet(), 1),
+ (MeshTet(), 2),
+ (MeshTet(), 10),
+ ]
+)
+def test_finder_simplex(m, seed):
+
+ np.random.seed(seed)
+ points = np.hstack((m.p, np.random.rand(m.p.shape[0], 100)))
+ tri = Delaunay(points.T)
+ M = type(m)(points, tri.simplices.T)
+ finder = M.element_finder()
+
+ query_pts = np.random.rand(m.p.shape[0], 500)
+ assert_array_equal(
+ tri.find_simplex(query_pts.T),
+ finder(*query_pts),
+ )
+
+
@pytest.mark.parametrize(
"m",
[
|
Examples providing your own mesh and retriving the basis functions?
Are there any examples for supplying your own mesh (for example from scipy Delaunay) and extracting basis functions of some degree?
For example you might evaluate the basis functions at a set of points for fitting against data as a kind of smoothing spline.
|
0.0
|
d08af2a3f4607e28023656b1b6ad025b1a530aa1
|
[
"tests/test_basis.py::TestCompositeSplitting::runTest",
"tests/test_basis.py::TestCompositeFacetAssembly::runTest",
"tests/test_basis.py::TestFacetExpansion::runTest",
"tests/test_basis.py::TestFacetExpansionHexS2::runTest",
"tests/test_basis.py::TestFacetExpansionHex2::runTest",
"tests/test_basis.py::TestInterpolatorTet::runTest",
"tests/test_basis.py::TestInterpolatorTet2::runTest",
"tests/test_basis.py::TestInterpolatorTri::runTest",
"tests/test_basis.py::TestInterpolatorQuad::runTest",
"tests/test_basis.py::TestInterpolatorHex::runTest",
"tests/test_basis.py::TestInterpolatorLine::runTest",
"tests/test_basis.py::TestInterpolatorLine2::runTest",
"tests/test_basis.py::TestIncompatibleMeshElement::runTest",
"tests/test_basis.py::test_interpolator_probes[MeshTri1-e0-0-10]",
"tests/test_basis.py::test_interpolator_probes[MeshTri1-e1-1-10]",
"tests/test_basis.py::test_interpolator_probes[MeshTri1-e2-5-10]",
"tests/test_basis.py::test_interpolator_probes[MeshTri1-e3-1-300000.0]",
"tests/test_basis.py::test_interpolator_probes[MeshTet1-e4-1-10]",
"tests/test_basis.py::test_interpolator_probes[MeshTet1-e5-5-10]",
"tests/test_basis.py::test_interpolator_probes[MeshTet1-e6-1-300000.0]",
"tests/test_basis.py::test_interpolator_probes[MeshQuad1-e7-1-10]",
"tests/test_basis.py::test_interpolator_probes[MeshQuad1-e8-1-300000.0]",
"tests/test_basis.py::test_interpolator_probes[MeshHex1-e9-1-100000.0]",
"tests/test_basis.py::test_trace[MeshTri1-e10-e20]",
"tests/test_basis.py::test_trace[MeshTri1-e11-e21]",
"tests/test_basis.py::test_trace[MeshTri1-e12-e22]",
"tests/test_basis.py::test_trace[MeshTri1-e13-e23]",
"tests/test_basis.py::test_trace[MeshTri1-e14-None]",
"tests/test_basis.py::test_trace[MeshQuad1-e15-e25]",
"tests/test_basis.py::test_trace[MeshQuad1-e16-e26]",
"tests/test_basis.py::test_trace[MeshQuad1-e17-e27]",
"tests/test_basis.py::test_trace[MeshTet1-e18-e28]",
"tests/test_basis.py::test_trace[MeshTet1-e19-e29]",
"tests/test_basis.py::test_trace[MeshHex1-e110-e210]",
"tests/test_basis.py::test_trace[MeshHex1-e111-e211]",
"tests/test_basis.py::test_trace[MeshHex1-e112-e212]",
"tests/test_basis.py::test_point_source[ElementLineP1]",
"tests/test_basis.py::test_point_source[ElementLineP2]",
"tests/test_basis.py::test_point_source[ElementLineMini]",
"tests/test_mesh.py::MeshTests::runTest",
"tests/test_mesh.py::Loading::runTest",
"tests/test_mesh.py::SerializeUnserializeCycle::runTest",
"tests/test_mesh.py::TestBoundaryEdges::runTest",
"tests/test_mesh.py::TestBoundaryEdges2::runTest",
"tests/test_mesh.py::TestMeshAddition::runTest",
"tests/test_mesh.py::TestMeshQuadSplit::runTest",
"tests/test_mesh.py::TestAdaptiveSplitting1D::runTest",
"tests/test_mesh.py::TestAdaptiveSplitting2D::runTest",
"tests/test_mesh.py::TestFinder1DRefined::runTest",
"tests/test_mesh.py::TestFinder1DLinspaced::runTest",
"tests/test_mesh.py::test_finder_simplex[m0-0]",
"tests/test_mesh.py::test_finder_simplex[m1-1]",
"tests/test_mesh.py::test_finder_simplex[m2-2]",
"tests/test_mesh.py::test_finder_simplex[m3-0]",
"tests/test_mesh.py::test_finder_simplex[m4-1]",
"tests/test_mesh.py::test_finder_simplex[m5-2]",
"tests/test_mesh.py::test_finder_simplex[m6-10]",
"tests/test_mesh.py::test_meshio_cycle[m0]",
"tests/test_mesh.py::test_meshio_cycle[m1]",
"tests/test_mesh.py::test_meshio_cycle[m2]",
"tests/test_mesh.py::test_meshio_cycle[m3]",
"tests/test_mesh.py::test_meshio_cycle[m4]",
"tests/test_mesh.py::test_meshio_cycle[m5]",
"tests/test_mesh.py::test_meshio_cycle[m6]",
"tests/test_mesh.py::test_saveload_cycle[m0]",
"tests/test_mesh.py::test_saveload_cycle[m1]",
"tests/test_mesh.py::test_saveload_cycle[m2]",
"tests/test_mesh.py::test_saveload_cycle[m3]"
] |
[] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-07-13 15:30:08+00:00
|
bsd-3-clause
| 3,433 |
|
kinnala__scikit-fem-752
|
diff --git a/docs/examples/ex03.py b/docs/examples/ex03.py
index 5d236923..6df35d63 100644
--- a/docs/examples/ex03.py
+++ b/docs/examples/ex03.py
@@ -1,23 +1,25 @@
"""Linear elastic eigenvalue problem."""
from skfem import *
-from skfem.helpers import dot
-from skfem.models.elasticity import linear_elasticity
+from skfem.helpers import dot, ddot, sym_grad
+from skfem.models.elasticity import linear_elasticity, linear_stress
import numpy as np
m1 = MeshLine(np.linspace(0, 5, 50))
m2 = MeshLine(np.linspace(0, 1, 10))
-m = m1*m2
+m = m1 * m2
e1 = ElementQuad1()
mapping = MappingIsoparametric(m, e1)
-e = ElementVectorH1(e1)
+e = ElementVector(e1)
gb = Basis(m, e, mapping, 2)
-K = asm(linear_elasticity(1.0, 1.0), gb)
+lam = 1.
+mu = 1.
+K = asm(linear_elasticity(lam, mu), gb)
@BilinearForm
def mass(u, v, w):
@@ -25,17 +27,30 @@ def mass(u, v, w):
M = asm(mass, gb)
-D = gb.find_dofs({'': m.facets_satisfying(lambda x: x[0]==0.0)})
+D = gb.find_dofs({'left': m.facets_satisfying(lambda x: x[0] == 0.)})
y = gb.zeros()
I = gb.complement_dofs(D)
-L, x = solve(*condense(K, M, I=I), solver=solver_eigen_scipy_sym(k=6, sigma=0.0))
+L, x = solve(*condense(K, M, I=I),
+ solver=solver_eigen_scipy_sym(k=6, sigma=0.0))
y = x[:, 4]
+# calculate stress
+sgb = gb.with_element(ElementVector(e))
+C = linear_stress(lam, mu)
+yi = gb.interpolate(y)
+
+@LinearForm
+def proj(v, _):
+ return ddot(C(sym_grad(yi)), v)
+
+sigma = projection(proj, sgb, gb)
+
if __name__ == "__main__":
- from skfem.visuals.matplotlib import draw, show
+ from skfem.visuals.matplotlib import plot, draw, show
M = MeshQuad(np.array(m.p + y[gb.nodal_dofs]), m.t)
- draw(M)
+ ax = draw(M)
+ plot(M, sigma[sgb.nodal_dofs[0]], ax=ax, colorbar=True)
show()
diff --git a/docs/listofexamples.rst b/docs/listofexamples.rst
index dfb96f1e..808add85 100644
--- a/docs/listofexamples.rst
+++ b/docs/listofexamples.rst
@@ -39,7 +39,7 @@ This example solves the linear elastic eigenvalue problem
:math:`\mathrm{div}\,\sigma(u)= \lambda u` with
the displacement fixed on the left hand side boundary.
-.. figure:: https://user-images.githubusercontent.com/973268/87661134-cbec2b00-c768-11ea-81bc-f5455df7cc33.png
+.. figure:: https://user-images.githubusercontent.com/973268/134467300-f7e635ed-39c4-4a36-9e98-aadb6e51961a.png
The fifth eigenmode of Example 3.
diff --git a/skfem/utils.py b/skfem/utils.py
index b43d0557..d3d23878 100644
--- a/skfem/utils.py
+++ b/skfem/utils.py
@@ -606,13 +606,23 @@ def projection(fun,
@BilinearForm
def mass(u, v, w):
- p = u * v
- return sum(p) if isinstance(basis_to.elem, ElementVector) else p
-
- @LinearForm
- def funv(v, w):
- p = fun(w.x) * v
- return sum(p) if isinstance(basis_to.elem, ElementVector) else p
+ from skfem.helpers import dot, ddot
+ p = 0
+ if len(u.value.shape) == 2:
+ p = u * v
+ elif len(u.value.shape) == 3:
+ p = dot(u, v)
+ elif len(u.value.shape) == 4:
+ p = ddot(u, v)
+ return p
+
+ if isinstance(fun, LinearForm):
+ funv = fun
+ else:
+ @LinearForm
+ def funv(v, w):
+ p = fun(w.x) * v
+ return sum(p) if isinstance(basis_to.elem, ElementVector) else p
@BilinearForm
def deriv(u, v, w):
|
kinnala/scikit-fem
|
d37551116d2582f9d8c8bb5a9eca7bca8034be4d
|
diff --git a/tests/test_assembly.py b/tests/test_assembly.py
index bdf242ef..eed9a7f6 100644
--- a/tests/test_assembly.py
+++ b/tests/test_assembly.py
@@ -13,14 +13,15 @@ from skfem.element import (ElementQuad1, ElementQuadS2, ElementHex1,
ElementTriMorley, ElementVectorH1, ElementQuadP,
ElementHex2, ElementTriArgyris, ElementTriP2,
ElementTriDG, ElementQuadDG, ElementHexDG,
- ElementTetDG, ElementTriHermite)
+ ElementTetDG, ElementTriHermite, ElementVector)
from skfem.mesh import (MeshQuad, MeshHex, MeshTet, MeshTri, MeshQuad2,
MeshTri2, MeshTet2, MeshHex2, MeshTri1DG, MeshQuad1DG,
MeshHex1DG)
from skfem.assembly import FacetBasis, Basis
from skfem.utils import projection
from skfem.models import laplace, unit_load, mass
-from skfem.helpers import grad, dot
+from skfem.helpers import grad, dot, ddot, sym_grad
+from skfem.models import linear_stress
class IntegrateOneOverBoundaryQ1(TestCase):
@@ -564,6 +565,30 @@ def test_trilinear_form(m, e):
assert abs((opt1[i] - opt2).max()) < 1e-10
[email protected](
+ "m,e",
+ [
+ (MeshTri(), ElementTriP1()),
+ (MeshTri(), ElementTriP2()),
+ (MeshTet(), ElementTetP1()),
+ ]
+)
+def test_matrix_element_projection(m, e):
+
+ E1 = ElementVector(e)
+ E2 = ElementVector(ElementVector(e))
+ basis0 = Basis(m, E1)
+ basis1 = basis0.with_element(E2)
+ C = linear_stress()
+
+ x = basis0.interpolate(np.random.random(basis0.N))
+
+ @LinearForm
+ def proj(v, _):
+ return ddot(C(sym_grad(x)), v)
+
+ y = projection(proj, basis1, basis0)
+
if __name__ == '__main__':
main()
diff --git a/tests/test_elements.py b/tests/test_elements.py
index aa0024f2..f48ca9a5 100644
--- a/tests/test_elements.py
+++ b/tests/test_elements.py
@@ -361,14 +361,9 @@ def test_dg_element(m, e, edg):
"e,edg",
[
(ElementTriP1(), ElementTriDG),
- (ElementTriP2(), ElementTriDG),
- (ElementTetP1(), ElementTetDG),
(ElementTetP2(), ElementTetDG),
(ElementTriArgyris(), ElementTriDG),
- (ElementTriMorley(), ElementTriDG),
- (ElementTriHermite(), ElementTriDG),
(ElementQuad1(), ElementQuadDG),
- (ElementQuad2(), ElementQuadDG),
(ElementQuadP(4), ElementQuadDG),
(ElementHex2(), ElementHexDG),
]
|
Test ElementVector(ElementVector(...))
The following has not been tested but should work:
```python
In [1]: from skfem import *
In [2]: m = MeshHex().refined()
In [3]: e = ElementVector(ElementVector(ElementHex1()))
In [4]: e
Out[4]: <skfem.element.element_vector.ElementVector at 0x7f0e795acdc0>
In [5]: basis = InteriorBasis(m, e)
In [6]: from skfem.helpers import ddot
In [7]: A = asm(BilinearForm(lambda u, v, w: ddot(u, v)), basis)
In [8]: A
Out[8]:
<243x243 sparse matrix of type '<class 'numpy.float64'>'
with 3087 stored elements in Compressed Sparse Row format>
```
_Originally posted by @kinnala in https://github.com/kinnala/scikit-fem/issues/619#issuecomment-817656881_
|
0.0
|
d37551116d2582f9d8c8bb5a9eca7bca8034be4d
|
[
"tests/test_assembly.py::test_matrix_element_projection[m0-e0]",
"tests/test_assembly.py::test_matrix_element_projection[m1-e1]",
"tests/test_assembly.py::test_matrix_element_projection[m2-e2]"
] |
[
"tests/test_assembly.py::IntegrateOneOverBoundaryQ1::runTest",
"tests/test_assembly.py::IntegrateOneOverBoundaryS2::runTest",
"tests/test_assembly.py::IntegrateOneOverBoundaryHex1::runTest",
"tests/test_assembly.py::IntegrateOneOverBoundaryHex1_2::runTest",
"tests/test_assembly.py::IntegrateOneOverBoundaryHex2::runTest",
"tests/test_assembly.py::IntegrateFuncOverBoundary::runTest",
"tests/test_assembly.py::IntegrateFuncOverBoundaryPart::runTest",
"tests/test_assembly.py::IntegrateFuncOverBoundaryPartHexS2::runTest",
"tests/test_assembly.py::IntegrateFuncOverBoundaryPartHex2::runTest",
"tests/test_assembly.py::IntegrateFuncOverBoundaryPartTetP1::runTest",
"tests/test_assembly.py::IntegrateFuncOverBoundaryPartTetP2::runTest",
"tests/test_assembly.py::IntegrateFuncOverBoundaryPartTetP0::runTest",
"tests/test_assembly.py::BasisInterpolator::runTest",
"tests/test_assembly.py::BasisInterpolatorTriP2::runTest",
"tests/test_assembly.py::BasisInterpolatorQuad1::runTest",
"tests/test_assembly.py::BasisInterpolatorQuad2::runTest",
"tests/test_assembly.py::BasisInterpolatorQuadS2::runTest",
"tests/test_assembly.py::BasisInterpolatorMorley::runTest",
"tests/test_assembly.py::NormalVectorTestTri::runTest",
"tests/test_assembly.py::NormalVectorTestTet::runTest",
"tests/test_assembly.py::NormalVectorTestTetP2::runTest",
"tests/test_assembly.py::NormalVectorTestQuad::runTest",
"tests/test_assembly.py::NormalVectorTestQuadP::runTest",
"tests/test_assembly.py::NormalVectorTestHex::runTest",
"tests/test_assembly.py::NormalVectorTestHexS2::runTest",
"tests/test_assembly.py::NormalVectorTestHex2::runTest",
"tests/test_assembly.py::test_evaluate_functional[MeshTri1-e0-None]",
"tests/test_assembly.py::test_evaluate_functional[MeshTri1-e1-None]",
"tests/test_assembly.py::test_evaluate_functional[MeshHex1-e2-None]",
"tests/test_assembly.py::test_evaluate_functional[MeshQuad1-e3-None]",
"tests/test_assembly.py::test_evaluate_functional[MeshQuad1-e4-None]",
"tests/test_assembly.py::test_evaluate_functional[MeshQuad1-e5-MeshQuad2]",
"tests/test_assembly.py::test_evaluate_functional[MeshTri1-e6-MeshTri2]",
"tests/test_assembly.py::test_evaluate_functional[MeshTet1-e7-MeshTet2]",
"tests/test_assembly.py::test_evaluate_functional[MeshHex1-e8-MeshHex2]",
"tests/test_assembly.py::TestRefinterp::runTest",
"tests/test_assembly.py::TestCompositeAssembly::runTest",
"tests/test_assembly.py::TestFieldInterpolation::runTest",
"tests/test_assembly.py::TestFieldInterpolation_2::runTest",
"tests/test_assembly.py::VectorialFunctional::runTest",
"tests/test_assembly.py::TestComplexValuedAssembly::runTest",
"tests/test_assembly.py::TestThreadedAssembly::runTest",
"tests/test_assembly.py::test_coodata_inverse[m0-e0-ElementTriDG]",
"tests/test_assembly.py::test_coodata_inverse[m1-e1-ElementTriDG]",
"tests/test_assembly.py::test_coodata_inverse[m2-e2-ElementTetDG]",
"tests/test_assembly.py::test_coodata_inverse[m3-e3-ElementTetDG]",
"tests/test_assembly.py::test_coodata_inverse[m4-e4-ElementTriDG]",
"tests/test_assembly.py::test_coodata_inverse[m5-e5-ElementTriDG]",
"tests/test_assembly.py::test_coodata_inverse[m6-e6-ElementQuadDG]",
"tests/test_assembly.py::test_coodata_inverse[m7-e7-ElementQuadDG]",
"tests/test_assembly.py::test_coodata_inverse[m8-e8-ElementQuadDG]",
"tests/test_assembly.py::test_coodata_inverse[m9-e9-ElementHexDG]",
"tests/test_assembly.py::test_trilinear_form[m0-e0]",
"tests/test_assembly.py::test_trilinear_form[m1-e1]",
"tests/test_assembly.py::test_trilinear_form[m2-e2]",
"tests/test_assembly.py::test_trilinear_form[m3-e3]",
"tests/test_assembly.py::test_trilinear_form[m4-e4]",
"tests/test_elements.py::TestNodality::runTest",
"tests/test_elements.py::TestNodalityTriRT0::runTest",
"tests/test_elements.py::TestComposite::runTest",
"tests/test_elements.py::TestCompositeMul::runTest",
"tests/test_elements.py::TestCompatibilityWarning::runTest",
"tests/test_elements.py::TestDerivatives::runTest",
"tests/test_elements.py::TestPartitionofUnity::runTest",
"tests/test_elements.py::TestElementLinePp::test_p_less_than_1_error",
"tests/test_elements.py::TestElementQuadBFS::test_throw_index_error",
"tests/test_elements.py::test_dg_element[m0-e0-ElementTriDG]",
"tests/test_elements.py::test_dg_element[m1-e1-ElementTriDG]",
"tests/test_elements.py::test_dg_element[m2-e2-ElementTetDG]",
"tests/test_elements.py::test_dg_element[m3-e3-ElementTetDG]",
"tests/test_elements.py::test_dg_element[m4-e4-ElementTriDG]",
"tests/test_elements.py::test_dg_element[m5-e5-ElementTriDG]",
"tests/test_elements.py::test_dg_element[m6-e6-ElementTriDG]",
"tests/test_elements.py::test_dg_element[m7-e7-ElementHexDG]",
"tests/test_elements.py::test_dg_element[m8-e8-ElementQuadDG]",
"tests/test_elements.py::test_initialize_dg_composite_elements[e0-ElementTriDG]",
"tests/test_elements.py::test_initialize_dg_composite_elements[e1-ElementTetDG]",
"tests/test_elements.py::test_initialize_dg_composite_elements[e2-ElementTriDG]",
"tests/test_elements.py::test_initialize_dg_composite_elements[e3-ElementQuadDG]",
"tests/test_elements.py::test_initialize_dg_composite_elements[e4-ElementQuadDG]",
"tests/test_elements.py::test_initialize_dg_composite_elements[e5-ElementHexDG]"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-09-23 07:09:10+00:00
|
bsd-3-clause
| 3,434 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.